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