/
Resolver.ts
840 lines (742 loc) · 28.4 KB
/
Resolver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
import { utils } from '@pixi/core';
import { convertToList } from '../utils/convertToList';
import { createStringVariations } from '../utils/createStringVariations';
import { isSingleItem } from '../utils/isSingleItem';
import type {
ArrayOr,
AssetsBundle,
AssetsManifest,
AssetSrc,
LoadParserName,
ResolvedAsset,
ResolvedSrc,
UnresolvedAsset,
UnresolvedAssetObject
} from '../types';
import type { PreferOrder, ResolveURLParser } from './types';
export interface BundleIdentifierOptions
{
/** The character that is used to connect the bundleId and the assetId when generating a bundle asset id key */
connector?: string;
/**
* A function that generates a bundle asset id key from a bundleId and an assetId
* @param bundleId - the bundleId
* @param assetId - the assetId
* @returns the bundle asset id key
*/
createBundleAssetId?: (bundleId: string, assetId: string) => string;
/**
* A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId
* @param bundleId - the bundleId
* @param assetBundleId - the bundle asset id key
* @returns the assetId
*/
extractAssetIdFromBundle?: (bundleId: string, assetBundleId: string) => string;
}
/**
* A class that is responsible for resolving mapping asset URLs to keys.
* At its most basic it can be used for Aliases:
*
* ```js
* resolver.add('foo', 'bar');
* resolver.resolveUrl('foo') // => 'bar'
* ```
*
* It can also be used to resolve the most appropriate asset for a given URL:
*
* ```js
* resolver.prefer({
* params: {
* format: 'webp',
* resolution: 2,
* }
* });
*
* resolver.add('foo', ['bar@2x.webp', 'bar@2x.png', 'bar.webp', 'bar.png']);
*
* resolver.resolveUrl('foo') // => 'bar@2x.webp'
* ```
* Other features include:
* - Ability to process a manifest file to get the correct understanding of how to resolve all assets
* - Ability to add custom parsers for specific file types
* - Ability to add custom prefer rules
*
* This class only cares about the URL, not the loading of the asset itself.
*
* It is not intended that this class is created by developers - its part of the Asset class
* This is the third major system of PixiJS' main Assets class
* @memberof PIXI
*/
export class Resolver
{
private _defaultBundleIdentifierOptions: Required<BundleIdentifierOptions> = {
connector: '-',
createBundleAssetId: (bundleId, assetId) =>
`${bundleId}${this._bundleIdConnector}${assetId}`,
extractAssetIdFromBundle: (bundleId, assetBundleId) =>
assetBundleId.replace(`${bundleId}${this._bundleIdConnector}`, ''),
};
/** The character that is used to connect the bundleId and the assetId when generating a bundle asset id key */
private _bundleIdConnector = this._defaultBundleIdentifierOptions.connector;
/**
* A function that generates a bundle asset id key from a bundleId and an assetId
* @param bundleId - the bundleId
* @param assetId - the assetId
* @returns the bundle asset id key
*/
private _createBundleAssetId: (
bundleId: string,
assetId: string
) => string = this._defaultBundleIdentifierOptions.createBundleAssetId;
/**
* A function that generates an assetId from a bundle asset id key. This is the reverse of generateBundleAssetId
* @param bundleId - the bundleId
* @param assetBundleId - the bundle asset id key
* @returns the assetId
*/
private _extractAssetIdFromBundle: (
bundleId: string,
assetBundleId: string
) => string = this._defaultBundleIdentifierOptions.extractAssetIdFromBundle;
private _assetMap: Record<string, ResolvedAsset[]> = {};
private _preferredOrder: PreferOrder[] = [];
private _parsers: ResolveURLParser[] = [];
private _resolverHash: Record<string, ResolvedAsset> = {};
private _rootPath: string;
private _basePath: string;
private _manifest: AssetsManifest;
private _bundles: Record<string, string[]> = {};
private _defaultSearchParams: string;
/**
* Override how the resolver deals with generating bundle ids.
* must be called before any bundles are added
* @param bundleIdentifier - the bundle identifier options
*/
public setBundleIdentifier(bundleIdentifier: BundleIdentifierOptions): void
{
this._bundleIdConnector = bundleIdentifier.connector ?? this._bundleIdConnector;
this._createBundleAssetId = bundleIdentifier.createBundleAssetId ?? this._createBundleAssetId;
this._extractAssetIdFromBundle = bundleIdentifier.extractAssetIdFromBundle ?? this._extractAssetIdFromBundle;
if (this._extractAssetIdFromBundle('foo', this._createBundleAssetId('foo', 'bar')) !== 'bar')
{
throw new Error('[Resolver] GenerateBundleAssetId are not working correctly');
}
}
/**
* Let the resolver know which assets you prefer to use when resolving assets.
* Multiple prefer user defined rules can be added.
* @example
* resolver.prefer({
* // first look for something with the correct format, and then then correct resolution
* priority: ['format', 'resolution'],
* params:{
* format:'webp', // prefer webp images
* resolution: 2, // prefer a resolution of 2
* }
* })
* resolver.add('foo', ['bar@2x.webp', 'bar@2x.png', 'bar.webp', 'bar.png']);
* resolver.resolveUrl('foo') // => 'bar@2x.webp'
* @param preferOrders - the prefer options
*/
public prefer(...preferOrders: PreferOrder[]): void
{
preferOrders.forEach((prefer) =>
{
this._preferredOrder.push(prefer);
if (!prefer.priority)
{
// generate the priority based on the order of the object
prefer.priority = Object.keys(prefer.params);
}
});
this._resolverHash = {};
}
/**
* Set the base path to prepend to all urls when resolving
* @example
* resolver.basePath = 'https://home.com/';
* resolver.add('foo', 'bar.ong');
* resolver.resolveUrl('foo', 'bar.png'); // => 'https://home.com/bar.png'
* @param basePath - the base path to use
*/
public set basePath(basePath: string)
{
this._basePath = basePath;
}
public get basePath(): string
{
return this._basePath;
}
/**
* Set the root path for root-relative URLs. By default the `basePath`'s root is used. If no `basePath` is set, then the
* default value for browsers is `window.location.origin`
* @example
* // Application hosted on https://home.com/some-path/index.html
* resolver.basePath = 'https://home.com/some-path/';
* resolver.rootPath = 'https://home.com/';
* resolver.add('foo', '/bar.png');
* resolver.resolveUrl('foo', '/bar.png'); // => 'https://home.com/bar.png'
* @param rootPath - the root path to use
*/
public set rootPath(rootPath: string)
{
this._rootPath = rootPath;
}
public get rootPath(): string
{
return this._rootPath;
}
/**
* All the active URL parsers that help the parser to extract information and create
* an asset object-based on parsing the URL itself.
*
* Can be added using the extensions API
* @example
* resolver.add('foo', [
* {
* resolution: 2,
* format: 'png',
* src: 'image@2x.png',
* },
* {
* resolution:1,
* format:'png',
* src: 'image.png',
* },
* ]);
*
* // With a url parser the information such as resolution and file format could extracted from the url itself:
* extensions.add({
* extension: ExtensionType.ResolveParser,
* test: loadTextures.test, // test if url ends in an image
* parse: (value: string) =>
* ({
* resolution: parseFloat(settings.RETINA_PREFIX.exec(value)?.[1] ?? '1'),
* format: value.split('.').pop(),
* src: value,
* }),
* });
*
* // Now resolution and format can be extracted from the url
* resolver.add('foo', [
* 'image@2x.png',
* 'image.png',
* ]);
*/
public get parsers(): ResolveURLParser[]
{
return this._parsers;
}
/** Used for testing, this resets the resolver to its initial state */
public reset(): void
{
this.setBundleIdentifier(this._defaultBundleIdentifierOptions);
this._assetMap = {};
this._preferredOrder = [];
// Do not reset this._parsers
this._resolverHash = {};
this._rootPath = null;
this._basePath = null;
this._manifest = null;
this._bundles = {};
this._defaultSearchParams = null;
}
/**
* Sets the default URL search parameters for the URL resolver. The urls can be specified as a string or an object.
* @param searchParams - the default url parameters to append when resolving urls
*/
public setDefaultSearchParams(searchParams: string | Record<string, unknown>): void
{
if (typeof searchParams === 'string')
{
this._defaultSearchParams = searchParams;
}
else
{
const queryValues = searchParams as Record<string, any>;
this._defaultSearchParams = Object.keys(queryValues)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(queryValues[key])}`)
.join('&');
}
}
/**
* Returns the aliases for a given asset
* @param asset - the asset to get the aliases for
*/
public getAlias(asset: UnresolvedAsset): string[]
{
const { alias, name, src, srcs } = asset;
const aliasesToUse = convertToList<ArrayOr<string | AssetSrc>>(
alias || name || src || srcs, (value: string | AssetSrc) =>
{
if (typeof value === 'string') return value;
if (Array.isArray(value)) return value.map((v) => (v as ResolvedSrc)?.src ?? (v as ResolvedSrc)?.srcs ?? v);
if (value?.src || value?.srcs) return value.src ?? value.srcs;
return value;
}, true) as string[];
return aliasesToUse;
}
/**
* Add a manifest to the asset resolver. This is a nice way to add all the asset information in one go.
* generally a manifest would be built using a tool.
* @param manifest - the manifest to add to the resolver
*/
public addManifest(manifest: AssetsManifest): void
{
if (this._manifest)
{
if (process.env.DEBUG)
{
console.warn('[Resolver] Manifest already exists, this will be overwritten');
}
}
this._manifest = manifest;
manifest.bundles.forEach((bundle) =>
{
this.addBundle(bundle.name, bundle.assets);
});
}
/**
* This adds a bundle of assets in one go so that you can resolve them as a group.
* For example you could add a bundle for each screen in you pixi app
* @example
* resolver.addBundle('animals', {
* bunny: 'bunny.png',
* chicken: 'chicken.png',
* thumper: 'thumper.png',
* });
*
* const resolvedAssets = await resolver.resolveBundle('animals');
* @param bundleId - The id of the bundle to add
* @param assets - A record of the asset or assets that will be chosen from when loading via the specified key
*/
public addBundle(bundleId: string, assets: AssetsBundle['assets']): void
{
const assetNames: string[] = [];
// when storing keys against a bundle we prepend the bundleId to each asset key
// and pass it through as an additional alias for the asset
// this keeps clashing ids separate on a per-bundle basis
// you can also resolve a file using the bundleId-assetId syntax
if (Array.isArray(assets))
{
assets.forEach((asset) =>
{
const srcs = asset.src ?? asset.srcs;
const aliases = asset.alias ?? asset.name;
let ids: string[];
if (typeof aliases === 'string')
{
const bundleAssetId = this._createBundleAssetId(bundleId, aliases);
assetNames.push(bundleAssetId);
ids = [aliases, bundleAssetId];
}
else
{
const bundleIds = aliases.map((name) => this._createBundleAssetId(bundleId, name));
assetNames.push(...bundleIds);
ids = [...aliases, ...bundleIds];
}
this.add({
...asset,
...{
alias: ids,
src: srcs,
}
});
});
}
else
{
Object.keys(assets).forEach((key) =>
{
const aliases: string[] = [key, this._createBundleAssetId(bundleId, key)];
if (typeof assets[key] === 'string')
{
this.add({
alias: aliases,
src: assets[key] as string,
});
}
else if (Array.isArray(assets[key]))
{
this.add({
alias: aliases,
src: assets[key] as string[],
});
}
else
{
const asset = assets[key] as UnresolvedAssetObject;
const assetSrc = asset.src ?? asset.srcs;
this.add({
...asset,
...{
alias: aliases,
src: Array.isArray(assetSrc) ? assetSrc : [assetSrc],
}
});
}
assetNames.push(...aliases);
});
}
this._bundles[bundleId] = assetNames;
}
/** @deprecated */
public add(a: ArrayOr<string>, s?: AssetSrc, d?: unknown, f?: string, lp?: LoadParserName): void;
/**
* Tells the resolver what keys are associated with witch asset.
* The most important thing the resolver does
* @example
* // Single key, single asset:
* resolver.add({alias: 'foo', src: 'bar.png');
* resolver.resolveUrl('foo') // => 'bar.png'
*
* // Multiple keys, single asset:
* resolver.add({alias: ['foo', 'boo'], src: 'bar.png'});
* resolver.resolveUrl('foo') // => 'bar.png'
* resolver.resolveUrl('boo') // => 'bar.png'
*
* // Multiple keys, multiple assets:
* resolver.add({alias: ['foo', 'boo'], src: ['bar.png', 'bar.webp']});
* resolver.resolveUrl('foo') // => 'bar.png'
*
* // Add custom data attached to the resolver
* Resolver.add({
* alias: 'bunnyBooBooSmooth',
* src: 'bunny{png,webp}',
* data: { scaleMode:SCALE_MODES.NEAREST }, // Base texture options
* });
*
* resolver.resolve('bunnyBooBooSmooth') // => { src: 'bunny.png', data: { scaleMode: SCALE_MODES.NEAREST } }
* @param data - the data to add to the resolver
* @param data.aliases - the key or keys that you will reference when loading this asset
* @param data.srcs - the asset or assets that will be chosen from when loading via the specified key
* @param data.data - asset-specific data that will be passed to the loaders
* - Useful if you want to initiate loaded objects with specific data
* @param data.format - the format of the asset
* @param data.loadParser - the name of the load parser to use
*/
public add(data:(ArrayOr<UnresolvedAsset>)): void;
public add(
aliases: ArrayOr<string> | (ArrayOr<UnresolvedAsset>),
srcs?: AssetSrc,
data?: unknown,
format?: string,
loadParser?: LoadParserName
): void
{
const assets: UnresolvedAsset[] = [];
if (typeof aliases === 'string' || (Array.isArray(aliases) && typeof aliases[0] === 'string'))
{
if (process.env.DEBUG)
{
// eslint-disable-next-line max-len
utils.deprecation('7.2.0', `Assets.add now uses an object instead of individual parameters.\nPlease use Assets.add({ alias, src, data, format, loadParser }) instead.`);
}
assets.push({ alias: aliases as ArrayOr<string>, src: srcs, data, format, loadParser });
}
else if (Array.isArray(aliases))
{
assets.push(...(aliases as UnresolvedAsset[]));
}
else
{
assets.push(aliases as UnresolvedAsset);
}
let keyCheck: (key: string) => void;
if (process.env.DEBUG)
{
keyCheck = (key: string) =>
{
if (this.hasKey(key))
{
console.warn(`[Resolver] already has key: ${key} overwriting`);
}
};
}
const assetArray = convertToList(assets);
// loop through all the assets and generate a resolve asset for each src
assetArray.forEach((asset) =>
{
const { src, srcs } = asset;
let { data, format, loadParser } = asset;
// src can contain an unresolved asset itself
// so we need to merge that data with the current asset
// we dont need to create string variations for the src if it is a ResolvedAsset
const srcsToUse: (string | ResolvedSrc)[][] = convertToList<AssetSrc>(src || srcs).map((src) =>
{
if (typeof src === 'string')
{ return createStringVariations(src); }
return Array.isArray(src) ? src : [src];
});
const aliasesToUse = this.getAlias(asset);
if (process.env.DEBUG)
{
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
Array.isArray(aliasesToUse) ? aliasesToUse.forEach(keyCheck) : keyCheck(aliasesToUse);
}
// loop through all the srcs and generate a resolve asset for each src
const resolvedAssets: ResolvedAsset[] = [];
srcsToUse.forEach((srcs) =>
{
srcs.forEach((src) =>
{
let formattedAsset = {} as ResolvedAsset;
if (typeof src !== 'object')
{
formattedAsset.src = src;
// first see if it contains any {} tags...
for (let i = 0; i < this._parsers.length; i++)
{
const parser = this._parsers[i];
if (parser.test(src))
{
formattedAsset = parser.parse(src);
break;
}
}
}
else
{
data = src.data ?? data;
format = src.format ?? format;
loadParser = src.loadParser ?? loadParser;
formattedAsset = {
...formattedAsset,
...src,
};
}
// check if aliases is undefined
if (!aliasesToUse)
{
throw new Error(`[Resolver] alias is undefined for this asset: ${formattedAsset.src}`);
}
formattedAsset = this.buildResolvedAsset(formattedAsset, {
aliases: aliasesToUse,
data,
format,
loadParser,
});
resolvedAssets.push(formattedAsset);
});
});
aliasesToUse.forEach((alias) =>
{
this._assetMap[alias] = resolvedAssets;
});
});
}
// TODO: this needs an overload like load did in Assets
/**
* If the resolver has had a manifest set via setManifest, this will return the assets urls for
* a given bundleId or bundleIds.
* @example
* // Manifest Example
* const manifest = {
* bundles: [
* {
* name: 'load-screen',
* assets: [
* {
* alias: 'background',
* src: 'sunset.png',
* },
* {
* alias: 'bar',
* src: 'load-bar.{png,webp}',
* },
* ],
* },
* {
* name: 'game-screen',
* assets: [
* {
* alias: 'character',
* src: 'robot.png',
* },
* {
* alias: 'enemy',
* src: 'bad-guy.png',
* },
* ],
* },
* ]
* };
*
* resolver.setManifest(manifest);
* const resolved = resolver.resolveBundle('load-screen');
* @param bundleIds - The bundle ids to resolve
* @returns All the bundles assets or a hash of assets for each bundle specified
*/
public resolveBundle(bundleIds: ArrayOr<string>):
Record<string, ResolvedAsset> | Record<string, Record<string, ResolvedAsset>>
{
const singleAsset = isSingleItem(bundleIds);
bundleIds = convertToList<string>(bundleIds);
const out: Record<string, Record<string, ResolvedAsset>> = {};
bundleIds.forEach((bundleId) =>
{
const assetNames = this._bundles[bundleId];
if (assetNames)
{
const results = this.resolve(assetNames) as Record<string, ResolvedAsset>;
const assets: Record<string, ResolvedAsset> = {};
for (const key in results)
{
const asset = results[key];
assets[this._extractAssetIdFromBundle(bundleId, key)] = asset;
}
out[bundleId] = assets;
}
});
return singleAsset ? out[bundleIds[0]] : out;
}
/**
* Does exactly what resolve does, but returns just the URL rather than the whole asset object
* @param key - The key or keys to resolve
* @returns - The URLs associated with the key(s)
*/
public resolveUrl(key: ArrayOr<string>): string | Record<string, string>
{
const result = this.resolve(key as string) as ResolvedAsset | Record<string, ResolvedAsset>;
if (typeof key !== 'string')
{
const out: Record<string, string> = {};
for (const i in result)
{
out[i] = (result as Record<string, ResolvedAsset>)[i].src;
}
return out;
}
return (result as ResolvedAsset).src;
}
/**
* Resolves each key in the list to an asset object.
* Another key function of the resolver! After adding all the various key/asset pairs. this will run the logic
* of finding which asset to return based on any preferences set using the `prefer` function
* by default the same key passed in will be returned if nothing is matched by the resolver.
* @example
* resolver.add('boo', 'bunny.png');
*
* resolver.resolve('boo') // => { src: 'bunny.png' }
*
* // Will return the same string as no key was added for this value..
* resolver.resolve('another-thing.png') // => { src: 'another-thing.png' }
* @param keys - key or keys to resolve
* @returns - the resolve asset or a hash of resolve assets for each key specified
*/
public resolve(keys: string): ResolvedAsset;
public resolve(keys: string[]): Record<string, ResolvedAsset>;
public resolve(keys: ArrayOr<string>): ResolvedAsset | Record<string, ResolvedAsset>
{
const singleAsset = isSingleItem(keys);
keys = convertToList<string>(keys);
const result: Record<string, ResolvedAsset> = {};
keys.forEach((key) =>
{
if (!this._resolverHash[key])
{
if (this._assetMap[key])
{
let assets = this._assetMap[key];
const bestAsset = assets[0];
const preferredOrder = this._getPreferredOrder(assets);
preferredOrder?.priority.forEach((priorityKey) =>
{
preferredOrder.params[priorityKey].forEach((value: unknown) =>
{
const filteredAssets = assets.filter((asset) =>
{
if (asset[priorityKey as keyof ResolvedAsset])
{
return asset[priorityKey as keyof ResolvedAsset] === value;
}
return false;
});
if (filteredAssets.length)
{
assets = filteredAssets;
}
});
});
this._resolverHash[key] = (assets[0] ?? bestAsset);
}
else
{
this._resolverHash[key] = this.buildResolvedAsset({
alias: [key],
src: key,
}, {});
}
}
result[key] = this._resolverHash[key];
});
return singleAsset ? result[keys[0]] : result;
}
/**
* Checks if an asset with a given key exists in the resolver
* @param key - The key of the asset
*/
public hasKey(key: string): boolean
{
return !!this._assetMap[key];
}
/**
* Checks if a bundle with the given key exists in the resolver
* @param key - The key of the bundle
*/
public hasBundle(key: string): boolean
{
return !!this._bundles[key];
}
/**
* Internal function for figuring out what prefer criteria an asset should use.
* @param assets
*/
private _getPreferredOrder(assets: ResolvedAsset[]): PreferOrder
{
for (let i = 0; i < assets.length; i++)
{
const asset = assets[0];
const preferred = this._preferredOrder.find((preference: PreferOrder) =>
preference.params.format.includes(asset.format));
if (preferred)
{
return preferred;
}
}
return this._preferredOrder[0];
}
/**
* Appends the default url parameters to the url
* @param url - The url to append the default parameters to
* @returns - The url with the default parameters appended
*/
private _appendDefaultSearchParams(url: string): string
{
if (!this._defaultSearchParams) return url;
const paramConnector = (/\?/).test(url) ? '&' : '?';
return `${url}${paramConnector}${this._defaultSearchParams}`;
}
private buildResolvedAsset(formattedAsset: ResolvedAsset, data?: {
aliases?: string[],
data?: Record<string, unknown>
loadParser?: string,
format?: string,
}): ResolvedAsset
{
const { aliases, data: assetData, loadParser, format } = data;
if (this._basePath || this._rootPath)
{
formattedAsset.src = utils.path.toAbsolute(formattedAsset.src, this._basePath, this._rootPath);
}
formattedAsset.alias = aliases ?? formattedAsset.alias ?? [formattedAsset.src];
formattedAsset.src = this._appendDefaultSearchParams(formattedAsset.src);
formattedAsset.data = { ...assetData || {}, ...formattedAsset.data };
formattedAsset.loadParser = loadParser ?? formattedAsset.loadParser;
formattedAsset.format = format ?? utils.path.extname(formattedAsset.src).slice(1);
formattedAsset.srcs = formattedAsset.src;
formattedAsset.name = formattedAsset.alias;
return formattedAsset;
}
}