X Tutup
Skip to content

Commit 600959b

Browse files
committed
[#1220] fix settings for the fetch request not being applied in es6 builds
1 parent 104b002 commit 600959b

File tree

11 files changed

+158
-122
lines changed

11 files changed

+158
-122
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@
55
### Added
66
- Sprite: add support for aseprite texture atlas
77
- Atlas: `createSpritefromAnim` parameter is now optional, and if not defined will use all defined index in the corresponding atlas
8+
- Loader: new `setOptions` method that allows specifying custom settings to be applied to fetch requests (crossOrigin, withCredentials, etc..)
89

910
### Fixed
1011
- Doc: fix hyperlinks to source code within documentation (thanks @Waltibaba)
12+
- Loader: fix settings for the fetch request not being applied in es6 builds (thanks @B0sh)
13+
1114

1215
## [16.1.2] (melonJS 2) - _2024-02-12_
1316

src/audio/audio.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// external import
22
import {Howl, Howler} from "howler";
33
import {clamp} from "./../math/math.js";
4-
import { nocache, withCredentials} from "./../loader/settings.js";
54
import { isDataUrl } from "./../utils/string.js";
65

76
/**
@@ -141,9 +140,10 @@ export function disable() {
141140
* @param {loader.Asset} sound
142141
* @param {Function} [onloadcb] - function to be called when the resource is loaded
143142
* @param {Function} [onerrorcb] - function to be called in case of error
143+
* @param {Object} [settings] - custom settings to apply to the request (@link https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)
144144
* @returns {number} the amount of asset loaded (always 1 if successfull)
145145
*/
146-
export function load(sound, onloadcb, onerrorcb) {
146+
export function load(sound, onloadcb, onerrorcb, settings = {}) {
147147
let urls = [];
148148
if (audioExts.length === 0) {
149149
throw new Error("target audio extension(s) should be set through me.audio.init() before calling the preloader.");
@@ -152,7 +152,7 @@ export function load(sound, onloadcb, onerrorcb) {
152152
urls.push(sound.src);
153153
} else {
154154
for (let i = 0; i < audioExts.length; i++) {
155-
urls.push(sound.src + sound.name + "." + audioExts[i] + nocache);
155+
urls.push(sound.src + sound.name + "." + audioExts[i] + settings.nocache);
156156
}
157157
}
158158

@@ -162,7 +162,7 @@ export function load(sound, onloadcb, onerrorcb) {
162162
autoplay : sound.autoplay === true,
163163
loop : sound.loop = true,
164164
html5 : sound.stream === true || sound.html5 === true,
165-
xhrWithCredentials : withCredentials,
165+
xhrWithCredentials : settings.withCredentials,
166166
onloaderror() {
167167
soundLoadError.call(this, sound.name, onerrorcb);
168168
},

src/loader/loader.js

Lines changed: 119 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,127 @@ import { preloadJSON } from "./parsers/json.js";
1010
import { preloadBinary } from "./parsers/binary.js";
1111
import { preloadJavascript } from "./parsers/script.js";
1212
import { preloadVideo } from "./parsers/video.js";
13-
import { baseURL } from "./settings.js";
1413
import { warning } from "../lang/console.js";
1514

16-
1715
/**
1816
* a small class to manage loading of stuff and manage resources
1917
* @namespace loader
2018
*/
2119

22-
// for backward compatibility
23-
export * from "./settings.js";
20+
21+
// to enable/disable caching
22+
export let nocache = "";
23+
24+
// baseURL
25+
export let baseURL = {};
26+
27+
/**
28+
* crossOrigin attribute to configure the CORS requests for Image and Video data element.
29+
* By default (that is, when the attribute is not specified), CORS is not used at all.
30+
* The "anonymous" keyword means that there will be no exchange of user credentials via cookies,
31+
* client-side SSL certificates or HTTP authentication as described in the Terminology section of the CORS specification.<br>
32+
* @type {string}
33+
* @name crossOrigin
34+
* @default undefined
35+
* @see loader.setOptions
36+
* @memberof loader
37+
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes
38+
* @example
39+
* // allow for cross-origin texture loading
40+
* me.loader.crossOrigin = "anonymous";
41+
*
42+
* // set all ressources to be loaded
43+
* me.loader.preload(game.resources, () => this.loaded());
44+
*/
45+
export let crossOrigin;
46+
47+
/**
48+
* indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies,
49+
* authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.
50+
* @public
51+
* @type {boolean}
52+
* @name withCredentials
53+
* @see loader.setOptions
54+
* @default false
55+
* @memberof loader
56+
* @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
57+
* @example
58+
* // enable withCredentials
59+
* me.loader.withCredentials = true;
60+
*
61+
* // set all ressources to be loaded
62+
* me.loader.preload(game.resources, () => this.loaded());
63+
*/
64+
export let withCredentials = false;
65+
66+
/**
67+
* enable the nocache mechanism
68+
* @ignore
69+
*/
70+
export function setNocache(enable = false) {
71+
nocache = enable ? "?" + ~~(Math.random() * 10000000) : "";
72+
}
73+
74+
/**
75+
* Sets the options for the loader.
76+
* @memberof loader
77+
* @param {Object} options - The options to set.
78+
* @param {string} [options.crossOrigin] - The crossOrigin attribute to configure the CORS requests for Image and Video data element.
79+
* @param {boolean} [options.nocache] - Enable or disable the nocache mechanism.
80+
* @param {boolean} [options.withCredentials] - Indicates whether or not cross-site Access-Control requests should be made using credentials.
81+
* @example
82+
* // Set the crossOrigin attribute to "anonymous"
83+
* me.loader.setOptions({ crossOrigin: "anonymous" });
84+
*
85+
* // Enable the nocache mechanism
86+
* me.loader.setOptions({ nocache: true });
87+
*
88+
* // Enable withCredentials
89+
* me.loader.setOptions({ withCredentials: true });
90+
*/
91+
export function setOptions(options) {
92+
if (options.crossOrigin !== undefined) {
93+
crossOrigin = options.crossOrigin;
94+
}
95+
if (options.nocache !== undefined) {
96+
setNocache(options.nocache);
97+
}
98+
if (options.withCredentials !== undefined) {
99+
withCredentials = options.withCredentials;
100+
}
101+
}
102+
103+
/**
104+
* change the default baseURL for the given asset type.<br>
105+
* (this will prepend the asset URL and must finish with a '/')
106+
* @name setBaseURL
107+
* @memberof loader
108+
* @public
109+
* @param {string} type - "*", "audio", "video", "binary", "image", "json", "js", "tmx", "tsx"
110+
* @param {string} [url="./"] - default base URL
111+
* @example
112+
* // change the base URL relative address for audio assets
113+
* me.loader.setBaseURL("audio", "data/audio/");
114+
* // change the base URL absolute address for all object types
115+
* me.loader.setBaseURL("*", "http://myurl.com/")
116+
*/
117+
export function setBaseURL(type, url) {
118+
if (type !== "*") {
119+
baseURL[type] = url;
120+
} else {
121+
// "wildcards"
122+
baseURL["audio"] = url;
123+
baseURL["video"] = url;
124+
baseURL["binary"] = url;
125+
baseURL["image"] = url;
126+
baseURL["json"] = url;
127+
baseURL["js"] = url;
128+
baseURL["tmx"] = url;
129+
baseURL["tsx"] = url;
130+
// XXX ?
131+
//baseURL["fontface"] = url;
132+
}
133+
}
24134

25135
/**
26136
* onload callback
@@ -375,7 +485,11 @@ export function load(asset, onload, onerror) {
375485
}
376486

377487
// parser returns the amount of asset to be loaded (usually 1 unless an asset is splitted into several ones)
378-
return parser.call(this, asset, onload, onerror);
488+
return parser.call(this, asset, onload, onerror, {
489+
nocache: nocache,
490+
crossOrigin: crossOrigin,
491+
withCredentials: withCredentials
492+
});
379493
}
380494

381495
/**

src/loader/parsers/binary.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@ import { fetchData } from "./fetchdata.js";
66
* @param {loader.Asset} data - asset data
77
* @param {Function} [onload] - function to be called when the asset is loaded
88
* @param {Function} [onerror] - function to be called in case of error
9+
* @param {Object} [settings] - Additional settings to be passed when loading the asset
910
* @returns {number} the amount of corresponding resource parsed/preloaded
1011
* @ignore
1112
*/
12-
export function preloadBinary(data, onload, onerror) {
13+
export function preloadBinary(data, onload, onerror, settings) {
1314

14-
fetchData(data.src, "arrayBuffer")
15+
fetchData(data.src, "arrayBuffer", settings)
1516
.then(response => {
1617
// this method is native and might be slightly more efficient
1718
const decoder = new TextDecoder(); // the default for this is 'utf-8'

src/loader/parsers/fetchdata.js

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import { nocache, crossOrigin, withCredentials } from "../settings.js";
2-
31
/**
42
* Fetches data from the specified URL.
53
* @param {string} url - The URL to fetch the data from.
64
* @param {string} responseType - The type of response expected ('json', 'text', 'blob', 'arrayBuffer').
5+
* @param {Object} [settings] - custom settings to apply to the request (@link https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)
76
* @returns {Promise} A promise that resolves with the fetched data or rejects with an error.
87
* @example
98
* fetchData('https://api.example.com/data', 'json')
@@ -14,15 +13,18 @@ import { nocache, crossOrigin, withCredentials } from "../settings.js";
1413
* // Handle the error
1514
* });
1615
*/
17-
export function fetchData(url, responseType) {
16+
export function fetchData(url, responseType, settings = {}) {
17+
console.log("cache", settings.nocache);
18+
console.log("crossOrigin", settings.crossOrigin);
19+
console.log("withCredentials", settings.withCredentials);
1820
return new Promise((resolve, reject) => {
1921
fetch(url, {
2022
method: "GET",
2123
// internally nocache is a string with a generated random number
22-
cache: nocache === "" ? "no-cache" : "reload",
23-
credentials: withCredentials ? "include" : "omit",
24+
cache: settings.nocache === "" ? "no-cache" : "reload",
25+
credentials: settings.withCredentials === true ? "include" : "omit",
2426
// see setting.crossorigin, "anonymous" is used for cross-origin requests
25-
mode: crossOrigin === "anonymous" ? "cors" : "no-cors"
27+
mode: settings.crossOrigin === "anonymous" ? "cors" : "no-cors"
2628
})
2729
.then(response => {
2830
if (!response.ok) {

src/loader/parsers/image.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as fileUtil from "./../../utils/file.js";
77
* @param {loader.Asset} img
88
* @param {Function} [onload] - function to be called when the resource is loaded
99
* @param {Function} [onerror] - function to be called in case of error
10+
* @param {Object} [settings] - Additional settings to be passed when loading the asset
1011
* @returns {number} the amount of corresponding resource parsed/preloaded
1112
* @ignore
1213
* @example
@@ -17,7 +18,7 @@ import * as fileUtil from "./../../utils/file.js";
1718
* { name : 'image4', src : 'images/image4.png'}
1819
* ]);
1920
*/
20-
export function preloadImage(img, onload, onerror) {
21+
export function preloadImage(img, onload, onerror, settings) {
2122
if (typeof imgList[img.name] !== "undefined") {
2223
// already loaded
2324
return 0;
@@ -26,7 +27,7 @@ export function preloadImage(img, onload, onerror) {
2627
// handle SVG file loading
2728
if (fileUtil.getExtension(img.src) === "svg") {
2829
// handle SVG file
29-
fetchData(img.src, "text")
30+
fetchData(img.src, "text", settings)
3031
.then(svgText => {
3132
const svgImage = new Image();
3233
svgImage.onload = function() {
@@ -50,7 +51,7 @@ export function preloadImage(img, onload, onerror) {
5051
});
5152
} else {
5253
// handle all other image files
53-
fetchData(img.src, "blob")
54+
fetchData(img.src, "blob", settings)
5455
.then(blob => {
5556
globalThis.createImageBitmap(blob)
5657
.then((bitmap) => {

src/loader/parsers/json.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@ import { fetchData } from "./fetchdata.js";
44
/**
55
* parse/preload a JSON files
66
* @param {loader.Asset} data - asset data
7-
* @param {Function} [onload] - function to be called when the asset is loaded
7+
* @param {Function} [onload] - function to be called when the resource is loaded
88
* @param {Function} [onerror] - function to be called in case of error
9+
* @param {Object} [settings] - Additional settings to be passed when loading the asset
910
* @returns {number} the amount of corresponding resource parsed/preloaded
1011
* @ignore
1112
*/
12-
export function preloadJSON(data, onload, onerror) {
13+
export function preloadJSON(data, onload, onerror, settings) {
1314
if (typeof jsonList[data.name] !== "undefined") {
1415
// already loaded
1516
return 0;
1617
}
1718

18-
fetchData(data.src, "json")
19+
fetchData(data.src, "json", settings)
1920
.then(response => {
2021
jsonList[data.name] = response;
2122
if (typeof onload === "function") {

src/loader/parsers/script.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
1-
import { crossOrigin } from "../settings.js";
2-
31
/**
42
* parse/preload a Javascript files
53
* @param {loader.Asset} data - asset data
6-
* @param {Function} [onload] - function to be called when the asset is loaded
4+
* @param {Function} [onload] - function to be called when the resource is loaded
75
* @param {Function} [onerror] - function to be called in case of error
6+
* @param {Object} [settings] - Additional settings to be passed when loading the asset
87
* @returns {number} the amount of corresponding resource parsed/preloaded
98
* @ignore
109
*/
11-
export function preloadJavascript(data, onload, onerror) {
10+
export function preloadJavascript(data, onload, onerror, settings) {
1211
let script = globalThis.document.createElement("script");
1312

1413
script.src = data.src;
1514
script.type = "text/javascript";
1615
if (typeof (crossOrigin) === "string") {
17-
script.crossOrigin = crossOrigin;
16+
script.crossOrigin = settings.crossOrigin;
1817
}
1918
script.defer = true;
2019

src/loader/parsers/tmx.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ import { fetchData } from "./fetchdata.js";
99
* parse/preload a TMX file
1010
* @param {loader.Asset} data - asset data
1111
* @param {Function} [onload] - function to be called when the asset is loaded
12+
* @param {Function} [onload] - function to be called when the resource is loaded
1213
* @param {Function} [onerror] - function to be called in case of error
13-
* @param {Function} [fetchData] - function to use instead of default window.fetch, has some error handling and things
14+
* @param {Object} [settings] - Additional settings to be passed when loading the asset
1415
* @returns {number} the amount of corresponding resource parsed/preloaded
1516
* @ignore
1617
*/
17-
export function preloadTMX(tmxData, onload, onerror) {
18+
export function preloadTMX(tmxData, onload, onerror, settings) {
1819
if (typeof tmxList[tmxData.name] !== "undefined") {
1920
// already loaded
2021
return 0;
@@ -42,7 +43,7 @@ export function preloadTMX(tmxData, onload, onerror) {
4243
return;
4344
}
4445

45-
fetchData(tmxData.src, "text")
46+
fetchData(tmxData.src, "text", settings)
4647
.then(response => {
4748
if (typeof response !== "string") {
4849
throw new Error("Invalid response type");

src/loader/parsers/video.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@ import { videoList } from "../cache.js";
22
import { fetchData } from "./fetchdata.js";
33
import { hasVideoFormat } from "../../system/device.js";
44
import * as fileUtil from "../../utils/file.js";
5-
import { crossOrigin } from "../settings.js";
65
import { isDataUrl } from "./../../utils/string.js";
76

87
/**
98
* parse/preload a Video file
109
* @param {loader.Asset} data - asset data
11-
* @param {Function} [onload] - function to be called when the asset is loaded
10+
* @param {Function} [onload] - function to be called when the resource is loaded
1211
* @param {Function} [onerror] - function to be called in case of error
12+
* @param {Object} [settings] - Additional settings to be passed when loading the asset
1313
* @returns {number} the amount of corresponding resource parsed/preloaded
1414
* @ignore
1515
*/
16-
export function preloadVideo(data, onload, onerror) {
16+
export function preloadVideo(data, onload, onerror, settings) {
1717

1818
if (typeof videoList[data.name] !== "undefined") {
1919
// Video already preloaded
@@ -34,7 +34,7 @@ export function preloadVideo(data, onload, onerror) {
3434
}
3535

3636
if (isDataUrl(data.src)) {
37-
fetchData(data.src, "blob")
37+
fetchData(data.src, "blob", settings)
3838
.then(blob => {
3939
videoElement.src = globalThis.URL.createObjectURL(blob);
4040
})
@@ -52,7 +52,7 @@ export function preloadVideo(data, onload, onerror) {
5252
videoElement.setAttribute("playsinline", "true");
5353
videoElement.setAttribute("disablePictureInPicture", "true");
5454
videoElement.setAttribute("controls", "false");
55-
videoElement.setAttribute("crossorigin", crossOrigin);
55+
videoElement.setAttribute("crossorigin", settings.crossOrigin);
5656

5757
if (data.autoplay === true) {
5858
videoElement.setAttribute("autoplay", "true");

0 commit comments

Comments
 (0)
X Tutup