@immense/vue-pom-generator 1.0.94 → 1.0.96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ import * as compilerDom from "@vue/compiler-dom";
7
7
  import { parse as parse$2, NodeTypes as NodeTypes$1 } from "@vue/compiler-dom";
8
8
  import { parse as parse$1, compileScript } from "@vue/compiler-sfc";
9
9
  import { parseExpression, parse } from "@babel/parser";
10
- import { NodeTypes, stringifyExpression, ConstantTypes, createSimpleExpression, ElementTypes } from "@vue/compiler-core";
10
+ import { NodeTypes, stringifyExpression, createSimpleExpression, ConstantTypes, 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, isImportDeclaration, isImportSpecifier, isExportDefaultDeclaration, isExpression, isVariableDeclaration, isFunctionDeclaration, isFunctionExpression, isReturnStatement, isTSAsExpression, isTSTypeAssertion, isTSNonNullExpression, isForInStatement, isIfStatement } from "@babel/types";
13
13
  import { POM_ROUTER_GLOBAL_NAME } from "./router.mjs";
@@ -2901,18 +2901,18 @@ function safeMethodNameFromParts(parts) {
2901
2901
  }
2902
2902
  return name;
2903
2903
  }
2904
- function toPomKeyPattern(templateValue) {
2904
+ function toPomKeyPattern(templateValue, parameterName = "key") {
2905
2905
  const { templateLiteral } = templateValue.parsedTemplate;
2906
2906
  let out = "";
2907
2907
  let hasExpression = false;
2908
2908
  for (let i = 0; i < templateLiteral.quasis.length; i += 1) {
2909
2909
  out += templateLiteral.quasis[i]?.value.raw ?? "";
2910
2910
  if (templateLiteral.expressions[i]) {
2911
- out += "${key}";
2911
+ out += `\${${parameterName}}`;
2912
2912
  hasExpression = true;
2913
2913
  }
2914
2914
  }
2915
- return { formatted: out, templateVariables: hasExpression ? ["key"] : [] };
2915
+ return { formatted: out, templateVariables: hasExpression ? [parameterName] : [] };
2916
2916
  }
2917
2917
  function applyResolvedDataTestId(args) {
2918
2918
  const addHtmlAttribute = args.addHtmlAttribute ?? true;
@@ -3037,7 +3037,8 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3037
3037
  };
3038
3038
  const normalizedRole = normalizeNativeRole(args.nativeRole) ?? "button";
3039
3039
  const targetPageObjectModelClass = entryOverrides.targetPageObjectModelClass;
3040
- const pomKeyPattern = dataTestId.kind === "template" ? toPomKeyPattern(dataTestId) : null;
3040
+ const selectorParameterName = args.selectorParameterName?.trim() || "key";
3041
+ const pomKeyPattern = dataTestId.kind === "template" ? toPomKeyPattern(dataTestId, selectorParameterName) : null;
3041
3042
  const formattedDataTestIdForPom = dataTestId.kind === "template" ? pomKeyPattern.formatted : dataTestId.value;
3042
3043
  const selectorPatternKind = dataTestId.kind === "template" ? "parameterized" : "static";
3043
3044
  const selectorTemplateVariables = dataTestId.kind === "template" ? pomKeyPattern.templateVariables : [];
@@ -3183,8 +3184,11 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3183
3184
  existingPom.alternateSelectors.push(selectorPattern);
3184
3185
  }
3185
3186
  }
3186
- if (selectorIsParameterized && !existingPom.parameters.some((param) => param.name === "key")) {
3187
- existingPom.parameters = [createPomParameterSpec("key", keyTypeFromValues), ...existingPom.parameters];
3187
+ if (selectorIsParameterized && !existingPom.parameters.some((param) => param.name === selectorParameterName)) {
3188
+ existingPom.parameters = [
3189
+ createPomParameterSpec(selectorParameterName, keyTypeFromValues),
3190
+ ...existingPom.parameters
3191
+ ];
3188
3192
  }
3189
3193
  return true;
3190
3194
  };
@@ -3198,7 +3202,8 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3198
3202
  let suffix = 1;
3199
3203
  while (true) {
3200
3204
  const baseWithSuffix = suffix === 1 ? base : `${base}${suffix}`;
3201
- const candidate = selectorIsParameterized ? `${baseWithSuffix}ByKey` : baseWithSuffix;
3205
+ const parameterizedSuffix = `By${upperFirst(selectorParameterName)}`;
3206
+ const candidate = selectorIsParameterized ? normalizedRole === "radio" && selectorParameterName !== "key" ? parameterizedSuffix : `${baseWithSuffix}${parameterizedSuffix}` : baseWithSuffix;
3202
3207
  const actionName = getPrimaryActionMethodName(candidate);
3203
3208
  const getterCandidates = getPrimaryGetterNameCandidates(candidate);
3204
3209
  let chosenGetterName = getterCandidates.primary;
@@ -3224,7 +3229,7 @@ Fix: either (1) include ${bestKeyPreservePlaceholder} in your :${attrLabel} temp
3224
3229
  const baseNameUpper = upperFirst(baseWithSuffix);
3225
3230
  if (!hasRoleSuffix(baseNameUpper, roleSuffix)) {
3226
3231
  const baseWithRoleSuffix = `${baseWithSuffix}${roleSuffix}`;
3227
- const candidateWithRoleSuffix = selectorIsParameterized ? `${baseWithRoleSuffix}ByKey` : baseWithRoleSuffix;
3232
+ const candidateWithRoleSuffix = selectorIsParameterized ? `${baseWithRoleSuffix}By${upperFirst(selectorParameterName)}` : baseWithRoleSuffix;
3228
3233
  const actionNameWithRoleSuffix = getPrimaryActionMethodName(candidateWithRoleSuffix);
3229
3234
  const getterCandidatesWithRoleSuffix = getPrimaryGetterNameCandidates(candidateWithRoleSuffix);
3230
3235
  let chosenGetterNameWithRoleSuffix = getterCandidatesWithRoleSuffix.primary;
@@ -3292,7 +3297,7 @@ Conflicts: getter=${last.getterName}, method=${last.actionName}
3292
3297
  Fix: make the element identifiable (e.g. add id/name/inner text or use a more specific click handler name), or switch generation.nameCollisionBehavior to "warn"/"suffix".`
3293
3298
  );
3294
3299
  }
3295
- let parameters = selectorIsParameterized ? [createPomParameterSpec("key", keyTypeFromValues)] : [];
3300
+ let parameters = selectorIsParameterized ? [createPomParameterSpec(selectorParameterName, keyTypeFromValues)] : [];
3296
3301
  switch (normalizedRole) {
3297
3302
  case "input":
3298
3303
  parameters = setPomParameter(parameters, "text", "string");
@@ -3311,7 +3316,7 @@ Fix: make the element identifiable (e.g. add id/name/inner text or use a more sp
3311
3316
  parameters = setPomParameter(parameters, "annotationText", 'string = ""');
3312
3317
  break;
3313
3318
  }
3314
- const normalizedParameters = selectorIsParameterized ? setPomParameter(parameters, "key", keyTypeFromValues) : removePomParameter(parameters, "key");
3319
+ const normalizedParameters = selectorIsParameterized ? setPomParameter(parameters, selectorParameterName, keyTypeFromValues) : removePomParameter(parameters, selectorParameterName);
3315
3320
  if (addHtmlAttribute && !fromExisting) {
3316
3321
  upsertAttribute(args.element, testIdAttribute, dataTestId);
3317
3322
  }
@@ -6468,21 +6473,116 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6468
6473
  const nestedRefs = resolvedDependencies.usedComponentSet?.size ? resolvedDependencies.usedComponentSet : resolvedDependencies.childrenComponentSet;
6469
6474
  return Array.from(nestedRefs).some((child) => hasGeneratedPomSurface(child, nextSeen));
6470
6475
  };
6471
- const rawComponentRefsForInstances = usedComponentSet?.size ? usedComponentSet : childrenComponentSet;
6472
6476
  const ownClassName = toPascalCaseLocal(componentName);
6473
6477
  const isSelfReference = (ref) => {
6474
6478
  return toPascalCaseLocal(normalizeTrackedComponentRef(ref)) === ownClassName && ownClassName.length > 0;
6475
6479
  };
6476
- const componentRefsForInstances = /* @__PURE__ */ new Set();
6477
- for (const ref of rawComponentRefsForInstances) {
6478
- const resolvedRef = resolveTrackedComponentRef(ref) ?? normalizeTrackedComponentRef(ref);
6479
- if (isSelfReference(resolvedRef)) {
6480
- continue;
6480
+ const resolveComponentInstance = (spec) => {
6481
+ const componentRef = resolveTrackedComponentRef(spec.componentName);
6482
+ if (!componentRef || isSelfReference(componentRef) || !hasGeneratedPomSurface(componentRef, /* @__PURE__ */ new Set([componentName]))) {
6483
+ return null;
6484
+ }
6485
+ return {
6486
+ ...spec,
6487
+ componentRef,
6488
+ className: normalizeTrackedComponentRef(componentRef)
6489
+ };
6490
+ };
6491
+ const uniqueInstances = (instances, ownerName) => {
6492
+ const byPublicName = /* @__PURE__ */ new Map();
6493
+ for (const instance of instances) {
6494
+ const existing = byPublicName.get(instance.instanceName);
6495
+ if (!existing) {
6496
+ byPublicName.set(instance.instanceName, instance);
6497
+ continue;
6498
+ }
6499
+ const sameInvocationShape = existing.componentRef === instance.componentRef && JSON.stringify(existing.selector) === JSON.stringify(instance.selector) && JSON.stringify(existing.parameters) === JSON.stringify(instance.parameters);
6500
+ if (sameInvocationShape) {
6501
+ continue;
6502
+ }
6503
+ throw new VuePomGeneratorError(
6504
+ `Semantic component instance name ${JSON.stringify(instance.instanceName)} is ambiguous in ${ownerName}.
6505
+ It refers to both <${existing.componentName}> and <${instance.componentName}>.
6506
+
6507
+ Fix: give the invocations distinct accessible names or distinct semantic model/options bindings.`
6508
+ );
6481
6509
  }
6482
- if (!hasGeneratedPomSurface(resolvedRef, /* @__PURE__ */ new Set([componentName]))) {
6510
+ return Array.from(byPublicName.values());
6511
+ };
6512
+ const allInvocationSpecs = dependencies.componentInstances ?? [];
6513
+ const directComponentInstances = uniqueInstances(
6514
+ allInvocationSpecs.filter((spec) => !spec.suppliedSlot).map(resolveComponentInstance).filter((instance) => !!instance),
6515
+ componentName
6516
+ );
6517
+ const projectedComponentInstances = [];
6518
+ for (const owner of directComponentInstances) {
6519
+ const ownerDependencies = componentHierarchyMap.get(owner.componentRef);
6520
+ if (!ownerDependencies?.slotOutlets?.length) {
6483
6521
  continue;
6484
6522
  }
6485
- componentRefsForInstances.add(resolvedRef);
6523
+ const suppliedBySlot = /* @__PURE__ */ new Map();
6524
+ for (const suppliedSpec of allInvocationSpecs) {
6525
+ if (suppliedSpec.suppliedSlot?.ownerSourceId !== owner.sourceId) {
6526
+ continue;
6527
+ }
6528
+ const supplied = resolveComponentInstance(suppliedSpec);
6529
+ if (!supplied) {
6530
+ continue;
6531
+ }
6532
+ const values = suppliedBySlot.get(suppliedSpec.suppliedSlot.name) ?? [];
6533
+ values.push(supplied);
6534
+ suppliedBySlot.set(suppliedSpec.suppliedSlot.name, values);
6535
+ }
6536
+ for (const [slotName, rawContents] of suppliedBySlot) {
6537
+ const outletTargetIds = new Set(
6538
+ ownerDependencies.slotOutlets.filter((outlet) => outlet.name === slotName).map((outlet) => outlet.targetSourceId)
6539
+ );
6540
+ const targetInstances = uniqueInstances(
6541
+ (ownerDependencies.componentInstances ?? []).filter((spec) => outletTargetIds.has(spec.sourceId)).map(resolveComponentInstance).filter((instance) => !!instance),
6542
+ `${owner.className} slot ${JSON.stringify(slotName)}`
6543
+ );
6544
+ const contents = uniqueInstances(rawContents, `${componentName} slot ${JSON.stringify(slotName)}`);
6545
+ for (const target of targetInstances) {
6546
+ if (owner.parameters.length > 0) {
6547
+ throw new VuePomGeneratorError(
6548
+ `Cannot project slot ${JSON.stringify(slotName)} through keyed component instance ${owner.instanceName} in ${componentName}.
6549
+ The owner and projected target require distinct key scopes, which cannot be represented by one unambiguous generated accessor.`
6550
+ );
6551
+ }
6552
+ const keyedContent = contents.find((content) => content.parameters.length > 0);
6553
+ if (keyedContent) {
6554
+ throw new VuePomGeneratorError(
6555
+ `Cannot attach keyed slot content ${keyedContent.instanceName} as a property of ${target.instanceName} in ${componentName}.
6556
+ Move the repetition to the receiving component boundary so the generator can expose it as a keyed accessor.`
6557
+ );
6558
+ }
6559
+ const existingProjection = projectedComponentInstances.find((projection) => {
6560
+ return projection.owner.sourceId === owner.sourceId && projection.target.instanceName === target.instanceName && projection.target.componentRef === target.componentRef && JSON.stringify(projection.target.selector) === JSON.stringify(target.selector);
6561
+ });
6562
+ if (existingProjection) {
6563
+ existingProjection.contents = uniqueInstances(
6564
+ [...existingProjection.contents, ...contents],
6565
+ `${componentName} projected ${target.instanceName}`
6566
+ );
6567
+ continue;
6568
+ }
6569
+ projectedComponentInstances.push({ owner, target, contents });
6570
+ }
6571
+ }
6572
+ }
6573
+ const rawComponentRefsForInstances = usedComponentSet?.size ? usedComponentSet : childrenComponentSet;
6574
+ const componentRefsForInstances = /* @__PURE__ */ new Set();
6575
+ for (const instance of directComponentInstances) {
6576
+ if (!isSelfReference(instance.componentRef)) {
6577
+ componentRefsForInstances.add(instance.componentRef);
6578
+ }
6579
+ }
6580
+ for (const projection of projectedComponentInstances) {
6581
+ for (const instance of [projection.owner, projection.target, ...projection.contents]) {
6582
+ if (!isSelfReference(instance.componentRef)) {
6583
+ componentRefsForInstances.add(instance.componentRef);
6584
+ }
6585
+ }
6486
6586
  }
6487
6587
  const hasChildComponent = (needle) => {
6488
6588
  const normalizedNeedle = normalizeTrackedComponentRef(needle);
@@ -6523,7 +6623,19 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6523
6623
  }));
6524
6624
  const widgetInstances = isView ? getWidgetInstancesForView(componentName, dependencies.dataTestIdSet, customPomAvailableClassIdentifiers) : [];
6525
6625
  const className = toPascalCaseLocal(componentName);
6526
- const childInstancePropertyNames = Array.from(componentRefsForInstances).map((child) => child.split(".vue")[0]);
6626
+ const childInstancePropertyNames = [
6627
+ ...directComponentInstances.map((instance) => instance.instanceName),
6628
+ ...projectedComponentInstances.map((projection) => projection.target.instanceName)
6629
+ ];
6630
+ const duplicateChildInstanceName = childInstancePropertyNames.find((name, index) => {
6631
+ return childInstancePropertyNames.indexOf(name) !== index;
6632
+ });
6633
+ if (duplicateChildInstanceName) {
6634
+ throw new VuePomGeneratorError(
6635
+ `Semantic component instance ${JSON.stringify(duplicateChildInstanceName)} would be emitted more than once in ${componentName}.
6636
+ Fix: give direct and slot-projected instances distinct accessible names or semantic bindings.`
6637
+ );
6638
+ }
6527
6639
  const blockedViewPassthroughMethodNames = new Set(
6528
6640
  attachmentsForThisClass.filter((a) => a.flatten).flatMap((a) => Array.from(a.methodSignatures.keys()))
6529
6641
  );
@@ -6534,22 +6646,22 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6534
6646
  ]);
6535
6647
  const members = [];
6536
6648
  if (isView && (componentRefsForInstances.size > 0 || attachmentsForThisClass.length > 0 || widgetInstances.length > 0)) {
6537
- members.push(...getComponentInstances(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, widgetInstances));
6538
- members.push(getConstructor(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, widgetInstances, { testIdAttribute }));
6649
+ members.push(...getComponentInstances(directComponentInstances, projectedComponentInstances, attachmentsForThisClass, widgetInstances));
6650
+ members.push(getConstructor(directComponentInstances, attachmentsForThisClass, widgetInstances, { testIdAttribute }));
6539
6651
  }
6540
6652
  if (!isView && (componentRefsForInstances.size > 0 || attachmentsForThisClass.length > 0)) {
6541
- members.push(...getComponentInstances(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass));
6542
- members.push(getConstructor(componentRefsForInstances, componentHierarchyMap, attachmentsForThisClass, [], { testIdAttribute }));
6653
+ members.push(...getComponentInstances(directComponentInstances, projectedComponentInstances, attachmentsForThisClass));
6654
+ members.push(getConstructor(directComponentInstances, attachmentsForThisClass, [], { testIdAttribute }));
6543
6655
  }
6544
6656
  members.push(
6545
6657
  ...getAttachmentPassthroughMethods(componentName, dependencies, attachmentsForThisClass, reservedAttachmentPassthroughNames)
6546
6658
  );
6547
- if (isView && componentRefsForInstances.size === 1) {
6659
+ if (isView && directComponentInstances.length === 1) {
6548
6660
  members.push(
6549
6661
  ...getViewPassthroughMethods(
6550
6662
  componentName,
6551
6663
  dependencies,
6552
- componentRefsForInstances,
6664
+ directComponentInstances,
6553
6665
  componentHierarchyMap,
6554
6666
  blockedViewPassthroughMethodNames
6555
6667
  )
@@ -6564,6 +6676,8 @@ function prepareViewObjectModelClass(componentName, dependencies, componentHiera
6564
6676
  return {
6565
6677
  className,
6566
6678
  componentRefsForInstances,
6679
+ directComponentInstances,
6680
+ projectedComponentInstances,
6567
6681
  attachmentsForThisClass,
6568
6682
  widgetInstances,
6569
6683
  isView,
@@ -6639,7 +6753,10 @@ function generateViewObjectModelContent(componentName, dependencies, componentHi
6639
6753
  addNamedImport(sourceFile, {
6640
6754
  moduleSpecifier: "@playwright/test",
6641
6755
  isTypeOnly: true,
6642
- namedImports: [{ name: "Page", alias: "PwPage" }]
6756
+ namedImports: [
6757
+ { name: "Locator", alias: "PwLocator" },
6758
+ { name: "Page", alias: "PwPage" }
6759
+ ]
6643
6760
  });
6644
6761
  }
6645
6762
  addNamedImport(sourceFile, {
@@ -6668,17 +6785,17 @@ function generateViewObjectModelContent(componentName, dependencies, componentHi
6668
6785
  }
6669
6786
  }, { prefixText });
6670
6787
  }
6671
- function getViewPassthroughMethods(viewName, viewDependencies, childrenComponentSet, componentHierarchyMap, blockedMethodNames = /* @__PURE__ */ new Set()) {
6788
+ function getViewPassthroughMethods(viewName, viewDependencies, componentInstances, componentHierarchyMap, blockedMethodNames = /* @__PURE__ */ new Set()) {
6672
6789
  const existingOnView = viewDependencies.generatedMethods ?? /* @__PURE__ */ new Map();
6673
6790
  const methodToChildren = /* @__PURE__ */ new Map();
6674
- for (const child of childrenComponentSet) {
6675
- const childDeps = componentHierarchyMap.get(child);
6791
+ for (const instance of componentInstances) {
6792
+ const childDeps = componentHierarchyMap.get(instance.componentRef);
6676
6793
  if (!childDeps || !childDeps.dataTestIdSet?.size)
6677
6794
  continue;
6678
6795
  const methods = childDeps.generatedMethods;
6679
6796
  if (!methods)
6680
6797
  continue;
6681
- const childProp = child.endsWith(".vue") ? child.slice(0, -4) : child;
6798
+ const childProp = instance.instanceName;
6682
6799
  for (const [name, sig] of methods.entries()) {
6683
6800
  if (!sig)
6684
6801
  continue;
@@ -7368,7 +7485,7 @@ function getWidgetInstancesForView(componentName, dataTestIdSet, availableClassI
7368
7485
  }
7369
7486
  return out;
7370
7487
  }
7371
- function getComponentInstances(childrenComponent, componentHierarchyMap, attachmentsForThisView = [], widgetInstances = []) {
7488
+ function getComponentInstances(componentInstances, projectedComponentInstances, attachmentsForThisView = [], widgetInstances = []) {
7372
7489
  const declarations = [];
7373
7490
  for (const a of attachmentsForThisView) {
7374
7491
  declarations.push(createClassProperty({
@@ -7382,35 +7499,80 @@ function getComponentInstances(childrenComponent, componentHierarchyMap, attachm
7382
7499
  type: w.className
7383
7500
  }));
7384
7501
  }
7385
- childrenComponent.forEach((child) => {
7386
- if (componentHierarchyMap.has(child)) {
7387
- const childName = child.split(".vue")[0];
7502
+ for (const instance of componentInstances) {
7503
+ if (instance.parameters.length === 0) {
7388
7504
  declarations.push(createClassProperty({
7389
- name: childName,
7390
- type: childName
7505
+ name: instance.instanceName,
7506
+ type: instance.className
7391
7507
  }));
7508
+ continue;
7392
7509
  }
7393
- });
7510
+ declarations.push(createClassMethod({
7511
+ name: instance.instanceName,
7512
+ parameters: toTypeScriptPomParameterStructures(instance.parameters),
7513
+ returnType: instance.className,
7514
+ statements: (writer) => {
7515
+ writer.writeLine(`const root = this.componentInstanceLocator(${toTypeScriptPomPatternExpression(instance.selector)});`);
7516
+ writer.writeLine(`return new ${instance.className}(this.page, root);`);
7517
+ }
7518
+ }));
7519
+ }
7520
+ for (const projection of projectedComponentInstances) {
7521
+ const projectedPropertiesType = projection.contents.length > 0 ? ` & { ${projection.contents.map((content) => `readonly ${content.instanceName}: ${content.className}`).join("; ")} }` : "";
7522
+ const statements = (writer) => {
7523
+ const ownerSelector = toTypeScriptPomPatternExpression(projection.owner.selector);
7524
+ const targetSelector = toTypeScriptPomPatternExpression(projection.target.selector);
7525
+ writer.writeLine(`const ownerRoot = this.componentInstanceLocator(${ownerSelector});`);
7526
+ writer.writeLine(`const root = this.componentInstanceLocator(${targetSelector}, ownerRoot);`);
7527
+ writer.writeLine(`const instance = new ${projection.target.className}(this.page, root);`);
7528
+ if (projection.contents.length === 0) {
7529
+ writer.writeLine("return instance;");
7530
+ return;
7531
+ }
7532
+ writer.writeLine("return Object.assign(instance, {");
7533
+ writer.indent(() => {
7534
+ for (const content of projection.contents) {
7535
+ const contentSelector = toTypeScriptPomPatternExpression(content.selector);
7536
+ writer.writeLine(`${content.instanceName}: new ${content.className}(this.page, this.componentInstanceLocator(${contentSelector}, root)),`);
7537
+ }
7538
+ });
7539
+ writer.writeLine("});");
7540
+ };
7541
+ const returnType = `${projection.target.className}${projectedPropertiesType}`;
7542
+ declarations.push(projection.target.parameters.length > 0 ? createClassMethod({
7543
+ name: projection.target.instanceName,
7544
+ parameters: toTypeScriptPomParameterStructures(projection.target.parameters),
7545
+ returnType,
7546
+ statements
7547
+ }) : createClassGetter({
7548
+ name: projection.target.instanceName,
7549
+ returnType,
7550
+ statements
7551
+ }));
7552
+ }
7394
7553
  return declarations;
7395
7554
  }
7396
- function getConstructor(childrenComponent, componentHierarchyMap, attachmentsForThisView = [], widgetInstances = [], options) {
7555
+ function getConstructor(componentInstances, attachmentsForThisView = [], widgetInstances = [], options) {
7397
7556
  const attr = (options?.testIdAttribute ?? "data-testid").trim() || "data-testid";
7398
7557
  return createClassConstructor({
7399
- parameters: [{ name: "page", type: "PwPage" }],
7558
+ parameters: [
7559
+ { name: "page", type: "PwPage" },
7560
+ { name: "root", type: "PwLocator", hasQuestionToken: true }
7561
+ ],
7400
7562
  statements: (writer) => {
7401
- writer.writeLine(`super(page, { testIdAttribute: ${JSON.stringify(attr)} });`);
7563
+ writer.writeLine(`super(page, { root, testIdAttribute: ${JSON.stringify(attr)} });`);
7402
7564
  for (const a of attachmentsForThisView) {
7403
7565
  writer.writeLine(`this.${a.propertyName} = new ${a.className}(this.page, this);`);
7404
7566
  }
7405
7567
  for (const w of widgetInstances) {
7406
7568
  writer.writeLine(`this.${w.propertyName} = new ${w.className}(this.page, ${JSON.stringify(w.testId)});`);
7407
7569
  }
7408
- childrenComponent.forEach((child) => {
7409
- if (componentHierarchyMap.has(child)) {
7410
- const childName = child.split(".vue")[0];
7411
- writer.writeLine(`this.${childName} = new ${childName}(page);`);
7570
+ for (const instance of componentInstances) {
7571
+ if (instance.parameters.length === 0) {
7572
+ const selector = toTypeScriptPomPatternExpression(instance.selector);
7573
+ writer.writeLine(`this.${instance.instanceName} = new ${instance.className}(page, this.componentInstanceLocator(${selector}));`);
7412
7574
  }
7413
- });
7575
+ }
7414
7576
  }
7415
7577
  });
7416
7578
  }
@@ -7959,7 +8121,7 @@ function getStaticAttributeContent$1(element, name) {
7959
8121
  });
7960
8122
  return attribute?.value?.content?.trim() || null;
7961
8123
  }
7962
- function mapExplicitAriaRole(role) {
8124
+ function mapExplicitAriaRole(role, elementTag) {
7963
8125
  switch (role.toLowerCase()) {
7964
8126
  case "button":
7965
8127
  case "checkbox":
@@ -7971,6 +8133,7 @@ function mapExplicitAriaRole(role) {
7971
8133
  case "radiogroup":
7972
8134
  return "radio";
7973
8135
  case "combobox":
8136
+ return elementTag === "input" || elementTag === "uinput" ? "input" : "select";
7974
8137
  case "listbox":
7975
8138
  return "select";
7976
8139
  case "searchbox":
@@ -7992,11 +8155,11 @@ function hasAttribute(element, name) {
7992
8155
  });
7993
8156
  }
7994
8157
  function getElementControlRole(element) {
8158
+ const tag = element.tag.toLowerCase();
7995
8159
  const explicitRole = getStaticAttributeContent$1(element, "role");
7996
8160
  if (explicitRole) {
7997
- return mapExplicitAriaRole(explicitRole);
8161
+ return mapExplicitAriaRole(explicitRole, tag);
7998
8162
  }
7999
- const tag = element.tag.toLowerCase();
8000
8163
  const type = (getStaticAttributeContent$1(element, "type") || "").toLowerCase();
8001
8164
  if (tag === "input" || tag === "uinput") {
8002
8165
  if (type === "radio") {
@@ -8185,6 +8348,92 @@ function resolveWrapperContractForTag(options) {
8185
8348
  return resolveTag(options.tag);
8186
8349
  }
8187
8350
  const CLICK_EVENT_NAME = TESTID_CLICK_EVENT_NAME;
8351
+ const POM_INSTANCE_ATTRIBUTE = "data-pom-instance";
8352
+ function getLastSemanticIdentifier(node) {
8353
+ if (!node) {
8354
+ return null;
8355
+ }
8356
+ if (node.type === "Identifier") {
8357
+ return node.name?.trim() || null;
8358
+ }
8359
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
8360
+ if (!node.computed && node.property?.type === "Identifier") {
8361
+ return node.property.name?.trim() || null;
8362
+ }
8363
+ if (node.computed && node.property?.type === "StringLiteral") {
8364
+ return node.property.value?.trim() || null;
8365
+ }
8366
+ return getLastSemanticIdentifier(node.object);
8367
+ }
8368
+ if (node.type === "CallExpression" || node.type === "OptionalCallExpression") {
8369
+ return getLastSemanticIdentifier(node.callee);
8370
+ }
8371
+ if (node.type === "TSAsExpression" || node.type === "TSTypeAssertion" || node.type === "TSNonNullExpression" || node.type === "ChainExpression") {
8372
+ return getLastSemanticIdentifier(node.expression);
8373
+ }
8374
+ return null;
8375
+ }
8376
+ function getBoundSemanticName(element, attributeName) {
8377
+ const directive = element.props.find((prop) => {
8378
+ return prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.content === attributeName && !!prop.exp;
8379
+ });
8380
+ if (!directive?.exp) {
8381
+ return null;
8382
+ }
8383
+ const source = getVueExpressionSource(
8384
+ directive.exp,
8385
+ "loc",
8386
+ "content",
8387
+ "compiled"
8388
+ );
8389
+ if (!source) {
8390
+ return null;
8391
+ }
8392
+ try {
8393
+ const identifier = getLastSemanticIdentifier(parseExpression(source, { plugins: ["typescript"] }));
8394
+ return identifier ? toPascalCase(identifier) : null;
8395
+ } catch {
8396
+ return null;
8397
+ }
8398
+ }
8399
+ function getComponentInstanceNameCandidates(element) {
8400
+ const explicitAccessibleNames = ["aria-label", "label", "title", "name"].map((attributeName) => getStaticAttributeContent(element, attributeName)).filter((value) => !!value).map(toPascalCase);
8401
+ const optionsName = getBoundSemanticName(element, "options");
8402
+ const { vModel, modelValue } = getModelBindingValues(element);
8403
+ const modelName = modelValue || vModel;
8404
+ const candidates = [
8405
+ ...explicitAccessibleNames,
8406
+ optionsName && optionsName !== "Options" ? optionsName : null,
8407
+ modelName && !(/* @__PURE__ */ new Set(["Data", "Item", "ModelValue", "Value"])).has(modelName) ? toPascalCase(modelName) : null,
8408
+ toPascalCase(element.tag)
8409
+ ].filter((value) => !!value);
8410
+ return Array.from(new Set(candidates));
8411
+ }
8412
+ function getElementSourceId(element) {
8413
+ return `${element.tag}:${element.loc.start.offset}:${element.loc.end.offset}`;
8414
+ }
8415
+ function getNearestComponentAncestor(element, hierarchyMap2, isComponentLikeTag2) {
8416
+ let parent = hierarchyMap2.get(element) ?? null;
8417
+ while (parent) {
8418
+ if (isComponentLikeTag2(parent.tag)) {
8419
+ return parent;
8420
+ }
8421
+ parent = hierarchyMap2.get(parent) ?? null;
8422
+ }
8423
+ return null;
8424
+ }
8425
+ function getSlotNameFromTemplate(element) {
8426
+ const directive = element.props.find((prop) => {
8427
+ return prop.type === NodeTypes.DIRECTIVE && prop.name === "slot";
8428
+ });
8429
+ if (!directive) {
8430
+ return null;
8431
+ }
8432
+ if (!directive.arg) {
8433
+ return "default";
8434
+ }
8435
+ return directive.arg.type === NodeTypes.SIMPLE_EXPRESSION ? directive.arg.content.trim() || "default" : null;
8436
+ }
8188
8437
  function getStaticAttributeContent(element, name) {
8189
8438
  const attr = element.props.find((prop) => {
8190
8439
  return prop.type === NodeTypes.ATTRIBUTE && prop.name === name;
@@ -8523,6 +8772,7 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8523
8772
  Object.entries(nativeWrappers).map(([tag, config]) => [tag, { ...config }])
8524
8773
  );
8525
8774
  const wrapperContractByTag = /* @__PURE__ */ new Map();
8775
+ const instanceWrapperContractByTag = /* @__PURE__ */ new Map();
8526
8776
  const getWrapperContract = (tag) => {
8527
8777
  if (!wrapperContractByTag.has(tag)) {
8528
8778
  wrapperContractByTag.set(tag, resolveWrapperContractForTag({
@@ -8534,6 +8784,17 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8534
8784
  }
8535
8785
  return wrapperContractByTag.get(tag) ?? null;
8536
8786
  };
8787
+ const getInstanceWrapperContract = (tag) => {
8788
+ if (!instanceWrapperContractByTag.has(tag)) {
8789
+ instanceWrapperContractByTag.set(tag, resolveWrapperContractForTag({
8790
+ tag,
8791
+ vueFilesPathMap,
8792
+ wrapperSearchRoots,
8793
+ testIdAttribute: POM_INSTANCE_ATTRIBUTE
8794
+ }));
8795
+ }
8796
+ return instanceWrapperContractByTag.get(tag) ?? null;
8797
+ };
8537
8798
  const safeRealpath2 = (p) => {
8538
8799
  try {
8539
8800
  return fs.existsSync(p) ? fs.realpathSync(p) : p;
@@ -8550,6 +8811,7 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8550
8811
  const conditionalMergeGroupByElement = /* @__PURE__ */ new WeakMap();
8551
8812
  const conditionalMergeGroupByElementLoc = /* @__PURE__ */ new Map();
8552
8813
  const conditionalMergeGroupByIfBranch = /* @__PURE__ */ new WeakMap();
8814
+ const componentInstanceNameOwnerByName = /* @__PURE__ */ new Map();
8553
8815
  let conditionalMergeGroupCounter = 0;
8554
8816
  const getElementLocationKey = (element) => {
8555
8817
  const startOffset = element.loc?.start.offset;
@@ -8643,6 +8905,8 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8643
8905
  childrenComponentSet: /* @__PURE__ */ new Set(),
8644
8906
  usedComponentSet: /* @__PURE__ */ new Set(),
8645
8907
  dataTestIdSet: /* @__PURE__ */ new Set(),
8908
+ componentInstances: [],
8909
+ slotOutlets: [],
8646
8910
  isView,
8647
8911
  methodsContent: ""
8648
8912
  };
@@ -8656,6 +8920,17 @@ function createTestIdTransform(componentName, componentHierarchyMap, nativeWrapp
8656
8920
  const isUpper = isAsciiUppercaseLetterCode$1(first);
8657
8921
  return isUpper || tag.includes("-");
8658
8922
  };
8923
+ if (element.tag === "slot") {
8924
+ const slotName = getStaticAttributeContent(element, "name") ?? "default";
8925
+ const target = getNearestComponentAncestor(element, hierarchyMap, isComponentLikeTag2);
8926
+ if (target) {
8927
+ dependencies.slotOutlets ??= [];
8928
+ const outlet = { name: slotName, targetSourceId: getElementSourceId(target) };
8929
+ if (!dependencies.slotOutlets.some((existing) => existing.name === outlet.name && existing.targetSourceId === outlet.targetSourceId)) {
8930
+ dependencies.slotOutlets.push(outlet);
8931
+ }
8932
+ }
8933
+ }
8659
8934
  if (isComponentLikeTag2(element.tag)) {
8660
8935
  dependencies.usedComponentSet.add(element.tag);
8661
8936
  if (crossFileKeyRegistry && context.scopes.vSlot > 0) {
@@ -8718,6 +8993,7 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8718
8993
  role: contract.role
8719
8994
  };
8720
8995
  }
8996
+ let selectorParameterName = "key";
8721
8997
  const getBestAvailableKeyInfo = () => {
8722
8998
  const parentNode = context.parent && typeof context.parent === "object" ? context.parent : null;
8723
8999
  const isDirectVForChild = parentNode?.type === NodeTypes.FOR;
@@ -8725,6 +9001,7 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8725
9001
  if (configuredAttrName && configuredAttrName !== "key") {
8726
9002
  const bindingKeyInfo = getBindingKeyInfo(element, configuredAttrName);
8727
9003
  if (bindingKeyInfo) {
9004
+ selectorParameterName = configuredAttrName === "value" ? "value" : "key";
8728
9005
  return bindingKeyInfo;
8729
9006
  }
8730
9007
  }
@@ -8751,6 +9028,50 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8751
9028
  const bestKeyInfo = getBestAvailableKeyInfo();
8752
9029
  const bestKeyPlaceholder = bestKeyInfo?.selectorFragment ?? null;
8753
9030
  const bestRuntimeKeyPlaceholder = bestKeyInfo?.runtimeFragment ?? null;
9031
+ if (isComponentLikeTag2(element.tag)) {
9032
+ const componentInstanceKeyInfo = getKeyDirectiveInfo(element) || getContainedInVForDirectiveKeyInfo(context, element, hierarchyMap);
9033
+ const instanceContract = getInstanceWrapperContract(element.tag);
9034
+ if ((instanceContract?.forwardedTestIdTargetOffsets.size ?? 0) > 0) {
9035
+ if (tryGetExistingElementDataTestId(element, POM_INSTANCE_ATTRIBUTE)) {
9036
+ const loc = element.loc.start;
9037
+ throw new Error(
9038
+ `[vue-pom-generator] ${POM_INSTANCE_ATTRIBUTE} is generator-owned and cannot be authored manually.
9039
+ Component: ${componentName}
9040
+ File: ${context.filename ?? "unknown"}:${loc.line}:${loc.column}`
9041
+ );
9042
+ }
9043
+ const sourceId = getElementSourceId(element);
9044
+ const semanticNameCandidates = getComponentInstanceNameCandidates(element);
9045
+ const componentTypeName = toPascalCase(element.tag);
9046
+ const instanceNameCandidates = componentInstanceKeyInfo ? [componentTypeName, ...semanticNameCandidates.filter((candidate) => candidate !== componentTypeName)] : semanticNameCandidates;
9047
+ const instanceName = instanceNameCandidates.find((candidate) => {
9048
+ const owner = componentInstanceNameOwnerByName.get(candidate);
9049
+ return !owner || !!componentInstanceKeyInfo && owner.keyed && owner.componentName === element.tag;
9050
+ });
9051
+ if (instanceName) {
9052
+ componentInstanceNameOwnerByName.set(instanceName, {
9053
+ componentName: element.tag,
9054
+ keyed: !!componentInstanceKeyInfo,
9055
+ sourceId
9056
+ });
9057
+ const runtimeMarker = componentInstanceKeyInfo ? templateAttributeValue(`${componentName}-${componentInstanceKeyInfo.runtimeFragment}-${instanceName}-component`) : staticAttributeValue(`${componentName}-${instanceName}-component`);
9058
+ const selector = componentInstanceKeyInfo ? createPomStringPattern(`${componentName}-\${key}-${instanceName}-component`, "parameterized", ["key"]) : createPomStringPattern(`${componentName}-${instanceName}-component`, "static", []);
9059
+ upsertAttribute(element, POM_INSTANCE_ATTRIBUTE, runtimeMarker);
9060
+ const slotTemplate = getContainedInSlotTemplateNode(element, hierarchyMap);
9061
+ const slotName = slotTemplate ? getSlotNameFromTemplate(slotTemplate) : null;
9062
+ const slotOwner = slotTemplate ? getNearestComponentAncestor(slotTemplate, hierarchyMap, isComponentLikeTag2) : null;
9063
+ dependencies.componentInstances ??= [];
9064
+ dependencies.componentInstances.push({
9065
+ sourceId,
9066
+ componentName: element.tag,
9067
+ instanceName,
9068
+ selector,
9069
+ parameters: componentInstanceKeyInfo ? [createPomParameterSpec("key", "string")] : [],
9070
+ suppliedSlot: slotName && slotOwner ? { ownerSourceId: getElementSourceId(slotOwner), name: slotName } : void 0
9071
+ });
9072
+ }
9073
+ }
9074
+ }
8754
9075
  const keyValuesOverride = tryGetContainedInStaticVForSourceLiteralValues(context);
8755
9076
  const parentKey = context?.parent ? context.parent : null;
8756
9077
  const conditional = getConditionalDirectiveInfo(element);
@@ -8859,6 +9180,7 @@ Fix: set \`role\` explicitly in nativeWrappers (e.g. { "${element.tag}": { role:
8859
9180
  preferredGeneratedValue: args.preferredGeneratedValue,
8860
9181
  preferredRuntimeValue: args.preferredRuntimeValue,
8861
9182
  keyInfo: bestKeyInfo,
9183
+ selectorParameterName,
8862
9184
  keyValuesOverride,
8863
9185
  entryOverrides: args.entryOverrides,
8864
9186
  semanticNameHint: args.semanticNameHint,