Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ScriptLoader #2417

Open
wants to merge 18 commits into
base: dev/1.4
Choose a base branch
from
4 changes: 3 additions & 1 deletion packages/core/src/asset/AssetType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,7 @@ export enum AssetType {
/** Source Font, include ttf、 otf and woff. */
SourceFont = "SourceFont",
/** Project asset. */
Project = "project"
Project = "project",
/** Script in ES module. */
Script = "Script"
}
20 changes: 20 additions & 0 deletions packages/loader/src/ScriptLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { AssetPromise, AssetType, Loader, LoadItem, resourceLoader, Script } from "@galacean/engine-core";

interface ESModuleStructure {
default?: Script;
[key: string]: any;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance type safety and documentation for ESModuleStructure interface

The interface could benefit from:

  1. Stricter typing instead of any
  2. JSDoc documentation explaining its purpose
  3. Validation for required properties
+/**
+ * Represents the structure of an ES module loaded by ScriptLoader.
+ * @property default - Optional default export containing the Script
+ * @property [key: string] - Additional named exports from the module
+ */
 interface ESModuleStructure {
   default?: Script;
-  [key: string]: any;
+  [key: string]: Script | unknown;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface ESModuleStructure {
default?: Script;
[key: string]: any;
}
/**
* Represents the structure of an ES module loaded by ScriptLoader.
* @property default - Optional default export containing the Script
* @property [key: string] - Additional named exports from the module
*/
interface ESModuleStructure {
default?: Script;
[key: string]: Script | unknown;
}


@resourceLoader(AssetType.Script, ["js", "mjs"], false)
export class ScriptLoader extends Loader<ESModuleStructure> {
load(item: LoadItem): AssetPromise<ESModuleStructure> {
return new AssetPromise((resolve, reject) => {
const { url } = item;
(import(/* @vite-ignore */url) as Promise<ESModuleStructure>)

Check failure on line 13 in packages/loader/src/ScriptLoader.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `·`
.then((esModule) => {
resolve(esModule);
})
.catch(reject);
});
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding resource cleanup.

The loader should implement cleanup logic to handle cases where the component is destroyed while scripts are still loading. This prevents memory leaks and ensures proper resource management.

 @resourceLoader(AssetType.Script, ["js", "mjs"], false)
 export class ScriptLoader extends Loader<ESModuleStructure> {
+  private loadingScripts = new Set<string>();
+
   load(item: LoadItem): AssetPromise<ESModuleStructure> {
     return new AssetPromise((resolve, reject) => {
       const { url } = item;
+      this.loadingScripts.add(url);
       (import(/* @vite-ignore */ url) as Promise<ESModuleStructure>)
         .then((esModule) => {
+          this.loadingScripts.delete(url);
           resolve(esModule);
         })
-        .catch(reject);
+        .catch((error) => {
+          this.loadingScripts.delete(url);
+          reject(error);
+        });
     });
   }
+
+  destroy(): void {
+    this.loadingScripts.clear();
+    super.destroy?.();
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@resourceLoader(AssetType.Script, ["js", "mjs"], false)
export class ScriptLoader extends Loader<ESModuleStructure> {
load(item: LoadItem): AssetPromise<ESModuleStructure> {
return new AssetPromise((resolve, reject) => {
const { url } = item;
(import(/* @vite-ignore */url) as Promise<ESModuleStructure>)
.then((esModule) => {
resolve(esModule);
})
.catch(reject);
});
}
}
@resourceLoader(AssetType.Script, ["js", "mjs"], false)
export class ScriptLoader extends Loader<ESModuleStructure> {
private loadingScripts = new Set<string>();
load(item: LoadItem): AssetPromise<ESModuleStructure> {
return new AssetPromise((resolve, reject) => {
const { url } = item;
this.loadingScripts.add(url);
(import(/* @vite-ignore */url) as Promise<ESModuleStructure>)
.then((esModule) => {
this.loadingScripts.delete(url);
resolve(esModule);
})
.catch((error) => {
this.loadingScripts.delete(url);
reject(error);
});
});
}
destroy(): void {
this.loadingScripts.clear();
super.destroy?.();
}
}
🧰 Tools
🪛 GitHub Check: lint

[failure] 13-13:
Insert ·

2 changes: 2 additions & 0 deletions packages/loader/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@ import "./SpriteLoader";
import "./Texture2DLoader";
import "./TextureCubeLoader";
import "./ktx2/KTX2Loader";
import "./ScriptLoader";

export { GLTFLoader } from "./GLTFLoader";
export type { GLTFParams } from "./GLTFLoader";
export * from "./SceneLoader";
export type { Texture2DParams } from "./Texture2DLoader";
export { parseSingleKTX } from "./compressed-texture";
export { ScriptLoader } from "./ScriptLoader";
export * from "./gltf";
export { KTX2Loader, KTX2Transcoder } from "./ktx2/KTX2Loader";
export { KTX2TargetFormat } from "./ktx2/KTX2TargetFormat";
Expand Down
59 changes: 59 additions & 0 deletions tests/src/loader/ScriptLoader.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { WebGLEngine } from "@galacean/engine-rhi-webgl";
import { AssetType, Script } from "@galacean/engine-core";
import "@galacean/engine-loader";
import { describe, it, expect, beforeAll, afterAll } from "vitest";

let engine: WebGLEngine;

interface ESModuleStructure {
default?: Script;
[key: string]: any;
}

beforeAll(async () => {
const canvasDOM = document.createElement("canvas");
canvasDOM.width = 1024;
canvasDOM.height = 1024;
engine = await WebGLEngine.create({ canvas: canvasDOM });
});

describe("ScriptLoader test", function () {
it("loader from string url", async () => {

engine.resourceManager.load<ESModuleStructure>({
url: "https://cdn.jsdelivr.net/npm/[email protected]/+esm",
type: AssetType.Script
})
.then((script) => {
expect(script).not.to.be.null;
expect(script.default).not.to.be.null;
expect(script.colord).not.to.be.null;
expect(script.getFormat).not.to.be.null;
expect(script.random).not.to.be.null;
});
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve async test handling.

The test uses async/await syntax but then switches to .then() chain. Consider using consistent async/await pattern and add proper error handling.

 it("loader from string url", async () => {
-    
-    engine.resourceManager.load<ESModuleStructure>({
+    const script = await engine.resourceManager.load<ESModuleStructure>({
       url: "https://cdn.jsdelivr.net/npm/[email protected]/+esm",
       type: AssetType.Script
-    })
-    .then((script) => {
-      expect(script).not.to.be.null;
-      expect(script.default).not.to.be.null;
-      expect(script.colord).not.to.be.null;
-      expect(script.getFormat).not.to.be.null;
-      expect(script.random).not.to.be.null;
     });
+    expect(script).not.to.be.null;
+    expect(script.default).not.to.be.null;
+    expect(script.colord).not.to.be.null;
+    expect(script.getFormat).not.to.be.null;
+    expect(script.random).not.to.be.null;
   });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it("loader from string url", async () => {
engine.resourceManager.load<ESModuleStructure>({
url: "https://cdn.jsdelivr.net/npm/[email protected]/+esm",
type: AssetType.Script
})
.then((script) => {
expect(script).not.to.be.null;
expect(script.default).not.to.be.null;
expect(script.colord).not.to.be.null;
expect(script.getFormat).not.to.be.null;
expect(script.random).not.to.be.null;
});
});
it("loader from string url", async () => {
const script = await engine.resourceManager.load<ESModuleStructure>({
url: "https://cdn.jsdelivr.net/npm/[email protected]/+esm",
type: AssetType.Script
});
expect(script).not.to.be.null;
expect(script.default).not.to.be.null;
expect(script.colord).not.to.be.null;
expect(script.getFormat).not.to.be.null;
expect(script.random).not.to.be.null;
});


it("loader from blob raw script text", async () => {
const esModuleString = `
export const colord = "colord";
export const getFormat = () => "getFormat";
export default colord;
`
engine.resourceManager.load<ESModuleStructure>({
url: URL.createObjectURL(new Blob([esModuleString], { type: "application/javascript" })),
type: AssetType.Script
})
.then((script) => {
expect(script).not.to.be.null;
expect(script.colord).not.to.be.null;
expect(script.getFormat).not.to.be.null;
expect(script.default).not.to.be.null;
expect(script.default).equal(script.colord)
})
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve test structure and async handling.

Similar to the previous test, consider using consistent async/await pattern and structured assertions.

 it("loader from blob raw script text", async () => {
   const esModuleString = `
     export const colord = "colord";
     export const getFormat = () => "getFormat";
     export default colord;
   `
-    engine.resourceManager.load<ESModuleStructure>({
+    const blobUrl = URL.createObjectURL(
+      new Blob([esModuleString], { type: "application/javascript" })
+    );
+    try {
+      const script = await engine.resourceManager.load<ESModuleStructure>({
-      url: URL.createObjectURL(new Blob([esModuleString], { type: "application/javascript" })),
+      url: blobUrl,
       type: AssetType.Script
-    })
-    .then((script) => {
-      expect(script).not.to.be.null;
-      expect(script.colord).not.to.be.null;
-      expect(script.getFormat).not.to.be.null;
-      expect(script.default).not.to.be.null;
-      expect(script.default).equal(script.colord)
-    })
+      });
+      expect(script).not.to.be.null;
+      expect(script.colord).not.to.be.null;
+      expect(script.getFormat).not.to.be.null;
+      expect(script.default).not.to.be.null;
+      expect(script.default).equal(script.colord);
+    } finally {
+      URL.revokeObjectURL(blobUrl);
+    }
   });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it("loader from blob raw script text", async () => {
const esModuleString = `
export const colord = "colord";
export const getFormat = () => "getFormat";
export default colord;
`
engine.resourceManager.load<ESModuleStructure>({
url: URL.createObjectURL(new Blob([esModuleString], { type: "application/javascript" })),
type: AssetType.Script
})
.then((script) => {
expect(script).not.to.be.null;
expect(script.colord).not.to.be.null;
expect(script.getFormat).not.to.be.null;
expect(script.default).not.to.be.null;
expect(script.default).equal(script.colord)
})
});
it("loader from blob raw script text", async () => {
const esModuleString = `
export const colord = "colord";
export const getFormat = () => "getFormat";
export default colord;
`
const blobUrl = URL.createObjectURL(
new Blob([esModuleString], { type: "application/javascript" })
);
try {
const script = await engine.resourceManager.load<ESModuleStructure>({
url: blobUrl,
type: AssetType.Script
});
expect(script).not.to.be.null;
expect(script.colord).not.to.be.null;
expect(script.getFormat).not.to.be.null;
expect(script.default).not.to.be.null;
expect(script.default).equal(script.colord);
} finally {
URL.revokeObjectURL(blobUrl);
}
});


afterAll(function () {
engine.resourceManager.gc();
engine.destroy();
});
});
Loading