@immense/vue-pom-generator 1.0.106 → 1.0.108

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 (36) hide show
  1. package/README.md +54 -0
  2. package/RELEASE_NOTES.md +36 -24
  3. package/class-generation/index.ts +111 -190
  4. package/dist/class-generation/index.d.ts +3 -0
  5. package/dist/class-generation/index.d.ts.map +1 -1
  6. package/dist/index.cjs +775 -707
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.mjs +776 -708
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/manifest-generator.d.ts +2 -1
  13. package/dist/manifest-generator.d.ts.map +1 -1
  14. package/dist/plugin/create-vue-pom-generator-plugins.d.ts +2 -0
  15. package/dist/plugin/create-vue-pom-generator-plugins.d.ts.map +1 -1
  16. package/dist/plugin/generate-vue-poms.d.ts +10 -0
  17. package/dist/plugin/generate-vue-poms.d.ts.map +1 -0
  18. package/dist/plugin/generated-outputs.d.ts +7 -0
  19. package/dist/plugin/generated-outputs.d.ts.map +1 -0
  20. package/dist/plugin/internal/build-plugin.d.ts +3 -10
  21. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  22. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  23. package/dist/plugin/internal-plugins.d.ts +2 -1
  24. package/dist/plugin/internal-plugins.d.ts.map +1 -1
  25. package/dist/plugin/vue-plugin.d.ts +1 -0
  26. package/dist/plugin/vue-plugin.d.ts.map +1 -1
  27. package/dist/tests/generate-vue-poms.test.d.ts +2 -0
  28. package/dist/tests/generate-vue-poms.test.d.ts.map +1 -0
  29. package/dist/tests/generated-outputs.test.d.ts +2 -0
  30. package/dist/tests/generated-outputs.test.d.ts.map +1 -0
  31. package/dist/tests/incremental-generation.test.d.ts +2 -0
  32. package/dist/tests/incremental-generation.test.d.ts.map +1 -0
  33. package/dist/typescript-codegen.d.ts +14 -1
  34. package/dist/typescript-codegen.d.ts.map +1 -1
  35. package/dist/utils.d.ts.map +1 -1
  36. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -3,16 +3,17 @@ import path from "node:path";
3
3
  import process from "node:process";
4
4
  import { createRequire } from "node:module";
5
5
  import { pathToFileURL, fileURLToPath } from "node:url";
6
+ import { parseExpression, parse } from "@babel/parser";
7
+ import { NodeTypes, stringifyExpression, createSimpleExpression, processExpression, ConstantTypes, ElementTypes } from "@vue/compiler-core";
6
8
  import * as compilerDom from "@vue/compiler-dom";
7
9
  import { parse as parse$2, NodeTypes as NodeTypes$1 } from "@vue/compiler-dom";
8
10
  import { parse as parse$1, compileScript } from "@vue/compiler-sfc";
9
- import { parseExpression, parse } from "@babel/parser";
10
- import { NodeTypes, stringifyExpression, createSimpleExpression, processExpression, ConstantTypes, ElementTypes } from "@vue/compiler-core";
11
11
  import { Project, QuoteKind, NewLineKind, IndentationText, CodeBlockWriter, StructureKind, VariableDeclarationKind } from "ts-morph";
12
- import { isIdentifier, isObjectPattern, isRestElement, isObjectProperty, isArrayExpression, isStringLiteral, isTemplateLiteral, isArrowFunctionExpression, isExpressionStatement, isAssignmentPattern, isMemberExpression, isOptionalMemberExpression, isCallExpression, isOptionalCallExpression, isAssignmentExpression, isSequenceExpression, isObjectExpression, isFile, isBlockStatement, isLogicalExpression, isConditionalExpression, isProgram, isArrayPattern, VISITOR_KEYS, isBooleanLiteral, isNumericLiteral, isNullLiteral, isImportDeclaration, isImportSpecifier, isExportDefaultDeclaration, isExpression, isVariableDeclaration, isFunctionDeclaration, isFunctionExpression, isReturnStatement, isTSAsExpression, isTSTypeAssertion, isTSNonNullExpression, isForInStatement, isIfStatement } from "@babel/types";
12
+ import { isIdentifier, isObjectPattern, isRestElement, isObjectProperty, isArrayExpression, isStringLiteral, isTemplateLiteral, isArrowFunctionExpression, isExpressionStatement, isAssignmentPattern, isMemberExpression, isOptionalMemberExpression, isCallExpression, isOptionalCallExpression, isAssignmentExpression, isObjectExpression, isFile, isBlockStatement, isLogicalExpression, isConditionalExpression, isSequenceExpression, isProgram, isArrayPattern, VISITOR_KEYS, isBooleanLiteral, isNumericLiteral, isNullLiteral, isImportDeclaration, isImportSpecifier, isExportDefaultDeclaration, isExpression, isVariableDeclaration, isFunctionDeclaration, isFunctionExpression, isReturnStatement, isTSAsExpression, isTSTypeAssertion, isTSNonNullExpression, isForInStatement, isIfStatement } from "@babel/types";
13
+ import { createHash, randomUUID } from "node:crypto";
13
14
  import { POM_ROUTER_GLOBAL_NAME } from "./router.mjs";
14
- import vue from "@vitejs/plugin-vue";
15
15
  import { performance } from "node:perf_hooks";
16
+ import vue from "@vitejs/plugin-vue";
16
17
  import { autoUpdate, computePosition, offset, autoPlacement, shift, arrow } from "@floating-ui/dom";
17
18
  const VUE_POM_GENERATOR_LOG_PREFIX = "[vue-pom-generator]";
18
19
  function normalize(message) {
@@ -253,6 +254,58 @@ function applyNuxtDiscoveryToInjectionOptions(options, discovery) {
253
254
  wrapperSearchRoots: discovery.wrapperSearchRoots
254
255
  };
255
256
  }
257
+ class TypeScriptRenderCache {
258
+ entries = /* @__PURE__ */ new Map();
259
+ render(filePath, input, build) {
260
+ const previous = this.entries.get(filePath);
261
+ if (previous?.input === input) return previous.content;
262
+ const content = build();
263
+ this.entries.set(filePath, { input, content });
264
+ return content;
265
+ }
266
+ retain(filePaths) {
267
+ for (const filePath of this.entries.keys()) {
268
+ if (!filePaths.has(filePath)) this.entries.delete(filePath);
269
+ }
270
+ }
271
+ }
272
+ function createClassDeclaration(declaration, members) {
273
+ const result = { ...declaration, kind: StructureKind.Class };
274
+ for (const member of members) {
275
+ switch (member.kind) {
276
+ case StructureKind.Constructor:
277
+ (result.ctors ??= []).push(member);
278
+ break;
279
+ case StructureKind.GetAccessor:
280
+ (result.getAccessors ??= []).push(member);
281
+ break;
282
+ case StructureKind.Method:
283
+ (result.methods ??= []).push(member);
284
+ break;
285
+ case StructureKind.Property:
286
+ (result.properties ??= []).push(member);
287
+ break;
288
+ default:
289
+ throw new Error(`Unsupported class member kind: ${String(member.kind)}`);
290
+ }
291
+ }
292
+ return result;
293
+ }
294
+ function renderStructuredSourceFile(filePath, structure, options = {}) {
295
+ const build = () => {
296
+ const project = createTypeScriptProject();
297
+ const sourceFile = project.createSourceFile(filePath, structure);
298
+ return ensureTrailingNewline(`${options.prefixText ?? ""}${sourceFile.getFullText()}`);
299
+ };
300
+ if (!options.cache) return build();
301
+ const input = JSON.stringify([options.prefixText, structure], (_key, value) => {
302
+ if (typeof value !== "function") return value;
303
+ const writer = createTypeScriptWriter();
304
+ value(writer);
305
+ return writer.toString();
306
+ });
307
+ return options.cache.render(filePath, input, build);
308
+ }
256
309
  function createTypeScriptProject() {
257
310
  return new Project({
258
311
  useInMemoryFileSystem: true,
@@ -317,9 +370,6 @@ function addNamedImport(sourceFile, options) {
317
370
  namedImports: options.namedImports
318
371
  });
319
372
  }
320
- function addExportAll(sourceFile, moduleSpecifier) {
321
- return sourceFile.addExportDeclaration({ moduleSpecifier });
322
- }
323
373
  function createClassMethod(method) {
324
374
  return {
325
375
  kind: StructureKind.Method,
@@ -1416,23 +1466,11 @@ function getSlotScopeVariablesUsedAsBareCallbackHandlers(templateNode) {
1416
1466
  const vFor = node.props.find(
1417
1467
  (prop) => prop.type === NodeTypes.DIRECTIVE && prop.name === "for"
1418
1468
  );
1419
- if (vFor?.exp) {
1420
- const forSource = getVueExpressionSource(vFor.exp, "content", "compiled");
1421
- if (forSource) {
1422
- const aliasMatch = /^\s*([\s\S]+?)\s+(?:in|of)\s+[\s\S]+$/.exec(forSource);
1423
- const aliasSource = aliasMatch?.[1];
1424
- if (aliasSource) {
1425
- try {
1426
- const aliasAst = parseExpression(aliasSource, { plugins: ["typescript"] });
1427
- if (isSequenceExpression(aliasAst)) {
1428
- for (const part of aliasAst.expressions) {
1429
- names.push(...collectBindingPatternNames(part));
1430
- }
1431
- } else {
1432
- names.push(...collectBindingPatternNames(aliasAst));
1433
- }
1434
- } catch {
1435
- }
1469
+ if (vFor?.forParseResult) {
1470
+ const { value, key, index } = vFor.forParseResult;
1471
+ for (const alias of [value, key, index]) {
1472
+ if (alias) {
1473
+ names.push(...collectBindingPatternNames(tryGetTemplateSlotScopeBindingNode(alias)));
1436
1474
  }
1437
1475
  }
1438
1476
  }
@@ -1602,10 +1640,6 @@ function tryGetTemplateSlotScopeBindingNode(expression) {
1602
1640
  if (!rawSource) {
1603
1641
  return null;
1604
1642
  }
1605
- try {
1606
- return parseExpression(rawSource, { plugins: ["typescript"] });
1607
- } catch {
1608
- }
1609
1643
  try {
1610
1644
  const parsed = parse(`(${rawSource}) => {}`, {
1611
1645
  sourceType: "module",
@@ -3966,29 +4000,129 @@ function generateTestIdsModule(componentHierarchyMap, elementMetadata) {
3966
4000
  });
3967
4001
  });
3968
4002
  }
3969
- function generatePomManifestModule(componentHierarchyMap, elementMetadata, fileName = "virtual-pom-manifest.ts") {
4003
+ function generatePomManifestModule(componentHierarchyMap, elementMetadata, fileName = "virtual-pom-manifest.ts", renderCache) {
3970
4004
  const pomManifest = buildPomManifest(componentHierarchyMap, elementMetadata);
3971
- return renderSourceFile(fileName, (sourceFile) => {
3972
- sourceFile.addStatements("// Rich POM discoverability manifest.");
3973
- sourceFile.addVariableStatement({
4005
+ return renderStructuredSourceFile(fileName, {
4006
+ statements: [{
4007
+ kind: StructureKind.VariableStatement,
4008
+ leadingTrivia: "// Rich POM discoverability manifest.\n",
3974
4009
  declarationKind: VariableDeclarationKind.Const,
3975
4010
  isExported: true,
3976
4011
  declarations: [{
3977
4012
  name: "pomManifest",
3978
4013
  initializer: writeConstJson(pomManifest)
3979
4014
  }]
3980
- });
3981
- sourceFile.addTypeAlias({
4015
+ }, {
4016
+ kind: StructureKind.TypeAlias,
3982
4017
  isExported: true,
3983
4018
  name: "PomManifest",
3984
4019
  type: "typeof pomManifest"
3985
- });
3986
- sourceFile.addTypeAlias({
4020
+ }, {
4021
+ kind: StructureKind.TypeAlias,
3987
4022
  isExported: true,
3988
4023
  name: "PomManifestComponentName",
3989
4024
  type: "keyof PomManifest"
3990
- });
3991
- });
4025
+ }]
4026
+ }, { cache: renderCache });
4027
+ }
4028
+ const manifestName = ".vue-pom-generator-outputs.json";
4029
+ function hash(content) {
4030
+ return createHash("sha256").update(content).digest("hex");
4031
+ }
4032
+ function readManifest(filePath) {
4033
+ if (!fs.existsSync(filePath)) {
4034
+ return { version: 1, files: {} };
4035
+ }
4036
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
4037
+ if (!value || typeof value !== "object" || !("version" in value) || value.version !== 1 || !("files" in value) || !value.files || typeof value.files !== "object" || Array.isArray(value.files)) {
4038
+ throw new Error(`[vue-pom-generator] Invalid output ownership manifest: ${filePath}`);
4039
+ }
4040
+ for (const [name, digest] of Object.entries(value.files)) {
4041
+ if (!name || path.isAbsolute(name) || path.win32.isAbsolute(name) || name.includes("\\") || name.includes("\0") || path.posix.normalize(name) !== name || name === "." || name === ".." || name.endsWith("/..") || name.endsWith("/") || path.basename(name) === manifestName || typeof digest !== "string" || digest.length !== 64 || !Array.from(digest).every((character) => "0123456789abcdef".includes(character))) {
4042
+ throw new Error(`[vue-pom-generator] Invalid output ownership entry in ${filePath}: ${name}`);
4043
+ }
4044
+ }
4045
+ return value;
4046
+ }
4047
+ function assertRegularFile(filePath) {
4048
+ const entry = fs.lstatSync(filePath, { throwIfNoEntry: false });
4049
+ if (entry && !entry.isFile()) {
4050
+ throw new Error(`[vue-pom-generator] Refusing to replace or remove a non-regular output file: ${filePath}`);
4051
+ }
4052
+ }
4053
+ function assertNoSymlinkParents(filePath, outDir, projectRoot) {
4054
+ const relativeOutput = path.relative(projectRoot, outDir);
4055
+ let ancestor = relativeOutput === ".." || relativeOutput.startsWith(`..${path.sep}`) || path.isAbsolute(relativeOutput) ? path.dirname(outDir) : projectRoot;
4056
+ const targetDirectory = path.dirname(filePath);
4057
+ while (path.relative(ancestor, targetDirectory) === ".." || path.relative(ancestor, targetDirectory).startsWith(`..${path.sep}`) || path.isAbsolute(path.relative(ancestor, targetDirectory))) {
4058
+ const parent = path.dirname(ancestor);
4059
+ if (parent === ancestor) {
4060
+ throw new Error(`[vue-pom-generator] Output must be on the same filesystem volume as its manifest: ${filePath}`);
4061
+ }
4062
+ ancestor = parent;
4063
+ }
4064
+ for (const target of [path.dirname(filePath), outDir]) {
4065
+ let directory = target;
4066
+ while (directory !== ancestor) {
4067
+ if (fs.lstatSync(directory, { throwIfNoEntry: false })?.isSymbolicLink()) {
4068
+ throw new Error(`[vue-pom-generator] Refusing to follow an output directory symlink: ${directory}`);
4069
+ }
4070
+ directory = path.dirname(directory);
4071
+ }
4072
+ }
4073
+ }
4074
+ function writeFile(filePath, content) {
4075
+ if (fs.existsSync(filePath) && fs.readFileSync(filePath, "utf8") === content) return;
4076
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
4077
+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
4078
+ try {
4079
+ fs.writeFileSync(temporaryPath, content, { flag: "wx" });
4080
+ fs.renameSync(temporaryPath, filePath);
4081
+ } finally {
4082
+ if (fs.existsSync(temporaryPath)) {
4083
+ fs.unlinkSync(temporaryPath);
4084
+ }
4085
+ }
4086
+ }
4087
+ function writeGeneratedOutputs(outDir, files, sharedFiles, projectRoot = path.dirname(path.resolve(outDir))) {
4088
+ const root = path.resolve(outDir);
4089
+ const manifestPath = path.join(root, manifestName);
4090
+ assertNoSymlinkParents(manifestPath, root, projectRoot);
4091
+ assertRegularFile(manifestPath);
4092
+ const previous = readManifest(manifestPath);
4093
+ const next = { version: 1, files: {} };
4094
+ const contents = /* @__PURE__ */ new Map();
4095
+ for (const file of files) {
4096
+ const absolutePath = path.resolve(file.filePath);
4097
+ if (contents.has(absolutePath) || absolutePath === manifestPath) {
4098
+ throw new Error(`[vue-pom-generator] Duplicate generated output: ${absolutePath}`);
4099
+ }
4100
+ contents.set(absolutePath, file.content);
4101
+ next.files[path.relative(root, absolutePath).split(path.sep).join("/")] = hash(file.content);
4102
+ }
4103
+ const obsolete = [];
4104
+ for (const [name, digest] of Object.entries(previous.files)) {
4105
+ const absolutePath = path.resolve(root, name);
4106
+ if (contents.has(absolutePath)) continue;
4107
+ assertNoSymlinkParents(absolutePath, root, projectRoot);
4108
+ assertRegularFile(absolutePath);
4109
+ if (!fs.existsSync(absolutePath)) continue;
4110
+ if (hash(fs.readFileSync(absolutePath, "utf8")) !== digest) {
4111
+ throw new Error(`[vue-pom-generator] Obsolete generated file was modified; move or remove it explicitly before regenerating: ${absolutePath}`);
4112
+ }
4113
+ obsolete.push(absolutePath);
4114
+ }
4115
+ for (const file of sharedFiles) {
4116
+ contents.set(path.resolve(file.filePath), file.content);
4117
+ }
4118
+ for (const filePath of contents.keys()) {
4119
+ assertNoSymlinkParents(filePath, root, projectRoot);
4120
+ assertRegularFile(filePath);
4121
+ }
4122
+ for (const [filePath, content] of contents) writeFile(filePath, content);
4123
+ for (const filePath of obsolete) fs.unlinkSync(filePath);
4124
+ writeFile(manifestPath, `${JSON.stringify(next, null, 2)}
4125
+ `);
3992
4126
  }
3993
4127
  function safeRealpath(value) {
3994
4128
  try {
@@ -5751,7 +5885,7 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5751
5885
  const {
5752
5886
  outDir: outDirOverride,
5753
5887
  generateFixtures,
5754
- vueTestUtilsOutDir,
5888
+ vueTestUtilsOutDir: vueTestUtilsOutDirOverride,
5755
5889
  customPomAttachments = [],
5756
5890
  projectRoot,
5757
5891
  customPomDir,
@@ -5769,10 +5903,13 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5769
5903
  componentDirs,
5770
5904
  layoutDirs,
5771
5905
  routeMetaByComponent: routeMetaByComponentOverride,
5772
- elementMetadata = /* @__PURE__ */ new Map()
5906
+ elementMetadata = /* @__PURE__ */ new Map(),
5907
+ renderCache
5773
5908
  } = options;
5774
5909
  const emitLanguages = emitLanguagesOverride?.length ? emitLanguagesOverride : ["ts"];
5775
- const outDir = outDirOverride ?? "./pom";
5910
+ const root = projectRoot ?? process.cwd();
5911
+ const outDir = path.resolve(root, outDirOverride ?? "./pom");
5912
+ const vueTestUtilsOutDir = vueTestUtilsOutDirOverride ? path.resolve(root, vueTestUtilsOutDirOverride) : void 0;
5776
5913
  if (vueTestUtilsOutDir && path.resolve(vueTestUtilsOutDir) === path.resolve(outDir)) {
5777
5914
  throw new Error("[vue-pom-generator] generation.vueTestUtils.outDir must differ from generation.outDir.");
5778
5915
  }
@@ -5782,14 +5919,10 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5782
5919
  layoutDirs
5783
5920
  }) : void 0);
5784
5921
  const emittableComponentHierarchyMap = componentHierarchyMap;
5785
- const generatedFilePaths = [];
5786
- const writeGeneratedFile = (file) => {
5787
- const resolvedFilePath = path.resolve(file.filePath);
5788
- createFile(resolvedFilePath, file.content);
5789
- generatedFilePaths.push(resolvedFilePath);
5790
- };
5922
+ const generatedFiles = [];
5791
5923
  if (emitLanguages.includes("ts")) {
5792
5924
  const files = typescriptOutputStructure === "split" ? await generateSplitTypeScriptFiles(emittableComponentHierarchyMap, vueFilesPathMap, basePageClassPath, outDir, {
5925
+ renderCache,
5793
5926
  customPomAttachments,
5794
5927
  projectRoot,
5795
5928
  customPomDir,
@@ -5800,6 +5933,7 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5800
5933
  routeMetaByComponent,
5801
5934
  vueRouterFluentChaining
5802
5935
  }) : await generateAggregatedFiles(emittableComponentHierarchyMap, vueFilesPathMap, basePageClassPath, outDir, {
5936
+ renderCache,
5803
5937
  customPomAttachments,
5804
5938
  projectRoot,
5805
5939
  customPomDir,
@@ -5810,10 +5944,9 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5810
5944
  routeMetaByComponent,
5811
5945
  vueRouterFluentChaining
5812
5946
  });
5813
- for (const file of files) {
5814
- writeGeneratedFile(file);
5815
- }
5947
+ generatedFiles.push(...files);
5816
5948
  const fixtureRegistryFiles = maybeGenerateFixtureRegistry(emittableComponentHierarchyMap, {
5949
+ renderCache,
5817
5950
  generateFixtures,
5818
5951
  pomOutDir: outDir,
5819
5952
  projectRoot,
@@ -5821,33 +5954,26 @@ async function generateFiles(componentHierarchyMap, vueFilesPathMap, basePageCla
5821
5954
  elementMetadata,
5822
5955
  testIdAttribute
5823
5956
  });
5824
- for (const fixtureRegistryFile of fixtureRegistryFiles) {
5825
- writeGeneratedFile(fixtureRegistryFile);
5826
- }
5957
+ generatedFiles.push(...fixtureRegistryFiles);
5827
5958
  }
5828
5959
  if (emitLanguages.includes("csharp")) {
5829
5960
  const csFiles = generateAggregatedCSharpFiles(emittableComponentHierarchyMap, outDir, {
5830
5961
  testIdAttribute,
5831
5962
  csharp
5832
5963
  });
5833
- for (const file of csFiles) {
5834
- writeGeneratedFile(file);
5835
- }
5964
+ generatedFiles.push(...csFiles);
5836
5965
  }
5837
5966
  if (vueTestUtilsOutDir) {
5838
5967
  const vueTestUtilsFiles = generateVueTestUtilsFiles(
5839
5968
  emittableComponentHierarchyMap,
5840
5969
  vueTestUtilsOutDir,
5841
- { testIdAttribute }
5970
+ { testIdAttribute, renderCache }
5842
5971
  );
5843
- for (const file of vueTestUtilsFiles) {
5844
- writeGeneratedFile(file);
5845
- }
5846
- }
5847
- const gitattributesFiles = buildGeneratedGitAttributesFiles(generatedFilePaths);
5848
- for (const file of gitattributesFiles) {
5849
- createFile(file.filePath, file.content);
5972
+ generatedFiles.push(...vueTestUtilsFiles);
5850
5973
  }
5974
+ const gitattributesFiles = buildGeneratedGitAttributesFiles(generatedFiles.map((file) => file.filePath));
5975
+ writeGeneratedOutputs(outDir, generatedFiles, gitattributesFiles, path.resolve(root));
5976
+ renderCache?.retain(new Set(generatedFiles.map((file) => file.filePath)));
5851
5977
  }
5852
5978
  const VUE_TEST_UTILS_OMITTED_PARAMETERS = /* @__PURE__ */ new Set(["annotationText", "timeOut", "timeout", "wait"]);
5853
5979
  function getVueTestUtilsParameters(parameters, patterns, options = {}) {
@@ -5975,7 +6101,7 @@ function getVueTestUtilsComponentMembers(componentInstances, projectedComponentI
5975
6101
  }));
5976
6102
  return members;
5977
6103
  }
5978
- function generateVueTestUtilsContent(componentName, dependencies, componentHierarchyMap, outputDir, runtimePath, generatedFilePathByComponent, testIdAttribute) {
6104
+ function generateVueTestUtilsContent(componentName, dependencies, componentHierarchyMap, outputDir, runtimePath, generatedFilePathByComponent, testIdAttribute, renderCache) {
5979
6105
  const prepared = prepareViewObjectModelClass(componentName, dependencies, componentHierarchyMap, {
5980
6106
  testIdAttribute
5981
6107
  });
@@ -5995,33 +6121,29 @@ function generateVueTestUtilsContent(componentName, dependencies, componentHiera
5995
6121
  ...getUniquePrimaryPomSpecs(dependencies).flatMap(({ pom }) => getVueTestUtilsPrimaryMembers(pom)),
5996
6122
  ...(dependencies.pomExtraMethods ?? []).flatMap(getVueTestUtilsExtraMembers)
5997
6123
  ];
5998
- return renderSourceFile(`${componentName}.vtu.g.ts`, (sourceFile) => {
5999
- addNamedImport(sourceFile, {
6124
+ return renderStructuredSourceFile(path.join(outputDir, `${componentName}.vtu.g.ts`), {
6125
+ statements: [{
6126
+ kind: StructureKind.ImportDeclaration,
6000
6127
  moduleSpecifier: runtimeImport,
6001
6128
  namedImports: ["VueTestUtilsPom"]
6002
- });
6003
- addNamedImport(sourceFile, {
6129
+ }, {
6130
+ kind: StructureKind.ImportDeclaration,
6004
6131
  moduleSpecifier: runtimeImport,
6005
6132
  namedImports: ["VueTestUtilsPomRoot"],
6006
6133
  isTypeOnly: true
6007
- });
6008
- for (const componentImport of componentImports) {
6009
- addNamedImport(sourceFile, {
6010
- moduleSpecifier: componentImport.moduleSpecifier,
6011
- namedImports: [componentImport.className]
6012
- });
6013
- }
6014
- const declaration = sourceFile.addClass({
6134
+ }, ...componentImports.map((componentImport) => ({
6135
+ kind: StructureKind.ImportDeclaration,
6136
+ moduleSpecifier: componentImport.moduleSpecifier,
6137
+ namedImports: [componentImport.className]
6138
+ })), createClassDeclaration({
6015
6139
  name: prepared.className,
6016
6140
  isExported: true,
6017
6141
  extends: "VueTestUtilsPom",
6018
6142
  docs: [`Vue Test Utils object for ${componentName} (source: ${sourceRel}).`]
6019
- });
6020
- for (const member of members) {
6021
- addClassMember(declaration, member);
6022
- }
6143
+ }, members)]
6023
6144
  }, {
6024
- prefixText: buildFilePrefix({ eslintDisableSortImports: true })
6145
+ prefixText: buildFilePrefix({ eslintDisableSortImports: true }),
6146
+ cache: renderCache
6025
6147
  });
6026
6148
  }
6027
6149
  function generateVueTestUtilsFiles(componentHierarchyMap, outDir, options = {}) {
@@ -6043,7 +6165,8 @@ function generateVueTestUtilsFiles(componentHierarchyMap, outDir, options = {})
6043
6165
  path.dirname(filePath),
6044
6166
  runtimePath,
6045
6167
  generatedFilePathByComponent,
6046
- testIdAttribute
6168
+ testIdAttribute,
6169
+ options.renderCache
6047
6170
  )
6048
6171
  };
6049
6172
  });
@@ -6055,12 +6178,13 @@ function generateVueTestUtilsFiles(componentHierarchyMap, outDir, options = {})
6055
6178
  if (!runtimeFile) {
6056
6179
  throw new Error("[vue-pom-generator] Failed to generate the Vue Test Utils runtime.");
6057
6180
  }
6058
- const indexContent = renderSourceFile("index.ts", (sourceFile) => {
6059
- addExportAll(sourceFile, stripExtension(toPosixRelativePath(base, runtimePath)));
6060
- for (const [, filePath] of generatedFilePathByComponent) {
6061
- addExportAll(sourceFile, `./${stripExtension(path.basename(filePath))}`);
6062
- }
6181
+ const indexContent = renderStructuredSourceFile(path.join(base, "index.ts"), {
6182
+ statements: [
6183
+ stripExtension(toPosixRelativePath(base, runtimePath)),
6184
+ ...Array.from(generatedFilePathByComponent.values(), (filePath) => `./${stripExtension(path.basename(filePath))}`)
6185
+ ].map((moduleSpecifier) => ({ kind: StructureKind.ExportDeclaration, moduleSpecifier }))
6063
6186
  }, {
6187
+ cache: options.renderCache,
6064
6188
  prefixText: buildFilePrefix({
6065
6189
  eslintDisableSortImports: true,
6066
6190
  commentLines: [
@@ -6114,6 +6238,7 @@ async function generateSplitTypeScriptFiles(componentHierarchyMap, vueFilesPathM
6114
6238
  continue;
6115
6239
  }
6116
6240
  const content = generateViewObjectModelContent(name, deps, componentHierarchyMap, vueFilesPathMap, runtimeBasePagePath, {
6241
+ renderCache: options.renderCache,
6117
6242
  outputDir: path.dirname(filePath),
6118
6243
  customPomAttachments: options.customPomAttachments ?? [],
6119
6244
  projectRoot,
@@ -6141,6 +6266,8 @@ async function generateSplitTypeScriptFiles(componentHierarchyMap, vueFilesPathM
6141
6266
  const childImports = getChildImportSpecifiers(outputDir, composed?.childClassNames ?? [], generatedTsFilePathByComponent);
6142
6267
  const members = composed?.members ?? getDefaultStubMembers();
6143
6268
  const content = renderSplitStubPomContent({
6269
+ filePath,
6270
+ renderCache: options.renderCache,
6144
6271
  className: targetClassName,
6145
6272
  basePageImportSpecifier,
6146
6273
  childImports,
@@ -6150,14 +6277,13 @@ async function generateSplitTypeScriptFiles(componentHierarchyMap, vueFilesPathM
6150
6277
  }
6151
6278
  const runtimeAssetSpecs = getRuntimeGeneratedAssetSpecs(base, basePageClassPath);
6152
6279
  const runtimeFiles = buildRuntimeGeneratedFilesFromSpecs(runtimeAssetSpecs);
6153
- const indexContent = renderSourceFile("index.ts", (sourceFile) => {
6154
- for (const spec of runtimeAssetSpecs) {
6155
- addExportAll(sourceFile, stripExtension(toPosixRelativePath(base, spec.outputPath)));
6156
- }
6157
- for (const [, filePath] of Array.from(generatedTsFilePathByComponent.entries()).sort((a, b) => a[0].localeCompare(b[0]))) {
6158
- addExportAll(sourceFile, `./${stripExtension(path.basename(filePath))}`);
6159
- }
6280
+ const indexContent = renderStructuredSourceFile(path.join(base, "index.ts"), {
6281
+ statements: [
6282
+ ...runtimeAssetSpecs.map((spec) => stripExtension(toPosixRelativePath(base, spec.outputPath))),
6283
+ ...Array.from(generatedTsFilePathByComponent.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([, filePath]) => `./${stripExtension(path.basename(filePath))}`)
6284
+ ].map((moduleSpecifier) => ({ kind: StructureKind.ExportDeclaration, moduleSpecifier }))
6160
6285
  }, {
6286
+ cache: options.renderCache,
6161
6287
  prefixText: buildFilePrefix({
6162
6288
  eslintDisableSortImports: true,
6163
6289
  commentLines: [
@@ -6833,7 +6959,8 @@ function maybeGenerateFixtureRegistry(componentHierarchyMap, options) {
6833
6959
  const manifestContent = generatePomManifestModule(
6834
6960
  componentHierarchyMap,
6835
6961
  options.elementMetadata,
6836
- manifestFileName
6962
+ path.resolve(fixtureOutDirAbs, manifestFileName),
6963
+ options.renderCache
6837
6964
  );
6838
6965
  const [diagnosticsRuntimeFile] = buildRuntimeGeneratedFilesFromSpecs([{
6839
6966
  absolutePath: resolvePluginAsset("../class-generation/diagnostics.ts"),
@@ -7181,40 +7308,33 @@ function generateViewObjectModelContent(componentName, dependencies, componentHi
7181
7308
  generatedImports.sort((a, b) => a.className.localeCompare(b.className));
7182
7309
  const prefixText = `${buildFilePrefix({ eslintDisableSortImports: true })}${doc}
7183
7310
  `;
7184
- return renderSourceFile(`${prepared.className}.ts`, (sourceFile) => {
7185
- addNamedImport(sourceFile, {
7311
+ return renderStructuredSourceFile(path.join(outputDir, `${componentName}.g.ts`), {
7312
+ statements: [{
7313
+ kind: StructureKind.ImportDeclaration,
7186
7314
  moduleSpecifier: "@playwright/test",
7187
7315
  isTypeOnly: true,
7188
7316
  namedImports: [
7189
7317
  { name: "Locator", alias: "PwLocator" },
7190
7318
  { name: "Page", alias: "PwPage" }
7191
7319
  ]
7192
- });
7193
- addNamedImport(sourceFile, {
7320
+ }, {
7321
+ kind: StructureKind.ImportDeclaration,
7194
7322
  moduleSpecifier: basePageImportSpecifier,
7195
7323
  namedImports: ["BasePage", "Fluent"]
7196
- });
7197
- for (const customImport of customImports) {
7198
- addNamedImport(sourceFile, {
7199
- moduleSpecifier: customImport.moduleSpecifier,
7200
- namedImports: [{ name: customImport.name, alias: customImport.alias }]
7201
- });
7202
- }
7203
- for (const generatedImport of generatedImports) {
7204
- addNamedImport(sourceFile, {
7205
- moduleSpecifier: generatedImport.moduleSpecifier,
7206
- namedImports: [generatedImport.className]
7207
- });
7208
- }
7209
- const classDeclaration = sourceFile.addClass({
7324
+ }, ...customImports.map((customImport) => ({
7325
+ kind: StructureKind.ImportDeclaration,
7326
+ moduleSpecifier: customImport.moduleSpecifier,
7327
+ namedImports: [{ name: customImport.name, alias: customImport.alias }]
7328
+ })), ...generatedImports.map((generatedImport) => ({
7329
+ kind: StructureKind.ImportDeclaration,
7330
+ moduleSpecifier: generatedImport.moduleSpecifier,
7331
+ namedImports: [generatedImport.className]
7332
+ })), createClassDeclaration({
7210
7333
  name: prepared.className,
7211
7334
  isExported: true,
7212
7335
  extends: "BasePage"
7213
- });
7214
- for (const member of prepared.members) {
7215
- addClassMember(classDeclaration, member);
7216
- }
7217
- }, { prefixText });
7336
+ }, prepared.members)]
7337
+ }, { prefixText, cache: options.renderCache });
7218
7338
  }
7219
7339
  function getViewPassthroughMethods(viewName, viewDependencies, componentInstances, componentHierarchyMap, blockedMethodNames = /* @__PURE__ */ new Set()) {
7220
7340
  const existingOnView = viewDependencies.generatedMethods ?? /* @__PURE__ */ new Map();
@@ -7435,35 +7555,32 @@ function renderSplitStubPomContent(options) {
7435
7555
  "Changes should be made in the generator/template, not in the generated output."
7436
7556
  ]
7437
7557
  });
7438
- return renderSourceFile(`${options.className}.ts`, (sourceFile) => {
7439
- addNamedImport(sourceFile, {
7558
+ return renderStructuredSourceFile(options.filePath, {
7559
+ // Stub ctors take Playwright's full `Page` (aliased `PwPage`), matching non-stub generated
7560
+ // POMs — stubs are constructed with `new Stub(this.page)` where `this.page` is `Page`.
7561
+ statements: [{
7562
+ kind: StructureKind.ImportDeclaration,
7440
7563
  moduleSpecifier: "@playwright/test",
7441
7564
  isTypeOnly: true,
7442
7565
  namedImports: [{ name: "Page", alias: "PwPage" }]
7443
- });
7444
- addNamedImport(sourceFile, {
7566
+ }, {
7567
+ kind: StructureKind.ImportDeclaration,
7445
7568
  moduleSpecifier: options.basePageImportSpecifier,
7446
7569
  namedImports: ["BasePage"]
7447
- });
7448
- for (const childImport of options.childImports) {
7449
- addNamedImport(sourceFile, {
7450
- moduleSpecifier: childImport.importPath,
7451
- namedImports: [childImport.className]
7452
- });
7453
- }
7454
- sourceFile.addStatements(buildCommentBlock([
7455
- "Stub POM generated because it is referenced as a navigation target but",
7456
- "did not have any generated test ids in this build."
7457
- ]).trimEnd());
7458
- const classDeclaration = sourceFile.addClass({
7570
+ }, ...options.childImports.map((childImport) => ({
7571
+ kind: StructureKind.ImportDeclaration,
7572
+ moduleSpecifier: childImport.importPath,
7573
+ namedImports: [childImport.className]
7574
+ })), createClassDeclaration({
7459
7575
  name: options.className,
7460
7576
  isExported: true,
7461
- extends: "BasePage"
7462
- });
7463
- for (const member of options.members) {
7464
- addClassMember(classDeclaration, member);
7465
- }
7466
- }, { prefixText });
7577
+ extends: "BasePage",
7578
+ leadingTrivia: buildCommentBlock([
7579
+ "Stub POM generated because it is referenced as a navigation target but",
7580
+ "did not have any generated test ids in this build."
7581
+ ])
7582
+ }, options.members)]
7583
+ }, { prefixText, cache: options.renderCache });
7467
7584
  }
7468
7585
  function getChildImportSpecifiers(outputDir, childClassNames, generatedTsFilePathByComponent) {
7469
7586
  return childClassNames.map((childClassName) => {
@@ -7477,37 +7594,6 @@ function getChildImportSpecifiers(outputDir, childClassNames, generatedTsFilePat
7477
7594
  };
7478
7595
  }).filter((entry) => !!entry).sort((a, b) => a.className.localeCompare(b.className));
7479
7596
  }
7480
- function isConstructorMember(member) {
7481
- return member.kind === StructureKind.Constructor;
7482
- }
7483
- function isGetterMember(member) {
7484
- return member.kind === StructureKind.GetAccessor;
7485
- }
7486
- function isMethodMember(member) {
7487
- return member.kind === StructureKind.Method;
7488
- }
7489
- function isPropertyMember(member) {
7490
- return member.kind === StructureKind.Property;
7491
- }
7492
- function addClassMember(classDeclaration, member) {
7493
- if (isConstructorMember(member)) {
7494
- classDeclaration.addConstructor(member);
7495
- return;
7496
- }
7497
- if (isGetterMember(member)) {
7498
- classDeclaration.addGetAccessor(member);
7499
- return;
7500
- }
7501
- if (isMethodMember(member)) {
7502
- classDeclaration.addMethod(member);
7503
- return;
7504
- }
7505
- if (isPropertyMember(member)) {
7506
- classDeclaration.addProperty(member);
7507
- return;
7508
- }
7509
- throw new Error(`Unsupported class member structure: ${String(member)}`);
7510
- }
7511
7597
  function getRuntimeGeneratedAssetSpecs(baseDir, basePageClassPath) {
7512
7598
  const runtimeDirAbs = path.join(baseDir, "_pom-runtime");
7513
7599
  const runtimeClassGenAbs = path.join(runtimeDirAbs, "class-generation");
@@ -7785,37 +7871,30 @@ async function generateAggregatedFiles(componentHierarchyMap, vueFilesPathMap, b
7785
7871
  "Changes should be made in the generator/template, not in the generated output."
7786
7872
  ]
7787
7873
  });
7788
- return renderSourceFile("page-object-models.g.ts", (sourceFile) => {
7789
- for (const line of imports) {
7790
- sourceFile.addStatements(line);
7791
- }
7792
- for (const entry of [...classes, ...stubs]) {
7793
- if (entry.isStub) {
7794
- sourceFile.addStatements(buildCommentBlock([
7795
- "Stub POM generated because it is referenced as a navigation target but",
7796
- "did not have any generated test ids in this build."
7797
- ]).trimEnd());
7798
- } else {
7799
- sourceFile.addStatements(entry.doc);
7800
- }
7801
- const classDeclaration = sourceFile.addClass({
7874
+ return renderStructuredSourceFile(path.join(outputDir, "page-object-models.g.ts"), {
7875
+ statements: [
7876
+ ...imports,
7877
+ ...[...classes, ...stubs].map((entry) => createClassDeclaration({
7802
7878
  name: entry.className,
7803
7879
  isExported: true,
7804
- extends: "BasePage"
7805
- });
7806
- for (const member of entry.members) {
7807
- addClassMember(classDeclaration, member);
7808
- }
7809
- }
7810
- }, { prefixText });
7880
+ extends: "BasePage",
7881
+ leadingTrivia: entry.isStub ? buildCommentBlock([
7882
+ "Stub POM generated because it is referenced as a navigation target but",
7883
+ "did not have any generated test ids in this build."
7884
+ ]) : `${entry.doc}
7885
+ `
7886
+ }, entry.members))
7887
+ ]
7888
+ }, { prefixText, cache: options.renderCache });
7811
7889
  };
7812
7890
  const base = ensureDir(outDir);
7813
7891
  const outputFile = path.join(base, "page-object-models.g.ts");
7814
7892
  const content = makeAggregatedContent(path.dirname(outputFile), [...views, ...components]);
7815
7893
  const indexFile = path.join(base, "index.ts");
7816
- const indexContent = renderSourceFile("index.ts", (sourceFile) => {
7817
- addExportAll(sourceFile, "./page-object-models.g");
7894
+ const indexContent = renderStructuredSourceFile(indexFile, {
7895
+ statements: [{ kind: StructureKind.ExportDeclaration, moduleSpecifier: "./page-object-models.g" }]
7818
7896
  }, {
7897
+ cache: options.renderCache,
7819
7898
  prefixText: buildFilePrefix({
7820
7899
  eslintDisableSortImports: true,
7821
7900
  commentLines: [
@@ -7834,16 +7913,6 @@ async function generateAggregatedFiles(componentHierarchyMap, vueFilesPathMap, b
7834
7913
  ...runtimeFiles
7835
7914
  ];
7836
7915
  }
7837
- function createFile(filePath, content) {
7838
- const dir = path.dirname(filePath);
7839
- if (!fs.existsSync(dir)) {
7840
- fs.mkdirSync(dir, { recursive: true });
7841
- }
7842
- if (fs.existsSync(filePath)) {
7843
- fs.unlinkSync(filePath);
7844
- }
7845
- fs.writeFileSync(filePath, content);
7846
- }
7847
7916
  function lowerFirst(value) {
7848
7917
  if (!value)
7849
7918
  return value;
@@ -8007,108 +8076,331 @@ function getConstructor(componentInstances, attachmentsForThisView = [], widgetI
8007
8076
  }
8008
8077
  });
8009
8078
  }
8010
- const TESTID_CLICK_EVENT_NAME = "__testid_event__";
8011
- const indexedVueSfcPathsByRoots = /* @__PURE__ */ new Map();
8012
- const resolvedSfcPathByLookup = /* @__PURE__ */ new Map();
8013
- function isAsciiUppercaseLetterCode(code) {
8014
- return code >= 65 && code <= 90;
8015
- }
8016
- function isAsciiLetterCode(code) {
8017
- return code >= 65 && code <= 90 || code >= 97 && code <= 122;
8018
- }
8019
- function isAsciiDigitCode(code) {
8020
- return code >= 48 && code <= 57;
8021
- }
8022
- function toKebabCaseTag(tag) {
8023
- let result = "";
8024
- let previousWasSeparator = false;
8025
- for (let i = 0; i < tag.length; i += 1) {
8026
- const ch = tag[i];
8027
- const code = ch.charCodeAt(0);
8028
- if (ch === "_" || ch === "-" || ch === "." || ch === " " || ch === " " || ch === "\n" || ch === "\r") {
8029
- if (result && !previousWasSeparator) {
8030
- result += "-";
8031
- }
8032
- previousWasSeparator = true;
8033
- continue;
8034
- }
8035
- const previous = i > 0 ? tag[i - 1] : "";
8036
- const previousCode = previous ? previous.charCodeAt(0) : 0;
8037
- const shouldInsertSeparator = i > 0 && isAsciiUppercaseLetterCode(code) && (isAsciiLetterCode(previousCode) || isAsciiDigitCode(previousCode)) && !previousWasSeparator;
8038
- if (shouldInsertSeparator) {
8039
- result += "-";
8079
+ function summarizeHierarchyMap(componentHierarchyMap) {
8080
+ let interactiveComponentCount = 0;
8081
+ let dataTestIdCount = 0;
8082
+ for (const dependencies of componentHierarchyMap.values()) {
8083
+ const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
8084
+ if (selectorCount > 0) {
8085
+ interactiveComponentCount += 1;
8086
+ dataTestIdCount += selectorCount;
8040
8087
  }
8041
- result += ch.toLowerCase();
8042
- previousWasSeparator = false;
8043
8088
  }
8044
- return result;
8089
+ return {
8090
+ entryCount: componentHierarchyMap.size,
8091
+ interactiveComponentCount,
8092
+ dataTestIdCount
8093
+ };
8045
8094
  }
8046
- function normalizeWrapperSearchRoots(wrapperSearchRoots) {
8047
- const normalized = /* @__PURE__ */ new Set();
8048
- for (const root of wrapperSearchRoots) {
8049
- const resolved = path.resolve(root);
8050
- try {
8051
- if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
8052
- continue;
8053
- }
8054
- normalized.add(path.normalize(fs.realpathSync(resolved)));
8055
- } catch {
8056
- continue;
8057
- }
8095
+ function isLessRich(candidate, previous) {
8096
+ if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
8097
+ return candidate.dataTestIdCount < previous.dataTestIdCount;
8058
8098
  }
8059
- return [...normalized];
8060
- }
8061
- function buildSearchRootsKey(searchRoots) {
8062
- return searchRoots.join("\n");
8063
- }
8064
- function buildVueSfcPathIndex(searchRoots) {
8065
- const indexKey = buildSearchRootsKey(searchRoots);
8066
- const existingIndex = indexedVueSfcPathsByRoots.get(indexKey);
8067
- if (existingIndex) {
8068
- return existingIndex;
8099
+ if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
8100
+ return candidate.interactiveComponentCount < previous.interactiveComponentCount;
8069
8101
  }
8070
- const index = /* @__PURE__ */ new Map();
8071
- const ignoredDirNames = /* @__PURE__ */ new Set([
8072
- ".git",
8073
- ".idea",
8074
- ".next",
8075
- ".nuxt",
8076
- ".output",
8077
- ".turbo",
8078
- ".yarn",
8079
- "coverage",
8080
- "dist",
8081
- "build",
8082
- "node_modules",
8083
- "out",
8084
- "tmp"
8085
- ]);
8086
- const stack = [...searchRoots];
8087
- const seenDirs = /* @__PURE__ */ new Set();
8088
- while (stack.length > 0) {
8089
- const dirPath = stack.pop();
8090
- const normalizedDir = path.normalize(dirPath);
8091
- if (seenDirs.has(normalizedDir)) {
8092
- continue;
8093
- }
8094
- seenDirs.add(normalizedDir);
8095
- let entries = [];
8096
- try {
8097
- entries = fs.readdirSync(dirPath, { withFileTypes: true });
8098
- } catch {
8099
- continue;
8100
- }
8101
- for (const entry of entries) {
8102
- const fullPath = path.join(dirPath, entry.name);
8103
- if (entry.isDirectory()) {
8104
- if (ignoredDirNames.has(entry.name) || entry.name.startsWith(".")) {
8105
- continue;
8106
- }
8107
- stack.push(fullPath);
8108
- continue;
8109
- }
8110
- if (!entry.isFile() || !entry.name.endsWith(".vue")) {
8111
- continue;
8102
+ return candidate.entryCount < previous.entryCount;
8103
+ }
8104
+ function createBuildProcessorPlugin(options) {
8105
+ const {
8106
+ componentHierarchyMap,
8107
+ elementMetadata,
8108
+ vueFilesPathMap,
8109
+ getPageDirs,
8110
+ getComponentDirs,
8111
+ getLayoutDirs,
8112
+ getViewsDir,
8113
+ getSourceDirs,
8114
+ basePageClassPath,
8115
+ normalizedBasePagePath,
8116
+ generation,
8117
+ projectRootRef,
8118
+ collectSource,
8119
+ generationOnly,
8120
+ getResolvedRouterEntry,
8121
+ loggerRef
8122
+ } = options;
8123
+ const {
8124
+ outDir,
8125
+ emitLanguages,
8126
+ typescriptOutputStructure,
8127
+ csharp,
8128
+ generateFixtures,
8129
+ vueTestUtilsOutDir,
8130
+ customPomAttachments,
8131
+ customPomDir,
8132
+ requireCustomPomDir,
8133
+ customPomImportAliases,
8134
+ customPomImportNameCollisionBehavior,
8135
+ testIdAttribute,
8136
+ routerAwarePoms,
8137
+ routerType,
8138
+ routerModuleShims
8139
+ } = generation;
8140
+ let lastGeneratedMetrics = {
8141
+ entryCount: 0,
8142
+ interactiveComponentCount: 0,
8143
+ dataTestIdCount: 0
8144
+ };
8145
+ const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
8146
+ const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
8147
+ const supplementHierarchyFromFilesystem = async () => {
8148
+ const walkFilesRecursive = (rootDir) => {
8149
+ const out = [];
8150
+ const stack = [rootDir];
8151
+ while (stack.length) {
8152
+ const dir = stack.pop();
8153
+ if (!dir) continue;
8154
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
8155
+ for (const ent of entries) {
8156
+ if (ent.isDirectory()) {
8157
+ if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
8158
+ continue;
8159
+ stack.push(path.join(dir, ent.name));
8160
+ continue;
8161
+ }
8162
+ if (ent.isFile() && ent.name.endsWith(".vue")) {
8163
+ out.push(path.join(dir, ent.name));
8164
+ }
8165
+ }
8166
+ }
8167
+ return out;
8168
+ };
8169
+ let supplemented = 0;
8170
+ let sourceDirectories = 0;
8171
+ for (const dir of getSourceDirs()) {
8172
+ const absDir = path.resolve(projectRootRef.current, dir);
8173
+ if (!fs.existsSync(absDir))
8174
+ continue;
8175
+ sourceDirectories++;
8176
+ for (const filePath of walkFilesRecursive(absDir)) {
8177
+ const absolutePath = path.resolve(filePath);
8178
+ const componentName = resolveComponentNameFromPath({
8179
+ filename: absolutePath,
8180
+ projectRoot: projectRootRef.current,
8181
+ viewsDirAbs: getViewsDirAbs(),
8182
+ sourceDirs: getSourceDirs(),
8183
+ extraRoots: [process.cwd()]
8184
+ });
8185
+ if (componentHierarchyMap.has(componentName))
8186
+ continue;
8187
+ await collectSource(fs.readFileSync(absolutePath, "utf8"), absolutePath);
8188
+ supplemented++;
8189
+ }
8190
+ }
8191
+ if (generationOnly && sourceDirectories === 0) {
8192
+ throw new Error("[vue-pom-generator] No configured source directories exist. Check the Vite root and injection directories.");
8193
+ }
8194
+ if (supplemented > 0) {
8195
+ loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
8196
+ }
8197
+ };
8198
+ return {
8199
+ name: "vue-pom-generator-build",
8200
+ // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
8201
+ apply: "build",
8202
+ enforce: "pre",
8203
+ async buildStart() {
8204
+ if (!routerAwarePoms) {
8205
+ setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
8206
+ setResolveToComponentNameFn(() => null);
8207
+ return;
8208
+ }
8209
+ let result;
8210
+ if (routerType === "nuxt") {
8211
+ result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
8212
+ } else {
8213
+ const resolvedRouterEntry = getResolvedRouterEntry();
8214
+ if (!resolvedRouterEntry)
8215
+ throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
8216
+ result = await parseRouterFileFromCwd(resolvedRouterEntry, {
8217
+ moduleShims: routerModuleShims,
8218
+ componentNaming: {
8219
+ projectRoot: projectRootRef.current,
8220
+ viewsDirAbs: getViewsDirAbs(),
8221
+ sourceDirs: getSourceDirs()
8222
+ }
8223
+ });
8224
+ }
8225
+ const { routeNameMap, routePathMap } = result;
8226
+ setRouteNameToComponentNameMap(routeNameMap);
8227
+ setResolveToComponentNameFn((to) => {
8228
+ if (typeof to === "string") {
8229
+ return routePathMap.get(to) ?? null;
8230
+ }
8231
+ const maybe = to;
8232
+ if (typeof maybe.name === "string" && maybe.name.length) {
8233
+ const key = toPascalCase(maybe.name);
8234
+ return routeNameMap.get(key) ?? null;
8235
+ }
8236
+ if (typeof maybe.path === "string" && maybe.path.length) {
8237
+ return routePathMap.get(maybe.path) ?? null;
8238
+ }
8239
+ return null;
8240
+ });
8241
+ if (!fs.existsSync(basePageClassPath)) {
8242
+ this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
8243
+ }
8244
+ this.addWatchFile(basePageClassPath);
8245
+ const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
8246
+ if (!fs.existsSync(pointerPath)) {
8247
+ this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
8248
+ }
8249
+ this.addWatchFile(pointerPath);
8250
+ const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
8251
+ if (!fs.existsSync(calloutPath)) {
8252
+ this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
8253
+ }
8254
+ this.addWatchFile(calloutPath);
8255
+ const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
8256
+ if (fs.existsSync(floatingUiCalloutPath)) {
8257
+ this.addWatchFile(floatingUiCalloutPath);
8258
+ }
8259
+ },
8260
+ async buildEnd(error) {
8261
+ if (error) {
8262
+ return;
8263
+ }
8264
+ await supplementHierarchyFromFilesystem();
8265
+ const metrics = summarizeHierarchyMap(componentHierarchyMap);
8266
+ if (!generationOnly && metrics.dataTestIdCount <= 0) {
8267
+ return;
8268
+ }
8269
+ if (!generationOnly && isLessRich(metrics, lastGeneratedMetrics)) {
8270
+ return;
8271
+ }
8272
+ await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
8273
+ outDir,
8274
+ emitLanguages,
8275
+ typescriptOutputStructure,
8276
+ csharp,
8277
+ generateFixtures,
8278
+ vueTestUtilsOutDir,
8279
+ customPomAttachments,
8280
+ projectRoot: projectRootRef.current,
8281
+ customPomDir,
8282
+ requireCustomPomDir,
8283
+ customPomImportAliases,
8284
+ customPomImportNameCollisionBehavior,
8285
+ testIdAttribute,
8286
+ vueRouterFluentChaining: routerAwarePoms,
8287
+ routerEntry: getResolvedRouterEntry(),
8288
+ routerType,
8289
+ pageDirs: getPageDirs(),
8290
+ componentDirs: getComponentDirs(),
8291
+ layoutDirs: getLayoutDirs(),
8292
+ elementMetadata
8293
+ });
8294
+ lastGeneratedMetrics = metrics;
8295
+ loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
8296
+ },
8297
+ closeBundle() {
8298
+ loggerRef.current.info("build complete");
8299
+ }
8300
+ };
8301
+ }
8302
+ const TESTID_CLICK_EVENT_NAME = "__testid_event__";
8303
+ const indexedVueSfcPathsByRoots = /* @__PURE__ */ new Map();
8304
+ const resolvedSfcPathByLookup = /* @__PURE__ */ new Map();
8305
+ function isAsciiUppercaseLetterCode(code) {
8306
+ return code >= 65 && code <= 90;
8307
+ }
8308
+ function isAsciiLetterCode(code) {
8309
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122;
8310
+ }
8311
+ function isAsciiDigitCode(code) {
8312
+ return code >= 48 && code <= 57;
8313
+ }
8314
+ function toKebabCaseTag(tag) {
8315
+ let result = "";
8316
+ let previousWasSeparator = false;
8317
+ for (let i = 0; i < tag.length; i += 1) {
8318
+ const ch = tag[i];
8319
+ const code = ch.charCodeAt(0);
8320
+ if (ch === "_" || ch === "-" || ch === "." || ch === " " || ch === " " || ch === "\n" || ch === "\r") {
8321
+ if (result && !previousWasSeparator) {
8322
+ result += "-";
8323
+ }
8324
+ previousWasSeparator = true;
8325
+ continue;
8326
+ }
8327
+ const previous = i > 0 ? tag[i - 1] : "";
8328
+ const previousCode = previous ? previous.charCodeAt(0) : 0;
8329
+ const shouldInsertSeparator = i > 0 && isAsciiUppercaseLetterCode(code) && (isAsciiLetterCode(previousCode) || isAsciiDigitCode(previousCode)) && !previousWasSeparator;
8330
+ if (shouldInsertSeparator) {
8331
+ result += "-";
8332
+ }
8333
+ result += ch.toLowerCase();
8334
+ previousWasSeparator = false;
8335
+ }
8336
+ return result;
8337
+ }
8338
+ function normalizeWrapperSearchRoots(wrapperSearchRoots) {
8339
+ const normalized = /* @__PURE__ */ new Set();
8340
+ for (const root of wrapperSearchRoots) {
8341
+ const resolved = path.resolve(root);
8342
+ try {
8343
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
8344
+ continue;
8345
+ }
8346
+ normalized.add(path.normalize(fs.realpathSync(resolved)));
8347
+ } catch {
8348
+ continue;
8349
+ }
8350
+ }
8351
+ return [...normalized];
8352
+ }
8353
+ function buildSearchRootsKey(searchRoots) {
8354
+ return searchRoots.join("\n");
8355
+ }
8356
+ function buildVueSfcPathIndex(searchRoots) {
8357
+ const indexKey = buildSearchRootsKey(searchRoots);
8358
+ const existingIndex = indexedVueSfcPathsByRoots.get(indexKey);
8359
+ if (existingIndex) {
8360
+ return existingIndex;
8361
+ }
8362
+ const index = /* @__PURE__ */ new Map();
8363
+ const ignoredDirNames = /* @__PURE__ */ new Set([
8364
+ ".git",
8365
+ ".idea",
8366
+ ".next",
8367
+ ".nuxt",
8368
+ ".output",
8369
+ ".turbo",
8370
+ ".yarn",
8371
+ "coverage",
8372
+ "dist",
8373
+ "build",
8374
+ "node_modules",
8375
+ "out",
8376
+ "tmp"
8377
+ ]);
8378
+ const stack = [...searchRoots];
8379
+ const seenDirs = /* @__PURE__ */ new Set();
8380
+ while (stack.length > 0) {
8381
+ const dirPath = stack.pop();
8382
+ const normalizedDir = path.normalize(dirPath);
8383
+ if (seenDirs.has(normalizedDir)) {
8384
+ continue;
8385
+ }
8386
+ seenDirs.add(normalizedDir);
8387
+ let entries = [];
8388
+ try {
8389
+ entries = fs.readdirSync(dirPath, { withFileTypes: true });
8390
+ } catch {
8391
+ continue;
8392
+ }
8393
+ for (const entry of entries) {
8394
+ const fullPath = path.join(dirPath, entry.name);
8395
+ if (entry.isDirectory()) {
8396
+ if (ignoredDirNames.has(entry.name) || entry.name.startsWith(".")) {
8397
+ continue;
8398
+ }
8399
+ stack.push(fullPath);
8400
+ continue;
8401
+ }
8402
+ if (!entry.isFile() || !entry.name.endsWith(".vue")) {
8403
+ continue;
8112
8404
  }
8113
8405
  const matches = index.get(entry.name) ?? [];
8114
8406
  matches.push(fullPath);
@@ -10074,9 +10366,7 @@ function extractMetadataAfterTransform(ast, componentName, elementMetadata, sema
10074
10366
  }
10075
10367
  }
10076
10368
  traverseNode(ast);
10077
- if (componentMetadata.size > 0) {
10078
- elementMetadata.set(componentName, componentMetadata);
10079
- }
10369
+ elementMetadata.set(componentName, componentMetadata);
10080
10370
  return componentMetadata;
10081
10371
  }
10082
10372
  function createVuePluginWithTestIds(options) {
@@ -10222,403 +10512,132 @@ function createVuePluginWithTestIds(options) {
10222
10512
  crossFileKeyRegistry,
10223
10513
  optionKeyAttribute
10224
10514
  }
10225
- );
10226
- perFileTransform.set(componentName, transform);
10227
- }
10228
- return transform(node, context);
10229
- }
10230
- ];
10231
- };
10232
- const runtimeNodeTransform = (node, context) => {
10233
- const filename = context.filename;
10234
- if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
10235
- return;
10236
- }
10237
- const transforms = getNodeTransforms(filename);
10238
- const ourTransform = transforms[transforms.length - 1];
10239
- return ourTransform(node, context);
10240
- };
10241
- const templateCompilerOptions = {
10242
- ...userCompilerOptions,
10243
- prefixIdentifiers: true,
10244
- nodeTransforms: [
10245
- ...userNodeTransforms,
10246
- runtimeNodeTransform
10247
- ]
10248
- };
10249
- const metadataCollectorPlugin = {
10250
- name: "vue-pom-generator-metadata-collector",
10251
- enforce: "pre",
10252
- async transform(code, id) {
10253
- const cleanPath = id.includes("?") ? id.substring(0, id.indexOf("?")) : id;
10254
- if (!cleanPath.endsWith(".vue") || !isFileInScope(id)) {
10255
- return null;
10256
- }
10257
- if (id !== cleanPath) {
10258
- return null;
10259
- }
10260
- const componentName = getComponentNameFromPath(cleanPath);
10261
- loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
10262
- const compilerSfc = await import("@vue/compiler-sfc");
10263
- const parse2 = resolveCompilerSfcParse(compilerSfc);
10264
- const compilerDom2 = await import("@vue/compiler-dom");
10265
- const compile = compilerDom2.compile;
10266
- const { descriptor } = parse2(code, { filename: cleanPath });
10267
- if (descriptor.template) {
10268
- const mergedExpressionPlugins = Array.from(
10269
- /* @__PURE__ */ new Set([
10270
- "typescript",
10271
- ...userCompilerOptions.expressionPlugins ?? []
10272
- ])
10273
- );
10274
- compile(descriptor.template.content, {
10275
- ...userCompilerOptions,
10276
- filename: cleanPath,
10277
- expressionPlugins: mergedExpressionPlugins,
10278
- nodeTransforms: getNodeTransforms(cleanPath, componentName)
10279
- });
10280
- loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
10281
- }
10282
- return null;
10283
- }
10284
- };
10285
- const template = {
10286
- ...userTemplate,
10287
- compilerOptions: templateCompilerOptions
10288
- };
10289
- const internalVuePlugin = vue({
10290
- ...vueOptions,
10291
- template
10292
- });
10293
- const nuxtVueBridgePlugin = {
10294
- name: "vue-pom-generator-nuxt-vue-bridge",
10295
- apply: "serve",
10296
- configResolved(config) {
10297
- const viteVuePlugin = config.plugins.find((plugin) => {
10298
- return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
10299
- });
10300
- const api = viteVuePlugin?.api;
10301
- if (!api) {
10302
- throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
10303
- }
10304
- const currentOptions = api.options ?? {};
10305
- const currentTemplate = currentOptions.template ?? {};
10306
- const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
10307
- const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
10308
- if (currentNodeTransforms.includes(runtimeNodeTransform)) {
10309
- return;
10310
- }
10311
- api.options = {
10312
- ...currentOptions,
10313
- template: {
10314
- ...currentTemplate,
10315
- compilerOptions: {
10316
- ...currentCompilerOptions,
10317
- prefixIdentifiers: true,
10318
- nodeTransforms: [
10319
- ...currentNodeTransforms,
10320
- runtimeNodeTransform
10321
- ]
10322
- }
10323
- }
10324
- };
10325
- }
10326
- };
10327
- return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions };
10328
- }
10329
- function summarizeHierarchyMap(componentHierarchyMap) {
10330
- let interactiveComponentCount = 0;
10331
- let dataTestIdCount = 0;
10332
- for (const dependencies of componentHierarchyMap.values()) {
10333
- const selectorCount = dependencies.dataTestIdSet?.size ?? 0;
10334
- if (selectorCount > 0) {
10335
- interactiveComponentCount += 1;
10336
- dataTestIdCount += selectorCount;
10337
- }
10338
- }
10339
- return {
10340
- entryCount: componentHierarchyMap.size,
10341
- interactiveComponentCount,
10342
- dataTestIdCount
10343
- };
10344
- }
10345
- function isLessRich(candidate, previous) {
10346
- if (candidate.dataTestIdCount !== previous.dataTestIdCount) {
10347
- return candidate.dataTestIdCount < previous.dataTestIdCount;
10348
- }
10349
- if (candidate.interactiveComponentCount !== previous.interactiveComponentCount) {
10350
- return candidate.interactiveComponentCount < previous.interactiveComponentCount;
10351
- }
10352
- return candidate.entryCount < previous.entryCount;
10353
- }
10354
- function createBuildProcessorPlugin(options) {
10355
- const {
10356
- componentHierarchyMap,
10357
- elementMetadata,
10358
- crossFileKeyRegistry,
10359
- vueFilesPathMap,
10360
- getPageDirs,
10361
- getComponentDirs,
10362
- getLayoutDirs,
10363
- getViewsDir,
10364
- getSourceDirs,
10365
- basePageClassPath,
10366
- normalizedBasePagePath,
10367
- generation,
10368
- projectRootRef,
10369
- nativeWrappers,
10370
- optionKeyAttribute,
10371
- skipTestIdGenerationInsideComponents,
10372
- getWrapperSearchRoots,
10373
- getResolvedRouterEntry,
10374
- loggerRef
10375
- } = options;
10376
- const {
10377
- outDir,
10378
- emitLanguages,
10379
- typescriptOutputStructure,
10380
- csharp,
10381
- generateFixtures,
10382
- vueTestUtilsOutDir,
10383
- customPomAttachments,
10384
- customPomDir,
10385
- requireCustomPomDir,
10386
- customPomImportAliases,
10387
- customPomImportNameCollisionBehavior,
10388
- testIdAttribute,
10389
- nameCollisionBehavior,
10390
- missingSemanticNameBehavior,
10391
- existingIdBehavior,
10392
- routerAwarePoms,
10393
- routerType,
10394
- routerModuleShims
10395
- } = generation;
10396
- let lastGeneratedMetrics = {
10397
- entryCount: 0,
10398
- interactiveComponentCount: 0,
10399
- dataTestIdCount: 0
10515
+ );
10516
+ perFileTransform.set(componentName, transform);
10517
+ }
10518
+ return transform(node, context);
10519
+ }
10520
+ ];
10400
10521
  };
10401
- const getViewsDirAbs = () => path.isAbsolute(getViewsDir()) ? getViewsDir() : path.resolve(projectRootRef.current, getViewsDir());
10402
- const getPageDirsAbs = () => getPageDirs().map((dir) => path.isAbsolute(dir) ? dir : path.resolve(projectRootRef.current, dir));
10403
- const getScriptInfo = (source, filename) => {
10404
- try {
10405
- const { descriptor } = parse$1(source, { filename });
10406
- if (!descriptor.script && !descriptor.scriptSetup)
10407
- return { bindings: void 0, isScriptSetup: false };
10408
- const scriptBlock = compileScript(descriptor, { id: filename });
10409
- return { bindings: scriptBlock.bindings, isScriptSetup: !!descriptor.scriptSetup };
10410
- } catch {
10411
- return { bindings: void 0, isScriptSetup: false };
10522
+ const runtimeNodeTransform = (node, context) => {
10523
+ const filename = context.filename;
10524
+ if (!filename || !filename.endsWith(".vue") || !isFileInScope(filename)) {
10525
+ return;
10412
10526
  }
10527
+ const transforms = getNodeTransforms(filename);
10528
+ const ourTransform = transforms[transforms.length - 1];
10529
+ return ourTransform(node, context);
10413
10530
  };
10414
- const supplementHierarchyFromFilesystem = () => {
10415
- const walkFilesRecursive = (rootDir) => {
10416
- const out = [];
10417
- const stack = [rootDir];
10418
- while (stack.length) {
10419
- const dir = stack.pop();
10420
- if (!dir) continue;
10421
- let entries = [];
10422
- try {
10423
- entries = fs.readdirSync(dir, { withFileTypes: true });
10424
- } catch {
10425
- continue;
10426
- }
10427
- for (const ent of entries) {
10428
- if (ent.isDirectory()) {
10429
- if (ent.name === "node_modules" || ent.name === ".git" || ent.name === "dist")
10430
- continue;
10431
- stack.push(path.join(dir, ent.name));
10432
- continue;
10433
- }
10434
- if (ent.isFile() && ent.name.endsWith(".vue")) {
10435
- out.push(path.join(dir, ent.name));
10436
- }
10437
- }
10438
- }
10439
- return out;
10440
- };
10441
- let supplemented = 0;
10442
- for (const dir of getSourceDirs()) {
10443
- const absDir = path.resolve(projectRootRef.current, dir);
10444
- if (!fs.existsSync(absDir))
10445
- continue;
10446
- for (const filePath of walkFilesRecursive(absDir)) {
10447
- const absolutePath = path.resolve(filePath);
10448
- const componentName = resolveComponentNameFromPath({
10449
- filename: absolutePath,
10450
- projectRoot: projectRootRef.current,
10451
- viewsDirAbs: getViewsDirAbs(),
10452
- sourceDirs: getSourceDirs(),
10453
- extraRoots: [process.cwd()]
10454
- });
10455
- if (componentHierarchyMap.has(componentName))
10456
- continue;
10457
- let sfc = "";
10458
- try {
10459
- sfc = fs.readFileSync(absolutePath, "utf8");
10460
- } catch {
10461
- continue;
10462
- }
10463
- const { descriptor } = parse$1(sfc, { filename: absolutePath });
10464
- const template = descriptor.template?.content ?? "";
10465
- if (!template.trim()) {
10466
- vueFilesPathMap.set(componentName, absolutePath);
10467
- componentHierarchyMap.set(componentName, {
10468
- filePath: absolutePath,
10469
- childrenComponentSet: /* @__PURE__ */ new Set(),
10470
- usedComponentSet: /* @__PURE__ */ new Set(),
10471
- dataTestIdSet: /* @__PURE__ */ new Set(),
10472
- isView: false,
10473
- methodsContent: ""
10474
- });
10475
- supplemented++;
10476
- continue;
10477
- }
10478
- const { bindings: bindingMetadata, isScriptSetup } = getScriptInfo(sfc, absolutePath);
10479
- vueFilesPathMap.set(componentName, absolutePath);
10480
- try {
10481
- compilerDom.compile(template, {
10482
- filename: absolutePath,
10483
- prefixIdentifiers: true,
10484
- inline: isScriptSetup,
10485
- bindingMetadata,
10486
- // See dev-plugin.ts — same rationale: enable TS in template
10487
- // expressions so `(row: RowType) => ...` handlers parse.
10488
- expressionPlugins: ["typescript"],
10489
- nodeTransforms: [
10490
- createTestIdTransform(
10491
- componentName,
10492
- componentHierarchyMap,
10493
- nativeWrappers,
10494
- skipTestIdGenerationInsideComponents,
10495
- getViewsDirAbs(),
10496
- {
10497
- existingIdBehavior: resolveExistingIdBehavior(existingIdBehavior, componentName),
10498
- testIdAttribute,
10499
- nameCollisionBehavior,
10500
- missingSemanticNameBehavior,
10501
- warn: (message) => loggerRef.current.warn(message),
10502
- vueFilesPathMap,
10503
- wrapperSearchRoots: getWrapperSearchRoots(),
10504
- crossFileKeyRegistry,
10505
- optionKeyAttribute
10506
- }
10507
- )
10508
- ]
10509
- });
10510
- } catch {
10531
+ const templateCompilerOptions = {
10532
+ ...userCompilerOptions,
10533
+ prefixIdentifiers: true,
10534
+ nodeTransforms: [
10535
+ ...userNodeTransforms,
10536
+ runtimeNodeTransform
10537
+ ]
10538
+ };
10539
+ const collectSource = async (code, cleanPath) => {
10540
+ const componentName = getComponentNameFromPath(cleanPath);
10541
+ loggerRef.current.debug(`Collecting metadata for ${cleanPath} (component: ${componentName})`);
10542
+ const compilerSfc = await import("@vue/compiler-sfc");
10543
+ const parse2 = resolveCompilerSfcParse(compilerSfc);
10544
+ const { descriptor, errors } = parse2(code, { filename: cleanPath });
10545
+ if (errors.length) {
10546
+ throw new Error(`[vue-pom-generator] Cannot parse ${cleanPath}: ${errors.map(String).join("\n")}`);
10547
+ }
10548
+ const script = descriptor.script || descriptor.scriptSetup ? compilerSfc.compileScript(descriptor, { ...vueOptions?.script, id: cleanPath }) : void 0;
10549
+ if (descriptor.template) {
10550
+ const mergedExpressionPlugins = Array.from(
10551
+ /* @__PURE__ */ new Set([
10552
+ "typescript",
10553
+ ...userCompilerOptions.expressionPlugins ?? []
10554
+ ])
10555
+ );
10556
+ const compiled = compilerSfc.compileTemplate({
10557
+ ...userTemplate,
10558
+ id: cleanPath,
10559
+ filename: cleanPath,
10560
+ source: descriptor.template.content,
10561
+ ast: descriptor.template.ast,
10562
+ preprocessLang: descriptor.template.lang,
10563
+ compilerOptions: {
10564
+ ...userCompilerOptions,
10565
+ prefixIdentifiers: true,
10566
+ inline: !!descriptor.scriptSetup,
10567
+ bindingMetadata: script?.bindings,
10568
+ expressionPlugins: mergedExpressionPlugins,
10569
+ nodeTransforms: getNodeTransforms(cleanPath, componentName)
10511
10570
  }
10512
- supplemented++;
10571
+ });
10572
+ if (compiled.errors.length) {
10573
+ throw new Error(`[vue-pom-generator] Cannot compile ${cleanPath}: ${compiled.errors.map(String).join("\n")}`);
10513
10574
  }
10514
- }
10515
- if (supplemented > 0) {
10516
- loggerRef.current.info(`supplemented ${supplemented} components from filesystem walk (not in build graph)`);
10575
+ loggerRef.current.debug(`Metadata collected for ${cleanPath}`);
10576
+ } else {
10577
+ vueFilesPathMap.set(componentName, cleanPath);
10578
+ elementMetadata.delete(componentName);
10579
+ componentHierarchyMap.set(componentName, {
10580
+ filePath: cleanPath,
10581
+ childrenComponentSet: /* @__PURE__ */ new Set(),
10582
+ usedComponentSet: /* @__PURE__ */ new Set(),
10583
+ dataTestIdSet: /* @__PURE__ */ new Set(),
10584
+ isView: false,
10585
+ methodsContent: ""
10586
+ });
10517
10587
  }
10518
10588
  };
10519
- return {
10520
- name: "vue-pom-generator-build",
10521
- // This plugin exists to generate code on build output; it is not needed during dev-server HMR.
10522
- apply: "build",
10589
+ const metadataCollectorPlugin = {
10590
+ name: "vue-pom-generator-metadata-collector",
10523
10591
  enforce: "pre",
10524
- async buildStart() {
10525
- if (!routerAwarePoms) {
10526
- setRouteNameToComponentNameMap(/* @__PURE__ */ new Map());
10527
- setResolveToComponentNameFn(() => null);
10528
- return;
10529
- }
10530
- let result;
10531
- if (routerType === "nuxt") {
10532
- result = await introspectNuxtPages(projectRootRef.current, { pageDirs: getPageDirsAbs() });
10533
- } else {
10534
- const resolvedRouterEntry = getResolvedRouterEntry();
10535
- if (!resolvedRouterEntry)
10536
- throw new Error("[vue-pom-generator] router.entry is required when router introspection is enabled.");
10537
- result = await parseRouterFileFromCwd(resolvedRouterEntry, {
10538
- moduleShims: routerModuleShims,
10539
- componentNaming: {
10540
- projectRoot: projectRootRef.current,
10541
- viewsDirAbs: getViewsDirAbs(),
10542
- sourceDirs: getSourceDirs()
10543
- }
10544
- });
10545
- }
10546
- const { routeNameMap, routePathMap } = result;
10547
- setRouteNameToComponentNameMap(routeNameMap);
10548
- setResolveToComponentNameFn((to) => {
10549
- if (typeof to === "string") {
10550
- return routePathMap.get(to) ?? null;
10551
- }
10552
- const maybe = to;
10553
- if (typeof maybe.name === "string" && maybe.name.length) {
10554
- const key = toPascalCase(maybe.name);
10555
- return routeNameMap.get(key) ?? null;
10556
- }
10557
- if (typeof maybe.path === "string" && maybe.path.length) {
10558
- return routePathMap.get(maybe.path) ?? null;
10559
- }
10560
- return null;
10592
+ async transform(code, id) {
10593
+ if (!id.endsWith(".vue") || !isFileInScope(id)) return null;
10594
+ await collectSource(code, id);
10595
+ return null;
10596
+ }
10597
+ };
10598
+ const template = {
10599
+ ...userTemplate,
10600
+ compilerOptions: templateCompilerOptions
10601
+ };
10602
+ const internalVuePlugin = vue({
10603
+ ...vueOptions,
10604
+ template
10605
+ });
10606
+ const nuxtVueBridgePlugin = {
10607
+ name: "vue-pom-generator-nuxt-vue-bridge",
10608
+ apply: "serve",
10609
+ configResolved(config) {
10610
+ const viteVuePlugin = config.plugins.find((plugin) => {
10611
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "vite:vue" && "api" in plugin;
10561
10612
  });
10562
- if (!fs.existsSync(basePageClassPath)) {
10563
- this.error(`Base page runtime file not found at ${basePageClassPath}. Ensure it is included in the build.`);
10564
- }
10565
- this.addWatchFile(basePageClassPath);
10566
- const pointerPath = path.resolve(path.dirname(basePageClassPath), "pointer.ts");
10567
- if (!fs.existsSync(pointerPath)) {
10568
- this.error(`pointer.ts not found at ${pointerPath}. Ensure it is included in the build.`);
10569
- }
10570
- this.addWatchFile(pointerPath);
10571
- const calloutPath = path.resolve(path.dirname(basePageClassPath), "callout.ts");
10572
- if (!fs.existsSync(calloutPath)) {
10573
- this.error(`callout.ts not found at ${calloutPath}. Ensure it is included in the build.`);
10574
- }
10575
- this.addWatchFile(calloutPath);
10576
- const floatingUiCalloutPath = path.resolve(path.dirname(basePageClassPath), "floating-ui-callout.ts");
10577
- if (fs.existsSync(floatingUiCalloutPath)) {
10578
- this.addWatchFile(floatingUiCalloutPath);
10579
- }
10580
- },
10581
- async buildEnd(error) {
10582
- if (error) {
10583
- return;
10584
- }
10585
- supplementHierarchyFromFilesystem();
10586
- const metrics = summarizeHierarchyMap(componentHierarchyMap);
10587
- if (metrics.dataTestIdCount <= 0) {
10588
- return;
10613
+ const api = viteVuePlugin?.api;
10614
+ if (!api) {
10615
+ throw new Error("[vue-pom-generator] Nuxt bridge could not find vite:vue plugin to patch.");
10589
10616
  }
10590
- if (isLessRich(metrics, lastGeneratedMetrics)) {
10617
+ const currentOptions = api.options ?? {};
10618
+ const currentTemplate = currentOptions.template ?? {};
10619
+ const currentCompilerOptions = currentTemplate.compilerOptions ?? {};
10620
+ const currentNodeTransforms = currentCompilerOptions.nodeTransforms ?? [];
10621
+ if (currentNodeTransforms.includes(runtimeNodeTransform)) {
10591
10622
  return;
10592
10623
  }
10593
- await generateFiles(componentHierarchyMap, vueFilesPathMap, normalizedBasePagePath, {
10594
- outDir,
10595
- emitLanguages,
10596
- typescriptOutputStructure,
10597
- csharp,
10598
- generateFixtures,
10599
- vueTestUtilsOutDir,
10600
- customPomAttachments,
10601
- projectRoot: projectRootRef.current,
10602
- customPomDir,
10603
- requireCustomPomDir,
10604
- customPomImportAliases,
10605
- customPomImportNameCollisionBehavior,
10606
- testIdAttribute,
10607
- vueRouterFluentChaining: routerAwarePoms,
10608
- routerEntry: getResolvedRouterEntry(),
10609
- routerType,
10610
- pageDirs: getPageDirs(),
10611
- componentDirs: getComponentDirs(),
10612
- layoutDirs: getLayoutDirs(),
10613
- elementMetadata
10614
- });
10615
- lastGeneratedMetrics = metrics;
10616
- loggerRef.current.info(`generated POMs (${metrics.entryCount} entries, ${metrics.interactiveComponentCount} interactive components, ${metrics.dataTestIdCount} selectors)`);
10617
- },
10618
- closeBundle() {
10619
- loggerRef.current.info("build complete");
10624
+ api.options = {
10625
+ ...currentOptions,
10626
+ template: {
10627
+ ...currentTemplate,
10628
+ compilerOptions: {
10629
+ ...currentCompilerOptions,
10630
+ prefixIdentifiers: true,
10631
+ nodeTransforms: [
10632
+ ...currentNodeTransforms,
10633
+ runtimeNodeTransform
10634
+ ]
10635
+ }
10636
+ }
10637
+ };
10620
10638
  }
10621
10639
  };
10640
+ return { metadataCollectorPlugin, internalVuePlugin, nuxtVueBridgePlugin, templateCompilerOptions, collectSource };
10622
10641
  }
10623
10642
  function createDevProcessorPlugin(options) {
10624
10643
  const {
@@ -10692,6 +10711,7 @@ function createDevProcessorPlugin(options) {
10692
10711
  scheduleVueFileRegen(ctx.file, "hmr");
10693
10712
  },
10694
10713
  async configureServer(server) {
10714
+ const renderCache = new TypeScriptRenderCache();
10695
10715
  const getViewsDirAbs = () => resolveProjectPath(getViewsDir());
10696
10716
  const getPageDirsAbs = () => getPageDirs().map((dir) => resolveProjectPath(dir));
10697
10717
  const routerInitPromise = (async () => {
@@ -10899,6 +10919,7 @@ function createDevProcessorPlugin(options) {
10899
10919
  const generateAggregatedFromSnapshot = async (logLabel) => {
10900
10920
  const t0 = performance.now();
10901
10921
  await generateFiles(snapshotHierarchy, snapshotVuePathMap, normalizedBasePagePath, {
10922
+ renderCache,
10902
10923
  outDir,
10903
10924
  emitLanguages,
10904
10925
  typescriptOutputStructure,
@@ -11196,7 +11217,6 @@ ${code}`,
11196
11217
  function createInternalPlugins(options) {
11197
11218
  const {
11198
11219
  componentHierarchyMap,
11199
- crossFileKeyRegistry,
11200
11220
  elementMetadata,
11201
11221
  vueFilesPathMap,
11202
11222
  nativeWrappers,
@@ -11212,7 +11232,9 @@ function createInternalPlugins(options) {
11212
11232
  projectRootRef,
11213
11233
  basePageClassPath: basePageClassPathOverride,
11214
11234
  loggerRef,
11215
- annotatorRuntime
11235
+ annotatorRuntime,
11236
+ collectSource,
11237
+ generationOnly
11216
11238
  } = options;
11217
11239
  const {
11218
11240
  routerAwarePoms,
@@ -11240,7 +11262,6 @@ function createInternalPlugins(options) {
11240
11262
  const tsProcessor = createBuildProcessorPlugin({
11241
11263
  componentHierarchyMap,
11242
11264
  elementMetadata,
11243
- crossFileKeyRegistry,
11244
11265
  vueFilesPathMap,
11245
11266
  getPageDirs,
11246
11267
  getComponentDirs,
@@ -11251,10 +11272,8 @@ function createInternalPlugins(options) {
11251
11272
  normalizedBasePagePath,
11252
11273
  generation,
11253
11274
  projectRootRef,
11254
- nativeWrappers,
11255
- optionKeyAttribute,
11256
- skipTestIdGenerationInsideComponents,
11257
- getWrapperSearchRoots,
11275
+ collectSource,
11276
+ generationOnly,
11258
11277
  getResolvedRouterEntry: resolveRouterEntry2,
11259
11278
  loggerRef
11260
11279
  });
@@ -11416,16 +11435,19 @@ const sharedGeneratorStateRegistry = /* @__PURE__ */ new Map();
11416
11435
  function toArray(value) {
11417
11436
  return Array.isArray(value) ? value : [];
11418
11437
  }
11438
+ function createGeneratorState() {
11439
+ return {
11440
+ elementMetadata: /* @__PURE__ */ new Map(),
11441
+ semanticNameMap: /* @__PURE__ */ new Map(),
11442
+ componentHierarchyMap: /* @__PURE__ */ new Map(),
11443
+ crossFileKeyRegistry: /* @__PURE__ */ new Map(),
11444
+ vueFilesPathMap: /* @__PURE__ */ new Map()
11445
+ };
11446
+ }
11419
11447
  function getSharedGeneratorState(key) {
11420
11448
  let state = sharedGeneratorStateRegistry.get(key);
11421
11449
  if (!state) {
11422
- state = {
11423
- elementMetadata: /* @__PURE__ */ new Map(),
11424
- semanticNameMap: /* @__PURE__ */ new Map(),
11425
- componentHierarchyMap: /* @__PURE__ */ new Map(),
11426
- crossFileKeyRegistry: /* @__PURE__ */ new Map(),
11427
- vueFilesPathMap: /* @__PURE__ */ new Map()
11428
- };
11450
+ state = createGeneratorState();
11429
11451
  sharedGeneratorStateRegistry.set(key, state);
11430
11452
  }
11431
11453
  return state;
@@ -11486,9 +11508,15 @@ function assertNotVitePluginInstance(options) {
11486
11508
  );
11487
11509
  }
11488
11510
  function createVuePomGeneratorPlugins(options = {}) {
11511
+ return createGeneratorPlugins(options, false);
11512
+ }
11513
+ function createGeneratorPlugins(options, generationOnly, projectRoot = process.cwd()) {
11489
11514
  assertNotVitePluginInstance(options);
11490
11515
  const injection = options.injection ?? {};
11491
- const isNuxt = detectNuxtProject(options, process.cwd());
11516
+ const isNuxt = detectNuxtProject(options, projectRoot);
11517
+ if (generationOnly && isNuxt) {
11518
+ throw new Error("[vue-pom-generator] generateVuePoms does not run Nuxt project preparation. Use the Nuxt Vite integration.");
11519
+ }
11492
11520
  const generationSetting = options.generation;
11493
11521
  const generationOptions = generationSetting === false ? null : generationSetting ?? {};
11494
11522
  const generationEnabled = generationOptions !== null;
@@ -11574,7 +11602,7 @@ function createVuePomGeneratorPlugins(options = {}) {
11574
11602
  ]));
11575
11603
  const getWrapperSearchRoots = () => resolvedInjectionOptionsRef.current.wrapperSearchRoots;
11576
11604
  const sharedStateKey = JSON.stringify({
11577
- cwd: process.cwd(),
11605
+ cwd: projectRoot,
11578
11606
  mode: isNuxt ? "nuxt" : "vue",
11579
11607
  pageDirs: isNuxt ? null : getPageDirs(),
11580
11608
  componentDirs: isNuxt ? null : getComponentDirs(),
@@ -11586,9 +11614,9 @@ function createVuePomGeneratorPlugins(options = {}) {
11586
11614
  routerType: resolvedGenerationOptions.routerType,
11587
11615
  vuePluginOwnership
11588
11616
  });
11589
- const sharedState = getSharedGeneratorState(sharedStateKey);
11617
+ const sharedState = generationOnly ? createGeneratorState() : getSharedGeneratorState(sharedStateKey);
11590
11618
  let templateCompilerOptionsForResolvedPlugin;
11591
- const projectRootRef = { current: process.cwd() };
11619
+ const projectRootRef = { current: projectRoot };
11592
11620
  const loggerRef = {
11593
11621
  current: createLogger({ verbosity })
11594
11622
  };
@@ -11652,7 +11680,7 @@ function createVuePomGeneratorPlugins(options = {}) {
11652
11680
  ...getWrapperSearchRoots()
11653
11681
  ].map((root) => resolveFromProjectRoot(projectRootRef.current, root))));
11654
11682
  const { elementMetadata, semanticNameMap, componentHierarchyMap, crossFileKeyRegistry, vueFilesPathMap } = sharedState;
11655
- const { metadataCollectorPlugin, internalVuePlugin, templateCompilerOptions } = createVuePluginWithTestIds({
11683
+ const { metadataCollectorPlugin, internalVuePlugin, templateCompilerOptions, collectSource } = createVuePluginWithTestIds({
11656
11684
  vueOptions,
11657
11685
  existingIdBehavior: resolvedGenerationOptions.existingIdBehavior,
11658
11686
  nameCollisionBehavior: resolvedGenerationOptions.nameCollisionBehavior,
@@ -11680,7 +11708,6 @@ function createVuePomGeneratorPlugins(options = {}) {
11680
11708
  templateCompilerOptionsForResolvedPlugin = templateCompilerOptions;
11681
11709
  const internalPlugins = createInternalPlugins({
11682
11710
  componentHierarchyMap,
11683
- crossFileKeyRegistry,
11684
11711
  elementMetadata,
11685
11712
  vueFilesPathMap,
11686
11713
  nativeWrappers,
@@ -11693,6 +11720,8 @@ function createVuePomGeneratorPlugins(options = {}) {
11693
11720
  getSourceDirs,
11694
11721
  getWrapperSearchRoots: getWrapperSearchRootsAbs,
11695
11722
  generation: resolvedGenerationOptions,
11723
+ collectSource,
11724
+ generationOnly,
11696
11725
  projectRootRef,
11697
11726
  basePageClassPath: basePageClassPathOverride,
11698
11727
  loggerRef,
@@ -13113,6 +13142,44 @@ function mountAnnotatorClient(options) {
13113
13142
  runtimeWindow[RUNTIME_GUARD] = runtime;
13114
13143
  return runtime;
13115
13144
  }
13145
+ let generating = false;
13146
+ async function generateVuePoms(options = {}, viteOptions = {}) {
13147
+ if (options.generation === false) {
13148
+ throw new Error("[vue-pom-generator] generateVuePoms requires generation to be enabled.");
13149
+ }
13150
+ const entryId = "virtual:vue-pom-generator-entry";
13151
+ const resolvedEntryId = `\0${entryId}`;
13152
+ const entry = {
13153
+ name: "vue-pom-generator-entry",
13154
+ resolveId(id) {
13155
+ return id === entryId ? resolvedEntryId : void 0;
13156
+ },
13157
+ load(id) {
13158
+ return id === resolvedEntryId ? "export {};" : void 0;
13159
+ }
13160
+ };
13161
+ if (generating) {
13162
+ throw new Error("[vue-pom-generator] Await the previous generateVuePoms call before starting another.");
13163
+ }
13164
+ generating = true;
13165
+ try {
13166
+ const { build } = await import("vite");
13167
+ await build({
13168
+ ...viteOptions,
13169
+ configFile: false,
13170
+ publicDir: false,
13171
+ plugins: [entry, ...createGeneratorPlugins(options, true, path.resolve(viteOptions.root ?? ".")), ...viteOptions.plugins ?? []],
13172
+ build: {
13173
+ write: false,
13174
+ emptyOutDir: false,
13175
+ minify: false,
13176
+ rollupOptions: { input: entryId }
13177
+ }
13178
+ });
13179
+ } finally {
13180
+ generating = false;
13181
+ }
13182
+ }
13116
13183
  const nuxtConfigMarker = /* @__PURE__ */ Symbol.for("@immense/vue-pom-generator.nuxt");
13117
13184
  function defineVuePomGeneratorConfig(options) {
13118
13185
  return options;
@@ -13130,6 +13197,7 @@ export {
13130
13197
  createVuePomGeneratorPlugins as default,
13131
13198
  defineNuxtPomGeneratorConfig,
13132
13199
  defineVuePomGeneratorConfig,
13200
+ generateVuePoms,
13133
13201
  mountAnnotatorClient,
13134
13202
  createVuePomGeneratorPlugins as vuePomGenerator
13135
13203
  };