Skip to content

Conversation

@kingston
Copy link
Collaborator

@kingston kingston commented May 2, 2025

Summary by CodeRabbit

  • New Features

    • Added a locality-based topological sort utility and a function to sort object keys alphabetically.
    • Introduced utilities for merging TypeScript code fragments with dependencies to improve code generation.
  • Enhancements

    • Refactored Pothos and Prisma generators to use new code fragment abstractions, improving modularity and maintainability.
    • Improved error message formatting in the application UI.
    • Updated Fastify and Yoga GraphQL generators with enhanced configuration, import management, and template rendering.
    • Unified code generation patterns using typed code fragments and import builders.
  • Bug Fixes

    • Enhanced canonical path handling in change detection logic.
    • Normalized file paths in filtering post-write commands and improved import resolution.
  • Documentation

    • Expanded and reorganized the code style guide for clarity.
    • Added comprehensive tests for new utilities including topological sort and object key sorting.
  • Chores

    • Reorganized exports in utility and provider modules for better maintainability.
    • Removed deprecated provider files and consolidated exports across the codebase.

@linear
Copy link

linear bot commented May 2, 2025

@changeset-bot
Copy link

changeset-bot bot commented May 2, 2025

🦋 Changeset detected

Latest commit: 3211cfe

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 13 packages
Name Type
@halfdomelabs/utils Patch
@halfdomelabs/baseplate-plugin-storage Patch
@halfdomelabs/project-builder-server Patch
@halfdomelabs/fastify-generators Patch
@halfdomelabs/sync Patch
@halfdomelabs/core-generators Patch
@halfdomelabs/create-project Patch
@halfdomelabs/project-builder-cli Patch
@halfdomelabs/project-builder-lib Patch
@halfdomelabs/project-builder-test Patch
@halfdomelabs/project-builder-web Patch
@halfdomelabs/react-generators Patch
@halfdomelabs/project-builder-common Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented May 2, 2025

Walkthrough

This set of changes introduces substantial refactoring and feature expansion across the codebase, focusing on code generation, utility enhancements, and improved modularity. The Pothos and Prisma generator systems are reworked to use a new TypeScript fragment abstraction (TsCodeFragment) and dependency management via topological sorting, replacing legacy expression-based representations. Numerous interfaces, provider patterns, and code fragment utilities are updated or replaced to support more robust, ordered, and maintainable code generation. New utility functions such as sortObjectKeys and a locality-sensitive topological sort (toposortLocal) are added, along with comprehensive test suites for these utilities. The exports and internal structure of provider and writer modules are reorganized for clarity and modularity. Template-based code generation for GraphQL Yoga and Fastify plugins is expanded, with new error handling, logging, and WebSocket integration features. Additional changes include improved error message sanitization, styling enhancements for UI error displays, and the removal or migration of deprecated provider modules.

Changes

File(s) / Path(s) Change Summary
.changeset/... Added changeset files documenting patch updates and new utility functions.
packages/utils/src/toposort/toposort-local.ts, .../toposort-local.unit.test.ts Introduced toposortLocal, a locality-based topological sort function, with comprehensive tests.
packages/utils/src/objects/sort-object-keys.ts, .../sort-object-keys.unit.test.ts Added sortObjectKeys utility and corresponding tests for sorting object keys.
packages/utils/src/toposort/index.ts, packages/utils/src/objects/index.ts Extended exports to include new utilities (toposortLocal, sortObjectKeys).
packages/utils/src/index.ts, packages/utils/src/type-guards/index.ts, .../not-empty.ts Added and documented notEmpty type guard, updated exports for type guards.
packages/core-generators/src/renderers/typescript/fragments/utils.ts, .../utils.unit.test.ts Refactored fragment flattening to use dependency graphs and topological sort; updated tests to match new ordering logic.
packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.ts, .../unit.test.ts Introduced utility to merge code fragments with colocated dependencies and tests.
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts, .../unit.test.ts Updated import paths, exported additional functions, added case-insensitive sorting option.
packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.ts, .../unit.test.ts Added new action for rendering TypeScript code fragments and its tests.
packages/core-generators/src/renderers/typescript/actions/index.ts, .../ts-template-file-action.ts, .../unit.test.ts Updated and extended exports, adjusted type enforcement for import map providers, updated related tests.
packages/core-generators/src/generators/node/typescript/typescript.generator.ts Added support for rendering TypeScript template fragments and resolving module specifiers.
packages/core-generators/src/generators/node/ts-utils/ts-utils.generator.ts, .../ts-extractor.json Added type export and configuration for TypeScript utilities.
packages/core-generators/src/renderers/typescript/extractor/preprocess-code-for-extraction-hack.ts, .../test.ts Added new transformation pattern for template markers and corresponding test.
packages/core-generators/src/renderers/typescript/extractor/organize-ts-template-imports.ts Excluded Node.js built-in modules and 'ws' from import modification.
packages/core-generators/src/renderers/typescript/extractor/ts-template-file-extractor.ts, .../write-ts-project-exports.ts Updated import paths for utility modules.
packages/core-generators/src/renderers/typescript/index.ts, .../utils/index.ts Changed and added utility re-exports for centralized imports.
packages/fastify-generators/src/generators/pothos/_providers/pothos-type-output.ts, .../pothos-field.ts, .../index.ts Added new provider interfaces and centralized exports for Pothos field and type output providers.
packages/fastify-generators/src/generators/pothos/index.ts, .../providers/index.ts, .../providers/pothos-type.ts Switched provider export paths, removed deprecated provider files.
packages/fastify-generators/src/generators/pothos/pothos-authorize-field/pothos-authorize-field.generator.ts Updated import path for field provider.
packages/fastify-generators/src/generators/pothos/pothos-auth/pothos-auth.generator.ts Refactored to use new providers, modularized config setup, updated code fragment handling.
packages/fastify-generators/src/generators/pothos/pothos-enums-file/pothos-enums-file.generator.ts Refactored to use TsCodeFragment, simplified import logic, changed enum handling to use maps and fragments.
packages/fastify-generators/src/generators/pothos/pothos-prisma-crud-mutation/pothos-prisma-crud-mutation.generator.ts, .../pothos-prisma-find-query.generator.ts, .../pothos-prisma-list-query.generator.ts, .../pothos-prisma-object.generator.ts, .../pothos-prisma-primary-key.generator.ts Refactored to use fragments, added ordering, improved dependency handling, updated type references and registration logic.
packages/fastify-generators/src/generators/pothos/pothos-prisma-enum/pothos-prisma-enum.generator.ts Updated to use new utilities and providers for enum generation.
packages/fastify-generators/src/generators/pothos/pothos-prisma/pothos-prisma.generator.ts Updated to use fragment-based configuration and imports, removed deprecated utilities.
packages/fastify-generators/src/generators/pothos/pothos-scalar/pothos-scalar.generator.ts Refactored to use explicit providers, updated template handling, improved dependency management.
packages/fastify-generators/src/generators/pothos/pothos-types-file/pothos-types-file.generator.ts Refactored type handling, added ordering, updated provider interface, and improved code composition.
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts Replaced custom provider/config with new config provider task, modularized config and schema handling.
packages/fastify-generators/src/generators/pothos/pothos-auth/templates/FieldAuthorizePlugin/global-types.ts, .../index.ts Reordered and cleaned up imports, updated import sources.
packages/fastify-generators/src/generators/pothos/pothos/templates/FieldWithInputPayloadPlugin/global-types.ts, .../index.ts, .../schema-builder.ts, .../builder.ts Updated import orders, changed placeholder tokens, adjusted template placeholders.
packages/fastify-generators/src/generators/pothos/pothos-scalar/templates/date-time.ts, .../date.ts, .../uuid.ts Updated import sources for error handler and builder.
packages/fastify-generators/src/generators/prisma/_shared/crud-method/data-method.ts, .../embedded-relation-transformer/embedded-relation-transformer.generator.ts, .../prisma-crud-create/prisma-crud-create.generator.ts, .../prisma-crud-delete/prisma-crud-delete.generator.ts, .../prisma-crud-update/prisma-crud-update.generator.ts Consolidated imports for notEmpty, refactored method reference handling to use fragments.
packages/fastify-generators/src/generators/core/service-file/service-file.generator.ts Changed notEmpty import source to external utility package.
packages/fastify-generators/src/generators/core/error-handler-service/error-handler-service.generator.ts Added re-export for error handler service imports provider.
packages/fastify-generators/src/generators/core/fastify-redis/fastify-redis.generator.ts, .../templates/mock-redis.ts, .../templates/redis.ts Refactored generator to modular tasks, updated import handling, centralized redis path, updated template imports.
packages/fastify-generators/src/generators/core/fastify-sentry/fastify-sentry.generator.ts, .../templates/instrument.ts, .../templates/services/sentry.ts Refactored to use config provider pattern, modularized fragment/integration management, updated template placeholders and imports.
packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts, .../templates/db.test-helper.ts, .../templates/prisma.test-helper.ts Split generator into modular tasks, improved import management, updated template variable handling.
packages/fastify-generators/src/generators/yoga/yoga-plugin/yoga-plugin.generator.ts, .../templates/graphql-plugin.ts, .../templates/plugins/graphql/index.ts, .../plugins/graphql/pubsub.ts, .../plugins/graphql/useGraphLogger.ts, .../plugins/graphql/websocket.ts, .../pubsub.ts, .../useGraphLogger.ts, .../websocket-fragments.ts, .../websocket.ts Refactored Yoga plugin generator and templates for fragment-based code generation, improved logging, error handling, WebSocket and PubSub integration, and modularized plugin setup.
packages/fastify-generators/src/types/service-output.ts Updated interface to use TsCodeFragment for method references.
packages/fastify-generators/src/writers/pothos/args.ts, .../definitions.ts, .../helpers.ts, .../input-types.ts, .../object-types.ts, .../options.ts, .../resolvers.ts, .../scalar-fields.ts Refactored to use TsCodeFragment and new fragment utilities, updated type definitions, removed deprecated container class, unified fragment/dependency handling.
packages/fastify-generators/src/writers/index.ts Added export for Pothos writers.
packages/fastify-generators/src/index.ts Changed exports to remove providers and add writers.
packages/fastify-generators/src/providers/index.ts, .../pothos-type.ts, .../generators/pothos/providers/index.ts Removed deprecated provider index and type files.
packages/project-builder-server/src/compiler/backend/graphql.ts Added explicit IDs and ordering to generator bundles and children, updated function signatures.
packages/project-builder-server/src/sync/build-project.ts Sanitized error messages by stripping VT control characters.
packages/project-builder-web/src/app/ProjectSyncModal/ApplicationCard.tsx Enhanced error message display with whitespace and monospace styling.
plugins/baseplate-plugin-storage/src/generators/fastify/storage-module/storage-module.generator.ts Migrated input type registration to new config provider, updated module/type assignment logic.
packages/react-generators/src/generators/apollo/react-apollo/react-apollo.generator.ts Switched to toposortLocal for ordering Apollo links.

Sequence Diagram(s)

Locality-Based Topological Sort (toposortLocal)

sequenceDiagram
    participant Caller
    participant toposortLocal
    participant Helpers

    Caller->>toposortLocal: Call with (nodes, edges, options)
    toposortLocal->>Helpers: makeInboundEdges(nodes, edges)
    toposortLocal->>Helpers: makeNodeOutDegrees(inboundEdges)
    toposortLocal->>Helpers: detectCycle(inboundEdges)
    alt No cycle detected
        toposortLocal->>toposortLocal: Initialize stack with nodes of out-degree 0
        loop While stack not empty
            toposortLocal->>toposortLocal: Pop node, add to result
            toposortLocal->>toposortLocal: For each inbound edge, decrement out-degree
            toposortLocal->>toposortLocal: If out-degree is 0, push to stack
        end
        toposortLocal->>Caller: Return sorted nodes
    else Cycle detected
        toposortLocal->>Caller: Throw ToposortCyclicalDependencyError
    end
Loading

Merging Code Fragments with Colocated Dependencies

sequenceDiagram
    participant Caller
    participant mergeFragmentsWithColocatedDependencies
    participant FlattenHelpers
    participant ToposortLocal

    Caller->>mergeFragmentsWithColocatedDependencies: Call with rootFragments
    mergeFragmentsWithColocatedDependencies->>FlattenHelpers: Flatten all fragments and dependencies
    FlattenHelpers->>mergeFragmentsWithColocatedDependencies: Return fragments, dependencies
    mergeFragmentsWithColocatedDependencies->>ToposortLocal: toposortLocal(fragments, dependencies)
    ToposortLocal-->>mergeFragmentsWithColocatedDependencies: Sorted fragment order
    mergeFragmentsWithColocatedDependencies->>mergeFragmentsWithColocatedDependencies: Merge fragments, imports, and hoisted fragments
    mergeFragmentsWithColocatedDependencies->>Caller: Return merged TsCodeFragment
Loading

Pothos Generator Task Refactoring

sequenceDiagram
    participant BuildTask
    participant ConfigProvider
    participant TypeScriptFileProvider
    participant FragmentUtils

    BuildTask->>ConfigProvider: Register plugins, enums, input types, schema files
    BuildTask->>FragmentUtils: Merge fragments and dependencies (toposort)
    BuildTask->>TypeScriptFileProvider: renderTemplateFragment(mergedFragment, id, destination)
    TypeScriptFileProvider->>BuildTask: File written
Loading

Yoga Plugin GraphQL Handler Generation

sequenceDiagram
    participant Generator
    participant TypeScriptFileProvider
    participant TemplateEngine

    Generator->>TemplateEngine: Prepare template variables and fragments
    Generator->>TypeScriptFileProvider: renderTemplateFile(template, variables, importMapProviders)
    TypeScriptFileProvider->>Generator: File written
Loading

These diagrams illustrate the core interactions for the new locality-based topological sort, merging code fragments with dependencies, the refactored generator task flow, and template-based code generation for GraphQL plugins.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 31

🔭 Outside diff range comments (6)
packages/fastify-generators/src/generators/pothos/pothos-auth/templates/FieldAuthorizePlugin/index.ts (1)

85-87: ⚠️ Potential issue

Potential bug in error checking logic.

There appears to be an issue in the error checking logic. The condition r.status === 'rejected' && !(r.reason instanceof ForbiddenError) is identical to the one used for unexpectedError at lines 77-79. This likely should be checking for instances of ForbiddenError rather than non-instances.

-  const forbiddenError = results.find(
-    (r) => r.status === 'rejected' && !(r.reason instanceof ForbiddenError),
-  ) as PromiseRejectedResult;
+  const forbiddenError = results.find(
+    (r) => r.status === 'rejected' && (r.reason instanceof ForbiddenError),
+  ) as PromiseRejectedResult;
packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts (1)

30-35: ⚠️ Potential issue

extractPackageVersions on custom package names can return undefined
FASTIFY_PACKAGES does not list vitest-mock-extended or pg-connection-string; if so,
extractPackageVersions injects a dependency with an undefined version → invalid package.json.

Either:

dev: {
-  ...extractPackageVersions(FASTIFY_PACKAGES, [...]),
+  ...extractPackageVersions(FASTIFY_PACKAGES, [...]),
+  'vitest-mock-extended': '^2',
+  'pg-connection-string': '^5',
},

or extend FASTIFY_PACKAGES.
Failing CI at npm install is expensive; catching it here is cheaper.

packages/fastify-generators/src/writers/pothos/helpers.ts (1)

31-35: ⚠️ Potential issue

Boolean literals should be emitted as code fragments, not raw strings

'true' and 'false' are string literals in the generated code, not booleans. Replace with tsCodeFragment('true') / tsCodeFragment('false') (or booleans if mergeFragmentsAsObject supports them).

- required: fieldOptions.required ? 'true' : undefined,
- nullable: fieldOptions.nullable ? 'true' : undefined,
+ required: fieldOptions.required ? tsCodeFragment('true') : undefined,
+ nullable: fieldOptions.nullable ? tsCodeFragment('true') : undefined,

Otherwise Pothos will receive strings instead of booleans.

packages/fastify-generators/src/generators/pothos/pothos-scalar/pothos-scalar.generator.ts (1)

25-33: ⚠️ Potential issue

sourceType missing from interface

uuid config adds a sourceType property (line 71) which isn’t declared in PothosScalarConfig; this causes it to be typed as never when accessed later and may break consumers.

 interface PothosScalarConfig {
   ...
   outputType: string;
+  sourceType?: string;
   dependencies?: Record<string, string>;
packages/fastify-generators/src/generators/core/fastify-sentry/fastify-sentry.generator.ts (1)

102-110: ⚠️ Potential issue

.ts extension in production --import flag will break at runtime

The prod flag points Node to ./dist/instrument.ts, but after compilation only *.js (or *.mjs) exists in dist.
On Node ≥20 this leads to ERR_MODULE_NOT_FOUND during bootstrap.

-  flag: '--import ./dist/instrument.ts',
+  flag: '--import ./dist/instrument.js',

(Keep the dev flag as *.ts, assuming ts-node or tsx is used in development.)

packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)

224-230: 🛠️ Refactor suggestion

Primitive booleans should be wrapped in tsCodeFragment

DefaultEdgesNullability and DefaultFieldNullability are supplied as raw strings.
TsCodeUtils.mergeFragmentsAsInterfaceContent will quote plain strings, emitting "false" instead of the boolean literal.

-DefaultEdgesNullability: 'false',
-DefaultFieldNullability: 'false',
+DefaultEdgesNullability: tsCodeFragment('false'),
+DefaultFieldNullability: tsCodeFragment('false'),

This silently changes the generated type to the string "false".

♻️ Duplicate comments (1)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)

320-322: Duplicate toSorted usage has the same compatibility risk

Replicate the fix applied above here (and in any other helper that now calls toSorted) to maintain runtime consistency.

🧹 Nitpick comments (36)
packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/pubsub.ts (2)

1-1: Consider avoiding @ts-nocheck if possible.

Using @ts-nocheck disables all TypeScript type checking for this file. While this might be acceptable for a template file, consider using more targeted type assertions or @ts-ignore comments for specific issues instead of disabling checking for the entire file.

-// @ts-nocheck
+// Consider using more targeted type assertions instead

13-22: Consider adding connection cleanup for Redis clients.

The current implementation creates Redis clients but doesn't provide a mechanism to close these connections when the application shuts down. This could potentially lead to resource leaks.

Consider adding a cleanup function that can be called during application shutdown:

export function closePubSub(): void {
  if (cachedPubSub !== null) {
    // Access the Redis clients and close them
    const eventTarget = (cachedPubSub as any).options.eventTarget;
    if (eventTarget?.publishClient?.disconnect) {
      eventTarget.publishClient.disconnect();
    }
    if (eventTarget?.subscribeClient?.disconnect) {
      eventTarget.subscribeClient.disconnect();
    }
    cachedPubSub = null;
  }
}
packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/websocket.ts (1)

212-212: Extracted WebSocket connection handler to template token.

The inline implementation of the onConnect handler has been replaced with a template token TPL_ON_CONNECT. This improves modularity by externalizing the connection initialization logic into a separate template fragment, making it easier to customize and maintain.

Consider adding a comment above the template token to indicate its purpose, especially since this is a critical part of the WebSocket connection handling.

packages/fastify-generators/src/generators/prisma/prisma-crud-create/prisma-crud-create.generator.ts (1)

146-149: Redundant variable shadowing

serviceMethodReference is computed immediately after the methodName declaration and is only used once. Construct it inline when calling getMethodDefinition or rename to avoid the Reference-reference naming pattern for clarity.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/useGraphLogger.ts (2)

43-47: Ensure error objects are properly handled.

When logging errors, ensure that originalError or the error itself is an actual Error object that can be properly handled by the logError function.

Consider adding a type guard or validation:

-      errors.forEach((error: GraphQLError) =>
-        logError(error.originalError ?? error),
-      );
+      errors.forEach((error: GraphQLError) => {
+        const errorToLog = error.originalError ?? error;
+        logError(errorToLog);
+      });

74-77: Add type safety to validation error handling.

The current implementation assumes all validation results are Error objects, but GraphQL validation can return other types of errors.

-          result.forEach((error: Error) => logger.error(error.message));
+          result.forEach((error) => {
+            if (error instanceof Error) {
+              logger.error(error.message);
+            } else {
+              logger.error(String(error));
+            }
+          });
packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.ts (1)

16-44: Simple and effective implementation that leverages existing utilities.

The renderTsFragmentAction function:

  1. Creates a BuilderAction with an execute method
  2. Uses the existing renderTsCodeFileTemplate utility with a simple template containing just the fragment
  3. Writes the rendered result to the specified destination

This implementation is straightforward yet effective, reusing existing infrastructure rather than duplicating functionality.

Consider adding error handling for edge cases:

 execute: (builder) => {
+  if (!fragment) {
+    throw new Error('Fragment is required for rendering');
+  }
   const renderedTemplate = renderTsCodeFileTemplate(
     'TPL_CONTENTS',
     { TPL_CONTENTS: fragment },
     {},
packages/fastify-generators/src/generators/pothos/pothos-enums-file/pothos-enums-file.generator.ts (2)

62-64: Potential duplicate entries in appModule.moduleImports & pothosConfig.schemaFiles

moduleImports/schemaFiles are plain arrays, so repeated generator runs for the same typesPath will append duplicates, which can later surface as duplicate-import errors.

Suggestion: guard with a quick .includes() check.

-if (!appModule.moduleImports.includes(typesPath))
-  appModule.moduleImports.push(typesPath);
-if (!pothosConfig.schemaFiles.includes(typesPath))
-  pothosConfig.schemaFiles.push(typesPath);
+if (!appModule.moduleImports.includes(typesPath)) {
+  appModule.moduleImports.push(typesPath);
+}
+if (!pothosConfig.schemaFiles.includes(typesPath)) {
+  pothosConfig.schemaFiles.push(typesPath);
+}

72-80: Overwriting enums silently can hide mistakes

registerEnum overwrites an existing entry with the same name:

enums.set(pothosEnum.name, pothosEnum);

A typo will silently replace the previous enum and make debugging painful.
Emit an explicit error or warning instead:

- enums.set(pothosEnum.name, pothosEnum);
+ if (enums.has(pothosEnum.name)) {
+   throw new Error(`Enum "${pothosEnum.name}" already registered in ${id}`);
+ }
+ enums.set(pothosEnum.name, pothosEnum);
packages/fastify-generators/src/generators/pothos/pothos-prisma-list-query/pothos-prisma-list-query.generator.ts (1)

48-53: idFields is read but never used

const { idFields } = modelOutput; is extracted and then ignored, triggering lint warnings and confusing readers.

Either use it (e.g. to build default ordering) or drop it:

-const { idFields } = modelOutput;
-
-if (!idFields) {
-  throw new Error(`Model ${modelName} does not have an ID field`);
-}
+// If ID is not actually required, delete the guard; otherwise
+// use `idFields` below and keep the check.
packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts (1)

94-104: allowedImports list is narrower than helpers actually export
db.test-helper.ts exports createTestDatabase, destroyTestDatabase, replaceDatabase, etc.
Limiting to two members causes consumers to fall back to deep-imports later.

Ensure allowedImports matches the full helper API or expose multiple maps.

- allowedImports: ['createTestDatabase', 'destroyTestDatabase'],
+ allowedImports: [
+   'createTestDatabase',
+   'destroyTestDatabase',
+   'replaceDatabase',
+   'createTestDatabaseFromTemplate',
+ ],
packages/fastify-generators/src/writers/pothos/definitions.ts (2)

12-19: Minor wording & typo fix in JSDoc
"declares the a variable with the type""declares a variable for the generated type".

- * A Pothos type definition that declares the a variable with the type.
+ * A Pothos type definition that declares a variable for the generated type.

25-33: Consider making dependencies readonly for immutability
Since fragments are composed once during generation, mutate-free structures help avoid accidental side-effects:

-  dependencies?: PothosTypeDefinition[];
+  readonly dependencies?: readonly PothosTypeDefinition[];
packages/fastify-generators/src/writers/pothos/args.ts (2)

34-36: Propagate scalar-field dependencies as well

For scalar fields the returned object hard-codes dependencies: [].
If either getPothosMethodAndTypeForScalar() or writePothosFieldOptions() embeds nested fragments (e.g. imported scalars, custom input types), those imports/hoisted fragments are captured inside the tsTemplate, but the dependency graph that drives higher-level colocated‐merging logic will not “see” them.

Consider forwarding the union of argOptions?.dependencies ?? [] (if that helper ever returns dependencies) to keep the contract symmetric with the nested-field branch.


67-73: Possible micro-optimisation: skip empty arrays

Object.values(argMap).flatMap((arg) => arg.dependencies ?? []) allocates an intermediate array even when every dependency list is empty.
A tiny optimisation (and readability tweak) would be:

-    dependencies: Object.values(argMap).flatMap(
-      (arg) => arg.dependencies ?? [],
-    ),
+    dependencies: Object.values(argMap)
+      .flatMap(({ dependencies }) => dependencies ?? [])
+      .filter(Boolean),

This filters out empty results early and avoids passing noisy [] further up the pipeline.

packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.ts (2)

127-137: Edge-case: non-deterministic ordering when preserveOrder is false

When preserveOrder is false, root fragments are sorted by name, including the "0-" prefix, whereas dependency fragments get a "1-" prefix.
If two root fragments share a prefix such that their localeCompare result ties (rare but possible with case sensitivity differences), JavaScript’s sort is not stable, leading to non-deterministic output between runs.

Consider using Array.prototype.sort with a fully deterministic tiebreaker, e.g.:

compareFunc: (a, b) => {
  const aKey = getFragmentOrderKey(a);
  const diff = aKey.localeCompare(bKey);
  return diff !== 0 ? diff : a.localeCompare(b); // tiebreak
},

This guarantees the same output regardless of engine optimisations.


142-146: Imports & hoisted fragments of root + dependencies are merged but not deduped

mergeFragmentImportsAndHoistedFragments concatenates arrays. If a dependency graph re-uses the same fragment several times, identical import declarations/hoisted fragments may be emitted multiple times, violating TS/ES “duplicate import” rules.

A trivial fix is to dedupe inside the helper:

imports: Array.from(
  new Map([...fragments.flatMap(f => f.imports ?? [])]
    .map((imp) => [`${imp.from}-${imp.name}`, imp]))
  .values()
),

(or similar). This would keep the responsibility local without ballooning caller complexity.

packages/project-builder-server/src/compiler/backend/graphql.ts (2)

44-55: Non-contiguous order values may produce unstable merges

primaryKey is added with order: 0 and objectType with order: 1.
If primaryKey is undefined (single-field PK, or mutations disabled), the first generated child starts at 1, leaving a gap.
Down-stream utilities that assume contiguous ordering (e.g. Array.sort((a,b)=>a.order-b.order)) will still work, but humans reading the output may be confused.

Consider either:

  • Always generating primaryKey with a harmless noop fragment, or
  • Starting ordering from 0 only for the fragments that are actually emitted.

90-93: hasPrimaryKeyInputType computed twice

The expression ModelUtils.getModelIdFields(model).length > 1 is evaluated both for queries and for mutations.
Caching it in a local constant would avoid duplication and guarantee consistency:

const hasCompositePK = ModelUtils.getModelIdFields(model).length > 1;

hasPrimaryKeyInputType: hasCompositePK,
packages/utils/src/toposort/toposort-local.ts (4)

156-166: Comment contradicts implementation (incoming ≠ outgoing)

The stack collects nodes with zero out-degree (no outgoing edges), yet the comment says “no incoming edges (in-degree == 0)”.
This can mislead future maintainers.

-// Create a stack of nodes with no incoming edges (in-degree == 0)
+// Create a stack of nodes with no outgoing edges (out-degree == 0)

170-176: Mislabelled traversal – it’s DFS, not BFS

The algorithm uses a stack (pop()/push()), which is depth-first order, yet the comment says “Process nodes in BFS order”.


91-98: Typo in variable name and potential undefined behaviour

const unvistedNodeIdx is missing an “i”. More importantly, if dfs never finds a cycle, path may remain empty, leading to ToposortCyclicalDependencyError([]) with no insight.

Consider:

-const unvistedNodeIdx = …
+const unvisitedNodeIdx = …

if (path.length === 0) return [];

145-150: Linear search inside comparator can hurt performance

compareIdx calls compareFunc(nodes[a], nodes[b]) every time a sort is needed.
Because nodes[a] dereferences the original array each time, complex node objects could incur noticeable overhead for large graphs. Caching nodes[a]/nodes[b] before sorting or passing pre-computed keys could improve performance.

packages/fastify-generators/src/writers/pothos/resolvers.ts (1)

59-66: trimStart().startsWith('{') heuristic can wrongly parenthesise fragments

The current logic only guards for a leading {, but:

  1. It fails for whitespace, comments, or multi-line fragments (\n{).
  2. Future structural changes (e.g. wrapping with tsTemplate itself) will break detection.

Consider a utility:

-return tsTemplate`${field.name}: ${arg.name}.${field.name}?.map((${singularize(
-  field.name,
-)}) => ${
-  expression.contents.trimStart().startsWith('{')
-    ? tsTemplate`(${expression})`
-    : expression
-})`;
+const exprToMap = TsCodeUtils.wrapIfObject(expression);
+return tsTemplate`${field.name}: ${arg.name}.${field.name}?.map((${singularize(
+  field.name,
+)}) => ${exprToMap})`;

where wrapIfObject inspects the fragment AST, not plain text.

packages/fastify-generators/src/writers/pothos/helpers.ts (1)

58-61: Minor nit: avoid shadowing with generic fragment variable

Renaming the temporary to resolvedFragment (or similar) clarifies intent and avoids confusion with fragmentOrReference.

packages/fastify-generators/src/generators/pothos/pothos-scalar/pothos-scalar.generator.ts (1)

118-124: Path handling is POSIX-only

path.posix.join forces forward slashes, which breaks on Windows when the path is later used by Node’s resolver (which expects OS-native separators).
Prefer path.join and normalise only the import specifier if necessary.

packages/fastify-generators/src/writers/pothos/scalar-fields.ts (1)

41-41: (Nit) avoid empty argument for .field()
(${fieldOptions ?? ''}) produces .field( ) (note the space) when there are no options.
Not harmful, but you can remove the space by making the interpolation conditional (same pattern as the fix above) for slightly cleaner output.

packages/fastify-generators/src/generators/core/fastify-redis/fastify-redis.generator.ts (2)

65-74: Consider omitting the “.ts” extension in virtual import paths
redisPath is set to '@/src/services/redis.ts'. Most of the code-gen in this repo uses extension-less module specifiers (e.g. '@/src/services/redis').
Carrying the .ts suffix leaks into generated import statements and forces downstream path-mapping to rewrite extensions during emit. Dropping it keeps the import ergonomic and consistent:

-const redisPath = '@/src/services/redis.ts';
+const redisPath = '@/src/services/redis';

90-100: Health-check snippet never closes the Redis connection
getRedisClient() returns a long-lived client, but ping() inside a health-check can leave listeners hanging in test runs.
Consider wrapping the ping in try/finally and optionally calling redisClient.quit() (or re-using an existing singleton) to avoid resource leaks.

packages/fastify-generators/src/writers/pothos/options.ts (1)

24-36: Guard against duplicate type-reference names
createPothosTypeReference does not prevent two references with the same name being added to typeReferences, which can lead to duplicate import identifiers when fragments are merged.

Consider either:

  1. Converting typeReferences to a Map<string, PothosTypeReference> for uniqueness, or
  2. Providing a helper that deduplicates when pushing into the array.

Not blocking for now, but worth addressing before large schemas are generated.

packages/fastify-generators/src/generators/pothos/pothos-prisma-find-query/pothos-prisma-find-query.generator.ts (2)

125-131: Redundant key-sorting followed by disableSort: true

sortObjectKeys(customFields.value()) sorts the keys, but then mergeFragmentsAsObject(options, { disableSort: true }) prevents further sorting.
One of these is unnecessary; prefer letting mergeFragmentsAsObject keep the existing order:

- ...sortObjectKeys(customFields.value()),
+ ...customFields.value(),

133-144: Unused placeholder QUERY_EXPORT in formatFragment

QUERY_EXPORT is supplied but not referenced in the template string, which can be misleading for future maintainers.

Remove the unused parameter or use it explicitly.

packages/fastify-generators/src/generators/pothos/pothos-prisma-object/pothos-prisma-object.generator.ts (2)

36-39: Validate the order constraint in the schema.

order is declared as a bare z.number(), which silently allows negative and fractional values.
Because this field controls the relative ordering of generated fragments, an unexpected value could silently break the sort or even throw during topological ordering elsewhere.

-  order: z.number(),
+  // Positive integer – lower numbers are emitted first
+  order: z.number().int().nonnegative(),

156-160: Possible ordering collisions in typeDefinitions.

pothosTypeFile.typeDefinitions.add({ … order }) blindly inserts the entry.
If two generators accidentally emit the same order, whichever registers last wins, silently overriding the previous fragment.

Consider guarding with a uniqueness check or documenting that callers must coordinate unique orders.

packages/fastify-generators/src/writers/pothos/object-types.ts (1)

58-66: disableSort is a temporary workaround – add TODO context.

A comment says “TODO: Re-enable sort once we have better ways of sorting Prisma fields” but gives no tracking reference.
Add a ticket/issue number or elaborate on the sorting strategy to avoid bit-rot.

packages/fastify-generators/src/writers/pothos/input-types.ts (1)

80-84: Variable name collision risk

${lowerCaseFirst(name)}InputType may clash when two distinct GraphQL input types differ only by case in the first character (e.g. User vs user).
Consider using a deterministic unique suffix or the original case to avoid shadowing.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 25dde93 and f602f21.

⛔ Files ignored due to path filters (19)
  • packages/core-generators/src/generators/node/ts-utils/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/auth/auth-context/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/core/error-handler-service/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/core/fastify-redis/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/core/fastify-redis/generated/ts-templates.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/core/fastify-sentry/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/core/fastify-sentry/generated/ts-templates.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/core/request-service-context/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/core/service-context/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/pothos/pothos-auth/generated/ts-templates.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/pothos/pothos-scalar/generated/ts-templates.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/pothos/pothos-sentry/generated/ts-templates.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/pothos/pothos/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/pothos/pothos/generated/ts-templates.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/prisma/prisma-utils/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/vitest/prisma-vitest/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/vitest/prisma-vitest/generated/ts-templates.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/generated/ts-import-maps.ts is excluded by !**/generated/**
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/generated/ts-templates.ts is excluded by !**/generated/**
📒 Files selected for processing (94)
  • .changeset/five-symbols-speak.md (1 hunks)
  • .changeset/puny-hornets-wave.md (1 hunks)
  • .changeset/upset-taxis-stare.md (1 hunks)
  • .cursor/rules/code-style.mdc (1 hunks)
  • packages/core-generators/src/generators/node/ts-utils/ts-extractor.json (1 hunks)
  • packages/core-generators/src/generators/node/ts-utils/ts-utils.generator.ts (1 hunks)
  • packages/core-generators/src/generators/node/typescript/typescript.generator.ts (6 hunks)
  • packages/core-generators/src/renderers/typescript/actions/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/actions/render-ts-template-file-action.ts (2 hunks)
  • packages/core-generators/src/renderers/typescript/actions/render-ts-template-file-action.unit.test.ts (2 hunks)
  • packages/core-generators/src/renderers/typescript/extractor/organize-ts-template-imports.ts (2 hunks)
  • packages/core-generators/src/renderers/typescript/extractor/preprocess-code-for-extraction-hack.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/extractor/preprocess-code-for-extraction-hack.ts (2 hunks)
  • packages/core-generators/src/renderers/typescript/extractor/ts-template-file-extractor.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/extractor/write-ts-project-exports.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/fragments/utils.ts (2 hunks)
  • packages/core-generators/src/renderers/typescript/fragments/utils.unit.test.ts (5 hunks)
  • packages/core-generators/src/renderers/typescript/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/utils/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (4 hunks)
  • packages/core-generators/src/renderers/typescript/utils/ts-code-utils.unit.test.ts (1 hunks)
  • packages/fastify-generators/src/generators/core/error-handler-service/error-handler-service.generator.ts (1 hunks)
  • packages/fastify-generators/src/generators/core/fastify-redis/fastify-redis.generator.ts (3 hunks)
  • packages/fastify-generators/src/generators/core/fastify-redis/templates/mock-redis.ts (1 hunks)
  • packages/fastify-generators/src/generators/core/fastify-redis/templates/redis.ts (1 hunks)
  • packages/fastify-generators/src/generators/core/fastify-sentry/fastify-sentry.generator.ts (7 hunks)
  • packages/fastify-generators/src/generators/core/fastify-sentry/templates/instrument.ts (2 hunks)
  • packages/fastify-generators/src/generators/core/fastify-sentry/templates/services/sentry.ts (3 hunks)
  • packages/fastify-generators/src/generators/pothos/_providers/pothos-type-output.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-auth/pothos-auth.generator.ts (4 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-auth/templates/FieldAuthorizePlugin/global-types.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-auth/templates/FieldAuthorizePlugin/index.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-enums-file/pothos-enums-file.generator.ts (2 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-prisma-crud-mutation/pothos-prisma-crud-mutation.generator.ts (6 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-prisma-enum/pothos-prisma-enum.generator.ts (3 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-prisma-find-query/pothos-prisma-find-query.generator.ts (5 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-prisma-list-query/pothos-prisma-list-query.generator.ts (4 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-prisma-object/pothos-prisma-object.generator.ts (4 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-prisma-primary-key/pothos-prisma-primary-key.generator.ts (3 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-prisma/pothos-prisma.generator.ts (3 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-scalar/pothos-scalar.generator.ts (4 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-scalar/templates/date-time.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-scalar/templates/date.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-scalar/templates/uuid.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-sentry/pothos-sentry.generator.ts (4 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos-types-file/pothos-types-file.generator.ts (2 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (6 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos/templates/FieldWithInputPayloadPlugin/global-types.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos/templates/FieldWithInputPayloadPlugin/index.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos/templates/FieldWithInputPayloadPlugin/schema-builder.ts (1 hunks)
  • packages/fastify-generators/src/generators/pothos/pothos/templates/builder.ts (1 hunks)
  • packages/fastify-generators/src/generators/prisma/prisma-crud-create/prisma-crud-create.generator.ts (5 hunks)
  • packages/fastify-generators/src/generators/prisma/prisma-crud-delete/prisma-crud-delete.generator.ts (3 hunks)
  • packages/fastify-generators/src/generators/prisma/prisma-crud-update/prisma-crud-update.generator.ts (5 hunks)
  • packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts (4 hunks)
  • packages/fastify-generators/src/generators/vitest/prisma-vitest/templates/db.test-helper.ts (1 hunks)
  • packages/fastify-generators/src/generators/vitest/prisma-vitest/templates/prisma.test-helper.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/graphql-plugin.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/index.ts (3 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/pubsub.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/useGraphLogger.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/websocket.ts (3 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/pubsub.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/useGraphLogger.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/websocket-fragments.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/websocket.ts (1 hunks)
  • packages/fastify-generators/src/generators/yoga/yoga-plugin/yoga-plugin.generator.ts (6 hunks)
  • packages/fastify-generators/src/providers/pothos-field.ts (1 hunks)
  • packages/fastify-generators/src/providers/pothos-type.ts (2 hunks)
  • packages/fastify-generators/src/types/service-output.ts (2 hunks)
  • packages/fastify-generators/src/writers/pothos/args.ts (5 hunks)
  • packages/fastify-generators/src/writers/pothos/definitions.ts (1 hunks)
  • packages/fastify-generators/src/writers/pothos/helpers.ts (4 hunks)
  • packages/fastify-generators/src/writers/pothos/input-types.ts (3 hunks)
  • packages/fastify-generators/src/writers/pothos/object-types.ts (4 hunks)
  • packages/fastify-generators/src/writers/pothos/options.ts (1 hunks)
  • packages/fastify-generators/src/writers/pothos/resolvers.ts (4 hunks)
  • packages/fastify-generators/src/writers/pothos/scalar-fields.ts (4 hunks)
  • packages/project-builder-server/src/compiler/backend/graphql.ts (8 hunks)
  • packages/project-builder-server/src/sync/build-project.ts (2 hunks)
  • packages/project-builder-web/src/app/ProjectSyncModal/ApplicationCard.tsx (1 hunks)
  • packages/react-generators/src/generators/apollo/react-apollo/react-apollo.generator.ts (2 hunks)
  • packages/sync/src/output/post-write-commands/filter-commands.ts (2 hunks)
  • packages/utils/src/objects/index.ts (1 hunks)
  • packages/utils/src/objects/sort-object-keys.ts (1 hunks)
  • packages/utils/src/objects/sort-object-keys.unit.test.ts (1 hunks)
  • packages/utils/src/toposort/index.ts (1 hunks)
  • packages/utils/src/toposort/toposort-local.ts (1 hunks)
  • packages/utils/src/toposort/toposort-local.unit.test.ts (1 hunks)
  • plugins/baseplate-plugin-storage/src/generators/fastify/storage-module/storage-module.generator.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (33)
packages/core-generators/src/renderers/typescript/extractor/preprocess-code-for-extraction-hack.test.ts (1)
packages/core-generators/src/renderers/typescript/extractor/preprocess-code-for-extraction-hack.ts (1)
  • preprocessCodeForExtractionHack (16-58)
packages/fastify-generators/src/providers/pothos-type.ts (2)
packages/sync/src/providers/providers.ts (1)
  • createReadOnlyProviderType (219-224)
packages/fastify-generators/src/generators/pothos/_providers/pothos-type-output.ts (1)
  • PothosTypeOutputProvider (8-13)
packages/sync/src/output/post-write-commands/filter-commands.ts (1)
packages/sync/src/utils/canonical-path.ts (1)
  • normalizePathToProjectPath (14-19)
packages/core-generators/src/renderers/typescript/actions/render-ts-template-file-action.unit.test.ts (1)
packages/sync/src/providers/providers.ts (1)
  • createProviderType (151-210)
packages/utils/src/objects/sort-object-keys.unit.test.ts (1)
packages/utils/src/objects/sort-object-keys.ts (1)
  • sortObjectKeys (7-11)
packages/fastify-generators/src/providers/pothos-field.ts (1)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/fastify-generators/src/generators/pothos/_providers/pothos-type-output.ts (2)
packages/fastify-generators/src/writers/pothos/options.ts (1)
  • PothosTypeReference (10-19)
packages/sync/src/providers/providers.ts (1)
  • createReadOnlyProviderType (219-224)
packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/pubsub.ts (2)
packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/pubsub.ts (1)
  • getPubSub (13-22)
packages/fastify-generators/src/generators/core/fastify-redis/templates/redis.ts (1)
  • createRedisClient (6-10)
packages/fastify-generators/src/types/service-output.ts (1)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/actions/render-ts-template-file-action.ts (1)
packages/sync/src/providers/providers.ts (1)
  • Provider (11-11)
packages/fastify-generators/src/generators/pothos/pothos-prisma/pothos-prisma.generator.ts (5)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)
  • pothosConfigProvider (69-69)
packages/core-generators/src/providers/scopes.ts (1)
  • projectScope (3-6)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (1)
  • tsCodeFragment (39-49)
packages/core-generators/src/renderers/typescript/imports/builder.ts (1)
  • tsImportBuilder (69-77)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • tsTemplate (520-520)
packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/websocket-fragments.ts (1)
packages/fastify-generators/src/generators/auth/auth-context/templates/utils/auth-context.utils.ts (1)
  • createAuthContextFromSessionInfo (9-34)
packages/fastify-generators/src/generators/prisma/prisma-crud-update/prisma-crud-update.generator.ts (2)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • TsCodeUtils (85-517)
packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.ts (3)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/utils/src/toposort/toposort-local.ts (1)
  • toposortLocal (138-201)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • mergeFragmentImportsAndHoistedFragments (33-53)
packages/fastify-generators/src/generators/pothos/pothos-auth/pothos-auth.generator.ts (7)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (2)
  • pothosConfigProvider (69-69)
  • pothosSchemaProvider (75-76)
packages/fastify-generators/src/generators/auth/auth-roles/generated/ts-import-maps.ts (1)
  • authRolesImportsProvider (21-22)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • TsCodeUtils (85-517)
packages/core-generators/src/generators/node/typescript/typescript.generator.ts (1)
  • typescriptFileProvider (178-179)
packages/fastify-generators/src/generators/pothos/pothos-auth/generated/ts-templates.ts (1)
  • POTHOS_POTHOS_AUTH_TS_TEMPLATES (43-43)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (1)
  • tsCodeFragment (39-49)
packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.unit.test.ts (4)
packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.ts (1)
  • renderTsFragmentAction (16-44)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (1)
  • tsCodeFragment (39-49)
packages/core-generators/src/renderers/typescript/imports/builder.ts (1)
  • tsImportBuilder (69-77)
packages/sync/src/output/builder-action-test-helpers.ts (1)
  • testAction (35-42)
packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts (9)
packages/sync/src/generators/generators.ts (1)
  • createGeneratorTask (196-204)
packages/fastify-generators/src/generators/vitest/prisma-vitest/generated/ts-import-maps.ts (2)
  • prismaVitestImportsProvider (23-26)
  • createPrismaVitestImports (28-43)
packages/core-generators/src/providers/scopes.ts (1)
  • projectScope (3-6)
packages/core-generators/src/generators/node/vitest/vitest.generator.ts (1)
  • vitestConfigProvider (44-44)
packages/core-generators/src/generators/node/typescript/typescript.generator.ts (1)
  • typescriptFileProvider (178-179)
packages/fastify-generators/src/generators/prisma/prisma/prisma.generator.ts (1)
  • prismaImportsProvider (304-304)
packages/core-generators/src/providers/project.ts (1)
  • projectProvider (7-8)
packages/fastify-generators/src/generators/vitest/prisma-vitest/generated/ts-templates.ts (1)
  • VITEST_PRISMA_VITEST_TS_TEMPLATES (26-29)
packages/utils/src/string/quot.ts (1)
  • quot (6-8)
packages/react-generators/src/generators/apollo/react-apollo/react-apollo.generator.ts (1)
packages/utils/src/toposort/toposort-local.ts (1)
  • toposortLocal (138-201)
packages/fastify-generators/src/generators/prisma/prisma-crud-delete/prisma-crud-delete.generator.ts (5)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/fastify-generators/src/generators/prisma/prisma-utils/generated/ts-import-maps.ts (1)
  • PrismaUtilsImportsProvider (27-29)
packages/fastify-generators/src/generators/prisma/prisma-utils/prisma-utils.generator.ts (1)
  • PrismaUtilsImportsProvider (120-120)
packages/fastify-generators/src/generators/prisma/_shared/crud-method/primary-key-input.ts (1)
  • getPrimaryKeyDefinition (22-70)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • TsCodeUtils (85-517)
plugins/baseplate-plugin-storage/src/generators/fastify/storage-module/storage-module.generator.ts (2)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)
  • pothosConfigProvider (69-69)
packages/fastify-generators/src/writers/pothos/options.ts (1)
  • createPothosTypeReference (24-37)
packages/utils/src/toposort/toposort-local.ts (1)
packages/utils/src/toposort/errors.ts (2)
  • ToposortUnknownNodeError (12-19)
  • ToposortCyclicalDependencyError (1-10)
packages/core-generators/src/renderers/typescript/fragments/utils.ts (3)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/fragments/types.ts (2)
  • TsHoistedFragment (16-36)
  • TsCodeFragment (45-62)
packages/utils/src/toposort/toposort-local.ts (1)
  • toposortLocal (138-201)
packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/websocket.ts (1)
packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/websocket.ts (2)
  • makeHandler (45-198)
  • getGraphqlWsHandler (200-256)
packages/fastify-generators/src/generators/pothos/pothos-prisma-primary-key/pothos-prisma-primary-key.generator.ts (9)
packages/sync/src/utils/create-generator.ts (1)
  • createGenerator (96-123)
packages/sync/src/generators/generators.ts (1)
  • createGeneratorTask (196-204)
packages/fastify-generators/src/generators/prisma/prisma/prisma.generator.ts (1)
  • prismaOutputProvider (78-79)
packages/fastify-generators/src/generators/pothos/pothos-types-file/pothos-types-file.generator.ts (1)
  • pothosTypesFileProvider (47-48)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)
  • pothosSchemaBaseTypesProvider (89-92)
packages/fastify-generators/src/providers/pothos-type.ts (1)
  • pothosTypeOutputProvider (9-10)
packages/core-generators/src/providers/scopes.ts (1)
  • projectScope (3-6)
packages/fastify-generators/src/writers/pothos/options.ts (2)
  • PothosWriterOptions (157-175)
  • createPothosTypeReference (24-37)
packages/project-builder-server/src/utils/case.ts (1)
  • lowerCaseFirst (3-8)
packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.ts (4)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/renderers/file.ts (2)
  • RenderTsCodeFileTemplateOptions (23-27)
  • renderTsCodeFileTemplate (122-160)
packages/sync/src/output/generator-task-output.ts (1)
  • WriteFileOptions (22-49)
packages/sync/src/output/builder-action.ts (1)
  • BuilderAction (6-8)
packages/fastify-generators/src/writers/pothos/scalar-fields.ts (7)
packages/fastify-generators/src/types/service-output.ts (1)
  • ServiceOutputDtoScalarField (32-37)
packages/fastify-generators/src/writers/pothos/options.ts (1)
  • PothosWriterOptions (157-175)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • tsTemplate (520-520)
packages/fastify-generators/src/writers/pothos/helpers.ts (2)
  • getPothosMethodAndTypeForScalar (74-120)
  • writePothosFieldOptions (28-44)
packages/project-builder-server/src/utils/case.ts (1)
  • upperCaseFirst (10-15)
packages/utils/src/string/quot.ts (1)
  • quot (6-8)
packages/fastify-generators/src/generators/core/fastify-redis/fastify-redis.generator.ts (11)
packages/sync/src/generators/generators.ts (1)
  • createGeneratorTask (196-204)
packages/core-generators/src/providers/scopes.ts (1)
  • projectScope (3-6)
packages/fastify-generators/src/generators/core/fastify-redis/generated/ts-import-maps.ts (2)
  • fastifyRedisImportsProvider (19-22)
  • createFastifyRedisImports (24-35)
packages/sync/src/utils/create-provider-task.ts (1)
  • createProviderTask (18-32)
packages/fastify-generators/src/generators/core/config-service/config-service.generator.ts (2)
  • configServiceProvider (75-76)
  • configServiceImportsProvider (220-220)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (1)
  • tsCodeFragment (39-49)
packages/fastify-generators/src/generators/core/fastify-health-check/fastify-health-check.generator.ts (1)
  • fastifyHealthCheckConfigProvider (37-37)
packages/core-generators/src/renderers/typescript/imports/builder.ts (1)
  • tsImportBuilder (69-77)
packages/core-generators/src/generators/node/typescript/typescript.generator.ts (1)
  • typescriptFileProvider (178-179)
packages/core-generators/src/generators/node/vitest/vitest.generator.ts (1)
  • vitestConfigProvider (44-44)
packages/fastify-generators/src/generators/core/fastify-redis/generated/ts-templates.ts (1)
  • CORE_FASTIFY_REDIS_TS_TEMPLATES (20-20)
packages/fastify-generators/src/writers/pothos/definitions.ts (2)
packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.ts (1)
  • TsCodeFragmentWithDependencies (11-24)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/fastify-generators/src/generators/pothos/pothos-enums-file/pothos-enums-file.generator.ts (6)
packages/fastify-generators/src/generators/core/app-module/app-module.generator.ts (1)
  • appModuleProvider (44-45)
packages/core-generators/src/generators/node/typescript/typescript.generator.ts (1)
  • typescriptFileProvider (178-179)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)
  • pothosConfigProvider (69-69)
packages/fastify-generators/src/writers/pothos/options.ts (1)
  • createPothosTypeReference (24-37)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • TsCodeUtils (85-517)
packages/utils/src/maps/map-values-of-map.ts (1)
  • mapValuesOfMap (11-20)
packages/core-generators/src/generators/node/typescript/typescript.generator.ts (3)
packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.ts (2)
  • RenderTsFragmentActionInput (8-14)
  • renderTsFragmentAction (16-44)
packages/sync/src/output/builder-action.ts (1)
  • BuilderAction (6-8)
packages/sync/src/utils/canonical-path.ts (1)
  • normalizePathToProjectPath (14-19)
packages/fastify-generators/src/generators/pothos/pothos-sentry/pothos-sentry.generator.ts (6)
packages/core-generators/src/generators/node/typescript/typescript.generator.ts (1)
  • typescriptFileProvider (178-179)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (2)
  • tsCodeFragment (39-49)
  • tsHoistedFragment (15-26)
packages/core-generators/src/renderers/typescript/imports/builder.ts (1)
  • tsImportBuilder (69-77)
packages/fastify-generators/src/generators/pothos/pothos-sentry/generated/ts-templates.ts (1)
  • POTHOS_POTHOS_SENTRY_TS_TEMPLATES (10-10)
packages/fastify-generators/src/generators/core/fastify-sentry/fastify-sentry.generator.ts (1)
  • fastifySentryConfigProvider (71-71)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)
  • pothosConfigProvider (69-69)
packages/fastify-generators/src/generators/pothos/pothos-prisma-find-query/pothos-prisma-find-query.generator.ts (12)
packages/fastify-generators/src/generators/pothos/providers/scopes.ts (1)
  • pothosFieldScope (3-6)
packages/fastify-generators/src/generators/prisma/prisma/prisma.generator.ts (1)
  • prismaOutputProvider (78-79)
packages/fastify-generators/src/generators/pothos/pothos-types-file/pothos-types-file.generator.ts (1)
  • pothosTypesFileProvider (47-48)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)
  • pothosSchemaBaseTypesProvider (89-92)
packages/fastify-generators/src/generators/pothos/_providers/pothos-type-output.ts (1)
  • pothosTypeOutputProvider (18-19)
packages/fastify-generators/src/generators/pothos/pothos-prisma-primary-key/pothos-prisma-primary-key.generator.ts (1)
  • getPothosPrismaPrimaryKeyTypeOutputName (30-34)
packages/fastify-generators/src/providers/pothos-field.ts (1)
  • pothosFieldProvider (14-15)
packages/project-builder-server/src/utils/case.ts (1)
  • lowerCaseFirst (3-8)
packages/sync/src/utils/non-overwriteable-map.ts (1)
  • createNonOverwriteableMap (82-195)
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts (1)
  • TsCodeUtils (85-517)
packages/utils/src/objects/sort-object-keys.ts (1)
  • sortObjectKeys (7-11)
packages/utils/src/string/quot.ts (1)
  • quot (6-8)
packages/fastify-generators/src/generators/pothos/pothos-types-file/pothos-types-file.generator.ts (9)
packages/fastify-generators/src/writers/pothos/definitions.ts (1)
  • PothosTypeDefinition (9-9)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/utils/src/field-map/field-map.ts (1)
  • NamedArrayFieldContainer (189-234)
packages/sync/src/generators/generators.ts (1)
  • createGeneratorTask (196-204)
packages/fastify-generators/src/generators/core/app-module/app-module.generator.ts (1)
  • appModuleProvider (44-45)
packages/core-generators/src/generators/node/typescript/typescript.generator.ts (1)
  • typescriptFileProvider (178-179)
packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)
  • pothosSchemaProvider (75-76)
packages/fastify-generators/src/generators/pothos/pothos/generated/ts-import-maps.ts (1)
  • pothosImportsProvider (16-17)
packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.ts (1)
  • mergeFragmentsWithColocatedDependencies (99-146)
🔇 Additional comments (129)
packages/sync/src/output/post-write-commands/filter-commands.ts (2)

1-1: Added utility for canonical path handling.

Good addition of the normalizePathToProjectPath import to support the enhanced functionality.


32-34: Improved path handling for onlyIfChanged.

This change properly normalizes file paths before checking against modified paths, allowing the function to correctly handle both canonical and non-canonical paths. This is a valuable enhancement that makes the code more robust.

.changeset/upset-taxis-stare.md (1)

1-5: Well-documented changeset.

The changeset correctly describes the change as a patch update and clearly explains the enhancement to accept canonical paths in the onlyIfChanged functionality. This ensures proper versioning and release notes generation.

packages/fastify-generators/src/generators/core/fastify-redis/templates/mock-redis.ts (1)

2-4: Formatting improvement: Blank lines added around import statements improve readability and align with the project's stylistic conventions.

packages/fastify-generators/src/generators/pothos/pothos/templates/FieldWithInputPayloadPlugin/schema-builder.ts (1)

3-3: Verify updated import alias: The import path for capitalizeString has been changed to use the %tsUtilsImports alias. Ensure this alias is correctly mapped in your import configuration (e.g., tsconfig.json or import map) and resolves to the expected utility module.

packages/core-generators/src/renderers/typescript/extractor/write-ts-project-exports.ts (1)

16-16: Correct import path for TsCodeUtils: Updated to ../utils/ts-code-utils.js to reflect the new directory structure. This aligns with the refactored utilities layout.

packages/core-generators/src/renderers/typescript/extractor/ts-template-file-extractor.ts (1)

38-38: Update import for TsCodeUtils: The import path now points to the consolidated utils/ts-code-utils.js module, ensuring consistency with recent refactoring.

packages/core-generators/src/generators/node/ts-utils/ts-extractor.json (1)

1-7: Confirm default export group configuration: A new ts-extractor.json defines an empty ("") export group with "exportProviderType": true. Verify that this setting produces the intended provider types for your Node ts-utils generator and that downstream consumers import them correctly.

packages/fastify-generators/src/generators/pothos/pothos/templates/FieldWithInputPayloadPlugin/index.ts (1)

3-3: Approve reordered import grouping.
Moving external @pothos/core imports above local imports improves readability and aligns with the project’s import ordering conventions.

packages/fastify-generators/src/generators/pothos/pothos-scalar/templates/date.ts (1)

3-4: Approve import map placeholders.
Switching to %errorHandlerServiceImports and %pothosImports correctly leverages the new import‐map providers for error handling and Pothos builder. No functional changes; this aligns with the updated generator patterns.

packages/fastify-generators/src/generators/pothos/pothos-scalar/templates/date-time.ts (1)

3-4: Approve import map updates.
Updating to %errorHandlerServiceImports and %pothosImports maintains consistency with the other scalar template refactorings. No logic changes detected.

packages/core-generators/src/renderers/typescript/utils/ts-code-utils.unit.test.ts (1)

3-4: Approve updated test imports.
Changing the paths to ../fragments/creators.js and ../imports/builder.js matches the new barrel structure under utils/. Tests will now correctly reference the relocated modules.

packages/fastify-generators/src/generators/vitest/prisma-vitest/templates/db.test-helper.ts (2)

3-6: Approve reordered and added imports.
Importing Prisma, PrismaClient first and adding the path import aligns with the generator’s import-task output, improving consistency.


9-9: Verify placeholder for test database name.
The constant now uses TPL_TEST_DB instead of a hardcoded string. Ensure that the generator defines and injects TPL_TEST_DB with the intended database name.

packages/fastify-generators/src/generators/pothos/pothos/templates/FieldWithInputPayloadPlugin/global-types.ts (1)

14-15: Import organization looks good.

The reorganized import statements improve code organization by separating external imports from local imports, following best practices.

packages/fastify-generators/src/generators/pothos/pothos-scalar/templates/uuid.ts (1)

2-4: Import paths updated correctly.

The changes to import from template placeholders align with the refactoring of import providers. Using %errorHandlerServiceImports and %pothosImports provides better modularity and consistency across the codebase.

packages/fastify-generators/src/generators/core/fastify-redis/templates/redis.ts (2)

3-3: Good improvement to dependency management.

Importing the config object explicitly rather than relying on a global CONFIG variable improves modularity and testability.


7-7: Correct configuration reference update.

Updated to use the imported config object consistently with the import change.

packages/fastify-generators/src/generators/pothos/pothos-auth/templates/FieldAuthorizePlugin/index.ts (3)

3-3: Import source properly updated.

Correctly updated to use the centralized error handler imports provider.


10-13: Import organization improved.

The reordering of imports creates a clearer separation between different import sources.


15-15: ESLint directive properly repositioned.

The ESLint directive is now correctly positioned after all imports.

packages/utils/src/objects/index.ts (1)

2-2: Expose the new sortObjectKeys utility in the public API
Adding export * from './sort-object-keys.js'; extends the barrel to include the new key-sorting function alongside safe-merge.js. This correctly surfaces sortObjectKeys for downstream consumers.

packages/core-generators/src/renderers/typescript/utils/index.ts (1)

1-2: Centralize TypeScript utility exports
This new barrel re-exports both merge-fragments-with-colocated-dependencies.js and ts-code-utils.js, simplifying imports across the renderer and aligning with the refactored modular structure.

packages/core-generators/src/renderers/typescript/actions/index.ts (1)

1-1: Re-export the new fragment rendering action
Including export * from './render-ts-fragment-action.js'; makes the renderTsFragmentAction available alongside existing render actions. Ensure any consumer code updates its imports if needed.

.changeset/five-symbols-speak.md (1)

1-6: Document addition of new utilities in the patch changeset
The changeset correctly records the introduction of toposortLocal and sortObjectKeys for @halfdomelabs/utils. It follows the standard changeset format and clearly describes the patch.

packages/core-generators/src/renderers/typescript/index.ts (1)

8-8: Expose the new utils barrel in the TypeScript renderer
Adding export * from './utils/index.js'; integrates the newly consolidated utility set into the renderer’s public API. Confirm that downstream modules import from this updated barrel.

packages/fastify-generators/src/generators/pothos/pothos-auth/templates/FieldAuthorizePlugin/global-types.ts (2)

6-16: Clean import organization improves code structure

The reordering of imports and separation of imports into distinct groups follows best practices for code organization. Moving the InputShapeFromFields within the import block and adding a separate import for PothosAuthorizeByRolesPlugin improves readability and maintainability.


17-17: Better ESLint directive placement

Moving the ESLint directive closer to where it's actually needed (just before the global declaration block) follows best practices for code organization.

packages/core-generators/src/generators/node/ts-utils/ts-utils.generator.ts (1)

115-115: Good type export addition

Exporting the TsUtilsImportsProvider type alongside the existing value export improves type safety and follows the pattern of exporting both implementations and their corresponding types. This enhances the developer experience by making the type available to consumers.

packages/fastify-generators/src/generators/core/fastify-sentry/templates/instrument.ts (2)

3-5: Import source refactoring aligns with new provider pattern

Changing the import source for config from '%config' to '%configServiceImports' and reordering imports aligns with the broader refactoring to use the new config provider pattern.


21-22: Verify template placeholder implementation

The change from SENTRY_INTEGRATIONS to TPL_INTEGRATIONS appears to be part of the template-driven approach, and the added trailing comma improves future Git diff readability.

Please confirm that TPL_INTEGRATIONS is correctly implemented as a template placeholder that will be replaced during code generation. Since this is a template file, it's important to ensure that the placeholder follows the expected pattern for substitution.

packages/utils/src/toposort/index.ts (1)

3-3: Valuable addition of locality-based topological sort

Exporting the new locality-based topological sort implementation enhances the utility library with a valuable sorting algorithm. This addition aligns well with the PR's objective of introducing the toposortLocal utility.

.changeset/puny-hornets-wave.md (1)

1-8: LGTM: Well-structured changeset.

The changeset correctly identifies the affected packages and provides a clear description of the changes. The patch version increments are appropriate for this type of refactoring.

packages/project-builder-web/src/app/ProjectSyncModal/ApplicationCard.tsx (1)

327-329: Improved error message formatting.

Adding whitespace-pre-wrap and font-mono classes to error messages is a good UI enhancement that will preserve whitespace formatting and make error messages more readable with a monospace font.

packages/fastify-generators/src/generators/core/error-handler-service/error-handler-service.generator.ts (1)

222-222: LGTM: Properly exposing import provider.

Exporting errorHandlerServiceImportsProvider from the module allows it to be imported and reused by other modules, improving modularity and consistency with the pattern established in other generators as part of this refactoring.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/useGraphLogger.ts (1)

4-7: LGTM: Updated imports to use template placeholders.

The changes properly update the import paths to use the new placeholder tokens (%loggerServiceImports and %errorHandlerServiceImports) instead of hardcoded paths, and add the necessary import from perf_hooks. This aligns with the PR's objective of improving modularity and consistency in import handling.

packages/utils/src/objects/sort-object-keys.unit.test.ts (1)

1-36: LGTM: Comprehensive test coverage for sortObjectKeys.

The test file provides thorough coverage for the sortObjectKeys utility function:

  • Tests basic key sorting
  • Verifies value preservation
  • Handles edge cases (empty objects)
  • Tests numeric string keys

The tests use clear assertions and follow good testing practices.

packages/utils/src/objects/sort-object-keys.ts (1)

1-11: Well-implemented utility function

This is a clean, well-implemented utility function for sorting object keys lexicographically. The implementation correctly:

  • Uses localeCompare for proper locale-aware string comparison
  • Maintains type information with appropriate generics
  • Provides clear documentation
  • Uses modern JavaScript methods (Object.entries/fromEntries)

The function is simple yet effective for standardizing object key order across the codebase.

packages/fastify-generators/src/providers/pothos-field.ts (1)

1-1: Good migration to the new TsCodeFragment abstraction

Updating the type from TypescriptCodeExpression to TsCodeFragment aligns with the broader refactoring effort to standardize code generation patterns. This change enhances the code generation capabilities by leveraging the richer TsCodeFragment interface, which supports imports tracking and hoisted fragments.

Also applies to: 7-7

packages/fastify-generators/src/generators/vitest/prisma-vitest/templates/prisma.test-helper.ts (1)

3-3:

Details

✅ Verification successful

Verify the template variable TPL_PRISMA_PATH is correctly handled

The changes to modernize imports and templating look good, but there's an undefined variable TPL_PRISMA_PATH used in the vi.mock() call that needs verification.

Since this is a template file, please verify that TPL_PRISMA_PATH is properly replaced during code generation:

Also applies to: 6-6, 8-8


🏁 Script executed:

#!/bin/bash
# Check how TPL_PRISMA_PATH is defined and replaced in the generator
echo "Looking for TPL_PRISMA_PATH in the generator file:"
rg -A 3 "TPL_PRISMA_PATH" packages/fastify-generators/src/generators/vitest/prisma-vitest/

Length of output: 1704


🏁 Script executed:

#!/bin/bash
# Inspect the generated ts-templates around prisma.test-helper.ts
rg -C 20 "prisma.test-helper.ts" packages/fastify-generators/src/generators/vitest/prisma-vitest/generated/ts-templates.ts

Length of output: 894


🏁 Script executed:

#!/bin/bash
# Show how TPL_PRISMA_PATH is passed into createTsTemplateFile in prisma-vitest.generator.ts
rg -C 5 "createTsTemplateFile" -n packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts

Length of output: 124


TPL_PRISMA_PATH substitution verified

The TPL_PRISMA_PATH template variable is defined in prisma-vitest.generator.ts and passed into createTsTemplateFile as a quoted, resolved module specifier:

// packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts

variables: {
  TPL_PRISMA_PATH: quot(
    typescriptFile.resolveModuleSpecifier(
      prismaImports.prisma.moduleSpecifier,
      prismaHelperPath
    )
  ),
},

At generation time, this ensures that in prisma.test-helper.ts the placeholder is replaced with the correct import path. No further changes are needed here.

packages/fastify-generators/src/providers/pothos-type.ts (1)

1-1: Enhanced code clarity with specialized provider creation

Good refactoring to use createReadOnlyProviderType instead of manually setting { isReadOnly: true }. This change:

  • Makes the code more explicit about its intention
  • Reduces boilerplate
  • Is less error-prone
  • Follows the principle of using the most specific API for the task

This small change improves maintainability and aligns with the broader refactoring efforts.

Also applies to: 10-10

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/pubsub.ts (3)

3-3: Import path updated to use centralized provider

The import path for createRedisClient has been updated to use the new centralized import path %fastifyRedisImports instead of the previous %fastify-redis. This change aligns with the broader refactoring of the fastify-redis generator to centralize import management.


5-5: Import ordering improved

Imports from 'graphql-yoga' have been reordered, improving readability by listing createPubSub before PubSub in alphabetical order.


9-9: Type definition enhanced with template parameter

The PubSubPublishArgs type has been changed from a hardcoded empty object type {} to a template parameter TPL_PUBLISH_ARGS, making the code more flexible and allowing for customization of publish arguments.

packages/react-generators/src/generators/apollo/react-apollo/react-apollo.generator.ts (2)

32-32: Updated to use improved topological sort algorithm

The import has been changed from toposortOrdered to the new toposortLocal function, which provides a locality-based topological sort with improved stability.


324-337: Function call updated to use new toposortLocal

The Apollo links sorting implementation now uses toposortLocal with the same arguments and usage pattern as before. The new algorithm maintains the same behavior but with improved locality in the resulting order.

packages/core-generators/src/renderers/typescript/actions/render-ts-template-file-action.unit.test.ts (2)

1-1: Added import for createProviderType

The createProviderType function is now imported from '@halfdomelabs/sync' to support the enhanced test case for multiple import maps.


167-170: Enhanced test with explicit provider types

The test definition for handling multiple import maps has been improved by adding explicit provider types for testImport1 and testImport2 using createProviderType. This makes the test more robust by properly testing the provider type system integration.

packages/core-generators/src/renderers/typescript/extractor/preprocess-code-for-extraction-hack.test.ts (1)

60-100: Added test case for END marker comma handling

Added a new test case to verify the third transformation pattern that moves END markers before commas. This test complements the implementation in preprocess-code-for-extraction-hack.ts that handles this pattern, ensuring proper behavior across different code patterns like function arguments, arrays, and objects.

packages/core-generators/src/renderers/typescript/extractor/organize-ts-template-imports.ts (1)

138-146: Good addition of safeguards for built-in modules and special cases.

This change properly handles built-in Node.js modules and the special 'ws' module case by returning their original import declarations without modification. This prevents potential resolution issues with these modules.

packages/fastify-generators/src/generators/pothos/pothos/templates/builder.ts (1)

5-7: Template placeholder naming convention improvement.

The template placeholders have been renamed from SCHEMA_TYPE_OPTIONS, SCHEMA_BUILDER_OPTIONS, and SUBSCRIPTION_TYPE to include the TPL_ prefix, making them more clearly identifiable as template tokens to be replaced during code generation.

Also applies to: 11-11

packages/project-builder-server/src/sync/build-project.ts (1)

169-172: Good error message sanitization.

Adding stripVTControlCharacters is an excellent improvement for handling error messages. It removes ANSI escape sequences and other control characters that could cause display issues or corrupt logs, especially when tools like Prettier throw formatted errors.

packages/fastify-generators/src/types/service-output.ts (1)

72-76: Type refinement with improved documentation.

Replacing expression: TypescriptCodeExpression with the well-documented referenceFragment: TsCodeFragment aligns with the broader refactoring to use a more comprehensive code fragment abstraction. The TsCodeFragment includes not only the code content but also associated imports and hoisted fragments, providing better support for dependency management.

packages/core-generators/src/renderers/typescript/extractor/preprocess-code-for-extraction-hack.ts (1)

44-55: Well-structured addition of Pattern 3 for handling comma markers.

The implementation for handling END marker positioning around commas follows the established pattern of the existing transformations. The regex pattern correctly identifies END markers after commas and preserves whitespace when repositioning them.

packages/fastify-generators/src/generators/pothos/_providers/pothos-type-output.ts (1)

1-19: Clean provider implementation for Pothos type references.

This provider implementation correctly follows the read-only provider pattern, which is appropriate for type references that shouldn't be modified after creation. The interface and implementation are well-documented with JSDoc comments.

packages/core-generators/src/renderers/typescript/actions/render-ts-template-file-action.ts (1)

60-62: Improved type-safety with empty import map providers hack.

The change enforces stricter key checking for empty import map providers using Partial<Record<'', Provider>>. While slightly unconventional, this approach effectively forces TypeScript to validate keys properly, improving type-safety without changing runtime behavior.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/pubsub.ts (1)

7-9: Type definition uses template placeholder.

The PubSubPublishArgs is defined using a template placeholder TPL_PUBLISH_ARGS which will be replaced during code generation. Ensure that the replacement mechanism properly substitutes this with a type that aligns with the actual publish arguments structure.

This is a template file, so the placeholder is expected. Verify that the code generation process correctly replaces this placeholder with an appropriate type definition that matches the GraphQL subscription event structure in your application.

packages/fastify-generators/src/generators/pothos/pothos-prisma-enum/pothos-prisma-enum.generator.ts (4)

1-1: Refactored imports to use new TypeScript code fragment system

The change from TypescriptCodeUtils to TsCodeUtils and tsTemplate aligns with the PR's goal of using the new TypeScript system for better type safety.


10-10: Added pothosImportsProvider to dependencies

This change incorporates the new provider pattern, making the code more modular and maintainable by centralizing imports management.

Also applies to: 26-26


32-40: Improved enum generation with structured code fragments

The refactoring from string templates to tsTemplate and TsCodeUtils.mergeFragmentsAsObject provides better type safety and maintainability when generating enum values.


45-45: Updated property name from 'block' to 'fragment'

This naming change reflects the shift from string-based code blocks to structured code fragments, maintaining consistency with the new TypeScript system.

packages/fastify-generators/src/generators/core/fastify-sentry/templates/services/sentry.ts (3)

3-4: Improved import flexibility with import placeholders

Using %configServiceImports and %errorHandlerServiceImports placeholders allows the generator to dynamically inject the correct import paths, making the template more portable across different project structures.


24-24: Extracted Sentry logging conditions to a template placeholder

Replacing inline conditions with TPL_LOG_TO_SENTRY_CONDITIONS enables customization of error logging logic without modifying the template file.


35-35: Extracted Sentry scope configuration to a template placeholder

Using TPL_SCOPE_CONFIGURATION allows for dynamic injection of Sentry scoping logic, making the template more adaptable to different project requirements.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/websocket-fragments.ts (5)

3-47: Well-structured WebSocket connection handler with authentication and error handling

The extracted onConnect handler provides a comprehensive approach to WebSocket connection management with:

  • Authentication context creation
  • Token expiry management with socket timeouts
  • Detailed error mapping from HTTP to WebSocket close codes

This modular approach improves reusability and maintainability.


11-24: Effective token expiry handling with socket timeout

The implementation correctly:

  1. Checks for token expiry time
  2. Sets a timeout to close the socket when the token expires
  3. Cleans up the timeout when the socket closes normally

This prevents zombie connections from expired tokens while properly handling normal disconnections.


27-33: Clear mapping of HTTP error codes to WebSocket close codes

The implementation maps HTTP status codes to appropriate WebSocket close codes, with a helpful comment explaining why 401 is mapped to Forbidden for retry behavior.


39-44: Comprehensive error handling with appropriate logging

The code handles both HTTP errors with known status codes and unknown errors, ensuring all error scenarios are properly managed with appropriate socket close codes and error logging.


8-9:

Details

✅ Verification successful

Verify the session info creator implementation

The template placeholder TPL_SESSION_INFO_CREATOR needs to correctly extract session information from the authorization header and work with the createAuthContextFromSessionInfo function.


🏁 Script executed:

#!/bin/bash
# Verify how TPL_SESSION_INFO_CREATOR is implemented in the generator
grep -r "TPL_SESSION_INFO_CREATOR" packages/fastify-generators/src/generators/yoga/ --include="*.ts"

Length of output: 398


I’d like to inspect the actual code fragment provided for TPL_SESSION_INFO_CREATOR in the generator to confirm it correctly parses the authorization header. Running a grep with context in the generator file:


🏁 Script executed:

#!/bin/bash
grep -R "TPL_SESSION_INFO_CREATOR" -n -A5 -B5 packages/fastify-generators/src/generators/yoga/yoga-plugin/yoga-plugin.generator.ts

Length of output: 714


To confirm that authorizationHeader is defined before being used in the generated fragment, let’s inspect the websocket-fragments.ts template:


🏁 Script executed:

#!/bin/bash
file="packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/websocket-fragments.ts"

echo "=== Searching for authorizationHeader ==="
grep -n -R "authorizationHeader" -A3 -B3 "$file" || true

echo
echo "=== Printing first 200 lines of the template ==="
sed -n '1,200p' "$file"

Length of output: 2412


Session info creator implementation verified

The TPL_SESSION_INFO_CREATOR fragment is correctly defined to call

await userSessionService.getSessionInfoFromToken(
  ctx.extra.request,
  typeof authorizationHeader === 'string' ? authorizationHeader : undefined,
)

which properly extracts the session info from the authorization header and feeds it into createAuthContextFromSessionInfo. No changes are required here.

.cursor/rules/code-style.mdc (4)

6-8: Clear TypeScript guidelines promote type safety

The explicit requirements for strict type checking and return type declarations align well with the project's move toward more structured and type-safe code generation.


9-13: Well-defined file organization improves project structure

The guidelines for test file naming and colocation with implementation files will help maintain a consistent and navigable project structure.


17-22: Structured import guidelines improve code readability

The clear rules for import sorting and path management will create consistency across the codebase, making it easier to navigate and understand dependencies.


27-29: Code style guidance promotes maintainability

The emphasis on functional programming patterns and extracting repeated components aligns with the modular approach seen in the generator refactoring.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/index.ts (3)

3-6: Template placeholders standardized for service imports.

The import statements have been refactored to use standardized placeholder tokens for service imports (%configServiceImports, %errorHandlerServiceImports, etc.). This approach centralizes the management of imports and makes the template more maintainable.


14-14: Renamed template token for side-effect imports.

The token CUSTOM_IMPORTS has been renamed to TPL_SIDE_EFFECT_IMPORTS, which better reflects its purpose and follows the new naming convention for template tokens (prefixed with TPL_).


18-18: Standardized template token naming convention.

All template tokens have been renamed to follow a consistent naming convention with the TPL_ prefix:

  • SCHEMATPL_SCHEMA
  • POST_SCHEMA_BLOCKSTPL_POST_SCHEMA_FRAGMENTS
  • ENVELOP_PLUGINSTPL_ENVELOP_PLUGINS
  • GRAPHQL_HANDLERTPL_GRAPHQL_HANDLER

This improves code clarity by clearly identifying template placeholders and makes the templating system more consistent.

Also applies to: 20-20, 76-76, 102-102

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/plugins/graphql/websocket.ts (1)

3-5: Service imports standardized using placeholders.

The imports for error handling, logging, and request context have been refactored to use consistent placeholder tokens. This aligns with the broader refactoring pattern seen in the GraphQL index file.

packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.unit.test.ts (4)

1-7: Well-structured imports for the test suite.

The imports are cleanly organized, properly importing testing utilities from external packages and the implementation modules being tested.


8-26: Comprehensive test for rendering fragments with imports.

This test effectively verifies that renderTsFragmentAction can correctly process TypeScript code fragments with imports. It checks that the action:

  1. Generates the expected file
  2. Uses the correct ID
  3. Properly formats the content with imports

The test structure is clear and follows best practices for testing action functions.


28-51: Test coverage for hoisted fragments functionality.

This test verifies an important aspect of the fragment rendering system - the ability to handle hoisted fragments that appear before imports. This ensures the action correctly implements fragment positioning in the generated output.


53-67: Simple case test for string fragment rendering.

This test verifies the base case of rendering a simple string fragment without imports or hoisted content. Including this simpler test alongside more complex cases follows good testing practices by ensuring the core functionality works in isolation.

packages/fastify-generators/src/generators/pothos/pothos-prisma/pothos-prisma.generator.ts (3)

5-7: Updated imports for new TypeScript code generation system.

The imports have been updated to use the new TypeScript code generation utilities:

  • Added tsCodeFragment, tsImportBuilder, and tsTemplate from core-generators
  • Changed from a different provider to prismaImportsProvider
  • Updated from pothosSetupProvider to pothosConfigProvider

These changes align with the broader refactoring effort to use a more structured and type-safe system for generating TypeScript code.

Also applies to: 18-18, 23-23


42-43: Updated dependencies for task execution.

The generator dependencies have been updated to match the imported provider changes:

  • pothosSetup to pothosConfig
  • Something else to prismaImports

This ensures the task has access to the correct providers needed for the refactored code generation system.

Also applies to: 48-48


54-80: Refactored configuration system using TypeScript code fragments.

The configuration for Pothos Prisma has been completely refactored to use the new TypeScript code fragment system. Key improvements:

  1. Uses map-based configuration (pothosConfig.pothosPlugins, etc.) instead of chained .append() calls
  2. Creates structured imports with tsImportBuilder
  3. Uses tsCodeFragment to combine imports with code
  4. Properly marks the PrismaTypes import as type-only
  5. References the Prisma client with prismaImports.prisma.fragment()

This approach provides better type safety, improved modularity, and clearer structure for generated code.

packages/core-generators/src/renderers/typescript/fragments/utils.unit.test.ts (2)

40-40: The test now clearly verifies nested fragment ordering.

The test description and assertions have been updated to reflect the new locality-based ordering approach, making the test more precise about expected behavior.

Also applies to: 66-67


108-108: Well-documented test for the new topological sorting behavior.

This test now explicitly verifies that hoisted fragments are ordered using locality-based topological sorting followed by alphabetical key ordering. The comments and assertions clearly explain the expected ordering, which helps document the behavior change from priority-based to locality-based sorting.

Also applies to: 139-139, 155-162

packages/fastify-generators/src/generators/prisma/prisma-crud-update/prisma-crud-update.generator.ts (3)

1-3: LGTM: Updated imports to use new TS abstractions.

The imports have been correctly updated to use the new TsCodeFragment, TsCodeUtils, and tsImportBuilder abstractions from @halfdomelabs/core-generators.


43-43: LGTM: Function parameter and return property names updated for consistency.

The function parameter type has been updated from TypescriptCodeExpression to TsCodeFragment, and the return property has been renamed from expression to referenceFragment for consistency with the new TS system.

Also applies to: 55-55


167-170: LGTM: Updated to use the new import fragment creation approach.

The code now uses TsCodeUtils.importFragment instead of the previous createExpression method, which is in line with the refactoring to use the new TS system.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/useGraphLogger.ts (3)

80-89: LGTM: Performance measurement implementation.

The execution timing implementation using performance.now() is a good approach for measuring GraphQL operation execution times.


90-107: LGTM: Comprehensive subscription logging.

The subscription logging implementation properly captures the start of subscriptions and handles both results and errors, providing good observability for GraphQL subscriptions.


5-6:

Details

✅ Verification successful

Verify token replacement for service imports.

The code uses placeholder tokens (%errorHandlerServiceImports and %loggerServiceImports) that will be replaced during code generation. Ensure that these tokens are properly defined in the import map for the generator.


🏁 Script executed:

#!/bin/bash
# Check if these placeholder tokens are defined in the import map
rg -A 3 -B 3 "errorHandlerServiceImports|loggerServiceImports" --type ts packages/fastify-generators/src/generators/yoga/yoga-plugin/

Length of output: 20365


Import tokens verified

The %errorHandlerServiceImports and %loggerServiceImports placeholders are already defined and wired up through errorHandlerServiceImportsProvider and loggerServiceImportsProvider in the generator’s import map (see packages/fastify-generators/src/generators/yoga/yoga-plugin/yoga-plugin.generator.ts and the corresponding generated ts-import-maps.js). No further changes are required.

packages/fastify-generators/src/generators/prisma/prisma-crud-delete/prisma-crud-delete.generator.ts (3)

1-3: LGTM: Updated imports to use new TS abstractions.

The imports have been correctly updated to use the new TsCodeFragment, TsCodeUtils, and tsImportBuilder abstractions from @halfdomelabs/core-generators.


31-31: LGTM: Property and parameter names updated for consistency.

The interface property, function parameter, and return property have been renamed to use serviceMethodReference and referenceFragment to be consistent with the new TS system.

Also applies to: 39-39, 45-45


119-122: LGTM: Updated to use the new import fragment creation approach.

The code now uses TsCodeUtils.importFragment instead of the previous createExpression method, and updates the property name in the options object, which is in line with the refactoring to use the new TS system.

Also applies to: 128-128

packages/core-generators/src/renderers/typescript/utils/merge-fragments-with-colocated-dependencies.unit.test.ts (1)

1-285: Well-structured, comprehensive test suite for the fragment merging utility.

This test suite thoroughly validates the mergeFragmentsWithColocatedDependencies utility, covering:

  • Empty input handling
  • Simple dependency ordering
  • Shared dependency resolution
  • Order preservation options
  • Import collection
  • Error detection for duplicate fragments with different contents
  • Nested dependency chains

The tests are well-organized with clear arrange-act-assert patterns and descriptive assertions. This provides good confidence in the functionality of the dependency-aware fragment merging system.

packages/core-generators/src/generators/node/typescript/typescript.generator.ts (4)

151-152: API extension adds fragment rendering capability.

Adding the renderTemplateFragment method to the TypescriptFileProvider interface provides a consistent way to render individual TypeScript code fragments, complementing the existing template file and group rendering capabilities.


168-176: Good documentation for exported module resolution method.

Exposing the resolveModuleSpecifier method with clear JSDoc comments makes the functionality more accessible and self-documenting. This will help consumers understand how to resolve module specifiers correctly.


428-441: Implementation follows established patterns for consistency.

The renderTemplateFragment implementation follows the same pattern as the existing renderTemplateFile method:

  1. Extracts the directory from the destination path
  2. Uses shared rendering options including module resolution and import sorting
  3. Delegates to the appropriate rendering action

This consistency makes the API predictable and easier to use.


461-461: Effectively exposes internal module resolution capability.

This simple but effective change exposes the internal resolveModuleSpecifier function as part of the public interface, allowing consumers to leverage the same module resolution logic used internally.

packages/core-generators/src/renderers/typescript/actions/render-ts-fragment-action.ts (1)

8-14: Clear interface design with appropriate optional properties.

The RenderTsFragmentActionInput interface is well-designed with:

  • Required properties for essential information (fragment, id, destination)
  • Optional properties for customization (renderOptions, writeOptions)

This makes the API both usable and flexible.

packages/fastify-generators/src/generators/pothos/pothos-prisma-primary-key/pothos-prisma-primary-key.generator.ts (7)

11-14: Updated imports align with new architecture.

The changes replace direct use of utility functions with more structured imports from the Pothos writers module, and update the provider dependency to use the base types provider. This supports the broader refactoring effort.

Also applies to: 17-17


20-28: Added order property with good documentation.

Adding the order property to the descriptor schema allows explicit control over the ordering of generated types, with clear JSDoc that explains its purpose.


30-34: New utility function improves naming consistency.

The getPothosPrismaPrimaryKeyTypeOutputName function standardizes type output naming, making it more consistent and reducing the chance of naming errors.


40-40: Dependency updates and parameter renaming for consistency.

These changes align the generator with the updated architecture:

  • Adding order to the destructured parameters
  • Replacing pothosSchema with pothosSchemaBaseTypes
  • Using the new naming function for type outputs
  • Updating parameter names to match the provider changes

Also applies to: 45-45, 50-50, 53-53


59-63: Improved options creation with builder fragment and empty type references.

Using pothosTypeFile.getBuilderFragment() instead of a hardcoded string improves maintainability, while initializing typeReferences as an empty array provides better structure.


80-84: Structured type reference creation improves consistency.

Using the createPothosTypeReference function with named parameters provides a more structured and type-safe way to create type references, with clear property names.


93-96: Direct type definition with order property for explicit control.

Adding the type definition directly to pothosTypeFile.typeDefinitions with the order property included provides explicit control over type ordering in the generated output.

packages/fastify-generators/src/generators/pothos/pothos-enums-file/pothos-enums-file.generator.ts (1)

56-61: Consider path.join instead of path.posix.join for cross-platform FS paths

path.posix.join forces forward slashes even on Windows.
While that’s perfect for import specifiers, it may break when the same string is later used as a real file-system path (e.g. when the builder writes the file on Windows).

-const typesPath = path.posix.join(
+const typesPath = path.join(

If you do rely on the POSIX form downstream (e.g. for import specifiers), keep path.posix here and convert to path.join only when invoking fs APIs.

packages/fastify-generators/src/generators/pothos/pothos-prisma-list-query/pothos-prisma-list-query.generator.ts (1)

56-58: Generic parameter of createNonOverwriteableMap looks off

createNonOverwriteableMap<Record<string, TsCodeFragment>>({}) defines the value as an object rather than TsCodeFragment.
Downstream you call .set(field.name, field.value) which expects the map value to be a fragment, not a record.

-const customFields = createNonOverwriteableMap<
-  Record<string, TsCodeFragment>
->({});
+const customFields = createNonOverwriteableMap<TsCodeFragment>({});

Double-check the helper’s signature; this adjustment aligns types with usage.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/graphql-plugin.ts (1)

92-96: Headers.forEach loses duplicated header keys (e.g. set-cookie)
Fastify needs reply.header('set-cookie', value, 'append') for multiple cookies.
Headers.forEach collapses duplicates – only the last value survives.
Consider iterating with response.headers.getSetCookie() or headers.raw()['set-cookie'] and using reply.header(key, value, 'append').

packages/fastify-generators/src/generators/vitest/prisma-vitest/prisma-vitest.generator.ts (1)

58-78: Top-level await inside the global-setup fragment may break CommonJS builds
The generated snippet contains:

// create separate test DB
const testDatabaseUrl = await createTestDatabase(process.env.DATABASE_URL);

If vitest.config.ts ends up in commonjs or targets Node < 14.8, top-level await is a syntax error.
Verify that tsCodeFragment wraps this snippet in an async function (Vitest requires export async function setup() { … }).
If not, wrap explicitly:

- const { TEST_MODE } = process.env;
+ export default async function prismaGlobalSetup() {
+   const { TEST_MODE } = process.env;- }
+ }
packages/fastify-generators/src/generators/pothos/pothos-sentry/pothos-sentry.generator.ts (1)

90-95: Confirm tsImportBuilder().default() API exists

tsImportBuilder() is called without arguments and then .default('TracingPlugin') is chained.
The published helper shown in builder.ts only exposes namedImports – the fluent default() method is not demonstrated. If that method is missing, the generated import will be undefined and TypeScript will fail to compile.

Please verify the builder’s public API or switch to:

tsImportDeclarationBuilder({ defaultImport: { name: 'TracingPlugin' } })
  .from('@pothos/plugin-tracing')
packages/fastify-generators/src/writers/pothos/resolvers.ts (1)

37-45: Potential name collision when singularising list arguments

Passing

name: nestedField.isList ? singularize(nestedField.name) : `${arg.name}.${nestedField.name}`,

may create duplicate identifiers if two sibling list fields singularise to the same value (e.g. categories & category).
Add a collision-avoidance strategy (suffixing, uniqueId(), etc.) before emitting variable names.

packages/fastify-generators/src/writers/pothos/helpers.ts (1)

114-118: List fallback emits string scalar names – verify expected shape

The fallback generates:

['Uuid']

i.e. an array of string literals.
Ensure Pothos expects string scalar names in this form; otherwise import and pass the scalar reference:

- type: tsCodeFragment(field.isList ? `[${quotedScalarName}]` : quotedScalarName),
+ type: getPothosTypeAsFragment(tsCodeFragment(quotedScalarName), field.isList),
packages/fastify-generators/src/writers/pothos/options.ts (1)

157-175: LGTM on the new PothosWriterOptions shape
Switching schemaBuilder to TsCodeFragment and simplifying typeReferences improves flexibility and aligns with the rest of the refactor.

packages/fastify-generators/src/generators/yoga/yoga-plugin/templates/websocket.ts (4)

1-2: Remove // @ts-nocheck to regain compile-time safety

ts-nocheck silences all type errors in the template.
Now that the file is fairly mature and relies on subtle ws/Fastify typings, restoring the type checker will help catch accidental regressions (e.g. misuse of WebSocket.OPEN, wrong callback signatures, etc.).

-// @ts-nocheck
+
+// NOTE: Keep the type checker enabled – the generator should inject valid TS.

[ suggest_optional_refactor ]


51-56: Typo in JSDoc – “timout” → “timeout”

Minor, but worth fixing to avoid propagating the typo into IDE tooltips.

-   * The timout between dispatched keep-alive messages. Internally uses the [ws Ping and Pongs]…
+   * The timeout between dispatched keep-alive messages. Internally uses the [ws Ping and Pongs]…

[ suggest_nitpick ]


126-147: Use ws.WebSocket.OPEN instead of the non-standard socket.OPEN constant

OPEN is a static property on the WebSocket class, not on its
instances. Accessing it through socket works only because ws copies
the static fields onto the instance at runtime, but TypeScript’s typings
do not reflect this, so the code will fail the type checker once
ts-nocheck is removed.

-            if (socket.readyState === socket.OPEN) {
+            if (socket.readyState === ws.WebSocket.OPEN) {

[ flag_critical_issue ]


210-214: Placeholder TPL_ON_CONNECT can break compilation if left blank

The object literal currently contains:

execute: ,
TPL_ON_CONNECT,
subscribe: ,

If the generator expands TPL_ON_CONNECT to an empty string (e.g.
because no custom onConnect is required) the trailing comma will leave
an orphan comma and the file will not compile.
Ensure the placeholder expands to a full property (including key and
comma) or gate its insertion:

-    execute: …,
-    TPL_ON_CONNECT,
-    subscribe: …,
+    execute: …,
+    /* TPL_ON_CONNECT */
+    subscribe: …,

so that removal leaves valid code.
[ request_verification ]

packages/fastify-generators/src/generators/pothos/pothos-prisma-crud-mutation/pothos-prisma-crud-mutation.generator.ts (2)

186-205: context is always forwarded – breaks services that don’t expect it

SERVICE_ARGUMENTS unconditionally injects context, even when
serviceOutput.requiresContext === false. This produces a type error
for service methods that have no context parameter.

-                    context: 'context',
+                    ...(serviceOutput.requiresContext
+                      ? { context: 'context' }
+                      : {}),

You can drop the unused CONTEXT replacement in the surrounding
formatFragment, because the variable is no longer referenced.

[ flag_critical_issue ]


48-53: Validate order and add positive constraint

descriptorSchema allows any number (including NaN, negative or
fractional). Consider tightening:

-  order: z.number(),
+  order: z.number().int().nonnegative(),

to prevent accidental invalid values that would later break the
topological merge.
[ suggest_nitpick ]

packages/core-generators/src/renderers/typescript/fragments/utils.ts (2)

24-34: Edge direction in dependencies may be inverted

flattenHoistedFragment records edges as [child.key, key]. If the
intention is “child depends on parent”, the correct edge for a
topological sort is usually [parent, child] (parent must appear first
so that child can depend on it). An inverted edge results in the parent
being scheduled after its children, breaking lexical-closeness
ordering.

Please double-check against toposortLocal’s contract; swap the tuple
order if necessary.

-    fragment.hoistedFragments?.map((f) => [f.key, key]) ?? [];
+    fragment.hoistedFragments?.map((f) => [key, f.key]) ?? [];

[ request_verification ]


124-137: Duplicate imports are not deduplicated – may yield identical lines

uniqWith is applied to hoisted fragments, but flattenResult.imports
is forwarded verbatim, so identical import specifiers can appear
multiple times. Suggest deduplicating before returning:

  return {
-    imports: flattenResult.imports,
+    imports: uniqWith(flattenResult.imports, isEqual),

(This mirrors the hoisted-fragment dedup logic.)
[ suggest_optional_refactor ]

packages/fastify-generators/src/generators/core/fastify-sentry/fastify-sentry.generator.ts (2)

234-236: Verify helper name: mergeFragmentsAsArray may not exist

TsCodeUtils exposes mergeFragmentsAsArrayPresorted (and recently mergeFragmentsAsArrayUnsorted).
If mergeFragmentsAsArray is not exported, this will be a compile-time error.

Please confirm the function name or update accordingly:

-  TPL_INTEGRATIONS: TsCodeUtils.mergeFragmentsAsArray(sentryIntegrations),
+  TPL_INTEGRATIONS: TsCodeUtils.mergeFragmentsAsArrayPresorted(
+    sentryIntegrations,
+  ),

182-185: z import for validator fragment is implicit – ensure it’s present

tsCodeFragment('z.string().optional()') requires import { z } from 'zod' to be hoisted.
configServiceImportsProvider probably already exposes that import, but if the template omits it the generated file will not compile.

Double-check that configServiceImports adds the z import to any file where this validator is emitted.

packages/fastify-generators/src/writers/pothos/object-types.ts (1)

81-94: Template placeholder uses bare BUILDER token.

If options.schemaBuilder is itself a fragment that declares imports, using it as a raw substitution (BUILDER) instead of a formatted fragment may lose the imports.
Safer:

-    `const VARIABLE_NAME = BUILDER.simpleObject(NAME, {
+    `const VARIABLE_NAME = ${options.schemaBuilder}.simpleObject(NAME, {

(or wrap it with TsCodeUtils.formatFragment and provide SCHEMA_BUILDER placeholder).

packages/fastify-generators/src/generators/yoga/yoga-plugin/yoga-plugin.generator.ts (1)

300-327: extractTemplateSnippet failure not guarded.

If snippet ON_CONNECT is missing from websocket-fragments.ts, TypescriptCodeUtils.extractTemplateSnippet will return an empty string, but subsequent formatFragment still runs, producing invalid code.
Add an explicit check and throw with a helpful message to fail fast.

packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts (1)

134-139:

Details

❌ Incorrect review comment

Inconsistent builder path (.js vs .ts) may break runtime imports

getImportMap exposes the builder as .../builder.js, while later you import the fragment from builderPath that ends with .ts.
Depending on the module resolver (and whether .ts files are transpiled in-place), this mismatch can produce two separate modules (or even a runtime resolution error).

-  path: '@/src/plugins/graphql/builder.js',
+  path: '@/src/plugins/graphql/builder.ts',

and/or

- tsImportBuilder(['builder']).from(builderPath),
+ tsImportBuilder(['builder']).from(builderPath.replace(/\.ts$/, '.js')),

Align both references to the same emitted file extension.

Also applies to: 278-299


🏁 Script executed:

#!/bin/bash
set -e
FILE="packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts"

echo "=== Occurrences of 'builderPath' ==="
rg "builderPath" -n "$FILE" || true

echo ""
echo "=== Occurrences of 'tsImportBuilder' ==="
rg "tsImportBuilder" -n "$FILE" || true

echo ""
echo "=== Context around 'getImportMap' ==="
rg -n -A2 -B2 "getImportMap" "$FILE" || true

Length of output: 1393


🏁 Script executed:

#!/bin/bash
set -e
FILE="packages/fastify-generators/src/generators/pothos/pothos/pothos.generator.ts"

echo "=== Import statement for tsImportBuilder ==="
sed -n '1,40p' "$FILE" | rg "import .*tsImportBuilder" || true

echo ""
echo "=== Searching definition of tsImportBuilder ==="
rg -n "function tsImportBuilder" -n .
rg -n "export .*tsImportBuilder" -n .

Length of output: 732


🏁 Script executed:

#!/bin/bash
set -e
echo "=== Searching for getImportMap usages in the repository ==="
rg "getImportMap" -n .

Length of output: 5493


Ignore .js vs .ts mismatch here

The distinction is intentional:

  • builderPath points to the TypeScript source file used by the generator (builder.ts).
  • getImportMap must reference the runtime-loaded module (the transpiled .js).

No change required.

Likely an incorrect or invalid review comment.

Comment on lines +215 to 219
// definitive hack until we convert this to using the new TS system
FILE_OBJECT_MODULE:
fileObjectRef.fragment.imports?.[0].moduleSpecifier ?? '',
FILE_OBJECT_TYPE: fileObjectRef.fragment.contents,
},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Potentially invalid replacement tokens when no imports exist

fileObjectRef.fragment.imports?.[0] can be undefined, resulting in an empty string replacement for FILE_OBJECT_MODULE; generated code will then include from '', which is invalid ES import syntax.

Guard against the missing-import case or compute the module specifier deterministically:

- FILE_OBJECT_MODULE:
-   fileObjectRef.fragment.imports?.[0].moduleSpecifier ?? '',
+ FILE_OBJECT_MODULE: (() => {
+   const [firstImport] = fileObjectRef.fragment.imports ?? [];
+   if (!firstImport) {
+     throw new Error('fileObjectRef is missing expected import information');
+   }
+   return firstImport.moduleSpecifier;
+ })(),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// definitive hack until we convert this to using the new TS system
FILE_OBJECT_MODULE:
fileObjectRef.fragment.imports?.[0].moduleSpecifier ?? '',
FILE_OBJECT_TYPE: fileObjectRef.fragment.contents,
},
// definitive hack until we convert this to using the new TS system
FILE_OBJECT_MODULE: (() => {
const [firstImport] = fileObjectRef.fragment.imports ?? [];
if (!firstImport) {
throw new Error('fileObjectRef is missing expected import information');
}
return firstImport.moduleSpecifier;
})(),
FILE_OBJECT_TYPE: fileObjectRef.fragment.contents,
},

Comment on lines 80 to 98
setupFileInputSchema: createGeneratorTask({
dependencies: {
appModule: appModuleProvider,
pothosSetup: pothosSetupProvider,
pothosConfig: pothosConfigProvider,
},
run({ pothosSetup, appModule }) {
run({ pothosConfig, appModule }) {
const moduleFolder = appModule.getModuleFolder();
pothosSetup.getTypeReferences().addInputType({
typeName: 'FileUploadInput',
exportName: 'fileUploadInputInputType',
moduleName: path.posix.join(
moduleFolder,
'schema/file-upload.input-type.js',
),
});
pothosConfig.inputTypes.set(
'FileUploadInput',
createPothosTypeReference({
name: 'FileUploadInput',
exportName: 'fileUploadInputInputType',
moduleSpecifier: path.posix.join(
moduleFolder,
'schema/file-upload.input-type.js',
),
}),
);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

setupFileInputSchema may silently overwrite an existing registration

pothosConfig.inputTypes.set('FileUploadInput', …) unconditionally replaces any prior entry. If multiple modules invoke this generator the latter call wins, potentially breaking earlier schemas.

- pothosConfig.inputTypes.set(
-   'FileUploadInput',
-   createPothosTypeReference({ … }),
- );
+ if (!pothosConfig.inputTypes.has('FileUploadInput')) {
+   pothosConfig.inputTypes.set(
+     'FileUploadInput',
+     createPothosTypeReference({ … }),
+   );
+ }

Consider logging when a duplicate is ignored to aid debugging.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setupFileInputSchema: createGeneratorTask({
dependencies: {
appModule: appModuleProvider,
pothosSetup: pothosSetupProvider,
pothosConfig: pothosConfigProvider,
},
run({ pothosSetup, appModule }) {
run({ pothosConfig, appModule }) {
const moduleFolder = appModule.getModuleFolder();
pothosSetup.getTypeReferences().addInputType({
typeName: 'FileUploadInput',
exportName: 'fileUploadInputInputType',
moduleName: path.posix.join(
moduleFolder,
'schema/file-upload.input-type.js',
),
});
pothosConfig.inputTypes.set(
'FileUploadInput',
createPothosTypeReference({
name: 'FileUploadInput',
exportName: 'fileUploadInputInputType',
moduleSpecifier: path.posix.join(
moduleFolder,
'schema/file-upload.input-type.js',
),
}),
);
setupFileInputSchema: createGeneratorTask({
dependencies: {
appModule: appModuleProvider,
pothosConfig: pothosConfigProvider,
},
run({ pothosConfig, appModule }) {
const moduleFolder = appModule.getModuleFolder();
if (!pothosConfig.inputTypes.has('FileUploadInput')) {
pothosConfig.inputTypes.set(
'FileUploadInput',
createPothosTypeReference({
name: 'FileUploadInput',
exportName: 'fileUploadInputInputType',
moduleSpecifier: path.posix.join(
moduleFolder,
'schema/file-upload.input-type.js',
),
}),
);
}

Comment on lines 176 to +179
serviceFile.registerMethod(
name,
getMethodBlock(methodOptions),
getMethodDefinition(serviceMethodExpression, methodOptions),
getMethodDefinition(serviceMethodReference, methodOptions),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Method name mismatch leads to unresolvable symbol

serviceFile.registerMethod is called with name (e.g. "create"), yet the generated implementation/definition uses methodName (e.g. "createUser"). Down-stream imports that rely on the key returned by registerMethod will therefore not find the implementation.

- serviceFile.registerMethod(
-   name,
+ serviceFile.registerMethod(
+   methodName,
   getMethodBlock(methodOptions),
   getMethodDefinition(serviceMethodReference, methodOptions),
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
serviceFile.registerMethod(
name,
getMethodBlock(methodOptions),
getMethodDefinition(serviceMethodExpression, methodOptions),
getMethodDefinition(serviceMethodReference, methodOptions),
serviceFile.registerMethod(
methodName,
getMethodBlock(methodOptions),
getMethodDefinition(serviceMethodReference, methodOptions),
);

Comment on lines +239 to 242
const sortedKeys = disableSort
? keys
: keys.toSorted(caseSensitive ? undefined : (a, b) => a.localeCompare(b));

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Array.prototype.toSorted is not available on Node ≤18

toSorted landed in ES2023 and is absent in the current LTS (Node 18). Using it directly will throw TypeError: toSorted is not a function in many production environments.

Replace with a backwards-compatible helper:

- : keys.toSorted(caseSensitive ? undefined : (a, b) => a.localeCompare(b));
+ : [...keys].sort(
+     caseSensitive ? undefined : (a, b) => a.localeCompare(b),
+   );

(or poly-fill the method globally).


🏁 Script executed:

#!/bin/bash
# Search for all usages of Array.prototype.toSorted in the codebase
rg "toSorted\(" -n

Length of output: 1230


Replace toSorted with a backwards-compatible helper
Array.prototype.toSorted is an ES2023 feature and isn’t available in Node ≤18. Calling it in our generators will throw “TypeError: toSorted is not a function” in LTS environments.

Introduce a small utility, for example in ts-code-utils.ts:

/** Clone and sort an array without mutating the original. */
export function sorted<T>(arr: T[], compareFn?: (a: T, b: T) => number): T[] {
  return [...arr].sort(compareFn);
}

Then replace all direct .toSorted(...) calls, e.g. in
packages/core-generators/src/renderers/typescript/utils/ts-code-utils.ts at lines 241 and 321:

- const sortedKeys = disableSort
-   ? keys
-   : keys.toSorted(caseSensitive ? undefined : (a, b) => a.localeCompare(b));
+ const sortedKeys = disableSort
+   ? keys
+   : sorted(keys, caseSensitive ? undefined : (a, b) => a.localeCompare(b));

And apply the same pattern in the other affected files:

  • packages/core-generators/src/writers/typescript/import-order.ts
  • packages/core-generators/src/generators/node/prettier/prettier.generator.ts
  • packages/core-generators/src/generators/node/vitest/vitest.generator.ts
  • packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.ts
  • packages/react-generators/src/generators/apollo/react-apollo/react-apollo.generator.ts
  • packages/sync/src/templates/text-template/text-template-file-extractor.ts
  • packages/fastify-generators/src/generators/core/app-module/app-module.generator.ts

This keeps our code runnable on Node 18 while preserving the non-mutating sort behavior.

Comment on lines +48 to 55
const pothosFields: PothosCodeFragment[] = fields.map((field) => {
if (field.type === 'scalar') {
return {
expression: writePothosObjectFieldFromDtoScalarField(field, options),
fragment: writePothosObjectFieldFromDtoScalarField(field, options),
};
}
return writeSimplePothosObjectFieldFromDtoNestedField(field, options);
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Scalar-field dependencies are dropped.

When the field is scalar the mapper returns

{ fragment: writePothosObjectFieldFromDtoScalarField() }

but omits a dependencies property. Any imports produced by writePothosObjectFieldFromDtoScalarField will therefore be lost, and the downstream flatMap((f) => f.dependencies) will insert an undefined, later filtered out.

Expose dependencies explicitly:

-      return {
-        fragment: writePothosObjectFieldFromDtoScalarField(field, options),
-      };
+      const scalarFragment = writePothosObjectFieldFromDtoScalarField(
+        field,
+        options,
+      );
+      return {
+        fragment: scalarFragment,
+        dependencies: [],       // or scalarFragment.dependencies if it returns one
+      };

Comment on lines +173 to 195
? tsCodeFragment(
`fastify.route({
url: '/graphql',
method: 'GET',
handler: httpHandler,
wsHandler: getGraphqlWsHandler(graphQLServer),
});
pluginFile.addCodeExpression(
'ENVELOP_PLUGINS',
TypescriptCodeUtils.mergeExpressionsAsArray(
config.envelopPlugins,
),
);

pluginFile.addCodeBlock(
'GRAPHQL_HANDLER',
enableSubscriptions
? TypescriptCodeUtils.createBlock(
`fastify.route({
url: '/graphql',
method: 'GET',
handler: httpHandler,
wsHandler: getGraphqlWsHandler(graphQLServer),
});
fastify.route({
url: '/graphql',
method: ['POST', 'OPTIONS'],
handler: httpHandler,
});`,
"import { getGraphqlWsHandler } from './websocket.js';",
)
: `fastify.route({
url: '/graphql',
method: ['GET', 'POST', 'OPTIONS'],
handler: httpHandler,
});`,
);
fastify.route({
url: '/graphql',
method: ['POST', 'OPTIONS'],
handler: httpHandler,
});`,
tsImportBuilder(['getGraphqlWsHandler']).from(
'./websocket.js',
),
)
: `fastify.route({
url: '/graphql',
method: ['GET', 'POST', 'OPTIONS'],
handler: httpHandler,
});`;

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent fragment type for graphqlHandler.

graphqlHandler is a TsCodeFragment when subscriptions are enabled but a raw string otherwise.
Down-stream template substitution expects consistent fragment handling (imports, formatting).
Wrap the non-subscription branch in tsCodeFragment to keep the API uniform.

-              : `fastify.route({
+              : tsCodeFragment(
+                  `fastify.route({
 url: '/graphql',
 method: ['GET', 'POST', 'OPTIONS'],
 handler: httpHandler,
-});`;
+});`,
+                )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
? tsCodeFragment(
`fastify.route({
url: '/graphql',
method: 'GET',
handler: httpHandler,
wsHandler: getGraphqlWsHandler(graphQLServer),
});
pluginFile.addCodeExpression(
'ENVELOP_PLUGINS',
TypescriptCodeUtils.mergeExpressionsAsArray(
config.envelopPlugins,
),
);
pluginFile.addCodeBlock(
'GRAPHQL_HANDLER',
enableSubscriptions
? TypescriptCodeUtils.createBlock(
`fastify.route({
url: '/graphql',
method: 'GET',
handler: httpHandler,
wsHandler: getGraphqlWsHandler(graphQLServer),
});
fastify.route({
url: '/graphql',
method: ['POST', 'OPTIONS'],
handler: httpHandler,
});`,
"import { getGraphqlWsHandler } from './websocket.js';",
)
: `fastify.route({
url: '/graphql',
method: ['GET', 'POST', 'OPTIONS'],
handler: httpHandler,
});`,
);
fastify.route({
url: '/graphql',
method: ['POST', 'OPTIONS'],
handler: httpHandler,
});`,
tsImportBuilder(['getGraphqlWsHandler']).from(
'./websocket.js',
),
)
: `fastify.route({
url: '/graphql',
method: ['GET', 'POST', 'OPTIONS'],
handler: httpHandler,
});`;
? tsCodeFragment(
`fastify.route({
url: '/graphql',
method: 'GET',
handler: httpHandler,
wsHandler: getGraphqlWsHandler(graphQLServer),
});
fastify.route({
url: '/graphql',
method: ['POST', 'OPTIONS'],
handler: httpHandler,
});`,
tsImportBuilder(['getGraphqlWsHandler']).from(
'./websocket.js',
),
)
: tsCodeFragment(
`fastify.route({
url: '/graphql',
method: ['GET', 'POST', 'OPTIONS'],
handler: httpHandler,
});`,
)

Comment on lines +51 to 60
'useGraphLogger()',
tsImportBuilder(['useGraphLogger']).from('./useGraphLogger.js'),
),
useDisableIntrospection: tsCodeFragment(
'useDisableIntrospection({ disableIf: () => !IS_DEVELOPMENT })',
"import { useDisableIntrospection } from '@envelop/disable-introspection';",
tsImportBuilder(['useDisableIntrospection']).from(
'@envelop/disable-introspection',
),
),
]),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

useDisableIntrospection references an undefined IS_DEVELOPMENT.

The fragment

useDisableIntrospection({ disableIf: () => !IS_DEVELOPMENT })

will fail unless IS_DEVELOPMENT is globally available in the generated file. Verify that such a constant (or env injection) exists, or inline the check via process.env.NODE_ENV !== 'production'.


🏁 Script executed:

#!/bin/bash
# Search for any declaration or usage of IS_DEVELOPMENT in the repo
rg -n "IS_DEVELOPMENT" .

Length of output: 2536


Missing definition of IS_DEVELOPMENT in generated code

The tsCodeFragment in
packages/fastify-generators/src/generators/yoga/yoga-plugin/yoga-plugin.generator.ts (around line 56)
injects:

useDisableIntrospection({ disableIf: () => !IS_DEVELOPMENT })

but no IS_DEVELOPMENT constant is ever declared or imported in the generated file. This will cause a runtime error in any new Yoga plugin.

Possible fixes:

  • Define the constant before it’s used:

    tsCodeFragment(
      'const IS_DEVELOPMENT = process.env.NODE_ENV === "development";'
    ),

    and insert it ahead of the plugin fragments.

  • Or inline the check and remove the undefined identifier:

    - useDisableIntrospection({ disableIf: () => !IS_DEVELOPMENT })
    + useDisableIntrospection({ disableIf: () => process.env.NODE_ENV === 'production' })

Please update the generator to ensure IS_DEVELOPMENT is either defined or the check is inlined.

Comment on lines +330 to 335
tsImportBuilder([
'printSchema',
'lexicographicSortSchema',
]).from('graphql'),
tsImportBuilder().default('fs').from('fs/promises'),
],
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

fs/promises has no default export

import fs from 'fs/promises' resolves to undefined at runtime. Use a namespace import instead:

-tsImportBuilder().default('fs').from('fs/promises'),
+tsImportBuilder().namespace('fs').from('node:fs/promises'),

(or adjust the template accordingly).

Comment on lines 48 to 53
if (field.type === 'scalar') {
return {
expression: writePothosInputFieldFromDtoScalarField(field, options),
fragment: writePothosInputFieldFromDtoScalarField(field, options),
};
}
return writePothosInputFieldFromDtoNestedField(field, options);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Scalar-field dependencies are dropped

For scalar branches you return { fragment: … } without propagating dependencies.
If writePothosInputFieldFromDtoScalarField ever returns non-empty dependencies (e.g. custom scalars), they will be lost.

-  return {
-    fragment: writePothosInputFieldFromDtoScalarField(field, options),
-  };
+  return writePothosInputFieldFromDtoScalarField(field, options);

(The helper already returns a PothosCodeFragment.)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (field.type === 'scalar') {
return {
expression: writePothosInputFieldFromDtoScalarField(field, options),
fragment: writePothosInputFieldFromDtoScalarField(field, options),
};
}
return writePothosInputFieldFromDtoNestedField(field, options);
if (field.type === 'scalar') {
- return {
- fragment: writePothosInputFieldFromDtoScalarField(field, options),
- };
+ return writePothosInputFieldFromDtoScalarField(field, options);
}
return writePothosInputFieldFromDtoNestedField(field, options);

@kingston kingston merged commit 4695cbe into main May 2, 2025
7 checks passed
@kingston kingston deleted the kingston/eng-632-convert-pothos-fastify-generators-to-new-typescript-template branch May 2, 2025 14:57
@github-actions github-actions bot mentioned this pull request May 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants