ruffle/web/packages/core/src/public-path.ts

70 lines
2.3 KiB
TypeScript
Raw Normal View History

/**
* The configuration object to control Ruffle's behaviour on the website
* that it is included on.
*/
interface Config {
/**
* A map of public paths from source name to URL.
*/
public_paths?: Record<string, string>;
/**
* The URL at which Ruffle can load its extra files (ie `.wasm`).
*
* [public_paths] is consulted first for a source-specific URL,
* with this field being a fallback.
*/
public_path?: string;
}
2019-10-15 02:52:53 +00:00
/**
* Attempt to discover the public path of the current Ruffle source. This can
* be used to configure Webpack.
*
2019-10-15 02:52:53 +00:00
* We have several points of configuration for how the Ruffle public path can
* be determined:
*
2019-10-15 02:52:53 +00:00
* 1. The public path can be specified on a per-source basis using the
* RufflePlayer config, for example:
* `window.RufflePlayer.config.public_paths.local = "/dist/";`
2019-10-15 02:52:53 +00:00
* 2. A global public path can be specified for all sources, also in config.
* `window.RufflePlayer.config.public_path = "/dist/";`
2019-10-15 02:52:53 +00:00
* 3. If there is absolutely no configuration that yields a public path then we
* return the parent path of where this script is hosted, which should be
* the correct default in most cases.
*
* @param config The `window.RufflePlayer.config` object.
* @param source_name The name of the source.
* @returns The public path for the given source.
2019-10-15 02:52:53 +00:00
*/
export function public_path(config: Config, source_name: string): string {
let public_path = "";
if (
config !== undefined &&
config.public_paths !== undefined &&
config.public_paths[source_name] !== undefined
) {
public_path = config.public_paths[source_name];
} else if (config !== undefined && config.public_path !== undefined) {
public_path = config.public_path;
} else if (
document.currentScript !== undefined &&
document.currentScript !== null &&
"src" in document.currentScript
) {
// Default to the directory where this script resides.
try {
public_path = new URL(".", document.currentScript.src).href;
} catch (e) {
console.warn("Unable to get currentScript URL");
}
2019-10-15 02:52:53 +00:00
}
// Webpack expects the paths to end with a /.
if (public_path !== "" && !public_path.endsWith("/")) {
public_path += "/";
}
return public_path;
}