@playcraft/build 0.1.88 → 0.1.90

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 (101) hide show
  1. package/dist/audio-source-files.d.ts +5 -0
  2. package/dist/audio-source-files.js +135 -0
  3. package/dist/base-builder.js +41 -2
  4. package/dist/delivery/agent-build-runner.d.ts +44 -0
  5. package/dist/delivery/agent-build-runner.js +365 -0
  6. package/dist/delivery/agent-build-source.d.ts +8 -0
  7. package/dist/delivery/agent-build-source.js +25 -0
  8. package/dist/delivery/artifact-descriptor.d.ts +31 -0
  9. package/dist/delivery/artifact-descriptor.js +237 -0
  10. package/dist/delivery/artifact-package.d.ts +43 -0
  11. package/dist/delivery/artifact-package.js +283 -0
  12. package/dist/delivery/build-plan.d.ts +4 -0
  13. package/dist/delivery/build-plan.js +189 -0
  14. package/dist/delivery/build-plan.types.d.ts +51 -0
  15. package/dist/delivery/build-plan.types.js +1 -0
  16. package/dist/delivery/command-isolation.d.ts +7 -0
  17. package/dist/delivery/command-isolation.js +252 -0
  18. package/dist/delivery/commands.d.ts +5 -0
  19. package/dist/delivery/commands.js +137 -0
  20. package/dist/delivery/files.d.ts +9 -0
  21. package/dist/delivery/files.js +144 -0
  22. package/dist/delivery/git-source-fingerprint.d.ts +2 -0
  23. package/dist/delivery/git-source-fingerprint.js +58 -0
  24. package/dist/delivery/isolated-source.d.ts +5 -0
  25. package/dist/delivery/isolated-source.js +126 -0
  26. package/dist/delivery/output-publication.d.ts +21 -0
  27. package/dist/delivery/output-publication.js +444 -0
  28. package/dist/delivery/project-delivery.d.ts +6 -0
  29. package/dist/delivery/project-delivery.js +287 -0
  30. package/dist/delivery/recipe-build-plan.d.ts +4 -0
  31. package/dist/delivery/recipe-build-plan.js +53 -0
  32. package/dist/delivery/recipe.d.ts +20 -0
  33. package/dist/delivery/recipe.js +211 -0
  34. package/dist/delivery/safe-path.d.ts +2 -0
  35. package/dist/delivery/safe-path.js +18 -0
  36. package/dist/delivery/types.d.ts +76 -0
  37. package/dist/delivery/types.js +1 -0
  38. package/dist/engines/engine-detector.js +4 -0
  39. package/dist/engines/generic-adapter.js +14 -19
  40. package/dist/index.d.ts +19 -4
  41. package/dist/index.js +11 -2
  42. package/dist/platforms/adikteev.js +1 -0
  43. package/dist/platforms/applovin.js +1 -0
  44. package/dist/platforms/base.js +2 -2
  45. package/dist/platforms/bigo.js +1 -0
  46. package/dist/platforms/facebook.js +1 -0
  47. package/dist/platforms/google.js +1 -0
  48. package/dist/platforms/inmobi.js +1 -0
  49. package/dist/platforms/ironsource.js +1 -0
  50. package/dist/platforms/liftoff.js +1 -0
  51. package/dist/platforms/mintegral.js +1 -0
  52. package/dist/platforms/moloco.js +1 -0
  53. package/dist/platforms/playcraft.js +1 -0
  54. package/dist/platforms/remerge.js +1 -0
  55. package/dist/platforms/snapchat.js +1 -0
  56. package/dist/platforms/tiktok.js +1 -0
  57. package/dist/platforms/unity.js +1 -0
  58. package/dist/production-animation-presence.d.ts +2 -0
  59. package/dist/production-animation-presence.js +146 -0
  60. package/dist/production-inputs.d.ts +30 -0
  61. package/dist/production-inputs.js +262 -0
  62. package/dist/production-source-paths.d.ts +5 -0
  63. package/dist/production-source-paths.js +27 -0
  64. package/dist/types.d.ts +5 -0
  65. package/dist/validation/artifact.js +1 -1
  66. package/dist/validation/html-validator.d.ts +2 -0
  67. package/dist/validation/html-validator.js +16 -14
  68. package/dist/validation/package-validator.d.ts +2 -0
  69. package/dist/validation/package-validator.js +24 -15
  70. package/dist/validation/profiles.d.ts +13 -1
  71. package/dist/validation/profiles.js +27 -0
  72. package/dist/validation/types.d.ts +5 -0
  73. package/dist/validation/validation-runner.d.ts +11 -1
  74. package/dist/validation/validation-runner.js +37 -2
  75. package/dist/validation/zip-reader.d.ts +7 -1
  76. package/dist/validation/zip-reader.js +150 -25
  77. package/dist/vite/config-builder-generic.d.ts +3 -1
  78. package/dist/vite/config-builder-generic.js +9 -7
  79. package/dist/vite/config-builder.js +1 -1
  80. package/dist/vite/plugin-platform.js +30 -54
  81. package/dist/vite/plugin-source-builder.d.ts +2 -14
  82. package/dist/vite/plugin-source-builder.js +61 -997
  83. package/dist/vite/source-builder-asset-paths.d.ts +25 -0
  84. package/dist/vite/source-builder-asset-paths.js +154 -0
  85. package/dist/vite/source-builder-esm.d.ts +7 -0
  86. package/dist/vite/source-builder-esm.js +877 -0
  87. package/dist/vite/source-builder-types.d.ts +14 -0
  88. package/dist/vite/source-builder-types.js +1 -0
  89. package/dist/vite/workspace.d.ts +6 -0
  90. package/dist/vite/workspace.js +41 -0
  91. package/dist/vite-builder.d.ts +4 -5
  92. package/dist/vite-builder.js +33 -34
  93. package/dist/workspace-css-imports.d.ts +2 -0
  94. package/dist/workspace-css-imports.js +139 -0
  95. package/dist/workspace-model-source.d.ts +14 -0
  96. package/dist/workspace-model-source.js +184 -0
  97. package/dist/workspace-public-imports.d.ts +11 -0
  98. package/dist/workspace-public-imports.js +232 -0
  99. package/dist/workspace-public-source.d.ts +15 -0
  100. package/dist/workspace-public-source.js +564 -0
  101. package/package.json +15 -3
@@ -0,0 +1,262 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { constants } from 'node:fs';
4
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { PRODUCTION_INPUTS_MANIFEST_PATH, workspaceProductionInputsManifestSchema, computeProductionInputClosureHash, workspaceAudioBindingSchema, inspectAudioArtifactPackage, FRAME_ANIMATION_BINDINGS_PATH, frameAnimationBindingsSchema, inspectFrameAnimationBindings, assertUniqueJsonKeys, } from '@playcraft/common/cloud-workspace/runtime';
8
+ import { productionImmutableAudioPath, readProductionAudioFiles } from './audio-source-files.js';
9
+ import { hasWorkspacePublicSourceDeclaration, readWorkspacePublicSourceClosure } from './workspace-public-source.js';
10
+ import { PUBLIC_METADATA, productionSourcePathAllowed, sourcePathAllowed, materializedPathAllowed } from './production-source-paths.js';
11
+ import { assertNoUnanchoredFrameAnimationSources } from './production-animation-presence.js';
12
+ export { productionSourcePathAllowed } from './production-source-paths.js';
13
+ /** Legacy capability advertisement; newer builders explicitly enumerate supported rules. */
14
+ export const PRODUCTION_SOURCE_RULES_VERSION = 1;
15
+ export const SUPPORTED_PRODUCTION_SOURCE_RULES_VERSIONS = [1, 2];
16
+ export class ProductionSourceError extends Error {
17
+ constructor(code, file) {
18
+ super(file ? `${code}: ${file}` : code);
19
+ this.code = code;
20
+ this.file = file;
21
+ this.name = 'ProductionSourceError';
22
+ }
23
+ }
24
+ const execute = promisify(execFile);
25
+ const digest = (body) => createHash('sha256').update(body).digest('hex');
26
+ const AUXILIARY_METADATA = new Set(['.playcraft/skills.json', '.playcraft/skills.lock.json', '.playcraft/remix-references.json']);
27
+ /** Locked engineering guidance is saved with the project, but does not masquerade as build input. */
28
+ export function productionAuxiliaryPathAllowed(value) {
29
+ if (AUXILIARY_METADATA.has(value) || /^\.playcraft\/skill-artifacts\/[a-f0-9]{64}\.tar\.gz$/.test(value))
30
+ return true;
31
+ return value.startsWith('.agents/skills/') && productionSourcePathAllowed(value.slice('.agents/'.length));
32
+ }
33
+ /** Bounded, no-link reads used for both declarations and the exact production file set. */
34
+ export async function readProductionSourceFile(root, relative, maximum = 64 * 1024 * 1024) {
35
+ return readSourceFile(root, relative, maximum, false);
36
+ }
37
+ async function readSourceFile(root, relative, maximum, immutableAudio, selectedMember = false) {
38
+ if (!productionSourcePathAllowed(relative) && !(immutableAudio && sourcePathAllowed(relative, true) && productionImmutableAudioPath(relative)) && !(selectedMember && materializedPathAllowed(relative)))
39
+ throw new ProductionSourceError('production_input_path_forbidden', relative);
40
+ let current = root;
41
+ const parts = relative.split('/');
42
+ for (let index = 0; index < parts.length; index++) {
43
+ current = path.join(current, parts[index]);
44
+ const stat = await lstat(current);
45
+ if (stat.isSymbolicLink() || (index < parts.length - 1 ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1 || stat.size > maximum))
46
+ throw new ProductionSourceError('production_input_path_unsafe', relative);
47
+ }
48
+ const file = await open(current, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
49
+ try {
50
+ const before = await file.stat();
51
+ if (!before.isFile() || before.nlink !== 1 || before.size > maximum)
52
+ throw new ProductionSourceError('production_input_path_unsafe', relative);
53
+ const body = await file.readFile(), after = await file.stat(), named = await lstat(current);
54
+ if (body.length !== before.size || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size ||
55
+ before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || named.ino !== after.ino || named.dev !== after.dev)
56
+ throw new ProductionSourceError('production_input_changed', relative);
57
+ return { body, mode: before.mode & 0o111 ? '100755' : '100644' };
58
+ }
59
+ finally {
60
+ await file.close();
61
+ }
62
+ }
63
+ async function boundAudioFiles(root) {
64
+ const files = new Map();
65
+ for (const name of ['source', 'source/audio-bindings']) {
66
+ const entry = await lstat(path.join(root, name)).catch((error) => {
67
+ if (error.code === 'ENOENT')
68
+ return undefined;
69
+ throw error;
70
+ });
71
+ if (!entry || (name === 'source' && entry.isFile()))
72
+ return files;
73
+ if (!entry.isDirectory() || entry.isSymbolicLink())
74
+ throw new ProductionSourceError('production_input_path_unsafe', name);
75
+ }
76
+ const entries = await readdir(path.join(root, 'source/audio-bindings'), { withFileTypes: true });
77
+ if (entries.length > 1024)
78
+ throw new ProductionSourceError('production_input_limit');
79
+ for (const entry of entries) {
80
+ if (!entry.name.endsWith('.json'))
81
+ continue;
82
+ const bindingPath = `source/audio-bindings/${entry.name}`;
83
+ const file = await readProductionSourceFile(root, bindingPath, 16384);
84
+ const binding = workspaceAudioBindingSchema.parse(JSON.parse(file.body.toString('utf8')));
85
+ const directory = `dist/audio/${digest(binding.sourcePath)}/${binding.sourceContentHash}/${binding.representationSetHash}`;
86
+ if (bindingPath !== `source/audio-bindings/${binding.eventName}.json` || binding.modulePath !== `${directory}/sound.mjs`)
87
+ throw new ProductionSourceError('production_audio_binding_invalid', bindingPath);
88
+ files.set(bindingPath, file);
89
+ files.set(binding.sourcePath, await readProductionSourceFile(root, binding.sourcePath));
90
+ const bundle = await inspectAudioArtifactPackage(`${directory}/sound.${binding.sourcePath.endsWith('.pcscore.json') ? 'pcscore' : 'pcaudio'}.json`, async (name, maximum) => {
91
+ const member = await readSourceFile(root, name, maximum, true);
92
+ files.set(name, member);
93
+ return member.body;
94
+ });
95
+ if (bundle.sourcePath !== binding.sourcePath || bundle.sourceContentHash !== binding.sourceContentHash ||
96
+ digest(files.get(`${directory}/audition.wav`).body) !== binding.auditionContentHash)
97
+ throw new ProductionSourceError('production_audio_binding_invalid', bindingPath);
98
+ }
99
+ return files;
100
+ }
101
+ async function sourcePaths(root) {
102
+ const marker = await lstat(path.join(root, '.git')).catch(() => undefined);
103
+ if (marker) {
104
+ const { stdout } = await execute('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-C', root,
105
+ 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], { timeout: 60000, maxBuffer: 16 * 1024 * 1024,
106
+ env: { PATH: process.env.PATH, HOME: root, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' } });
107
+ return stdout.split('\0').filter(Boolean);
108
+ }
109
+ const paths = [];
110
+ async function visit(prefix = '') {
111
+ for (const entry of await readdir(path.join(root, prefix), { withFileTypes: true })) {
112
+ const name = prefix ? `${prefix}/${entry.name}` : entry.name;
113
+ if (!productionSourcePathAllowed(name) &&
114
+ !(entry.isDirectory() && [...PUBLIC_METADATA].some(file => file.startsWith(`${name}/`))))
115
+ continue;
116
+ if (entry.isDirectory())
117
+ await visit(name);
118
+ else
119
+ paths.push(name);
120
+ if (paths.length > 8192)
121
+ throw new ProductionSourceError('production_input_limit');
122
+ }
123
+ }
124
+ await visit();
125
+ return paths;
126
+ }
127
+ /** Undefined preserves the exact legacy fingerprint and save rules for older projects. */
128
+ export async function readProductionSourceSnapshot(root, options = {}) {
129
+ root = await realpath(root);
130
+ let declaration;
131
+ try {
132
+ declaration = await readProductionSourceFile(root, PRODUCTION_INPUTS_MANIFEST_PATH, 2 * 1024 * 1024);
133
+ }
134
+ catch (error) {
135
+ if (error.code === 'ENOENT') {
136
+ await assertNoUnanchoredFrameAnimationSources(root);
137
+ return undefined;
138
+ }
139
+ throw error;
140
+ }
141
+ let manifest;
142
+ try {
143
+ manifest = workspaceProductionInputsManifestSchema.parse(JSON.parse(declaration.body.toString('utf8')));
144
+ }
145
+ catch {
146
+ throw new ProductionSourceError('production_inputs_manifest_invalid', PRODUCTION_INPUTS_MANIFEST_PATH);
147
+ }
148
+ if (manifest.schemaVersion !== 3) {
149
+ try {
150
+ if (await hasWorkspacePublicSourceDeclaration(root))
151
+ throw new ProductionSourceError('production_public_workspace_upgrade_required', '.playcraft/workspace.json');
152
+ }
153
+ catch (error) {
154
+ if (error instanceof ProductionSourceError)
155
+ throw error;
156
+ throw new ProductionSourceError('production_public_workspace_invalid', '.playcraft/workspace.json');
157
+ }
158
+ }
159
+ const required = new Map();
160
+ for (const input of manifest.inputs) {
161
+ const { closureHash, ...body } = input;
162
+ if (computeProductionInputClosureHash(body) !== closureHash)
163
+ throw new ProductionSourceError('production_input_closure_changed');
164
+ for (const file of input.files) {
165
+ if (!materializedPathAllowed(file.path))
166
+ throw new ProductionSourceError('production_input_path_forbidden', file.path);
167
+ const previous = required.get(file.path);
168
+ if (previous && JSON.stringify(previous) !== JSON.stringify({ contentHash: file.contentHash, bytes: file.bytes, mode: file.mode }))
169
+ throw new ProductionSourceError('production_input_conflict', file.path);
170
+ required.set(file.path, { contentHash: file.contentHash, bytes: file.bytes, mode: file.mode });
171
+ }
172
+ }
173
+ const animationFiles = new Map();
174
+ const animationIndex = await readProductionSourceFile(root, FRAME_ANIMATION_BINDINGS_PATH, 2 * 1024 * 1024).catch((error) => {
175
+ if (error.code === 'ENOENT')
176
+ return undefined;
177
+ throw error;
178
+ });
179
+ const animationAnchor = manifest.schemaVersion === 1 ? undefined : manifest.animationBindings;
180
+ if (!animationAnchor)
181
+ await assertNoUnanchoredFrameAnimationSources(root);
182
+ if (animationAnchor && (!animationIndex || digest(animationIndex.body) !== animationAnchor.contentHash))
183
+ throw new ProductionSourceError('production_animation_index_changed', FRAME_ANIMATION_BINDINGS_PATH);
184
+ if (animationIndex) {
185
+ if (!animationAnchor)
186
+ throw new ProductionSourceError('production_animation_manifest_required', PRODUCTION_INPUTS_MANIFEST_PATH);
187
+ assertUniqueJsonKeys(animationIndex.body.toString('utf8'));
188
+ const index = frameAnimationBindingsSchema.parse(JSON.parse(animationIndex.body.toString('utf8')));
189
+ const closure = await inspectFrameAnimationBindings(index, manifest, async (name, maximum) => {
190
+ const file = await readProductionSourceFile(root, name, maximum);
191
+ return { bytes: file.body, mode: file.mode };
192
+ });
193
+ animationFiles.set(FRAME_ANIMATION_BINDINGS_PATH, animationIndex);
194
+ for (const [name, file] of closure)
195
+ animationFiles.set(name, { body: Buffer.from(file.bytes), mode: file.mode });
196
+ for (const [name, file] of animationFiles)
197
+ required.set(name, { contentHash: digest(file.body), bytes: file.body.length, mode: file.mode });
198
+ }
199
+ const audio = await readProductionAudioFiles(root, (name, maximum) => readSourceFile(root, name, maximum, true));
200
+ for (const [name, file] of await boundAudioFiles(root)) {
201
+ const previous = audio.get(name);
202
+ if (previous && (previous.mode !== file.mode || !previous.body.equals(file.body)))
203
+ throw new ProductionSourceError('production_input_changed', name);
204
+ audio.set(name, file);
205
+ }
206
+ for (const [name, file] of audio)
207
+ required.set(name, { contentHash: digest(file.body), bytes: file.body.length, mode: file.mode });
208
+ const publicFiles = manifest.schemaVersion === 3
209
+ ? (await readWorkspacePublicSourceClosure(root)).files
210
+ : new Map();
211
+ for (const [name, file] of publicFiles) {
212
+ const previous = animationFiles.get(name) ?? audio.get(name);
213
+ if (previous && (previous.mode !== file.mode || !previous.body.equals(file.body)))
214
+ throw new ProductionSourceError('production_input_conflict', name);
215
+ const immutable = required.get(name);
216
+ const current = { contentHash: digest(file.body), bytes: file.body.length, mode: file.mode };
217
+ if (immutable && JSON.stringify(immutable) !== JSON.stringify(current))
218
+ throw new ProductionSourceError('production_input_conflict', name);
219
+ required.set(name, current);
220
+ }
221
+ const excluded = options.excludedDirectories ?? [];
222
+ const excludedPath = (name) => options.excludedPath?.(name) || excluded.some(prefix => name === prefix || name.startsWith(`${prefix}/`));
223
+ for (const name of required.keys())
224
+ if (excludedPath(name))
225
+ throw new ProductionSourceError('production_input_is_generated', name);
226
+ const candidates = new Set([...(await sourcePaths(root)), PRODUCTION_INPUTS_MANIFEST_PATH, ...required.keys()]);
227
+ const files = new Map();
228
+ let total = 0;
229
+ for (const name of [...candidates].sort()) {
230
+ if ((!productionSourcePathAllowed(name) && !audio.has(name) && !publicFiles.has(name) && !(required.has(name) && materializedPathAllowed(name))) || excludedPath(name))
231
+ continue;
232
+ let file;
233
+ try {
234
+ file = name === PRODUCTION_INPUTS_MANIFEST_PATH ? declaration : publicFiles.get(name) ?? animationFiles.get(name) ?? audio.get(name) ?? await readSourceFile(root, name, 64 * 1024 * 1024, false, required.has(name));
235
+ }
236
+ catch (error) {
237
+ if (!required.has(name) && error.code === 'ENOENT')
238
+ continue;
239
+ throw error;
240
+ }
241
+ const expected = required.get(name);
242
+ if (expected && (expected.contentHash !== digest(file.body) || expected.bytes !== file.body.length || expected.mode !== file.mode))
243
+ throw new ProductionSourceError('production_input_changed', name);
244
+ total += file.body.length;
245
+ if (files.size >= 8192 || total > 256 * 1024 * 1024)
246
+ throw new ProductionSourceError('production_input_limit');
247
+ files.set(name, file);
248
+ }
249
+ const sourceRulesVersion = manifest.schemaVersion === 3 ? 2 : 1;
250
+ const hash = createHash('sha256').update(`playcraft-production-source-v${sourceRulesVersion}\0`);
251
+ for (const [name, file] of files)
252
+ hash.update(name).update('\0').update(file.mode).update('\0').update(file.body).update('\0');
253
+ return { sourceRulesVersion, files, requiredPaths: new Set([PRODUCTION_INPUTS_MANIFEST_PATH, ...required.keys()]), fingerprint: hash.digest('hex') };
254
+ }
255
+ /** Check actual Git-tree bytes and executable bits before declaring save/freeze successful. */
256
+ export async function verifyProductionSourceSnapshot(snapshot, read) {
257
+ for (const [name, expected] of snapshot.files) {
258
+ const actual = await read(name);
259
+ if (!actual || actual.mode !== expected.mode || !actual.body.equals(expected.body))
260
+ throw new ProductionSourceError('production_input_not_committed', name);
261
+ }
262
+ }
@@ -0,0 +1,5 @@
1
+ export declare const PUBLIC_METADATA: Set<string>;
2
+ /** Credentials and process paths are never promoted merely because a declaration names them. */
3
+ export declare function productionSourcePathAllowed(value: string): boolean;
4
+ export declare function materializedPathAllowed(value: string): boolean;
5
+ export declare function sourcePathAllowed(value: string, selectedMember: boolean): boolean;
@@ -0,0 +1,27 @@
1
+ import { workspaceProductionInputPathSchema } from '@playcraft/common/cloud-workspace/runtime';
2
+ const PRIVATE_NAMES = new Set([
3
+ '.git', 'node_modules', '.ssh', '.aws', '.azure', '.gnupg', '.codex', '.npm', '.pnpm-store',
4
+ '.config', '.npmrc', '.yarnrc', '.yarnrc.yml', '.netrc', '.git-credentials', 'credentials',
5
+ 'credentials.json', 'secrets', 'id_rsa', 'id_ed25519', 'settings.local.json',
6
+ '.playcraft.json', 'playcraft.config.json', '.agents', '.claude',
7
+ ]);
8
+ const PROCESS_NAMES = new Set(['work', '.tmp', '.temp', '.cache', '.next', '.vite', '.turbo',
9
+ 'coverage', '.playcraft-temp', '.playcraft-preview-out', 'dist', 'dist-all', '.ds_store', 'thumbs.db', '.eslintcache', '.parcel-cache']);
10
+ export const PUBLIC_METADATA = new Set(['.playcraft/model-build-inputs.json']);
11
+ /** Credentials and process paths are never promoted merely because a declaration names them. */
12
+ export function productionSourcePathAllowed(value) {
13
+ return sourcePathAllowed(value, false);
14
+ }
15
+ export function materializedPathAllowed(value) {
16
+ return workspaceProductionInputPathSchema.safeParse(value).success && sourcePathAllowed(value, true);
17
+ }
18
+ export function sourcePathAllowed(value, selectedMember) {
19
+ if (!value || value.includes('\\') || value.includes('\0') || value.startsWith('/') || value.includes(':') ||
20
+ value.split('/').some(segment => !segment || segment === '.' || segment === '..'))
21
+ return false;
22
+ const parts = value.split('/');
23
+ if (parts.some(segment => PRIVATE_NAMES.has(segment.toLowerCase()) || (!selectedMember && PROCESS_NAMES.has(segment.toLowerCase())) ||
24
+ /^\.env(?:$|\.)/i.test(segment) || /\.(?:pem|key|p12|pfx)$/i.test(segment)))
25
+ return false;
26
+ return !parts.some(segment => segment.toLowerCase() === '.playcraft') || PUBLIC_METADATA.has(value);
27
+ }
package/dist/types.d.ts CHANGED
@@ -20,6 +20,7 @@ export interface ComplianceValidationOptions {
20
20
  export type BuildMode = 'classic' | 'esm';
21
21
  export type ESMMode = 'auto' | 'enabled' | 'disabled';
22
22
  export interface BuildOptions {
23
+ deliveryPreparation?: import('./delivery/types.js').DeliveryPreparationStamp;
23
24
  platform: Platform;
24
25
  format?: OutputFormat;
25
26
  outputDir?: string;
@@ -76,6 +77,9 @@ export interface BaseBuildMetadata {
76
77
  buildTool?: BuildTool;
77
78
  skipChannelBuild?: boolean;
78
79
  buildOutputDir?: string;
80
+ /** Explicit output from the project's delivery recipe; never selected by filename scanning. */
81
+ deliveryArtifact?: string;
82
+ deliveryRecipeDigest?: string;
79
83
  }
80
84
  export interface LocalBuildOptions {
81
85
  scriptsConcatenate?: boolean;
@@ -220,6 +224,7 @@ export interface BaseBuildOptions {
220
224
  /** 渠道产物格式(playable-scripts 阶段;与 Vite 阶段 format 对齐) */
221
225
  format?: OutputFormat;
222
226
  validation?: ComplianceValidationOptions;
227
+ deliveryPreparation?: import('./delivery/types.js').DeliveryPreparationStamp;
223
228
  }
224
229
  /**
225
230
  * 基础构建输出
@@ -109,7 +109,7 @@ function zipSource(buffer) {
109
109
  totalSize: buffer.length,
110
110
  read: async (filePath) => {
111
111
  try {
112
- return zip.readEntryBuffer(filePath);
112
+ return zip.readEntry(filePath);
113
113
  }
114
114
  catch (error) {
115
115
  throw new ArtifactReadError('artifact_zip_invalid', error instanceof Error ? error.message : String(error));
@@ -1,5 +1,7 @@
1
1
  import type { ChannelRuleProfile, ValidationContext, ValidationResult } from './types.js';
2
2
  export declare function validateHtmlArtifact(context: ValidationContext, profile?: ChannelRuleProfile): Promise<ValidationResult[]>;
3
+ /** Validates the exact final bytes, including objects downloaded by Business. */
4
+ export declare function validateHtmlArtifactContent(context: ValidationContext, content: string | Uint8Array, displayPath?: string, profile?: ChannelRuleProfile): ValidationResult[];
3
5
  export declare function collectExternalResources(html: string): string[];
4
6
  export declare function collectLocalResourceReferences(html: string): string[];
5
7
  export declare function isAllowedExternalResource(url: string, allowedPatterns?: string[]): boolean;
@@ -3,31 +3,33 @@ import { getRulesForStage } from './profiles.js';
3
3
  const RESOURCE_ATTR_RE = /\b(?:src|href|data)\s*=\s*["']([^"']+)["']/gi;
4
4
  const CSS_URL_RE = /url\(\s*["']?([^"')]+)["']?\s*\)/gi;
5
5
  export async function validateHtmlArtifact(context, profile) {
6
- const rules = profile?.rules.filter((rule) => rule.stage === 'html-artifact')
7
- ?? getRulesForStage(context.channel, 'html-artifact');
6
+ if (context.htmlContent !== undefined) {
7
+ return validateHtmlArtifactContent(context, context.htmlContent, context.htmlPath, profile);
8
+ }
8
9
  if (!context.htmlPath) {
9
10
  return [missingHtmlResult(context.channel)];
10
11
  }
11
- let artifact;
12
12
  try {
13
- const [content, stat] = await Promise.all([
14
- fs.readFile(context.htmlPath, 'utf-8'),
15
- fs.stat(context.htmlPath),
16
- ]);
17
- artifact = {
18
- path: context.htmlPath,
19
- content,
20
- size: stat.size,
21
- };
13
+ const content = await fs.readFile(context.htmlPath);
14
+ return validateHtmlArtifactContent(context, content, context.htmlPath, profile);
22
15
  }
23
16
  catch (error) {
24
17
  return [missingHtmlResult(context.channel, context.htmlPath, error)];
25
18
  }
19
+ }
20
+ /** Validates the exact final bytes, including objects downloaded by Business. */
21
+ export function validateHtmlArtifactContent(context, content, displayPath = 'index.html', profile) {
22
+ const rules = profile?.rules.filter((rule) => rule.stage === 'html-artifact')
23
+ ?? getRulesForStage(context.channel, 'html-artifact');
24
+ const artifact = {
25
+ path: displayPath,
26
+ content: typeof content === 'string' ? content : Buffer.from(content).toString('utf-8'),
27
+ size: typeof content === 'string' ? Buffer.byteLength(content) : content.byteLength,
28
+ };
26
29
  const results = [];
27
30
  for (const rule of rules) {
28
- if (!rule.detectable || !rule.check) {
31
+ if (!rule.detectable || !rule.check)
29
32
  continue;
30
- }
31
33
  results.push(evaluateHtmlRule(rule, artifact));
32
34
  }
33
35
  return results;
@@ -1,2 +1,4 @@
1
+ import type { Platform } from '../types.js';
1
2
  import type { ChannelRuleProfile, ValidationContext, ValidationResult } from './types.js';
2
3
  export declare function validateDeliveryPackage(context: ValidationContext, profile?: ChannelRuleProfile): Promise<ValidationResult[]>;
4
+ export declare function validateSingleHtmlPackage(channel: Platform, bytes: Uint8Array, artifactName?: string): ValidationResult[];
@@ -6,7 +6,7 @@ import { directorySize, listDirectoryEntries } from './artifact.js';
6
6
  import { SimpleZipReader } from './zip-reader.js';
7
7
  const FIVE_MB = 5 * 1024 * 1024;
8
8
  export async function validateDeliveryPackage(context, profile = getChannelRuleProfile(context.channel)) {
9
- if (!context.packagePath) {
9
+ if (!context.packagePath && !context.packageBytes) {
10
10
  return [{
11
11
  ruleId: `${context.channel}.package.path.required`,
12
12
  channel: context.channel,
@@ -19,9 +19,10 @@ export async function validateDeliveryPackage(context, profile = getChannelRuleP
19
19
  confidence: 'high',
20
20
  }];
21
21
  }
22
+ const packagePath = context.packagePath ?? 'delivery.zip';
22
23
  let inventory;
23
24
  try {
24
- inventory = await readPackageInventory(context.packagePath);
25
+ inventory = await readPackageInventory(packagePath, context.packageBytes);
25
26
  }
26
27
  catch (error) {
27
28
  return [{
@@ -30,9 +31,9 @@ export async function validateDeliveryPackage(context, profile = getChannelRuleP
30
31
  stage: 'delivery-package',
31
32
  severity: 'error',
32
33
  status: 'fail',
33
- message: `Delivery package is not readable: ${context.packagePath}`,
34
+ message: `Delivery package is not readable: ${packagePath}`,
34
35
  recommendation: 'Verify the generated ZIP or delivery directory exists and is readable.',
35
- file: context.packagePath,
36
+ file: packagePath,
36
37
  evidence: error instanceof Error ? error.message : String(error),
37
38
  owner: 'playcraft-delivery',
38
39
  confidence: 'high',
@@ -63,18 +64,26 @@ export async function validateDeliveryPackage(context, profile = getChannelRuleP
63
64
  }
64
65
  return results;
65
66
  }
66
- async function readPackageInventory(packagePath) {
67
- const stat = await fs.stat(packagePath);
68
- if (stat.isDirectory()) {
69
- const entries = await listDirectoryEntries(packagePath);
70
- return {
71
- packagePath,
72
- entries,
73
- readText: (entryPath) => readTextFromDirectorySyncUnsupported(packagePath, entryPath),
74
- size: await directorySize(packagePath),
75
- };
67
+ export function validateSingleHtmlPackage(channel, bytes, artifactName = 'index.html') {
68
+ return [
69
+ boolResult(channel, 'package.size.max-5mb', bytes.byteLength <= FIVE_MB, 'Delivery HTML should be smaller than 5 MB.', 'Reduce artifact size or inline assets more aggressively.', artifactName, `actual=${bytes.byteLength}, limit=${FIVE_MB}`),
70
+ boolResult(channel, 'package.single-html.required', bytes.byteLength > 0 && artifactName.toLowerCase().endsWith('.html'), 'Delivery must be one nonempty HTML file.', 'Provide exactly one nonempty HTML artifact.', artifactName),
71
+ ];
72
+ }
73
+ async function readPackageInventory(packagePath, packageBytes) {
74
+ if (packageBytes === undefined) {
75
+ const stat = await fs.stat(packagePath);
76
+ if (stat.isDirectory()) {
77
+ const entries = await listDirectoryEntries(packagePath);
78
+ return {
79
+ packagePath,
80
+ entries,
81
+ readText: (entryPath) => readTextFromDirectorySyncUnsupported(packagePath, entryPath),
82
+ size: await directorySize(packagePath),
83
+ };
84
+ }
76
85
  }
77
- const buffer = await fs.readFile(packagePath);
86
+ const buffer = packageBytes === undefined ? await fs.readFile(packagePath) : Buffer.from(packageBytes);
78
87
  const zip = new SimpleZipReader(buffer);
79
88
  return {
80
89
  packagePath,
@@ -1,5 +1,17 @@
1
- import type { Platform } from '../types.js';
1
+ import type { OutputFormat, Platform } from '../types.js';
2
2
  import type { ChannelRuleProfile, ValidationRule, ValidationStage } from './types.js';
3
3
  export declare const CHANNEL_RULE_PROFILES: Record<Platform, ChannelRuleProfile>;
4
4
  export declare function getChannelRuleProfile(channel: Platform): ChannelRuleProfile;
5
5
  export declare function getRulesForStage(channel: Platform, stage: ValidationStage): ValidationRule[];
6
+ export declare const CHANNEL_RULES_VERSION = "channel-rules-v1";
7
+ export type ChannelCapability = {
8
+ channel: Platform;
9
+ channelRulesVersion: typeof CHANNEL_RULES_VERSION;
10
+ supportedFormats: OutputFormat[];
11
+ packageStrategy: 'single-html' | 'normalized-zip' | 'format-dependent';
12
+ rootEntryRequired: boolean;
13
+ maxFiles?: number;
14
+ maxArtifactBytes?: number;
15
+ };
16
+ /** Versioned delivery facts shared by Runner packaging and Business revalidation. */
17
+ export declare function getChannelCapability(channel: Platform): ChannelCapability;
@@ -219,3 +219,30 @@ export function getChannelRuleProfile(channel) {
219
219
  export function getRulesForStage(channel, stage) {
220
220
  return getChannelRuleProfile(channel).rules.filter((rule) => rule.stage === stage);
221
221
  }
222
+ export const CHANNEL_RULES_VERSION = 'channel-rules-v1';
223
+ /** Versioned delivery facts shared by Runner packaging and Business revalidation. */
224
+ export function getChannelCapability(channel) {
225
+ const profile = getChannelRuleProfile(channel);
226
+ const supportsZip = profile.deliveryMode === 'zip' ||
227
+ profile.deliveryMode === 'html-backed-zip' ||
228
+ profile.deliveryMode === 'mixed';
229
+ const supportsHtml = profile.deliveryMode === 'single-html' || profile.deliveryMode === 'mixed';
230
+ return {
231
+ channel,
232
+ channelRulesVersion: CHANNEL_RULES_VERSION,
233
+ supportedFormats: [
234
+ ...(supportsHtml ? ['html'] : []),
235
+ ...(supportsZip ? ['zip'] : []),
236
+ ],
237
+ packageStrategy: profile.deliveryMode === 'mixed'
238
+ ? 'format-dependent'
239
+ : profile.deliveryMode === 'single-html'
240
+ ? 'single-html'
241
+ : 'normalized-zip',
242
+ rootEntryRequired: supportsZip,
243
+ ...(channel === 'google' ? { maxFiles: 512 } : {}),
244
+ ...(profile.rules.some((rule) => rule.check?.kind === 'max-size')
245
+ ? { maxArtifactBytes: FIVE_MB }
246
+ : {}),
247
+ };
248
+ }
@@ -59,7 +59,12 @@ export interface ValidationContext {
59
59
  buildTool?: BuildTool;
60
60
  buildChain: BuildChain;
61
61
  htmlPath?: string;
62
+ /** Final HTML bytes; lets Business validate an uploaded object without staging it. */
63
+ htmlContent?: string | Uint8Array;
62
64
  packagePath?: string;
65
+ /** Final ZIP bytes; no filesystem extraction is required. */
66
+ packageBytes?: Uint8Array;
67
+ format?: OutputFormat;
63
68
  outputDir?: string;
64
69
  sourceGlobs?: string[];
65
70
  metadata?: Record<string, unknown>;
@@ -1,7 +1,17 @@
1
- import type { Platform } from '../types.js';
1
+ import type { OutputFormat, Platform } from '../types.js';
2
2
  import type { ExternalChecklistItem, ManualChecklistItem, QaStageId, QaStageReport, ValidationContext, ValidationReport, ValidationResult, ValidationStage, ValidationSummary } from './types.js';
3
3
  export declare const VALIDATION_REPORT_VERSION = "0.1.0";
4
4
  export declare function runPlayableValidation(context: ValidationContext, stages?: ValidationStage[]): Promise<ValidationReport>;
5
+ export type ChannelArtifactValidationOptions = {
6
+ channel: Platform;
7
+ format: OutputFormat;
8
+ bytes: Uint8Array;
9
+ htmlBytes?: Uint8Array;
10
+ artifactName?: string;
11
+ projectRoot?: string;
12
+ };
13
+ /** Revalidates final HTML and ZIP bytes without trusting a Runner-side report or staging files. */
14
+ export declare function runChannelArtifactValidation(options: ChannelArtifactValidationOptions): Promise<ValidationReport>;
5
15
  export declare function runPlayableSourceValidationForChannels(context: Omit<ValidationContext, 'channel'>, channels: Platform[]): Promise<ValidationReport>;
6
16
  export declare function summarize(results: ValidationResult[], manualChecklist: ManualChecklistItem[], externalChecklist: ExternalChecklistItem[]): ValidationSummary;
7
17
  /** Builds the report of a QA stage that ran. */
@@ -1,12 +1,13 @@
1
1
  import { getChannelRuleProfile } from './profiles.js';
2
2
  import { validateHtmlArtifact } from './html-validator.js';
3
- import { validateDeliveryPackage } from './package-validator.js';
3
+ import { validateDeliveryPackage, validateSingleHtmlPackage } from './package-validator.js';
4
4
  import { scanSourceForChannels, scanSourceForCompliance } from './source-scanner.js';
5
+ import { SimpleZipReader } from './zip-reader.js';
5
6
  export const VALIDATION_REPORT_VERSION = '0.1.0';
6
7
  export async function runPlayableValidation(context, stages) {
7
8
  const profile = getChannelRuleProfile(context.channel);
8
9
  const defaultStages = [...profile.defaultStages];
9
- if (context.packagePath && profile.optionalStages.includes('delivery-package')) {
10
+ if ((context.packagePath || context.packageBytes) && profile.optionalStages.includes('delivery-package')) {
10
11
  defaultStages.push('delivery-package');
11
12
  }
12
13
  const enabledStages = new Set(stages ?? defaultStages);
@@ -32,6 +33,40 @@ export async function runPlayableValidation(context, stages) {
32
33
  externalChecklist,
33
34
  };
34
35
  }
36
+ /** Revalidates final HTML and ZIP bytes without trusting a Runner-side report or staging files. */
37
+ export async function runChannelArtifactValidation(options) {
38
+ const artifactName = options.artifactName ?? (options.format === 'html' ? 'index.html' : 'delivery.zip');
39
+ let htmlBytes = options.htmlBytes ?? (options.format === 'html' ? options.bytes : undefined);
40
+ if (!htmlBytes && options.format === 'zip') {
41
+ try {
42
+ htmlBytes = new SimpleZipReader(Buffer.from(options.bytes)).readEntry('index.html') ?? undefined;
43
+ }
44
+ catch {
45
+ // The package validator returns the structured readable/path failure below.
46
+ }
47
+ }
48
+ const report = await runPlayableValidation({
49
+ projectRoot: options.projectRoot ?? '.',
50
+ channel: options.channel,
51
+ engine: 'unknown',
52
+ buildChain: 'generic',
53
+ format: options.format,
54
+ htmlPath: htmlBytes ? artifactName : undefined,
55
+ htmlContent: htmlBytes,
56
+ packagePath: options.format === 'zip' ? artifactName : undefined,
57
+ packageBytes: options.format === 'zip' ? options.bytes : undefined,
58
+ }, [
59
+ 'html-artifact',
60
+ ...(options.format === 'zip' ? ['delivery-package'] : []),
61
+ 'runtime-manual',
62
+ 'external-validator',
63
+ ]);
64
+ if (options.format === 'html') {
65
+ report.results.push(...validateSingleHtmlPackage(options.channel, options.bytes, artifactName));
66
+ report.summary = summarize(report.results, report.manualChecklist, report.externalChecklist);
67
+ }
68
+ return report;
69
+ }
35
70
  export async function runPlayableSourceValidationForChannels(context, channels) {
36
71
  const uniqueChannels = Array.from(new Set(channels));
37
72
  const results = await scanSourceForChannels(context, uniqueChannels);
@@ -4,15 +4,21 @@ export interface ZipEntryInfo {
4
4
  uncompressedSize: number;
5
5
  compressionMethod: number;
6
6
  isDirectory: boolean;
7
+ externalAttributes?: number;
8
+ creatorOs?: number;
9
+ encrypted?: boolean;
10
+ crc32?: number;
7
11
  }
12
+ /** Bounded ZIP reader used for both local reports and untrusted uploaded bytes. */
8
13
  export declare class SimpleZipReader {
9
14
  private readonly buffer;
10
15
  private entriesCache?;
11
16
  constructor(buffer: Buffer);
12
17
  listEntries(): ZipEntryInfo[];
13
18
  readEntryText(entryPath: string): string | null;
14
- readEntryBuffer(entryPath: string): Buffer | null;
19
+ readEntry(entryPath: string): Buffer | null;
15
20
  private readCentralDirectory;
16
21
  private readEntryData;
17
22
  private findEndOfCentralDirectory;
23
+ private requireRange;
18
24
  }