@immense/vue-pom-generator 1.0.90 → 1.0.92

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.
Files changed (62) hide show
  1. package/README.md +88 -10
  2. package/RELEASE_NOTES.md +95 -62
  3. package/class-generation/base-page.ts +141 -59
  4. package/class-generation/diagnostics.ts +559 -0
  5. package/class-generation/index.ts +247 -128
  6. package/class-generation/playwright-types.ts +7 -11
  7. package/class-generation/pointer.ts +65 -18
  8. package/dist/class-generation/base-page.d.ts +19 -4
  9. package/dist/class-generation/base-page.d.ts.map +1 -1
  10. package/dist/class-generation/diagnostics.d.ts +110 -0
  11. package/dist/class-generation/diagnostics.d.ts.map +1 -0
  12. package/dist/class-generation/index.d.ts +4 -0
  13. package/dist/class-generation/index.d.ts.map +1 -1
  14. package/dist/class-generation/playwright-types.d.ts +3 -39
  15. package/dist/class-generation/playwright-types.d.ts.map +1 -1
  16. package/dist/class-generation/pointer.d.ts +10 -1
  17. package/dist/class-generation/pointer.d.ts.map +1 -1
  18. package/dist/eslint/index.cjs +52 -9
  19. package/dist/eslint/index.cjs.map +1 -1
  20. package/dist/eslint/index.d.ts +16 -7
  21. package/dist/eslint/index.d.ts.map +1 -1
  22. package/dist/eslint/index.mjs +52 -9
  23. package/dist/eslint/index.mjs.map +1 -1
  24. package/dist/index.cjs +728 -324
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.mjs +728 -324
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/manifest-generator.d.ts +10 -5
  29. package/dist/manifest-generator.d.ts.map +1 -1
  30. package/dist/method-generation.d.ts.map +1 -1
  31. package/dist/playwright/reporter.cjs +174 -0
  32. package/dist/playwright/reporter.cjs.map +1 -0
  33. package/dist/playwright/reporter.d.ts +13 -0
  34. package/dist/playwright/reporter.d.ts.map +1 -0
  35. package/dist/playwright/reporter.mjs +174 -0
  36. package/dist/playwright/reporter.mjs.map +1 -0
  37. package/dist/plugin/internal/build-plugin.d.ts +2 -0
  38. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  39. package/dist/plugin/internal/dev-plugin.d.ts +2 -0
  40. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  41. package/dist/plugin/internal-plugins.d.ts.map +1 -1
  42. package/dist/route-navigation-codegen.d.ts +40 -0
  43. package/dist/route-navigation-codegen.d.ts.map +1 -0
  44. package/dist/router-bridge.d.ts +15 -0
  45. package/dist/router-bridge.d.ts.map +1 -1
  46. package/dist/router.cjs +41 -1
  47. package/dist/router.cjs.map +1 -1
  48. package/dist/router.mjs +41 -1
  49. package/dist/router.mjs.map +1 -1
  50. package/dist/tests/broad/helpers/fake-runtime.d.ts +27 -3
  51. package/dist/tests/broad/helpers/fake-runtime.d.ts.map +1 -1
  52. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts +16 -3
  53. package/dist/tests/fixtures/generated-tsc/base-page.full.d.ts.map +1 -1
  54. package/dist/tests/method-generation.test.d.ts +2 -0
  55. package/dist/tests/method-generation.test.d.ts.map +1 -0
  56. package/dist/tests/playwright-diagnostics.test.d.ts +2 -0
  57. package/dist/tests/playwright-diagnostics.test.d.ts.map +1 -0
  58. package/dist/tests/playwright-reporter.test.d.ts +2 -0
  59. package/dist/tests/playwright-reporter.test.d.ts.map +1 -0
  60. package/dist/transform.d.ts.map +1 -1
  61. package/dist/vite.config.d.ts.map +1 -1
  62. package/package.json +8 -1
package/dist/index.cjs CHANGED
@@ -665,6 +665,10 @@ function upperFirst$1(value) {
665
665
  }
666
666
  return value.charAt(0).toUpperCase() + value.slice(1);
667
667
  }
668
+ function generatedActionMetadata(componentName, methodName, options = {}) {
669
+ const preferAssociatedLabel = options.preferAssociatedLabel ? ", preferAssociatedLabel: true" : "";
670
+ return `{ componentName: ${JSON.stringify(componentName)}, methodName: ${JSON.stringify(methodName)}${preferAssociatedLabel} }`;
671
+ }
668
672
  function createParameters(params) {
669
673
  return toTypeScriptPomParameterStructures(params);
670
674
  }
@@ -690,7 +694,7 @@ function createAsyncMethod(name, parameters, statements) {
690
694
  statements
691
695
  });
692
696
  }
693
- function generateClickMethod(componentName, methodName, selector, alternateSelectors, parameters) {
697
+ function generateClickMethod(componentName, methodName, nativeRole, selector, alternateSelectors, parameters) {
694
698
  const name = `click${methodName}`;
695
699
  const noWaitName = `${name}NoWait`;
696
700
  const locatorDescription = JSON.stringify(buildPomLocatorDescription({
@@ -704,6 +708,9 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
704
708
  const argsForForward = getPomParameterNames(selectorParams).join(", ");
705
709
  const alternates = uniquePomStringPatterns(selector, alternateSelectors).slice(1);
706
710
  const primaryTestIdExpr = toTypeScriptPomPatternExpression(selector);
711
+ const actionMetadata = generatedActionMetadata(componentName, name, {
712
+ preferAssociatedLabel: nativeRole === "checkbox"
713
+ });
707
714
  if (alternates.length > 0) {
708
715
  const candidatesExpr = [primaryTestIdExpr, ...alternates.map((id) => toTypeScriptPomPatternExpression(id))].join(", ");
709
716
  const clickMethod = createAsyncMethod(
@@ -718,20 +725,8 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
718
725
  ],
719
726
  (writer) => {
720
727
  writer.writeLine(`const candidates = [${candidatesExpr}] as const;`);
721
- writer.writeLine("let lastError: unknown;");
722
- writer.write("for (const testId of candidates) ").block(() => {
723
- writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription});`);
724
- writer.write("try ").block(() => {
725
- writer.write("if (await locator.count()) ").block(() => {
726
- writer.writeLine("await this.clickLocator(locator, annotationText, wait);");
727
- writer.writeLine("return;");
728
- });
729
- });
730
- writer.write("catch (e) ").block(() => {
731
- writer.writeLine("lastError = e;");
732
- });
733
- });
734
- writer.writeLine(`throw (lastError instanceof Error) ? lastError : new Error("[pom] Failed to click any candidate locator for ${name}.");`);
728
+ writer.writeLine(`const locator = await this.resolveVisibleTestIdLocator(candidates, ${locatorDescription}, ${JSON.stringify(name)}, ${JSON.stringify(componentName)});`);
729
+ writer.writeLine("await this.clickLocator(locator, annotationText, wait);");
735
730
  }
736
731
  );
737
732
  const noWaitArgs = argsForForward ? `${argsForForward}, false, annotationText` : "false, annotationText";
@@ -754,7 +749,7 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
754
749
  createInlineParameter("annotationText", { type: "string", initializer: '""' })
755
750
  ],
756
751
  (writer) => {
757
- writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription});`);
752
+ writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription}, ${actionMetadata});`);
758
753
  }
759
754
  ),
760
755
  createAsyncMethod(
@@ -774,7 +769,7 @@ function generateClickMethod(componentName, methodName, selector, alternateSelec
774
769
  createInlineParameter("annotationText", { type: "string", initializer: '""' })
775
770
  ],
776
771
  (writer) => {
777
- writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription});`);
772
+ writer.writeLine(`await this.clickByTestId(${primaryTestIdExpr}, annotationText, wait, ${locatorDescription}, ${actionMetadata});`);
778
773
  }
779
774
  ),
780
775
  createAsyncMethod(
@@ -798,7 +793,7 @@ function generateRadioMethod(componentName, methodName, selector, parameters) {
798
793
  const testIdExpr = toTypeScriptPomPatternExpression(selector);
799
794
  return [
800
795
  createAsyncMethod(name, methodParameters, (writer) => {
801
- writer.writeLine(`await this.clickByTestId(${testIdExpr}, annotationText, true, ${locatorDescription});`);
796
+ writer.writeLine(`await this.clickByTestId(${testIdExpr}, annotationText, true, ${locatorDescription}, ${generatedActionMetadata(componentName, name, { preferAssociatedLabel: true })});`);
802
797
  })
803
798
  ];
804
799
  }
@@ -817,7 +812,8 @@ function generateSelectMethod(componentName, methodName, selector, parameters) {
817
812
  createParameters(selectorParams),
818
813
  (writer) => {
819
814
  writer.writeLine(`const testId = ${testIdExpr};`);
820
- writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription});`);
815
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(componentName)}, ${JSON.stringify(name)}, [testId]);`);
816
+ writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription}).filter({ visible: true }).first();`);
821
817
  writer.writeLine("await this.animateCursorToElement(locator, false, 500, annotationText);");
822
818
  writer.writeLine("await locator.selectOption(value);");
823
819
  }
@@ -831,13 +827,13 @@ function generateVSelectMethod(componentName, methodName, selector, parameters)
831
827
  methodName,
832
828
  nativeRole: "vselect"
833
829
  }));
834
- const selectorParams = orderPomPatternParameters(parameters, [selector]);
830
+ const selectorParams = orderPomPatternParameters(parameters, [selector]).filter((parameter) => parameter.name !== "timeOut" && parameter.name !== "timeout");
835
831
  return [
836
832
  createAsyncMethod(
837
833
  name,
838
834
  createParameters(selectorParams),
839
835
  (writer) => {
840
- writer.writeLine(`await this.selectVSelectByTestId(${toTypeScriptPomPatternExpression(selector)}, value, timeOut, annotationText, ${locatorDescription});`);
836
+ writer.writeLine(`await this.selectVSelectByTestId(${toTypeScriptPomPatternExpression(selector)}, value, annotationText, ${locatorDescription}, ${generatedActionMetadata(componentName, name)});`);
841
837
  }
842
838
  )
843
839
  ];
@@ -855,7 +851,7 @@ function generateTypeMethod(componentName, methodName, selector, parameters) {
855
851
  name,
856
852
  createParameters(selectorParams),
857
853
  (writer) => {
858
- writer.writeLine(`await this.fillInputByTestId(${toTypeScriptPomPatternExpression(selector)}, text, annotationText, ${locatorDescription});`);
854
+ writer.writeLine(`await this.fillInputByTestId(${toTypeScriptPomPatternExpression(selector)}, text, annotationText, ${locatorDescription}, ${generatedActionMetadata(componentName, name)});`);
859
855
  }
860
856
  )
861
857
  ];
@@ -935,20 +931,9 @@ function generateNavigationMethod(args) {
935
931
  statements: (writer) => {
936
932
  writer.write("return this.fluent(async () => ").block(() => {
937
933
  writer.writeLine(`const candidates = [${candidatesExpr}] as const;`);
938
- writer.writeLine("let lastError: unknown;");
939
- writer.write("for (const testId of candidates) ").block(() => {
940
- writer.writeLine(`const locator = this.locatorByTestId(testId, ${locatorDescription});`);
941
- writer.write("try ").block(() => {
942
- writer.write("if (await locator.count()) ").block(() => {
943
- writer.writeLine("await this.clickLocator(locator);");
944
- writer.writeLine(`return new ${target}(this.page);`);
945
- });
946
- });
947
- writer.write("catch (e) ").block(() => {
948
- writer.writeLine("lastError = e;");
949
- });
950
- });
951
- writer.writeLine(`throw (lastError instanceof Error) ? lastError : new Error("[pom] Failed to navigate using any candidate locator for ${methodName}.");`);
934
+ writer.writeLine(`const locator = await this.resolveVisibleTestIdLocator(candidates, ${locatorDescription}, ${JSON.stringify(methodName)}, ${JSON.stringify(componentName)});`);
935
+ writer.writeLine("await this.clickLocator(locator);");
936
+ writer.writeLine(`return new ${target}(this.page);`);
952
937
  });
953
938
  writer.writeLine(");");
954
939
  }
@@ -963,6 +948,7 @@ function generateNavigationMethod(args) {
963
948
  statements: (writer) => {
964
949
  writer.write("return this.fluent(async () => ").block(() => {
965
950
  writer.writeLine(`const locator = this.locatorByTestId(${toTypeScriptPomPatternExpression(selector)}, ${locatorDescription});`);
951
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(componentName)}, ${JSON.stringify(methodName)}, [${toTypeScriptPomPatternExpression(selector)}]);`);
966
952
  writer.writeLine("await this.clickLocator(locator);");
967
953
  writer.writeLine(`return new ${target}(this.page);`);
968
954
  });
@@ -1007,7 +993,60 @@ function generateViewObjectModelMembers(componentName, targetPageObjectModelClas
1007
993
  if (nativeRole === "radio") {
1008
994
  return [...members, ...generateRadioMethod(componentName, baseMethodName || "Radio", selector, parameters)];
1009
995
  }
1010
- return [...members, ...generateClickMethod(componentName, baseMethodName, selector, alternateSelectors, parameters)];
996
+ return [...members, ...generateClickMethod(componentName, baseMethodName, nativeRole, selector, alternateSelectors, parameters)];
997
+ }
998
+ function supportsInlineTextAccessibleName(role) {
999
+ return role === "button" || role === "radio";
1000
+ }
1001
+ function buildAccessibilityAudit(metadata, inferredRole) {
1002
+ if (!metadata || !inferredRole) {
1003
+ return void 0;
1004
+ }
1005
+ const role = normalizePomRoleLabel(inferredRole).toLowerCase();
1006
+ const dynamicProps = new Set(metadata.dynamicProps ?? []);
1007
+ const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
1008
+ let accessibleNameSource;
1009
+ const reasons = [];
1010
+ if (metadata.staticAriaLabel) {
1011
+ accessibleNameSource = "aria-label";
1012
+ } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
1013
+ accessibleNameSource = "text";
1014
+ } else if (metadata.staticTitle) {
1015
+ accessibleNameSource = "title";
1016
+ } else if (hasDynamicAccessibleNameSignal) {
1017
+ accessibleNameSource = "dynamic";
1018
+ } else if (role === "input" || role === "select") {
1019
+ accessibleNameSource = "unknown";
1020
+ reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
1021
+ } else {
1022
+ accessibleNameSource = "missing";
1023
+ reasons.push("No compile-time accessible-name signal was found.");
1024
+ }
1025
+ return {
1026
+ needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
1027
+ accessibleNameSource,
1028
+ reasons,
1029
+ ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
1030
+ ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
1031
+ ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
1032
+ ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
1033
+ };
1034
+ }
1035
+ function collectAccessibilityReviewWarnings(manifest) {
1036
+ const warnings = [];
1037
+ for (const [componentName, component] of Object.entries(manifest)) {
1038
+ for (const entry of component.entries) {
1039
+ if (!entry.accessibility?.needsReview) {
1040
+ continue;
1041
+ }
1042
+ const entryLabel = entry.generatedPropertyName ?? entry.testId;
1043
+ const reasonText = entry.accessibility.reasons.join(" ");
1044
+ warnings.push(
1045
+ `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
1046
+ );
1047
+ }
1048
+ }
1049
+ return warnings;
1011
1050
  }
1012
1051
  function isSimpleExpressionNode(value) {
1013
1052
  return value !== null && "type" in value && value.type === compilerCore.NodeTypes.SIMPLE_EXPRESSION;
@@ -1353,7 +1392,7 @@ function findTemplateSlotScopeExpression(node) {
1353
1392
  return slotProp?.exp && (slotProp.exp.type === compilerCore.NodeTypes.SIMPLE_EXPRESSION || slotProp.exp.type === compilerCore.NodeTypes.COMPOUND_EXPRESSION) ? slotProp.exp : null;
1354
1393
  }
1355
1394
  function buildSlotScopeFallbackKeyExpression(identifier) {
1356
- return `${identifier}.key ?? ${identifier}.data?.id ?? ${identifier}.id ?? ${identifier}.value ?? ${identifier}`;
1395
+ return `${identifier}.key ?? ${identifier}.data?.id ?? ${identifier}.id ?? ${identifier}.value ?? ${identifier}.url ?? ${identifier}`;
1357
1396
  }
1358
1397
  function tryGetBindingIdentifierName(node) {
1359
1398
  if (!node) {
@@ -3645,6 +3684,157 @@ function buildPomGeneratedPropertyName(pom) {
3645
3684
  function buildPomGeneratedActionName(pom) {
3646
3685
  return requireStructuredPomName(pom.generatedActionName, "generatedActionName", pom);
3647
3686
  }
3687
+ function matchesPrimarySelector(extraMethod, pom) {
3688
+ if (extraMethod.selector.kind !== "testId") {
3689
+ return false;
3690
+ }
3691
+ return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
3692
+ }
3693
+ function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
3694
+ const testId = entry.selectorValue.formatted;
3695
+ const metadata = componentMetadata?.get(testId);
3696
+ const pom = entry.pom;
3697
+ const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
3698
+ const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
3699
+ const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
3700
+ ...generatedActionName ? [generatedActionName] : [],
3701
+ ...extraActionNames.filter((name) => name !== generatedActionName)
3702
+ ]));
3703
+ const generatedMethods = [
3704
+ ...pom && generatedActionName ? [{ name: generatedActionName, kind: "action", parameters: pom.parameters }] : [],
3705
+ ...pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => ({ name: extraMethod.name, kind: "action", parameters: extraMethod.parameters })) : [],
3706
+ ...pom ? [{ name: buildPomGeneratedPropertyName(pom), kind: "locator", parameters: pom.parameters }] : []
3707
+ ].filter((method, index, methods) => methods.findIndex((candidate) => candidate.name === method.name && candidate.kind === method.kind) === index);
3708
+ const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
3709
+ return {
3710
+ testId,
3711
+ selectorPatternKind: entry.selectorValue.patternKind,
3712
+ semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
3713
+ locatorDescription: pom ? buildPomLocatorDescription({
3714
+ componentName,
3715
+ methodName: pom.methodName,
3716
+ nativeRole: pom.nativeRole
3717
+ }) : componentName,
3718
+ inferredRole: pom?.nativeRole ?? null,
3719
+ ...accessibility ? { accessibility } : {},
3720
+ generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
3721
+ generatedActionName,
3722
+ generatedActionNames,
3723
+ generatedMethods,
3724
+ emitPrimary: pom?.emitPrimary !== false,
3725
+ ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
3726
+ ...metadata?.tag ? { sourceTag: metadata.tag } : {},
3727
+ ...metadata ? { sourceTagType: metadata.tagType } : {},
3728
+ ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
3729
+ ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
3730
+ ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
3731
+ ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
3732
+ ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
3733
+ ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
3734
+ ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
3735
+ ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
3736
+ };
3737
+ }
3738
+ function buildPomManifest(componentHierarchyMap, elementMetadata) {
3739
+ const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
3740
+ const entries = Array.from(dependencies.dataTestIdSet).sort((a, b) => a.selectorValue.formatted.localeCompare(b.selectorValue.formatted)).map((entry) => getManifestEntry(componentName, entry, elementMetadata.get(componentName), dependencies.pomExtraMethods ?? []));
3741
+ if (!entries.length) {
3742
+ return null;
3743
+ }
3744
+ return [componentName, {
3745
+ componentName,
3746
+ className: componentName,
3747
+ sourceFile: dependencies.filePath,
3748
+ kind: dependencies.isView ? "view" : "component",
3749
+ testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
3750
+ entries
3751
+ }];
3752
+ }).filter((entry) => entry !== null);
3753
+ return Object.fromEntries(manifestEntries);
3754
+ }
3755
+ function buildTestIdManifest(componentHierarchyMap) {
3756
+ return Object.fromEntries(
3757
+ Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
3758
+ const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
3759
+ if (!testIds.length) {
3760
+ return null;
3761
+ }
3762
+ return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
3763
+ }).filter((entry) => entry !== null)
3764
+ );
3765
+ }
3766
+ function writeConstJson(value) {
3767
+ return (writer) => {
3768
+ writer.write(`${JSON.stringify(value, null, 2)} as const`);
3769
+ };
3770
+ }
3771
+ function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
3772
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
3773
+ const testIdManifest = buildTestIdManifest(componentHierarchyMap);
3774
+ return renderSourceFile("virtual-testids.ts", (sourceFile) => {
3775
+ sourceFile.addStatements("// Virtual module: test id manifest");
3776
+ sourceFile.addVariableStatement({
3777
+ declarationKind: tsMorph.VariableDeclarationKind.Const,
3778
+ isExported: true,
3779
+ declarations: [{
3780
+ name: "testIdManifest",
3781
+ initializer: writeConstJson(testIdManifest)
3782
+ }]
3783
+ });
3784
+ sourceFile.addVariableStatement({
3785
+ declarationKind: tsMorph.VariableDeclarationKind.Const,
3786
+ isExported: true,
3787
+ declarations: [{
3788
+ name: "pomManifest",
3789
+ initializer: writeConstJson(pomManifest)
3790
+ }]
3791
+ });
3792
+ sourceFile.addTypeAlias({
3793
+ isExported: true,
3794
+ name: "TestIdManifest",
3795
+ type: "typeof testIdManifest"
3796
+ });
3797
+ sourceFile.addTypeAlias({
3798
+ isExported: true,
3799
+ name: "ComponentName",
3800
+ type: "keyof TestIdManifest"
3801
+ });
3802
+ sourceFile.addTypeAlias({
3803
+ isExported: true,
3804
+ name: "PomManifest",
3805
+ type: "typeof pomManifest"
3806
+ });
3807
+ sourceFile.addTypeAlias({
3808
+ isExported: true,
3809
+ name: "PomManifestComponentName",
3810
+ type: "keyof PomManifest"
3811
+ });
3812
+ });
3813
+ }
3814
+ function generatePomManifestModule(componentHierarchyMap, elementMetadata, fileName = "virtual-pom-manifest.ts") {
3815
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
3816
+ return renderSourceFile(fileName, (sourceFile) => {
3817
+ sourceFile.addStatements("// Rich POM discoverability manifest.");
3818
+ sourceFile.addVariableStatement({
3819
+ declarationKind: tsMorph.VariableDeclarationKind.Const,
3820
+ isExported: true,
3821
+ declarations: [{
3822
+ name: "pomManifest",
3823
+ initializer: writeConstJson(pomManifest)
3824
+ }]
3825
+ });
3826
+ sourceFile.addTypeAlias({
3827
+ isExported: true,
3828
+ name: "PomManifest",
3829
+ type: "typeof pomManifest"
3830
+ });
3831
+ sourceFile.addTypeAlias({
3832
+ isExported: true,
3833
+ name: "PomManifestComponentName",
3834
+ type: "keyof PomManifest"
3835
+ });
3836
+ });
3837
+ }
3648
3838
  function safeRealpath(value) {
3649
3839
  try {
3650
3840
  if (fs.existsSync(value)) {
@@ -4670,6 +4860,282 @@ async function parseRouterFileFromCwd(routerEntryPath, options = {}) {
4670
4860
  }
4671
4861
  });
4672
4862
  }
4863
+ function writeNavigationValue(writer, input, name) {
4864
+ writer.write(input.identifier);
4865
+ if (input.optional) {
4866
+ writer.write("?.");
4867
+ }
4868
+ writer.write(`[${JSON.stringify(name)}]`);
4869
+ }
4870
+ function writeFilteredNavigationRecord(writer, variableName, input, names) {
4871
+ writer.write(`const ${variableName} = `);
4872
+ if (!input || names.length === 0) {
4873
+ writer.write("{};").newLine();
4874
+ return;
4875
+ }
4876
+ writer.write("Object.fromEntries([");
4877
+ names.forEach((name, index) => {
4878
+ if (index > 0) {
4879
+ writer.write(", ");
4880
+ }
4881
+ writer.write(`[${JSON.stringify(name)}, `);
4882
+ writeNavigationValue(writer, input, name);
4883
+ writer.write("]");
4884
+ });
4885
+ writer.write("].filter(([, value]) => value !== undefined));").newLine();
4886
+ }
4887
+ function writeUnpartitionedRouteParams(writer, input) {
4888
+ writer.write("const routeParams = ");
4889
+ if (!input) {
4890
+ writer.write("{};").newLine();
4891
+ return;
4892
+ }
4893
+ writer.write("Object.fromEntries(Object.entries(");
4894
+ writer.write(input.identifier);
4895
+ if (input.optional) {
4896
+ writer.write(" ?? {}");
4897
+ }
4898
+ writer.write(").filter(([, v]) => v !== undefined));").newLine();
4899
+ }
4900
+ function writeRouterTargetType(writer, includeQuery) {
4901
+ writer.write("{ name: string; params: Record<string, unknown>");
4902
+ if (includeQuery) {
4903
+ writer.write("; query: Record<string, unknown>");
4904
+ }
4905
+ writer.write(" }");
4906
+ }
4907
+ function writeRouterType(writer, includeQuery) {
4908
+ writer.write(`{ ${router.POM_ROUTER_GLOBAL_NAME}?: { beginNavigation: (to: `);
4909
+ writeRouterTargetType(writer, includeQuery);
4910
+ writer.write(') => number; navigation?: { id: number; status: "pending" | "succeeded" | "failed"; stage: "waiting-for-router-ready" | "pushing-route" | "complete"; targetName: string; error?: string } } }');
4911
+ }
4912
+ function writeRouterBinding(writer, includeQuery) {
4913
+ writer.write("{ name, params");
4914
+ if (includeQuery) {
4915
+ writer.write(", query");
4916
+ }
4917
+ writer.write(" }");
4918
+ }
4919
+ function writeRouterTarget(writer, writeName, includeQuery, paramsExpression, queryExpression) {
4920
+ writer.write("{ name: ");
4921
+ writeName(writer);
4922
+ writer.write(`, params: ${paramsExpression}`);
4923
+ if (includeQuery) {
4924
+ writer.write(`, query: ${queryExpression}`);
4925
+ }
4926
+ writer.write(" }");
4927
+ }
4928
+ function writeRouterNavigation(writer, writeName, includeQuery) {
4929
+ writer.write("const navigationId = await this.page.evaluate((");
4930
+ writeRouterBinding(writer, includeQuery);
4931
+ writer.write(") => {").newLine();
4932
+ writer.indent(() => {
4933
+ writer.write("const router = (globalThis as ");
4934
+ writeRouterType(writer, includeQuery);
4935
+ writer.write(`).${router.POM_ROUTER_GLOBAL_NAME};`).newLine();
4936
+ writer.writeLine("if (!router) {");
4937
+ writer.indent(() => {
4938
+ writer.writeLine('throw new Error("[vue-pom-generator] Vue Router bridge is unavailable.");');
4939
+ });
4940
+ writer.writeLine("}");
4941
+ writer.write("return router.beginNavigation(");
4942
+ writeRouterBinding(writer, includeQuery);
4943
+ writer.write(");").newLine();
4944
+ });
4945
+ writer.write("}, ");
4946
+ writeRouterTarget(writer, writeName, includeQuery, "routeParams", "routeQuery");
4947
+ writer.write(");").newLine();
4948
+ writer.writeLine("try {");
4949
+ writer.indent(() => {
4950
+ writer.write("await this.page.waitForFunction((id) => {").newLine();
4951
+ writer.indent(() => {
4952
+ writer.write("const navigation = (globalThis as ");
4953
+ writeRouterType(writer, includeQuery);
4954
+ writer.write(`).${router.POM_ROUTER_GLOBAL_NAME}?.navigation;`).newLine();
4955
+ writer.writeLine('return navigation?.id === id && navigation.status !== "pending";');
4956
+ });
4957
+ writer.writeLine("}, navigationId, { timeout: 5000 });");
4958
+ });
4959
+ writer.writeLine("}");
4960
+ writer.writeLine("catch (error) {");
4961
+ writer.indent(() => {
4962
+ writer.write("const navigation = await this.page.evaluate((id) => {").newLine();
4963
+ writer.indent(() => {
4964
+ writer.write("const current = (globalThis as ");
4965
+ writeRouterType(writer, includeQuery);
4966
+ writer.write(`).${router.POM_ROUTER_GLOBAL_NAME}?.navigation;`).newLine();
4967
+ writer.writeLine("return current?.id === id ? current : undefined;");
4968
+ });
4969
+ writer.writeLine("}, navigationId).catch(() => undefined);");
4970
+ writer.writeLine("const detail = error instanceof Error ? error.message : String(error);");
4971
+ writer.writeLine('throw new Error(`[vue-pom-generator] Vue Router navigation timed out after 5000ms (stage: ${navigation?.stage ?? "unknown"}, target: ${navigation?.targetName ?? "unknown"}, current URL: ${this.page.url()}). ${detail}`);');
4972
+ });
4973
+ writer.writeLine("}");
4974
+ writer.write("const navigationError = await this.page.evaluate((id) => {").newLine();
4975
+ writer.indent(() => {
4976
+ writer.write("const navigation = (globalThis as ");
4977
+ writeRouterType(writer, includeQuery);
4978
+ writer.write(`).${router.POM_ROUTER_GLOBAL_NAME}?.navigation;`).newLine();
4979
+ writer.writeLine('return navigation?.id === id && navigation.status === "failed" ? navigation.error ?? "Unknown navigation error" : undefined;');
4980
+ });
4981
+ writer.writeLine("}, navigationId);");
4982
+ writer.writeLine("if (navigationError) {");
4983
+ writer.indent(() => {
4984
+ writer.writeLine("throw new Error(`[vue-pom-generator] Vue Router navigation failed: ${navigationError}`);");
4985
+ });
4986
+ writer.writeLine("}");
4987
+ }
4988
+ function requireNavigationInput(input, context) {
4989
+ if (!input) {
4990
+ throw new Error(`${context} requires a navigation input.`);
4991
+ }
4992
+ return input;
4993
+ }
4994
+ function writeParametrizedRouteSelector(writer, input, pathParamNames) {
4995
+ writer.write(`const useParametrizedRoute = ${input.identifier} !== undefined && [`);
4996
+ pathParamNames.forEach((name, index) => {
4997
+ if (index > 0) {
4998
+ writer.write(", ");
4999
+ }
5000
+ writer.write(JSON.stringify(name));
5001
+ });
5002
+ writer.write(`].some(key => Object.prototype.hasOwnProperty.call(${input.identifier}, key));`).newLine();
5003
+ }
5004
+ function writeSelectionPrelude(writer, selection, input, pathParamNames) {
5005
+ if (selection.kind === "dual" && selection.selectBy === "path-param-presence") {
5006
+ writeParametrizedRouteSelector(
5007
+ writer,
5008
+ requireNavigationInput(input, "Path-param route selection"),
5009
+ pathParamNames
5010
+ );
5011
+ }
5012
+ }
5013
+ function writeSelectedTarget(writer, selection, input) {
5014
+ if (selection.kind === "single") {
5015
+ writer.write(JSON.stringify(selection.target));
5016
+ return;
5017
+ }
5018
+ if (selection.selectBy === "path-param-presence") {
5019
+ writer.write("useParametrizedRoute");
5020
+ } else {
5021
+ writer.write(requireNavigationInput(input, "Input-presence route selection").identifier);
5022
+ }
5023
+ writer.write(` ? ${JSON.stringify(selection.parametrizedTarget)} : ${JSON.stringify(selection.paramlessTarget)}`);
5024
+ }
5025
+ function createRouterNavigationWriter(options) {
5026
+ return (writer) => {
5027
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(options.componentName)}, "goTo", []);`);
5028
+ writeSelectionPrelude(writer, options.routeName, options.input, options.pathParamNames);
5029
+ const writeRouteName = (nameWriter) => writeSelectedTarget(nameWriter, options.routeName, options.input);
5030
+ const includeQuery = options.queryNames.length > 0;
5031
+ if (includeQuery) {
5032
+ writeFilteredNavigationRecord(writer, "routeParams", options.input, options.pathParamNames);
5033
+ writeFilteredNavigationRecord(writer, "routeQuery", options.input, options.queryNames);
5034
+ } else {
5035
+ writeUnpartitionedRouteParams(writer, options.input);
5036
+ }
5037
+ writer.writeLine(
5038
+ `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${router.POM_ROUTER_GLOBAL_NAME}?: unknown }).${router.POM_ROUTER_GLOBAL_NAME} === "undefined");`
5039
+ );
5040
+ writer.writeLine("if (isCold) {");
5041
+ writer.indent(() => {
5042
+ writer.writeLine('await this.page.goto("/", { waitUntil: "commit" });');
5043
+ writer.writeLine(
5044
+ `await this.page.waitForFunction(() => typeof (globalThis as { ${router.POM_ROUTER_GLOBAL_NAME}?: unknown }).${router.POM_ROUTER_GLOBAL_NAME} !== "undefined", undefined, { timeout: 5000 });`
5045
+ );
5046
+ });
5047
+ writer.writeLine("}");
5048
+ writeRouterNavigation(writer, writeRouteName, includeQuery);
5049
+ };
5050
+ }
5051
+ function writePathParamAssignments(writer, input, pathParams) {
5052
+ for (const param of pathParams) {
5053
+ const token = getParamToken(param.name);
5054
+ if (param.optional) {
5055
+ writer.write("targetUrl = ");
5056
+ writeNavigationValue(writer, input, param.name);
5057
+ writer.write(` === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
5058
+ writeNavigationValue(writer, input, param.name);
5059
+ writer.write("));").newLine();
5060
+ } else {
5061
+ writer.write(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
5062
+ writeNavigationValue(writer, input, param.name);
5063
+ writer.write("));").newLine();
5064
+ }
5065
+ }
5066
+ }
5067
+ function writeQueryString(writer, input, queryNames) {
5068
+ if (queryNames.length === 0) {
5069
+ return;
5070
+ }
5071
+ writer.writeLine("const routeQuery = new URLSearchParams();");
5072
+ for (const queryName of queryNames) {
5073
+ writer.write("if (");
5074
+ writeNavigationValue(writer, input, queryName);
5075
+ writer.write(" !== undefined) {").newLine();
5076
+ writer.indent(() => {
5077
+ writer.write(`routeQuery.set(${JSON.stringify(queryName)}, String(`);
5078
+ writeNavigationValue(writer, input, queryName);
5079
+ writer.write("));").newLine();
5080
+ });
5081
+ writer.writeLine("}");
5082
+ }
5083
+ writer.writeLine("const routeQueryString = routeQuery.toString();");
5084
+ writer.writeLine("if (routeQueryString) {");
5085
+ writer.indent(() => {
5086
+ writer.writeLine("targetUrl += `?${routeQueryString}`;");
5087
+ });
5088
+ writer.writeLine("}");
5089
+ }
5090
+ function writeRuntimeUrlNavigation(writer) {
5091
+ writer.writeLine(
5092
+ "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;"
5093
+ );
5094
+ writer.writeLine(
5095
+ "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;"
5096
+ );
5097
+ writer.writeLine("const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;");
5098
+ writer.writeLine("await this.page.goto(resolvedUrl);");
5099
+ }
5100
+ function createUrlNavigationWriter(options) {
5101
+ return (writer) => {
5102
+ writer.writeLine(`this.recordPomAction(${JSON.stringify(options.componentName)}, "goTo", []);`);
5103
+ writeSelectionPrelude(writer, options.routeTemplate, options.input, options.pathParams.map((param) => param.name));
5104
+ if (options.routeTemplate.kind === "single") {
5105
+ writer.write(`let targetUrl = ${JSON.stringify(options.routeTemplate.target)};`).newLine();
5106
+ } else {
5107
+ writer.write("const template = ");
5108
+ writeSelectedTarget(writer, options.routeTemplate, options.input);
5109
+ writer.write(";").newLine();
5110
+ writer.writeLine("let targetUrl = template;");
5111
+ }
5112
+ if (options.pathParams.length > 0) {
5113
+ const input = requireNavigationInput(options.input, "URL navigation with path params");
5114
+ if (options.routeTemplate.kind === "dual") {
5115
+ writer.write("if (");
5116
+ writer.write(input.identifier);
5117
+ if (options.routeTemplate.selectBy === "path-param-presence") {
5118
+ writer.write(" && useParametrizedRoute");
5119
+ }
5120
+ writer.write(") {").newLine();
5121
+ writer.indent(() => {
5122
+ writePathParamAssignments(writer, input, options.pathParams);
5123
+ });
5124
+ writer.writeLine("}");
5125
+ } else {
5126
+ writePathParamAssignments(writer, input, options.pathParams);
5127
+ }
5128
+ }
5129
+ if (options.queryNames.length > 0) {
5130
+ writeQueryString(
5131
+ writer,
5132
+ requireNavigationInput(options.input, "URL navigation with query params"),
5133
+ options.queryNames
5134
+ );
5135
+ }
5136
+ writeRuntimeUrlNavigation(writer);
5137
+ };
5138
+ }
4673
5139
  const GENERATED_GITATTRIBUTES_BLOCK_START = "# BEGIN vue-pom-generator generated files";
4674
5140
  const GENERATED_GITATTRIBUTES_BLOCK_END = "# END vue-pom-generator generated files";
4675
5141
  const VUE_POM_GENERATOR_ERROR_PREFIX = "[vue-pom-generator]";
@@ -4800,7 +5266,7 @@ async function getRouteMetaByComponent(projectRoot, routerEntry, routerType, opt
4800
5266
  const map = /* @__PURE__ */ new Map();
4801
5267
  for (const entry of routeMetaEntries) {
4802
5268
  const list = map.get(entry.componentName) ?? [];
4803
- list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params });
5269
+ list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params, query: entry.query });
4804
5270
  map.set(entry.componentName, list);
4805
5271
  }
4806
5272
  const dedupeRoutes = (entries) => {
@@ -4839,8 +5305,37 @@ function generateRouteProperty(routeMeta) {
4839
5305
  })
4840
5306
  ];
4841
5307
  }
4842
- function buildParamTypeString(params) {
4843
- return `{ ${params.map((p) => `${p.name}${p.optional ? "?" : ""}: string | number`).join("; ")} }`;
5308
+ function formatNavigationFieldName(name) {
5309
+ return /^[$a-z_][$\w]*$/i.test(name) ? name : JSON.stringify(name);
5310
+ }
5311
+ function buildNavigationTypeString(route, requiredOptionalParamName) {
5312
+ const pathFields = route.params.map((param) => {
5313
+ const forcePresent = param.optional && param.name === requiredOptionalParamName;
5314
+ return `${formatNavigationFieldName(param.name)}${param.optional && !forcePresent ? "?" : ""}: string | number${forcePresent ? " | undefined" : ""}`;
5315
+ });
5316
+ const pathNames = new Set(route.params.map((param) => param.name));
5317
+ const queryFields = route.query.filter((query) => !pathNames.has(query)).map((query) => `${formatNavigationFieldName(query)}?: string | number`);
5318
+ return `{ ${[...pathFields, ...queryFields].join("; ")} }`;
5319
+ }
5320
+ function buildParametrizedRouteSelectionTypeString(route) {
5321
+ if (route.params.some((param) => !param.optional)) {
5322
+ return buildNavigationTypeString(route);
5323
+ }
5324
+ return route.params.map((param) => buildNavigationTypeString(route, param.name)).join(" | ");
5325
+ }
5326
+ function buildImplementationNavigationTypeString(routes) {
5327
+ const fields = /* @__PURE__ */ new Map();
5328
+ for (const route of routes) {
5329
+ for (const param of route.params) {
5330
+ fields.set(param.name, true);
5331
+ }
5332
+ for (const query of route.query) {
5333
+ if (!fields.has(query)) {
5334
+ fields.set(query, true);
5335
+ }
5336
+ }
5337
+ }
5338
+ return `{ ${Array.from(fields.keys()).map((name) => `${formatNavigationFieldName(name)}?: string | number`).join("; ")} }`;
4844
5339
  }
4845
5340
  function chooseParamlessRoute(routes) {
4846
5341
  const paramless = routes.filter((r) => r.params.length === 0);
@@ -4854,31 +5349,12 @@ function chooseParametrizedRoute(routes) {
4854
5349
  return null;
4855
5350
  return parametrized.slice().sort((a, b) => a.params.length - b.params.length || a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
4856
5351
  }
4857
- const GOTO_RUNTIME_LINES = [
4858
- "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;",
4859
- "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;",
4860
- "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
4861
- "await this.page.goto(resolvedUrl);"
4862
- ];
4863
- const ROUTER_GLOBAL_NAME = router.POM_ROUTER_GLOBAL_NAME;
4864
- const pushBlock = (routeNameExpr, paramsExpr, nullable) => {
4865
- const routerType = `{ ${ROUTER_GLOBAL_NAME}?: { push: (to: { name: string; params: Record<string, unknown> }) => Promise<unknown>; resolve: (to: { name: string; params: Record<string, unknown> }) => { href: string } } }`;
4866
- const routeParamsLine = paramsExpr === "undefined" ? "const routeParams = {};" : nullable ? `const routeParams = Object.fromEntries(Object.entries(${paramsExpr} ?? {}).filter(([, v]) => v !== undefined));` : `const routeParams = Object.fromEntries(Object.entries(${paramsExpr}).filter(([, v]) => v !== undefined));`;
4867
- return [
4868
- routeParamsLine,
4869
- `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} === "undefined");`,
4870
- `if (isCold) {`,
4871
- ` await this.page.goto("/", { waitUntil: "commit" });`,
4872
- ` await this.page.waitForFunction(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`,
4873
- ` const href = await this.page.evaluate(({ name, params }) => (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.resolve({ name, params })?.href, { name: ${routeNameExpr}, params: routeParams });`,
4874
- ` if (href) { await this.page.goto(href, { waitUntil: "domcontentloaded" }); }`,
4875
- `} else {`,
4876
- ` await this.page.evaluate(async ({ name, params }) => {`,
4877
- ` await (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.push({ name, params });`,
4878
- ` }, { name: ${routeNameExpr}, params: routeParams });`,
4879
- `}`
4880
- ];
4881
- };
5352
+ function requireRouteName(route) {
5353
+ if (route.name === null) {
5354
+ throw new VuePomGeneratorError(`Named navigation requires a route name for template "${route.template}".`);
5355
+ }
5356
+ return route.name;
5357
+ }
4882
5358
  function generateGoToMethod(componentName, routeMeta) {
4883
5359
  if (!routeMeta) {
4884
5360
  return [
@@ -4903,32 +5379,35 @@ function generateGoToMethod(componentName, routeMeta) {
4903
5379
  statements: [
4904
5380
  `throw new Error("[pom] No router path found for component/page-object '${componentName}'.");`
4905
5381
  ]
4906
- })
4907
- ];
4908
- }
4909
- const paramStatements = (entry) => {
4910
- const lines = [];
4911
- for (const param of entry.params) {
4912
- const token = getParamToken(param.name);
4913
- if (param.optional) {
4914
- lines.push(`targetUrl = params.${param.name} === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4915
- } else {
4916
- lines.push(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4917
- }
4918
- }
4919
- return lines;
4920
- };
5382
+ })
5383
+ ];
5384
+ }
4921
5385
  if (hasParamless && !hasParametrized) {
4922
5386
  const route = paramless;
5387
+ const hasQuery2 = route.query.length > 0;
5388
+ const paramType2 = buildNavigationTypeString(route);
4923
5389
  return [
4924
5390
  createClassMethod({
4925
5391
  name: "goTo",
4926
5392
  isAsync: true,
4927
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "undefined", false) : [`const targetUrl = ${JSON.stringify(route.template)};`, ...GOTO_RUNTIME_LINES]
5393
+ parameters: hasQuery2 ? [{ name: "params", type: paramType2, hasQuestionToken: true }] : [],
5394
+ statements: route.name !== null ? createRouterNavigationWriter({
5395
+ componentName,
5396
+ routeName: { kind: "single", target: route.name },
5397
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5398
+ pathParamNames: [],
5399
+ queryNames: route.query
5400
+ }) : createUrlNavigationWriter({
5401
+ componentName,
5402
+ routeTemplate: { kind: "single", target: route.template },
5403
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5404
+ pathParams: [],
5405
+ queryNames: route.query
5406
+ })
4928
5407
  })
4929
5408
  ];
4930
5409
  }
4931
- const paramType = buildParamTypeString(parametrized.params);
5410
+ const paramType = buildNavigationTypeString(parametrized);
4932
5411
  if (hasParametrized && !hasParamless) {
4933
5412
  const route = parametrized;
4934
5413
  const allOptional = route.params.every((p) => p.optional);
@@ -4937,34 +5416,65 @@ function generateGoToMethod(componentName, routeMeta) {
4937
5416
  name: "goTo",
4938
5417
  isAsync: true,
4939
5418
  parameters: [{ name: "params", type: paramType, hasQuestionToken: allOptional }],
4940
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "params", allOptional) : [`let targetUrl = ${JSON.stringify(route.template)};`, ...paramStatements(route), ...GOTO_RUNTIME_LINES]
5419
+ statements: route.name !== null ? createRouterNavigationWriter({
5420
+ componentName,
5421
+ routeName: { kind: "single", target: route.name },
5422
+ input: { identifier: "params", optional: allOptional },
5423
+ pathParamNames: route.params.map((param) => param.name),
5424
+ queryNames: route.query
5425
+ }) : createUrlNavigationWriter({
5426
+ componentName,
5427
+ routeTemplate: { kind: "single", target: route.template },
5428
+ input: { identifier: "params", optional: allOptional },
5429
+ pathParams: route.params,
5430
+ queryNames: route.query
5431
+ })
4941
5432
  })
4942
5433
  ];
4943
5434
  }
4944
5435
  const paramlessRoute = paramless;
4945
5436
  const parametrizedRoute = parametrized;
4946
5437
  const usePush = paramlessRoute.name !== null && parametrizedRoute.name !== null;
5438
+ const paramlessType = buildNavigationTypeString(paramlessRoute);
5439
+ const parametrizedOverloadType = buildParametrizedRouteSelectionTypeString(parametrizedRoute);
5440
+ const queryNames = Array.from(/* @__PURE__ */ new Set([...paramlessRoute.query, ...parametrizedRoute.query]));
5441
+ const hasQuery = queryNames.length > 0;
5442
+ const implementationType = hasQuery ? buildImplementationNavigationTypeString([paramlessRoute, parametrizedRoute]) : paramType;
4947
5443
  return [
4948
5444
  createClassMethod({
4949
5445
  name: "goTo",
4950
5446
  isAsync: true,
4951
5447
  overloads: [
4952
- { parameters: [], returnType: "Promise<void>" },
4953
- { parameters: [{ name: "params", type: paramType }], returnType: "Promise<void>" }
5448
+ {
5449
+ parameters: paramlessRoute.query.length ? [{ name: "params", type: paramlessType, hasQuestionToken: true }] : [],
5450
+ returnType: "Promise<void>"
5451
+ },
5452
+ { parameters: [{ name: "params", type: parametrizedOverloadType }], returnType: "Promise<void>" }
4954
5453
  ],
4955
- parameters: [{ name: "params", type: paramType, hasQuestionToken: true }],
4956
- statements: usePush ? pushBlock(
4957
- `params ? ${JSON.stringify(parametrizedRoute.name)} : ${JSON.stringify(paramlessRoute.name)}`,
4958
- "params",
4959
- true
4960
- ) : [
4961
- `const template = params ? ${JSON.stringify(parametrizedRoute.template)} : ${JSON.stringify(paramlessRoute.template)};`,
4962
- "let targetUrl = template;",
4963
- `if (params) {`,
4964
- ...paramStatements(parametrizedRoute).map((line) => ` ${line}`),
4965
- "}",
4966
- ...GOTO_RUNTIME_LINES
4967
- ]
5454
+ parameters: [{ name: "params", type: implementationType, hasQuestionToken: true }],
5455
+ statements: usePush ? createRouterNavigationWriter({
5456
+ componentName,
5457
+ routeName: {
5458
+ kind: "dual",
5459
+ parametrizedTarget: requireRouteName(parametrizedRoute),
5460
+ paramlessTarget: requireRouteName(paramlessRoute),
5461
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5462
+ },
5463
+ input: { identifier: "params", optional: true },
5464
+ pathParamNames: parametrizedRoute.params.map((param) => param.name),
5465
+ queryNames: hasQuery ? queryNames : []
5466
+ }) : createUrlNavigationWriter({
5467
+ componentName,
5468
+ routeTemplate: {
5469
+ kind: "dual",
5470
+ parametrizedTarget: parametrizedRoute.template,
5471
+ paramlessTarget: paramlessRoute.template,
5472
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5473
+ },
5474
+ input: { identifier: "params", optional: true },
5475
+ pathParams: parametrizedRoute.params,
5476
+ queryNames: hasQuery ? queryNames : []
5477
+ })
4968
5478
  })
4969
5479
  ];
4970
5480
  }
@@ -5005,7 +5515,7 @@ function generateExtraClickMethodMembers(spec, componentName) {
5005
5515
  for (const statement of testIdBinding.setupStatements) {
5006
5516
  writer.writeLine(statement);
5007
5517
  }
5008
- writer.writeLine(`await this.clickByTestId(${testIdBinding.expression}, ${annotationArg}, ${waitArg}, ${locatorDescription});`);
5518
+ writer.writeLine(`await this.clickByTestId(${testIdBinding.expression}, ${annotationArg}, ${waitArg}, ${locatorDescription}, { componentName: ${JSON.stringify(componentName)}, methodName: ${JSON.stringify(spec.name)} });`);
5009
5519
  }
5010
5520
  })
5011
5521
  ];
@@ -5027,7 +5537,7 @@ function generateExtraClickMethodMembers(spec, componentName) {
5027
5537
  for (const statement of labelBinding.setupStatements) {
5028
5538
  writer.writeLine(statement);
5029
5539
  }
5030
- writer.writeLine(`await this.clickWithinTestIdByLabel(${rootBinding.expression}, ${labelBinding.expression}, ${annotationArg}, ${waitArg}, { description: ${locatorDescription} });`);
5540
+ writer.writeLine(`await this.clickWithinTestIdByLabel(${rootBinding.expression}, ${labelBinding.expression}, ${annotationArg}, ${waitArg}, { description: ${locatorDescription}, componentName: ${JSON.stringify(componentName)}, methodName: ${JSON.stringify(spec.name)} });`);
5031
5541
  }
5032
5542
  })
5033
5543
  ];
@@ -5099,7 +5609,8 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5099
5609
  pageDirs,
5100
5610
  componentDirs,
5101
5611
  layoutDirs,
5102
- routeMetaByComponent: routeMetaByComponentOverride
5612
+ routeMetaByComponent: routeMetaByComponentOverride,
5613
+ elementMetadata = /* @__PURE__ */ new Map()
5103
5614
  } = options;
5104
5615
  const emitLanguages = emitLanguagesOverride?.length ? emitLanguagesOverride : ["ts"];
5105
5616
  const outDir = outDirOverride ?? "./pom";
@@ -5140,13 +5651,15 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5140
5651
  for (const file of files) {
5141
5652
  writeGeneratedFile(file);
5142
5653
  }
5143
- const fixtureRegistryFile = maybeGenerateFixtureRegistry(emittableComponentHierarchyMap, {
5654
+ const fixtureRegistryFiles = maybeGenerateFixtureRegistry(emittableComponentHierarchyMap, {
5144
5655
  generateFixtures,
5145
5656
  pomOutDir: outDir,
5146
5657
  projectRoot,
5147
- customPomDir
5658
+ customPomDir,
5659
+ elementMetadata,
5660
+ testIdAttribute
5148
5661
  });
5149
- if (fixtureRegistryFile) {
5662
+ for (const fixtureRegistryFile of fixtureRegistryFiles) {
5150
5663
  writeGeneratedFile(fixtureRegistryFile);
5151
5664
  }
5152
5665
  }
@@ -5628,7 +6141,7 @@ function generateAggregatedCSharpFiles(componentHierarchyMap, outDir, options =
5628
6141
  function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5629
6142
  const { generateFixtures, pomOutDir } = options;
5630
6143
  if (!generateFixtures)
5631
- return null;
6144
+ return [];
5632
6145
  const defaultFixtureOutDirRel = pomOutDir;
5633
6146
  const fixtureOutRel = typeof generateFixtures === "string" ? generateFixtures : typeof generateFixtures === "object" && generateFixtures?.outDir ? generateFixtures.outDir : defaultFixtureOutDirRel;
5634
6147
  const looksLikeFilePath = fixtureOutRel.endsWith(".ts") || fixtureOutRel.endsWith(".tsx") || fixtureOutRel.endsWith(".mts") || fixtureOutRel.endsWith(".cts");
@@ -5641,6 +6154,10 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5641
6154
  const overridePomDirAbs = path.resolve(path.dirname(customPomDirAbs), "overrides");
5642
6155
  const pomDirAbs = path.isAbsolute(pomOutDir) ? pomOutDir : path.resolve(root, pomOutDir);
5643
6156
  const pomImport = toPosixRelativePath(fixtureOutDirAbs, pomDirAbs);
6157
+ const diagnosticsImport = stripExtension(toPosixRelativePath(
6158
+ fixtureOutDirAbs,
6159
+ path.join(pomDirAbs, "_pom-runtime", "class-generation", "diagnostics.ts")
6160
+ ));
5644
6161
  const viewClassNames = Array.from(componentHierarchyMap.entries()).filter(([, deps]) => !!deps.isView).map(([name]) => name).sort((a, b) => a.localeCompare(b));
5645
6162
  const reservedPlaywrightFixtureNames = /* @__PURE__ */ new Set([
5646
6163
  // Built-in Playwright fixtures
@@ -5650,7 +6167,8 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5650
6167
  "browserName",
5651
6168
  "request",
5652
6169
  // Our own fixtureOptions
5653
- "animation"
6170
+ "animation",
6171
+ "pomDiagnostics"
5654
6172
  ]);
5655
6173
  const viewFixtureNames = new Set(viewClassNames.map((name) => lowerFirst(name)));
5656
6174
  const componentClassNames = Array.from(componentHierarchyMap.entries()).filter(([, deps]) => !deps.isView).map(([name]) => name).filter((name) => {
@@ -5694,13 +6212,27 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5694
6212
  namedImports: [
5695
6213
  { name: "Page", alias: "PwPage" },
5696
6214
  "PlaywrightTestArgs",
6215
+ "TestInfo",
5697
6216
  "TestType"
5698
6217
  ]
5699
6218
  });
6219
+ addNamedImport(sourceFile, {
6220
+ moduleSpecifier: diagnosticsImport,
6221
+ namedImports: ["installPomFailureDiagnostics"]
6222
+ });
6223
+ addNamedImport(sourceFile, {
6224
+ moduleSpecifier: diagnosticsImport,
6225
+ isTypeOnly: true,
6226
+ namedImports: ["PomFailureDiagnosticsOptions"]
6227
+ });
5700
6228
  sourceFile.addImportDeclaration({
5701
6229
  namespaceImport: "Pom",
5702
6230
  moduleSpecifier: pomImport
5703
6231
  });
6232
+ addNamedImport(sourceFile, {
6233
+ moduleSpecifier: "./pom-manifest.g",
6234
+ namedImports: ["pomManifest"]
6235
+ });
5704
6236
  for (const entry of overrideCtorEntries) {
5705
6237
  addNamedImport(sourceFile, {
5706
6238
  moduleSpecifier: entry.importSpecifier,
@@ -5713,6 +6245,9 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5713
6245
  properties: [{
5714
6246
  name: "animation",
5715
6247
  type: "Pom.PlaywrightAnimationOptions"
6248
+ }, {
6249
+ name: "pomDiagnostics",
6250
+ type: "PomFailureDiagnosticsOptions"
5716
6251
  }]
5717
6252
  });
5718
6253
  sourceFile.addTypeAlias({
@@ -5739,6 +6274,10 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5739
6274
  name: "PomFactoryFixture",
5740
6275
  type: "{ pomFactory: PomFactory }"
5741
6276
  });
6277
+ sourceFile.addTypeAlias({
6278
+ name: "PomDiagnosticsSetupFixture",
6279
+ type: "{ pomDiagnosticsSetup: void }"
6280
+ });
5742
6281
  sourceFile.addVariableStatement({
5743
6282
  declarationKind: tsMorph.VariableDeclarationKind.Const,
5744
6283
  declarations: [{
@@ -5785,7 +6324,7 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5785
6324
  docs: [{
5786
6325
  description: "Every fixture contributed by the generator: the `animation` option, the internal\n`pomSetup`/`pomFactory` fixtures, and one fixture per generated page/component POM."
5787
6326
  }],
5788
- type: "PlaywrightOptions & PomSetupFixture & PomFactoryFixture & GeneratedPageFixtures & GeneratedComponentFixtures"
6327
+ type: "PlaywrightOptions & PomSetupFixture & PomFactoryFixture & PomDiagnosticsSetupFixture & GeneratedPageFixtures & GeneratedComponentFixtures"
5789
6328
  });
5790
6329
  sourceFile.addFunction({
5791
6330
  name: "makePomFixture",
@@ -5837,16 +6376,32 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5837
6376
  writer.block(() => {
5838
6377
  writer.writeLine("animation: [{");
5839
6378
  writer.indent(() => {
6379
+ writer.writeLine("enabled: false,");
5840
6380
  writer.writeLine('pointer: { durationMilliseconds: 250, transitionStyle: "ease-in-out", clickDelayMilliseconds: 0 },');
5841
6381
  writer.writeLine("keyboard: { typeDelayMilliseconds: 100 },");
5842
6382
  });
5843
6383
  writer.writeLine("}, { option: true }],");
6384
+ writer.writeLine(`pomDiagnostics: [{ captureBudgetMs: 5_000, testIdAttribute: ${JSON.stringify(options.testIdAttribute ?? "data-testid")} }, { option: true }],`);
5844
6385
  writer.writeLine("pomSetup: [async ({ animation }: PomFixtures, use: (r: void) => Promise<void>) => {");
5845
6386
  writer.indent(() => {
5846
6387
  writer.writeLine("Pom.setPlaywrightAnimationOptions(animation);");
5847
6388
  writer.writeLine("await use();");
5848
6389
  });
5849
6390
  writer.writeLine("}, { auto: true }],");
6391
+ writer.writeLine("pomDiagnosticsSetup: [async ({ page, pomDiagnostics }: { page: PwPage; pomDiagnostics: PomFailureDiagnosticsOptions }, use: (r: void) => Promise<void>, testInfo: TestInfo) => {");
6392
+ writer.indent(() => {
6393
+ writer.writeLine("const capture = installPomFailureDiagnostics(page, pomManifest, testInfo, pomDiagnostics);");
6394
+ writer.writeLine("try {");
6395
+ writer.indent(() => writer.writeLine("await use();"));
6396
+ writer.writeLine("} finally {");
6397
+ writer.indent(() => {
6398
+ writer.writeLine("if (testInfo.status !== undefined && testInfo.status !== testInfo.expectedStatus) {");
6399
+ writer.indent(() => writer.writeLine("await capture.capture().catch(() => undefined);"));
6400
+ writer.writeLine("}");
6401
+ });
6402
+ writer.writeLine("}");
6403
+ });
6404
+ writer.writeLine("}, { auto: true }],");
5850
6405
  writer.writeLine("pomFactory: async ({ page }: { page: PwPage }, use: (r: PomFactory) => Promise<void>) => {");
5851
6406
  writer.indent(() => {
5852
6407
  writer.writeLine("await use({");
@@ -5876,10 +6431,31 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
5876
6431
  ]
5877
6432
  })
5878
6433
  });
5879
- return {
5880
- filePath: path.resolve(fixtureOutDirAbs, fixtureFileName),
5881
- content: fixturesContent
5882
- };
6434
+ const manifestFileName = "pom-manifest.g.ts";
6435
+ const manifestContent = generatePomManifestModule(
6436
+ componentHierarchyMap,
6437
+ options.elementMetadata,
6438
+ manifestFileName
6439
+ );
6440
+ const [diagnosticsRuntimeFile] = buildRuntimeGeneratedFilesFromSpecs([{
6441
+ absolutePath: resolvePluginAsset("../class-generation/diagnostics.ts"),
6442
+ description: "diagnostics.ts",
6443
+ outputPath: path.join(pomDirAbs, "_pom-runtime", "class-generation", "diagnostics.ts")
6444
+ }]);
6445
+ if (!diagnosticsRuntimeFile) {
6446
+ throw new Error("[vue-pom-generator] Failed to generate the Playwright diagnostics runtime.");
6447
+ }
6448
+ return [
6449
+ {
6450
+ filePath: path.resolve(fixtureOutDirAbs, fixtureFileName),
6451
+ content: fixturesContent
6452
+ },
6453
+ {
6454
+ filePath: path.resolve(fixtureOutDirAbs, manifestFileName),
6455
+ content: manifestContent
6456
+ },
6457
+ diagnosticsRuntimeFile
6458
+ ];
5883
6459
  }
5884
6460
  function prepareViewObjectModelClass(componentName, dependencies, componentHierarchyMap, options = {}) {
5885
6461
  const { isView, childrenComponentSet, usedComponentSet } = dependencies;
@@ -5912,6 +6488,23 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
5912
6488
  }
5913
6489
  return match;
5914
6490
  };
6491
+ const hasGeneratedPomSurface = (value, seen = /* @__PURE__ */ new Set()) => {
6492
+ const resolvedRef = resolveTrackedComponentRef(value);
6493
+ if (!resolvedRef || seen.has(resolvedRef)) {
6494
+ return false;
6495
+ }
6496
+ const resolvedDependencies = componentHierarchyMap.get(resolvedRef);
6497
+ if (!resolvedDependencies) {
6498
+ return false;
6499
+ }
6500
+ if (resolvedDependencies.dataTestIdSet.size > 0 || (resolvedDependencies.pomExtraMethods?.length ?? 0) > 0 || (resolvedDependencies.generatedMethods?.size ?? 0) > 0) {
6501
+ return true;
6502
+ }
6503
+ const nextSeen = new Set(seen);
6504
+ nextSeen.add(resolvedRef);
6505
+ const nestedRefs = resolvedDependencies.usedComponentSet?.size ? resolvedDependencies.usedComponentSet : resolvedDependencies.childrenComponentSet;
6506
+ return Array.from(nestedRefs).some((child) => hasGeneratedPomSurface(child, nextSeen));
6507
+ };
5915
6508
  const rawComponentRefsForInstances = usedComponentSet?.size ? usedComponentSet : childrenComponentSet;
5916
6509
  const ownClassName = toPascalCaseLocal(componentName);
5917
6510
  const isSelfReference = (ref) => {
@@ -5923,8 +6516,7 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
5923
6516
  if (isSelfReference(resolvedRef)) {
5924
6517
  continue;
5925
6518
  }
5926
- const resolvedDependencies = componentHierarchyMap.get(resolvedRef);
5927
- if (!resolvedDependencies?.dataTestIdSet.size) {
6519
+ if (!hasGeneratedPomSurface(resolvedRef, /* @__PURE__ */ new Set([componentName]))) {
5928
6520
  continue;
5929
6521
  }
5930
6522
  componentRefsForInstances.add(resolvedRef);
@@ -5968,7 +6560,7 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
5968
6560
  }));
5969
6561
  const widgetInstances = isView ? getWidgetInstancesForView(componentName, dependencies.dataTestIdSet, customPomAvailableClassIdentifiers) : [];
5970
6562
  const className = toPascalCaseLocal(componentName);
5971
- const childInstancePropertyNames = Array.from(componentRefsForInstances).filter((child) => componentHierarchyMap.has(child) && componentHierarchyMap.get(child)?.dataTestIdSet.size).map((child) => child.split(".vue")[0]);
6563
+ const childInstancePropertyNames = Array.from(componentRefsForInstances).map((child) => child.split(".vue")[0]);
5972
6564
  const blockedViewPassthroughMethodNames = new Set(
5973
6565
  attachmentsForThisClass.filter((a) => a.flatten).flatMap((a) => Array.from(a.methodSignatures.keys()))
5974
6566
  );
@@ -6066,10 +6658,7 @@ function generateViewObjectModelContent(componentName, dependencies, componentHi
6066
6658
  };
6067
6659
  for (const child of prepared.componentRefsForInstances) {
6068
6660
  const childName = child.endsWith(".vue") ? child.slice(0, -4) : child;
6069
- const childDeps = componentHierarchyMap.get(child) ?? componentHierarchyMap.get(childName);
6070
- if (childDeps?.dataTestIdSet.size) {
6071
- addGeneratedImport(childName);
6072
- }
6661
+ addGeneratedImport(childName);
6073
6662
  }
6074
6663
  const targetClassNames = Array.from(
6075
6664
  new Set(
@@ -6412,7 +7001,7 @@ function getRuntimeGeneratedAssetSpecs(baseDir, basePageClassPath) {
6412
7001
  const runtimeDirAbs = path.join(baseDir, "_pom-runtime");
6413
7002
  const runtimeClassGenAbs = path.join(runtimeDirAbs, "class-generation");
6414
7003
  const runtimeClassGenSourceDir = resolvePluginAsset("../class-generation");
6415
- const runtimeClassGenFiles = fs.readdirSync(runtimeClassGenSourceDir).filter((file) => file.endsWith(".ts")).filter((file) => file !== "base-page.ts" && file !== "index.ts").sort((left, right) => left.localeCompare(right));
7004
+ const runtimeClassGenFiles = fs.readdirSync(runtimeClassGenSourceDir).filter((file) => file.endsWith(".ts")).filter((file) => file !== "base-page.ts" && file !== "diagnostics.ts" && file !== "index.ts").sort((left, right) => left.localeCompare(right));
6416
7005
  return [
6417
7006
  {
6418
7007
  absolutePath: resolvePluginAsset("../click-instrumentation.ts"),
@@ -6831,7 +7420,7 @@ function getComponentInstances(childrenComponent, componentHierarchyMap, attachm
6831
7420
  }));
6832
7421
  }
6833
7422
  childrenComponent.forEach((child) => {
6834
- if (componentHierarchyMap.has(child) && componentHierarchyMap.get(child)?.dataTestIdSet.size) {
7423
+ if (componentHierarchyMap.has(child)) {
6835
7424
  const childName = child.split(".vue")[0];
6836
7425
  declarations.push(createClassProperty({
6837
7426
  name: childName,
@@ -6854,7 +7443,7 @@ function getConstructor(childrenComponent, componentHierarchyMap, attachmentsFor
6854
7443
  writer.writeLine(`this.${w.propertyName} = new ${w.className}(this.page, ${JSON.stringify(w.testId)});`);
6855
7444
  }
6856
7445
  childrenComponent.forEach((child) => {
6857
- if (componentHierarchyMap.has(child) && componentHierarchyMap.get(child)?.dataTestIdSet.size) {
7446
+ if (componentHierarchyMap.has(child)) {
6858
7447
  const childName = child.split(".vue")[0];
6859
7448
  writer.writeLine(`this.${childName} = new ${childName}(page);`);
6860
7449
  }
@@ -7254,6 +7843,13 @@ ${buildSearchRootsKey(normalizedSearchRoots)}`;
7254
7843
  }
7255
7844
  try {
7256
7845
  const ast = compilerDom.parse(template, { comments: false });
7846
+ const renderedRoots = ast.children.filter((child) => {
7847
+ return child.type !== compilerCore.NodeTypes.COMMENT && !(child.type === compilerCore.NodeTypes.TEXT && child.content.trim() === "");
7848
+ });
7849
+ if (renderedRoots.length !== 1) {
7850
+ inferredNativeWrapperConfigByLookup.set(cacheKey, { role: "" });
7851
+ return null;
7852
+ }
7257
7853
  const nextSeen = new Set(seenTags);
7258
7854
  nextSeen.add(tag);
7259
7855
  const isComponentLikeTag = (value) => {
@@ -7660,7 +8256,7 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
7660
8256
  const inferred = tryInferNativeWrapperRoleFromSfc(element.tag, vueFilesPathMap, wrapperSearchRoots);
7661
8257
  if (inferred?.role) {
7662
8258
  nativeWrappers[element.tag] = { role: inferred.role, inferred: true };
7663
- } else if (element.tag.endsWith("Button")) {
8259
+ } else if (element.tag.endsWith("Button") && !tryResolveSfcPathForTag(element.tag, vueFilesPathMap, wrapperSearchRoots)) {
7664
8260
  nativeWrappers[element.tag] = { role: "button" };
7665
8261
  } else if (element.tag === "DxDataGrid") {
7666
8262
  nativeWrappers[element.tag] = { role: "grid" };
@@ -7963,7 +8559,7 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
7963
8559
  });
7964
8560
  return;
7965
8561
  }
7966
- if (handlerInfo) {
8562
+ if (handlerInfo && nativeWrappers[element.tag]) {
7967
8563
  const testId = getHandlerAttributeValueDataTestId(handlerInfo.semanticNameHint);
7968
8564
  applyResolvedDataTestIdForElement({
7969
8565
  preferredGeneratedValue: testId,
@@ -8031,59 +8627,6 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
8031
8627
  }
8032
8628
  };
8033
8629
  }
8034
- function supportsInlineTextAccessibleName(role) {
8035
- return role === "button" || role === "radio";
8036
- }
8037
- function buildAccessibilityAudit(metadata, inferredRole) {
8038
- if (!metadata || !inferredRole) {
8039
- return void 0;
8040
- }
8041
- const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8042
- const dynamicProps = new Set(metadata.dynamicProps ?? []);
8043
- const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8044
- let accessibleNameSource;
8045
- const reasons = [];
8046
- if (metadata.staticAriaLabel) {
8047
- accessibleNameSource = "aria-label";
8048
- } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8049
- accessibleNameSource = "text";
8050
- } else if (metadata.staticTitle) {
8051
- accessibleNameSource = "title";
8052
- } else if (hasDynamicAccessibleNameSignal) {
8053
- accessibleNameSource = "dynamic";
8054
- } else if (role === "input" || role === "select") {
8055
- accessibleNameSource = "unknown";
8056
- reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8057
- } else {
8058
- accessibleNameSource = "missing";
8059
- reasons.push("No compile-time accessible-name signal was found.");
8060
- }
8061
- return {
8062
- needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8063
- accessibleNameSource,
8064
- reasons,
8065
- ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8066
- ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8067
- ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8068
- ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8069
- };
8070
- }
8071
- function collectAccessibilityReviewWarnings(manifest) {
8072
- const warnings = [];
8073
- for (const [componentName, component] of Object.entries(manifest)) {
8074
- for (const entry of component.entries) {
8075
- if (!entry.accessibility?.needsReview) {
8076
- continue;
8077
- }
8078
- const entryLabel = entry.generatedPropertyName ?? entry.testId;
8079
- const reasonText = entry.accessibility.reasons.join(" ");
8080
- warnings.push(
8081
- `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8082
- );
8083
- }
8084
- }
8085
- return warnings;
8086
- }
8087
8630
  function findDataTestIdProp(element, attributeName = "data-testid") {
8088
8631
  return element.props.find(
8089
8632
  (prop) => prop.type === compilerCore.NodeTypes.ATTRIBUTE && prop.name === attributeName || prop.type === compilerCore.NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === compilerCore.NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName
@@ -8208,151 +8751,6 @@ function tryCreateElementMetadata(args) {
8208
8751
  };
8209
8752
  return metadata;
8210
8753
  }
8211
- function matchesPrimarySelector(extraMethod, pom) {
8212
- if (extraMethod.selector.kind !== "testId") {
8213
- return false;
8214
- }
8215
- return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8216
- }
8217
- function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8218
- const testId = entry.selectorValue.formatted;
8219
- const metadata = componentMetadata?.get(testId);
8220
- const pom = entry.pom;
8221
- const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8222
- const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8223
- const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8224
- ...generatedActionName ? [generatedActionName] : [],
8225
- ...extraActionNames.filter((name) => name !== generatedActionName)
8226
- ]));
8227
- const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8228
- return {
8229
- testId,
8230
- selectorPatternKind: entry.selectorValue.patternKind,
8231
- semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8232
- locatorDescription: pom ? buildPomLocatorDescription({
8233
- componentName,
8234
- methodName: pom.methodName,
8235
- nativeRole: pom.nativeRole
8236
- }) : componentName,
8237
- inferredRole: pom?.nativeRole ?? null,
8238
- ...accessibility ? { accessibility } : {},
8239
- generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8240
- generatedActionName,
8241
- generatedActionNames,
8242
- emitPrimary: pom?.emitPrimary !== false,
8243
- ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8244
- ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8245
- ...metadata ? { sourceTagType: metadata.tagType } : {},
8246
- ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8247
- ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8248
- ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8249
- ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8250
- ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8251
- ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8252
- ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8253
- ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8254
- };
8255
- }
8256
- function buildPomManifest(componentHierarchyMap, elementMetadata) {
8257
- const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8258
- const entries = Array.from(dependencies.dataTestIdSet).sort((a, b) => a.selectorValue.formatted.localeCompare(b.selectorValue.formatted)).map((entry) => getManifestEntry(componentName, entry, elementMetadata.get(componentName), dependencies.pomExtraMethods ?? []));
8259
- if (!entries.length) {
8260
- return null;
8261
- }
8262
- return [componentName, {
8263
- componentName,
8264
- className: componentName,
8265
- sourceFile: dependencies.filePath,
8266
- kind: dependencies.isView ? "view" : "component",
8267
- testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8268
- entries
8269
- }];
8270
- }).filter((entry) => entry !== null);
8271
- return Object.fromEntries(manifestEntries);
8272
- }
8273
- function buildTestIdManifest(componentHierarchyMap) {
8274
- return Object.fromEntries(
8275
- Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8276
- const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8277
- if (!testIds.length) {
8278
- return null;
8279
- }
8280
- return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8281
- }).filter((entry) => entry !== null)
8282
- );
8283
- }
8284
- function writeConstJson(value) {
8285
- return (writer) => {
8286
- writer.write(`${JSON.stringify(value, null, 2)} as const`);
8287
- };
8288
- }
8289
- function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8290
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8291
- const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8292
- return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8293
- sourceFile.addStatements("// Virtual module: test id manifest");
8294
- sourceFile.addVariableStatement({
8295
- declarationKind: tsMorph.VariableDeclarationKind.Const,
8296
- isExported: true,
8297
- declarations: [{
8298
- name: "testIdManifest",
8299
- initializer: writeConstJson(testIdManifest)
8300
- }]
8301
- });
8302
- sourceFile.addVariableStatement({
8303
- declarationKind: tsMorph.VariableDeclarationKind.Const,
8304
- isExported: true,
8305
- declarations: [{
8306
- name: "pomManifest",
8307
- initializer: writeConstJson(pomManifest)
8308
- }]
8309
- });
8310
- sourceFile.addTypeAlias({
8311
- isExported: true,
8312
- name: "TestIdManifest",
8313
- type: "typeof testIdManifest"
8314
- });
8315
- sourceFile.addTypeAlias({
8316
- isExported: true,
8317
- name: "ComponentName",
8318
- type: "keyof TestIdManifest"
8319
- });
8320
- sourceFile.addTypeAlias({
8321
- isExported: true,
8322
- name: "PomManifest",
8323
- type: "typeof pomManifest"
8324
- });
8325
- sourceFile.addTypeAlias({
8326
- isExported: true,
8327
- name: "PomManifestComponentName",
8328
- type: "keyof PomManifest"
8329
- });
8330
- });
8331
- }
8332
- function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8333
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8334
- return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8335
- sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8336
- sourceFile.addVariableStatement({
8337
- declarationKind: tsMorph.VariableDeclarationKind.Const,
8338
- isExported: true,
8339
- declarations: [{
8340
- name: "pomManifest",
8341
- initializer: writeConstJson(pomManifest)
8342
- }]
8343
- });
8344
- sourceFile.addTypeAlias({
8345
- isExported: true,
8346
- name: "PomManifest",
8347
- type: "typeof pomManifest"
8348
- });
8349
- sourceFile.addTypeAlias({
8350
- isExported: true,
8351
- name: "PomManifestComponentName",
8352
- type: "keyof PomManifest"
8353
- });
8354
- });
8355
- }
8356
8754
  function resolveExistingIdBehavior(config, componentName) {
8357
8755
  return typeof config === "string" ? config : config.components[componentName] ?? config.default;
8358
8756
  }
@@ -8681,6 +9079,7 @@ function isLessRich(candidate, previous) {
8681
9079
  function createBuildProcessorPlugin(options) {
8682
9080
  const {
8683
9081
  componentHierarchyMap,
9082
+ elementMetadata,
8684
9083
  crossFileKeyRegistry,
8685
9084
  vueFilesPathMap,
8686
9085
  getPageDirs,
@@ -8933,7 +9332,8 @@ function createBuildProcessorPlugin(options) {
8933
9332
  routerType,
8934
9333
  pageDirs: getPageDirs(),
8935
9334
  componentDirs: getComponentDirs(),
8936
- layoutDirs: getLayoutDirs()
9335
+ layoutDirs: getLayoutDirs(),
9336
+ elementMetadata
8937
9337
  });
8938
9338
  lastGeneratedMetrics = metrics;
8939
9339
  loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
@@ -8945,6 +9345,7 @@ function createBuildProcessorPlugin(options) {
8945
9345
  }
8946
9346
  function createDevProcessorPlugin(options) {
8947
9347
  const {
9348
+ elementMetadata,
8948
9349
  nativeWrappers,
8949
9350
  optionKeyAttribute,
8950
9351
  excludedComponents,
@@ -9237,7 +9638,8 @@ function createDevProcessorPlugin(options) {
9237
9638
  testIdAttribute,
9238
9639
  vueRouterFluentChaining: routerAwarePoms,
9239
9640
  routerEntry: getResolvedRouterEntry(),
9240
- routerType
9641
+ routerType,
9642
+ elementMetadata
9241
9643
  });
9242
9644
  const t1 = node_perf_hooks.performance.now();
9243
9645
  logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
@@ -9553,6 +9955,7 @@ function createInternalPlugins(options) {
9553
9955
  const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9554
9956
  const tsProcessor = createBuildProcessorPlugin({
9555
9957
  componentHierarchyMap,
9958
+ elementMetadata,
9556
9959
  crossFileKeyRegistry,
9557
9960
  vueFilesPathMap,
9558
9961
  getPageDirs,
@@ -9572,6 +9975,7 @@ function createInternalPlugins(options) {
9572
9975
  loggerRef
9573
9976
  });
9574
9977
  const devProcessor = createDevProcessorPlugin({
9978
+ elementMetadata,
9575
9979
  nativeWrappers,
9576
9980
  optionKeyAttribute,
9577
9981
  excludedComponents,