Skip to content

Conversation

@tbouffard
Copy link
Member

@tbouffard tbouffard commented May 13, 2025

The new commonjs resources are built with a new tsc command and now referenced in the package.json file.

Add new examples using CommonJS with Node.js to demonstrate the new support:

  • TypeScript example: show the integration with jest and ts-jest
  • JavaScript example: use maxGraph in a headless environment with Node.js (and jsdom).
    This example exports Graph Model as XML, and exports the rendered Graph to SVG.

In addition, add missing git extension in the repository attribute of the package.json file.

Notes

Closes #790
Closes #824
Covers #827

The implementation is inspired by https://medium.com/ekino-france/supporting-dual-package-for-cjs-and-esm-in-typescript-library-b5feabac1357

The size of the examples remains unchanged compared to #822.
See logs of the GH workflow run on commit 57c250e 👇🏿 https://github.com/maxGraph/maxGraph/actions/runs/14990485089/job/42112503223#step:9:249

Logs of the GH workflow run
##################################################
Files in packages/ts-example/dist directory:
##################################################
2.54 kB packages/ts-example/dist/assets/index-XPX6PJvz.js
435.23 kB packages/ts-example/dist/assets/maxgraph-DUJ4XncJ.js

##################################################
Files in packages/ts-example-jest-commonjs/dist directory:
##################################################
No dist directory found in packages/ts-example-jest-commonjs

##################################################
Files in packages/ts-example-selected-features/dist directory:
##################################################
2.47 kB packages/ts-example-selected-features/dist/assets/index-CG2i1Xd8.js
369.09 kB packages/ts-example-selected-features/dist/assets/maxgraph-BF6pCuCs.js

##################################################
Files in packages/ts-example-without-defaults/dist directory:
##################################################
1.77 kB packages/ts-example-without-defaults/dist/assets/index-DFbIbaiz.js
309.18 kB packages/ts-example-without-defaults/dist/assets/maxgraph-Ce65xPnK.js

##################################################
Files in packages/js-example/dist directory:
##################################################
467.58 kB packages/js-example/dist/main.232c3ff42bb552ca905e.js

##################################################
Files in packages/js-example-nodejs/dist directory:
##################################################
No dist directory found in packages/js-example-nodejs

##################################################
Files in packages/js-example-selected-features/dist directory:
##################################################
390.39 kB packages/js-example-selected-features/dist/main.3865a07f1c2324716dfe.js

##################################################
Files in packages/js-example-without-defaults/dist directory:
##################################################
325.44 kB packages/js-example-without-defaults/dist/main.2449303e1a3ab1069100.js

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added a TypeScript example project demonstrating Jest testing with ts-jest in a CommonJS environment.
    • Added a JavaScript example project showcasing maxGraph usage in a Node.js headless environment, including XML and SVG export.
  • Documentation

    • Updated documentation and README files to reference and explain the new example projects and their usage.
  • Chores

    • Enhanced dependency update configuration for broader test-related package coverage.
    • Improved package build scripts and module support for both CommonJS and ESM builds.

The new commonjs resources are built with a new tsc command and now referenced in the package.json file.

Add new examples using CommonJS with Node.js to demonstrate the new support:
- TypeScript example: show the integration with jest and ts-jest
- JavaScript example: use `maxGraph` in a headless environment with Node.js (and jsdom).
  This example exports Graph Model as XML, and exports the rendered Graph to SVG.

In addition, add missing git extension in the repository attribute of the package.json file.
@tbouffard tbouffard added the enhancement New feature or request label May 13, 2025
@coderabbitai
Copy link

coderabbitai bot commented May 13, 2025

Walkthrough

This change introduces dual ESM and CommonJS (CJS) build support for the @maxgraph/core package, updates its npm configuration, and adds two new example projects: one demonstrating Jest+ts-jest testing with CJS, and another showcasing Node.js headless usage with jsdom. Documentation and dependency management files are updated accordingly.

Changes

File(s) Change Summary
.github/dependabot.yml Expanded test dependency patterns for Dependabot monitoring to include jsdom, ts-jest, and related packages.
README.md
packages/website/docs/demo-and-examples.md
Added entries for new example projects (ts-example-jest-commonjs, js-example-nodejs) in documentation and README.
packages/core/package.json
packages/core/tsconfig.json
Added dual ESM+CJS build support: updated entry points, exports, types, scripts, and output directories. Repository URL fixed.
packages/core/scripts/generate-cjs-package-json.mjs New script to generate a package.json with "type": "commonjs" for the CJS build output.
packages/js-example-nodejs/* New example package: includes README, package.json, CJS/ESM entry scripts for headless Node.js usage with jsdom.
packages/ts-example-jest-commonjs/* New example package: includes README, package.json, Jest config, and TypeScript test cases demonstrating Jest+ts-jest integration with CJS.
packages/core/src/view/GraphView.ts Documentation and JSDoc comment fixes: updated type references and corrected minor spelling and phrasing errors.

Sequence Diagram(s)

sequenceDiagram
    participant Dev as Developer
    participant Jest as Jest (ts-jest)
    participant Node as Node.js (jsdom)
    participant MaxCore as @maxgraph/core (ESM/CJS)
    participant Graph as Graph Instance

    Dev->>Jest: Run tests (CommonJS)
    Jest->>MaxCore: require('@maxgraph/core') (CJS)
    MaxCore-->>Jest: Provide CJS API
    Jest->>Graph: Instantiate BaseGraph, run tests

    Dev->>Node: Run headless script (CommonJS)
    Node->>MaxCore: require('@maxgraph/core') (CJS)
    MaxCore-->>Node: Provide CJS API
    Node->>Graph: Instantiate BaseGraph, export XML/SVG
Loading

Assessment against linked issues

Objective Addressed Explanation
Provide CommonJS support in the npm package, including types (#824)
Create a minimal Jest + CommonJS example using ts-jest and verify type resolution (#824, #790)
Create a Node.js example using maxGraph with CommonJS + jsdom (#824)

Possibly related PRs

  • maxGraph/maxGraph#629: Extends Dependabot configuration for the "test" group, which is directly built upon in this PR by further expanding test dependency patterns.
  • maxGraph/maxGraph#808: Updates documentation comments in GraphView.ts, related by targeting the same class but differing in scope and type of changes.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 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 a3a6df5 and 7ae54d7.

📒 Files selected for processing (1)
  • packages/js-example-nodejs/src/index.mjs (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
packages/js-example-nodejs/src/index.mjs (1)
Learnt from: tbouffard
PR: maxGraph/maxGraph#826
File: packages/js-example-nodejs/src/index.cjs:64-69
Timestamp: 2025-05-13T12:54:55.231Z
Learning: For example code in the maxGraph repository, maintainers prefer to keep scripts simple without error handling to focus on demonstrating core functionality, especially in demonstration scripts like those in packages/js-example-nodejs.
🪛 ESLint
packages/js-example-nodejs/src/index.mjs

[error] 21-21: Unexpected console statement.

(no-console)

🔇 Additional comments (1)
packages/js-example-nodejs/src/index.mjs (1)

21-23: LGTM: Simple and clear example implementation.

This code provides a clean demonstration of how to create a BaseGraph instance in an ESM environment. The console output helps users understand what's happening when they run the example.

I'm ignoring the ESLint no-console warning since this is example code where console output is expected and appropriate.

🧰 Tools
🪛 ESLint

[error] 21-21: Unexpected console statement.

(no-console)

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 docstrings to generate docstrings for this 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.

This is more portable, the previous implementation failed on Windows.
@tbouffard tbouffard marked this pull request as ready for review May 13, 2025 07:46
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: 5

🧹 Nitpick comments (15)
packages/core/tsconfig.json (1)

9-9: Redirect ESM build output: Changing outDir to ./lib/esm correctly isolates the ESM artifacts for the dual-package setup. For improved build hygiene, consider configuring a distinct tsBuildInfoFile or using separate project references/tsconfig files to avoid incremental build caches clashing between the ESM and CJS outputs.

packages/ts-example-jest-commonjs/README.md (1)

9-14: Augment setup with test execution instructions: After building maxGraph@core, include the command to run the Jest tests (e.g., npm test or npx jest). This completes the end-to-end setup guidance and helps users verify their environment.

README.md (1)

156-156: Consistent link formatting: The js-example-nodejs link uses ./packages/js-example-nodejs, while other entries use packages/... without ./. Consider removing the ./ prefix for consistency.

packages/ts-example-jest-commonjs/package.json (1)

1-17: LGTM: Package configuration appropriately set up for CommonJS example with Jest

The package configuration is properly set up with the correct dependencies for Jest testing in a TypeScript CommonJS environment.

Consider adding a description field to provide context about this example package's purpose, and specify its relationship to the core package (potentially as a peer dependency or installation instruction in a README).

packages/js-example-nodejs/src/index.mjs (2)

2-2: Update copyright year

The copyright year is set to 2025, which is in the future.

-Copyright 2025-present The maxGraph project Contributors
+Copyright 2024-present The maxGraph project Contributors

17-18: Clarify TODO comment with issue reference

The TODO comment mentions "XXX" which appears to be a placeholder for an issue reference.

Consider updating the TODO with a specific issue number or more descriptive context about the planned fix:

-// TODO this fails because the import statements in the files of the maxGraph package doesn't add the "js" file extension
-// Node.js requires such extensions. This should be fixed when implementing XXX
+// TODO this fails because the import statements in the files of the maxGraph package don't include the ".js" file extension
+// Node.js requires these extensions for ESM imports. This will be fixed when implementing issue #XXX (ESM path resolution)
packages/js-example-nodejs/README.md (2)

1-1: Missing article in title

Consider adding the article "a" before "headless" for improved readability.

-# Integrate `maxGraph` in headless environment with Node.js
+# Integrate `maxGraph` in a headless environment with Node.js
🧰 Tools
🪛 LanguageTool

[uncategorized] ~1-~1: You might be missing the article “a” here.
Context: # Integrate maxGraph in headless environment with Node.js Demonstrate h...

(AI_EN_LECTOR_MISSING_DETERMINER_A)


15-22: Consider adding example execution instructions

The README provides good setup instructions but doesn't include how to run the examples after setup.

Consider adding a "Running the examples" section with commands to execute both the CommonJS and ESM examples:

 Build maxgraph@core
 > From the `packages/core` directory, run `npm run build`.
+
+## Running the examples
+
+Run the CommonJS example:
+> From the `packages/js-example-nodejs` directory, run `npm run example:cjs`.
+
+Run the ESM example (currently not working):
+> From the `packages/js-example-nodejs` directory, run `npm run example:esm`.
packages/ts-example-jest-commonjs/__tests__/index.ts (1)

1-15: Update copyright year

The copyright year is set to 2025, which is in the future. Consider updating to the current year.

-Copyright 2025-present The maxGraph project Contributors
+Copyright 2023-present The maxGraph project Contributors

Ensure you use the correct starting year for this new file.

packages/core/scripts/generate-cjs-package-json.mjs (3)

1-15: Update copyright year

The copyright year is set to 2025, which is in the future. Consider updating to the current year.

-Copyright 2025-present The maxGraph project Contributors
+Copyright 2023-present The maxGraph project Contributors

Ensure you use the correct starting year for this new file.


19-21: Add error handling for file operations

The writeJsonContentToFile function doesn't include error handling, which could lead to silent failures.

 const writeJsonContentToFile = (path, obj) => {
-  writeFileSync(path, JSON.stringify(obj, null, 2) + '\n');
+  try {
+    writeFileSync(path, JSON.stringify(obj, null, 2) + '\n');
+  } catch (error) {
+    console.error(`Failed to write package.json to ${path}:`, error);
+    process.exit(1);
+  }
 };

23-29: Consider handling directory creation

The script assumes the lib/cjs directory exists, but it might not if the TypeScript compilation failed or hasn't been run yet.

+import { existsSync, mkdirSync } from 'node:fs';
+import { dirname } from 'node:path';

 console.info('Writing package.json file for CommonJS...');

 const path = 'lib/cjs/package.json';
+
+// Ensure the directory exists
+const dir = dirname(path);
+if (!existsSync(dir)) {
+  console.info(`Creating directory ${dir}...`);
+  mkdirSync(dir, { recursive: true });
+}
+
 const packageJson = { type: 'commonjs' };
 writeJsonContentToFile(path, packageJson);

 console.info('package.json file for CommonJS written to', path);
🧰 Tools
🪛 ESLint

[error] 23-23: Unexpected console statement.

(no-console)


[error] 29-29: Unexpected console statement.

(no-console)

packages/js-example-nodejs/src/index.cjs (2)

1-15: Update copyright year

The copyright year is set to 2025, which is in the future. Consider updating to the current year.

-Copyright 2025-present The maxGraph project Contributors
+Copyright 2023-present The maxGraph project Contributors

Ensure you use the correct starting year for this new file.


84-101: Consider adding JSDoc parameters and return type

The export method could benefit from complete JSDoc documentation of parameters and return type.

/**
+ * Exports the graph as an SVG string
+ * @param {Object} [options] - Export options
+ * @param {number} [options.margin=10] - Margin to add around the graph bounds
+ * @returns {string} The SVG content as a string
+ */
export(options) {
packages/core/package.json (1)

56-58: Simplify and order build scripts
The current wildcard run-s build:* will run build:cjs then build:esm alphabetically, which may be non-intuitive. Also, logging tsc --version on every build can clutter CI logs. Consider explicitly sequencing the builds and removing the version check:

-  "build": "run-s build:*",
-  "build:esm": "tsc --version && tsc",
-  "build:cjs": "tsc --version && tsc --outDir lib/cjs --module commonjs && node scripts/generate-cjs-package-json.mjs",
+  "build": "run-s build:esm build:cjs",
+  "build:esm": "tsc",
+  "build:cjs": "tsc --outDir lib/cjs --module commonjs && node scripts/generate-cjs-package-json.mjs",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7b1985 and 57c250e.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (14)
  • .github/dependabot.yml (1 hunks)
  • README.md (1 hunks)
  • packages/core/package.json (2 hunks)
  • packages/core/scripts/generate-cjs-package-json.mjs (1 hunks)
  • packages/core/tsconfig.json (1 hunks)
  • packages/js-example-nodejs/README.md (1 hunks)
  • packages/js-example-nodejs/package.json (1 hunks)
  • packages/js-example-nodejs/src/index.cjs (1 hunks)
  • packages/js-example-nodejs/src/index.mjs (1 hunks)
  • packages/ts-example-jest-commonjs/README.md (1 hunks)
  • packages/ts-example-jest-commonjs/__tests__/index.ts (1 hunks)
  • packages/ts-example-jest-commonjs/jest.config.cjs (1 hunks)
  • packages/ts-example-jest-commonjs/package.json (1 hunks)
  • packages/website/docs/demo-and-examples.md (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
packages/website/docs/demo-and-examples.md (3)
Learnt from: tbouffard
PR: maxGraph/maxGraph#791
File: packages/ts-example/vite.config.js:30-30
Timestamp: 2025-04-29T13:25:31.494Z
Learning: In the maxGraph project, each example package (ts-example, ts-example-selected-features, ts-example-without-defaults) implements different use cases with varying features, resulting in different application sizes. Therefore, each package has its own specific chunkSizeWarningLimit value in its vite.config.js file, calibrated to its expected bundle size.
Learnt from: tbouffard
PR: maxGraph/maxGraph#774
File: packages/ts-example-selected-features/package.json:11-13
Timestamp: 2025-04-22T16:34:40.309Z
Learning: In the maxGraph project, TypeScript is defined as a dependency in the root package.json and not in individual package.json files for example packages. The build scripts in example packages can use `tsc` because it's available through this hoisted dependency in the monorepo structure.
Learnt from: tbouffard
PR: maxGraph/maxGraph#774
File: packages/ts-example-selected-features/package.json:11-13
Timestamp: 2025-04-22T16:34:40.309Z
Learning: In the maxGraph project, TypeScript is defined as a dependency in the root package.json (~5.8.2) and not in individual package.json files for example packages. The build scripts in example packages can use `tsc` commands because the TypeScript dependency is hoisted in the monorepo structure.
README.md (3)
Learnt from: tbouffard
PR: maxGraph/maxGraph#774
File: packages/ts-example-selected-features/package.json:11-13
Timestamp: 2025-04-22T16:34:40.309Z
Learning: In the maxGraph project, TypeScript is defined as a dependency in the root package.json (~5.8.2) and not in individual package.json files for example packages. The build scripts in example packages can use `tsc` commands because the TypeScript dependency is hoisted in the monorepo structure.
Learnt from: tbouffard
PR: maxGraph/maxGraph#774
File: packages/ts-example-selected-features/package.json:11-13
Timestamp: 2025-04-22T16:34:40.309Z
Learning: In the maxGraph project, TypeScript is defined as a dependency in the root package.json and not in individual package.json files for example packages. The build scripts in example packages can use `tsc` because it's available through this hoisted dependency in the monorepo structure.
Learnt from: tbouffard
PR: maxGraph/maxGraph#791
File: packages/ts-example/vite.config.js:30-30
Timestamp: 2025-04-29T13:25:31.494Z
Learning: In the maxGraph project, each example package (ts-example, ts-example-selected-features, ts-example-without-defaults) implements different use cases with varying features, resulting in different application sizes. Therefore, each package has its own specific chunkSizeWarningLimit value in its vite.config.js file, calibrated to its expected bundle size.
🧬 Code Graph Analysis (1)
packages/ts-example-jest-commonjs/__tests__/index.ts (1)
packages/core/src/types.ts (1)
  • CellStyle (50-75)
🪛 ESLint
packages/core/scripts/generate-cjs-package-json.mjs

[error] 23-23: Unexpected console statement.

(no-console)


[error] 29-29: Unexpected console statement.

(no-console)

packages/js-example-nodejs/src/index.mjs

[error] 21-21: Unexpected console statement.

(no-console)

packages/ts-example-jest-commonjs/jest.config.cjs

[error] 18-18: 'module' is not defined.

(no-undef)


[error] 21-21: Unnecessary escape character: ..

(no-useless-escape)

packages/js-example-nodejs/src/index.cjs

[error] 17-17: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 17-17: 'require' is not defined.

(no-undef)


[error] 18-18: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 18-18: 'require' is not defined.

(no-undef)


[error] 19-19: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 19-19: 'require' is not defined.

(no-undef)


[error] 21-21: Unexpected console statement.

(no-console)


[error] 59-59: Unexpected console statement.

(no-console)


[error] 71-71: Unexpected console statement.

(no-console)


[error] 104-104: Unexpected console statement.

(no-console)


[error] 107-107: Unexpected console statement.

(no-console)

🪛 LanguageTool
packages/js-example-nodejs/README.md

[uncategorized] ~1-~1: You might be missing the article “a” here.
Context: # Integrate maxGraph in headless environment with Node.js Demonstrate h...

(AI_EN_LECTOR_MISSING_DETERMINER_A)

🪛 markdownlint-cli2 (0.17.2)
packages/js-example-nodejs/README.md

13-13: No empty links
null

(MD042, no-empty-links)

🔇 Additional comments (15)
.github/dependabot.yml (1)

55-61: Expand test dependency monitoring: Adding @types/jest, jsdom, jsdom-*, and ts-jest to the test group ensures that the new example projects' dependencies remain up-to-date and secure.

packages/ts-example-jest-commonjs/README.md (1)

1-6: Clear introduction and context: The title and overview succinctly explain the goal of running maxGraph in CommonJS Jest tests with ts-jest and jest-jsdom. This sets the right expectations for users.

README.md (1)

152-152: Include new TypeScript example: Adding ts-example-jest-commonjs to the examples list keeps the documentation in sync with the new CommonJS Jest testing setup.

packages/website/docs/demo-and-examples.md (2)

29-29: Document TypeScript Jest example: Including ts-example-jest-commonjs under the TypeScript Examples section accurately guides users to the new Jest+ts-jest CommonJS setup.


35-35: Document headless Node.js example: Adding js-example-nodejs to the JavaScript Examples ensures users know how to run maxGraph in a headless Node.js environment with jsdom.

packages/js-example-nodejs/package.json (1)

6-10: Build script only runs CommonJS example

The build script only runs build:cjs and not the ESM example, which aligns with the ESM implementation being incomplete as mentioned in the AI summary.

packages/js-example-nodejs/src/index.mjs (1)

21-21: Console statement in example code

The console statement is flagged by ESLint, but is appropriate for an example showing how the code works.

🧰 Tools
🪛 ESLint

[error] 21-21: Unexpected console statement.

(no-console)

packages/ts-example-jest-commonjs/__tests__/index.ts (2)

21-24: Good test for BaseGraph.isOrthogonal functionality

This test correctly demonstrates using the maxGraph API with Jest in a CommonJS environment.


26-36: Good test for cell style management

This test effectively demonstrates modifying cell styles and verifying both the cell's style property and the view state. Great example for showing style management in maxGraph.

packages/js-example-nodejs/src/index.cjs (2)

64-69: Good practice: Creating output directory

The code correctly checks if the output directory exists and creates it if necessary, ensuring the file operations won't fail.


25-51: Well-structured graph creation example

The batch update pattern is correctly demonstrated, showing how to insert multiple graph elements efficiently. This is a good example for users learning the maxGraph API.

packages/core/package.json (4)

24-25: Verify ESM export mapping
The exports.import block correctly provides separate paths for TypeScript and runtime consumers. This aligns with the "module" and "types" fields above.


27-29: Verify CJS export mapping and type declarations
The exports.require block directs require() to lib/cjs/index.js and its types to lib/cjs/index.d.ts. Confirm that generate-cjs-package-json.mjs not only writes a package.json with "type": "commonjs" into lib/cjs, but also that a .d.ts lives at lib/cjs/index.d.ts.

You can adapt the above shell snippet to check for lib/cjs/index.d.ts.


48-48: Fix repository URL to include .git suffix
This corrects the missing extension in the repository.url field.


18-20:

Details

❓ Verification inconclusive

Add dual entry points for CJS and ESM
The new "main", "module", and "types" fields correctly point to the CJS and ESM bundles. Ensure that after running the build scripts, the files lib/cjs/index.js, lib/esm/index.js, and lib/esm/index.d.ts actually exist and match these paths.

Run a quick check after building:


🏁 Script executed:

#!/bin/bash
# Verify outputs for CJS and ESM entry points
for f in lib/cjs/index.js lib/esm/index.js lib/esm/index.d.ts; do
  if [ ! -f "$f" ]; then
    echo "Missing build artifact: $f"
    exit 1
  fi
done
echo "All entry points are present."

Length of output: 197


🏁 Script executed:

#!/bin/bash
# List all build artifacts under lib to verify presence of entry points
find lib -type f

Length of output: 57


Verify build output for CJS and ESM entry points
The main, module, and types fields in packages/core/package.json point to:

  • lib/cjs/index.js
  • lib/esm/index.js
  • lib/esm/index.d.ts

However, no lib/ directory was found in the PR’s build environment. Please run the package’s build locally (e.g. npm run build) and confirm that those files are generated and match the declared entry points. You can use this quick check:

#!/bin/bash
npm run build
for f in lib/cjs/index.js lib/esm/index.js lib/esm/index.d.ts; do
  if [ ! -f "$f" ]; then
    echo "Missing build artifact: $f"
    exit 1
  fi
done
echo "All entry points are present."

Once verified, update the PR (or CI) accordingly.

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: 2

♻️ Duplicate comments (1)
packages/js-example-nodejs/src/index.cjs (1)

94-96: Enhance SimpleSvgExporter class with error handling

The exporter class doesn't include any error handling, which could lead to hard-to-debug issues. Consider adding basic error checking.

// we are sure that we have an SVG node here, it is always created at Graph creation
-const svgNode = this.graph.container.querySelector('svg');
+const svgNode = this.graph.container.querySelector('svg');
+if (!svgNode) {
+  throw new Error('SVG element not found in graph container');
+}
🧹 Nitpick comments (1)
packages/ts-example-jest-commonjs/jest.config.cjs (1)

18-18: Ignore ESLint 'module is not defined' warning.

The ESLint warning about 'module' not being defined is a false positive for CommonJS files. In .cjs files, 'module' is automatically defined in the global scope by Node.js.

If you want to silence this warning in the future, you could add a comment directive:

/** @type {import('ts-jest').JestConfigWithTsJest} **/
+/* global module */
module.exports = {
🧰 Tools
🪛 ESLint

[error] 18-18: 'module' is not defined.

(no-undef)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 57c250e and 4959ead.

📒 Files selected for processing (2)
  • packages/js-example-nodejs/src/index.cjs (1 hunks)
  • packages/ts-example-jest-commonjs/jest.config.cjs (1 hunks)
🧰 Additional context used
🪛 ESLint
packages/js-example-nodejs/src/index.cjs

[error] 17-17: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 17-17: 'require' is not defined.

(no-undef)


[error] 18-18: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 18-18: 'require' is not defined.

(no-undef)


[error] 19-19: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 19-19: 'require' is not defined.

(no-undef)


[error] 21-21: Unexpected console statement.

(no-console)


[error] 59-59: Unexpected console statement.

(no-console)


[error] 71-71: Unexpected console statement.

(no-console)


[error] 105-105: Unexpected console statement.

(no-console)


[error] 108-108: Unexpected console statement.

(no-console)

packages/ts-example-jest-commonjs/jest.config.cjs

[error] 18-18: 'module' is not defined.

(no-undef)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build (windows-2022)
  • GitHub Check: build (ubuntu-22.04)
🔇 Additional comments (5)
packages/ts-example-jest-commonjs/jest.config.cjs (1)

1-23: Well-structured Jest configuration for CommonJS support.

The configuration is correctly set up with:

  • Proper JSDoc type annotation for TypeScript intellisense
  • JSDOM test environment (necessary for maxGraph's browser dependencies)
  • Correctly configured TypeScript transformer

The past issue with the regex escape character has been properly addressed with the correct double backslash pattern.

🧰 Tools
🪛 ESLint

[error] 18-18: 'module' is not defined.

(no-undef)

packages/js-example-nodejs/src/index.cjs (4)

1-20: Well-implemented CommonJS file header and imports

The file structure correctly follows CommonJS patterns with proper license header and required imports. The use of jsdom-global is appropriate for creating a DOM environment in Node.js.

Note: The ESLint errors about require() style imports are expected for a CommonJS file and can be safely ignored.

🧰 Tools
🪛 ESLint

[error] 17-17: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 17-17: 'require' is not defined.

(no-undef)


[error] 18-18: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 18-18: 'require' is not defined.

(no-undef)


[error] 19-19: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 19-19: 'require' is not defined.

(no-undef)


25-51: Good use of batch update pattern

The graph creation code uses batchUpdate to efficiently add multiple elements at once, which is a good practice for performance. The vertex and edge configurations are clearly defined with appropriate styling options.


73-103: Well-documented SVG exporter implementation with clear limitations

The SimpleSvgExporter class is well-documented with JSDoc comments explaining its limitations regarding HTML labels. The implementation correctly calculates graph bounds with margins and properly constructs the SVG.


17-19:

Details

❓ Verification inconclusive

Verify CommonJS compatibility with maxGraph core

This example demonstrates using maxGraph with CommonJS imports, but it would be beneficial to verify that all required features work correctly with this import style.


🏁 Script executed:

#!/bin/bash
# Check if all required maxGraph features are exported in the CommonJS build
# Look at the package.json to see how the CommonJS exports are configured

rg -A 10 "exports" package.json

# Check if there are any ESM-only features by looking at type declarations
fd -e d.ts -x grep -l "export" {} \; | xargs grep -l "export" | head -n 5

Length of output: 106


Verify CommonJS exports for @maxgraph/core

This example uses CommonJS (require('@maxgraph/core')) to pull in constants, Graph, ModelXmlSerializer, and Rectangle. Please confirm that all of these are actually exposed by the CommonJS build:

  • Check the root package.json for a "type": "module" field (files with a .cjs extension are exempt, but good to verify).

  • Inspect node_modules/@maxgraph/core/package.json and its "main" or "exports" to ensure they point at a CommonJS entry that includes the above symbols.

  • Run a quick smoke test:

    node -e "const mod = require('@maxgraph/core'); console.log(Object.keys(mod));"

    Verify that constants, Graph, ModelXmlSerializer, and Rectangle appear in the output without errors.

🧰 Tools
🪛 ESLint

[error] 17-17: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 17-17: 'require' is not defined.

(no-undef)


[error] 18-18: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 18-18: 'require' is not defined.

(no-undef)


[error] 19-19: A require() style import is forbidden.

(@typescript-eslint/no-require-imports)


[error] 19-19: 'require' is not defined.

(no-undef)

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: 0

🔭 Outside diff range comments (1)
packages/js-example-nodejs/README.md (1)

23-23: ⚠️ Potential issue

Remove stray line artifact
The trailing “23” appears to be an unintended artifact—please remove it to avoid confusion.

♻️ Duplicate comments (1)
packages/js-example-nodejs/README.md (1)

13-13: Empty placeholder link needs to be filled
Replace [xxxx]() with the actual issue or PR number that will implement ESM compatibility for Node.js, for example:

This will be implemented in the future with [issue #824](https://github.com/maxGraph/maxGraph/issues/824).
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

13-13: No empty links
null

(MD042, no-empty-links)

🧹 Nitpick comments (3)
packages/js-example-nodejs/README.md (3)

8-11: Enhance example section with usage details and file references
The README mentions CommonJS and ESM examples but doesn’t link to or show how to execute them. Consider adding direct links to src/index.cjs and src/index.mjs, and commands (e.g., node src/index.cjs) so users can run the demos immediately.


12-12: Correct grammar in ESM compatibility note
Change “doesn't provide ESM compatible yet with Node.js” to “doesn't yet provide ESM compatibility for Node.js” for clarity and grammatical accuracy.


16-22: Use fenced code blocks for setup commands
Switch from blockquotes to fenced code blocks so commands are more readable and easily copy-pasted. For example:

- > From the repository root, run `npm install`.
+ ```bash
+ npm install
+ ```

- > From the `packages/core` directory, run `npm run build`.
+ ```bash
+ cd packages/core
+ npm run build
+ ```
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4959ead and e23ab0d.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • packages/core/src/view/GraphView.ts (22 hunks)
  • packages/js-example-nodejs/README.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • README.md
🧰 Additional context used
🧠 Learnings (1)
packages/js-example-nodejs/README.md (1)
Learnt from: tbouffard
PR: maxGraph/maxGraph#826
File: packages/js-example-nodejs/src/index.cjs:64-69
Timestamp: 2025-05-13T12:54:55.196Z
Learning: For example code in the maxGraph repository, maintainers prefer to keep scripts simple without error handling to focus on demonstrating core functionality, especially in demonstration scripts like those in packages/js-example-nodejs.
🪛 markdownlint-cli2 (0.17.2)
packages/js-example-nodejs/README.md

13-13: No empty links
null

(MD042, no-empty-links)

🔇 Additional comments (23)
packages/core/src/view/GraphView.ts (23)

317-318: Documentation updated correctly

The comment now accurately describes the DOM node returned by getCanvas() method.


353-356: Documentation type references updated appropriately

The JSDoc comments have been updated to use modern type references (Cell instead of outdated mxCell), aligning with the module's type system.


383-384: Documentation type reference updated correctly

Updated type reference from outdated mxCell to current Cell type.


537-539: Documentation clarification improved

The comment for validate() method has been updated with proper type references.


620-621: Type reference updated in parameter documentation

Updated from mxRectangle to Rectangle for consistency with the codebase's type system.


688-690: Comment clarification improved

The comment now better explains the purpose of the event listeners for graph event dispatching.


762-764: Parameter type references updated

Updated from mxImageShape to ImageShape and mxImage to Image to align with current type system.


784-787: Documentation type reference updated appropriately

Updated from mxCell to Cell for the validateCell method parameter.


811-814: Documentation type reference updated

Parameter documentation now correctly uses Cell instead of outdated mxCell.


849-851: Comment clarity improved

The comment now more accurately describes the handling of changes to vertex paint bounds.


1130-1132: Parameter documentation updated with current type references

Updated from mxCellState to CellState for method parameters.


1150-1152: Documentation references updated for parameters

Updated from mxCellState to CellState for consistent type naming throughout the codebase.


1187-1188: Parameter type documentation updated

Updated from mxCellState to CellState for the updateBoundsFromStencil method.


1640-1643: Documentation type reference updated

Changed from mxCell to Cell for the getVisibleTerminal method parameter.


1671-1676: Documentation updated with correct references

The method documentation now uses proper type references and explains the purpose clearly.


1738-1739: Type reference in parameter documentation updated

Updated from mxGeometry to Geometry for consistency with current type system.


1800-1803: Documentation reference updated for method parameter

Updated from mxCellState to CellState for the getRelativePoint method.


1893-1900: Documentation clarity improved

The comment for updateEdgeLabelOffset now more accurately describes the purpose of the method.


1946-1949: Parameter type reference updated

Changed from mxCell to Cell for the getState method parameter.


1966-1970: Method documentation updated with correct type reference

Updated from mxCell to Cell for array parameters in getCellStates.


1991-1992: Parameter type reference updated

Changed from mxCell to Cell in the removeState method documentation.


2009-2010: Documentation reference updated

Changed from mxCell to Cell for the createState method parameter.


1-2395: Overall documentation improvements are well-executed

The changes in this file consist solely of documentation updates that replace outdated type references in JSDoc comments (e.g., mxCell to Cell, mxCellState to CellState, mxRectangle to Rectangle, etc.) and improve comment clarity. These changes align perfectly with the PR's goal of modernizing the codebase to support both ESM and CommonJS module formats.

The consistent replacement of legacy mx prefixed types with their modern equivalents ensures that the documentation matches the actual types used in the codebase, improving developer experience and code maintainability.

🧰 Tools
🪛 Biome (1.9.4)

[error] 584-584: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 589-589: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 699-699: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 1193-1195: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 2189-2189: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 2363-2363: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

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: 0

♻️ Duplicate comments (1)
packages/js-example-nodejs/README.md (1)

13-13: ⚠️ Potential issue

Fill in the placeholder link

The placeholder link [xxxx]() needs to reference the actual issue tracking ESM compatibility (e.g. issue #824). Please replace it accordingly:

-This will be implemented in the future with [xxxx]().
+This will be implemented in the future with [issue #824](https://github.com/maxGraph/maxGraph/issues/824).
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

13-13: No empty links
null

(MD042, no-empty-links)

🧹 Nitpick comments (4)
packages/js-example-nodejs/README.md (4)

1-2: Refine Heading for Clarity

Consider making the top-level heading more descriptive by referencing the actual package name (@maxgraph/core) and highlighting that this is the CommonJS Node.js example. For example:

-# Integrate `maxGraph` in a headless environment with Node.js
+# Node.js Headless CommonJS Example for `@maxgraph/core`

3-7: Consistent Code Formatting

Wrap library names in backticks for consistency and clarity. For example:

-Demonstrate how to integrate maxGraph with Node.js to use it in a headless environment.
+Demonstrate how to integrate `@maxgraph/core` with Node.js to use it in a headless environment.

-In this example, `jsdom` is used to provide an implementation of the browser objects whose `maxGraph` depends on.
+In this example, `jsdom` is used to provide implementations of the browser objects on which `@maxgraph/core` depends.

8-12: Include a Quick Usage Snippet

To make this README more actionable, it would be helpful to include a minimal CommonJS code example showing how to import and instantiate a graph. For instance:

```js
// packages/js-example-nodejs/src/index.cjs
const { mxGraph, mxCodec, mxUtils } = require('@maxgraph/core');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;

// setup jsdom, create graph, export to XML/SVG...

---

`16-23`: **Verify CJS Build Instructions & Improve Command Formatting**

1. Ensure the setup instructions cover the new CommonJS build step (e.g., `npm run build:cjs` if applicable).
2. Consider switching from blockquotes (`>`) to fenced code blocks for readability:

```diff
-> From the repository root, run `npm install`.
+```bash
+npm install
+```

-> From the `packages/core` directory, run `npm run build`.
+```bash
+cd packages/core
+npm run build       # builds ESM & CJS outputs (or specify `npm run build:cjs`)
+```
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e23ab0d and 38cc084.

📒 Files selected for processing (1)
  • packages/js-example-nodejs/README.md (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
packages/js-example-nodejs/README.md (1)
Learnt from: tbouffard
PR: maxGraph/maxGraph#826
File: packages/js-example-nodejs/src/index.cjs:64-69
Timestamp: 2025-05-13T12:54:55.196Z
Learning: For example code in the maxGraph repository, maintainers prefer to keep scripts simple without error handling to focus on demonstrating core functionality, especially in demonstration scripts like those in packages/js-example-nodejs.
🪛 markdownlint-cli2 (0.17.2)
packages/js-example-nodejs/README.md

13-13: No empty links
null

(MD042, no-empty-links)

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

🧹 Nitpick comments (2)
packages/js-example-nodejs/src/index.mjs (2)

21-21: Disable ESLint rule for console statements in this example.
This demo uses console.info() for output. Suppress the no-console ESLint rule with an inline comment:

+/* eslint-disable no-console */
🧰 Tools
🪛 ESLint

[error] 21-21: Unexpected console statement.

(no-console)


23-23: Enhance the example with a simple usage demonstration.
After instantiating the graph, consider logging or exporting something to show the graph in action:

-const graph = new BaseGraph();
+const graph = new BaseGraph();
// Simple demonstration: log the graph instance
+console.log('Graph instance created:', graph);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38cc084 and a3a6df5.

📒 Files selected for processing (2)
  • packages/js-example-nodejs/README.md (1 hunks)
  • packages/js-example-nodejs/src/index.mjs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/js-example-nodejs/README.md
🧰 Additional context used
🧠 Learnings (1)
packages/js-example-nodejs/src/index.mjs (1)
Learnt from: tbouffard
PR: maxGraph/maxGraph#826
File: packages/js-example-nodejs/src/index.cjs:64-69
Timestamp: 2025-05-13T12:54:55.196Z
Learning: For example code in the maxGraph repository, maintainers prefer to keep scripts simple without error handling to focus on demonstrating core functionality, especially in demonstration scripts like those in packages/js-example-nodejs.
🪛 ESLint
packages/js-example-nodejs/src/index.mjs

[error] 21-21: Unexpected console statement.

(no-console)

🔇 Additional comments (1)
packages/js-example-nodejs/src/index.mjs (1)

1-15: Standard Apache 2.0 license header requires no review.

@sonarqubecloud
Copy link

@tbouffard tbouffard merged commit dcfb4d4 into main May 14, 2025
2 checks passed
@tbouffard tbouffard deleted the feat/824-add_commonjs_support_in_npm_package branch May 14, 2025 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Consider adding CommonJS support in the npm package [QUESTION] can not find module while writing jest unit test cases for maxGraph

1 participant