@playcraft/build 0.2.19-test-a → 0.2.20

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 (123) hide show
  1. package/dist/base-builder.js +2 -42
  2. package/dist/engines/engine-detector.js +0 -4
  3. package/dist/engines/generic-adapter.js +19 -14
  4. package/dist/engines/playable-scripts-adapter.js +5 -2
  5. package/dist/index.d.ts +4 -21
  6. package/dist/index.js +2 -12
  7. package/dist/platforms/adikteev.js +0 -1
  8. package/dist/platforms/applovin.js +0 -1
  9. package/dist/platforms/base.d.ts +0 -4
  10. package/dist/platforms/base.js +6 -25
  11. package/dist/platforms/bigo.js +0 -1
  12. package/dist/platforms/facebook.js +0 -1
  13. package/dist/platforms/google.js +0 -1
  14. package/dist/platforms/inmobi.js +0 -1
  15. package/dist/platforms/ironsource.js +0 -1
  16. package/dist/platforms/liftoff.js +0 -1
  17. package/dist/platforms/mintegral.js +0 -1
  18. package/dist/platforms/moloco.js +0 -1
  19. package/dist/platforms/playcraft.js +0 -1
  20. package/dist/platforms/remerge.js +0 -1
  21. package/dist/platforms/snapchat.js +0 -1
  22. package/dist/platforms/tiktok.js +0 -1
  23. package/dist/platforms/unity.js +0 -1
  24. package/dist/types.d.ts +2 -12
  25. package/dist/validation/html-validator.d.ts +0 -5
  26. package/dist/validation/html-validator.js +17 -19
  27. package/dist/validation/index.d.ts +0 -5
  28. package/dist/validation/index.js +0 -5
  29. package/dist/validation/package-validator.d.ts +0 -2
  30. package/dist/validation/package-validator.js +64 -25
  31. package/dist/validation/profiles.d.ts +1 -13
  32. package/dist/validation/profiles.js +0 -27
  33. package/dist/validation/source-scanner.d.ts +0 -11
  34. package/dist/validation/source-scanner.js +2 -32
  35. package/dist/validation/types.d.ts +2 -201
  36. package/dist/validation/types.js +1 -1
  37. package/dist/validation/validation-runner.d.ts +2 -22
  38. package/dist/validation/validation-runner.js +3 -64
  39. package/dist/validation/zip-reader.d.ts +0 -7
  40. package/dist/validation/zip-reader.js +26 -159
  41. package/dist/vite/config-builder-generic.d.ts +1 -3
  42. package/dist/vite/config-builder-generic.js +7 -9
  43. package/dist/vite/config-builder.js +1 -1
  44. package/dist/vite/plugin-platform.js +30 -16
  45. package/dist/vite/plugin-source-builder.d.ts +14 -2
  46. package/dist/vite/plugin-source-builder.js +997 -61
  47. package/dist/vite-builder.d.ts +5 -4
  48. package/dist/vite-builder.js +34 -33
  49. package/package.json +4 -30
  50. package/templates/patches/one-page-mraid-resize-canvas.js +2 -0
  51. package/dist/audio-source-files.d.ts +0 -5
  52. package/dist/audio-source-files.js +0 -135
  53. package/dist/delivery/agent-build-runner.d.ts +0 -44
  54. package/dist/delivery/agent-build-runner.js +0 -365
  55. package/dist/delivery/agent-build-source.d.ts +0 -8
  56. package/dist/delivery/agent-build-source.js +0 -25
  57. package/dist/delivery/artifact-descriptor.d.ts +0 -31
  58. package/dist/delivery/artifact-descriptor.js +0 -237
  59. package/dist/delivery/artifact-package.d.ts +0 -43
  60. package/dist/delivery/artifact-package.js +0 -283
  61. package/dist/delivery/build-plan.d.ts +0 -4
  62. package/dist/delivery/build-plan.js +0 -189
  63. package/dist/delivery/build-plan.types.d.ts +0 -51
  64. package/dist/delivery/build-plan.types.js +0 -1
  65. package/dist/delivery/command-isolation.d.ts +0 -21
  66. package/dist/delivery/command-isolation.js +0 -327
  67. package/dist/delivery/commands.d.ts +0 -5
  68. package/dist/delivery/commands.js +0 -146
  69. package/dist/delivery/files.d.ts +0 -9
  70. package/dist/delivery/files.js +0 -144
  71. package/dist/delivery/git-source-fingerprint.d.ts +0 -2
  72. package/dist/delivery/git-source-fingerprint.js +0 -58
  73. package/dist/delivery/isolated-source.d.ts +0 -5
  74. package/dist/delivery/isolated-source.js +0 -148
  75. package/dist/delivery/output-publication.d.ts +0 -21
  76. package/dist/delivery/output-publication.js +0 -444
  77. package/dist/delivery/project-delivery.d.ts +0 -6
  78. package/dist/delivery/project-delivery.js +0 -287
  79. package/dist/delivery/recipe-build-plan.d.ts +0 -4
  80. package/dist/delivery/recipe-build-plan.js +0 -53
  81. package/dist/delivery/recipe.d.ts +0 -20
  82. package/dist/delivery/recipe.js +0 -211
  83. package/dist/delivery/safe-path.d.ts +0 -2
  84. package/dist/delivery/safe-path.js +0 -18
  85. package/dist/delivery/types.d.ts +0 -81
  86. package/dist/delivery/types.js +0 -1
  87. package/dist/production-animation-presence.d.ts +0 -2
  88. package/dist/production-animation-presence.js +0 -146
  89. package/dist/production-inputs.d.ts +0 -30
  90. package/dist/production-inputs.js +0 -262
  91. package/dist/production-source-paths.d.ts +0 -5
  92. package/dist/production-source-paths.js +0 -27
  93. package/dist/redirect-policy.d.ts +0 -23
  94. package/dist/redirect-policy.js +0 -25
  95. package/dist/validation/artifact-qa.d.ts +0 -36
  96. package/dist/validation/artifact-qa.js +0 -263
  97. package/dist/validation/artifact-rules.d.ts +0 -39
  98. package/dist/validation/artifact-rules.js +0 -451
  99. package/dist/validation/artifact.d.ts +0 -14
  100. package/dist/validation/artifact.js +0 -188
  101. package/dist/validation/playwright-driver.d.ts +0 -37
  102. package/dist/validation/playwright-driver.js +0 -302
  103. package/dist/validation/runtime-cover.d.ts +0 -32
  104. package/dist/validation/runtime-cover.js +0 -120
  105. package/dist/validation/runtime-load.d.ts +0 -141
  106. package/dist/validation/runtime-load.js +0 -812
  107. package/dist/vite/source-builder-asset-paths.d.ts +0 -25
  108. package/dist/vite/source-builder-asset-paths.js +0 -154
  109. package/dist/vite/source-builder-esm.d.ts +0 -7
  110. package/dist/vite/source-builder-esm.js +0 -877
  111. package/dist/vite/source-builder-types.d.ts +0 -14
  112. package/dist/vite/source-builder-types.js +0 -1
  113. package/dist/vite/workspace.d.ts +0 -6
  114. package/dist/vite/workspace.js +0 -41
  115. package/dist/workspace-css-imports.d.ts +0 -2
  116. package/dist/workspace-css-imports.js +0 -139
  117. package/dist/workspace-model-source.d.ts +0 -14
  118. package/dist/workspace-model-source.js +0 -184
  119. package/dist/workspace-public-imports.d.ts +0 -11
  120. package/dist/workspace-public-imports.js +0 -232
  121. package/dist/workspace-public-source.d.ts +0 -15
  122. package/dist/workspace-public-source.js +0 -564
  123. package/templates/patches/playcraft-redirect-policy.js +0 -115
@@ -1,365 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
- import path from 'node:path';
5
- import { createRecipeBuildPlan } from './recipe-build-plan.js';
6
- import { parseBuildPlan, buildPlanDigest } from './build-plan.js';
7
- import { wrapDeliveryCommand } from './command-isolation.js';
8
- import { runDeliveryCommand } from './commands.js';
9
- import { safeExistingPath } from './safe-path.js';
10
- import { readAgentBuildSourceIdentity } from './agent-build-source.js';
11
- import { packageChannelArtifact, describeChannelArtifact, readArtifactDirectory } from './artifact-package.js';
12
- import { deliveryContext, ProjectDeliveryError, readProjectDeliveryRecipe, recipeDigest } from './recipe.js';
13
- export const AGENT_BUILD_RUNNER_VERSION = 'agent-build-runner-v1';
14
- export class AgentBuildRunnerError extends Error {
15
- constructor(code, stage, message, retryable = false) {
16
- super(message);
17
- this.code = code;
18
- this.stage = stage;
19
- this.retryable = retryable;
20
- this.name = 'AgentBuildRunnerError';
21
- }
22
- }
23
- function digest(value) {
24
- return createHash('sha256').update(JSON.stringify(value)).digest('hex');
25
- }
26
- function assertRequest(request) {
27
- if (request.version !== 1 ||
28
- !/^[a-f0-9]{64}$/.test(request.inputHash) ||
29
- !/^[a-f0-9]{64}$/.test(request.bindingHash) ||
30
- !/^[a-f0-9]{40,64}$/.test(request.commitHash) ||
31
- !/^[a-f0-9]{64}$/.test(request.recipeDigest) ||
32
- !/^[a-f0-9]{64}$/.test(request.fingerprint) ||
33
- !path.isAbsolute(request.projectRoot) ||
34
- !path.isAbsolute(request.attemptRoot)) {
35
- throw new AgentBuildRunnerError('agent_build_runner_request_invalid', 'environment_preflight', 'Invalid Runner request');
36
- }
37
- }
38
- function workRoot(request) {
39
- return path.join(request.attemptRoot, 'work');
40
- }
41
- function sourceRoot(request) {
42
- return path.join(workRoot(request), 'source');
43
- }
44
- function isolation(request) {
45
- return { projectRoot: request.projectRoot, isolatedRoot: workRoot(request) };
46
- }
47
- async function execute(argv, cwd, timeoutMs = 60000) {
48
- return new Promise((resolve, reject) => {
49
- const child = spawn(argv[0], argv.slice(1), {
50
- cwd,
51
- shell: false,
52
- detached: process.platform !== 'win32',
53
- env: {
54
- PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin',
55
- HOME: cwd,
56
- GIT_CONFIG_GLOBAL: '/dev/null',
57
- GIT_CONFIG_NOSYSTEM: '1',
58
- GIT_OPTIONAL_LOCKS: '0',
59
- GIT_TERMINAL_PROMPT: '0',
60
- CI: 'true',
61
- },
62
- stdio: ['ignore', 'pipe', 'pipe'],
63
- });
64
- let stdout = '';
65
- let stderr = '';
66
- const collect = (target) => (chunk) => {
67
- if (target === 'stdout')
68
- stdout = (stdout + chunk.toString()).slice(-16384);
69
- else
70
- stderr = (stderr + chunk.toString()).slice(-4000);
71
- };
72
- child.stdout.on('data', collect('stdout'));
73
- child.stderr.on('data', collect('stderr'));
74
- const stop = () => {
75
- try {
76
- if (process.platform !== 'win32' && child.pid)
77
- process.kill(-child.pid, 'SIGTERM');
78
- else
79
- child.kill('SIGTERM');
80
- }
81
- catch {
82
- // The process may already be gone.
83
- }
84
- };
85
- const timer = setTimeout(stop, timeoutMs);
86
- child.once('error', (error) => {
87
- clearTimeout(timer);
88
- reject(error);
89
- });
90
- child.once('close', (code, signal) => {
91
- clearTimeout(timer);
92
- if (code === 0)
93
- resolve(stdout);
94
- else
95
- reject(new AgentBuildRunnerError('source_snapshot_failed', 'source_snapshot', `Controlled Git command failed (${code ?? signal}): ${stderr}`));
96
- });
97
- });
98
- }
99
- async function exportCommit(request) {
100
- const git = [
101
- '-c', 'core.hooksPath=/dev/null',
102
- '-c', 'core.fsmonitor=false',
103
- '-C', request.projectRoot,
104
- ];
105
- const environment = {
106
- PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin',
107
- HOME: workRoot(request),
108
- GIT_CONFIG_GLOBAL: '/dev/null',
109
- GIT_CONFIG_NOSYSTEM: '1',
110
- GIT_OPTIONAL_LOCKS: '0',
111
- GIT_TERMINAL_PROMPT: '0',
112
- };
113
- const head = async () => (await execute(['git', ...git, 'rev-parse', '--verify', 'HEAD^{commit}'], request.projectRoot)).trim();
114
- if (await head() !== request.commitHash) {
115
- throw new AgentBuildRunnerError('build_source_changed', 'source_snapshot', 'Sandbox HEAD differs from the reserved remote commit');
116
- }
117
- const source = sourceRoot(request);
118
- await mkdir(source, { recursive: false, mode: 0o700 });
119
- await new Promise((resolve, reject) => {
120
- const archive = spawn('git', [...git, 'archive', '--format=tar', request.commitHash], {
121
- cwd: request.projectRoot,
122
- shell: false,
123
- env: environment,
124
- stdio: ['ignore', 'pipe', 'pipe'],
125
- });
126
- const extract = spawn('tar', ['-x', '-C', source, '--no-same-owner', '--no-same-permissions'], {
127
- cwd: workRoot(request),
128
- shell: false,
129
- env: environment,
130
- stdio: ['pipe', 'ignore', 'pipe'],
131
- });
132
- let errors = '';
133
- let archiveCode = null;
134
- let extractCode = null;
135
- archive.stderr.on('data', (chunk) => { errors = `${errors}${chunk}`.slice(-4000); });
136
- extract.stderr.on('data', (chunk) => { errors = `${errors}${chunk}`.slice(-4000); });
137
- archive.stdout.pipe(extract.stdin);
138
- const done = () => {
139
- if (archiveCode === null || extractCode === null)
140
- return;
141
- if (archiveCode === 0 && extractCode === 0)
142
- resolve();
143
- else
144
- reject(new AgentBuildRunnerError('source_snapshot_failed', 'source_snapshot', `Could not export the reserved commit: ${errors}`));
145
- };
146
- archive.once('error', reject);
147
- extract.once('error', reject);
148
- archive.once('close', (code) => { archiveCode = code; done(); });
149
- extract.once('close', (code) => { extractCode = code; done(); });
150
- });
151
- if (await head() !== request.commitHash) {
152
- throw new AgentBuildRunnerError('build_source_changed', 'source_snapshot', 'Sandbox HEAD changed while exporting the reserved commit');
153
- }
154
- }
155
- async function packageManager(root) {
156
- const candidates = [
157
- ['pnpm', ['pnpm-lock.yaml']],
158
- ['npm', ['package-lock.json', 'npm-shrinkwrap.json']],
159
- ['yarn', ['yarn.lock']],
160
- ['bun', ['bun.lock', 'bun.lockb']],
161
- ];
162
- const found = [];
163
- for (const [name, files] of candidates) {
164
- for (const lockfile of files) {
165
- try {
166
- const bytes = await readFile(path.join(root, lockfile));
167
- found.push({ name, lockfile, lockDigest: createHash('sha256').update(bytes).digest('hex') });
168
- break;
169
- }
170
- catch (error) {
171
- if (error.code !== 'ENOENT')
172
- throw error;
173
- }
174
- }
175
- }
176
- if (found.length !== 1) {
177
- throw new AgentBuildRunnerError('environment_unsupported', 'environment_preflight', 'Exactly one supported package-manager lockfile is required');
178
- }
179
- return found[0];
180
- }
181
- async function isolatedVersion(executable, request) {
182
- const argv = await wrapDeliveryCommand([executable, '--version'], isolation(request));
183
- return new Promise((resolve, reject) => {
184
- const child = spawn(argv[0], argv.slice(1), {
185
- cwd: sourceRoot(request),
186
- shell: false,
187
- env: { PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin', HOME: workRoot(request), CI: 'true' },
188
- stdio: ['ignore', 'pipe', 'pipe'],
189
- });
190
- let stdout = '';
191
- let stderr = '';
192
- child.stdout.on('data', (chunk) => { stdout = `${stdout}${chunk}`.slice(-2000); });
193
- child.stderr.on('data', (chunk) => { stderr = `${stderr}${chunk}`.slice(-2000); });
194
- const timer = setTimeout(() => child.kill('SIGTERM'), 20000);
195
- child.once('error', reject);
196
- child.once('close', (code) => {
197
- clearTimeout(timer);
198
- if (code === 0 && stdout.trim())
199
- resolve(stdout.trim());
200
- else
201
- reject(new AgentBuildRunnerError('delivery_isolation_unavailable', 'environment_preflight', `Managed isolation preflight failed: ${stderr || `exit ${code}`}`));
202
- });
203
- });
204
- }
205
- async function reportProgress(request, stage) {
206
- const target = path.join(request.attemptRoot, 'progress.json');
207
- const temporary = `${target}.${process.pid}.tmp`;
208
- await writeFile(temporary, JSON.stringify({ fingerprint: request.fingerprint, stage }), { mode: 0o600, flag: 'wx' });
209
- await rename(temporary, target);
210
- }
211
- async function sourceIdentityAt(root, recipe, stage, legacyOutputDirectory = recipe.output.directory) {
212
- try {
213
- return await readAgentBuildSourceIdentity(root, recipe, legacyOutputDirectory);
214
- }
215
- catch (error) {
216
- if (error instanceof ProjectDeliveryError)
217
- throw new AgentBuildRunnerError(error.code, stage, error.message);
218
- throw new AgentBuildRunnerError('source_snapshot_failed', stage, 'The source input closure could not be verified');
219
- }
220
- }
221
- async function plan(request) {
222
- await mkdir(workRoot(request), { recursive: false, mode: 0o700 });
223
- await exportCommit(request);
224
- const source = sourceRoot(request);
225
- const recipe = await readProjectDeliveryRecipe(source);
226
- if (!recipe || recipeDigest(recipe) !== request.recipeDigest) {
227
- throw new AgentBuildRunnerError('delivery_recipe_digest_mismatch', 'source_snapshot', 'The exported recipe differs from the Business reservation');
228
- }
229
- const sourceIdentity = await sourceIdentityAt(source, recipe, 'source_snapshot');
230
- const manager = await packageManager(source);
231
- const value = createRecipeBuildPlan(recipe, {
232
- commitHash: request.commitHash,
233
- ...sourceIdentity,
234
- channel: request.channel,
235
- format: request.format,
236
- packageManager: manager.name,
237
- });
238
- await reportProgress(request, 'environment_preflight');
239
- const managerVersion = await isolatedVersion(manager.name, request);
240
- await isolatedVersion(process.execPath, request);
241
- const environmentDigest = digest({
242
- version: 1,
243
- runner: AGENT_BUILD_RUNNER_VERSION,
244
- node: process.version,
245
- packageManager: manager.name,
246
- packageManagerVersion: managerVersion,
247
- platform: process.platform,
248
- arch: process.arch,
249
- lockfile: manager.lockfile,
250
- lockDigest: manager.lockDigest,
251
- planDigest: buildPlanDigest(value),
252
- });
253
- return { outcome: 'settled', status: 'success', fingerprint: request.fingerprint, phase: 'plan', plan: value, environmentDigest };
254
- }
255
- function installCommand(manager) {
256
- if (manager === 'pnpm')
257
- return ['pnpm', 'install', '--frozen-lockfile'];
258
- if (manager === 'npm')
259
- return ['npm', 'ci'];
260
- if (manager === 'yarn')
261
- return ['yarn', 'install', '--frozen-lockfile'];
262
- return ['bun', 'install', '--frozen-lockfile'];
263
- }
264
- async function build(request) {
265
- const plan = parseBuildPlan(request.plan);
266
- if (plan.source.commitHash !== request.commitHash ||
267
- plan.source.recipeDigest !== request.recipeDigest ||
268
- plan.target.channel !== request.channel ||
269
- plan.target.format !== request.format ||
270
- !request.environmentDigest) {
271
- throw new AgentBuildRunnerError('delivery_build_plan_invalid', 'preparing', 'The bound BuildPlan does not match this attempt');
272
- }
273
- const source = sourceRoot(request);
274
- const recipe = await readProjectDeliveryRecipe(source);
275
- if (!recipe || recipeDigest(recipe) !== request.recipeDigest) {
276
- throw new AgentBuildRunnerError('delivery_recipe_digest_mismatch', 'preparing', 'The source recipe changed after planning');
277
- }
278
- const context = deliveryContext(recipe, request);
279
- const current = await sourceIdentityAt(source, recipe, 'preparing', context.outputDirectory);
280
- if (current.sourceFingerprint !== plan.source.sourceFingerprint || current.sourceRulesVersion !== plan.source.sourceRulesVersion) {
281
- throw new AgentBuildRunnerError('build_source_changed', 'preparing', 'The source snapshot changed after planning');
282
- }
283
- const controller = new AbortController();
284
- const options = { channel: request.channel, format: request.format, signal: controller.signal };
285
- const isolated = isolation(request);
286
- await reportProgress(request, 'preparing');
287
- await runDeliveryCommand(source, { argv: installCommand(plan.environment.packageManager), timeoutMs: plan.environment.maxDurationMs }, context.replace, options, isolated);
288
- for (const executable of plan.environment.executables) {
289
- await runDeliveryCommand(source, { argv: [context.replace(executable), '--version'], timeoutMs: 20000 }, context.replace, options, isolated);
290
- }
291
- for (const command of plan.setup.prepareCommands) {
292
- await runDeliveryCommand(source, command, context.replace, options, isolated);
293
- }
294
- await reportProgress(request, 'compiling');
295
- if (plan.compile.command) {
296
- await runDeliveryCommand(source, plan.compile.command, context.replace, options, isolated);
297
- }
298
- const after = await sourceIdentityAt(source, recipe, 'compiling', context.outputDirectory);
299
- if (after.sourceFingerprint !== plan.source.sourceFingerprint || after.sourceRulesVersion !== plan.source.sourceRulesVersion) {
300
- throw new AgentBuildRunnerError('build_source_changed', 'compiling', 'Project commands modified undeclared source inputs');
301
- }
302
- await reportProgress(request, 'packaging');
303
- const output = await safeExistingPath(source, context.outputDirectory);
304
- const entry = await safeExistingPath(source, path.posix.join(context.outputDirectory, context.entry));
305
- const identity = {
306
- sourceFingerprint: plan.source.sourceFingerprint,
307
- recipeDigest: plan.source.recipeDigest,
308
- environmentDigest: request.environmentDigest,
309
- channelRulesVersion: plan.delivery.channelRulesVersion,
310
- };
311
- let bytes;
312
- let descriptor;
313
- let artifactName;
314
- if (plan.compile.output.kind === 'web-bundle') {
315
- const files = await readArtifactDirectory(output, request.channel);
316
- const packaged = await packageChannelArtifact({ channel: request.channel, format: request.format, files, ...identity });
317
- bytes = packaged.bytes;
318
- descriptor = packaged.descriptor;
319
- artifactName = request.format === 'html' ? files[0].path : 'index.html';
320
- }
321
- else {
322
- bytes = await readFile(entry);
323
- artifactName = request.format === 'html' ? path.basename(entry) : 'index.html';
324
- descriptor = await describeChannelArtifact({
325
- channel: request.channel,
326
- format: request.format,
327
- bytes,
328
- artifactName,
329
- ...identity,
330
- });
331
- }
332
- await reportProgress(request, 'validating');
333
- const artifact = path.join(request.attemptRoot, `artifact.${request.format}`);
334
- const descriptorPath = path.join(request.attemptRoot, 'descriptor.json');
335
- const temporaryArtifact = `${artifact}.${process.pid}.tmp`;
336
- const temporaryDescriptor = `${descriptorPath}.${process.pid}.tmp`;
337
- await writeFile(temporaryArtifact, bytes, { flag: 'wx', mode: 0o600 });
338
- await rename(temporaryArtifact, artifact);
339
- await writeFile(temporaryDescriptor, JSON.stringify(descriptor), { flag: 'wx', mode: 0o600 });
340
- await rename(temporaryDescriptor, descriptorPath);
341
- return { outcome: 'settled', status: 'success', fingerprint: request.fingerprint, phase: 'build', descriptor, artifactName };
342
- }
343
- export async function runAgentBuildRunner(request) {
344
- assertRequest(request);
345
- try {
346
- return request.phase === 'plan' ? await plan(request) : await build(request);
347
- }
348
- catch (error) {
349
- if (error instanceof AgentBuildRunnerError)
350
- throw error;
351
- if (error instanceof ProjectDeliveryError) {
352
- const stage = error.code === 'delivery_isolation_unavailable' ? 'environment_preflight'
353
- : request.phase === 'plan' ? 'source_snapshot'
354
- : error.code.startsWith('artifact_') ? 'validating' : 'compiling';
355
- throw new AgentBuildRunnerError(error.code, stage, error.message, false);
356
- }
357
- throw new AgentBuildRunnerError('agent_build_runner_failed', request.phase === 'plan' ? 'source_snapshot' : 'compiling', error instanceof Error ? error.message.slice(0, 2000) : 'Runner failed');
358
- }
359
- finally {
360
- await rm(path.join(request.attemptRoot, `progress.json.${process.pid}.tmp`), { force: true }).catch(() => undefined);
361
- }
362
- }
363
- export { parseBuildPlan } from './build-plan.js';
364
- export { parseArtifactDescriptor } from './artifact-descriptor.js';
365
- export { verifyChannelArtifactDescriptor } from './artifact-package.js';
@@ -1,8 +0,0 @@
1
- import type { AgentBuildSourceRulesVersion } from '@playcraft/common/cloud-workspace/runtime';
2
- import type { ProjectDeliveryRecipe } from './types.js';
3
- export type AgentBuildSourceIdentity = {
4
- sourceFingerprint: string;
5
- sourceRulesVersion: AgentBuildSourceRulesVersion;
6
- };
7
- /** Shares save/freeze/legacy delivery's exact production closure, never a fallback for invalid declarations. */
8
- export declare function readAgentBuildSourceIdentity(root: string, recipe: ProjectDeliveryRecipe, legacyOutputDirectory?: string): Promise<AgentBuildSourceIdentity>;
@@ -1,25 +0,0 @@
1
- import { deliveryProductionSourceSnapshot } from './files.js';
2
- import { deliveryGitSourceFingerprint } from './git-source-fingerprint.js';
3
- import { ProjectDeliveryError } from './recipe.js';
4
- /** Shares save/freeze/legacy delivery's exact production closure, never a fallback for invalid declarations. */
5
- export async function readAgentBuildSourceIdentity(root, recipe, legacyOutputDirectory = recipe.output.directory) {
6
- const production = await deliveryProductionSourceSnapshot(root, recipe.output.directory, undefined, recipe.generatedDirectories);
7
- if (production) {
8
- let sourceRulesVersion;
9
- switch (production.sourceRulesVersion) {
10
- case 1:
11
- sourceRulesVersion = 'production-v1';
12
- break;
13
- case 2:
14
- sourceRulesVersion = 'production-v2';
15
- break;
16
- default:
17
- throw new ProjectDeliveryError('delivery_source_rules_unsupported', 'Unsupported production source rules');
18
- }
19
- return { sourceFingerprint: production.fingerprint, sourceRulesVersion };
20
- }
21
- return {
22
- sourceFingerprint: await deliveryGitSourceFingerprint(root, legacyOutputDirectory, undefined, recipe.generatedDirectories),
23
- sourceRulesVersion: 'legacy-v1',
24
- };
25
- }
@@ -1,31 +0,0 @@
1
- import type { OutputFormat, Platform } from '../types.js';
2
- import type { ValidationReport } from '../validation/types.js';
3
- export type ArtifactFileDescriptor = {
4
- path: string;
5
- sizeBytes: number;
6
- sha256: string;
7
- };
8
- export type ArtifactDescriptor = {
9
- version: 1;
10
- channel: Platform;
11
- format: OutputFormat;
12
- artifactDigest: string;
13
- sizeBytes: number;
14
- contentMd5Base64: string;
15
- contentType: 'text/html; charset=utf-8' | 'application/zip';
16
- files: ArtifactFileDescriptor[];
17
- sourceFingerprint: string;
18
- recipeDigest: string;
19
- environmentDigest: string;
20
- channelRulesVersion: string;
21
- validation: ValidationReport;
22
- };
23
- export type ArtifactIdentity = Pick<ArtifactDescriptor, 'sourceFingerprint' | 'recipeDigest' | 'environmentDigest' | 'channelRulesVersion'>;
24
- export declare function parseArtifactDescriptor(value: unknown): ArtifactDescriptor;
25
- export declare function artifactBytesDigest(bytes: Uint8Array): {
26
- artifactDigest: string;
27
- sizeBytes: number;
28
- contentMd5Base64: string;
29
- };
30
- export declare function artifactFileDescriptor(path: string, bytes: Uint8Array): ArtifactFileDescriptor;
31
- export declare function assertArtifactDescriptorDigest(value: unknown, bytes: Uint8Array): ArtifactDescriptor;
@@ -1,237 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { CHANNEL_RULE_PROFILES } from '../validation/profiles.js';
3
- import { ProjectDeliveryError } from './recipe.js';
4
- const HASH = /^[a-f0-9]{64}$/;
5
- const STATUSES = ['pass', 'failed', 'warning', 'manual-required'];
6
- const RULE_STATUSES = ['pass', 'fail', 'warning', 'manual', 'external', 'not-applicable'];
7
- const STAGES = ['prebuild-source', 'base-output', 'html-artifact', 'delivery-package', 'runtime-manual', 'external-validator'];
8
- const SEVERITIES = ['error', 'warning', 'info'];
9
- const OWNERS = ['playcraft-build', 'playcraft-delivery', 'devkit', 'manual', 'external'];
10
- const CONFIDENCE = ['high', 'medium', 'low'];
11
- const CHAINS = ['generic', 'devkit', 'playcanvas-native'];
12
- function invalid(message, file) {
13
- throw new ProjectDeliveryError('artifact_descriptor_invalid', message, file);
14
- }
15
- function record(value, field) {
16
- if (!value || typeof value !== 'object' || Array.isArray(value))
17
- invalid(`${field} must be an object`);
18
- return value;
19
- }
20
- function exactKeys(value, expected, field) {
21
- const actual = Object.keys(value).sort();
22
- const sorted = [...expected].sort();
23
- if (actual.length !== sorted.length || actual.some((key, index) => key !== sorted[index])) {
24
- invalid(`${field} has missing or unsupported fields`);
25
- }
26
- }
27
- function allowedKeys(value, allowed, field) {
28
- if (Object.keys(value).some((key) => !allowed.includes(key)))
29
- invalid(`${field} has unsupported fields`);
30
- }
31
- function text(value, field, maximum = 8192) {
32
- if (typeof value !== 'string' || !value || value.length > maximum || value.includes('\0')) {
33
- invalid(`Invalid ${field}`);
34
- }
35
- return value;
36
- }
37
- function integer(value, field, maximum = Number.MAX_SAFE_INTEGER) {
38
- if (!Number.isSafeInteger(value) || Number(value) < 0 || Number(value) > maximum)
39
- invalid(`Invalid ${field}`);
40
- return Number(value);
41
- }
42
- function hash(value, field) {
43
- const result = text(value, field, 64);
44
- if (!HASH.test(result))
45
- invalid(`${field} must be a lowercase SHA-256 digest`);
46
- return result;
47
- }
48
- function choice(value, choices, field) {
49
- if (typeof value !== 'string' || !choices.includes(value))
50
- invalid(`Invalid ${field}`);
51
- return value;
52
- }
53
- function channel(value, allowCommon = false) {
54
- const result = text(value, 'channel', 64);
55
- if ((allowCommon && result === 'common') || Object.prototype.hasOwnProperty.call(CHANNEL_RULE_PROFILES, result)) {
56
- return result;
57
- }
58
- invalid('Invalid validation channel');
59
- }
60
- function artifactPath(value) {
61
- const result = text(value, 'files.path', 1024);
62
- if (result.includes('\\') ||
63
- result.startsWith('/') ||
64
- /^[A-Za-z]:/.test(result) ||
65
- result.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
66
- invalid('Artifact files must use normalized POSIX relative paths', result);
67
- }
68
- return result;
69
- }
70
- function parseFiles(value) {
71
- if (!Array.isArray(value) || value.length === 0 || value.length > 4096)
72
- invalid('Invalid files');
73
- const paths = new Set();
74
- const folded = new Set();
75
- let previous = '';
76
- const files = value.map((item, index) => {
77
- const input = record(item, `files[${index}]`);
78
- exactKeys(input, ['path', 'sizeBytes', 'sha256'], `files[${index}]`);
79
- const member = artifactPath(input.path);
80
- const caseFolded = member.normalize('NFC').toLowerCase();
81
- if (paths.has(member))
82
- invalid('Duplicate artifact file', member);
83
- if (folded.has(caseFolded))
84
- invalid('Case-conflicting artifact file', member);
85
- if (index > 0 && Buffer.compare(Buffer.from(previous), Buffer.from(member)) >= 0) {
86
- invalid('Artifact files must be sorted by UTF-8 path bytes');
87
- }
88
- paths.add(member);
89
- folded.add(caseFolded);
90
- previous = member;
91
- return {
92
- path: member,
93
- sizeBytes: integer(input.sizeBytes, `files[${index}].sizeBytes`, 64 * 1024 * 1024),
94
- sha256: hash(input.sha256, `files[${index}].sha256`),
95
- };
96
- });
97
- return files;
98
- }
99
- function parseResult(value, index) {
100
- const input = record(value, `validation.results[${index}]`);
101
- allowedKeys(input, ['ruleId', 'channel', 'stage', 'severity', 'status', 'message', 'recommendation', 'file', 'line', 'evidence', 'owner', 'confidence'], `validation.results[${index}]`);
102
- for (const key of ['ruleId', 'channel', 'stage', 'severity', 'status', 'message', 'recommendation', 'owner', 'confidence']) {
103
- if (input[key] === undefined)
104
- invalid(`Missing validation result ${key}`);
105
- }
106
- return {
107
- ruleId: text(input.ruleId, 'ruleId', 256),
108
- channel: channel(input.channel, true),
109
- stage: choice(input.stage, STAGES, 'stage'),
110
- severity: choice(input.severity, SEVERITIES, 'severity'),
111
- status: choice(input.status, RULE_STATUSES, 'status'),
112
- message: text(input.message, 'message'),
113
- recommendation: text(input.recommendation, 'recommendation'),
114
- ...(input.file !== undefined ? { file: text(input.file, 'file', 2048) } : {}),
115
- ...(input.line !== undefined ? { line: integer(input.line, 'line', 1000000000) } : {}),
116
- ...(input.evidence !== undefined ? { evidence: text(input.evidence, 'evidence') } : {}),
117
- owner: choice(input.owner, OWNERS, 'owner'),
118
- confidence: choice(input.confidence, CONFIDENCE, 'confidence'),
119
- };
120
- }
121
- function parseChecklist(value, field) {
122
- if (!Array.isArray(value) || value.length > 4096)
123
- invalid(`Invalid ${field}`);
124
- return value.map((item, index) => {
125
- const input = record(item, `${field}[${index}]`);
126
- exactKeys(input, ['ruleId', 'channel', 'stage', 'message', 'recommendation', 'owner'], `${field}[${index}]`);
127
- return {
128
- ruleId: text(input.ruleId, 'ruleId', 256),
129
- channel: channel(input.channel, true),
130
- stage: choice(input.stage, STAGES, 'stage'),
131
- message: text(input.message, 'message'),
132
- recommendation: text(input.recommendation, 'recommendation'),
133
- owner: choice(input.owner, OWNERS, 'owner'),
134
- };
135
- });
136
- }
137
- function parseValidation(value, expectedChannel) {
138
- const input = record(value, 'validation');
139
- exactKeys(input, ['version', 'channel', 'buildChain', 'summary', 'results', 'manualChecklist', 'externalChecklist'], 'validation');
140
- const actualChannel = channel(input.channel);
141
- if (actualChannel !== expectedChannel)
142
- invalid('Validation channel differs from artifact channel');
143
- if (!Array.isArray(input.results) || input.results.length > 4096)
144
- invalid('Invalid validation results');
145
- const results = input.results.map(parseResult);
146
- const manualChecklist = parseChecklist(input.manualChecklist, 'manualChecklist');
147
- const externalChecklist = parseChecklist(input.externalChecklist, 'externalChecklist');
148
- const summary = record(input.summary, 'validation.summary');
149
- exactKeys(summary, ['status', 'errorCount', 'warningCount', 'manualCount', 'externalCount'], 'validation.summary');
150
- const errorCount = results.filter((result) => result.status === 'fail').length;
151
- const warningCount = results.filter((result) => result.status === 'warning').length;
152
- const expectedStatus = errorCount > 0
153
- ? 'failed'
154
- : warningCount > 0
155
- ? 'warning'
156
- : manualChecklist.length > 0 || externalChecklist.length > 0
157
- ? 'manual-required'
158
- : 'pass';
159
- if (choice(summary.status, STATUSES, 'summary.status') !== expectedStatus ||
160
- integer(summary.errorCount, 'summary.errorCount', 4096) !== errorCount ||
161
- integer(summary.warningCount, 'summary.warningCount', 4096) !== warningCount ||
162
- integer(summary.manualCount, 'summary.manualCount', 4096) !== manualChecklist.length ||
163
- integer(summary.externalCount, 'summary.externalCount', 4096) !== externalChecklist.length) {
164
- invalid('Validation summary does not match its findings');
165
- }
166
- return {
167
- version: text(input.version, 'validation.version', 64),
168
- channel: actualChannel,
169
- buildChain: choice(input.buildChain, CHAINS, 'validation.buildChain'),
170
- summary: {
171
- status: expectedStatus,
172
- errorCount,
173
- warningCount,
174
- manualCount: manualChecklist.length,
175
- externalCount: externalChecklist.length,
176
- },
177
- results,
178
- manualChecklist,
179
- externalChecklist,
180
- };
181
- }
182
- export function parseArtifactDescriptor(value) {
183
- const input = record(value, 'artifactDescriptor');
184
- exactKeys(input, ['version', 'channel', 'format', 'artifactDigest', 'sizeBytes', 'contentMd5Base64', 'contentType', 'files', 'sourceFingerprint', 'recipeDigest', 'environmentDigest', 'channelRulesVersion', 'validation'], 'artifactDescriptor');
185
- if (input.version !== 1)
186
- invalid('artifactDescriptor.version must be 1');
187
- const actualChannel = channel(input.channel);
188
- const format = choice(input.format, ['html', 'zip'], 'format');
189
- const files = parseFiles(input.files);
190
- if (format === 'html' && files.length !== 1)
191
- invalid('HTML descriptor must contain exactly one file');
192
- const md5 = text(input.contentMd5Base64, 'contentMd5Base64', 24);
193
- if (!/^[A-Za-z0-9+/]{22}==$/.test(md5))
194
- invalid('contentMd5Base64 must be a Base64 MD5');
195
- const expectedContentType = format === 'html' ? 'text/html; charset=utf-8' : 'application/zip';
196
- if (input.contentType !== expectedContentType)
197
- invalid('Invalid contentType');
198
- return {
199
- version: 1,
200
- channel: actualChannel,
201
- format,
202
- artifactDigest: hash(input.artifactDigest, 'artifactDigest'),
203
- sizeBytes: integer(input.sizeBytes, 'sizeBytes', 64 * 1024 * 1024),
204
- contentMd5Base64: md5,
205
- contentType: expectedContentType,
206
- files,
207
- sourceFingerprint: hash(input.sourceFingerprint, 'sourceFingerprint'),
208
- recipeDigest: hash(input.recipeDigest, 'recipeDigest'),
209
- environmentDigest: hash(input.environmentDigest, 'environmentDigest'),
210
- channelRulesVersion: text(input.channelRulesVersion, 'channelRulesVersion', 64),
211
- validation: parseValidation(input.validation, actualChannel),
212
- };
213
- }
214
- export function artifactBytesDigest(bytes) {
215
- return {
216
- artifactDigest: createHash('sha256').update(bytes).digest('hex'),
217
- sizeBytes: bytes.byteLength,
218
- contentMd5Base64: createHash('md5').update(bytes).digest('base64'),
219
- };
220
- }
221
- export function artifactFileDescriptor(path, bytes) {
222
- return {
223
- path,
224
- sizeBytes: bytes.byteLength,
225
- sha256: createHash('sha256').update(bytes).digest('hex'),
226
- };
227
- }
228
- export function assertArtifactDescriptorDigest(value, bytes) {
229
- const descriptor = parseArtifactDescriptor(value);
230
- const actual = artifactBytesDigest(bytes);
231
- if (descriptor.artifactDigest !== actual.artifactDigest ||
232
- descriptor.sizeBytes !== actual.sizeBytes ||
233
- descriptor.contentMd5Base64 !== actual.contentMd5Base64) {
234
- throw new ProjectDeliveryError('artifact_descriptor_mismatch', 'Artifact descriptor does not match the final bytes');
235
- }
236
- return descriptor;
237
- }