Repository navigation
fix(api): export Resolver, GraphqlContext and helper types from the public entry - #3474
Conversation
…ublic entry `Resolver`, `Options`, `FeatureFlags`, `PromiseType` and `ArrayElementType` were ambient (script-scoped) declarations in `src/typings/globals.ts`. Ambient types are not reachable from the emitted `index.d.ts`, so stores importing `GraphqlResolver`/`APIOptions` saw them silently degrade to implicit `any` under `strict: true`, and `GraphqlContext` was not exported at all. Turn `globals.ts` into a real module, import the helpers explicitly where they are used, and re-export `GraphqlContext`, `Resolver` and the helper types from the package entry so the published typings are self-contained. Add a unit test that compiles a consumer against the entrypoint with strict/noImplicitAny and asserts the resolver parameters are properly typed.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Essentials Run ID: 📒 Files selected for processing (28)
Included review availability: 4 reviews are currently available. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour. WalkthroughThe API package now emits and exports shared TypeScript helpers, GraphQL context, options, feature flags, and resolver types. VTEX modules use explicit type-only imports. New consumer compilation tests validate public typing behavior. ChangesPublic API typings
Estimated code review effort: 3 (Moderate) | ~20 minutes Merge Risk: ⚪ Minimal · up to This PR corrects public TypeScript exports without changing runtime behavior; no actionable merge-blocking risk remains after normal checks and review. Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
Type-checking the whole package graph twice, with every @types/* package loaded, took over 5s under coverage instrumentation and timed out in CI. Compile both consumer snippets in a single program with `types: []` and give the setup an explicit budget for slow runners.
Stores that extend the API (e.g. Whirlpool) type their resolvers with the `Resolver<Root, Args, Return>` signature that `@faststore/api@3` exported. In v4 the internal `Resolver` became a 4-parameter generic with the context first, so re-exporting it as-is would still break those stores (`Resolver<unknown, Args>` -> "unknown does not satisfy Record<string, any>", `Parameters<Resolver>[2]` -> "requires between 1 and 4 type arguments"). Export `Resolver` as an alias of `GraphqlResolver` with the v3 signature instead, so existing custom resolvers type-check without changes. Validated against the 16 resolver files of the Whirlpool monorepo: 115 errors on 4.6.0 -> 0 with this build.
|
hellofanny
left a comment
There was a problem hiding this comment.
Tested locally.
Confirmed the root cause is real: built packages/api on dev and checked the emitted dist/src/index.d.ts — export type APIOptions = Options; has zero import for Options anywhere in the file, a dangling ambient reference that skipLibCheck (Next's default) silently resolves to any. After checking out this branch and rebuilding, the same file now has proper import { Options } from './typings/globals' / import { GraphqlResolver } from './platforms/vtex' at the top.
Ran:
pnpm test → 284 unit + 55 integration tests passing, including the new publicTypings.test.ts (correctly rejects source.doesNotExist/ctx.doesNotExist with TS2339)
pnpm exec tsc --noEmit → clean
pnpm build → succeeds; .d.ts output diffed against dev as above
Also checked:
No naming collisions from the newly exported types (GraphqlContext, ArrayElementType, FeatureFlags, PromiseType, Resolver) against anything already re-exported via export * in index.ts
packages/core, the only in-repo consumer of @faststore/api, only uses APIOptions — unaffected
No regressions found. This is type-only, no runtime paths touched, and the fix does what it claims.
One non-blocking note: the public Resolver<TRoot, TArgs, TReturn> alias in index.ts is a deliberate v3-compat shim over the internal 4-param Resolver in globals.ts — worth a quick mental note for whoever touches this file next that there are now two Resolver types with different signatures, but it's well-tested (Whirlpool: 115→0 errors) and clearly commented.
(o codesandbox tá demorando p/ criar o package p/ testar 🙈 )
…3481) ## What's the purpose of this pull request? `@faststore/api` maintains two helpers that stores writing API extensions need, but does not export them: | Helper | What it does | | --- | --- | | `validateUserAuthentication(ctx)` | Calls `commerce.vtexid.validate()` and throws `UnauthorizedError` / `ForbiddenError` based on the result | | `getAuthCookie(cookies, account)` | Normalizes the cookie string and returns `VtexIdclientAutCookie_{account}` | Because neither `utils/auth` nor `utils/cookies` is re-exported from `packages/api/src/index.ts`, a custom resolver under `src/graphql/vtex/resolvers` cannot import either one — so every project rewrites them, and the copies drift. `getAuthCookie` is the sharp edge: the shipped version normalizes duplicated cookie keys to the last value and parses the cookie properly, while a hand-written `split('=')[1]` truncates any token containing `=` and fails as a `401` that is tedious to trace back. Closes #3480. ## How it works? Two lines added to the package entrypoint: ```ts export { validateUserAuthentication } from './platforms/vtex/utils/auth' export { getAuthCookie } from './platforms/vtex/utils/cookies' ``` Additive only — no existing export or behavior changes. `GraphqlContext`, the argument type of `validateUserAuthentication`, is already public (#3474), so the helper is usable with full typing from a store resolver: ```ts import { getAuthCookie, validateUserAuthentication } from '@faststore/api' import type { GraphqlContext } from '@faststore/api' export const myResolver = async (_: unknown, __: unknown, ctx: GraphqlContext) => { await validateUserAuthentication(ctx) const token = getAuthCookie(ctx.headers.cookie ?? '', ctx.account) // forward `token` to a VTEX API } ``` `test/unit/publicExports.test.ts` pins the two exports to the entrypoint so a later refactor of the module layout cannot silently drop them, and covers the behavior that motivated the request: `getAuthCookie` keeps `=` inside the token, keeps the last value for a duplicated cookie key, and returns `''` when the account has no auth cookie; `validateUserAuthentication` resolves on success, throws `UnauthorizedError` on a failed validation and `ForbiddenError` on a 403 from VtexId. ## How to test it? - `cd packages/api && pnpm test:unit` — 23 files / 292 tests pass, including the 8 new ones. - Typecheck: `pnpm tsc --noEmit -p packages/api/tsconfig.json` is clean. - In a store, import both helpers from `@faststore/api` inside a custom resolver and confirm they resolve and type-check. ### Starters Deploy Preview Not applicable — no runtime or rendering change. ## References - Issue #3480 - PR #3474 — exported `GraphqlContext` / `Resolver`, the typing half of the same gap - [Extending API schemas](https://developers.vtex.com/docs/guides/faststore/api-extensions-extending-api-schema) ## Checklist - [x] PR title and commit messages follow Conventional Commits - [x] PR description - [ ] Dependencies — no package changes, no lockfile update needed <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Publicly exposes authentication validation and authentication-cookie utilities through the API package. * **Tests** * Added coverage for cookie extraction, duplicate and missing cookies, authentication outcomes, and forbidden-access error handling. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
) ## What's the purpose of this pull request? A store cloned under a directory whose name contains a space (e.g. `/Users/me/My Store/store`, `C:\Users\John Doe\...`) cannot run `faststore build` / `faststore dev` / `faststore generate`: ``` [STARTED] Load GraphQL documents [FAILED] Failed to load documents from /Users/me/My Store/store/.faststore/src/**/*.{ts,tsx},!/Users/me/My Store/store/.faststore/@generated/: [FAILED] Failed to parse the GraphQL document. Syntax Error: Unexpected character: "/". ``` This had been assumed fixed by #3454 — it is not: #3454 fixed the `next` binary resolution, this is a different failure in the GraphQL codegen step. Reproduced on `4.6.0` and on `dev` (`4.7.1-dev.2`) with a real Yarn 1 workspaces store cloned under a path with a space. Root cause: `generate-types.ts` passed the codegen `documents` glob and the `generates` output dir as **absolute paths**. `@graphql-tools/load` (`isDocumentString`) treats any pointer that contains whitespace and is not parseable SDL as a broken inline document and throws instead of falling through to the glob loader. The `@graphql-codegen/client-preset` also appends `!<outputDir>` to the documents, so the output dir hit the same check. ## How it works? - New `getCodegenPointers(root, cwd = process.cwd())` builds the `documents` glob, the `schema` path and the output dir **relative to the directory codegen resolves pointers from**, so the parent directories (where the space lives) are never part of the pointer: - `.faststore/src/**/*.{ts,tsx}` / `.faststore/@generated/schema.graphql` / `.faststore/@generated/` - Glob-special characters in the relative segments are still escaped (`globby.convertPathToPattern`, same approach as #3454 for the typeDefs glob); the schema and output dir are plain paths, not globs, so they are not escaped. - Symlinks are resolved on both sides (`/var` → `/private/var` on macOS) so the relative path does not climb back through the parents. - `genTsTypes` now awaits the codegen run (it was fire-and-forget). - CLI `vitest.config.ts`: alias `graphql` to its CJS build. The code under test and the externalized `@graphql-tools/*` otherwise load two `graphql` instances and fail `instanceof` checks ("Duplicate graphql modules"), which made an end-to-end test of the generator impossible. No behaviour change for paths without spaces: the same files are matched and written, only the pointer form changes. ## How to test it? - `cd packages/cli && pnpm test` — 177 tests. New in `generate-types.test.ts`: - `getCodegenPointers` never embeds the absolute project path, targets `.faststore` when present, escapes glob-special characters only in the glob. - `genTsTypes` end-to-end from a store under `<tmp>/faststore gen (x86) XXXX/store`: merges a custom `thirdParty` typeDef and generates `graphql.ts` containing the query type. - Manual: clone any store into a directory with a space, install this CLI build and run `yarn build`. On `dev` it fails at "Load GraphQL documents"; with this branch the generate step completes. ### Starters Deploy Preview Pending CodeSandbox / pkg.pr.new build for this PR. ## References - #3454 (`next` binary resolution — different issue, same symptom family) - Companion PRs (independent): #3474, #3475, #3477 Made with [Cursor](https://cursor.com) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved CLI TypeScript type generation for projects located in paths containing spaces, special characters, or symlinks. * Ensured type generation completes reliably before the CLI proceeds. * **Tests** * Expanded automated coverage for schema discovery, path handling, and generated TypeScript output. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
## What's the purpose of this pull request? Graduation of the `dev` prerelease cycle (`4.8.0-dev.8`) into a stable `4.8.0` release on `main`. Merging this PR triggers the `release` CD workflow, which runs `lerna version --conventional-graduate --force-conventional-graduate` and publishes all 8 `@faststore/*` packages under the `latest` dist-tag. The bump is decided by the Conventional Commits accumulated on `dev` (`feat:` → **minor** `4.8.0`). No unmerged hotfixes on `main`. ## How it works? No new product code in this PR itself — it is the merge of `dev` into `main`. After merge, CD graduates `4.8.0-dev.8` → `4.8.0`. ### Highlights (features) * feat(core): add mini cart recommendation shelf ([#3466](#3466)) * feat(api): export `validateUserAuthentication` and `getAuthCookie` ([#3481](#3481)) ### Fixes * fix(core): align the saved-cards list with the design reference ([#3487](#3487)) * fix: stop retrying upstream 429 responses ([#3453](#3453)) * fix: normalize outputFileTracingRoot to forward slashes on Windows ([#3484](#3484)) * fix: forward contentSource.project as --storeId in cms-sync CP flow ([#3482](#3482)) * fix: generate GraphQL types when the project path contains spaces ([#3476](#3476)) * fix: keep store stories and Jest mocks out of the .faststore type-check ([#3477](#3477)) * fix(api): export Resolver, GraphqlContext and helper types from the public entry ([#3474](#3474)) * fix: stop forwarding unvalidated ni output to the shell in the CLI ([#3422](#3422)) * fix: point localized canonical and hreflang at the rendered locale ([#3470](#3470)) ## Packages published (latest) `@faststore/{api,cli,components,core,diagnostics,lighthouse,sdk,ui}` → `4.8.0` ## How to test it? * CI green on this PR * After merge, `release` workflow succeeds on `main` * All 8 packages report `4.8.0` under the `latest` dist-tag on npm * Back-merge `main` → `dev` to open the next dev cycle ## Checklist **PR Title and Commit Messages** * PR title and commit messages follow the Conventional Commits specification **PR Description** * Added a label according to the PR goal **Dependencies** * No extra lockfile changes in this graduation PR <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added configurable product recommendations to the cart drawer, including campaign selection, carousel options, titles, and product-card customization. * Added public authentication utilities, GraphQL types, and resolver typings. * **Bug Fixes** * Improved localized canonical and hreflang URLs across storefront pages. * Prevented automatic retries for rate-limit responses. * Improved CLI handling of package managers, Windows paths, spaces, and CMS Sync store IDs. * **Documentation** * Updated package changelogs and recommendation-shelf guidance. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Válber Laux <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Thiago Pereira <[email protected]> Co-authored-by: eduardoformiga <[email protected]> Co-authored-by: vtexgithubbot <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Larícia Mota <[email protected]> Co-authored-by: Arthur Andrade <[email protected]>

0 New Issues
0 Fixed Issues
0 Accepted Issues
No data about coverage (37.40% Estimated after merge)
What's the purpose of this pull request?
Stores extending the BFF with custom resolvers hit three related typing problems on v4:
GraphqlResolver<S>degrades its parameters to implicitanyunderstrict: true,GraphqlContextcannot be imported from@faststore/api, andStoreProductRootcollapses toany.Root cause:
Resolver,Options,FeatureFlags,PromiseTypeandArrayElementTypewere ambient (script-scoped) declarations insrc/typings/globals.ts. Ambient types are not reachable from the emitteddist/src/index.d.ts, so the published typings referenced names that consumers could not resolve — and withskipLibCheck: true(which Next enables) TypeScript silently treated them asany.How it works?
src/typings/globals.tsbecomes a real module (export type/export interface).src/, 6 undertest/;local/server.mjsJSDoc now points atAPIOptions).src/index.tsre-exportsGraphqlContext,PromiseType,ArrayElementTypeandFeatureFlagsalongside the existingGraphqlResolver/APIOptions.src/index.tsalso exportsResolverwith the signature@faststore/api@3had publicly —Resolver<Root = unknown, Args = unknown, Return = any>, context fixed toGraphqlContext(an alias ofGraphqlResolver). v4 silently dropped that export and turned the internalResolverinto a 4-parameter generic with the context first; re-exporting the internal one would still break stores written against v3 (Resolver<unknown, Args>→ "unknown does not satisfy Record<string, any>",Parameters<Resolver>[2]→ "requires between 1 and 4 type arguments"). Validated against a real v3 store with 16 custom resolver files: 115 type errors on 4.6.0 → 0 with this branch, with no changes on the store side.test/unit/publicTypings.test.tscompiles a consumer snippet against the package entrypoint withstrict+noImplicitAnythrough the TypeScript compiler API and asserts (a) valid usage compiles with zero diagnostics and (b)source.doesNotExist/ctx.doesNotExistare rejected with TS2339 — i.e. the types did not collapse toany.No runtime change: everything touched is type-only. Deliberately not included: changing the
GraphqlResolver<S = any, ...>defaults tounknown. That is a public-signature change that could break stores writingconst r: GraphqlResolver = (source) => source.foowithout typingS; it should be a separate, explicitly approved follow-up.How to test it?
cd packages/api && pnpm test(284 unit tests, including the newpublicTypings.test.ts, which also covers the v3-styleResolver<Root, Args, Return>andParameters<Resolver>[2]patterns)cd packages/api && pnpm exec tsc --noEmit -p tsconfig.json(clean)cd packages/api && pnpm build, then checkdist/src/index.d.ts— it now containsimport { Options } from './typings/globals'instead of dangling references, anddist/src/platforms/vtex/index.d.tsimportsFeatureFlags, Options, Resolverexplicitly.packages/core), a file such as:compiles under
--strict --noImplicitAny(the@ts-expect-erroris honoured).Starters Deploy Preview
Pending CodeSandbox build for this PR.
References
.faststore)Made with Cursor
Summary by CodeRabbit
New Features
Bug Fixes
Tests