@playcraft/build 0.1.92-test → 0.1.94-test-a

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 (113) 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 +20 -0
  17. package/dist/delivery/command-isolation.js +324 -0
  18. package/dist/delivery/commands.d.ts +5 -0
  19. package/dist/delivery/commands.js +146 -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-qa.d.ts +44 -0
  66. package/dist/validation/artifact-qa.js +170 -0
  67. package/dist/validation/artifact-rules.d.ts +28 -0
  68. package/dist/validation/artifact-rules.js +440 -0
  69. package/dist/validation/artifact.d.ts +14 -0
  70. package/dist/validation/artifact.js +188 -0
  71. package/dist/validation/html-validator.d.ts +5 -0
  72. package/dist/validation/html-validator.js +19 -17
  73. package/dist/validation/index.d.ts +4 -0
  74. package/dist/validation/index.js +4 -0
  75. package/dist/validation/package-validator.d.ts +2 -0
  76. package/dist/validation/package-validator.js +25 -64
  77. package/dist/validation/profiles.d.ts +13 -1
  78. package/dist/validation/profiles.js +27 -0
  79. package/dist/validation/runtime-load.d.ts +89 -0
  80. package/dist/validation/runtime-load.js +654 -0
  81. package/dist/validation/source-scanner.d.ts +11 -0
  82. package/dist/validation/source-scanner.js +32 -2
  83. package/dist/validation/types.d.ts +155 -2
  84. package/dist/validation/types.js +1 -1
  85. package/dist/validation/validation-runner.d.ts +22 -2
  86. package/dist/validation/validation-runner.js +68 -3
  87. package/dist/validation/zip-reader.d.ts +7 -0
  88. package/dist/validation/zip-reader.js +159 -26
  89. package/dist/vite/config-builder-generic.d.ts +3 -1
  90. package/dist/vite/config-builder-generic.js +9 -7
  91. package/dist/vite/config-builder.js +1 -1
  92. package/dist/vite/plugin-platform.js +30 -54
  93. package/dist/vite/plugin-source-builder.d.ts +2 -14
  94. package/dist/vite/plugin-source-builder.js +61 -997
  95. package/dist/vite/source-builder-asset-paths.d.ts +25 -0
  96. package/dist/vite/source-builder-asset-paths.js +154 -0
  97. package/dist/vite/source-builder-esm.d.ts +7 -0
  98. package/dist/vite/source-builder-esm.js +877 -0
  99. package/dist/vite/source-builder-types.d.ts +14 -0
  100. package/dist/vite/source-builder-types.js +1 -0
  101. package/dist/vite/workspace.d.ts +6 -0
  102. package/dist/vite/workspace.js +41 -0
  103. package/dist/vite-builder.d.ts +4 -5
  104. package/dist/vite-builder.js +33 -34
  105. package/dist/workspace-css-imports.d.ts +2 -0
  106. package/dist/workspace-css-imports.js +139 -0
  107. package/dist/workspace-model-source.d.ts +14 -0
  108. package/dist/workspace-model-source.js +184 -0
  109. package/dist/workspace-public-imports.d.ts +11 -0
  110. package/dist/workspace-public-imports.js +232 -0
  111. package/dist/workspace-public-source.d.ts +15 -0
  112. package/dist/workspace-public-source.js +564 -0
  113. package/package.json +16 -4
@@ -99,6 +99,37 @@ export async function scanSourceForChannels(context, channels) {
99
99
  }
100
100
  return results;
101
101
  }
102
+ /**
103
+ * Finds where each pattern first occurs in executable project source (comments and strings in
104
+ * JavaScript-like files are ignored, as in the compliance scan). Absent patterns are left out.
105
+ */
106
+ export async function findSourcePatterns(projectRoot, patterns, sourceGlobs) {
107
+ const found = new Map();
108
+ const ids = Object.keys(patterns);
109
+ for (const filePath of await collectSourceFiles(projectRoot, sourceGlobs)) {
110
+ if (found.size === ids.length)
111
+ break;
112
+ let content;
113
+ try {
114
+ content = await fs.readFile(filePath, 'utf-8');
115
+ }
116
+ catch {
117
+ continue;
118
+ }
119
+ for (const id of ids) {
120
+ if (found.has(id))
121
+ continue;
122
+ const match = findExecutableSourcePattern(filePath, content, patterns[id]);
123
+ if (match)
124
+ found.set(id, {
125
+ file: filePath,
126
+ line: lineOfIndex(content, match.index),
127
+ evidence: trimEvidence(match.evidence),
128
+ });
129
+ }
130
+ }
131
+ return found;
132
+ }
102
133
  async function scanSourceFilesForChannel(context, sourceFiles, includeCommonPatterns) {
103
134
  const results = [];
104
135
  const requiredPatterns = CHANNEL_SOURCE_PATTERNS[context.channel] ?? [];
@@ -333,7 +364,6 @@ function maskJavaScriptLikeSource(content) {
333
364
  maskRange(start, index);
334
365
  return index;
335
366
  };
336
- let scanCode;
337
367
  const scanTemplate = (start) => {
338
368
  maskAt(start);
339
369
  let index = start + 1;
@@ -361,7 +391,7 @@ function maskJavaScriptLikeSource(content) {
361
391
  }
362
392
  return index;
363
393
  };
364
- scanCode = (start, interpolation) => {
394
+ const scanCode = (start, interpolation) => {
365
395
  let index = start;
366
396
  let braceDepth = interpolation ? 1 : 0;
367
397
  while (index < content.length) {
@@ -1,7 +1,7 @@
1
1
  import type { BuildTool, EngineType, OutputFormat, Platform } from '../types.js';
2
- export type ValidationStage = 'prebuild-source' | 'base-output' | 'html-artifact' | 'delivery-package' | 'runtime-manual' | 'external-validator';
2
+ export type ValidationStage = 'prebuild-source' | 'base-output' | 'html-artifact' | 'delivery-package' | 'runtime-load' | 'runtime-manual' | 'external-validator';
3
3
  export type RuleSeverity = 'error' | 'warning' | 'info';
4
- export type RuleStatus = 'pass' | 'fail' | 'warning' | 'manual' | 'external' | 'not-applicable';
4
+ export type RuleStatus = 'pass' | 'fail' | 'warning' | 'manual' | 'external' | 'not-applicable' | 'inconclusive';
5
5
  export type RuleConfidence = 'high' | 'medium' | 'low';
6
6
  export type RuleOwner = 'playcraft-build' | 'playcraft-delivery' | 'devkit' | 'manual' | 'external';
7
7
  export type DeliveryMode = 'single-html' | 'zip' | 'html-backed-zip' | 'fragment-assets' | 'mixed';
@@ -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>;
@@ -110,3 +115,151 @@ export interface ValidationReport {
110
115
  manualChecklist: ManualChecklistItem[];
111
116
  externalChecklist: ExternalChecklistItem[];
112
117
  }
118
+ /** How a built artifact is stored on disk. */
119
+ export type ArtifactContainer = 'html' | 'zip' | 'directory';
120
+ /**
121
+ * How the playable is laid out inside its container: one self-contained HTML file,
122
+ * or an HTML entry with separate files (scripts, styles, assets).
123
+ */
124
+ export type ArtifactLayout = 'single-html' | 'multi-file';
125
+ export interface ArtifactFile {
126
+ /** Path inside the artifact, `/`-separated, without a leading slash. */
127
+ path: string;
128
+ /** Uncompressed size in bytes. */
129
+ size: number;
130
+ }
131
+ export interface PlayableArtifact {
132
+ /** Absolute path of the file or directory that was read. */
133
+ sourcePath: string;
134
+ container: ArtifactContainer;
135
+ layout: ArtifactLayout;
136
+ /** Entry HTML path inside the artifact. */
137
+ entry: string;
138
+ files: ArtifactFile[];
139
+ /** Bytes on disk: the HTML or ZIP file size, or the sum of the directory's files. */
140
+ totalSize: number;
141
+ /** `sha256:<hex>`; stable for the same content regardless of where it is stored. */
142
+ digest: string;
143
+ readText(filePath: string): Promise<string | null>;
144
+ readBuffer(filePath: string): Promise<Buffer | null>;
145
+ }
146
+ export type ArtifactReadErrorCode = 'artifact_not_found' | 'artifact_unsupported' | 'artifact_zip_invalid' | 'artifact_entry_missing' | 'artifact_entry_ambiguous' | 'artifact_entry_invalid';
147
+ /**
148
+ * Artifact QA stages. Each stage runs on its own: it depends only on the artifact and its own
149
+ * options, never on another stage's results, and produces its own report.
150
+ * - `base`: static checks of the artifact files.
151
+ * - `channel`: the channel's existing `html-artifact` / `delivery-package` rules.
152
+ * - `runtime-load`: opens the artifact in a headless browser.
153
+ * - `source-hints`: scans project source; advisory only.
154
+ */
155
+ export type QaStageId = 'base' | 'channel' | 'runtime-load' | 'source-hints';
156
+ export declare const QA_STAGES: readonly QaStageId[];
157
+ /**
158
+ * - `ran`: the stage ran; see its results.
159
+ * - `skipped`: the stage applies but could not run (e.g. no browser); the QA is incomplete.
160
+ * - `not-applicable`: the stage does not apply (e.g. channel rules for the `playcraft` profile).
161
+ */
162
+ export type QaStageStatus = 'ran' | 'skipped' | 'not-applicable';
163
+ export interface QaStageReport {
164
+ stage: QaStageId;
165
+ status: QaStageStatus;
166
+ /** Why the stage did not run. */
167
+ reason?: string;
168
+ /** Advisory stages never affect the overall summary or exit code. */
169
+ advisory: boolean;
170
+ durationMs: number;
171
+ summary: ValidationSummary;
172
+ results: ValidationResult[];
173
+ manualChecklist: ManualChecklistItem[];
174
+ externalChecklist: ExternalChecklistItem[];
175
+ /** Stage-specific facts, e.g. the size limit used by `base`. */
176
+ details?: Record<string, unknown>;
177
+ }
178
+ /**
179
+ * Report of `runArtifactQa`: one report per stage, and an overall summary of the non-advisory
180
+ * stages that ran. Kept apart from `ValidationReport` so the existing delivery validation output,
181
+ * which is checked against strict schemas, stays unchanged.
182
+ */
183
+ export interface ArtifactQaReport {
184
+ version: string;
185
+ rulesVersion: string;
186
+ profile: Platform;
187
+ artifact: {
188
+ sourcePath: string;
189
+ container: ArtifactContainer;
190
+ layout: ArtifactLayout;
191
+ entry: string;
192
+ digest: string;
193
+ totalSize: number;
194
+ fileCount: number;
195
+ };
196
+ summary: ValidationSummary;
197
+ /** A requested stage was skipped, so passing does not cover it. */
198
+ incomplete: boolean;
199
+ stages: QaStageReport[];
200
+ }
201
+ export interface ReadArtifactOptions {
202
+ /** Entry HTML path inside a ZIP or directory; defaults to `index.html`, then the only HTML file. */
203
+ entry?: string;
204
+ }
205
+ /**
206
+ * Browser access for runtime QA. `@playcraft/build` only defines this contract; hosts provide the
207
+ * implementation (the CLI uses playwright-core), so the build package does not depend on a browser.
208
+ */
209
+ export interface RuntimeViewport {
210
+ width: number;
211
+ height: number;
212
+ deviceScaleFactor: number;
213
+ isMobile: boolean;
214
+ hasTouch: boolean;
215
+ }
216
+ export interface RuntimeResource {
217
+ body: Buffer;
218
+ contentType: string;
219
+ }
220
+ export interface RuntimePageOptions {
221
+ /** Origin the artifact is served from, e.g. `http://artifact.playcraft-qa.test`. */
222
+ origin: string;
223
+ /** Entry path inside the artifact, served at `${origin}/${entryPath}`. */
224
+ entryPath: string;
225
+ viewport: RuntimeViewport;
226
+ userAgent: string;
227
+ /** Runs before any page script. */
228
+ initScript: string;
229
+ /** Content-Security-Policy header sent with HTML responses. */
230
+ contentSecurityPolicy: string;
231
+ /** Serves a path inside the artifact; null means the file does not exist (404). */
232
+ resolve(pathname: string): Promise<RuntimeResource | null>;
233
+ /** Navigation timeout in milliseconds. */
234
+ timeoutMs: number;
235
+ }
236
+ export interface RuntimePageEvents {
237
+ consoleErrors: string[];
238
+ pageErrors: string[];
239
+ /** Requests for artifact files that do not exist, or that failed to load. */
240
+ failedRequests: Array<{
241
+ url: string;
242
+ reason: string;
243
+ }>;
244
+ /** Requests to any host other than the artifact origin; they are blocked, never sent. */
245
+ blockedRequests: string[];
246
+ /** Top-level navigations away from the entry; they are blocked, never followed. */
247
+ navigationAttempts: string[];
248
+ }
249
+ export interface RuntimePage {
250
+ /** Whether the entry document loaded. */
251
+ loaded: boolean;
252
+ loadError?: string;
253
+ events(): RuntimePageEvents;
254
+ /** Evaluates a JavaScript expression in the page and returns its JSON-serializable result. */
255
+ evaluate<T>(expression: string): Promise<T>;
256
+ /** Dispatches a real pointer click at viewport coordinates. */
257
+ click(x: number, y: number): Promise<void>;
258
+ /** PNG screenshot of the viewport. */
259
+ screenshot(): Promise<Buffer>;
260
+ wait(ms: number): Promise<void>;
261
+ close(): Promise<void>;
262
+ }
263
+ export interface BrowserDriver {
264
+ open(options: RuntimePageOptions): Promise<RuntimePage>;
265
+ }
@@ -1 +1 @@
1
- export {};
1
+ export const QA_STAGES = ['base', 'channel', 'runtime-load', 'source-hints'];
@@ -1,5 +1,25 @@
1
- import type { Platform } from '../types.js';
2
- import type { ValidationContext, ValidationReport, ValidationStage } from './types.js';
1
+ import type { OutputFormat, Platform } from '../types.js';
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>;
16
+ export declare function summarize(results: ValidationResult[], manualChecklist: ManualChecklistItem[], externalChecklist: ExternalChecklistItem[]): ValidationSummary;
17
+ /** Builds the report of a QA stage that ran. */
18
+ export declare function ranStageReport(stage: QaStageId, startedAt: number, results: ValidationResult[], extra?: {
19
+ advisory?: boolean;
20
+ manualChecklist?: ManualChecklistItem[];
21
+ externalChecklist?: ExternalChecklistItem[];
22
+ details?: Record<string, unknown>;
23
+ }): QaStageReport;
24
+ /** Builds the report of a QA stage that did not run. */
25
+ export declare function idleStageReport(stage: QaStageId, status: 'skipped' | 'not-applicable', reason: string, advisory?: boolean): QaStageReport;
@@ -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);
@@ -71,7 +106,7 @@ function buildExternalChecklist(rules, enabledStages) {
71
106
  owner: rule.owner,
72
107
  }));
73
108
  }
74
- function summarize(results, manualChecklist, externalChecklist) {
109
+ export function summarize(results, manualChecklist, externalChecklist) {
75
110
  const errorCount = results.filter((result) => result.status === 'fail').length;
76
111
  const warningCount = results.filter((result) => result.status === 'warning').length;
77
112
  const manualCount = manualChecklist.length;
@@ -94,3 +129,33 @@ function summarize(results, manualChecklist, externalChecklist) {
94
129
  externalCount,
95
130
  };
96
131
  }
132
+ /** Builds the report of a QA stage that ran. */
133
+ export function ranStageReport(stage, startedAt, results, extra = {}) {
134
+ const manualChecklist = extra.manualChecklist ?? [];
135
+ const externalChecklist = extra.externalChecklist ?? [];
136
+ return {
137
+ stage,
138
+ status: 'ran',
139
+ advisory: extra.advisory ?? false,
140
+ durationMs: Date.now() - startedAt,
141
+ summary: summarize(results, manualChecklist, externalChecklist),
142
+ results,
143
+ manualChecklist,
144
+ externalChecklist,
145
+ ...(extra.details ? { details: extra.details } : {}),
146
+ };
147
+ }
148
+ /** Builds the report of a QA stage that did not run. */
149
+ export function idleStageReport(stage, status, reason, advisory = false) {
150
+ return {
151
+ stage,
152
+ status,
153
+ reason,
154
+ advisory,
155
+ durationMs: 0,
156
+ summary: summarize([], [], []),
157
+ results: [],
158
+ manualChecklist: [],
159
+ externalChecklist: [],
160
+ };
161
+ }
@@ -4,14 +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;
19
+ readEntry(entryPath: string): Buffer | null;
14
20
  private readCentralDirectory;
15
21
  private readEntryData;
16
22
  private findEndOfCentralDirectory;
23
+ private requireRange;
17
24
  }
@@ -1,84 +1,217 @@
1
- import { inflateRawSync } from 'zlib';
1
+ import { inflateRawSync } from 'node:zlib';
2
+ const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
3
+ const MAX_ENTRY_BYTES = 64 * 1024 * 1024;
4
+ const MAX_TOTAL_BYTES = 128 * 1024 * 1024;
5
+ const MAX_ENTRIES = 4096;
6
+ const MAX_COMPRESSION_RATIO = 200;
7
+ const decoder = new TextDecoder('utf-8', { fatal: true });
8
+ function invalid(message) {
9
+ throw new Error(`Invalid ZIP: ${message}`);
10
+ }
11
+ function decode(bytes) {
12
+ try {
13
+ return decoder.decode(bytes);
14
+ }
15
+ catch {
16
+ invalid('entry filename is not valid UTF-8');
17
+ }
18
+ }
19
+ function validateEntryPath(value, directory) {
20
+ const member = directory ? value.slice(0, -1) : value;
21
+ if (!member ||
22
+ member.length > 1024 ||
23
+ member.includes('\0') ||
24
+ member.includes('\\') ||
25
+ member.startsWith('/') ||
26
+ /^[A-Za-z]:/.test(member) ||
27
+ member.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
28
+ invalid(`unsafe entry path: ${JSON.stringify(value)}`);
29
+ }
30
+ }
31
+ function crc32(bytes) {
32
+ let crc = 0xffffffff;
33
+ for (const byte of bytes) {
34
+ crc ^= byte;
35
+ for (let bit = 0; bit < 8; bit++) {
36
+ crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
37
+ }
38
+ }
39
+ return (crc ^ 0xffffffff) >>> 0;
40
+ }
41
+ /** Bounded ZIP reader used for both local reports and untrusted uploaded bytes. */
2
42
  export class SimpleZipReader {
3
43
  constructor(buffer) {
4
44
  this.buffer = buffer;
45
+ if (buffer.byteLength > MAX_ARCHIVE_BYTES)
46
+ invalid('archive exceeds the size limit');
5
47
  }
6
48
  listEntries() {
7
- return this.readCentralDirectory().map(({ localHeaderOffset: _offset, ...entry }) => entry);
49
+ return this.readCentralDirectory().map((entry) => ({
50
+ path: entry.path,
51
+ compressedSize: entry.compressedSize,
52
+ uncompressedSize: entry.uncompressedSize,
53
+ compressionMethod: entry.compressionMethod,
54
+ isDirectory: entry.isDirectory,
55
+ externalAttributes: entry.externalAttributes,
56
+ creatorOs: entry.creatorOs,
57
+ encrypted: entry.encrypted,
58
+ crc32: entry.crc32,
59
+ }));
8
60
  }
9
61
  readEntryText(entryPath) {
62
+ return this.readEntry(entryPath)?.toString('utf-8') ?? null;
63
+ }
64
+ readEntry(entryPath) {
10
65
  const entry = this.readCentralDirectory().find((item) => item.path === entryPath);
11
66
  if (!entry || entry.isDirectory)
12
67
  return null;
13
- const data = this.readEntryData(entry);
14
- return data.toString('utf-8');
68
+ return this.readEntryData(entry);
15
69
  }
16
70
  readCentralDirectory() {
17
71
  if (this.entriesCache)
18
72
  return this.entriesCache;
19
73
  const eocdOffset = this.findEndOfCentralDirectory();
20
- if (eocdOffset < 0) {
21
- throw new Error('Invalid ZIP: end of central directory not found');
74
+ if (eocdOffset < 0)
75
+ invalid('end of central directory not found');
76
+ this.requireRange(eocdOffset, 22);
77
+ if (this.buffer.readUInt16LE(eocdOffset + 4) !== 0 ||
78
+ this.buffer.readUInt16LE(eocdOffset + 6) !== 0) {
79
+ invalid('multi-disk archives are not supported');
22
80
  }
23
81
  const totalEntries = this.buffer.readUInt16LE(eocdOffset + 10);
82
+ if (totalEntries !== this.buffer.readUInt16LE(eocdOffset + 8) || totalEntries > MAX_ENTRIES) {
83
+ invalid('entry count is inconsistent or exceeds the limit');
84
+ }
85
+ const centralDirectorySize = this.buffer.readUInt32LE(eocdOffset + 12);
24
86
  const centralDirectoryOffset = this.buffer.readUInt32LE(eocdOffset + 16);
87
+ if (centralDirectoryOffset === 0xffffffff ||
88
+ centralDirectorySize === 0xffffffff ||
89
+ centralDirectoryOffset + centralDirectorySize !== eocdOffset) {
90
+ invalid('ZIP64 or inconsistent central directory');
91
+ }
92
+ this.requireRange(centralDirectoryOffset, centralDirectorySize);
25
93
  const entries = [];
94
+ const exactPaths = new Set();
95
+ const foldedPaths = new Set();
26
96
  let offset = centralDirectoryOffset;
27
- for (let i = 0; i < totalEntries; i++) {
28
- const signature = this.buffer.readUInt32LE(offset);
29
- if (signature !== 0x02014b50) {
30
- throw new Error(`Invalid ZIP: bad central directory signature at ${offset}`);
97
+ let totalUncompressed = 0;
98
+ for (let index = 0; index < totalEntries; index++) {
99
+ this.requireRange(offset, 46);
100
+ if (this.buffer.readUInt32LE(offset) !== 0x02014b50) {
101
+ invalid(`bad central directory signature at ${offset}`);
31
102
  }
103
+ const creatorOs = this.buffer.readUInt8(offset + 5);
104
+ const flags = this.buffer.readUInt16LE(offset + 8);
32
105
  const compressionMethod = this.buffer.readUInt16LE(offset + 10);
106
+ const crc = this.buffer.readUInt32LE(offset + 16);
33
107
  const compressedSize = this.buffer.readUInt32LE(offset + 20);
34
108
  const uncompressedSize = this.buffer.readUInt32LE(offset + 24);
35
109
  const fileNameLength = this.buffer.readUInt16LE(offset + 28);
36
110
  const extraLength = this.buffer.readUInt16LE(offset + 30);
37
111
  const commentLength = this.buffer.readUInt16LE(offset + 32);
112
+ const externalAttributes = this.buffer.readUInt32LE(offset + 38);
38
113
  const localHeaderOffset = this.buffer.readUInt32LE(offset + 42);
39
- const fileNameStart = offset + 46;
40
- const entryPath = this.buffer
41
- .subarray(fileNameStart, fileNameStart + fileNameLength)
42
- .toString('utf-8')
43
- .replace(/\\/g, '/');
114
+ const entryLength = 46 + fileNameLength + extraLength + commentLength;
115
+ this.requireRange(offset, entryLength);
116
+ if (compressedSize === 0xffffffff ||
117
+ uncompressedSize === 0xffffffff ||
118
+ localHeaderOffset === 0xffffffff) {
119
+ invalid('ZIP64 entries are not supported');
120
+ }
121
+ const entryPath = decode(this.buffer.subarray(offset + 46, offset + 46 + fileNameLength));
122
+ const isDirectory = entryPath.endsWith('/');
123
+ validateEntryPath(entryPath, isDirectory);
124
+ const comparablePath = isDirectory ? entryPath.slice(0, -1) : entryPath;
125
+ const folded = comparablePath.normalize('NFC').toLowerCase();
126
+ if (exactPaths.has(comparablePath))
127
+ invalid(`duplicate entry path: ${comparablePath}`);
128
+ if (foldedPaths.has(folded))
129
+ invalid(`case-conflicting entry path: ${comparablePath}`);
130
+ exactPaths.add(comparablePath);
131
+ foldedPaths.add(folded);
132
+ const fileType = externalAttributes >>> 16;
133
+ if (!isDirectory && fileType !== 0 && (fileType & 0o170000) !== 0o100000) {
134
+ invalid(`entry is not a regular file: ${entryPath}`);
135
+ }
136
+ if (uncompressedSize > MAX_ENTRY_BYTES)
137
+ invalid(`entry exceeds the size limit: ${entryPath}`);
138
+ totalUncompressed += uncompressedSize;
139
+ if (totalUncompressed > MAX_TOTAL_BYTES)
140
+ invalid('total uncompressed size exceeds the limit');
141
+ if (uncompressedSize > 64 * 1024 &&
142
+ uncompressedSize / Math.max(1, compressedSize) > MAX_COMPRESSION_RATIO) {
143
+ invalid(`compression ratio exceeds the limit: ${entryPath}`);
144
+ }
44
145
  entries.push({
45
146
  path: entryPath,
46
147
  compressedSize,
47
148
  uncompressedSize,
48
149
  compressionMethod,
150
+ isDirectory,
151
+ externalAttributes,
152
+ creatorOs,
153
+ encrypted: (flags & 1) !== 0,
154
+ crc32: crc,
49
155
  localHeaderOffset,
50
- isDirectory: entryPath.endsWith('/'),
51
156
  });
52
- offset = fileNameStart + fileNameLength + extraLength + commentLength;
157
+ offset += entryLength;
53
158
  }
159
+ if (offset !== eocdOffset)
160
+ invalid('central directory size mismatch');
54
161
  this.entriesCache = entries;
55
162
  return entries;
56
163
  }
57
164
  readEntryData(entry) {
165
+ if (entry.encrypted)
166
+ invalid(`encrypted entry is not supported: ${entry.path}`);
167
+ if (entry.compressionMethod !== 0 && entry.compressionMethod !== 8) {
168
+ invalid(`unsupported compression method ${entry.compressionMethod}: ${entry.path}`);
169
+ }
58
170
  const offset = entry.localHeaderOffset;
59
- const signature = this.buffer.readUInt32LE(offset);
60
- if (signature !== 0x04034b50) {
61
- throw new Error(`Invalid ZIP: bad local header signature at ${offset}`);
171
+ this.requireRange(offset, 30);
172
+ if (this.buffer.readUInt32LE(offset) !== 0x04034b50) {
173
+ invalid(`bad local header signature at ${offset}`);
174
+ }
175
+ if (this.buffer.readUInt16LE(offset + 8) !== entry.compressionMethod) {
176
+ invalid(`local compression method differs: ${entry.path}`);
62
177
  }
63
178
  const fileNameLength = this.buffer.readUInt16LE(offset + 26);
64
179
  const extraLength = this.buffer.readUInt16LE(offset + 28);
180
+ this.requireRange(offset, 30 + fileNameLength + extraLength);
181
+ const localPath = decode(this.buffer.subarray(offset + 30, offset + 30 + fileNameLength));
182
+ if (localPath !== entry.path)
183
+ invalid(`local filename differs: ${entry.path}`);
65
184
  const dataStart = offset + 30 + fileNameLength + extraLength;
185
+ this.requireRange(dataStart, entry.compressedSize);
66
186
  const compressed = this.buffer.subarray(dataStart, dataStart + entry.compressedSize);
67
- if (entry.compressionMethod === 0) {
68
- return Buffer.from(compressed);
187
+ let data;
188
+ try {
189
+ data = entry.compressionMethod === 0
190
+ ? Buffer.from(compressed)
191
+ : inflateRawSync(compressed, { maxOutputLength: entry.uncompressedSize + 1 });
69
192
  }
70
- if (entry.compressionMethod === 8) {
71
- return inflateRawSync(compressed);
193
+ catch {
194
+ invalid(`entry cannot be inflated safely: ${entry.path}`);
72
195
  }
73
- throw new Error(`Unsupported ZIP compression method: ${entry.compressionMethod}`);
196
+ if (data.byteLength !== entry.uncompressedSize)
197
+ invalid(`entry size differs: ${entry.path}`);
198
+ if (crc32(data) !== entry.crc32)
199
+ invalid(`entry CRC differs: ${entry.path}`);
200
+ return data;
74
201
  }
75
202
  findEndOfCentralDirectory() {
76
203
  const minOffset = Math.max(0, this.buffer.length - 0xffff - 22);
77
204
  for (let offset = this.buffer.length - 22; offset >= minOffset; offset--) {
78
- if (this.buffer.readUInt32LE(offset) === 0x06054b50) {
205
+ if (this.buffer.readUInt32LE(offset) === 0x06054b50 &&
206
+ offset + 22 + this.buffer.readUInt16LE(offset + 20) === this.buffer.length) {
79
207
  return offset;
80
208
  }
81
209
  }
82
210
  return -1;
83
211
  }
212
+ requireRange(offset, length) {
213
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || offset + length > this.buffer.length) {
214
+ invalid('truncated archive');
215
+ }
216
+ }
84
217
  }
@@ -1,5 +1,6 @@
1
1
  import { type UserConfig } from 'vite';
2
2
  import type { Platform, BuildOptions, BaseBuildMetadata } from '../types.js';
3
+ import { type ViteWorkspace } from './workspace.js';
3
4
  /**
4
5
  * 通用 Vite 配置构建器(外部引擎专用)
5
6
  *
@@ -16,9 +17,10 @@ export declare class GenericViteConfigBuilder {
16
17
  private platform;
17
18
  private options;
18
19
  private baseBuildMetadata;
20
+ private workspace?;
19
21
  private finalOutputDir;
20
22
  private viteOutputDir;
21
- constructor(baseBuildDir: string, platform: Platform, options: BuildOptions, baseBuildMetadata: BaseBuildMetadata);
23
+ constructor(baseBuildDir: string, platform: Platform, options: BuildOptions, baseBuildMetadata: BaseBuildMetadata, workspace?: ViteWorkspace | undefined);
22
24
  /**
23
25
  * 创建 Vite 配置
24
26
  */