@caperjs/core 0.1.1 → 0.2.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.
Files changed (109) hide show
  1. package/README.md +1 -1
  2. package/{config → build}/assetpack.mjs +103 -45
  3. package/build/defaults.mjs +157 -0
  4. package/build/index.mjs +96 -0
  5. package/build/internal/ast.mjs +255 -0
  6. package/build/internal/buildFlags.mjs +50 -0
  7. package/build/internal/discovery.mjs +402 -0
  8. package/build/internal/manifest.mjs +38 -0
  9. package/build/internal/schema.mjs +65 -0
  10. package/build/internal/util.mjs +30 -0
  11. package/build/internal/validate.mjs +186 -0
  12. package/build/plugins/assetTypes.mjs +460 -0
  13. package/build/plugins/caperConfig.mjs +489 -0
  14. package/build/plugins/devHelper.mjs +31 -0
  15. package/build/plugins/lists.mjs +286 -0
  16. package/build/plugins/pruneFallbacks.mjs +150 -0
  17. package/build/plugins/pwa.mjs +240 -0
  18. package/build/plugins/runtime.mjs +129 -0
  19. package/cli.mjs +9 -6
  20. package/extras/llms.txt +23 -17
  21. package/lib/{CaptionsPlugin-Dc8fIrjy.js → CaptionsPlugin-DKhbmJvH.js} +15 -15
  22. package/lib/{CaptionsPlugin-Dc8fIrjy.js.map → CaptionsPlugin-DKhbmJvH.js.map} +1 -1
  23. package/lib/{DataAdapter-BY2114sp.js → DataAdapter-BZFTkFQ4.js} +4 -4
  24. package/lib/{DataAdapter-BY2114sp.js.map → DataAdapter-BZFTkFQ4.js.map} +1 -1
  25. package/lib/{DebugRenderer-BJMLILqI.js → DebugRenderer-C7X-nlXE.js} +2 -2
  26. package/lib/{DebugRenderer-BJMLILqI.js.map → DebugRenderer-C7X-nlXE.js.map} +1 -1
  27. package/lib/{DevToolsPlugin-wQ5rOkn0.js → DevToolsPlugin-P-atJ-5U.js} +2 -2
  28. package/lib/{DevToolsPlugin-wQ5rOkn0.js.map → DevToolsPlugin-P-atJ-5U.js.map} +1 -1
  29. package/lib/{GSAPPlugin-DHhSZKv8.js → GSAPPlugin-CeH9275z.js} +2 -2
  30. package/lib/{GSAPPlugin-DHhSZKv8.js.map → GSAPPlugin-CeH9275z.js.map} +1 -1
  31. package/lib/{LayoutPlugin-B-DF9SYM.js → LayoutPlugin-iZ3k6RsK.js} +4 -4
  32. package/lib/{LayoutPlugin-B-DF9SYM.js.map → LayoutPlugin-iZ3k6RsK.js.map} +1 -1
  33. package/lib/{SpinePlugin-Dz_3dljz.js → SpinePlugin-BWiavCpO.js} +2 -2
  34. package/lib/{SpinePlugin-Dz_3dljz.js.map → SpinePlugin-BWiavCpO.js.map} +1 -1
  35. package/lib/{StatsPlugin-Cg82JMBD.js → StatsPlugin-CBpzDJL0.js} +4 -4
  36. package/lib/{StatsPlugin-Cg82JMBD.js.map → StatsPlugin-CBpzDJL0.js.map} +1 -1
  37. package/lib/{VoiceOverPlugin-BR3ImT8C.js → VoiceOverPlugin-YaiKJtJ6.js} +26 -26
  38. package/lib/{VoiceOverPlugin-BR3ImT8C.js.map → VoiceOverPlugin-YaiKJtJ6.js.map} +1 -1
  39. package/lib/caper.mjs +95 -95
  40. package/lib/caper.mjs.map +1 -1
  41. package/lib/core/Application.d.ts +1 -1
  42. package/lib/core/Application.d.ts.map +1 -1
  43. package/lib/core/interfaces/IApplicationOptions.d.ts +2 -1
  44. package/lib/core/interfaces/IApplicationOptions.d.ts.map +1 -1
  45. package/lib/core/interfaces/ICoreSignals.d.ts +5 -1
  46. package/lib/core/interfaces/ICoreSignals.d.ts.map +1 -1
  47. package/lib/display/Container.d.ts +1 -1
  48. package/lib/display/Container.d.ts.map +1 -1
  49. package/lib/display/ParticleContainer.d.ts +1 -1
  50. package/lib/display/ParticleContainer.d.ts.map +1 -1
  51. package/lib/plugins/Plugin.d.ts +1 -1
  52. package/lib/plugins/Plugin.d.ts.map +1 -1
  53. package/lib/plugins/defaults.d.ts.map +1 -1
  54. package/lib/plugins/gesture/GesturePlugin.d.ts +58 -0
  55. package/lib/plugins/gesture/GesturePlugin.d.ts.map +1 -0
  56. package/lib/plugins/gesture/gestureMath.d.ts +32 -0
  57. package/lib/plugins/gesture/gestureMath.d.ts.map +1 -0
  58. package/lib/plugins/gesture/gestureMath.test.d.ts +2 -0
  59. package/lib/plugins/gesture/gestureMath.test.d.ts.map +1 -0
  60. package/lib/plugins/gesture/index.d.ts +3 -0
  61. package/lib/plugins/gesture/index.d.ts.map +1 -0
  62. package/lib/plugins/gesture/types.d.ts +45 -0
  63. package/lib/plugins/gesture/types.d.ts.map +1 -0
  64. package/lib/plugins/index.d.ts +1 -0
  65. package/lib/plugins/index.d.ts.map +1 -1
  66. package/lib/plugins/input/Controls.d.ts +5 -2
  67. package/lib/plugins/input/Controls.d.ts.map +1 -1
  68. package/lib/plugins/input/InputPlugin.d.ts +9 -2
  69. package/lib/plugins/input/InputPlugin.d.ts.map +1 -1
  70. package/lib/plugins/input/interfaces.d.ts +5 -3
  71. package/lib/plugins/input/interfaces.d.ts.map +1 -1
  72. package/lib/plugins/input/touch/{TouchControls.d.ts → VirtualControls.d.ts} +5 -4
  73. package/lib/plugins/input/touch/VirtualControls.d.ts.map +1 -0
  74. package/lib/plugins/input/touch/index.d.ts +1 -1
  75. package/lib/plugins/input/touch/index.d.ts.map +1 -1
  76. package/lib/{registries-CYCaYKZI.js → registries-qQmLeN0b.js} +505 -354
  77. package/lib/registries-qQmLeN0b.js.map +1 -0
  78. package/lib/types/caper-app.d.ts +1 -0
  79. package/lib/utils/bind.test.d.ts +2 -0
  80. package/lib/utils/bind.test.d.ts.map +1 -0
  81. package/package.json +33 -33
  82. package/src/core/Application.ts +1 -1
  83. package/src/core/interfaces/IApplicationOptions.ts +2 -0
  84. package/src/core/interfaces/ICoreSignals.ts +9 -0
  85. package/src/display/Container.ts +1 -1
  86. package/src/display/ParticleContainer.ts +1 -1
  87. package/src/plugins/Plugin.ts +1 -1
  88. package/src/plugins/defaults.ts +6 -0
  89. package/src/plugins/gesture/GesturePlugin.ts +215 -0
  90. package/src/plugins/gesture/gestureMath.test.ts +75 -0
  91. package/src/plugins/gesture/gestureMath.ts +59 -0
  92. package/src/plugins/gesture/index.ts +2 -0
  93. package/src/plugins/gesture/types.ts +54 -0
  94. package/src/plugins/index.ts +1 -0
  95. package/src/plugins/input/Controls.ts +9 -3
  96. package/src/plugins/input/InputPlugin.ts +61 -14
  97. package/src/plugins/input/interfaces.ts +5 -3
  98. package/src/plugins/input/touch/{TouchControls.ts → VirtualControls.ts} +4 -1
  99. package/src/plugins/input/touch/index.ts +1 -1
  100. package/src/types/caper-app.d.ts +1 -0
  101. package/src/utils/bind.test.ts +99 -0
  102. package/src/version.ts +1 -1
  103. package/templates/app/default/package.template.json +8 -4
  104. package/templates/app/default/vite.config.ts +15 -0
  105. package/LICENSE +0 -22
  106. package/cli/vite.mjs +0 -55
  107. package/config/vite.mjs +0 -2464
  108. package/lib/plugins/input/touch/TouchControls.d.ts.map +0 -1
  109. package/lib/registries-CYCaYKZI.js.map +0 -1
@@ -0,0 +1,460 @@
1
+ /**
2
+ * Turns AssetPack's `assets.json` into `caper-assets.d.ts`, so every bundle,
3
+ * texture, spritesheet, font, audio clip and JSON file in the project is a
4
+ * literal type rather than a string an app can typo.
5
+ *
6
+ * Regenerated whenever the manifest changes — the plugin watches it in dev and
7
+ * reloads the page, because vite does not reload for changes under `publicDir`.
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { loadManifestBundleNames } from '../internal/manifest.mjs';
12
+ import { ASSET_DTS_FILE_NAME, debounce, delay, logger } from '../internal/util.mjs';
13
+
14
+ export { loadManifestBundleNames };
15
+
16
+ async function generateAssetTypes(manifest, assetsDir) {
17
+ // Flat totals per category (back-compat: AssetTextures, AssetAudio, etc.)
18
+ const assetsByType = {
19
+ textures: new Set(),
20
+ spritesheets: new Set(),
21
+ tpsFrames: new Set(),
22
+ fonts: new Set(),
23
+ bitmapFonts: new Set(),
24
+ fontFamilies: new Set(),
25
+ bitmapFontFamilies: new Set(),
26
+ audio: new Set(),
27
+ json: new Set(),
28
+ spine: new Set(),
29
+ rive: new Set(),
30
+ };
31
+
32
+ // Per-bundle breakdown so we can narrow e.g. AssetTexturesIn<'menu'> → only
33
+ // textures that actually ship in the 'menu' bundle. Shape:
34
+ // byBundle.textures.menu = Set(['menu/logo'])
35
+ const byBundle = {
36
+ textures: {},
37
+ spritesheets: {},
38
+ tpsFrames: {},
39
+ fonts: {},
40
+ bitmapFonts: {},
41
+ audio: {},
42
+ json: {},
43
+ spine: {},
44
+ rive: {},
45
+ };
46
+ const addToBundle = (category, bundleName, alias) => {
47
+ if (!byBundle[category][bundleName]) byBundle[category][bundleName] = new Set();
48
+ byBundle[category][bundleName].add(alias);
49
+ };
50
+
51
+ const bundles = manifest.bundles || [];
52
+ const bundleNames = new Set();
53
+
54
+ // Process each bundle
55
+ for (const bundle of bundles) {
56
+ bundleNames.add(bundle.name);
57
+
58
+ // Process each asset in the bundle
59
+ for (const asset of bundle.assets) {
60
+ const aliases = asset.alias || [];
61
+ const srcs = Array.isArray(asset.src) ? asset.src : [asset.src];
62
+ const firstSrc = srcs[0];
63
+ const ext = path.extname(firstSrc).toLowerCase();
64
+
65
+ // Add to appropriate category based on extension and data tags
66
+ if (asset.data?.tags?.tps || (ext === '.json' && firstSrc.includes('sheet'))) {
67
+ aliases.forEach((alias) => {
68
+ assetsByType.spritesheets.add(alias);
69
+ addToBundle('spritesheets', bundle.name, alias);
70
+ });
71
+
72
+ // Extract frame names from TPS JSON files
73
+ if (asset.data?.tags?.tps) {
74
+ try {
75
+ // Find the first .json file in the src array
76
+ const jsonSrc = srcs.find((src) => src.endsWith('.json'));
77
+ if (jsonSrc) {
78
+ // Construct the full path to the JSON file
79
+ const jsonPath = path.join(assetsDir, jsonSrc);
80
+
81
+ // Read and parse the JSON file
82
+ const jsonContent = await fs.promises.readFile(jsonPath, 'utf8');
83
+ const tpsData = JSON.parse(jsonContent);
84
+
85
+ // Extract frame names from the "frames" object
86
+ if (tpsData.frames) {
87
+ Object.keys(tpsData.frames).forEach((frameName) => {
88
+ assetsByType.tpsFrames.add(frameName);
89
+ addToBundle('tpsFrames', bundle.name, frameName);
90
+ });
91
+ }
92
+ }
93
+ } catch (error) {
94
+ logger.warn(`Failed to load TPS frames from ${firstSrc}:`, error.message);
95
+ }
96
+ }
97
+ } else if (ext === '.json' && !firstSrc.includes('atlas')) {
98
+ aliases.forEach((alias) => {
99
+ assetsByType.json.add(alias);
100
+ addToBundle('json', bundle.name, alias);
101
+ });
102
+ } else if (['.png', '.webp', '.jpg', '.jpeg', '.svg'].includes(ext)) {
103
+ aliases.forEach((alias) => {
104
+ assetsByType.textures.add(alias);
105
+ addToBundle('textures', bundle.name, alias);
106
+ });
107
+ } else if (['.mp3', '.ogg', '.wav'].includes(ext)) {
108
+ aliases.forEach((alias) => {
109
+ assetsByType.audio.add(alias);
110
+ addToBundle('audio', bundle.name, alias);
111
+ });
112
+ } else if (['.ttf', '.woff', '.woff2'].includes(ext) || asset.data?.tags?.wf) {
113
+ aliases.forEach((alias) => {
114
+ assetsByType.fonts.add(alias);
115
+ addToBundle('fonts', bundle.name, alias);
116
+ });
117
+ if (asset.data?.family) {
118
+ assetsByType.fontFamilies.add(asset.data.family);
119
+ }
120
+ } else if (['.fnt'].includes(ext)) {
121
+ aliases.forEach((alias) => {
122
+ assetsByType.bitmapFonts.add(alias);
123
+ assetsByType.bitmapFontFamilies.add(alias);
124
+ addToBundle('bitmapFonts', bundle.name, alias);
125
+ });
126
+ } else if (['.atlas', '.skel', '.json'].some((e) => firstSrc.includes(e)) && firstSrc.includes('spine')) {
127
+ aliases.forEach((alias) => {
128
+ assetsByType.spine.add(alias);
129
+ addToBundle('spine', bundle.name, alias);
130
+ });
131
+ } else if (ext === '.riv') {
132
+ aliases.forEach((alias) => {
133
+ assetsByType.rive.add(alias);
134
+ addToBundle('rive', bundle.name, alias);
135
+ });
136
+ }
137
+ }
138
+ }
139
+
140
+ // Convert Sets to sorted arrays for consistent output
141
+ const types = Object.fromEntries(Object.entries(assetsByType).map(([key, value]) => [key, [...value].sort()]));
142
+
143
+ // Helper to emit a per-bundle mapped type body like:
144
+ // '\n menu: \'menu/logo\' | \'menu/bg\';\n game: \'game/hero\';\n '
145
+ // Returns `never` if no bundle contains anything in the category.
146
+ const emitByBundleMap = (category) => {
147
+ const entries = Object.entries(byBundle[category])
148
+ .map(([bundleName, set]) => [bundleName, [...set].sort()])
149
+ .filter(([, arr]) => arr.length > 0);
150
+ if (entries.length === 0) return '{}';
151
+ const lines = entries.map(([name, arr]) => ` ${name}: '${arr.join("' | '")}';`);
152
+ return `{\n${lines.join('\n')}\n }`;
153
+ };
154
+
155
+ return `// This file is auto-generated. Do not edit.
156
+ import type { ResolvedAsset, Texture, Spritesheet } from 'pixi.js';
157
+
158
+ /**
159
+ * Available bundle names in the asset manifest
160
+ * @example
161
+ * const bundle: AssetBundles = 'game';
162
+ */
163
+ export type AssetBundles = ${[...bundleNames].length ? `\n | '${[...bundleNames].sort().join("'\n | '")}'` : 'never'};
164
+
165
+ /**
166
+ * Available texture names in the asset manifest
167
+ * @example
168
+ * const texture: AssetTextures = 'game/wordmark';
169
+ */
170
+ export type AssetTextures = ${types.textures.length ? `\n | '${types.textures.join("'\n | '")}'` : 'never'};
171
+
172
+ /**
173
+ * Per-bundle texture map. Use \`AssetTexturesIn<'menu'>\` to get the exact
174
+ * set of textures shipped in a single bundle, so a scene that only loads
175
+ * the 'menu' bundle can't accidentally reference a 'game/*' texture.
176
+ */
177
+ export type AssetTexturesByBundle = ${emitByBundleMap('textures')};
178
+ export type AssetTexturesIn<B extends AssetBundles> = B extends keyof AssetTexturesByBundle ? AssetTexturesByBundle[B] : never;
179
+
180
+ /**
181
+ * Available spritesheet names in the asset manifest
182
+ * @example
183
+ * const spritesheet: AssetSpritesheets = 'game/sheet';
184
+ */
185
+ export type AssetSpritesheets = ${types.spritesheets.length ? `\n | '${types.spritesheets.join("'\n | '")}'` : 'never'};
186
+
187
+ export type AssetSpritesheetsByBundle = ${emitByBundleMap('spritesheets')};
188
+ export type AssetSpritesheetsIn<B extends AssetBundles> = B extends keyof AssetSpritesheetsByBundle ? AssetSpritesheetsByBundle[B] : never;
189
+
190
+ /**
191
+ * Available TPS frame names from spritesheets
192
+ * @example
193
+ * const frame: AssetTPSFrames = 'btn/blue';
194
+ */
195
+ export type AssetTPSFrames = ${types.tpsFrames.length ? `\n | '${types.tpsFrames.join("'\n | '")}'` : 'never'};
196
+
197
+ export type AssetTPSFramesByBundle = ${emitByBundleMap('tpsFrames')};
198
+ export type AssetTPSFramesIn<B extends AssetBundles> = B extends keyof AssetTPSFramesByBundle ? AssetTPSFramesByBundle[B] : never;
199
+
200
+ /**
201
+ * Available font names in the asset manifest
202
+ * @example
203
+ * const font: AssetFonts = 'SpaceGrotesk-Regular';
204
+ */
205
+ export type AssetFonts = ${types.fonts.length ? `\n | '${types.fonts.join("'\n | '")}'` : 'never'};
206
+
207
+ /**
208
+ * Available font names in the asset manifest
209
+ * @example
210
+ * const font: AssetFonts = 'SpaceGrotesk-Regular';
211
+ */
212
+ export type AssetBitmapFonts = ${types.bitmapFonts.length ? `\n | '${types.bitmapFonts.join("'\n | '")}'` : 'never'};
213
+
214
+ /**
215
+ * Available audio names in the asset manifest
216
+ * @example
217
+ * const audio: AssetAudio = 'click';
218
+ */
219
+ export type AssetAudio = ${types.audio.length ? `\n | '${types.audio.join("'\n | '")}'` : 'never'};
220
+
221
+ export type AssetAudioByBundle = ${emitByBundleMap('audio')};
222
+ export type AssetAudioIn<B extends AssetBundles> = B extends keyof AssetAudioByBundle ? AssetAudioByBundle[B] : never;
223
+
224
+ /**
225
+ * Available JSON file names in the asset manifest
226
+ * @example
227
+ * const json: AssetJson = 'locales/en';
228
+ */
229
+ export type AssetJson = ${types.json.length ? `\n | '${types.json.join("'\n | '")}'` : 'never'};
230
+
231
+ /**
232
+ * Available Spine animation names in the asset manifest
233
+ * @example
234
+ * const spine: AssetSpine = 'spine/hero';
235
+ */
236
+ export type AssetSpine = ${types.spine.length ? `\n | '${types.spine.join("'\n | '")}'` : 'never'};
237
+
238
+ /**
239
+ * Available Rive animation names in the asset manifest
240
+ * @example
241
+ * const rive: AssetRive = 'static/marty';
242
+ */
243
+ export type AssetRive = ${types.rive.length ? `\n | '${types.rive.join("'\n | '")}'` : 'never'};
244
+
245
+ /**
246
+ * Available font family names
247
+ * @example
248
+ * const fontFamily: AssetFontFamilies = 'Space Grotesk';
249
+ */
250
+ export type AssetFontFamilies = ${types.fontFamilies.length ? `\n | '${types.fontFamilies.join("'\n | '")}'` : 'never'};
251
+
252
+ /**
253
+ * Available font family names
254
+ * @example
255
+ * const fontFamily: AssetFontFamilies = 'Space Grotesk';
256
+ */
257
+ export type AssetBitmapFontFamilies = ${types.bitmapFontFamilies.length ? `\n | '${types.bitmapFontFamilies.join("'\n | '")}'` : 'never'};
258
+
259
+ /**
260
+ * Union type of all asset names
261
+ * @example
262
+ * const asset: AssetAlias = 'game/wordmark';
263
+ */
264
+ export type AssetAlias =
265
+ | AssetTextures
266
+ | AssetSpritesheets
267
+ | AssetTPSFrames
268
+ | AssetFonts
269
+ | AssetBitmapFonts
270
+ | AssetAudio
271
+ | AssetJson
272
+ | AssetSpine
273
+ | AssetRive;
274
+
275
+ /**
276
+ * Type-safe manifest structure
277
+ */
278
+ export interface AssetManifest {
279
+ bundles: {
280
+ [K in AssetBundles]: {
281
+ name: K;
282
+ assets: ResolvedAsset[];
283
+ }
284
+ };
285
+ }
286
+
287
+ /**
288
+ * Type-safe asset types after loading
289
+ */
290
+ export interface AssetTypes {
291
+ textures: Record<AssetTextures, Texture>;
292
+ spritesheets: Record<AssetSpritesheets, Spritesheet>;
293
+ tpsFrames: Record<AssetTPSFrames, Texture>;
294
+ fonts: Record<AssetFonts, any>;
295
+ audio: Record<AssetAudio, HTMLAudioElement>;
296
+ json: Record<AssetJson, any>;
297
+ spine: Record<AssetSpine, any>;
298
+ rive: Record<AssetRive, any>;
299
+ fontFamilies: Record<AssetFontFamilies, any>;
300
+ bitmapFonts: Record<AssetBitmapFonts, any>;
301
+ bitmapFontFamilies: Record<AssetBitmapFontFamilies, any>;
302
+ }
303
+
304
+ /**
305
+ * Helper type to get the asset type for a given alias
306
+ * @example
307
+ * type MyTextureType = AssetTypeOf<'game/wordmark'>; // Texture
308
+ */
309
+ export type AssetTypeOf<T extends AssetAlias> =
310
+ T extends AssetTextures ? Texture :
311
+ T extends AssetSpritesheets ? Spritesheet :
312
+ T extends AssetTPSFrames ? Texture :
313
+ T extends AssetFonts ? any :
314
+ T extends AssetBitmapFonts ? any :
315
+ T extends AssetAudio ? HTMLAudioElement :
316
+ T extends AssetJson ? any :
317
+ T extends AssetSpine ? any :
318
+ T extends AssetRive ? any :
319
+ T extends AssetFontFamilies ? any :
320
+ T extends AssetBitmapFontFamilies ? any :
321
+ never;
322
+
323
+
324
+ /**
325
+ * Get the bundle name for a given asset
326
+ * @example
327
+ * type MyBundle = AssetBundleOf<'game/wordmark'>; // 'game'
328
+ */
329
+ export type AssetBundleOf<T extends AssetAlias> = Extract<AssetBundles, T extends \`\${infer B}/\${string}\` ? B : never>;
330
+
331
+ /**
332
+ * Add type overrides to the framework
333
+ */
334
+ declare module '@caperjs/core' {
335
+ interface AssetTypeOverrides {
336
+ Texture: AssetTextures;
337
+ TPSFrames: AssetTPSFrames;
338
+ SpriteSheet: AssetSpritesheets;
339
+ SpineData: AssetSpine;
340
+ Audio: AssetAudio;
341
+ FontFamily: AssetFontFamilies;
342
+ BitmapFontFamily: AssetBitmapFontFamilies;
343
+ Bundles: AssetBundles;
344
+ }
345
+ }
346
+ `;
347
+ }
348
+
349
+ // Function to write types file
350
+
351
+ async function writeAssetTypes(manifest, outputDir, assetsDir, root) {
352
+ const types = await generateAssetTypes(manifest, assetsDir);
353
+ // Change output path to ./src/types/
354
+ const srcTypesDir = path.join(root, 'src', 'types');
355
+
356
+ try {
357
+ // Ensure the directory exists
358
+ await fs.promises.mkdir(srcTypesDir, { recursive: true });
359
+ const typesPath = path.join(srcTypesDir, ASSET_DTS_FILE_NAME);
360
+ await fs.promises.writeFile(typesPath, types, 'utf8');
361
+ logger.info(`Caper asset types plugin:: Generated types at ${typesPath}`);
362
+ } catch (error) {
363
+ logger.error('Caper asset types plugin:: Error writing types file:', error);
364
+ // Fallback to original location if src folder doesn't exist
365
+ const typesPath = path.join(outputDir, ASSET_DTS_FILE_NAME);
366
+ await fs.promises.writeFile(typesPath, types, 'utf8');
367
+ logger.info(`Caper asset types plugin:: Generated types at fallback location ${typesPath}`);
368
+ }
369
+ }
370
+
371
+ // Asset types generation plugin
372
+
373
+ export function assetTypesPlugin(manifestUrl = 'assets.json') {
374
+ // vite's resolved publicDir/root rather than process.cwd() — same reasoning as
375
+ // internal/discovery.mjs.
376
+ let publicDir;
377
+ let root;
378
+ let viteServer;
379
+ let manifestWatcher;
380
+ let ispPwaEnabled = false;
381
+
382
+ async function generate(manifestUrl) {
383
+ try {
384
+ const manifestPath = path.join(publicDir, 'assets', manifestUrl);
385
+ if (!fs.existsSync(manifestPath)) {
386
+ logger.warn(`Caper asset types plugin:: manifest not found at ${manifestPath}, skipping type generation`);
387
+ return;
388
+ }
389
+ const manifest = JSON.parse(await fs.promises.readFile(manifestPath, 'utf8'));
390
+ await writeAssetTypes(manifest, path.dirname(manifestPath), path.join(publicDir, 'assets'), root);
391
+ logger.info('Caper asset types plugin:: manifest changed, reloading browser...');
392
+ viteServer?.ws?.send({ type: 'full-reload' });
393
+ } catch (error) {
394
+ logger.error('Caper asset types plugin:: Error handling manifest change:', error);
395
+ }
396
+ }
397
+
398
+ const debouncedHandleManifestChange = debounce(generate, 300);
399
+
400
+ return {
401
+ name: 'vite-plugin-asset-types',
402
+ config(config) {
403
+ ispPwaEnabled = config.plugins.some((p) => p.name === 'vite-plugin-pwa');
404
+ },
405
+ configResolved(config) {
406
+ publicDir = config.publicDir;
407
+ root = config.root;
408
+ },
409
+ async buildStart() {
410
+ // a short delay to allow assetpack to generate the manifest
411
+ await delay(500);
412
+ await generate(manifestUrl);
413
+ await delay(500);
414
+ },
415
+ configureServer(server) {
416
+ viteServer = server;
417
+
418
+ // Watch for manifest changes in development
419
+ const manifestPath = path.join(publicDir, 'assets', manifestUrl);
420
+ server.watcher.add(manifestPath);
421
+ logger.info(`Caper asset types plugin:: watching manifest at ${manifestPath}`);
422
+
423
+ const handleChange = async (file) => {
424
+ if (file === manifestPath) {
425
+ await debouncedHandleManifestChange(manifestUrl);
426
+ }
427
+ };
428
+
429
+ server.watcher.on('add', handleChange);
430
+ server.watcher.on('change', handleChange);
431
+ },
432
+ async buildEnd() {
433
+ manifestWatcher?.close();
434
+
435
+ // Generate types in build mode as well
436
+ try {
437
+ const manifestPath = path.join(publicDir, 'assets', manifestUrl);
438
+ if (fs.existsSync(manifestPath)) {
439
+ const manifest = JSON.parse(await fs.promises.readFile(manifestPath, 'utf8'));
440
+ await writeAssetTypes(manifest, path.dirname(manifestPath), path.join(publicDir, 'assets'), root);
441
+ }
442
+ } catch (error) {
443
+ logger.error('Caper asset types plugin:: Error generating types during build:', error);
444
+ }
445
+ await delay(500);
446
+ },
447
+ async closeBundle() {
448
+ if (ispPwaEnabled && env !== 'development') {
449
+ logger.info('Caper asset types plugin:: PWA enabled, generating types one last time after bundle');
450
+ await generate(manifestUrl);
451
+ }
452
+ },
453
+ };
454
+ }
455
+
456
+ /**
457
+ * Read the assetpack manifest from disk and return the set of bundle names.
458
+ * Returns `null` if the manifest doesn't exist yet — in that case the caller
459
+ * should skip bundle-name validation rather than spam false warnings.
460
+ */