@immense/vue-pom-generator 1.0.89 → 1.0.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +42 -10
  2. package/RELEASE_NOTES.md +22 -47
  3. package/class-generation/index.ts +124 -107
  4. package/dist/class-generation/index.d.ts +1 -0
  5. package/dist/class-generation/index.d.ts.map +1 -1
  6. package/dist/eslint/index.cjs +42 -0
  7. package/dist/eslint/index.cjs.map +1 -1
  8. package/dist/eslint/index.d.ts +3 -0
  9. package/dist/eslint/index.d.ts.map +1 -1
  10. package/dist/eslint/index.mjs +42 -0
  11. package/dist/eslint/index.mjs.map +1 -1
  12. package/dist/eslint/no-data-testid-in-specs.d.ts +3 -0
  13. package/dist/eslint/no-data-testid-in-specs.d.ts.map +1 -0
  14. package/dist/index.cjs +1824 -1537
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.mjs +1815 -1528
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/plugin/internal/build-plugin.d.ts.map +1 -1
  21. package/dist/plugin/internal/dev-plugin.d.ts.map +1 -1
  22. package/dist/plugin/resolved-generation-options.d.ts +2 -2
  23. package/dist/plugin/resolved-generation-options.d.ts.map +1 -1
  24. package/dist/plugin/resolved-injection-options.d.ts +3 -3
  25. package/dist/plugin/resolved-injection-options.d.ts.map +1 -1
  26. package/dist/plugin/types.d.ts +11 -3
  27. package/dist/plugin/types.d.ts.map +1 -1
  28. package/dist/plugin/vue-plugin.d.ts +3 -2
  29. package/dist/plugin/vue-plugin.d.ts.map +1 -1
  30. package/dist/route-navigation-codegen.d.ts +38 -0
  31. package/dist/route-navigation-codegen.d.ts.map +1 -0
  32. package/dist/router-bridge.d.ts +19 -0
  33. package/dist/router-bridge.d.ts.map +1 -0
  34. package/dist/router.cjs +9 -0
  35. package/dist/router.cjs.map +1 -0
  36. package/dist/router.mjs +9 -0
  37. package/dist/router.mjs.map +1 -0
  38. package/dist/tests/existing-id-behavior.test.d.ts +2 -0
  39. package/dist/tests/existing-id-behavior.test.d.ts.map +1 -0
  40. package/dist/tests/router-bridge.test.d.ts +2 -0
  41. package/dist/tests/router-bridge.test.d.ts.map +1 -0
  42. package/dist/vite.config.d.ts.map +1 -1
  43. package/package.json +6 -1
package/README.md CHANGED
@@ -23,7 +23,7 @@ If you already use Playwright with `getByTestId`, the point is simple: this pack
23
23
 
24
24
  - **It is not a runtime DOM crawler.** It only knows what it can learn from Vue SFC templates and router introspection.
25
25
  - **It does not fully understand arbitrary wrapper components automatically.** There is some wrapper inference for simple local SFCs and some naming conventions, but serious design-system components still need `injection.nativeWrappers`.
26
- - **It does not fully fill route params for you.** Generated `goTo()` / `goToSelf()` methods use the discovered route template literally. A route like `/users/:id` still needs a real `/users/123` when you actually navigate.
26
+ - **It cannot infer query-value types from arbitrary route-props code.** Generated `goTo()` accepts discovered query keys as optional `string | number` values; callers still choose and supply the values appropriate for their application.
27
27
  - **It does not auto-attach every file in `pom/custom`.** Custom helpers are imported, but they only affect generated classes when you explicitly configure attachments, or when they match the built-in `Toggle` / `Checkbox` widget conventions.
28
28
  - **It does not make override classes globally replace generated classes.** `pom/overrides` only changes generated fixture instantiation. Direct imports from the generated barrel still give you the generated class unless you import your override yourself.
29
29
  - **The C# emitter is not feature-parity with the TypeScript emitter.** It emits locator/action classes, but not Playwright fixtures, not helper attachments, and not the same route helper surface.
@@ -215,6 +215,7 @@ Exports:
215
215
  - `defineVuePomGeneratorConfig()`
216
216
  - `defineNuxtPomGeneratorConfig()`
217
217
  - `@immense/vue-pom-generator/eslint`
218
+ - `@immense/vue-pom-generator/router` (browser-safe runtime bridge)
218
219
 
219
220
  ## Basic Vue/Vite setup
220
221
 
@@ -284,6 +285,17 @@ export default defineConfig({
284
285
  });
285
286
  ```
286
287
 
288
+ When router-aware generation is enabled, expose the live router only in the environment
289
+ where Playwright runs:
290
+
291
+ ```ts
292
+ import { exposeRouterForPomNavigation } from "@immense/vue-pom-generator/router";
293
+
294
+ if (import.meta.env.DEV) {
295
+ exposeRouterForPomNavigation(router);
296
+ }
297
+ ```
298
+
287
299
  ## Basic Nuxt setup
288
300
 
289
301
  ```ts
@@ -395,26 +407,46 @@ What is not fully supported:
395
407
 
396
408
  - arbitrary computed `:to` expressions
397
409
  - parameter-aware `goToSelf()` URL filling
398
- - exposing rich route-param metadata on the generated POM surface
410
+ - inferring query-value types from arbitrary route-props transformations
399
411
 
400
412
  ### 2) View-level `route`, `goTo()`, and `goToSelf()`
401
413
 
402
414
  When `generation.router` is enabled, each view POM gets:
403
415
 
404
416
  - `static readonly route: { template: string } | null`
405
- - `async goTo()`
417
+ - a typed `async goTo(...)` whose flat input includes discovered path params and optional query keys
406
418
  - `async goToSelf()`
407
419
 
420
+ For a route such as:
421
+
422
+ ```ts
423
+ {
424
+ path: "/users/:userId",
425
+ name: "user-details",
426
+ component: UserDetailsPage,
427
+ props: route => ({
428
+ userId: route.params.userId,
429
+ tab: route.query.tab,
430
+ }),
431
+ }
432
+ ```
433
+
434
+ the generated method is shaped like this:
435
+
436
+ ```ts
437
+ goTo(params: { userId: string | number; tab?: string | number }): Promise<void>
438
+ ```
439
+
440
+ `goTo({ userId: 42, tab: "activity" })` partitions the flat input into Vue Router's
441
+ `params` and `query` records. On a cold page it resolves and fully loads the named route;
442
+ on a warm page it uses `router.push`.
443
+
408
444
  Important caveats:
409
445
 
410
446
  - `goToSelf()` calls `page.goto(...)`, resolving the route template against `PLAYWRIGHT_RUNTIME_BASE_URL`, `PLAYWRIGHT_TEST_BASE_URL`, or `VITE_PLAYWRIGHT_BASE_URL` when those runtime env vars are present
411
- - a dynamic route template like `/users/:id` stays `/users/:id`
447
+ - unlike `goTo()`, a dynamic `goToSelf()` template like `/users/:id` stays `/users/:id`
412
448
  - if a component is matched by multiple routes, the generator currently picks one route template (the shortest one)
413
-
414
- So the safe rule is:
415
-
416
- - use generated `goTo()` for simple/static routes
417
- - for dynamic routes, navigate with a real URL yourself or wrap that behavior in your override/custom code
449
+ - when a component has both a paramless route and a route whose path params are all optional, pass at least one path-param key (it may be `undefined`) to select the parametrized route; a query-only object selects the paramless route
418
450
 
419
451
  ### Why `moduleShims` exists
420
452
 
@@ -1254,7 +1286,7 @@ If you are evaluating this package critically, the most accurate short version i
1254
1286
  - it is strongest when your team already wants `getByTestId`-style Playwright tests
1255
1287
  - it is strongest in TypeScript-first Playwright projects
1256
1288
  - it is strongest when your Vue component library is either native-heavy or can be described with `nativeWrappers`
1257
- - it is useful with router-aware pages, but you should treat dynamic-route `goTo()` support as partial and explicit
1289
+ - it is useful with router-aware pages, including typed path params and discovered query keys
1258
1290
  - it becomes much more maintainable when you pair it with the ESLint cleanup rule and a small `pom/custom` folder for the genuinely hard widgets
1259
1291
 
1260
1292
  If that matches your codebase, the package removes a surprising amount of repetitive test maintenance. If it does not, the caveats above are the important ones to believe.
package/RELEASE_NOTES.md CHANGED
@@ -1,61 +1,36 @@
1
- I'll verify the actual state of the repository to generate accurate release notes.
1
+ Looking at the provided data, the v1.0.90..HEAD range contains only one commit/PR (#53), confirmed
2
+ by the diffstat showing 6 files. I'll generate release notes focused on that change.
2
3
 
3
- Let me check the commit details and find any associated PR.
4
-
5
- Let me check the tag dates to understand the release boundaries.
6
-
7
- Based on my verification of the repository state, I have what I need. Key findings:
8
-
9
- - v1.0.88..HEAD contains exactly one commit (aa94a4a), a direct commit to main (no associated PR —
10
- confirmed via gh search).
11
- - The diffstat (7 files, 7 insertions, 213 deletions) matches that single commit exactly.
12
- - All 50+ PRs in the provided list were merged on/before 2026-08-10, while this release window is
13
- 2026-08-12 (10:19–12:21 UTC). None fall in the window — they shipped in v1.0.88 or earlier.
14
-
15
- So v1.0.89 is a small cleanup release containing one direct refactor commit and no merged PRs. Here
16
- are the release notes:
17
-
18
- -----------------------------------------------------------------------------------------------
19
-
20
- v1.0.89
4
+ v1.0.91
21
5
 
22
6
  Highlights
23
7
 
24
- - Removed dead standalone-wrapper suppression logic that fired on 0 of 628 components when
25
- instrumented against the full consumer build.
26
- - Net −213 lines of dead code and synthetic tests across utils.ts, manifest-generator.ts, and
27
- class-generation/index.ts.
28
- - Byte-neutral for the known consumer: 632 generated .g.ts files unchanged before and after; build
29
- and typecheck green.
8
+ - New route-navigation-codegen module generates type-safe Vue Router navigation helpers with
9
+ query-parameter awareness
10
+ - class-generation refactored to integrate route navigation generation into POM class output
11
+ - Router bridge wired to pass route metadata into the navigation codegen
12
+ - README updated with documentation for query-aware navigation generation
13
+ - New generated-tsc test suite verifies generated navigation code passes TypeScript compilation
30
14
 
31
15
  Changes
32
16
 
33
- Dead-code removal
34
-
35
- - Deleted shouldSuppressStandaloneWrapperFallbackSurface and its helpers
36
- (STANDALONE_WRAPPER_FALLBACK_ROLES, stripTrailingAsciiDigits,
37
- matchesStandaloneWrapperFallbackMethodName) from utils.ts.
38
- - Dropped the two emit-time suppression filters in manifest-generator.ts and
39
- class-generation/index.ts.
40
-
41
- Tests
42
-
43
- - Deleted the synthetic tests/generated-tsc.test.ts and the standalone-wrapper suppression cases in
44
- tests/broad/manifest-generator-ts.test.ts.
45
- - Flipped two class-generation-coverage assertions from "WrapperButton is suppressed" to
46
- "WrapperButton is emitted," and completed the Baz fixture's
47
- generatedActionName/generatedPropertyName fields in tests/virtual-testids.test.ts.
17
+ - Route navigation codegen: Added route-navigation-codegen.ts — generates goTo(params)-style
18
+ navigation accessors that account for declared route query parameters
19
+ - Class generation: Refactored class-generation/index.ts to produce navigation methods alongside
20
+ existing POM class members
21
+ - Router bridge: Updated router-bridge.ts to expose route metadata needed by the navigation codegen
22
+ - Documentation: Updated README.md with details on the new query-aware navigation generation
23
+ feature
24
+ - Tests: Added tests/generated-tsc.test.ts to assert generated navigation output type-checks;
25
+ updated tests/class-generation-coverage.test.ts for new navigation behavior
48
26
 
49
27
  Pull Requests Included
50
28
 
51
- - None. This release contains a single direct commit to main (aa94a4a); no pull requests were
52
- merged in the release window.
29
+ - #53 Support query-aware generated navigation
30
+ (]8;id=md-1gwtg7u;https://github.com/immense/vue-pom-generator/pull/53https://github.com/immense/vue-pom-generator/pull/53]8;;]8;;)]8;;
53
31
 
54
32
  Testing
55
33
 
56
- - Instrumented the suppression predicate with env-gated trace logging
57
- (VUE_POM_POM_TRACE_SUPPRESSION=1) and ran the full consumer build — suppression fired on 0/628
58
- components.
59
- - Verified byte-neutrality (632 .g.ts files identical before/after); build and typecheck green.
60
- Existing tests updated; no new suite added.
34
+ - Added generated-tsc.test.ts for TypeScript compilation validation of generated navigation code;
35
+ updated class-generation-coverage.test.ts to cover new navigation generation behavior.
61
36
 
@@ -28,7 +28,7 @@ import {
28
28
  type PomStringPattern,
29
29
  } from "../pom-patterns";
30
30
  import { buildPomLocatorDescription, stripPomActionPrefix } from "../pom-discoverability";
31
- import { getParamToken, introspectNuxtPages, parseRouterFileFromCwd } from "../router-introspection";
31
+ import { introspectNuxtPages, parseRouterFileFromCwd } from "../router-introspection";
32
32
  import {
33
33
  addExportAll,
34
34
  addNamedImport,
@@ -61,6 +61,10 @@ import {
61
61
  // Intentionally imported so tooling understands this exported helper is part of the
62
62
  // generated POM public surface (it is consumed by generated Playwright fixtures).
63
63
  import { setPlaywrightAnimationOptions } from "./pointer";
64
+ import {
65
+ createRouterNavigationWriter,
66
+ createUrlNavigationWriter,
67
+ } from "../route-navigation-codegen";
64
68
 
65
69
  void setPlaywrightAnimationOptions;
66
70
 
@@ -117,6 +121,7 @@ interface RouteEntry {
117
121
  name: string | null;
118
122
  template: string;
119
123
  params: RouteParamMeta[];
124
+ query: string[];
120
125
  }
121
126
 
122
127
  interface RouteMeta {
@@ -294,7 +299,7 @@ async function getRouteMetaByComponent(
294
299
  const map = new Map<string, RouteEntry[]>();
295
300
  for (const entry of routeMetaEntries) {
296
301
  const list = map.get(entry.componentName) ?? [];
297
- list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params });
302
+ list.push({ name: entry.name, template: entry.pathTemplate, params: entry.params, query: entry.query });
298
303
  map.set(entry.componentName, list);
299
304
  }
300
305
 
@@ -344,8 +349,50 @@ function generateRouteProperty(routeMeta: RouteMeta | null): TypeScriptClassMemb
344
349
  ];
345
350
  }
346
351
 
347
- function buildParamTypeString(params: RouteParamMeta[]): string {
348
- return `{ ${params.map(p => `${p.name}${p.optional ? "?" : ""}: string | number`).join("; ")} }`;
352
+ function formatNavigationFieldName(name: string): string {
353
+ return /^[$a-z_][$\w]*$/i.test(name) ? name : JSON.stringify(name);
354
+ }
355
+
356
+ function buildNavigationTypeString(route: RouteEntry, requiredOptionalParamName?: string): string {
357
+ const pathFields = route.params.map((param) => {
358
+ const forcePresent = param.optional && param.name === requiredOptionalParamName;
359
+ return `${formatNavigationFieldName(param.name)}${param.optional && !forcePresent ? "?" : ""}: string | number${forcePresent ? " | undefined" : ""}`;
360
+ });
361
+ const pathNames = new Set(route.params.map(param => param.name));
362
+ const queryFields = route.query
363
+ .filter(query => !pathNames.has(query))
364
+ .map(query => `${formatNavigationFieldName(query)}?: string | number`);
365
+ return `{ ${[...pathFields, ...queryFields].join("; ")} }`;
366
+ }
367
+
368
+ function buildParametrizedRouteSelectionTypeString(route: RouteEntry): string {
369
+ if (route.params.some(param => !param.optional)) {
370
+ return buildNavigationTypeString(route);
371
+ }
372
+
373
+ // In a dual-route overload, the runtime selects the parametrized route by path-key
374
+ // presence. Require at least one optional path key to be present so the public type
375
+ // cannot accept an object that runtime would send to the paramless route. Its value may
376
+ // still be undefined, which intentionally selects the optional-param route with that
377
+ // segment omitted.
378
+ return route.params
379
+ .map(param => buildNavigationTypeString(route, param.name))
380
+ .join(" | ");
381
+ }
382
+
383
+ function buildImplementationNavigationTypeString(routes: RouteEntry[]): string {
384
+ const fields = new Map<string, boolean>();
385
+ for (const route of routes) {
386
+ for (const param of route.params) {
387
+ fields.set(param.name, true);
388
+ }
389
+ for (const query of route.query) {
390
+ if (!fields.has(query)) {
391
+ fields.set(query, true);
392
+ }
393
+ }
394
+ }
395
+ return `{ ${Array.from(fields.keys()).map(name => `${formatNavigationFieldName(name)}?: string | number`).join("; ")} }`;
349
396
  }
350
397
 
351
398
  function chooseParamlessRoute(routes: RouteEntry[]): RouteEntry | null {
@@ -366,67 +413,12 @@ function chooseParametrizedRoute(routes: RouteEntry[]): RouteEntry | null {
366
413
  .sort((a, b) => a.params.length - b.params.length || a.template.length - b.template.length || a.template.localeCompare(b.template))[0];
367
414
  }
368
415
 
369
- const GOTO_RUNTIME_LINES = [
370
- "const runtimeEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;",
371
- "const runtimeBaseUrl = runtimeEnv?.PLAYWRIGHT_RUNTIME_BASE_URL ?? runtimeEnv?.PLAYWRIGHT_TEST_BASE_URL ?? runtimeEnv?.VITE_PLAYWRIGHT_BASE_URL;",
372
- "const resolvedUrl = runtimeBaseUrl ? new URL(targetUrl, runtimeBaseUrl).toString() : targetUrl;",
373
- "await this.page.goto(resolvedUrl);",
374
- ];
375
-
376
- /**
377
- * The `window`/`globalThis` key the consumer exposes the live Vue Router instance under
378
- * (dev-gated), so generated `goTo()` can drive `router.push({ name, params })` instead of
379
- * reconstructing URLs from opaque path-template tokens. The consumer is responsible for
380
- * installing `globalThis[ROUTER_GLOBAL_NAME] = router` in test/dev builds.
381
- */
382
- const ROUTER_GLOBAL_NAME = "__appRouter";
383
-
384
- /**
385
- * Emits the router-driven `goTo()` body for a named route. Two regimes:
386
- *
387
- * - **Cold page** (fresh Playwright page on `about:blank` — the SPA hasn't booted, so the
388
- * router global is `undefined`): boot the app with a cheap `page.goto("/")`, wait for the
389
- * router to install, then **full-load the resolved target URL** (`router.resolve({ name,
390
- * params }).href` + `page.goto`). A full load is unavoidable here — you cannot `push`
391
- * before the router exists — and resolving the target (rather than stopping at "/") means
392
- * the route's component mounts via a stable page load, exactly as the original
393
- * `page.goto`-based tests did. This matters because the POM runtime clicks with
394
- * `force: true` (skipping Playwright's actionability check): a SPA `push` into a freshly
395
- * mounted view can resolve before radios/inputs are interactive, so a force-click fired
396
- * the instant the push resolves can miss (the control's handler isn't attached yet). A
397
- * full load gives a fully-rendered, interactive page.
398
- * - **Warm page** (the app is already mounted — any later `goTo()` in the same test): the
399
- * guard is a single cheap `evaluate` that finds the router present, so the navigation is a
400
- * pure SPA `router.push({ name, params })` — no reload — the intended fast path.
401
- *
402
- * `routeNameExpr` is a TS expression yielding the route name (a string literal for single
403
- * routes, or `params ? "edit" : "new"` for the dual-route overload). `paramsExpr` is the
404
- * params source (`"undefined"` for a paramless route, `"params"` otherwise); `nullable` is
405
- * true only when that source may itself be `undefined` (the all-optional-params overload),
406
- * gating the `?? {}` guard that TS2871 would otherwise flag on a required param.
407
- */
408
- const pushBlock = (routeNameExpr: string, paramsExpr: string, nullable: boolean): string[] => {
409
- const routerType = `{ ${ROUTER_GLOBAL_NAME}?: { push: (to: { name: string; params: Record<string, unknown> }) => Promise<unknown>; resolve: (to: { name: string; params: Record<string, unknown> }) => { href: string } } }`;
410
- const routeParamsLine = paramsExpr === "undefined"
411
- ? "const routeParams = {};"
412
- : nullable
413
- ? `const routeParams = Object.fromEntries(Object.entries(${paramsExpr} ?? {}).filter(([, v]) => v !== undefined));`
414
- : `const routeParams = Object.fromEntries(Object.entries(${paramsExpr}).filter(([, v]) => v !== undefined));`;
415
- return [
416
- routeParamsLine,
417
- `const isCold = await this.page.evaluate(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} === "undefined");`,
418
- `if (isCold) {`,
419
- ` await this.page.goto("/", { waitUntil: "commit" });`,
420
- ` await this.page.waitForFunction(() => typeof (globalThis as { ${ROUTER_GLOBAL_NAME}?: unknown }).${ROUTER_GLOBAL_NAME} !== "undefined", { timeout: 15000 });`,
421
- ` const href = await this.page.evaluate(({ name, params }) => (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.resolve({ name, params })?.href, { name: ${routeNameExpr}, params: routeParams });`,
422
- ` if (href) { await this.page.goto(href, { waitUntil: "domcontentloaded" }); }`,
423
- `} else {`,
424
- ` await this.page.evaluate(async ({ name, params }) => {`,
425
- ` await (globalThis as ${routerType}).${ROUTER_GLOBAL_NAME}?.push({ name, params });`,
426
- ` }, { name: ${routeNameExpr}, params: routeParams });`,
427
- `}`,
428
- ];
429
- };
416
+ function requireRouteName(route: RouteEntry): string {
417
+ if (route.name === null) {
418
+ throw new VuePomGeneratorError(`Named navigation requires a route name for template "${route.template}".`);
419
+ }
420
+ return route.name;
421
+ }
430
422
 
431
423
  function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null): TypeScriptClassMember[] {
432
424
  // No route metadata: emit a goTo() that fails loudly when invoked.
@@ -460,44 +452,39 @@ function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null):
460
452
  ];
461
453
  }
462
454
 
463
- // Fallback (unnamed routes, e.g. Nuxt file-based routes whose names the static walk
464
- // cannot recover): reconstruct the URL from the tokenized template and `page.goto` it.
465
- const paramStatements = (entry: RouteEntry): string[] => {
466
- const lines: string[] = [];
467
- for (const param of entry.params) {
468
- const token = getParamToken(param.name);
469
- if (param.optional) {
470
- // An omitted optional param drops its entire path segment (including the leading "/"),
471
- // so `/persons/:personId/:tabName?` with tabName omitted resolves to `/persons/123`.
472
- lines.push(`targetUrl = params.${param.name} === undefined ? targetUrl.replaceAll(${JSON.stringify(`/${token}`)}, "") : targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
473
- }
474
- else {
475
- lines.push(`targetUrl = targetUrl.replaceAll(${JSON.stringify(token)}, String(params.${param.name}));`);
476
- }
477
- }
478
- return lines;
479
- };
480
-
481
455
  // Preferred path: the route is named, so hand the param object straight to the runtime
482
456
  // router. `undefined` values are stripped first — omitted optional params are simply not
483
457
  // passed, and the router builds the URL (handling optional segments, redirects, and param
484
- // coercion) itself. No opaque tokens, no string substitution. See `pushBlock` for the
458
+ // coercion) itself. No opaque tokens, no string substitution. The centralized router writer owns the
485
459
  // cold-start (full-load resolved target) vs warm (SPA `router.push`) regimes.
486
- // Paramless-only: simple no-arg goTo().
460
+ // Paramless-only: query keys, when present, are optional navigation arguments.
487
461
  if (hasParamless && !hasParametrized) {
488
462
  const route = paramless!;
463
+ const hasQuery = route.query.length > 0;
464
+ const paramType = buildNavigationTypeString(route);
489
465
  return [
490
466
  createClassMethod({
491
467
  name: "goTo",
492
468
  isAsync: true,
469
+ parameters: hasQuery ? [{ name: "params", type: paramType, hasQuestionToken: true }] : [],
493
470
  statements: route.name !== null
494
- ? pushBlock(JSON.stringify(route.name), "undefined", false)
495
- : [`const targetUrl = ${JSON.stringify(route.template)};`, ...GOTO_RUNTIME_LINES],
471
+ ? createRouterNavigationWriter({
472
+ routeName: { kind: "single", target: route.name },
473
+ input: hasQuery ? { identifier: "params", optional: true } : undefined,
474
+ pathParamNames: [],
475
+ queryNames: route.query,
476
+ })
477
+ : createUrlNavigationWriter({
478
+ routeTemplate: { kind: "single", target: route.template },
479
+ input: hasQuery ? { identifier: "params", optional: true } : undefined,
480
+ pathParams: [],
481
+ queryNames: route.query,
482
+ }),
496
483
  }),
497
484
  ];
498
485
  }
499
486
 
500
- const paramType = buildParamTypeString(parametrized!.params);
487
+ const paramType = buildNavigationTypeString(parametrized!);
501
488
 
502
489
  // Parametrized-only: goTo(params). When every declared param is optional, the params
503
490
  // object itself is optional too — `goTo()` is a valid call that navigates to the route
@@ -511,8 +498,18 @@ function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null):
511
498
  isAsync: true,
512
499
  parameters: [{ name: "params", type: paramType, hasQuestionToken: allOptional }],
513
500
  statements: route.name !== null
514
- ? pushBlock(JSON.stringify(route.name), "params", allOptional)
515
- : [`let targetUrl = ${JSON.stringify(route.template)};`, ...paramStatements(route), ...GOTO_RUNTIME_LINES],
501
+ ? createRouterNavigationWriter({
502
+ routeName: { kind: "single", target: route.name },
503
+ input: { identifier: "params", optional: allOptional },
504
+ pathParamNames: route.params.map(param => param.name),
505
+ queryNames: route.query,
506
+ })
507
+ : createUrlNavigationWriter({
508
+ routeTemplate: { kind: "single", target: route.template },
509
+ input: { identifier: "params", optional: allOptional },
510
+ pathParams: route.params,
511
+ queryNames: route.query,
512
+ }),
516
513
  }),
517
514
  ];
518
515
  }
@@ -522,30 +519,50 @@ function generateGoToMethod(componentName: string, routeMeta: RouteMeta | null):
522
519
  const paramlessRoute = paramless!;
523
520
  const parametrizedRoute = parametrized!;
524
521
  const usePush = paramlessRoute.name !== null && parametrizedRoute.name !== null;
525
-
522
+ const paramlessType = buildNavigationTypeString(paramlessRoute);
523
+ const parametrizedOverloadType = buildParametrizedRouteSelectionTypeString(parametrizedRoute);
524
+ const queryNames = Array.from(new Set([...paramlessRoute.query, ...parametrizedRoute.query]));
525
+ const hasQuery = queryNames.length > 0;
526
+ const implementationType = hasQuery
527
+ ? buildImplementationNavigationTypeString([paramlessRoute, parametrizedRoute])
528
+ : paramType;
526
529
  return [
527
530
  createClassMethod({
528
531
  name: "goTo",
529
532
  isAsync: true,
530
533
  overloads: [
531
- { parameters: [], returnType: "Promise<void>" },
532
- { parameters: [{ name: "params", type: paramType }], returnType: "Promise<void>" },
534
+ {
535
+ parameters: paramlessRoute.query.length
536
+ ? [{ name: "params", type: paramlessType, hasQuestionToken: true }]
537
+ : [],
538
+ returnType: "Promise<void>",
539
+ },
540
+ { parameters: [{ name: "params", type: parametrizedOverloadType }], returnType: "Promise<void>" },
533
541
  ],
534
- parameters: [{ name: "params", type: paramType, hasQuestionToken: true }],
542
+ parameters: [{ name: "params", type: implementationType, hasQuestionToken: true }],
535
543
  statements: usePush
536
- ? pushBlock(
537
- `params ? ${JSON.stringify(parametrizedRoute.name)} : ${JSON.stringify(paramlessRoute.name)}`,
538
- "params",
539
- true,
540
- )
541
- : [
542
- `const template = params ? ${JSON.stringify(parametrizedRoute.template)} : ${JSON.stringify(paramlessRoute.template)};`,
543
- "let targetUrl = template;",
544
- `if (params) {`,
545
- ...paramStatements(parametrizedRoute).map(line => ` ${line}`),
546
- "}",
547
- ...GOTO_RUNTIME_LINES,
548
- ],
544
+ ? createRouterNavigationWriter({
545
+ routeName: {
546
+ kind: "dual",
547
+ parametrizedTarget: requireRouteName(parametrizedRoute),
548
+ paramlessTarget: requireRouteName(paramlessRoute),
549
+ selectBy: hasQuery ? "path-param-presence" : "input-presence",
550
+ },
551
+ input: { identifier: "params", optional: true },
552
+ pathParamNames: parametrizedRoute.params.map(param => param.name),
553
+ queryNames: hasQuery ? queryNames : [],
554
+ })
555
+ : createUrlNavigationWriter({
556
+ routeTemplate: {
557
+ kind: "dual",
558
+ parametrizedTarget: parametrizedRoute.template,
559
+ paramlessTarget: paramlessRoute.template,
560
+ selectBy: hasQuery ? "path-param-presence" : "input-presence",
561
+ },
562
+ input: { identifier: "params", optional: true },
563
+ pathParams: parametrizedRoute.params,
564
+ queryNames: hasQuery ? queryNames : [],
565
+ }),
549
566
  }),
550
567
  ];
551
568
  }
@@ -10,6 +10,7 @@ interface RouteEntry {
10
10
  name: string | null;
11
11
  template: string;
12
12
  params: RouteParamMeta[];
13
+ query: string[];
13
14
  }
14
15
  interface RouteMeta {
15
16
  /** Shortest route template — used for the static `route` property. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../class-generation/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAkC,oCAAoC,EAAE,MAAM,sBAAsB,CAAC;AAwC5G,OAAO,EACL,sBAAsB,EAOvB,MAAM,UAAU,CAAC;AAQlB,OAAO,EAAE,oCAAoC,EAAE,CAAC;AA2ChD,UAAU,cAAc;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,UAAU,UAAU;IAClB,+FAA+F;IAC/F,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,cAAc,EAAE,CAAC;CAC1B;AAED,UAAU,SAAS;IACjB,sEAAsE;IACtE,QAAQ,EAAE,MAAM,CAAC;IACjB,mFAAmF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AEnC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IAEtB,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;CAClD;AAsCD,wBAAsB,aAAa,CACjC,qBAAqB,EAAE,GAAG,CAAC,MAAM,EAAE,sBAAsB,CAAC,EAC1D,eAAe,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EACpC,iBAAiB,EAAE,MAAM,EACzB,OAAO,GAAE,oBAAyB,iBAqGnC"}
@@ -1,6 +1,46 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const path = require("node:path");
4
+ function includesDataTestId(value) {
5
+ return typeof value === "string" && value.includes("data-testid");
6
+ }
7
+ const noDataTestIdInSpecsRule = {
8
+ meta: {
9
+ type: "problem",
10
+ docs: {
11
+ description: "Disallow raw data-testid strings and getByTestId calls in Playwright specs."
12
+ },
13
+ messages: {
14
+ noDataTestIdInSpecs: "Avoid data-testid in spec files; use a generated POM or fixture accessor instead.",
15
+ noGetByTestIdInSpecs: "Avoid getByTestId(...) in spec files; use a generated POM or fixture accessor instead."
16
+ },
17
+ schema: []
18
+ },
19
+ create(context) {
20
+ return {
21
+ Literal(node) {
22
+ if (includesDataTestId(node.value)) {
23
+ context.report({ node, messageId: "noDataTestIdInSpecs" });
24
+ }
25
+ },
26
+ TemplateLiteral(node) {
27
+ const staticText = node.quasis.map((quasi) => quasi.value.cooked).join("");
28
+ if (includesDataTestId(staticText)) {
29
+ context.report({ node, messageId: "noDataTestIdInSpecs" });
30
+ }
31
+ },
32
+ CallExpression(node) {
33
+ if (node.callee.type !== "MemberExpression")
34
+ return;
35
+ const callee = node.callee;
36
+ const isGetByTestId = !callee.computed ? callee.property.type === "Identifier" && callee.property.name === "getByTestId" : callee.property.type === "Literal" && callee.property.value === "getByTestId";
37
+ if (isGetByTestId) {
38
+ context.report({ node, messageId: "noGetByTestIdInSpecs" });
39
+ }
40
+ }
41
+ };
42
+ }
43
+ };
4
44
  const DIRECT_TEST_CALLS = /* @__PURE__ */ new Set(["test", "it"]);
5
45
  const TEST_WRAPPER_CALLS = /* @__PURE__ */ new Set(["only", "skip", "fixme", "fail"]);
6
46
  const TEST_HOOK_CALLS = /* @__PURE__ */ new Set(["beforeEach", "beforeAll", "afterEach", "afterAll"]);
@@ -318,12 +358,14 @@ const noRawLocatorActionRule = {
318
358
  };
319
359
  const plugin = {
320
360
  rules: {
361
+ "no-data-testid-in-specs": noDataTestIdInSpecsRule,
321
362
  "no-page-fixture-in-specs": noPageFixtureInSpecsRule,
322
363
  "no-raw-locator-action": noRawLocatorActionRule,
323
364
  "no-raw-playwright-apis": noRawPlaywrightApisRule,
324
365
  "remove-existing-test-id-attributes": removeExistingTestIdAttributesRule
325
366
  }
326
367
  };
368
+ exports.noDataTestIdInSpecsRule = noDataTestIdInSpecsRule;
327
369
  exports.noPageFixtureInSpecsRule = noPageFixtureInSpecsRule;
328
370
  exports.noRawLocatorActionRule = noRawLocatorActionRule;
329
371
  exports.noRawPlaywrightApisRule = noRawPlaywrightApisRule;