@theaiplatform/miniapp-sdk 0.3.2 → 0.4.0

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.
@@ -1,217 +1,1793 @@
1
1
  import * as __rspack_external__rstest_playwright_5734ff29 from "@rstest/playwright";
2
+ import * as __rspack_external_node_crypto_2e7c4b46 from "node:crypto";
2
3
  import * as __rspack_external_node_fs_promises_3b710708 from "node:fs/promises";
3
4
  import * as __rspack_external_node_path_806ed179 from "node:path";
4
5
  import * as __rspack_external_playwright from "playwright";
5
6
  import * as __rspack_external_zod from "zod";
6
- const SESSION_ENV = 'TAP_MINIAPP_TEST_SESSION_FILE';
7
- const sessionSchema = __rspack_external_zod.z.object({
8
- schemaVersion: __rspack_external_zod.z.literal(1),
9
- runId: __rspack_external_zod.z.string().min(1),
10
- workspaceId: __rspack_external_zod.z.string().min(1),
11
- channelId: __rspack_external_zod.z.string().min(1),
12
- packageId: __rspack_external_zod.z.string().min(1),
13
- installationId: __rspack_external_zod.z.string().min(1),
14
- mode: __rspack_external_zod.z["enum"]([
15
- 'surface',
16
- 'live-tap'
17
- ]),
18
- dataScope: __rspack_external_zod.z["enum"]([
19
- 'fixture',
20
- 'selected-channel'
21
- ]),
22
- permissionScenario: __rspack_external_zod.z.string().min(1),
23
- surfaceId: __rspack_external_zod.z.string().min(1),
24
- surfaceSelector: __rspack_external_zod.z.string().min(1),
25
- surfaceAssetOrigin: __rspack_external_zod.z.string().url(),
26
- pageUrlPrefix: __rspack_external_zod.z.string().url(),
27
- cdpEndpoint: __rspack_external_zod.z.string().url(),
28
- cdpAuthorization: __rspack_external_zod.z.string().min(1),
29
- artifactDirectory: __rspack_external_zod.z.string().min(1),
30
- allowedNetworkOrigins: __rspack_external_zod.z.array(__rspack_external_zod.z.string().url()).max(128),
31
- credentialAliases: __rspack_external_zod.z.array(__rspack_external_zod.z.string().min(1).max(256)).max(64),
32
- releaseDigest: __rspack_external_zod.z.string().min(1).optional(),
33
- localGeneration: __rspack_external_zod.z.number().int().nonnegative().optional(),
34
- sourceDigest: __rspack_external_zod.z.string().min(1),
35
- testBundleDigest: __rspack_external_zod.z.string().min(1)
7
+ import * as __rspack_external_node_fs_1b05aee1 from "node:fs";
8
+ import * as __rspack_external_node_util_types_4d803828 from "node:util/types";
9
+ const jsonValueSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.lazy(()=>__rspack_external_zod.z.union([
10
+ __rspack_external_zod.z["null"](),
11
+ __rspack_external_zod.z.boolean(),
12
+ __rspack_external_zod.z.number(),
13
+ __rspack_external_zod.z.string(),
14
+ __rspack_external_zod.z.array(jsonValueSchema),
15
+ __rspack_external_zod.z.record(__rspack_external_zod.z.string(), jsonValueSchema)
16
+ ])))();
17
+ const _miniappTestArtifactSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
18
+ artifactId: __rspack_external_zod.z.string(),
19
+ kind: __rspack_external_zod.z["enum"]([
20
+ 'MINIAPP_TEST_ARTIFACT_KIND_RUN_MANIFEST',
21
+ 'MINIAPP_TEST_ARTIFACT_KIND_JSON_REPORT',
22
+ 'MINIAPP_TEST_ARTIFACT_KIND_MARKDOWN_REPORT',
23
+ 'MINIAPP_TEST_ARTIFACT_KIND_SCREENSHOT',
24
+ 'MINIAPP_TEST_ARTIFACT_KIND_TRACE',
25
+ 'MINIAPP_TEST_ARTIFACT_KIND_TRACE_SUMMARY',
26
+ 'MINIAPP_TEST_ARTIFACT_KIND_DEBUG_REPORT',
27
+ 'MINIAPP_TEST_ARTIFACT_KIND_CONSOLE_LOG',
28
+ 'MINIAPP_TEST_ARTIFACT_KIND_NETWORK_LOG'
29
+ ]),
30
+ relativeVfsPath: __rspack_external_zod.z.string(),
31
+ contentSha256: __rspack_external_zod.z.string(),
32
+ mediaType: __rspack_external_zod.z.string(),
33
+ byteLength: __rspack_external_zod.z.number(),
34
+ redacted: __rspack_external_zod.z.boolean(),
35
+ caseId: __rspack_external_zod.z.string().optional()
36
+ }))();
37
+ const miniappTestArtifactSchema = _miniappTestArtifactSchema;
38
+ const _miniappTestArtifactPolicySchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
39
+ trace: __rspack_external_zod.z["enum"]([
40
+ 'MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_OFF',
41
+ 'MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_FAILURE_ONLY',
42
+ 'MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_ALWAYS'
43
+ ]),
44
+ screenshots: __rspack_external_zod.z["enum"]([
45
+ 'MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_OFF',
46
+ 'MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_FAILURE_ONLY',
47
+ 'MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_ALWAYS'
48
+ ]),
49
+ maxBytes: __rspack_external_zod.z.number().optional()
50
+ }).strict())();
51
+ const miniappTestArtifactPolicySchema = _miniappTestArtifactPolicySchema;
52
+ const _miniappTestCapabilityWaiverSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
53
+ capability: __rspack_external_zod.z.string(),
54
+ reason: __rspack_external_zod.z.string(),
55
+ issue: __rspack_external_zod.z.string().optional(),
56
+ expiresAt: __rspack_external_zod.z.string().optional()
57
+ }).strict())();
58
+ const miniappTestCapabilityWaiverSchema = _miniappTestCapabilityWaiverSchema;
59
+ const _miniappTestCapturedHttpRequestsControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
60
+ schemaVersion: __rspack_external_zod.z.literal(1),
61
+ requestId: __rspack_external_zod.z.string(),
62
+ runId: __rspack_external_zod.z.string(),
63
+ operation: __rspack_external_zod.z.literal('captured-http-requests'),
64
+ captures: __rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpCapturesSchema)
65
+ }).strict())();
66
+ const miniappTestCapturedHttpRequestsControlReceiptSchema = _miniappTestCapturedHttpRequestsControlReceiptSchema;
67
+ const _miniappTestCapturedHttpRequestsControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
68
+ schemaVersion: __rspack_external_zod.z.literal(1),
69
+ requestId: __rspack_external_zod.z.string(),
70
+ runId: __rspack_external_zod.z.string(),
71
+ operation: __rspack_external_zod.z.literal('captured-http-requests')
72
+ }).strict())();
73
+ const miniappTestCapturedHttpRequestsControlRequestSchema = _miniappTestCapturedHttpRequestsControlRequestSchema;
74
+ const _miniappTestCountsSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
75
+ testFiles: __rspack_external_zod.z.number(),
76
+ failedFiles: __rspack_external_zod.z.number(),
77
+ tests: __rspack_external_zod.z.number(),
78
+ passedTests: __rspack_external_zod.z.number(),
79
+ failedTests: __rspack_external_zod.z.number(),
80
+ skippedTests: __rspack_external_zod.z.number(),
81
+ todoTests: __rspack_external_zod.z.number()
82
+ }))();
83
+ const miniappTestCountsSchema = _miniappTestCountsSchema;
84
+ const _miniappTestDriverCdpTargetSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
85
+ targetId: __rspack_external_zod.z.string(),
86
+ browserContextId: __rspack_external_zod.z.string().optional(),
87
+ targetType: __rspack_external_zod.z.string(),
88
+ pageUrl: __rspack_external_zod.z.string(),
89
+ surfaceSelector: __rspack_external_zod.z.string(),
90
+ surfaceAssetOrigin: __rspack_external_zod.z.string()
91
+ }).strict())();
92
+ const miniappTestDriverCdpTargetSchema = _miniappTestDriverCdpTargetSchema;
93
+ const _miniappTestDriverDigestsSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
94
+ sourceSha256: __rspack_external_zod.z.string(),
95
+ testBundleSha256: __rspack_external_zod.z.string(),
96
+ descriptorSha256: __rspack_external_zod.z.string(),
97
+ fixtureSha256: __rspack_external_zod.z.string().optional(),
98
+ policySha256: __rspack_external_zod.z.string()
99
+ }).strict())();
100
+ const miniappTestDriverDigestsSchema = _miniappTestDriverDigestsSchema;
101
+ const _miniappTestDriverMatrixEntrySchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
102
+ entryId: __rspack_external_zod.z.string(),
103
+ target: __rspack_external_zod.z.string(),
104
+ surfaceId: __rspack_external_zod.z.string(),
105
+ mode: __rspack_external_zod.z["enum"]([
106
+ 'MINIAPP_TEST_MODE_SURFACE',
107
+ 'MINIAPP_TEST_MODE_LIVE_TAP'
108
+ ]),
109
+ presentation: __rspack_external_zod.z["enum"]([
110
+ 'MINIAPP_TEST_PRESENTATION_HEADLESS',
111
+ 'MINIAPP_TEST_PRESENTATION_VISIBLE'
112
+ ]),
113
+ dataScope: __rspack_external_zod.z["enum"]([
114
+ 'MINIAPP_TEST_DATA_SCOPE_FIXTURE',
115
+ 'MINIAPP_TEST_DATA_SCOPE_SELECTED_CHANNEL'
116
+ ]),
117
+ selectedChannelId: __rspack_external_zod.z.string().optional(),
118
+ permissionScenario: __rspack_external_zod.z.string(),
119
+ fixtureVersion: __rspack_external_zod.z.string().optional(),
120
+ profileId: __rspack_external_zod.z.string()
121
+ }).strict())();
122
+ const miniappTestDriverMatrixEntrySchema = _miniappTestDriverMatrixEntrySchema;
123
+ const _miniappTestDriverProtocolSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
124
+ major: __rspack_external_zod.z.number(),
125
+ minor: __rspack_external_zod.z.number(),
126
+ features: __rspack_external_zod.z.array(__rspack_external_zod.z.string())
127
+ }).strict())();
128
+ const miniappTestDriverProtocolSchema = _miniappTestDriverProtocolSchema;
129
+ const _miniappTestDriverSessionSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
130
+ protocol: __rspack_external_zod.z.lazy(()=>miniappTestDriverProtocolSchema),
131
+ runId: __rspack_external_zod.z.string(),
132
+ runNonce: __rspack_external_zod.z.string(),
133
+ expiresAt: __rspack_external_zod.z.string(),
134
+ workspaceId: __rspack_external_zod.z.string(),
135
+ channelId: __rspack_external_zod.z.string(),
136
+ packageId: __rspack_external_zod.z.string(),
137
+ installationId: __rspack_external_zod.z.string(),
138
+ bindingId: __rspack_external_zod.z.string(),
139
+ releaseDigest: __rspack_external_zod.z.string().optional(),
140
+ localGeneration: __rspack_external_zod.z.number().optional(),
141
+ matrixEntry: __rspack_external_zod.z.lazy(()=>miniappTestDriverMatrixEntrySchema),
142
+ seed: __rspack_external_zod.z.number(),
143
+ versions: __rspack_external_zod.z.lazy(()=>miniappTestDriverVersionsSchema),
144
+ digests: __rspack_external_zod.z.lazy(()=>miniappTestDriverDigestsSchema),
145
+ cdpTarget: __rspack_external_zod.z.lazy(()=>miniappTestDriverCdpTargetSchema),
146
+ policy: __rspack_external_zod.z.lazy(()=>miniappTestPolicySchema),
147
+ cdpEndpoint: __rspack_external_zod.z.string(),
148
+ cdpAuthorization: __rspack_external_zod.z.string(),
149
+ artifactDirectory: __rspack_external_zod.z.string(),
150
+ environment: __rspack_external_zod.z.lazy(()=>miniappTestEnvironmentSchema),
151
+ artifacts: __rspack_external_zod.z.lazy(()=>miniappTestArtifactPolicySchema)
152
+ }).strict())();
153
+ const miniappTestDriverSessionSchema = _miniappTestDriverSessionSchema;
154
+ const _miniappTestDriverVersionsSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
155
+ hostVersion: __rspack_external_zod.z.string(),
156
+ hostContractVersion: __rspack_external_zod.z.string(),
157
+ adapterPackage: __rspack_external_zod.z.string(),
158
+ adapterVersion: __rspack_external_zod.z.string(),
159
+ runnerName: __rspack_external_zod.z.string(),
160
+ runnerVersion: __rspack_external_zod.z.string(),
161
+ nodeVersion: __rspack_external_zod.z.string(),
162
+ playwrightVersion: __rspack_external_zod.z.string(),
163
+ browserEngine: __rspack_external_zod.z.string(),
164
+ browserVersion: __rspack_external_zod.z.string()
165
+ }).strict())();
166
+ const miniappTestDriverVersionsSchema = _miniappTestDriverVersionsSchema;
167
+ const _miniappTestEmitHostEventControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
168
+ schemaVersion: __rspack_external_zod.z.literal(1),
169
+ requestId: __rspack_external_zod.z.string(),
170
+ runId: __rspack_external_zod.z.string(),
171
+ operation: __rspack_external_zod.z.literal('emit-host-event'),
172
+ delivered: __rspack_external_zod.z.number()
173
+ }).strict())();
174
+ const miniappTestEmitHostEventControlReceiptSchema = _miniappTestEmitHostEventControlReceiptSchema;
175
+ const _miniappTestEmitHostEventControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
176
+ schemaVersion: __rspack_external_zod.z.literal(1),
177
+ requestId: __rspack_external_zod.z.string(),
178
+ runId: __rspack_external_zod.z.string(),
179
+ operation: __rspack_external_zod.z.literal('emit-host-event'),
180
+ event: __rspack_external_zod.z.string(),
181
+ payload: jsonValueSchema.optional()
182
+ }).strict())();
183
+ const miniappTestEmitHostEventControlRequestSchema = _miniappTestEmitHostEventControlRequestSchema;
184
+ const _miniappTestEnvironmentSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
185
+ viewport: __rspack_external_zod.z.lazy(()=>miniappTestViewportSchema),
186
+ locale: __rspack_external_zod.z.string(),
187
+ timezone: __rspack_external_zod.z.string(),
188
+ theme: __rspack_external_zod.z["enum"]([
189
+ 'MINIAPP_TEST_THEME_LIGHT',
190
+ 'MINIAPP_TEST_THEME_DARK'
191
+ ]),
192
+ reducedMotion: __rspack_external_zod.z.boolean(),
193
+ seed: __rspack_external_zod.z.number(),
194
+ fixedNow: __rspack_external_zod.z.string().optional()
195
+ }).strict())();
196
+ const miniappTestEnvironmentSchema = _miniappTestEnvironmentSchema;
197
+ const _miniappTestExecutionSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
198
+ mode: __rspack_external_zod.z["enum"]([
199
+ 'MINIAPP_TEST_MODE_SURFACE',
200
+ 'MINIAPP_TEST_MODE_LIVE_TAP'
201
+ ]),
202
+ presentation: __rspack_external_zod.z["enum"]([
203
+ 'MINIAPP_TEST_PRESENTATION_HEADLESS',
204
+ 'MINIAPP_TEST_PRESENTATION_VISIBLE'
205
+ ]),
206
+ dataScope: __rspack_external_zod.z["enum"]([
207
+ 'MINIAPP_TEST_DATA_SCOPE_FIXTURE',
208
+ 'MINIAPP_TEST_DATA_SCOPE_SELECTED_CHANNEL'
209
+ ]),
210
+ runner: __rspack_external_zod.z.string(),
211
+ runnerVersion: __rspack_external_zod.z.string(),
212
+ nodeVersion: __rspack_external_zod.z.string(),
213
+ browserEngine: __rspack_external_zod.z.string(),
214
+ browserVersion: __rspack_external_zod.z.string(),
215
+ tapVersion: __rspack_external_zod.z.string(),
216
+ hostContractVersion: __rspack_external_zod.z.string(),
217
+ surfaceId: __rspack_external_zod.z.string(),
218
+ selectedChannelId: __rspack_external_zod.z.string().optional(),
219
+ fixtureVersion: __rspack_external_zod.z.string().optional()
220
+ }))();
221
+ const miniappTestExecutionSchema = _miniappTestExecutionSchema;
222
+ const _miniappTestFixtureChannelSeedSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
223
+ roomId: __rspack_external_zod.z.string(),
224
+ title: __rspack_external_zod.z.string(),
225
+ archived: __rspack_external_zod.z.boolean().optional(),
226
+ createdAt: __rspack_external_zod.z.number().optional(),
227
+ updatedAt: __rspack_external_zod.z.number().optional(),
228
+ messages: __rspack_external_zod.z.array(jsonValueSchema).default([]),
229
+ specialistIds: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([])
230
+ }).strict())();
231
+ const miniappTestFixtureChannelSeedSchema = _miniappTestFixtureChannelSeedSchema;
232
+ const _miniappTestFixtureChannelStateSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
233
+ roomId: __rspack_external_zod.z.string(),
234
+ title: __rspack_external_zod.z.string(),
235
+ archived: __rspack_external_zod.z.boolean(),
236
+ createdAt: __rspack_external_zod.z.number(),
237
+ updatedAt: __rspack_external_zod.z.number(),
238
+ messages: __rspack_external_zod.z.array(jsonValueSchema),
239
+ specialistIds: __rspack_external_zod.z.array(__rspack_external_zod.z.string())
240
+ }).strict())();
241
+ const miniappTestFixtureChannelStateSchema = _miniappTestFixtureChannelStateSchema;
242
+ const _miniappTestFixtureCheckpointSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
243
+ installationId: __rspack_external_zod.z.string(),
244
+ releaseId: __rspack_external_zod.z.string(),
245
+ runtimeSlot: __rspack_external_zod.z.string(),
246
+ checkpointReference: __rspack_external_zod.z.string(),
247
+ value: jsonValueSchema
248
+ }).strict())();
249
+ const miniappTestFixtureCheckpointSchema = _miniappTestFixtureCheckpointSchema;
250
+ const _miniappTestFixtureHttpCaptureSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
251
+ sequence: __rspack_external_zod.z.number(),
252
+ matched: __rspack_external_zod.z.boolean(),
253
+ request: __rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpRequestSchema),
254
+ credentialRef: __rspack_external_zod.z.string().optional(),
255
+ auth: __rspack_external_zod.z.literal('github').optional()
256
+ }).strict())();
257
+ const miniappTestFixtureHttpCaptureSchema = _miniappTestFixtureHttpCaptureSchema;
258
+ const _miniappTestFixtureHttpCapturesSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
259
+ requests: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpCaptureSchema)),
260
+ dropped: __rspack_external_zod.z.number()
261
+ }).strict())();
262
+ const miniappTestFixtureHttpCapturesSchema = _miniappTestFixtureHttpCapturesSchema;
263
+ const _miniappTestFixtureHttpHeaderSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
264
+ name: __rspack_external_zod.z.string(),
265
+ value: __rspack_external_zod.z.string()
266
+ }).strict())();
267
+ const miniappTestFixtureHttpHeaderSchema = _miniappTestFixtureHttpHeaderSchema;
268
+ const _miniappTestFixtureHttpHeaderInputSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
269
+ name: __rspack_external_zod.z.string(),
270
+ value: __rspack_external_zod.z.string(),
271
+ enabled: __rspack_external_zod.z.boolean().optional()
272
+ }).strict())();
273
+ const miniappTestFixtureHttpHeaderInputSchema = _miniappTestFixtureHttpHeaderInputSchema;
274
+ const _miniappTestFixtureHttpRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
275
+ method: __rspack_external_zod.z.string(),
276
+ url: __rspack_external_zod.z.string(),
277
+ query: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpHeaderInputSchema)).default([]),
278
+ headers: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpHeaderInputSchema)).default([]),
279
+ body: __rspack_external_zod.z.string().optional(),
280
+ timeoutMs: __rspack_external_zod.z.number().optional(),
281
+ responseBodyLimitBytes: __rspack_external_zod.z.number().optional(),
282
+ followRedirects: __rspack_external_zod.z.boolean().optional()
283
+ }).strict())();
284
+ const miniappTestFixtureHttpRequestSchema = _miniappTestFixtureHttpRequestSchema;
285
+ const _miniappTestFixtureHttpResponseSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
286
+ finalUrl: __rspack_external_zod.z.string(),
287
+ status: __rspack_external_zod.z.number(),
288
+ statusText: __rspack_external_zod.z.string(),
289
+ headers: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpHeaderSchema)),
290
+ bodyText: __rspack_external_zod.z.string().optional(),
291
+ bodyBase64: __rspack_external_zod.z.string().optional(),
292
+ bodyKind: __rspack_external_zod.z["enum"]([
293
+ 'text',
294
+ 'binary'
295
+ ]),
296
+ bodyTruncated: __rspack_external_zod.z.boolean(),
297
+ sizeBytes: __rspack_external_zod.z.number(),
298
+ elapsedMs: __rspack_external_zod.z.number(),
299
+ contentType: __rspack_external_zod.z.string().optional()
300
+ }).strict())();
301
+ const miniappTestFixtureHttpResponseSchema = _miniappTestFixtureHttpResponseSchema;
302
+ const _miniappTestFixtureHttpScriptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
303
+ request: __rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpRequestSchema),
304
+ credentialRef: __rspack_external_zod.z.string().optional(),
305
+ auth: __rspack_external_zod.z.literal('github').optional(),
306
+ response: __rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpResponseSchema),
307
+ repeat: __rspack_external_zod.z.number().optional()
308
+ }).strict())();
309
+ const miniappTestFixtureHttpScriptSchema = _miniappTestFixtureHttpScriptSchema;
310
+ const _miniappTestFixtureHttpScriptStateSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
311
+ request: __rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpRequestSchema),
312
+ credentialRef: __rspack_external_zod.z.string().optional(),
313
+ auth: __rspack_external_zod.z.literal('github').optional(),
314
+ response: __rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpResponseSchema),
315
+ repeat: __rspack_external_zod.z.number()
316
+ }).strict())();
317
+ const miniappTestFixtureHttpScriptStateSchema = _miniappTestFixtureHttpScriptStateSchema;
318
+ const _miniappTestFixtureLedgerSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
319
+ entries: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureLedgerEntrySchema)),
320
+ dropped: __rspack_external_zod.z.number()
321
+ }).strict())();
322
+ const miniappTestFixtureLedgerSchema = _miniappTestFixtureLedgerSchema;
323
+ const _miniappTestFixtureLedgerEntrySchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
324
+ sequence: __rspack_external_zod.z.number(),
325
+ fixtureGeneration: __rspack_external_zod.z.number(),
326
+ timestampMs: __rspack_external_zod.z.number(),
327
+ kind: __rspack_external_zod.z["enum"]([
328
+ 'event',
329
+ 'host-action',
330
+ 'native',
331
+ 'platform'
332
+ ]),
333
+ operation: __rspack_external_zod.z.string(),
334
+ detail: jsonValueSchema
335
+ }).strict())();
336
+ const miniappTestFixtureLedgerEntrySchema = _miniappTestFixtureLedgerEntrySchema;
337
+ const _miniappTestFixturePresenceSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
338
+ packageId: __rspack_external_zod.z.string(),
339
+ namespace: __rspack_external_zod.z.string(),
340
+ room: __rspack_external_zod.z.string(),
341
+ selfParticipantId: __rspack_external_zod.z.string(),
342
+ participants: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixturePresenceParticipantSchema))
343
+ }).strict())();
344
+ const miniappTestFixturePresenceSchema = _miniappTestFixturePresenceSchema;
345
+ const _miniappTestFixturePresenceParticipantSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
346
+ participantId: __rspack_external_zod.z.string(),
347
+ displayName: __rspack_external_zod.z.string(),
348
+ state: jsonValueSchema,
349
+ updatedAtMs: __rspack_external_zod.z.number()
350
+ }).strict())();
351
+ const miniappTestFixturePresenceParticipantSchema = _miniappTestFixturePresenceParticipantSchema;
352
+ const _miniappTestFixtureProjectSeedSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
353
+ id: __rspack_external_zod.z.string(),
354
+ name: __rspack_external_zod.z.string(),
355
+ discoverable: __rspack_external_zod.z.boolean().optional(),
356
+ channelIds: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
357
+ archivedChannelIds: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([])
358
+ }).strict())();
359
+ const miniappTestFixtureProjectSeedSchema = _miniappTestFixtureProjectSeedSchema;
360
+ const _miniappTestFixtureProjectStateSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
361
+ id: __rspack_external_zod.z.string(),
362
+ name: __rspack_external_zod.z.string(),
363
+ discoverable: __rspack_external_zod.z.boolean(),
364
+ channelIds: __rspack_external_zod.z.array(__rspack_external_zod.z.string()),
365
+ archivedChannelIds: __rspack_external_zod.z.array(__rspack_external_zod.z.string())
366
+ }).strict())();
367
+ const miniappTestFixtureProjectStateSchema = _miniappTestFixtureProjectStateSchema;
368
+ const _miniappTestFixtureSeedSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
369
+ projects: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureProjectSeedSchema)).default([]),
370
+ channels: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureChannelSeedSchema)).default([]),
371
+ workflows: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureWorkflowSchema)).default([]),
372
+ vfsFiles: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureVfsFileSchema)).default([]),
373
+ vfsDirectories: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureVfsDirectorySchema)).default([]),
374
+ storage: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureStorageEntrySchema)).default([]),
375
+ presence: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixturePresenceSchema)).default([]),
376
+ checkpoints: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureCheckpointSchema)).default([]),
377
+ specialists: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureSpecialistSchema)).default([]),
378
+ httpScripts: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpScriptSchema)).default([])
379
+ }).strict())();
380
+ const miniappTestFixtureSeedSchema = _miniappTestFixtureSeedSchema;
381
+ const _miniappTestFixtureSnapshotSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
382
+ schemaVersion: __rspack_external_zod.z.literal(1),
383
+ fixtureVersion: __rspack_external_zod.z.string(),
384
+ workspaceId: __rspack_external_zod.z.string(),
385
+ channelId: __rspack_external_zod.z.string(),
386
+ fixtureGeneration: __rspack_external_zod.z.number(),
387
+ fixtureDigest: __rspack_external_zod.z.string(),
388
+ clockTick: __rspack_external_zod.z.number(),
389
+ state: __rspack_external_zod.z.lazy(()=>miniappTestFixtureStateSchema)
390
+ }).strict())();
391
+ const miniappTestFixtureSnapshotSchema = _miniappTestFixtureSnapshotSchema;
392
+ const _miniappTestFixtureSpecialistSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
393
+ id: __rspack_external_zod.z.string(),
394
+ value: jsonValueSchema
395
+ }).strict())();
396
+ const miniappTestFixtureSpecialistSchema = _miniappTestFixtureSpecialistSchema;
397
+ const _miniappTestFixtureStateSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
398
+ projects: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureProjectStateSchema)),
399
+ channels: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureChannelStateSchema)),
400
+ workflows: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureWorkflowSchema)),
401
+ vfsFiles: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureVfsFileSchema)),
402
+ vfsDirectories: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureVfsDirectorySchema)),
403
+ storage: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureStorageEntrySchema)),
404
+ presence: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixturePresenceSchema)),
405
+ checkpoints: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureCheckpointSchema)),
406
+ specialists: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureSpecialistSchema)),
407
+ httpScripts: __rspack_external_zod.z.array(__rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpScriptStateSchema))
408
+ }).strict())();
409
+ const miniappTestFixtureStateSchema = _miniappTestFixtureStateSchema;
410
+ const _miniappTestFixtureStorageEntrySchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
411
+ workspaceId: __rspack_external_zod.z.string(),
412
+ packageId: __rspack_external_zod.z.string(),
413
+ namespace: __rspack_external_zod.z.string(),
414
+ key: __rspack_external_zod.z.string(),
415
+ revision: __rspack_external_zod.z.number(),
416
+ value: jsonValueSchema
417
+ }).strict())();
418
+ const miniappTestFixtureStorageEntrySchema = _miniappTestFixtureStorageEntrySchema;
419
+ const _miniappTestFixtureVfsDirectorySchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
420
+ conversationId: __rspack_external_zod.z.string(),
421
+ path: __rspack_external_zod.z.string()
422
+ }).strict())();
423
+ const miniappTestFixtureVfsDirectorySchema = _miniappTestFixtureVfsDirectorySchema;
424
+ const _miniappTestFixtureVfsFileSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
425
+ conversationId: __rspack_external_zod.z.string(),
426
+ path: __rspack_external_zod.z.string(),
427
+ data: __rspack_external_zod.z.array(__rspack_external_zod.z.number())
428
+ }).strict())();
429
+ const miniappTestFixtureVfsFileSchema = _miniappTestFixtureVfsFileSchema;
430
+ const _miniappTestFixtureWorkflowSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
431
+ workflowId: __rspack_external_zod.z.string(),
432
+ name: __rspack_external_zod.z.string(),
433
+ result: jsonValueSchema,
434
+ type: __rspack_external_zod.z.string().optional(),
435
+ createdAt: __rspack_external_zod.z.number().optional(),
436
+ updatedAt: __rspack_external_zod.z.number().optional()
437
+ }).strict())();
438
+ const miniappTestFixtureWorkflowSchema = _miniappTestFixtureWorkflowSchema;
439
+ const _miniappTestMatrixEntrySchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
440
+ id: __rspack_external_zod.z.string(),
441
+ profile: __rspack_external_zod.z.string(),
442
+ testMatch: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
443
+ capabilities: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([])
444
+ }).strict())();
445
+ const miniappTestMatrixEntrySchema = _miniappTestMatrixEntrySchema;
446
+ const _miniappTestPolicySchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
447
+ permissionScenario: __rspack_external_zod.z.string(),
448
+ allowedNetworkOrigins: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
449
+ effectGrants: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
450
+ credentialAliases: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
451
+ artifactRedactionPolicy: __rspack_external_zod.z.string(),
452
+ timeoutSeconds: __rspack_external_zod.z.number()
453
+ }).strict())();
454
+ const miniappTestPolicySchema = _miniappTestPolicySchema;
455
+ const _miniappTestProfileSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
456
+ surface: __rspack_external_zod.z.string(),
457
+ target: __rspack_external_zod.z.string(),
458
+ mode: __rspack_external_zod.z["enum"]([
459
+ 'MINIAPP_TEST_MODE_SURFACE',
460
+ 'MINIAPP_TEST_MODE_LIVE_TAP'
461
+ ]),
462
+ permissionScenario: __rspack_external_zod.z.string(),
463
+ deniedActions: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
464
+ fixtureFiles: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
465
+ httpRouteFiles: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
466
+ requiredOrigins: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
467
+ requiredEffects: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
468
+ credentialSlots: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
469
+ environment: __rspack_external_zod.z.lazy(()=>miniappTestEnvironmentSchema),
470
+ artifacts: __rspack_external_zod.z.lazy(()=>miniappTestArtifactPolicySchema)
471
+ }).strict())();
472
+ const miniappTestProfileSchema = _miniappTestProfileSchema;
473
+ const _miniappTestReadLedgerControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
474
+ schemaVersion: __rspack_external_zod.z.literal(1),
475
+ requestId: __rspack_external_zod.z.string(),
476
+ runId: __rspack_external_zod.z.string(),
477
+ operation: __rspack_external_zod.z.literal('read-ledger'),
478
+ ledger: __rspack_external_zod.z.lazy(()=>miniappTestFixtureLedgerSchema)
479
+ }).strict())();
480
+ const miniappTestReadLedgerControlReceiptSchema = _miniappTestReadLedgerControlReceiptSchema;
481
+ const _miniappTestReadLedgerControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
482
+ schemaVersion: __rspack_external_zod.z.literal(1),
483
+ requestId: __rspack_external_zod.z.string(),
484
+ runId: __rspack_external_zod.z.string(),
485
+ operation: __rspack_external_zod.z.literal('read-ledger')
486
+ }).strict())();
487
+ const miniappTestReadLedgerControlRequestSchema = _miniappTestReadLedgerControlRequestSchema;
488
+ const _miniappTestRemountSurfaceControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
489
+ schemaVersion: __rspack_external_zod.z.literal(1),
490
+ requestId: __rspack_external_zod.z.string(),
491
+ runId: __rspack_external_zod.z.string(),
492
+ operation: __rspack_external_zod.z.literal('remount-surface'),
493
+ mode: __rspack_external_zod.z["enum"]([
494
+ 'MINIAPP_TEST_MODE_SURFACE',
495
+ 'MINIAPP_TEST_MODE_LIVE_TAP'
496
+ ]),
497
+ surfaceGeneration: __rspack_external_zod.z.number(),
498
+ fixtureGeneration: __rspack_external_zod.z.number().optional(),
499
+ fixtureDigest: __rspack_external_zod.z.string().optional(),
500
+ instanceId: __rspack_external_zod.z.string(),
501
+ documentId: __rspack_external_zod.z.string()
502
+ }).strict())();
503
+ const miniappTestRemountSurfaceControlReceiptSchema = _miniappTestRemountSurfaceControlReceiptSchema;
504
+ const _miniappTestRemountSurfaceControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
505
+ schemaVersion: __rspack_external_zod.z.literal(1),
506
+ requestId: __rspack_external_zod.z.string(),
507
+ runId: __rspack_external_zod.z.string(),
508
+ operation: __rspack_external_zod.z.literal('remount-surface')
509
+ }).strict())();
510
+ const miniappTestRemountSurfaceControlRequestSchema = _miniappTestRemountSurfaceControlRequestSchema;
511
+ const _miniappTestResetFixtureControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
512
+ schemaVersion: __rspack_external_zod.z.literal(1),
513
+ requestId: __rspack_external_zod.z.string(),
514
+ runId: __rspack_external_zod.z.string(),
515
+ operation: __rspack_external_zod.z.literal('reset-fixture'),
516
+ mode: __rspack_external_zod.z["enum"]([
517
+ 'MINIAPP_TEST_MODE_SURFACE',
518
+ 'MINIAPP_TEST_MODE_LIVE_TAP'
519
+ ]),
520
+ surfaceGeneration: __rspack_external_zod.z.number(),
521
+ fixtureGeneration: __rspack_external_zod.z.number().optional(),
522
+ fixtureDigest: __rspack_external_zod.z.string().optional(),
523
+ instanceId: __rspack_external_zod.z.string(),
524
+ documentId: __rspack_external_zod.z.string()
525
+ }).strict())();
526
+ const miniappTestResetFixtureControlReceiptSchema = _miniappTestResetFixtureControlReceiptSchema;
527
+ const _miniappTestResetFixtureControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
528
+ schemaVersion: __rspack_external_zod.z.literal(1),
529
+ requestId: __rspack_external_zod.z.string(),
530
+ runId: __rspack_external_zod.z.string(),
531
+ operation: __rspack_external_zod.z.literal('reset-fixture')
532
+ }).strict())();
533
+ const miniappTestResetFixtureControlRequestSchema = _miniappTestResetFixtureControlRequestSchema;
534
+ const _miniappTestScriptHttpControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
535
+ schemaVersion: __rspack_external_zod.z.literal(1),
536
+ requestId: __rspack_external_zod.z.string(),
537
+ runId: __rspack_external_zod.z.string(),
538
+ operation: __rspack_external_zod.z.literal("script-http"),
539
+ fixtureGeneration: __rspack_external_zod.z.number(),
540
+ scriptedRequests: __rspack_external_zod.z.number()
541
+ }).strict())();
542
+ const miniappTestScriptHttpControlReceiptSchema = _miniappTestScriptHttpControlReceiptSchema;
543
+ const _miniappTestScriptHttpControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
544
+ schemaVersion: __rspack_external_zod.z.literal(1),
545
+ requestId: __rspack_external_zod.z.string(),
546
+ runId: __rspack_external_zod.z.string(),
547
+ operation: __rspack_external_zod.z.literal("script-http"),
548
+ script: __rspack_external_zod.z.lazy(()=>miniappTestFixtureHttpScriptSchema)
549
+ }).strict())();
550
+ const miniappTestScriptHttpControlRequestSchema = _miniappTestScriptHttpControlRequestSchema;
551
+ const _miniappTestSeedFixtureControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
552
+ schemaVersion: __rspack_external_zod.z.literal(1),
553
+ requestId: __rspack_external_zod.z.string(),
554
+ runId: __rspack_external_zod.z.string(),
555
+ operation: __rspack_external_zod.z.literal('seed-fixture'),
556
+ fixtureGeneration: __rspack_external_zod.z.number(),
557
+ fixtureDigest: __rspack_external_zod.z.string(),
558
+ surfaceGeneration: __rspack_external_zod.z.number(),
559
+ instanceId: __rspack_external_zod.z.string(),
560
+ documentId: __rspack_external_zod.z.string()
561
+ }).strict())();
562
+ const miniappTestSeedFixtureControlReceiptSchema = _miniappTestSeedFixtureControlReceiptSchema;
563
+ const _miniappTestSeedFixtureControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
564
+ schemaVersion: __rspack_external_zod.z.literal(1),
565
+ requestId: __rspack_external_zod.z.string(),
566
+ runId: __rspack_external_zod.z.string(),
567
+ operation: __rspack_external_zod.z.literal('seed-fixture'),
568
+ seed: __rspack_external_zod.z.lazy(()=>miniappTestFixtureSeedSchema)
569
+ }).strict())();
570
+ const miniappTestSeedFixtureControlRequestSchema = _miniappTestSeedFixtureControlRequestSchema;
571
+ const _miniappTestSelectionSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
572
+ projectNames: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
573
+ filePaths: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
574
+ caseIds: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
575
+ nameFilter: __rspack_external_zod.z.string().optional(),
576
+ affectedSourcePaths: __rspack_external_zod.z.array(__rspack_external_zod.z.string()).default([]),
577
+ changedOnly: __rspack_external_zod.z.boolean()
578
+ }))();
579
+ const miniappTestSelectionSchema = _miniappTestSelectionSchema;
580
+ const _miniappTestSnapshotFixtureControlReceiptSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
581
+ schemaVersion: __rspack_external_zod.z.literal(1),
582
+ requestId: __rspack_external_zod.z.string(),
583
+ runId: __rspack_external_zod.z.string(),
584
+ operation: __rspack_external_zod.z.literal('snapshot-fixture'),
585
+ snapshot: __rspack_external_zod.z.lazy(()=>miniappTestFixtureSnapshotSchema)
586
+ }).strict())();
587
+ const miniappTestSnapshotFixtureControlReceiptSchema = _miniappTestSnapshotFixtureControlReceiptSchema;
588
+ const _miniappTestSnapshotFixtureControlRequestSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
589
+ schemaVersion: __rspack_external_zod.z.literal(1),
590
+ requestId: __rspack_external_zod.z.string(),
591
+ runId: __rspack_external_zod.z.string(),
592
+ operation: __rspack_external_zod.z.literal('snapshot-fixture')
593
+ }).strict())();
594
+ const miniappTestSnapshotFixtureControlRequestSchema = _miniappTestSnapshotFixtureControlRequestSchema;
595
+ const _miniappTestViewportSchema = /* @__PURE__ */ (()=>__rspack_external_zod.z.object({
596
+ width: __rspack_external_zod.z.number(),
597
+ height: __rspack_external_zod.z.number()
598
+ }).strict())();
599
+ const miniappTestViewportSchema = _miniappTestViewportSchema;
600
+ const TAP_DRIVER_PROTOCOL_MAJOR = 1;
601
+ const TAP_DRIVER_PROTOCOL_MINOR = 0;
602
+ const TAP_DRIVER_FEATURE_EXACT_CDP_TARGET = 'exact-cdp-target-v1';
603
+ const TAP_DRIVER_FEATURE_FIXTURE_CONTROL = 'fixture-control-v1';
604
+ const TAP_DRIVER_RUN_QUERY = 'tapMiniappTestRun';
605
+ const TAP_DRIVER_NONCE_QUERY = 'tapMiniappTestNonce';
606
+ const SDK_PACKAGE = '@theaiplatform/miniapp-sdk';
607
+ const SUPPORTED_FEATURES = new Set([
608
+ TAP_DRIVER_FEATURE_EXACT_CDP_TARGET,
609
+ TAP_DRIVER_FEATURE_FIXTURE_CONTROL
610
+ ]);
611
+ const REQUIRED_FEATURES = [
612
+ TAP_DRIVER_FEATURE_EXACT_CDP_TARGET,
613
+ TAP_DRIVER_FEATURE_FIXTURE_CONTROL
614
+ ];
615
+ const LOWERCASE_SHA256 = /^[0-9a-f]{64}$/u;
616
+ const CANONICAL_DESCRIPTOR_ID = /^[a-z0-9][a-z0-9._:-]*$/u;
617
+ const SHA256_SRI = /^sha256-([A-Za-z0-9+/]{43}=)$/u;
618
+ const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;
619
+ const CANONICAL_UTC_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u;
620
+ const MAX_UINT32 = 0xffffffff;
621
+ const HTTP_PROTOCOLS = new Set([
622
+ 'http:',
623
+ 'https:'
624
+ ]);
625
+ const MAX_CONTROL_JSON_DEPTH = 32;
626
+ const MAX_CONTROL_JSON_NODES = 50000;
627
+ const MAX_FIXTURE_SEED_BYTES = 8388608;
628
+ const MAX_FIXTURE_HTTP_SCRIPT_BYTES = 1048576;
629
+ const MAX_CONTROL_RESULT_BYTES = 8388608;
630
+ const MAX_HOST_EVENT_PAYLOAD_BYTES = 61440;
631
+ const MAX_FIXTURE_COLLECTION_ITEMS = 256;
632
+ const MAX_FIXTURE_HTTP_CAPTURES = 1024;
633
+ const MAX_FIXTURE_LEDGER_ENTRIES = 4096;
634
+ const MAX_FIXTURE_HTTP_REPEATS = 100;
635
+ const installedManifestSchema = __rspack_external_zod.z.object({
636
+ name: __rspack_external_zod.z.literal(SDK_PACKAGE),
637
+ version: __rspack_external_zod.z.string().trim().min(1)
36
638
  });
37
- let sessionPromise;
38
- let browserPromise;
39
- function parseTapMiniappTestSession(value) {
40
- return sessionSchema.parse(value);
639
+ const cdpTargetInfoResponseSchema = __rspack_external_zod.z.object({
640
+ targetInfo: __rspack_external_zod.z.object({
641
+ browserContextId: __rspack_external_zod.z.string().optional(),
642
+ targetId: __rspack_external_zod.z.string(),
643
+ type: __rspack_external_zod.z.string(),
644
+ url: __rspack_external_zod.z.string()
645
+ }).passthrough()
646
+ }).passthrough();
647
+ function contractError(message) {
648
+ return new Error(`Invalid TAP miniapp driver session: ${message}`);
41
649
  }
42
- async function loadSession() {
43
- sessionPromise ??= (async ()=>{
44
- const sessionPath = process.env[SESSION_ENV]?.trim();
45
- if (!sessionPath) throw new Error(`${SESSION_ENV} is missing. Start this suite from The AI Platform Miniapp Test Lab.`);
46
- const raw = await (0, __rspack_external_node_fs_promises_3b710708.readFile)(sessionPath, 'utf8');
47
- return parseTapMiniappTestSession(JSON.parse(raw));
48
- })();
49
- return sessionPromise;
650
+ function readInstalledSdkIdentity() {
651
+ const manifestUrl = new URL('../../package.json', import.meta.url);
652
+ let value;
653
+ try {
654
+ value = JSON.parse((0, __rspack_external_node_fs_1b05aee1.readFileSync)(manifestUrl, 'utf8'));
655
+ } catch (error) {
656
+ throw new Error(`Unable to read the installed ${SDK_PACKAGE} package manifest: ${error instanceof Error ? error.message : String(error)}`);
657
+ }
658
+ return Object.freeze(installedManifestSchema.parse(value));
659
+ }
660
+ const installedSdkIdentity = readInstalledSdkIdentity();
661
+ function requireTrimmed(value, label, maximumLength = 512) {
662
+ if (0 === value.length || value.length > maximumLength || value.trim() !== value) throw contractError(`${label} must be a non-empty trimmed value no longer than ${maximumLength} characters`);
663
+ return value;
664
+ }
665
+ function requireCanonicalDescriptorId(value, label) {
666
+ requireTrimmed(value, label, 128);
667
+ if (new TextEncoder().encode(value).byteLength > 128 || !CANONICAL_DESCRIPTOR_ID.test(value) || LOWERCASE_SHA256.test(value)) throw contractError(`${label} must be a lowercase canonical descriptor id no longer than 128 bytes`);
668
+ return value;
669
+ }
670
+ function validateEnvironment(session) {
671
+ const environment = session.environment;
672
+ const width = requireUnsignedInteger(environment.viewport.width, 'environment.viewport.width', 8192);
673
+ const height = requireUnsignedInteger(environment.viewport.height, 'environment.viewport.height', 8192);
674
+ if (width < 320 || height < 200) throw contractError('environment viewport must be at least 320 by 200 pixels');
675
+ const locale = requireTrimmed(environment.locale, 'environment.locale', 64);
676
+ if (!/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/u.test(locale)) throw contractError('environment.locale must be a canonical locale tag');
677
+ const timezone = requireTrimmed(environment.timezone, 'environment.timezone', 128);
678
+ try {
679
+ new Intl.DateTimeFormat('en-US', {
680
+ timeZone: timezone
681
+ }).format();
682
+ } catch {
683
+ throw contractError('environment.timezone must be an IANA time zone');
684
+ }
685
+ const seed = requireUnsignedInteger(environment.seed, 'environment.seed', MAX_UINT32);
686
+ if (requireUnsignedInteger(session.seed, 'seed', MAX_UINT32) !== seed) throw contractError('seed must match environment.seed');
687
+ const fixedNow = void 0 === environment.fixedNow ? void 0 : requireTrimmed(environment.fixedNow, 'environment.fixedNow', 64);
688
+ if (void 0 !== fixedNow && (!CANONICAL_UTC_INSTANT.test(fixedNow) || !Number.isFinite(Date.parse(fixedNow)))) throw contractError('environment.fixedNow must be a canonical UTC RFC 3339 instant');
689
+ return Object.freeze({
690
+ viewport: Object.freeze({
691
+ width,
692
+ height
693
+ }),
694
+ locale,
695
+ timezone,
696
+ theme: 'MINIAPP_TEST_THEME_LIGHT' === environment.theme ? 'light' : 'dark',
697
+ reducedMotion: environment.reducedMotion,
698
+ seed,
699
+ ...void 0 === fixedNow ? {} : {
700
+ fixedNow
701
+ }
702
+ });
703
+ }
704
+ function artifactCapturePolicy(value) {
705
+ if ('MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_OFF' === value) return 'off';
706
+ if ('MINIAPP_TEST_ARTIFACT_CAPTURE_POLICY_ALWAYS' === value) return 'always';
707
+ return 'failure-only';
708
+ }
709
+ function validateArtifacts(session) {
710
+ const maximum = session.artifacts.maxBytes;
711
+ if (void 0 !== maximum) {
712
+ const normalized = requireUnsignedInteger(maximum, 'artifacts.maxBytes', 67108864);
713
+ if (normalized < 1024) throw contractError('artifacts.maxBytes must be at least 1024');
714
+ }
715
+ return Object.freeze({
716
+ trace: artifactCapturePolicy(session.artifacts.trace),
717
+ screenshots: artifactCapturePolicy(session.artifacts.screenshots),
718
+ ...void 0 === maximum ? {} : {
719
+ maxBytes: maximum
720
+ }
721
+ });
722
+ }
723
+ function requireSha256(value, label) {
724
+ if (!LOWERCASE_SHA256.test(value)) throw contractError(`${label} must be a lowercase 64-character SHA-256 digest`);
725
+ return value;
726
+ }
727
+ function requireOptionalSha256(value, label) {
728
+ return void 0 === value ? void 0 : requireSha256(value, label);
729
+ }
730
+ function requireSha256Sri(value, label) {
731
+ const encoded = SHA256_SRI.exec(value)?.[1];
732
+ if (!encoded) throw contractError(`${label} must be a canonical sha256-<base64> SRI digest`);
733
+ const bytes = Buffer.from(encoded, 'base64');
734
+ if (32 !== bytes.byteLength || bytes.toString('base64') !== encoded) throw contractError(`${label} must be a canonical sha256-<base64> SRI digest`);
735
+ return value;
736
+ }
737
+ function requireHttpUrl(value, label) {
738
+ let parsed;
739
+ try {
740
+ parsed = new URL(value);
741
+ } catch {
742
+ throw contractError(`${label} must be an absolute URL`);
743
+ }
744
+ if (!HTTP_PROTOCOLS.has(parsed.protocol)) throw contractError(`${label} must use HTTP or HTTPS`);
745
+ return parsed;
746
+ }
747
+ function requireHttpOrigin(value, label) {
748
+ const parsed = requireHttpUrl(value, label);
749
+ if (parsed.username || parsed.password || '/' !== parsed.pathname || parsed.search || parsed.hash) throw contractError(`${label} must be an origin without a path or secrets`);
750
+ return parsed.origin;
50
751
  }
51
- function selectPage(context, session) {
52
- const candidates = context.pages().filter((candidate)=>candidate.url().startsWith(session.pageUrlPrefix));
53
- if (1 !== candidates.length) throw new Error(`TAP Browser Driver exposed ${candidates.length} matching pages for run ${session.runId}; expected exactly one.`);
54
- const page = candidates[0];
55
- if (!page) throw new Error('TAP Browser Driver page selection failed');
56
- return page;
752
+ function isLoopbackHostname(hostname) {
753
+ const unwrapped = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
754
+ if ('localhost' === unwrapped.toLocaleLowerCase('en-US') || '::1' === unwrapped || '0:0:0:0:0:0:0:1' === unwrapped) return true;
755
+ const octets = unwrapped.split('.');
756
+ return 4 === octets.length && '127' === octets[0] && octets.every((octet)=>/^(?:0|[1-9][0-9]{0,2})$/u.test(octet) && Number(octet) <= 255);
57
757
  }
58
- async function emitHostEvent(page, session, event, payload) {
59
- if (!event.startsWith('tap.') || event.length > 160 || event.trim() !== event) throw new Error('TAP host events must be bounded, trimmed tap.* event names.');
60
- await page.evaluate(({ controlEvent, event, payload, runId })=>{
758
+ function requireLoopbackCdpEndpoint(value) {
759
+ let parsed;
760
+ try {
761
+ parsed = new URL(value);
762
+ } catch {
763
+ throw contractError('cdpEndpoint must be an absolute URL');
764
+ }
765
+ if (!new Set([
766
+ 'http:',
767
+ 'ws:'
768
+ ]).has(parsed.protocol)) throw contractError('cdpEndpoint must use HTTP or WebSocket');
769
+ if (!isLoopbackHostname(parsed.hostname) || parsed.username || parsed.password || parsed.search || parsed.hash) throw contractError('cdpEndpoint must be a credential-free loopback-only URL');
770
+ return parsed.toString();
771
+ }
772
+ function requireUnsignedInteger(value, label, maximum) {
773
+ if (!Number.isSafeInteger(value) || value < 0 || value > maximum) throw contractError(`${label} must be an unsigned integer no greater than ${maximum}`);
774
+ return value;
775
+ }
776
+ function requireStringList(values, label, maximumEntries) {
777
+ if (values.length > maximumEntries) throw contractError(`${label} may contain at most ${maximumEntries} items`);
778
+ const normalized = values.map((value, index)=>requireTrimmed(value, `${label}[${index}]`, 256));
779
+ if (new Set(normalized).size !== normalized.length) throw contractError(`${label} must not contain duplicates`);
780
+ return Object.freeze(normalized);
781
+ }
782
+ function validateProtocol(session) {
783
+ if (session.protocol.major !== TAP_DRIVER_PROTOCOL_MAJOR) throw contractError(`protocol major ${session.protocol.major} is incompatible with supported major ${TAP_DRIVER_PROTOCOL_MAJOR}`);
784
+ requireUnsignedInteger(session.protocol.minor, 'protocol.minor', MAX_UINT32);
785
+ if (session.protocol.minor > TAP_DRIVER_PROTOCOL_MINOR) throw contractError(`protocol minor ${session.protocol.minor} is newer than supported minor ${TAP_DRIVER_PROTOCOL_MINOR}`);
786
+ if (0 === session.protocol.features.length) throw contractError('protocol.features must contain a negotiated feature');
787
+ const features = requireStringList(session.protocol.features, 'protocol.features', 32);
788
+ for (const feature of features)if (!SUPPORTED_FEATURES.has(feature)) throw contractError(`protocol feature ${feature} is not supported`);
789
+ for (const requiredFeature of REQUIRED_FEATURES)if (!features.includes(requiredFeature)) throw contractError(`protocol feature ${requiredFeature} must be negotiated`);
790
+ return features;
791
+ }
792
+ function validateExpiry(expiresAt) {
793
+ if (!RFC3339.test(expiresAt)) throw contractError('expiresAt must be an RFC 3339 timestamp');
794
+ const expiresAtMs = Date.parse(expiresAt);
795
+ if (!Number.isFinite(expiresAtMs)) throw contractError('expiresAt must be a real timestamp');
796
+ if (expiresAtMs <= Date.now()) throw contractError('the driver session has expired');
797
+ return expiresAt;
798
+ }
799
+ function validateAdapter(session) {
800
+ if (session.versions.adapterPackage !== installedSdkIdentity.name) throw contractError(`adapter package ${session.versions.adapterPackage} does not match ${installedSdkIdentity.name}`);
801
+ if (session.versions.adapterVersion !== installedSdkIdentity.version) throw contractError(`adapter version ${session.versions.adapterVersion} does not match installed version ${installedSdkIdentity.version}`);
802
+ if ('rstest' !== session.versions.runnerName) throw contractError('versions.runnerName must be rstest');
803
+ for (const [label, value] of Object.entries(session.versions))requireTrimmed(value, `versions.${label}`, 256);
804
+ return {
805
+ adapterVersion: session.versions.adapterVersion,
806
+ browserEngine: session.versions.browserEngine,
807
+ browserVersion: session.versions.browserVersion,
808
+ hostContractVersion: session.versions.hostContractVersion,
809
+ hostVersion: session.versions.hostVersion,
810
+ nodeVersion: session.versions.nodeVersion,
811
+ playwrightVersion: session.versions.playwrightVersion,
812
+ runnerName: 'rstest',
813
+ runnerVersion: session.versions.runnerVersion
814
+ };
815
+ }
816
+ function validateMatrixAndFixture(session) {
817
+ const matrix = session.matrixEntry;
818
+ const fixtureDigest = requireOptionalSha256(session.digests.fixtureSha256, 'digests.fixtureSha256');
819
+ if (matrix.permissionScenario !== session.policy.permissionScenario) throw contractError('matrixEntry.permissionScenario must match policy.permissionScenario');
820
+ const presentation = 'MINIAPP_TEST_PRESENTATION_HEADLESS' === matrix.presentation ? 'headless' : 'visible';
821
+ if ('MINIAPP_TEST_MODE_SURFACE' === matrix.mode) {
822
+ if ('MINIAPP_TEST_DATA_SCOPE_FIXTURE' !== matrix.dataScope) throw contractError('Surface mode requires fixture data scope');
823
+ if (!fixtureDigest) throw contractError('Surface mode requires digests.fixtureSha256');
824
+ const fixtureVersion = requireTrimmed(matrix.fixtureVersion ?? '', 'matrixEntry.fixtureVersion', 256);
825
+ if (void 0 !== matrix.selectedChannelId) throw contractError('Surface mode must not declare matrixEntry.selectedChannelId');
826
+ return {
827
+ dataScope: 'fixture',
828
+ fixtureDigest,
829
+ fixtureVersion,
830
+ mode: 'surface',
831
+ presentation
832
+ };
833
+ }
834
+ if ('MINIAPP_TEST_DATA_SCOPE_SELECTED_CHANNEL' !== matrix.dataScope) throw contractError('Live TAP mode requires selected-channel data scope');
835
+ if (void 0 !== fixtureDigest || void 0 !== matrix.fixtureVersion) throw contractError('Live TAP mode must not declare fixtureVersion or fixtureSha256');
836
+ return {
837
+ dataScope: 'selected-channel',
838
+ mode: 'live-tap',
839
+ presentation,
840
+ selectedChannelId: requireTrimmed(matrix.selectedChannelId ?? '', 'matrixEntry.selectedChannelId')
841
+ };
842
+ }
843
+ function validateTarget(session, runId, runNonce) {
844
+ const target = session.cdpTarget;
845
+ if ('page' !== target.targetType) throw contractError('cdpTarget.targetType must be page');
846
+ const pageUrl = requireHttpUrl(target.pageUrl, 'cdpTarget.pageUrl');
847
+ if (pageUrl.searchParams.get(TAP_DRIVER_RUN_QUERY) !== runId) throw contractError(`cdpTarget.pageUrl must bind ${TAP_DRIVER_RUN_QUERY} to runId`);
848
+ if (pageUrl.searchParams.get(TAP_DRIVER_NONCE_QUERY) !== runNonce) throw contractError(`cdpTarget.pageUrl must bind ${TAP_DRIVER_NONCE_QUERY} to runNonce`);
849
+ return {
850
+ browserContextId: void 0 === target.browserContextId ? void 0 : requireTrimmed(target.browserContextId, 'cdpTarget.browserContextId'),
851
+ pageUrl: target.pageUrl,
852
+ surfaceAssetOrigin: requireHttpOrigin(target.surfaceAssetOrigin, 'cdpTarget.surfaceAssetOrigin'),
853
+ surfaceSelector: requireTrimmed(target.surfaceSelector, 'cdpTarget.surfaceSelector', 1024),
854
+ targetId: requireTrimmed(target.targetId, 'cdpTarget.targetId'),
855
+ targetType: 'page'
856
+ };
857
+ }
858
+ function parseValidatedTapMiniappTestSession(value) {
859
+ const session = miniappTestDriverSessionSchema.parse(value);
860
+ const features = validateProtocol(session);
861
+ const versions = validateAdapter(session);
862
+ const environment = validateEnvironment(session);
863
+ const artifacts = validateArtifacts(session);
864
+ const runId = requireTrimmed(session.runId, 'runId');
865
+ const runNonce = requireSha256(session.runNonce, 'runNonce');
866
+ const matrixAndFixture = validateMatrixAndFixture(session);
867
+ const target = validateTarget(session, runId, runNonce);
868
+ const releaseDigest = void 0 === session.releaseDigest ? void 0 : requireSha256Sri(session.releaseDigest, 'releaseDigest');
869
+ const localGeneration = void 0 === session.localGeneration ? void 0 : requireUnsignedInteger(session.localGeneration, 'localGeneration', Number.MAX_SAFE_INTEGER);
870
+ if (void 0 === releaseDigest === (void 0 === localGeneration)) throw contractError('exactly one of releaseDigest or localGeneration must be present');
871
+ const allowedNetworkOrigins = Object.freeze(session.policy.allowedNetworkOrigins.map((origin, index)=>requireHttpOrigin(origin, `policy.allowedNetworkOrigins[${index}]`)));
872
+ if (allowedNetworkOrigins.length > 128) throw contractError('policy.allowedNetworkOrigins may contain at most 128 items');
873
+ if (0 === requireUnsignedInteger(session.policy.timeoutSeconds, 'policy.timeoutSeconds', 86400)) throw contractError('policy.timeoutSeconds must be greater than zero');
874
+ return Object.freeze({
875
+ protocolMajor: session.protocol.major,
876
+ protocolMinor: session.protocol.minor,
877
+ features,
878
+ runId,
879
+ runNonce,
880
+ expiresAt: validateExpiry(session.expiresAt),
881
+ workspaceId: requireTrimmed(session.workspaceId, 'workspaceId'),
882
+ channelId: requireTrimmed(session.channelId, 'channelId'),
883
+ packageId: requireTrimmed(session.packageId, 'packageId'),
884
+ installationId: requireTrimmed(session.installationId, 'installationId'),
885
+ bindingId: requireTrimmed(session.bindingId, 'bindingId'),
886
+ releaseDigest,
887
+ localGeneration,
888
+ matrixEntryId: requireCanonicalDescriptorId(session.matrixEntry.entryId, 'matrixEntry.entryId'),
889
+ profileId: requireCanonicalDescriptorId(session.matrixEntry.profileId, 'matrixEntry.profileId'),
890
+ target: requireTrimmed(session.matrixEntry.target, 'matrixEntry.target'),
891
+ matrixTarget: requireTrimmed(session.matrixEntry.target, 'matrixEntry.target'),
892
+ ...matrixAndFixture,
893
+ permissionScenario: requireTrimmed(session.policy.permissionScenario, 'policy.permissionScenario'),
894
+ seed: environment.seed,
895
+ environment,
896
+ artifacts,
897
+ sourceDigest: requireSha256(session.digests.sourceSha256, 'digests.sourceSha256'),
898
+ testBundleDigest: requireSha256(session.digests.testBundleSha256, 'digests.testBundleSha256'),
899
+ descriptorDigest: requireSha256(session.digests.descriptorSha256, "digests.descriptorSha256"),
900
+ policyDigest: requireSha256(session.digests.policySha256, 'digests.policySha256'),
901
+ ...versions,
902
+ ...target,
903
+ surfaceId: requireTrimmed(session.matrixEntry.surfaceId, 'matrixEntry.surfaceId'),
904
+ cdpEndpoint: requireLoopbackCdpEndpoint(session.cdpEndpoint),
905
+ cdpAuthorization: requireTrimmed(session.cdpAuthorization, 'cdpAuthorization', 1024),
906
+ artifactDirectory: requireTrimmed(session.artifactDirectory, 'artifactDirectory', 4096),
907
+ allowedNetworkOrigins,
908
+ effectGrants: requireStringList(session.policy.effectGrants, 'policy.effectGrants', 128),
909
+ credentialAliases: requireStringList(session.policy.credentialAliases, 'policy.credentialAliases', 64)
910
+ });
911
+ }
912
+ async function connectValidatedTapMiniappTestSession(value, connect) {
913
+ const session = parseValidatedTapMiniappTestSession(value);
914
+ const connection = await connect(session.cdpEndpoint, {
915
+ headers: {
916
+ authorization: `Bearer ${session.cdpAuthorization}`,
917
+ 'x-tap-miniapp-test-run': session.runId
918
+ }
919
+ });
920
+ return Object.freeze({
921
+ connection,
922
+ session
923
+ });
924
+ }
925
+ function requireBoundedJson(value, label, maximumBytes) {
926
+ const active = new WeakSet();
927
+ let nodes = 0;
928
+ let serializedBytes = 0;
929
+ const append = (serialized)=>{
930
+ serializedBytes += Buffer.byteLength(serialized, 'utf8');
931
+ if (serializedBytes > maximumBytes) throw contractError(`${label} must serialize to no more than ${maximumBytes} bytes`);
932
+ };
933
+ const visit = (candidate, depth)=>{
934
+ nodes += 1;
935
+ if (nodes > MAX_CONTROL_JSON_NODES) throw contractError(`${label} may contain at most ${MAX_CONTROL_JSON_NODES} JSON nodes`);
936
+ if (depth > MAX_CONTROL_JSON_DEPTH) throw contractError(`${label} may be at most ${MAX_CONTROL_JSON_DEPTH} levels deep`);
937
+ if (null === candidate || 'boolean' == typeof candidate || 'string' == typeof candidate) return void append(JSON.stringify(candidate));
938
+ if ('number' == typeof candidate) {
939
+ if (!Number.isFinite(candidate)) throw contractError(`${label} must contain only finite JSON numbers`);
940
+ append(JSON.stringify(candidate));
941
+ return;
942
+ }
943
+ if ('object' != typeof candidate) throw contractError(`${label} must contain only JSON-safe values`);
944
+ if ((0, __rspack_external_node_util_types_4d803828.isProxy)(candidate)) throw contractError(`${label} must not contain proxy objects`);
945
+ if (active.has(candidate)) throw contractError(`${label} must not contain cycles`);
946
+ active.add(candidate);
947
+ if (Array.isArray(candidate)) {
948
+ if (Object.getPrototypeOf(candidate) !== Array.prototype) throw contractError(`${label} must contain only plain JSON arrays`);
949
+ const descriptors = Object.getOwnPropertyDescriptors(candidate);
950
+ const ownKeys = Reflect.ownKeys(descriptors);
951
+ if (ownKeys.some((key)=>'string' != typeof key) || candidate.length + nodes > MAX_CONTROL_JSON_NODES || ownKeys.length !== candidate.length + 1) throw contractError(`${label} arrays must be dense and canonical`);
952
+ append('[');
953
+ for(let index = 0; index < candidate.length; index += 1){
954
+ const descriptor = descriptors[String(index)];
955
+ if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) throw contractError(`${label} arrays must be dense and canonical`);
956
+ if (index > 0) append(',');
957
+ visit(descriptor.value, depth + 1);
958
+ }
959
+ append(']');
960
+ } else {
961
+ const prototype = Object.getPrototypeOf(candidate);
962
+ if (prototype !== Object.prototype && null !== prototype) throw contractError(`${label} must contain only plain JSON objects`);
963
+ const descriptors = Object.getOwnPropertyDescriptors(candidate);
964
+ const ownKeys = Reflect.ownKeys(descriptors);
965
+ if (ownKeys.some((key)=>'string' != typeof key)) throw contractError(`${label} must contain only enumerable string-keyed properties`);
966
+ append('{');
967
+ for (const [index, key] of ownKeys.entries()){
968
+ const descriptor = descriptors[key];
969
+ if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) throw contractError(`${label} must contain only enumerable data properties`);
970
+ if (index > 0) append(',');
971
+ append(JSON.stringify(key));
972
+ append(':');
973
+ visit(descriptor.value, depth + 1);
974
+ }
975
+ append('}');
976
+ }
977
+ active.delete(candidate);
978
+ };
979
+ visit(value, 0);
980
+ }
981
+ async function dispatchControlRequest(page, request) {
982
+ return page.evaluate(async ({ controlEvent, request })=>{
61
983
  const response = {};
62
984
  globalThis.dispatchEvent(new CustomEvent(controlEvent, {
63
985
  detail: {
64
- event,
65
- payload,
66
- response,
67
- runId
986
+ request,
987
+ response
68
988
  }
69
989
  }));
70
- if (response.error) throw new Error(response.error);
71
- if (!response.delivered) throw new Error(`The TAP frame host has no active subscriber for ${event}. Declare the event on the miniapp surface before using it in a test.`);
990
+ if (!response.promise || 'function' != typeof Reflect.get(response.promise, 'then')) throw new Error('The TAP frame host did not accept the Miniapp Test control request.');
991
+ return response.promise;
72
992
  }, {
73
993
  controlEvent: 'tap:miniapp-test-control',
994
+ request
995
+ });
996
+ }
997
+ function assertControlReceipt(receipt, session, requestId) {
998
+ if (1 !== receipt.schemaVersion) throw contractError('the host control receipt schemaVersion must be 1');
999
+ if (receipt.runId !== session.runId) throw contractError('the host control receipt belongs to another run');
1000
+ if (receipt.requestId !== requestId) throw contractError('the host control receipt belongs to another request');
1001
+ }
1002
+ async function emitTapMiniappHostEvent(page, session, event, payload) {
1003
+ if (event.length < 5 || event.length > 160 || !event.startsWith('tap.') || event.trim() !== event) throw contractError('host events must be bounded, trimmed tap.* event names');
1004
+ if (void 0 !== payload) requireBoundedJson(payload, 'host event payload', MAX_HOST_EVENT_PAYLOAD_BYTES);
1005
+ const request = miniappTestEmitHostEventControlRequestSchema.parse({
1006
+ schemaVersion: 1,
1007
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1008
+ runId: session.runId,
1009
+ operation: 'emit-host-event',
74
1010
  event,
75
- payload,
76
- runId: session.runId
1011
+ ...void 0 === payload ? {} : {
1012
+ payload
1013
+ }
77
1014
  });
1015
+ const receipt = miniappTestEmitHostEventControlReceiptSchema.parse(await dispatchControlRequest(page, request));
1016
+ assertControlReceipt(receipt, session, request.requestId);
1017
+ requireUnsignedInteger(receipt.delivered, 'control.delivered', MAX_UINT32);
1018
+ if (0 === receipt.delivered) throw contractError('control.delivered must be greater than zero');
1019
+ return Object.freeze(receipt);
1020
+ }
1021
+ async function runTapMiniappLifecycleControl(page, session, operation) {
1022
+ if ('reset-fixture' === operation && 'surface' !== session.mode) throw contractError('reset-fixture is available only in Surface mode');
1023
+ const request = 'reset-fixture' === operation ? miniappTestResetFixtureControlRequestSchema.parse({
1024
+ schemaVersion: 1,
1025
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1026
+ runId: session.runId,
1027
+ operation
1028
+ }) : miniappTestRemountSurfaceControlRequestSchema.parse({
1029
+ schemaVersion: 1,
1030
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1031
+ runId: session.runId,
1032
+ operation
1033
+ });
1034
+ const rawReceipt = await dispatchControlRequest(page, request);
1035
+ const receipt = 'reset-fixture' === operation ? miniappTestResetFixtureControlReceiptSchema.parse(rawReceipt) : miniappTestRemountSurfaceControlReceiptSchema.parse(rawReceipt);
1036
+ assertControlReceipt(receipt, session, request.requestId);
1037
+ if (receipt.operation !== operation) throw contractError(`host control receipt operation ${receipt.operation} does not match ${operation}`);
1038
+ const expectedMode = 'surface' === session.mode ? 'MINIAPP_TEST_MODE_SURFACE' : 'MINIAPP_TEST_MODE_LIVE_TAP';
1039
+ if (receipt.mode !== expectedMode) throw contractError(`host control receipt mode ${receipt.mode} does not match ${session.mode}`);
1040
+ if ('surface' === session.mode) {
1041
+ if (void 0 === receipt.fixtureGeneration || void 0 === receipt.fixtureDigest) throw contractError('Surface lifecycle receipts require fixture generation and digest');
1042
+ requireUnsignedInteger(receipt.fixtureGeneration, 'control.fixtureGeneration', MAX_UINT32);
1043
+ if (0 === receipt.fixtureGeneration) throw contractError('control.fixtureGeneration must be greater than zero');
1044
+ requireSha256(receipt.fixtureDigest, 'control.fixtureDigest');
1045
+ } else if (void 0 !== receipt.fixtureGeneration || void 0 !== receipt.fixtureDigest) throw contractError('Live TAP lifecycle receipts must not contain fixture authority');
1046
+ requireUnsignedInteger(receipt.surfaceGeneration, 'control.surfaceGeneration', MAX_UINT32);
1047
+ if (0 === receipt.surfaceGeneration) throw contractError('control.surfaceGeneration must be greater than zero');
1048
+ requireTrimmed(receipt.instanceId, 'control.instanceId');
1049
+ requireTrimmed(receipt.documentId, 'control.documentId');
1050
+ return Object.freeze({
1051
+ ...receipt,
1052
+ mode: session.mode,
1053
+ fixtureGeneration: receipt.fixtureGeneration ?? null,
1054
+ fixtureDigest: receipt.fixtureDigest ?? null
1055
+ });
1056
+ }
1057
+ function requireSurfaceFixtureOperation(session, operation) {
1058
+ if ('surface' !== session.mode) throw contractError(`${operation} is available only in Surface mode`);
1059
+ }
1060
+ function requireFixtureIdentity(value, label) {
1061
+ requireUnsignedInteger(value.fixtureGeneration, `${label}.fixtureGeneration`, MAX_UINT32);
1062
+ if (0 === value.fixtureGeneration) throw contractError(`${label}.fixtureGeneration must be greater than zero`);
1063
+ requireSha256(value.fixtureDigest, `${label}.fixtureDigest`);
1064
+ }
1065
+ function generatedHttpHeaderInput(header) {
1066
+ return {
1067
+ name: header.name,
1068
+ value: header.value,
1069
+ ...void 0 === header.enabled || null === header.enabled ? {} : {
1070
+ enabled: header.enabled
1071
+ }
1072
+ };
1073
+ }
1074
+ function generatedHttpRequest(request) {
1075
+ return {
1076
+ method: request.method,
1077
+ url: request.url,
1078
+ ...void 0 === request.query ? {} : {
1079
+ query: request.query.map(generatedHttpHeaderInput)
1080
+ },
1081
+ ...void 0 === request.headers ? {} : {
1082
+ headers: request.headers.map(generatedHttpHeaderInput)
1083
+ },
1084
+ ...void 0 === request.body || null === request.body ? {} : {
1085
+ body: request.body
1086
+ },
1087
+ ...void 0 === request.timeoutMs || null === request.timeoutMs ? {} : {
1088
+ timeoutMs: request.timeoutMs
1089
+ },
1090
+ ...void 0 === request.responseBodyLimitBytes || null === request.responseBodyLimitBytes ? {} : {
1091
+ responseBodyLimitBytes: request.responseBodyLimitBytes
1092
+ },
1093
+ ...void 0 === request.followRedirects || null === request.followRedirects ? {} : {
1094
+ followRedirects: request.followRedirects
1095
+ }
1096
+ };
1097
+ }
1098
+ function generatedHttpScript(script) {
1099
+ if (void 0 !== script.credentialRef && void 0 !== script.auth) throw contractError("fixture HTTP scripts cannot combine credentialRef and auth");
1100
+ requireTrimmed(script.request.method, 'fixture HTTP request method', 32);
1101
+ requireHttpUrl(script.request.url, 'fixture HTTP request URL');
1102
+ if ((script.request.query?.length ?? 0) > MAX_FIXTURE_COLLECTION_ITEMS || (script.request.headers?.length ?? 0) > MAX_FIXTURE_COLLECTION_ITEMS || script.response.headers.length > MAX_FIXTURE_COLLECTION_ITEMS) throw contractError(`fixture HTTP header collections may contain at most ${MAX_FIXTURE_COLLECTION_ITEMS} entries`);
1103
+ if (void 0 !== script.repeat) {
1104
+ requireUnsignedInteger(script.repeat, "fixture HTTP script repeat", MAX_FIXTURE_HTTP_REPEATS);
1105
+ if (0 === script.repeat) throw contractError("fixture HTTP script repeat must be greater than zero");
1106
+ }
1107
+ requireHttpUrl(script.response.finalUrl, 'fixture HTTP response finalUrl');
1108
+ requireUnsignedInteger(script.response.status, 'fixture HTTP response status', 599);
1109
+ if (script.response.status < 100) throw contractError('fixture HTTP response status must be between 100 and 599');
1110
+ if ('text' !== script.response.bodyKind && 'binary' !== script.response.bodyKind) throw contractError('fixture HTTP response bodyKind must be text or binary');
1111
+ for (const nullableField of [
1112
+ 'bodyText',
1113
+ 'bodyBase64',
1114
+ 'contentType'
1115
+ ])if (!Object.hasOwn(script.response, nullableField)) throw contractError(`fixture HTTP response ${nullableField} must be explicit, using null when absent`);
1116
+ if (void 0 !== script.credentialRef) requireTrimmed(script.credentialRef, 'fixture HTTP credentialRef', 512);
1117
+ const { bodyBase64, bodyKind, bodyText, contentType, ...response } = script.response;
1118
+ return miniappTestFixtureHttpScriptSchema.parse({
1119
+ request: generatedHttpRequest(script.request),
1120
+ ...void 0 === script.credentialRef ? {} : {
1121
+ credentialRef: script.credentialRef
1122
+ },
1123
+ ...void 0 === script.auth ? {} : {
1124
+ auth: script.auth
1125
+ },
1126
+ response: {
1127
+ ...response,
1128
+ bodyKind,
1129
+ ...null === bodyText ? {} : {
1130
+ bodyText
1131
+ },
1132
+ ...null === bodyBase64 ? {} : {
1133
+ bodyBase64
1134
+ },
1135
+ ...null === contentType ? {} : {
1136
+ contentType
1137
+ }
1138
+ },
1139
+ ...void 0 === script.repeat ? {} : {
1140
+ repeat: script.repeat
1141
+ }
1142
+ });
1143
+ }
1144
+ function publicHttpScriptState(script) {
1145
+ return {
1146
+ ...script,
1147
+ request: script.request,
1148
+ response: {
1149
+ ...script.response,
1150
+ bodyText: script.response.bodyText ?? null,
1151
+ bodyBase64: script.response.bodyBase64 ?? null,
1152
+ contentType: script.response.contentType ?? null
1153
+ }
1154
+ };
1155
+ }
1156
+ function publicFixtureSnapshot(snapshot) {
1157
+ return {
1158
+ ...snapshot,
1159
+ state: {
1160
+ ...snapshot.state,
1161
+ httpScripts: snapshot.state.httpScripts.map(publicHttpScriptState)
1162
+ }
1163
+ };
1164
+ }
1165
+ function requireFixtureCollections(collections, label) {
1166
+ for (const [name, entries] of Object.entries(collections))if (entries.length > MAX_FIXTURE_COLLECTION_ITEMS) throw contractError(`${label}.${name} may contain at most ${MAX_FIXTURE_COLLECTION_ITEMS} entries`);
1167
+ }
1168
+ function requireFixtureSnapshot(snapshot, session) {
1169
+ requireFixtureIdentity(snapshot, 'control.snapshot');
1170
+ if (snapshot.workspaceId !== session.workspaceId) throw contractError('fixture snapshot belongs to another workspace');
1171
+ if (snapshot.channelId !== session.channelId) throw contractError('fixture snapshot belongs to another channel');
1172
+ if (void 0 !== session.fixtureVersion && snapshot.fixtureVersion !== session.fixtureVersion) throw contractError('fixture snapshot version does not match the session');
1173
+ requireUnsignedInteger(snapshot.clockTick, 'control.snapshot.clockTick', Number.MAX_SAFE_INTEGER);
1174
+ requireFixtureCollections(snapshot.state, 'control.snapshot.state');
1175
+ }
1176
+ function requireFixtureHttpCaptures(captures) {
1177
+ requireUnsignedInteger(captures.dropped, 'control.captures.dropped', MAX_UINT32);
1178
+ if (captures.requests.length > MAX_FIXTURE_HTTP_CAPTURES) throw contractError(`control.captures.requests may contain at most ${MAX_FIXTURE_HTTP_CAPTURES} entries`);
1179
+ let previousSequence = 0;
1180
+ for (const capture of captures.requests){
1181
+ requireUnsignedInteger(capture.sequence, 'control.captures.sequence', MAX_UINT32);
1182
+ if (capture.sequence <= previousSequence) throw contractError('control.captures requests must have strictly increasing sequences');
1183
+ previousSequence = capture.sequence;
1184
+ requireTrimmed(capture.request.method, 'control.captures.request.method', 32);
1185
+ requireHttpUrl(capture.request.url, 'control.captures.request.url');
1186
+ }
1187
+ }
1188
+ function publicFixtureLedger(ledger) {
1189
+ requireUnsignedInteger(ledger.dropped, 'control.ledger.dropped', MAX_UINT32);
1190
+ if (ledger.entries.length > MAX_FIXTURE_LEDGER_ENTRIES) throw contractError(`control.ledger.entries may contain at most ${MAX_FIXTURE_LEDGER_ENTRIES} entries`);
1191
+ let previousSequence = 0;
1192
+ return {
1193
+ ...ledger,
1194
+ entries: ledger.entries.map((entry)=>{
1195
+ requireUnsignedInteger(entry.sequence, 'control.ledger.sequence', MAX_UINT32);
1196
+ if (entry.sequence <= previousSequence) throw contractError('control.ledger entries must have strictly increasing sequences');
1197
+ previousSequence = entry.sequence;
1198
+ requireUnsignedInteger(entry.fixtureGeneration, 'control.ledger.fixtureGeneration', MAX_UINT32);
1199
+ if (0 === entry.fixtureGeneration) throw contractError('control.ledger.fixtureGeneration must be greater than zero');
1200
+ requireUnsignedInteger(entry.timestampMs, 'control.ledger.timestampMs', Number.MAX_SAFE_INTEGER);
1201
+ requireTrimmed(entry.operation, 'control.ledger.operation', 256);
1202
+ return entry;
1203
+ })
1204
+ };
1205
+ }
1206
+ async function seedTapMiniappFixture(page, session, seed) {
1207
+ requireSurfaceFixtureOperation(session, 'seed-fixture');
1208
+ requireBoundedJson(seed, 'fixture seed', MAX_FIXTURE_SEED_BYTES);
1209
+ const generatedSeed = miniappTestFixtureSeedSchema.parse({
1210
+ ...seed,
1211
+ httpScripts: (seed.httpScripts ?? []).map(generatedHttpScript)
1212
+ });
1213
+ requireFixtureCollections(generatedSeed, 'fixture seed');
1214
+ const request = miniappTestSeedFixtureControlRequestSchema.parse({
1215
+ schemaVersion: 1,
1216
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1217
+ runId: session.runId,
1218
+ operation: 'seed-fixture',
1219
+ seed: generatedSeed
1220
+ });
1221
+ const receipt = miniappTestSeedFixtureControlReceiptSchema.parse(await dispatchControlRequest(page, request));
1222
+ assertControlReceipt(receipt, session, request.requestId);
1223
+ requireFixtureIdentity(receipt, 'control.seed');
1224
+ requireUnsignedInteger(receipt.surfaceGeneration, 'control.seed.surfaceGeneration', MAX_UINT32);
1225
+ if (0 === receipt.surfaceGeneration) throw contractError('control.seed.surfaceGeneration must be greater than zero');
1226
+ requireTrimmed(receipt.instanceId, 'control.seed.instanceId');
1227
+ requireTrimmed(receipt.documentId, 'control.seed.documentId');
1228
+ return Object.freeze(receipt);
1229
+ }
1230
+ async function snapshotTapMiniappFixture(page, session) {
1231
+ requireSurfaceFixtureOperation(session, 'snapshot-fixture');
1232
+ const request = miniappTestSnapshotFixtureControlRequestSchema.parse({
1233
+ schemaVersion: 1,
1234
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1235
+ runId: session.runId,
1236
+ operation: 'snapshot-fixture'
1237
+ });
1238
+ const rawReceipt = await dispatchControlRequest(page, request);
1239
+ requireBoundedJson(rawReceipt, 'fixture snapshot receipt', MAX_CONTROL_RESULT_BYTES);
1240
+ const receipt = miniappTestSnapshotFixtureControlReceiptSchema.parse(rawReceipt);
1241
+ assertControlReceipt(receipt, session, request.requestId);
1242
+ requireFixtureSnapshot(receipt.snapshot, session);
1243
+ return Object.freeze(publicFixtureSnapshot(receipt.snapshot));
1244
+ }
1245
+ async function scriptTapMiniappHttp(page, session, script) {
1246
+ requireSurfaceFixtureOperation(session, "script-http");
1247
+ requireBoundedJson(script, "fixture HTTP script", MAX_FIXTURE_HTTP_SCRIPT_BYTES);
1248
+ const request = miniappTestScriptHttpControlRequestSchema.parse({
1249
+ schemaVersion: 1,
1250
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1251
+ runId: session.runId,
1252
+ operation: "script-http",
1253
+ script: generatedHttpScript(script)
1254
+ });
1255
+ const receipt = miniappTestScriptHttpControlReceiptSchema.parse(await dispatchControlRequest(page, request));
1256
+ assertControlReceipt(receipt, session, request.requestId);
1257
+ requireUnsignedInteger(receipt.fixtureGeneration, "control.scriptHttp.fixtureGeneration", MAX_UINT32);
1258
+ requireUnsignedInteger(receipt.scriptedRequests, "control.scriptHttp.scriptedRequests", MAX_UINT32);
1259
+ if (0 === receipt.fixtureGeneration || 0 === receipt.scriptedRequests) throw contractError("script-http receipt counters must be greater than zero");
1260
+ return Object.freeze(receipt);
1261
+ }
1262
+ async function readTapMiniappCapturedHttpRequests(page, session) {
1263
+ requireSurfaceFixtureOperation(session, 'captured-http-requests');
1264
+ const request = miniappTestCapturedHttpRequestsControlRequestSchema.parse({
1265
+ schemaVersion: 1,
1266
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1267
+ runId: session.runId,
1268
+ operation: 'captured-http-requests'
1269
+ });
1270
+ const rawReceipt = await dispatchControlRequest(page, request);
1271
+ requireBoundedJson(rawReceipt, 'fixture HTTP capture receipt', MAX_CONTROL_RESULT_BYTES);
1272
+ const receipt = miniappTestCapturedHttpRequestsControlReceiptSchema.parse(rawReceipt);
1273
+ assertControlReceipt(receipt, session, request.requestId);
1274
+ requireFixtureHttpCaptures(receipt.captures);
1275
+ return Object.freeze(receipt.captures);
1276
+ }
1277
+ async function readTapMiniappFixtureLedger(page, session) {
1278
+ requireSurfaceFixtureOperation(session, 'read-ledger');
1279
+ const request = miniappTestReadLedgerControlRequestSchema.parse({
1280
+ schemaVersion: 1,
1281
+ requestId: `sdk-${(0, __rspack_external_node_crypto_2e7c4b46.randomUUID)()}`,
1282
+ runId: session.runId,
1283
+ operation: 'read-ledger'
1284
+ });
1285
+ const rawReceipt = await dispatchControlRequest(page, request);
1286
+ requireBoundedJson(rawReceipt, 'fixture ledger receipt', MAX_CONTROL_RESULT_BYTES);
1287
+ const receipt = miniappTestReadLedgerControlReceiptSchema.parse(rawReceipt);
1288
+ assertControlReceipt(receipt, session, request.requestId);
1289
+ return Object.freeze(publicFixtureLedger(receipt.ledger));
1290
+ }
1291
+ async function quiesceTapMiniappSurface(page, session) {
1292
+ if ('surface' !== session.mode) return;
1293
+ const expectedMarker = await page.locator(session.surfaceSelector).evaluate(async (element, identity)=>{
1294
+ if (!(element instanceof HTMLIFrameElement)) throw new Error('The TAP Surface selector did not resolve to an iframe.');
1295
+ const readyMarker = await new Promise((resolve, reject)=>{
1296
+ const documentElement = globalThis.document.documentElement;
1297
+ let observer;
1298
+ const timeout = globalThis.setTimeout(()=>{
1299
+ observer?.disconnect();
1300
+ reject(new Error('The TAP Surface did not publish its exact active document before the isolation deadline.'));
1301
+ }, 15000);
1302
+ const acceptMarker = ()=>{
1303
+ const marker = documentElement.dataset.tapMiniappTestSurfaceReady?.trim();
1304
+ if (!marker) return false;
1305
+ globalThis.clearTimeout(timeout);
1306
+ observer?.disconnect();
1307
+ resolve(marker);
1308
+ return true;
1309
+ };
1310
+ if (acceptMarker()) return;
1311
+ observer = new MutationObserver(()=>{
1312
+ acceptMarker();
1313
+ });
1314
+ observer.observe(documentElement, {
1315
+ attributes: true,
1316
+ attributeFilter: [
1317
+ 'data-tap-miniapp-test-surface-ready'
1318
+ ]
1319
+ });
1320
+ acceptMarker();
1321
+ });
1322
+ const runtime = element.closest('[data-testid="miniapp-surface-test-runtime"]');
1323
+ const runtimeRunId = runtime?.getAttribute('data-run-id');
1324
+ const generationValue = runtime?.getAttribute('data-surface-generation');
1325
+ const surfaceGeneration = Number(generationValue);
1326
+ const sourceUrl = new URL(element.src);
1327
+ const instanceId = sourceUrl.searchParams.get('instanceId');
1328
+ const legacyInstanceIds = [
1329
+ sourceUrl.searchParams.get('miniappInstanceId'),
1330
+ sourceUrl.searchParams.get('miniappFrameId')
1331
+ ].filter((candidate)=>null !== candidate);
1332
+ let readyIdentity;
1333
+ try {
1334
+ const value = JSON.parse(readyMarker);
1335
+ if ('object' == typeof value && null !== value) readyIdentity = value;
1336
+ } catch {}
1337
+ if (runtimeRunId !== identity.runId || !Number.isSafeInteger(surfaceGeneration) || surfaceGeneration < 1 || sourceUrl.origin !== identity.surfaceAssetOrigin || !instanceId || legacyInstanceIds.some((candidate)=>candidate !== instanceId) || readyIdentity?.runId !== identity.runId || readyIdentity.surfaceGeneration !== surfaceGeneration || readyIdentity.instanceId !== instanceId || 'string' != typeof readyIdentity.documentId || 0 === readyIdentity.documentId.length || readyMarker !== JSON.stringify({
1338
+ runId: identity.runId,
1339
+ surfaceGeneration,
1340
+ instanceId,
1341
+ documentId: readyIdentity.documentId
1342
+ })) throw new Error('The TAP Surface DOM identity does not match its exact run.');
1343
+ const marker = readyMarker;
1344
+ await new Promise((resolve, reject)=>{
1345
+ const timeout = globalThis.setTimeout(()=>{
1346
+ cleanup();
1347
+ reject(new Error('The TAP Surface document did not quiesce before the isolation deadline.'));
1348
+ }, 15000);
1349
+ const cleanup = ()=>{
1350
+ globalThis.clearTimeout(timeout);
1351
+ element.removeEventListener('load', handleLoad);
1352
+ element.removeEventListener('error', handleError);
1353
+ };
1354
+ const handleLoad = ()=>{
1355
+ cleanup();
1356
+ if ('about:blank' !== element.getAttribute('src')) return void reject(new Error('The TAP Surface document changed while it was being quiesced.'));
1357
+ resolve();
1358
+ };
1359
+ const handleError = ()=>{
1360
+ cleanup();
1361
+ reject(new Error('The TAP Surface document could not be quiesced.'));
1362
+ };
1363
+ element.addEventListener('load', handleLoad, {
1364
+ once: true
1365
+ });
1366
+ element.addEventListener('error', handleError, {
1367
+ once: true
1368
+ });
1369
+ element.setAttribute('src', 'about:blank');
1370
+ });
1371
+ return marker;
1372
+ }, {
1373
+ runId: session.runId,
1374
+ surfaceAssetOrigin: session.surfaceAssetOrigin
1375
+ });
1376
+ await page.waitForFunction((marker)=>document.documentElement.dataset.tapMiniappTestSurfaceQuiesced === marker, expectedMarker);
1377
+ return expectedMarker;
1378
+ }
1379
+ async function clearTapMiniappSurfaceBrowserState(context, page, session) {
1380
+ if ('surface' !== session.mode) return;
1381
+ let cdp;
1382
+ try {
1383
+ cdp = await context.newCDPSession(page);
1384
+ await cdp.send('Storage.clearDataForOrigin', {
1385
+ origin: session.surfaceAssetOrigin,
1386
+ storageTypes: 'all'
1387
+ });
1388
+ await cdp.send('DOMStorage.clear', {
1389
+ storageId: {
1390
+ isLocalStorage: true,
1391
+ securityOrigin: session.surfaceAssetOrigin
1392
+ }
1393
+ });
1394
+ await cdp.send('DOMStorage.clear', {
1395
+ storageId: {
1396
+ isLocalStorage: false,
1397
+ securityOrigin: session.surfaceAssetOrigin
1398
+ }
1399
+ });
1400
+ await cdp.send('Network.clearBrowserCache');
1401
+ } finally{
1402
+ await cdp?.detach();
1403
+ }
1404
+ }
1405
+ async function inspectPageTarget(context, page) {
1406
+ let cdp;
1407
+ try {
1408
+ cdp = await context.newCDPSession(page);
1409
+ const response = cdpTargetInfoResponseSchema.parse(await cdp.send('Target.getTargetInfo'));
1410
+ return {
1411
+ browserContextId: response.targetInfo.browserContextId,
1412
+ context,
1413
+ page,
1414
+ targetId: response.targetInfo.targetId,
1415
+ type: response.targetInfo.type,
1416
+ url: response.targetInfo.url
1417
+ };
1418
+ } finally{
1419
+ await cdp?.detach();
1420
+ }
1421
+ }
1422
+ function assertExactTarget(targets, session) {
1423
+ const matchingIdentity = targets.filter((target)=>target.targetId === session.targetId);
1424
+ if (1 !== matchingIdentity.length) throw new Error(`TAP Browser Driver exposed ${matchingIdentity.length} pages with target ${session.targetId} for run ${session.runId}; expected exactly one.`);
1425
+ const target = matchingIdentity[0];
1426
+ if (!target) throw new Error('TAP Browser Driver target selection failed');
1427
+ if (target.type !== session.targetType || target.url !== session.pageUrl || target.page.url() !== session.pageUrl) throw new Error(`TAP Browser Driver target ${session.targetId} did not match its declared page identity.`);
1428
+ if (void 0 !== session.browserContextId && target.browserContextId !== session.browserContextId) throw new Error(`TAP Browser Driver target ${session.targetId} did not match its declared browser context.`);
1429
+ return target;
1430
+ }
1431
+ async function resolveExactTapMiniappTarget(browser, session) {
1432
+ const targets = await Promise.all(browser.contexts().flatMap((context)=>context.pages().map((page)=>inspectPageTarget(context, page))));
1433
+ const target = assertExactTarget(targets, session);
1434
+ return Object.freeze({
1435
+ context: target.context,
1436
+ page: target.page
1437
+ });
1438
+ }
1439
+ async function resolveExactTapMiniappPage(context, session) {
1440
+ const targets = await Promise.all(context.pages().map((page)=>inspectPageTarget(context, page)));
1441
+ return assertExactTarget(targets, session).page;
1442
+ }
1443
+ const SESSION_ENV = 'TAP_MINIAPP_TEST_SESSION_FILE';
1444
+ let sessionPromise;
1445
+ let sessionDocumentPromise;
1446
+ let browserPromise;
1447
+ function parseTapMiniappTestSession(value) {
1448
+ return parseValidatedTapMiniappTestSession(value);
1449
+ }
1450
+ async function loadSessionDocument() {
1451
+ sessionDocumentPromise ??= (async ()=>{
1452
+ const sessionPath = process.env[SESSION_ENV]?.trim();
1453
+ if (!sessionPath) throw new Error(`${SESSION_ENV} is missing. Start this suite from The AI Platform Miniapp Test Lab.`);
1454
+ const raw = await (0, __rspack_external_node_fs_promises_3b710708.readFile)(sessionPath, 'utf8');
1455
+ return JSON.parse(raw);
1456
+ })();
1457
+ return sessionDocumentPromise;
1458
+ }
1459
+ async function loadSession() {
1460
+ sessionPromise ??= loadSessionDocument().then((value)=>parseTapMiniappTestSession(value));
1461
+ return sessionPromise;
78
1462
  }
79
1463
  function fixtureMetadata(session, page) {
1464
+ const reset = ()=>runTapMiniappLifecycleControl(page, session, 'reset-fixture');
1465
+ const remountSurface = ()=>runTapMiniappLifecycleControl(page, session, 'remount-surface');
1466
+ const emitHostEvent = (event, payload)=>emitTapMiniappHostEvent(page, session, event, payload);
80
1467
  return Object.freeze({
81
1468
  allowedNetworkOrigins: Object.freeze([
82
1469
  ...session.allowedNetworkOrigins
83
1470
  ]),
1471
+ adapterVersion: session.adapterVersion,
84
1472
  channelId: session.channelId,
85
1473
  credentialAliases: Object.freeze([
86
1474
  ...session.credentialAliases
87
1475
  ]),
88
1476
  control: Object.freeze({
89
- emitHostEvent: (event, payload)=>emitHostEvent(page, session, event, payload),
90
- reset: async ()=>{
91
- await page.reload({
92
- waitUntil: 'domcontentloaded'
93
- });
94
- await page.locator(session.surfaceSelector).waitFor({
95
- state: 'attached'
96
- });
97
- }
1477
+ emitHostEvent,
1478
+ remountSurface,
1479
+ reset
98
1480
  }),
99
1481
  dataScope: session.dataScope,
1482
+ descriptorDigest: session.descriptorDigest,
1483
+ environment: session.environment,
1484
+ artifacts: session.artifacts,
100
1485
  installationId: session.installationId,
1486
+ fixtureDigest: session.fixtureDigest,
1487
+ hostContractVersion: session.hostContractVersion,
1488
+ hostVersion: session.hostVersion,
1489
+ fixture: Object.freeze({
1490
+ schemaVersion: 1,
1491
+ reset,
1492
+ seed: (seed)=>seedTapMiniappFixture(page, session, seed),
1493
+ snapshot: ()=>snapshotTapMiniappFixture(page, session),
1494
+ http: Object.freeze({
1495
+ script: (script)=>scriptTapMiniappHttp(page, session, script),
1496
+ requests: ()=>readTapMiniappCapturedHttpRequests(page, session)
1497
+ }),
1498
+ ledger: Object.freeze({
1499
+ read: ()=>readTapMiniappFixtureLedger(page, session)
1500
+ })
1501
+ }),
101
1502
  localGeneration: session.localGeneration,
102
1503
  mode: session.mode,
1504
+ matrixEntryId: session.matrixEntryId,
103
1505
  packageId: session.packageId,
104
1506
  permissionScenario: session.permissionScenario,
1507
+ policyDigest: session.policyDigest,
1508
+ profileId: session.profileId,
105
1509
  releaseDigest: session.releaseDigest,
106
1510
  runId: session.runId,
1511
+ runnerName: session.runnerName,
1512
+ runnerVersion: session.runnerVersion,
1513
+ seed: session.seed,
107
1514
  sourceDigest: session.sourceDigest,
108
1515
  surfaceAssetOrigin: session.surfaceAssetOrigin,
109
1516
  surfaceId: session.surfaceId,
110
1517
  testBundleDigest: session.testBundleDigest,
1518
+ target: session.target,
111
1519
  workspaceId: session.workspaceId
112
1520
  });
113
1521
  }
114
1522
  function safeArtifactSegment(value) {
115
- return value.replaceAll(/[^a-zA-Z0-9._-]/g, '-').slice(0, 160);
1523
+ const slug = value.replaceAll(/[^a-zA-Z0-9._-]/g, '-');
1524
+ const digest = (0, __rspack_external_node_crypto_2e7c4b46.createHash)('sha256').update(value).digest('hex').slice(0, 16);
1525
+ return `${slug.slice(0, 143)}-${digest}`;
1526
+ }
1527
+ const rstest_HTTP_PROTOCOLS = new Set([
1528
+ 'http:',
1529
+ 'https:'
1530
+ ]);
1531
+ const SAFE_INTERNAL_PROTOCOLS = new Set([
1532
+ 'about:',
1533
+ 'blob:',
1534
+ 'data:'
1535
+ ]);
1536
+ function explicitHttpOrigin(value, label) {
1537
+ const url = new URL(value);
1538
+ if (!rstest_HTTP_PROTOCOLS.has(url.protocol)) throw new Error(`${label} must use HTTP or HTTPS.`);
1539
+ return url.origin;
1540
+ }
1541
+ function allowedHttpOrigins(session) {
1542
+ return new Set([
1543
+ explicitHttpOrigin(session.pageUrl, 'TAP host page URL'),
1544
+ explicitHttpOrigin(session.surfaceAssetOrigin, 'Surface asset origin'),
1545
+ ...session.allowedNetworkOrigins.map((value)=>explicitHttpOrigin(value, 'Allowed network origin'))
1546
+ ]);
1547
+ }
1548
+ function classifyRequestUrl(value, allowedOrigins) {
1549
+ let url;
1550
+ try {
1551
+ url = new URL(value);
1552
+ } catch {
1553
+ return {
1554
+ action: 'abort',
1555
+ reason: 'malformed-url'
1556
+ };
1557
+ }
1558
+ if (SAFE_INTERNAL_PROTOCOLS.has(url.protocol)) return {
1559
+ action: 'continue',
1560
+ reason: 'safe-internal'
1561
+ };
1562
+ if ('file:' === url.protocol) return {
1563
+ action: 'abort',
1564
+ reason: 'file-scheme',
1565
+ target: 'file:'
1566
+ };
1567
+ if (!rstest_HTTP_PROTOCOLS.has(url.protocol)) return {
1568
+ action: 'abort',
1569
+ reason: 'unsupported-scheme',
1570
+ target: url.protocol.slice(0, 32)
1571
+ };
1572
+ if (!allowedOrigins.has(url.origin)) return {
1573
+ action: 'abort',
1574
+ reason: 'origin-not-allowed',
1575
+ target: url.origin.slice(0, 256)
1576
+ };
1577
+ return {
1578
+ action: 'continue',
1579
+ reason: 'explicit-http-origin'
1580
+ };
1581
+ }
1582
+ function classifyWebSocketUrl(value, allowedOrigins) {
1583
+ let url;
1584
+ try {
1585
+ url = new URL(value);
1586
+ } catch {
1587
+ return {
1588
+ action: 'abort',
1589
+ reason: 'malformed-url'
1590
+ };
1591
+ }
1592
+ if ('ws:' !== url.protocol && 'wss:' !== url.protocol) return {
1593
+ action: 'abort',
1594
+ reason: 'file:' === url.protocol ? 'file-scheme' : 'unsupported-scheme',
1595
+ target: url.protocol.slice(0, 32)
1596
+ };
1597
+ const diagnosticOrigin = url.origin.slice(0, 256);
1598
+ url.protocol = 'ws:' === url.protocol ? 'http:' : 'https:';
1599
+ if (!allowedOrigins.has(url.origin)) return {
1600
+ action: 'abort',
1601
+ reason: 'origin-not-allowed',
1602
+ target: diagnosticOrigin
1603
+ };
1604
+ return {
1605
+ action: 'continue',
1606
+ reason: 'explicit-http-origin'
1607
+ };
1608
+ }
1609
+ function reportUnexpectedWebSocket(webSocket, allowedOrigins) {
1610
+ const decision = classifyWebSocketUrl(webSocket.url(), allowedOrigins);
1611
+ if ('continue' === decision.action) return;
1612
+ const target = decision.target ? ` (${decision.target})` : '';
1613
+ process.emitWarning(`TAP Test Lab observed a WebSocket outside the run's SDK HTTP origin set: ${decision.reason}${target}. This check is diagnostic only; TAP does not yet provide native browser-wide egress enforcement.`, {
1614
+ code: 'TAP_MINIAPP_TEST_NETWORK_DIAGNOSTIC',
1615
+ type: 'Warning'
1616
+ });
1617
+ }
1618
+ async function applyTapMiniappTestEnvironment(context, page, session) {
1619
+ const { environment } = session;
1620
+ if (void 0 !== environment.fixedNow) await page.clock.setFixedTime(environment.fixedNow);
1621
+ await page.setViewportSize(environment.viewport);
1622
+ await page.emulateMedia({
1623
+ colorScheme: environment.theme,
1624
+ reducedMotion: environment.reducedMotion ? 'reduce' : 'no-preference'
1625
+ });
1626
+ const cdp = await context.newCDPSession(page);
1627
+ try {
1628
+ await cdp.send('Emulation.setLocaleOverride', {
1629
+ locale: environment.locale
1630
+ });
1631
+ await cdp.send('Emulation.setTimezoneOverride', {
1632
+ timezoneId: environment.timezone
1633
+ });
1634
+ } finally{
1635
+ await cdp.detach();
1636
+ }
1637
+ }
1638
+ function shouldSaveArtifact(policy, failed) {
1639
+ return 'always' === policy || 'failure-only' === policy && failed;
1640
+ }
1641
+ async function enforceArtifactBudget(paths, maximumBytes) {
1642
+ if (void 0 === maximumBytes) return;
1643
+ const sizes = await Promise.all(paths.map((artifactPath)=>(0, __rspack_external_node_fs_promises_3b710708.stat)(artifactPath)));
1644
+ const total = sizes.reduce((sum, entry)=>sum + entry.size, 0);
1645
+ if (total <= maximumBytes) return;
1646
+ await Promise.all(paths.map((artifactPath)=>(0, __rspack_external_node_fs_promises_3b710708.rm)(artifactPath, {
1647
+ force: true
1648
+ })));
1649
+ throw new Error(`TAP test artifacts used ${total} bytes, exceeding the profile limit of ${maximumBytes} bytes.`);
116
1650
  }
117
1651
  const test = __rspack_external__rstest_playwright_5734ff29.test.extend({
118
1652
  browser: async (_context, use)=>{
119
- const session = await loadSession();
120
- browserPromise ??= __rspack_external_playwright.chromium.connectOverCDP(session.cdpEndpoint, {
121
- headers: {
122
- authorization: `Bearer ${session.cdpAuthorization}`,
123
- 'x-tap-miniapp-test-run': session.runId
124
- }
125
- });
1653
+ browserPromise ??= (async ()=>{
1654
+ const connected = await connectValidatedTapMiniappTestSession(await loadSessionDocument(), (endpoint, options)=>__rspack_external_playwright.chromium.connectOverCDP(endpoint, {
1655
+ headers: {
1656
+ ...options.headers
1657
+ }
1658
+ }));
1659
+ sessionPromise ??= Promise.resolve(connected.session);
1660
+ return connected.connection;
1661
+ })();
126
1662
  await use(await browserPromise);
127
1663
  },
128
- context: async ({ browser, task }, use)=>{
1664
+ context: async ({ browser, onTestFailed, onTestFinished, task }, use)=>{
129
1665
  const session = await loadSession();
130
- const contexts = browser.contexts().filter((candidate)=>candidate.pages().some((page)=>page.url().startsWith(session.pageUrlPrefix)));
131
- if (1 !== contexts.length) throw new Error(`TAP Browser Driver exposed ${contexts.length} matching contexts for run ${session.runId}; expected exactly one.`);
132
- const context = contexts[0];
133
- if (!context) throw new Error('TAP Browser Driver context selection failed');
134
- const hostPage = selectPage(context, session);
135
- const runtimeOrigins = new Set(hostPage.frames().map((frame)=>originOf(frame.url())).filter((origin)=>void 0 !== origin));
136
- const allowedOrigins = new Set([
137
- ...runtimeOrigins,
138
- new URL(session.surfaceAssetOrigin).origin,
139
- ...session.allowedNetworkOrigins.map((value)=>new URL(value).origin)
140
- ]);
141
- const enforceNetworkPolicy = async (route)=>{
142
- const url = route.request().url();
143
- const origin = originOf(url);
144
- if (void 0 === origin || allowedOrigins.has(origin)) return void await route.continue();
1666
+ const { context, page: hostPage } = await resolveExactTapMiniappTarget(browser, session);
1667
+ const allowedOrigins = allowedHttpOrigins(session);
1668
+ const enforceDiagnosticNetworkPolicy = async (route)=>{
1669
+ const decision = classifyRequestUrl(route.request().url(), allowedOrigins);
1670
+ if ('continue' === decision.action) return void await route.continue();
145
1671
  await route.abort('blockedbyclient');
146
1672
  };
147
- await context.route('**/*', enforceNetworkPolicy);
148
- const traceDirectory = (0, __rspack_external_node_path_806ed179.join)(session.artifactDirectory, 'traces', safeArtifactSegment(task.id));
149
- await (0, __rspack_external_node_fs_promises_3b710708.mkdir)(traceDirectory, {
150
- recursive: true
151
- });
152
- await context.tracing.start({
1673
+ const diagnoseWebSocket = (webSocket)=>reportUnexpectedWebSocket(webSocket, allowedOrigins);
1674
+ await context.route('**/*', enforceDiagnosticNetworkPolicy);
1675
+ hostPage.on('websocket', diagnoseWebSocket);
1676
+ const artifactDirectory = (0, __rspack_external_node_path_806ed179.join)(session.artifactDirectory, 'cases', safeArtifactSegment(task.id));
1677
+ const traceEnabled = 'off' !== session.artifacts.trace;
1678
+ let finalized = false;
1679
+ if (traceEnabled) await context.tracing.start({
153
1680
  screenshots: true,
154
1681
  snapshots: true,
155
- sources: true
1682
+ sources: true,
1683
+ title: task.name
156
1684
  });
1685
+ const finalize = async (failed)=>{
1686
+ if (finalized) return;
1687
+ finalized = true;
1688
+ const savedPaths = [];
1689
+ const tracePath = (0, __rspack_external_node_path_806ed179.join)(artifactDirectory, 'trace.zip');
1690
+ const screenshotPath = (0, __rspack_external_node_path_806ed179.join)(artifactDirectory, 'screenshot.png');
1691
+ const summaryPath = (0, __rspack_external_node_path_806ed179.join)(artifactDirectory, 'artifact-summary.json');
1692
+ const debugPath = (0, __rspack_external_node_path_806ed179.join)(artifactDirectory, 'debug.md');
1693
+ try {
1694
+ if (shouldSaveArtifact(session.artifacts.screenshots, failed)) {
1695
+ await (0, __rspack_external_node_fs_promises_3b710708.mkdir)(artifactDirectory, {
1696
+ recursive: true
1697
+ });
1698
+ await hostPage.screenshot({
1699
+ path: screenshotPath,
1700
+ fullPage: true
1701
+ });
1702
+ savedPaths.push(screenshotPath);
1703
+ }
1704
+ if (traceEnabled && shouldSaveArtifact(session.artifacts.trace, failed)) {
1705
+ await (0, __rspack_external_node_fs_promises_3b710708.mkdir)(artifactDirectory, {
1706
+ recursive: true
1707
+ });
1708
+ await context.tracing.stop({
1709
+ path: tracePath
1710
+ });
1711
+ savedPaths.push(tracePath);
1712
+ } else if (traceEnabled) await context.tracing.stop();
1713
+ if (savedPaths.length > 0) {
1714
+ const traceSummary = {
1715
+ schemaVersion: 3,
1716
+ runId: session.runId,
1717
+ taskId: task.id,
1718
+ failed,
1719
+ mode: session.mode,
1720
+ dataScope: session.dataScope,
1721
+ packageId: session.packageId,
1722
+ surfaceId: session.surfaceId,
1723
+ environment: session.environment,
1724
+ artifactPolicy: session.artifacts,
1725
+ sourceDigest: session.sourceDigest,
1726
+ testBundleDigest: session.testBundleDigest,
1727
+ networkPolicyRole: 'diagnostic-only',
1728
+ tracePath: savedPaths.includes(tracePath) ? 'trace.zip' : null,
1729
+ screenshotPath: savedPaths.includes(screenshotPath) ? 'screenshot.png' : null,
1730
+ traceRedacted: false,
1731
+ traceSensitivity: 'raw-sensitive',
1732
+ traceAccessScope: 'channel-only',
1733
+ traceMayContain: [
1734
+ 'authorization headers',
1735
+ 'cookies',
1736
+ 'credential values',
1737
+ 'network request and response bodies',
1738
+ 'DOM snapshots',
1739
+ 'screenshots',
1740
+ 'test sources'
1741
+ ]
1742
+ };
1743
+ await Promise.all([
1744
+ (0, __rspack_external_node_fs_promises_3b710708.writeFile)(summaryPath, `${JSON.stringify(traceSummary, void 0, 2)}\n`, 'utf8'),
1745
+ (0, __rspack_external_node_fs_promises_3b710708.writeFile)(debugPath, [
1746
+ '# Miniapp test artifacts',
1747
+ '',
1748
+ `- Run: \`${session.runId}\``,
1749
+ `- Rstest task: \`${task.id}\``,
1750
+ `- Mode: \`${session.mode}\``,
1751
+ `- Data scope: \`${session.dataScope}\``,
1752
+ `- Surface: \`${session.surfaceId}\``,
1753
+ `- Source digest: \`${session.sourceDigest}\``,
1754
+ `- Test bundle digest: \`${session.testBundleDigest}\``,
1755
+ '- Browser network routing: diagnostic-only; not native egress enforcement',
1756
+ '',
1757
+ 'These files are raw, sensitive, channel-only evidence. They are not redacted and may contain authorization headers, cookies, credential values, network bodies, DOM snapshots, screenshots, and test source.',
1758
+ '',
1759
+ 'Open artifacts from The AI Platform Test Lab for debugging. Do not publish them or attach them to specialist context. The final assertion outcome is authoritative in `report.json` and `report.md`.',
1760
+ ''
1761
+ ].join('\n'), 'utf8')
1762
+ ]);
1763
+ savedPaths.push(summaryPath, debugPath);
1764
+ }
1765
+ await enforceArtifactBudget(savedPaths, session.artifacts.maxBytes);
1766
+ } finally{
1767
+ hostPage.removeListener('websocket', diagnoseWebSocket);
1768
+ await context.unroute('**/*', enforceDiagnosticNetworkPolicy);
1769
+ }
1770
+ };
1771
+ onTestFailed(()=>finalize(true), 0);
157
1772
  try {
158
1773
  await use(context);
159
- } finally{
160
- await context.tracing.stop({
161
- path: (0, __rspack_external_node_path_806ed179.join)(traceDirectory, 'trace.zip')
162
- });
163
- const traceSummary = {
164
- schemaVersion: 2,
165
- runId: session.runId,
166
- taskId: task.id,
167
- mode: session.mode,
168
- dataScope: session.dataScope,
169
- packageId: session.packageId,
170
- surfaceId: session.surfaceId,
171
- sourceDigest: session.sourceDigest,
172
- testBundleDigest: session.testBundleDigest,
173
- tracePath: 'trace.zip',
174
- traceRedacted: false,
175
- traceSensitivity: 'raw-sensitive',
176
- traceAccessScope: 'channel-only',
177
- traceMayContain: [
178
- 'authorization headers',
179
- 'cookies',
180
- 'credential values',
181
- 'network request and response bodies',
182
- 'DOM snapshots',
183
- 'screenshots',
184
- 'test sources'
185
- ]
186
- };
187
- await Promise.all([
188
- (0, __rspack_external_node_fs_promises_3b710708.writeFile)((0, __rspack_external_node_path_806ed179.join)(traceDirectory, 'trace-summary.json'), `${JSON.stringify(traceSummary, void 0, 2)}\n`, 'utf8'),
189
- (0, __rspack_external_node_fs_promises_3b710708.writeFile)((0, __rspack_external_node_path_806ed179.join)(traceDirectory, 'debug.md'), [
190
- '# Miniapp test trace',
191
- '',
192
- `- Run: \`${session.runId}\``,
193
- `- Rstest task: \`${task.id}\``,
194
- `- Mode: \`${session.mode}\``,
195
- `- Data scope: \`${session.dataScope}\``,
196
- `- Surface: \`${session.surfaceId}\``,
197
- `- Source digest: \`${session.sourceDigest}\``,
198
- `- Test bundle digest: \`${session.testBundleDigest}\``,
199
- '',
200
- '`trace.zip` is raw, sensitive, channel-only evidence. It is not redacted and may contain authorization headers, cookies, credential values, network bodies, DOM snapshots, screenshots, and test source.',
201
- '',
202
- 'Open the trace from The AI Platform Test Lab for debugging. Do not publish it or attach it to specialist context. The final assertion outcome is authoritative in `report.json` and `report.md`.',
203
- ''
204
- ].join('\n'), 'utf8')
205
- ]);
206
- await context.unroute('**/*', enforceNetworkPolicy);
1774
+ } catch (error) {
1775
+ await finalize(true);
1776
+ throw error;
207
1777
  }
1778
+ if (task.result?.status === 'fail') await finalize(true);
1779
+ else onTestFinished(()=>finalize(task.result?.status === 'fail'), 0);
208
1780
  },
209
1781
  page: async ({ context }, use)=>{
210
1782
  const session = await loadSession();
211
- const page = selectPage(context, session);
1783
+ const page = await resolveExactTapMiniappPage(context, session);
1784
+ await applyTapMiniappTestEnvironment(context, page, session);
212
1785
  await page.locator(session.surfaceSelector).waitFor({
213
1786
  state: 'attached'
214
1787
  });
1788
+ await page.waitForFunction((runId)=>document.documentElement.dataset.tapMiniappTestControlRun === runId, session.runId);
1789
+ await quiesceTapMiniappSurface(page, session);
1790
+ await clearTapMiniappSurfaceBrowserState(context, page, session);
215
1791
  await use(page);
216
1792
  },
217
1793
  surface: async ({ page }, use)=>{
@@ -220,28 +1796,19 @@ const test = __rspack_external__rstest_playwright_5734ff29.test.extend({
220
1796
  },
221
1797
  tap: async ({ page }, use)=>{
222
1798
  await use(fixtureMetadata(await loadSession(), page));
223
- }
1799
+ },
1800
+ __tapMiniappHookContext: [
1801
+ async ({ browser, context, page, surface, tap }, use)=>{
1802
+ if ('surface' === tap.mode) await tap.fixture.reset();
1803
+ await use(void 0);
1804
+ },
1805
+ {
1806
+ auto: true
1807
+ }
1808
+ ]
224
1809
  });
225
1810
  const afterEach = __rspack_external__rstest_playwright_5734ff29.afterEach;
226
1811
  const beforeEach = __rspack_external__rstest_playwright_5734ff29.beforeEach;
227
- function originOf(value) {
228
- try {
229
- const url = new URL(value);
230
- if (matchesNonNetworkScheme(url.protocol)) return;
231
- return url.origin;
232
- } catch {
233
- return;
234
- }
235
- }
236
- function matchesNonNetworkScheme(protocol) {
237
- return NON_NETWORK_PROTOCOLS.has(protocol);
238
- }
239
- const NON_NETWORK_PROTOCOLS = new Set([
240
- 'about:',
241
- 'blob:',
242
- 'data:',
243
- 'file:'
244
- ]);
245
1812
  var afterAll = __rspack_external__rstest_playwright_5734ff29.afterAll;
246
1813
  var beforeAll = __rspack_external__rstest_playwright_5734ff29.beforeAll;
247
1814
  var describe = __rspack_external__rstest_playwright_5734ff29.describe;