@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,58 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { readdir, readFile } from 'node:fs/promises';
3
- import path from 'node:path';
4
- import { ProjectDeliveryError } from './recipe.js';
5
- const SOURCE_IGNORED = new Set([
6
- '.git',
7
- 'node_modules',
8
- 'dist',
9
- '.cache',
10
- '.turbo',
11
- '.next',
12
- '.vite',
13
- '.parcel-cache',
14
- '.pnpm-store',
15
- '.eslintcache',
16
- '.DS_Store',
17
- '.playcraft',
18
- '.playcraft-temp',
19
- '.tmp',
20
- '.agents',
21
- '.claude',
22
- '.codex',
23
- '.playcraft.json',
24
- ]);
25
- /** The clean-Git fallback has no production audio or native package dependencies. */
26
- export async function deliveryGitSourceFingerprint(root, outputDirectory, receiptPath, generatedDirectories = []) {
27
- const hash = createHash('sha256');
28
- const outputPattern = new RegExp(`^${path.posix
29
- .normalize(outputDirectory)
30
- .replace(/[.*+?^$()|[\]\\]/g, '\\$&')
31
- .replace(/\{channel\}/g, '[a-z][a-z0-9-]{0,63}')
32
- .replace(/\{format\}/g, '(?:html|zip)')}(?:/|$)`);
33
- const receipt = receiptPath ? path.resolve(receiptPath) : undefined;
34
- const visit = async (directory) => {
35
- const entries = (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, 'en'));
36
- for (const entry of entries) {
37
- const absolute = path.join(directory, entry.name);
38
- const relative = path.relative(root, absolute).split(path.sep).join('/');
39
- if (SOURCE_IGNORED.has(entry.name) ||
40
- /^\.env(?:\..*)?$/.test(entry.name) ||
41
- absolute === receipt ||
42
- generatedDirectories.some((directory) => relative === directory || relative.startsWith(`${directory}/`)) ||
43
- outputPattern.test(relative))
44
- continue;
45
- if (entry.isDirectory())
46
- await visit(absolute);
47
- else if (entry.isSymbolicLink()) {
48
- throw new ProjectDeliveryError('delivery_source_symlink', 'Source symlinks require a reproducible project build input', relative);
49
- }
50
- else if (entry.isFile()) {
51
- const content = await readFile(absolute);
52
- hash.update(`${relative.length}:${relative}:${content.length}:`).update(content);
53
- }
54
- }
55
- };
56
- await visit(root);
57
- return hash.digest('hex');
58
- }
@@ -1,5 +0,0 @@
1
- import { type ProductionSourceSnapshot } from '../production-inputs.js';
2
- import type { ProjectDeliveryOptions, ProjectDeliveryRecipe } from './types.js';
3
- import type { DeliveryCommandIsolation } from './commands.js';
4
- /** A clean source directory contains only the versioned production snapshot and controlled dependencies. */
5
- export declare function buildIsolatedDelivery(root: string, snapshot: ProductionSourceSnapshot, recipe: ProjectDeliveryRecipe, options: ProjectDeliveryOptions, build: (isolated: string, isolation: DeliveryCommandIsolation) => Promise<string>): Promise<string>;
@@ -1,148 +0,0 @@
1
- import { chown, chmod, cp, lstat, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises';
2
- import { randomUUID } from 'node:crypto';
3
- import path from 'node:path';
4
- import { readProductionSourceSnapshot } from '../production-inputs.js';
5
- import { ProjectDeliveryError, deliveryContext, recipeDigest, readProjectDeliveryRecipe } from './recipe.js';
6
- import { outputFingerprint } from './files.js';
7
- import { publishDeliveryOutput, recoverDeliveryOutputPublication } from './output-publication.js';
8
- /** A clean source directory contains only the versioned production snapshot and controlled dependencies. */
9
- export async function buildIsolatedDelivery(root, snapshot, recipe, options, build) {
10
- root = await realpath(root);
11
- const context = deliveryContext(recipe, options);
12
- const outputDirectory = path.posix.normalize(context.outputDirectory).replace(/\/+$/, '');
13
- if (!outputDirectory.startsWith('dist/'))
14
- throw new ProjectDeliveryError('delivery_output_overlaps_artifacts', 'Use a dedicated output directory below dist; original artifacts must be preserved');
15
- await assertOutputPath(root, outputDirectory);
16
- const publication = { root, outputDirectory, entry: context.entry,
17
- sourceFingerprint: snapshot.fingerprint, recipeDigest: recipeDigest(recipe), key: context.key,
18
- ...(options.receiptDirectory || options.receiptPath ? {
19
- receiptDirectory: options.receiptDirectory ?? path.dirname(options.receiptPath),
20
- } : {}) };
21
- if (await recoverDeliveryOutputPublication(publication) === 'published')
22
- return outputFingerprint(root, outputDirectory, context.entry);
23
- const group = (await lstat(root)).gid;
24
- const shared = async (target, directory, executable = false) => {
25
- if (process.platform !== 'win32') {
26
- await chown(target, process.getuid(), group);
27
- await chmod(target, directory ? 0o2770 : executable ? 0o770 : 0o660);
28
- }
29
- };
30
- const temporary = path.join(root, '.playcraft-temp');
31
- const existing = await lstat(temporary).catch((error) => { if (error.code === 'ENOENT')
32
- return undefined; throw error; });
33
- if (existing && (!existing.isDirectory() || existing.isSymbolicLink()))
34
- throw new ProjectDeliveryError('delivery_path_outside_project', 'Unsafe delivery staging directory');
35
- if (!existing) {
36
- await mkdir(temporary, { mode: 0o2770 });
37
- await shared(temporary, true);
38
- }
39
- const scratch = await mkdtemp(path.join(temporary, 'delivery-source-'));
40
- await shared(scratch, true);
41
- const directories = new Set([scratch]);
42
- const parent = async (relative) => {
43
- let directory = scratch;
44
- for (const segment of relative.split('/').slice(0, -1)) {
45
- directory = path.join(directory, segment);
46
- if (!directories.has(directory)) {
47
- await mkdir(directory);
48
- await shared(directory, true);
49
- directories.add(directory);
50
- }
51
- }
52
- };
53
- // On failure retain only this bounded staging directory. A managed process may still be
54
- // reconciling its original identity; deleting its cwd is not a stop acknowledgement.
55
- for (const [name, file] of snapshot.files) {
56
- await parent(name);
57
- const target = path.join(scratch, name);
58
- await writeFile(target, file.body, { flag: 'wx', mode: 0o660 });
59
- await shared(target, false, file.mode === '100755');
60
- }
61
- const projection = path.join(scratch, 'playcraft.config.json');
62
- await writeFile(projection, `${JSON.stringify({ build: { delivery: recipe } }, null, 2)}\n`, { flag: 'wx', mode: 0o660 });
63
- await shared(projection, false);
64
- const modules = await dependencyDirectory(root, options.trustedDependencyRoot);
65
- if (modules)
66
- await symlink(modules, path.join(scratch, 'node_modules'), 'dir');
67
- // Tool temporaries (for example Node's 0600 compile cache) must not land in the
68
- // rescanned production source; .playcraft-temp is a process path excluded from it.
69
- const toolTemporary = path.join(scratch, '.playcraft-temp');
70
- await mkdir(toolTemporary);
71
- await shared(toolTemporary, true);
72
- await build(scratch, { projectRoot: root, isolatedRoot: scratch, temporaryRoot: toolTemporary,
73
- dependencyRoots: modules ? [modules] : [] });
74
- const current = await readProductionSourceSnapshot(root, { excludedDirectories: recipe.generatedDirectories,
75
- excludedPath: name => name === context.outputDirectory || name.startsWith(`${context.outputDirectory}/`) });
76
- if (!current || current.fingerprint !== snapshot.fingerprint)
77
- throw new ProjectDeliveryError('delivery_source_changed', 'Production source changed while preparing delivery');
78
- const currentRecipe = await readProjectDeliveryRecipe(root);
79
- if (!currentRecipe || recipeDigest(currentRecipe) !== publication.recipeDigest)
80
- throw new ProjectDeliveryError('delivery_source_changed', 'The delivery recipe changed while preparing delivery');
81
- await assertOutputPath(scratch, outputDirectory, true);
82
- await assertOutputPath(root, outputDirectory);
83
- const source = path.join(scratch, outputDirectory);
84
- const expectedNewFingerprint = await outputFingerprint(scratch, context.outputDirectory, context.entry);
85
- // Publish only the declared output subtree. Never clean the root dist/ or other artifacts.
86
- const staged = path.join(temporary, `delivery-output-${randomUUID()}`);
87
- await cp(source, staged, { recursive: true, force: false, dereference: false });
88
- await assertOutputPath(root, outputDirectory, false, shared);
89
- const fingerprint = await publishDeliveryOutput({ ...publication, stagePath: staged, expectedNewFingerprint });
90
- await rm(scratch, { recursive: true, force: true });
91
- return fingerprint;
92
- }
93
- /**
94
- * Installed dependencies are a real node_modules directory, or a link the caller declared by its
95
- * resolved target. The snapshot links straight to that real path so the command mount view and
96
- * dependency allowance see one directory.
97
- */
98
- async function dependencyDirectory(root, trusted) {
99
- const modules = path.join(root, 'node_modules');
100
- const info = await lstat(modules).catch(() => undefined);
101
- if (!info)
102
- return undefined;
103
- if (info.isDirectory())
104
- return modules;
105
- if (info.isSymbolicLink() && trusted) {
106
- const [actual, expected] = await Promise.all([realpath(modules), realpath(trusted)]).catch(() => []);
107
- const target = actual ? await lstat(actual).catch(() => undefined) : undefined;
108
- if (actual && actual === expected && path.basename(actual) === 'node_modules' && target?.isDirectory())
109
- return actual;
110
- }
111
- throw new ProjectDeliveryError('delivery_dependency_path_unsafe', 'Installed dependencies must be a directory');
112
- }
113
- /** Neither an output root nor any parent may alias source files or another directory. */
114
- async function assertOutputPath(root, relative, required = false, create) {
115
- const segments = relative.split('/');
116
- let current = root;
117
- for (let index = 0; index < segments.length; index++) {
118
- current = path.join(current, segments[index]);
119
- let info = await lstat(current).catch((error) => {
120
- if (error.code === 'ENOENT')
121
- return undefined;
122
- throw error;
123
- });
124
- if (!info && create && index < segments.length - 1) {
125
- let created = false;
126
- try {
127
- await mkdir(current, { mode: 0o2770 });
128
- created = true;
129
- }
130
- catch (error) {
131
- if (error.code !== 'EEXIST')
132
- throw error;
133
- }
134
- if (created)
135
- await create(current, true);
136
- info = await lstat(current);
137
- }
138
- if (!info) {
139
- if (required)
140
- throw new ProjectDeliveryError('delivery_output_invalid', 'The output directory is missing');
141
- return;
142
- }
143
- if (info.isSymbolicLink())
144
- throw new ProjectDeliveryError('delivery_output_symlink', 'Delivery output paths must not contain symlinks');
145
- if (!info.isDirectory())
146
- throw new ProjectDeliveryError('delivery_output_invalid', 'Delivery output paths must be directories');
147
- }
148
- }
@@ -1,21 +0,0 @@
1
- export type DeliveryOutputPublicationScope = {
2
- root: string;
3
- outputDirectory: string;
4
- entry: string;
5
- sourceFingerprint: string;
6
- recipeDigest: string;
7
- receiptDirectory?: string;
8
- key: string;
9
- };
10
- export type DeliveryOutputPublicationInput = DeliveryOutputPublicationScope & {
11
- stagePath: string;
12
- expectedNewFingerprint: string;
13
- /** Controller-only fault injection; never part of a recipe or model tool schema. */
14
- checkpoint?: (phase: 'intent-durable' | 'old-moved' | 'new-published' | 'committed' | 'backup-removed') => Promise<void>;
15
- };
16
- /** Read-only: a pending or corrupt publication makes inspection stale; it never restores files. */
17
- export declare function hasPendingDeliveryOutputPublication(scope: DeliveryOutputPublicationScope): Promise<boolean>;
18
- /** Call only after the existing preparation/execution owner has exclusive directory access. */
19
- export declare function recoverDeliveryOutputPublication(scope: DeliveryOutputPublicationScope): Promise<'none' | 'published' | 'restored'>;
20
- /** A durable, conditional publication of a pre-copied output tree; unknown values are never removed. */
21
- export declare function publishDeliveryOutput(input: DeliveryOutputPublicationInput): Promise<string>;
@@ -1,444 +0,0 @@
1
- import { constants } from 'node:fs';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { chmod, chown, lstat, mkdir, open, realpath, readdir, rename, rm } from 'node:fs/promises';
4
- import path from 'node:path';
5
- import { outputFingerprint } from './files.js';
6
- import { ProjectDeliveryError } from './recipe.js';
7
- const digest = (value) => createHash('sha256').update(value).digest('hex');
8
- const isHash = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
9
- function failure(code = 'delivery_publication_conflict') {
10
- throw new ProjectDeliveryError(code, 'Delivery output publication needs its original source, paths and receipt to be reconciled');
11
- }
12
- const missing = (error) => error.code === 'ENOENT';
13
- const info = async (name) => lstat(name).catch((error) => {
14
- if (missing(error))
15
- return undefined;
16
- throw error;
17
- });
18
- const identity = (value) => ({ dev: value.dev, ino: value.ino });
19
- const sameIdentity = (left, right) => left.dev === right.dev && left.ino === right.ino;
20
- const same = (left, right) => left === null || right === null
21
- ? left === right
22
- : sameIdentity(left, right) && left.treeHash === right.treeHash;
23
- const inside = (root, name) => {
24
- const relative = path.relative(root, name);
25
- return (relative === '' ||
26
- (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)));
27
- };
28
- function relative(value) {
29
- if (typeof value !== 'string' ||
30
- !value ||
31
- value.includes('\\') ||
32
- value.includes('\0') ||
33
- path.posix.isAbsolute(value) ||
34
- value.split('/').includes('..') ||
35
- /^[A-Za-z]:/.test(value))
36
- failure('delivery_publication_path_unsafe');
37
- const result = path.posix.normalize(value).replace(/\/+$/, '');
38
- if (!result || result === '.')
39
- failure('delivery_publication_path_unsafe');
40
- return result;
41
- }
42
- async function syncDirectory(name) {
43
- const handle = await open(name, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
44
- try {
45
- await handle.sync();
46
- }
47
- finally {
48
- await handle.close();
49
- }
50
- }
51
- async function createPrivateDirectory(requested) {
52
- const pending = [];
53
- let current = requested;
54
- while (!(await info(current))) {
55
- pending.unshift(path.basename(current));
56
- const parent = path.dirname(current);
57
- if (parent === current)
58
- failure('delivery_publication_path_unsafe');
59
- current = parent;
60
- }
61
- const anchor = await lstat(current);
62
- if (!anchor.isDirectory() || anchor.isSymbolicLink())
63
- failure('delivery_publication_path_unsafe');
64
- for (const segment of pending) {
65
- const next = path.join(current, segment);
66
- await mkdir(next, { mode: 0o700 });
67
- await syncDirectory(current);
68
- current = next;
69
- }
70
- }
71
- /** Never follow project-controlled directory links, including an existing output root. */
72
- async function directory(root, relativePath, create = false, shared = false) {
73
- let current = root;
74
- const rootStat = await lstat(current);
75
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink())
76
- failure('delivery_publication_path_unsafe');
77
- for (const segment of relativePath === '.' ? [] : relative(relativePath).split('/')) {
78
- const next = path.join(current, segment);
79
- let entry = await info(next);
80
- if (!entry && create) {
81
- await mkdir(next, { mode: shared ? 0o2770 : 0o700 });
82
- if (shared && process.platform !== 'win32') {
83
- await chown(next, process.getuid(), rootStat.gid);
84
- await chmod(next, 0o2770);
85
- await syncDirectory(next);
86
- }
87
- await syncDirectory(current);
88
- entry = await lstat(next);
89
- }
90
- if (!entry?.isDirectory() || entry.isSymbolicLink())
91
- failure('delivery_publication_path_unsafe');
92
- current = next;
93
- }
94
- return identity(await lstat(current));
95
- }
96
- async function directoryState(name, durable = false) {
97
- const top = await info(name);
98
- if (!top)
99
- return null;
100
- if (!top.isDirectory() || top.isSymbolicLink())
101
- failure('delivery_publication_path_unsafe');
102
- const hash = createHash('sha256').update('playcraft-output-publication-v1\0');
103
- let bytes = 0, count = 0;
104
- async function visit(current, prefix) {
105
- const start = await lstat(current);
106
- if (!start.isDirectory() || start.isSymbolicLink())
107
- failure('delivery_publication_path_unsafe');
108
- for (const entry of (await readdir(current, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
109
- if (++count > 16384)
110
- failure('delivery_publication_limit');
111
- const full = path.join(current, entry.name), member = prefix ? `${prefix}/${entry.name}` : entry.name;
112
- if (entry.isDirectory()) {
113
- hash.update(`d\0${member}\0`);
114
- await visit(full, member);
115
- }
116
- else {
117
- if (!entry.isFile() || entry.isSymbolicLink())
118
- failure('delivery_publication_path_unsafe');
119
- const handle = await open(full, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
120
- try {
121
- const before = await handle.stat();
122
- if (!before.isFile() || before.nlink !== 1 || (bytes += before.size) > 512 * 1024 * 1024)
123
- failure('delivery_publication_limit');
124
- const body = await handle.readFile(), after = await handle.stat(), named = await lstat(full);
125
- if (!sameIdentity(before, after) ||
126
- !sameIdentity(after, named) ||
127
- body.length !== before.size ||
128
- before.mtimeMs !== after.mtimeMs ||
129
- before.ctimeMs !== after.ctimeMs)
130
- failure();
131
- hash
132
- .update(`f\0${member}\0${before.mode & 0o111}\0`)
133
- .update(body)
134
- .update('\0');
135
- if (durable)
136
- await handle.sync();
137
- }
138
- finally {
139
- await handle.close();
140
- }
141
- }
142
- }
143
- if (!sameIdentity(start, await lstat(current)))
144
- failure();
145
- if (durable)
146
- await syncDirectory(current);
147
- }
148
- await visit(name, '');
149
- const end = await lstat(name);
150
- if (!sameIdentity(top, end))
151
- failure();
152
- return { ...identity(top), treeHash: hash.digest('hex') };
153
- }
154
- async function journalPath(scope, create) {
155
- if (typeof scope.key !== 'string' ||
156
- !scope.key ||
157
- scope.key.length > 256 ||
158
- scope.key.includes('\0'))
159
- failure();
160
- const root = await realpath(scope.root), requested = path.resolve(scope.receiptDirectory ?? path.join(root, '.playcraft/delivery'));
161
- if (inside(root, requested)) {
162
- if (create)
163
- await directory(root, path.relative(root, requested) || '.', true);
164
- else {
165
- let current = root;
166
- for (const segment of path.relative(root, requested).split(path.sep).filter(Boolean)) {
167
- current = path.join(current, segment);
168
- const entry = await info(current);
169
- if (!entry)
170
- break;
171
- if (!entry.isDirectory() || entry.isSymbolicLink())
172
- failure('delivery_publication_path_unsafe');
173
- }
174
- }
175
- }
176
- else {
177
- const existing = await info(requested);
178
- if (!existing && create)
179
- await createPrivateDirectory(requested);
180
- const current = await info(requested);
181
- if (current && (!current.isDirectory() || current.isSymbolicLink()))
182
- failure('delivery_publication_path_unsafe');
183
- }
184
- // A stable key intentionally survives output, recipe and source changes, which must block recovery.
185
- return path.join(requested, `output-publication-${digest(scope.key)}.json`);
186
- }
187
- function isIdentity(value) {
188
- const item = value;
189
- return Boolean(item &&
190
- typeof item === 'object' &&
191
- !Array.isArray(item) &&
192
- Object.keys(item).length === 2 &&
193
- Object.keys(item).every((key) => key === 'dev' || key === 'ino') &&
194
- Number.isSafeInteger(item.dev) &&
195
- item.dev >= 0 &&
196
- Number.isSafeInteger(item.ino) &&
197
- item.ino >= 0);
198
- }
199
- function isState(value) {
200
- const item = value;
201
- return Boolean(item &&
202
- typeof item === 'object' &&
203
- !Array.isArray(item) &&
204
- Object.keys(item).length === 3 &&
205
- isIdentity({ dev: item.dev, ino: item.ino }) &&
206
- isHash(item.treeHash));
207
- }
208
- async function readRecord(file) {
209
- const entry = await info(file);
210
- if (!entry)
211
- return undefined;
212
- if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.size > 65536)
213
- failure('delivery_publication_journal_invalid');
214
- const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
215
- let record;
216
- try {
217
- record = JSON.parse(await handle.readFile('utf8'));
218
- }
219
- catch {
220
- failure('delivery_publication_journal_invalid');
221
- }
222
- finally {
223
- await handle.close();
224
- }
225
- if (!record ||
226
- typeof record !== 'object' ||
227
- Array.isArray(record) ||
228
- Object.keys(record).some((key) => ![
229
- 'version',
230
- 'id',
231
- 'key',
232
- 'root',
233
- 'rootIdentity',
234
- 'parentIdentity',
235
- 'outputDirectory',
236
- 'entry',
237
- 'sourceFingerprint',
238
- 'recipeDigest',
239
- 'stageName',
240
- 'backupName',
241
- 'before',
242
- 'after',
243
- 'expectedNewFingerprint',
244
- 'phase',
245
- ].includes(key)) ||
246
- record.version !== 1 ||
247
- !/^[a-f0-9-]{36}$/.test(record.id) ||
248
- typeof record.key !== 'string' ||
249
- typeof record.root !== 'string' ||
250
- !path.isAbsolute(record.root) ||
251
- !isIdentity(record.rootIdentity) ||
252
- !isIdentity(record.parentIdentity) ||
253
- !isHash(record.sourceFingerprint) ||
254
- !isHash(record.recipeDigest) ||
255
- !isHash(record.expectedNewFingerprint) ||
256
- !(record.before === null || isState(record.before)) ||
257
- !isState(record.after) ||
258
- !/^delivery-output-[a-zA-Z0-9-]{1,100}$/.test(record.stageName) ||
259
- record.backupName !== `delivery-before-${record.id}` ||
260
- !['planned', 'old-moved', 'published', 'committed', 'restored'].includes(record.phase) ||
261
- typeof record.outputDirectory !== 'string' ||
262
- typeof record.entry !== 'string')
263
- failure('delivery_publication_journal_invalid');
264
- return record;
265
- }
266
- async function writeRecord(file, record) {
267
- const temporary = `${file}.${randomUUID()}.tmp`, handle = await open(temporary, 'wx', 0o600);
268
- try {
269
- await handle.writeFile(`${JSON.stringify(record)}\n`);
270
- await handle.sync();
271
- }
272
- finally {
273
- await handle.close();
274
- }
275
- await rename(temporary, file);
276
- await syncDirectory(path.dirname(file));
277
- }
278
- async function scopePaths(scope, record) {
279
- const root = await realpath(scope.root), outputDirectory = relative(scope.outputDirectory), entry = relative(scope.entry);
280
- if (!outputDirectory.startsWith('dist/') ||
281
- outputDirectory.split('/').length < 2 ||
282
- !isHash(scope.sourceFingerprint) ||
283
- !isHash(scope.recipeDigest))
284
- failure('delivery_publication_path_unsafe');
285
- const rootIdentity = identity(await lstat(root)), parentRelative = path.posix.dirname(outputDirectory);
286
- const parentIdentity = await directory(root, parentRelative, !record, true);
287
- await directory(root, '.playcraft-temp');
288
- if (record &&
289
- (record.key !== scope.key ||
290
- record.root !== root ||
291
- !sameIdentity(record.rootIdentity, rootIdentity) ||
292
- !sameIdentity(record.parentIdentity, parentIdentity) ||
293
- record.outputDirectory !== outputDirectory ||
294
- record.entry !== entry ||
295
- record.sourceFingerprint !== scope.sourceFingerprint ||
296
- record.recipeDigest !== scope.recipeDigest))
297
- failure('delivery_publication_scope_changed');
298
- return {
299
- root,
300
- rootIdentity,
301
- parentIdentity,
302
- outputDirectory,
303
- entry,
304
- destination: path.join(root, outputDirectory),
305
- temporary: path.join(root, '.playcraft-temp'),
306
- };
307
- }
308
- async function finish(file, record, paths, status, checkpoint) {
309
- const destination = await directoryState(paths.destination), backup = path.join(paths.temporary, record.backupName), stage = path.join(paths.temporary, record.stageName);
310
- if (!same(destination, status === 'published' ? record.after : record.before))
311
- failure();
312
- if (status === 'published' &&
313
- (await outputFingerprint(paths.root, paths.outputDirectory, paths.entry)) !==
314
- record.expectedNewFingerprint)
315
- failure();
316
- const saved = await directoryState(backup), pending = await directoryState(stage);
317
- if (saved && !same(saved, record.before))
318
- failure();
319
- if (pending && !same(pending, record.after))
320
- failure();
321
- record.phase = status === 'published' ? 'committed' : 'restored';
322
- await writeRecord(file, record);
323
- await checkpoint?.('committed');
324
- if (saved)
325
- await rm(backup, { recursive: true });
326
- if (pending)
327
- await rm(stage, { recursive: true });
328
- await syncDirectory(paths.temporary);
329
- await checkpoint?.('backup-removed');
330
- await rm(file);
331
- await syncDirectory(path.dirname(file));
332
- return status;
333
- }
334
- async function advance(file, record, scope, checkpoint) {
335
- const paths = await scopePaths(scope, record), stage = path.join(paths.temporary, record.stageName), backup = path.join(paths.temporary, record.backupName);
336
- let destination = await directoryState(paths.destination), staged = await directoryState(stage), saved = await directoryState(backup);
337
- if ((staged && !same(staged, record.after)) || (saved && !same(saved, record.before)))
338
- failure();
339
- if (record.phase === 'restored') {
340
- if (!same(destination, record.before) || saved)
341
- failure();
342
- return finish(file, record, paths, 'restored', checkpoint);
343
- }
344
- if (same(destination, record.after)) {
345
- if (staged || (record.before && !saved && record.phase !== 'committed'))
346
- failure();
347
- return finish(file, record, paths, 'published', checkpoint);
348
- }
349
- if (record.phase === 'committed')
350
- failure();
351
- if (same(destination, record.before) && !saved) {
352
- if (!staged)
353
- return finish(file, record, paths, 'restored', checkpoint);
354
- if (destination) {
355
- await rename(paths.destination, backup);
356
- await syncDirectory(path.dirname(paths.destination));
357
- await syncDirectory(paths.temporary);
358
- saved = await directoryState(backup);
359
- if (!same(saved, record.before))
360
- failure();
361
- }
362
- destination = null;
363
- record.phase = 'old-moved';
364
- await writeRecord(file, record);
365
- await checkpoint?.('old-moved');
366
- }
367
- if (destination !== null || (record.before && !same(saved, record.before)))
368
- failure();
369
- staged = await directoryState(stage);
370
- if (!staged) {
371
- if (saved) {
372
- await rename(backup, paths.destination);
373
- await syncDirectory(path.dirname(paths.destination));
374
- await syncDirectory(paths.temporary);
375
- }
376
- return finish(file, record, paths, 'restored', checkpoint);
377
- }
378
- if (!same(staged, record.after))
379
- failure();
380
- await rename(stage, paths.destination);
381
- await syncDirectory(path.dirname(paths.destination));
382
- await syncDirectory(paths.temporary);
383
- record.phase = 'published';
384
- await writeRecord(file, record);
385
- await checkpoint?.('new-published');
386
- return finish(file, record, paths, 'published', checkpoint);
387
- }
388
- /** Read-only: a pending or corrupt publication makes inspection stale; it never restores files. */
389
- export async function hasPendingDeliveryOutputPublication(scope) {
390
- const file = await journalPath(scope, false);
391
- return Boolean(await readRecord(file));
392
- }
393
- /** Call only after the existing preparation/execution owner has exclusive directory access. */
394
- export async function recoverDeliveryOutputPublication(scope) {
395
- const file = await journalPath(scope, false), record = await readRecord(file);
396
- return record ? advance(file, record, scope) : 'none';
397
- }
398
- /** A durable, conditional publication of a pre-copied output tree; unknown values are never removed. */
399
- export async function publishDeliveryOutput(input) {
400
- const file = await journalPath(input, true);
401
- if (await readRecord(file))
402
- failure('delivery_publication_pending');
403
- const paths = await scopePaths(input), stagePath = path.resolve(input.stagePath), stageName = path.basename(stagePath);
404
- if (path.dirname(stagePath) !== paths.temporary ||
405
- !/^delivery-output-[a-zA-Z0-9-]{1,100}$/.test(stageName) ||
406
- !isHash(input.expectedNewFingerprint))
407
- failure('delivery_publication_path_unsafe');
408
- await directory(paths.root, path.relative(paths.root, stagePath));
409
- const after = await directoryState(stagePath, true);
410
- if (!after ||
411
- after.dev !== paths.rootIdentity.dev ||
412
- after.dev !== paths.parentIdentity.dev ||
413
- (await outputFingerprint(paths.root, path.relative(paths.root, stagePath), paths.entry)) !==
414
- input.expectedNewFingerprint)
415
- failure();
416
- await syncDirectory(paths.temporary);
417
- await syncDirectory(path.dirname(paths.destination));
418
- const id = randomUUID(), backupName = `delivery-before-${id}`;
419
- if (await info(path.join(paths.temporary, backupName)))
420
- failure();
421
- const record = {
422
- version: 1,
423
- id,
424
- key: input.key,
425
- root: paths.root,
426
- rootIdentity: paths.rootIdentity,
427
- parentIdentity: paths.parentIdentity,
428
- outputDirectory: paths.outputDirectory,
429
- entry: paths.entry,
430
- sourceFingerprint: input.sourceFingerprint,
431
- recipeDigest: input.recipeDigest,
432
- stageName,
433
- backupName,
434
- before: await directoryState(paths.destination, true),
435
- after,
436
- expectedNewFingerprint: input.expectedNewFingerprint,
437
- phase: 'planned',
438
- };
439
- await writeRecord(file, record);
440
- await input.checkpoint?.('intent-durable');
441
- if ((await advance(file, record, input, input.checkpoint)) !== 'published')
442
- failure('delivery_publication_not_published');
443
- return input.expectedNewFingerprint;
444
- }