Skip to content

Conversation

@chilingling
Copy link
Member

@chilingling chilingling commented Nov 3, 2025

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

    • Enhanced HTTP service with improved request/response handling and streaming support.
    • Added code formatting utilities supporting JavaScript, JSON, HTML, and CSS.
    • Expanded code generation capabilities for application assets.
  • Improvements

    • Comprehensive TypeScript type safety enhancements across common utilities and composables.
    • Better IDE support and code intelligence through exported type definitions.

✏️ Tip: You can customize this high-level summary in your review settings.

@github-actions github-actions bot added the chore label Nov 3, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 3, 2025

Walkthrough

This PR migrates several core JavaScript modules to TypeScript, adding comprehensive type definitions and interfaces while maintaining existing functionality. Configuration files are updated to support TypeScript builds with type declaration generation, and several existing TypeScript files receive stronger type annotations for improved type safety.

Changes

Cohort / File(s) Summary
HTTP Service Migration
packages/common/composable/http/index.jsindex.ts, packages/common/js/http.jshttp.ts
Converts HTTP composable and request utilities to TypeScript with full type coverage: Axios-based MetaService with interceptor typing, HTTP verb methods, and generic response types. http.ts adds strongly-typed event request and page update handlers with control flow for VSCode environment integration.
AST & Code Formatting Utilities
packages/common/js/ast.jsast.ts
Converts AST parsing, code formatting, and expression inspection utilities to TypeScript with comprehensive type definitions: BabelAst, GeneratorInput, FormatterFn, SupportedLanguage, and schema-related interfaces (SchemaValue, PageSchema, SchemaExpressionNode).
VSCode File Generation
packages/common/js/vscodeGenerateFile.jsvscodeGenerateFile.ts
Migrates seven generator functions (Router, I18n, Block, Page, DataSource, Bridge, Util) to TypeScript with dedicated parameter interfaces and return type annotations.
Type Annotations – Core Modules
packages/common/js/canvas.ts, comment.ts, css.ts, environments.ts, example.ts, verification.ts
Adds explicit parameter and return type annotations, type guards, and type-narrowing patterns (e.g., node type guards, cast assertions) without altering runtime behavior.
Type Annotations – Advanced Modules
packages/common/js/i18n.ts, linter.ts, monitor.ts, preview.ts
Introduces structured interfaces and stricter typing: LocaleKeyMap/LocaleMessages for i18n, monaco editor types for linter, WorkerMessage types for async communication, and PreviewMessage/PreviewParams for preview window handling.
ESLint Configuration
packages/common/js/config-files/eslint-rule.ts
Updates import path from '@eslint/js/src/configs/eslint-recommended.js' to 'eslint-recommended' (removes file extension).
Build Configuration & Package Metadata
packages/common/package.json, tsconfig.json, vite.config.ts
Adds TypeScript configuration, upgrades package.json exports to include type declarations, integrates vite-plugin-dts for .d.ts generation, and adds @types dependencies for Babel, css-tree, and Prettier.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 From JS to TypeScript we hop with pride,
Types flowing clear on every side.
Interfaces guard what once ran free,
Safer code, as strong as can be!
The rabbit's work: migration done, ✨
Type-safe and ready—hopping fun! 🚀

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'chore: enhance common package types' is directly related to the main changes, which involve TypeScript type enhancements across the common package.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

@chilingling chilingling force-pushed the chore/enhanceCommonTypes branch from 5928998 to 8b96ed5 Compare December 26, 2025 07:08
@chilingling chilingling force-pushed the chore/enhanceCommonTypes branch from 8b96ed5 to 85b7520 Compare December 26, 2025 07:52
@chilingling chilingling marked this pull request as ready for review December 26, 2025 07:55
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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/common/js/monitor.ts (1)

25-36: Add edge case handling for URL parameters without values.

Line 31 assigns unitItem[1] directly without checking if it exists. When a URL parameter lacks an = delimiter (e.g., ?foo&bar=baz), the split result has fewer than 2 elements, causing unitItem[1] to be undefined. This creates inconsistency with the Record<string, string> type annotation and results in incorrect parsing.

Handle this by either filtering invalid parameters or using a default value:

   urlUnit.forEach((item) => {
     const unitItem = item.split('=')
-    unit[unitItem[0]] = unitItem[1]
+    if (unitItem.length >= 2) {
+      unit[unitItem[0]] = unitItem[1]
+    }
   })

Or preserve empty values:

   urlUnit.forEach((item) => {
     const unitItem = item.split('=')
-    unit[unitItem[0]] = unitItem[1]
+    unit[unitItem[0]] = unitItem[1] ?? ''
   })
🧹 Nitpick comments (8)
packages/common/js/environments.ts (1)

23-23: Consider augmenting the Window interface for better type safety.

The double cast works but could be improved by declaring the vscodeBridge property on the Window interface.

🔎 Suggested type-safe alternative

Add a type declaration file (e.g., types/window.d.ts):

declare global {
  interface Window {
    vscodeBridge?: boolean
  }
}

export {}

Then simplify the code:

-export const isVsCodeEnv = (window as any).vscodeBridge as boolean
+export const isVsCodeEnv = window.vscodeBridge ?? false
packages/common/js/verification.ts (1)

15-15: LGTM! Type annotations improve type safety.

The explicit string parameter types are correctly added and align with the regex test operations.

Optional: Add explicit boolean return types for consistency

For complete type coverage, consider adding explicit boolean return types:

-export const verifyEventName = (name: string) => REGEXP_EVENT_NAME.test(name)
+export const verifyEventName = (name: string): boolean => REGEXP_EVENT_NAME.test(name)

-export const verifyBlockName = (string: string) => REGEXP_BLOCK_NAME.test(string)
+export const verifyBlockName = (string: string): boolean => REGEXP_BLOCK_NAME.test(string)

-export const verifyBlockId = (string: string) => REGEXP_BLOCK_ID.test(string)
+export const verifyBlockId = (string: string): boolean => REGEXP_BLOCK_ID.test(string)

-export const verifyBlockPath = (string: string) => !string || REGEXP_BLOCK_PATH.test(string)
+export const verifyBlockPath = (string: string): boolean => !string || REGEXP_BLOCK_PATH.test(string)

-export const verifyJsVarName = (name: string) => REGEXP_JS_VAR.test(name)
+export const verifyJsVarName = (name: string): boolean => REGEXP_JS_VAR.test(name)

-export const verifyJsVarSymbolName = (name: string) => REGEXP_JS_VAR_SYMBOL.test(name)
+export const verifyJsVarSymbolName = (name: string): boolean => REGEXP_JS_VAR_SYMBOL.test(name)

Also applies to: 19-19, 23-23, 27-27, 45-45, 47-47

packages/common/js/http.ts (1)

86-138: Consider addressing the return type TODO.

The function has comprehensive side effects and error handling. The TODO comment at Line 92 indicates the return type needs optimization from any to a more specific type.

While the current implementation works, would you like me to help determine the specific return type based on the API response structure, or should this TODO be tracked in a separate issue?

packages/common/js/ast.ts (1)

40-73: Complex expression formatting logic needs careful testing.

The special handling for single JavaScript expressions (Lines 53-63) wraps code in !() for formatting and then unwraps it. This workaround addresses Prettier's semicolon insertion behavior but adds complexity.

Consider adding unit tests for edge cases

The expression wrapping logic handles multiple cases:

  1. Wrapped result still has !()
  2. Only leading ! remains

Ensure this is well-tested with various expression types (arrow functions, object literals, JSX, etc.) to prevent formatting bugs.

packages/common/js/vscodeGenerateFile.ts (1)

93-94: LGTM! Consistent generator function pattern.

All seven generator functions follow a consistent pattern of delegating to the HTTP service. The Promise<any> return type is acceptable for these API wrappers where response structures may vary.

Optional: Consider specific return types if API responses are well-defined

If the API responses have consistent structures, consider defining specific return types instead of any:

interface GenerateResult {
  success: boolean
  message?: string
  // ... other common fields
}

const generateRouter = (params: GenerateRouterParams): Promise<GenerateResult> =>
  getMetaApi(META_SERVICE.Http).post('/generate/api/generateRouter', params)

Also applies to: 111-112, 126-127, 140-141, 157-158, 170-171, 183-184

packages/common/composable/http/index.ts (1)

58-90: Review tuple detection logic for edge cases.

The tuple detection at Line 80 checks config.length <= 2 && typeof config[0] === 'function' && typeof config[1] !== 'object'. This may incorrectly classify certain arrays as tuples.

Example edge case:

// This would be detected as a tuple, but might be intended as an interceptor array:
const config = [fulfillFn, undefined]  // length=2, config[1] is not an object
Consider a more explicit tuple detection
-    const isTuple = config.length <= 2 && typeof config[0] === 'function' && typeof config[1] !== 'object'
+    const isTuple = 
+      config.length <= 2 && 
+      typeof config[0] === 'function' && 
+      (config.length === 1 || typeof config[1] === 'function' || config[1] === undefined)

This more explicitly checks if the second element is a valid rejection handler or undefined.

packages/common/js/linter.ts (2)

87-94: Remove unnecessary type assertion.

The as WorkerRequestMessage cast at line 93 is unnecessary because the object literal already matches the WorkerRequestMessage interface structure exactly. TypeScript can infer this type automatically.

🔎 Proposed simplification
   timer = setTimeout(() => {
     timer = null
     worker.postMessage({
       code: model.getValue(),
       // 发起 ESLint 静态检查时,携带 versionId
       version: model.getVersionId()
-    } as WorkerRequestMessage)
+    })
   }, 500)

17-20: Consider gradually refining the index signature.

The [key: string]: any index signature allows any additional properties and weakens type safety. Based on learnings, if the exact structure of additional state properties becomes clearer through usage, consider refining this to more specific types in future iterations.

📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c592f46 and 85b7520.

📒 Files selected for processing (27)
  • packages/common/composable/http/index.js
  • packages/common/composable/http/index.ts
  • packages/common/i18n/index.ts
  • packages/common/js/app.ts
  • packages/common/js/ast.js
  • packages/common/js/ast.ts
  • packages/common/js/canvas.ts
  • packages/common/js/comment.ts
  • packages/common/js/config-files/eslint-rule.ts
  • packages/common/js/config-files/prettierrc.ts
  • packages/common/js/constants.ts
  • packages/common/js/css.ts
  • packages/common/js/environments.ts
  • packages/common/js/example.ts
  • packages/common/js/http.js
  • packages/common/js/http.ts
  • packages/common/js/i18n.ts
  • packages/common/js/importMap.ts
  • packages/common/js/linter.ts
  • packages/common/js/monitor.ts
  • packages/common/js/preview.ts
  • packages/common/js/verification.ts
  • packages/common/js/vscodeGenerateFile.js
  • packages/common/js/vscodeGenerateFile.ts
  • packages/common/package.json
  • packages/common/tsconfig.json
  • packages/common/vite.config.ts
💤 Files with no reviewable changes (4)
  • packages/common/js/vscodeGenerateFile.js
  • packages/common/js/http.js
  • packages/common/composable/http/index.js
  • packages/common/js/ast.js
🧰 Additional context used
🧠 Learnings (16)
📓 Common learnings
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/material-function/configure.ts:1-4
Timestamp: 2025-01-14T06:52:56.236Z
Learning: In the configure.ts module, type definitions were intentionally kept as Record<string, any> during the initial refactoring to separate files. Type definitions will be added in a follow-up task after thorough analysis of the configuration structure.
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/RenderMain.ts:82-88
Timestamp: 2025-01-14T08:50:50.226Z
Learning: For PR #1011, the focus is on resolving conflicts and migrating code, with architectural improvements deferred for future PRs.
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/type.d.ts:1-14
Timestamp: 2025-01-14T06:57:07.645Z
Learning: In the tiny-engine project, the team prefers to gradually refine TypeScript types as they become clearer, rather than prematurely defining specific types when the exact structure is not yet well-understood.
📚 Learning: 2025-01-14T06:52:56.236Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/material-function/configure.ts:1-4
Timestamp: 2025-01-14T06:52:56.236Z
Learning: In the configure.ts module, type definitions were intentionally kept as Record<string, any> during the initial refactoring to separate files. Type definitions will be added in a follow-up task after thorough analysis of the configuration structure.

Applied to files:

  • packages/common/tsconfig.json
  • packages/common/js/i18n.ts
  • packages/common/vite.config.ts
📚 Learning: 2025-07-03T09:22:59.512Z
Learnt from: hexqi
Repo: opentiny/tiny-engine PR: 1501
File: mockServer/src/tool/Common.js:79-82
Timestamp: 2025-07-03T09:22:59.512Z
Learning: In the tiny-engine project, the mockServer code uses ES6 import syntax but is compiled to CommonJS output. This means CommonJS globals like `__dirname` are available at runtime, while ES6 module-specific features like `import.meta` would cause runtime errors.

Applied to files:

  • packages/common/js/environments.ts
  • packages/common/package.json
  • packages/common/vite.config.ts
📚 Learning: 2025-01-14T04:25:46.281Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/material-function/material-getter.ts:66-80
Timestamp: 2025-01-14T04:25:46.281Z
Learning: In the tiny-engine project, styles from block components are processed through Vite's CSS compilation pipeline, and additional style sanitization libraries should be avoided to maintain consistency with this approach.

Applied to files:

  • packages/common/js/css.ts
📚 Learning: 2025-01-14T04:22:02.404Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/builtin/builtin.json:645-850
Timestamp: 2025-01-14T04:22:02.404Z
Learning: In TinyEngine, components must use inline styles instead of CSS classes because components cannot carry class styles when dragged into the canvas.

Applied to files:

  • packages/common/js/css.ts
📚 Learning: 2024-09-30T07:51:10.036Z
Learnt from: chilingling
Repo: opentiny/tiny-engine PR: 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.

Applied to files:

  • packages/common/package.json
📚 Learning: 2025-01-14T08:44:09.485Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/canvas-function/controller.ts:1-7
Timestamp: 2025-01-14T08:44:09.485Z
Learning: Type safety improvements for the controller in `packages/canvas/render/src/canvas-function/controller.ts` should be deferred until the data structure is finalized.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T06:55:14.457Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/canvas-function/design-mode.ts:6-13
Timestamp: 2025-01-14T06:55:14.457Z
Learning: The code in `packages/canvas/render/src/canvas-function/design-mode.ts` is migrated code that should be preserved in its current form during the migration process. Refactoring suggestions for type safety and state management improvements should be considered in future PRs.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T08:45:57.032Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/application-function/global-state.ts:12-25
Timestamp: 2025-01-14T08:45:57.032Z
Learning: The code in `packages/canvas/render/src/application-function/global-state.ts` is migrated from an existing codebase and should be handled with care when making modifications.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T06:59:23.602Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/page-block-function/methods.ts:9-21
Timestamp: 2025-01-14T06:59:23.602Z
Learning: The code in packages/canvas/render/src/page-block-function/methods.ts is migrated code that should not be modified during the migration phase. Error handling improvements can be addressed in future PRs.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T07:11:44.138Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/canvas-function/custom-renderer.ts:28-32
Timestamp: 2025-01-14T07:11:44.138Z
Learning: The locale and webComponent wrapper in `packages/canvas/render/src/canvas-function/custom-renderer.ts` are part of migrated code and will be improved in a future PR.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T08:47:20.946Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/application-function/utils.ts:18-18
Timestamp: 2025-01-14T08:47:20.946Z
Learning: The use of `Function` type in `packages/canvas/render/src/application-function/utils.ts` is acceptable per team's decision, despite TypeScript's recommendation to use more specific function types.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T07:11:58.019Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/page-block-function/accessor-map.ts:13-13
Timestamp: 2025-01-14T07:11:58.019Z
Learning: The user prefers to keep the `Function` type in `packages/canvas/render/src/page-block-function/accessor-map.ts` for now, despite static analysis warnings.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T06:59:02.999Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/material-function/support-collection.ts:3-15
Timestamp: 2025-01-14T06:59:02.999Z
Learning: The code in `packages/canvas/render/src/material-function/support-collection.ts` is migrated code that should not be modified at this time to maintain stability during the migration process.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2025-01-14T06:58:38.661Z
Learnt from: rhlin
Repo: opentiny/tiny-engine PR: 1011
File: packages/canvas/render/src/data-utils.ts:8-12
Timestamp: 2025-01-14T06:58:38.661Z
Learning: The use of Function constructor in `packages/canvas/render/src/data-utils.ts` is part of migrated code and was intentionally kept as-is during migration, despite potential security concerns.

Applied to files:

  • packages/common/js/canvas.ts
📚 Learning: 2024-10-30T02:10:38.028Z
Learnt from: yy-wow
Repo: opentiny/tiny-engine PR: 886
File: packages/common/composable/index.js:3-3
Timestamp: 2024-10-30T02:10:38.028Z
Learning: 在 `packages/common/composable` 目录中,`HttpService` 模块位于 `./http/index.js`,而不是 `./http.js`。

Applied to files:

  • packages/common/composable/http/index.ts
🧬 Code graph analysis (4)
packages/common/js/http.ts (3)
packages/common/js/environments.ts (1)
  • isVsCodeEnv (23-23)
packages/common/js/vscodeGenerateFile.ts (2)
  • generatePage (186-186)
  • generateRouter (186-186)
packages/register/src/hooks.ts (3)
  • useNotify (95-95)
  • useBreadcrumb (89-89)
  • usePage (87-87)
packages/common/js/preview.ts (1)
packages/register/src/hooks.ts (1)
  • useMaterial (96-96)
packages/common/js/linter.ts (1)
packages/common/js/worker-files/eslint.worker.js (2)
  • event (50-50)
  • markers (55-67)
packages/common/js/i18n.ts (1)
packages/common/js/constants.ts (1)
  • i18nKeyMaps (74-77)
⏰ 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 (45)
packages/common/js/comment.ts (1)

13-16: LGTM! Clean type annotation.

The explicit TypeScript types enhance type safety without altering behavior.

packages/common/tsconfig.json (1)

1-12: LGTM! Well-structured TypeScript configuration.

The include patterns appropriately cover the package's TypeScript and Vue files.

packages/common/js/canvas.ts (2)

16-26: LGTM! Well-defined interfaces.

The Occupier and CanvasStatus interfaces provide clear type definitions for canvas state management.


28-45: LGTM! Type-safe function signature.

The function signature now provides clear type contracts while preserving existing logic.

packages/common/vite.config.ts (3)

21-21: LGTM! Type declaration generation added.

The vite-plugin-dts integration will generate TypeScript declarations for consumers of this package.


23-25: LGTM! Updated entry discovery.

The glob pattern now correctly includes both JavaScript and TypeScript files.


42-45: LGTM! Independent type declarations per entry.

The rollupTypes: false configuration generates separate .d.ts files for each entry point, which is appropriate for a library package.

packages/common/js/example.ts (1)

96-99: LGTM! Enhanced type safety.

The function now guarantees a string return type with explicit parameter typing and a fallback empty string.

packages/common/js/css.ts (3)

14-14: LGTM! Type-only import.

Importing types separately keeps the runtime bundle smaller.


26-32: LGTM! Excellent use of type guard.

The type predicate (node): node is Rule properly narrows the type in the forEach callback, enabling type-safe access to Rule properties.


51-55: LGTM! Explicit parameter typing.

The typed parameter improves function clarity and enables better IDE support.

packages/common/js/i18n.ts (4)

18-25: LGTM! Well-defined type interfaces.

The type definitions provide clear contracts for i18n configuration and usage.


28-40: LGTM! Type-safe i18n creation.

The function signature and key casting ensure type safety throughout the i18n initialization process.


42-48: LGTM! Appropriate handling of external library typing.

The comment clearly documents why any is used here, which is reasonable given potential incomplete type definitions in @opentiny/vue-locale.


54-54: LGTM! Exported types for consumers.

Exporting the type definitions enables consumers of this package to use these types in their own code.

packages/common/js/preview.ts (7)

30-56: LGTM! Well-structured TypeScript interfaces.

The new interfaces provide clear type definitions for preview message events, parameters, and dependencies. The use of optional properties and index signatures offers appropriate flexibility.


58-58: LGTM! Explicit typing improves type safety.

The explicit typing for previewWindow as Window | null and the structured return type for getScriptAndStyleDeps with typed reducer parameter enhance type safety.

Also applies to: 60-63, 67-67


80-85: LGTM! Comprehensive return type definition.

The explicit async return type with all properties (currentPage, ancestors, scripts, styles) provides excellent type documentation and safety.


201-201: LGTM! Message event typing is appropriate.

The typed message event handler and window source assertion correctly handle the preview communication protocol.

Also applies to: 209-209


235-240: LGTM! Strong typing for history preview handler.

The explicit parameter types combining PreviewParams with partial schema params and the typed event handler improve type safety for history preview flows.


271-271: LGTM! Consistent parameter typing across functions.

The explicit PreviewParams and boolean types for isHistory parameter improve API clarity and type safety across getQueryParams, open, and previewPage.

Also applies to: 301-301, 341-341


126-127: All call sites of sendSchemaUpdate already guarantee previewWindow is initialized through proper guard checks. The non-null assertions are justified.

At line 165 (in handleSchemaChange), the call is preceded by a guard at line 158 that returns early if !previewWindow || previewWindow.closed. At line 215 (in the message listener), the call is gated by an explicit previewWindow check at line 213. The non-null assertions are safe.

Likely an incorrect or invalid review comment.

packages/common/js/http.ts (3)

20-29: LGTM! Well-documented event parameters interface.

The EventParams interface clearly defines the telemetry event structure with appropriate field types and flexibility for custom fields.


31-61: LGTM! Comprehensive type definitions for page updates.

The interfaces provide clear structure for page content, parameters, and update operations with appropriate optional fields and flexibility.


70-78: Silent error swallowing is appropriate for telemetry.

The empty catch block at Line 77 is acceptable for telemetry/monitoring use cases where failures should not impact the user experience. The function correctly returns undefined when no URL is provided or when the request fails.

packages/common/package.json (2)

61-64: LGTM! Type definitions align with runtime dependencies.

The added devDependencies for Babel, CSS-tree, and Prettier type definitions correctly support the TypeScript migration. The vite-plugin-dts enables declaration file generation.

Also applies to: 69-69


14-21: Wildcard export pattern for "./js/*" is correctly configured and will work as intended.

The vite configuration dynamically generates entry points for all .js and .ts files in the js/ directory using glob.sync('./js/**/*.{js,ts}'). Each file becomes an individual entry that outputs to dist/js/ with the same relative path structure. The dts plugin (configured with rollupTypes: false) generates independent .d.ts files for each entry, properly supporting the wildcard export pattern that maps "./js/*" to "./dist/js/*.d.ts" and "./dist/js/*.js". Imports like @opentiny/tiny-engine-common/js/app will correctly resolve to the corresponding built files.

packages/common/js/ast.ts (6)

26-30: LGTM! Simple utility functions for name manipulation.

The regex-based name insertion and removal functions correctly handle function declarations.


32-38: LGTM! Well-typed AST conversion utilities.

The type aliases and conversion functions provide a clean API for working with Babel ASTs. The use of TypeScript's utility types (ReturnType, Parameters) ensures consistency with Babel's API.


75-103: LGTM! Clean formatter implementations.

The language-specific formatters correctly configure Prettier with appropriate parsers and plugins.


105-116: Error logging via console is appropriate for formatting utilities.

The formatString function logs errors via console.log (Line 112) and returns the original string on failure. This graceful degradation is suitable for formatting utilities where failures shouldn't break the application.


120-138: LGTM! Expression detection with error handling.

The includedExpression function correctly traverses the AST to detect expression usage, with appropriate error logging.


140-205: LGTM! Comprehensive schema traversal utilities.

The recursive schema checking functions correctly handle various value types (primitives, objects, arrays) and properly detect JSExpression, JSFunction, and jsstring types. The type definitions are well-structured.

packages/common/js/vscodeGenerateFile.ts (1)

17-77: LGTM! Well-documented parameter interfaces.

The interfaces provide clear structure for each generation operation. The use of any for complex schema/tree structures is pragmatic given the flexible nature of these objects.

packages/common/composable/http/index.ts (3)

4-37: LGTM! Comprehensive interceptor type system.

The type definitions elegantly handle various interceptor patterns: single functions, tuples with optional rejection handlers, and arrays of interceptors. This provides excellent flexibility while maintaining type safety.


92-116: LGTM! Well-structured service initialization.

The service definition properly initializes the Axios instance and registers interceptors in the correct order.


117-159: LGTM! Type-safe HTTP method wrappers.

All HTTP methods are properly typed with generics and safely return undefined when the Axios instance is not initialized. The stream method correctly sets responseType: 'stream'.

packages/common/js/linter.ts (3)

14-14: Good use of type-only import.

Using import type for Monaco Editor types is the correct pattern for type-only imports in TypeScript, which helps with tree-shaking and avoids unnecessary runtime dependencies.


72-72: Verify cast safety after fixing ESLintMarker interface.

This cast to monaco.editor.IMarkerData[] is potentially unsafe due to the type mismatches in the ESLintMarker interface (lines 23-32). After correcting the code and severity field types in ESLintMarker, verify that the interface fully aligns with monaco.editor.IMarkerData to ensure this cast is safe.


46-50: Excellent type safety improvements.

The TypeScript enhancements throughout this file are well-implemented:

  • Function signatures with explicit parameter and return types
  • Proper typing for the worker URL and event handlers
  • Good use of ReturnType<typeof setTimeout> for the timer
  • Clear type annotations that improve code maintainability

These changes significantly enhance type safety while maintaining the existing functionality.

Also applies to: 51-51, 64-64, 79-79, 81-81

packages/common/js/monitor.ts (5)

13-13: LGTM: Import path updated for TypeScript.

The file extension removal follows TypeScript conventions for module imports.


38-47: LGTM: Unused parameter correctly marked.

The _lineNo prefix correctly suppresses linter warnings for the unused parameter while maintaining the standard window.onerror signature.


55-84: LGTM: Improved immutability with const.

The change from let to const for reason correctly enforces immutability since the variable is never reassigned.


95-113: LGTM: Consistent unused parameter handling.

The _lineNo prefix maintains consistency with globalMonitoring and correctly suppresses linter warnings.


115-119: LGTM: Function signature properly typed.

The explicit url: string parameter type enhances type safety and aligns with the TypeScript migration objectives.

@hexqi hexqi merged commit 810766d into opentiny:develop Dec 27, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants