@immense/vue-pom-generator 1.0.88 → 1.0.90

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 +12 -0
  2. package/RELEASE_NOTES.md +63 -36
  3. package/class-generation/index.ts +6 -11
  4. package/dist/class-generation/index.d.ts.map +1 -1
  5. package/dist/eslint/index.cjs +42 -0
  6. package/dist/eslint/index.cjs.map +1 -1
  7. package/dist/eslint/index.d.ts +3 -0
  8. package/dist/eslint/index.d.ts.map +1 -1
  9. package/dist/eslint/index.mjs +42 -0
  10. package/dist/eslint/index.mjs.map +1 -1
  11. package/dist/eslint/no-data-testid-in-specs.d.ts +3 -0
  12. package/dist/eslint/no-data-testid-in-specs.d.ts.map +1 -0
  13. package/dist/index.cjs +1481 -1529
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.mjs +1472 -1520
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/manifest-generator.d.ts.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/router-bridge.d.ts +18 -0
  31. package/dist/router-bridge.d.ts.map +1 -0
  32. package/dist/router.cjs +9 -0
  33. package/dist/router.cjs.map +1 -0
  34. package/dist/router.mjs +9 -0
  35. package/dist/router.mjs.map +1 -0
  36. package/dist/tests/existing-id-behavior.test.d.ts +2 -0
  37. package/dist/tests/existing-id-behavior.test.d.ts.map +1 -0
  38. package/dist/tests/router-bridge.test.d.ts +2 -0
  39. package/dist/tests/router-bridge.test.d.ts.map +1 -0
  40. package/dist/utils.d.ts +0 -11
  41. package/dist/utils.d.ts.map +1 -1
  42. package/dist/vite.config.d.ts.map +1 -1
  43. package/package.json +6 -1
package/dist/index.mjs CHANGED
@@ -10,8 +10,9 @@ import { parseExpression, parse } from "@babel/parser";
10
10
  import { NodeTypes, stringifyExpression, ConstantTypes, createSimpleExpression, ElementTypes } from "@vue/compiler-core";
11
11
  import { Project, QuoteKind, NewLineKind, IndentationText, CodeBlockWriter, StructureKind, VariableDeclarationKind } from "ts-morph";
12
12
  import { isIdentifier, isObjectPattern, isRestElement, isObjectProperty, isArrayExpression, isStringLiteral, isTemplateLiteral, isArrowFunctionExpression, isExpressionStatement, isAssignmentPattern, isMemberExpression, isOptionalMemberExpression, isCallExpression, isOptionalCallExpression, isAssignmentExpression, isObjectExpression, isFile, isBlockStatement, isLogicalExpression, isConditionalExpression, isSequenceExpression, isProgram, VISITOR_KEYS, isBooleanLiteral, isNumericLiteral, isNullLiteral } from "@babel/types";
13
- import { performance } from "node:perf_hooks";
13
+ import { POM_ROUTER_GLOBAL_NAME } from "./router.mjs";
14
14
  import vue from "@vitejs/plugin-vue";
15
+ import { performance } from "node:perf_hooks";
15
16
  import { autoUpdate, computePosition, offset, autoPlacement, shift, arrow } from "@floating-ui/dom";
16
17
  const VUE_POM_GENERATOR_LOG_PREFIX = "[vue-pom-generator]";
17
18
  function normalize(message) {
@@ -3603,54 +3604,6 @@ function buildPomGeneratedPropertyName(pom) {
3603
3604
  function buildPomGeneratedActionName(pom) {
3604
3605
  return requireStructuredPomName(pom.generatedActionName, "generatedActionName", pom);
3605
3606
  }
3606
- const STANDALONE_WRAPPER_FALLBACK_ROLES = /* @__PURE__ */ new Set([
3607
- "button",
3608
- "input",
3609
- "select",
3610
- "vselect",
3611
- "checkbox",
3612
- "toggle",
3613
- "radio",
3614
- "link",
3615
- "tab"
3616
- ]);
3617
- function stripTrailingAsciiDigits(value) {
3618
- let end = value.length;
3619
- while (end > 0 && isAsciiDigitCode(value.charCodeAt(end - 1))) {
3620
- end -= 1;
3621
- }
3622
- return value.slice(0, end);
3623
- }
3624
- function matchesStandaloneWrapperFallbackMethodName(methodName, componentClassName) {
3625
- let normalizedMethodName = methodName;
3626
- if (normalizedMethodName.endsWith("ByKey")) {
3627
- normalizedMethodName = normalizedMethodName.slice(0, -"ByKey".length);
3628
- }
3629
- normalizedMethodName = stripTrailingAsciiDigits(normalizedMethodName);
3630
- return normalizedMethodName === componentClassName;
3631
- }
3632
- function shouldSuppressStandaloneWrapperFallbackSurface(componentName, dependencies) {
3633
- if (dependencies.isView || (dependencies.pomExtraMethods?.length ?? 0) > 0) {
3634
- return false;
3635
- }
3636
- const entries = Array.from(dependencies.dataTestIdSet ?? []);
3637
- if (!entries.length) {
3638
- return false;
3639
- }
3640
- const primaryEntries = entries.filter((entry) => {
3641
- return !!entry.pom && entry.pom.emitPrimary !== false;
3642
- });
3643
- if (!primaryEntries.length || primaryEntries.length !== entries.length) {
3644
- return false;
3645
- }
3646
- const componentClassName = toPascalCase(componentName.endsWith(".vue") ? componentName.slice(0, -4) : componentName);
3647
- if (!componentClassName) {
3648
- return false;
3649
- }
3650
- return primaryEntries.every(({ pom }) => {
3651
- return STANDALONE_WRAPPER_FALLBACK_ROLES.has(pom.nativeRole) && matchesStandaloneWrapperFallbackMethodName(pom.methodName, componentClassName);
3652
- });
3653
- }
3654
3607
  function safeRealpath(value) {
3655
3608
  try {
3656
3609
  if (fs.existsSync(value)) {
@@ -4866,7 +4819,7 @@ const GOTO_RUNTIME_LINES = [
4866
4819
  "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
4867
4820
  "await this.page.goto(resolvedUrl);"
4868
4821
  ];
4869
- const ROUTER_GLOBAL_NAME = "__appRouter";
4822
+ const ROUTER_GLOBAL_NAME = POM_ROUTER_GLOBAL_NAME;
4870
4823
  const pushBlock = (routeNameExpr, paramsExpr, nullable) => {
4871
4824
  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 } } }`;
4872
4825
  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));`;
@@ -5114,11 +5067,7 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5114
5067
  componentDirs,
5115
5068
  layoutDirs
5116
5069
  }) : void 0);
5117
- const emittableComponentHierarchyMap = new Map(
5118
- Array.from(componentHierarchyMap.entries()).filter(([componentName, dependencies]) => {
5119
- return !shouldSuppressStandaloneWrapperFallbackSurface(componentName, dependencies);
5120
- })
5121
- );
5070
+ const emittableComponentHierarchyMap = componentHierarchyMap;
5122
5071
  const generatedFilePaths = [];
5123
5072
  const writeGeneratedFile = (file) => {
5124
5073
  const resolvedFilePath = path.resolve(file.filePath);
@@ -8041,1568 +7990,1571 @@ Fix: remove the explicit ${attrLabel}, or change existingIdBehavior to "overwrit
8041
7990
  }
8042
7991
  };
8043
7992
  }
8044
- function summarizeHierarchyMap(componentHierarchyMap) {
8045
- let interactiveComponentCount = 0;
8046
- let dataTestIdCount = 0;
8047
- for (const dependencies of componentHierarchyMap.values()) {
8048
- const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
8049
- if (selectorCount > 0) {
8050
- interactiveComponentCount += 1;
8051
- dataTestIdCount += selectorCount;
8052
- }
7993
+ function supportsInlineTextAccessibleName(role) {
7994
+ return role === "button" || role === "radio";
7995
+ }
7996
+ function buildAccessibilityAudit(metadata, inferredRole) {
7997
+ if (!metadata || !inferredRole) {
7998
+ return void 0;
7999
+ }
8000
+ const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8001
+ const dynamicProps = new Set(metadata.dynamicProps ?? []);
8002
+ const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8003
+ let accessibleNameSource;
8004
+ const reasons = [];
8005
+ if (metadata.staticAriaLabel) {
8006
+ accessibleNameSource = "aria-label";
8007
+ } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8008
+ accessibleNameSource = "text";
8009
+ } else if (metadata.staticTitle) {
8010
+ accessibleNameSource = "title";
8011
+ } else if (hasDynamicAccessibleNameSignal) {
8012
+ accessibleNameSource = "dynamic";
8013
+ } else if (role === "input" || role === "select") {
8014
+ accessibleNameSource = "unknown";
8015
+ reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8016
+ } else {
8017
+ accessibleNameSource = "missing";
8018
+ reasons.push("No compile-time accessible-name signal was found.");
8053
8019
  }
8054
8020
  return {
8055
- entryCount: componentHierarchyMap.size,
8056
- interactiveComponentCount,
8057
- dataTestIdCount
8021
+ needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8022
+ accessibleNameSource,
8023
+ reasons,
8024
+ ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8025
+ ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8026
+ ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8027
+ ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8058
8028
  };
8059
8029
  }
8060
- function isLessRich(candidate, previous) {
8061
- if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8062
- return candidate.dataTestIdCount < previous.dataTestIdCount;
8030
+ function collectAccessibilityReviewWarnings(manifest) {
8031
+ const warnings = [];
8032
+ for (const [componentName, component] of Object.entries(manifest)) {
8033
+ for (const entry of component.entries) {
8034
+ if (!entry.accessibility?.needsReview) {
8035
+ continue;
8036
+ }
8037
+ const entryLabel = entry.generatedPropertyName ?? entry.testId;
8038
+ const reasonText = entry.accessibility.reasons.join(" ");
8039
+ warnings.push(
8040
+ `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8041
+ );
8042
+ }
8063
8043
  }
8064
- if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8065
- return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8044
+ return warnings;
8045
+ }
8046
+ function findDataTestIdProp(element, attributeName = "data-testid") {
8047
+ return element.props.find(
8048
+ (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName || prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName
8049
+ );
8050
+ }
8051
+ function getTestIdFromProp(prop) {
8052
+ if (!prop) {
8053
+ return null;
8066
8054
  }
8067
- return candidate.entryCount < previous.entryCount;
8055
+ if (prop.type === NodeTypes.ATTRIBUTE) {
8056
+ return prop.value ? prop.value.content : null;
8057
+ }
8058
+ if (prop.type === NodeTypes.DIRECTIVE) {
8059
+ return prop.exp?.type === NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content : null;
8060
+ }
8061
+ return null;
8068
8062
  }
8069
- function createBuildProcessorPlugin(options) {
8070
- const {
8071
- componentHierarchyMap,
8072
- crossFileKeyRegistry,
8073
- vueFilesPathMap,
8074
- getPageDirs,
8075
- getComponentDirs,
8076
- getLayoutDirs,
8077
- getViewsDir,
8078
- getSourceDirs,
8079
- basePageClassPath,
8080
- normalizedBasePagePath,
8081
- generation,
8082
- projectRootRef,
8083
- nativeWrappers,
8084
- optionKeyAttribute,
8085
- excludedComponents,
8086
- getWrapperSearchRoots,
8087
- getResolvedRouterEntry,
8088
- loggerRef
8089
- } = options;
8090
- const {
8091
- outDir,
8092
- emitLanguages,
8093
- typescriptOutputStructure,
8094
- csharp,
8095
- generateFixtures,
8096
- customPomAttachments,
8097
- customPomDir,
8098
- requireCustomPomDir,
8099
- customPomImportAliases,
8100
- customPomImportNameCollisionBehavior,
8101
- testIdAttribute,
8102
- nameCollisionBehavior,
8103
- missingSemanticNameBehavior,
8104
- existingIdBehavior,
8105
- routerAwarePoms,
8106
- routerType,
8107
- routerModuleShims
8108
- } = generation;
8109
- let lastGeneratedMetrics = {
8110
- entryCount: 0,
8111
- interactiveComponentCount: 0,
8112
- dataTestIdCount: 0
8113
- };
8114
- const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
8115
- const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
8116
- const getScriptInfo = (source, filename) => {
8117
- try {
8118
- const { descriptor } = parse$1(source, { filename });
8119
- if (!descriptor.script && !descriptor.scriptSetup)
8120
- return { bindings: void 0, isScriptSetup: false };
8121
- const scriptBlock = compileScript(descriptor, { id: filename });
8122
- return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
8123
- } catch {
8124
- return { bindings: void 0, isScriptSetup: false };
8063
+ function parseDynamicProps(dynamicProps) {
8064
+ if (!dynamicProps) {
8065
+ return void 0;
8066
+ }
8067
+ if (typeof dynamicProps === "string") {
8068
+ const parts = [];
8069
+ let current = "";
8070
+ for (let i = 0; i < dynamicProps.length; i++) {
8071
+ const ch = dynamicProps[i];
8072
+ if (ch === ",") {
8073
+ const token = current.trim();
8074
+ if (token.length)
8075
+ parts.push(token);
8076
+ current = "";
8077
+ continue;
8078
+ }
8079
+ current += ch;
8125
8080
  }
8126
- };
8127
- const supplementHierarchyFromFilesystem = () => {
8128
- const walkFilesRecursive = (rootDir) => {
8129
- const out = [];
8130
- const stack = [rootDir];
8131
- while (stack.length) {
8132
- const dir = stack.pop();
8133
- if (!dir) continue;
8134
- let entries = [];
8135
- try {
8136
- entries = fs.readdirSync(dir, { withFileTypes: true });
8137
- } catch {
8138
- continue;
8139
- }
8140
- for (const ent of entries) {
8141
- if (ent.isDirectory()) {
8142
- if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8143
- continue;
8144
- stack.push(path.join(dir, ent.name));
8145
- continue;
8146
- }
8147
- if (ent.isFile() && ent.name.endsWith(".vue")) {
8148
- out.push(path.join(dir, ent.name));
8149
- }
8150
- }
8081
+ const last = current.trim();
8082
+ if (last.length)
8083
+ parts.push(last);
8084
+ return parts;
8085
+ }
8086
+ if (isSimpleExpressionNode(dynamicProps)) {
8087
+ const content = dynamicProps.content;
8088
+ if (content.startsWith("[") && content.endsWith("]")) {
8089
+ try {
8090
+ return JSON.parse(content);
8091
+ } catch {
8092
+ return void 0;
8151
8093
  }
8152
- return out;
8153
- };
8154
- let supplemented = 0;
8155
- for (const dir of getSourceDirs()) {
8156
- const absDir = path.resolve(projectRootRef.current, dir);
8157
- if (!fs.existsSync(absDir))
8158
- continue;
8159
- for (const filePath of walkFilesRecursive(absDir)) {
8160
- const absolutePath = path.resolve(filePath);
8161
- const componentName = resolveComponentNameFromPath({
8162
- filename: absolutePath,
8163
- projectRoot: projectRootRef.current,
8164
- viewsDirAbs: getViewsDirAbs(),
8165
- sourceDirs: getSourceDirs(),
8166
- extraRoots: [process.cwd()]
8167
- });
8168
- if (componentHierarchyMap.has(componentName))
8169
- continue;
8170
- let sfc = "";
8171
- try {
8172
- sfc = fs.readFileSync(absolutePath, "utf8");
8173
- } catch {
8174
- continue;
8094
+ }
8095
+ return [content];
8096
+ }
8097
+ return void 0;
8098
+ }
8099
+ function findStaticAttributeValue(element, attributeName) {
8100
+ const attribute = element.props.find(
8101
+ (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName
8102
+ );
8103
+ const value = attribute?.value?.content?.trim();
8104
+ return value || void 0;
8105
+ }
8106
+ function collectStaticTextContent(children) {
8107
+ const parts = [];
8108
+ const visit = (nodes) => {
8109
+ for (const node of nodes) {
8110
+ if (node.type === NodeTypes.TEXT) {
8111
+ const text2 = collapseWhitespace(node.content);
8112
+ if (text2) {
8113
+ parts.push(text2);
8175
8114
  }
8176
- const { descriptor } = parse$1(sfc, { filename: absolutePath });
8177
- const template = descriptor.template?.content ?? "";
8178
- if (!template.trim()) {
8179
- vueFilesPathMap.set(componentName, absolutePath);
8180
- componentHierarchyMap.set(componentName, {
8181
- filePath: absolutePath,
8182
- childrenComponentSet: /* @__PURE__ */ new Set(),
8183
- usedComponentSet: /* @__PURE__ */ new Set(),
8184
- dataTestIdSet: /* @__PURE__ */ new Set(),
8185
- isView: false,
8186
- methodsContent: ""
8187
- });
8188
- supplemented++;
8189
- continue;
8190
- }
8191
- const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8192
- vueFilesPathMap.set(componentName, absolutePath);
8193
- try {
8194
- compilerDom.compile(template, {
8195
- filename: absolutePath,
8196
- prefixIdentifiers: true,
8197
- inline: isScriptSetup,
8198
- bindingMetadata,
8199
- // See dev-plugin.ts — same rationale: enable TS in template
8200
- // expressions so `(row: RowType) => ...` handlers parse.
8201
- expressionPlugins: ["typescript"],
8202
- nodeTransforms: [
8203
- createTestIdTransform(
8204
- componentName,
8205
- componentHierarchyMap,
8206
- nativeWrappers,
8207
- excludedComponents,
8208
- getViewsDirAbs(),
8209
- {
8210
- existingIdBehavior: existingIdBehavior ?? "error",
8211
- testIdAttribute,
8212
- nameCollisionBehavior,
8213
- missingSemanticNameBehavior,
8214
- warn: (message) => loggerRef.current.warn(message),
8215
- vueFilesPathMap,
8216
- wrapperSearchRoots: getWrapperSearchRoots(),
8217
- crossFileKeyRegistry,
8218
- optionKeyAttribute
8219
- }
8220
- )
8221
- ]
8222
- });
8223
- } catch {
8224
- }
8225
- supplemented++;
8115
+ continue;
8116
+ }
8117
+ if (node.type === NodeTypes.ELEMENT) {
8118
+ visit(node.children);
8226
8119
  }
8227
- }
8228
- if (supplemented > 0) {
8229
- loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
8230
8120
  }
8231
8121
  };
8232
- return {
8233
- name: "vue-pom-generator-build",
8234
- // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
8235
- apply: "build",
8236
- enforce: "pre",
8237
- async buildStart() {
8238
- if (!routerAwarePoms) {
8239
- setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8240
- setResolveToComponentNameFn(() => null);
8241
- return;
8242
- }
8243
- let result;
8244
- if (routerType === "nuxt") {
8245
- result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8246
- } else {
8247
- const resolvedRouterEntry = getResolvedRouterEntry();
8248
- if (!resolvedRouterEntry)
8249
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8250
- result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8251
- moduleShims: routerModuleShims,
8252
- componentNaming: {
8253
- projectRoot: projectRootRef.current,
8254
- viewsDirAbs: getViewsDirAbs(),
8255
- sourceDirs: getSourceDirs()
8256
- }
8257
- });
8258
- }
8259
- const { routeNameMap, routePathMap } = result;
8260
- setRouteNameToComponentNameMap(routeNameMap);
8261
- setResolveToComponentNameFn((to) => {
8262
- if (typeof to === "string") {
8263
- return routePathMap.get(to) ?? null;
8264
- }
8265
- const maybe = to;
8266
- if (typeof maybe.name === "string" && maybe.name.length) {
8267
- const key = toPascalCase(maybe.name);
8268
- return routeNameMap.get(key) ?? null;
8269
- }
8270
- if (typeof maybe.path === "string" && maybe.path.length) {
8271
- return routePathMap.get(maybe.path) ?? null;
8272
- }
8273
- return null;
8274
- });
8275
- if (!fs.existsSync(basePageClassPath)) {
8276
- this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
8277
- }
8278
- this.addWatchFile(basePageClassPath);
8279
- const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
8280
- if (!fs.existsSync(pointerPath)) {
8281
- this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
8282
- }
8283
- this.addWatchFile(pointerPath);
8284
- const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
8285
- if (!fs.existsSync(calloutPath)) {
8286
- this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
8287
- }
8288
- this.addWatchFile(calloutPath);
8289
- const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
8290
- if (fs.existsSync(floatingUiCalloutPath)) {
8291
- this.addWatchFile(floatingUiCalloutPath);
8292
- }
8293
- },
8294
- async buildEnd(error) {
8295
- if (error) {
8296
- return;
8297
- }
8298
- supplementHierarchyFromFilesystem();
8299
- const metrics = summarizeHierarchyMap(componentHierarchyMap);
8300
- if (metrics.dataTestIdCount <= 0) {
8301
- return;
8302
- }
8303
- if (isLessRich(metrics, lastGeneratedMetrics)) {
8304
- return;
8305
- }
8306
- await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
8307
- outDir,
8308
- emitLanguages,
8309
- typescriptOutputStructure,
8310
- csharp,
8311
- generateFixtures,
8312
- customPomAttachments,
8313
- projectRoot: projectRootRef.current,
8314
- customPomDir,
8315
- requireCustomPomDir,
8316
- customPomImportAliases,
8317
- customPomImportNameCollisionBehavior,
8318
- testIdAttribute,
8319
- vueRouterFluentChaining: routerAwarePoms,
8320
- routerEntry: getResolvedRouterEntry(),
8321
- routerType,
8322
- pageDirs: getPageDirs(),
8323
- componentDirs: getComponentDirs(),
8324
- layoutDirs: getLayoutDirs()
8325
- });
8326
- lastGeneratedMetrics = metrics;
8327
- loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
8328
- },
8329
- closeBundle() {
8330
- loggerRef.current.info("build complete");
8122
+ visit(children);
8123
+ const text = collapseWhitespace(parts.join(" "));
8124
+ return text || void 0;
8125
+ }
8126
+ function tryCreateElementMetadata(args) {
8127
+ const { element, semanticNameMap } = args;
8128
+ const testIdAttribute = (args.testIdAttribute ?? "data-testid").trim() || "data-testid";
8129
+ const testIdProp = findDataTestIdProp(element, testIdAttribute);
8130
+ if (!testIdProp) {
8131
+ return null;
8132
+ }
8133
+ const testId = getTestIdFromProp(testIdProp);
8134
+ if (!testId) {
8135
+ return null;
8136
+ }
8137
+ if (!element.codegenNode || element.codegenNode.type !== NodeTypes.VNODE_CALL) {
8138
+ return null;
8139
+ }
8140
+ const codegenNode = element.codegenNode;
8141
+ const patchFlag = codegenNode.patchFlag;
8142
+ let dynamicPropsList = parseDynamicProps(codegenNode.dynamicProps);
8143
+ if (!dynamicPropsList && codegenNode.dynamicProps && typeof codegenNode.dynamicProps !== "string" && isSimpleExpressionNode(codegenNode.dynamicProps)) {
8144
+ const content = codegenNode.dynamicProps.content;
8145
+ if (content.startsWith("[") && content.endsWith("]")) {
8146
+ dynamicPropsList = [content];
8331
8147
  }
8148
+ }
8149
+ const metadata = {
8150
+ testId,
8151
+ semanticName: semanticNameMap.get(testId),
8152
+ tag: element.tag,
8153
+ tagType: element.tagType,
8154
+ patchFlag,
8155
+ dynamicProps: dynamicPropsList,
8156
+ // Decode patch flags (bitwise) - preserved as-is from existing code.
8157
+ hasClickHandler: patchFlag ? Boolean(patchFlag & 32) : void 0,
8158
+ hasDynamicClass: patchFlag ? Boolean(patchFlag & 2) : void 0,
8159
+ hasDynamicStyle: patchFlag ? Boolean(patchFlag & 4) : void 0,
8160
+ hasDynamicText: patchFlag ? Boolean(patchFlag & 1) : void 0,
8161
+ staticAriaLabel: findStaticAttributeValue(element, "aria-label"),
8162
+ staticRole: findStaticAttributeValue(element, "role"),
8163
+ staticTitle: findStaticAttributeValue(element, "title"),
8164
+ staticTextContent: collectStaticTextContent(element.children),
8165
+ sourceLine: element.loc?.start.line,
8166
+ sourceColumn: element.loc?.start.column
8332
8167
  };
8168
+ return metadata;
8333
8169
  }
8334
- function createDevProcessorPlugin(options) {
8335
- const {
8336
- nativeWrappers,
8337
- optionKeyAttribute,
8338
- excludedComponents,
8339
- getPageDirs,
8340
- getComponentDirs,
8341
- getLayoutDirs,
8342
- getViewsDir,
8343
- getSourceDirs,
8344
- getWrapperSearchRoots,
8345
- projectRootRef,
8346
- normalizedBasePagePath,
8347
- basePageClassPath,
8348
- generation,
8349
- getResolvedRouterEntry,
8350
- loggerRef
8351
- } = options;
8352
- const {
8353
- outDir,
8354
- emitLanguages,
8355
- typescriptOutputStructure,
8356
- csharp,
8357
- generateFixtures,
8358
- customPomAttachments,
8359
- customPomDir,
8360
- requireCustomPomDir,
8361
- customPomImportAliases,
8362
- customPomImportNameCollisionBehavior,
8363
- nameCollisionBehavior,
8364
- missingSemanticNameBehavior,
8365
- existingIdBehavior,
8366
- testIdAttribute,
8367
- routerAwarePoms,
8368
- routerType,
8369
- routerModuleShims
8370
- } = generation;
8371
- let scheduleVueFileRegen = null;
8372
- const getProjectRootCandidates = () => Array.from(/* @__PURE__ */ new Set([
8373
- path.resolve(projectRootRef.current),
8374
- path.resolve(process.cwd())
8170
+ function matchesPrimarySelector(extraMethod, pom) {
8171
+ if (extraMethod.selector.kind !== "testId") {
8172
+ return false;
8173
+ }
8174
+ return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8175
+ }
8176
+ function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8177
+ const testId = entry.selectorValue.formatted;
8178
+ const metadata = componentMetadata?.get(testId);
8179
+ const pom = entry.pom;
8180
+ const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8181
+ const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8182
+ const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8183
+ ...generatedActionName ? [generatedActionName] : [],
8184
+ ...extraActionNames.filter((name) => name !== generatedActionName)
8375
8185
  ]));
8376
- const resolveProjectPath = (maybePath) => {
8377
- if (path.isAbsolute(maybePath))
8378
- return maybePath;
8379
- const candidates = getProjectRootCandidates().map((root) => path.resolve(root, maybePath));
8380
- return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
8381
- };
8382
- const getSourceDirRoots = () => Array.from(new Set(
8383
- getProjectRootCandidates().flatMap((root) => getSourceDirs().map((dir) => path.resolve(root, dir)))
8384
- ));
8385
- const isContainedInScanDirs = (filePath) => {
8386
- const absolutePath = path.resolve(filePath);
8387
- return getSourceDirRoots().some((scanDirAbs) => isPathWithinDir(absolutePath, scanDirAbs));
8388
- };
8186
+ const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8389
8187
  return {
8390
- name: "vue-pom-generator-dev",
8391
- apply: "serve",
8392
- // Prefer hot-update events over filesystem change events for speed and reliability.
8393
- // This fires when Vite has actually processed the module update.
8394
- handleHotUpdate(ctx) {
8395
- if (!scheduleVueFileRegen)
8396
- return;
8397
- if (!ctx.file.endsWith(".vue"))
8398
- return;
8399
- if (!isContainedInScanDirs(ctx.file))
8400
- return;
8401
- scheduleVueFileRegen(ctx.file, "hmr");
8402
- },
8403
- async configureServer(server) {
8404
- const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
8405
- const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
8406
- const routerInitPromise = (async () => {
8407
- if (!routerAwarePoms) {
8408
- setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8409
- setResolveToComponentNameFn(() => null);
8410
- return;
8188
+ testId,
8189
+ selectorPatternKind: entry.selectorValue.patternKind,
8190
+ semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8191
+ locatorDescription: pom ? buildPomLocatorDescription({
8192
+ componentName,
8193
+ methodName: pom.methodName,
8194
+ nativeRole: pom.nativeRole
8195
+ }) : componentName,
8196
+ inferredRole: pom?.nativeRole ?? null,
8197
+ ...accessibility ? { accessibility } : {},
8198
+ generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8199
+ generatedActionName,
8200
+ generatedActionNames,
8201
+ emitPrimary: pom?.emitPrimary !== false,
8202
+ ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8203
+ ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8204
+ ...metadata ? { sourceTagType: metadata.tagType } : {},
8205
+ ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8206
+ ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8207
+ ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8208
+ ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8209
+ ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8210
+ ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8211
+ ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8212
+ ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8213
+ };
8214
+ }
8215
+ function buildPomManifest(componentHierarchyMap, elementMetadata) {
8216
+ const manifestEntries = Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8217
+ 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 ?? []));
8218
+ if (!entries.length) {
8219
+ return null;
8220
+ }
8221
+ return [componentName, {
8222
+ componentName,
8223
+ className: componentName,
8224
+ sourceFile: dependencies.filePath,
8225
+ kind: dependencies.isView ? "view" : "component",
8226
+ testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8227
+ entries
8228
+ }];
8229
+ }).filter((entry) => entry !== null);
8230
+ return Object.fromEntries(manifestEntries);
8231
+ }
8232
+ function buildTestIdManifest(componentHierarchyMap) {
8233
+ return Object.fromEntries(
8234
+ Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8235
+ const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8236
+ if (!testIds.length) {
8237
+ return null;
8238
+ }
8239
+ return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8240
+ }).filter((entry) => entry !== null)
8241
+ );
8242
+ }
8243
+ function writeConstJson(value) {
8244
+ return (writer) => {
8245
+ writer.write(`${JSON.stringify(value, null, 2)} as const`);
8246
+ };
8247
+ }
8248
+ function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8249
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8250
+ const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8251
+ return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8252
+ sourceFile.addStatements("// Virtual module: test id manifest");
8253
+ sourceFile.addVariableStatement({
8254
+ declarationKind: VariableDeclarationKind.Const,
8255
+ isExported: true,
8256
+ declarations: [{
8257
+ name: "testIdManifest",
8258
+ initializer: writeConstJson(testIdManifest)
8259
+ }]
8260
+ });
8261
+ sourceFile.addVariableStatement({
8262
+ declarationKind: VariableDeclarationKind.Const,
8263
+ isExported: true,
8264
+ declarations: [{
8265
+ name: "pomManifest",
8266
+ initializer: writeConstJson(pomManifest)
8267
+ }]
8268
+ });
8269
+ sourceFile.addTypeAlias({
8270
+ isExported: true,
8271
+ name: "TestIdManifest",
8272
+ type: "typeof testIdManifest"
8273
+ });
8274
+ sourceFile.addTypeAlias({
8275
+ isExported: true,
8276
+ name: "ComponentName",
8277
+ type: "keyof TestIdManifest"
8278
+ });
8279
+ sourceFile.addTypeAlias({
8280
+ isExported: true,
8281
+ name: "PomManifest",
8282
+ type: "typeof pomManifest"
8283
+ });
8284
+ sourceFile.addTypeAlias({
8285
+ isExported: true,
8286
+ name: "PomManifestComponentName",
8287
+ type: "keyof PomManifest"
8288
+ });
8289
+ });
8290
+ }
8291
+ function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8292
+ const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8293
+ return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8294
+ sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8295
+ sourceFile.addVariableStatement({
8296
+ declarationKind: VariableDeclarationKind.Const,
8297
+ isExported: true,
8298
+ declarations: [{
8299
+ name: "pomManifest",
8300
+ initializer: writeConstJson(pomManifest)
8301
+ }]
8302
+ });
8303
+ sourceFile.addTypeAlias({
8304
+ isExported: true,
8305
+ name: "PomManifest",
8306
+ type: "typeof pomManifest"
8307
+ });
8308
+ sourceFile.addTypeAlias({
8309
+ isExported: true,
8310
+ name: "PomManifestComponentName",
8311
+ type: "keyof PomManifest"
8312
+ });
8313
+ });
8314
+ }
8315
+ function resolveExistingIdBehavior(config, componentName) {
8316
+ return typeof config === "string" ? config : config.components[componentName] ?? config.default;
8317
+ }
8318
+ function resolveCompilerSfcParse(compilerSfc) {
8319
+ const parse2 = compilerSfc.parse ?? compilerSfc.default?.parse;
8320
+ if (typeof parse2 !== "function") {
8321
+ throw new TypeError("[vue-pom-generator] Failed to resolve @vue/compiler-sfc.parse.");
8322
+ }
8323
+ return parse2;
8324
+ }
8325
+ function extractMetadataAfterTransform(ast, componentName, elementMetadata, semanticNameMap, testIdAttribute) {
8326
+ const componentMetadata = /* @__PURE__ */ new Map();
8327
+ function traverseNode(node) {
8328
+ if (node.type === NodeTypes.ELEMENT) {
8329
+ const element = node;
8330
+ const testIdAttr = findDataTestIdProp(element, testIdAttribute);
8331
+ if (testIdAttr) {
8332
+ const metadata = tryCreateElementMetadata({
8333
+ element,
8334
+ semanticNameMap,
8335
+ testIdAttribute
8336
+ });
8337
+ if (metadata) {
8338
+ componentMetadata.set(metadata.testId, metadata);
8411
8339
  }
8412
- let result;
8413
- if (routerType === "nuxt") {
8414
- result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8415
- } else {
8416
- const resolvedRouterEntry = getResolvedRouterEntry();
8417
- if (!resolvedRouterEntry)
8418
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8419
- result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8420
- moduleShims: routerModuleShims,
8421
- componentNaming: {
8422
- projectRoot: projectRootRef.current,
8423
- viewsDirAbs: getViewsDirAbs(),
8424
- sourceDirs: getSourceDirs(),
8425
- extraRoots: [process.cwd()]
8426
- }
8427
- });
8340
+ }
8341
+ if (element.children) {
8342
+ for (const child of element.children) {
8343
+ traverseNode(child);
8428
8344
  }
8429
- const { routeNameMap, routePathMap } = result;
8430
- setRouteNameToComponentNameMap(routeNameMap);
8431
- setResolveToComponentNameFn((to) => {
8432
- if (typeof to === "string") {
8433
- return routePathMap.get(to) ?? null;
8434
- }
8435
- const maybe = to;
8436
- if (typeof maybe.name === "string" && maybe.name.length) {
8437
- const key = toPascalCase(maybe.name);
8438
- return routeNameMap.get(key) ?? null;
8439
- }
8440
- if (typeof maybe.path === "string" && maybe.path.length) {
8441
- return routePathMap.get(maybe.path) ?? null;
8442
- }
8443
- return null;
8444
- });
8445
- })();
8446
- const logInfo = (message) => loggerRef.current.info(message);
8447
- const logDebug = (message) => loggerRef.current.debug(message);
8448
- let scheduleVueFileRegenLocal = null;
8449
- const formatMs = (ms) => `${ms.toFixed(1)}ms`;
8450
- const extractTemplateFromSfc = (source, filename) => {
8451
- const { descriptor } = parse$1(source, {
8452
- filename: filename ?? "anonymous.vue"
8453
- });
8454
- return descriptor.template?.content ?? "";
8455
- };
8456
- const getScriptInfo = (source, filename) => {
8457
- try {
8458
- const { descriptor } = parse$1(source, { filename });
8459
- if (!descriptor.script && !descriptor.scriptSetup)
8460
- return { bindings: void 0, isScriptSetup: false };
8461
- const scriptBlock = compileScript(descriptor, { id: filename });
8462
- return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
8463
- } catch {
8464
- return { bindings: void 0, isScriptSetup: false };
8345
+ }
8346
+ } else if (node.type === NodeTypes.IF) {
8347
+ for (const branch of node.branches) {
8348
+ traverseNode(branch);
8349
+ }
8350
+ } else if (node.type === NodeTypes.IF_BRANCH || node.type === NodeTypes.FOR) {
8351
+ if (node.children) {
8352
+ for (const child of node.children) {
8353
+ traverseNode(child);
8465
8354
  }
8466
- };
8467
- const walkFilesRecursive = (rootDir) => {
8468
- const out = [];
8469
- const stack = [rootDir];
8470
- while (stack.length) {
8471
- const dir = stack.pop();
8472
- if (!dir) continue;
8473
- let entries = [];
8474
- try {
8475
- entries = fs.readdirSync(dir, { withFileTypes: true });
8476
- } catch {
8477
- continue;
8478
- }
8479
- for (const ent of entries) {
8480
- if (ent.isDirectory()) {
8481
- if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8482
- continue;
8483
- stack.push(path.join(dir, ent.name));
8484
- continue;
8485
- }
8486
- if (ent.isFile() && ent.name.endsWith(".vue")) {
8487
- out.push(path.join(dir, ent.name));
8488
- }
8489
- }
8490
- }
8491
- return out;
8492
- };
8493
- let snapshotHierarchy = /* @__PURE__ */ new Map();
8494
- let snapshotVuePathMap = /* @__PURE__ */ new Map();
8495
- const filePathToComponentName = /* @__PURE__ */ new Map();
8496
- const createEmptyComponentDependencies = (absolutePath) => {
8497
- const viewsDirAbs = path.resolve(getViewsDirAbs());
8498
- const relToViewsDir = path.relative(viewsDirAbs, absolutePath);
8499
- const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
8500
- return {
8501
- filePath: absolutePath,
8502
- childrenComponentSet: /* @__PURE__ */ new Set(),
8503
- usedComponentSet: /* @__PURE__ */ new Set(),
8504
- dataTestIdSet: /* @__PURE__ */ new Set(),
8505
- isView,
8506
- methodsContent: ""
8507
- };
8508
- };
8509
- const getComponentNameForFile = (filePath) => {
8510
- const normalized = path.resolve(filePath);
8511
- const existing = filePathToComponentName.get(normalized);
8512
- if (existing)
8513
- return existing;
8514
- const name = resolveComponentNameFromPath({
8515
- filename: normalized,
8516
- projectRoot: projectRootRef.current,
8517
- viewsDirAbs: getViewsDirAbs(),
8518
- sourceDirs: getSourceDirs(),
8519
- extraRoots: [process.cwd()]
8520
- });
8521
- filePathToComponentName.set(normalized, name);
8522
- return name;
8523
- };
8524
- const compileVueFileIntoSnapshot = (filePath, targetHierarchy = snapshotHierarchy, targetVuePathMap = snapshotVuePathMap) => {
8525
- const started = performance.now();
8526
- const absolutePath = path.resolve(filePath);
8527
- const componentName = getComponentNameForFile(absolutePath);
8528
- let sfc = "";
8529
- try {
8530
- sfc = fs.readFileSync(absolutePath, "utf8");
8531
- } catch {
8532
- return { componentName, ms: performance.now() - started, compiled: false };
8533
- }
8534
- const template = extractTemplateFromSfc(sfc, absolutePath);
8535
- if (!template.trim()) {
8536
- targetVuePathMap.set(componentName, absolutePath);
8537
- targetHierarchy.set(componentName, createEmptyComponentDependencies(absolutePath));
8538
- return { componentName, ms: performance.now() - started, compiled: true };
8539
- }
8540
- const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8541
- const provisionalHierarchy = /* @__PURE__ */ new Map();
8542
- const provisionalKeyRegistry = /* @__PURE__ */ new Map();
8543
- const provisionalVuePathMap = new Map(targetVuePathMap);
8544
- provisionalVuePathMap.set(componentName, absolutePath);
8545
- compilerDom.compile(template, {
8546
- filename: absolutePath,
8547
- prefixIdentifiers: true,
8548
- inline: isScriptSetup,
8549
- bindingMetadata,
8550
- // Vue templates may contain TypeScript type annotations in expressions
8551
- // (e.g. `@row-click="(row: RowType) => navigateTo(...)"` in Nuxt + TS
8552
- // apps). Without this flag, Vue's internal processExpression step
8553
- // delegates to @babel/parser without the TS plugin and crashes on
8554
- // "Unexpected token, expected ','".
8555
- expressionPlugins: ["typescript"],
8556
- nodeTransforms: [
8355
+ }
8356
+ } else if (node.type === NodeTypes.ROOT) {
8357
+ for (const child of node.children) {
8358
+ traverseNode(child);
8359
+ }
8360
+ }
8361
+ }
8362
+ traverseNode(ast);
8363
+ if (componentMetadata.size > 0) {
8364
+ elementMetadata.set(componentName, componentMetadata);
8365
+ }
8366
+ return componentMetadata;
8367
+ }
8368
+ function createVuePluginWithTestIds(options) {
8369
+ const {
8370
+ vueOptions,
8371
+ existingIdBehavior,
8372
+ nameCollisionBehavior,
8373
+ missingSemanticNameBehavior = "error",
8374
+ nativeWrappers,
8375
+ optionKeyAttribute,
8376
+ elementMetadata,
8377
+ semanticNameMap,
8378
+ componentHierarchyMap,
8379
+ crossFileKeyRegistry,
8380
+ vueFilesPathMap,
8381
+ excludedComponents,
8382
+ getViewsDirAbs,
8383
+ testIdAttribute,
8384
+ accessibilityAudit,
8385
+ loggerRef,
8386
+ getSourceDirs,
8387
+ getWrapperSearchRoots,
8388
+ getProjectRoot,
8389
+ annotatorMetadata
8390
+ } = options;
8391
+ const lastAccessibilityWarningSignatureByComponent = /* @__PURE__ */ new Map();
8392
+ const getComponentNameFromPath = (filename) => {
8393
+ return resolveComponentNameFromPath({
8394
+ filename,
8395
+ projectRoot: getProjectRoot(),
8396
+ viewsDirAbs: getViewsDirAbs(),
8397
+ sourceDirs: getSourceDirs(),
8398
+ extraRoots: [process.cwd()]
8399
+ });
8400
+ };
8401
+ const isFileInScope = (filename) => {
8402
+ if (!filename)
8403
+ return false;
8404
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8405
+ const projectRoot = getProjectRoot();
8406
+ const matched = isFileInConfiguredSourceScope({
8407
+ filename,
8408
+ projectRoot,
8409
+ viewsDirAbs: getViewsDirAbs(),
8410
+ sourceDirs: getSourceDirs(),
8411
+ extraRoots: [process.cwd()]
8412
+ });
8413
+ if (cleanPath.endsWith(".vue") && !matched) {
8414
+ const absFilename = path.normalize(path.isAbsolute(cleanPath) ? cleanPath : path.resolve(projectRoot, cleanPath));
8415
+ loggerRef.current.debug(`[isFileInScope] REJECTED: ${absFilename} (Clean: ${cleanPath})`);
8416
+ }
8417
+ return matched;
8418
+ };
8419
+ const userTemplate = vueOptions?.template ?? {};
8420
+ const userCompilerOptions = userTemplate.compilerOptions ?? {};
8421
+ const userNodeTransforms = userCompilerOptions.nodeTransforms ?? [];
8422
+ const perFileTransform = /* @__PURE__ */ new Map();
8423
+ const getNodeTransforms = (filename, componentNameOverride) => {
8424
+ const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
8425
+ const viewsDirAbs = getViewsDirAbs();
8426
+ const componentName = componentNameOverride || getComponentNameFromPath(cleanPath);
8427
+ return [
8428
+ ...userNodeTransforms,
8429
+ (node, context) => {
8430
+ if (node.type === NodeTypes.ROOT) {
8431
+ componentHierarchyMap.delete(componentName);
8432
+ vueFilesPathMap.set(componentName, filename);
8433
+ perFileTransform.set(
8434
+ componentName,
8557
8435
  createTestIdTransform(
8558
8436
  componentName,
8559
- provisionalHierarchy,
8437
+ componentHierarchyMap,
8560
8438
  nativeWrappers,
8561
8439
  excludedComponents,
8562
- getViewsDirAbs(),
8440
+ viewsDirAbs,
8563
8441
  {
8564
- existingIdBehavior: existingIdBehavior ?? "error",
8442
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8443
+ testIdAttribute,
8565
8444
  nameCollisionBehavior,
8566
8445
  missingSemanticNameBehavior,
8567
- testIdAttribute,
8568
8446
  warn: (message) => loggerRef.current.warn(message),
8569
- vueFilesPathMap: provisionalVuePathMap,
8447
+ vueFilesPathMap,
8570
8448
  wrapperSearchRoots: getWrapperSearchRoots(),
8571
- crossFileKeyRegistry: provisionalKeyRegistry,
8449
+ annotatorMetadata,
8450
+ crossFileKeyRegistry,
8572
8451
  optionKeyAttribute
8573
8452
  }
8574
8453
  )
8575
- ]
8576
- });
8577
- targetVuePathMap.set(componentName, absolutePath);
8578
- targetHierarchy.set(
8579
- componentName,
8580
- provisionalHierarchy.get(componentName) ?? createEmptyComponentDependencies(absolutePath)
8581
- );
8582
- return { componentName, ms: performance.now() - started, compiled: true };
8583
- };
8584
- const fullRebuildSnapshotFromFilesystem = (logLabel) => {
8585
- const t0 = performance.now();
8586
- const nextHierarchy = /* @__PURE__ */ new Map();
8587
- const nextVuePathMap = /* @__PURE__ */ new Map();
8588
- filePathToComponentName.clear();
8589
- let totalVueFiles = 0;
8590
- let compiledCount = 0;
8591
- for (const absDir of getSourceDirRoots()) {
8592
- if (!fs.existsSync(absDir))
8593
- continue;
8594
- const vueFiles = walkFilesRecursive(absDir);
8595
- totalVueFiles += vueFiles.length;
8596
- for (const file of vueFiles) {
8597
- const res = compileVueFileIntoSnapshot(file, nextHierarchy, nextVuePathMap);
8598
- if (res.compiled)
8599
- compiledCount++;
8600
- }
8454
+ );
8455
+ return () => {
8456
+ const componentMetadata = extractMetadataAfterTransform(
8457
+ node,
8458
+ componentName,
8459
+ elementMetadata,
8460
+ semanticNameMap,
8461
+ testIdAttribute
8462
+ );
8463
+ if (!accessibilityAudit) {
8464
+ return;
8465
+ }
8466
+ const dependencies = componentHierarchyMap.get(componentName);
8467
+ if (!dependencies || componentMetadata.size === 0) {
8468
+ return;
8469
+ }
8470
+ const manifest = buildPomManifest(
8471
+ /* @__PURE__ */ new Map([[componentName, dependencies]]),
8472
+ /* @__PURE__ */ new Map([[componentName, componentMetadata]])
8473
+ );
8474
+ const warnings = collectAccessibilityReviewWarnings(manifest);
8475
+ const signature = warnings.join("\n");
8476
+ if (!signature) {
8477
+ lastAccessibilityWarningSignatureByComponent.delete(componentName);
8478
+ return;
8479
+ }
8480
+ if (lastAccessibilityWarningSignatureByComponent.get(componentName) === signature) {
8481
+ return;
8482
+ }
8483
+ lastAccessibilityWarningSignatureByComponent.set(componentName, signature);
8484
+ for (const warning of warnings) {
8485
+ loggerRef.current.warn(warning);
8486
+ }
8487
+ };
8601
8488
  }
8602
- snapshotHierarchy = nextHierarchy;
8603
- snapshotVuePathMap = nextVuePathMap;
8604
- const t1 = performance.now();
8605
- logInfo(`scan(${logLabel}): found ${totalVueFiles} .vue files in ${getSourceDirs().join(", ")}`);
8606
- logInfo(`compile(${logLabel}): ${compiledCount}/${totalVueFiles} files in ${formatMs(t1 - t0)} (components=${snapshotHierarchy.size})`);
8607
- };
8608
- const generateAggregatedFromSnapshot = async (logLabel) => {
8609
- const t0 = performance.now();
8610
- await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
8611
- outDir,
8612
- emitLanguages,
8613
- typescriptOutputStructure,
8614
- csharp,
8615
- generateFixtures,
8616
- customPomAttachments,
8617
- projectRoot: projectRootRef.current,
8618
- customPomDir,
8619
- requireCustomPomDir,
8620
- customPomImportAliases,
8621
- customPomImportNameCollisionBehavior,
8622
- pageDirs: getPageDirs(),
8623
- componentDirs: getComponentDirs(),
8624
- layoutDirs: getLayoutDirs(),
8625
- testIdAttribute,
8626
- vueRouterFluentChaining: routerAwarePoms,
8627
- routerEntry: getResolvedRouterEntry(),
8628
- routerType
8629
- });
8630
- const t1 = performance.now();
8631
- logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
8632
- };
8633
- let timer = null;
8634
- let maxWaitTimer = null;
8635
- const pendingChangedVueFiles = /* @__PURE__ */ new Set();
8636
- const pendingDeletedComponents = /* @__PURE__ */ new Set();
8637
- let regenerationSequence = Promise.resolve();
8638
- const initialBuildPromise = (async () => {
8639
- const t0 = performance.now();
8640
- await routerInitPromise;
8641
- fullRebuildSnapshotFromFilesystem("startup");
8642
- await generateAggregatedFromSnapshot("startup");
8643
- const t1 = performance.now();
8644
- logInfo(`startup total: ${formatMs(t1 - t0)}`);
8645
- })();
8646
- const logGenerationError = (reason, message) => {
8647
- server.config.logger.error(`[vue-pom-generator] dev generation failed during ${reason}: ${message}`);
8648
- };
8649
- const regenerateFromPending = async (reason) => {
8650
- const t0 = performance.now();
8651
- await initialBuildPromise;
8652
- const nextHierarchy = new Map(snapshotHierarchy);
8653
- const nextVuePathMap = new Map(snapshotVuePathMap);
8654
- for (const componentName of pendingDeletedComponents) {
8655
- nextHierarchy.delete(componentName);
8656
- nextVuePathMap.delete(componentName);
8657
- }
8658
- const files = Array.from(pendingChangedVueFiles);
8659
- const deletedCount = pendingDeletedComponents.size;
8660
- pendingChangedVueFiles.clear();
8661
- pendingDeletedComponents.clear();
8662
- let compileMs = 0;
8663
- for (const f of files) {
8664
- const res = compileVueFileIntoSnapshot(f, nextHierarchy, nextVuePathMap);
8665
- compileMs += res.ms;
8666
- }
8667
- snapshotHierarchy = nextHierarchy;
8668
- snapshotVuePathMap = nextVuePathMap;
8669
- const t1 = performance.now();
8670
- await generateAggregatedFromSnapshot(reason);
8671
- const t2 = performance.now();
8672
- return {
8673
- files,
8674
- deletedCount,
8675
- compileMs,
8676
- preGenerateMs: t1 - t0,
8677
- generateMs: t2 - t1,
8678
- totalMs: t2 - t0
8679
- };
8680
- };
8681
- const enqueueRegeneration = (reason) => {
8682
- const currentRun = regenerationSequence.catch(() => void 0).then(() => regenerateFromPending(reason));
8683
- regenerationSequence = currentRun.then(() => void 0, () => void 0);
8684
- return currentRun;
8685
- };
8686
- const runtimeDir = path.dirname(basePageClassPath);
8687
- const localPluginDir = path.resolve(projectRootRef.current, "vite-plugins", "vue-pom-generator");
8688
- server.watcher.add([
8689
- ...fs.existsSync(localPluginDir) ? [localPluginDir] : [],
8690
- basePageClassPath,
8691
- path.resolve(runtimeDir, "pointer.ts"),
8692
- path.resolve(runtimeDir, "callout.ts"),
8693
- path.resolve(runtimeDir, "floating-ui-callout.ts")
8694
- ]);
8695
- scheduleVueFileRegenLocal = (filePath, source) => {
8696
- pendingChangedVueFiles.add(filePath);
8697
- logDebug(`queued(${source}): files=${pendingChangedVueFiles.size} deleted=${pendingDeletedComponents.size}`);
8698
- scheduleAggregatedRegen();
8699
- };
8700
- scheduleVueFileRegen = scheduleVueFileRegenLocal;
8701
- function scheduleAggregatedRegen() {
8702
- const wasEmpty = pendingChangedVueFiles.size === 0 && pendingDeletedComponents.size === 0;
8703
- const MAX_WAIT_MS = 750;
8704
- if (!maxWaitTimer) {
8705
- maxWaitTimer = setTimeout(() => {
8706
- if (timer) {
8707
- clearTimeout(timer);
8708
- timer = null;
8489
+ let transform = perFileTransform.get(componentName);
8490
+ if (!transform) {
8491
+ componentHierarchyMap.delete(componentName);
8492
+ vueFilesPathMap.set(componentName, filename);
8493
+ transform = createTestIdTransform(
8494
+ componentName,
8495
+ componentHierarchyMap,
8496
+ nativeWrappers,
8497
+ excludedComponents,
8498
+ viewsDirAbs,
8499
+ {
8500
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8501
+ testIdAttribute,
8502
+ nameCollisionBehavior,
8503
+ missingSemanticNameBehavior,
8504
+ warn: (message) => loggerRef.current.warn(message),
8505
+ vueFilesPathMap,
8506
+ wrapperSearchRoots: getWrapperSearchRoots(),
8507
+ annotatorMetadata,
8508
+ crossFileKeyRegistry,
8509
+ optionKeyAttribute
8709
8510
  }
8710
- maxWaitTimer = null;
8711
- void enqueueRegeneration("max-wait").then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
8712
- logInfo(
8713
- `max-wait: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
8714
- );
8715
- }).catch((error) => {
8716
- const message = error instanceof Error ? error.message : String(error);
8717
- logGenerationError("max-wait", message);
8718
- });
8719
- }, MAX_WAIT_MS);
8720
- }
8721
- if (wasEmpty) {
8722
- const queuedFiles = pendingChangedVueFiles.size;
8723
- const queuedDeletes = pendingDeletedComponents.size;
8724
- logDebug(`queued: files=${queuedFiles} deleted=${queuedDeletes}`);
8511
+ );
8512
+ perFileTransform.set(componentName, transform);
8725
8513
  }
8726
- if (timer)
8727
- clearTimeout(timer);
8728
- timer = setTimeout(() => {
8729
- timer = null;
8730
- if (maxWaitTimer) {
8731
- clearTimeout(maxWaitTimer);
8732
- maxWaitTimer = null;
8733
- }
8734
- const reason = pendingChangedVueFiles.size || pendingDeletedComponents.size ? "batched" : "noop";
8735
- void enqueueRegeneration(reason).then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
8736
- if (files.length || deletedCount) {
8737
- logInfo(
8738
- `batched: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
8739
- );
8740
- }
8741
- }).catch((error) => {
8742
- const message = error instanceof Error ? error.message : String(error);
8743
- logGenerationError(reason, message);
8744
- });
8745
- }, 75);
8514
+ return transform(node, context);
8746
8515
  }
8747
- server.watcher.on("change", async (changedPath) => {
8748
- const changedAbsPosix = path.posix.normalize(path.resolve(changedPath));
8749
- const outDirAbsPosix = path.posix.normalize(path.resolve(projectRootRef.current, outDir ?? "./pom"));
8750
- if (changedAbsPosix.startsWith(`${outDirAbsPosix}/`) && (changedAbsPosix.endsWith(".g.ts") || changedAbsPosix.endsWith(".g.ts.map"))) {
8751
- return;
8752
- }
8753
- if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
8754
- void server.restart();
8755
- }
8756
- });
8757
- server.watcher.on("add", (p) => {
8758
- if (typeof p !== "string")
8759
- return;
8760
- if (!p.endsWith(".vue"))
8761
- return;
8762
- if (!isContainedInScanDirs(p))
8763
- return;
8764
- void (async () => {
8765
- await initialBuildPromise;
8766
- pendingChangedVueFiles.add(p);
8767
- scheduleAggregatedRegen();
8768
- })();
8769
- });
8770
- server.watcher.on("unlink", (p) => {
8771
- if (typeof p !== "string")
8772
- return;
8773
- if (!p.endsWith(".vue"))
8774
- return;
8775
- if (!isContainedInScanDirs(p))
8776
- return;
8777
- void (async () => {
8778
- await initialBuildPromise;
8779
- const absolutePath = path.resolve(p);
8780
- const componentName = getComponentNameForFile(absolutePath);
8781
- filePathToComponentName.delete(absolutePath);
8782
- pendingDeletedComponents.add(componentName);
8783
- scheduleAggregatedRegen();
8784
- })();
8785
- });
8786
- setTimeout(() => {
8787
- }, 250);
8788
- await initialBuildPromise;
8516
+ ];
8517
+ };
8518
+ const runtimeNodeTransform = (node, context) => {
8519
+ const filename = context.filename;
8520
+ if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
8521
+ return;
8789
8522
  }
8523
+ const transforms = getNodeTransforms(filename);
8524
+ const ourTransform = transforms[transforms.length - 1];
8525
+ return ourTransform(node, context);
8790
8526
  };
8791
- }
8792
- function supportsInlineTextAccessibleName(role) {
8793
- return role === "button" || role === "radio";
8794
- }
8795
- function buildAccessibilityAudit(metadata, inferredRole) {
8796
- if (!metadata || !inferredRole) {
8797
- return void 0;
8798
- }
8799
- const role = normalizePomRoleLabel(inferredRole).toLowerCase();
8800
- const dynamicProps = new Set(metadata.dynamicProps ?? []);
8801
- const hasDynamicAccessibleNameSignal = dynamicProps.has("aria-label") || dynamicProps.has("title") || !!metadata.hasDynamicText;
8802
- let accessibleNameSource;
8803
- const reasons = [];
8804
- if (metadata.staticAriaLabel) {
8805
- accessibleNameSource = "aria-label";
8806
- } else if (supportsInlineTextAccessibleName(role) && metadata.staticTextContent) {
8807
- accessibleNameSource = "text";
8808
- } else if (metadata.staticTitle) {
8809
- accessibleNameSource = "title";
8810
- } else if (hasDynamicAccessibleNameSignal) {
8811
- accessibleNameSource = "dynamic";
8812
- } else if (role === "input" || role === "select") {
8813
- accessibleNameSource = "unknown";
8814
- reasons.push("No inline accessible-name signal was found; the element may rely on external markup such as a separate <label>.");
8815
- } else {
8816
- accessibleNameSource = "missing";
8817
- reasons.push("No compile-time accessible-name signal was found.");
8818
- }
8819
- return {
8820
- needsReview: accessibleNameSource === "unknown" || accessibleNameSource === "missing",
8821
- accessibleNameSource,
8822
- reasons,
8823
- ...metadata.staticAriaLabel ? { staticAriaLabel: metadata.staticAriaLabel } : {},
8824
- ...metadata.staticRole ? { staticRole: metadata.staticRole } : {},
8825
- ...metadata.staticTitle ? { staticTitle: metadata.staticTitle } : {},
8826
- ...metadata.staticTextContent ? { staticTextContent: metadata.staticTextContent } : {}
8527
+ const templateCompilerOptions = {
8528
+ ...userCompilerOptions,
8529
+ prefixIdentifiers: true,
8530
+ nodeTransforms: [
8531
+ ...userNodeTransforms,
8532
+ runtimeNodeTransform
8533
+ ]
8827
8534
  };
8828
- }
8829
- function collectAccessibilityReviewWarnings(manifest) {
8830
- const warnings = [];
8831
- for (const [componentName, component] of Object.entries(manifest)) {
8832
- for (const entry of component.entries) {
8833
- if (!entry.accessibility?.needsReview) {
8834
- continue;
8535
+ const metadataCollectorPlugin = {
8536
+ name: "vue-pom-generator-metadata-collector",
8537
+ enforce: "pre",
8538
+ async transform(code, id) {
8539
+ const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
8540
+ if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
8541
+ return null;
8835
8542
  }
8836
- const entryLabel = entry.generatedPropertyName ?? entry.testId;
8837
- const reasonText = entry.accessibility.reasons.join(" ");
8838
- warnings.push(
8839
- `[vue-pom-generator] Accessibility review suggested for ${componentName}.${entryLabel} (role=${entry.inferredRole ?? "unknown"}, testId=${JSON.stringify(entry.testId)}): ${reasonText}`
8840
- );
8841
- }
8842
- }
8843
- return warnings;
8844
- }
8845
- function matchesPrimarySelector(extraMethod, pom) {
8846
- if (extraMethod.selector.kind !== "testId") {
8847
- return false;
8848
- }
8849
- return extraMethod.selector.testId.formatted === pom.selector.formatted && extraMethod.selector.testId.patternKind === pom.selector.patternKind;
8850
- }
8851
- function getManifestEntry(componentName, entry, componentMetadata, extraMethods) {
8852
- const testId = entry.selectorValue.formatted;
8853
- const metadata = componentMetadata?.get(testId);
8854
- const pom = entry.pom;
8855
- const generatedActionName = pom ? buildPomGeneratedActionName(pom) : null;
8856
- const extraActionNames = pom ? extraMethods.filter((extraMethod) => matchesPrimarySelector(extraMethod, pom)).map((extraMethod) => extraMethod.name).sort((a, b) => a.localeCompare(b)) : [];
8857
- const generatedActionNames = Array.from(/* @__PURE__ */ new Set([
8858
- ...generatedActionName ? [generatedActionName] : [],
8859
- ...extraActionNames.filter((name) => name !== generatedActionName)
8860
- ]));
8861
- const accessibility = buildAccessibilityAudit(metadata, pom?.nativeRole ?? null);
8862
- return {
8863
- testId,
8864
- selectorPatternKind: entry.selectorValue.patternKind,
8865
- semanticName: metadata?.semanticName ?? (pom ? humanizePomMethodName(pom.methodName) : testId),
8866
- locatorDescription: pom ? buildPomLocatorDescription({
8867
- componentName,
8868
- methodName: pom.methodName,
8869
- nativeRole: pom.nativeRole
8870
- }) : componentName,
8871
- inferredRole: pom?.nativeRole ?? null,
8872
- ...accessibility ? { accessibility } : {},
8873
- generatedPropertyName: pom ? buildPomGeneratedPropertyName(pom) : null,
8874
- generatedActionName,
8875
- generatedActionNames,
8876
- emitPrimary: pom?.emitPrimary !== false,
8877
- ...entry.targetPageObjectModelClass ? { targetPageObjectModelClass: entry.targetPageObjectModelClass } : {},
8878
- ...metadata?.tag ? { sourceTag: metadata.tag } : {},
8879
- ...metadata ? { sourceTagType: metadata.tagType } : {},
8880
- ...metadata?.sourceLine !== void 0 ? { sourceLine: metadata.sourceLine } : {},
8881
- ...metadata?.sourceColumn !== void 0 ? { sourceColumn: metadata.sourceColumn } : {},
8882
- ...metadata?.patchFlag !== void 0 ? { patchFlag: metadata.patchFlag } : {},
8883
- ...metadata?.dynamicProps?.length ? { dynamicProps: metadata.dynamicProps } : {},
8884
- ...metadata?.hasClickHandler !== void 0 ? { hasClickHandler: metadata.hasClickHandler } : {},
8885
- ...metadata?.hasDynamicClass !== void 0 ? { hasDynamicClass: metadata.hasDynamicClass } : {},
8886
- ...metadata?.hasDynamicStyle !== void 0 ? { hasDynamicStyle: metadata.hasDynamicStyle } : {},
8887
- ...metadata?.hasDynamicText !== void 0 ? { hasDynamicText: metadata.hasDynamicText } : {}
8888
- };
8889
- }
8890
- function buildPomManifest(componentHierarchyMap, elementMetadata) {
8891
- const manifestEntries = Array.from(componentHierarchyMap.entries()).filter(([componentName, dependencies]) => !shouldSuppressStandaloneWrapperFallbackSurface(componentName, dependencies)).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8892
- 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 ?? []));
8893
- if (!entries.length) {
8894
- return null;
8895
- }
8896
- return [componentName, {
8897
- componentName,
8898
- className: componentName,
8899
- sourceFile: dependencies.filePath,
8900
- kind: dependencies.isView ? "view" : "component",
8901
- testIds: Array.from(new Set(entries.map((entry) => entry.testId))),
8902
- entries
8903
- }];
8904
- }).filter((entry) => entry !== null);
8905
- return Object.fromEntries(manifestEntries);
8906
- }
8907
- function buildTestIdManifest(componentHierarchyMap) {
8908
- return Object.fromEntries(
8909
- Array.from(componentHierarchyMap.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([componentName, dependencies]) => {
8910
- const testIds = Array.from(dependencies.dataTestIdSet).map((entry) => entry.selectorValue.formatted).filter(Boolean);
8911
- if (!testIds.length) {
8543
+ if (id !== cleanPath) {
8912
8544
  return null;
8913
8545
  }
8914
- return [componentName, Array.from(new Set(testIds)).sort((a, b) => a.localeCompare(b))];
8915
- }).filter((entry) => entry !== null)
8916
- );
8917
- }
8918
- function writeConstJson(value) {
8919
- return (writer) => {
8920
- writer.write(`${JSON.stringify(value, null, 2)} as const`);
8546
+ const componentName = getComponentNameFromPath(cleanPath);
8547
+ loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
8548
+ const compilerSfc = await import("@vue/compiler-sfc");
8549
+ const parse2 = resolveCompilerSfcParse(compilerSfc);
8550
+ const compilerDom2 = await import("@vue/compiler-dom");
8551
+ const compile = compilerDom2.compile;
8552
+ const { descriptor } = parse2(code, { filename: cleanPath });
8553
+ if (descriptor.template) {
8554
+ const mergedExpressionPlugins = Array.from(
8555
+ /* @__PURE__ */ new Set([
8556
+ "typescript",
8557
+ ...userCompilerOptions.expressionPlugins ?? []
8558
+ ])
8559
+ );
8560
+ compile(descriptor.template.content, {
8561
+ ...userCompilerOptions,
8562
+ filename: cleanPath,
8563
+ expressionPlugins: mergedExpressionPlugins,
8564
+ nodeTransforms: getNodeTransforms(cleanPath, componentName)
8565
+ });
8566
+ loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
8567
+ }
8568
+ return null;
8569
+ }
8921
8570
  };
8922
- }
8923
- function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
8924
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8925
- const testIdManifest = buildTestIdManifest(componentHierarchyMap);
8926
- return renderSourceFile("virtual-testids.ts", (sourceFile) => {
8927
- sourceFile.addStatements("// Virtual module: test id manifest");
8928
- sourceFile.addVariableStatement({
8929
- declarationKind: VariableDeclarationKind.Const,
8930
- isExported: true,
8931
- declarations: [{
8932
- name: "testIdManifest",
8933
- initializer: writeConstJson(testIdManifest)
8934
- }]
8935
- });
8936
- sourceFile.addVariableStatement({
8937
- declarationKind: VariableDeclarationKind.Const,
8938
- isExported: true,
8939
- declarations: [{
8940
- name: "pomManifest",
8941
- initializer: writeConstJson(pomManifest)
8942
- }]
8943
- });
8944
- sourceFile.addTypeAlias({
8945
- isExported: true,
8946
- name: "TestIdManifest",
8947
- type: "typeof testIdManifest"
8948
- });
8949
- sourceFile.addTypeAlias({
8950
- isExported: true,
8951
- name: "ComponentName",
8952
- type: "keyof TestIdManifest"
8953
- });
8954
- sourceFile.addTypeAlias({
8955
- isExported: true,
8956
- name: "PomManifest",
8957
- type: "typeof pomManifest"
8958
- });
8959
- sourceFile.addTypeAlias({
8960
- isExported: true,
8961
- name: "PomManifestComponentName",
8962
- type: "keyof PomManifest"
8963
- });
8964
- });
8965
- }
8966
- function generatePomManifestModule(componentHierarchyMap, elementMetadata) {
8967
- const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
8968
- return renderSourceFile("virtual-pom-manifest.ts", (sourceFile) => {
8969
- sourceFile.addStatements("// Virtual module: richer POM discoverability manifest");
8970
- sourceFile.addVariableStatement({
8971
- declarationKind: VariableDeclarationKind.Const,
8972
- isExported: true,
8973
- declarations: [{
8974
- name: "pomManifest",
8975
- initializer: writeConstJson(pomManifest)
8976
- }]
8977
- });
8978
- sourceFile.addTypeAlias({
8979
- isExported: true,
8980
- name: "PomManifest",
8981
- type: "typeof pomManifest"
8982
- });
8983
- sourceFile.addTypeAlias({
8984
- isExported: true,
8985
- name: "PomManifestComponentName",
8986
- type: "keyof PomManifest"
8987
- });
8571
+ const template = {
8572
+ ...userTemplate,
8573
+ compilerOptions: templateCompilerOptions
8574
+ };
8575
+ const internalVuePlugin = vue({
8576
+ ...vueOptions,
8577
+ template
8988
8578
  });
8579
+ const nuxtVueBridgePlugin = {
8580
+ name: "vue-pom-generator-nuxt-vue-bridge",
8581
+ apply: "serve",
8582
+ configResolved(config) {
8583
+ const viteVuePlugin = config.plugins.find((plugin) => {
8584
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
8585
+ });
8586
+ const api = viteVuePlugin?.api;
8587
+ if (!api) {
8588
+ throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
8589
+ }
8590
+ const currentOptions = api.options ?? {};
8591
+ const currentTemplate = currentOptions.template ?? {};
8592
+ const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
8593
+ const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
8594
+ if (currentNodeTransforms.includes(runtimeNodeTransform)) {
8595
+ return;
8596
+ }
8597
+ api.options = {
8598
+ ...currentOptions,
8599
+ template: {
8600
+ ...currentTemplate,
8601
+ compilerOptions: {
8602
+ ...currentCompilerOptions,
8603
+ prefixIdentifiers: true,
8604
+ nodeTransforms: [
8605
+ ...currentNodeTransforms,
8606
+ runtimeNodeTransform
8607
+ ]
8608
+ }
8609
+ }
8610
+ };
8611
+ }
8612
+ };
8613
+ return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
8989
8614
  }
8990
- const TEST_IDS_VIRTUAL_ID = "virtual:testids";
8991
- const TEST_IDS_RESOLVED_ID = `\0${TEST_IDS_VIRTUAL_ID}`;
8992
- const POM_MANIFEST_VIRTUAL_ID = "virtual:pom-manifest";
8993
- const POM_MANIFEST_RESOLVED_ID = `\0${POM_MANIFEST_VIRTUAL_ID}`;
8994
- function createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata) {
8995
- return {
8996
- name: "vue-pom-generator:virtual-testids",
8997
- resolveId(id) {
8998
- if (id === TEST_IDS_VIRTUAL_ID)
8999
- return TEST_IDS_RESOLVED_ID;
9000
- if (id === POM_MANIFEST_VIRTUAL_ID)
9001
- return POM_MANIFEST_RESOLVED_ID;
9002
- },
9003
- load(id) {
9004
- if (id === TEST_IDS_RESOLVED_ID)
9005
- return generateTestIdsModule(componentHierarchyMap, elementMetadata);
9006
- if (id === POM_MANIFEST_RESOLVED_ID)
9007
- return generatePomManifestModule(componentHierarchyMap, elementMetadata);
8615
+ function summarizeHierarchyMap(componentHierarchyMap) {
8616
+ let interactiveComponentCount = 0;
8617
+ let dataTestIdCount = 0;
8618
+ for (const dependencies of componentHierarchyMap.values()) {
8619
+ const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
8620
+ if (selectorCount > 0) {
8621
+ interactiveComponentCount += 1;
8622
+ dataTestIdCount += selectorCount;
9008
8623
  }
8624
+ }
8625
+ return {
8626
+ entryCount: componentHierarchyMap.size,
8627
+ interactiveComponentCount,
8628
+ dataTestIdCount
9009
8629
  };
9010
8630
  }
9011
- const ANNOTATOR_CLIENT_VIRTUAL_ID = "virtual:vue-pom-generator/annotator-client";
9012
- const ANNOTATOR_CLIENT_RESOLVED_ID = `\0${ANNOTATOR_CLIENT_VIRTUAL_ID}`;
9013
- const DEFAULT_ENTRY_SUFFIXES = [
9014
- "/src/main.ts",
9015
- "/src/main.js",
9016
- "/src/main.mts",
9017
- "/src/main.tsx",
9018
- "/src/main.jsx"
9019
- ];
9020
- function normalizePathSeparators(filePath) {
9021
- return filePath.replace(/\\/g, "/");
8631
+ function isLessRich(candidate, previous) {
8632
+ if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8633
+ return candidate.dataTestIdCount < previous.dataTestIdCount;
8634
+ }
8635
+ if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8636
+ return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8637
+ }
8638
+ return candidate.entryCount < previous.entryCount;
9022
8639
  }
9023
- function toFsImportPath(filePath) {
9024
- return `/@fs/${normalizePathSeparators(filePath)}`;
9025
- }
9026
- function resolveAnnotatorClientPath() {
9027
- const candidates = [
9028
- fileURLToPath(new URL("./client.ts", import.meta.url)),
9029
- fileURLToPath(new URL("../plugin/runtime/annotator/client.ts", import.meta.url))
9030
- ];
9031
- const resolved = candidates.find((candidate) => fs.existsSync(candidate));
9032
- if (!resolved) {
9033
- throw new Error("[vue-pom-generator] Unable to locate annotator client source.");
9034
- }
9035
- return path.resolve(resolved);
9036
- }
9037
- function createAnnotatorUiPlugin(options) {
9038
- const clientPath = resolveAnnotatorClientPath();
9039
- const clientImportPath = toFsImportPath(clientPath);
9040
- const clientOptions = JSON.stringify({
9041
- sourceAttribute: options.sourceAttribute,
9042
- metadataAttributePrefix: options.metadataAttributePrefix,
9043
- outputDetail: options.outputDetail,
9044
- copyToClipboard: options.copyToClipboard,
9045
- showComponentTree: options.showComponentTree
9046
- });
9047
- return {
9048
- name: "vue-pom-generator:annotator-ui",
9049
- apply: "serve",
9050
- resolveId(id) {
9051
- if (id === ANNOTATOR_CLIENT_VIRTUAL_ID) {
9052
- return ANNOTATOR_CLIENT_RESOLVED_ID;
9053
- }
9054
- },
9055
- load(id) {
9056
- if (id !== ANNOTATOR_CLIENT_RESOLVED_ID) {
9057
- return null;
9058
- }
9059
- return [
9060
- `import { mountAnnotatorClient } from ${JSON.stringify(clientImportPath)};`,
9061
- `mountAnnotatorClient(${clientOptions});`,
9062
- ""
9063
- ].join("\n");
9064
- },
9065
- transform(code, id) {
9066
- if (!options.enabled) {
9067
- return null;
9068
- }
9069
- const normalizedId = normalizePathSeparators(id);
9070
- if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9071
- return null;
9072
- }
9073
- if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9074
- return null;
9075
- }
9076
- return {
9077
- code: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};
9078
- ${code}`,
9079
- map: null
9080
- };
9081
- },
9082
- transformIndexHtml() {
9083
- if (!options.enabled) {
9084
- return void 0;
9085
- }
9086
- const tag = {
9087
- tag: "script",
9088
- attrs: { type: "module" },
9089
- children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9090
- injectTo: "body"
9091
- };
9092
- return [tag];
9093
- }
9094
- };
9095
- }
9096
- function createInternalPlugins(options) {
8640
+ function createBuildProcessorPlugin(options) {
9097
8641
  const {
9098
8642
  componentHierarchyMap,
9099
8643
  crossFileKeyRegistry,
9100
- elementMetadata,
9101
8644
  vueFilesPathMap,
9102
- nativeWrappers,
9103
- optionKeyAttribute,
9104
- excludedComponents,
9105
8645
  getPageDirs,
9106
8646
  getComponentDirs,
9107
8647
  getLayoutDirs,
9108
8648
  getViewsDir,
9109
8649
  getSourceDirs,
9110
- getWrapperSearchRoots,
8650
+ basePageClassPath,
8651
+ normalizedBasePagePath,
9111
8652
  generation,
9112
8653
  projectRootRef,
9113
- basePageClassPath: basePageClassPathOverride,
9114
- loggerRef,
9115
- annotatorRuntime
8654
+ nativeWrappers,
8655
+ optionKeyAttribute,
8656
+ excludedComponents,
8657
+ getWrapperSearchRoots,
8658
+ getResolvedRouterEntry,
8659
+ loggerRef
9116
8660
  } = options;
9117
8661
  const {
8662
+ outDir,
8663
+ emitLanguages,
8664
+ typescriptOutputStructure,
8665
+ csharp,
8666
+ generateFixtures,
8667
+ customPomAttachments,
8668
+ customPomDir,
8669
+ requireCustomPomDir,
8670
+ customPomImportAliases,
8671
+ customPomImportNameCollisionBehavior,
8672
+ testIdAttribute,
8673
+ nameCollisionBehavior,
8674
+ missingSemanticNameBehavior,
8675
+ existingIdBehavior,
9118
8676
  routerAwarePoms,
9119
- routerEntry,
9120
- routerType
8677
+ routerType,
8678
+ routerModuleShims
9121
8679
  } = generation;
9122
- const resolveRouterEntry2 = () => {
9123
- if (!routerAwarePoms)
9124
- return void 0;
9125
- if (routerType === "nuxt")
9126
- return void 0;
9127
- if (!routerEntry)
9128
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9129
- return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(projectRootRef.current, routerEntry);
8680
+ let lastGeneratedMetrics = {
8681
+ entryCount: 0,
8682
+ interactiveComponentCount: 0,
8683
+ dataTestIdCount: 0
9130
8684
  };
9131
- const getDefaultBasePageClassPath = () => {
8685
+ const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
8686
+ const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
8687
+ const getScriptInfo = (source, filename) => {
9132
8688
  try {
9133
- return fileURLToPath(new URL("../class-generation/base-page.ts", import.meta.url));
8689
+ const { descriptor } = parse$1(source, { filename });
8690
+ if (!descriptor.script && !descriptor.scriptSetup)
8691
+ return { bindings: void 0, isScriptSetup: false };
8692
+ const scriptBlock = compileScript(descriptor, { id: filename });
8693
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
9134
8694
  } catch {
9135
- return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
8695
+ return { bindings: void 0, isScriptSetup: false };
9136
8696
  }
9137
8697
  };
9138
- const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9139
- const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9140
- const tsProcessor = createBuildProcessorPlugin({
9141
- componentHierarchyMap,
9142
- crossFileKeyRegistry,
9143
- vueFilesPathMap,
9144
- getPageDirs,
9145
- getComponentDirs,
9146
- getLayoutDirs,
9147
- getViewsDir,
9148
- getSourceDirs,
9149
- basePageClassPath,
9150
- normalizedBasePagePath,
9151
- generation,
9152
- projectRootRef,
9153
- nativeWrappers,
9154
- optionKeyAttribute,
9155
- excludedComponents,
9156
- getWrapperSearchRoots,
9157
- getResolvedRouterEntry: resolveRouterEntry2,
9158
- loggerRef
9159
- });
9160
- const devProcessor = createDevProcessorPlugin({
9161
- nativeWrappers,
9162
- optionKeyAttribute,
9163
- excludedComponents,
9164
- getPageDirs,
9165
- getComponentDirs,
9166
- getLayoutDirs,
9167
- getViewsDir,
9168
- getSourceDirs,
9169
- getWrapperSearchRoots,
9170
- projectRootRef,
9171
- normalizedBasePagePath,
9172
- basePageClassPath,
9173
- generation,
9174
- getResolvedRouterEntry: resolveRouterEntry2,
9175
- loggerRef
9176
- });
9177
- const virtualModules = createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata);
9178
- const annotatorUiPlugin = createAnnotatorUiPlugin({
9179
- ...annotatorRuntime.ui,
9180
- enabled: annotatorRuntime.enabled && annotatorRuntime.ui.enabled,
9181
- sourceAttribute: annotatorRuntime.sourceAttribute,
9182
- metadataAttributePrefix: annotatorRuntime.metadataAttributePrefix
9183
- });
9184
- return [tsProcessor, devProcessor, virtualModules, annotatorUiPlugin];
9185
- }
9186
- function findDataTestIdProp(element, attributeName = "data-testid") {
9187
- return element.props.find(
9188
- (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName || prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName
9189
- );
9190
- }
9191
- function getTestIdFromProp(prop) {
9192
- if (!prop) {
9193
- return null;
9194
- }
9195
- if (prop.type === NodeTypes.ATTRIBUTE) {
9196
- return prop.value ? prop.value.content : null;
9197
- }
9198
- if (prop.type === NodeTypes.DIRECTIVE) {
9199
- return prop.exp?.type === NodeTypes.SIMPLE_EXPRESSION ? prop.exp.content : null;
9200
- }
9201
- return null;
9202
- }
9203
- function parseDynamicProps(dynamicProps) {
9204
- if (!dynamicProps) {
9205
- return void 0;
9206
- }
9207
- if (typeof dynamicProps === "string") {
9208
- const parts = [];
9209
- let current = "";
9210
- for (let i = 0; i < dynamicProps.length; i++) {
9211
- const ch = dynamicProps[i];
9212
- if (ch === ",") {
9213
- const token = current.trim();
9214
- if (token.length)
9215
- parts.push(token);
9216
- current = "";
9217
- continue;
9218
- }
9219
- current += ch;
9220
- }
9221
- const last = current.trim();
9222
- if (last.length)
9223
- parts.push(last);
9224
- return parts;
9225
- }
9226
- if (isSimpleExpressionNode(dynamicProps)) {
9227
- const content = dynamicProps.content;
9228
- if (content.startsWith("[") && content.endsWith("]")) {
9229
- try {
9230
- return JSON.parse(content);
9231
- } catch {
9232
- return void 0;
8698
+ const supplementHierarchyFromFilesystem = () => {
8699
+ const walkFilesRecursive = (rootDir) => {
8700
+ const out = [];
8701
+ const stack = [rootDir];
8702
+ while (stack.length) {
8703
+ const dir = stack.pop();
8704
+ if (!dir) continue;
8705
+ let entries = [];
8706
+ try {
8707
+ entries = fs.readdirSync(dir, { withFileTypes: true });
8708
+ } catch {
8709
+ continue;
8710
+ }
8711
+ for (const ent of entries) {
8712
+ if (ent.isDirectory()) {
8713
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8714
+ continue;
8715
+ stack.push(path.join(dir, ent.name));
8716
+ continue;
8717
+ }
8718
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
8719
+ out.push(path.join(dir, ent.name));
8720
+ }
8721
+ }
9233
8722
  }
9234
- }
9235
- return [content];
9236
- }
9237
- return void 0;
9238
- }
9239
- function findStaticAttributeValue(element, attributeName) {
9240
- const attribute = element.props.find(
9241
- (prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === attributeName
9242
- );
9243
- const value = attribute?.value?.content?.trim();
9244
- return value || void 0;
9245
- }
9246
- function collectStaticTextContent(children) {
9247
- const parts = [];
9248
- const visit = (nodes) => {
9249
- for (const node of nodes) {
9250
- if (node.type === NodeTypes.TEXT) {
9251
- const text2 = collapseWhitespace(node.content);
9252
- if (text2) {
9253
- parts.push(text2);
9254
- }
8723
+ return out;
8724
+ };
8725
+ let supplemented = 0;
8726
+ for (const dir of getSourceDirs()) {
8727
+ const absDir = path.resolve(projectRootRef.current, dir);
8728
+ if (!fs.existsSync(absDir))
9255
8729
  continue;
9256
- }
9257
- if (node.type === NodeTypes.ELEMENT) {
9258
- visit(node.children);
8730
+ for (const filePath of walkFilesRecursive(absDir)) {
8731
+ const absolutePath = path.resolve(filePath);
8732
+ const componentName = resolveComponentNameFromPath({
8733
+ filename: absolutePath,
8734
+ projectRoot: projectRootRef.current,
8735
+ viewsDirAbs: getViewsDirAbs(),
8736
+ sourceDirs: getSourceDirs(),
8737
+ extraRoots: [process.cwd()]
8738
+ });
8739
+ if (componentHierarchyMap.has(componentName))
8740
+ continue;
8741
+ let sfc = "";
8742
+ try {
8743
+ sfc = fs.readFileSync(absolutePath, "utf8");
8744
+ } catch {
8745
+ continue;
8746
+ }
8747
+ const { descriptor } = parse$1(sfc, { filename: absolutePath });
8748
+ const template = descriptor.template?.content ?? "";
8749
+ if (!template.trim()) {
8750
+ vueFilesPathMap.set(componentName, absolutePath);
8751
+ componentHierarchyMap.set(componentName, {
8752
+ filePath: absolutePath,
8753
+ childrenComponentSet: /* @__PURE__ */ new Set(),
8754
+ usedComponentSet: /* @__PURE__ */ new Set(),
8755
+ dataTestIdSet: /* @__PURE__ */ new Set(),
8756
+ isView: false,
8757
+ methodsContent: ""
8758
+ });
8759
+ supplemented++;
8760
+ continue;
8761
+ }
8762
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
8763
+ vueFilesPathMap.set(componentName, absolutePath);
8764
+ try {
8765
+ compilerDom.compile(template, {
8766
+ filename: absolutePath,
8767
+ prefixIdentifiers: true,
8768
+ inline: isScriptSetup,
8769
+ bindingMetadata,
8770
+ // See dev-plugin.ts — same rationale: enable TS in template
8771
+ // expressions so `(row: RowType) => ...` handlers parse.
8772
+ expressionPlugins: ["typescript"],
8773
+ nodeTransforms: [
8774
+ createTestIdTransform(
8775
+ componentName,
8776
+ componentHierarchyMap,
8777
+ nativeWrappers,
8778
+ excludedComponents,
8779
+ getViewsDirAbs(),
8780
+ {
8781
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
8782
+ testIdAttribute,
8783
+ nameCollisionBehavior,
8784
+ missingSemanticNameBehavior,
8785
+ warn: (message) => loggerRef.current.warn(message),
8786
+ vueFilesPathMap,
8787
+ wrapperSearchRoots: getWrapperSearchRoots(),
8788
+ crossFileKeyRegistry,
8789
+ optionKeyAttribute
8790
+ }
8791
+ )
8792
+ ]
8793
+ });
8794
+ } catch {
8795
+ }
8796
+ supplemented++;
9259
8797
  }
9260
8798
  }
9261
- };
9262
- visit(children);
9263
- const text = collapseWhitespace(parts.join(" "));
9264
- return text || void 0;
9265
- }
9266
- function tryCreateElementMetadata(args) {
9267
- const { element, semanticNameMap } = args;
9268
- const testIdAttribute = (args.testIdAttribute ?? "data-testid").trim() || "data-testid";
9269
- const testIdProp = findDataTestIdProp(element, testIdAttribute);
9270
- if (!testIdProp) {
9271
- return null;
9272
- }
9273
- const testId = getTestIdFromProp(testIdProp);
9274
- if (!testId) {
9275
- return null;
9276
- }
9277
- if (!element.codegenNode || element.codegenNode.type !== NodeTypes.VNODE_CALL) {
9278
- return null;
9279
- }
9280
- const codegenNode = element.codegenNode;
9281
- const patchFlag = codegenNode.patchFlag;
9282
- let dynamicPropsList = parseDynamicProps(codegenNode.dynamicProps);
9283
- if (!dynamicPropsList && codegenNode.dynamicProps && typeof codegenNode.dynamicProps !== "string" && isSimpleExpressionNode(codegenNode.dynamicProps)) {
9284
- const content = codegenNode.dynamicProps.content;
9285
- if (content.startsWith("[") && content.endsWith("]")) {
9286
- dynamicPropsList = [content];
8799
+ if (supplemented > 0) {
8800
+ loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
9287
8801
  }
9288
- }
9289
- const metadata = {
9290
- testId,
9291
- semanticName: semanticNameMap.get(testId),
9292
- tag: element.tag,
9293
- tagType: element.tagType,
9294
- patchFlag,
9295
- dynamicProps: dynamicPropsList,
9296
- // Decode patch flags (bitwise) - preserved as-is from existing code.
9297
- hasClickHandler: patchFlag ? Boolean(patchFlag & 32) : void 0,
9298
- hasDynamicClass: patchFlag ? Boolean(patchFlag & 2) : void 0,
9299
- hasDynamicStyle: patchFlag ? Boolean(patchFlag & 4) : void 0,
9300
- hasDynamicText: patchFlag ? Boolean(patchFlag & 1) : void 0,
9301
- staticAriaLabel: findStaticAttributeValue(element, "aria-label"),
9302
- staticRole: findStaticAttributeValue(element, "role"),
9303
- staticTitle: findStaticAttributeValue(element, "title"),
9304
- staticTextContent: collectStaticTextContent(element.children),
9305
- sourceLine: element.loc?.start.line,
9306
- sourceColumn: element.loc?.start.column
9307
8802
  };
9308
- return metadata;
9309
- }
9310
- function resolveCompilerSfcParse(compilerSfc) {
9311
- const parse2 = compilerSfc.parse ?? compilerSfc.default?.parse;
9312
- if (typeof parse2 !== "function") {
9313
- throw new TypeError("[vue-pom-generator] Failed to resolve @vue/compiler-sfc.parse.");
9314
- }
9315
- return parse2;
9316
- }
9317
- function extractMetadataAfterTransform(ast, componentName, elementMetadata, semanticNameMap, testIdAttribute) {
9318
- const componentMetadata = /* @__PURE__ */ new Map();
9319
- function traverseNode(node) {
9320
- if (node.type === NodeTypes.ELEMENT) {
9321
- const element = node;
9322
- const testIdAttr = findDataTestIdProp(element, testIdAttribute);
9323
- if (testIdAttr) {
9324
- const metadata = tryCreateElementMetadata({
9325
- element,
9326
- semanticNameMap,
9327
- testIdAttribute
8803
+ return {
8804
+ name: "vue-pom-generator-build",
8805
+ // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
8806
+ apply: "build",
8807
+ enforce: "pre",
8808
+ async buildStart() {
8809
+ if (!routerAwarePoms) {
8810
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8811
+ setResolveToComponentNameFn(() => null);
8812
+ return;
8813
+ }
8814
+ let result;
8815
+ if (routerType === "nuxt") {
8816
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8817
+ } else {
8818
+ const resolvedRouterEntry = getResolvedRouterEntry();
8819
+ if (!resolvedRouterEntry)
8820
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8821
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8822
+ moduleShims: routerModuleShims,
8823
+ componentNaming: {
8824
+ projectRoot: projectRootRef.current,
8825
+ viewsDirAbs: getViewsDirAbs(),
8826
+ sourceDirs: getSourceDirs()
8827
+ }
9328
8828
  });
9329
- if (metadata) {
9330
- componentMetadata.set(metadata.testId, metadata);
8829
+ }
8830
+ const { routeNameMap, routePathMap } = result;
8831
+ setRouteNameToComponentNameMap(routeNameMap);
8832
+ setResolveToComponentNameFn((to) => {
8833
+ if (typeof to === "string") {
8834
+ return routePathMap.get(to) ?? null;
8835
+ }
8836
+ const maybe = to;
8837
+ if (typeof maybe.name === "string" && maybe.name.length) {
8838
+ const key = toPascalCase(maybe.name);
8839
+ return routeNameMap.get(key) ?? null;
8840
+ }
8841
+ if (typeof maybe.path === "string" && maybe.path.length) {
8842
+ return routePathMap.get(maybe.path) ?? null;
9331
8843
  }
8844
+ return null;
8845
+ });
8846
+ if (!fs.existsSync(basePageClassPath)) {
8847
+ this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
9332
8848
  }
9333
- if (element.children) {
9334
- for (const child of element.children) {
9335
- traverseNode(child);
8849
+ this.addWatchFile(basePageClassPath);
8850
+ const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
8851
+ if (!fs.existsSync(pointerPath)) {
8852
+ this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
8853
+ }
8854
+ this.addWatchFile(pointerPath);
8855
+ const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
8856
+ if (!fs.existsSync(calloutPath)) {
8857
+ this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
8858
+ }
8859
+ this.addWatchFile(calloutPath);
8860
+ const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
8861
+ if (fs.existsSync(floatingUiCalloutPath)) {
8862
+ this.addWatchFile(floatingUiCalloutPath);
8863
+ }
8864
+ },
8865
+ async buildEnd(error) {
8866
+ if (error) {
8867
+ return;
8868
+ }
8869
+ supplementHierarchyFromFilesystem();
8870
+ const metrics = summarizeHierarchyMap(componentHierarchyMap);
8871
+ if (metrics.dataTestIdCount <= 0) {
8872
+ return;
8873
+ }
8874
+ if (isLessRich(metrics, lastGeneratedMetrics)) {
8875
+ return;
8876
+ }
8877
+ await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
8878
+ outDir,
8879
+ emitLanguages,
8880
+ typescriptOutputStructure,
8881
+ csharp,
8882
+ generateFixtures,
8883
+ customPomAttachments,
8884
+ projectRoot: projectRootRef.current,
8885
+ customPomDir,
8886
+ requireCustomPomDir,
8887
+ customPomImportAliases,
8888
+ customPomImportNameCollisionBehavior,
8889
+ testIdAttribute,
8890
+ vueRouterFluentChaining: routerAwarePoms,
8891
+ routerEntry: getResolvedRouterEntry(),
8892
+ routerType,
8893
+ pageDirs: getPageDirs(),
8894
+ componentDirs: getComponentDirs(),
8895
+ layoutDirs: getLayoutDirs()
8896
+ });
8897
+ lastGeneratedMetrics = metrics;
8898
+ loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
8899
+ },
8900
+ closeBundle() {
8901
+ loggerRef.current.info("build complete");
8902
+ }
8903
+ };
8904
+ }
8905
+ function createDevProcessorPlugin(options) {
8906
+ const {
8907
+ nativeWrappers,
8908
+ optionKeyAttribute,
8909
+ excludedComponents,
8910
+ getPageDirs,
8911
+ getComponentDirs,
8912
+ getLayoutDirs,
8913
+ getViewsDir,
8914
+ getSourceDirs,
8915
+ getWrapperSearchRoots,
8916
+ projectRootRef,
8917
+ normalizedBasePagePath,
8918
+ basePageClassPath,
8919
+ generation,
8920
+ getResolvedRouterEntry,
8921
+ loggerRef
8922
+ } = options;
8923
+ const {
8924
+ outDir,
8925
+ emitLanguages,
8926
+ typescriptOutputStructure,
8927
+ csharp,
8928
+ generateFixtures,
8929
+ customPomAttachments,
8930
+ customPomDir,
8931
+ requireCustomPomDir,
8932
+ customPomImportAliases,
8933
+ customPomImportNameCollisionBehavior,
8934
+ nameCollisionBehavior,
8935
+ missingSemanticNameBehavior,
8936
+ existingIdBehavior,
8937
+ testIdAttribute,
8938
+ routerAwarePoms,
8939
+ routerType,
8940
+ routerModuleShims
8941
+ } = generation;
8942
+ let scheduleVueFileRegen = null;
8943
+ const getProjectRootCandidates = () => Array.from(/* @__PURE__ */ new Set([
8944
+ path.resolve(projectRootRef.current),
8945
+ path.resolve(process.cwd())
8946
+ ]));
8947
+ const resolveProjectPath = (maybePath) => {
8948
+ if (path.isAbsolute(maybePath))
8949
+ return maybePath;
8950
+ const candidates = getProjectRootCandidates().map((root) => path.resolve(root, maybePath));
8951
+ return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
8952
+ };
8953
+ const getSourceDirRoots = () => Array.from(new Set(
8954
+ getProjectRootCandidates().flatMap((root) => getSourceDirs().map((dir) => path.resolve(root, dir)))
8955
+ ));
8956
+ const isContainedInScanDirs = (filePath) => {
8957
+ const absolutePath = path.resolve(filePath);
8958
+ return getSourceDirRoots().some((scanDirAbs) => isPathWithinDir(absolutePath, scanDirAbs));
8959
+ };
8960
+ return {
8961
+ name: "vue-pom-generator-dev",
8962
+ apply: "serve",
8963
+ // Prefer hot-update events over filesystem change events for speed and reliability.
8964
+ // This fires when Vite has actually processed the module update.
8965
+ handleHotUpdate(ctx) {
8966
+ if (!scheduleVueFileRegen)
8967
+ return;
8968
+ if (!ctx.file.endsWith(".vue"))
8969
+ return;
8970
+ if (!isContainedInScanDirs(ctx.file))
8971
+ return;
8972
+ scheduleVueFileRegen(ctx.file, "hmr");
8973
+ },
8974
+ async configureServer(server) {
8975
+ const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
8976
+ const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
8977
+ const routerInitPromise = (async () => {
8978
+ if (!routerAwarePoms) {
8979
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8980
+ setResolveToComponentNameFn(() => null);
8981
+ return;
8982
+ }
8983
+ let result;
8984
+ if (routerType === "nuxt") {
8985
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8986
+ } else {
8987
+ const resolvedRouterEntry = getResolvedRouterEntry();
8988
+ if (!resolvedRouterEntry)
8989
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8990
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8991
+ moduleShims: routerModuleShims,
8992
+ componentNaming: {
8993
+ projectRoot: projectRootRef.current,
8994
+ viewsDirAbs: getViewsDirAbs(),
8995
+ sourceDirs: getSourceDirs(),
8996
+ extraRoots: [process.cwd()]
8997
+ }
8998
+ });
8999
+ }
9000
+ const { routeNameMap, routePathMap } = result;
9001
+ setRouteNameToComponentNameMap(routeNameMap);
9002
+ setResolveToComponentNameFn((to) => {
9003
+ if (typeof to === "string") {
9004
+ return routePathMap.get(to) ?? null;
9005
+ }
9006
+ const maybe = to;
9007
+ if (typeof maybe.name === "string" && maybe.name.length) {
9008
+ const key = toPascalCase(maybe.name);
9009
+ return routeNameMap.get(key) ?? null;
9010
+ }
9011
+ if (typeof maybe.path === "string" && maybe.path.length) {
9012
+ return routePathMap.get(maybe.path) ?? null;
9013
+ }
9014
+ return null;
9015
+ });
9016
+ })();
9017
+ const logInfo = (message) => loggerRef.current.info(message);
9018
+ const logDebug = (message) => loggerRef.current.debug(message);
9019
+ let scheduleVueFileRegenLocal = null;
9020
+ const formatMs = (ms) => `${ms.toFixed(1)}ms`;
9021
+ const extractTemplateFromSfc = (source, filename) => {
9022
+ const { descriptor } = parse$1(source, {
9023
+ filename: filename ?? "anonymous.vue"
9024
+ });
9025
+ return descriptor.template?.content ?? "";
9026
+ };
9027
+ const getScriptInfo = (source, filename) => {
9028
+ try {
9029
+ const { descriptor } = parse$1(source, { filename });
9030
+ if (!descriptor.script && !descriptor.scriptSetup)
9031
+ return { bindings: void 0, isScriptSetup: false };
9032
+ const scriptBlock = compileScript(descriptor, { id: filename });
9033
+ return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
9034
+ } catch {
9035
+ return { bindings: void 0, isScriptSetup: false };
9036
+ }
9037
+ };
9038
+ const walkFilesRecursive = (rootDir) => {
9039
+ const out = [];
9040
+ const stack = [rootDir];
9041
+ while (stack.length) {
9042
+ const dir = stack.pop();
9043
+ if (!dir) continue;
9044
+ let entries = [];
9045
+ try {
9046
+ entries = fs.readdirSync(dir, { withFileTypes: true });
9047
+ } catch {
9048
+ continue;
9049
+ }
9050
+ for (const ent of entries) {
9051
+ if (ent.isDirectory()) {
9052
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
9053
+ continue;
9054
+ stack.push(path.join(dir, ent.name));
9055
+ continue;
9056
+ }
9057
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
9058
+ out.push(path.join(dir, ent.name));
9059
+ }
9060
+ }
9061
+ }
9062
+ return out;
9063
+ };
9064
+ let snapshotHierarchy = /* @__PURE__ */ new Map();
9065
+ let snapshotVuePathMap = /* @__PURE__ */ new Map();
9066
+ const filePathToComponentName = /* @__PURE__ */ new Map();
9067
+ const createEmptyComponentDependencies = (absolutePath) => {
9068
+ const viewsDirAbs = path.resolve(getViewsDirAbs());
9069
+ const relToViewsDir = path.relative(viewsDirAbs, absolutePath);
9070
+ const isView = !relToViewsDir.startsWith("..") && !path.isAbsolute(relToViewsDir);
9071
+ return {
9072
+ filePath: absolutePath,
9073
+ childrenComponentSet: /* @__PURE__ */ new Set(),
9074
+ usedComponentSet: /* @__PURE__ */ new Set(),
9075
+ dataTestIdSet: /* @__PURE__ */ new Set(),
9076
+ isView,
9077
+ methodsContent: ""
9078
+ };
9079
+ };
9080
+ const getComponentNameForFile = (filePath) => {
9081
+ const normalized = path.resolve(filePath);
9082
+ const existing = filePathToComponentName.get(normalized);
9083
+ if (existing)
9084
+ return existing;
9085
+ const name = resolveComponentNameFromPath({
9086
+ filename: normalized,
9087
+ projectRoot: projectRootRef.current,
9088
+ viewsDirAbs: getViewsDirAbs(),
9089
+ sourceDirs: getSourceDirs(),
9090
+ extraRoots: [process.cwd()]
9091
+ });
9092
+ filePathToComponentName.set(normalized, name);
9093
+ return name;
9094
+ };
9095
+ const compileVueFileIntoSnapshot = (filePath, targetHierarchy = snapshotHierarchy, targetVuePathMap = snapshotVuePathMap) => {
9096
+ const started = performance.now();
9097
+ const absolutePath = path.resolve(filePath);
9098
+ const componentName = getComponentNameForFile(absolutePath);
9099
+ let sfc = "";
9100
+ try {
9101
+ sfc = fs.readFileSync(absolutePath, "utf8");
9102
+ } catch {
9103
+ return { componentName, ms: performance.now() - started, compiled: false };
9104
+ }
9105
+ const template = extractTemplateFromSfc(sfc, absolutePath);
9106
+ if (!template.trim()) {
9107
+ targetVuePathMap.set(componentName, absolutePath);
9108
+ targetHierarchy.set(componentName, createEmptyComponentDependencies(absolutePath));
9109
+ return { componentName, ms: performance.now() - started, compiled: true };
9110
+ }
9111
+ const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
9112
+ const provisionalHierarchy = /* @__PURE__ */ new Map();
9113
+ const provisionalKeyRegistry = /* @__PURE__ */ new Map();
9114
+ const provisionalVuePathMap = new Map(targetVuePathMap);
9115
+ provisionalVuePathMap.set(componentName, absolutePath);
9116
+ compilerDom.compile(template, {
9117
+ filename: absolutePath,
9118
+ prefixIdentifiers: true,
9119
+ inline: isScriptSetup,
9120
+ bindingMetadata,
9121
+ // Vue templates may contain TypeScript type annotations in expressions
9122
+ // (e.g. `@row-click="(row: RowType) => navigateTo(...)"` in Nuxt + TS
9123
+ // apps). Without this flag, Vue's internal processExpression step
9124
+ // delegates to @babel/parser without the TS plugin and crashes on
9125
+ // "Unexpected token, expected ','".
9126
+ expressionPlugins: ["typescript"],
9127
+ nodeTransforms: [
9128
+ createTestIdTransform(
9129
+ componentName,
9130
+ provisionalHierarchy,
9131
+ nativeWrappers,
9132
+ excludedComponents,
9133
+ getViewsDirAbs(),
9134
+ {
9135
+ existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
9136
+ nameCollisionBehavior,
9137
+ missingSemanticNameBehavior,
9138
+ testIdAttribute,
9139
+ warn: (message) => loggerRef.current.warn(message),
9140
+ vueFilesPathMap: provisionalVuePathMap,
9141
+ wrapperSearchRoots: getWrapperSearchRoots(),
9142
+ crossFileKeyRegistry: provisionalKeyRegistry,
9143
+ optionKeyAttribute
9144
+ }
9145
+ )
9146
+ ]
9147
+ });
9148
+ targetVuePathMap.set(componentName, absolutePath);
9149
+ targetHierarchy.set(
9150
+ componentName,
9151
+ provisionalHierarchy.get(componentName) ?? createEmptyComponentDependencies(absolutePath)
9152
+ );
9153
+ return { componentName, ms: performance.now() - started, compiled: true };
9154
+ };
9155
+ const fullRebuildSnapshotFromFilesystem = (logLabel) => {
9156
+ const t0 = performance.now();
9157
+ const nextHierarchy = /* @__PURE__ */ new Map();
9158
+ const nextVuePathMap = /* @__PURE__ */ new Map();
9159
+ filePathToComponentName.clear();
9160
+ let totalVueFiles = 0;
9161
+ let compiledCount = 0;
9162
+ for (const absDir of getSourceDirRoots()) {
9163
+ if (!fs.existsSync(absDir))
9164
+ continue;
9165
+ const vueFiles = walkFilesRecursive(absDir);
9166
+ totalVueFiles += vueFiles.length;
9167
+ for (const file of vueFiles) {
9168
+ const res = compileVueFileIntoSnapshot(file, nextHierarchy, nextVuePathMap);
9169
+ if (res.compiled)
9170
+ compiledCount++;
9171
+ }
9172
+ }
9173
+ snapshotHierarchy = nextHierarchy;
9174
+ snapshotVuePathMap = nextVuePathMap;
9175
+ const t1 = performance.now();
9176
+ logInfo(`scan(${logLabel}): found ${totalVueFiles} .vue files in ${getSourceDirs().join(", ")}`);
9177
+ logInfo(`compile(${logLabel}): ${compiledCount}/${totalVueFiles} files in ${formatMs(t1 - t0)} (components=${snapshotHierarchy.size})`);
9178
+ };
9179
+ const generateAggregatedFromSnapshot = async (logLabel) => {
9180
+ const t0 = performance.now();
9181
+ await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
9182
+ outDir,
9183
+ emitLanguages,
9184
+ typescriptOutputStructure,
9185
+ csharp,
9186
+ generateFixtures,
9187
+ customPomAttachments,
9188
+ projectRoot: projectRootRef.current,
9189
+ customPomDir,
9190
+ requireCustomPomDir,
9191
+ customPomImportAliases,
9192
+ customPomImportNameCollisionBehavior,
9193
+ pageDirs: getPageDirs(),
9194
+ componentDirs: getComponentDirs(),
9195
+ layoutDirs: getLayoutDirs(),
9196
+ testIdAttribute,
9197
+ vueRouterFluentChaining: routerAwarePoms,
9198
+ routerEntry: getResolvedRouterEntry(),
9199
+ routerType
9200
+ });
9201
+ const t1 = performance.now();
9202
+ logInfo(`generate(${logLabel}): components=${snapshotHierarchy.size} in ${formatMs(t1 - t0)}`);
9203
+ };
9204
+ let timer = null;
9205
+ let maxWaitTimer = null;
9206
+ const pendingChangedVueFiles = /* @__PURE__ */ new Set();
9207
+ const pendingDeletedComponents = /* @__PURE__ */ new Set();
9208
+ let regenerationSequence = Promise.resolve();
9209
+ const initialBuildPromise = (async () => {
9210
+ const t0 = performance.now();
9211
+ await routerInitPromise;
9212
+ fullRebuildSnapshotFromFilesystem("startup");
9213
+ await generateAggregatedFromSnapshot("startup");
9214
+ const t1 = performance.now();
9215
+ logInfo(`startup total: ${formatMs(t1 - t0)}`);
9216
+ })();
9217
+ const logGenerationError = (reason, message) => {
9218
+ server.config.logger.error(`[vue-pom-generator] dev generation failed during ${reason}: ${message}`);
9219
+ };
9220
+ const regenerateFromPending = async (reason) => {
9221
+ const t0 = performance.now();
9222
+ await initialBuildPromise;
9223
+ const nextHierarchy = new Map(snapshotHierarchy);
9224
+ const nextVuePathMap = new Map(snapshotVuePathMap);
9225
+ for (const componentName of pendingDeletedComponents) {
9226
+ nextHierarchy.delete(componentName);
9227
+ nextVuePathMap.delete(componentName);
9228
+ }
9229
+ const files = Array.from(pendingChangedVueFiles);
9230
+ const deletedCount = pendingDeletedComponents.size;
9231
+ pendingChangedVueFiles.clear();
9232
+ pendingDeletedComponents.clear();
9233
+ let compileMs = 0;
9234
+ for (const f of files) {
9235
+ const res = compileVueFileIntoSnapshot(f, nextHierarchy, nextVuePathMap);
9236
+ compileMs += res.ms;
9237
+ }
9238
+ snapshotHierarchy = nextHierarchy;
9239
+ snapshotVuePathMap = nextVuePathMap;
9240
+ const t1 = performance.now();
9241
+ await generateAggregatedFromSnapshot(reason);
9242
+ const t2 = performance.now();
9243
+ return {
9244
+ files,
9245
+ deletedCount,
9246
+ compileMs,
9247
+ preGenerateMs: t1 - t0,
9248
+ generateMs: t2 - t1,
9249
+ totalMs: t2 - t0
9250
+ };
9251
+ };
9252
+ const enqueueRegeneration = (reason) => {
9253
+ const currentRun = regenerationSequence.catch(() => void 0).then(() => regenerateFromPending(reason));
9254
+ regenerationSequence = currentRun.then(() => void 0, () => void 0);
9255
+ return currentRun;
9256
+ };
9257
+ const runtimeDir = path.dirname(basePageClassPath);
9258
+ const localPluginDir = path.resolve(projectRootRef.current, "vite-plugins", "vue-pom-generator");
9259
+ server.watcher.add([
9260
+ ...fs.existsSync(localPluginDir) ? [localPluginDir] : [],
9261
+ basePageClassPath,
9262
+ path.resolve(runtimeDir, "pointer.ts"),
9263
+ path.resolve(runtimeDir, "callout.ts"),
9264
+ path.resolve(runtimeDir, "floating-ui-callout.ts")
9265
+ ]);
9266
+ scheduleVueFileRegenLocal = (filePath, source) => {
9267
+ pendingChangedVueFiles.add(filePath);
9268
+ logDebug(`queued(${source}): files=${pendingChangedVueFiles.size} deleted=${pendingDeletedComponents.size}`);
9269
+ scheduleAggregatedRegen();
9270
+ };
9271
+ scheduleVueFileRegen = scheduleVueFileRegenLocal;
9272
+ function scheduleAggregatedRegen() {
9273
+ const wasEmpty = pendingChangedVueFiles.size === 0 && pendingDeletedComponents.size === 0;
9274
+ const MAX_WAIT_MS = 750;
9275
+ if (!maxWaitTimer) {
9276
+ maxWaitTimer = setTimeout(() => {
9277
+ if (timer) {
9278
+ clearTimeout(timer);
9279
+ timer = null;
9280
+ }
9281
+ maxWaitTimer = null;
9282
+ void enqueueRegeneration("max-wait").then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9283
+ logInfo(
9284
+ `max-wait: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9285
+ );
9286
+ }).catch((error) => {
9287
+ const message = error instanceof Error ? error.message : String(error);
9288
+ logGenerationError("max-wait", message);
9289
+ });
9290
+ }, MAX_WAIT_MS);
9336
9291
  }
9337
- }
9338
- } else if (node.type === NodeTypes.IF) {
9339
- for (const branch of node.branches) {
9340
- traverseNode(branch);
9341
- }
9342
- } else if (node.type === NodeTypes.IF_BRANCH || node.type === NodeTypes.FOR) {
9343
- if (node.children) {
9344
- for (const child of node.children) {
9345
- traverseNode(child);
9292
+ if (wasEmpty) {
9293
+ const queuedFiles = pendingChangedVueFiles.size;
9294
+ const queuedDeletes = pendingDeletedComponents.size;
9295
+ logDebug(`queued: files=${queuedFiles} deleted=${queuedDeletes}`);
9346
9296
  }
9347
- }
9348
- } else if (node.type === NodeTypes.ROOT) {
9349
- for (const child of node.children) {
9350
- traverseNode(child);
9351
- }
9352
- }
9353
- }
9354
- traverseNode(ast);
9355
- if (componentMetadata.size > 0) {
9356
- elementMetadata.set(componentName, componentMetadata);
9357
- }
9358
- return componentMetadata;
9359
- }
9360
- function createVuePluginWithTestIds(options) {
9361
- const {
9362
- vueOptions,
9363
- existingIdBehavior,
9364
- nameCollisionBehavior,
9365
- missingSemanticNameBehavior = "error",
9366
- nativeWrappers,
9367
- optionKeyAttribute,
9368
- elementMetadata,
9369
- semanticNameMap,
9370
- componentHierarchyMap,
9371
- crossFileKeyRegistry,
9372
- vueFilesPathMap,
9373
- excludedComponents,
9374
- getViewsDirAbs,
9375
- testIdAttribute,
9376
- accessibilityAudit,
9377
- loggerRef,
9378
- getSourceDirs,
9379
- getWrapperSearchRoots,
9380
- getProjectRoot,
9381
- annotatorMetadata
9382
- } = options;
9383
- const lastAccessibilityWarningSignatureByComponent = /* @__PURE__ */ new Map();
9384
- const getComponentNameFromPath = (filename) => {
9385
- return resolveComponentNameFromPath({
9386
- filename,
9387
- projectRoot: getProjectRoot(),
9388
- viewsDirAbs: getViewsDirAbs(),
9389
- sourceDirs: getSourceDirs(),
9390
- extraRoots: [process.cwd()]
9391
- });
9392
- };
9393
- const isFileInScope = (filename) => {
9394
- if (!filename)
9395
- return false;
9396
- const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
9397
- const projectRoot = getProjectRoot();
9398
- const matched = isFileInConfiguredSourceScope({
9399
- filename,
9400
- projectRoot,
9401
- viewsDirAbs: getViewsDirAbs(),
9402
- sourceDirs: getSourceDirs(),
9403
- extraRoots: [process.cwd()]
9404
- });
9405
- if (cleanPath.endsWith(".vue") && !matched) {
9406
- const absFilename = path.normalize(path.isAbsolute(cleanPath) ? cleanPath : path.resolve(projectRoot, cleanPath));
9407
- loggerRef.current.debug(`[isFileInScope] REJECTED: ${absFilename} (Clean: ${cleanPath})`);
9408
- }
9409
- return matched;
9410
- };
9411
- const userTemplate = vueOptions?.template ?? {};
9412
- const userCompilerOptions = userTemplate.compilerOptions ?? {};
9413
- const userNodeTransforms = userCompilerOptions.nodeTransforms ?? [];
9414
- const perFileTransform = /* @__PURE__ */ new Map();
9415
- const getNodeTransforms = (filename, componentNameOverride) => {
9416
- const cleanPath = filename.includes("?") ? filename.substring(0, filename.indexOf("?")) : filename;
9417
- const viewsDirAbs = getViewsDirAbs();
9418
- const componentName = componentNameOverride || getComponentNameFromPath(cleanPath);
9419
- return [
9420
- ...userNodeTransforms,
9421
- (node, context) => {
9422
- if (node.type === NodeTypes.ROOT) {
9423
- componentHierarchyMap.delete(componentName);
9424
- vueFilesPathMap.set(componentName, filename);
9425
- perFileTransform.set(
9426
- componentName,
9427
- createTestIdTransform(
9428
- componentName,
9429
- componentHierarchyMap,
9430
- nativeWrappers,
9431
- excludedComponents,
9432
- viewsDirAbs,
9433
- {
9434
- existingIdBehavior,
9435
- testIdAttribute,
9436
- nameCollisionBehavior,
9437
- missingSemanticNameBehavior,
9438
- warn: (message) => loggerRef.current.warn(message),
9439
- vueFilesPathMap,
9440
- wrapperSearchRoots: getWrapperSearchRoots(),
9441
- annotatorMetadata,
9442
- crossFileKeyRegistry,
9443
- optionKeyAttribute
9444
- }
9445
- )
9446
- );
9447
- return () => {
9448
- const componentMetadata = extractMetadataAfterTransform(
9449
- node,
9450
- componentName,
9451
- elementMetadata,
9452
- semanticNameMap,
9453
- testIdAttribute
9454
- );
9455
- if (!accessibilityAudit) {
9456
- return;
9457
- }
9458
- const dependencies = componentHierarchyMap.get(componentName);
9459
- if (!dependencies || componentMetadata.size === 0) {
9460
- return;
9461
- }
9462
- const manifest = buildPomManifest(
9463
- /* @__PURE__ */ new Map([[componentName, dependencies]]),
9464
- /* @__PURE__ */ new Map([[componentName, componentMetadata]])
9465
- );
9466
- const warnings = collectAccessibilityReviewWarnings(manifest);
9467
- const signature = warnings.join("\n");
9468
- if (!signature) {
9469
- lastAccessibilityWarningSignatureByComponent.delete(componentName);
9470
- return;
9471
- }
9472
- if (lastAccessibilityWarningSignatureByComponent.get(componentName) === signature) {
9473
- return;
9474
- }
9475
- lastAccessibilityWarningSignatureByComponent.set(componentName, signature);
9476
- for (const warning of warnings) {
9477
- loggerRef.current.warn(warning);
9297
+ if (timer)
9298
+ clearTimeout(timer);
9299
+ timer = setTimeout(() => {
9300
+ timer = null;
9301
+ if (maxWaitTimer) {
9302
+ clearTimeout(maxWaitTimer);
9303
+ maxWaitTimer = null;
9304
+ }
9305
+ const reason = pendingChangedVueFiles.size || pendingDeletedComponents.size ? "batched" : "noop";
9306
+ void enqueueRegeneration(reason).then(({ files, deletedCount, compileMs, preGenerateMs, generateMs, totalMs }) => {
9307
+ if (files.length || deletedCount) {
9308
+ logInfo(
9309
+ `batched: files=${files.length} deleted=${deletedCount} compile=${formatMs(compileMs)} wall=${formatMs(preGenerateMs)} gen=${formatMs(generateMs)} total=${formatMs(totalMs)}`
9310
+ );
9478
9311
  }
9479
- };
9312
+ }).catch((error) => {
9313
+ const message = error instanceof Error ? error.message : String(error);
9314
+ logGenerationError(reason, message);
9315
+ });
9316
+ }, 75);
9317
+ }
9318
+ server.watcher.on("change", async (changedPath) => {
9319
+ const changedAbsPosix = path.posix.normalize(path.resolve(changedPath));
9320
+ const outDirAbsPosix = path.posix.normalize(path.resolve(projectRootRef.current, outDir ?? "./pom"));
9321
+ if (changedAbsPosix.startsWith(`${outDirAbsPosix}/`) && (changedAbsPosix.endsWith(".g.ts") || changedAbsPosix.endsWith(".g.ts.map"))) {
9322
+ return;
9480
9323
  }
9481
- let transform = perFileTransform.get(componentName);
9482
- if (!transform) {
9483
- componentHierarchyMap.delete(componentName);
9484
- vueFilesPathMap.set(componentName, filename);
9485
- transform = createTestIdTransform(
9486
- componentName,
9487
- componentHierarchyMap,
9488
- nativeWrappers,
9489
- excludedComponents,
9490
- viewsDirAbs,
9491
- {
9492
- existingIdBehavior,
9493
- testIdAttribute,
9494
- nameCollisionBehavior,
9495
- missingSemanticNameBehavior,
9496
- warn: (message) => loggerRef.current.warn(message),
9497
- vueFilesPathMap,
9498
- wrapperSearchRoots: getWrapperSearchRoots(),
9499
- annotatorMetadata,
9500
- crossFileKeyRegistry,
9501
- optionKeyAttribute
9502
- }
9503
- );
9504
- perFileTransform.set(componentName, transform);
9324
+ if (changedAbsPosix.includes("/vite-plugins/vue-pom-generator/")) {
9325
+ void server.restart();
9505
9326
  }
9506
- return transform(node, context);
9507
- }
9508
- ];
9327
+ });
9328
+ server.watcher.on("add", (p) => {
9329
+ if (typeof p !== "string")
9330
+ return;
9331
+ if (!p.endsWith(".vue"))
9332
+ return;
9333
+ if (!isContainedInScanDirs(p))
9334
+ return;
9335
+ void (async () => {
9336
+ await initialBuildPromise;
9337
+ pendingChangedVueFiles.add(p);
9338
+ scheduleAggregatedRegen();
9339
+ })();
9340
+ });
9341
+ server.watcher.on("unlink", (p) => {
9342
+ if (typeof p !== "string")
9343
+ return;
9344
+ if (!p.endsWith(".vue"))
9345
+ return;
9346
+ if (!isContainedInScanDirs(p))
9347
+ return;
9348
+ void (async () => {
9349
+ await initialBuildPromise;
9350
+ const absolutePath = path.resolve(p);
9351
+ const componentName = getComponentNameForFile(absolutePath);
9352
+ filePathToComponentName.delete(absolutePath);
9353
+ pendingDeletedComponents.add(componentName);
9354
+ scheduleAggregatedRegen();
9355
+ })();
9356
+ });
9357
+ setTimeout(() => {
9358
+ }, 250);
9359
+ await initialBuildPromise;
9360
+ }
9509
9361
  };
9510
- const runtimeNodeTransform = (node, context) => {
9511
- const filename = context.filename;
9512
- if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
9513
- return;
9362
+ }
9363
+ const TEST_IDS_VIRTUAL_ID = "virtual:testids";
9364
+ const TEST_IDS_RESOLVED_ID = `\0${TEST_IDS_VIRTUAL_ID}`;
9365
+ const POM_MANIFEST_VIRTUAL_ID = "virtual:pom-manifest";
9366
+ const POM_MANIFEST_RESOLVED_ID = `\0${POM_MANIFEST_VIRTUAL_ID}`;
9367
+ function createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata) {
9368
+ return {
9369
+ name: "vue-pom-generator:virtual-testids",
9370
+ resolveId(id) {
9371
+ if (id === TEST_IDS_VIRTUAL_ID)
9372
+ return TEST_IDS_RESOLVED_ID;
9373
+ if (id === POM_MANIFEST_VIRTUAL_ID)
9374
+ return POM_MANIFEST_RESOLVED_ID;
9375
+ },
9376
+ load(id) {
9377
+ if (id === TEST_IDS_RESOLVED_ID)
9378
+ return generateTestIdsModule(componentHierarchyMap, elementMetadata);
9379
+ if (id === POM_MANIFEST_RESOLVED_ID)
9380
+ return generatePomManifestModule(componentHierarchyMap, elementMetadata);
9514
9381
  }
9515
- const transforms = getNodeTransforms(filename);
9516
- const ourTransform = transforms[transforms.length - 1];
9517
- return ourTransform(node, context);
9518
- };
9519
- const templateCompilerOptions = {
9520
- ...userCompilerOptions,
9521
- prefixIdentifiers: true,
9522
- nodeTransforms: [
9523
- ...userNodeTransforms,
9524
- runtimeNodeTransform
9525
- ]
9526
9382
  };
9527
- const metadataCollectorPlugin = {
9528
- name: "vue-pom-generator-metadata-collector",
9529
- enforce: "pre",
9530
- async transform(code, id) {
9531
- const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
9532
- if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
9383
+ }
9384
+ const ANNOTATOR_CLIENT_VIRTUAL_ID = "virtual:vue-pom-generator/annotator-client";
9385
+ const ANNOTATOR_CLIENT_RESOLVED_ID = `\0${ANNOTATOR_CLIENT_VIRTUAL_ID}`;
9386
+ const DEFAULT_ENTRY_SUFFIXES = [
9387
+ "/src/main.ts",
9388
+ "/src/main.js",
9389
+ "/src/main.mts",
9390
+ "/src/main.tsx",
9391
+ "/src/main.jsx"
9392
+ ];
9393
+ function normalizePathSeparators(filePath) {
9394
+ return filePath.replace(/\\/g, "/");
9395
+ }
9396
+ function toFsImportPath(filePath) {
9397
+ return `/@fs/${normalizePathSeparators(filePath)}`;
9398
+ }
9399
+ function resolveAnnotatorClientPath() {
9400
+ const candidates = [
9401
+ fileURLToPath(new URL("./client.ts", import.meta.url)),
9402
+ fileURLToPath(new URL("../plugin/runtime/annotator/client.ts", import.meta.url))
9403
+ ];
9404
+ const resolved = candidates.find((candidate) => fs.existsSync(candidate));
9405
+ if (!resolved) {
9406
+ throw new Error("[vue-pom-generator] Unable to locate annotator client source.");
9407
+ }
9408
+ return path.resolve(resolved);
9409
+ }
9410
+ function createAnnotatorUiPlugin(options) {
9411
+ const clientPath = resolveAnnotatorClientPath();
9412
+ const clientImportPath = toFsImportPath(clientPath);
9413
+ const clientOptions = JSON.stringify({
9414
+ sourceAttribute: options.sourceAttribute,
9415
+ metadataAttributePrefix: options.metadataAttributePrefix,
9416
+ outputDetail: options.outputDetail,
9417
+ copyToClipboard: options.copyToClipboard,
9418
+ showComponentTree: options.showComponentTree
9419
+ });
9420
+ return {
9421
+ name: "vue-pom-generator:annotator-ui",
9422
+ apply: "serve",
9423
+ resolveId(id) {
9424
+ if (id === ANNOTATOR_CLIENT_VIRTUAL_ID) {
9425
+ return ANNOTATOR_CLIENT_RESOLVED_ID;
9426
+ }
9427
+ },
9428
+ load(id) {
9429
+ if (id !== ANNOTATOR_CLIENT_RESOLVED_ID) {
9533
9430
  return null;
9534
9431
  }
9535
- if (id !== cleanPath) {
9432
+ return [
9433
+ `import { mountAnnotatorClient } from ${JSON.stringify(clientImportPath)};`,
9434
+ `mountAnnotatorClient(${clientOptions});`,
9435
+ ""
9436
+ ].join("\n");
9437
+ },
9438
+ transform(code, id) {
9439
+ if (!options.enabled) {
9536
9440
  return null;
9537
9441
  }
9538
- const componentName = getComponentNameFromPath(cleanPath);
9539
- loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
9540
- const compilerSfc = await import("@vue/compiler-sfc");
9541
- const parse2 = resolveCompilerSfcParse(compilerSfc);
9542
- const compilerDom2 = await import("@vue/compiler-dom");
9543
- const compile = compilerDom2.compile;
9544
- const { descriptor } = parse2(code, { filename: cleanPath });
9545
- if (descriptor.template) {
9546
- const mergedExpressionPlugins = Array.from(
9547
- /* @__PURE__ */ new Set([
9548
- "typescript",
9549
- ...userCompilerOptions.expressionPlugins ?? []
9550
- ])
9551
- );
9552
- compile(descriptor.template.content, {
9553
- ...userCompilerOptions,
9554
- filename: cleanPath,
9555
- expressionPlugins: mergedExpressionPlugins,
9556
- nodeTransforms: getNodeTransforms(cleanPath, componentName)
9557
- });
9558
- loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
9442
+ const normalizedId = normalizePathSeparators(id);
9443
+ if (!DEFAULT_ENTRY_SUFFIXES.some((suffix) => normalizedId.endsWith(suffix))) {
9444
+ return null;
9559
9445
  }
9560
- return null;
9561
- }
9562
- };
9563
- const template = {
9564
- ...userTemplate,
9565
- compilerOptions: templateCompilerOptions
9566
- };
9567
- const internalVuePlugin = vue({
9568
- ...vueOptions,
9569
- template
9570
- });
9571
- const nuxtVueBridgePlugin = {
9572
- name: "vue-pom-generator-nuxt-vue-bridge",
9573
- apply: "serve",
9574
- configResolved(config) {
9575
- const viteVuePlugin = config.plugins.find((plugin) => {
9576
- return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
9577
- });
9578
- const api = viteVuePlugin?.api;
9579
- if (!api) {
9580
- throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
9446
+ if (code.includes(ANNOTATOR_CLIENT_VIRTUAL_ID)) {
9447
+ return null;
9581
9448
  }
9582
- const currentOptions = api.options ?? {};
9583
- const currentTemplate = currentOptions.template ?? {};
9584
- const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
9585
- const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
9586
- if (currentNodeTransforms.includes(runtimeNodeTransform)) {
9587
- return;
9449
+ return {
9450
+ code: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};
9451
+ ${code}`,
9452
+ map: null
9453
+ };
9454
+ },
9455
+ transformIndexHtml() {
9456
+ if (!options.enabled) {
9457
+ return void 0;
9588
9458
  }
9589
- api.options = {
9590
- ...currentOptions,
9591
- template: {
9592
- ...currentTemplate,
9593
- compilerOptions: {
9594
- ...currentCompilerOptions,
9595
- prefixIdentifiers: true,
9596
- nodeTransforms: [
9597
- ...currentNodeTransforms,
9598
- runtimeNodeTransform
9599
- ]
9600
- }
9601
- }
9459
+ const tag = {
9460
+ tag: "script",
9461
+ attrs: { type: "module" },
9462
+ children: `import ${JSON.stringify(ANNOTATOR_CLIENT_VIRTUAL_ID)};`,
9463
+ injectTo: "body"
9602
9464
  };
9465
+ return [tag];
9603
9466
  }
9604
9467
  };
9605
- return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
9468
+ }
9469
+ function createInternalPlugins(options) {
9470
+ const {
9471
+ componentHierarchyMap,
9472
+ crossFileKeyRegistry,
9473
+ elementMetadata,
9474
+ vueFilesPathMap,
9475
+ nativeWrappers,
9476
+ optionKeyAttribute,
9477
+ excludedComponents,
9478
+ getPageDirs,
9479
+ getComponentDirs,
9480
+ getLayoutDirs,
9481
+ getViewsDir,
9482
+ getSourceDirs,
9483
+ getWrapperSearchRoots,
9484
+ generation,
9485
+ projectRootRef,
9486
+ basePageClassPath: basePageClassPathOverride,
9487
+ loggerRef,
9488
+ annotatorRuntime
9489
+ } = options;
9490
+ const {
9491
+ routerAwarePoms,
9492
+ routerEntry,
9493
+ routerType
9494
+ } = generation;
9495
+ const resolveRouterEntry2 = () => {
9496
+ if (!routerAwarePoms)
9497
+ return void 0;
9498
+ if (routerType === "nuxt")
9499
+ return void 0;
9500
+ if (!routerEntry)
9501
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
9502
+ return path.isAbsolute(routerEntry) ? routerEntry : path.resolve(projectRootRef.current, routerEntry);
9503
+ };
9504
+ const getDefaultBasePageClassPath = () => {
9505
+ try {
9506
+ return fileURLToPath(new URL("../class-generation/base-page.ts", import.meta.url));
9507
+ } catch {
9508
+ return path.resolve(__dirname, "..", "class-generation", "base-page.ts");
9509
+ }
9510
+ };
9511
+ const basePageClassPath = basePageClassPathOverride ?? getDefaultBasePageClassPath();
9512
+ const normalizedBasePagePath = path.posix.normalize(basePageClassPath);
9513
+ const tsProcessor = createBuildProcessorPlugin({
9514
+ componentHierarchyMap,
9515
+ crossFileKeyRegistry,
9516
+ vueFilesPathMap,
9517
+ getPageDirs,
9518
+ getComponentDirs,
9519
+ getLayoutDirs,
9520
+ getViewsDir,
9521
+ getSourceDirs,
9522
+ basePageClassPath,
9523
+ normalizedBasePagePath,
9524
+ generation,
9525
+ projectRootRef,
9526
+ nativeWrappers,
9527
+ optionKeyAttribute,
9528
+ excludedComponents,
9529
+ getWrapperSearchRoots,
9530
+ getResolvedRouterEntry: resolveRouterEntry2,
9531
+ loggerRef
9532
+ });
9533
+ const devProcessor = createDevProcessorPlugin({
9534
+ nativeWrappers,
9535
+ optionKeyAttribute,
9536
+ excludedComponents,
9537
+ getPageDirs,
9538
+ getComponentDirs,
9539
+ getLayoutDirs,
9540
+ getViewsDir,
9541
+ getSourceDirs,
9542
+ getWrapperSearchRoots,
9543
+ projectRootRef,
9544
+ normalizedBasePagePath,
9545
+ basePageClassPath,
9546
+ generation,
9547
+ getResolvedRouterEntry: resolveRouterEntry2,
9548
+ loggerRef
9549
+ });
9550
+ const virtualModules = createTestIdsVirtualModulesPlugin(componentHierarchyMap, elementMetadata);
9551
+ const annotatorUiPlugin = createAnnotatorUiPlugin({
9552
+ ...annotatorRuntime.ui,
9553
+ enabled: annotatorRuntime.enabled && annotatorRuntime.ui.enabled,
9554
+ sourceAttribute: annotatorRuntime.sourceAttribute,
9555
+ metadataAttributePrefix: annotatorRuntime.metadataAttributePrefix
9556
+ });
9557
+ return [tsProcessor, devProcessor, virtualModules, annotatorUiPlugin];
9606
9558
  }
9607
9559
  const nuxtConfigMarker$1 = /* @__PURE__ */ Symbol.for("@immense/vue-pom-generator.nuxt");
9608
9560
  const nuxtConfigFileNames = [