Make WordPress Core

Opened 9 months ago

Closed 8 months ago

Last modified 2 months ago

#64662 closed task (blessed) (fixed)

Add TypeScript static analysis for core JavaScript files

Reported by: westonruter Owned by: westonruter
Priority: normal Milestone: 7.0
Component: Build/Test Tools Version:
Severity: normal Keywords: has-patch changes-requested
Cc: Focuses: javascript

Description (last modified by westonruter)

For #64661, a ​PR is proposed which adds TypeScript checking for the scripts related to the CodeMirror code editor integrations. With that in place, core should start expanding the scope of which JS files are checked to ensure code quality and fix subtle bugs. The same is being done for PHP with PHPStan in #61175.

Note that TypeScript is already being used in Gutenberg. See ​https://make.wordpress.org/core/2021/03/18/proposal-native-typescript-support-in-gutenberg/

To do:

  1. Commit ​https://github.com/WordPress/wordpress-develop/pull/10900
  2. Add typecheck:js to the precommit Grunt task.
  3. Add GHA workflow which runs typecheck:js

Change History (21)

#1 @westonruter
9 months ago

  • Description modified (diff)

#2 @westonruter
9 months ago

  • Milestone Awaiting Review → 7.0

#3 @westonruter
9 months ago

  • Owner set to westonruter
  • Status new → accepted

#4 @westonruter
9 months ago

PHPStan static analysis (exposed via npm run typecheck:php and composer phpstan) has landed in r61699.

#5 @westonruter
8 months ago

In 61800:

Code Editor: Improve types and fix options handling to avoid double-linting at initialization.

  • Refactor how CodeMirror is initialized so that the full settings are provided up-front. This avoids the linting from being applied twice at initialization, the first time with an incorrect configuration.
  • Add initial TypeScript configuration for core with npm run typecheck:js.
  • Add comprehensive types for code editor files: code-editor.js, javascript-lint.js, and htmlhint-kses.js.
  • Move code editor scripts from src/js/_enqueues/vendor/codemirror/ to src/js/_enqueues/lib/codemirror/. The CodeMirror library is sourced from the npm package as of r61539.
  • Remove (deprecated) esprima.js from being committed to SVN since in r61539 it was switched to using the npm package as its source.
  • Move fakejshint.js to src/js/_enqueues/deprecated.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/10900

Follow up to r61611, r61539.

Props westonruter, jonsurrell, justlevine.
See #64662, #48456.
Fixes #64661.

This ticket was mentioned in ​PR #11131 on ​WordPress/wordpress-develop by ​@westonruter.


8 months ago
#6

  • Keywords has-patch added

This introduces a new GitHub Action workflow for JavaScript type checking, mirroring the implementation for PHPStan. It also adds a typecheck:js Grunt task and includes it in the precommit:js task list.

Trac ticket: https://core.trac.wordpress.org/ticket/64662

## Use of AI Tools

Initial commit authored by Gemini CLI with prompt:

Take a look at https://core.trac.wordpress.org/ticket/64662 and implement. You can see that typecheck:js npm script was added in b6c1bb776b360ef64a00468e6df72792511866d3. Similarly, you can see in 8a82e67cf65766fcb8a11e3fe5c6e2f48083fcdb how typecheck:php was introduced for PHPStan and a GitHub action was added to automatically run. What was done for PHPStan, implement similarly for TypeScript.

​@westonruter commented on ​PR #11131:


8 months ago
#7

Difference between reusable-phpstan-static-analysis.yml and reusable-javascript-type-checking.yml:

  • .github/workflows/

    old new  
    11##
    2 # A reusable workflow that runs PHP Static Analysis tests.
     2# A reusable workflow that runs JavaScript Type Checking.
    33##
    4 name: PHP Static Analysis
     4name: JavaScript Type Checking
    55
    66on:
    77  workflow_call:
    8     inputs:
    9       php-version:
    10         description: 'The PHP version to use.'
    11         required: false
    12         type: 'string'
    13         default: 'latest'
    148
    159# Disable permissions for all available scopes by default.
    1610# Any needed permissions should be configured at the job level.
    1711permissions: {}
    1812
    1913jobs:
    20   # Runs PHP static analysis tests.
     14  # Runs JavaScript type checking.
    2115  #
    2216  # Violations are reported inline with annotations.
    2317  #
    2418  # Performs the following steps:
    2519  # - Checks out the repository.
    26   # - Sets up PHP.
     20  # - Sets up Node.js.
    2721  # - Logs debug information.
    28   # - Installs Composer dependencies.
    29   # - Configures caching for PHP static analysis scans.
    30   # - Make Composer packages available globally.
    31   # - Runs PHPStan static analysis (with Pull Request annotations).
    32   # - Saves the PHPStan result cache.
     22  # - Installs npm dependencies.
     23  # - Configures caching for TypeScript build info.
     24  # - Runs JavaScript type checking.
     25  # - Saves the TypeScript build info.
    3326  # - Ensures version-controlled files are not modified or deleted.
    34   phpstan:
    35     name: Run PHP static analysis
     27  typecheck:
     28    name: Run JavaScript type checking
    3629    runs-on: ubuntu-24.04
    3730    permissions:
    3831      contents: read
    … …  
    5144          node-version-file: '.nvmrc'
    5245          cache: npm
    5346
    54       - name: Set up PHP
    55         uses: shivammathur/setup-php@20529878ed81ef8e78ddf08b480401e6101a850f # v2.35.3
    56         with:
    57           php-version: ${{ inputs.php-version }}
    58           coverage: none
    59           tools: cs2pr
    60 
    61       # This date is used to ensure that the Composer cache is cleared at least once every week.
    62       # http://man7.org/linux/man-pages/man1/date.1.html
    63       - name: "Get last Monday's date"
    64         id: get-date
    65         run: echo "date=$(/bin/date -u --date='last Mon' "+%F")" >> "$GITHUB_OUTPUT"
    66 
    67       - name: General debug information
     47      - name: Log debug information
    6848        run: |
    6949          npm --version
    7050          node --version
    71           composer --version
    7251
    73       # Since Composer dependencies are installed using `composer update` and no lock file is in version control,
    74       # passing a custom cache suffix ensures that the cache is flushed at least once per week.
    75       - name: Install Composer dependencies
    76         uses: ramsey/composer-install@3cf229dc2919194e9e36783941438d17239e8520 # v3.1.1
    77         with:
    78           custom-cache-suffix: ${{ steps.get-date.outputs.date }}
    79 
    80       - name: Make Composer packages available globally
    81         run: echo "${PWD}/vendor/bin" >> "$GITHUB_PATH"
    82 
    8352      - name: Install npm dependencies
    8453        run: npm ci --ignore-scripts
    8554
    86       - name: Build WordPress
    87         run: npm run build:dev
    88 
    89       - name: Cache PHP Static Analysis scan cache
     55      - name: Cache TypeScript build info
    9056        uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
    9157        with:
    92           path: .cache # This is defined in the base.neon file.
    93           key: "phpstan-result-cache-${{ github.run_id }}"
     58          path: |
     59            *.tsbuildinfo
     60          key: "ts-build-info-${{ github.run_id }}"
    9461          restore-keys: |
    95             phpstan-result-cache-
     62            ts-build-info-
    9663
    97       - name: Run PHP static analysis tests
    98         id: phpstan
    99         run: composer run phpstan -- -vvv --error-format=checkstyle | cs2pr --errors-as-warnings --graceful-warnings
     64      - name: Run JavaScript type checking
     65        run: npm run typecheck:js
    10066
    10167      - name: "Save result cache"
    10268        uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
    10369        if: ${{ !cancelled() }}
    10470        with:
    105           path: .cache
    106           key: "phpstan-result-cache-${{ github.run_id }}"
     71          path: |
     72            *.tsbuildinfo
     73          key: "ts-build-info-${{ github.run_id }}"
    10774
    10875      - name: Ensure version-controlled files are not modified or deleted
    10976        run: git diff --exit-code

​@westonruter commented on ​PR #11131:


8 months ago
#8

Difference between .github/workflows/phpstan-static-analysis.yml and .github/workflows/javascript-type-checking.yml:

  • .github/workflows/

    old new  
    1 name: PHPStan Static Analysis
     1name: JavaScript Type Checking
    22
    33on:
    4   # PHPStan testing was introduced in 7.0.0.
     4  # JavaScript type checking was introduced in 7.0.0.
    55  push:
    66    branches:
    77      - trunk
    … …  
    1414      - trunk
    1515      - '[7-9].[0-9]'
    1616    paths:
    17       # This workflow only scans PHP files.
    18       - '**.php'
    19       # These files configure Composer. Changes could affect the outcome.
    20       - 'composer.*'
    21       # These files configure PHPStan. Changes could affect the outcome.
    22       - 'phpstan.neon.dist'
    23       - 'tests/phpstan/base.neon'
    24       - 'tests/phpstan/baseline.php'
     17      # This workflow only scans JavaScript files.
     18      - '**.js'
     19      # These files configure npm. Changes could affect the outcome.
     20      - 'package*.json'
     21      - '.nvmrc'
     22      # This file configures TypeScript. Changes could affect the outcome.
     23      - 'tsconfig.json'
     24      # This directory contains TypeScript definitions. Changes could affect the outcome.
     25      - 'typings/**'
    2526      # Confirm any changes to relevant workflow files.
    26       - '.github/workflows/phpstan-static-analysis.yml'
    27       - '.github/workflows/reusable-phpstan-static-analysis.yml'
     27      - '.github/workflows/javascript-type-checking.yml'
     28      - '.github/workflows/reusable-javascript-type-checking.yml'
    2829  workflow_dispatch:
    2930
    3031# Cancels all previous workflow runs for pull requests that have not completed.
    … …  
    3940permissions: {}
    4041
    4142jobs:
    42   # Runs PHPStan Static Analysis.
    43   phpstan:
    44     name: PHP static analysis
    45     uses: ./.github/workflows/reusable-phpstan-static-analysis.yml
     43  # Runs JavaScript type checking.
     44  typecheck:
     45    name: JavaScript type checking
     46    uses: ./.github/workflows/reusable-javascript-type-checking.yml
    4647    permissions:
    4748      contents: read
    4849    if: ${{ github.repository == 'WordPress/wordpress-develop' || ( github.event_name == 'pull_request' && github.actor != 'dependabot[bot]' ) }}
    … …  
    5354    permissions:
    5455      actions: read
    5556      contents: read
    56     needs: [ phpstan ]
     57    needs: [ typecheck ]
    5758    if: ${{ github.repository == 'WordPress/wordpress-develop' && github.event_name != 'pull_request' && always() }}
    5859    with:
    5960      calling_status: ${{ contains( needs.*.result, 'cancelled' ) && 'cancelled' || contains( needs.*.result, 'failure' ) && 'failure' || 'success' }}
    … …  
    8182
    8283    steps:
    8384      - name: Dispatch workflow run
    84         uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
     85        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
    8586        with:
    8687          retries: 2
    8788          retry-exempt-status-codes: 418

​@westonruter commented on ​PR #11131:


8 months ago
#9

When a TypeScript error occurs (e.g. d2ad278), the ​job fails as expected:

https://github.com/user-attachments/assets/1952be8b-f2d5-43ae-9679-3addf7c5375c

https://github.com/user-attachments/assets/7c8aa3e1-450d-44b4-a2b2-133f0177cc41

And the errors are annotated in the PR:

https://github.com/user-attachments/assets/353fd1ef-73d1-4d8e-b719-ea7514aaa864

This is in contrast with PHPStan's analysis which does _not_ fail its job when there are errors, but instead the errors are annotated as warnings.

I think this is fine given that TypeScript checking is being incrementally added to files on an opt-in basis. (Personally I would have wanted PHPStan errors to also cause jobs to fail with error annotations.)

#10 @westonruter
8 months ago

​PR is ready for review.

​@westonruter commented on ​PR #11131:


8 months ago
#11

Also, running npx grunt precommit:js with d2ad278 staged:

...
https://github.com/user-attachments/assets/5c2ca068-128f-4193-9c71-90c34ce481bd

#12 @westonruter
8 months ago

  • Resolution → fixed
  • Status accepted → closed

In 61830:

Build/Test Tools: Integrate TypeScript into the core development workflow.

This introduces a new GitHub Action workflow for JavaScript type checking, mirroring the implementation for PHPStan in #61175. It also adds a typecheck:js Grunt task and includes it in the precommit:js task list. Only files related to the code editor are initially checked with TypeScript, with the expectation that additional files will be added to the files list in tsconfig.json as a part of ongoing maintenance work, for example #64238 and #64226.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/11131

Follow up to r61699, r61800, r61539.

Props westonruter, jonsurrell.
See #61175, #64661, #48456.
Fixes #64662.

#13 @desrosj
8 months ago

  • Keywords changes-requested added
  • Resolution fixed
  • Status closed → reopened

Thanks for this, everyone!

I have a few small points of feedback for a follow up commit. Can the reusable workflow file be renamed to include a -v1 suffix? Initially only the PHPUnit reusable workflow contained the -v1 suffix, but all new ones introduced since then have included it.

I know it's inconsistent, but I would like to update all the others eventually. It's just a pain to backport to every single branch calling the file. I do plan to try and tackle that the next time a given workflow requires a new -v2 file.

It just makes it more apparent which one is the most recent. It's reasonable to assume that the file without any suffix is the current or active version and all with a suffix are old.

( github.event_name == 'pull_request' && github.actor != 'dependabot[bot]' )

Can we remove the dependabot check here? The bot was deactivated in [61049] because it stopped working when GitHub switched over to their new runner architecture, and all bot specific checks were removed in [61050].

If we ever decide to try and get that working again, we can re-add this check with the others.

#14 @westonruter
8 months ago

@desrosj Would this also apply to the new PHPStan reusable workflow .github/workflows/reusable-phpstan-static-analysis.yml added in #61175?

This ticket was mentioned in ​PR #11163 on ​WordPress/wordpress-develop by ​@westonruter.


8 months ago
#15

Trac ticket: https://core.trac.wordpress.org/ticket/64662

  • Add -v1 suffix to reusable workflows for JavaScript type checking and PHPStan analysis: This follows the established convention of including a version suffix for reusable workflow files, ensuring consistency with other workflows like PHPUnit.
  • Remove Dependabot exclusion from type checking workflows: Since Dependabot was deactivated in b60c06c67e4a5a2b1351cb8bb54ed4cdd2e8e49e and other bot-specific checks were removed in 26230c33261cf559907a90547b4827ea66ff9f30, this exclusion is no longer necessary.

## Use of AI Tools

Feedback from @desrosj fed into Gemini CLI to implement.

#16 @westonruter
8 months ago

  • Resolution → fixed
  • Status reopened → closed

In 61837:

Build/Test Tools: Add -v1 suffix to TypeScript/PHPStan reusable workflows and remove unused Dependabot exclusion.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/11163

Follow up to r61830, r61699, r61050, r61049.

Props desrosj, westonruter.
See #61175.
Fixes #64662.

#17 @westonruter
2 months ago

In 63454:

Customize: Document and modernize the JS base API.

The variadic signatures could not be documented without names for their arguments, so the arguments object is replaced with modern rest parameters across wp.customize.Class, Events, Value, Values, Element and Messenger. The Array.prototype.slice alias they relied on is no longer needed and is removed. Rest parameters are supported by >96% of users globally and all browser versions supported by WordPress.

The argument these two files receive was named exports, while the docblock beside the line using it said window.wp.customize. It is now wp, and the arguments of both wrapping functions are documented.

Many of the types named nothing that resolves. Seven tags were typed mixed, which is not a JSDoc type; one still carried the [type] placeholder an IDE had left behind; and one each read ..., an unqualified Value, and string|jQuery collection, which is two words rather than a type expression. Where the jQuery namespace appeared it was spelled in lower case, so it named the $ function rather than a collection or an event. The value accepted by Value#set() was typed as an object, though a Value holds anything. In loader.js the one documented parameter had no braces at all.

The remaining docblocks are new, since most of these methods carried none. Among what they now record: Class returns a function rather than an object whenever the prototype defines an instance method, which is how wp.customize() and wp.customize.control() come to be callable, and Value#link() binds the receiver to follow the values it is given rather than the reverse.

QUnit tests cover the applicator form of the constructor, the forwarding of arguments through the event methods, and unsync() in both directions, resolving two long-standing todos in that file.

Developed as subset of ​https://github.com/WordPress/wordpress-develop/pull/10743.
Follow-up to r48110, r48650.

Props westonruter, afercia, grapplerulrich, vishalkakadiya, shailu25.
See #39671, #40831, #64662, #66033.

#18 @westonruter
2 months ago

In 63455:

Customize: Correct the JSDoc for the controls API.

Many of the types named nothing that resolves. The four deferred getters referred to their callback typedefs without a namespace, the promise they return was spelled jQuery.promise, which is neither the capitalization the namespace is declared under nor the name of a type, and jQuery events were typed as plain objects.

Two blocks documented the wrong thing outright. ThemesPanel lent its prototype to a name misspelled without the second e, so its methods were attached to a namespace that exists nowhere else, and getInitialHeaderImage() carried the return of the method beside it, describing a set of cropper options where its own summary already said it returns a model.

Parameters the code treats as optional are marked as such.

Developed as subset of ​https://github.com/WordPress/wordpress-develop/pull/10743.
Follow-up to r41799, r48650, r63454.

Props westonruter, afercia.
See #39671, #39930, #40831, #64662, #66033.

#19 @westonruter
2 months ago

In 63456:

Customize: Correct the widgets and menus JSDoc.

Three blocks described something the code does not do.

  1. WidgetsPanel lent its prototype to WigetsPanel, so its methods were attached to a name that appears nowhere else in core.
  2. WidgetControl.onChangeExpanded() said its arguments were merged over defaultActiveArguments, while the handler that calls it merges over defaultExpandedArguments; the two carry separate defaults and separate queues, so the wrong one points a reader at the wrong callback.
  3. The field toggle handler in the menu section annotated this as a jQuery object, when it is used with each() and a click binding, both of which set this to the raw element its body then wraps.

The offset parameters described what they accept by writing out the two literals it may hold, which does not convey that the sign selects a direction rather than an amount.

Developed as subset of ​https://github.com/WordPress/wordpress-develop/pull/10743.
Follow-up to r48650, r63454, r63455.

Props westonruter, afercia.
See #39671, #40831, #64662, #66033.

#20 @westonruter
2 months ago

In 63457:

Customize: Correct the JSDoc in the preview frame.

Missing tags and descriptions are added, and the types are corrected, whether they named nothing resolvable (Promise for JQuery.Promise<*>), said too little (Array for string[]), or were narrower than what the code passes.

Both classes in selective-refresh.js lent their prototypes to the wrong name: Partial named wp.customize.SelectiveRefresh.Partial, capitalized unlike the namespace it lives in, and Placement named wp.customize.selectiveRefresh itself, so its methods were attached to the module rather than to the class.

Developed as subset of ​https://github.com/WordPress/wordpress-develop/pull/10743.
Follow-up to r48110, r48650, r63454, r63455, r63456.

Props westonruter, afercia, grapplerulrich, mukesh27.
See #39671, #40831, #64662, #66033.

#21 @westonruter
2 months ago

In 63458:

Customize: Document the header image models and views.

Neither file documented a single method: only the classes themselves carried a docblock. Every method across the two now says what it does, in the third person, along with the arguments of the function wrapping each file.

One behavior is changed: ChoiceListView.render() returned nothing, unlike the sibling views beside it, so it now returns this as the Backbone convention expects. Nothing reads the value, since the view is only ever constructed, never chained, and render is otherwise reached as a listenTo handler, whose return is discarded.

Developed as subset of ​https://github.com/WordPress/wordpress-develop/pull/10743.
Follow-up to r63454, r63455, r63456, r63457.

Props westonruter, afercia, grapplerulrich.
See #39671, #64662, #66033.
Fixes #40831.

Note: See TracTickets for help on using tickets.