@playcraft/build 0.2.1 → 0.2.2

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.
@@ -0,0 +1,11 @@
1
+ type DeliveryFileOptions = {
2
+ excludePaths?: readonly string[];
3
+ excludeRootTemporaryDirectories?: boolean;
4
+ };
5
+ /**
6
+ * 复制、外置和归档共用的交付文件规则:忽略任意层级的隐藏路径,
7
+ * 保留所有可见文件,不按扩展名或静态引用裁剪动态加载的资源。
8
+ * 只收集叶子条目;符号链接不递归跟随,交给复制或归档步骤处理。
9
+ */
10
+ export declare function collectDeliveryFiles(rootDir: string, options?: DeliveryFileOptions): Promise<string[]>;
11
+ export {};
@@ -0,0 +1,30 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ /**
4
+ * 复制、外置和归档共用的交付文件规则:忽略任意层级的隐藏路径,
5
+ * 保留所有可见文件,不按扩展名或静态引用裁剪动态加载的资源。
6
+ * 只收集叶子条目;符号链接不递归跟随,交给复制或归档步骤处理。
7
+ */
8
+ export async function collectDeliveryFiles(rootDir, options = {}) {
9
+ const excluded = new Set((options.excludePaths ?? []).map((entry) => path.normalize(entry)));
10
+ const files = [];
11
+ async function visit(relativeDir) {
12
+ const entries = await fs.readdir(path.join(rootDir, relativeDir), { withFileTypes: true });
13
+ for (const entry of entries) {
14
+ const relativePath = path.join(relativeDir, entry.name);
15
+ if (entry.name.startsWith('.') || excluded.has(relativePath))
16
+ continue;
17
+ if (relativeDir === '' && options.excludeRootTemporaryDirectories &&
18
+ entry.isDirectory() && entry.name.startsWith('__'))
19
+ continue;
20
+ if (entry.isDirectory()) {
21
+ await visit(relativePath);
22
+ }
23
+ else {
24
+ files.push(relativePath);
25
+ }
26
+ }
27
+ }
28
+ await visit('');
29
+ return files.sort();
30
+ }
@@ -6,6 +6,7 @@ import archiver from 'archiver';
6
6
  import { createWriteStream } from 'fs';
7
7
  import { PLATFORM_CONFIGS } from './platform-configs.js';
8
8
  import { minifyJS, minifyPatchCode } from '../utils/minify.js';
9
+ import { collectDeliveryFiles } from './delivery-files.js';
9
10
  /**
10
11
  * 平台 Vite 插件
11
12
  * 注入平台特定代码和处理输出格式
@@ -62,7 +63,7 @@ export function vitePlatformPlugin(options) {
62
63
  }
63
64
  if (options.outputFormat === 'zip') {
64
65
  // 等待 ZIP 创建完成
65
- await createZipOutput(options.outputDir, platformConfig.outputFileName);
66
+ await createZipOutput(options.outputDir);
66
67
  }
67
68
  },
68
69
  };
@@ -70,8 +71,9 @@ export function vitePlatformPlugin(options) {
70
71
  /**
71
72
  * 创建 ZIP 输出
72
73
  */
73
- function createZipOutput(outDir, htmlFileName) {
74
- return new Promise(async (resolve, reject) => {
74
+ async function createZipOutput(outDir) {
75
+ const files = await collectDeliveryFiles(outDir, { excludePaths: ['playable.zip'] });
76
+ return new Promise((resolve, reject) => {
75
77
  const zipPath = path.join(outDir, 'playable.zip');
76
78
  const output = createWriteStream(zipPath);
77
79
  const archive = archiver('zip', { zlib: { level: 9 } });
@@ -82,12 +84,14 @@ function createZipOutput(outDir, htmlFileName) {
82
84
  archive.on('error', (err) => {
83
85
  reject(err);
84
86
  });
87
+ output.on('error', reject);
85
88
  archive.pipe(output);
86
- // 添加输出目录全部内容(排除 zip 本身)
87
- archive.glob('**/*', {
88
- cwd: outDir,
89
- ignore: ['playable.zip'],
90
- });
89
+ // 仅加入交付文件,目录由文件路径自然形成,避免归档空目录条目。
90
+ for (const relativePath of files) {
91
+ archive.file(path.join(outDir, relativePath), {
92
+ name: relativePath.split(path.sep).join('/'),
93
+ });
94
+ }
91
95
  archive.finalize();
92
96
  });
93
97
  }
@@ -96,7 +100,7 @@ async function keepSingleHtml(outDir, htmlFileName) {
96
100
  try {
97
101
  entries = await fs.readdir(outDir, { withFileTypes: true });
98
102
  }
99
- catch (error) {
103
+ catch {
100
104
  return;
101
105
  }
102
106
  // 如果目标文件名不是 index.html,先重命名
@@ -107,7 +111,7 @@ async function keepSingleHtml(outDir, htmlFileName) {
107
111
  await fs.rename(indexPath, targetPath);
108
112
  console.log(`[Platform] 已重命名 index.html -> ${htmlFileName}`);
109
113
  }
110
- catch (error) {
114
+ catch {
111
115
  // index.html 可能不存在,忽略错误
112
116
  }
113
117
  }
@@ -131,25 +135,28 @@ async function applyExternFiles(outDir, externFiles) {
131
135
  const folderName = externFiles.folderName?.trim() || `playcraft-assets-${crypto.randomUUID()}`;
132
136
  const externalPrefix = externFiles.externalUrlPrefix?.trim().replace(/\/+$/g, '');
133
137
  const assetPrefix = externalPrefix ? `${externalPrefix}/${folderName}/` : `${folderName}/`;
134
- // 资源已全部内联到 index.html 时没有文件需要外置,不创建资源文件夹,也不改写路径,
135
- // 否则 ZIP 中会留下一个没有引用的空目录。
136
- const entries = (await fs.readdir(outDir, { withFileTypes: true })).filter((entry) => entry.name !== 'index.html' && entry.name !== folderName);
137
- if (entries.length === 0) {
138
+ await cleanEmptyDirs(outDir);
139
+ // 仅实际参与交付的文件需要外置;隐藏文件和空目录不触发目录创建或路径改写。
140
+ const folderPath = path.join(outDir, folderName);
141
+ const files = await collectDeliveryFiles(outDir, {
142
+ excludePaths: ['index.html', 'playable.zip', path.relative(outDir, folderPath)],
143
+ });
144
+ if (files.length === 0) {
138
145
  return;
139
146
  }
140
- const folderPath = path.join(outDir, folderName);
141
- await fs.mkdir(folderPath, { recursive: true });
142
- for (const entry of entries) {
143
- const srcPath = path.join(outDir, entry.name);
144
- const destPath = path.join(folderPath, entry.name);
147
+ for (const relativePath of files) {
148
+ const srcPath = path.join(outDir, relativePath);
149
+ const destPath = path.join(folderPath, relativePath);
150
+ await fs.mkdir(path.dirname(destPath), { recursive: true });
145
151
  await fs.rename(srcPath, destPath);
146
152
  }
153
+ await cleanEmptyDirs(outDir);
147
154
  // config.json 也移入资产文件夹,最外层只保留 index.html + 资产文件夹
148
155
  // CONFIG_FILENAME 需要加上资产文件夹前缀,引擎通过 CONFIG_FILENAME 加载 config
149
156
  const configFilename = `${folderName}/config.json`;
150
157
  await rewriteIndexHtml(outDir, assetPrefix, configFilename);
151
158
  await rewriteSettings(folderPath, assetPrefix, configFilename);
152
- await rewriteConfig(path.join(folderPath), folderPath, folderName);
159
+ await rewriteConfig(folderPath);
153
160
  }
154
161
  async function rewriteIndexHtml(outDir, assetPrefix, configFilename) {
155
162
  const indexPath = path.join(outDir, 'index.html');
@@ -237,17 +244,17 @@ async function rewriteSettings(folderPath, assetPrefix, configFilename) {
237
244
  }
238
245
  await fs.writeFile(settingsPath, code);
239
246
  }
240
- catch (error) {
247
+ catch {
241
248
  // 忽略缺失
242
249
  }
243
250
  }
244
- async function rewriteConfig(configDir, _folderPath, _folderName) {
251
+ async function rewriteConfig(configDir) {
245
252
  // config.json 已移入资产文件夹,在此处可对其进行后处理
246
253
  const configPath = path.join(configDir, 'config.json');
247
254
  try {
248
255
  await fs.access(configPath);
249
256
  }
250
- catch (error) {
257
+ catch {
251
258
  // 忽略缺失
252
259
  }
253
260
  }
@@ -411,24 +418,8 @@ function isAmmoModule(module) {
411
418
  async function applyMraidSupport(outDir) {
412
419
  // Note: We no longer patch fillMode to 'NONE' because it causes canvas scaling issues
413
420
  // The MRAID resize patch handles the sizing correctly with any fillMode
414
- // await patchConfigFillMode(outDir); // Removed: causes canvas scaling issues
415
421
  await patchStylesForMraid(outDir);
416
422
  }
417
- async function patchConfigFillMode(outDir) {
418
- const configPath = path.join(outDir, 'config.json');
419
- try {
420
- const raw = await fs.readFile(configPath, 'utf-8');
421
- const json = JSON.parse(raw);
422
- json.application_properties = {
423
- ...(json.application_properties || {}),
424
- fillMode: 'NONE',
425
- };
426
- await fs.writeFile(configPath, JSON.stringify(json));
427
- }
428
- catch (error) {
429
- // 忽略缺失
430
- }
431
- }
432
423
  async function patchStylesForMraid(outDir) {
433
424
  const cssPath = path.join(outDir, 'styles.css');
434
425
  try {
@@ -438,7 +429,7 @@ async function patchStylesForMraid(outDir) {
438
429
  await fs.writeFile(cssPath, css);
439
430
  }
440
431
  }
441
- catch (error) {
432
+ catch {
442
433
  // 忽略缺失
443
434
  }
444
435
  }
@@ -453,47 +444,23 @@ async function readPatchFile(name) {
453
444
  return await fs.readFile(patchPath, 'utf-8');
454
445
  }
455
446
  async function copyBaseBuildAssets(baseBuildDir, outDir) {
456
- // 计算 outDir 相对于 baseBuildDir 的名称(如果 outDir 是 baseBuildDir 的子目录)
447
+ // 输出目录可能位于基础构建中;只排除其自身子树,保留同级的真实资源。
457
448
  const outDirRelative = path.relative(baseBuildDir, outDir);
458
- const outDirName = outDirRelative.split(path.sep)[0]; // 获取第一级目录名
459
- const entries = await fs.readdir(baseBuildDir, { withFileTypes: true });
460
- for (const entry of entries) {
461
- // 跳过 index.html
462
- if (entry.name === 'index.html') {
463
- continue;
464
- }
465
- // 跳过输出目录本身(避免无限递归)
466
- if (entry.name === outDirName) {
467
- continue;
468
- }
469
- // 跳过以 __ 开头的临时目录(如 __dist__, __esm-temp__, __esm-work__ 等)
470
- // 注意:不能跳过 __ 开头的文件,因为 Classic 模式下
471
- // __start__.js, __settings__.js, __modules__.js, __loading__.js, __game-scripts.js 都是必需的
472
- if (entry.isDirectory() && entry.name.startsWith('__')) {
473
- continue;
474
- }
475
- const srcPath = path.join(baseBuildDir, entry.name);
476
- const destPath = path.join(outDir, entry.name);
477
- if (entry.isDirectory()) {
478
- await copyDirectory(srcPath, destPath);
479
- }
480
- else {
481
- await fs.copyFile(srcPath, destPath);
482
- }
483
- }
484
- }
485
- async function copyDirectory(src, dest) {
486
- await fs.mkdir(dest, { recursive: true });
487
- const entries = await fs.readdir(src, { withFileTypes: true });
488
- for (const entry of entries) {
489
- const srcPath = path.join(src, entry.name);
490
- const destPath = path.join(dest, entry.name);
491
- if (entry.isDirectory()) {
492
- await copyDirectory(srcPath, destPath);
493
- }
494
- else {
495
- await fs.copyFile(srcPath, destPath);
496
- }
449
+ if (outDirRelative === '')
450
+ return;
451
+ const excludePaths = ['index.html', 'playable.zip'];
452
+ if (!path.isAbsolute(outDirRelative) && outDirRelative !== '..' && !outDirRelative.startsWith(`..${path.sep}`)) {
453
+ excludePaths.push(outDirRelative);
454
+ }
455
+ const files = await collectDeliveryFiles(baseBuildDir, {
456
+ excludePaths,
457
+ // 根层 __* 目录属于基础构建的临时工作区;同名文件仍是合法引擎资源。
458
+ excludeRootTemporaryDirectories: true,
459
+ });
460
+ for (const relativePath of files) {
461
+ const destPath = path.join(outDir, relativePath);
462
+ await fs.mkdir(path.dirname(destPath), { recursive: true });
463
+ await fs.copyFile(path.join(baseBuildDir, relativePath), destPath);
497
464
  }
498
465
  }
499
466
  /**
@@ -525,7 +492,7 @@ async function minifyJSFilesInDir(dir) {
525
492
  const ratio = originalSize > 0 ? ((saved / originalSize) * 100).toFixed(1) : '0';
526
493
  console.log(` ✓ ${relativePath}: ${(originalSize / 1024).toFixed(1)}KB → ${(minifiedSize / 1024).toFixed(1)}KB (-${ratio}%)`);
527
494
  }
528
- catch (error) {
495
+ catch {
529
496
  console.warn(` ⚠ ${path.relative(dir, filePath)}: 压缩失败,保留原文件`);
530
497
  }
531
498
  }
@@ -708,7 +675,9 @@ async function findConfigJson(outDir) {
708
675
  await fs.access(directPath);
709
676
  return directPath;
710
677
  }
711
- catch { }
678
+ catch {
679
+ // 根目录没有配置时继续查找外置资源目录。
680
+ }
712
681
  // 在子目录中查找(externFiles 场景)
713
682
  const entries = await fs.readdir(outDir, { withFileTypes: true });
714
683
  for (const entry of entries) {
@@ -718,7 +687,9 @@ async function findConfigJson(outDir) {
718
687
  await fs.access(subPath);
719
688
  return subPath;
720
689
  }
721
- catch { }
690
+ catch {
691
+ // 当前子目录没有配置时继续检查其余目录。
692
+ }
722
693
  }
723
694
  }
724
695
  return null;
@@ -734,7 +705,9 @@ async function cleanEmptyDirs(dir) {
734
705
  try {
735
706
  await fs.rmdir(fullPath);
736
707
  }
737
- catch { }
708
+ catch {
709
+ // 目录已消失或被其他操作写入时保留现有内容。
710
+ }
738
711
  }
739
712
  else {
740
713
  isEmpty = false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@playcraft/build",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",