qti-clockwork-assets 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/LICENSE ADDED
@@ -0,0 +1,173 @@
1
+ Clockwork Engine
2
+ Copyright (C) 2026 Quiet Terminal Interactive LTD
3
+
4
+ This project is licensed under the GNU Lesser General Public License v3.0.
5
+ See the license text below.
6
+
7
+ -----------------------------------------------------------------------
8
+
9
+ GNU LESSER GENERAL PUBLIC LICENSE
10
+ Version 3, 29 June 2007
11
+
12
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
13
+ Everyone is permitted to copy and distribute verbatim copies
14
+ of this license document, but changing it is not allowed.
15
+
16
+
17
+ This version of the GNU Lesser General Public License incorporates
18
+ the terms and conditions of version 3 of the GNU General Public
19
+ License, supplemented by the additional permissions listed below.
20
+
21
+ 0. Additional Definitions.
22
+
23
+ As used herein, "this License" refers to version 3 of the GNU Lesser
24
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
25
+ General Public License.
26
+
27
+ "The Library" refers to a covered work governed by this License,
28
+ other than an Application or a Combined Work as defined below.
29
+
30
+ An "Application" is any work that makes use of an interface provided
31
+ by the Library, but which is not otherwise based on the Library.
32
+ Defining a subclass of a class defined by the Library is deemed a mode
33
+ of using an interface provided by the Library.
34
+
35
+ A "Combined Work" is a work produced by combining or linking an
36
+ Application with the Library. The particular version of the Library
37
+ with which the Combined Work was made is also called the "Linked
38
+ Version".
39
+
40
+ The "Minimal Corresponding Source" for a Combined Work means the
41
+ Corresponding Source for the Combined Work, excluding any source code
42
+ for portions of the Combined Work that, considered in isolation, are
43
+ based on the Application, and not on the Linked Version.
44
+
45
+ The "Corresponding Application Code" for a Combined Work means the
46
+ object code and/or source code for the Application, including any data
47
+ and utility programs needed for reproducing the Combined Work from the
48
+ Application, but excluding the System Libraries of the Combined Work.
49
+
50
+ 1. Exception to Section 3 of the GNU GPL.
51
+
52
+ You may convey a covered work under sections 3 and 4 of this License
53
+ without being bound by section 3 of the GNU GPL.
54
+
55
+ 2. Conveying Modified Versions.
56
+
57
+ If you modify a copy of the Library, and, in your modifications, a
58
+ facility refers to a function or data to be supplied by an Application
59
+ that uses the facility (other than as an argument passed when the
60
+ facility is invoked), then you may convey a copy of the modified
61
+ version:
62
+
63
+ a) under this License, provided that you make a good faith effort to
64
+ ensure that, in the event an Application does not supply the
65
+ function or data, the facility still operates, and performs
66
+ whatever part of its purpose remains meaningful, or
67
+
68
+ b) under the GNU GPL, with none of the additional permissions of
69
+ this License applicable to that copy.
70
+
71
+ 3. Object Code Incorporating Material from Library Header Files.
72
+
73
+ The object code form of an Application may incorporate material from
74
+ a header file that is part of the Library. You may convey such object
75
+ code under terms of your choice, provided that, if the incorporated
76
+ material is not limited to numerical parameters, data structure
77
+ layouts and accessors, or small macros, inline functions and templates
78
+ (ten or fewer lines in length), you do both of the following:
79
+
80
+ a) Give prominent notice with each copy of the object code that the
81
+ Library is used in it and that the Library and its use are
82
+ covered by this License.
83
+
84
+ b) Accompany the object code with a copy of the GNU GPL and this license
85
+ document.
86
+
87
+ 4. Combined Works.
88
+
89
+ You may convey a Combined Work under terms of your choice that,
90
+ taken together, effectively do not restrict modification of the
91
+ portions of the Library contained in the Combined Work and reverse
92
+ engineering for debugging such modifications, if you also do each of
93
+ the following:
94
+
95
+ a) Give prominent notice with each copy of the Combined Work that
96
+ the Library is used in it and that the Library and its use are
97
+ covered by this License.
98
+
99
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
100
+ document.
101
+
102
+ c) For a Combined Work that displays copyright notices during
103
+ execution, include the copyright notice for the Library among
104
+ these notices, as well as a reference directing the user to the
105
+ copies of the GNU GPL and this license document.
106
+
107
+ d) Do one of the following:
108
+
109
+ 0) Convey the Minimal Corresponding Source under the terms of this
110
+ License, and the Corresponding Application Code in a form
111
+ suitable for, and under terms that permit, the user to
112
+ recombine or relink the Application with a modified version of
113
+ the Linked Version to produce a modified Combined Work, in the
114
+ manner specified by section 6 of the GNU GPL for conveying
115
+ Corresponding Source.
116
+
117
+ 1) Use a suitable shared library mechanism for linking with the
118
+ Library. A suitable mechanism is one that (a) uses at run time
119
+ a copy of the Library already present on the user's computer
120
+ system, and (b) will operate properly with a modified version
121
+ of the Library that is interface-compatible with the Linked
122
+ Version.
123
+
124
+ e) Provide Installation Information, but only if you would otherwise
125
+ be required to provide such information under section 6 of the
126
+ GNU GPL, and only to the extent that such information is
127
+ necessary to install and execute a modified version of the
128
+ Combined Work produced by recombining or relinking the
129
+ Application with a modified version of the Linked Version. (If
130
+ you use option 4d0, the Installation Information must accompany
131
+ the Minimal Corresponding Source and Corresponding Application
132
+ Code. If you use option 4d1, you must provide the Installation
133
+ Information in the manner specified by section 6 of the GNU GPL
134
+ for conveying Corresponding Source.)
135
+
136
+ 5. Combined Libraries.
137
+
138
+ You may place library facilities that are a work based on the
139
+ Library side by side in a single library together with other library
140
+ facilities that are not Applications and are not covered by this
141
+ License, and convey such a combined library under terms of your
142
+ choice, if you do both of the following:
143
+
144
+ a) Accompany the combined library with a copy of the same work based
145
+ on the Library, uncombined with any other library facilities,
146
+ conveyed under the terms of this License.
147
+
148
+ b) Give prominent notice with the combined library that part of it
149
+ is a work based on the Library, and explaining where to find the
150
+ accompanying uncombined form of the same work.
151
+
152
+ 6. Revised Versions of the GNU Lesser General Public License.
153
+
154
+ The Free Software Foundation may publish revised and/or new versions
155
+ of the GNU Lesser General Public License from time to time. Such new
156
+ versions will be similar in spirit to the present version, but may
157
+ differ in detail to address new problems or concerns.
158
+
159
+ Each version is given a distinguishing version number. If the
160
+ Library as you received it specifies that a certain numbered version
161
+ of the GNU Lesser General Public License "or any later version"
162
+ applies to it, you have the option of following the terms and
163
+ conditions either of that published version or of any later version
164
+ published by the Free Software Foundation. If the Library as you
165
+ received it does not specify a version number of the GNU Lesser
166
+ General Public License, you may choose any version of the GNU Lesser
167
+ General Public License ever published by the Free Software Foundation.
168
+
169
+ If the Library as you received it specifies that a proxy can decide
170
+ whether future versions of the GNU Lesser General Public License shall
171
+ apply, that proxy's public statement of acceptance of any version is
172
+ permanent authorization for you to choose that version for the
173
+ Library.
package/dist/index.cjs ADDED
@@ -0,0 +1,396 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AssetCache: () => AssetCache,
24
+ AtlasLoader: () => AtlasLoader,
25
+ AudioLoader: () => AudioLoader,
26
+ BinaryLoader: () => BinaryLoader,
27
+ FontLoader: () => FontLoader,
28
+ Handle: () => Handle,
29
+ JsonLoader: () => JsonLoader,
30
+ ShaderLoader: () => ShaderLoader,
31
+ TextureLoader: () => TextureLoader,
32
+ packageId: () => packageId
33
+ });
34
+ module.exports = __toCommonJS(index_exports);
35
+ var packageId = "qti-clockwork-assets";
36
+ var ConsoleAssetLogger = class {
37
+ error(message, metadata) {
38
+ if (metadata) {
39
+ console.error(message, metadata);
40
+ return;
41
+ }
42
+ console.error(message);
43
+ }
44
+ };
45
+ var Handle = class {
46
+ constructor(id, version, resolve) {
47
+ this.id = id;
48
+ this.version = version;
49
+ this.resolve = resolve;
50
+ }
51
+ get() {
52
+ return this.resolve(this);
53
+ }
54
+ isLoaded() {
55
+ return this.get() !== void 0;
56
+ }
57
+ };
58
+ var AssetCache = class {
59
+ constructor(source, logger = new ConsoleAssetLogger()) {
60
+ this.source = source;
61
+ this.logger = logger;
62
+ }
63
+ loaders = /* @__PURE__ */ new Map();
64
+ entries = /* @__PURE__ */ new Map();
65
+ registerLoader(loader) {
66
+ for (const extension of loader.extensions) {
67
+ this.loaders.set(this.normalizeExtension(extension), loader);
68
+ }
69
+ }
70
+ load(id) {
71
+ const safeId = assertSafeAssetPath(id);
72
+ const entry = this.getOrCreateEntry(safeId);
73
+ if (entry.asset === void 0 && !entry.inFlight) {
74
+ this.startLoading(entry);
75
+ }
76
+ return new Handle(safeId, entry.version, (handle) => this.get(handle));
77
+ }
78
+ get(handle) {
79
+ const entry = this.entries.get(handle.id);
80
+ if (!entry || entry.version !== handle.version || entry.error) {
81
+ return void 0;
82
+ }
83
+ return entry.asset;
84
+ }
85
+ async waitFor(handle) {
86
+ const entry = this.entries.get(handle.id);
87
+ if (!entry) {
88
+ throw new Error(`Unknown asset "${handle.id}"`);
89
+ }
90
+ if (entry.inFlight) {
91
+ await entry.inFlight;
92
+ }
93
+ const latest = this.entries.get(handle.id);
94
+ if (!latest) {
95
+ throw new Error(`Asset "${handle.id}" is unavailable for this handle`);
96
+ }
97
+ const asset = this.get(handle);
98
+ if (asset === void 0) {
99
+ if (latest.error) {
100
+ throw new Error(
101
+ `Asset "${handle.id}" failed to load: ${latest.error instanceof Error ? latest.error.message : String(latest.error)}`
102
+ );
103
+ }
104
+ throw new Error(`Asset "${handle.id}" is unavailable for this handle`);
105
+ }
106
+ return asset;
107
+ }
108
+ unload(id) {
109
+ const safeId = assertSafeAssetPath(id);
110
+ const entry = this.entries.get(safeId);
111
+ if (!entry) {
112
+ return;
113
+ }
114
+ delete entry.inFlight;
115
+ entry.loadToken += 1;
116
+ entry.error = void 0;
117
+ entry.watchStop?.();
118
+ delete entry.watchStop;
119
+ this.unlinkDependencies(entry);
120
+ this.disposeAsset(entry);
121
+ this.entries.delete(safeId);
122
+ }
123
+ async reload(id) {
124
+ await this.reloadInternal(assertSafeAssetPath(id), /* @__PURE__ */ new Set());
125
+ }
126
+ async reloadInternal(id, visited) {
127
+ if (visited.has(id)) {
128
+ return;
129
+ }
130
+ visited.add(id);
131
+ const entry = this.entries.get(id);
132
+ if (!entry) {
133
+ return;
134
+ }
135
+ if (entry.inFlight) {
136
+ await entry.inFlight;
137
+ }
138
+ this.disposeAsset(entry);
139
+ this.unlinkDependencies(entry);
140
+ entry.asset = void 0;
141
+ entry.error = void 0;
142
+ entry.version += 1;
143
+ entry.loadToken += 1;
144
+ this.startLoading(entry);
145
+ if (entry.inFlight) {
146
+ await entry.inFlight;
147
+ }
148
+ const dependents = [...entry.dependents];
149
+ for (const dependent of dependents) {
150
+ await this.reloadInternal(dependent, visited);
151
+ }
152
+ }
153
+ startLoading(entry) {
154
+ const token = entry.loadToken + 1;
155
+ entry.loadToken = token;
156
+ const loader = this.getLoader(entry.id);
157
+ const ctx = {
158
+ dependOn: (dependencyId) => {
159
+ const safeDependencyId = assertSafeAssetPath(dependencyId);
160
+ const dependency = this.getOrCreateEntry(safeDependencyId);
161
+ entry.dependencies.add(safeDependencyId);
162
+ dependency.dependents.add(entry.id);
163
+ },
164
+ loadDependency: (dependencyId) => {
165
+ ctx.dependOn(dependencyId);
166
+ return this.load(assertSafeAssetPath(dependencyId));
167
+ }
168
+ };
169
+ entry.inFlight = (async () => {
170
+ const loaded = await loader.load(entry.id, this.source, ctx);
171
+ if (!this.isCurrentEntry(entry.id, entry, token)) {
172
+ const staleLoader = this.getLoader(entry.id);
173
+ if (staleLoader.unload) {
174
+ staleLoader.unload(loaded);
175
+ }
176
+ return;
177
+ }
178
+ entry.asset = loaded;
179
+ entry.error = void 0;
180
+ if (!entry.watchStop && this.source.watch) {
181
+ entry.watchStop = this.source.watch(entry.id, () => {
182
+ void this.reload(entry.id);
183
+ });
184
+ }
185
+ })().catch((error) => {
186
+ if (!this.isCurrentEntry(entry.id, entry, token)) {
187
+ return;
188
+ }
189
+ entry.asset = void 0;
190
+ entry.error = error;
191
+ this.logger.error(`Failed to load asset "${entry.id}"`, {
192
+ error: error instanceof Error ? error.message : String(error)
193
+ });
194
+ }).finally(() => {
195
+ if (this.isCurrentEntry(entry.id, entry, token)) {
196
+ delete entry.inFlight;
197
+ }
198
+ });
199
+ }
200
+ getLoader(id) {
201
+ let match;
202
+ let longest = -1;
203
+ for (const [extension, loader] of this.loaders.entries()) {
204
+ if (id.toLowerCase().endsWith(extension) && extension.length > longest) {
205
+ match = loader;
206
+ longest = extension.length;
207
+ }
208
+ }
209
+ if (!match) {
210
+ throw new Error(`No asset loader registered for "${id}"`);
211
+ }
212
+ return match;
213
+ }
214
+ getOrCreateEntry(id) {
215
+ let entry = this.entries.get(id);
216
+ if (!entry) {
217
+ entry = {
218
+ id,
219
+ version: 1,
220
+ loadToken: 0,
221
+ dependencies: /* @__PURE__ */ new Set(),
222
+ dependents: /* @__PURE__ */ new Set()
223
+ };
224
+ this.entries.set(id, entry);
225
+ }
226
+ return entry;
227
+ }
228
+ unlinkDependencies(entry) {
229
+ for (const dependencyId of entry.dependencies) {
230
+ const dependency = this.entries.get(dependencyId);
231
+ dependency?.dependents.delete(entry.id);
232
+ }
233
+ entry.dependencies.clear();
234
+ }
235
+ disposeAsset(entry) {
236
+ if (entry.asset === void 0) {
237
+ return;
238
+ }
239
+ const loader = this.getLoader(entry.id);
240
+ if (loader.unload) {
241
+ loader.unload(entry.asset);
242
+ }
243
+ entry.asset = void 0;
244
+ }
245
+ normalizeExtension(extension) {
246
+ const trimmed = extension.trim().toLowerCase();
247
+ if (!trimmed.startsWith(".")) {
248
+ return `.${trimmed}`;
249
+ }
250
+ return trimmed;
251
+ }
252
+ isCurrentEntry(id, entry, token) {
253
+ return this.entries.get(id) === entry && entry.loadToken === token;
254
+ }
255
+ };
256
+ var TextureLoader = class {
257
+ extensions = [".png", ".jpg", ".jpeg", ".webp"];
258
+ async load(path, source) {
259
+ return source.readFile(path);
260
+ }
261
+ };
262
+ var AtlasLoader = class {
263
+ extensions = [".atlas.json"];
264
+ decoder = new TextDecoder();
265
+ async load(path, source, context) {
266
+ const bytes = await source.readFile(path);
267
+ const data = parseJsonRecord(this.decoder.decode(bytes), path);
268
+ const texturePath = this.extractTexturePath(data, path);
269
+ if (!texturePath || !context) {
270
+ const result = { data };
271
+ if (texturePath) {
272
+ result.texturePath = texturePath;
273
+ }
274
+ return result;
275
+ }
276
+ const texture = context.loadDependency(texturePath);
277
+ return { data, texturePath, texture };
278
+ }
279
+ extractTexturePath(data, atlasPath) {
280
+ const direct = data.texture;
281
+ if (typeof direct === "string") {
282
+ return this.resolveSibling(atlasPath, direct);
283
+ }
284
+ const meta = data.meta;
285
+ if (meta && typeof meta === "object") {
286
+ const image = meta.image;
287
+ if (typeof image === "string") {
288
+ return this.resolveSibling(atlasPath, image);
289
+ }
290
+ }
291
+ const normalized = atlasPath.replaceAll("\\", "/");
292
+ const sibling = normalized.replace(/\.atlas\.json$/i, ".png");
293
+ return sibling;
294
+ }
295
+ resolveSibling(path, sibling) {
296
+ const normalizedPath = assertSafeAssetPath(path);
297
+ const normalizedSibling = assertSafeRelativeSegment(sibling);
298
+ const separator = normalizedPath.lastIndexOf("/");
299
+ const baseSegments = separator === -1 ? [] : normalizedPath.slice(0, separator).split("/").filter(Boolean);
300
+ for (const segment of normalizedSibling.split("/")) {
301
+ if (segment === "." || segment.length === 0) {
302
+ continue;
303
+ }
304
+ if (segment === "..") {
305
+ if (baseSegments.length === 0) {
306
+ throw new Error(`Unsafe asset path traversal: "${sibling}"`);
307
+ }
308
+ baseSegments.pop();
309
+ continue;
310
+ }
311
+ baseSegments.push(segment);
312
+ }
313
+ return baseSegments.join("/");
314
+ }
315
+ };
316
+ var AudioLoader = class {
317
+ extensions = [".mp3", ".ogg", ".wav"];
318
+ async load(path, source) {
319
+ return source.readFile(path);
320
+ }
321
+ };
322
+ var FontLoader = class {
323
+ extensions = [".ttf", ".otf"];
324
+ async load(path, source) {
325
+ return source.readFile(path);
326
+ }
327
+ };
328
+ var ShaderLoader = class {
329
+ extensions = [".vert", ".frag"];
330
+ decoder = new TextDecoder();
331
+ async load(path, source) {
332
+ const bytes = await source.readFile(path);
333
+ return this.decoder.decode(bytes);
334
+ }
335
+ };
336
+ var JsonLoader = class {
337
+ extensions = [".json"];
338
+ decoder = new TextDecoder();
339
+ async load(path, source) {
340
+ const bytes = await source.readFile(path);
341
+ return JSON.parse(this.decoder.decode(bytes));
342
+ }
343
+ };
344
+ var BinaryLoader = class {
345
+ extensions = [".bin"];
346
+ async load(path, source) {
347
+ return source.readFile(path);
348
+ }
349
+ };
350
+ function parseJsonRecord(raw, path) {
351
+ let parsed;
352
+ try {
353
+ parsed = JSON.parse(raw);
354
+ } catch (error) {
355
+ throw new Error(
356
+ `Failed to parse JSON asset "${path}": ${error instanceof Error ? error.message : String(error)}`
357
+ );
358
+ }
359
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
360
+ throw new Error(`JSON asset "${path}" must be an object`);
361
+ }
362
+ return parsed;
363
+ }
364
+ function assertSafeAssetPath(path) {
365
+ if (typeof path !== "string" || path.trim().length === 0) {
366
+ throw new Error("Asset path must be a non-empty string");
367
+ }
368
+ const normalized = path.replaceAll("\\", "/");
369
+ if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized)) {
370
+ throw new Error(`Asset path "${path}" must be relative`);
371
+ }
372
+ if (normalized.split("/").some((segment) => segment === "..")) {
373
+ throw new Error(`Asset path "${path}" contains path traversal`);
374
+ }
375
+ return normalized;
376
+ }
377
+ function assertSafeRelativeSegment(path) {
378
+ const normalized = path.replaceAll("\\", "/");
379
+ if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized)) {
380
+ throw new Error(`Asset path "${path}" must be relative`);
381
+ }
382
+ return normalized;
383
+ }
384
+ // Annotate the CommonJS export names for ESM import in node:
385
+ 0 && (module.exports = {
386
+ AssetCache,
387
+ AtlasLoader,
388
+ AudioLoader,
389
+ BinaryLoader,
390
+ FontLoader,
391
+ Handle,
392
+ JsonLoader,
393
+ ShaderLoader,
394
+ TextureLoader,
395
+ packageId
396
+ });
@@ -0,0 +1,90 @@
1
+ declare const packageId = "qti-clockwork-assets";
2
+ type AssetId = string;
3
+ interface AssetLogger {
4
+ error(message: string, metadata?: Record<string, unknown>): void;
5
+ }
6
+ interface AssetSource {
7
+ fetch(url: string): Promise<ArrayBuffer>;
8
+ readFile(path: string): Promise<Uint8Array>;
9
+ watch?(path: string, callback: () => void): () => void;
10
+ }
11
+ interface AssetLoader<T> {
12
+ extensions: string[];
13
+ load(path: string, source: AssetSource): Promise<T>;
14
+ unload?(asset: T): void;
15
+ }
16
+ interface LoaderContext {
17
+ dependOn(id: AssetId): void;
18
+ loadDependency<T>(id: AssetId): Handle<T>;
19
+ }
20
+ /** Versioned reference to a loading or loaded asset, invalidated on reload. */
21
+ declare class Handle<T> {
22
+ readonly id: AssetId;
23
+ readonly version: number;
24
+ private readonly resolve;
25
+ constructor(id: AssetId, version: number, resolve: (handle: Handle<T>) => T | undefined);
26
+ get(): T | undefined;
27
+ isLoaded(): boolean;
28
+ }
29
+ interface AtlasAsset {
30
+ texturePath?: string;
31
+ texture?: Handle<unknown>;
32
+ data: Record<string, unknown>;
33
+ }
34
+ /** Central asset manager handling loading, caching, hot-reload, and dependency tracking. */
35
+ declare class AssetCache {
36
+ private readonly source;
37
+ private readonly logger;
38
+ private readonly loaders;
39
+ private readonly entries;
40
+ constructor(source: AssetSource, logger?: AssetLogger);
41
+ registerLoader<T>(loader: AssetLoader<T>): void;
42
+ load<T>(id: AssetId): Handle<T>;
43
+ get<T>(handle: Handle<T>): T | undefined;
44
+ waitFor<T>(handle: Handle<T>): Promise<T>;
45
+ unload(id: AssetId): void;
46
+ reload(id: AssetId): Promise<void>;
47
+ private reloadInternal;
48
+ private startLoading;
49
+ private getLoader;
50
+ private getOrCreateEntry;
51
+ private unlinkDependencies;
52
+ private disposeAsset;
53
+ private normalizeExtension;
54
+ private isCurrentEntry;
55
+ }
56
+ declare class TextureLoader implements AssetLoader<Uint8Array> {
57
+ readonly extensions: string[];
58
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
59
+ }
60
+ declare class AtlasLoader implements AssetLoader<AtlasAsset> {
61
+ readonly extensions: string[];
62
+ private readonly decoder;
63
+ load(path: string, source: AssetSource, context?: LoaderContext): Promise<AtlasAsset>;
64
+ private extractTexturePath;
65
+ private resolveSibling;
66
+ }
67
+ declare class AudioLoader implements AssetLoader<Uint8Array> {
68
+ readonly extensions: string[];
69
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
70
+ }
71
+ declare class FontLoader implements AssetLoader<Uint8Array> {
72
+ readonly extensions: string[];
73
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
74
+ }
75
+ declare class ShaderLoader implements AssetLoader<string> {
76
+ readonly extensions: string[];
77
+ private readonly decoder;
78
+ load(path: string, source: AssetSource): Promise<string>;
79
+ }
80
+ declare class JsonLoader implements AssetLoader<unknown> {
81
+ readonly extensions: string[];
82
+ private readonly decoder;
83
+ load(path: string, source: AssetSource): Promise<unknown>;
84
+ }
85
+ declare class BinaryLoader implements AssetLoader<Uint8Array> {
86
+ readonly extensions: string[];
87
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
88
+ }
89
+
90
+ export { AssetCache, type AssetId, type AssetLoader, type AssetLogger, type AssetSource, type AtlasAsset, AtlasLoader, AudioLoader, BinaryLoader, FontLoader, Handle, JsonLoader, ShaderLoader, TextureLoader, packageId };
@@ -0,0 +1,90 @@
1
+ declare const packageId = "qti-clockwork-assets";
2
+ type AssetId = string;
3
+ interface AssetLogger {
4
+ error(message: string, metadata?: Record<string, unknown>): void;
5
+ }
6
+ interface AssetSource {
7
+ fetch(url: string): Promise<ArrayBuffer>;
8
+ readFile(path: string): Promise<Uint8Array>;
9
+ watch?(path: string, callback: () => void): () => void;
10
+ }
11
+ interface AssetLoader<T> {
12
+ extensions: string[];
13
+ load(path: string, source: AssetSource): Promise<T>;
14
+ unload?(asset: T): void;
15
+ }
16
+ interface LoaderContext {
17
+ dependOn(id: AssetId): void;
18
+ loadDependency<T>(id: AssetId): Handle<T>;
19
+ }
20
+ /** Versioned reference to a loading or loaded asset, invalidated on reload. */
21
+ declare class Handle<T> {
22
+ readonly id: AssetId;
23
+ readonly version: number;
24
+ private readonly resolve;
25
+ constructor(id: AssetId, version: number, resolve: (handle: Handle<T>) => T | undefined);
26
+ get(): T | undefined;
27
+ isLoaded(): boolean;
28
+ }
29
+ interface AtlasAsset {
30
+ texturePath?: string;
31
+ texture?: Handle<unknown>;
32
+ data: Record<string, unknown>;
33
+ }
34
+ /** Central asset manager handling loading, caching, hot-reload, and dependency tracking. */
35
+ declare class AssetCache {
36
+ private readonly source;
37
+ private readonly logger;
38
+ private readonly loaders;
39
+ private readonly entries;
40
+ constructor(source: AssetSource, logger?: AssetLogger);
41
+ registerLoader<T>(loader: AssetLoader<T>): void;
42
+ load<T>(id: AssetId): Handle<T>;
43
+ get<T>(handle: Handle<T>): T | undefined;
44
+ waitFor<T>(handle: Handle<T>): Promise<T>;
45
+ unload(id: AssetId): void;
46
+ reload(id: AssetId): Promise<void>;
47
+ private reloadInternal;
48
+ private startLoading;
49
+ private getLoader;
50
+ private getOrCreateEntry;
51
+ private unlinkDependencies;
52
+ private disposeAsset;
53
+ private normalizeExtension;
54
+ private isCurrentEntry;
55
+ }
56
+ declare class TextureLoader implements AssetLoader<Uint8Array> {
57
+ readonly extensions: string[];
58
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
59
+ }
60
+ declare class AtlasLoader implements AssetLoader<AtlasAsset> {
61
+ readonly extensions: string[];
62
+ private readonly decoder;
63
+ load(path: string, source: AssetSource, context?: LoaderContext): Promise<AtlasAsset>;
64
+ private extractTexturePath;
65
+ private resolveSibling;
66
+ }
67
+ declare class AudioLoader implements AssetLoader<Uint8Array> {
68
+ readonly extensions: string[];
69
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
70
+ }
71
+ declare class FontLoader implements AssetLoader<Uint8Array> {
72
+ readonly extensions: string[];
73
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
74
+ }
75
+ declare class ShaderLoader implements AssetLoader<string> {
76
+ readonly extensions: string[];
77
+ private readonly decoder;
78
+ load(path: string, source: AssetSource): Promise<string>;
79
+ }
80
+ declare class JsonLoader implements AssetLoader<unknown> {
81
+ readonly extensions: string[];
82
+ private readonly decoder;
83
+ load(path: string, source: AssetSource): Promise<unknown>;
84
+ }
85
+ declare class BinaryLoader implements AssetLoader<Uint8Array> {
86
+ readonly extensions: string[];
87
+ load(path: string, source: AssetSource): Promise<Uint8Array>;
88
+ }
89
+
90
+ export { AssetCache, type AssetId, type AssetLoader, type AssetLogger, type AssetSource, type AtlasAsset, AtlasLoader, AudioLoader, BinaryLoader, FontLoader, Handle, JsonLoader, ShaderLoader, TextureLoader, packageId };
package/dist/index.js ADDED
@@ -0,0 +1,362 @@
1
+ // src/index.ts
2
+ var packageId = "qti-clockwork-assets";
3
+ var ConsoleAssetLogger = class {
4
+ error(message, metadata) {
5
+ if (metadata) {
6
+ console.error(message, metadata);
7
+ return;
8
+ }
9
+ console.error(message);
10
+ }
11
+ };
12
+ var Handle = class {
13
+ constructor(id, version, resolve) {
14
+ this.id = id;
15
+ this.version = version;
16
+ this.resolve = resolve;
17
+ }
18
+ get() {
19
+ return this.resolve(this);
20
+ }
21
+ isLoaded() {
22
+ return this.get() !== void 0;
23
+ }
24
+ };
25
+ var AssetCache = class {
26
+ constructor(source, logger = new ConsoleAssetLogger()) {
27
+ this.source = source;
28
+ this.logger = logger;
29
+ }
30
+ loaders = /* @__PURE__ */ new Map();
31
+ entries = /* @__PURE__ */ new Map();
32
+ registerLoader(loader) {
33
+ for (const extension of loader.extensions) {
34
+ this.loaders.set(this.normalizeExtension(extension), loader);
35
+ }
36
+ }
37
+ load(id) {
38
+ const safeId = assertSafeAssetPath(id);
39
+ const entry = this.getOrCreateEntry(safeId);
40
+ if (entry.asset === void 0 && !entry.inFlight) {
41
+ this.startLoading(entry);
42
+ }
43
+ return new Handle(safeId, entry.version, (handle) => this.get(handle));
44
+ }
45
+ get(handle) {
46
+ const entry = this.entries.get(handle.id);
47
+ if (!entry || entry.version !== handle.version || entry.error) {
48
+ return void 0;
49
+ }
50
+ return entry.asset;
51
+ }
52
+ async waitFor(handle) {
53
+ const entry = this.entries.get(handle.id);
54
+ if (!entry) {
55
+ throw new Error(`Unknown asset "${handle.id}"`);
56
+ }
57
+ if (entry.inFlight) {
58
+ await entry.inFlight;
59
+ }
60
+ const latest = this.entries.get(handle.id);
61
+ if (!latest) {
62
+ throw new Error(`Asset "${handle.id}" is unavailable for this handle`);
63
+ }
64
+ const asset = this.get(handle);
65
+ if (asset === void 0) {
66
+ if (latest.error) {
67
+ throw new Error(
68
+ `Asset "${handle.id}" failed to load: ${latest.error instanceof Error ? latest.error.message : String(latest.error)}`
69
+ );
70
+ }
71
+ throw new Error(`Asset "${handle.id}" is unavailable for this handle`);
72
+ }
73
+ return asset;
74
+ }
75
+ unload(id) {
76
+ const safeId = assertSafeAssetPath(id);
77
+ const entry = this.entries.get(safeId);
78
+ if (!entry) {
79
+ return;
80
+ }
81
+ delete entry.inFlight;
82
+ entry.loadToken += 1;
83
+ entry.error = void 0;
84
+ entry.watchStop?.();
85
+ delete entry.watchStop;
86
+ this.unlinkDependencies(entry);
87
+ this.disposeAsset(entry);
88
+ this.entries.delete(safeId);
89
+ }
90
+ async reload(id) {
91
+ await this.reloadInternal(assertSafeAssetPath(id), /* @__PURE__ */ new Set());
92
+ }
93
+ async reloadInternal(id, visited) {
94
+ if (visited.has(id)) {
95
+ return;
96
+ }
97
+ visited.add(id);
98
+ const entry = this.entries.get(id);
99
+ if (!entry) {
100
+ return;
101
+ }
102
+ if (entry.inFlight) {
103
+ await entry.inFlight;
104
+ }
105
+ this.disposeAsset(entry);
106
+ this.unlinkDependencies(entry);
107
+ entry.asset = void 0;
108
+ entry.error = void 0;
109
+ entry.version += 1;
110
+ entry.loadToken += 1;
111
+ this.startLoading(entry);
112
+ if (entry.inFlight) {
113
+ await entry.inFlight;
114
+ }
115
+ const dependents = [...entry.dependents];
116
+ for (const dependent of dependents) {
117
+ await this.reloadInternal(dependent, visited);
118
+ }
119
+ }
120
+ startLoading(entry) {
121
+ const token = entry.loadToken + 1;
122
+ entry.loadToken = token;
123
+ const loader = this.getLoader(entry.id);
124
+ const ctx = {
125
+ dependOn: (dependencyId) => {
126
+ const safeDependencyId = assertSafeAssetPath(dependencyId);
127
+ const dependency = this.getOrCreateEntry(safeDependencyId);
128
+ entry.dependencies.add(safeDependencyId);
129
+ dependency.dependents.add(entry.id);
130
+ },
131
+ loadDependency: (dependencyId) => {
132
+ ctx.dependOn(dependencyId);
133
+ return this.load(assertSafeAssetPath(dependencyId));
134
+ }
135
+ };
136
+ entry.inFlight = (async () => {
137
+ const loaded = await loader.load(entry.id, this.source, ctx);
138
+ if (!this.isCurrentEntry(entry.id, entry, token)) {
139
+ const staleLoader = this.getLoader(entry.id);
140
+ if (staleLoader.unload) {
141
+ staleLoader.unload(loaded);
142
+ }
143
+ return;
144
+ }
145
+ entry.asset = loaded;
146
+ entry.error = void 0;
147
+ if (!entry.watchStop && this.source.watch) {
148
+ entry.watchStop = this.source.watch(entry.id, () => {
149
+ void this.reload(entry.id);
150
+ });
151
+ }
152
+ })().catch((error) => {
153
+ if (!this.isCurrentEntry(entry.id, entry, token)) {
154
+ return;
155
+ }
156
+ entry.asset = void 0;
157
+ entry.error = error;
158
+ this.logger.error(`Failed to load asset "${entry.id}"`, {
159
+ error: error instanceof Error ? error.message : String(error)
160
+ });
161
+ }).finally(() => {
162
+ if (this.isCurrentEntry(entry.id, entry, token)) {
163
+ delete entry.inFlight;
164
+ }
165
+ });
166
+ }
167
+ getLoader(id) {
168
+ let match;
169
+ let longest = -1;
170
+ for (const [extension, loader] of this.loaders.entries()) {
171
+ if (id.toLowerCase().endsWith(extension) && extension.length > longest) {
172
+ match = loader;
173
+ longest = extension.length;
174
+ }
175
+ }
176
+ if (!match) {
177
+ throw new Error(`No asset loader registered for "${id}"`);
178
+ }
179
+ return match;
180
+ }
181
+ getOrCreateEntry(id) {
182
+ let entry = this.entries.get(id);
183
+ if (!entry) {
184
+ entry = {
185
+ id,
186
+ version: 1,
187
+ loadToken: 0,
188
+ dependencies: /* @__PURE__ */ new Set(),
189
+ dependents: /* @__PURE__ */ new Set()
190
+ };
191
+ this.entries.set(id, entry);
192
+ }
193
+ return entry;
194
+ }
195
+ unlinkDependencies(entry) {
196
+ for (const dependencyId of entry.dependencies) {
197
+ const dependency = this.entries.get(dependencyId);
198
+ dependency?.dependents.delete(entry.id);
199
+ }
200
+ entry.dependencies.clear();
201
+ }
202
+ disposeAsset(entry) {
203
+ if (entry.asset === void 0) {
204
+ return;
205
+ }
206
+ const loader = this.getLoader(entry.id);
207
+ if (loader.unload) {
208
+ loader.unload(entry.asset);
209
+ }
210
+ entry.asset = void 0;
211
+ }
212
+ normalizeExtension(extension) {
213
+ const trimmed = extension.trim().toLowerCase();
214
+ if (!trimmed.startsWith(".")) {
215
+ return `.${trimmed}`;
216
+ }
217
+ return trimmed;
218
+ }
219
+ isCurrentEntry(id, entry, token) {
220
+ return this.entries.get(id) === entry && entry.loadToken === token;
221
+ }
222
+ };
223
+ var TextureLoader = class {
224
+ extensions = [".png", ".jpg", ".jpeg", ".webp"];
225
+ async load(path, source) {
226
+ return source.readFile(path);
227
+ }
228
+ };
229
+ var AtlasLoader = class {
230
+ extensions = [".atlas.json"];
231
+ decoder = new TextDecoder();
232
+ async load(path, source, context) {
233
+ const bytes = await source.readFile(path);
234
+ const data = parseJsonRecord(this.decoder.decode(bytes), path);
235
+ const texturePath = this.extractTexturePath(data, path);
236
+ if (!texturePath || !context) {
237
+ const result = { data };
238
+ if (texturePath) {
239
+ result.texturePath = texturePath;
240
+ }
241
+ return result;
242
+ }
243
+ const texture = context.loadDependency(texturePath);
244
+ return { data, texturePath, texture };
245
+ }
246
+ extractTexturePath(data, atlasPath) {
247
+ const direct = data.texture;
248
+ if (typeof direct === "string") {
249
+ return this.resolveSibling(atlasPath, direct);
250
+ }
251
+ const meta = data.meta;
252
+ if (meta && typeof meta === "object") {
253
+ const image = meta.image;
254
+ if (typeof image === "string") {
255
+ return this.resolveSibling(atlasPath, image);
256
+ }
257
+ }
258
+ const normalized = atlasPath.replaceAll("\\", "/");
259
+ const sibling = normalized.replace(/\.atlas\.json$/i, ".png");
260
+ return sibling;
261
+ }
262
+ resolveSibling(path, sibling) {
263
+ const normalizedPath = assertSafeAssetPath(path);
264
+ const normalizedSibling = assertSafeRelativeSegment(sibling);
265
+ const separator = normalizedPath.lastIndexOf("/");
266
+ const baseSegments = separator === -1 ? [] : normalizedPath.slice(0, separator).split("/").filter(Boolean);
267
+ for (const segment of normalizedSibling.split("/")) {
268
+ if (segment === "." || segment.length === 0) {
269
+ continue;
270
+ }
271
+ if (segment === "..") {
272
+ if (baseSegments.length === 0) {
273
+ throw new Error(`Unsafe asset path traversal: "${sibling}"`);
274
+ }
275
+ baseSegments.pop();
276
+ continue;
277
+ }
278
+ baseSegments.push(segment);
279
+ }
280
+ return baseSegments.join("/");
281
+ }
282
+ };
283
+ var AudioLoader = class {
284
+ extensions = [".mp3", ".ogg", ".wav"];
285
+ async load(path, source) {
286
+ return source.readFile(path);
287
+ }
288
+ };
289
+ var FontLoader = class {
290
+ extensions = [".ttf", ".otf"];
291
+ async load(path, source) {
292
+ return source.readFile(path);
293
+ }
294
+ };
295
+ var ShaderLoader = class {
296
+ extensions = [".vert", ".frag"];
297
+ decoder = new TextDecoder();
298
+ async load(path, source) {
299
+ const bytes = await source.readFile(path);
300
+ return this.decoder.decode(bytes);
301
+ }
302
+ };
303
+ var JsonLoader = class {
304
+ extensions = [".json"];
305
+ decoder = new TextDecoder();
306
+ async load(path, source) {
307
+ const bytes = await source.readFile(path);
308
+ return JSON.parse(this.decoder.decode(bytes));
309
+ }
310
+ };
311
+ var BinaryLoader = class {
312
+ extensions = [".bin"];
313
+ async load(path, source) {
314
+ return source.readFile(path);
315
+ }
316
+ };
317
+ function parseJsonRecord(raw, path) {
318
+ let parsed;
319
+ try {
320
+ parsed = JSON.parse(raw);
321
+ } catch (error) {
322
+ throw new Error(
323
+ `Failed to parse JSON asset "${path}": ${error instanceof Error ? error.message : String(error)}`
324
+ );
325
+ }
326
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
327
+ throw new Error(`JSON asset "${path}" must be an object`);
328
+ }
329
+ return parsed;
330
+ }
331
+ function assertSafeAssetPath(path) {
332
+ if (typeof path !== "string" || path.trim().length === 0) {
333
+ throw new Error("Asset path must be a non-empty string");
334
+ }
335
+ const normalized = path.replaceAll("\\", "/");
336
+ if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized)) {
337
+ throw new Error(`Asset path "${path}" must be relative`);
338
+ }
339
+ if (normalized.split("/").some((segment) => segment === "..")) {
340
+ throw new Error(`Asset path "${path}" contains path traversal`);
341
+ }
342
+ return normalized;
343
+ }
344
+ function assertSafeRelativeSegment(path) {
345
+ const normalized = path.replaceAll("\\", "/");
346
+ if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized)) {
347
+ throw new Error(`Asset path "${path}" must be relative`);
348
+ }
349
+ return normalized;
350
+ }
351
+ export {
352
+ AssetCache,
353
+ AtlasLoader,
354
+ AudioLoader,
355
+ BinaryLoader,
356
+ FontLoader,
357
+ Handle,
358
+ JsonLoader,
359
+ ShaderLoader,
360
+ TextureLoader,
361
+ packageId
362
+ };
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "qti-clockwork-assets",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
20
+ "test": "vitest run",
21
+ "typecheck": "tsc -p tsconfig.json --noEmit"
22
+ }
23
+ }