@dioramajs/assets 0.0.0-stage → 0.1.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.
package/src/loaders.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { AssetError } from './errors'
2
+ import { abortError } from './queue'
3
+ import type { AssetLoader, Loaded, LoaderContext } from './types'
4
+
5
+ /** Resolves once the image has loaded, or rejects with ASSET_LOAD. Aborting stops the request. */
6
+ export function loaded(img: HTMLImageElement, url: string, signal: AbortSignal): Promise<void> {
7
+ return new Promise((resolve, reject) => {
8
+ if (signal.aborted) return reject(abortError())
9
+ // A cached image may be complete at once. happy-dom never loads and reports complete.
10
+ if (img.complete && (img.currentSrc || img.src)) return resolve()
11
+ const done = (): void => {
12
+ img.removeEventListener('load', ok)
13
+ img.removeEventListener('error', fail)
14
+ signal.removeEventListener('abort', abort)
15
+ }
16
+ const ok = (): void => {
17
+ done()
18
+ resolve()
19
+ }
20
+ const fail = (): void => {
21
+ done()
22
+ // In CORS mode a server without Access-Control-Allow-Origin fails the same way as a 404.
23
+ const foreign = new URL(url, location.href).origin !== location.origin
24
+ const hint =
25
+ foreign && img.crossOrigin !== null
26
+ ? ': is it served with Access-Control-Allow-Origin?'
27
+ : ''
28
+ reject(new AssetError('ASSET_LOAD', `cannot load ${url}${hint}`, { url }))
29
+ }
30
+ const abort = (): void => {
31
+ done()
32
+ img.removeAttribute('srcset')
33
+ img.removeAttribute('src')
34
+ reject(abortError())
35
+ }
36
+ img.addEventListener('load', ok)
37
+ img.addEventListener('error', fail)
38
+ signal.addEventListener('abort', abort)
39
+ })
40
+ }
41
+
42
+ const FLIP: ImageBitmapOptions = { imageOrientation: 'flipY' }
43
+
44
+ /**
45
+ * The image's bytes decoded, or `undefined` when they cannot be read. Chrome decodes a Blob off
46
+ * the main thread, but an <img> on it: about 60 ms for 1920×1080. The bytes come from the HTTP
47
+ * cache, where the image left them. Mirrors `fromBytes` of the effects pool.
48
+ */
49
+ async function fromBytes(img: HTMLImageElement): Promise<ImageBitmap | undefined> {
50
+ try {
51
+ const mode = img.crossOrigin
52
+ const target = new URL(img.currentSrc || img.src, location.href)
53
+ // A no-CORS image of another origin: opaque bytes, and pixels no texture may use anyway
54
+ if (mode === null && target.origin !== location.origin && target.protocol !== 'data:') return
55
+ const response = await fetch(target, {
56
+ credentials: mode === 'use-credentials' ? 'include' : 'same-origin',
57
+ cache: 'force-cache',
58
+ })
59
+ if (!response.ok) return
60
+ return await createImageBitmap(await response.blob(), FLIP)
61
+ } catch {
62
+ return undefined
63
+ }
64
+ }
65
+
66
+ /** Shared with the effects pool. Decodes, then flips the pixels like effects textures. */
67
+ export async function bitmap(img: HTMLImageElement, url: string): Promise<Loaded<ImageBitmap>> {
68
+ try {
69
+ let pixels = await fromBytes(img)
70
+ if (!pixels) {
71
+ await img.decode()
72
+ pixels = await createImageBitmap(img, FLIP)
73
+ }
74
+ return {
75
+ value: pixels,
76
+ bytes: pixels.width * pixels.height * 4,
77
+ dispose: () => pixels.close(),
78
+ }
79
+ } catch (cause) {
80
+ throw new AssetError('ASSET_PARSE', `cannot decode ${url}`, { url, cause })
81
+ }
82
+ }
83
+
84
+ /** A detached image. The browser makes the request, then it takes a decode slot. */
85
+ export const image: AssetLoader<ImageBitmap> = {
86
+ async load(context) {
87
+ const img = new Image()
88
+ if (context.crossOrigin) img.crossOrigin = context.crossOrigin
89
+ if (context.priority !== 'normal') img.setAttribute('fetchpriority', context.priority)
90
+ img.src = context.url
91
+ await loaded(img, context.url, context.signal)
92
+ return context.decode(() => bitmap(img, context.url))
93
+ },
94
+ }
95
+
96
+ async function body(context: LoaderContext): Promise<ArrayBuffer> {
97
+ return context.bytes(await context.fetch())
98
+ }
99
+
100
+ export const buffer: AssetLoader<ArrayBuffer> = {
101
+ async load(context) {
102
+ const value = await body(context)
103
+ return { value, bytes: value.byteLength }
104
+ },
105
+ }
106
+
107
+ export const json: AssetLoader<unknown> = {
108
+ async load(context) {
109
+ const bytes = await body(context)
110
+ try {
111
+ return { value: JSON.parse(new TextDecoder().decode(bytes)), bytes: bytes.byteLength }
112
+ } catch (cause) {
113
+ throw new AssetError('ASSET_PARSE', `${context.url} is not JSON`, {
114
+ url: context.url,
115
+ cause,
116
+ })
117
+ }
118
+ },
119
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,315 @@
1
+ import {
2
+ definePlugin,
3
+ isCancel,
4
+ type Off,
5
+ type Plugin,
6
+ type PluginApp,
7
+ signal,
8
+ } from '@dioramajs/core'
9
+ import type { RenderApi } from '@dioramajs/render'
10
+ import { Cache, ESTIMATE, type Make, type Spec } from './cache'
11
+ import { AssetError, DEV, linked, noop } from './errors'
12
+ import { absolute, BY_EXTENSION, extensionOf, keyOf, parseKey, textureCors } from './keys'
13
+ import { buffer, image, json } from './loaders'
14
+ import { frugal, Preloads } from './preload'
15
+ import { abortError, Queue } from './queue'
16
+ import type {
17
+ Asset,
18
+ AssetLoader,
19
+ AssetStatus,
20
+ AssetsApi,
21
+ AssetsOptions,
22
+ LoadOptions,
23
+ Preload,
24
+ } from './types'
25
+ import { Wave } from './wave'
26
+
27
+ type View = PluginApp<{ readonly render?: RenderApi }>
28
+ type ThreeModule = typeof import('./three/index')
29
+
30
+ const BUILT_IN: Readonly<Record<string, AssetLoader>> = { image, buffer, json }
31
+ const THREE_TYPES = ['texture', 'gltf', 'ktx2'] as const
32
+ /** KTX2 waits for `render`. Show a development hint after this long. */
33
+ const RENDER_WAIT_MS = 5000
34
+
35
+ const defaults: AssetsOptions = {
36
+ loaders: {},
37
+ decoders: {},
38
+ concurrency: 6,
39
+ retain: 32 * 1024 * 1024,
40
+ preload: true,
41
+ }
42
+
43
+ const isThree = (type: string): type is (typeof THREE_TYPES)[number] =>
44
+ (THREE_TYPES as readonly string[]).includes(type)
45
+
46
+ /** A lease that failed before it began, for SSR or a URL that doesn't parse. */
47
+ function failed<T>(url: string, error: AssetError): Asset<T> {
48
+ linked(error)
49
+ const ready = Promise.reject(error)
50
+ ready.catch(noop)
51
+ // A fresh function, since the handle carries its own key and url.
52
+ const release = (): void => {}
53
+ return Object.assign(release, {
54
+ release,
55
+ dispose: release,
56
+ key: url,
57
+ url,
58
+ status: signal<AssetStatus>('failed'),
59
+ ready,
60
+ value: undefined,
61
+ error,
62
+ }) as unknown as Asset<T>
63
+ }
64
+
65
+ const settled: Preload = Object.freeze({
66
+ release: noop,
67
+ dispose: noop,
68
+ // biome-ignore lint/suspicious/noThenProperty: a preload is thenable by design
69
+ then: (fulfilled, rejected) => Promise.resolve().then(fulfilled, rejected),
70
+ } satisfies Preload)
71
+
72
+ /** Without a DOM (SSR) loads fail silently and nothing waits. */
73
+ function inert(): AssetsApi {
74
+ const none = (url: string): Asset<never> =>
75
+ failed(url, new AssetError('ASSET_LOAD', 'no DOM to load in', { url }))
76
+ return {
77
+ load: none,
78
+ acquire: none,
79
+ preload: () => settled,
80
+ track: noop,
81
+ pause: () => noop,
82
+ progress: signal(0),
83
+ ready: () => Promise.resolve(),
84
+ stats: () => ({ entries: 0, used: 0, retained: 0, pending: 0 }),
85
+ }
86
+ }
87
+
88
+ /** One cache, queue, wave and preloads per app. */
89
+ class Assets {
90
+ readonly api: AssetsApi
91
+ readonly #app: View
92
+ readonly #options: AssetsOptions
93
+ readonly #queue: Queue
94
+ readonly #wave: Wave
95
+ readonly #cache: Cache
96
+ readonly #preloads: Preloads
97
+ #three: Promise<ThreeModule> | undefined
98
+ #module: ThreeModule | undefined
99
+ #leave: Off | undefined
100
+ #renderer: object | undefined
101
+ #destroying = false
102
+
103
+ constructor(app: View, options: AssetsOptions) {
104
+ this.#app = app
105
+ this.#options = options
106
+ this.#queue = new Queue(options.concurrency)
107
+ this.#wave = new Wave(() => [...document.querySelectorAll<HTMLElement>('[data-dio-progress]')])
108
+ const decoders = { meshopt: true, workers: undefined, ...options.decoders }
109
+ this.#cache = new Cache({
110
+ queue: this.#queue,
111
+ wave: this.#wave,
112
+ retain: options.retain,
113
+ decoders,
114
+ report: (error, url) => app.report(error, `asset:${url}`),
115
+ transform: (value, type, url) => {
116
+ const result = app.callHook('assets:transform', value, { type, url })
117
+ return isCancel(result) ? value : result
118
+ },
119
+ render: (abort) => this.#render(abort),
120
+ load: (url, options) => this.#load(url, options, false),
121
+ })
122
+ this.#preloads = new Preloads({
123
+ load: (url, options) => this.#load(url, options, false),
124
+ acquire: (key, make, priority) => this.api.acquire(key, make, { priority }),
125
+ has: (key) => this.#cache.has(key),
126
+ slot: (priority, abort) => this.#queue.slot('request', () => priority, abort),
127
+ typeOf: (url) => this.#typeOf(url),
128
+ track: (work, priority) => this.api.track(work, { priority }),
129
+ warn: (message) => app.log.warn(message),
130
+ })
131
+ if (options.preload && !frugal()) this.#preloads.listen(app.abortSignal)
132
+ app.on('app:destroy', () => {
133
+ this.#destroying = true
134
+ })
135
+ // Emitted by @dioramajs/transitions on every page change, explicit or auto.
136
+ const events = app as unknown as { on(name: string, fn: () => void): void }
137
+ events.on('page:leave', () => this.#wave.page())
138
+ app.on('plugin:status', ({ name, status }) => {
139
+ if (name !== 'render' || status !== 'stopping') return
140
+ if (this.#renderer) this.#module?.forget(this.#renderer)
141
+ this.#renderer = undefined
142
+ this.#cache.rebind()
143
+ })
144
+ app.onDispose(() => {
145
+ this.#preloads.close()
146
+ this.#cache.close(this.#destroying)
147
+ this.#leave?.()
148
+ })
149
+
150
+ const wave = this.#wave
151
+ this.api = {
152
+ load: (url: string, options?: LoadOptions) => this.#load(url, options ?? {}, true),
153
+ acquire: (key, make, { priority, weight } = {}) =>
154
+ this.#cache.get(
155
+ {
156
+ key,
157
+ // `type url` keys (effects bitmaps) name their URL. Other keys are their own URL.
158
+ ...parseKey(key),
159
+ crossOrigin: '',
160
+ options: {},
161
+ make: () => make as Make,
162
+ wrap: false,
163
+ weight,
164
+ },
165
+ priority ?? 'normal',
166
+ false,
167
+ ),
168
+ preload: (source, preload) => this.#preloads.preload(source, preload),
169
+ track(work, { priority, weight } = {}) {
170
+ if (priority === 'low') return
171
+ const item = { total: weight ?? ESTIMATE, loaded: 0 }
172
+ wave.add(item)
173
+ const done = (): void => wave.done(item)
174
+ Promise.resolve(work).then(done, done)
175
+ },
176
+ pause: () => this.#queue.pause(),
177
+ progress: wave.progress,
178
+ ready: () => wave.ready(),
179
+ stats: () => this.#cache.stats(),
180
+ } as AssetsApi
181
+ }
182
+
183
+ #load<T>(url: string, options: LoadOptions, report: boolean): Asset<T> {
184
+ let href: string
185
+ try {
186
+ href = absolute(url)
187
+ } catch (cause) {
188
+ const error = linked(new AssetError('ASSET_LOAD', `${url} is not a URL`, { url, cause }))
189
+ if (report) this.#app.report(error, `asset:${url}`)
190
+ return failed(url, error)
191
+ }
192
+ const type = options.type ?? this.#typeOf(href)
193
+ const name = type ?? '?'
194
+ const crossOrigin =
195
+ name === 'texture'
196
+ ? textureCors(href, options.crossOrigin ?? '')
197
+ : (options.crossOrigin ?? '')
198
+ const params = options.options ?? {}
199
+ const spec: Spec = {
200
+ key: keyOf(name, href, crossOrigin, params),
201
+ url: href,
202
+ type: name,
203
+ crossOrigin,
204
+ options: params,
205
+ make: () => this.#loader(type, href).then((loader) => (context) => loader.load(context)),
206
+ wrap: true,
207
+ }
208
+ return this.#cache.get(spec, options.priority ?? 'normal', report, options.signal)
209
+ }
210
+
211
+ /** Own loaders' extensions first, then the built-in table. */
212
+ #typeOf(url: string): string | undefined {
213
+ const extension = extensionOf(url)
214
+ if (!extension) return undefined
215
+ for (const [type, entry] of Object.entries(this.#options.loaders)) {
216
+ const extensions = typeof entry === 'function' ? undefined : entry.extensions
217
+ if (extensions?.some((e) => e.replace(/^\./, '').toLowerCase() === extension)) return type
218
+ }
219
+ return BY_EXTENSION[extension]
220
+ }
221
+
222
+ async #loader(type: string | undefined, url: string): Promise<AssetLoader> {
223
+ const known = [
224
+ ...new Set([...Object.keys(this.#options.loaders), ...Object.keys(BUILT_IN), ...THREE_TYPES]),
225
+ ]
226
+ if (type === undefined) {
227
+ const message = `no type for ${url}: pass { type } (known: ${known.join(', ')}); a page address is not an asset`
228
+ throw new AssetError('ASSET_TYPE', message, { url })
229
+ }
230
+ const own = this.#options.loaders[type]
231
+ try {
232
+ if (own) {
233
+ const found = typeof own === 'function' ? await own() : own
234
+ const loader = 'default' in found ? found.default : found
235
+ if (typeof loader?.load === 'function') return loader
236
+ } else if (BUILT_IN[type]) return BUILT_IN[type]
237
+ else if (isThree(type)) return (await this.#import())[type] as AssetLoader
238
+ } catch (cause) {
239
+ throw new AssetError('ASSET_TYPE', `the loader of "${type}" did not load`, { url, cause })
240
+ }
241
+ throw new AssetError('ASSET_TYPE', `no loader for "${type}" (known: ${known.join(', ')})`, {
242
+ url,
243
+ })
244
+ }
245
+
246
+ /** The three loaders, once per app. The app joins the decoders shared by the page. */
247
+ #import(): Promise<ThreeModule> {
248
+ if (!this.#three) {
249
+ const pending = import('./three/index').then((module) => {
250
+ if (!this.#app.abortSignal.aborted && !this.#module) this.#leave = module.join()
251
+ this.#module = module
252
+ return module
253
+ })
254
+ this.#three = pending
255
+ pending.catch(() => {
256
+ if (this.#three === pending) this.#three = undefined
257
+ })
258
+ }
259
+ return this.#three
260
+ }
261
+
262
+ #render(abort: AbortSignal): Promise<RenderApi> {
263
+ const app = this.#app
264
+ const found = app.find('render')
265
+ if (found) {
266
+ this.#renderer = found.renderer
267
+ return Promise.resolve(found)
268
+ }
269
+ if (abort.aborted || app.abortSignal.aborted) return Promise.reject(abortError())
270
+ return new Promise((resolve, reject) => {
271
+ const timer = DEV
272
+ ? setTimeout(() => app.log.warn('assets: a KTX2 load waits for render'), RENDER_WAIT_MS)
273
+ : undefined
274
+ const done = (): void => {
275
+ off()
276
+ clearTimeout(timer)
277
+ abort.removeEventListener('abort', stop)
278
+ }
279
+ const stop = (): void => {
280
+ done()
281
+ reject(abortError())
282
+ }
283
+ const off = app.on('plugin:status', ({ name, status }) => {
284
+ const render = name === 'render' && status === 'running' ? app.find('render') : undefined
285
+ if (!render) return
286
+ done()
287
+ this.#renderer = render.renderer
288
+ resolve(render)
289
+ })
290
+ abort.addEventListener('abort', stop, { once: true })
291
+ })
292
+ }
293
+ }
294
+
295
+ /**
296
+ * `app.assets`. One cache with leases for media and models, a priority queue, preloading of
297
+ * the next page and the progress wave of a preloader.
298
+ */
299
+ export const assets: Plugin<'assets', AssetsOptions, AssetsApi> = /*#__PURE__*/ definePlugin<
300
+ 'assets',
301
+ AssetsOptions,
302
+ typeof defaults,
303
+ AssetsApi,
304
+ [],
305
+ ['render']
306
+ >({
307
+ name: 'assets',
308
+ optionalDependencies: ['render'],
309
+ defaults,
310
+ setup(app, options): AssetsApi {
311
+ return typeof document === 'undefined'
312
+ ? inert()
313
+ : new Assets(app as unknown as View, options).api
314
+ },
315
+ })