@skillbuilder/miniapp-simulator 0.2.4 → 0.2.7

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.
@@ -0,0 +1,1220 @@
1
+ import { c as je, r as ze, v as ge, o as De, e as Ve } from "./index-CqClPZVv.mjs";
2
+ function F(t) {
3
+ return Object.fromEntries(
4
+ Object.entries(t).filter(
5
+ ([, i]) => i != null && (typeof i != "number" || Number.isFinite(i))
6
+ )
7
+ );
8
+ }
9
+ function We(t) {
10
+ return t.map(F).filter(
11
+ (i) => i.result !== void 0 || i.message !== void 0 || ["time", "memory", "size", "score", "weight", "ratio", "value", "count"].some(
12
+ (o) => i[o] !== void 0
13
+ )
14
+ );
15
+ }
16
+ function we(t, i) {
17
+ const o = k(t), n = k(i), c = k(o.quality), m = k(o.score), y = k(m.byCategory), M = k(o.blocking), h = k(o.classification), w = k(o.versions), R = k(o.paintTiming), U = Array.isArray(M.failures) ? M.failures.map(k) : [], E = U[0] ?? {}, S = v(k(o.loadFailure).code) ?? v(E.code) ?? v(E.id), j = Array.isArray(h.frameworks) ? h.frameworks.map(k) : [], Y = Array.isArray(o.items) ? o.items.map(k) : [], l = (T) => Y.find((_) => _.id === T) ?? {}, q = {
18
+ failure_code: S,
19
+ truncated_reason: Ge(c.truncatedReason),
20
+ quality: F({
21
+ sample_count: a(c.sampleCount),
22
+ interaction_count: a(c.interactionCount),
23
+ first_interaction_ms: a(c.firstInteractionAt),
24
+ reload_count: a(c.reloadCount),
25
+ infrastructure_error_count: a(c.infrastructureErrorCount),
26
+ complete: N(c.complete),
27
+ sufficient: N(c.sufficient),
28
+ probe_saturated: N(c.probeSaturated),
29
+ auto_stop_on_leave_ms: a(o.autoStopOnLeaveMs)
30
+ }),
31
+ blocking: F({ passed: N(M.passed), enforced: N(M.enforced) }),
32
+ classification: {
33
+ engine: v(h.engine)?.slice(0, 32),
34
+ tag_mismatch: N(o.tagMismatch),
35
+ inferred: N(h.inferred),
36
+ source_scan_complete: N(h.sourceScanComplete),
37
+ webgl_3d_active_samples: a(n.webgl3dActiveSamples),
38
+ evidence: Array.isArray(h.evidence) ? h.evidence.filter((T) => typeof T == "string").slice(0, 3).map((T) => T.slice(0, 48)) : [],
39
+ frameworks: j.slice(0, 6).map((T) => ({
40
+ id: v(T.id)?.slice(0, 32),
41
+ confidence: v(T.confidence)?.slice(0, 16),
42
+ evidence: Array.isArray(T.evidence) ? T.evidence.filter((_) => typeof _ == "string").slice(0, 3).map(
43
+ (_) => _.startsWith("source:") ? "source:brand+api" : _.startsWith("filename:") ? "filename" : _.slice(0, 32)
44
+ ) : []
45
+ }))
46
+ },
47
+ category_scores: F({
48
+ memory: G(y.memory),
49
+ stability: G(y.stability),
50
+ performance: G(y.performance),
51
+ experience: G(y.experience),
52
+ package: G(y.package)
53
+ }),
54
+ paint: F({
55
+ fcp_status: v(R.fcpStatus),
56
+ lcp_status: v(R.lcpStatus),
57
+ fcp_threshold_ms: a(l("fcp").threshold),
58
+ lcp_threshold_ms: a(l("lcp").threshold)
59
+ })
60
+ }, H = [
61
+ {
62
+ name: "total_score",
63
+ score: a(m.total),
64
+ result: v(o.status),
65
+ count: U.length,
66
+ ratio: a(k(o.coverage).ratio),
67
+ time: a(c.effectiveMs),
68
+ message: JSON.stringify(q)
69
+ },
70
+ {
71
+ name: "fcp",
72
+ time: a(R.fcpMs),
73
+ score: a(l("fcp").score),
74
+ weight: a(l("fcp").weight)
75
+ },
76
+ {
77
+ name: "lcp",
78
+ time: a(R.lcpMs),
79
+ score: a(l("lcp").score),
80
+ weight: a(l("lcp").weight)
81
+ },
82
+ {
83
+ name: "zip_size",
84
+ size: a(n.zipBytes),
85
+ score: a(l("zipSize").score),
86
+ weight: a(l("zipSize").weight)
87
+ },
88
+ {
89
+ name: "unpacked_size",
90
+ size: a(n.unpackedBytes),
91
+ score: a(l("unpackedSize").score),
92
+ weight: a(l("unpackedSize").weight)
93
+ },
94
+ {
95
+ name: "largest_image",
96
+ size: a(n.largestImageBytes),
97
+ score: a(l("singleImage").score),
98
+ weight: a(l("singleImage").weight)
99
+ },
100
+ {
101
+ name: "uncompressed_js",
102
+ size: a(n.uncompressedJsBytes),
103
+ score: a(l("uncompressedJs").score),
104
+ weight: a(l("uncompressedJs").weight)
105
+ },
106
+ {
107
+ name: "fps_median",
108
+ value: a(n.fpsMedian),
109
+ unit: "fps",
110
+ score: a(l("fps").score),
111
+ weight: a(l("fps").weight)
112
+ },
113
+ {
114
+ name: "long_task_max",
115
+ time: a(n.longTaskMaxMs),
116
+ count: a(n.longTaskTotal),
117
+ score: a(l("longTask").score),
118
+ weight: a(l("longTask").weight)
119
+ },
120
+ {
121
+ name: "js_error_total",
122
+ count: a(n.jsErrorTotal),
123
+ score: a(l("jsError").score),
124
+ weight: a(l("jsError").weight)
125
+ },
126
+ {
127
+ name: "peak_heap",
128
+ memory: a(n.peakHeapBytes),
129
+ score: a(l("peakHeap").score),
130
+ weight: a(l("peakHeap").weight)
131
+ },
132
+ {
133
+ name: "heap_growth",
134
+ value: a(n.heapGrowthMBPerMin),
135
+ unit: "MB/min",
136
+ score: a(l("heapGrowth").score),
137
+ weight: a(l("heapGrowth").weight)
138
+ },
139
+ {
140
+ name: "texture_watermark",
141
+ memory: a(n.texWatermarkBytes),
142
+ score: a(l("texWatermark").score),
143
+ weight: a(l("texWatermark").weight)
144
+ },
145
+ {
146
+ name: "canvas",
147
+ memory: a(n.canvasWatermarkBytes),
148
+ score: a(l("canvasBuffer").score),
149
+ weight: a(l("canvasBuffer").weight)
150
+ },
151
+ {
152
+ name: "decoded_images",
153
+ memory: a(n.imgWatermarkBytes),
154
+ score: a(l("decodedImages").score),
155
+ weight: a(l("decodedImages").weight)
156
+ },
157
+ {
158
+ name: "wasm",
159
+ memory: a(n.wasmPeakBytes),
160
+ score: a(l("wasmMemory").score),
161
+ weight: a(l("wasmMemory").weight)
162
+ },
163
+ {
164
+ name: "max_workers",
165
+ count: a(n.maxWorkers),
166
+ score: a(l("workerCount").score),
167
+ weight: a(l("workerCount").weight)
168
+ },
169
+ { name: "heap_p95", memory: a(n.heapP95Bytes) },
170
+ { name: "buffer_watermark", memory: a(n.bufWatermarkBytes) },
171
+ { name: "fps_p5", value: a(n.fpsP5), unit: "fps" }
172
+ ], A = We(H);
173
+ return A[0].message = JSON.stringify({
174
+ ...q,
175
+ result_record_count: A.length
176
+ }), A.map(
177
+ (T) => F({
178
+ app_type: v(o.appType),
179
+ policy_version: v(w.policyVersion),
180
+ rules_version: v(w.rulesVersion),
181
+ probe_version: v(w.probeVersion),
182
+ result: v(o.status),
183
+ stage: v(o.stopReason),
184
+ ...T
185
+ })
186
+ );
187
+ }
188
+ function k(t) {
189
+ return t && typeof t == "object" && !Array.isArray(t) ? t : {};
190
+ }
191
+ function a(t) {
192
+ return typeof t == "number" && Number.isFinite(t) ? t : void 0;
193
+ }
194
+ function v(t) {
195
+ return typeof t == "string" && t ? t : void 0;
196
+ }
197
+ function N(t) {
198
+ return typeof t == "boolean" ? Number(t) : void 0;
199
+ }
200
+ function G(t) {
201
+ const i = k(t), o = a(i.got), n = a(i.max);
202
+ return o !== void 0 && n !== void 0 && n > 0 ? Math.round(o / n * 1e4) / 100 : void 0;
203
+ }
204
+ function Ge(t) {
205
+ const i = v(t);
206
+ if (i)
207
+ return /runtime|失去响应|超时/i.test(i) ? "runtime_hung" : /内存|熔断|guard/i.test(i) ? "simulator_guard" : /销毁|中断|unload|destroy/i.test(i) ? "session_interrupted" : /reload|刷新/i.test(i) ? "guest_reload" : "collection_interrupted";
208
+ }
209
+ const ce = "RUNTIME_HUNG", Je = 12e3, Ye = 35e3;
210
+ function Ze(t, i) {
211
+ const o = i ? "评测超时未返回:小工具长时间占用主线程,Runtime 失去响应" : "评测超时未返回:探针未上报任何数据,小工具可能在加载期即阻塞主线程", n = t.blocking.failures.map(
212
+ (c) => c.id === "loadFailed" ? { ...c, code: ce, message: o } : c
213
+ );
214
+ return n.some((c) => c.id === "loadFailed") || n.push({ id: "loadFailed", code: ce, message: o }), {
215
+ ...t,
216
+ status: "loadFailed",
217
+ blocking: { ...t.blocking, passed: !1, failures: n },
218
+ loadFailure: { code: ce, message: o },
219
+ quality: { ...t.quality, complete: !1, truncatedReason: o }
220
+ };
221
+ }
222
+ const _e = {
223
+ report() {
224
+ },
225
+ reportEvent() {
226
+ },
227
+ flush() {
228
+ }
229
+ };
230
+ function Ke(t) {
231
+ if (!t.enabled) return _e;
232
+ let i;
233
+ try {
234
+ const o = { business_line: t.businessLine };
235
+ i = je({
236
+ endpoint: ze(o),
237
+ region: "cn",
238
+ resolveUserId: t.resolveUserId ?? (() => Promise.resolve("")),
239
+ onDelivery: t.onDelivery
240
+ });
241
+ } catch {
242
+ return _e;
243
+ }
244
+ return {
245
+ report(o, n = {}) {
246
+ try {
247
+ i.sendCustomPoint({
248
+ name: "simulator_load_stage",
249
+ timestamp: Date.now(),
250
+ payload: {
251
+ business_line: t.businessLine,
252
+ sdk_version: ge,
253
+ renderer: "iframe-service-worker",
254
+ app_id: t.appId,
255
+ session_id: t.sessionId,
256
+ runtime_version: t.runtimeVersion,
257
+ stage: o,
258
+ ...n
259
+ }
260
+ });
261
+ } catch {
262
+ }
263
+ },
264
+ reportEvent(o, n, c) {
265
+ try {
266
+ i.sendCustomPoint({
267
+ name: o,
268
+ timestamp: Date.now(),
269
+ payload: {
270
+ business_line: t.businessLine,
271
+ sdk_version: ge,
272
+ renderer: "iframe-service-worker",
273
+ app_id: t.appId,
274
+ simulator_session_id: t.sessionId,
275
+ runtime_version: t.runtimeVersion,
276
+ ...n
277
+ }
278
+ }), c?.flush && i.flush();
279
+ } catch {
280
+ }
281
+ },
282
+ flush() {
283
+ const o = () => {
284
+ try {
285
+ i.flush();
286
+ } catch {
287
+ }
288
+ };
289
+ try {
290
+ typeof queueMicrotask == "function" ? queueMicrotask(o) : setTimeout(o, 0);
291
+ } catch {
292
+ }
293
+ }
294
+ };
295
+ }
296
+ function P() {
297
+ try {
298
+ return typeof performance < "u" && typeof performance.now == "function" ? performance.now() : Date.now();
299
+ } catch {
300
+ return Date.now();
301
+ }
302
+ }
303
+ function b(t) {
304
+ return Math.max(0, Math.round(P() - t));
305
+ }
306
+ function ke(t, i, o, n = {}) {
307
+ try {
308
+ const c = Xe(o);
309
+ if (!c) {
310
+ Object.keys(n).length > 0 && t.report(i, n);
311
+ return;
312
+ }
313
+ const { duration: m, ...y } = Qe(c);
314
+ t.report(i, {
315
+ result: "success",
316
+ duration: y.network_duration,
317
+ ...n,
318
+ ...y
319
+ }), t.report(`${i}_download`, {
320
+ result: "success",
321
+ duration: m
322
+ });
323
+ } catch {
324
+ Object.keys(n).length > 0 && t.report(i, n);
325
+ }
326
+ }
327
+ function Xe(t) {
328
+ if (typeof performance > "u" || !performance.getEntriesByName) return;
329
+ const i = typeof window > "u" ? t : new URL(t, window.location.href).href, o = performance.getEntriesByName(i, "resource");
330
+ return o[o.length - 1];
331
+ }
332
+ function Qe(t) {
333
+ return {
334
+ network_duration: Math.round(t.duration),
335
+ dns_duration: Math.round(t.domainLookupEnd - t.domainLookupStart),
336
+ connect_duration: Math.round(t.connectEnd - t.connectStart),
337
+ ttfb_duration: Math.round(t.responseStart - t.requestStart),
338
+ duration: Math.round(t.responseEnd - t.responseStart),
339
+ bytes: t.transferSize
340
+ };
341
+ }
342
+ const et = 8, tt = {
343
+ version: et
344
+ }, $ = tt.version, rt = "miniapp-simulator:connect", vt = "inspectorPauseRuntime", ot = 3e4, ve = 2, nt = 100;
345
+ function bt(t) {
346
+ if (!t.appId.trim()) throw new Error("remote simulator appId is required");
347
+ if (!t.businessLine.trim()) throw new Error("remote simulator businessLine is required");
348
+ if (t.auditContext && (!t.auditContext.reviewTaskId.trim() || !t.auditContext.packageVersion.trim()))
349
+ throw new Error("remote simulator auditContext requires reviewTaskId and packageVersion");
350
+ const i = st(t.gateway), o = pt(t.mount), n = ft([t.serviceUrl, ...t.fallbackServiceUrls ?? []]), c = document.createElement("iframe");
351
+ c.className = t.className ?? "", c.allow = t.iframeAllow ?? "camera; microphone; autoplay; geolocation", c.referrerPolicy = "no-referrer", c.style.display = "block", c.style.width = "100%", c.style.height = "100%", c.style.border = "0";
352
+ const m = t.timeout ?? ot, y = /* @__PURE__ */ new Map(), M = $e(t.options), h = new Map(Object.entries(t.hostApi ?? {})), w = /* @__PURE__ */ new Map(), R = /* @__PURE__ */ new Map();
353
+ let U = 0, E = Ie(), S, j, Y, l, q = !1, H, A = !1, T = "single", _ = null, C = !1;
354
+ const z = P();
355
+ let ee = z, te = z, Z, re, oe = t.auditContext?.packageHash;
356
+ const ue = /* @__PURE__ */ new Map(), le = /* @__PURE__ */ new Map(), ne = /* @__PURE__ */ new Map(), se = /* @__PURE__ */ new Map(), D = /* @__PURE__ */ new Set(), g = Ke({
357
+ enabled: t.tracker !== !1,
358
+ businessLine: t.businessLine,
359
+ appId: t.appId,
360
+ sessionId: E,
361
+ resolveUserId: () => Promise.resolve(typeof re?.userId == "string" ? re.userId : ""),
362
+ onDelivery: t.onTrackerDelivery
363
+ });
364
+ let de, V;
365
+ const Ae = new Promise((e, r) => {
366
+ de = e, V = r;
367
+ });
368
+ let K;
369
+ function B() {
370
+ K !== void 0 && (window.clearTimeout(K), K = void 0);
371
+ }
372
+ function Me() {
373
+ B(), K = window.setTimeout(() => {
374
+ const e = new Error(`remote simulator timed out after ${m}ms`);
375
+ C = !0, g.report("client_ready", {
376
+ result: "timeout",
377
+ duration: b(z)
378
+ }), g.flush(), l(e), V(e);
379
+ }, m);
380
+ }
381
+ xe();
382
+ function qe(e) {
383
+ const r = R.get(e.requestId);
384
+ if (r)
385
+ if (R.delete(e.requestId), window.clearTimeout(r.timer), e.ok)
386
+ g.report("remote_request", {
387
+ type: r.method,
388
+ request_id: e.requestId,
389
+ result: "success",
390
+ duration: b(r.startedAt)
391
+ }), r.resolve(e.result);
392
+ else {
393
+ const s = new Error(
394
+ e.error?.message ?? "remote simulator request failed"
395
+ );
396
+ e.error?.code && (s.code = e.error.code), g.report("remote_request", {
397
+ type: r.method,
398
+ request_id: e.requestId,
399
+ result: "fail",
400
+ duration: b(r.startedAt),
401
+ error_name: e.error?.code,
402
+ message: s.message.slice(0, 512)
403
+ }), r.reject(s);
404
+ }
405
+ }
406
+ async function Ue(e, r) {
407
+ const s = h.get(e.event);
408
+ if (typeof s != "function") {
409
+ r.postMessage({
410
+ type: "host-api-response",
411
+ requestId: e.requestId,
412
+ ok: !1,
413
+ error: { message: `hostApi handler is unavailable: ${e.event}` }
414
+ });
415
+ return;
416
+ }
417
+ try {
418
+ const f = await s(e.request);
419
+ r.postMessage({
420
+ type: "host-api-response",
421
+ requestId: e.requestId,
422
+ ok: !0,
423
+ result: f
424
+ });
425
+ } catch (f) {
426
+ const d = f;
427
+ r.postMessage({
428
+ type: "host-api-response",
429
+ requestId: e.requestId,
430
+ ok: !1,
431
+ error: {
432
+ message: d instanceof Error ? d.message : String(f),
433
+ code: d?.code
434
+ }
435
+ });
436
+ }
437
+ }
438
+ async function Ce(e, r) {
439
+ const s = h.get("request");
440
+ if (typeof s != "function") {
441
+ r.postMessage({
442
+ type: "host-request-response",
443
+ requestId: e.requestId,
444
+ ok: !1,
445
+ error: { message: "host request implementation is unavailable" }
446
+ });
447
+ return;
448
+ }
449
+ const f = new AbortController();
450
+ w.set(e.requestId, f);
451
+ try {
452
+ const d = await Ve(s, e.options, {
453
+ signal: f.signal,
454
+ onHeaders(I) {
455
+ r.postMessage({
456
+ type: "host-request-event",
457
+ requestId: e.requestId,
458
+ event: "headers",
459
+ payload: I
460
+ });
461
+ },
462
+ onChunk(I) {
463
+ r.postMessage({
464
+ type: "host-request-event",
465
+ requestId: e.requestId,
466
+ event: "chunk",
467
+ payload: I
468
+ });
469
+ }
470
+ });
471
+ r.postMessage({
472
+ type: "host-request-response",
473
+ requestId: e.requestId,
474
+ ok: !0,
475
+ result: d
476
+ });
477
+ } catch (d) {
478
+ const I = d;
479
+ r.postMessage({
480
+ type: "host-request-response",
481
+ requestId: e.requestId,
482
+ ok: !1,
483
+ error: {
484
+ message: I instanceof Error ? I.message : String(d),
485
+ code: I?.code
486
+ }
487
+ });
488
+ } finally {
489
+ w.delete(e.requestId);
490
+ }
491
+ }
492
+ function Oe(e) {
493
+ w.get(e.requestId)?.abort();
494
+ }
495
+ function Ne(e) {
496
+ if (e.event === "auditTelemetry") {
497
+ const s = Fe(e.payload);
498
+ s && Pe(s);
499
+ return;
500
+ }
501
+ e.event === "inspectorChange" && (A = !!e.payload?.enabled);
502
+ const r = Le(e.payload);
503
+ if (e.event === "auditStarted") {
504
+ const s = He(e.payload);
505
+ s && me(s);
506
+ }
507
+ if (e.event === "auditProgress" && (!r || r === u.sessionId) && (u.sawProgress = !0, pe(u.sessionId)), e.event === "auditReport" || e.event === "auditFailed") {
508
+ if (r && r === u.terminalSessionId) return;
509
+ if (ie(r), r && !D.has(r))
510
+ if (e.event === "auditReport") {
511
+ const s = e.payload;
512
+ O(
513
+ "miniapp_audit_result",
514
+ r,
515
+ we(s?.report, s?.metrics),
516
+ !0
517
+ );
518
+ } else {
519
+ const s = e.payload?.code;
520
+ O(
521
+ "miniapp_audit_result",
522
+ r,
523
+ [
524
+ {
525
+ name: "total_score",
526
+ result: "loadFailed",
527
+ message: typeof s == "string" ? s : "AUDIT_FAILED"
528
+ }
529
+ ],
530
+ !0
531
+ );
532
+ }
533
+ }
534
+ W(e.event, e.payload);
535
+ }
536
+ function Pe(e) {
537
+ const r = e.fields.attempt_no;
538
+ typeof r == "number" && Number.isFinite(r) && ue.set(e.sessionId, r), e.name === "miniapp_audit_result" && D.add(e.sessionId), O(
539
+ e.name,
540
+ e.sessionId,
541
+ [e.fields],
542
+ e.flush === !0
543
+ );
544
+ }
545
+ function O(e, r, s, f = !1) {
546
+ s.forEach((d, I) => {
547
+ const Q = F({
548
+ app_type: d.app_type,
549
+ policy_version: d.policy_version,
550
+ rules_version: d.rules_version,
551
+ probe_version: d.probe_version
552
+ });
553
+ se.set(r, {
554
+ ...se.get(r),
555
+ ...Q
556
+ });
557
+ const x = { ...se.get(r), ...d };
558
+ if (e === "miniapp_audit_session") {
559
+ d.stage === "started" && !ne.has(r) && ne.set(r, Date.now());
560
+ const ye = typeof d.count == "number" ? d.count : le.get(r) ?? 0;
561
+ x.count = ye, x.duration = d.duration ?? Math.max(0, Date.now() - (ne.get(r) ?? Date.now())), le.set(r, ye + 1);
562
+ }
563
+ g.reportEvent(
564
+ e,
565
+ F({
566
+ ...x,
567
+ review_task_id: t.auditContext?.reviewTaskId,
568
+ audit_session_id: r,
569
+ attempt_no: x.attempt_no ?? ue.get(r) ?? 1,
570
+ package_version: t.auditContext?.packageVersion,
571
+ package_hash: oe,
572
+ runtime_version: Z
573
+ }),
574
+ { flush: f && I === s.length - 1 }
575
+ );
576
+ });
577
+ }
578
+ const u = {
579
+ deadlineTimer: null,
580
+ stallTimer: null,
581
+ sessionId: null,
582
+ sawProgress: !1,
583
+ runtimeHungReport: null,
584
+ terminalSessionId: null,
585
+ terminalReport: null
586
+ };
587
+ function Le(e) {
588
+ if (!e || typeof e != "object") return null;
589
+ const r = e.sessionId;
590
+ return typeof r == "string" && r ? r : null;
591
+ }
592
+ function Fe(e) {
593
+ if (!e || typeof e != "object") return null;
594
+ const r = e, s = /* @__PURE__ */ new Set([
595
+ "miniapp_audit_session",
596
+ "miniapp_audit_paint",
597
+ "miniapp_audit_incident",
598
+ "miniapp_audit_package",
599
+ "miniapp_audit_result"
600
+ ]);
601
+ return typeof r.name != "string" || !s.has(r.name) || typeof r.sessionId != "string" || !r.sessionId || !r.fields || typeof r.fields != "object" || Array.isArray(r.fields) ? null : r;
602
+ }
603
+ function He(e) {
604
+ if (!e || typeof e != "object") return null;
605
+ const r = e;
606
+ return r.ok === !0 && typeof r.sessionId == "string" && r.sessionId ? r : null;
607
+ }
608
+ function ie(e) {
609
+ e && u.sessionId && e !== u.sessionId || (u.deadlineTimer !== null && clearTimeout(u.deadlineTimer), u.stallTimer !== null && clearTimeout(u.stallTimer), u.deadlineTimer = null, u.stallTimer = null, u.sessionId = null, u.sawProgress = !1, u.runtimeHungReport = null);
610
+ }
611
+ function fe(e) {
612
+ if (u.sessionId !== e) return;
613
+ const r = u.runtimeHungReport, s = u.sawProgress;
614
+ if (u.deadlineTimer !== null && clearTimeout(u.deadlineTimer), u.stallTimer !== null && clearTimeout(u.stallTimer), u.deadlineTimer = null, u.stallTimer = null, u.sessionId = null, u.runtimeHungReport = null, O("miniapp_audit_session", e, [
615
+ { name: "interrupted", stage: "interrupted", result: "runtime_hung" }
616
+ ]), !r) {
617
+ O(
618
+ "miniapp_audit_result",
619
+ e,
620
+ [{ name: "total_score", result: "loadFailed", message: "RUNTIME_HUNG" }],
621
+ !0
622
+ ), D.add(e), W("auditFailed", {
623
+ sessionId: e,
624
+ code: "RUNTIME_HUNG",
625
+ message: "评测超时未返回:Runtime 失去响应"
626
+ });
627
+ return;
628
+ }
629
+ const f = Ze(r, s);
630
+ u.terminalSessionId = e, u.terminalReport = f, O("miniapp_audit_result", e, we(f), !0), D.add(e), W("auditReport", {
631
+ sessionId: e,
632
+ source: "host-watchdog",
633
+ report: f
634
+ });
635
+ }
636
+ function pe(e) {
637
+ if (!e || u.sessionId !== e) return;
638
+ u.stallTimer !== null && clearTimeout(u.stallTimer);
639
+ const r = setTimeout(() => {
640
+ u.stallTimer === r && fe(e);
641
+ }, Je);
642
+ u.stallTimer = r;
643
+ }
644
+ function me(e, r) {
645
+ ie(), u.terminalSessionId = null, u.terminalReport = null, u.sessionId = e.sessionId, u.runtimeHungReport = e.runtimeHungReport ?? null, u.sawProgress = !1, pe(e.sessionId);
646
+ const f = (typeof e.evaluationDurationMs == "number" ? e.evaluationDurationMs : r?.durationMs ?? 3e4) + Ye, d = e.sessionId, I = setTimeout(() => {
647
+ u.deadlineTimer === I && fe(d);
648
+ }, f);
649
+ u.deadlineTimer = I;
650
+ }
651
+ function he(e, r) {
652
+ let s = y.get(e);
653
+ s || (s = /* @__PURE__ */ new Set(), y.set(e, s)), s.add(r);
654
+ }
655
+ function $e(e) {
656
+ if (!e) return {};
657
+ const { onRouterChange: r, onScreenShot: s, ...f } = e;
658
+ return r && he(
659
+ "routerChange",
660
+ (d) => r(d)
661
+ ), s && he("screenShot", (d) => s(d)), f;
662
+ }
663
+ c.onload = () => {
664
+ _ && ke(g, "runtime_document", _.href, {
665
+ result: "success",
666
+ duration: b(ee)
667
+ }), Be();
668
+ };
669
+ async function Be() {
670
+ if (q || !_) return;
671
+ const e = S, r = E, s = await at(h);
672
+ if (re = s, q || !_ || e !== S) return;
673
+ const f = {
674
+ type: rt,
675
+ protocolVersion: $,
676
+ sessionId: r,
677
+ appId: t.appId,
678
+ businessLine: t.businessLine,
679
+ tracker: t.tracker !== !1,
680
+ auditContext: t.auditContext,
681
+ gateway: i,
682
+ userInfo: s,
683
+ hostApiMethods: be(h),
684
+ hostApiStubs: Te(h),
685
+ options: M
686
+ };
687
+ te = P(), c.contentWindow?.postMessage(f, _.origin, [e.port2]);
688
+ }
689
+ c.onerror = () => {
690
+ const e = new Error(
691
+ `remote simulator failed to load: ${_?.href ?? n[0]}`
692
+ );
693
+ g.report("runtime_document", {
694
+ result: "fail",
695
+ duration: b(ee),
696
+ message: e.message.slice(0, 512)
697
+ }), g.flush(), l(e), C ? W("error", {
698
+ code: "LOAD_FAILED",
699
+ message: e.message,
700
+ url: _?.href,
701
+ cause: e
702
+ }) : (C = !0, B(), V(e));
703
+ }, ct(n, g).then(
704
+ (e) => {
705
+ q || (_ = e, ee = P(), Me(), c.src = e.href, o.appendChild(c));
706
+ },
707
+ (e) => {
708
+ const r = e instanceof Error ? e : new Error(String(e));
709
+ C = !0, B(), g.report("client_ready", {
710
+ result: "fail",
711
+ duration: b(z),
712
+ message: r.message.slice(0, 512)
713
+ }), g.flush(), l(r), V(r);
714
+ }
715
+ );
716
+ async function p(e, ...r) {
717
+ return ae(`${E}-${++U}`, e, ...r);
718
+ }
719
+ async function ae(e, r, ...s) {
720
+ if (q) throw new Error("remote simulator has been destroyed");
721
+ await j;
722
+ const f = mt(s);
723
+ return new Promise((d, I) => {
724
+ const Q = P(), x = window.setTimeout(() => {
725
+ R.delete(e), g.report("remote_request", {
726
+ type: r,
727
+ request_id: e,
728
+ result: "timeout",
729
+ duration: b(Q)
730
+ }), I(new Error(`remote simulator ${r} timed out after ${m}ms`));
731
+ }, m);
732
+ R.set(e, { resolve: d, reject: I, timer: x, method: r, startedAt: Q }), S.port1.postMessage({ type: "request", requestId: e, method: r, args: s }, f);
733
+ });
734
+ }
735
+ return {
736
+ iframe: c,
737
+ ready: Ae,
738
+ load: () => p("load"),
739
+ async loadZip(e, r) {
740
+ const s = `${E}-${++U}`, f = P();
741
+ try {
742
+ const d = await Re(e).arrayBuffer();
743
+ return oe = t.auditContext?.packageHash ?? await Ee(d), g.report("package_materialize", {
744
+ request_id: s,
745
+ result: "success",
746
+ duration: b(f),
747
+ bytes: d.byteLength,
748
+ type: "zip"
749
+ }), ae(s, "loadZip", {
750
+ buffer: d,
751
+ options: r
752
+ });
753
+ } catch (d) {
754
+ throw g.report("package_materialize", {
755
+ request_id: s,
756
+ result: "fail",
757
+ duration: b(f),
758
+ type: "zip",
759
+ message: J(d).slice(0, 512)
760
+ }), d;
761
+ }
762
+ },
763
+ loadFiles: async (e, r) => {
764
+ const s = `${E}-${++U}`, f = P();
765
+ try {
766
+ const d = await ht(e);
767
+ return oe = t.auditContext?.packageHash ?? await gt(d), g.report("package_materialize", {
768
+ request_id: s,
769
+ result: "success",
770
+ duration: b(f),
771
+ type: "files",
772
+ count: Object.keys(d).length,
773
+ bytes: yt(d)
774
+ }), ae(s, "loadFiles", {
775
+ files: d,
776
+ options: r
777
+ });
778
+ } catch (d) {
779
+ throw g.report("package_materialize", {
780
+ request_id: s,
781
+ result: "fail",
782
+ duration: b(f),
783
+ type: "files",
784
+ message: J(d).slice(0, 512)
785
+ }), d;
786
+ }
787
+ },
788
+ loadApp: (e, r) => p("loadApp", e, r),
789
+ unload: () => void p("unload"),
790
+ reload: () => p("reload"),
791
+ capture: (e) => p("capture", e),
792
+ setViewport: (e) => {
793
+ p("setViewport", e);
794
+ },
795
+ switchContentMode: (e) => p("switchContentMode", e),
796
+ switchPhoneFrame: (e) => p("switchPhoneFrame", e),
797
+ permissionSheet: {
798
+ show: (e) => p("permissionSheet.show", e),
799
+ hide: () => {
800
+ p("permissionSheet.hide");
801
+ }
802
+ },
803
+ notePreview: {
804
+ update: (e) => {
805
+ p("notePreview.update", e);
806
+ },
807
+ updateUser: (e) => {
808
+ p("notePreview.updateUser", e);
809
+ },
810
+ updateAppCard: (e) => {
811
+ p("notePreview.updateAppCard", e);
812
+ }
813
+ },
814
+ widgetCover: {
815
+ update: (e) => {
816
+ p("widgetCover.update", e);
817
+ }
818
+ },
819
+ redirectTo: (e, r) => p("router.redirectTo", e, r),
820
+ getCurrentRoute: () => p("router.getRoute"),
821
+ screenShot: () => p("screenShot"),
822
+ setAutoScreenShot: (e) => p("setAutoScreenShot", e),
823
+ inspector: {
824
+ enable: () => {
825
+ A = !0, p("inspector.enable");
826
+ },
827
+ disable: () => {
828
+ A = !1, p("inspector.disable");
829
+ },
830
+ toggle: () => {
831
+ A = !A, p("inspector.toggle");
832
+ },
833
+ isEnabled: () => A,
834
+ clear: () => {
835
+ p("inspector.clear");
836
+ },
837
+ setSelectionMode: (e) => {
838
+ T = e, p("inspector.setSelectionMode", e);
839
+ },
840
+ getSelectionMode: () => T,
841
+ getSceneTree: () => p("inspector.getSceneTree"),
842
+ selectByRef: (e) => p("inspector.selectByRef", e)
843
+ },
844
+ hostApi: {
845
+ set(e, r) {
846
+ h.set(e, r), X();
847
+ },
848
+ registerAll(e) {
849
+ for (const [r, s] of Object.entries(e)) h.set(r, s);
850
+ X();
851
+ },
852
+ remove(e) {
853
+ h.delete(e), X();
854
+ },
855
+ clear() {
856
+ h.clear(), X();
857
+ },
858
+ has: (e) => h.has(e),
859
+ emit: (e, r) => {
860
+ p("hostApi.emit", e, r);
861
+ }
862
+ },
863
+ audit: {
864
+ start: async (e) => {
865
+ const r = await p("audit.start", e);
866
+ return r.ok && me(r, e), r;
867
+ },
868
+ stop: async () => {
869
+ u.terminalReport || await p("audit.stop");
870
+ },
871
+ status: () => u.terminalReport ? Promise.resolve({ phase: "failed", sessionId: u.terminalSessionId }) : p("audit.status"),
872
+ report: () => u.terminalReport ? Promise.resolve(u.terminalReport) : p("audit.report"),
873
+ setPolicy: async (e) => {
874
+ await p("audit.setPolicy", e);
875
+ }
876
+ },
877
+ invoke: p,
878
+ on(e, r) {
879
+ let s = y.get(e);
880
+ return s || (s = /* @__PURE__ */ new Set(), y.set(e, s)), s.add(r), () => s?.delete(r);
881
+ },
882
+ destroy(e) {
883
+ if (q) return;
884
+ q = !0, H?.();
885
+ const r = u.sessionId;
886
+ r && (O("miniapp_audit_session", r, [
887
+ { name: "interrupted", stage: "interrupted", result: "session_interrupted" }
888
+ ]), O(
889
+ "miniapp_audit_result",
890
+ r,
891
+ [{ name: "total_score", result: "loadFailed", message: "SESSION_INTERRUPTED" }],
892
+ !0
893
+ ), D.add(r), W("auditFailed", {
894
+ sessionId: r,
895
+ code: "SESSION_INTERRUPTED",
896
+ message: "评测会话中断:宿主已销毁模拟器会话"
897
+ })), B(), ie(), wt(S.port1, E, ++U, e), l(new Error("remote simulator has been destroyed"));
898
+ for (const s of R.values())
899
+ window.clearTimeout(s.timer), s.reject(new Error("remote simulator has been destroyed"));
900
+ R.clear();
901
+ for (const s of w.values()) s.abort();
902
+ w.clear(), S.port1.close(), g.flush(), c.remove(), y.clear();
903
+ }
904
+ };
905
+ function X() {
906
+ return p("hostApi.sync", be(h), Te(h));
907
+ }
908
+ function xe() {
909
+ H?.(), H = void 0;
910
+ for (const r of w.values()) r.abort();
911
+ w.clear(), S && (S.port1.close(), E = Ie()), U = 0, S = new MessageChannel(), j = new Promise((r, s) => {
912
+ Y = r, l = s;
913
+ }), j.catch(() => {
914
+ });
915
+ const e = S;
916
+ e.port1.onmessage = (r) => {
917
+ if (e !== S) return;
918
+ const s = r.data;
919
+ if (s?.type === "ready") {
920
+ if (s.protocolVersion !== $) {
921
+ const f = new Error(
922
+ `unsupported remote simulator protocol: ${s.protocolVersion} (client=${$})`
923
+ );
924
+ g.report("runtime_handshake", {
925
+ result: "protocol_mismatch",
926
+ duration: b(te),
927
+ runtime_version: s.runtimeVersion
928
+ }), g.flush(), l(f), C || (C = !0, B(), V(f));
929
+ return;
930
+ }
931
+ Z = s.runtimeVersion, H?.(), H = De(c, (f) => {
932
+ e.port1.postMessage({ type: "worker-visibility", visible: f });
933
+ }), g.report("runtime_handshake", {
934
+ result: "success",
935
+ duration: b(te),
936
+ runtime_version: Z
937
+ }), g.report("client_ready", {
938
+ result: "success",
939
+ duration: b(z),
940
+ runtime_version: Z
941
+ }), Y(s), C || (C = !0, B(), de(s));
942
+ return;
943
+ }
944
+ if (s?.type === "response") {
945
+ qe(s);
946
+ return;
947
+ }
948
+ if (s?.type === "host-api-request") {
949
+ Ue(s, e.port1);
950
+ return;
951
+ }
952
+ if (s?.type === "host-request") {
953
+ Ce(s, e.port1);
954
+ return;
955
+ }
956
+ if (s?.type === "host-request-abort") {
957
+ Oe(s);
958
+ return;
959
+ }
960
+ s?.type === "event" && Ne(s);
961
+ }, e.port1.start();
962
+ }
963
+ function W(e, r) {
964
+ for (const s of [e, "*"])
965
+ for (const f of y.get(s) ?? []) f(r);
966
+ }
967
+ }
968
+ function st(t) {
969
+ if (!t) return;
970
+ const i = {};
971
+ for (const [o, n] of Object.entries(t)) {
972
+ if (typeof n != "string" || !n.trim())
973
+ throw new Error(`remote simulator gateway.${o} must be a non-empty HTTPS URL`);
974
+ const c = n.trim().replace(/\/+$/, "");
975
+ let m;
976
+ try {
977
+ m = new URL(c);
978
+ } catch {
979
+ throw new Error(`remote simulator gateway.${o} must be an absolute HTTPS URL`);
980
+ }
981
+ if (!it(m))
982
+ throw new Error(
983
+ `remote simulator gateway.${o} must use HTTPS (HTTP is allowed only for loopback development)`
984
+ );
985
+ i[o] = c;
986
+ }
987
+ if (!i.edith)
988
+ throw new Error("remote simulator gateway.edith is required");
989
+ if (!i.www)
990
+ throw new Error("remote simulator gateway.www is required");
991
+ return i;
992
+ }
993
+ function it(t) {
994
+ return t.protocol === "https:" ? !0 : t.protocol === "http:" && (t.hostname === "localhost" || t.hostname === "127.0.0.1" || t.hostname === "[::1]");
995
+ }
996
+ function be(t) {
997
+ return [...t].filter(([, i]) => typeof i == "function").map(([i]) => i);
998
+ }
999
+ async function at(t) {
1000
+ const i = t.get("getUserInfo");
1001
+ if (typeof i == "function")
1002
+ try {
1003
+ const o = await i({
1004
+ event: "getUserInfo",
1005
+ message: {},
1006
+ callbackId: ""
1007
+ });
1008
+ return o && typeof o == "object" ? o : void 0;
1009
+ } catch {
1010
+ return;
1011
+ }
1012
+ }
1013
+ function Te(t) {
1014
+ return Object.fromEntries(
1015
+ [...t].filter((i) => {
1016
+ const o = i[1];
1017
+ return typeof o != "function" && typeof o.toast == "string";
1018
+ })
1019
+ );
1020
+ }
1021
+ class L extends Error {
1022
+ constructor(i, o, n, c) {
1023
+ super(i), this.kind = o, this.retryable = n, this.status = c, this.name = "ManifestRequestError";
1024
+ }
1025
+ }
1026
+ async function ct(t, i) {
1027
+ const o = [], n = new Set(t.map((c) => c.href));
1028
+ for (let c = 1; c <= ve; c += 1) {
1029
+ for (const [m, y] of t.entries()) {
1030
+ if (c > 1 && !n.has(y.href)) continue;
1031
+ const M = P();
1032
+ try {
1033
+ const h = await ut(y), w = Se(y);
1034
+ return ke(i, "runtime_manifest", w.href, {
1035
+ result: "success",
1036
+ duration: b(M),
1037
+ type: m === 0 ? "primary" : "fallback",
1038
+ count: c
1039
+ }), h;
1040
+ } catch (h) {
1041
+ const w = lt(h);
1042
+ i.report("runtime_manifest", {
1043
+ result: "fail",
1044
+ duration: b(M),
1045
+ type: m === 0 ? "primary" : "fallback",
1046
+ count: c,
1047
+ ...w.status === void 0 ? { error_name: w.kind } : { code: w.status },
1048
+ message: w.message.slice(0, 512)
1049
+ }), o.push(`${y.href} attempt ${c}: ${w.message}`), w.retryable || n.delete(y.href);
1050
+ }
1051
+ }
1052
+ if (c >= ve || n.size === 0) break;
1053
+ await dt();
1054
+ }
1055
+ throw new Error(`remote simulator services unavailable: ${o.join("; ")}`);
1056
+ }
1057
+ async function ut(t) {
1058
+ const i = Se(t);
1059
+ i.searchParams.set("protocolVersion", String($));
1060
+ let o;
1061
+ try {
1062
+ o = await fetch(i, {
1063
+ method: "GET",
1064
+ credentials: "omit",
1065
+ cache: "no-store"
1066
+ });
1067
+ } catch (m) {
1068
+ throw new L(
1069
+ `remote simulator manifest network error: ${J(m)}`,
1070
+ "MANIFEST_NETWORK_ERROR",
1071
+ !0
1072
+ );
1073
+ }
1074
+ if (!o.ok)
1075
+ throw new L(
1076
+ `remote simulator manifest request failed: HTTP ${o.status}`,
1077
+ "MANIFEST_HTTP_ERROR",
1078
+ !0,
1079
+ o.status
1080
+ );
1081
+ let n;
1082
+ try {
1083
+ n = await o.json();
1084
+ } catch (m) {
1085
+ throw new L(
1086
+ `remote simulator manifest JSON is invalid: ${J(m)}`,
1087
+ "MANIFEST_INVALID_JSON",
1088
+ !0
1089
+ );
1090
+ }
1091
+ if (typeof n.buildId != "string" || !n.buildId || typeof n.documentUrl != "string" || !n.documentUrl)
1092
+ throw new L(
1093
+ "remote simulator manifest response is invalid",
1094
+ "MANIFEST_INVALID_RESPONSE",
1095
+ !1
1096
+ );
1097
+ if (n.protocolVersion !== $)
1098
+ throw new L(
1099
+ `unsupported remote simulator protocol: ${String(n.protocolVersion)} (client=${$})`,
1100
+ "MANIFEST_PROTOCOL_MISMATCH",
1101
+ !1
1102
+ );
1103
+ const c = new URL(n.documentUrl, i);
1104
+ if (c.origin !== t.origin)
1105
+ throw new L(
1106
+ `remote simulator document origin mismatch: ${c.origin} (service=${t.origin})`,
1107
+ "MANIFEST_ORIGIN_MISMATCH",
1108
+ !1
1109
+ );
1110
+ return c;
1111
+ }
1112
+ function lt(t) {
1113
+ return t instanceof L ? t : new L(J(t), "MANIFEST_UNKNOWN_ERROR", !1);
1114
+ }
1115
+ function dt() {
1116
+ return new Promise((t) => window.setTimeout(t, nt));
1117
+ }
1118
+ function Se(t) {
1119
+ const i = t.href.endsWith("/") ? t : new URL(`${t.href}/`), o = new URL("runtime-manifest", i);
1120
+ return o.searchParams.set("protocolVersion", String($)), o;
1121
+ }
1122
+ function ft(t) {
1123
+ const i = /* @__PURE__ */ new Set(), o = [];
1124
+ for (const n of t) {
1125
+ const c = new URL(n, window.location.href), m = c.href.endsWith("/") ? c : new URL(`${c.href}/`);
1126
+ i.has(m.href) || (i.add(m.href), o.push(m));
1127
+ }
1128
+ return o;
1129
+ }
1130
+ function J(t) {
1131
+ return t instanceof Error ? t.message : String(t);
1132
+ }
1133
+ function pt(t) {
1134
+ const i = typeof t == "string" ? document.querySelector(t) : t;
1135
+ if (!i) throw new Error("remote simulator mount element not found");
1136
+ return i;
1137
+ }
1138
+ function Re(t) {
1139
+ if (t instanceof Blob) return t;
1140
+ const i = t instanceof ArrayBuffer ? t : Uint8Array.from(t).buffer;
1141
+ return new Blob([i]);
1142
+ }
1143
+ function mt(t) {
1144
+ const i = /* @__PURE__ */ new Set(), o = (n) => {
1145
+ if (n instanceof ArrayBuffer) {
1146
+ i.add(n);
1147
+ return;
1148
+ }
1149
+ if (ArrayBuffer.isView(n)) {
1150
+ i.add(n.buffer);
1151
+ return;
1152
+ }
1153
+ if (!(!n || typeof n != "object")) {
1154
+ if (Array.isArray(n)) {
1155
+ n.forEach(o);
1156
+ return;
1157
+ }
1158
+ Object.values(n).forEach(o);
1159
+ }
1160
+ };
1161
+ return o(t), [...i];
1162
+ }
1163
+ async function ht(t) {
1164
+ return Object.fromEntries(
1165
+ await Promise.all(
1166
+ Object.entries(t).map(async ([i, o]) => [
1167
+ i,
1168
+ typeof o == "string" ? o : await Re(o).arrayBuffer()
1169
+ ])
1170
+ )
1171
+ );
1172
+ }
1173
+ function yt(t) {
1174
+ try {
1175
+ const i = new TextEncoder();
1176
+ return Object.values(t).reduce((o, n) => typeof n == "string" ? o + i.encode(n).byteLength : n instanceof ArrayBuffer || ArrayBuffer.isView(n) ? o + n.byteLength : o, 0);
1177
+ } catch {
1178
+ return;
1179
+ }
1180
+ }
1181
+ async function gt(t) {
1182
+ try {
1183
+ const i = [];
1184
+ for (const [o, n] of Object.entries(t).sort(([c], [m]) => c.localeCompare(m))) {
1185
+ const c = typeof n == "string" ? new TextEncoder().encode(n).byteLength : (n instanceof ArrayBuffer, n.byteLength);
1186
+ i.push(`${o.length}:${o}:${c}:`, n);
1187
+ }
1188
+ return Ee(await new Blob(i).arrayBuffer());
1189
+ } catch {
1190
+ return;
1191
+ }
1192
+ }
1193
+ async function Ee(t) {
1194
+ try {
1195
+ if (typeof crypto > "u" || !crypto.subtle) return;
1196
+ const i = await crypto.subtle.digest("SHA-256", t);
1197
+ return [...new Uint8Array(i)].map((o) => o.toString(16).padStart(2, "0")).join("");
1198
+ } catch {
1199
+ return;
1200
+ }
1201
+ }
1202
+ function wt(t, i, o, n) {
1203
+ try {
1204
+ t.postMessage({
1205
+ type: "request",
1206
+ requestId: `${i}-${o}`,
1207
+ method: "destroy",
1208
+ args: [n]
1209
+ });
1210
+ } catch {
1211
+ }
1212
+ }
1213
+ function Ie() {
1214
+ return typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1215
+ }
1216
+ export {
1217
+ vt as R,
1218
+ $ as a,
1219
+ bt as c
1220
+ };