Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(runtime): Refactor logical client exports to be ESM/CJS agnostic #2078

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

diesal11
Copy link
Contributor

@diesal11 diesal11 commented Apr 10, 2025

When zenstack generate is run in a project with "type": "module" in it's package.json, startup fails with the following error:

 ⚠ ./lib/zenstack/models.js
Specified module format (EcmaScript Modules) is not matching the module format of the source code (CommonJs)
The EcmaScript module format was specified in the package.json that is affecting this source file or by using an special extension, but it looks like that CommonJs syntax is used in the source code.
Exports made by CommonJs syntax will lead to a runtime error, since the module is in EcmaScript mode. Either change the "type" field in the package.json or replace CommonJs syntax with EcmaScript import/export syntax in the source file.

Sidenote: Should this simply be inferred by reading package.json? I wasn't certain that would catch some cases in a monorepo.

Copy link
Contributor

coderabbitai bot commented Apr 10, 2025

📝 Walkthrough

Walkthrough

The changes update the logical client generation in the enhancer module. In the file packages/schema/src/plugins/enhancer/enhance/index.ts, the reference for the Prisma type import has been updated from using /index-fixed to /index. Additionally, the generated file for the models has been renamed from models.d.ts to models.ts, with the corresponding save method adjusted. The return path for the Prisma client type definitions has also been changed from index-fixed.d.ts to index.d.ts, and related comments have been updated accordingly.

Changes

File(s) Change Summary
packages/schema/src/plugins/enhancer/enhance/index.ts - Updated resultPrismaTypeImport from /index-fixed to /index
- Changed models file creation from models.d.ts to models.ts
- Replaced modelsDts.save() with modelsTs.save()
- Modified return path from index-fixed.d.ts to index.d.ts and updated comments in processClientTypes

Sequence Diagram(s)

sequenceDiagram
    participant EG as EnhancerGenerator
    participant FS as FileSystem
    EG->>FS: Import Prisma type from "/index" (was "/index-fixed")
    EG->>FS: Create models.ts file (was models.d.ts)
    EG->>FS: Save Prisma client types to "index.d.ts" (overwriting previous file)
Loading

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0fab3e6 and 017d66e.

📒 Files selected for processing (1)
  • packages/schema/src/plugins/enhancer/enhance/index.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/schema/src/plugins/enhancer/enhance/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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.

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 docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
Contributor

@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: 1

🧹 Nitpick comments (1)
packages/schema/src/cli/index.ts (1)

128-128: Good addition of the --esm flag

The new command line option provides a clear way for users to specify ESM output format when needed, which directly addresses the issue for projects with "type": "module" in their package.json.

One potential enhancement to consider (not required): could the ESM setting be automatically inferred from the package.json "type": "module" setting? This would reduce the need for manual flag specification, though as mentioned in the PR description, this might be challenging in monorepo setups.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d2a4ec0 and 6710a10.

📒 Files selected for processing (3)
  • packages/schema/src/cli/index.ts (1 hunks)
  • packages/schema/src/plugins/enhancer/enhance/index.ts (2 hunks)
  • packages/sdk/src/types.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/schema/src/plugins/enhancer/enhance/index.ts (1)
packages/schema/build/bundle.js (1)
  • fs (4-4)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (2)
packages/schema/src/plugins/enhancer/enhance/index.ts (1)

131-136: Great implementation of conditional ESM/CommonJS exports.

The code elegantly handles both module formats based on the esm option, which correctly addresses the issue with projects using "type": "module" in their package.json.

packages/sdk/src/types.ts (1)

45-48: Well-implemented ESM support in plugin options

The addition of the esm property to PluginOptions is a clean approach to indicate module format preference. The property has a clear name, purpose, and is properly marked as optional to maintain backward compatibility.

@@ -338,6 +343,7 @@ export type Enhanced<Client> =
overrideClientGenerationPath: prismaClientOutDir,
mode: 'logical',
customAttributesAsComments: true,
isEsm: this.options.isEsm,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Property name inconsistency.

There's a mismatch between property names: isEsm is used here but esm is used in the PluginOptions type and elsewhere in this file. This could cause confusion or bugs.

Apply this change to maintain naming consistency:

-            isEsm: this.options.isEsm,
+            isEsm: this.options.esm,
📝 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
isEsm: this.options.isEsm,
isEsm: this.options.esm,

@ymc9
Copy link
Member

ymc9 commented Apr 11, 2025

Hi @diesal11 , I feel the entire approach is quite hacky now ... The original idea was to only reexport types from logical prisma client at "@zenstackhq/runtime/models", which was why previously only models.d.ts was generated. Then we found to import enums there you need value exports as well. For better safety, the "models.js" file reexports from the original prisma client, just to avoid accidentally importing duplicated copies of values from different prisma locations ...

I feel maybe it's an overkill. If we simply generate a "models.ts" to just reexport everything from logical prisma, the esm/cjs problem would just go away as it'll be compiled according to user's project settings. What do you think?

@diesal11 diesal11 force-pushed the fix/models-esm-export branch from 6710a10 to 0fab3e6 Compare April 12, 2025 05:10
@diesal11
Copy link
Contributor Author

Yes I agree this isn't an ideal approach. I've had another look and I believe what you're suggesting is possible, it would also require saving index-fixed.d.ts as index.d.ts within the logical schema so that types & values can be exported at once within a ts file.

Initially I wasn't confident touching the index-fixed.d.ts file as I wasn't sure about the reason this was saved separately. But I've quickly tested this solution in my side project by manually applying the changes and it appears to work without issue. It looks like most of the value exports from prisma client are just enum like objects that map to strings. So it looks like it should be fine.

Thanks for the feedback! I've updated the PR to implement this, let me chase down test failures :)

@diesal11 diesal11 force-pushed the fix/models-esm-export branch from 0fab3e6 to 017d66e Compare April 12, 2025 05:26
@diesal11 diesal11 changed the title fix(runtime): Add --esm flag to generate command, to export ".zenstack/models.js" in ESM format fix(runtime): Refactor logical client exports to be ESM/CJS agnostic Apr 12, 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