@immense/vue-pom-generator 1.0.89 → 1.0.91

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 (43) hide show
  1. package/README.md +42 -10
  2. package/RELEASE_NOTES.md +22 -47
  3. package/class-generation/index.ts +124 -107
  4. package/dist/class-generation/index.d.ts +1 -0
  5. package/dist/class-generation/index.d.ts.map +1 -1
  6. package/dist/eslint/index.cjs +42 -0
  7. package/dist/eslint/index.cjs.map +1 -1
  8. package/dist/eslint/index.d.ts +3 -0
  9. package/dist/eslint/index.d.ts.map +1 -1
  10. package/dist/eslint/index.mjs +42 -0
  11. package/dist/eslint/index.mjs.map +1 -1
  12. package/dist/eslint/no-data-testid-in-specs.d.ts +3 -0
  13. package/dist/eslint/no-data-testid-in-specs.d.ts.map +1 -0
  14. package/dist/index.cjs +1824 -1537
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.mjs +1815 -1528
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  21. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  22. package/dist/plugin/resolved-generation-options.d.ts +2 -2
  23. package/dist/plugin/resolved-generation-options.d.ts.map +1 -1
  24. package/dist/plugin/resolved-injection-options.d.ts +3 -3
  25. package/dist/plugin/resolved-injection-options.d.ts.map +1 -1
  26. package/dist/plugin/types.d.ts +11 -3
  27. package/dist/plugin/types.d.ts.map +1 -1
  28. package/dist/plugin/vue-plugin.d.ts +3 -2
  29. package/dist/plugin/vue-plugin.d.ts.map +1 -1
  30. package/dist/route-navigation-codegen.d.ts +38 -0
  31. package/dist/route-navigation-codegen.d.ts.map +1 -0
  32. package/dist/router-bridge.d.ts +19 -0
  33. package/dist/router-bridge.d.ts.map +1 -0
  34. package/dist/router.cjs +9 -0
  35. package/dist/router.cjs.map +1 -0
  36. package/dist/router.mjs +9 -0
  37. package/dist/router.mjs.map +1 -0
  38. package/dist/tests/existing-id-behavior.test.d.ts +2 -0
  39. package/dist/tests/existing-id-behavior.test.d.ts.map +1 -0
  40. package/dist/tests/router-bridge.test.d.ts +2 -0
  41. package/dist/tests/router-bridge.test.d.ts.map +1 -0
  42. package/dist/vite.config.d.ts.map +1 -1
  43. package/package.json +6 -1
package/dist/index.cjs CHANGED
@@ -33,8 +33,9 @@ const parser = require("@babel/parser");
33
33
  const compilerCore = require("@vue/compiler-core");
34
34
  const tsMorph = require("ts-morph");
35
35
  const types = require("@babel/types");
36
- const node_perf_hooks = require("node:perf_hooks");
36
+ const router = require("./router.cjs");
37
37
  const vue = require("@vitejs/plugin-vue");
38
+ const node_perf_hooks = require("node:perf_hooks");
38
39
  const dom = require("@floating-ui/dom");
39
40
  var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
40
41
  function _interopNamespaceDefault(e) {
@@ -4035,18 +4036,18 @@ function getRoutePropsKeys(record) {
4035
4036
  }
4036
4037
  return { paramKeys: [], queryKeys: [] };
4037
4038
  }
4038
- function buildRouteTemplate(router, record, paramNames) {
4039
+ function buildRouteTemplate(router2, record, paramNames) {
4039
4040
  if (typeof record.name !== "string" || !record.name.length) {
4040
4041
  return record.path;
4041
4042
  }
4042
4043
  const params = Object.fromEntries(paramNames.map((name) => [name, getParamToken(name)]));
4043
4044
  try {
4044
- return router.resolve({ name: record.name, params }).path;
4045
+ return router2.resolve({ name: record.name, params }).path;
4045
4046
  } catch {
4046
4047
  return record.path;
4047
4048
  }
4048
4049
  }
4049
- function getRouteParamMeta(router, record, paramNames) {
4050
+ function getRouteParamMeta(router2, record, paramNames) {
4050
4051
  if (typeof record.name !== "string" || !record.name.length) {
4051
4052
  return paramNames.map((name) => ({ name, optional: false }));
4052
4053
  }
@@ -4055,7 +4056,7 @@ function getRouteParamMeta(router, record, paramNames) {
4055
4056
  const params = { ...paramsWithAll };
4056
4057
  delete params[name];
4057
4058
  try {
4058
- router.resolve({ name: record.name, params });
4059
+ router2.resolve({ name: record.name, params });
4059
4060
  return { name, optional: true };
4060
4061
  } catch {
4061
4062
  return { name, optional: false };
@@ -4625,16 +4626,16 @@ async function parseRouterFileFromCwd(routerEntryPath, options = {}) {
4625
4626
  if (typeof makeRouter !== "function") {
4626
4627
  throw new TypeError(`[vue-pom-generator] ${routerEntry} must export a default router factory function (export default makeRouter).`);
4627
4628
  }
4628
- let router;
4629
+ let router2;
4629
4630
  try {
4630
- router = makeRouter();
4631
+ router2 = makeRouter();
4631
4632
  } catch (err) {
4632
4633
  throw new Error(`[vue-pom-generator] makeRouter() invocation failed: ${String(err)}`);
4633
4634
  }
4634
4635
  const routeNameMap = /* @__PURE__ */ new Map();
4635
4636
  const routePathMap = /* @__PURE__ */ new Map();
4636
4637
  const routeMetaEntries = [];
4637
- for (const r of router.getRoutes()) {
4638
+ for (const r of router2.getRoutes()) {
4638
4639
  const componentInfo = await getComponentInfoFromRouteRecord(r, { rootDir: cwd });
4639
4640
  const componentName = resolveIntrospectedComponentName(componentInfo, options.componentNaming);
4640
4641
  if (!componentName)
@@ -4647,8 +4648,8 @@ async function parseRouterFileFromCwd(routerEntryPath, options = {}) {
4647
4648
  routeNameMap.set(key, componentName);
4648
4649
  }
4649
4650
  const { paramKeys, queryKeys } = getRoutePropsKeys(r);
4650
- const paramsMeta = getRouteParamMeta(router, r, paramKeys);
4651
- const pathTemplate = buildRouteTemplate(router, r, paramsMeta.map((p) => p.name));
4651
+ const paramsMeta = getRouteParamMeta(router2, r, paramKeys);
4652
+ const pathTemplate = buildRouteTemplate(router2, r, paramsMeta.map((p) => p.name));
4652
4653
  if (typeof pathTemplate === "string" && pathTemplate.length) {
4653
4654
  routeMetaEntries.push({
4654
4655
  componentName,
@@ -4669,6 +4670,251 @@ async function parseRouterFileFromCwd(routerEntryPath, options = {}) {
4669
4670
  }
4670
4671
  });
4671
4672
  }
4673
+ function writeNavigationValue(writer, input, name) {
4674
+ writer.write(input.identifier);
4675
+ if (input.optional) {
4676
+ writer.write("?.");
4677
+ }
4678
+ writer.write(`[${JSON.stringify(name)}]`);
4679
+ }
4680
+ function writeFilteredNavigationRecord(writer, variableName, input, names) {
4681
+ writer.write(`const ${variableName} = `);
4682
+ if (!input || names.length === 0) {
4683
+ writer.write("{};").newLine();
4684
+ return;
4685
+ }
4686
+ writer.write("Object.fromEntries([");
4687
+ names.forEach((name, index) => {
4688
+ if (index > 0) {
4689
+ writer.write(", ");
4690
+ }
4691
+ writer.write(`[${JSON.stringify(name)}, `);
4692
+ writeNavigationValue(writer, input, name);
4693
+ writer.write("]");
4694
+ });
4695
+ writer.write("].filter(([, value]) => value !== undefined));").newLine();
4696
+ }
4697
+ function writeUnpartitionedRouteParams(writer, input) {
4698
+ writer.write("const routeParams = ");
4699
+ if (!input) {
4700
+ writer.write("{};").newLine();
4701
+ return;
4702
+ }
4703
+ writer.write("Object.fromEntries(Object.entries(");
4704
+ writer.write(input.identifier);
4705
+ if (input.optional) {
4706
+ writer.write(" ?? {}");
4707
+ }
4708
+ writer.write(").filter(([, v]) => v !== undefined));").newLine();
4709
+ }
4710
+ function writeRouterTargetType(writer, includeQuery) {
4711
+ writer.write("{ name: string; params: Record<string, unknown>");
4712
+ if (includeQuery) {
4713
+ writer.write("; query: Record<string, unknown>");
4714
+ }
4715
+ writer.write(" }");
4716
+ }
4717
+ function writeRouterType(writer, includeQuery) {
4718
+ writer.write(`{ ${router.POM_ROUTER_GLOBAL_NAME}?: { push: (to: `);
4719
+ writeRouterTargetType(writer, includeQuery);
4720
+ writer.write(") => Promise<unknown>; resolve: (to: ");
4721
+ writeRouterTargetType(writer, includeQuery);
4722
+ writer.write(") => { href: string } } }");
4723
+ }
4724
+ function writeRouterBinding(writer, includeQuery) {
4725
+ writer.write("{ name, params");
4726
+ if (includeQuery) {
4727
+ writer.write(", query");
4728
+ }
4729
+ writer.write(" }");
4730
+ }
4731
+ function writeRouterTarget(writer, writeName, includeQuery, paramsExpression, queryExpression) {
4732
+ writer.write("{ name: ");
4733
+ writeName(writer);
4734
+ writer.write(`, params: ${paramsExpression}`);
4735
+ if (includeQuery) {
4736
+ writer.write(`, query: ${queryExpression}`);
4737
+ }
4738
+ writer.write(" }");
4739
+ }
4740
+ function requireNavigationInput(input, context) {
4741
+ if (!input) {
4742
+ throw new Error(`${context} requires a navigation input.`);
4743
+ }
4744
+ return input;
4745
+ }
4746
+ function writeParametrizedRouteSelector(writer, input, pathParamNames) {
4747
+ writer.write(`const useParametrizedRoute = ${input.identifier} !== undefined && [`);
4748
+ pathParamNames.forEach((name, index) => {
4749
+ if (index > 0) {
4750
+ writer.write(", ");
4751
+ }
4752
+ writer.write(JSON.stringify(name));
4753
+ });
4754
+ writer.write(`].some(key => Object.prototype.hasOwnProperty.call(${input.identifier}, key));`).newLine();
4755
+ }
4756
+ function writeSelectionPrelude(writer, selection, input, pathParamNames) {
4757
+ if (selection.kind === "dual" && selection.selectBy === "path-param-presence") {
4758
+ writeParametrizedRouteSelector(
4759
+ writer,
4760
+ requireNavigationInput(input, "Path-param route selection"),
4761
+ pathParamNames
4762
+ );
4763
+ }
4764
+ }
4765
+ function writeSelectedTarget(writer, selection, input) {
4766
+ if (selection.kind === "single") {
4767
+ writer.write(JSON.stringify(selection.target));
4768
+ return;
4769
+ }
4770
+ if (selection.selectBy === "path-param-presence") {
4771
+ writer.write("useParametrizedRoute");
4772
+ } else {
4773
+ writer.write(requireNavigationInput(input, "Input-presence route selection").identifier);
4774
+ }
4775
+ writer.write(` ? ${JSON.stringify(selection.parametrizedTarget)} : ${JSON.stringify(selection.paramlessTarget)}`);
4776
+ }
4777
+ function createRouterNavigationWriter(options) {
4778
+ return (writer) => {
4779
+ writeSelectionPrelude(writer, options.routeName, options.input, options.pathParamNames);
4780
+ const writeRouteName = (nameWriter) => writeSelectedTarget(nameWriter, options.routeName, options.input);
4781
+ const includeQuery = options.queryNames.length > 0;
4782
+ if (includeQuery) {
4783
+ writeFilteredNavigationRecord(writer, "routeParams", options.input, options.pathParamNames);
4784
+ writeFilteredNavigationRecord(writer, "routeQuery", options.input, options.queryNames);
4785
+ } else {
4786
+ writeUnpartitionedRouteParams(writer, options.input);
4787
+ }
4788
+ writer.writeLine(
4789
+ `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${router.POM_ROUTER_GLOBAL_NAME}?: unknown }).${router.POM_ROUTER_GLOBAL_NAME} === "undefined");`
4790
+ );
4791
+ writer.writeLine("if (isCold) {");
4792
+ writer.indent(() => {
4793
+ writer.writeLine('await this.page.goto("/", { waitUntil: "commit" });');
4794
+ writer.writeLine(
4795
+ `await this.page.waitForFunction(() => typeof (globalThis as { ${router.POM_ROUTER_GLOBAL_NAME}?: unknown }).${router.POM_ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`
4796
+ );
4797
+ writer.write("const href = await this.page.evaluate((");
4798
+ writeRouterBinding(writer, includeQuery);
4799
+ writer.write(") => (globalThis as ");
4800
+ writeRouterType(writer, includeQuery);
4801
+ writer.write(`).${router.POM_ROUTER_GLOBAL_NAME}?.resolve(`);
4802
+ writeRouterBinding(writer, includeQuery);
4803
+ writer.write(")?.href, ");
4804
+ writeRouterTarget(writer, writeRouteName, includeQuery, "routeParams", "routeQuery");
4805
+ writer.write(");").newLine();
4806
+ writer.writeLine("if (href) {");
4807
+ writer.indent(() => {
4808
+ writer.writeLine('await this.page.goto(href, { waitUntil: "domcontentloaded" });');
4809
+ });
4810
+ writer.writeLine("}");
4811
+ });
4812
+ writer.writeLine("} else {");
4813
+ writer.indent(() => {
4814
+ writer.write("await this.page.evaluate(async (");
4815
+ writeRouterBinding(writer, includeQuery);
4816
+ writer.write(") => {").newLine();
4817
+ writer.indent(() => {
4818
+ writer.write("await (globalThis as ");
4819
+ writeRouterType(writer, includeQuery);
4820
+ writer.write(`).${router.POM_ROUTER_GLOBAL_NAME}?.push(`);
4821
+ writeRouterBinding(writer, includeQuery);
4822
+ writer.write(");").newLine();
4823
+ });
4824
+ writer.write("}, ");
4825
+ writeRouterTarget(writer, writeRouteName, includeQuery, "routeParams", "routeQuery");
4826
+ writer.write(");").newLine();
4827
+ });
4828
+ writer.writeLine("}");
4829
+ };
4830
+ }
4831
+ function writePathParamAssignments(writer, input, pathParams) {
4832
+ for (const param of pathParams) {
4833
+ const token = getParamToken(param.name);
4834
+ if (param.optional) {
4835
+ writer.write("targetUrl = ");
4836
+ writeNavigationValue(writer, input, param.name);
4837
+ writer.write(` === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
4838
+ writeNavigationValue(writer, input, param.name);
4839
+ writer.write("));").newLine();
4840
+ } else {
4841
+ writer.write(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(`);
4842
+ writeNavigationValue(writer, input, param.name);
4843
+ writer.write("));").newLine();
4844
+ }
4845
+ }
4846
+ }
4847
+ function writeQueryString(writer, input, queryNames) {
4848
+ if (queryNames.length === 0) {
4849
+ return;
4850
+ }
4851
+ writer.writeLine("const routeQuery = new URLSearchParams();");
4852
+ for (const queryName of queryNames) {
4853
+ writer.write("if (");
4854
+ writeNavigationValue(writer, input, queryName);
4855
+ writer.write(" !== undefined) {").newLine();
4856
+ writer.indent(() => {
4857
+ writer.write(`routeQuery.set(${JSON.stringify(queryName)}, String(`);
4858
+ writeNavigationValue(writer, input, queryName);
4859
+ writer.write("));").newLine();
4860
+ });
4861
+ writer.writeLine("}");
4862
+ }
4863
+ writer.writeLine("const routeQueryString = routeQuery.toString();");
4864
+ writer.writeLine("if (routeQueryString) {");
4865
+ writer.indent(() => {
4866
+ writer.writeLine("targetUrl += `?${routeQueryString}`;");
4867
+ });
4868
+ writer.writeLine("}");
4869
+ }
4870
+ function writeRuntimeUrlNavigation(writer) {
4871
+ writer.writeLine(
4872
+ "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;"
4873
+ );
4874
+ writer.writeLine(
4875
+ "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;"
4876
+ );
4877
+ writer.writeLine("const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;");
4878
+ writer.writeLine("await this.page.goto(resolvedUrl);");
4879
+ }
4880
+ function createUrlNavigationWriter(options) {
4881
+ return (writer) => {
4882
+ writeSelectionPrelude(writer, options.routeTemplate, options.input, options.pathParams.map((param) => param.name));
4883
+ if (options.routeTemplate.kind === "single") {
4884
+ writer.write(`let targetUrl = ${JSON.stringify(options.routeTemplate.target)};`).newLine();
4885
+ } else {
4886
+ writer.write("const template = ");
4887
+ writeSelectedTarget(writer, options.routeTemplate, options.input);
4888
+ writer.write(";").newLine();
4889
+ writer.writeLine("let targetUrl = template;");
4890
+ }
4891
+ if (options.pathParams.length > 0) {
4892
+ const input = requireNavigationInput(options.input, "URL navigation with path params");
4893
+ if (options.routeTemplate.kind === "dual") {
4894
+ writer.write("if (");
4895
+ writer.write(input.identifier);
4896
+ if (options.routeTemplate.selectBy === "path-param-presence") {
4897
+ writer.write(" && useParametrizedRoute");
4898
+ }
4899
+ writer.write(") {").newLine();
4900
+ writer.indent(() => {
4901
+ writePathParamAssignments(writer, input, options.pathParams);
4902
+ });
4903
+ writer.writeLine("}");
4904
+ } else {
4905
+ writePathParamAssignments(writer, input, options.pathParams);
4906
+ }
4907
+ }
4908
+ if (options.queryNames.length > 0) {
4909
+ writeQueryString(
4910
+ writer,
4911
+ requireNavigationInput(options.input, "URL navigation with query params"),
4912
+ options.queryNames
4913
+ );
4914
+ }
4915
+ writeRuntimeUrlNavigation(writer);
4916
+ };
4917
+ }
4672
4918
  const GENERATED_GITATTRIBUTES_BLOCK_START = "# BEGIN vue-pom-generator generated files";
4673
4919
  const GENERATED_GITATTRIBUTES_BLOCK_END = "# END vue-pom-generator generated files";
4674
4920
  const VUE_POM_GENERATOR_ERROR_PREFIX = "[vue-pom-generator]";
@@ -4799,7 +5045,7 @@ async function getRouteMetaByComponent(projectRoot, routerEntry, routerType, opt
4799
5045
  const map = /* @__PURE__ */ new Map();
4800
5046
  for (const entry of routeMetaEntries) {
4801
5047
  const list = map.get(entry.componentName) ?? [];
4802
- list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params });
5048
+ list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params, query: entry.query });
4803
5049
  map.set(entry.componentName, list);
4804
5050
  }
4805
5051
  const dedupeRoutes = (entries) => {
@@ -4838,8 +5084,37 @@ function generateRouteProperty(routeMeta) {
4838
5084
  })
4839
5085
  ];
4840
5086
  }
4841
- function buildParamTypeString(params) {
4842
- return `{ ${params.map((p) => `${p.name}${p.optional ? "?" : ""}: string | number`).join("; ")} }`;
5087
+ function formatNavigationFieldName(name) {
5088
+ return /^[$a-z_][$\w]*$/i.test(name) ? name : JSON.stringify(name);
5089
+ }
5090
+ function buildNavigationTypeString(route, requiredOptionalParamName) {
5091
+ const pathFields = route.params.map((param) => {
5092
+ const forcePresent = param.optional && param.name === requiredOptionalParamName;
5093
+ return `${formatNavigationFieldName(param.name)}${param.optional && !forcePresent ? "?" : ""}: string | number${forcePresent ? " | undefined" : ""}`;
5094
+ });
5095
+ const pathNames = new Set(route.params.map((param) => param.name));
5096
+ const queryFields = route.query.filter((query) => !pathNames.has(query)).map((query) => `${formatNavigationFieldName(query)}?: string | number`);
5097
+ return `{ ${[...pathFields, ...queryFields].join("; ")} }`;
5098
+ }
5099
+ function buildParametrizedRouteSelectionTypeString(route) {
5100
+ if (route.params.some((param) => !param.optional)) {
5101
+ return buildNavigationTypeString(route);
5102
+ }
5103
+ return route.params.map((param) => buildNavigationTypeString(route, param.name)).join(" | ");
5104
+ }
5105
+ function buildImplementationNavigationTypeString(routes) {
5106
+ const fields = /* @__PURE__ */ new Map();
5107
+ for (const route of routes) {
5108
+ for (const param of route.params) {
5109
+ fields.set(param.name, true);
5110
+ }
5111
+ for (const query of route.query) {
5112
+ if (!fields.has(query)) {
5113
+ fields.set(query, true);
5114
+ }
5115
+ }
5116
+ }
5117
+ return `{ ${Array.from(fields.keys()).map((name) => `${formatNavigationFieldName(name)}?: string | number`).join("; ")} }`;
4843
5118
  }
4844
5119
  function chooseParamlessRoute(routes) {
4845
5120
  const paramless = routes.filter((r) => r.params.length === 0);
@@ -4853,31 +5128,12 @@ function chooseParametrizedRoute(routes) {
4853
5128
  return null;
4854
5129
  return parametrized.slice().sort((a, b) => a.params.length - b.params.length || a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
4855
5130
  }
4856
- const GOTO_RUNTIME_LINES = [
4857
- "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;",
4858
- "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;",
4859
- "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
4860
- "await this.page.goto(resolvedUrl);"
4861
- ];
4862
- const ROUTER_GLOBAL_NAME = "__appRouter";
4863
- const pushBlock = (routeNameExpr, paramsExpr, nullable) => {
4864
- 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 } } }`;
4865
- 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));`;
4866
- return [
4867
- routeParamsLine,
4868
- `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} === "undefined");`,
4869
- `if (isCold) {`,
4870
- ` await this.page.goto("/", { waitUntil: "commit" });`,
4871
- ` await this.page.waitForFunction(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`,
4872
- ` const href = await this.page.evaluate(({ name, params }) => (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.resolve({ name, params })?.href, { name: ${routeNameExpr}, params: routeParams });`,
4873
- ` if (href) { await this.page.goto(href, { waitUntil: "domcontentloaded" }); }`,
4874
- `} else {`,
4875
- ` await this.page.evaluate(async ({ name, params }) => {`,
4876
- ` await (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.push({ name, params });`,
4877
- ` }, { name: ${routeNameExpr}, params: routeParams });`,
4878
- `}`
4879
- ];
4880
- };
5131
+ function requireRouteName(route) {
5132
+ if (route.name === null) {
5133
+ throw new VuePomGeneratorError(`Named navigation requires a route name for template "${route.template}".`);
5134
+ }
5135
+ return route.name;
5136
+ }
4881
5137
  function generateGoToMethod(componentName, routeMeta) {
4882
5138
  if (!routeMeta) {
4883
5139
  return [
@@ -4905,29 +5161,30 @@ function generateGoToMethod(componentName, routeMeta) {
4905
5161
  })
4906
5162
  ];
4907
5163
  }
4908
- const paramStatements = (entry) => {
4909
- const lines = [];
4910
- for (const param of entry.params) {
4911
- const token = getParamToken(param.name);
4912
- if (param.optional) {
4913
- lines.push(`targetUrl = params.${param.name} === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4914
- } else {
4915
- lines.push(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
4916
- }
4917
- }
4918
- return lines;
4919
- };
4920
5164
  if (hasParamless && !hasParametrized) {
4921
5165
  const route = paramless;
5166
+ const hasQuery2 = route.query.length > 0;
5167
+ const paramType2 = buildNavigationTypeString(route);
4922
5168
  return [
4923
5169
  createClassMethod({
4924
5170
  name: "goTo",
4925
5171
  isAsync: true,
4926
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "undefined", false) : [`const targetUrl = ${JSON.stringify(route.template)};`, ...GOTO_RUNTIME_LINES]
5172
+ parameters: hasQuery2 ? [{ name: "params", type: paramType2, hasQuestionToken: true }] : [],
5173
+ statements: route.name !== null ? createRouterNavigationWriter({
5174
+ routeName: { kind: "single", target: route.name },
5175
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5176
+ pathParamNames: [],
5177
+ queryNames: route.query
5178
+ }) : createUrlNavigationWriter({
5179
+ routeTemplate: { kind: "single", target: route.template },
5180
+ input: hasQuery2 ? { identifier: "params", optional: true } : void 0,
5181
+ pathParams: [],
5182
+ queryNames: route.query
5183
+ })
4927
5184
  })
4928
5185
  ];
4929
5186
  }
4930
- const paramType = buildParamTypeString(parametrized.params);
5187
+ const paramType = buildNavigationTypeString(parametrized);
4931
5188
  if (hasParametrized && !hasParamless) {
4932
5189
  const route = parametrized;
4933
5190
  const allOptional = route.params.every((p) => p.optional);
@@ -4936,34 +5193,61 @@ function generateGoToMethod(componentName, routeMeta) {
4936
5193
  name: "goTo",
4937
5194
  isAsync: true,
4938
5195
  parameters: [{ name: "params", type: paramType, hasQuestionToken: allOptional }],
4939
- statements: route.name !== null ? pushBlock(JSON.stringify(route.name), "params", allOptional) : [`let targetUrl = ${JSON.stringify(route.template)};`, ...paramStatements(route), ...GOTO_RUNTIME_LINES]
5196
+ statements: route.name !== null ? createRouterNavigationWriter({
5197
+ routeName: { kind: "single", target: route.name },
5198
+ input: { identifier: "params", optional: allOptional },
5199
+ pathParamNames: route.params.map((param) => param.name),
5200
+ queryNames: route.query
5201
+ }) : createUrlNavigationWriter({
5202
+ routeTemplate: { kind: "single", target: route.template },
5203
+ input: { identifier: "params", optional: allOptional },
5204
+ pathParams: route.params,
5205
+ queryNames: route.query
5206
+ })
4940
5207
  })
4941
5208
  ];
4942
5209
  }
4943
5210
  const paramlessRoute = paramless;
4944
5211
  const parametrizedRoute = parametrized;
4945
5212
  const usePush = paramlessRoute.name !== null && parametrizedRoute.name !== null;
5213
+ const paramlessType = buildNavigationTypeString(paramlessRoute);
5214
+ const parametrizedOverloadType = buildParametrizedRouteSelectionTypeString(parametrizedRoute);
5215
+ const queryNames = Array.from(/* @__PURE__ */ new Set([...paramlessRoute.query, ...parametrizedRoute.query]));
5216
+ const hasQuery = queryNames.length > 0;
5217
+ const implementationType = hasQuery ? buildImplementationNavigationTypeString([paramlessRoute, parametrizedRoute]) : paramType;
4946
5218
  return [
4947
5219
  createClassMethod({
4948
5220
  name: "goTo",
4949
5221
  isAsync: true,
4950
5222
  overloads: [
4951
- { parameters: [], returnType: "Promise<void>" },
4952
- { parameters: [{ name: "params", type: paramType }], returnType: "Promise<void>" }
5223
+ {
5224
+ parameters: paramlessRoute.query.length ? [{ name: "params", type: paramlessType, hasQuestionToken: true }] : [],
5225
+ returnType: "Promise<void>"
5226
+ },
5227
+ { parameters: [{ name: "params", type: parametrizedOverloadType }], returnType: "Promise<void>" }
4953
5228
  ],
4954
- parameters: [{ name: "params", type: paramType, hasQuestionToken: true }],
4955
- statements: usePush ? pushBlock(
4956
- `params ? ${JSON.stringify(parametrizedRoute.name)} : ${JSON.stringify(paramlessRoute.name)}`,
4957
- "params",
4958
- true
4959
- ) : [
4960
- `const template = params ? ${JSON.stringify(parametrizedRoute.template)} : ${JSON.stringify(paramlessRoute.template)};`,
4961
- "let targetUrl = template;",
4962
- `if (params) {`,
4963
- ...paramStatements(parametrizedRoute).map((line) => ` ${line}`),
4964
- "}",
4965
- ...GOTO_RUNTIME_LINES
4966
- ]
5229
+ parameters: [{ name: "params", type: implementationType, hasQuestionToken: true }],
5230
+ statements: usePush ? createRouterNavigationWriter({
5231
+ routeName: {
5232
+ kind: "dual",
5233
+ parametrizedTarget: requireRouteName(parametrizedRoute),
5234
+ paramlessTarget: requireRouteName(paramlessRoute),
5235
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5236
+ },
5237
+ input: { identifier: "params", optional: true },
5238
+ pathParamNames: parametrizedRoute.params.map((param) => param.name),
5239
+ queryNames: hasQuery ? queryNames : []
5240
+ }) : createUrlNavigationWriter({
5241
+ routeTemplate: {
5242
+ kind: "dual",
5243
+ parametrizedTarget: parametrizedRoute.template,
5244
+ paramlessTarget: paramlessRoute.template,
5245
+ selectBy: hasQuery ? "path-param-presence" : "input-presence"
5246
+ },
5247
+ input: { identifier: "params", optional: true },
5248
+ pathParams: parametrizedRoute.params,
5249
+ queryNames: hasQuery ? queryNames : []
5250
+ })
4967
5251
  })
4968
5252
  ];
4969
5253
  }
@@ -8030,1568 +8314,1571 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
8030
8314
  }
8031
8315
  };
8032
8316
  }
8033
- function summarizeHierarchyMap(componentHierarchyMap) {
8034
- let interactiveComponentCount = 0;
8035
- let dataTestIdCount = 0;
8036
- for (const dependencies of componentHierarchyMap.values()) {
8037
- const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
8038
- if (selectorCount > 0) {
8039
- interactiveComponentCount += 1;
8040
- dataTestIdCount += selectorCount;
8041
- }
8317
+ function supportsInlineTextAccessibleName(role) {
8318
+ return role === "button" || role === "radio";
8319
+ }
8320
+ function buildAccessibilityAudit(metadata, inferredRole) {
8321
+ if (!metadata || !inferredRole) {
8322
+ return void 0;
8323
+ }
8324
+ const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8325
+ const dynamicProps = new Set(metadata.dynamicProps ?? []);
8326
+ const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8327
+ let accessibleNameSource;
8328
+ const reasons = [];
8329
+ if (metadata.staticAriaLabel) {
8330
+ accessibleNameSource = "aria-label";
8331
+ } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8332
+ accessibleNameSource = "text";
8333
+ } else if (metadata.staticTitle) {
8334
+ accessibleNameSource = "title";
8335
+ } else if (hasDynamicAccessibleNameSignal) {
8336
+ accessibleNameSource = "dynamic";
8337
+ } else if (role === "input" || role === "select") {
8338
+ accessibleNameSource = "unknown";
8339
+ reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8340
+ } else {
8341
+ accessibleNameSource = "missing";
8342
+ reasons.push("No compile-time accessible-name signal was found.");
8042
8343
  }
8043
8344
  return {
8044
- entryCount: componentHierarchyMap.size,
8045
- interactiveComponentCount,
8046
- dataTestIdCount
8345
+ needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8346
+ accessibleNameSource,
8347
+ reasons,
8348
+ ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8349
+ ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8350
+ ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8351
+ ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8047
8352
  };
8048
8353
  }
8049
- function isLessRich(candidate, previous) {
8050
- if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8051
- return candidate.dataTestIdCount < previous.dataTestIdCount;
8354
+ function collectAccessibilityReviewWarnings(manifest) {
8355
+ const warnings = [];
8356
+ for (const [componentName, component] of Object.entries(manifest)) {
8357
+ for (const entry of component.entries) {
8358
+ if (!entry.accessibility?.needsReview) {
8359
+ continue;
8360
+ }
8361
+ const entryLabel = entry.generatedPropertyName ?? entry.testId;
8362
+ const reasonText = entry.accessibility.reasons.join(" ");
8363
+ warnings.push(
8364
+ `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8365
+ );
8366
+ }
8052
8367
  }
8053
- if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8054
- return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8368
+ return warnings;
8369
+ }
8370
+ function findDataTestIdProp(element, attributeName = "data-testid") {
8371
+ return element.props.find(
8372
+ (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
8373
+ );
8374
+ }
8375
+ function getTestIdFromProp(prop) {
8376
+ if (!prop) {
8377
+ return null;
8055
8378
  }
8056
- return candidate.entryCount < previous.entryCount;
8379
+ if (prop.type === compilerCore.NodeTypes.ATTRIBUTE) {
8380
+ return prop.value ? prop.value.content : null;
8381
+ }
8382
+ if (prop.type === compilerCore.NodeTypes.DIRECTIVE) {
8383
+ return prop.exp?.type === compilerCore.NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content : null;
8384
+ }
8385
+ return null;
8057
8386
  }
8058
- function createBuildProcessorPlugin(options) {
8059
- const {
8060
- componentHierarchyMap,
8061
- crossFileKeyRegistry,
8062
- vueFilesPathMap,
8063
- getPageDirs,
8064
- getComponentDirs,
8065
- getLayoutDirs,
8066
- getViewsDir,
8067
- getSourceDirs,
8068
- basePageClassPath,
8069
- normalizedBasePagePath,
8070
- generation,
8071
- projectRootRef,
8072
- nativeWrappers,
8073
- optionKeyAttribute,
8074
- excludedComponents,
8075
- getWrapperSearchRoots,
8076
- getResolvedRouterEntry,
8077
- loggerRef
8078
- } = options;
8079
- const {
8080
- outDir,
8081
- emitLanguages,
8082
- typescriptOutputStructure,
8083
- csharp,
8084
- generateFixtures,
8085
- customPomAttachments,
8086
- customPomDir,
8087
- requireCustomPomDir,
8088
- customPomImportAliases,
8089
- customPomImportNameCollisionBehavior,
8090
- testIdAttribute,
8091
- nameCollisionBehavior,
8092
- missingSemanticNameBehavior,
8093
- existingIdBehavior,
8094
- routerAwarePoms,
8095
- routerType,
8096
- routerModuleShims
8097
- } = generation;
8098
- let lastGeneratedMetrics = {
8099
- entryCount: 0,
8100
- interactiveComponentCount: 0,
8101
- dataTestIdCount: 0
8102
- };
8103
- const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
8104
- const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
8105
- const getScriptInfo = (source, filename) => {
8106
- try {
8107
- const { descriptor } = compilerSfc.parse(source, { filename });
8108
- if (!descriptor.script && !descriptor.scriptSetup)
8109
- return { bindings: void 0, isScriptSetup: false };
8110
- const scriptBlock = compilerSfc.compileScript(descriptor, { id: filename });
8111
- return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
8112
- } catch {
8113
- return { bindings: void 0, isScriptSetup: false };
8387
+ function parseDynamicProps(dynamicProps) {
8388
+ if (!dynamicProps) {
8389
+ return void 0;
8390
+ }
8391
+ if (typeof dynamicProps === "string") {
8392
+ const parts = [];
8393
+ let current = "";
8394
+ for (let i = 0; i < dynamicProps.length; i++) {
8395
+ const ch = dynamicProps[i];
8396
+ if (ch === ",") {
8397
+ const token = current.trim();
8398
+ if (token.length)
8399
+ parts.push(token);
8400
+ current = "";
8401
+ continue;
8402
+ }
8403
+ current += ch;
8114
8404
  }
8115
- };
8116
- const supplementHierarchyFromFilesystem = () => {
8117
- const walkFilesRecursive = (rootDir) => {
8118
- const out = [];
8119
- const stack = [rootDir];
8120
- while (stack.length) {
8121
- const dir = stack.pop();
8122
- if (!dir) continue;
8123
- let entries = [];
8124
- try {
8125
- entries = fs.readdirSync(dir, { withFileTypes: true });
8126
- } catch {
8127
- continue;
8128
- }
8129
- for (const ent of entries) {
8130
- if (ent.isDirectory()) {
8131
- if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8132
- continue;
8133
- stack.push(path.join(dir, ent.name));
8134
- continue;
8135
- }
8136
- if (ent.isFile() && ent.name.endsWith(".vue")) {
8137
- out.push(path.join(dir, ent.name));
8138
- }
8139
- }
8140
- }
8141
- return out;
8142
- };
8143
- let supplemented = 0;
8144
- for (const dir of getSourceDirs()) {
8145
- const absDir = path.resolve(projectRootRef.current, dir);
8146
- if (!fs.existsSync(absDir))
8147
- continue;
8148
- for (const filePath of walkFilesRecursive(absDir)) {
8149
- const absolutePath = path.resolve(filePath);
8150
- const componentName = resolveComponentNameFromPath({
8151
- filename: absolutePath,
8152
- projectRoot: projectRootRef.current,
8153
- viewsDirAbs: getViewsDirAbs(),
8154
- sourceDirs: getSourceDirs(),
8155
- extraRoots: [process.cwd()]
8156
- });
8157
- if (componentHierarchyMap.has(componentName))
8158
- continue;
8159
- let sfc = "";
8160
- try {
8161
- sfc = fs.readFileSync(absolutePath, "utf8");
8162
- } catch {
8163
- continue;
8164
- }
8165
- const { descriptor } = compilerSfc.parse(sfc, { filename: absolutePath });
8166
- const template = descriptor.template?.content ?? "";
8167
- if (!template.trim()) {
8168
- vueFilesPathMap.set(componentName, absolutePath);
8169
- componentHierarchyMap.set(componentName, {
8170
- filePath: absolutePath,
8171
- childrenComponentSet: /* @__PURE__ */ new Set(),
8172
- usedComponentSet: /* @__PURE__ */ new Set(),
8173
- dataTestIdSet: /* @__PURE__ */ new Set(),
8174
- isView: false,
8175
- methodsContent: ""
8176
- });
8177
- supplemented++;
8178
- continue;
8179
- }
8180
- const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8181
- vueFilesPathMap.set(componentName, absolutePath);
8182
- try {
8183
- compilerDom__namespace.compile(template, {
8184
- filename: absolutePath,
8185
- prefixIdentifiers: true,
8186
- inline: isScriptSetup,
8187
- bindingMetadata,
8188
- // See dev-plugin.ts — same rationale: enable TS in template
8189
- // expressions so `(row: RowType) => ...` handlers parse.
8190
- expressionPlugins: ["typescript"],
8191
- nodeTransforms: [
8192
- createTestIdTransform(
8193
- componentName,
8194
- componentHierarchyMap,
8195
- nativeWrappers,
8196
- excludedComponents,
8197
- getViewsDirAbs(),
8198
- {
8199
- existingIdBehavior: existingIdBehavior ?? "error",
8200
- testIdAttribute,
8201
- nameCollisionBehavior,
8202
- missingSemanticNameBehavior,
8203
- warn: (message) => loggerRef.current.warn(message),
8204
- vueFilesPathMap,
8205
- wrapperSearchRoots: getWrapperSearchRoots(),
8206
- crossFileKeyRegistry,
8207
- optionKeyAttribute
8208
- }
8209
- )
8210
- ]
8211
- });
8212
- } catch {
8213
- }
8214
- supplemented++;
8405
+ const last = current.trim();
8406
+ if (last.length)
8407
+ parts.push(last);
8408
+ return parts;
8409
+ }
8410
+ if (isSimpleExpressionNode(dynamicProps)) {
8411
+ const content = dynamicProps.content;
8412
+ if (content.startsWith("[") && content.endsWith("]")) {
8413
+ try {
8414
+ return JSON.parse(content);
8415
+ } catch {
8416
+ return void 0;
8215
8417
  }
8216
8418
  }
8217
- if (supplemented > 0) {
8218
- loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
8219
- }
8220
- };
8221
- return {
8222
- name: "vue-pom-generator-build",
8223
- // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
8224
- apply: "build",
8225
- enforce: "pre",
8226
- async buildStart() {
8227
- if (!routerAwarePoms) {
8228
- setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8229
- setResolveToComponentNameFn(() => null);
8230
- return;
8231
- }
8232
- let result;
8233
- if (routerType === "nuxt") {
8234
- result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8235
- } else {
8236
- const resolvedRouterEntry = getResolvedRouterEntry();
8237
- if (!resolvedRouterEntry)
8238
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8239
- result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8240
- moduleShims: routerModuleShims,
8241
- componentNaming: {
8242
- projectRoot: projectRootRef.current,
8243
- viewsDirAbs: getViewsDirAbs(),
8244
- sourceDirs: getSourceDirs()
8245
- }
8246
- });
8247
- }
8248
- const { routeNameMap, routePathMap } = result;
8249
- setRouteNameToComponentNameMap(routeNameMap);
8250
- setResolveToComponentNameFn((to) => {
8251
- if (typeof to === "string") {
8252
- return routePathMap.get(to) ?? null;
8253
- }
8254
- const maybe = to;
8255
- if (typeof maybe.name === "string" && maybe.name.length) {
8256
- const key = toPascalCase(maybe.name);
8257
- return routeNameMap.get(key) ?? null;
8258
- }
8259
- if (typeof maybe.path === "string" && maybe.path.length) {
8260
- return routePathMap.get(maybe.path) ?? null;
8419
+ return [content];
8420
+ }
8421
+ return void 0;
8422
+ }
8423
+ function findStaticAttributeValue(element, attributeName) {
8424
+ const attribute = element.props.find(
8425
+ (prop) => prop.type === compilerCore.NodeTypes.ATTRIBUTE && prop.name === attributeName
8426
+ );
8427
+ const value = attribute?.value?.content?.trim();
8428
+ return value || void 0;
8429
+ }
8430
+ function collectStaticTextContent(children) {
8431
+ const parts = [];
8432
+ const visit = (nodes) => {
8433
+ for (const node of nodes) {
8434
+ if (node.type === compilerCore.NodeTypes.TEXT) {
8435
+ const text2 = collapseWhitespace(node.content);
8436
+ if (text2) {
8437
+ parts.push(text2);
8261
8438
  }
8262
- return null;
8263
- });
8264
- if (!fs.existsSync(basePageClassPath)) {
8265
- this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
8266
- }
8267
- this.addWatchFile(basePageClassPath);
8268
- const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
8269
- if (!fs.existsSync(pointerPath)) {
8270
- this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
8271
- }
8272
- this.addWatchFile(pointerPath);
8273
- const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
8274
- if (!fs.existsSync(calloutPath)) {
8275
- this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
8276
- }
8277
- this.addWatchFile(calloutPath);
8278
- const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
8279
- if (fs.existsSync(floatingUiCalloutPath)) {
8280
- this.addWatchFile(floatingUiCalloutPath);
8281
- }
8282
- },
8283
- async buildEnd(error) {
8284
- if (error) {
8285
- return;
8286
- }
8287
- supplementHierarchyFromFilesystem();
8288
- const metrics = summarizeHierarchyMap(componentHierarchyMap);
8289
- if (metrics.dataTestIdCount <= 0) {
8290
- return;
8439
+ continue;
8291
8440
  }
8292
- if (isLessRich(metrics, lastGeneratedMetrics)) {
8293
- return;
8441
+ if (node.type === compilerCore.NodeTypes.ELEMENT) {
8442
+ visit(node.children);
8294
8443
  }
8295
- await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
8296
- outDir,
8297
- emitLanguages,
8298
- typescriptOutputStructure,
8299
- csharp,
8300
- generateFixtures,
8301
- customPomAttachments,
8302
- projectRoot: projectRootRef.current,
8303
- customPomDir,
8304
- requireCustomPomDir,
8305
- customPomImportAliases,
8306
- customPomImportNameCollisionBehavior,
8307
- testIdAttribute,
8308
- vueRouterFluentChaining: routerAwarePoms,
8309
- routerEntry: getResolvedRouterEntry(),
8310
- routerType,
8311
- pageDirs: getPageDirs(),
8312
- componentDirs: getComponentDirs(),
8313
- layoutDirs: getLayoutDirs()
8314
- });
8315
- lastGeneratedMetrics = metrics;
8316
- loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
8317
- },
8318
- closeBundle() {
8319
- loggerRef.current.info("build complete");
8320
8444
  }
8321
8445
  };
8446
+ visit(children);
8447
+ const text = collapseWhitespace(parts.join(" "));
8448
+ return text || void 0;
8322
8449
  }
8323
- function createDevProcessorPlugin(options) {
8324
- const {
8325
- nativeWrappers,
8326
- optionKeyAttribute,
8327
- excludedComponents,
8328
- getPageDirs,
8329
- getComponentDirs,
8330
- getLayoutDirs,
8331
- getViewsDir,
8332
- getSourceDirs,
8333
- getWrapperSearchRoots,
8334
- projectRootRef,
8335
- normalizedBasePagePath,
8336
- basePageClassPath,
8337
- generation,
8338
- getResolvedRouterEntry,
8339
- loggerRef
8340
- } = options;
8341
- const {
8342
- outDir,
8343
- emitLanguages,
8344
- typescriptOutputStructure,
8345
- csharp,
8346
- generateFixtures,
8347
- customPomAttachments,
8348
- customPomDir,
8349
- requireCustomPomDir,
8350
- customPomImportAliases,
8351
- customPomImportNameCollisionBehavior,
8352
- nameCollisionBehavior,
8353
- missingSemanticNameBehavior,
8354
- existingIdBehavior,
8355
- testIdAttribute,
8356
- routerAwarePoms,
8357
- routerType,
8358
- routerModuleShims
8359
- } = generation;
8360
- let scheduleVueFileRegen = null;
8361
- const getProjectRootCandidates = () => Array.from(/* @__PURE__ */ new Set([
8362
- path.resolve(projectRootRef.current),
8363
- path.resolve(process.cwd())
8450
+ function tryCreateElementMetadata(args) {
8451
+ const { element, semanticNameMap } = args;
8452
+ const testIdAttribute = (args.testIdAttribute ?? "data-testid").trim() || "data-testid";
8453
+ const testIdProp = findDataTestIdProp(element, testIdAttribute);
8454
+ if (!testIdProp) {
8455
+ return null;
8456
+ }
8457
+ const testId = getTestIdFromProp(testIdProp);
8458
+ if (!testId) {
8459
+ return null;
8460
+ }
8461
+ if (!element.codegenNode || element.codegenNode.type !== compilerCore.NodeTypes.VNODE_CALL) {
8462
+ return null;
8463
+ }
8464
+ const codegenNode = element.codegenNode;
8465
+ const patchFlag = codegenNode.patchFlag;
8466
+ let dynamicPropsList = parseDynamicProps(codegenNode.dynamicProps);
8467
+ if (!dynamicPropsList && codegenNode.dynamicProps && typeof codegenNode.dynamicProps !== "string" && isSimpleExpressionNode(codegenNode.dynamicProps)) {
8468
+ const content = codegenNode.dynamicProps.content;
8469
+ if (content.startsWith("[") && content.endsWith("]")) {
8470
+ dynamicPropsList = [content];
8471
+ }
8472
+ }
8473
+ const metadata = {
8474
+ testId,
8475
+ semanticName: semanticNameMap.get(testId),
8476
+ tag: element.tag,
8477
+ tagType: element.tagType,
8478
+ patchFlag,
8479
+ dynamicProps: dynamicPropsList,
8480
+ // Decode patch flags (bitwise) - preserved as-is from existing code.
8481
+ hasClickHandler: patchFlag ? Boolean(patchFlag & 32) : void 0,
8482
+ hasDynamicClass: patchFlag ? Boolean(patchFlag & 2) : void 0,
8483
+ hasDynamicStyle: patchFlag ? Boolean(patchFlag & 4) : void 0,
8484
+ hasDynamicText: patchFlag ? Boolean(patchFlag & 1) : void 0,
8485
+ staticAriaLabel: findStaticAttributeValue(element, "aria-label"),
8486
+ staticRole: findStaticAttributeValue(element, "role"),
8487
+ staticTitle: findStaticAttributeValue(element, "title"),
8488
+ staticTextContent: collectStaticTextContent(element.children),
8489
+ sourceLine: element.loc?.start.line,
8490
+ sourceColumn: element.loc?.start.column
8491
+ };
8492
+ return metadata;
8493
+ }
8494
+ function matchesPrimarySelector(extraMethod, pom) {
8495
+ if (extraMethod.selector.kind !== "testId") {
8496
+ return false;
8497
+ }
8498
+ return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8499
+ }
8500
+ function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8501
+ const testId = entry.selectorValue.formatted;
8502
+ const metadata = componentMetadata?.get(testId);
8503
+ const pom = entry.pom;
8504
+ const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8505
+ const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8506
+ const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8507
+ ...generatedActionName ? [generatedActionName] : [],
8508
+ ...extraActionNames.filter((name) => name !== generatedActionName)
8364
8509
  ]));
8365
- const resolveProjectPath = (maybePath) => {
8366
- if (path.isAbsolute(maybePath))
8367
- return maybePath;
8368
- const candidates = getProjectRootCandidates().map((root) => path.resolve(root, maybePath));
8369
- return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
8510
+ const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8511
+ return {
8512
+ testId,
8513
+ selectorPatternKind: entry.selectorValue.patternKind,
8514
+ semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8515
+ locatorDescription: pom ? buildPomLocatorDescription({
8516
+ componentName,
8517
+ methodName: pom.methodName,
8518
+ nativeRole: pom.nativeRole
8519
+ }) : componentName,
8520
+ inferredRole: pom?.nativeRole ?? null,
8521
+ ...accessibility ? { accessibility } : {},
8522
+ generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8523
+ generatedActionName,
8524
+ generatedActionNames,
8525
+ emitPrimary: pom?.emitPrimary !== false,
8526
+ ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8527
+ ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8528
+ ...metadata ? { sourceTagType: metadata.tagType } : {},
8529
+ ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8530
+ ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8531
+ ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8532
+ ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8533
+ ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8534
+ ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8535
+ ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8536
+ ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8370
8537
  };
8371
- const getSourceDirRoots = () => Array.from(new Set(
8372
- getProjectRootCandidates().flatMap((root) => getSourceDirs().map((dir) => path.resolve(root, dir)))
8373
- ));
8374
- const isContainedInScanDirs = (filePath) => {
8375
- const absolutePath = path.resolve(filePath);
8376
- return getSourceDirRoots().some((scanDirAbs) => isPathWithinDir(absolutePath, scanDirAbs));
8538
+ }
8539
+ function buildPomManifest(componentHierarchyMap, elementMetadata) {
8540
+ const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8541
+ 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 ?? []));
8542
+ if (!entries.length) {
8543
+ return null;
8544
+ }
8545
+ return [componentName, {
8546
+ componentName,
8547
+ className: componentName,
8548
+ sourceFile: dependencies.filePath,
8549
+ kind: dependencies.isView ? "view" : "component",
8550
+ testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8551
+ entries
8552
+ }];
8553
+ }).filter((entry) => entry !== null);
8554
+ return Object.fromEntries(manifestEntries);
8555
+ }
8556
+ function buildTestIdManifest(componentHierarchyMap) {
8557
+ return Object.fromEntries(
8558
+ Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8559
+ const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8560
+ if (!testIds.length) {
8561
+ return null;
8562
+ }
8563
+ return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8564
+ }).filter((entry) => entry !== null)
8565
+ );
8566
+ }
8567
+ function writeConstJson(value) {
8568
+ return (writer) => {
8569
+ writer.write(`${JSON.stringify(value, null, 2)} as const`);
8377
8570
  };
8378
- return {
8379
- name: "vue-pom-generator-dev",
8380
- apply: "serve",
8381
- // Prefer hot-update events over filesystem change events for speed and reliability.
8382
- // This fires when Vite has actually processed the module update.
8383
- handleHotUpdate(ctx) {
8384
- if (!scheduleVueFileRegen)
8385
- return;
8386
- if (!ctx.file.endsWith(".vue"))
8387
- return;
8388
- if (!isContainedInScanDirs(ctx.file))
8389
- return;
8390
- scheduleVueFileRegen(ctx.file, "hmr");
8391
- },
8392
- async configureServer(server) {
8393
- const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
8394
- const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
8395
- const routerInitPromise = (async () => {
8396
- if (!routerAwarePoms) {
8397
- setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8398
- setResolveToComponentNameFn(() => null);
8399
- return;
8571
+ }
8572
+ function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8573
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8574
+ const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8575
+ return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8576
+ sourceFile.addStatements("// Virtual module: test id manifest");
8577
+ sourceFile.addVariableStatement({
8578
+ declarationKind: tsMorph.VariableDeclarationKind.Const,
8579
+ isExported: true,
8580
+ declarations: [{
8581
+ name: "testIdManifest",
8582
+ initializer: writeConstJson(testIdManifest)
8583
+ }]
8584
+ });
8585
+ sourceFile.addVariableStatement({
8586
+ declarationKind: tsMorph.VariableDeclarationKind.Const,
8587
+ isExported: true,
8588
+ declarations: [{
8589
+ name: "pomManifest",
8590
+ initializer: writeConstJson(pomManifest)
8591
+ }]
8592
+ });
8593
+ sourceFile.addTypeAlias({
8594
+ isExported: true,
8595
+ name: "TestIdManifest",
8596
+ type: "typeof testIdManifest"
8597
+ });
8598
+ sourceFile.addTypeAlias({
8599
+ isExported: true,
8600
+ name: "ComponentName",
8601
+ type: "keyof TestIdManifest"
8602
+ });
8603
+ sourceFile.addTypeAlias({
8604
+ isExported: true,
8605
+ name: "PomManifest",
8606
+ type: "typeof pomManifest"
8607
+ });
8608
+ sourceFile.addTypeAlias({
8609
+ isExported: true,
8610
+ name: "PomManifestComponentName",
8611
+ type: "keyof PomManifest"
8612
+ });
8613
+ });
8614
+ }
8615
+ function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8616
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8617
+ return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8618
+ sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8619
+ sourceFile.addVariableStatement({
8620
+ declarationKind: tsMorph.VariableDeclarationKind.Const,
8621
+ isExported: true,
8622
+ declarations: [{
8623
+ name: "pomManifest",
8624
+ initializer: writeConstJson(pomManifest)
8625
+ }]
8626
+ });
8627
+ sourceFile.addTypeAlias({
8628
+ isExported: true,
8629
+ name: "PomManifest",
8630
+ type: "typeof pomManifest"
8631
+ });
8632
+ sourceFile.addTypeAlias({
8633
+ isExported: true,
8634
+ name: "PomManifestComponentName",
8635
+ type: "keyof PomManifest"
8636
+ });
8637
+ });
8638
+ }
8639
+ function resolveExistingIdBehavior(config, componentName) {
8640
+ return typeof config === "string" ? config : config.components[componentName] ?? config.default;
8641
+ }
8642
+ function resolveCompilerSfcParse(compilerSfc2) {
8643
+ const parse = compilerSfc2.parse ?? compilerSfc2.default?.parse;
8644
+ if (typeof parse !== "function") {
8645
+ throw new TypeError("[vue-pom-generator] Failed to resolve @vue/compiler-sfc.parse.");
8646
+ }
8647
+ return parse;
8648
+ }
8649
+ function extractMetadataAfterTransform(ast, componentName, elementMetadata, semanticNameMap, testIdAttribute) {
8650
+ const componentMetadata = /* @__PURE__ */ new Map();
8651
+ function traverseNode(node) {
8652
+ if (node.type === compilerCore.NodeTypes.ELEMENT) {
8653
+ const element = node;
8654
+ const testIdAttr = findDataTestIdProp(element, testIdAttribute);
8655
+ if (testIdAttr) {
8656
+ const metadata = tryCreateElementMetadata({
8657
+ element,
8658
+ semanticNameMap,
8659
+ testIdAttribute
8660
+ });
8661
+ if (metadata) {
8662
+ componentMetadata.set(metadata.testId, metadata);
8400
8663
  }
8401
- let result;
8402
- if (routerType === "nuxt") {
8403
- result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8404
- } else {
8405
- const resolvedRouterEntry = getResolvedRouterEntry();
8406
- if (!resolvedRouterEntry)
8407
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8408
- result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8409
- moduleShims: routerModuleShims,
8410
- componentNaming: {
8411
- projectRoot: projectRootRef.current,
8412
- viewsDirAbs: getViewsDirAbs(),
8413
- sourceDirs: getSourceDirs(),
8414
- extraRoots: [process.cwd()]
8415
- }
8416
- });
8417
- }
8418
- const { routeNameMap, routePathMap } = result;
8419
- setRouteNameToComponentNameMap(routeNameMap);
8420
- setResolveToComponentNameFn((to) => {
8421
- if (typeof to === "string") {
8422
- return routePathMap.get(to) ?? null;
8423
- }
8424
- const maybe = to;
8425
- if (typeof maybe.name === "string" && maybe.name.length) {
8426
- const key = toPascalCase(maybe.name);
8427
- return routeNameMap.get(key) ?? null;
8428
- }
8429
- if (typeof maybe.path === "string" && maybe.path.length) {
8430
- return routePathMap.get(maybe.path) ?? null;
8431
- }
8432
- return null;
8433
- });
8434
- })();
8435
- const logInfo = (message) => loggerRef.current.info(message);
8436
- const logDebug = (message) => loggerRef.current.debug(message);
8437
- let scheduleVueFileRegenLocal = null;
8438
- const formatMs = (ms) => `${ms.toFixed(1)}ms`;
8439
- const extractTemplateFromSfc = (source, filename) => {
8440
- const { descriptor } = compilerSfc.parse(source, {
8441
- filename: filename ?? "anonymous.vue"
8442
- });
8443
- return descriptor.template?.content ?? "";
8444
- };
8445
- const getScriptInfo = (source, filename) => {
8446
- try {
8447
- const { descriptor } = compilerSfc.parse(source, { filename });
8448
- if (!descriptor.script && !descriptor.scriptSetup)
8449
- return { bindings: void 0, isScriptSetup: false };
8450
- const scriptBlock = compilerSfc.compileScript(descriptor, { id: filename });
8451
- return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
8452
- } catch {
8453
- return { bindings: void 0, isScriptSetup: false };
8454
- }
8455
- };
8456
- const walkFilesRecursive = (rootDir) => {
8457
- const out = [];
8458
- const stack = [rootDir];
8459
- while (stack.length) {
8460
- const dir = stack.pop();
8461
- if (!dir) continue;
8462
- let entries = [];
8463
- try {
8464
- entries = fs.readdirSync(dir, { withFileTypes: true });
8465
- } catch {
8466
- continue;
8467
- }
8468
- for (const ent of entries) {
8469
- if (ent.isDirectory()) {
8470
- if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8471
- continue;
8472
- stack.push(path.join(dir, ent.name));
8473
- continue;
8474
- }
8475
- if (ent.isFile() && ent.name.endsWith(".vue")) {
8476
- out.push(path.join(dir, ent.name));
8477
- }
8478
- }
8479
- }
8480
- return out;
8481
- };
8482
- let snapshotHierarchy = /* @__PURE__ */ new Map();
8483
- let snapshotVuePathMap = /* @__PURE__ */ new Map();
8484
- const filePathToComponentName = /* @__PURE__ */ new Map();
8485
- const createEmptyComponentDependencies = (absolutePath) => {
8486
- const viewsDirAbs = path.resolve(getViewsDirAbs());
8487
- const relToViewsDir = path.relative(viewsDirAbs, absolutePath);
8488
- const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
8489
- return {
8490
- filePath: absolutePath,
8491
- childrenComponentSet: /* @__PURE__ */ new Set(),
8492
- usedComponentSet: /* @__PURE__ */ new Set(),
8493
- dataTestIdSet: /* @__PURE__ */ new Set(),
8494
- isView,
8495
- methodsContent: ""
8496
- };
8497
- };
8498
- const getComponentNameForFile = (filePath) => {
8499
- const normalized = path.resolve(filePath);
8500
- const existing = filePathToComponentName.get(normalized);
8501
- if (existing)
8502
- return existing;
8503
- const name = resolveComponentNameFromPath({
8504
- filename: normalized,
8505
- projectRoot: projectRootRef.current,
8506
- viewsDirAbs: getViewsDirAbs(),
8507
- sourceDirs: getSourceDirs(),
8508
- extraRoots: [process.cwd()]
8509
- });
8510
- filePathToComponentName.set(normalized, name);
8511
- return name;
8512
- };
8513
- const compileVueFileIntoSnapshot = (filePath, targetHierarchy = snapshotHierarchy, targetVuePathMap = snapshotVuePathMap) => {
8514
- const started = node_perf_hooks.performance.now();
8515
- const absolutePath = path.resolve(filePath);
8516
- const componentName = getComponentNameForFile(absolutePath);
8517
- let sfc = "";
8518
- try {
8519
- sfc = fs.readFileSync(absolutePath, "utf8");
8520
- } catch {
8521
- return { componentName, ms: node_perf_hooks.performance.now() - started, compiled: false };
8664
+ }
8665
+ if (element.children) {
8666
+ for (const child of element.children) {
8667
+ traverseNode(child);
8522
8668
  }
8523
- const template = extractTemplateFromSfc(sfc, absolutePath);
8524
- if (!template.trim()) {
8525
- targetVuePathMap.set(componentName, absolutePath);
8526
- targetHierarchy.set(componentName, createEmptyComponentDependencies(absolutePath));
8527
- return { componentName, ms: node_perf_hooks.performance.now() - started, compiled: true };
8669
+ }
8670
+ } else if (node.type === compilerCore.NodeTypes.IF) {
8671
+ for (const branch of node.branches) {
8672
+ traverseNode(branch);
8673
+ }
8674
+ } else if (node.type === compilerCore.NodeTypes.IF_BRANCH || node.type === compilerCore.NodeTypes.FOR) {
8675
+ if (node.children) {
8676
+ for (const child of node.children) {
8677
+ traverseNode(child);
8528
8678
  }
8529
- const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8530
- const provisionalHierarchy = /* @__PURE__ */ new Map();
8531
- const provisionalKeyRegistry = /* @__PURE__ */ new Map();
8532
- const provisionalVuePathMap = new Map(targetVuePathMap);
8533
- provisionalVuePathMap.set(componentName, absolutePath);
8534
- compilerDom__namespace.compile(template, {
8535
- filename: absolutePath,
8536
- prefixIdentifiers: true,
8537
- inline: isScriptSetup,
8538
- bindingMetadata,
8539
- // Vue templates may contain TypeScript type annotations in expressions
8540
- // (e.g. `@row-click="(row: RowType) => navigateTo(...)"` in Nuxt + TS
8541
- // apps). Without this flag, Vue's internal processExpression step
8542
- // delegates to @babel/parser without the TS plugin and crashes on
8543
- // "Unexpected token, expected ','".
8544
- expressionPlugins: ["typescript"],
8545
- nodeTransforms: [
8679
+ }
8680
+ } else if (node.type === compilerCore.NodeTypes.ROOT) {
8681
+ for (const child of node.children) {
8682
+ traverseNode(child);
8683
+ }
8684
+ }
8685
+ }
8686
+ traverseNode(ast);
8687
+ if (componentMetadata.size > 0) {
8688
+ elementMetadata.set(componentName, componentMetadata);
8689
+ }
8690
+ return componentMetadata;
8691
+ }
8692
+ function createVuePluginWithTestIds(options) {
8693
+ const {
8694
+ vueOptions,
8695
+ existingIdBehavior,
8696
+ nameCollisionBehavior,
8697
+ missingSemanticNameBehavior = "error",
8698
+ nativeWrappers,
8699
+ optionKeyAttribute,
8700
+ elementMetadata,
8701
+ semanticNameMap,
8702
+ componentHierarchyMap,
8703
+ crossFileKeyRegistry,
8704
+ vueFilesPathMap,
8705
+ excludedComponents,
8706
+ getViewsDirAbs,
8707
+ testIdAttribute,
8708
+ accessibilityAudit,
8709
+ loggerRef,
8710
+ getSourceDirs,
8711
+ getWrapperSearchRoots,
8712
+ getProjectRoot,
8713
+ annotatorMetadata
8714
+ } = options;
8715
+ const lastAccessibilityWarningSignatureByComponent = /* @__PURE__ */ new Map();
8716
+ const getComponentNameFromPath = (filename) => {
8717
+ return resolveComponentNameFromPath({
8718
+ filename,
8719
+ projectRoot: getProjectRoot(),
8720
+ viewsDirAbs: getViewsDirAbs(),
8721
+ sourceDirs: getSourceDirs(),
8722
+ extraRoots: [process.cwd()]
8723
+ });
8724
+ };
8725
+ const isFileInScope = (filename) => {
8726
+ if (!filename)
8727
+ return false;
8728
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8729
+ const projectRoot = getProjectRoot();
8730
+ const matched = isFileInConfiguredSourceScope({
8731
+ filename,
8732
+ projectRoot,
8733
+ viewsDirAbs: getViewsDirAbs(),
8734
+ sourceDirs: getSourceDirs(),
8735
+ extraRoots: [process.cwd()]
8736
+ });
8737
+ if (cleanPath.endsWith(".vue") && !matched) {
8738
+ const absFilename = path.normalize(path.isAbsolute(cleanPath) ? cleanPath : path.resolve(projectRoot, cleanPath));
8739
+ loggerRef.current.debug(`[isFileInScope] REJECTED: ${absFilename} (Clean: ${cleanPath})`);
8740
+ }
8741
+ return matched;
8742
+ };
8743
+ const userTemplate = vueOptions?.template ?? {};
8744
+ const userCompilerOptions = userTemplate.compilerOptions ?? {};
8745
+ const userNodeTransforms = userCompilerOptions.nodeTransforms ?? [];
8746
+ const perFileTransform = /* @__PURE__ */ new Map();
8747
+ const getNodeTransforms = (filename, componentNameOverride) => {
8748
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8749
+ const viewsDirAbs = getViewsDirAbs();
8750
+ const componentName = componentNameOverride || getComponentNameFromPath(cleanPath);
8751
+ return [
8752
+ ...userNodeTransforms,
8753
+ (node, context) => {
8754
+ if (node.type === compilerCore.NodeTypes.ROOT) {
8755
+ componentHierarchyMap.delete(componentName);
8756
+ vueFilesPathMap.set(componentName, filename);
8757
+ perFileTransform.set(
8758
+ componentName,
8546
8759
  createTestIdTransform(
8547
8760
  componentName,
8548
- provisionalHierarchy,
8761
+ componentHierarchyMap,
8549
8762
  nativeWrappers,
8550
8763
  excludedComponents,
8551
- getViewsDirAbs(),
8764
+ viewsDirAbs,
8552
8765
  {
8553
- existingIdBehavior: existingIdBehavior ?? "error",
8766
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8767
+ testIdAttribute,
8554
8768
  nameCollisionBehavior,
8555
8769
  missingSemanticNameBehavior,
8556
- testIdAttribute,
8557
8770
  warn: (message) => loggerRef.current.warn(message),
8558
- vueFilesPathMap: provisionalVuePathMap,
8771
+ vueFilesPathMap,
8559
8772
  wrapperSearchRoots: getWrapperSearchRoots(),
8560
- crossFileKeyRegistry: provisionalKeyRegistry,
8773
+ annotatorMetadata,
8774
+ crossFileKeyRegistry,
8561
8775
  optionKeyAttribute
8562
8776
  }
8563
8777
  )
8564
- ]
8565
- });
8566
- targetVuePathMap.set(componentName, absolutePath);
8567
- targetHierarchy.set(
8568
- componentName,
8569
- provisionalHierarchy.get(componentName) ?? createEmptyComponentDependencies(absolutePath)
8570
- );
8571
- return { componentName, ms: node_perf_hooks.performance.now() - started, compiled: true };
8572
- };
8573
- const fullRebuildSnapshotFromFilesystem = (logLabel) => {
8574
- const t0 = node_perf_hooks.performance.now();
8575
- const nextHierarchy = /* @__PURE__ */ new Map();
8576
- const nextVuePathMap = /* @__PURE__ */ new Map();
8577
- filePathToComponentName.clear();
8578
- let totalVueFiles = 0;
8579
- let compiledCount = 0;
8580
- for (const absDir of getSourceDirRoots()) {
8581
- if (!fs.existsSync(absDir))
8582
- continue;
8583
- const vueFiles = walkFilesRecursive(absDir);
8584
- totalVueFiles += vueFiles.length;
8585
- for (const file of vueFiles) {
8586
- const res = compileVueFileIntoSnapshot(file, nextHierarchy, nextVuePathMap);
8587
- if (res.compiled)
8588
- compiledCount++;
8589
- }
8590
- }
8591
- snapshotHierarchy = nextHierarchy;
8592
- snapshotVuePathMap = nextVuePathMap;
8593
- const t1 = node_perf_hooks.performance.now();
8594
- logInfo(`scan(${logLabel}): found ${totalVueFiles} .vue files in ${getSourceDirs().join(", ")}`);
8595
- logInfo(`compile(${logLabel}): ${compiledCount}/${totalVueFiles} files in ${formatMs(t1 - t0)} (components=${snapshotHierarchy.size})`);
8596
- };
8597
- const generateAggregatedFromSnapshot = async (logLabel) => {
8598
- const t0 = node_perf_hooks.performance.now();
8599
- await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
8600
- outDir,
8601
- emitLanguages,
8602
- typescriptOutputStructure,
8603
- csharp,
8604
- generateFixtures,
8605
- customPomAttachments,
8606
- projectRoot: projectRootRef.current,
8607
- customPomDir,
8608
- requireCustomPomDir,
8609
- customPomImportAliases,
8610
- customPomImportNameCollisionBehavior,
8611
- pageDirs: getPageDirs(),
8612
- componentDirs: getComponentDirs(),
8613
- layoutDirs: getLayoutDirs(),
8614
- testIdAttribute,
8615
- vueRouterFluentChaining: routerAwarePoms,
8616
- routerEntry: getResolvedRouterEntry(),
8617
- routerType
8618
- });
8619
- const t1 = node_perf_hooks.performance.now();
8620
- logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
8621
- };
8622
- let timer = null;
8623
- let maxWaitTimer = null;
8624
- const pendingChangedVueFiles = /* @__PURE__ */ new Set();
8625
- const pendingDeletedComponents = /* @__PURE__ */ new Set();
8626
- let regenerationSequence = Promise.resolve();
8627
- const initialBuildPromise = (async () => {
8628
- const t0 = node_perf_hooks.performance.now();
8629
- await routerInitPromise;
8630
- fullRebuildSnapshotFromFilesystem("startup");
8631
- await generateAggregatedFromSnapshot("startup");
8632
- const t1 = node_perf_hooks.performance.now();
8633
- logInfo(`startup total: ${formatMs(t1 - t0)}`);
8634
- })();
8635
- const logGenerationError = (reason, message) => {
8636
- server.config.logger.error(`[vue-pom-generator] dev generation failed during ${reason}: ${message}`);
8637
- };
8638
- const regenerateFromPending = async (reason) => {
8639
- const t0 = node_perf_hooks.performance.now();
8640
- await initialBuildPromise;
8641
- const nextHierarchy = new Map(snapshotHierarchy);
8642
- const nextVuePathMap = new Map(snapshotVuePathMap);
8643
- for (const componentName of pendingDeletedComponents) {
8644
- nextHierarchy.delete(componentName);
8645
- nextVuePathMap.delete(componentName);
8646
- }
8647
- const files = Array.from(pendingChangedVueFiles);
8648
- const deletedCount = pendingDeletedComponents.size;
8649
- pendingChangedVueFiles.clear();
8650
- pendingDeletedComponents.clear();
8651
- let compileMs = 0;
8652
- for (const f of files) {
8653
- const res = compileVueFileIntoSnapshot(f, nextHierarchy, nextVuePathMap);
8654
- compileMs += res.ms;
8655
- }
8656
- snapshotHierarchy = nextHierarchy;
8657
- snapshotVuePathMap = nextVuePathMap;
8658
- const t1 = node_perf_hooks.performance.now();
8659
- await generateAggregatedFromSnapshot(reason);
8660
- const t2 = node_perf_hooks.performance.now();
8661
- return {
8662
- files,
8663
- deletedCount,
8664
- compileMs,
8665
- preGenerateMs: t1 - t0,
8666
- generateMs: t2 - t1,
8667
- totalMs: t2 - t0
8668
- };
8669
- };
8670
- const enqueueRegeneration = (reason) => {
8671
- const currentRun = regenerationSequence.catch(() => void 0).then(() => regenerateFromPending(reason));
8672
- regenerationSequence = currentRun.then(() => void 0, () => void 0);
8673
- return currentRun;
8674
- };
8675
- const runtimeDir = path.dirname(basePageClassPath);
8676
- const localPluginDir = path.resolve(projectRootRef.current, "vite-plugins", "vue-pom-generator");
8677
- server.watcher.add([
8678
- ...fs.existsSync(localPluginDir) ? [localPluginDir] : [],
8679
- basePageClassPath,
8680
- path.resolve(runtimeDir, "pointer.ts"),
8681
- path.resolve(runtimeDir, "callout.ts"),
8682
- path.resolve(runtimeDir, "floating-ui-callout.ts")
8683
- ]);
8684
- scheduleVueFileRegenLocal = (filePath, source) => {
8685
- pendingChangedVueFiles.add(filePath);
8686
- logDebug(`queued(${source}): files=${pendingChangedVueFiles.size} deleted=${pendingDeletedComponents.size}`);
8687
- scheduleAggregatedRegen();
8688
- };
8689
- scheduleVueFileRegen = scheduleVueFileRegenLocal;
8690
- function scheduleAggregatedRegen() {
8691
- const wasEmpty = pendingChangedVueFiles.size === 0 && pendingDeletedComponents.size === 0;
8692
- const MAX_WAIT_MS = 750;
8693
- if (!maxWaitTimer) {
8694
- maxWaitTimer = setTimeout(() => {
8695
- if (timer) {
8696
- clearTimeout(timer);
8697
- timer = null;
8778
+ );
8779
+ return () => {
8780
+ const componentMetadata = extractMetadataAfterTransform(
8781
+ node,
8782
+ componentName,
8783
+ elementMetadata,
8784
+ semanticNameMap,
8785
+ testIdAttribute
8786
+ );
8787
+ if (!accessibilityAudit) {
8788
+ return;
8698
8789
  }
8699
- maxWaitTimer = null;
8700
- void enqueueRegeneration("max-wait").then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
8701
- logInfo(
8702
- `max-wait: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
8703
- );
8704
- }).catch((error) => {
8705
- const message = error instanceof Error ? error.message : String(error);
8706
- logGenerationError("max-wait", message);
8707
- });
8708
- }, MAX_WAIT_MS);
8709
- }
8710
- if (wasEmpty) {
8711
- const queuedFiles = pendingChangedVueFiles.size;
8712
- const queuedDeletes = pendingDeletedComponents.size;
8713
- logDebug(`queued: files=${queuedFiles} deleted=${queuedDeletes}`);
8714
- }
8715
- if (timer)
8716
- clearTimeout(timer);
8717
- timer = setTimeout(() => {
8718
- timer = null;
8719
- if (maxWaitTimer) {
8720
- clearTimeout(maxWaitTimer);
8721
- maxWaitTimer = null;
8722
- }
8723
- const reason = pendingChangedVueFiles.size || pendingDeletedComponents.size ? "batched" : "noop";
8724
- void enqueueRegeneration(reason).then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
8725
- if (files.length || deletedCount) {
8726
- logInfo(
8727
- `batched: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
8728
- );
8790
+ const dependencies = componentHierarchyMap.get(componentName);
8791
+ if (!dependencies || componentMetadata.size === 0) {
8792
+ return;
8729
8793
  }
8730
- }).catch((error) => {
8731
- const message = error instanceof Error ? error.message : String(error);
8732
- logGenerationError(reason, message);
8733
- });
8734
- }, 75);
8735
- }
8736
- server.watcher.on("change", async (changedPath) => {
8737
- const changedAbsPosix = path.posix.normalize(path.resolve(changedPath));
8738
- const outDirAbsPosix = path.posix.normalize(path.resolve(projectRootRef.current, outDir ?? "./pom"));
8739
- if (changedAbsPosix.startsWith(`${outDirAbsPosix}/`) && (changedAbsPosix.endsWith(".g.ts") || changedAbsPosix.endsWith(".g.ts.map"))) {
8740
- return;
8794
+ const manifest = buildPomManifest(
8795
+ /* @__PURE__ */ new Map([[componentName, dependencies]]),
8796
+ /* @__PURE__ */ new Map([[componentName, componentMetadata]])
8797
+ );
8798
+ const warnings = collectAccessibilityReviewWarnings(manifest);
8799
+ const signature = warnings.join("\n");
8800
+ if (!signature) {
8801
+ lastAccessibilityWarningSignatureByComponent.delete(componentName);
8802
+ return;
8803
+ }
8804
+ if (lastAccessibilityWarningSignatureByComponent.get(componentName) === signature) {
8805
+ return;
8806
+ }
8807
+ lastAccessibilityWarningSignatureByComponent.set(componentName, signature);
8808
+ for (const warning of warnings) {
8809
+ loggerRef.current.warn(warning);
8810
+ }
8811
+ };
8741
8812
  }
8742
- if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
8743
- void server.restart();
8813
+ let transform = perFileTransform.get(componentName);
8814
+ if (!transform) {
8815
+ componentHierarchyMap.delete(componentName);
8816
+ vueFilesPathMap.set(componentName, filename);
8817
+ transform = createTestIdTransform(
8818
+ componentName,
8819
+ componentHierarchyMap,
8820
+ nativeWrappers,
8821
+ excludedComponents,
8822
+ viewsDirAbs,
8823
+ {
8824
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8825
+ testIdAttribute,
8826
+ nameCollisionBehavior,
8827
+ missingSemanticNameBehavior,
8828
+ warn: (message) => loggerRef.current.warn(message),
8829
+ vueFilesPathMap,
8830
+ wrapperSearchRoots: getWrapperSearchRoots(),
8831
+ annotatorMetadata,
8832
+ crossFileKeyRegistry,
8833
+ optionKeyAttribute
8834
+ }
8835
+ );
8836
+ perFileTransform.set(componentName, transform);
8744
8837
  }
8745
- });
8746
- server.watcher.on("add", (p) => {
8747
- if (typeof p !== "string")
8748
- return;
8749
- if (!p.endsWith(".vue"))
8750
- return;
8751
- if (!isContainedInScanDirs(p))
8752
- return;
8753
- void (async () => {
8754
- await initialBuildPromise;
8755
- pendingChangedVueFiles.add(p);
8756
- scheduleAggregatedRegen();
8757
- })();
8758
- });
8759
- server.watcher.on("unlink", (p) => {
8760
- if (typeof p !== "string")
8761
- return;
8762
- if (!p.endsWith(".vue"))
8763
- return;
8764
- if (!isContainedInScanDirs(p))
8765
- return;
8766
- void (async () => {
8767
- await initialBuildPromise;
8768
- const absolutePath = path.resolve(p);
8769
- const componentName = getComponentNameForFile(absolutePath);
8770
- filePathToComponentName.delete(absolutePath);
8771
- pendingDeletedComponents.add(componentName);
8772
- scheduleAggregatedRegen();
8773
- })();
8774
- });
8775
- setTimeout(() => {
8776
- }, 250);
8777
- await initialBuildPromise;
8778
- }
8838
+ return transform(node, context);
8839
+ }
8840
+ ];
8779
8841
  };
8780
- }
8781
- function supportsInlineTextAccessibleName(role) {
8782
- return role === "button" || role === "radio";
8783
- }
8784
- function buildAccessibilityAudit(metadata, inferredRole) {
8785
- if (!metadata || !inferredRole) {
8786
- return void 0;
8787
- }
8788
- const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8789
- const dynamicProps = new Set(metadata.dynamicProps ?? []);
8790
- const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8791
- let accessibleNameSource;
8792
- const reasons = [];
8793
- if (metadata.staticAriaLabel) {
8794
- accessibleNameSource = "aria-label";
8795
- } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8796
- accessibleNameSource = "text";
8797
- } else if (metadata.staticTitle) {
8798
- accessibleNameSource = "title";
8799
- } else if (hasDynamicAccessibleNameSignal) {
8800
- accessibleNameSource = "dynamic";
8801
- } else if (role === "input" || role === "select") {
8802
- accessibleNameSource = "unknown";
8803
- reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8804
- } else {
8805
- accessibleNameSource = "missing";
8806
- reasons.push("No compile-time accessible-name signal was found.");
8807
- }
8808
- return {
8809
- needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8810
- accessibleNameSource,
8811
- reasons,
8812
- ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8813
- ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8814
- ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8815
- ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8842
+ const runtimeNodeTransform = (node, context) => {
8843
+ const filename = context.filename;
8844
+ if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
8845
+ return;
8846
+ }
8847
+ const transforms = getNodeTransforms(filename);
8848
+ const ourTransform = transforms[transforms.length - 1];
8849
+ return ourTransform(node, context);
8816
8850
  };
8817
- }
8818
- function collectAccessibilityReviewWarnings(manifest) {
8819
- const warnings = [];
8820
- for (const [componentName, component] of Object.entries(manifest)) {
8821
- for (const entry of component.entries) {
8822
- if (!entry.accessibility?.needsReview) {
8823
- continue;
8851
+ const templateCompilerOptions = {
8852
+ ...userCompilerOptions,
8853
+ prefixIdentifiers: true,
8854
+ nodeTransforms: [
8855
+ ...userNodeTransforms,
8856
+ runtimeNodeTransform
8857
+ ]
8858
+ };
8859
+ const metadataCollectorPlugin = {
8860
+ name: "vue-pom-generator-metadata-collector",
8861
+ enforce: "pre",
8862
+ async transform(code, id) {
8863
+ const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
8864
+ if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
8865
+ return null;
8824
8866
  }
8825
- const entryLabel = entry.generatedPropertyName ?? entry.testId;
8826
- const reasonText = entry.accessibility.reasons.join(" ");
8827
- warnings.push(
8828
- `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8829
- );
8867
+ if (id !== cleanPath) {
8868
+ return null;
8869
+ }
8870
+ const componentName = getComponentNameFromPath(cleanPath);
8871
+ loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
8872
+ const compilerSfc2 = await import("@vue/compiler-sfc");
8873
+ const parse = resolveCompilerSfcParse(compilerSfc2);
8874
+ const compilerDom2 = await import("@vue/compiler-dom");
8875
+ const compile = compilerDom2.compile;
8876
+ const { descriptor } = parse(code, { filename: cleanPath });
8877
+ if (descriptor.template) {
8878
+ const mergedExpressionPlugins = Array.from(
8879
+ /* @__PURE__ */ new Set([
8880
+ "typescript",
8881
+ ...userCompilerOptions.expressionPlugins ?? []
8882
+ ])
8883
+ );
8884
+ compile(descriptor.template.content, {
8885
+ ...userCompilerOptions,
8886
+ filename: cleanPath,
8887
+ expressionPlugins: mergedExpressionPlugins,
8888
+ nodeTransforms: getNodeTransforms(cleanPath, componentName)
8889
+ });
8890
+ loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
8891
+ }
8892
+ return null;
8830
8893
  }
8831
- }
8832
- return warnings;
8894
+ };
8895
+ const template = {
8896
+ ...userTemplate,
8897
+ compilerOptions: templateCompilerOptions
8898
+ };
8899
+ const internalVuePlugin = vue({
8900
+ ...vueOptions,
8901
+ template
8902
+ });
8903
+ const nuxtVueBridgePlugin = {
8904
+ name: "vue-pom-generator-nuxt-vue-bridge",
8905
+ apply: "serve",
8906
+ configResolved(config) {
8907
+ const viteVuePlugin = config.plugins.find((plugin) => {
8908
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
8909
+ });
8910
+ const api = viteVuePlugin?.api;
8911
+ if (!api) {
8912
+ throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
8913
+ }
8914
+ const currentOptions = api.options ?? {};
8915
+ const currentTemplate = currentOptions.template ?? {};
8916
+ const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
8917
+ const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
8918
+ if (currentNodeTransforms.includes(runtimeNodeTransform)) {
8919
+ return;
8920
+ }
8921
+ api.options = {
8922
+ ...currentOptions,
8923
+ template: {
8924
+ ...currentTemplate,
8925
+ compilerOptions: {
8926
+ ...currentCompilerOptions,
8927
+ prefixIdentifiers: true,
8928
+ nodeTransforms: [
8929
+ ...currentNodeTransforms,
8930
+ runtimeNodeTransform
8931
+ ]
8932
+ }
8933
+ }
8934
+ };
8935
+ }
8936
+ };
8937
+ return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
8833
8938
  }
8834
- function matchesPrimarySelector(extraMethod, pom) {
8835
- if (extraMethod.selector.kind !== "testId") {
8836
- return false;
8939
+ function summarizeHierarchyMap(componentHierarchyMap) {
8940
+ let interactiveComponentCount = 0;
8941
+ let dataTestIdCount = 0;
8942
+ for (const dependencies of componentHierarchyMap.values()) {
8943
+ const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
8944
+ if (selectorCount > 0) {
8945
+ interactiveComponentCount += 1;
8946
+ dataTestIdCount += selectorCount;
8947
+ }
8837
8948
  }
8838
- return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8839
- }
8840
- function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8841
- const testId = entry.selectorValue.formatted;
8842
- const metadata = componentMetadata?.get(testId);
8843
- const pom = entry.pom;
8844
- const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8845
- const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8846
- const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8847
- ...generatedActionName ? [generatedActionName] : [],
8848
- ...extraActionNames.filter((name) => name !== generatedActionName)
8849
- ]));
8850
- const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8851
8949
  return {
8852
- testId,
8853
- selectorPatternKind: entry.selectorValue.patternKind,
8854
- semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8855
- locatorDescription: pom ? buildPomLocatorDescription({
8856
- componentName,
8857
- methodName: pom.methodName,
8858
- nativeRole: pom.nativeRole
8859
- }) : componentName,
8860
- inferredRole: pom?.nativeRole ?? null,
8861
- ...accessibility ? { accessibility } : {},
8862
- generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8863
- generatedActionName,
8864
- generatedActionNames,
8865
- emitPrimary: pom?.emitPrimary !== false,
8866
- ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8867
- ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8868
- ...metadata ? { sourceTagType: metadata.tagType } : {},
8869
- ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8870
- ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8871
- ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8872
- ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8873
- ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8874
- ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8875
- ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8876
- ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8950
+ entryCount: componentHierarchyMap.size,
8951
+ interactiveComponentCount,
8952
+ dataTestIdCount
8877
8953
  };
8878
8954
  }
8879
- function buildPomManifest(componentHierarchyMap, elementMetadata) {
8880
- const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8881
- 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 ?? []));
8882
- if (!entries.length) {
8883
- return null;
8884
- }
8885
- return [componentName, {
8886
- componentName,
8887
- className: componentName,
8888
- sourceFile: dependencies.filePath,
8889
- kind: dependencies.isView ? "view" : "component",
8890
- testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8891
- entries
8892
- }];
8893
- }).filter((entry) => entry !== null);
8894
- return Object.fromEntries(manifestEntries);
8895
- }
8896
- function buildTestIdManifest(componentHierarchyMap) {
8897
- return Object.fromEntries(
8898
- Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8899
- const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8900
- if (!testIds.length) {
8901
- return null;
8902
- }
8903
- return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8904
- }).filter((entry) => entry !== null)
8905
- );
8906
- }
8907
- function writeConstJson(value) {
8908
- return (writer) => {
8909
- writer.write(`${JSON.stringify(value, null, 2)} as const`);
8910
- };
8955
+ function isLessRich(candidate, previous) {
8956
+ if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8957
+ return candidate.dataTestIdCount < previous.dataTestIdCount;
8958
+ }
8959
+ if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8960
+ return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8961
+ }
8962
+ return candidate.entryCount < previous.entryCount;
8911
8963
  }
8912
- function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8913
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8914
- const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8915
- return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8916
- sourceFile.addStatements("// Virtual module: test id manifest");
8917
- sourceFile.addVariableStatement({
8918
- declarationKind: tsMorph.VariableDeclarationKind.Const,
8919
- isExported: true,
8920
- declarations: [{
8921
- name: "testIdManifest",
8922
- initializer: writeConstJson(testIdManifest)
8923
- }]
8924
- });
8925
- sourceFile.addVariableStatement({
8926
- declarationKind: tsMorph.VariableDeclarationKind.Const,
8927
- isExported: true,
8928
- declarations: [{
8929
- name: "pomManifest",
8930
- initializer: writeConstJson(pomManifest)
8931
- }]
8932
- });
8933
- sourceFile.addTypeAlias({
8934
- isExported: true,
8935
- name: "TestIdManifest",
8936
- type: "typeof testIdManifest"
8937
- });
8938
- sourceFile.addTypeAlias({
8939
- isExported: true,
8940
- name: "ComponentName",
8941
- type: "keyof TestIdManifest"
8942
- });
8943
- sourceFile.addTypeAlias({
8944
- isExported: true,
8945
- name: "PomManifest",
8946
- type: "typeof pomManifest"
8947
- });
8948
- sourceFile.addTypeAlias({
8949
- isExported: true,
8950
- name: "PomManifestComponentName",
8951
- type: "keyof PomManifest"
8952
- });
8953
- });
8954
- }
8955
- function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8956
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8957
- return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8958
- sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8959
- sourceFile.addVariableStatement({
8960
- declarationKind: tsMorph.VariableDeclarationKind.Const,
8961
- isExported: true,
8962
- declarations: [{
8963
- name: "pomManifest",
8964
- initializer: writeConstJson(pomManifest)
8965
- }]
8966
- });
8967
- sourceFile.addTypeAlias({
8968
- isExported: true,
8969
- name: "PomManifest",
8970
- type: "typeof pomManifest"
8971
- });
8972
- sourceFile.addTypeAlias({
8973
- isExported: true,
8974
- name: "PomManifestComponentName",
8975
- type: "keyof PomManifest"
8976
- });
8977
- });
8978
- }
8979
- const TEST_IDS_VIRTUAL_ID = "virtual:testids";
8980
- const TEST_IDS_RESOLVED_ID = `\0${TEST_IDS_VIRTUAL_ID}`;
8981
- const POM_MANIFEST_VIRTUAL_ID = "virtual:pom-manifest";
8982
- const POM_MANIFEST_RESOLVED_ID = `\0${POM_MANIFEST_VIRTUAL_ID}`;
8983
- function createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata) {
8984
- return {
8985
- name: "vue-pom-generator:virtual-testids",
8986
- resolveId(id) {
8987
- if (id === TEST_IDS_VIRTUAL_ID)
8988
- return TEST_IDS_RESOLVED_ID;
8989
- if (id === POM_MANIFEST_VIRTUAL_ID)
8990
- return POM_MANIFEST_RESOLVED_ID;
8991
- },
8992
- load(id) {
8993
- if (id === TEST_IDS_RESOLVED_ID)
8994
- return generateTestIdsModule(componentHierarchyMap, elementMetadata);
8995
- if (id === POM_MANIFEST_RESOLVED_ID)
8996
- return generatePomManifestModule(componentHierarchyMap, elementMetadata);
8997
- }
8998
- };
8999
- }
9000
- const ANNOTATOR_CLIENT_VIRTUAL_ID = "virtual:vue-pom-generator/annotator-client";
9001
- const ANNOTATOR_CLIENT_RESOLVED_ID = `\0${ANNOTATOR_CLIENT_VIRTUAL_ID}`;
9002
- const DEFAULT_ENTRY_SUFFIXES = [
9003
- "/src/main.ts",
9004
- "/src/main.js",
9005
- "/src/main.mts",
9006
- "/src/main.tsx",
9007
- "/src/main.jsx"
9008
- ];
9009
- function normalizePathSeparators(filePath) {
9010
- return filePath.replace(/\\/g, "/");
9011
- }
9012
- function toFsImportPath(filePath) {
9013
- return `/@fs/${normalizePathSeparators(filePath)}`;
9014
- }
9015
- function resolveAnnotatorClientPath() {
9016
- const candidates = [
9017
- node_url.fileURLToPath(new URL("./client.ts", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href)),
9018
- node_url.fileURLToPath(new URL("../plugin/runtime/annotator/client.ts", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href))
9019
- ];
9020
- const resolved = candidates.find((candidate) => fs.existsSync(candidate));
9021
- if (!resolved) {
9022
- throw new Error("[vue-pom-generator] Unable to locate annotator client source.");
9023
- }
9024
- return path.resolve(resolved);
9025
- }
9026
- function createAnnotatorUiPlugin(options) {
9027
- const clientPath = resolveAnnotatorClientPath();
9028
- const clientImportPath = toFsImportPath(clientPath);
9029
- const clientOptions = JSON.stringify({
9030
- sourceAttribute: options.sourceAttribute,
9031
- metadataAttributePrefix: options.metadataAttributePrefix,
9032
- outputDetail: options.outputDetail,
9033
- copyToClipboard: options.copyToClipboard,
9034
- showComponentTree: options.showComponentTree
9035
- });
9036
- return {
9037
- name: "vue-pom-generator:annotator-ui",
9038
- apply: "serve",
9039
- resolveId(id) {
9040
- if (id === ANNOTATOR_CLIENT_VIRTUAL_ID) {
9041
- return ANNOTATOR_CLIENT_RESOLVED_ID;
9042
- }
9043
- },
9044
- load(id) {
9045
- if (id !== ANNOTATOR_CLIENT_RESOLVED_ID) {
9046
- return null;
9047
- }
9048
- return [
9049
- `import { mountAnnotatorClient } from ${JSON.stringify(clientImportPath)};`,
9050
- `mountAnnotatorClient(${clientOptions});`,
9051
- ""
9052
- ].join("\n");
9053
- },
9054
- transform(code, id) {
9055
- if (!options.enabled) {
9056
- return null;
9057
- }
9058
- const normalizedId = normalizePathSeparators(id);
9059
- if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9060
- return null;
9061
- }
9062
- if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9063
- return null;
9064
- }
9065
- return {
9066
- code: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};
9067
- ${code}`,
9068
- map: null
9069
- };
9070
- },
9071
- transformIndexHtml() {
9072
- if (!options.enabled) {
9073
- return void 0;
9074
- }
9075
- const tag = {
9076
- tag: "script",
9077
- attrs: { type: "module" },
9078
- children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9079
- injectTo: "body"
9080
- };
9081
- return [tag];
9082
- }
9083
- };
9084
- }
9085
- function createInternalPlugins(options) {
8964
+ function createBuildProcessorPlugin(options) {
9086
8965
  const {
9087
8966
  componentHierarchyMap,
9088
8967
  crossFileKeyRegistry,
9089
- elementMetadata,
9090
8968
  vueFilesPathMap,
9091
- nativeWrappers,
9092
- optionKeyAttribute,
9093
- excludedComponents,
9094
8969
  getPageDirs,
9095
8970
  getComponentDirs,
9096
8971
  getLayoutDirs,
9097
8972
  getViewsDir,
9098
8973
  getSourceDirs,
9099
- getWrapperSearchRoots,
8974
+ basePageClassPath,
8975
+ normalizedBasePagePath,
9100
8976
  generation,
9101
8977
  projectRootRef,
9102
- basePageClassPath: basePageClassPathOverride,
9103
- loggerRef,
9104
- annotatorRuntime
8978
+ nativeWrappers,
8979
+ optionKeyAttribute,
8980
+ excludedComponents,
8981
+ getWrapperSearchRoots,
8982
+ getResolvedRouterEntry,
8983
+ loggerRef
9105
8984
  } = options;
9106
8985
  const {
8986
+ outDir,
8987
+ emitLanguages,
8988
+ typescriptOutputStructure,
8989
+ csharp,
8990
+ generateFixtures,
8991
+ customPomAttachments,
8992
+ customPomDir,
8993
+ requireCustomPomDir,
8994
+ customPomImportAliases,
8995
+ customPomImportNameCollisionBehavior,
8996
+ testIdAttribute,
8997
+ nameCollisionBehavior,
8998
+ missingSemanticNameBehavior,
8999
+ existingIdBehavior,
9107
9000
  routerAwarePoms,
9108
- routerEntry,
9109
- routerType
9001
+ routerType,
9002
+ routerModuleShims
9110
9003
  } = generation;
9111
- const resolveRouterEntry2 = () => {
9112
- if (!routerAwarePoms)
9113
- return void 0;
9114
- if (routerType === "nuxt")
9115
- return void 0;
9116
- if (!routerEntry)
9117
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9118
- return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(projectRootRef.current, routerEntry);
9004
+ let lastGeneratedMetrics = {
9005
+ entryCount: 0,
9006
+ interactiveComponentCount: 0,
9007
+ dataTestIdCount: 0
9119
9008
  };
9120
- const getDefaultBasePageClassPath = () => {
9009
+ const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
9010
+ const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
9011
+ const getScriptInfo = (source, filename) => {
9121
9012
  try {
9122
- return node_url.fileURLToPath(new URL("../class-generation/base-page.ts", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href));
9013
+ const { descriptor } = compilerSfc.parse(source, { filename });
9014
+ if (!descriptor.script && !descriptor.scriptSetup)
9015
+ return { bindings: void 0, isScriptSetup: false };
9016
+ const scriptBlock = compilerSfc.compileScript(descriptor, { id: filename });
9017
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
9123
9018
  } catch {
9124
- return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
9019
+ return { bindings: void 0, isScriptSetup: false };
9125
9020
  }
9126
9021
  };
9127
- const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9128
- const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9129
- const tsProcessor = createBuildProcessorPlugin({
9130
- componentHierarchyMap,
9131
- crossFileKeyRegistry,
9132
- vueFilesPathMap,
9133
- getPageDirs,
9134
- getComponentDirs,
9135
- getLayoutDirs,
9136
- getViewsDir,
9137
- getSourceDirs,
9138
- basePageClassPath,
9139
- normalizedBasePagePath,
9140
- generation,
9141
- projectRootRef,
9142
- nativeWrappers,
9143
- optionKeyAttribute,
9144
- excludedComponents,
9145
- getWrapperSearchRoots,
9146
- getResolvedRouterEntry: resolveRouterEntry2,
9147
- loggerRef
9148
- });
9149
- const devProcessor = createDevProcessorPlugin({
9150
- nativeWrappers,
9151
- optionKeyAttribute,
9152
- excludedComponents,
9153
- getPageDirs,
9154
- getComponentDirs,
9155
- getLayoutDirs,
9156
- getViewsDir,
9157
- getSourceDirs,
9158
- getWrapperSearchRoots,
9159
- projectRootRef,
9160
- normalizedBasePagePath,
9161
- basePageClassPath,
9162
- generation,
9163
- getResolvedRouterEntry: resolveRouterEntry2,
9164
- loggerRef
9165
- });
9166
- const virtualModules = createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata);
9167
- const annotatorUiPlugin = createAnnotatorUiPlugin({
9168
- ...annotatorRuntime.ui,
9169
- enabled: annotatorRuntime.enabled && annotatorRuntime.ui.enabled,
9170
- sourceAttribute: annotatorRuntime.sourceAttribute,
9171
- metadataAttributePrefix: annotatorRuntime.metadataAttributePrefix
9172
- });
9173
- return [tsProcessor, devProcessor, virtualModules, annotatorUiPlugin];
9174
- }
9175
- function findDataTestIdProp(element, attributeName = "data-testid") {
9176
- return element.props.find(
9177
- (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
9178
- );
9179
- }
9180
- function getTestIdFromProp(prop) {
9181
- if (!prop) {
9182
- return null;
9183
- }
9184
- if (prop.type === compilerCore.NodeTypes.ATTRIBUTE) {
9185
- return prop.value ? prop.value.content : null;
9186
- }
9187
- if (prop.type === compilerCore.NodeTypes.DIRECTIVE) {
9188
- return prop.exp?.type === compilerCore.NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content : null;
9189
- }
9190
- return null;
9191
- }
9192
- function parseDynamicProps(dynamicProps) {
9193
- if (!dynamicProps) {
9194
- return void 0;
9195
- }
9196
- if (typeof dynamicProps === "string") {
9197
- const parts = [];
9198
- let current = "";
9199
- for (let i = 0; i < dynamicProps.length; i++) {
9200
- const ch = dynamicProps[i];
9201
- if (ch === ",") {
9202
- const token = current.trim();
9203
- if (token.length)
9204
- parts.push(token);
9205
- current = "";
9206
- continue;
9207
- }
9208
- current += ch;
9209
- }
9210
- const last = current.trim();
9211
- if (last.length)
9212
- parts.push(last);
9213
- return parts;
9214
- }
9215
- if (isSimpleExpressionNode(dynamicProps)) {
9216
- const content = dynamicProps.content;
9217
- if (content.startsWith("[") && content.endsWith("]")) {
9218
- try {
9219
- return JSON.parse(content);
9220
- } catch {
9221
- return void 0;
9222
- }
9223
- }
9224
- return [content];
9225
- }
9226
- return void 0;
9227
- }
9228
- function findStaticAttributeValue(element, attributeName) {
9229
- const attribute = element.props.find(
9230
- (prop) => prop.type === compilerCore.NodeTypes.ATTRIBUTE && prop.name === attributeName
9231
- );
9232
- const value = attribute?.value?.content?.trim();
9233
- return value || void 0;
9234
- }
9235
- function collectStaticTextContent(children) {
9236
- const parts = [];
9237
- const visit = (nodes) => {
9238
- for (const node of nodes) {
9239
- if (node.type === compilerCore.NodeTypes.TEXT) {
9240
- const text2 = collapseWhitespace(node.content);
9241
- if (text2) {
9242
- parts.push(text2);
9022
+ const supplementHierarchyFromFilesystem = () => {
9023
+ const walkFilesRecursive = (rootDir) => {
9024
+ const out = [];
9025
+ const stack = [rootDir];
9026
+ while (stack.length) {
9027
+ const dir = stack.pop();
9028
+ if (!dir) continue;
9029
+ let entries = [];
9030
+ try {
9031
+ entries = fs.readdirSync(dir, { withFileTypes: true });
9032
+ } catch {
9033
+ continue;
9034
+ }
9035
+ for (const ent of entries) {
9036
+ if (ent.isDirectory()) {
9037
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
9038
+ continue;
9039
+ stack.push(path.join(dir, ent.name));
9040
+ continue;
9041
+ }
9042
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
9043
+ out.push(path.join(dir, ent.name));
9044
+ }
9243
9045
  }
9244
- continue;
9245
9046
  }
9246
- if (node.type === compilerCore.NodeTypes.ELEMENT) {
9247
- visit(node.children);
9047
+ return out;
9048
+ };
9049
+ let supplemented = 0;
9050
+ for (const dir of getSourceDirs()) {
9051
+ const absDir = path.resolve(projectRootRef.current, dir);
9052
+ if (!fs.existsSync(absDir))
9053
+ continue;
9054
+ for (const filePath of walkFilesRecursive(absDir)) {
9055
+ const absolutePath = path.resolve(filePath);
9056
+ const componentName = resolveComponentNameFromPath({
9057
+ filename: absolutePath,
9058
+ projectRoot: projectRootRef.current,
9059
+ viewsDirAbs: getViewsDirAbs(),
9060
+ sourceDirs: getSourceDirs(),
9061
+ extraRoots: [process.cwd()]
9062
+ });
9063
+ if (componentHierarchyMap.has(componentName))
9064
+ continue;
9065
+ let sfc = "";
9066
+ try {
9067
+ sfc = fs.readFileSync(absolutePath, "utf8");
9068
+ } catch {
9069
+ continue;
9070
+ }
9071
+ const { descriptor } = compilerSfc.parse(sfc, { filename: absolutePath });
9072
+ const template = descriptor.template?.content ?? "";
9073
+ if (!template.trim()) {
9074
+ vueFilesPathMap.set(componentName, absolutePath);
9075
+ componentHierarchyMap.set(componentName, {
9076
+ filePath: absolutePath,
9077
+ childrenComponentSet: /* @__PURE__ */ new Set(),
9078
+ usedComponentSet: /* @__PURE__ */ new Set(),
9079
+ dataTestIdSet: /* @__PURE__ */ new Set(),
9080
+ isView: false,
9081
+ methodsContent: ""
9082
+ });
9083
+ supplemented++;
9084
+ continue;
9085
+ }
9086
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
9087
+ vueFilesPathMap.set(componentName, absolutePath);
9088
+ try {
9089
+ compilerDom__namespace.compile(template, {
9090
+ filename: absolutePath,
9091
+ prefixIdentifiers: true,
9092
+ inline: isScriptSetup,
9093
+ bindingMetadata,
9094
+ // See dev-plugin.ts — same rationale: enable TS in template
9095
+ // expressions so `(row: RowType) => ...` handlers parse.
9096
+ expressionPlugins: ["typescript"],
9097
+ nodeTransforms: [
9098
+ createTestIdTransform(
9099
+ componentName,
9100
+ componentHierarchyMap,
9101
+ nativeWrappers,
9102
+ excludedComponents,
9103
+ getViewsDirAbs(),
9104
+ {
9105
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
9106
+ testIdAttribute,
9107
+ nameCollisionBehavior,
9108
+ missingSemanticNameBehavior,
9109
+ warn: (message) => loggerRef.current.warn(message),
9110
+ vueFilesPathMap,
9111
+ wrapperSearchRoots: getWrapperSearchRoots(),
9112
+ crossFileKeyRegistry,
9113
+ optionKeyAttribute
9114
+ }
9115
+ )
9116
+ ]
9117
+ });
9118
+ } catch {
9119
+ }
9120
+ supplemented++;
9248
9121
  }
9249
9122
  }
9250
- };
9251
- visit(children);
9252
- const text = collapseWhitespace(parts.join(" "));
9253
- return text || void 0;
9254
- }
9255
- function tryCreateElementMetadata(args) {
9256
- const { element, semanticNameMap } = args;
9257
- const testIdAttribute = (args.testIdAttribute ?? "data-testid").trim() || "data-testid";
9258
- const testIdProp = findDataTestIdProp(element, testIdAttribute);
9259
- if (!testIdProp) {
9260
- return null;
9261
- }
9262
- const testId = getTestIdFromProp(testIdProp);
9263
- if (!testId) {
9264
- return null;
9265
- }
9266
- if (!element.codegenNode || element.codegenNode.type !== compilerCore.NodeTypes.VNODE_CALL) {
9267
- return null;
9268
- }
9269
- const codegenNode = element.codegenNode;
9270
- const patchFlag = codegenNode.patchFlag;
9271
- let dynamicPropsList = parseDynamicProps(codegenNode.dynamicProps);
9272
- if (!dynamicPropsList && codegenNode.dynamicProps && typeof codegenNode.dynamicProps !== "string" && isSimpleExpressionNode(codegenNode.dynamicProps)) {
9273
- const content = codegenNode.dynamicProps.content;
9274
- if (content.startsWith("[") && content.endsWith("]")) {
9275
- dynamicPropsList = [content];
9123
+ if (supplemented > 0) {
9124
+ loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
9276
9125
  }
9277
- }
9278
- const metadata = {
9279
- testId,
9280
- semanticName: semanticNameMap.get(testId),
9281
- tag: element.tag,
9282
- tagType: element.tagType,
9283
- patchFlag,
9284
- dynamicProps: dynamicPropsList,
9285
- // Decode patch flags (bitwise) - preserved as-is from existing code.
9286
- hasClickHandler: patchFlag ? Boolean(patchFlag & 32) : void 0,
9287
- hasDynamicClass: patchFlag ? Boolean(patchFlag & 2) : void 0,
9288
- hasDynamicStyle: patchFlag ? Boolean(patchFlag & 4) : void 0,
9289
- hasDynamicText: patchFlag ? Boolean(patchFlag & 1) : void 0,
9290
- staticAriaLabel: findStaticAttributeValue(element, "aria-label"),
9291
- staticRole: findStaticAttributeValue(element, "role"),
9292
- staticTitle: findStaticAttributeValue(element, "title"),
9293
- staticTextContent: collectStaticTextContent(element.children),
9294
- sourceLine: element.loc?.start.line,
9295
- sourceColumn: element.loc?.start.column
9296
9126
  };
9297
- return metadata;
9298
- }
9299
- function resolveCompilerSfcParse(compilerSfc2) {
9300
- const parse = compilerSfc2.parse ?? compilerSfc2.default?.parse;
9301
- if (typeof parse !== "function") {
9302
- throw new TypeError("[vue-pom-generator] Failed to resolve @vue/compiler-sfc.parse.");
9303
- }
9304
- return parse;
9305
- }
9306
- function extractMetadataAfterTransform(ast, componentName, elementMetadata, semanticNameMap, testIdAttribute) {
9307
- const componentMetadata = /* @__PURE__ */ new Map();
9308
- function traverseNode(node) {
9309
- if (node.type === compilerCore.NodeTypes.ELEMENT) {
9310
- const element = node;
9311
- const testIdAttr = findDataTestIdProp(element, testIdAttribute);
9312
- if (testIdAttr) {
9313
- const metadata = tryCreateElementMetadata({
9314
- element,
9315
- semanticNameMap,
9316
- testIdAttribute
9317
- });
9318
- if (metadata) {
9319
- componentMetadata.set(metadata.testId, metadata);
9320
- }
9127
+ return {
9128
+ name: "vue-pom-generator-build",
9129
+ // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
9130
+ apply: "build",
9131
+ enforce: "pre",
9132
+ async buildStart() {
9133
+ if (!routerAwarePoms) {
9134
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
9135
+ setResolveToComponentNameFn(() => null);
9136
+ return;
9321
9137
  }
9322
- if (element.children) {
9323
- for (const child of element.children) {
9324
- traverseNode(child);
9138
+ let result;
9139
+ if (routerType === "nuxt") {
9140
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
9141
+ } else {
9142
+ const resolvedRouterEntry = getResolvedRouterEntry();
9143
+ if (!resolvedRouterEntry)
9144
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9145
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
9146
+ moduleShims: routerModuleShims,
9147
+ componentNaming: {
9148
+ projectRoot: projectRootRef.current,
9149
+ viewsDirAbs: getViewsDirAbs(),
9150
+ sourceDirs: getSourceDirs()
9151
+ }
9152
+ });
9153
+ }
9154
+ const { routeNameMap, routePathMap } = result;
9155
+ setRouteNameToComponentNameMap(routeNameMap);
9156
+ setResolveToComponentNameFn((to) => {
9157
+ if (typeof to === "string") {
9158
+ return routePathMap.get(to) ?? null;
9159
+ }
9160
+ const maybe = to;
9161
+ if (typeof maybe.name === "string" && maybe.name.length) {
9162
+ const key = toPascalCase(maybe.name);
9163
+ return routeNameMap.get(key) ?? null;
9164
+ }
9165
+ if (typeof maybe.path === "string" && maybe.path.length) {
9166
+ return routePathMap.get(maybe.path) ?? null;
9167
+ }
9168
+ return null;
9169
+ });
9170
+ if (!fs.existsSync(basePageClassPath)) {
9171
+ this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
9172
+ }
9173
+ this.addWatchFile(basePageClassPath);
9174
+ const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
9175
+ if (!fs.existsSync(pointerPath)) {
9176
+ this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
9177
+ }
9178
+ this.addWatchFile(pointerPath);
9179
+ const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
9180
+ if (!fs.existsSync(calloutPath)) {
9181
+ this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
9182
+ }
9183
+ this.addWatchFile(calloutPath);
9184
+ const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
9185
+ if (fs.existsSync(floatingUiCalloutPath)) {
9186
+ this.addWatchFile(floatingUiCalloutPath);
9187
+ }
9188
+ },
9189
+ async buildEnd(error) {
9190
+ if (error) {
9191
+ return;
9192
+ }
9193
+ supplementHierarchyFromFilesystem();
9194
+ const metrics = summarizeHierarchyMap(componentHierarchyMap);
9195
+ if (metrics.dataTestIdCount <= 0) {
9196
+ return;
9197
+ }
9198
+ if (isLessRich(metrics, lastGeneratedMetrics)) {
9199
+ return;
9200
+ }
9201
+ await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
9202
+ outDir,
9203
+ emitLanguages,
9204
+ typescriptOutputStructure,
9205
+ csharp,
9206
+ generateFixtures,
9207
+ customPomAttachments,
9208
+ projectRoot: projectRootRef.current,
9209
+ customPomDir,
9210
+ requireCustomPomDir,
9211
+ customPomImportAliases,
9212
+ customPomImportNameCollisionBehavior,
9213
+ testIdAttribute,
9214
+ vueRouterFluentChaining: routerAwarePoms,
9215
+ routerEntry: getResolvedRouterEntry(),
9216
+ routerType,
9217
+ pageDirs: getPageDirs(),
9218
+ componentDirs: getComponentDirs(),
9219
+ layoutDirs: getLayoutDirs()
9220
+ });
9221
+ lastGeneratedMetrics = metrics;
9222
+ loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
9223
+ },
9224
+ closeBundle() {
9225
+ loggerRef.current.info("build complete");
9226
+ }
9227
+ };
9228
+ }
9229
+ function createDevProcessorPlugin(options) {
9230
+ const {
9231
+ nativeWrappers,
9232
+ optionKeyAttribute,
9233
+ excludedComponents,
9234
+ getPageDirs,
9235
+ getComponentDirs,
9236
+ getLayoutDirs,
9237
+ getViewsDir,
9238
+ getSourceDirs,
9239
+ getWrapperSearchRoots,
9240
+ projectRootRef,
9241
+ normalizedBasePagePath,
9242
+ basePageClassPath,
9243
+ generation,
9244
+ getResolvedRouterEntry,
9245
+ loggerRef
9246
+ } = options;
9247
+ const {
9248
+ outDir,
9249
+ emitLanguages,
9250
+ typescriptOutputStructure,
9251
+ csharp,
9252
+ generateFixtures,
9253
+ customPomAttachments,
9254
+ customPomDir,
9255
+ requireCustomPomDir,
9256
+ customPomImportAliases,
9257
+ customPomImportNameCollisionBehavior,
9258
+ nameCollisionBehavior,
9259
+ missingSemanticNameBehavior,
9260
+ existingIdBehavior,
9261
+ testIdAttribute,
9262
+ routerAwarePoms,
9263
+ routerType,
9264
+ routerModuleShims
9265
+ } = generation;
9266
+ let scheduleVueFileRegen = null;
9267
+ const getProjectRootCandidates = () => Array.from(/* @__PURE__ */ new Set([
9268
+ path.resolve(projectRootRef.current),
9269
+ path.resolve(process.cwd())
9270
+ ]));
9271
+ const resolveProjectPath = (maybePath) => {
9272
+ if (path.isAbsolute(maybePath))
9273
+ return maybePath;
9274
+ const candidates = getProjectRootCandidates().map((root) => path.resolve(root, maybePath));
9275
+ return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
9276
+ };
9277
+ const getSourceDirRoots = () => Array.from(new Set(
9278
+ getProjectRootCandidates().flatMap((root) => getSourceDirs().map((dir) => path.resolve(root, dir)))
9279
+ ));
9280
+ const isContainedInScanDirs = (filePath) => {
9281
+ const absolutePath = path.resolve(filePath);
9282
+ return getSourceDirRoots().some((scanDirAbs) => isPathWithinDir(absolutePath, scanDirAbs));
9283
+ };
9284
+ return {
9285
+ name: "vue-pom-generator-dev",
9286
+ apply: "serve",
9287
+ // Prefer hot-update events over filesystem change events for speed and reliability.
9288
+ // This fires when Vite has actually processed the module update.
9289
+ handleHotUpdate(ctx) {
9290
+ if (!scheduleVueFileRegen)
9291
+ return;
9292
+ if (!ctx.file.endsWith(".vue"))
9293
+ return;
9294
+ if (!isContainedInScanDirs(ctx.file))
9295
+ return;
9296
+ scheduleVueFileRegen(ctx.file, "hmr");
9297
+ },
9298
+ async configureServer(server) {
9299
+ const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
9300
+ const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
9301
+ const routerInitPromise = (async () => {
9302
+ if (!routerAwarePoms) {
9303
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
9304
+ setResolveToComponentNameFn(() => null);
9305
+ return;
9306
+ }
9307
+ let result;
9308
+ if (routerType === "nuxt") {
9309
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
9310
+ } else {
9311
+ const resolvedRouterEntry = getResolvedRouterEntry();
9312
+ if (!resolvedRouterEntry)
9313
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9314
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
9315
+ moduleShims: routerModuleShims,
9316
+ componentNaming: {
9317
+ projectRoot: projectRootRef.current,
9318
+ viewsDirAbs: getViewsDirAbs(),
9319
+ sourceDirs: getSourceDirs(),
9320
+ extraRoots: [process.cwd()]
9321
+ }
9322
+ });
9323
+ }
9324
+ const { routeNameMap, routePathMap } = result;
9325
+ setRouteNameToComponentNameMap(routeNameMap);
9326
+ setResolveToComponentNameFn((to) => {
9327
+ if (typeof to === "string") {
9328
+ return routePathMap.get(to) ?? null;
9329
+ }
9330
+ const maybe = to;
9331
+ if (typeof maybe.name === "string" && maybe.name.length) {
9332
+ const key = toPascalCase(maybe.name);
9333
+ return routeNameMap.get(key) ?? null;
9334
+ }
9335
+ if (typeof maybe.path === "string" && maybe.path.length) {
9336
+ return routePathMap.get(maybe.path) ?? null;
9337
+ }
9338
+ return null;
9339
+ });
9340
+ })();
9341
+ const logInfo = (message) => loggerRef.current.info(message);
9342
+ const logDebug = (message) => loggerRef.current.debug(message);
9343
+ let scheduleVueFileRegenLocal = null;
9344
+ const formatMs = (ms) => `${ms.toFixed(1)}ms`;
9345
+ const extractTemplateFromSfc = (source, filename) => {
9346
+ const { descriptor } = compilerSfc.parse(source, {
9347
+ filename: filename ?? "anonymous.vue"
9348
+ });
9349
+ return descriptor.template?.content ?? "";
9350
+ };
9351
+ const getScriptInfo = (source, filename) => {
9352
+ try {
9353
+ const { descriptor } = compilerSfc.parse(source, { filename });
9354
+ if (!descriptor.script && !descriptor.scriptSetup)
9355
+ return { bindings: void 0, isScriptSetup: false };
9356
+ const scriptBlock = compilerSfc.compileScript(descriptor, { id: filename });
9357
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
9358
+ } catch {
9359
+ return { bindings: void 0, isScriptSetup: false };
9360
+ }
9361
+ };
9362
+ const walkFilesRecursive = (rootDir) => {
9363
+ const out = [];
9364
+ const stack = [rootDir];
9365
+ while (stack.length) {
9366
+ const dir = stack.pop();
9367
+ if (!dir) continue;
9368
+ let entries = [];
9369
+ try {
9370
+ entries = fs.readdirSync(dir, { withFileTypes: true });
9371
+ } catch {
9372
+ continue;
9373
+ }
9374
+ for (const ent of entries) {
9375
+ if (ent.isDirectory()) {
9376
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
9377
+ continue;
9378
+ stack.push(path.join(dir, ent.name));
9379
+ continue;
9380
+ }
9381
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
9382
+ out.push(path.join(dir, ent.name));
9383
+ }
9384
+ }
9385
+ }
9386
+ return out;
9387
+ };
9388
+ let snapshotHierarchy = /* @__PURE__ */ new Map();
9389
+ let snapshotVuePathMap = /* @__PURE__ */ new Map();
9390
+ const filePathToComponentName = /* @__PURE__ */ new Map();
9391
+ const createEmptyComponentDependencies = (absolutePath) => {
9392
+ const viewsDirAbs = path.resolve(getViewsDirAbs());
9393
+ const relToViewsDir = path.relative(viewsDirAbs, absolutePath);
9394
+ const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
9395
+ return {
9396
+ filePath: absolutePath,
9397
+ childrenComponentSet: /* @__PURE__ */ new Set(),
9398
+ usedComponentSet: /* @__PURE__ */ new Set(),
9399
+ dataTestIdSet: /* @__PURE__ */ new Set(),
9400
+ isView,
9401
+ methodsContent: ""
9402
+ };
9403
+ };
9404
+ const getComponentNameForFile = (filePath) => {
9405
+ const normalized = path.resolve(filePath);
9406
+ const existing = filePathToComponentName.get(normalized);
9407
+ if (existing)
9408
+ return existing;
9409
+ const name = resolveComponentNameFromPath({
9410
+ filename: normalized,
9411
+ projectRoot: projectRootRef.current,
9412
+ viewsDirAbs: getViewsDirAbs(),
9413
+ sourceDirs: getSourceDirs(),
9414
+ extraRoots: [process.cwd()]
9415
+ });
9416
+ filePathToComponentName.set(normalized, name);
9417
+ return name;
9418
+ };
9419
+ const compileVueFileIntoSnapshot = (filePath, targetHierarchy = snapshotHierarchy, targetVuePathMap = snapshotVuePathMap) => {
9420
+ const started = node_perf_hooks.performance.now();
9421
+ const absolutePath = path.resolve(filePath);
9422
+ const componentName = getComponentNameForFile(absolutePath);
9423
+ let sfc = "";
9424
+ try {
9425
+ sfc = fs.readFileSync(absolutePath, "utf8");
9426
+ } catch {
9427
+ return { componentName, ms: node_perf_hooks.performance.now() - started, compiled: false };
9428
+ }
9429
+ const template = extractTemplateFromSfc(sfc, absolutePath);
9430
+ if (!template.trim()) {
9431
+ targetVuePathMap.set(componentName, absolutePath);
9432
+ targetHierarchy.set(componentName, createEmptyComponentDependencies(absolutePath));
9433
+ return { componentName, ms: node_perf_hooks.performance.now() - started, compiled: true };
9434
+ }
9435
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
9436
+ const provisionalHierarchy = /* @__PURE__ */ new Map();
9437
+ const provisionalKeyRegistry = /* @__PURE__ */ new Map();
9438
+ const provisionalVuePathMap = new Map(targetVuePathMap);
9439
+ provisionalVuePathMap.set(componentName, absolutePath);
9440
+ compilerDom__namespace.compile(template, {
9441
+ filename: absolutePath,
9442
+ prefixIdentifiers: true,
9443
+ inline: isScriptSetup,
9444
+ bindingMetadata,
9445
+ // Vue templates may contain TypeScript type annotations in expressions
9446
+ // (e.g. `@row-click="(row: RowType) => navigateTo(...)"` in Nuxt + TS
9447
+ // apps). Without this flag, Vue's internal processExpression step
9448
+ // delegates to @babel/parser without the TS plugin and crashes on
9449
+ // "Unexpected token, expected ','".
9450
+ expressionPlugins: ["typescript"],
9451
+ nodeTransforms: [
9452
+ createTestIdTransform(
9453
+ componentName,
9454
+ provisionalHierarchy,
9455
+ nativeWrappers,
9456
+ excludedComponents,
9457
+ getViewsDirAbs(),
9458
+ {
9459
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
9460
+ nameCollisionBehavior,
9461
+ missingSemanticNameBehavior,
9462
+ testIdAttribute,
9463
+ warn: (message) => loggerRef.current.warn(message),
9464
+ vueFilesPathMap: provisionalVuePathMap,
9465
+ wrapperSearchRoots: getWrapperSearchRoots(),
9466
+ crossFileKeyRegistry: provisionalKeyRegistry,
9467
+ optionKeyAttribute
9468
+ }
9469
+ )
9470
+ ]
9471
+ });
9472
+ targetVuePathMap.set(componentName, absolutePath);
9473
+ targetHierarchy.set(
9474
+ componentName,
9475
+ provisionalHierarchy.get(componentName) ?? createEmptyComponentDependencies(absolutePath)
9476
+ );
9477
+ return { componentName, ms: node_perf_hooks.performance.now() - started, compiled: true };
9478
+ };
9479
+ const fullRebuildSnapshotFromFilesystem = (logLabel) => {
9480
+ const t0 = node_perf_hooks.performance.now();
9481
+ const nextHierarchy = /* @__PURE__ */ new Map();
9482
+ const nextVuePathMap = /* @__PURE__ */ new Map();
9483
+ filePathToComponentName.clear();
9484
+ let totalVueFiles = 0;
9485
+ let compiledCount = 0;
9486
+ for (const absDir of getSourceDirRoots()) {
9487
+ if (!fs.existsSync(absDir))
9488
+ continue;
9489
+ const vueFiles = walkFilesRecursive(absDir);
9490
+ totalVueFiles += vueFiles.length;
9491
+ for (const file of vueFiles) {
9492
+ const res = compileVueFileIntoSnapshot(file, nextHierarchy, nextVuePathMap);
9493
+ if (res.compiled)
9494
+ compiledCount++;
9495
+ }
9496
+ }
9497
+ snapshotHierarchy = nextHierarchy;
9498
+ snapshotVuePathMap = nextVuePathMap;
9499
+ const t1 = node_perf_hooks.performance.now();
9500
+ logInfo(`scan(${logLabel}): found ${totalVueFiles} .vue files in ${getSourceDirs().join(", ")}`);
9501
+ logInfo(`compile(${logLabel}): ${compiledCount}/${totalVueFiles} files in ${formatMs(t1 - t0)} (components=${snapshotHierarchy.size})`);
9502
+ };
9503
+ const generateAggregatedFromSnapshot = async (logLabel) => {
9504
+ const t0 = node_perf_hooks.performance.now();
9505
+ await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
9506
+ outDir,
9507
+ emitLanguages,
9508
+ typescriptOutputStructure,
9509
+ csharp,
9510
+ generateFixtures,
9511
+ customPomAttachments,
9512
+ projectRoot: projectRootRef.current,
9513
+ customPomDir,
9514
+ requireCustomPomDir,
9515
+ customPomImportAliases,
9516
+ customPomImportNameCollisionBehavior,
9517
+ pageDirs: getPageDirs(),
9518
+ componentDirs: getComponentDirs(),
9519
+ layoutDirs: getLayoutDirs(),
9520
+ testIdAttribute,
9521
+ vueRouterFluentChaining: routerAwarePoms,
9522
+ routerEntry: getResolvedRouterEntry(),
9523
+ routerType
9524
+ });
9525
+ const t1 = node_perf_hooks.performance.now();
9526
+ logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
9527
+ };
9528
+ let timer = null;
9529
+ let maxWaitTimer = null;
9530
+ const pendingChangedVueFiles = /* @__PURE__ */ new Set();
9531
+ const pendingDeletedComponents = /* @__PURE__ */ new Set();
9532
+ let regenerationSequence = Promise.resolve();
9533
+ const initialBuildPromise = (async () => {
9534
+ const t0 = node_perf_hooks.performance.now();
9535
+ await routerInitPromise;
9536
+ fullRebuildSnapshotFromFilesystem("startup");
9537
+ await generateAggregatedFromSnapshot("startup");
9538
+ const t1 = node_perf_hooks.performance.now();
9539
+ logInfo(`startup total: ${formatMs(t1 - t0)}`);
9540
+ })();
9541
+ const logGenerationError = (reason, message) => {
9542
+ server.config.logger.error(`[vue-pom-generator] dev generation failed during ${reason}: ${message}`);
9543
+ };
9544
+ const regenerateFromPending = async (reason) => {
9545
+ const t0 = node_perf_hooks.performance.now();
9546
+ await initialBuildPromise;
9547
+ const nextHierarchy = new Map(snapshotHierarchy);
9548
+ const nextVuePathMap = new Map(snapshotVuePathMap);
9549
+ for (const componentName of pendingDeletedComponents) {
9550
+ nextHierarchy.delete(componentName);
9551
+ nextVuePathMap.delete(componentName);
9552
+ }
9553
+ const files = Array.from(pendingChangedVueFiles);
9554
+ const deletedCount = pendingDeletedComponents.size;
9555
+ pendingChangedVueFiles.clear();
9556
+ pendingDeletedComponents.clear();
9557
+ let compileMs = 0;
9558
+ for (const f of files) {
9559
+ const res = compileVueFileIntoSnapshot(f, nextHierarchy, nextVuePathMap);
9560
+ compileMs += res.ms;
9561
+ }
9562
+ snapshotHierarchy = nextHierarchy;
9563
+ snapshotVuePathMap = nextVuePathMap;
9564
+ const t1 = node_perf_hooks.performance.now();
9565
+ await generateAggregatedFromSnapshot(reason);
9566
+ const t2 = node_perf_hooks.performance.now();
9567
+ return {
9568
+ files,
9569
+ deletedCount,
9570
+ compileMs,
9571
+ preGenerateMs: t1 - t0,
9572
+ generateMs: t2 - t1,
9573
+ totalMs: t2 - t0
9574
+ };
9575
+ };
9576
+ const enqueueRegeneration = (reason) => {
9577
+ const currentRun = regenerationSequence.catch(() => void 0).then(() => regenerateFromPending(reason));
9578
+ regenerationSequence = currentRun.then(() => void 0, () => void 0);
9579
+ return currentRun;
9580
+ };
9581
+ const runtimeDir = path.dirname(basePageClassPath);
9582
+ const localPluginDir = path.resolve(projectRootRef.current, "vite-plugins", "vue-pom-generator");
9583
+ server.watcher.add([
9584
+ ...fs.existsSync(localPluginDir) ? [localPluginDir] : [],
9585
+ basePageClassPath,
9586
+ path.resolve(runtimeDir, "pointer.ts"),
9587
+ path.resolve(runtimeDir, "callout.ts"),
9588
+ path.resolve(runtimeDir, "floating-ui-callout.ts")
9589
+ ]);
9590
+ scheduleVueFileRegenLocal = (filePath, source) => {
9591
+ pendingChangedVueFiles.add(filePath);
9592
+ logDebug(`queued(${source}): files=${pendingChangedVueFiles.size} deleted=${pendingDeletedComponents.size}`);
9593
+ scheduleAggregatedRegen();
9594
+ };
9595
+ scheduleVueFileRegen = scheduleVueFileRegenLocal;
9596
+ function scheduleAggregatedRegen() {
9597
+ const wasEmpty = pendingChangedVueFiles.size === 0 && pendingDeletedComponents.size === 0;
9598
+ const MAX_WAIT_MS = 750;
9599
+ if (!maxWaitTimer) {
9600
+ maxWaitTimer = setTimeout(() => {
9601
+ if (timer) {
9602
+ clearTimeout(timer);
9603
+ timer = null;
9604
+ }
9605
+ maxWaitTimer = null;
9606
+ void enqueueRegeneration("max-wait").then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9607
+ logInfo(
9608
+ `max-wait: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9609
+ );
9610
+ }).catch((error) => {
9611
+ const message = error instanceof Error ? error.message : String(error);
9612
+ logGenerationError("max-wait", message);
9613
+ });
9614
+ }, MAX_WAIT_MS);
9325
9615
  }
9326
- }
9327
- } else if (node.type === compilerCore.NodeTypes.IF) {
9328
- for (const branch of node.branches) {
9329
- traverseNode(branch);
9330
- }
9331
- } else if (node.type === compilerCore.NodeTypes.IF_BRANCH || node.type === compilerCore.NodeTypes.FOR) {
9332
- if (node.children) {
9333
- for (const child of node.children) {
9334
- traverseNode(child);
9616
+ if (wasEmpty) {
9617
+ const queuedFiles = pendingChangedVueFiles.size;
9618
+ const queuedDeletes = pendingDeletedComponents.size;
9619
+ logDebug(`queued: files=${queuedFiles} deleted=${queuedDeletes}`);
9335
9620
  }
9336
- }
9337
- } else if (node.type === compilerCore.NodeTypes.ROOT) {
9338
- for (const child of node.children) {
9339
- traverseNode(child);
9340
- }
9341
- }
9342
- }
9343
- traverseNode(ast);
9344
- if (componentMetadata.size > 0) {
9345
- elementMetadata.set(componentName, componentMetadata);
9346
- }
9347
- return componentMetadata;
9348
- }
9349
- function createVuePluginWithTestIds(options) {
9350
- const {
9351
- vueOptions,
9352
- existingIdBehavior,
9353
- nameCollisionBehavior,
9354
- missingSemanticNameBehavior = "error",
9355
- nativeWrappers,
9356
- optionKeyAttribute,
9357
- elementMetadata,
9358
- semanticNameMap,
9359
- componentHierarchyMap,
9360
- crossFileKeyRegistry,
9361
- vueFilesPathMap,
9362
- excludedComponents,
9363
- getViewsDirAbs,
9364
- testIdAttribute,
9365
- accessibilityAudit,
9366
- loggerRef,
9367
- getSourceDirs,
9368
- getWrapperSearchRoots,
9369
- getProjectRoot,
9370
- annotatorMetadata
9371
- } = options;
9372
- const lastAccessibilityWarningSignatureByComponent = /* @__PURE__ */ new Map();
9373
- const getComponentNameFromPath = (filename) => {
9374
- return resolveComponentNameFromPath({
9375
- filename,
9376
- projectRoot: getProjectRoot(),
9377
- viewsDirAbs: getViewsDirAbs(),
9378
- sourceDirs: getSourceDirs(),
9379
- extraRoots: [process.cwd()]
9380
- });
9381
- };
9382
- const isFileInScope = (filename) => {
9383
- if (!filename)
9384
- return false;
9385
- const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
9386
- const projectRoot = getProjectRoot();
9387
- const matched = isFileInConfiguredSourceScope({
9388
- filename,
9389
- projectRoot,
9390
- viewsDirAbs: getViewsDirAbs(),
9391
- sourceDirs: getSourceDirs(),
9392
- extraRoots: [process.cwd()]
9393
- });
9394
- if (cleanPath.endsWith(".vue") && !matched) {
9395
- const absFilename = path.normalize(path.isAbsolute(cleanPath) ? cleanPath : path.resolve(projectRoot, cleanPath));
9396
- loggerRef.current.debug(`[isFileInScope] REJECTED: ${absFilename} (Clean: ${cleanPath})`);
9397
- }
9398
- return matched;
9399
- };
9400
- const userTemplate = vueOptions?.template ?? {};
9401
- const userCompilerOptions = userTemplate.compilerOptions ?? {};
9402
- const userNodeTransforms = userCompilerOptions.nodeTransforms ?? [];
9403
- const perFileTransform = /* @__PURE__ */ new Map();
9404
- const getNodeTransforms = (filename, componentNameOverride) => {
9405
- const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
9406
- const viewsDirAbs = getViewsDirAbs();
9407
- const componentName = componentNameOverride || getComponentNameFromPath(cleanPath);
9408
- return [
9409
- ...userNodeTransforms,
9410
- (node, context) => {
9411
- if (node.type === compilerCore.NodeTypes.ROOT) {
9412
- componentHierarchyMap.delete(componentName);
9413
- vueFilesPathMap.set(componentName, filename);
9414
- perFileTransform.set(
9415
- componentName,
9416
- createTestIdTransform(
9417
- componentName,
9418
- componentHierarchyMap,
9419
- nativeWrappers,
9420
- excludedComponents,
9421
- viewsDirAbs,
9422
- {
9423
- existingIdBehavior,
9424
- testIdAttribute,
9425
- nameCollisionBehavior,
9426
- missingSemanticNameBehavior,
9427
- warn: (message) => loggerRef.current.warn(message),
9428
- vueFilesPathMap,
9429
- wrapperSearchRoots: getWrapperSearchRoots(),
9430
- annotatorMetadata,
9431
- crossFileKeyRegistry,
9432
- optionKeyAttribute
9433
- }
9434
- )
9435
- );
9436
- return () => {
9437
- const componentMetadata = extractMetadataAfterTransform(
9438
- node,
9439
- componentName,
9440
- elementMetadata,
9441
- semanticNameMap,
9442
- testIdAttribute
9443
- );
9444
- if (!accessibilityAudit) {
9445
- return;
9446
- }
9447
- const dependencies = componentHierarchyMap.get(componentName);
9448
- if (!dependencies || componentMetadata.size === 0) {
9449
- return;
9450
- }
9451
- const manifest = buildPomManifest(
9452
- /* @__PURE__ */ new Map([[componentName, dependencies]]),
9453
- /* @__PURE__ */ new Map([[componentName, componentMetadata]])
9454
- );
9455
- const warnings = collectAccessibilityReviewWarnings(manifest);
9456
- const signature = warnings.join("\n");
9457
- if (!signature) {
9458
- lastAccessibilityWarningSignatureByComponent.delete(componentName);
9459
- return;
9460
- }
9461
- if (lastAccessibilityWarningSignatureByComponent.get(componentName) === signature) {
9462
- return;
9463
- }
9464
- lastAccessibilityWarningSignatureByComponent.set(componentName, signature);
9465
- for (const warning of warnings) {
9466
- loggerRef.current.warn(warning);
9621
+ if (timer)
9622
+ clearTimeout(timer);
9623
+ timer = setTimeout(() => {
9624
+ timer = null;
9625
+ if (maxWaitTimer) {
9626
+ clearTimeout(maxWaitTimer);
9627
+ maxWaitTimer = null;
9628
+ }
9629
+ const reason = pendingChangedVueFiles.size || pendingDeletedComponents.size ? "batched" : "noop";
9630
+ void enqueueRegeneration(reason).then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9631
+ if (files.length || deletedCount) {
9632
+ logInfo(
9633
+ `batched: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9634
+ );
9467
9635
  }
9468
- };
9636
+ }).catch((error) => {
9637
+ const message = error instanceof Error ? error.message : String(error);
9638
+ logGenerationError(reason, message);
9639
+ });
9640
+ }, 75);
9641
+ }
9642
+ server.watcher.on("change", async (changedPath) => {
9643
+ const changedAbsPosix = path.posix.normalize(path.resolve(changedPath));
9644
+ const outDirAbsPosix = path.posix.normalize(path.resolve(projectRootRef.current, outDir ?? "./pom"));
9645
+ if (changedAbsPosix.startsWith(`${outDirAbsPosix}/`) && (changedAbsPosix.endsWith(".g.ts") || changedAbsPosix.endsWith(".g.ts.map"))) {
9646
+ return;
9469
9647
  }
9470
- let transform = perFileTransform.get(componentName);
9471
- if (!transform) {
9472
- componentHierarchyMap.delete(componentName);
9473
- vueFilesPathMap.set(componentName, filename);
9474
- transform = createTestIdTransform(
9475
- componentName,
9476
- componentHierarchyMap,
9477
- nativeWrappers,
9478
- excludedComponents,
9479
- viewsDirAbs,
9480
- {
9481
- existingIdBehavior,
9482
- testIdAttribute,
9483
- nameCollisionBehavior,
9484
- missingSemanticNameBehavior,
9485
- warn: (message) => loggerRef.current.warn(message),
9486
- vueFilesPathMap,
9487
- wrapperSearchRoots: getWrapperSearchRoots(),
9488
- annotatorMetadata,
9489
- crossFileKeyRegistry,
9490
- optionKeyAttribute
9491
- }
9492
- );
9493
- perFileTransform.set(componentName, transform);
9648
+ if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
9649
+ void server.restart();
9494
9650
  }
9495
- return transform(node, context);
9496
- }
9497
- ];
9651
+ });
9652
+ server.watcher.on("add", (p) => {
9653
+ if (typeof p !== "string")
9654
+ return;
9655
+ if (!p.endsWith(".vue"))
9656
+ return;
9657
+ if (!isContainedInScanDirs(p))
9658
+ return;
9659
+ void (async () => {
9660
+ await initialBuildPromise;
9661
+ pendingChangedVueFiles.add(p);
9662
+ scheduleAggregatedRegen();
9663
+ })();
9664
+ });
9665
+ server.watcher.on("unlink", (p) => {
9666
+ if (typeof p !== "string")
9667
+ return;
9668
+ if (!p.endsWith(".vue"))
9669
+ return;
9670
+ if (!isContainedInScanDirs(p))
9671
+ return;
9672
+ void (async () => {
9673
+ await initialBuildPromise;
9674
+ const absolutePath = path.resolve(p);
9675
+ const componentName = getComponentNameForFile(absolutePath);
9676
+ filePathToComponentName.delete(absolutePath);
9677
+ pendingDeletedComponents.add(componentName);
9678
+ scheduleAggregatedRegen();
9679
+ })();
9680
+ });
9681
+ setTimeout(() => {
9682
+ }, 250);
9683
+ await initialBuildPromise;
9684
+ }
9498
9685
  };
9499
- const runtimeNodeTransform = (node, context) => {
9500
- const filename = context.filename;
9501
- if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
9502
- return;
9686
+ }
9687
+ const TEST_IDS_VIRTUAL_ID = "virtual:testids";
9688
+ const TEST_IDS_RESOLVED_ID = `\0${TEST_IDS_VIRTUAL_ID}`;
9689
+ const POM_MANIFEST_VIRTUAL_ID = "virtual:pom-manifest";
9690
+ const POM_MANIFEST_RESOLVED_ID = `\0${POM_MANIFEST_VIRTUAL_ID}`;
9691
+ function createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata) {
9692
+ return {
9693
+ name: "vue-pom-generator:virtual-testids",
9694
+ resolveId(id) {
9695
+ if (id === TEST_IDS_VIRTUAL_ID)
9696
+ return TEST_IDS_RESOLVED_ID;
9697
+ if (id === POM_MANIFEST_VIRTUAL_ID)
9698
+ return POM_MANIFEST_RESOLVED_ID;
9699
+ },
9700
+ load(id) {
9701
+ if (id === TEST_IDS_RESOLVED_ID)
9702
+ return generateTestIdsModule(componentHierarchyMap, elementMetadata);
9703
+ if (id === POM_MANIFEST_RESOLVED_ID)
9704
+ return generatePomManifestModule(componentHierarchyMap, elementMetadata);
9503
9705
  }
9504
- const transforms = getNodeTransforms(filename);
9505
- const ourTransform = transforms[transforms.length - 1];
9506
- return ourTransform(node, context);
9507
- };
9508
- const templateCompilerOptions = {
9509
- ...userCompilerOptions,
9510
- prefixIdentifiers: true,
9511
- nodeTransforms: [
9512
- ...userNodeTransforms,
9513
- runtimeNodeTransform
9514
- ]
9515
9706
  };
9516
- const metadataCollectorPlugin = {
9517
- name: "vue-pom-generator-metadata-collector",
9518
- enforce: "pre",
9519
- async transform(code, id) {
9520
- const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
9521
- if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
9707
+ }
9708
+ const ANNOTATOR_CLIENT_VIRTUAL_ID = "virtual:vue-pom-generator/annotator-client";
9709
+ const ANNOTATOR_CLIENT_RESOLVED_ID = `\0${ANNOTATOR_CLIENT_VIRTUAL_ID}`;
9710
+ const DEFAULT_ENTRY_SUFFIXES = [
9711
+ "/src/main.ts",
9712
+ "/src/main.js",
9713
+ "/src/main.mts",
9714
+ "/src/main.tsx",
9715
+ "/src/main.jsx"
9716
+ ];
9717
+ function normalizePathSeparators(filePath) {
9718
+ return filePath.replace(/\\/g, "/");
9719
+ }
9720
+ function toFsImportPath(filePath) {
9721
+ return `/@fs/${normalizePathSeparators(filePath)}`;
9722
+ }
9723
+ function resolveAnnotatorClientPath() {
9724
+ const candidates = [
9725
+ node_url.fileURLToPath(new URL("./client.ts", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href)),
9726
+ node_url.fileURLToPath(new URL("../plugin/runtime/annotator/client.ts", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href))
9727
+ ];
9728
+ const resolved = candidates.find((candidate) => fs.existsSync(candidate));
9729
+ if (!resolved) {
9730
+ throw new Error("[vue-pom-generator] Unable to locate annotator client source.");
9731
+ }
9732
+ return path.resolve(resolved);
9733
+ }
9734
+ function createAnnotatorUiPlugin(options) {
9735
+ const clientPath = resolveAnnotatorClientPath();
9736
+ const clientImportPath = toFsImportPath(clientPath);
9737
+ const clientOptions = JSON.stringify({
9738
+ sourceAttribute: options.sourceAttribute,
9739
+ metadataAttributePrefix: options.metadataAttributePrefix,
9740
+ outputDetail: options.outputDetail,
9741
+ copyToClipboard: options.copyToClipboard,
9742
+ showComponentTree: options.showComponentTree
9743
+ });
9744
+ return {
9745
+ name: "vue-pom-generator:annotator-ui",
9746
+ apply: "serve",
9747
+ resolveId(id) {
9748
+ if (id === ANNOTATOR_CLIENT_VIRTUAL_ID) {
9749
+ return ANNOTATOR_CLIENT_RESOLVED_ID;
9750
+ }
9751
+ },
9752
+ load(id) {
9753
+ if (id !== ANNOTATOR_CLIENT_RESOLVED_ID) {
9522
9754
  return null;
9523
9755
  }
9524
- if (id !== cleanPath) {
9756
+ return [
9757
+ `import { mountAnnotatorClient } from ${JSON.stringify(clientImportPath)};`,
9758
+ `mountAnnotatorClient(${clientOptions});`,
9759
+ ""
9760
+ ].join("\n");
9761
+ },
9762
+ transform(code, id) {
9763
+ if (!options.enabled) {
9525
9764
  return null;
9526
9765
  }
9527
- const componentName = getComponentNameFromPath(cleanPath);
9528
- loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
9529
- const compilerSfc2 = await import("@vue/compiler-sfc");
9530
- const parse = resolveCompilerSfcParse(compilerSfc2);
9531
- const compilerDom2 = await import("@vue/compiler-dom");
9532
- const compile = compilerDom2.compile;
9533
- const { descriptor } = parse(code, { filename: cleanPath });
9534
- if (descriptor.template) {
9535
- const mergedExpressionPlugins = Array.from(
9536
- /* @__PURE__ */ new Set([
9537
- "typescript",
9538
- ...userCompilerOptions.expressionPlugins ?? []
9539
- ])
9540
- );
9541
- compile(descriptor.template.content, {
9542
- ...userCompilerOptions,
9543
- filename: cleanPath,
9544
- expressionPlugins: mergedExpressionPlugins,
9545
- nodeTransforms: getNodeTransforms(cleanPath, componentName)
9546
- });
9547
- loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
9766
+ const normalizedId = normalizePathSeparators(id);
9767
+ if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9768
+ return null;
9548
9769
  }
9549
- return null;
9550
- }
9551
- };
9552
- const template = {
9553
- ...userTemplate,
9554
- compilerOptions: templateCompilerOptions
9555
- };
9556
- const internalVuePlugin = vue({
9557
- ...vueOptions,
9558
- template
9559
- });
9560
- const nuxtVueBridgePlugin = {
9561
- name: "vue-pom-generator-nuxt-vue-bridge",
9562
- apply: "serve",
9563
- configResolved(config) {
9564
- const viteVuePlugin = config.plugins.find((plugin) => {
9565
- return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
9566
- });
9567
- const api = viteVuePlugin?.api;
9568
- if (!api) {
9569
- throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
9770
+ if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9771
+ return null;
9570
9772
  }
9571
- const currentOptions = api.options ?? {};
9572
- const currentTemplate = currentOptions.template ?? {};
9573
- const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
9574
- const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
9575
- if (currentNodeTransforms.includes(runtimeNodeTransform)) {
9576
- return;
9773
+ return {
9774
+ code: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};
9775
+ ${code}`,
9776
+ map: null
9777
+ };
9778
+ },
9779
+ transformIndexHtml() {
9780
+ if (!options.enabled) {
9781
+ return void 0;
9577
9782
  }
9578
- api.options = {
9579
- ...currentOptions,
9580
- template: {
9581
- ...currentTemplate,
9582
- compilerOptions: {
9583
- ...currentCompilerOptions,
9584
- prefixIdentifiers: true,
9585
- nodeTransforms: [
9586
- ...currentNodeTransforms,
9587
- runtimeNodeTransform
9588
- ]
9589
- }
9590
- }
9783
+ const tag = {
9784
+ tag: "script",
9785
+ attrs: { type: "module" },
9786
+ children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9787
+ injectTo: "body"
9591
9788
  };
9789
+ return [tag];
9592
9790
  }
9593
9791
  };
9594
- return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
9792
+ }
9793
+ function createInternalPlugins(options) {
9794
+ const {
9795
+ componentHierarchyMap,
9796
+ crossFileKeyRegistry,
9797
+ elementMetadata,
9798
+ vueFilesPathMap,
9799
+ nativeWrappers,
9800
+ optionKeyAttribute,
9801
+ excludedComponents,
9802
+ getPageDirs,
9803
+ getComponentDirs,
9804
+ getLayoutDirs,
9805
+ getViewsDir,
9806
+ getSourceDirs,
9807
+ getWrapperSearchRoots,
9808
+ generation,
9809
+ projectRootRef,
9810
+ basePageClassPath: basePageClassPathOverride,
9811
+ loggerRef,
9812
+ annotatorRuntime
9813
+ } = options;
9814
+ const {
9815
+ routerAwarePoms,
9816
+ routerEntry,
9817
+ routerType
9818
+ } = generation;
9819
+ const resolveRouterEntry2 = () => {
9820
+ if (!routerAwarePoms)
9821
+ return void 0;
9822
+ if (routerType === "nuxt")
9823
+ return void 0;
9824
+ if (!routerEntry)
9825
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9826
+ return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(projectRootRef.current, routerEntry);
9827
+ };
9828
+ const getDefaultBasePageClassPath = () => {
9829
+ try {
9830
+ return node_url.fileURLToPath(new URL("../class-generation/base-page.ts", typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href));
9831
+ } catch {
9832
+ return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
9833
+ }
9834
+ };
9835
+ const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9836
+ const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9837
+ const tsProcessor = createBuildProcessorPlugin({
9838
+ componentHierarchyMap,
9839
+ crossFileKeyRegistry,
9840
+ vueFilesPathMap,
9841
+ getPageDirs,
9842
+ getComponentDirs,
9843
+ getLayoutDirs,
9844
+ getViewsDir,
9845
+ getSourceDirs,
9846
+ basePageClassPath,
9847
+ normalizedBasePagePath,
9848
+ generation,
9849
+ projectRootRef,
9850
+ nativeWrappers,
9851
+ optionKeyAttribute,
9852
+ excludedComponents,
9853
+ getWrapperSearchRoots,
9854
+ getResolvedRouterEntry: resolveRouterEntry2,
9855
+ loggerRef
9856
+ });
9857
+ const devProcessor = createDevProcessorPlugin({
9858
+ nativeWrappers,
9859
+ optionKeyAttribute,
9860
+ excludedComponents,
9861
+ getPageDirs,
9862
+ getComponentDirs,
9863
+ getLayoutDirs,
9864
+ getViewsDir,
9865
+ getSourceDirs,
9866
+ getWrapperSearchRoots,
9867
+ projectRootRef,
9868
+ normalizedBasePagePath,
9869
+ basePageClassPath,
9870
+ generation,
9871
+ getResolvedRouterEntry: resolveRouterEntry2,
9872
+ loggerRef
9873
+ });
9874
+ const virtualModules = createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata);
9875
+ const annotatorUiPlugin = createAnnotatorUiPlugin({
9876
+ ...annotatorRuntime.ui,
9877
+ enabled: annotatorRuntime.enabled && annotatorRuntime.ui.enabled,
9878
+ sourceAttribute: annotatorRuntime.sourceAttribute,
9879
+ metadataAttributePrefix: annotatorRuntime.metadataAttributePrefix
9880
+ });
9881
+ return [tsProcessor, devProcessor, virtualModules, annotatorUiPlugin];
9595
9882
  }
9596
9883
  const nuxtConfigMarker$1 = /* @__PURE__ */ Symbol.for("@immense/vue-pom-generator.nuxt");
9597
9884
  const nuxtConfigFileNames = [