Skip to content

feat(material): add material package#537

Open
chilingling wants to merge 11 commits intoopentiny:developfrom
chilingling:feat/materialPackage
Open

feat(material): add material package#537
chilingling wants to merge 11 commits intoopentiny:developfrom
chilingling:feat/materialPackage

Conversation

@chilingling
Copy link
Copy Markdown
Member

@chilingling chilingling commented Jun 4, 2024

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Engine now loads materials from a module-based source for more flexible and maintainable material usage.
    • Added a material build/serve tool with build and watch/serve modes to generate and serve material bundles for easier development.
  • Chores

    • Added the materials package dependency to support the new module-based material source.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 4, 2024

Walkthrough

Replaced a static materials JSON in the designer-demo engine config with an imported @opentiny/tiny-engine-materials module and added that dependency; added a new materials build/serve CLI script packages/materials/buildMaterials.mjs that builds bundles, optionally combines them, watches files, and can serve the dist folder.

Changes

Cohort / File(s) Change Summaries
Designer demo config
designer-demo/engine.config.js
Replaced material: ['/mock/bundle.json'] with material: [material], switching material source from a static JSON file to an imported module.
Designer demo deps
designer-demo/package.json
Added dependency "@opentiny/tiny-engine-materials": "workspace:*" under dependencies.
Materials builder CLI
packages/materials/buildMaterials.mjs
Added a new CLI module that: scans materials directories, validates component JSON and optional meta.json, emits per-entry entry.json and entry.compsMap.json, optionally combines outputs into dist/index.json and dist/index.compsMap.json, supports build, build:split, and serve commands, watches files in serve mode, and can start a static HTTP server to serve dist.

Sequence Diagram(s)

sequenceDiagram
  participant DevCLI as CLI
  participant Builder as MaterialsBuilder
  participant FS as FileSystem
  participant HTTP as StaticServer
  rect rgb(230,248,255)
    DevCLI->>Builder: run build / build:split / serve
    opt build or build:split
      Builder->>FS: read materials/*/*.json, meta.json
      Builder->>Builder: validate & generate bundles
      Builder->>FS: write dist/entry.json, entry.compsMap.json
      alt build (combine)
        Builder->>FS: write dist/index.json, index.compsMap.json
      end
    end
    opt serve
      Builder->>FS: initial build
      Builder->>FS: watch files (add/change/unlink)
      FS->>Builder: file change events
      Builder->>FS: rebuild affected entries
      DevCLI->>HTTP: start static server (serve dist)
      HTTP->>DevCLI: serve on auto-detected port
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Pay attention to packages/materials/buildMaterials.mjs for: file-watching edge cases, JSON validation rules, error handling/log messages, and correctness of combined bundle format.
  • Verify designer-demo/engine.config.js change integrates correctly with the new @opentiny/tiny-engine-materials export shape and that the new dependency version aligns with workspace expectations.

Poem

I nibble JSON under starlight bright,
Bundles hop, components take flight.
I watch and build, then serve with glee,
A tiny engine, tidy and free.
— the rabbit hums, sip of tea 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "feat(material): add material package" is clearly related to the changes in the pull request. The changeset includes the introduction of a new materials package with a build orchestration module (buildMaterials.mjs), integration into the engine configuration, and a new dependency addition. The title accurately captures the primary objective—adding a material package—and uses clear, conventional commit format with a specific scope ("material") rather than vague terminology. A teammate reviewing the commit history would understand this involves material-related features being added to the project.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
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: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ec2c752 and f43f9dd.

Files selected for processing (8)
  • packages/materials/README.md (1 hunks)
  • packages/materials/buildMaterials.mjs (1 hunks)
  • packages/materials/package.json (1 hunks)
  • packages/materials/src/ElementPlus/ElButton.json (1 hunks)
  • packages/materials/src/ElementPlus/ElInput.json (1 hunks)
  • packages/materials/src/TinyVue/TinyButton.json (1 hunks)
  • packages/materials/src/TinyVue/TinyInput.json (1 hunks)
  • packages/materials/src/html/Input.json (1 hunks)
Files skipped from review due to trivial changes (5)
  • packages/materials/package.json
  • packages/materials/src/ElementPlus/ElButton.json
  • packages/materials/src/TinyVue/TinyButton.json
  • packages/materials/src/TinyVue/TinyInput.json
  • packages/materials/src/html/Input.json
Additional context used
Markdownlint
packages/materials/README.md

12-12: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


33-33: null (MD034, no-bare-urls)
Bare URL used

Additional comments not posted (4)
packages/materials/buildMaterials.mjs (3)

24-42: Ensure all required fields are checked in validateComponent.

This function correctly checks for missing required fields and logs appropriate errors. Good use of array operations for validation.


118-154: Ensure error handling in buildComponents is robust.

Good use of try-catch for error handling. Consider adding more specific error messages or handling different types of exceptions if applicable.


156-190: Review the implementation of the serve function.

The function sets up a watcher and a static server correctly. Good use of asynchronous programming and logging.

packages/materials/src/ElementPlus/ElInput.json (1)

1-292: Review the schema definition for ElInput.

The JSON schema is well-structured and includes comprehensive details about the component, its properties, events, and slots. Good use of nested structures and data types.

Comment thread packages/materials/README.md
Comment thread packages/materials/README.md Outdated
Comment thread packages/materials/buildMaterials.mjs Outdated
Comment thread packages/materials/buildMaterials.mjs Outdated
Comment on lines +202 to +219

function start() {
const commandsMap = {
serve: serve,
build: build,
'build:split': buildSplit
}

const command = process.argv.slice(2)

if (!commandsMap[command]) {
logger.error(`[@opentiny/tiny-engine-materials] 不支持${command}命令`)

return
}

commandsMap[command]()
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The start function in packages/materials/buildMaterials.mjs does include a basic validation check to ensure the command is in the commandsMap. However, it only checks if the command exists in the map and does not handle other potential issues such as invalid command formats or additional arguments.

  • Location in codebase:
    • packages/materials/buildMaterials.mjs (lines 202-219)

To improve the validation, consider adding more comprehensive checks, such as verifying the format of the command and handling unexpected additional arguments.

Analysis chain

Validate command input in start function.

Ensure that the command validation is comprehensive and covers all expected scenarios.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify command validation in the start function.

# Test: Search for command validation logic. Expect: Comprehensive validation logic.
rg --type javascript $'commandsMap[command]'

Length of output: 80



Script:

#!/bin/bash
# Description: Verify command validation in the start function.

# Test: Search for command validation logic. Expect: Comprehensive validation logic.
rg --type js $'commandsMap[command]'

Length of output: 37



Script:

#!/bin/bash
# Description: Locate the start function and review its implementation.

# Search for the start function definition in JavaScript files.
rg --type js 'function start'

Length of output: 31



Script:

#!/bin/bash
# Description: Locate the start function and review its implementation.

# Search for the start function definition in JavaScript and ES module files.
rg --type-add 'mjs:*.mjs' --type js --type mjs 'function start'

Length of output: 122



Script:

#!/bin/bash
# Description: Extract and display the start function implementation from buildMaterials.mjs.

# Extract the start function implementation.
rg --type-add 'mjs:*.mjs' --type mjs --context 10 'function start' packages/materials/buildMaterials.mjs

Length of output: 495

yy-wow
yy-wow previously approved these changes Oct 23, 2024
rhlin
rhlin previously approved these changes Oct 25, 2024
"test": "echo \"Error: no test specified\" && exit 1",
"serve": "node buildMaterials.mjs serve",
"build": "node buildMaterials.mjs build",
"build:split": "node buildMaterials.mjs build:split"
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

外层也有两个物料的命令,看下是不是一起整合下

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

全体迁移完成后再整合

Comment thread packages/materials/package.json Outdated
Comment thread packages/materials/package.json
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
designer-demo/package.json (1)

13-13: Use consistent version specifier for workspace dependencies.

The new dependency uses workspace:* while @opentiny/tiny-engine uses workspace:^. Consider using consistent version specifiers across workspace dependencies.

-    "@opentiny/tiny-engine-materials": "workspace:*",
+    "@opentiny/tiny-engine-materials": "workspace:^",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f43f9dd and 7c7bc09.

📒 Files selected for processing (2)
  • designer-demo/engine.config.js (1 hunks)
  • designer-demo/package.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (3)
designer-demo/engine.config.js (2)

1-10: Document the breaking changes and provide a migration guide.

This change introduces a breaking change by modifying how materials are configured. Please:

  1. Document the new material module structure
  2. Provide a migration guide for users moving from the JSON file format
  3. Update the README with the new configuration details

1-1: Verify the material module's structure and add error handling.

The change from a static JSON file to a dynamic module is a breaking change. Consider:

  1. Adding error handling for module loading failures
  2. Documenting the expected shape of the material module
  3. Providing type information

Also applies to: 6-6

designer-demo/package.json (1)

1-34: Add tests for the material package.

The PR checklist indicates that tests are missing. Please add tests to verify:

  1. Material module loading
  2. Integration with the engine configuration
  3. Error handling for invalid material configurations

Would you like me to help generate test cases for the material package?

@hexqi hexqi modified the milestone: v2.3.0 Feb 13, 2025
@chilingling chilingling force-pushed the feat/materialPackage branch from 7c7bc09 to 79adeb4 Compare August 18, 2025 13:43
@github-actions github-actions Bot added breaking-change enhancement New feature or request labels Aug 18, 2025
Copy link
Copy Markdown
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: 2

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7c7bc09 and 79adeb4.

📒 Files selected for processing (2)
  • designer-demo/engine.config.js (1 hunks)
  • designer-demo/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • designer-demo/package.json
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: chilingling
PR: opentiny/tiny-engine#837
File: packages/vue-generator/src/plugins/genDependenciesPlugin.js:66-66
Timestamp: 2024-09-30T07:51:10.036Z
Learning: In the `tiny-engine` project, `opentiny/tiny-engine-dsl-vue` refers to the current package itself, and importing types from it may cause circular dependencies.
🧬 Code Graph Analysis (1)
designer-demo/engine.config.js (1)
packages/materials/buildMaterials.mjs (1)
  • material (77-77)

@@ -1,7 +1,9 @@
import material from '@opentiny/tiny-engine-materials'
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Default import may not match the package’s export shape — consider interop-safe import.

If @opentiny/tiny-engine-materials does not export a default (e.g., CommonJS export or named export), this will break at runtime. Use a namespace import and normalize to a material object for robustness.

Apply this diff:

-import material from '@opentiny/tiny-engine-materials'
+import * as materials from '@opentiny/tiny-engine-materials'
+const material = materials.default ?? materials.material ?? materials

To verify the export shape of the materials package and the dependency wiring, run:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) Check demo dependency is declared"
rg -n -C2 '"@opentiny/tiny-engine-materials"\s*:\s*' designer-demo/package.json || {
  echo "Dependency not found in designer-demo/package.json"; exit 1; }

echo
echo "2) Locate the materials package and inspect export style"
# Path inferred from context (packages/materials/…)
if [ -d packages/materials ]; then
  echo "- package.json name:"
  rg -n -C1 '"name"\s*:\s*' packages/materials/package.json || true

  echo
  echo "- Look for default or CJS exports under packages/materials:"
  rg -n -C2 -S 'export\s+default|module\.exports\s*=|exports\.' packages/materials || true
else
  echo "packages/materials not found; adjust the path if the package lives elsewhere."
fi

Length of output: 1001


Ensure interop-safe import of @opentiny/tiny-engine-materials

The @opentiny/tiny-engine-materials package has no default export, so this will break at runtime:

designer-demo/engine.config.js:1

-import material from '@opentiny/tiny-engine-materials'
+import * as materials from '@opentiny/tiny-engine-materials'
+const material = materials.default ?? materials.material ?? materials;

This normalizes the import to work with both ESM and CJS export shapes.

📝 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
import material from '@opentiny/tiny-engine-materials'
import * as materials from '@opentiny/tiny-engine-materials'
const material = materials.default ?? materials.material ?? materials;
🤖 Prompt for AI Agents
In designer-demo/engine.config.js at line 1, the current statement imports a
package that has no default export; change the import to be interop-safe by
either importing the module namespace (import * as material from
'@opentiny/tiny-engine-materials') or normalizing a default import (import
materialImport from '@opentiny/tiny-engine-materials' then const material =
materialImport?.default ?? materialImport); update the file to use one of these
patterns so the code works with both ESM and CJS export shapes.

id: 'engine.config',
theme: 'light',
material: ['/mock/bundle.json'],
material: [material],
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Switching from a mock JSON URL to the materials package looks good — confirm engine compatibility and document the migration.

Nice move away from hardcoded /mock/bundle.json to a shareable materials package; this should improve consistency across demos. Please confirm the engine accepts inlined material objects (not just URLs) in the material array and add a short migration note since the PR is marked “breaking.”

Optional (to ease migration/backward-compat): allow a fallback/toggle to the legacy bundle for now. Example:

-import * as materials from '@opentiny/tiny-engine-materials'
-const material = materials.default ?? materials.material ?? materials
+import * as materials from '@opentiny/tiny-engine-materials'
+const material = materials.default ?? materials.material ?? materials
+const usePkg = !!(import.meta?.env?.VITE_USE_MATERIAL_PKG ?? true)

 export default {
   id: 'engine.config',
   theme: 'light',
-  material: [material],
+  material: [usePkg ? material : '/mock/bundle.json'],
   scripts: [],
   styles: []
 }

Quick checks you can run:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) Ensure no stale references to the old mock bundle remain"
rg -n -C2 '/mock/bundle\.json' || echo "No references found."

echo
echo "2) Grep for material array handling to ensure objects are supported (heuristic)"
rg -n -C3 -S '\bmaterial\b' packages | head -n 100 || true

Length of output: 14235


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Context around material in designer-demo/src/preview.js:"
rg -n -C3 'material' designer-demo/src/preview.js || true

echo
echo "Import statements in designer-demo/src/preview.js:"
rg -n 'import ' designer-demo/src/preview.js

Length of output: 608


Confirm inline material support & document breaking change migration

Engine already accepts in‐memory material objects (see “也可以传入 JSON 对象” examples in docs/api/frontend-api/preview-api.md and docs/extension-capabilities-overview/registry.md). To finish this breaking change:

• Update documentation

  • docs/api/frontend-api/preview-api.md: show both URL and inlined object usage, and add a “Migration” note for replacing /mock/bundle.json with the new package import.
  • docs/extension-capabilities-overview/registry.md: mirror the inline-object example and call out the breaking change.

• (Optional) provide a runtime toggle/fallback to the legacy mock bundle in designer-demo/engine.config.js:

 import * as materials from '@opentiny/tiny-engine-materials'
 const material = materials.default ?? materials.material ?? materials
+  const usePkg = Boolean(import.meta.env.VITE_USE_MATERIAL_PKG ?? true)

 export default {
   id: 'engine.config',
   theme: 'light',
-    material: [material],
+    material: [usePkg ? material : '/mock/bundle.json'],
   scripts: [],
   styles: []
 }

• (Out-of-scope for this PR) schedule follow-up to clean up stale /mock/bundle.json references in CLI templates, scripts, and other demos.

📝 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
material: [material],
import * as materials from '@opentiny/tiny-engine-materials'
const material = materials.default ?? materials.material ?? materials
const usePkg = Boolean(import.meta.env.VITE_USE_MATERIAL_PKG ?? true)
export default {
id: 'engine.config',
theme: 'light',
material: [usePkg ? material : '/mock/bundle.json'],
scripts: [],
styles: []
}
🤖 Prompt for AI Agents
In designer-demo/engine.config.js around line 6 (material: [material]), confirm
and support inline in-memory material objects and add a runtime fallback to
preserve legacy /mock/bundle.json behavior: update engine.config.js to accept
either an imported object or a URL/string — if material is a string treat it as
a URL and load the legacy bundle, otherwise treat it as the inlined object; also
update docs/api/frontend-api/preview-api.md to show both URL and inline-object
usage and add a “Migration” note explaining replacing /mock/bundle.json with the
new package import, and mirror the inline-object example and breaking-change
callout in docs/extension-capabilities-overview/registry.md.

Copy link
Copy Markdown
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: 3

🧹 Nitpick comments (3)
packages/materials/buildMaterials.mjs (3)

121-123: Use consistent variable reference.

Line 122 accesses componentInfo.npm.destructuring, but npmInfo was already extracted at line 112 for this purpose. Use npmInfo.destructuring for consistency.

Apply this diff:

     if (typeof npmInfo.destructuring === 'boolean') {
-      mapItem.destructuring = componentInfo.npm.destructuring
+      mapItem.destructuring = npmInfo.destructuring
     }

223-223: Fix typo in comment.

Line 223 contains a typo: "手动出发" should be "手动触发".

-  // 第一次需要手动出发构建一遍
+  // 第一次需要手动触发构建一遍

207-221: Consider debouncing file change events.

The watcher triggers a full rebuild on every file change without debouncing. If multiple files change simultaneously (e.g., during a git checkout), this could trigger multiple concurrent builds, potentially causing race conditions or wasted resources.

Consider adding a debounce mechanism to batch multiple changes:

let rebuildTimer = null

watcher.on('all', (event, file) => {
  const eventMap = {
    add: '新增',
    change: '更新',
    unlink: '删除'
  }
  const fileFullPath = path.join(process.cwd(), file)

  logger.info(`${eventMap[event]}组件文件 (${fileFullPath})`)

  // Debounce rebuilds
  clearTimeout(rebuildTimer)
  rebuildTimer = setTimeout(() => {
    buildComponents()
  }, 300) // 300ms debounce
})
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 79adeb4 and 74a7abd.

📒 Files selected for processing (1)
  • packages/materials/buildMaterials.mjs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/materials/buildMaterials.mjs (2)
scripts/splitMaterials.mjs (1)
  • fileName (56-56)
scripts/buildMaterials.mjs (1)
  • componentInfo (157-157)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: push-check
🔇 Additional comments (2)
packages/materials/buildMaterials.mjs (2)

1-16: LGTM!

The imports and initial setup are appropriate for the build orchestration functionality.


143-202: LGTM!

The build logic correctly processes entries, aggregates bundles, and writes both per-entry and combined output files. Error handling is appropriate.

Comment on lines +35 to +39
if (!component.npm) {
logger.warn(`组件文件 ${file} 缺少 npm 字段,出码时将不能通过import语句导入组件。`)

return false
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Inconsistent validation behavior: warning with failure.

The function logs a warning when the npm field is missing (line 36) but returns false (line 38), causing the component to be skipped. This is inconsistent—warnings typically shouldn't fail validation. Either return true to allow components without npm fields, or change the log level to error to match the failure behavior.

Apply this diff to align the log level with the behavior:

   if (!component.npm) {
-    logger.warn(`组件文件 ${file} 缺少 npm 字段,出码时将不能通过import语句导入组件。`)
+    logger.error(`组件文件 ${file} 缺少 npm 字段,出码时将不能通过import语句导入组件。`)
 
     return false
   }

Alternatively, if components without npm should be allowed:

   if (!component.npm) {
     logger.warn(`组件文件 ${file} 缺少 npm 字段,出码时将不能通过import语句导入组件。`)
 
-    return false
+    // Allow components without npm field
   }
📝 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 (!component.npm) {
logger.warn(`组件文件 ${file} 缺少 npm 字段,出码时将不能通过import语句导入组件。`)
return false
}
if (!component.npm) {
logger.error(`组件文件 ${file} 缺少 npm 字段,出码时将不能通过import语句导入组件。`)
return false
}
🤖 Prompt for AI Agents
In packages/materials/buildMaterials.mjs around lines 35 to 39, the code logs a
warning when component.npm is missing but then returns false (failing the
component); change the log level to logger.error so the log matches the failure
behavior (keep the return false), i.e., replace logger.warn with logger.error
and keep the existing message so that missing npm is treated as an error and
clearly recorded.

Comment on lines +76 to +85
componentFiles.forEach((file) => {
const material = fsExtra.readJsonSync(path.resolve(entry, file), { throws: false })

if (!material) {
const fileFullPath = path.join(process.cwd(), file)

logger.error(`文件格式有误 (${fileFullPath})`)

return
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Incorrect path construction in error message.

Line 80 constructs the error path using path.join(process.cwd(), file), but file is a filename relative to entry, not relative to process.cwd(). This produces an incorrect path in the error message.

Apply this diff to fix the path construction:

     if (!material) {
-      const fileFullPath = path.join(process.cwd(), file)
+      const fileFullPath = path.resolve(entry, file)
 
       logger.error(`文件格式有误 (${fileFullPath})`)
📝 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
componentFiles.forEach((file) => {
const material = fsExtra.readJsonSync(path.resolve(entry, file), { throws: false })
if (!material) {
const fileFullPath = path.join(process.cwd(), file)
logger.error(`文件格式有误 (${fileFullPath})`)
return
}
componentFiles.forEach((file) => {
const material = fsExtra.readJsonSync(path.resolve(entry, file), { throws: false })
if (!material) {
const fileFullPath = path.resolve(entry, file)
logger.error(`文件格式有误 (${fileFullPath})`)
return
}
🤖 Prompt for AI Agents
In packages/materials/buildMaterials.mjs around lines 76 to 85, the error path
is built with path.join(process.cwd(), file) but `file` is relative to `entry`;
change the construction to resolve using the entry directory (e.g.
path.resolve(entry, file) or path.join(entry, file)) so the error message shows
the correct full path, and update the logger.error call to use that resolved
path variable.

Comment on lines +249 to +265
function start() {
const commandsMap = {
serve: serve,
build: build,
'build:split': buildSplit
}

const command = process.argv.slice(2)

if (!commandsMap[command]) {
logger.error(`[@opentiny/tiny-engine-materials] 不支持${command}命令`)

return
}

commandsMap[command]()
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical: Command argument extracted incorrectly.

Line 256 uses process.argv.slice(2), which returns an array, but line 258 uses command as if it were a string when accessing commandsMap[command]. This means commandsMap[command] will always be undefined, and the script will never execute any command.

Apply this diff to fix the bug:

-  const command = process.argv.slice(2)
+  const command = process.argv[2]
 
   if (!commandsMap[command]) {

Alternatively, extract the first element explicitly:

-  const command = process.argv.slice(2)
+  const [command] = process.argv.slice(2)
 
   if (!commandsMap[command]) {
🤖 Prompt for AI Agents
In packages/materials/buildMaterials.mjs around lines 249 to 265, the code uses
process.argv.slice(2) which returns an array but treats it as a string key when
looking up commandsMap, causing commandsMap[command] to always be undefined;
change the extraction to get the first argument (e.g., const command =
process.argv[2] or const [command] = process.argv.slice(2)) and then use that
string to check and invoke commandsMap[command], keeping the existing error
handling and return behavior if the command is not found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking-change enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants