@deviltea/widget-inspector 0.0.3 → 0.1.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.
package/dist/agent.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { INSPECT_ANCHOR_ID_ATTRIBUTE, INSPECT_ANCHOR_TYPE_ATTRIBUTE } from "./anchor.mjs";
2
2
  import { encodeInspectableValue } from "./value.mjs";
3
- import { n as isCompatibleProtocolVersion, s as parseInspectorRequestMessage, t as INSPECTOR_PROTOCOL_VERSION } from "./protocol-D1gtirOC.mjs";
3
+ import { n as classifyInspectorRequest, r as isCompatibleProtocolVersion, t as INSPECTOR_PROTOCOL_VERSION } from "./protocol-ZhhQaTAa.mjs";
4
4
  import { inspectRuntime } from "@deviltea/widget-core/inspection";
5
5
  //#region src/overlay.ts
6
6
  /** Marks the Agent-owned overlay host so geometry observation can ignore Agent chrome. */
@@ -331,13 +331,50 @@ function createSemanticGeometryController(options) {
331
331
  }
332
332
  //#endregion
333
333
  //#region src/projection.ts
334
+ /** `authorWritable`, `valueContractId` and `transitivelyEmits` are emitted from protocol 0.4 on. */
335
+ const MEMBER_METADATA_PROTOCOL_MINOR = 4;
334
336
  function wireNodeId(nodeId) {
335
337
  return nodeId;
336
338
  }
339
+ function projectDependencyTarget(target) {
340
+ switch (target.type) {
341
+ case "self": return { type: "self" };
342
+ case "root": return { type: "root" };
343
+ case "parent": return {
344
+ type: "parent",
345
+ optional: target.optional
346
+ };
347
+ case "widget": return {
348
+ type: "widget",
349
+ widgetId: target.widgetId,
350
+ optional: target.optional
351
+ };
352
+ }
353
+ }
354
+ function projectDependencyOperation(operation) {
355
+ switch (operation.type) {
356
+ case "state-get": return {
357
+ type: "state-get",
358
+ key: operation.key
359
+ };
360
+ case "state-set": return {
361
+ type: "state-set",
362
+ key: operation.key
363
+ };
364
+ case "property-get": return {
365
+ type: "property-get",
366
+ name: operation.name
367
+ };
368
+ case "method-invoke": return {
369
+ type: "method-invoke",
370
+ name: operation.name
371
+ };
372
+ }
373
+ }
337
374
  function projectDependencyReference(reference) {
338
375
  return {
339
- target: { ...reference.target },
340
- operation: { ...reference.operation }
376
+ target: projectDependencyTarget(reference.target),
377
+ operation: projectDependencyOperation(reference.operation)
341
378
  };
342
379
  }
343
380
  function projectDependency(dependency) {
@@ -350,7 +387,10 @@ function projectDependency(dependency) {
350
387
  status: "resolved",
351
388
  target: {
352
389
  nodeId: wireNodeId(dependency.target.nodeId),
353
- member: { ...dependency.target.member }
390
+ member: {
391
+ type: dependency.target.member.type,
392
+ name: dependency.target.member.name
393
+ }
354
394
  }
355
395
  };
356
396
  if (dependency.status === "invalid") return {
@@ -439,32 +479,55 @@ function projectBlueprintSnapshot(runtimeId, inspection, protocolMinor = 2) {
439
479
  state: node.capabilities.state,
440
480
  properties: node.capabilities.properties,
441
481
  methods: node.capabilities.methods
442
- } : { ...node.capabilities },
482
+ } : {
483
+ config: node.capabilities.config,
484
+ slots: node.capabilities.slots,
485
+ state: node.capabilities.state,
486
+ properties: node.capabilities.properties,
487
+ methods: node.capabilities.methods,
488
+ events: node.capabilities.events
489
+ },
443
490
  ...protocolMinor < 2 ? {} : {
444
491
  config: node.config === null ? null : {
445
492
  description: node.config.description,
446
493
  schema: node.config.schema
447
494
  },
448
- events: node.events.map((event) => ({ ...event }))
495
+ events: node.events.map((event) => ({
496
+ type: "event",
497
+ name: event.name,
498
+ description: event.description
499
+ }))
449
500
  },
450
501
  semanticSlots: node.semanticSlots.map((slot) => ({
451
502
  name: slot.name,
452
503
  children: slot.children.map(wireNodeId)
453
504
  })),
454
- state: node.state.map((member) => ({ ...member })),
505
+ state: node.state.map((member) => ({
506
+ type: "state",
507
+ name: member.name,
508
+ ...protocolMinor < MEMBER_METADATA_PROTOCOL_MINOR ? {} : { authorWritable: member.authorWritable }
509
+ })),
455
510
  properties: node.properties.map((member) => ({
456
- ...member,
511
+ type: "property",
512
+ name: member.name,
513
+ ...protocolMinor < MEMBER_METADATA_PROTOCOL_MINOR ? {} : { valueContractId: member.valueContractId },
457
514
  dependencies: member.dependencies.map(projectDependency)
458
515
  })),
459
516
  methods: node.methods.map((member) => ({
460
- ...member,
517
+ type: "method",
518
+ name: member.name,
519
+ transitivelyWrites: member.transitivelyWrites,
520
+ ...protocolMinor < MEMBER_METADATA_PROTOCOL_MINOR ? {} : { transitivelyEmits: member.transitivelyEmits },
461
521
  dependencies: member.dependencies.map(projectDependency)
462
522
  }))
463
523
  };
464
524
  }),
465
525
  invalidCycles: inspection.invalidCycles.map((cycle) => ({ members: cycle.members.map((member) => ({
466
526
  nodeId: wireNodeId(member.nodeId),
467
- member: { ...member.member }
527
+ member: {
528
+ type: member.member.type,
529
+ name: member.member.name
530
+ }
468
531
  })) }))
469
532
  };
470
533
  }
@@ -475,7 +538,7 @@ function projectRuntimeDiagnosticLocation(location) {
475
538
  name: location.type === "state" ? location.key : location.name
476
539
  };
477
540
  }
478
- function projectRuntimeDiagnostic(diagnostic) {
541
+ function projectRuntimeDiagnostic(diagnostic, encoding) {
479
542
  return {
480
543
  code: diagnostic.code,
481
544
  message: diagnostic.message,
@@ -483,15 +546,15 @@ function projectRuntimeDiagnostic(diagnostic) {
483
546
  ..."path" in diagnostic && diagnostic.path !== void 0 ? { path: diagnostic.path.map((segment) => typeof segment === "symbol" ? segment.description ?? "Symbol()" : segment) } : {},
484
547
  ..."reason" in diagnostic && typeof diagnostic.reason === "string" ? { reason: diagnostic.reason } : {},
485
548
  ..."dependency" in diagnostic ? { dependency: projectDependencyReference(diagnostic.dependency) } : {},
486
- ..."candidate" in diagnostic ? { candidate: encodeInspectableValue(diagnostic.candidate) } : {},
487
- ..."received" in diagnostic ? { received: encodeInspectableValue(diagnostic.received) } : {},
488
- ..."result" in diagnostic ? { result: encodeInspectableValue(diagnostic.result) } : {},
489
- ..."args" in diagnostic ? { args: diagnostic.args.map((value) => encodeInspectableValue(value)) } : {},
549
+ ..."candidate" in diagnostic ? { candidate: encodeInspectableValue(diagnostic.candidate, encoding) } : {},
550
+ ..."received" in diagnostic ? { received: encodeInspectableValue(diagnostic.received, encoding) } : {},
551
+ ..."result" in diagnostic ? { result: encodeInspectableValue(diagnostic.result, encoding) } : {},
552
+ ..."args" in diagnostic ? { args: diagnostic.args.map((value) => encodeInspectableValue(value, encoding)) } : {},
490
553
  ..."related" in diagnostic ? { related: diagnostic.related.map(projectRuntimeDiagnosticLocation) } : {},
491
- ..."cause" in diagnostic ? { cause: projectRuntimeDiagnostic(diagnostic.cause) } : {}
554
+ ..."cause" in diagnostic ? { cause: projectRuntimeDiagnostic(diagnostic.cause, encoding) } : {}
492
555
  };
493
556
  }
494
- function projectPropertySnapshot(name, snapshot) {
557
+ function projectPropertySnapshot(name, snapshot, encoding) {
495
558
  if (snapshot.status === "never-evaluated") return {
496
559
  type: "property",
497
560
  name,
@@ -504,37 +567,37 @@ function projectPropertySnapshot(name, snapshot) {
504
567
  status: "completed",
505
568
  result: snapshot.result.ok ? {
506
569
  ok: true,
507
- value: encodeInspectableValue(snapshot.result.value)
570
+ value: encodeInspectableValue(snapshot.result.value, encoding)
508
571
  } : {
509
572
  ok: false,
510
- diagnostics: snapshot.result.failure.diagnostics.map(projectRuntimeDiagnostic)
573
+ diagnostics: snapshot.result.failure.diagnostics.map((diagnostic) => projectRuntimeDiagnostic(diagnostic, encoding))
511
574
  }
512
575
  }
513
576
  };
514
577
  }
515
- function projectRuntimeMemberSnapshot(widget, member) {
578
+ function projectRuntimeMemberSnapshot(widget, member, encoding) {
516
579
  if (member.type === "state") {
517
580
  const inspection = widget.getState(member.name);
518
581
  if (inspection === null) return null;
519
582
  return {
520
583
  type: "state",
521
584
  name: member.name,
522
- value: encodeInspectableValue(inspection.getSnapshot().value)
585
+ value: encodeInspectableValue(inspection.getSnapshot().value, encoding)
523
586
  };
524
587
  }
525
588
  const inspection = widget.getProperty(member.name);
526
- return inspection === null ? null : projectPropertySnapshot(member.name, inspection.getSnapshot());
589
+ return inspection === null ? null : projectPropertySnapshot(member.name, inspection.getSnapshot(), encoding);
527
590
  }
528
- function projectRuntimeWidgetSnapshot(runtimeId, runtimeInspection, nodeId) {
591
+ function projectRuntimeWidgetSnapshot(runtimeId, runtimeInspection, nodeId, encoding) {
529
592
  const widget = runtimeInspection.getWidget(nodeId);
530
593
  if (widget === null || !widget.blueprintNode.resolved) return null;
531
594
  const members = [];
532
595
  for (const state of widget.blueprintNode.state) {
533
- const projected = projectRuntimeMemberSnapshot(widget, state);
596
+ const projected = projectRuntimeMemberSnapshot(widget, state, encoding);
534
597
  if (projected !== null) members.push(projected);
535
598
  }
536
599
  for (const property of widget.blueprintNode.properties) {
537
- const projected = projectRuntimeMemberSnapshot(widget, property);
600
+ const projected = projectRuntimeMemberSnapshot(widget, property, encoding);
538
601
  if (projected !== null) members.push(projected);
539
602
  }
540
603
  return {
@@ -547,8 +610,8 @@ function projectRuntimeWidgetSnapshot(runtimeId, runtimeInspection, nodeId) {
547
610
  members
548
611
  };
549
612
  }
550
- function projectEventArgs(args) {
551
- return args.map((value) => encodeInspectableValue(value));
613
+ function projectEventArgs(args, encoding) {
614
+ return args.map((value) => encodeInspectableValue(value, encoding));
552
615
  }
553
616
  //#endregion
554
617
  //#region src/agent.ts
@@ -558,7 +621,10 @@ const PROTOCOL_0_1_METHODS = Object.freeze([
558
621
  "blueprint.getSnapshot",
559
622
  "runtime.getWidgetSnapshot",
560
623
  "runtime.subscribeMember",
561
- "runtime.unsubscribeMember",
624
+ "runtime.unsubscribeMember"
625
+ ]);
626
+ /** Present only when the Agent has an inspected DOM root: without one they cannot do anything. */
627
+ const PROTOCOL_0_1_DOM_METHODS = Object.freeze([
562
628
  "inspect.enable",
563
629
  "inspect.disable",
564
630
  "highlight.show",
@@ -574,6 +640,9 @@ const PROTOCOL_0_1_EVENTS = Object.freeze([
574
640
  ]);
575
641
  const PROTOCOL_0_2_EVENTS = Object.freeze(["runtime.eventOccurred"]);
576
642
  const PROTOCOL_0_2_GEOMETRY_EVENTS = Object.freeze(["geometry.invalidated"]);
643
+ const PROTOCOL_0_4_EVENTS = Object.freeze(["runtime.disposed"]);
644
+ /** `runtime.disposed` and the `runtime-disposed` error code exist from this protocol minor on. */
645
+ const RUNTIME_LIFECYCLE_PROTOCOL_MINOR = 4;
577
646
  let runtimeSequence = 1;
578
647
  let subscriptionSequence = 1;
579
648
  function createRuntimeId() {
@@ -591,31 +660,44 @@ function protocolError(code, message) {
591
660
  function createInspectorAgent(options) {
592
661
  const maxSubscriptions = options.maxSubscriptions;
593
662
  if (maxSubscriptions !== void 0 && !(Number.isSafeInteger(maxSubscriptions) && maxSubscriptions >= 1)) throw new RangeError("maxSubscriptions must be a positive safe integer when configured.");
663
+ const valueLimits = { ...options.valueLimits };
664
+ for (const [name, limit] of Object.entries(valueLimits)) {
665
+ const minimum = name === "maxDepth" ? 0 : 1;
666
+ if (limit !== void 0 && !(Number.isSafeInteger(limit) && limit >= minimum)) throw new RangeError(`valueLimits.${name} must be a safe integer of at least ${minimum} when configured.`);
667
+ }
594
668
  const runtimeId = options.runtimeId ?? createRuntimeId();
595
669
  const runtimeInspection = inspectRuntime(options.runtime);
596
670
  const dom = options.dom;
597
671
  const memberSubscriptions = /* @__PURE__ */ new Map();
598
672
  const eventSubscriptions = /* @__PURE__ */ new Map();
599
673
  let negotiatedMinor = INSPECTOR_PROTOCOL_VERSION.minor;
674
+ let requestMinor = null;
675
+ const currentMinor = () => requestMinor ?? negotiatedMinor;
600
676
  const envelopeVersion = () => ({
601
677
  major: INSPECTOR_PROTOCOL_VERSION.major,
602
- minor: negotiatedMinor
678
+ minor: currentMinor()
679
+ });
680
+ const valueEncoding = () => ({
681
+ ...valueLimits,
682
+ markTruncatedKeys: currentMinor() >= 4
603
683
  });
604
684
  function capabilitiesForMinor(minor) {
605
685
  if (minor < 2) return {
606
- methods: PROTOCOL_0_1_METHODS,
686
+ methods: dom === void 0 ? PROTOCOL_0_1_METHODS : Object.freeze([...PROTOCOL_0_1_METHODS, ...PROTOCOL_0_1_DOM_METHODS]),
607
687
  events: PROTOCOL_0_1_EVENTS
608
688
  };
609
689
  return {
610
690
  methods: dom === void 0 ? Object.freeze([...PROTOCOL_0_1_METHODS, ...PROTOCOL_0_2_METHODS]) : Object.freeze([
611
691
  ...PROTOCOL_0_1_METHODS,
692
+ ...PROTOCOL_0_1_DOM_METHODS,
612
693
  ...PROTOCOL_0_2_METHODS,
613
694
  ...PROTOCOL_0_2_GEOMETRY_METHODS
614
695
  ]),
615
- events: dom === void 0 ? Object.freeze([...PROTOCOL_0_1_EVENTS, ...PROTOCOL_0_2_EVENTS]) : Object.freeze([
696
+ events: Object.freeze([
616
697
  ...PROTOCOL_0_1_EVENTS,
617
698
  ...PROTOCOL_0_2_EVENTS,
618
- ...PROTOCOL_0_2_GEOMETRY_EVENTS
699
+ ...dom === void 0 ? [] : PROTOCOL_0_2_GEOMETRY_EVENTS,
700
+ ...minor < RUNTIME_LIFECYCLE_PROTOCOL_MINOR ? [] : PROTOCOL_0_4_EVENTS
619
701
  ])
620
702
  };
621
703
  }
@@ -623,14 +705,49 @@ function createInspectorAgent(options) {
623
705
  let disposed = false;
624
706
  const overlay = dom === void 0 ? null : createInspectorOverlay(dom.root.ownerDocument);
625
707
  let highlightedTarget = null;
708
+ let runtimeDisposalAnnounced = false;
709
+ let peerHeard = false;
626
710
  function emit(event, payload) {
711
+ if (event !== "runtime.disposed") observeRuntimeDisposal();
627
712
  if (disposed || options.transport.closed || !capabilitiesForMinor(negotiatedMinor).events.includes(event)) return;
628
- options.transport.send({
629
- protocol: envelopeVersion(),
630
- kind: "event",
631
- event,
632
- payload
633
- });
713
+ try {
714
+ options.transport.send({
715
+ protocol: {
716
+ major: INSPECTOR_PROTOCOL_VERSION.major,
717
+ minor: negotiatedMinor
718
+ },
719
+ kind: "event",
720
+ event,
721
+ payload
722
+ });
723
+ } catch {}
724
+ }
725
+ /**
726
+ * Announces disposal at most once. The Agent registers `runtime.subscribeDisposal()` so this runs inside
727
+ * `runtime.dispose()`, but only once the peer has sent a request (before that nobody is known to be
728
+ * listening). It also checks `isDisposed` when any request arrives, before it emits any other event, and
729
+ * when the Agent itself is disposed: that is the path for a peer the Agent had not heard from at disposal
730
+ * and for an Agent created on a Runtime that was already disposed (subscribing to one throws), and it keeps
731
+ * everything consistent whenever the listener could not tell the peer.
732
+ */
733
+ function observeRuntimeDisposal() {
734
+ if (!options.runtime.isDisposed) return false;
735
+ if (!runtimeDisposalAnnounced) {
736
+ runtimeDisposalAnnounced = true;
737
+ releaseSubscriptions();
738
+ clearHighlight();
739
+ emit("runtime.disposed", {
740
+ runtimeId,
741
+ reason: "runtime-disposed"
742
+ });
743
+ }
744
+ return true;
745
+ }
746
+ function releaseSubscriptions() {
747
+ for (const unsubscribe of memberSubscriptions.values()) unsubscribe();
748
+ memberSubscriptions.clear();
749
+ for (const unsubscribe of eventSubscriptions.values()) unsubscribe();
750
+ eventSubscriptions.clear();
634
751
  }
635
752
  function sendSuccess(request, result) {
636
753
  if (disposed || options.transport.closed) return;
@@ -654,15 +771,20 @@ function createInspectorAgent(options) {
654
771
  }
655
772
  function resolveNodeId(ref) {
656
773
  if (ref.runtimeId !== runtimeId) return null;
657
- return runtimeInspection.blueprint.nodes.find((node) => node.nodeId === ref.nodeId)?.nodeId ?? null;
774
+ const node = runtimeInspection.blueprint.getNode(ref.nodeId);
775
+ return node !== null && node.nodeId === ref.nodeId ? node.nodeId : null;
658
776
  }
659
777
  function resolveWidget(ref) {
660
778
  const nodeId = resolveNodeId(ref);
661
779
  return nodeId === null ? null : runtimeInspection.getWidget(nodeId);
662
780
  }
663
781
  function nodeForAnchor(anchor) {
664
- const node = runtimeInspection.blueprint.nodes.find((candidate) => candidate.resolved && candidate.node.id === anchor.widgetId && candidate.node.type === anchor.widgetType);
665
- return node === void 0 ? null : {
782
+ const widget = options.runtime.blueprint.getWidget(anchor.widgetId);
783
+ if (widget === null) return null;
784
+ const nodeId = runtimeInspection.blueprint.getNodeId(widget);
785
+ const node = nodeId === null ? null : runtimeInspection.blueprint.getNode(nodeId);
786
+ if (node === null || !node.resolved || node.node.id !== anchor.widgetId || node.node.type !== anchor.widgetType) return null;
787
+ return {
666
788
  runtimeId,
667
789
  nodeId: node.nodeId
668
790
  };
@@ -702,21 +824,27 @@ function createInspectorAgent(options) {
702
824
  ...identity
703
825
  };
704
826
  }
705
- const geometry = dom === void 0 ? null : createSemanticGeometryController({
706
- root: dom.root,
707
- resolveRef: semanticTargetForRef,
708
- resolveAnchor: semanticTargetForAnchorElement,
709
- onInvalidated: (revision) => {
710
- drawHighlight();
711
- emit("geometry.invalidated", { revision });
712
- }
713
- });
827
+ let geometryController = null;
828
+ function ensureGeometry() {
829
+ if (dom === void 0 || disposed) return geometryController;
830
+ geometryController ??= createSemanticGeometryController({
831
+ root: dom.root,
832
+ resolveRef: semanticTargetForRef,
833
+ resolveAnchor: semanticTargetForAnchorElement,
834
+ onInvalidated: (revision) => {
835
+ drawHighlight();
836
+ emit("geometry.invalidated", { revision });
837
+ }
838
+ });
839
+ return geometryController;
840
+ }
714
841
  function clearHighlight() {
715
842
  highlightedTarget = null;
716
843
  overlay?.clear();
717
844
  }
718
845
  /** Draws every fragment of the highlighted Widget; returns whether any anchor element exists. */
719
846
  function drawHighlight() {
847
+ const geometry = ensureGeometry();
720
848
  if (overlay === null || geometry === null || highlightedTarget === null) return false;
721
849
  const measurement = geometry.measure(highlightedTarget);
722
850
  if (measurement.rects.length === 0) overlay.clear();
@@ -727,6 +855,7 @@ function createInspectorAgent(options) {
727
855
  return measurement.anchorCount > 0;
728
856
  }
729
857
  function highlightTarget(target) {
858
+ const geometry = ensureGeometry();
730
859
  if (geometry === null || overlay === null || geometry.measure(target).anchorCount === 0) return false;
731
860
  highlightedTarget = target;
732
861
  return drawHighlight();
@@ -739,46 +868,57 @@ function createInspectorAgent(options) {
739
868
  if (!inspectEnabled) return;
740
869
  inspectEnabled = false;
741
870
  clearHighlight();
742
- emit("inspect.hovered", { ref: null });
871
+ setHovered(null);
743
872
  emit("agent.status", { inspectEnabled: false });
744
873
  }
874
+ let hoveredNodeId = null;
875
+ function setHovered(target) {
876
+ const nodeId = target === null ? null : target.ref.nodeId;
877
+ if (nodeId === hoveredNodeId) return;
878
+ hoveredNodeId = nodeId;
879
+ emit("inspect.hovered", target === null ? { ref: null } : {
880
+ ref: target.ref,
881
+ widgetId: target.widgetId,
882
+ widgetType: target.widgetType
883
+ });
884
+ }
885
+ function inspectingLiveRuntime() {
886
+ return inspectEnabled && !options.runtime.isDisposed;
887
+ }
745
888
  function onPointerOver(event) {
746
- if (!inspectEnabled) return;
889
+ if (!inspectingLiveRuntime()) return;
747
890
  const anchor = resolveAnchor(event.target);
748
891
  if (anchor === null) {
749
892
  clearHighlight();
750
- emit("inspect.hovered", { ref: null });
893
+ setHovered(null);
751
894
  return;
752
895
  }
753
896
  const ref = nodeForAnchor(anchor);
754
897
  if (ref === null) {
755
898
  clearHighlight();
756
- emit("inspect.hovered", { ref: null });
899
+ setHovered(null);
757
900
  return;
758
901
  }
759
- highlightTarget({
760
- ref,
761
- widgetId: anchor.widgetId,
762
- widgetType: anchor.widgetType
763
- });
764
- emit("inspect.hovered", {
902
+ const target = {
765
903
  ref,
766
904
  widgetId: anchor.widgetId,
767
905
  widgetType: anchor.widgetType
768
- });
906
+ };
907
+ highlightTarget(target);
908
+ setHovered(target);
769
909
  }
770
910
  function onPointerLeave() {
771
911
  if (!inspectEnabled) return;
772
912
  clearHighlight();
773
- emit("inspect.hovered", { ref: null });
913
+ setHovered(null);
774
914
  }
775
915
  function suppressPointerActivation(event) {
776
- if (!inspectEnabled || resolveAnchor(event.target) === null) return;
916
+ if (!inspectingLiveRuntime() || resolveAnchor(event.target) === null) return;
777
917
  event.preventDefault();
778
918
  event.stopPropagation();
779
919
  }
780
920
  function onClick(event) {
781
- if (!inspectEnabled) return;
921
+ if (!inspectingLiveRuntime()) return;
782
922
  const anchor = resolveAnchor(event.target);
783
923
  if (anchor === null) return;
784
924
  event.preventDefault();
@@ -819,7 +959,7 @@ function createInspectorAgent(options) {
819
959
  function rejectAtSubscriptionLimit(request) {
820
960
  if (maxSubscriptions === void 0 || memberSubscriptions.size + eventSubscriptions.size < maxSubscriptions) return false;
821
961
  const message = `This Inspector Agent allows at most ${maxSubscriptions} live subscriptions.`;
822
- sendError(request.requestId, protocolError(negotiatedMinor >= 3 ? "subscription-limit" : "internal-error", message));
962
+ sendError(request.requestId, protocolError(currentMinor() >= 3 ? "subscription-limit" : "internal-error", message));
823
963
  return true;
824
964
  }
825
965
  function subscribeMember(request) {
@@ -834,7 +974,7 @@ function createInspectorAgent(options) {
834
974
  }
835
975
  const member = request.params.member;
836
976
  const observable = member.type === "state" ? widget.getState(member.name) : widget.getProperty(member.name);
837
- const projected = projectRuntimeMemberSnapshot(widget, member);
977
+ const projected = projectRuntimeMemberSnapshot(widget, member, valueEncoding());
838
978
  if (observable === null || projected === null) {
839
979
  sendError(request.requestId, protocolError("member-not-found", "The requested Runtime member does not exist."));
840
980
  return;
@@ -844,7 +984,7 @@ function createInspectorAgent(options) {
844
984
  let unsubscribe;
845
985
  try {
846
986
  unsubscribe = observable.subscribe(() => {
847
- const next = projectRuntimeMemberSnapshot(widget, member);
987
+ const next = projectRuntimeMemberSnapshot(widget, member, valueEncoding());
848
988
  if (next !== null) emit("runtime.memberChanged", {
849
989
  subscriptionId,
850
990
  ref: request.params.ref,
@@ -856,10 +996,16 @@ function createInspectorAgent(options) {
856
996
  return;
857
997
  }
858
998
  memberSubscriptions.set(subscriptionId, unsubscribe);
859
- sendSuccess(request, {
860
- subscriptionId,
861
- member: projected
862
- });
999
+ try {
1000
+ sendSuccess(request, {
1001
+ subscriptionId,
1002
+ member: projected
1003
+ });
1004
+ } catch (error) {
1005
+ memberSubscriptions.delete(subscriptionId);
1006
+ unsubscribe();
1007
+ throw error;
1008
+ }
863
1009
  }
864
1010
  function subscribeEvent(request) {
865
1011
  if (request.params.ref.runtimeId !== runtimeId) {
@@ -885,7 +1031,7 @@ function createInspectorAgent(options) {
885
1031
  subscriptionId,
886
1032
  ref: request.params.ref,
887
1033
  event: request.params.event,
888
- args: projectEventArgs(args)
1034
+ args: projectEventArgs(args, valueEncoding())
889
1035
  });
890
1036
  });
891
1037
  } catch {
@@ -893,22 +1039,56 @@ function createInspectorAgent(options) {
893
1039
  return;
894
1040
  }
895
1041
  eventSubscriptions.set(subscriptionId, unsubscribe);
896
- sendSuccess(request, {
897
- subscriptionId,
898
- event: request.params.event
899
- });
1042
+ try {
1043
+ sendSuccess(request, {
1044
+ subscriptionId,
1045
+ event: request.params.event
1046
+ });
1047
+ } catch (error) {
1048
+ eventSubscriptions.delete(subscriptionId);
1049
+ unsubscribe();
1050
+ throw error;
1051
+ }
1052
+ }
1053
+ /** The Runtime id a request addresses (directly or through a WidgetRef), if it addresses one. */
1054
+ function addressedRuntimeId(request) {
1055
+ switch (request.method) {
1056
+ case "blueprint.getSnapshot": return request.params.runtimeId;
1057
+ case "runtime.getWidgetSnapshot":
1058
+ case "runtime.subscribeMember":
1059
+ case "runtime.subscribeEvent":
1060
+ case "geometry.resolve":
1061
+ case "highlight.show": return request.params.ref.runtimeId;
1062
+ default: return null;
1063
+ }
1064
+ }
1065
+ /** Methods that address no Runtime id but still act on the live Runtime's inspected document. */
1066
+ function dependsOnLiveRuntime(request) {
1067
+ return request.method === "inspect.hitTest" || request.method === "inspect.enable" || request.method === "highlight.clear";
900
1068
  }
901
1069
  function handleRequest(request) {
1070
+ try {
1071
+ handleRequestAtMinor(request);
1072
+ } finally {
1073
+ requestMinor = null;
1074
+ }
1075
+ }
1076
+ function handleRequestAtMinor(request) {
902
1077
  if (!isCompatibleProtocolVersion(request.protocol)) {
903
1078
  sendError(request.requestId, protocolError("unsupported-version", `Unsupported Inspector protocol major ${request.protocol.major}.`));
904
1079
  return;
905
1080
  }
1081
+ const runtimeDisposed = observeRuntimeDisposal();
906
1082
  if (request.method !== "handshake") {
907
- negotiatedMinor = Math.min(negotiatedMinor, request.protocol.minor);
908
- if (!capabilitiesForMinor(negotiatedMinor).methods.includes(request.method)) {
1083
+ requestMinor = Math.min(negotiatedMinor, request.protocol.minor);
1084
+ if (!capabilitiesForMinor(requestMinor).methods.includes(request.method)) {
909
1085
  sendError(request.requestId, protocolError("unknown-method", "Method unavailable in this Inspector protocol session."));
910
1086
  return;
911
1087
  }
1088
+ if (runtimeDisposed && requestMinor >= RUNTIME_LIFECYCLE_PROTOCOL_MINOR && (addressedRuntimeId(request) === runtimeId || dependsOnLiveRuntime(request))) {
1089
+ sendError(request.requestId, protocolError("runtime-disposed", "The requested Runtime has been disposed."));
1090
+ return;
1091
+ }
912
1092
  }
913
1093
  switch (request.method) {
914
1094
  case "handshake": {
@@ -925,7 +1105,7 @@ function createInspectorAgent(options) {
925
1105
  return;
926
1106
  }
927
1107
  case "runtime.list":
928
- sendSuccess(request, { runtimes: [{
1108
+ sendSuccess(request, { runtimes: runtimeDisposed && currentMinor() >= RUNTIME_LIFECYCLE_PROTOCOL_MINOR ? [] : [{
929
1109
  runtimeId,
930
1110
  rootNodeId: runtimeInspection.blueprint.rootNodeId
931
1111
  }] });
@@ -935,7 +1115,7 @@ function createInspectorAgent(options) {
935
1115
  sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
936
1116
  return;
937
1117
  }
938
- sendSuccess(request, projectBlueprintSnapshot(runtimeId, runtimeInspection.blueprint, negotiatedMinor));
1118
+ sendSuccess(request, projectBlueprintSnapshot(runtimeId, runtimeInspection.blueprint, currentMinor()));
939
1119
  return;
940
1120
  case "runtime.getWidgetSnapshot": {
941
1121
  if (request.params.ref.runtimeId !== runtimeId) {
@@ -943,7 +1123,7 @@ function createInspectorAgent(options) {
943
1123
  return;
944
1124
  }
945
1125
  const nodeId = resolveNodeId(request.params.ref);
946
- const snapshot = nodeId === null ? null : projectRuntimeWidgetSnapshot(runtimeId, runtimeInspection, nodeId);
1126
+ const snapshot = nodeId === null ? null : projectRuntimeWidgetSnapshot(runtimeId, runtimeInspection, nodeId, valueEncoding());
947
1127
  if (snapshot === null) {
948
1128
  sendError(request.requestId, protocolError("widget-not-found", "The requested widget does not exist in this Runtime snapshot."));
949
1129
  return;
@@ -979,25 +1159,30 @@ function createInspectorAgent(options) {
979
1159
  sendSuccess(request, { removed: true });
980
1160
  return;
981
1161
  }
982
- case "inspect.hitTest":
1162
+ case "inspect.hitTest": {
1163
+ const geometry = ensureGeometry();
983
1164
  if (geometry === null) {
984
1165
  sendError(request.requestId, protocolError("internal-error", "DOM geometry is unavailable for this Inspector Agent."));
985
1166
  return;
986
1167
  }
987
1168
  sendSuccess(request, geometry.hitTest(request.params));
988
1169
  return;
989
- case "geometry.resolve":
1170
+ }
1171
+ case "geometry.resolve": {
990
1172
  if (request.params.ref.runtimeId !== runtimeId) {
991
1173
  sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
992
1174
  return;
993
1175
  }
1176
+ const geometry = ensureGeometry();
994
1177
  if (geometry === null) {
995
1178
  sendError(request.requestId, protocolError("internal-error", "DOM geometry is unavailable for this Inspector Agent."));
996
1179
  return;
997
1180
  }
998
1181
  sendSuccess(request, geometry.resolve(request.params.ref));
999
1182
  return;
1183
+ }
1000
1184
  case "inspect.enable":
1185
+ ensureGeometry();
1001
1186
  inspectEnabled = true;
1002
1187
  emit("agent.status", { inspectEnabled: true });
1003
1188
  sendSuccess(request, { enabled: true });
@@ -1019,24 +1204,50 @@ function createInspectorAgent(options) {
1019
1204
  }
1020
1205
  }
1021
1206
  const removeDomListeners = installDomListeners();
1207
+ const unsubscribeDisposal = options.runtime.isDisposed ? () => {} : options.runtime.subscribeDisposal(() => {
1208
+ if (peerHeard) observeRuntimeDisposal();
1209
+ });
1022
1210
  const unsubscribeTransport = options.transport.subscribe((raw) => {
1023
- const request = parseInspectorRequestMessage(raw);
1024
- if (request !== null) {
1025
- handleRequest(request);
1026
- return;
1211
+ peerHeard = true;
1212
+ let requestId = null;
1213
+ try {
1214
+ const classified = classifyInspectorRequest(raw);
1215
+ if (classified.ok) {
1216
+ requestId = classified.request.requestId;
1217
+ handleRequest(classified.request);
1218
+ return;
1219
+ }
1220
+ if (classified.requestId === null) return;
1221
+ requestId = classified.requestId;
1222
+ if (classified.protocol !== null && !isCompatibleProtocolVersion(classified.protocol)) sendError(requestId, protocolError("unsupported-version", `Unsupported Inspector protocol major ${classified.protocol.major}.`));
1223
+ else if (classified.code === "unknown-method") sendError(requestId, protocolError("unknown-method", "The requested method is not defined by this Inspector protocol."));
1224
+ else if (classified.code === "invalid-params") sendError(requestId, protocolError("invalid-params", "Invalid parameters for the requested Inspector method."));
1225
+ else sendError(requestId, protocolError("invalid-message", "Invalid Inspector protocol request."));
1226
+ } catch (error) {
1227
+ queueMicrotask(() => {
1228
+ throw error;
1229
+ });
1230
+ try {
1231
+ if (requestId === null && typeof raw === "object" && raw !== null && "requestId" in raw && typeof raw.requestId === "string") requestId = raw.requestId;
1232
+ if (requestId !== null) sendError(requestId, protocolError("internal-error", "The Inspector Agent failed to handle the request."));
1233
+ } catch {}
1027
1234
  }
1028
- if (typeof raw === "object" && raw !== null && "kind" in raw && raw.kind === "request" && "requestId" in raw && typeof raw.requestId === "string") sendError(raw.requestId, protocolError("invalid-message", "Invalid Inspector protocol request."));
1029
1235
  });
1030
1236
  let unsubscribeClose = () => {};
1031
1237
  function cleanup(closeTransport) {
1032
1238
  if (disposed) return;
1239
+ if (!closeTransport && !runtimeDisposalAnnounced) {
1240
+ runtimeDisposalAnnounced = true;
1241
+ emit("runtime.disposed", {
1242
+ runtimeId,
1243
+ reason: options.runtime.isDisposed ? "runtime-disposed" : "agent-disposed"
1244
+ });
1245
+ }
1033
1246
  disposed = true;
1034
- for (const unsubscribe of memberSubscriptions.values()) unsubscribe();
1035
- memberSubscriptions.clear();
1036
- for (const unsubscribe of eventSubscriptions.values()) unsubscribe();
1037
- eventSubscriptions.clear();
1247
+ unsubscribeDisposal();
1248
+ releaseSubscriptions();
1038
1249
  removeDomListeners();
1039
- geometry?.dispose();
1250
+ geometryController?.dispose();
1040
1251
  clearHighlight();
1041
1252
  unsubscribeTransport();
1042
1253
  unsubscribeClose();
@@ -1049,7 +1260,7 @@ function createInspectorAgent(options) {
1049
1260
  return inspectEnabled;
1050
1261
  },
1051
1262
  invalidateGeometry() {
1052
- geometry?.invalidate();
1263
+ geometryController?.invalidate();
1053
1264
  },
1054
1265
  dispose() {
1055
1266
  cleanup(options.closeTransportOnDispose ?? true);