@playcraft/build 0.1.91 → 0.1.92-test

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/base-builder.js +2 -41
  2. package/dist/engines/engine-detector.js +0 -4
  3. package/dist/engines/generic-adapter.js +19 -14
  4. package/dist/index.d.ts +4 -19
  5. package/dist/index.js +2 -11
  6. package/dist/platforms/adikteev.js +0 -1
  7. package/dist/platforms/applovin.js +0 -1
  8. package/dist/platforms/base.js +2 -2
  9. package/dist/platforms/bigo.js +0 -1
  10. package/dist/platforms/facebook.js +0 -1
  11. package/dist/platforms/google.js +0 -1
  12. package/dist/platforms/inmobi.js +0 -1
  13. package/dist/platforms/ironsource.js +0 -1
  14. package/dist/platforms/liftoff.js +0 -1
  15. package/dist/platforms/mintegral.js +0 -1
  16. package/dist/platforms/moloco.js +0 -1
  17. package/dist/platforms/playcraft.js +0 -1
  18. package/dist/platforms/remerge.js +0 -1
  19. package/dist/platforms/snapchat.js +0 -1
  20. package/dist/platforms/tiktok.js +0 -1
  21. package/dist/platforms/unity.js +0 -1
  22. package/dist/types.d.ts +0 -5
  23. package/dist/validation/html-validator.d.ts +0 -5
  24. package/dist/validation/html-validator.js +17 -19
  25. package/dist/validation/index.d.ts +0 -4
  26. package/dist/validation/index.js +0 -4
  27. package/dist/validation/package-validator.d.ts +0 -2
  28. package/dist/validation/package-validator.js +64 -25
  29. package/dist/validation/profiles.d.ts +1 -13
  30. package/dist/validation/profiles.js +0 -27
  31. package/dist/validation/source-scanner.d.ts +0 -11
  32. package/dist/validation/source-scanner.js +2 -32
  33. package/dist/validation/types.d.ts +2 -155
  34. package/dist/validation/types.js +1 -1
  35. package/dist/validation/validation-runner.d.ts +2 -22
  36. package/dist/validation/validation-runner.js +3 -68
  37. package/dist/validation/zip-reader.d.ts +0 -7
  38. package/dist/validation/zip-reader.js +26 -159
  39. package/dist/vite/config-builder-generic.d.ts +1 -3
  40. package/dist/vite/config-builder-generic.js +7 -9
  41. package/dist/vite/config-builder.js +1 -1
  42. package/dist/vite/plugin-platform.js +54 -30
  43. package/dist/vite/plugin-source-builder.d.ts +14 -2
  44. package/dist/vite/plugin-source-builder.js +997 -61
  45. package/dist/vite-builder.d.ts +5 -4
  46. package/dist/vite-builder.js +34 -33
  47. package/package.json +4 -16
  48. package/dist/audio-source-files.d.ts +0 -5
  49. package/dist/audio-source-files.js +0 -135
  50. package/dist/delivery/agent-build-runner.d.ts +0 -44
  51. package/dist/delivery/agent-build-runner.js +0 -365
  52. package/dist/delivery/agent-build-source.d.ts +0 -8
  53. package/dist/delivery/agent-build-source.js +0 -25
  54. package/dist/delivery/artifact-descriptor.d.ts +0 -31
  55. package/dist/delivery/artifact-descriptor.js +0 -237
  56. package/dist/delivery/artifact-package.d.ts +0 -43
  57. package/dist/delivery/artifact-package.js +0 -283
  58. package/dist/delivery/build-plan.d.ts +0 -4
  59. package/dist/delivery/build-plan.js +0 -189
  60. package/dist/delivery/build-plan.types.d.ts +0 -51
  61. package/dist/delivery/build-plan.types.js +0 -1
  62. package/dist/delivery/command-isolation.d.ts +0 -7
  63. package/dist/delivery/command-isolation.js +0 -252
  64. package/dist/delivery/commands.d.ts +0 -5
  65. package/dist/delivery/commands.js +0 -137
  66. package/dist/delivery/files.d.ts +0 -9
  67. package/dist/delivery/files.js +0 -144
  68. package/dist/delivery/git-source-fingerprint.d.ts +0 -2
  69. package/dist/delivery/git-source-fingerprint.js +0 -58
  70. package/dist/delivery/isolated-source.d.ts +0 -5
  71. package/dist/delivery/isolated-source.js +0 -126
  72. package/dist/delivery/output-publication.d.ts +0 -21
  73. package/dist/delivery/output-publication.js +0 -444
  74. package/dist/delivery/project-delivery.d.ts +0 -6
  75. package/dist/delivery/project-delivery.js +0 -287
  76. package/dist/delivery/recipe-build-plan.d.ts +0 -4
  77. package/dist/delivery/recipe-build-plan.js +0 -53
  78. package/dist/delivery/recipe.d.ts +0 -20
  79. package/dist/delivery/recipe.js +0 -211
  80. package/dist/delivery/safe-path.d.ts +0 -2
  81. package/dist/delivery/safe-path.js +0 -18
  82. package/dist/delivery/types.d.ts +0 -76
  83. package/dist/delivery/types.js +0 -1
  84. package/dist/production-animation-presence.d.ts +0 -2
  85. package/dist/production-animation-presence.js +0 -146
  86. package/dist/production-inputs.d.ts +0 -30
  87. package/dist/production-inputs.js +0 -262
  88. package/dist/production-source-paths.d.ts +0 -5
  89. package/dist/production-source-paths.js +0 -27
  90. package/dist/validation/artifact-qa.d.ts +0 -44
  91. package/dist/validation/artifact-qa.js +0 -170
  92. package/dist/validation/artifact-rules.d.ts +0 -28
  93. package/dist/validation/artifact-rules.js +0 -440
  94. package/dist/validation/artifact.d.ts +0 -14
  95. package/dist/validation/artifact.js +0 -188
  96. package/dist/validation/runtime-load.d.ts +0 -89
  97. package/dist/validation/runtime-load.js +0 -654
  98. package/dist/vite/source-builder-asset-paths.d.ts +0 -25
  99. package/dist/vite/source-builder-asset-paths.js +0 -154
  100. package/dist/vite/source-builder-esm.d.ts +0 -7
  101. package/dist/vite/source-builder-esm.js +0 -877
  102. package/dist/vite/source-builder-types.d.ts +0 -14
  103. package/dist/vite/source-builder-types.js +0 -1
  104. package/dist/vite/workspace.d.ts +0 -6
  105. package/dist/vite/workspace.js +0 -41
  106. package/dist/workspace-css-imports.d.ts +0 -2
  107. package/dist/workspace-css-imports.js +0 -139
  108. package/dist/workspace-model-source.d.ts +0 -14
  109. package/dist/workspace-model-source.js +0 -184
  110. package/dist/workspace-public-imports.d.ts +0 -11
  111. package/dist/workspace-public-imports.js +0 -232
  112. package/dist/workspace-public-source.d.ts +0 -15
  113. package/dist/workspace-public-source.js +0 -564
@@ -1,654 +0,0 @@
1
- import path from 'node:path';
2
- import { ranStageReport } from './validation-runner.js';
3
- /**
4
- * `runtime-load` rules: open the artifact in a headless browser without playing it. All network
5
- * access outside the artifact is blocked, store-opening calls are recorded instead of followed,
6
- * and the CTA chain is exercised through whichever CTA entry the artifact has: adsdk's
7
- * `window.PlayableSDK`, or the platform-injected CTA adapter's `window.PlayCraftCTA`. Either is
8
- * accepted; what matters is that the CTA reaches the channel's store API.
9
- */
10
- export const RUNTIME_LOAD_RULE_IDS = {
11
- pageLoads: 'common.runtime.page.loads',
12
- requests: 'common.runtime.requests.resolved',
13
- csp: 'common.runtime.csp.clean',
14
- errors: 'common.runtime.errors.none',
15
- firstFrame: 'common.runtime.first-frame.content',
16
- ctaEntry: 'common.runtime.cta.entry',
17
- startSignal: 'common.runtime.start-signal.sent',
18
- noAutoRedirect: 'common.runtime.redirect.none-on-load',
19
- ctaRouted: 'common.runtime.cta.routed',
20
- ctaStoreUrl: 'common.runtime.cta.store-url',
21
- viewportCanvasFit: 'common.runtime.viewport.canvas-fit',
22
- viewportOverflow: 'common.runtime.viewport.no-overflow',
23
- viewportErrors: 'common.runtime.viewport.errors',
24
- viewportContent: 'common.runtime.viewport.content',
25
- };
26
- export const RUNTIME_ORIGIN = 'http://artifact.playcraft-qa.test';
27
- /** Same-origin artifact files and inline data only; no network, workers or frames. */
28
- export const RUNTIME_CSP = [
29
- "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob:",
30
- "img-src 'self' data: blob:",
31
- "media-src 'self' data: blob:",
32
- "font-src 'self' data:",
33
- "connect-src 'self' data: blob:",
34
- "worker-src 'none'",
35
- "frame-src 'none'",
36
- ].join('; ');
37
- const DEFAULT_VIEWPORT = {
38
- name: 'phone portrait 393×852',
39
- viewport: { width: 393, height: 852, deviceScaleFactor: 2, isMobile: true, hasTouch: true },
40
- };
41
- const USER_AGENTS = {
42
- ios: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
43
- android: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36',
44
- };
45
- const STORE_HOSTS = {
46
- ios: /^https:\/\/(?:apps|itunes)\.apple\.com\//i,
47
- android: /^https:\/\/play\.google\.com\//i,
48
- };
49
- const CTA_CALLS = {
50
- adsdk: 'window.PlayableSDK.playcraftInstall()',
51
- adapter: 'window.PlayCraftCTA.jump()',
52
- };
53
- /** APIs that receive the store URL as an argument, so the URL can be checked. */
54
- const URL_APIS = new Set(['window.open', 'mraid.open', 'BGY_MRAID.open', 'NUC.trigger.convert']);
55
- /**
56
- * The store-opening API adsdk calls for each profile (its `AD_NETWORK` branches). Profiles not
57
- * listed accept any channel API.
58
- */
59
- const EXPECTED_CTA_APIS = {
60
- playcraft: ['window.open'],
61
- applovin: ['mraid.open'],
62
- unity: ['mraid.open'],
63
- inmobi: ['mraid.open'],
64
- adikteev: ['mraid.open'],
65
- facebook: ['FbPlayableAd.onCTAClick'],
66
- moloco: ['FbPlayableAd.onCTAClick', 'mraid.open'],
67
- bigo: ['BGY_MRAID.open'],
68
- google: ['ExitApi.exit'],
69
- snapchat: ['ScPlayableAd.onCTAClick'],
70
- tiktok: ['openAppStore'],
71
- mintegral: ['install'],
72
- ironsource: ['dapi.openStoreUrl', 'mraid.open'],
73
- };
74
- /**
75
- * Without a channel container, the CTA adapter falls back to `postMessage('download')`, and to
76
- * `window.open` only when it has a store link.
77
- */
78
- const ADAPTER_PLAYCRAFT_APIS = ['window.open', 'postMessage:download'];
79
- /**
80
- * Channel globals the probe may stub. The CTA adapter picks its channel by which of these exists,
81
- * so a channel profile only gets the globals of its own store APIs; adsdk is unaffected because it
82
- * routes by build-time constants. Profiles without expected APIs get every stub.
83
- */
84
- const CHANNEL_GLOBALS = [
85
- 'FbPlayableAd',
86
- 'mraid',
87
- 'dapi',
88
- 'ExitApi',
89
- 'BGY_MRAID',
90
- 'ScPlayableAd',
91
- 'openAppStore',
92
- 'install',
93
- 'TJ_API',
94
- 'NUC',
95
- 'smxTracking',
96
- ];
97
- export function channelGlobalsFor(profile) {
98
- if (profile === 'playcraft')
99
- return [];
100
- const expected = EXPECTED_CTA_APIS[profile];
101
- if (!expected)
102
- return [...CHANNEL_GLOBALS];
103
- return [...new Set(expected.map((api) => api.split('.')[0]))];
104
- }
105
- const RULES = {
106
- [RUNTIME_LOAD_RULE_IDS.pageLoads]: {
107
- title: 'Artifact opens in a mobile browser',
108
- severity: 'error',
109
- recommendation: 'Fix the entry HTML so it loads without network access.',
110
- confidence: 'high',
111
- },
112
- [RUNTIME_LOAD_RULE_IDS.requests]: {
113
- title: 'Every request during load is served from the artifact',
114
- severity: 'error',
115
- recommendation: 'Include missing files in the build output, or inline them; remote requests are not allowed in ad containers.',
116
- confidence: 'high',
117
- },
118
- [RUNTIME_LOAD_RULE_IDS.csp]: {
119
- title: 'No content security policy violations',
120
- severity: 'error',
121
- recommendation: 'Remove remote resources, workers and frames; keep images, media and fonts inline or inside the artifact.',
122
- confidence: 'high',
123
- },
124
- [RUNTIME_LOAD_RULE_IDS.errors]: {
125
- title: 'No console errors or uncaught exceptions during load',
126
- severity: 'error',
127
- recommendation: 'Fix the reported error; the stack and message point to the failing code.',
128
- confidence: 'high',
129
- },
130
- [RUNTIME_LOAD_RULE_IDS.firstFrame]: {
131
- title: 'First screen shows content',
132
- severity: 'error',
133
- recommendation: 'The page renders a single flat color; check that the game starts and draws after load.',
134
- confidence: 'medium',
135
- },
136
- [RUNTIME_LOAD_RULE_IDS.ctaEntry]: {
137
- title: 'A CTA entry is available (adsdk window.PlayableSDK or the platform CTA adapter window.PlayCraftCTA)',
138
- severity: 'error',
139
- recommendation: 'Build with playcraft build so the platform CTA adapter is injected, or bundle @playcraft/adsdk and call sdk.playcraftInit; adsdk also sends the lifecycle signals.',
140
- confidence: 'high',
141
- },
142
- [RUNTIME_LOAD_RULE_IDS.startSignal]: {
143
- title: 'Game sends the start signal after loading',
144
- severity: 'error',
145
- recommendation: 'Call sdk.playcraftStart() when the first frame can render.',
146
- confidence: 'high',
147
- },
148
- [RUNTIME_LOAD_RULE_IDS.noAutoRedirect]: {
149
- title: 'No store redirect without a user tap',
150
- severity: 'error',
151
- recommendation: 'Open the store only from a CTA tap through sdk.playcraftInstall().',
152
- confidence: 'high',
153
- },
154
- [RUNTIME_LOAD_RULE_IDS.ctaRouted]: {
155
- title: 'CTA reaches the channel store API',
156
- severity: 'error',
157
- recommendation: 'With adsdk, call sdk.playcraftStart() before the CTA is used and build the package for this channel so adsdk routes to its API; with the CTA adapter, call window.PlayCraftCTA.jump() from the CTA button.',
158
- confidence: 'high',
159
- },
160
- [RUNTIME_LOAD_RULE_IDS.ctaStoreUrl]: {
161
- title: 'CTA opens the right store link on iOS and Android',
162
- severity: 'error',
163
- recommendation: 'Set the App Store and Google Play links for the export (adsdk APP_STORE_URL / GOOGLE_PLAY_URL, or the store links the CTA adapter reads from window.__PLAYCRAFT_STORE_URLS__).',
164
- confidence: 'high',
165
- },
166
- [RUNTIME_LOAD_RULE_IDS.viewportCanvasFit]: {
167
- title: 'Game canvas stays inside the screen and fills it in every viewport',
168
- severity: 'error',
169
- recommendation: 'Size the canvas from the viewport (or the adsdk init size) and rescale on resize, e.g. a FIT scale mode.',
170
- confidence: 'medium',
171
- },
172
- [RUNTIME_LOAD_RULE_IDS.viewportOverflow]: {
173
- title: 'Page does not scroll or overflow the screen in any viewport',
174
- severity: 'error',
175
- recommendation: 'Remove fixed pixel widths and heights; set html and body to the viewport size with overflow hidden.',
176
- confidence: 'high',
177
- },
178
- [RUNTIME_LOAD_RULE_IDS.viewportErrors]: {
179
- title: 'Loads without errors in every viewport',
180
- severity: 'error',
181
- recommendation: 'Fix the error raised only at that screen size or orientation.',
182
- confidence: 'high',
183
- },
184
- [RUNTIME_LOAD_RULE_IDS.viewportContent]: {
185
- title: 'First screen shows content in every viewport',
186
- severity: 'error',
187
- recommendation: 'Check the layout and start-up path for that screen size or orientation.',
188
- confidence: 'medium',
189
- },
190
- };
191
- /** `runtime-load` stage: opens the artifact in a headless browser. Needs the artifact and a driver. */
192
- export async function runRuntimeLoadStage(artifact, options) {
193
- const startedAt = Date.now();
194
- const results = await runRuntimeLoadChecks(artifact, options);
195
- return ranStageReport('runtime-load', startedAt, results, {
196
- details: { viewports: (options.viewports ?? [DEFAULT_VIEWPORT]).map((item) => item.name) },
197
- });
198
- }
199
- export async function runRuntimeLoadChecks(artifact, options) {
200
- const [main = DEFAULT_VIEWPORT, ...others] = options.viewports?.length
201
- ? options.viewports
202
- : [DEFAULT_VIEWPORT];
203
- const ios = await runPass(artifact, options, 'ios', main, true);
204
- const results = [];
205
- results.push(result(RUNTIME_LOAD_RULE_IDS.pageLoads, ios.page.loaded, {
206
- ...(ios.page.loadError ? { evidence: ios.page.loadError } : {}),
207
- }));
208
- if (!ios.page.loaded || !ios.beforeClick)
209
- return results;
210
- const requestProblems = [
211
- ...ios.events.failedRequests
212
- // Browsers request a favicon on their own; artifacts are not expected to ship one.
213
- .filter((item) => relative(item.url) !== 'favicon.ico')
214
- .map((item) => `${relative(item.url)} (${item.reason})`),
215
- ...ios.events.blockedRequests.map((url) => `${url} (blocked: outside the artifact)`),
216
- ];
217
- results.push(listResult(RUNTIME_LOAD_RULE_IDS.requests, requestProblems));
218
- results.push(listResult(RUNTIME_LOAD_RULE_IDS.csp, ios.beforeClick.csp.map((item) => `${item.violatedDirective} ${item.blockedURI}`)));
219
- results.push(listResult(RUNTIME_LOAD_RULE_IDS.errors, pageErrors(ios)));
220
- results.push(await firstFrameResult(ios.screenshot));
221
- const preClick = [
222
- ...ios.beforeClick.calls.map((call) => `${call.api}${call.url ? ` ${call.url}` : ''}`),
223
- ...ios.events.navigationAttempts.map((url) => `navigation ${url}`),
224
- ];
225
- results.push(listResult(RUNTIME_LOAD_RULE_IDS.noAutoRedirect, preClick));
226
- const extra = [];
227
- for (const preset of others)
228
- extra.push(await runPass(artifact, options, 'ios', preset, false));
229
- results.push(...(await viewportResults([ios, ...extra], extra)));
230
- const entry = ctaEntryOf(ios.beforeClick);
231
- results.push(result(RUNTIME_LOAD_RULE_IDS.ctaEntry, Boolean(entry), {
232
- evidence: entry
233
- ? `CTA through ${CTA_CALLS[entry]}`
234
- : 'neither window.PlayableSDK nor window.PlayCraftCTA was found',
235
- }));
236
- if (!entry) {
237
- for (const id of [
238
- RUNTIME_LOAD_RULE_IDS.startSignal,
239
- RUNTIME_LOAD_RULE_IDS.ctaRouted,
240
- RUNTIME_LOAD_RULE_IDS.ctaStoreUrl,
241
- ])
242
- results.push(result(id, false, { status: 'inconclusive', evidence: 'no CTA entry' }));
243
- return results;
244
- }
245
- if (entry === 'adsdk') {
246
- const started = ios.beforeClick.events.some((event) => event.name === 'playcraftStart');
247
- results.push(result(RUNTIME_LOAD_RULE_IDS.startSignal, started, {
248
- evidence: `adsdk events before any tap: ${eventNames(ios.beforeClick) || 'none'}`,
249
- }));
250
- }
251
- else
252
- results.push(result(RUNTIME_LOAD_RULE_IDS.startSignal, false, {
253
- status: 'not-applicable',
254
- evidence: 'no adsdk: the platform CTA adapter sends no lifecycle signals',
255
- }));
256
- const android = await runPass(artifact, options, 'android', main, true);
257
- results.push(ctaRoutedResult(options.profile, ios));
258
- results.push(ctaStoreUrlResult(ios, android));
259
- return results;
260
- }
261
- async function runPass(artifact, options, platform, preset, cta) {
262
- const viewport = preset.viewport;
263
- const page = await options.driver.open({
264
- origin: RUNTIME_ORIGIN,
265
- entryPath: artifact.entry,
266
- viewport,
267
- userAgent: USER_AGENTS[platform],
268
- initScript: buildRuntimeProbeScript({ channelGlobals: channelGlobalsFor(options.profile) }),
269
- contentSecurityPolicy: RUNTIME_CSP,
270
- timeoutMs: options.timeoutMs ?? 15000,
271
- resolve: async (pathname) => {
272
- const body = await artifact.readBuffer(pathname.replace(/^\/+/, ''));
273
- return body ? { body, contentType: contentType(pathname) } : null;
274
- },
275
- });
276
- try {
277
- if (!page.loaded)
278
- return {
279
- preset,
280
- page: { loaded: false, ...(page.loadError ? { loadError: page.loadError } : {}) },
281
- events: page.events(),
282
- };
283
- await page.wait(options.settleMs ?? 1500);
284
- const beforeClick = await probeState(page);
285
- const layout = await page.evaluate(LAYOUT_PROBE);
286
- const screenshot = await page.screenshot();
287
- // Load-time events only: errors or navigations the probe's own CTA call causes are not load problems.
288
- const events = page.events();
289
- let afterInstall;
290
- let ctaError;
291
- const entry = ctaEntryOf(beforeClick);
292
- if (cta && entry) {
293
- // A tap first, for channels whose SDK ignores a CTA before the first interaction.
294
- await page.click(viewport.width / 2, viewport.height / 2);
295
- await page.wait(150);
296
- ctaError = await page.evaluate(`(() => { try { ${CTA_CALLS[entry]}; return undefined; } catch (error) { return String(error && error.message || error); } })()`);
297
- await page.wait(1200);
298
- afterInstall = await probeState(page);
299
- }
300
- return {
301
- preset,
302
- layout,
303
- page: { loaded: true },
304
- beforeClick,
305
- ...(afterInstall ? { afterInstall } : {}),
306
- events,
307
- screenshot,
308
- ...(cta && entry ? { entry } : {}),
309
- ...(ctaError ? { ctaError } : {}),
310
- };
311
- }
312
- finally {
313
- await page.close();
314
- }
315
- }
316
- function probeState(page) {
317
- return page.evaluate(`JSON.parse(JSON.stringify(Object.assign({}, window.__PLAYCRAFT_QA__, {
318
- adapter: Boolean(window.PlayCraftCTA && typeof window.PlayCraftCTA.jump === 'function'),
319
- storeUrls: Boolean(window.__PLAYCRAFT_STORE_URLS__),
320
- })))`);
321
- }
322
- /** adsdk wins when both are present: it is the fuller path and also carries lifecycle signals. */
323
- function ctaEntryOf(state) {
324
- if (state.sdk)
325
- return 'adsdk';
326
- if (state.adapter)
327
- return 'adapter';
328
- return undefined;
329
- }
330
- /** Calls made after the tap: the game's own CTA handler, or the probe's CTA call. */
331
- function callsAfterClick(pass) {
332
- const before = pass.beforeClick?.calls.length ?? 0;
333
- return pass.afterInstall?.calls.slice(before) ?? [];
334
- }
335
- function ctaRoutedResult(profile, pass) {
336
- const calls = callsAfterClick(pass);
337
- const expected = profile === 'playcraft' && pass.entry === 'adapter'
338
- ? ADAPTER_PLAYCRAFT_APIS
339
- : EXPECTED_CTA_APIS[profile];
340
- const routed = calls.find((call) => expected ? expected.includes(call.api) : call.api !== 'window.open');
341
- const seen = calls.map((call) => call.api).join(', ') || 'no store-opening call';
342
- const call = pass.entry ? CTA_CALLS[pass.entry] : 'the CTA';
343
- return result(RUNTIME_LOAD_RULE_IDS.ctaRouted, Boolean(routed), {
344
- evidence: [
345
- `called ${call}; expected ${expected ? expected.join(' or ') : 'a channel SDK API'}; recorded ${seen}`,
346
- pass.ctaError ? `${call} threw: ${pass.ctaError}` : '',
347
- pass.entry === 'adsdk'
348
- ? `adsdk events: ${pass.afterInstall ? eventNames(pass.afterInstall) : 'none'}`
349
- : '',
350
- ]
351
- .filter(Boolean)
352
- .join('; '),
353
- });
354
- }
355
- function ctaStoreUrlResult(ios, android) {
356
- // The adapter only knows the store links the export writes into the page; the game may still
357
- // pass its own link to jump({ url }), which only a real tap on its CTA button would show.
358
- if (ios.entry === 'adapter' && !ios.beforeClick?.storeUrls)
359
- return result(RUNTIME_LOAD_RULE_IDS.ctaStoreUrl, false, {
360
- status: 'inconclusive',
361
- evidence: 'store links are set at export: this artifact has no window.__PLAYCRAFT_STORE_URLS__, and the link the game passes to PlayCraftCTA.jump({ url }) is only seen when its CTA button is tapped',
362
- });
363
- const check = (pass, platform) => {
364
- const call = callsAfterClick(pass).find((item) => URL_APIS.has(item.api));
365
- if (!call)
366
- return { known: false, ok: true, text: `${platform}: no URL-carrying call` };
367
- const ok = Boolean(call.url && STORE_HOSTS[platform].test(call.url));
368
- return { known: true, ok, text: `${platform}: ${call.api} ${call.url || '(empty URL)'}` };
369
- };
370
- const results = [check(ios, 'ios'), check(android, 'android')];
371
- const evidence = results.map((item) => item.text).join('; ');
372
- if (!results.some((item) => item.known))
373
- return result(RUNTIME_LOAD_RULE_IDS.ctaStoreUrl, false, {
374
- status: 'not-applicable',
375
- evidence: `${evidence}; the channel API opens the store itself`,
376
- });
377
- return result(RUNTIME_LOAD_RULE_IDS.ctaStoreUrl, results.every((item) => item.ok), { evidence });
378
- }
379
- async function firstFrameResult(screenshot) {
380
- if (!screenshot)
381
- return result(RUNTIME_LOAD_RULE_IDS.firstFrame, false, {
382
- status: 'inconclusive',
383
- evidence: 'no screenshot',
384
- });
385
- const deviation = await frameDeviation(screenshot);
386
- return result(RUNTIME_LOAD_RULE_IDS.firstFrame, deviation > 2, {
387
- evidence: `max channel standard deviation ${deviation.toFixed(2)}`,
388
- });
389
- }
390
- /** Largest RGB standard deviation of a screenshot; near zero means a single flat color. */
391
- async function frameDeviation(screenshot) {
392
- const sharp = (await import('sharp')).default;
393
- const stats = await sharp(screenshot).stats();
394
- return Math.max(...stats.channels.slice(0, 3).map((channel) => channel.stdev));
395
- }
396
- /** Page errors and console errors; blocked requests and CSP violations have their own rules. */
397
- function pageErrors(pass) {
398
- return [
399
- ...pass.events.pageErrors,
400
- ...pass.events.consoleErrors.filter((text) => !/^Failed to load resource\b/.test(text) &&
401
- !/violates the following Content Security Policy directive/.test(text)),
402
- ];
403
- }
404
- /**
405
- * Layout rules over every viewport, and load rules over the extra viewports (the main viewport's
406
- * errors and first frame are reported by the main rules).
407
- */
408
- async function viewportResults(all, extra) {
409
- const results = layoutResults(all);
410
- if (extra.length > 0)
411
- results.push(...(await extraViewportResults(extra)));
412
- return results;
413
- }
414
- function layoutResults(all) {
415
- const fitProblems = [];
416
- const overflowProblems = [];
417
- let canvasSeen = false;
418
- for (const pass of all) {
419
- const layout = pass.layout;
420
- if (!layout)
421
- continue;
422
- const overflow = overflowProblem(pass.preset.name, layout);
423
- if (overflow)
424
- overflowProblems.push(overflow);
425
- if (!layout.canvas)
426
- continue;
427
- canvasSeen = true;
428
- const fit = canvasFitProblem(pass.preset.name, layout, layout.canvas);
429
- if (fit)
430
- fitProblems.push(fit);
431
- }
432
- const names = all.map((pass) => pass.preset.name).join(', ');
433
- return [
434
- canvasSeen
435
- ? listResult(RUNTIME_LOAD_RULE_IDS.viewportCanvasFit, fitProblems, `checked ${names}`)
436
- : result(RUNTIME_LOAD_RULE_IDS.viewportCanvasFit, false, {
437
- status: 'not-applicable',
438
- evidence: 'no visible canvas',
439
- }),
440
- listResult(RUNTIME_LOAD_RULE_IDS.viewportOverflow, overflowProblems, `checked ${names}`),
441
- ];
442
- }
443
- async function extraViewportResults(extra) {
444
- const errors = [];
445
- const blank = [];
446
- for (const pass of extra) {
447
- const name = pass.preset.name;
448
- if (!pass.page.loaded) {
449
- errors.push(`${name}: did not load (${pass.page.loadError ?? 'unknown error'})`);
450
- continue;
451
- }
452
- for (const text of pageErrors(pass))
453
- errors.push(`${name}: ${text}`);
454
- if (pass.screenshot && (await frameDeviation(pass.screenshot)) <= 2)
455
- blank.push(name);
456
- }
457
- const names = extra.map((pass) => pass.preset.name).join(', ');
458
- return [
459
- listResult(RUNTIME_LOAD_RULE_IDS.viewportErrors, errors, `checked ${names}`),
460
- listResult(RUNTIME_LOAD_RULE_IDS.viewportContent, blank.map((name) => `${name}: single flat color`), `checked ${names}`),
461
- ];
462
- }
463
- function eventNames(state) {
464
- return state.events.map((event) => event.name).join(', ');
465
- }
466
- function relative(url) {
467
- return url.startsWith(RUNTIME_ORIGIN) ? url.slice(RUNTIME_ORIGIN.length + 1) : url;
468
- }
469
- function listResult(id, problems, passEvidence) {
470
- const shown = problems.slice(0, 10).join('; ');
471
- const evidence = problems.length > 10 ? `${shown}; … ${problems.length - 10} more` : shown || passEvidence;
472
- return result(id, problems.length === 0, evidence ? { evidence } : {});
473
- }
474
- function result(id, passed, details) {
475
- const rule = RULES[id];
476
- const status = details.status ?? (passed ? 'pass' : rule.severity === 'error' ? 'fail' : 'warning');
477
- return {
478
- ruleId: id,
479
- channel: 'common',
480
- stage: 'runtime-load',
481
- severity: rule.severity,
482
- status,
483
- message: status === 'pass' ? `${rule.title}: passed` : rule.title,
484
- recommendation: rule.recommendation,
485
- ...(details.evidence ? { evidence: details.evidence.slice(0, 2000) } : {}),
486
- owner: 'playcraft-build',
487
- confidence: rule.confidence,
488
- };
489
- }
490
- // ---- Probe script injected before page scripts ----
491
- /**
492
- * Script injected before any page script during runtime QA. It records, without side effects:
493
- * store-opening calls (channel SDK APIs, `window.open`, `postMessage('download')`), adsdk events
494
- * (via `window.PlayableSDK.on`), and CSP violations. Results live on `window.__PLAYCRAFT_QA__`.
495
- *
496
- * adsdk picks the channel from build-time constants (`AD_NETWORK`, `AD_PROTOCOL`) and only checks
497
- * that the channel's global exists. The platform CTA adapter instead picks the channel by which
498
- * global exists, so only the profile's own channel globals are stubbed (`channelGlobalsFor`).
499
- * Stubs are defined only when the page has none, matching the platform fallbacks in
500
- * `packages/build/src/platforms/*.ts`.
501
- */
502
- /** adsdk events the probe subscribes to. */
503
- export const ADSDK_PROBE_EVENTS = [
504
- 'playcraftInit',
505
- 'playcraftReady',
506
- 'playcraftStart',
507
- 'playcraftInteractive',
508
- 'playcraftFinish',
509
- 'playcraftInstall',
510
- ];
511
- export function buildRuntimeProbeScript(options) {
512
- return `(() => {
513
- const state = { calls: [], events: [], csp: [], sdk: false, adapter: false, storeUrls: false };
514
- Object.defineProperty(window, '__PLAYCRAFT_QA__', { value: state, configurable: false });
515
- const now = () => Math.round(performance.now());
516
- const record = (api, url) => {
517
- state.calls.push({ api, url: typeof url === 'string' ? url : undefined, at: now() });
518
- };
519
-
520
- window.open = function (url) { record('window.open', url); return null; };
521
- const postMessage = window.postMessage.bind(window);
522
- window.postMessage = function (message, ...rest) {
523
- if (message === 'download') record('postMessage:download');
524
- return postMessage(message, ...rest);
525
- };
526
- document.addEventListener('securitypolicyviolation', (event) => {
527
- state.csp.push({ blockedURI: String(event.blockedURI), violatedDirective: String(event.violatedDirective) });
528
- });
529
-
530
- let sdk;
531
- Object.defineProperty(window, 'PlayableSDK', {
532
- configurable: true,
533
- get: () => sdk,
534
- set: (value) => {
535
- sdk = value;
536
- state.sdk = Boolean(value);
537
- if (value && typeof value.on === 'function')
538
- for (const name of ${JSON.stringify(ADSDK_PROBE_EVENTS)})
539
- try { value.on(name, () => state.events.push({ name, at: now() })); } catch {}
540
- },
541
- });
542
-
543
- const stubbed = new Set(${JSON.stringify(options.channelGlobals)});
544
- if (stubbed.size === 0) return;
545
- const define = (name, value) => {
546
- if ((stubbed.has(name) || name === 'gameReady' || name === 'gameEnd') && window[name] === undefined) window[name] = value;
547
- };
548
- const listeners = () => ({
549
- addEventListener: (event, callback) => {
550
- if (event === 'ready') setTimeout(() => callback(), 0);
551
- if (event === 'viewableChange') setTimeout(() => callback(true), 0);
552
- },
553
- removeEventListener: () => {},
554
- });
555
- define('mraid', Object.assign(listeners(), {
556
- getVersion: () => '3.0', getState: () => 'default', isReady: () => true, isViewable: () => true,
557
- getPlacementType: () => 'interstitial', getMaxSize: () => ({ width: innerWidth, height: innerHeight }),
558
- getScreenSize: () => ({ width: innerWidth, height: innerHeight }),
559
- getCurrentPosition: () => ({ x: 0, y: 0, width: innerWidth, height: innerHeight }),
560
- getAudioVolume: () => 1, useCustomClose: () => {}, close: () => {}, expand: () => {},
561
- open: (url) => record('mraid.open', url), openStoreUrl: () => record('mraid.openStoreUrl'),
562
- }));
563
- define('dapi', Object.assign(listeners(), {
564
- isReady: () => true, isViewable: () => true, getAudioVolume: () => 1,
565
- getScreenSize: () => ({ width: innerWidth, height: innerHeight }),
566
- openStoreUrl: () => record('dapi.openStoreUrl'),
567
- }));
568
- define('FbPlayableAd', { onCTAClick: () => record('FbPlayableAd.onCTAClick'), logGameLoad: () => {}, logButtonClick: () => {} });
569
- define('ScPlayableAd', { onCTAClick: () => record('ScPlayableAd.onCTAClick') });
570
- define('ExitApi', { exit: () => record('ExitApi.exit') });
571
- define('BGY_MRAID', {
572
- open: () => record('BGY_MRAID.open', window.ADS_MRAID_CONFIG && window.ADS_MRAID_CONFIG.landUrl),
573
- gameEnd: () => {}, gameReady: () => {}, gameStart: () => {}, gameClose: () => {},
574
- });
575
- define('openAppStore', () => record('openAppStore'));
576
- define('install', () => record('install'));
577
- define('gameReady', () => {});
578
- define('gameEnd', () => {});
579
- define('TJ_API', { click: () => record('TJ_API.click'), setPlayableAPI: () => {}, objectiveComplete: () => {}, gameplayFinished: () => {} });
580
- define('NUC', { trigger: { convert: (url) => record('NUC.trigger.convert', url) } });
581
- define('smxTracking', { redirect: () => record('smxTracking.redirect') });
582
- })();`;
583
- }
584
- // ---- Layout checks ----
585
- /** A canvas fills the viewport in at least one dimension when scaled to fit (letterboxing allowed). */
586
- const CANVAS_FILL_RATIO = 0.9;
587
- /** Evaluated in the page: viewport size, scrollable size and the largest visible canvas. */
588
- const LAYOUT_PROBE = `(() => {
589
- const root = document.documentElement;
590
- const body = document.body;
591
- const canvases = Array.from(document.querySelectorAll('canvas'))
592
- .map((canvas) => canvas.getBoundingClientRect())
593
- .filter((rect) => rect.width > 0 && rect.height > 0)
594
- .sort((a, b) => b.width * b.height - a.width * a.height);
595
- const canvas = canvases[0];
596
- return {
597
- width: innerWidth,
598
- height: innerHeight,
599
- scrollWidth: Math.max(root.scrollWidth, body ? body.scrollWidth : 0),
600
- scrollHeight: Math.max(root.scrollHeight, body ? body.scrollHeight : 0),
601
- canvas: canvas ? { left: canvas.left, top: canvas.top, width: canvas.width, height: canvas.height } : null,
602
- };
603
- })()`;
604
- function overflowProblem(name, layout) {
605
- if (layout.scrollWidth <= layout.width + 1 && layout.scrollHeight <= layout.height + 1)
606
- return undefined;
607
- return `${name}: content ${layout.scrollWidth}×${layout.scrollHeight} in ${layout.width}×${layout.height}`;
608
- }
609
- function canvasFitProblem(name, layout, canvas) {
610
- const inside = canvas.left >= -1 &&
611
- canvas.top >= -1 &&
612
- canvas.left + canvas.width <= layout.width + 1 &&
613
- canvas.top + canvas.height <= layout.height + 1;
614
- const fill = Math.max(canvas.width / layout.width, canvas.height / layout.height);
615
- if (inside && fill >= CANVAS_FILL_RATIO)
616
- return undefined;
617
- const where = `canvas ${Math.round(canvas.width)}×${Math.round(canvas.height)} at (${Math.round(canvas.left)}, ${Math.round(canvas.top)}) in ${layout.width}×${layout.height}`;
618
- const reasons = [
619
- inside ? '' : 'outside the screen',
620
- fill < CANVAS_FILL_RATIO ? `fills ${Math.round(fill * 100)}%` : '',
621
- ].filter(Boolean);
622
- return `${name}: ${where}, ${reasons.join(', ')}`;
623
- }
624
- // ---- Serving artifact files ----
625
- const CONTENT_TYPES = {
626
- '.html': 'text/html; charset=utf-8',
627
- '.htm': 'text/html; charset=utf-8',
628
- '.js': 'text/javascript; charset=utf-8',
629
- '.mjs': 'text/javascript; charset=utf-8',
630
- '.css': 'text/css; charset=utf-8',
631
- '.json': 'application/json',
632
- '.svg': 'image/svg+xml',
633
- '.png': 'image/png',
634
- '.jpg': 'image/jpeg',
635
- '.jpeg': 'image/jpeg',
636
- '.gif': 'image/gif',
637
- '.webp': 'image/webp',
638
- '.mp3': 'audio/mpeg',
639
- '.ogg': 'audio/ogg',
640
- '.wav': 'audio/wav',
641
- '.m4a': 'audio/mp4',
642
- '.mp4': 'video/mp4',
643
- '.webm': 'video/webm',
644
- '.woff': 'font/woff',
645
- '.woff2': 'font/woff2',
646
- '.ttf': 'font/ttf',
647
- '.otf': 'font/otf',
648
- '.glb': 'model/gltf-binary',
649
- '.gltf': 'model/gltf+json',
650
- '.wasm': 'application/wasm',
651
- };
652
- function contentType(pathname) {
653
- return CONTENT_TYPES[path.posix.extname(pathname).toLowerCase()] ?? 'application/octet-stream';
654
- }
@@ -1,25 +0,0 @@
1
- import type { ImportMapAsset } from '../loaders/playcanvas-loader.js';
2
- /**
3
- * 构建文件夹 ID -> 完整目录路径的映射
4
- * PlayCraft Git 项目的 assets.json 中,资产的 path 字段是文件夹 ID 数组(如 [30097022, 30097024]),
5
- * 需要通过递归遍历构建每个 folder ID 对应的完整路径(如 "LiteCreator/System")
6
- */
7
- export declare function buildFolderFullPathMap(assets: Record<string, any>): Map<string, string>;
8
- /**
9
- * 从资产的 path 数组(文件夹 ID 列表)重建 treePath
10
- * path 数组中最后一个 ID 是直接父文件夹
11
- */
12
- export declare function resolveTreePathFromPathArray(pathIds: any[], folderFullPathMap: Map<string, string>): string;
13
- /**
14
- * Resolve the source file path for a script asset.
15
- * @param assets - 可选,所有资产的 map,用于从 path 数组重建 treePath(PlayCraft Git 仓库场景)
16
- */
17
- export declare function resolveScriptSourcePath(assetData: any, scriptId: string, projectDir: string, assets?: Record<string, any>): Promise<string | null>;
18
- /**
19
- * 构建脚本的文件夹路径(从 asset.path 数组)
20
- */
21
- export declare function buildScriptFolderPath(pathIds: any[], folderMap: Map<string, string>): string;
22
- /**
23
- * 根据 import map 确定目标路径
24
- */
25
- export declare function resolveTargetPathFromImportMap(folderPath: string, filename: string, importMap: ImportMapAsset): string | null;