@ai-ecoverse/slicc-browsers 1.24.1 → 1.25.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.
@@ -514,6 +514,1663 @@ async function sandboxedSrcdoc({
514
514
  };
515
515
  }
516
516
 
517
+ const pageFrameEvents = [
518
+ 'Page.frameAttached',
519
+ 'Page.frameStartedLoading',
520
+ 'Page.frameNavigated',
521
+ 'Page.frameRequestedNavigation',
522
+ 'Page.lifecycleEvent',
523
+ 'Page.navigatedWithinDocument',
524
+ ];
525
+
526
+ function midFrameIdsOf(raw) {
527
+ if (raw.midFrameIds?.size) return raw.midFrameIds;
528
+ return new Set([raw.midFrameId].filter(Boolean));
529
+ }
530
+
531
+ function frameEventHit(event, raw) {
532
+ if (!pageFrameEvents.includes(event.method)) return false;
533
+ const params = event.params ?? {};
534
+ const frame = params.frame ?? {};
535
+ const frameId = params.frameId ?? frame.id;
536
+ const parentId = params.parentFrameId ?? params.parentId ?? frame.parentId;
537
+ const url = params.url ?? frame.url ?? '';
538
+ if (frameId && raw.frameIds.has(frameId)) return true;
539
+ if (parentId && midFrameIdsOf(raw).has(parentId)) return true;
540
+ if (typeof url === 'string' && url.length > 0 && raw.urls.has(url)) return true;
541
+ return false;
542
+ }
543
+
544
+ function contextHit(event, raw) {
545
+ if (event.method !== 'Runtime.executionContextCreated') return false;
546
+ const context = event.params?.context;
547
+ const frameId = context?.auxData?.frameId;
548
+ if (frameId && raw.frameIds.has(frameId)) return true;
549
+ if (raw.frameIds.size) return false;
550
+ const origin = context?.origin ?? '';
551
+ return Boolean(origin && raw.origins.has(origin));
552
+ }
553
+
554
+ function treeMentions(tree, raw) {
555
+ const mids = midFrameIdsOf(raw);
556
+ for (const frame of walkFrames(tree)) {
557
+ if (raw.frameIds.has(frame.id)) return true;
558
+ if (typeof frame.url === 'string' && frame.url.length > 0 && raw.urls.has(frame.url))
559
+ return true;
560
+ if (frame.parentId && mids.has(frame.parentId)) return true;
561
+ }
562
+ const visit = (node, underMid) => {
563
+ if (!node?.frame) return false;
564
+ const here = underMid || mids.has(node.frame.id);
565
+ for (const child of node.childFrames ?? []) {
566
+ if (here) return true;
567
+ if (visit(child, here)) return true;
568
+ }
569
+ return false;
570
+ };
571
+ return visit(tree, false);
572
+ }
573
+
574
+ function resourceMentions(resource, raw) {
575
+ const frameTree = resource?.frameTree ?? resource;
576
+ if (treeMentions(frameTree, raw)) return true;
577
+ const text = JSON.stringify(resource ?? {});
578
+ for (const id of raw.frameIds) if (text.includes(id)) return true;
579
+ for (const url of raw.urls) if (url && text.includes(url)) return true;
580
+ for (const mid of midFrameIdsOf(raw)) {
581
+ if (text.includes(`"parentId":"${mid}"`)) return true;
582
+ }
583
+ return false;
584
+ }
585
+
586
+ function midFrameAttachedHit(event, raw) {
587
+ if (event.method !== 'Page.frameAttached') return false;
588
+ const frameId = event.params?.frameId;
589
+ return Boolean(frameId && midFrameIdsOf(raw).has(frameId));
590
+ }
591
+
592
+ function childMatches(url, innerNeedle) {
593
+ if (innerNeedle === 'about:srcdoc') return url === 'about:srcdoc';
594
+ return typeof url === 'string' && (url === innerNeedle || url.includes(innerNeedle));
595
+ }
596
+
597
+ function midMatches(midUrl, midHint) {
598
+ if (!midHint) return true;
599
+ try {
600
+ const hint = new URL(midHint);
601
+ const mid = new URL(midUrl);
602
+ return mid.origin === hint.origin;
603
+ } catch {
604
+ return midUrl.includes(midHint) || midUrl.startsWith(String(midHint).split('?')[0]);
605
+ }
606
+ }
607
+
608
+ function grandchildFromMid(mid, innerNeedle) {
609
+ const midUrl = mid.frame?.url ?? '';
610
+ for (const child of mid.childFrames ?? []) {
611
+ const url = child.frame?.url ?? '';
612
+ if (!childMatches(url, innerNeedle)) continue;
613
+ return {
614
+ midFrameId: mid.frame.id,
615
+ midUrl,
616
+ frameId: child.frame.id,
617
+ url,
618
+ parentId: child.frame.parentId ?? mid.frame.id,
619
+ };
620
+ }
621
+ return null;
622
+ }
623
+
624
+ function findGrandchild(tree, midHint, innerNeedle) {
625
+ if (!tree?.frame) return null;
626
+ for (const mid of tree.childFrames ?? []) {
627
+ if (!midMatches(mid.frame?.url ?? '', midHint)) continue;
628
+ const hit = grandchildFromMid(mid, innerNeedle);
629
+ if (hit) return hit;
630
+ }
631
+ for (const mid of tree.childFrames ?? []) {
632
+ if (!/\/oopif-(mid|srcdoc)/.test(mid.frame?.url ?? '')) continue;
633
+ const hit = grandchildFromMid(mid, innerNeedle);
634
+ if (hit) return hit;
635
+ }
636
+ return null;
637
+ }
638
+
639
+ function hitFromMidTree(midTree, innerNeedle, midUrl) {
640
+ if (!midTree?.frame) return null;
641
+ for (const child of midTree.childFrames ?? []) {
642
+ const url = child.frame?.url ?? '';
643
+ if (!childMatches(url, innerNeedle)) continue;
644
+ return {
645
+ midFrameId: midTree.frame.id,
646
+ midUrl: midTree.frame.url ?? midUrl ?? '',
647
+ frameId: child.frame.id,
648
+ url,
649
+ parentId: child.frame.parentId ?? midTree.frame.id,
650
+ };
651
+ }
652
+ return null;
653
+ }
654
+
655
+ function targetSnapshot(infos) {
656
+ return (infos ?? []).map((info) => ({
657
+ targetId: info.targetId,
658
+ type: info.type,
659
+ url: info.url,
660
+ parentId: info.parentId,
661
+ }));
662
+ }
663
+
664
+ async function listTargetSnapshot(reader) {
665
+ const listed = await outcome(reader.send('Target.getTargets', {}));
666
+ if (!answered(listed) || !listed.ok) return { unanswered: !answered(listed), targets: [] };
667
+ return { unanswered: false, targets: targetSnapshot(listed.result?.targetInfos) };
668
+ }
669
+
670
+ function liveNestPlan(pageUrl, innerKind, innerHint) {
671
+ const page = new URL(pageUrl);
672
+ const midRaw = page.searchParams.get('mid');
673
+ let midNeedle = null;
674
+ if (midRaw) {
675
+ try {
676
+ midNeedle = new URL(midRaw).searchParams.get('n');
677
+ } catch {
678
+ midNeedle = null;
679
+ }
680
+ }
681
+ page.searchParams.set('live', '1');
682
+ return {
683
+ liveUrl: page.toString(),
684
+ innerHint: innerHint || (innerKind === 'srcdoc' ? 'about:srcdoc' : ''),
685
+ midNeedle,
686
+ };
687
+ }
688
+
689
+ function stampedMidLive(midUrl, innerKind, innerHint) {
690
+ const stamp = `live-${Date.now().toString(36)}`;
691
+ try {
692
+ const mid = new URL(midUrl);
693
+ mid.searchParams.set('n', `${mid.searchParams.get('n') ?? 'mid'}-${stamp}`);
694
+ if (innerKind === 'srcdoc' || innerHint === 'about:srcdoc') {
695
+ return {
696
+ midUrl: mid.toString(),
697
+ innerHint: 'about:srcdoc',
698
+ midNeedle: mid.searchParams.get('n'),
699
+ };
700
+ }
701
+ const innerRaw = mid.searchParams.get('inner');
702
+ if (!innerRaw) {
703
+ return {
704
+ midUrl: mid.toString(),
705
+ innerHint,
706
+ midNeedle: mid.searchParams.get('n'),
707
+ };
708
+ }
709
+ const inner = new URL(innerRaw);
710
+ const prior = inner.searchParams.get('n') ?? `inner-${stamp}`;
711
+ inner.searchParams.set('n', `${prior}-${stamp}`);
712
+ mid.searchParams.set('inner', inner.toString());
713
+ return {
714
+ midUrl: mid.toString(),
715
+ innerHint: inner.searchParams.get('n'),
716
+ midNeedle: mid.searchParams.get('n'),
717
+ };
718
+ } catch {
719
+ return { midUrl, innerHint, midNeedle: null };
720
+ }
721
+ }
722
+
723
+ async function waitChildUnderMid(
724
+ reader,
725
+ midAttached,
726
+ innerHint,
727
+ budget,
728
+ internalSessions,
729
+ beforeIds,
730
+ midNeedle = null
731
+ ) {
732
+ return until(async () => {
733
+ return hitFromGrandchildTarget(
734
+ reader,
735
+ midAttached,
736
+ innerHint,
737
+ internalSessions,
738
+ beforeIds,
739
+ midNeedle
740
+ );
741
+ }, budget);
742
+ }
743
+
744
+ async function attachIframeTarget(reader, match, internalSessions) {
745
+ const listed = await outcome(reader.send('Target.getTargets', {}));
746
+ if (!answered(listed) || !listed.ok) return null;
747
+ const info = (listed.result?.targetInfos ?? []).find(
748
+ (entry) => entry.type === 'iframe' && match(entry)
749
+ );
750
+ if (!info?.targetId) return null;
751
+ const attached = await outcome(
752
+ reader.send('Target.attachToTarget', { targetId: info.targetId, flatten: true })
753
+ );
754
+ if (!answered(attached) || !attached.ok || !attached.result?.sessionId) return null;
755
+ internalSessions?.add(attached.result.sessionId);
756
+ await outcome(reader.send('Page.enable', {}, attached.result.sessionId));
757
+ await outcome(reader.send('Runtime.enable', {}, attached.result.sessionId));
758
+ return { info, sessionId: attached.result.sessionId };
759
+ }
760
+
761
+ async function armMidChildWatch(reader, midSession, waitMs = 1500) {
762
+ await outcome(
763
+ reader.send(
764
+ 'Target.setAutoAttach',
765
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
766
+ midSession
767
+ )
768
+ );
769
+ await until(async () => {
770
+ const evaled = await outcome(
771
+ reader.send(
772
+ 'Runtime.evaluate',
773
+ { expression: 'document.querySelector("iframe")?.src || ""', returnByValue: true },
774
+ midSession
775
+ )
776
+ );
777
+ if (!answered(evaled) || !evaled.ok) return null;
778
+ const src = evaled.result?.result?.value;
779
+ return typeof src === 'string' && src.length > 0 ? src : null;
780
+ }, waitMs);
781
+ }
782
+
783
+ async function hitFromGrandchildTarget(
784
+ reader,
785
+ midAttached,
786
+ innerHint,
787
+ internalSessions,
788
+ beforeIds = null,
789
+ midNeedle = null
790
+ ) {
791
+ if (!midAttached.armed) {
792
+ await armMidChildWatch(reader, midAttached.sessionId, 400);
793
+ midAttached.armed = true;
794
+ }
795
+ const midTree = await readTree(reader, midAttached.sessionId);
796
+ const midFrameId = midTree?.frame?.id;
797
+ const midUrl = midTree?.frame?.url ?? midAttached.info.url ?? '';
798
+ const tag = midTagFrom(midUrl, midNeedle);
799
+ const fromMid = hitFromMidTree(midTree, innerHint, midUrl);
800
+ if (fromMid) {
801
+ return {
802
+ tree: midTree,
803
+ hit: fromMid,
804
+ via: 'mid-target',
805
+ midSession: midAttached.sessionId,
806
+ midTargetId: midAttached.info.targetId,
807
+ };
808
+ }
809
+ const child = await attachIframeTarget(
810
+ reader,
811
+ (info) => {
812
+ if (beforeIds?.has(info.targetId)) return false;
813
+ if (!childMatches(info.url ?? '', innerHint)) return false;
814
+ return info.parentId === midAttached.info.targetId;
815
+ },
816
+ internalSessions
817
+ );
818
+ if (!child) return null;
819
+ if (innerHint === 'about:srcdoc' && tag) {
820
+ if (!(await srcdocDocHasTag(reader, child.sessionId, tag))) return null;
821
+ }
822
+ const childTree = await readTree(reader, child.sessionId);
823
+ if (!childTree?.frame) return null;
824
+ const frameId = childTree.frame.id;
825
+ const frameParentId = childTree.frame.parentId ?? midFrameId;
826
+ const linked =
827
+ innerHint !== 'about:srcdoc' ||
828
+ srcdocLinkedToMid(reader, midFrameId ?? midAttached.info.targetId, frameId, frameParentId) ||
829
+ child.info.parentId === midAttached.info.targetId;
830
+ if (innerHint === 'about:srcdoc' && !linked) return null;
831
+ return {
832
+ tree: childTree,
833
+ hit: {
834
+ midFrameId: midFrameId ?? midAttached.info.targetId,
835
+ midUrl,
836
+ frameId,
837
+ url: childTree.frame.url ?? child.info.url ?? '',
838
+ parentId: frameParentId,
839
+ },
840
+ via: 'grandchild-target',
841
+ midSession: midAttached.sessionId,
842
+ midTargetId: midAttached.info.targetId,
843
+ grandchildSession: child.sessionId,
844
+ grandchildTargetId: child.info.targetId,
845
+ };
846
+ }
847
+
848
+ function midTargetMatch(info, midHint, pageId, midNeedle, beforeIds) {
849
+ if (beforeIds?.has(info.targetId)) return false;
850
+ if (midNeedle && !(info.url ?? '').includes(midNeedle)) return false;
851
+ if (!midMatches(info.url ?? '', midHint)) return false;
852
+ if (pageId && info.parentId && info.parentId !== pageId) return false;
853
+ return true;
854
+ }
855
+
856
+ function midTagFrom(midUrl, midNeedle) {
857
+ if (typeof midNeedle === 'string' && midNeedle.length > 0) return midNeedle;
858
+ try {
859
+ return new URL(midUrl).searchParams.get('n');
860
+ } catch {
861
+ return null;
862
+ }
863
+ }
864
+
865
+ function localMidFrame(tree, midHint) {
866
+ if (!tree?.frame) return null;
867
+ for (const mid of tree.childFrames ?? []) {
868
+ if (!midMatches(mid.frame?.url ?? '', midHint)) continue;
869
+ return mid;
870
+ }
871
+ for (const mid of tree.childFrames ?? []) {
872
+ if (!/\/oopif-(mid|srcdoc)/.test(mid.frame?.url ?? '')) continue;
873
+ return mid;
874
+ }
875
+ return null;
876
+ }
877
+
878
+ async function srcdocDocHasTag(reader, sessionId, tag) {
879
+ if (!tag) return false;
880
+ const evaluated = await outcome(
881
+ reader.send(
882
+ 'Runtime.evaluate',
883
+ {
884
+ expression:
885
+ '(document.body && (document.body.innerText || document.body.textContent)) || ""',
886
+ returnByValue: true,
887
+ },
888
+ sessionId
889
+ )
890
+ );
891
+ if (!answered(evaluated) || !evaluated.ok) return false;
892
+ const text = evaluated.result?.result?.value;
893
+ return typeof text === 'string' && text.includes(tag);
894
+ }
895
+
896
+ function srcdocLinkedToMid(reader, midFrameId, frameId, frameParentId) {
897
+ if (midFrameId && frameParentId && frameParentId === midFrameId) return true;
898
+ if (!midFrameId || !frameId) return false;
899
+ for (const event of reader.events ?? []) {
900
+ if (event.method === 'Page.frameAttached') {
901
+ if (event.params?.frameId === frameId && event.params?.parentFrameId === midFrameId)
902
+ return true;
903
+ }
904
+ if (event.method === 'Page.frameNavigated') {
905
+ const frame = event.params?.frame ?? {};
906
+ if (frame.id === frameId && frame.parentId === midFrameId) return true;
907
+ }
908
+ }
909
+ return false;
910
+ }
911
+
912
+ function srcdocTargetCandidate(info, pageId, midFrameId, beforeIds) {
913
+ if (info.type !== 'iframe') return false;
914
+ if ((info.url ?? '') !== 'about:srcdoc') return false;
915
+ if (beforeIds?.has(info.targetId)) return false;
916
+ if (!pageId || !info.parentId) return true;
917
+ return info.parentId === pageId || info.parentId === midFrameId;
918
+ }
919
+
920
+ function finishSrcdocHit({ tree, mid, info, attached, childTree, notes, pageId, tag, reader }) {
921
+ const midFrameId = mid.frame.id;
922
+ const frameId = childTree?.frame?.id ?? info.targetId;
923
+ const frameParentId = childTree?.frame?.parentId ?? null;
924
+ const linked = srcdocLinkedToMid(reader, midFrameId, frameId, frameParentId);
925
+ const topParentOnly = Boolean(pageId && info.parentId === pageId);
926
+ if (!linked && !topParentOnly) return null;
927
+ if (!linked && topParentOnly) {
928
+ note(notes, 'protected-parent.srcdoc-top-parent', {
929
+ midFrameId,
930
+ frameId,
931
+ targetId: info.targetId,
932
+ targetParentId: info.parentId,
933
+ tag,
934
+ });
935
+ }
936
+ return {
937
+ tree: childTree ?? tree,
938
+ hit: {
939
+ midFrameId,
940
+ midUrl: mid.frame.url ?? '',
941
+ frameId,
942
+ url: childTree?.frame?.url ?? info.url ?? 'about:srcdoc',
943
+ parentId: frameParentId ?? (linked ? midFrameId : info.parentId),
944
+ },
945
+ via: 'grandchild-target',
946
+ grandchildSession: attached.sessionId,
947
+ grandchildTargetId: topParentOnly ? undefined : info.targetId,
948
+ };
949
+ }
950
+
951
+ async function hitFromSrcdocUnderLocalMid(
952
+ reader,
953
+ tree,
954
+ midHint,
955
+ pageId,
956
+ internalSessions,
957
+ beforeIds,
958
+ midNeedle,
959
+ notes
960
+ ) {
961
+ const mid = localMidFrame(tree, midHint);
962
+ if (!mid?.frame?.id) return null;
963
+ const tag = midTagFrom(mid.frame.url ?? '', midNeedle);
964
+ if (!tag) return null;
965
+ const listed = await outcome(reader.send('Target.getTargets', {}));
966
+ if (!answered(listed) || !listed.ok) return null;
967
+ for (const info of listed.result?.targetInfos ?? []) {
968
+ if (!srcdocTargetCandidate(info, pageId, mid.frame.id, beforeIds)) continue;
969
+ const attached = await attachIframeTarget(
970
+ reader,
971
+ (entry) => entry.targetId === info.targetId,
972
+ internalSessions
973
+ );
974
+ if (!attached) continue;
975
+ if (!(await srcdocDocHasTag(reader, attached.sessionId, tag))) continue;
976
+ const hit = finishSrcdocHit({
977
+ tree,
978
+ mid,
979
+ info,
980
+ attached,
981
+ childTree: await readTree(reader, attached.sessionId),
982
+ notes,
983
+ pageId,
984
+ tag,
985
+ reader,
986
+ });
987
+ if (hit) return hit;
988
+ }
989
+ return null;
990
+ }
991
+
992
+ async function waitGrandchild(
993
+ reader,
994
+ sessionId,
995
+ midHint,
996
+ innerHint,
997
+ budget,
998
+ notes,
999
+ pageId,
1000
+ internalSessions,
1001
+ midNeedle = null,
1002
+ beforeIds = null
1003
+ ) {
1004
+ let midAttached;
1005
+ await outcome(reader.send('Target.setDiscoverTargets', { discover: true }));
1006
+ const found = await until(async () => {
1007
+ const tree = await readTree(reader, sessionId);
1008
+ const hit = findGrandchild(tree, midHint, innerHint);
1009
+ if (hit) return { tree, hit, via: 'top' };
1010
+ if (innerHint === 'about:srcdoc') {
1011
+ const underTop = await hitFromSrcdocUnderLocalMid(
1012
+ reader,
1013
+ tree,
1014
+ midHint,
1015
+ pageId,
1016
+ internalSessions,
1017
+ beforeIds,
1018
+ midNeedle,
1019
+ notes
1020
+ );
1021
+ if (underTop) return underTop;
1022
+ }
1023
+ const listed = await outcome(reader.send('Target.getTargets', {}));
1024
+ const infos = answered(listed) && listed.ok ? (listed.result?.targetInfos ?? []) : [];
1025
+ if (
1026
+ midAttached &&
1027
+ !infos.some((info) => info.targetId === midAttached.info.targetId && info.type === 'iframe')
1028
+ )
1029
+ midAttached = null;
1030
+ midAttached ??= await attachIframeTarget(
1031
+ reader,
1032
+ (info) => midTargetMatch(info, midHint, pageId, midNeedle, beforeIds),
1033
+ internalSessions
1034
+ );
1035
+ if (!midAttached) return null;
1036
+ return hitFromGrandchildTarget(
1037
+ reader,
1038
+ midAttached,
1039
+ innerHint,
1040
+ internalSessions,
1041
+ beforeIds,
1042
+ midNeedle
1043
+ );
1044
+ }, budget);
1045
+ if (found) {
1046
+ const branch =
1047
+ found.via === 'top'
1048
+ ? 'top-tree'
1049
+ : found.via === 'mid-target'
1050
+ ? 'mid-target'
1051
+ : 'grandchild-target';
1052
+ note(notes, 'protected-parent.page-branch', { branch, via: found.via });
1053
+ note(notes, 'protected-parent.page-raw', {
1054
+ midFrameId: found.hit.midFrameId,
1055
+ midUrl: found.hit.midUrl,
1056
+ frameId: found.hit.frameId,
1057
+ url: found.hit.url,
1058
+ parentId: found.hit.parentId,
1059
+ via: found.via,
1060
+ branch,
1061
+ midTargetId: found.midTargetId,
1062
+ grandchildTargetId: found.grandchildTargetId,
1063
+ frames: walkFrames(found.tree).map((frame) => ({
1064
+ id: frame.id,
1065
+ url: frame.url,
1066
+ parentId: frame.parentId,
1067
+ })),
1068
+ });
1069
+ return found;
1070
+ }
1071
+ const tree = await readTree(reader, sessionId);
1072
+ const listed = await listTargetSnapshot(reader);
1073
+ note(notes, 'protected-parent.page-raw-missing', {
1074
+ midHint,
1075
+ innerHint,
1076
+ midNeedle,
1077
+ frames: walkFrames(tree).map((frame) => ({
1078
+ id: frame.id,
1079
+ url: frame.url,
1080
+ parentId: frame.parentId,
1081
+ })),
1082
+ targets: listed.targets,
1083
+ });
1084
+ return null;
1085
+ }
1086
+
1087
+ async function rawContexts(reader, sessionIds, raw, eventStart, budget, notes) {
1088
+ const allowed = new Set((sessionIds ?? []).filter(Boolean));
1089
+ const deadline = Date.now() + Math.min(budget, 1500);
1090
+ const contexts = [];
1091
+ while (Date.now() <= deadline) {
1092
+ for (const event of (reader.events ?? []).slice(eventStart)) {
1093
+ if (event.sessionId && allowed.size && !allowed.has(event.sessionId)) continue;
1094
+ if (!contextHit(event, raw)) continue;
1095
+ const context = event.params?.context;
1096
+ if (context?.id != null && !contexts.some((entry) => entry.id === context.id))
1097
+ contexts.push({
1098
+ id: context.id,
1099
+ origin: context.origin,
1100
+ frameId: context.auxData?.frameId,
1101
+ sessionId: event.sessionId,
1102
+ });
1103
+ }
1104
+ if (contexts.length) break;
1105
+ await pause(25);
1106
+ }
1107
+ note(notes, 'protected-parent.page-raw-contexts', { contexts });
1108
+ return contexts;
1109
+ }
1110
+
1111
+ function applyTreeSample(arm, sample, result, key, mentions) {
1112
+ takeFirst(arm, sample, (entry) => {
1113
+ if (entry.unanswered) return;
1114
+ if (entry.out.ok) {
1115
+ if (mentions(entry.out.result)) result[key] = true;
1116
+ else if (result[key] !== true) result[key] = false;
1117
+ } else if (result[key] !== true) result[key] = false;
1118
+ });
1119
+ }
1120
+
1121
+ async function attachOrdinaryTop(client, targetId, notes, internalSessions) {
1122
+ note(notes, 'protected-parent.page-attach-order', {
1123
+ midPresentBeforeAttach: true,
1124
+ targetId,
1125
+ });
1126
+ const attached = await outcome(client.send('Target.attachToTarget', { targetId, flatten: true }));
1127
+ if (!answered(attached)) {
1128
+ note(notes, 'protected-parent.page-attach', {
1129
+ ok: false,
1130
+ unanswered: true,
1131
+ error: String(attached.error?.message ?? attached.error ?? ''),
1132
+ });
1133
+ return { incomplete: 'Target.attachToTarget unanswered for ordinary top page' };
1134
+ }
1135
+ if (!attached.ok || !attached.result?.sessionId) {
1136
+ note(notes, 'protected-parent.page-attach', {
1137
+ ok: false,
1138
+ refused: refused(attached),
1139
+ error: String(attached.error?.message ?? attached.error ?? ''),
1140
+ });
1141
+ return {
1142
+ incomplete: `Target.attachToTarget on ordinary top failed: ${attached.error?.message ?? attached.error}`,
1143
+ };
1144
+ }
1145
+ internalSessions.add(attached.result.sessionId);
1146
+ return { sessionId: attached.result.sessionId };
1147
+ }
1148
+
1149
+ function adoptLiveRaw(raw, liveRaw) {
1150
+ if (liveRaw.midTargetId) raw.midTargetId = liveRaw.midTargetId;
1151
+ if (liveRaw.grandchildTargetId) raw.grandchildTargetId = liveRaw.grandchildTargetId;
1152
+ if (liveRaw.hit.midFrameId) {
1153
+ raw.midFrameIds = raw.midFrameIds ?? new Set([raw.midFrameId].filter(Boolean));
1154
+ raw.midFrameIds.add(liveRaw.hit.midFrameId);
1155
+ raw.midFrameId = liveRaw.hit.midFrameId;
1156
+ }
1157
+ if (liveRaw.hit.frameId) raw.frameIds.add(liveRaw.hit.frameId);
1158
+ if (typeof liveRaw.hit.url === 'string' && liveRaw.hit.url.length > 0)
1159
+ raw.urls.add(liveRaw.hit.url);
1160
+ try {
1161
+ raw.origins.add(new URL(liveRaw.hit.url).origin);
1162
+ } catch {
1163
+ if (liveRaw.hit.url === 'about:srcdoc') raw.origins.add('://');
1164
+ }
1165
+ }
1166
+
1167
+ async function evaluateContexts(client, sessionIds, contexts, evaluateArm, result) {
1168
+ const sessions = [...new Set((sessionIds ?? []).filter(Boolean))];
1169
+ let anyUnanswered = false;
1170
+ let unansweredId;
1171
+ for (const context of contexts) {
1172
+ const ordered = [
1173
+ context.sessionId,
1174
+ ...sessions.filter((id) => id && id !== context.sessionId),
1175
+ ].filter(Boolean);
1176
+ for (const sessionId of [...new Set(ordered)]) {
1177
+ const evaluated = await outcome(
1178
+ client.send(
1179
+ 'Runtime.evaluate',
1180
+ { expression: 'location.href', returnByValue: true, contextId: context.id },
1181
+ sessionId
1182
+ )
1183
+ );
1184
+ const message = String(evaluated.error?.message ?? evaluated.error ?? '');
1185
+ const gone =
1186
+ !evaluated.ok &&
1187
+ /Cannot find context|No context|Invalid context|Session with given id/i.test(message);
1188
+ if (!answered(evaluated) && !gone) {
1189
+ anyUnanswered = true;
1190
+ unansweredId ??= context.id;
1191
+ continue;
1192
+ }
1193
+ takeFirst(
1194
+ evaluateArm,
1195
+ { out: evaluated, unanswered: false, unansweredId: context.id },
1196
+ (sample) => {
1197
+ if (sample.out.ok) result.contextEvaluate = true;
1198
+ else result.contextEvaluate ??= false;
1199
+ }
1200
+ );
1201
+ if (result.contextEvaluate === true) {
1202
+ evaluateArm.unanswered = false;
1203
+ return;
1204
+ }
1205
+ }
1206
+ }
1207
+ if (result.contextEvaluate !== true && anyUnanswered) {
1208
+ evaluateArm.unanswered = true;
1209
+ evaluateArm.unansweredId ??= unansweredId;
1210
+ evaluateArm.out ??= { ok: false };
1211
+ }
1212
+ }
1213
+
1214
+ function collectAutoSessions(events, from) {
1215
+ const sessions = new Set();
1216
+ for (const event of events.slice(from)) {
1217
+ if (event.method !== 'Target.attachedToTarget') continue;
1218
+ const child = event.params?.sessionId;
1219
+ const type = event.params?.targetInfo?.type;
1220
+ if (child && (type === 'iframe' || type === 'page' || !type)) sessions.add(child);
1221
+ }
1222
+ return sessions;
1223
+ }
1224
+
1225
+ async function sampleTrees(client, sessionIds, treeArm, result, raw) {
1226
+ for (const sessionId of sessionIds) {
1227
+ const treeAgain = await outcome(client.send('Page.getFrameTree', {}, sessionId));
1228
+ applyTreeSample(
1229
+ treeArm,
1230
+ { out: treeAgain, unanswered: !answered(treeAgain) },
1231
+ result,
1232
+ 'frameTree',
1233
+ (payload) => treeMentions(payload?.frameTree, raw)
1234
+ );
1235
+ if (result.frameTree === true) return;
1236
+ }
1237
+ }
1238
+
1239
+ function recordChildEnable(out, label, child, childSessions, missing, result) {
1240
+ if (out.ok) return 'ok';
1241
+ if (refused(out)) {
1242
+ const message = String(out.error?.message ?? out.error ?? '');
1243
+ if (result) result.childEnableRefused = message;
1244
+ if (/No session with given id|Session with given id not found|Target closed/i.test(message))
1245
+ childSessions.delete(child);
1246
+ return 'refused';
1247
+ }
1248
+ if (!answered(out)) {
1249
+ missing.push(`${label} unanswered`);
1250
+ return 'missing';
1251
+ }
1252
+ missing.push(`${label} failed: ${out.error?.message ?? out.error}`);
1253
+ return 'missing';
1254
+ }
1255
+
1256
+ async function enableChildDomains(client, childSessions, missing, result) {
1257
+ for (const child of [...childSessions]) {
1258
+ const pageOut = await outcome(client.send('Page.enable', {}, child));
1259
+ const pageStatus = recordChildEnable(
1260
+ pageOut,
1261
+ 'Page.enable',
1262
+ child,
1263
+ childSessions,
1264
+ missing,
1265
+ result
1266
+ );
1267
+ if (pageStatus === 'missing') return;
1268
+ if (pageStatus === 'refused') continue;
1269
+ const runtimeOut = await outcome(client.send('Runtime.enable', {}, child));
1270
+ const runtimeStatus = recordChildEnable(
1271
+ runtimeOut,
1272
+ 'Runtime.enable',
1273
+ child,
1274
+ childSessions,
1275
+ missing,
1276
+ result
1277
+ );
1278
+ if (runtimeStatus === 'missing') return;
1279
+ }
1280
+ }
1281
+
1282
+ async function adoptLiveClientSessions(
1283
+ client,
1284
+ sessionId,
1285
+ clientEventStart,
1286
+ raw,
1287
+ childSessions,
1288
+ internalSessions,
1289
+ missing,
1290
+ result
1291
+ ) {
1292
+ await autoAttachSession(client, sessionId);
1293
+ pullAutoSessions(client, clientEventStart, childSessions);
1294
+ for (const targetId of [raw.midTargetId, raw.grandchildTargetId].filter(Boolean)) {
1295
+ const attached = await outcome(
1296
+ client.send('Target.attachToTarget', { targetId, flatten: true })
1297
+ );
1298
+ await adoptAttachedSession(attached, childSessions, internalSessions, null);
1299
+ }
1300
+ for (const child of [...childSessions]) await autoAttachSession(client, child);
1301
+ pullAutoSessions(client, clientEventStart, childSessions);
1302
+ await enableChildDomains(client, childSessions, missing, result);
1303
+ }
1304
+
1305
+ async function armNewChildSessions(client, events, childSessions, missing, result) {
1306
+ for (const child of collectAutoSessions(events, 0)) {
1307
+ if (childSessions.has(child)) continue;
1308
+ childSessions.add(child);
1309
+ const pageOut = await outcome(client.send('Page.enable', {}, child));
1310
+ const pageStatus = recordChildEnable(
1311
+ pageOut,
1312
+ 'Page.enable',
1313
+ child,
1314
+ childSessions,
1315
+ missing,
1316
+ result
1317
+ );
1318
+ if (pageStatus === 'missing') return;
1319
+ if (pageStatus === 'refused') continue;
1320
+ const runtimeOut = await outcome(client.send('Runtime.enable', {}, child));
1321
+ if (
1322
+ recordChildEnable(runtimeOut, 'Runtime.enable', child, childSessions, missing, result) ===
1323
+ 'missing'
1324
+ )
1325
+ return;
1326
+ }
1327
+ }
1328
+
1329
+ async function remasureLiveGrandchild({
1330
+ reader,
1331
+ readerSessionId,
1332
+ pageUrl,
1333
+ targetId,
1334
+ midHint,
1335
+ innerHint,
1336
+ innerKind,
1337
+ raw,
1338
+ budget,
1339
+ notes,
1340
+ internalSessions,
1341
+ }) {
1342
+ const before = await listTargetSnapshot(reader);
1343
+ const beforeIds = new Set(before.targets.map((info) => info.targetId).filter(Boolean));
1344
+ const kind = innerKind ?? (innerHint === 'about:srcdoc' ? 'srcdoc' : 'ordinary');
1345
+ const childBudget = budget < 2000 ? budget : Math.max(budget, 4000);
1346
+ if (raw.midTargetId) {
1347
+ const midAttached = await attachIframeTarget(
1348
+ reader,
1349
+ (info) => info.targetId === raw.midTargetId,
1350
+ internalSessions
1351
+ );
1352
+ if (midAttached) {
1353
+ const stamp = stampedMidLive(midAttached.info.url ?? '', kind, innerHint);
1354
+ note(notes, 'protected-parent.page-live-nav', {
1355
+ via: 'mid-session-remeasure',
1356
+ url: stamp.midUrl,
1357
+ innerHint: stamp.innerHint,
1358
+ midNeedle: stamp.midNeedle,
1359
+ midTargetId: raw.midTargetId,
1360
+ });
1361
+ const navigated = await outcome(
1362
+ reader.send('Page.navigate', { url: stamp.midUrl }, midAttached.sessionId)
1363
+ );
1364
+ if (answered(navigated) && navigated.ok) {
1365
+ const found = await waitChildUnderMid(
1366
+ reader,
1367
+ midAttached,
1368
+ stamp.innerHint || innerHint,
1369
+ childBudget,
1370
+ internalSessions,
1371
+ beforeIds,
1372
+ stamp.midNeedle
1373
+ );
1374
+ if (found) return found;
1375
+ }
1376
+ }
1377
+ }
1378
+ const plan = liveNestPlan(pageUrl, kind, innerHint);
1379
+ let liveUrl = plan.liveUrl;
1380
+ try {
1381
+ const page = new URL(plan.liveUrl);
1382
+ page.searchParams.set('live', String((Number(page.searchParams.get('live')) || 1) + 1));
1383
+ liveUrl = page.toString();
1384
+ } catch {
1385
+ liveUrl = plan.liveUrl;
1386
+ }
1387
+ note(notes, 'protected-parent.page-live-nav', {
1388
+ via: 'top-session-remeasure',
1389
+ url: liveUrl,
1390
+ innerHint: plan.innerHint,
1391
+ midNeedle: plan.midNeedle,
1392
+ beforeTargetIds: [...beforeIds],
1393
+ });
1394
+ const navigated = await outcome(reader.send('Page.navigate', { url: liveUrl }, readerSessionId));
1395
+ if (!answered(navigated) || !navigated.ok) return null;
1396
+ return waitGrandchild(
1397
+ reader,
1398
+ readerSessionId,
1399
+ midHint,
1400
+ plan.innerHint || innerHint,
1401
+ childBudget,
1402
+ notes,
1403
+ targetId,
1404
+ internalSessions,
1405
+ plan.midNeedle,
1406
+ beforeIds
1407
+ );
1408
+ }
1409
+
1410
+ async function pollPageClient({
1411
+ client,
1412
+ sessionId,
1413
+ childSessions,
1414
+ clientEventStart,
1415
+ raw,
1416
+ liveContexts,
1417
+ treeArm,
1418
+ resourceArm,
1419
+ evaluateArm,
1420
+ result,
1421
+ missing,
1422
+ budget,
1423
+ skipEvaluate = false,
1424
+ }) {
1425
+ const windowMs = Math.min(budget, 1500);
1426
+ const deadline = Date.now() + windowMs;
1427
+ while (Date.now() <= deadline) {
1428
+ const events = (client.events ?? []).slice(clientEventStart);
1429
+ await armNewChildSessions(client, events, childSessions, missing, result);
1430
+ if (missing.length) break;
1431
+ result.frameEvents = events.some((event) => frameEventHit(event, raw))
1432
+ ? true
1433
+ : (result.frameEvents ?? false);
1434
+ result.midFrameAttached = events.some((event) => midFrameAttachedHit(event, raw))
1435
+ ? true
1436
+ : (result.midFrameAttached ?? false);
1437
+ if (liveContexts.length) {
1438
+ if (events.some((event) => contextHit(event, raw))) result.contextCreated = true;
1439
+ if (!skipEvaluate && result.contextEvaluate !== true)
1440
+ await evaluateContexts(
1441
+ client,
1442
+ [sessionId, ...childSessions],
1443
+ liveContexts,
1444
+ evaluateArm,
1445
+ result
1446
+ );
1447
+ }
1448
+ await sampleTrees(client, [sessionId, ...childSessions], treeArm, result, raw);
1449
+ await sampleResources(client, [sessionId, ...childSessions], resourceArm, result, raw);
1450
+ if (
1451
+ result.frameTree === true &&
1452
+ result.resourceTree === true &&
1453
+ result.frameEvents === true &&
1454
+ result.contextCreated === true &&
1455
+ (skipEvaluate || result.contextEvaluate === true) &&
1456
+ result.midFrameAttached === true
1457
+ )
1458
+ break;
1459
+ await pause(50);
1460
+ }
1461
+ return windowMs;
1462
+ }
1463
+
1464
+ function enableFailure(out, label, missing) {
1465
+ if (!answered(out)) missing.push(`${label} unanswered`);
1466
+ else if (!out.ok) missing.push(`${label} failed: ${out.error?.message ?? out.error}`);
1467
+ }
1468
+
1469
+ async function abortPageClient(client, sessionId, notes, missing, result = {}) {
1470
+ note(notes, 'protected-parent.page-client', {
1471
+ unanswered: missing,
1472
+ frameTree: result.frameTree ?? 'unmeasured',
1473
+ resourceTree: result.resourceTree ?? 'unmeasured',
1474
+ frameEvents: 'unmeasured',
1475
+ contextCreated: 'unmeasured',
1476
+ contextEvaluate: 'unmeasured',
1477
+ midFrameAttached: 'unmeasured',
1478
+ });
1479
+ await outcome(client.send('Target.detachFromTarget', { sessionId }));
1480
+ return { ...result, incomplete: missing.join('; ') };
1481
+ }
1482
+
1483
+ async function sampleResources(client, sessionIds, resourceArm, result, raw) {
1484
+ for (const sessionId of sessionIds) {
1485
+ if (result.resourceTree === true) return;
1486
+ const resourceOut = await outcome(client.send('Page.getResourceTree', {}, sessionId));
1487
+ if (!resourceOut.ok && refused(resourceOut)) continue;
1488
+ applyTreeSample(
1489
+ resourceArm,
1490
+ { out: resourceOut, unanswered: !answered(resourceOut) },
1491
+ result,
1492
+ 'resourceTree',
1493
+ (payload) => resourceMentions(payload, raw)
1494
+ );
1495
+ }
1496
+ }
1497
+
1498
+ async function liveViaMidSession({
1499
+ reader,
1500
+ raw,
1501
+ innerKind,
1502
+ innerHint,
1503
+ budget,
1504
+ notes,
1505
+ internalSessions,
1506
+ beforeIds,
1507
+ preferMidLive,
1508
+ }) {
1509
+ if (!preferMidLive || !raw.midTargetId) return null;
1510
+ const midAttached = await attachIframeTarget(
1511
+ reader,
1512
+ (info) => info.targetId === raw.midTargetId,
1513
+ internalSessions
1514
+ );
1515
+ if (!midAttached) return null;
1516
+ const midUrl = midAttached.info.url ?? '';
1517
+ const stamp = stampedMidLive(
1518
+ midUrl,
1519
+ innerKind ?? (innerHint === 'about:srcdoc' ? 'srcdoc' : 'ordinary'),
1520
+ innerHint
1521
+ );
1522
+ note(notes, 'protected-parent.page-live-nav', {
1523
+ via: 'mid-session',
1524
+ url: stamp.midUrl,
1525
+ innerHint: stamp.innerHint,
1526
+ midNeedle: stamp.midNeedle,
1527
+ midTargetId: raw.midTargetId,
1528
+ });
1529
+ const navigated = await outcome(
1530
+ reader.send('Page.navigate', { url: stamp.midUrl }, midAttached.sessionId)
1531
+ );
1532
+ if (!answered(navigated) || !navigated.ok) return null;
1533
+ const childBudget = budget < 2000 ? budget : Math.max(budget, 8000);
1534
+ const found = await waitChildUnderMid(
1535
+ reader,
1536
+ midAttached,
1537
+ stamp.innerHint || innerHint,
1538
+ childBudget,
1539
+ internalSessions,
1540
+ beforeIds,
1541
+ stamp.midNeedle
1542
+ );
1543
+ if (!found) return null;
1544
+ const branch = found.via === 'mid-target' ? 'mid-target' : 'grandchild-target';
1545
+ note(notes, 'protected-parent.page-branch', { branch, via: found.via, live: 'mid-session' });
1546
+ return found;
1547
+ }
1548
+
1549
+ async function liveGrandchild({
1550
+ reader,
1551
+ readerSessionId,
1552
+ readerSessions,
1553
+ targetId,
1554
+ pageUrl,
1555
+ midHint,
1556
+ innerHint,
1557
+ innerKind,
1558
+ preferMidLive,
1559
+ raw,
1560
+ contexts,
1561
+ budget,
1562
+ notes,
1563
+ internalSessions,
1564
+ missing,
1565
+ }) {
1566
+ const before = await listTargetSnapshot(reader);
1567
+ note(notes, 'protected-parent.page-targets-before', {
1568
+ unanswered: before.unanswered,
1569
+ targets: before.targets,
1570
+ midTargetId: raw.midTargetId ?? null,
1571
+ grandchildTargetId: raw.grandchildTargetId ?? null,
1572
+ urls: [...raw.urls],
1573
+ });
1574
+ const beforeIds = new Set(before.targets.map((info) => info.targetId).filter(Boolean));
1575
+ const liveBudget = budget < 2000 ? budget : Math.max(budget, 8000);
1576
+ let liveRaw = await liveViaMidSession({
1577
+ reader,
1578
+ raw,
1579
+ innerKind,
1580
+ innerHint,
1581
+ budget: liveBudget,
1582
+ notes,
1583
+ internalSessions,
1584
+ beforeIds,
1585
+ preferMidLive,
1586
+ });
1587
+ if (!liveRaw) {
1588
+ const plan = liveNestPlan(
1589
+ pageUrl,
1590
+ innerKind ?? (innerHint === 'about:srcdoc' ? 'srcdoc' : 'ordinary'),
1591
+ innerHint
1592
+ );
1593
+ note(notes, 'protected-parent.page-live-nav', {
1594
+ via: 'top-session',
1595
+ url: plan.liveUrl,
1596
+ innerHint: plan.innerHint,
1597
+ midNeedle: plan.midNeedle,
1598
+ beforeTargetIds: [...beforeIds],
1599
+ });
1600
+ const navigated = await outcome(
1601
+ reader.send('Page.navigate', { url: plan.liveUrl }, readerSessionId)
1602
+ );
1603
+ if (!answered(navigated)) missing.push('unguarded Page.navigate unanswered after attach');
1604
+ else if (!navigated.ok)
1605
+ missing.push(
1606
+ `unguarded Page.navigate failed: ${navigated.error?.message ?? navigated.error}`
1607
+ );
1608
+ liveRaw = await waitGrandchild(
1609
+ reader,
1610
+ readerSessionId,
1611
+ midHint,
1612
+ plan.innerHint || innerHint,
1613
+ liveBudget,
1614
+ notes,
1615
+ targetId,
1616
+ internalSessions,
1617
+ plan.midNeedle,
1618
+ beforeIds
1619
+ );
1620
+ }
1621
+ const after = await listTargetSnapshot(reader);
1622
+ note(notes, 'protected-parent.page-targets-after', {
1623
+ unanswered: after.unanswered,
1624
+ targets: after.targets,
1625
+ foundLive: Boolean(liveRaw),
1626
+ });
1627
+ if (!liveRaw) {
1628
+ missing.push('grandchild missing in raw leg after post-attach navigation');
1629
+ return contexts;
1630
+ }
1631
+ adoptLiveRaw(raw, liveRaw);
1632
+ note(notes, 'protected-parent.page-live-raw', {
1633
+ midFrameId: liveRaw.hit.midFrameId,
1634
+ frameId: liveRaw.hit.frameId,
1635
+ url: liveRaw.hit.url,
1636
+ via: liveRaw.via,
1637
+ });
1638
+ const liveSessions = [
1639
+ ...(readerSessions ?? []),
1640
+ readerSessionId,
1641
+ liveRaw.midSession,
1642
+ liveRaw.grandchildSession,
1643
+ ].filter(Boolean);
1644
+ const liveContexts = await rawContexts(
1645
+ reader,
1646
+ liveSessions,
1647
+ raw,
1648
+ reader.events?.length ? reader.events.length - 50 : 0,
1649
+ budget,
1650
+ notes
1651
+ );
1652
+ return liveContexts.length ? liveContexts : contexts;
1653
+ }
1654
+
1655
+ function targetInfoHit(info, raw) {
1656
+ if (!info) return false;
1657
+ if (raw.grandchildTargetId && info.targetId === raw.grandchildTargetId) return true;
1658
+ if (raw.midTargetId && info.parentId === raw.midTargetId) {
1659
+ const url = info.url ?? '';
1660
+ if ([...raw.urls].some((entry) => entry && (url === entry || url.includes(entry)))) return true;
1661
+ }
1662
+ const url = info.url ?? '';
1663
+ return [...raw.urls].some((entry) => entry && url === entry);
1664
+ }
1665
+
1666
+ function targetEventHit(event, raw) {
1667
+ if (
1668
+ !['Target.targetCreated', 'Target.targetInfoChanged', 'Target.attachedToTarget'].includes(
1669
+ event.method
1670
+ )
1671
+ )
1672
+ return false;
1673
+ return targetInfoHit(event.params?.targetInfo, raw);
1674
+ }
1675
+
1676
+ async function autoAttachSession(client, sessionId) {
1677
+ await outcome(
1678
+ client.send(
1679
+ 'Target.setAutoAttach',
1680
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
1681
+ sessionId
1682
+ )
1683
+ );
1684
+ }
1685
+
1686
+ function pullAutoSessions(client, clientEventStart, childSessions) {
1687
+ for (const child of collectAutoSessions(client.events ?? [], clientEventStart))
1688
+ childSessions.add(child);
1689
+ }
1690
+
1691
+ async function adoptAttachedSession(out, childSessions, internalSessions, result) {
1692
+ if (!answered(out)) return 'unanswered';
1693
+ if (out.ok && out.result?.sessionId) {
1694
+ childSessions.add(out.result.sessionId);
1695
+ internalSessions?.add(out.result.sessionId);
1696
+ if (result) result.childAttach = true;
1697
+ return 'attached';
1698
+ }
1699
+ if (result) {
1700
+ result.childAttach ??= false;
1701
+ if (refused(out)) result.attachRefused = true;
1702
+ }
1703
+ return refused(out) ? 'refused' : 'failed';
1704
+ }
1705
+
1706
+ async function probeListedGrandchildren(
1707
+ client,
1708
+ raw,
1709
+ childSessions,
1710
+ internalSessions,
1711
+ result,
1712
+ missing
1713
+ ) {
1714
+ const listed = await outcome(client.send('Target.getTargets', {}));
1715
+ if (!answered(listed)) {
1716
+ missing.push('Target.getTargets unanswered');
1717
+ return;
1718
+ }
1719
+ if (!listed.ok) {
1720
+ result.targetInfo ??= false;
1721
+ return;
1722
+ }
1723
+ const infos = listed.result?.targetInfos ?? [];
1724
+ if (infos.some((info) => targetInfoHit(info, raw))) result.targetInfo = true;
1725
+ for (const info of infos) {
1726
+ if (info.type !== 'iframe') continue;
1727
+ if (!targetInfoHit(info, raw) && info.targetId !== raw.grandchildTargetId) continue;
1728
+ const attachedChild = await outcome(
1729
+ client.send('Target.attachToTarget', { targetId: info.targetId, flatten: true })
1730
+ );
1731
+ const status = await adoptAttachedSession(
1732
+ attachedChild,
1733
+ childSessions,
1734
+ internalSessions,
1735
+ result
1736
+ );
1737
+ if (status === 'unanswered')
1738
+ missing.push(`Target.attachToTarget unanswered (${info.targetId})`);
1739
+ }
1740
+ }
1741
+
1742
+ async function probeRawGrandchildTarget(
1743
+ client,
1744
+ raw,
1745
+ childSessions,
1746
+ internalSessions,
1747
+ result,
1748
+ missing
1749
+ ) {
1750
+ if (!raw.grandchildTargetId) {
1751
+ result.targetInfo ??= false;
1752
+ result.childAttach ??= false;
1753
+ return;
1754
+ }
1755
+ if (result.childAttach === true) return;
1756
+ const infoOut = await outcome(
1757
+ client.send('Target.getTargetInfo', { targetId: raw.grandchildTargetId })
1758
+ );
1759
+ if (!answered(infoOut)) missing.push('Target.getTargetInfo unanswered for grandchild');
1760
+ else if (infoOut.ok) result.targetInfo = true;
1761
+ else result.targetInfo ??= false;
1762
+ const attachedRaw = await outcome(
1763
+ client.send('Target.attachToTarget', {
1764
+ targetId: raw.grandchildTargetId,
1765
+ flatten: true,
1766
+ })
1767
+ );
1768
+ const status = await adoptAttachedSession(attachedRaw, childSessions, internalSessions, result);
1769
+ if (status === 'unanswered')
1770
+ missing.push('Target.attachToTarget unanswered for raw grandchild target');
1771
+ }
1772
+
1773
+ async function gatherChildSessions(
1774
+ client,
1775
+ sessionId,
1776
+ clientEventStart,
1777
+ raw,
1778
+ internalSessions,
1779
+ result,
1780
+ missing
1781
+ ) {
1782
+ const childSessions = new Set();
1783
+ await autoAttachSession(client, sessionId);
1784
+ await until(async () => {
1785
+ pullAutoSessions(client, clientEventStart, childSessions);
1786
+ return childSessions.size > 0 ? childSessions : null;
1787
+ }, 200);
1788
+ pullAutoSessions(client, clientEventStart, childSessions);
1789
+ if (raw.midTargetId) {
1790
+ const midAttached = await outcome(
1791
+ client.send('Target.attachToTarget', { targetId: raw.midTargetId, flatten: true })
1792
+ );
1793
+ await adoptAttachedSession(midAttached, childSessions, internalSessions, null);
1794
+ }
1795
+ for (const child of [...childSessions]) await autoAttachSession(client, child);
1796
+ const before = childSessions.size;
1797
+ await until(async () => {
1798
+ pullAutoSessions(client, clientEventStart, childSessions);
1799
+ return childSessions.size > before ? childSessions : null;
1800
+ }, 200);
1801
+ pullAutoSessions(client, clientEventStart, childSessions);
1802
+ result.targetEvents = (client.events ?? [])
1803
+ .slice(clientEventStart)
1804
+ .some((event) => targetEventHit(event, raw))
1805
+ ? true
1806
+ : (result.targetEvents ?? false);
1807
+ await probeListedGrandchildren(client, raw, childSessions, internalSessions, result, missing);
1808
+ await probeRawGrandchildTarget(client, raw, childSessions, internalSessions, result, missing);
1809
+ result.targetInfo ??= false;
1810
+ result.childAttach ??= false;
1811
+ result.targetEvents ??= false;
1812
+ return childSessions;
1813
+ }
1814
+
1815
+ async function measurePageClient({
1816
+ client,
1817
+ reader,
1818
+ readerSessionId,
1819
+ readerSessions,
1820
+ targetId,
1821
+ pageUrl,
1822
+ midHint,
1823
+ innerHint,
1824
+ innerKind,
1825
+ preferMidLive,
1826
+ raw,
1827
+ contexts,
1828
+ budget,
1829
+ notes,
1830
+ internalSessions,
1831
+ }) {
1832
+ const result = {};
1833
+ const missing = [];
1834
+ const attached = await attachOrdinaryTop(client, targetId, notes, internalSessions);
1835
+ if (attached.incomplete) return attached;
1836
+ const { sessionId } = attached;
1837
+ const clientEventStart = client.events?.length ?? 0;
1838
+ enableFailure(await outcome(client.send('Page.enable', {}, sessionId)), 'Page.enable', missing);
1839
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing);
1840
+ const treeArm = { out: undefined, unanswered: false };
1841
+ const resourceArm = { out: undefined, unanswered: false };
1842
+ const evaluateArm = { out: undefined, unanswered: false };
1843
+ const childSessions = await gatherChildSessions(
1844
+ client,
1845
+ sessionId,
1846
+ clientEventStart,
1847
+ raw,
1848
+ internalSessions,
1849
+ result,
1850
+ missing
1851
+ );
1852
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
1853
+ const sessions = [sessionId, ...childSessions];
1854
+ await sampleTrees(client, sessions, treeArm, result, raw);
1855
+ enableFailure(
1856
+ await outcome(client.send('Runtime.enable', {}, sessionId)),
1857
+ 'Runtime.enable',
1858
+ missing
1859
+ );
1860
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
1861
+ await enableChildDomains(client, childSessions, missing, result);
1862
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
1863
+ await outcome(client.send('Network.enable', {}, sessionId));
1864
+ if (contexts.length)
1865
+ result.contextCreated = (client.events ?? [])
1866
+ .slice(clientEventStart)
1867
+ .some((event) => contextHit(event, raw));
1868
+ let liveContexts = await liveGrandchild({
1869
+ reader,
1870
+ readerSessionId,
1871
+ readerSessions,
1872
+ targetId,
1873
+ pageUrl,
1874
+ midHint,
1875
+ innerHint,
1876
+ innerKind,
1877
+ preferMidLive,
1878
+ raw,
1879
+ contexts,
1880
+ budget,
1881
+ notes,
1882
+ internalSessions,
1883
+ missing,
1884
+ });
1885
+ await adoptLiveClientSessions(
1886
+ client,
1887
+ sessionId,
1888
+ clientEventStart,
1889
+ raw,
1890
+ childSessions,
1891
+ internalSessions,
1892
+ missing,
1893
+ result
1894
+ );
1895
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
1896
+ await probeRawGrandchildTarget(client, raw, childSessions, internalSessions, result, missing);
1897
+ if (raw.midTargetId || raw.grandchildTargetId) {
1898
+ const remasured = await remasureLiveGrandchild({
1899
+ reader,
1900
+ readerSessionId,
1901
+ pageUrl,
1902
+ targetId,
1903
+ midHint,
1904
+ innerHint,
1905
+ innerKind,
1906
+ raw,
1907
+ budget,
1908
+ notes,
1909
+ internalSessions,
1910
+ });
1911
+ if (remasured) {
1912
+ adoptLiveRaw(raw, remasured);
1913
+ note(notes, 'protected-parent.page-live-raw', {
1914
+ midFrameId: remasured.hit.midFrameId,
1915
+ frameId: remasured.hit.frameId,
1916
+ url: remasured.hit.url,
1917
+ via: remasured.via,
1918
+ remasure: true,
1919
+ });
1920
+ await adoptLiveClientSessions(
1921
+ client,
1922
+ sessionId,
1923
+ clientEventStart,
1924
+ raw,
1925
+ childSessions,
1926
+ internalSessions,
1927
+ missing,
1928
+ result
1929
+ );
1930
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
1931
+ await probeRawGrandchildTarget(client, raw, childSessions, internalSessions, result, missing);
1932
+ }
1933
+ }
1934
+ const clientContexts = await rawContexts(
1935
+ client,
1936
+ [sessionId, ...childSessions],
1937
+ raw,
1938
+ clientEventStart,
1939
+ Math.min(budget, 1500),
1940
+ notes
1941
+ );
1942
+ if (clientContexts.length) liveContexts = clientContexts;
1943
+ await sampleResources(client, [sessionId, ...childSessions], resourceArm, result, raw);
1944
+ const windowMs = await pollPageClient({
1945
+ client,
1946
+ sessionId,
1947
+ childSessions,
1948
+ clientEventStart,
1949
+ raw,
1950
+ liveContexts,
1951
+ treeArm,
1952
+ resourceArm,
1953
+ evaluateArm,
1954
+ result,
1955
+ missing,
1956
+ budget,
1957
+ skipEvaluate: innerKind === 'srcdoc',
1958
+ });
1959
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
1960
+ await finishPageClient(
1961
+ client,
1962
+ sessionId,
1963
+ clientEventStart,
1964
+ raw,
1965
+ liveContexts,
1966
+ treeArm,
1967
+ resourceArm,
1968
+ evaluateArm,
1969
+ result,
1970
+ missing,
1971
+ notes,
1972
+ childSessions,
1973
+ windowMs,
1974
+ innerKind === 'srcdoc'
1975
+ );
1976
+ if (missing.length) return { ...result, incomplete: missing.join('; ') };
1977
+ return result;
1978
+ }
1979
+
1980
+ function finishPageClient(
1981
+ client,
1982
+ sessionId,
1983
+ clientEventStart,
1984
+ raw,
1985
+ liveContexts,
1986
+ treeArm,
1987
+ resourceArm,
1988
+ evaluateArm,
1989
+ result,
1990
+ missing,
1991
+ notes,
1992
+ childSessions,
1993
+ windowMs,
1994
+ skipEvaluate = false
1995
+ ) {
1996
+ result.targetEvents = (client.events ?? [])
1997
+ .slice(clientEventStart)
1998
+ .some((event) => targetEventHit(event, raw))
1999
+ ? true
2000
+ : (result.targetEvents ?? false);
2001
+ settleArm(result, 'frameTree', treeArm.unanswered, 'Page.getFrameTree unanswered', missing, {
2002
+ frameTree: false,
2003
+ });
2004
+ settleArm(
2005
+ result,
2006
+ 'resourceTree',
2007
+ resourceArm.unanswered,
2008
+ 'Page.getResourceTree unanswered',
2009
+ missing,
2010
+ { resourceTree: false }
2011
+ );
2012
+ result.frameEvents ??= false;
2013
+ result.midFrameAttached ??= false;
2014
+ result.targetInfo ??= false;
2015
+ result.childAttach ??= false;
2016
+ result.targetEvents ??= false;
2017
+ result.childEnableRefused ??= false;
2018
+ if (!liveContexts.length) missing.push('grandchild execution context missing in raw leg');
2019
+ else {
2020
+ result.contextCreated ??= false;
2021
+ if (!skipEvaluate) {
2022
+ settleArm(
2023
+ result,
2024
+ 'contextEvaluate',
2025
+ evaluateArm.unanswered,
2026
+ evaluateArm.unansweredId
2027
+ ? `Runtime.evaluate unanswered (${evaluateArm.unansweredId})`
2028
+ : 'Runtime.evaluate unanswered',
2029
+ missing,
2030
+ { contextEvaluate: false }
2031
+ );
2032
+ }
2033
+ }
2034
+ note(notes, 'protected-parent.page-client', {
2035
+ frameTree: result.frameTree ?? 'unmeasured',
2036
+ resourceTree: result.resourceTree ?? 'unmeasured',
2037
+ frameEvents: result.frameEvents ?? 'unmeasured',
2038
+ contextCreated: result.contextCreated ?? 'unmeasured',
2039
+ contextEvaluate: skipEvaluate ? 'skipped' : (result.contextEvaluate ?? 'unmeasured'),
2040
+ midFrameAttached: result.midFrameAttached ?? 'unmeasured',
2041
+ targetInfo: result.targetInfo ?? 'unmeasured',
2042
+ childAttach: result.childAttach ?? 'unmeasured',
2043
+ targetEvents: result.targetEvents ?? 'unmeasured',
2044
+ childEnableRefused: result.childEnableRefused ?? false,
2045
+ attachRefused: result.attachRefused ?? false,
2046
+ grandchildTargetId: raw.grandchildTargetId ?? null,
2047
+ windowMs,
2048
+ childSessions: [...childSessions],
2049
+ firstTreeOk: treeArm.out?.ok,
2050
+ firstResourceOk: resourceArm.out?.ok,
2051
+ firstEvaluateOk: skipEvaluate ? false : evaluateArm.out?.ok,
2052
+ unanswered: missing,
2053
+ });
2054
+ return outcome(client.send('Target.detachFromTarget', { sessionId }));
2055
+ }
2056
+
2057
+ async function pageNested({
2058
+ reader,
2059
+ client,
2060
+ midOrigin,
2061
+ ordinary,
2062
+ tag,
2063
+ notes,
2064
+ budget,
2065
+ internalSessions,
2066
+ eventStart,
2067
+ innerKind,
2068
+ preferMidLive = false,
2069
+ }) {
2070
+ if (!midOrigin) return { incomplete: 'no middle origin mapped' };
2071
+ const inner = innerKind === 'srcdoc' ? 'about:srcdoc' : `${ordinary}/doc?n=inner-${tag}`;
2072
+ const mid =
2073
+ innerKind === 'srcdoc'
2074
+ ? `${midOrigin}/oopif-srcdoc?n=mid-${tag}`
2075
+ : `${midOrigin}/oopif-mid?inner=${encodeURIComponent(inner)}&n=mid-${tag}`;
2076
+ const page = `${ordinary}/oopif-nest?mid=${encodeURIComponent(mid)}&n=host-${tag}`;
2077
+ note(notes, 'protected-parent.page-urls', {
2078
+ top: ordinary,
2079
+ mid: midOrigin,
2080
+ inner,
2081
+ page,
2082
+ attachOrder: 'mid-already-present',
2083
+ });
2084
+ const opened = await openProtected(reader, page, notes, internalSessions);
2085
+ if (!opened.ok)
2086
+ return {
2087
+ incomplete: `observer setup failed: ${opened.error?.message ?? opened.error}`,
2088
+ };
2089
+ if (opened.result.incomplete) return { live: false, incomplete: opened.result.incomplete };
2090
+ const { targetId: pageId, sessionId } = opened.result;
2091
+ const midHint = midOrigin;
2092
+ const innerHint = innerKind === 'srcdoc' ? 'about:srcdoc' : `inner-${tag}`;
2093
+ const midNeedle = `mid-${tag}`;
2094
+ const rawFound = await waitGrandchild(
2095
+ reader,
2096
+ sessionId,
2097
+ midHint,
2098
+ innerHint,
2099
+ budget,
2100
+ notes,
2101
+ pageId,
2102
+ internalSessions,
2103
+ midNeedle
2104
+ );
2105
+ if (!rawFound) {
2106
+ return {
2107
+ live: true,
2108
+ incomplete:
2109
+ innerKind === 'srcdoc'
2110
+ ? 'srcdoc grandchild under the middle frame did not appear in the raw page frame tree within the budget'
2111
+ : 'ordinary grandchild under the middle frame did not appear in the raw page frame tree within the budget',
2112
+ pageId,
2113
+ };
2114
+ }
2115
+ const raw = {
2116
+ midFrameId: rawFound.hit.midFrameId,
2117
+ midTargetId: rawFound.midTargetId,
2118
+ grandchildTargetId: rawFound.grandchildTargetId,
2119
+ frameIds: new Set([rawFound.hit.frameId]),
2120
+ urls: new Set([rawFound.hit.url].filter((url) => typeof url === 'string' && url.length > 0)),
2121
+ origins: new Set(),
2122
+ };
2123
+ try {
2124
+ raw.origins.add(new URL(rawFound.hit.url).origin);
2125
+ } catch {
2126
+ if (rawFound.hit.url === 'about:srcdoc') raw.origins.add('://');
2127
+ }
2128
+ const readerEventStart = reader.events?.length ?? 0;
2129
+ const readerSessions = [sessionId, rawFound.midSession, rawFound.grandchildSession].filter(
2130
+ Boolean
2131
+ );
2132
+ const contexts = await rawContexts(
2133
+ reader,
2134
+ readerSessions,
2135
+ raw,
2136
+ Math.min(eventStart, readerEventStart),
2137
+ budget,
2138
+ notes
2139
+ );
2140
+ if (!contexts.length) {
2141
+ note(notes, 'protected-parent.page-no-context', {
2142
+ frameId: rawFound.hit.frameId,
2143
+ url: rawFound.hit.url,
2144
+ via: rawFound.via,
2145
+ });
2146
+ }
2147
+ const measured = await measurePageClient({
2148
+ client,
2149
+ reader,
2150
+ readerSessionId: sessionId,
2151
+ readerSessions,
2152
+ targetId: pageId,
2153
+ pageUrl: page,
2154
+ midHint,
2155
+ innerHint,
2156
+ innerKind,
2157
+ preferMidLive,
2158
+ raw,
2159
+ contexts,
2160
+ budget,
2161
+ notes,
2162
+ internalSessions,
2163
+ });
2164
+ return {
2165
+ live: true,
2166
+ pageId,
2167
+ frameIds: [...raw.frameIds],
2168
+ frameUrls: [...raw.urls],
2169
+ midFrameId: raw.midFrameId,
2170
+ ...measured,
2171
+ };
2172
+ }
2173
+
517
2174
  export async function protectedParentIframes({
518
2175
  client,
519
2176
  reader,
@@ -529,7 +2186,8 @@ export async function protectedParentIframes({
529
2186
  eventStart = 0,
530
2187
  }) {
531
2188
  if (!reader) return { incomplete: 'missing unguarded reader' };
532
- if (discovery) {
2189
+ const pageMode = ['page-nested', 'page-srcdoc', 'page-ordinary'].includes(mode);
2190
+ if (discovery && !pageMode) {
533
2191
  await outcome(client.send('Target.setDiscoverTargets', { discover: true }));
534
2192
  await outcome(reader.send('Target.setDiscoverTargets', { discover: true }));
535
2193
  notes.push('protected-parent.discovery: setDiscoverTargets discover=true');
@@ -561,7 +2219,49 @@ export async function protectedParentIframes({
561
2219
  internalSessions,
562
2220
  eventStart,
563
2221
  })
564
- : { incomplete: `unknown protectedParentIframes mode ${mode}` };
2222
+ : mode === 'page-nested'
2223
+ ? await pageNested({
2224
+ reader,
2225
+ client,
2226
+ midOrigin: protectedOrigin,
2227
+ ordinary,
2228
+ tag,
2229
+ notes,
2230
+ budget,
2231
+ internalSessions,
2232
+ eventStart,
2233
+ innerKind: 'ordinary',
2234
+ preferMidLive: true,
2235
+ })
2236
+ : mode === 'page-srcdoc'
2237
+ ? await pageNested({
2238
+ reader,
2239
+ client,
2240
+ midOrigin: protectedOrigin,
2241
+ ordinary,
2242
+ tag,
2243
+ notes,
2244
+ budget,
2245
+ internalSessions,
2246
+ eventStart,
2247
+ innerKind: 'srcdoc',
2248
+ preferMidLive: true,
2249
+ })
2250
+ : mode === 'page-ordinary'
2251
+ ? await pageNested({
2252
+ reader,
2253
+ client,
2254
+ midOrigin: cross,
2255
+ ordinary,
2256
+ tag,
2257
+ notes,
2258
+ budget,
2259
+ internalSessions,
2260
+ eventStart,
2261
+ innerKind: 'ordinary',
2262
+ preferMidLive: false,
2263
+ })
2264
+ : { incomplete: `unknown protectedParentIframes mode ${mode}` };
565
2265
  if (built.pageId) await outcome(reader.send('Target.closeTarget', { targetId: built.pageId }));
566
2266
  return built;
567
2267
  }