Compare commits

..

593 Commits

Author SHA1 Message Date
士子☀️ a706429395 Merge pull request #182 from caorushizi/feat/v2.2.1
feat:   v2.2.1
2024-06-17 23:34:01 +08:00
caorushizi f26c9761c3 feat: v2.2.1 2024-06-17 23:32:58 +08:00
士子☀️ 9424dd4c0e Merge pull request #181 from caorushizi/dev/form
Dev/form
2024-06-17 23:30:55 +08:00
caorushizi 271294a8e7 feat: conversion page 2024-06-17 23:29:27 +08:00
caorushizi 6b2786292f feat: conversion page 2024-06-10 00:17:32 +08:00
caorushizi c36247b5e1 feat: update form 2024-06-09 23:09:55 +08:00
士子☀️ c182afff2c Merge pull request #177 from caorushizi/feat/v2.2.1-beta.0
feat:   release 2.2.1-beta.0
2024-06-09 20:25:36 +08:00
caorushizi 1129d70dca feat: release 2.2.1-beta.0 2024-06-09 20:24:20 +08:00
士子☀️ bde71d13f9 Merge pull request #176 from caorushizi/dev/download-items
fix: 🐛  download items
2024-06-08 18:37:57 +08:00
caorushizi 67b513d380 fix: 🐛 merge master 2024-06-08 18:36:51 +08:00
caorushizi 8d8d1ee238 fix: 🐛 download item 2024-06-08 18:32:23 +08:00
caorushizi 7c10715607 Merge branch 'master' of https://github.com/caorushizi/m3u8-downloader 2024-06-08 18:27:50 +08:00
caorushizi a939f06fcd Revert "fix: 🐛 下载嗅探到的最后一个文件"
This reverts commit 2a42a02f3d.
2024-06-08 18:24:38 +08:00
士子☀️ c50625b0c8 Merge pull request #170 from caorushizi/feat/addForm
fix: 🐛  下载嗅探到的最后一个文件
2024-06-08 18:20:48 +08:00
caorushizi bfa2d88935 fix: 🐛 download items 2024-06-08 18:02:38 +08:00
士子☀️ b04ea61e83 Merge pull request #170 from caorushizi/feat/addForm
fix: 🐛  下载嗅探到的最后一个文件
2024-05-31 12:10:06 +08:00
caorushizi 2a42a02f3d fix: 🐛 下载嗅探到的最后一个文件 2024-05-31 12:08:25 +08:00
士子☀️ 1e80278a1d Merge pull request #167 from caorushizi/dependabot/npm_and_yarn/cz-git-1.9.2
chore(deps-dev): bump cz-git from 1.9.1 to 1.9.2
2024-05-27 21:20:01 +08:00
士子☀️ f38d9156c5 Merge pull request #169 from caorushizi/feat/addForm
docs: 📝  release
2024-05-27 21:18:58 +08:00
caorushizi 0f32864079 docs: 📝 release 2024-05-27 21:16:59 +08:00
士子☀️ f8fbecebc9 Merge pull request #168 from caorushizi/feat/addForm
fix: 🐛  build scripts
2024-05-27 20:52:39 +08:00
caorushizi 40c5656080 fix: 🐛 build scripts 2024-05-27 20:47:07 +08:00
dependabot[bot] ddf36a7091 chore(deps-dev): bump cz-git from 1.9.1 to 1.9.2
Bumps [cz-git](https://github.com/Zhengqbbb/cz-git/tree/HEAD/packages/cz-git) from 1.9.1 to 1.9.2.
- [Release notes](https://github.com/Zhengqbbb/cz-git/releases)
- [Changelog](https://github.com/Zhengqbbb/cz-git/blob/main/packages/cz-git/CHANGELOG.md)
- [Commits](https://github.com/Zhengqbbb/cz-git/commits/v1.9.2/packages/cz-git)

---
updated-dependencies:
- dependency-name: cz-git
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-27 04:15:52 +00:00
士子☀️ 258c67554d Merge pull request #166 from caorushizi/feat/addForm
feat:   完善表单项
2024-05-27 04:40:01 +08:00
caorushizi 007ff31200 feat: 完善表单项 2024-05-27 04:37:50 +08:00
士子☀️ ff75e3d94b Merge pull request #165 from caorushizi/feat/addForm
feat:   修改创建修改表单
2024-05-27 01:52:01 +08:00
caorushizi aaa18e0048 feat: 修改创建修改表单 2024-05-27 01:51:07 +08:00
士子☀️ 5c6f89a067 Merge pull request #164 from caorushizi/feat/dependencies
refactor: 📦️  update eslint
2024-05-26 20:00:37 +08:00
caorushizi c4efc4c293 refactor: 📦️ update eslint 2024-05-26 19:40:51 +08:00
士子☀️ 2d955257e6 Merge pull request #163 from caorushizi/feat/dependencies
fix: 🐛  update dependencies
2024-05-26 18:57:29 +08:00
caorushizi 3cf84a2992 fix: 🐛 update dependencies 2024-05-26 18:56:02 +08:00
士子☀️ 94a795fe69 Merge pull request #162 from caorushizi/feat/dependencies
feat:   update dependencies
2024-05-26 18:10:18 +08:00
caorushizi cc10ae8b2e feat: update dependencies 2024-05-26 17:58:40 +08:00
caorushizi 63ed7cdaca fix: 🐛 直播视频不展示下载进度 2024-05-26 17:21:58 +08:00
caorushizi 064919e0a2 fix: 🐛 build variable 2024-05-26 17:14:27 +08:00
士子☀️ 31b2652c9b Merge pull request #161 from caorushizi/fix/scripts
fix: 🐛  build script
2024-05-26 16:38:58 +08:00
caorushizi d080d709d1 fix: 🐛 build script 2024-05-26 16:37:59 +08:00
士子☀️ 0c301c79f2 Merge pull request #160 from caorushizi/fix/scripts
fix: 🐛  build
2024-05-26 15:59:19 +08:00
caorushizi a1dbb6234f fix: 🐛 build 2024-05-26 15:56:40 +08:00
士子☀️ 30248194af Merge pull request #159 from caorushizi/fix/scripts
fix: 🐛  pnpm actions
2024-05-26 15:32:03 +08:00
caorushizi 8f54ebeb3a fix: 🐛 pnpm actions 2024-05-26 15:30:34 +08:00
士子☀️ d8ef0b9eee Merge pull request #158 from caorushizi/fix/scripts
fix: 🐛  npm rebuild
2024-05-26 15:10:52 +08:00
caorushizi 6a3bfd071a fix: 🐛 npm rebuild 2024-05-26 15:05:58 +08:00
士子☀️ 849df04c05 Merge pull request #157 from caorushizi/fix/scripts
fix: 🐛  打包分片
2024-05-26 14:29:25 +08:00
caorushizi a40ae5ef82 fix: 🐛 打包分片 2024-05-26 14:28:18 +08:00
士子☀️ 00c535665f Merge pull request #156 from caorushizi/fix/scripts
fix: 🐛  scripts name
2024-05-26 02:29:51 +08:00
caorushizi 8b4a4d8ff8 fix: 🐛 scripts name 2024-05-26 02:29:05 +08:00
士子☀️ f9fecd541c Merge pull request #155 from caorushizi/fix/adblocker
Fix/adblocker
2024-05-26 02:07:25 +08:00
caorushizi 93b1028498 fix: 🐛 some bug
'
2024-05-26 02:05:53 +08:00
caorushizi a0a3dba188 refactor: 📦️ 代码分割 2024-05-25 23:37:23 +08:00
caorushizi 92ded00495 feat: 构建流程优化 2024-05-25 22:00:31 +08:00
caorushizi bcbe258f60 fix: 🐛 修复打包完成后没有权限执行的问题 2024-05-25 15:23:26 +08:00
caorushizi 660f9c7c9b feat: support linux 2024-05-25 03:02:49 +08:00
caorushizi 8c5ef29894 feat: support linux 2024-05-25 02:59:48 +08:00
caorushizi 612fc4c533 fix: 🐛 修复开启广告过滤时无法沉浸式嗅探 2024-05-24 21:27:36 +08:00
士子☀️ 635377d227 Merge pull request #153 from caorushizi/feat/webcontentsView
Feat/webcontents view
2024-05-22 21:11:38 +08:00
caorushizi dc86ab8f4c feat: release 2.2.0 2024-05-22 21:09:25 +08:00
caorushizi 36b63ad916 fix: 🐛 bilibili 2024-05-22 20:56:18 +08:00
士子☀️ e1b378811d Merge pull request #152 from caorushizi/feat/webcontentsView
fix: 🐛  .env
2024-05-22 19:30:00 +08:00
caorushizi 37fb9bba75 fix: 🐛 .env 2024-05-22 19:28:19 +08:00
士子☀️ 848253c678 Merge pull request #151 from caorushizi/feat/webcontentsView
Feat/webcontents view
2024-05-22 18:19:33 +08:00
caorushizi b64e779ed1 feat: release 2.2.0-beta.4 2024-05-22 18:18:07 +08:00
caorushizi 046a62cde3 fix: 🐛 load url 2024-05-22 18:16:38 +08:00
caorushizi 1a9e6efb90 feat: use webcontents view and capture page 2024-05-22 15:15:39 +08:00
士子☀️ fd422c15ba Merge pull request #150 from caorushizi/fix/addForm
fix: 🐛  fix run release scripts
2024-05-22 04:04:18 +08:00
caorushizi c338f76f8d fix: 🐛 fix run release scripts 2024-05-22 04:03:32 +08:00
士子☀️ 4285b3f4f7 Merge pull request #149 from caorushizi/fix/addForm
feat:   支持直播视频下载
2024-05-22 03:51:41 +08:00
caorushizi d0109869a6 feat: 支持直播视频下载 2024-05-22 03:50:38 +08:00
士子☀️ d29ad44c54 Merge pull request #148 from caorushizi/fix/addForm
fix: 🐛  float button position
2024-05-22 01:02:50 +08:00
caorushizi be61b07fea fix: 🐛 float button position 2024-05-22 01:01:38 +08:00
士子☀️ e5e171fb6f Merge pull request #147 from caorushizi/fix/addForm
fix: 🐛  release 2.2.0-beta.3
2024-05-22 00:33:59 +08:00
caorushizi 805d97c3ca fix: 🐛 release 2.2.0-beta.3 2024-05-22 00:32:35 +08:00
士子☀️ 040222f259 Merge pull request #146 from caorushizi/fix/addForm
fix: 🐛  fix browser window event
2024-05-21 22:52:39 +08:00
caorushizi 09ed55eba4 fix: 🐛 fix browser window event 2024-05-21 22:51:40 +08:00
士子☀️ a6d4f8cf98 Merge pull request #145 from caorushizi/fix/addForm
fix: 🐛  release 2.2.0-beta.2
2024-05-21 02:38:48 +08:00
caorushizi d19b2394e8 fix: 🐛 release 2.2.0-beta.2 2024-05-21 02:37:40 +08:00
士子☀️ 036a99d84d Merge pull request #143 from caorushizi/fix/video
Fix/video
2024-05-14 12:22:24 +08:00
caorushizi b022335af7 feat: release 2.2.0-beta.1 2024-05-14 12:21:21 +08:00
caorushizi a66c20c9d5 feat: 修复页面中下载嗅探问题 2024-05-14 12:19:47 +08:00
caorushizi f9fc135647 fix: 🐛 修复 dom-ready 执行的顺序 2024-05-13 09:49:34 +08:00
士子☀️ fbbee9c114 Merge pull request #142 from caorushizi/fix/docs
Fix/docs
2024-05-13 09:42:35 +08:00
caorushizi a65fbcbaf8 fix: 🐛 修复插件展现运行的时机 2024-05-13 09:41:06 +08:00
士子☀️ 39b68b71d4 refactor: 📦️ modify mediago protocol, upgrade adblocker 2024-05-13 01:51:13 +08:00
士子☀️ 4d12a0a937 Merge pull request #140 from caorushizi/fix/docs
ci: 🎡  github actions
2024-05-02 19:01:16 +08:00
士子☀️ 960973302e ci: 🎡 github actions 2024-05-02 18:58:01 +08:00
士子☀️ 1a68b00bdd Merge pull request #139 from caorushizi/fix/docs
ci: 🎡  modify github actions
2024-05-02 18:32:22 +08:00
士子☀️ dba73fc473 ci: 🎡 modify github actions 2024-05-02 18:30:24 +08:00
士子☀️ 211f7314ce Merge pull request #138 from caorushizi/fix/docs
docs: 📝  remove reaction
2024-05-02 18:18:19 +08:00
士子☀️ 64d719a63a docs: 📝 remove reaction 2024-05-02 18:17:19 +08:00
士子☀️ 0304e6b569 Merge pull request #135 from caorushizi/feat/mediago
Feat/mediago
2024-04-05 23:46:23 +08:00
士子☀️ 190447a0bd feat: release v2.2.0-beta.0 2024-04-05 23:44:13 +08:00
士子☀️ 497d1265f0 chore: 🔨 add lint-staged 2024-04-05 23:42:35 +08:00
士子☀️ 6d459e0692 feat: rename mediago 2024-04-05 23:09:30 +08:00
士子☀️ 45cde40cea chore: 🔨 fix pre-commit 2024-04-05 22:36:13 +08:00
士子☀️ e9deb4c7f7 chore: 🔨 use tsx instead of ts-node 2024-04-05 22:02:59 +08:00
caorushizi 1abfc763dc docs: 📝 update waline client 2024-03-26 14:31:00 +08:00
caorushizi b84ddcc88d docs: 📝 update vitepress 2024-03-26 13:02:22 +08:00
士子☀️ 33f7951901 refactor: 📦️ remove submodule 2024-03-20 23:23:09 +08:00
士子☀️ d3354f9109 Merge pull request #125 from caorushizi/feat/player
refactor: 📦️  remove tsno
2024-03-20 19:32:06 +08:00
caorushizi d252816cc3 refactor: 📦️ remove tsno 2024-03-20 19:29:27 +08:00
士子☀️ 6e31904e95 Merge pull request #124 from caorushizi/feat/player
refactor: 📦️  remove video player
2024-03-20 16:59:12 +08:00
caorushizi 2825d1f4c7 refactor: 📦️ remove video player 2024-03-20 16:50:58 +08:00
士子☀️ fcb10c6137 Merge pull request #118 from caorushizi/feat/player
fix: 🐛  catch video
2024-03-17 18:04:27 +08:00
士子☀️ f564739578 fix: 🐛 catch video 2024-03-17 18:03:24 +08:00
士子☀️ 40faf4b383 Merge pull request #117 from caorushizi/feat/player
fix: 🐛  fix mobile video size
2024-03-17 17:46:01 +08:00
士子☀️ affff353bd fix: 🐛 fix mobile video size 2024-03-17 17:45:04 +08:00
士子☀️ f410fabff7 Merge pull request #116 from caorushizi/feat/player
fix: 🐛  fix video container
2024-03-17 17:22:13 +08:00
士子☀️ 7d4b201b6e fix: 🐛 fix video container 2024-03-17 17:21:10 +08:00
士子☀️ a9ac0aa16b Merge pull request #115 from caorushizi/2.1.0-beta.1
feat:   v2.1.0-beta.1
2024-03-17 16:09:16 +08:00
士子☀️ 5419970080 feat: v2.1.0-beta.1 2024-03-17 16:08:34 +08:00
士子☀️ 506a573180 Merge pull request #114 from caorushizi/feat/dialog
fix: 🐛 按照获取时间正序排列
2024-03-17 02:03:43 +08:00
士子☀️ 17b2450b43 feat: use download dialog 2024-03-17 02:01:32 +08:00
士子☀️ 2942e65a54 fix: 🐛 按照获取时间正序排列 2024-03-17 00:17:47 +08:00
士子☀️ 913a7bd9e5 Merge pull request #113 from caorushizi/feat/dialog
feat:   show download dialog
2024-03-17 00:12:31 +08:00
士子☀️ c5f2edd9de feat: show download dialog 2024-03-17 00:09:34 +08:00
士子☀️ 24d511e6b6 Merge pull request #112 from caorushizi/feat/plugins
feat:  bilibili plguins
2024-03-10 19:23:15 +08:00
士子☀️ 47f3336f9a feat: 2.1.0-beta.0 2024-03-10 19:22:30 +08:00
士子☀️ e0e6e5dbed feat: bilibili plguins 2024-03-10 19:19:27 +08:00
士子☀️ aa7f3e7bf7 Merge pull request #111 from caorushizi/feat/terminal
feat:  use terminal
2024-03-10 16:43:04 +08:00
caorushizi 065a6c45f7 feat: terminal 2024-03-10 16:40:25 +08:00
士子☀️ b13174dda1 feat: use terminal 2024-03-10 16:19:16 +08:00
士子☀️ 9e6a931a41 Merge pull request #109 from caorushizi/feat/terminal
feat:  terminal
2024-03-09 08:57:23 +08:00
士子☀️ cdabdfd2f8 feat: layout style 2024-03-09 01:06:49 +08:00
士子☀️ b4cdbd7547 feat: show terminal 2024-03-09 00:05:15 +08:00
caorushizi 75fe603919 feat: terminal 2024-03-08 21:35:05 +08:00
士子☀️ 16ef9ae642 Merge pull request #104 from caorushizi/feat/actions
feat:   add vscode debug config
2024-02-27 23:13:35 +08:00
士子☀️ 7db3162748 feat: add vscode debug config 2024-02-27 23:11:37 +08:00
士子☀️ 3f0e6d9856 Merge pull request #102 from caorushizi/feat/actions
feat:   update actions version
2024-02-27 01:04:51 +08:00
士子☀️ d87fc4a400 feat: update actions version 2024-02-27 01:03:26 +08:00
士子☀️ ec6241b79e Merge pull request #101 from caorushizi/fix/node-pty
fix: 🐛  cannot find module 'node-pty'
2024-02-27 00:50:42 +08:00
士子☀️ 9b37398e9f fix: 🐛 cannot find module 'node-pty' 2024-02-27 00:49:05 +08:00
士子☀️ 3fca8694ee fix: 🐛 filename 2024-02-25 23:39:24 +08:00
士子☀️ 78efffa29b Merge pull request #95 from caorushizi/dev/terminal
Dev/terminal
2024-02-25 22:40:02 +08:00
士子☀️ 737ecbdadd fix: 🐛 build player 2024-02-25 22:37:34 +08:00
士子☀️ fa6ce22ea7 Merge pull request #94 from caorushizi/dev/terminal
Dev/terminal
2024-02-25 22:22:36 +08:00
士子☀️ 315c55c844 feat: terminal 2024-02-25 18:28:37 +08:00
士子☀️ d9ba60e1a5 feat: terminal 2024-02-25 17:31:58 +08:00
士子☀️ 7503322d01 feat: terminal 2024-02-25 13:36:14 +08:00
士子☀️ 2e5f2dc687 Merge pull request #91 from caorushizi/dev/plugins
style: 💄 eslint
2024-02-24 23:28:27 +08:00
士子☀️ e4afd27908 fix: 🐛 add tsconfig 2024-02-24 23:19:09 +08:00
士子☀️ 6fe5d5523e feat: remove player page. use node-pty 2024-02-24 22:50:03 +08:00
士子☀️ 7335946ec2 refactor: 📦️ refactoring the project directory structure 2024-02-23 19:32:06 +08:00
士子☀️ eb4576de9b feat: 使用 node 伪终端 2024-02-21 22:17:02 +08:00
士子☀️ 1e41a9ee99 feat: node 伪终端获取详细日志 2024-02-21 21:44:12 +08:00
士子☀️ dd5226ab47 refactor: 📦️ downloader 2024-02-12 09:56:07 +08:00
士子☀️ 989e5535eb feat: new player 2024-02-12 01:55:11 +08:00
士子☀️ 65efeed692 style: 💄 eslint 2024-02-11 23:18:45 +08:00
士子☀️ fcddb2d382 Merge pull request #88 from caorushizi/dev/plugins
fix: 🐛  types
2024-02-11 18:13:57 +08:00
士子☀️ bbc892ec81 fix: 🐛 types 2024-02-11 18:08:51 +08:00
士子☀️ ca1c2821a7 Merge pull request #87 from caorushizi/dev/plugins
fix: 🐛  types
2024-02-11 18:02:50 +08:00
士子☀️ c8d4f763fd fix: 🐛 types 2024-02-11 18:00:08 +08:00
士子☀️ a3d587af44 Merge pull request #85 from caorushizi/dev/plugins
feat:  new plugin
2024-02-11 17:00:28 +08:00
士子☀️ ce2146cc89 feat: add plugin 2024-02-11 16:59:02 +08:00
士子☀️ 8455f17517 style: 💄 somthing 2024-02-11 10:45:32 +08:00
士子☀️ c075bdd4f9 feat: new plugin 2024-02-09 22:18:35 +08:00
士子☀️ 65d88d0896 Merge pull request #82 from caorushizi/dev/i18n
feat: display language
2024-02-09 17:01:55 +08:00
士子☀️ 1c62640301 style: 💄 add lint-staged 2024-02-09 17:00:48 +08:00
士子☀️ dd6684c550 feat: build plugin
build plugin with lit.
2024-02-09 15:54:22 +08:00
士子☀️ 2e1a753583 test 2024-02-09 15:41:34 +08:00
士子☀️ cbf6e4ecfb test 2024-02-09 15:26:20 +08:00
士子☀️ 5af471fe1a plugin 2024-02-09 13:23:52 +08:00
士子☀️ 0deb205faa plugin 2024-02-09 00:11:40 +08:00
士子☀️ 73eaf0ecaa plugin 2024-02-09 00:10:32 +08:00
士子☀️ 4791defbdd sniffing helper 2024-02-08 18:23:49 +08:00
士子☀️ 926249184b i18n 2024-02-08 15:12:08 +08:00
士子☀️ 659b2755ef feat: display language 2024-02-04 20:15:43 +08:00
士子☀️ e9d36edaa4 v2.0.3-beta.3 2024-01-22 23:01:56 +08:00
士子☀️ fdcdbf27eb dev tools 2024-01-22 22:25:29 +08:00
士子☀️ 2f5cc2eb80 Merge branch 'master' of https://github.com/caorushizi/m3u8-downloader 2024-01-21 19:11:42 +08:00
士子☀️ c087fa4956 webview 2024-01-21 19:10:11 +08:00
士子☀️ ed33ec6532 actions 2024-01-21 17:54:37 +08:00
士子☀️ 2d96c2730c .npmrc 2024-01-21 17:41:59 +08:00
士子☀️ 5bcec10be3 docs 2024-01-21 17:18:02 +08:00
士子☀️ 207bd15b14 .npmrc 2024-01-21 17:07:41 +08:00
士子☀️ 00f0bfc84b os version 2024-01-21 17:06:59 +08:00
士子☀️ 7bc3f83c88 update electron. 2024-01-21 16:56:59 +08:00
士子☀️ 1af2803c22 eslint 2024-01-21 01:20:02 +08:00
士子☀️ fd6a81abfd package version 2024-01-21 00:01:09 +08:00
士子☀️ a383093914 Merge pull request #71 from caorushizi/dependabot/npm_and_yarn/typescript-eslint/parser-6.19.0
build(deps-dev): bump @typescript-eslint/parser from 5.60.0 to 6.19.0
2024-01-20 23:29:33 +08:00
士子☀️ 13656429af Merge pull request #70 from caorushizi/dependabot/npm_and_yarn/better-sqlite3-9.3.0
build(deps): bump better-sqlite3 from 8.7.0 to 9.3.0
2024-01-20 23:29:11 +08:00
dependabot[bot] bc34881b38 build(deps-dev): bump @typescript-eslint/parser from 5.60.0 to 6.19.0
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 5.60.0 to 6.19.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.19.0/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-20 15:11:08 +00:00
dependabot[bot] e3b11cb087 build(deps): bump better-sqlite3 from 8.7.0 to 9.3.0
Bumps [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) from 8.7.0 to 9.3.0.
- [Release notes](https://github.com/WiseLibs/better-sqlite3/releases)
- [Commits](https://github.com/WiseLibs/better-sqlite3/compare/v8.7.0...v9.3.0)

---
updated-dependencies:
- dependency-name: better-sqlite3
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-20 15:11:00 +00:00
士子☀️ 8df78ca377 Merge pull request #61 from caorushizi/dependabot/npm_and_yarn/typescript-5.3.3
build(deps-dev): bump typescript from 5.1.6 to 5.3.3
2024-01-20 23:08:49 +08:00
士子☀️ f12919c6bc Update README.md 2024-01-16 23:02:29 +08:00
士子☀️ 00df324ae7 Merge pull request #66 from caorushizi/readme
readme
2024-01-15 22:25:23 +08:00
士子☀️ f14f9ffc1b readme 2024-01-15 22:23:40 +08:00
dependabot[bot] a388b725bc build(deps-dev): bump typescript from 5.1.6 to 5.3.3
Bumps [typescript](https://github.com/Microsoft/TypeScript) from 5.1.6 to 5.3.3.
- [Release notes](https://github.com/Microsoft/TypeScript/releases)
- [Commits](https://github.com/Microsoft/TypeScript/compare/v5.1.6...v5.3.3)

---
updated-dependencies:
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-14 07:37:58 +00:00
caorushizi e64eaeefef macos 2024-01-14 15:35:15 +08:00
士子☀️ 6830d69b62 build script. 2024-01-14 12:09:08 +08:00
士子☀️ 8f609a8e93 checkout 2024-01-14 10:42:54 +08:00
士子☀️ 99c23f47c5 setup go 2024-01-14 10:36:14 +08:00
士子☀️ 95f9e20f39 go build 2024-01-14 01:34:08 +08:00
士子☀️ df1e664bc9 Merge pull request #60 from caorushizi/dev0114
add plugin
2024-01-14 01:25:05 +08:00
士子☀️ fec30a6453 add plugin 2024-01-14 01:24:24 +08:00
士子☀️ a048211486 add plugin 2024-01-14 01:14:02 +08:00
士子☀️ 465e9b2988 add plugin 2024-01-13 23:19:19 +08:00
士子☀️ af1ff19cb2 add web plugin 2024-01-13 20:28:58 +08:00
士子☀️ eae470f2ec video server 2024-01-13 12:24:52 +08:00
士子☀️ 1933799e32 feat: video list. 2024-01-13 01:03:46 +08:00
士子☀️ c7977bf7b4 Merge pull request #55 from caorushizi/dependabot/npm_and_yarn/electron-25.8.4
build(deps-dev): bump electron from 25.2.0 to 25.8.4
2023-12-29 16:40:43 +08:00
士子☀️ ce8407ce46 Merge pull request #58 from caorushizi/dependabot/npm_and_yarn/axios-1.6.0
build(deps): bump axios from 1.4.0 to 1.6.0
2023-12-29 16:40:01 +08:00
dependabot[bot] 5d313df190 build(deps): bump axios from 1.4.0 to 1.6.0
Bumps [axios](https://github.com/axios/axios) from 1.4.0 to 1.6.0.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.4.0...v1.6.0)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-11 13:41:05 +00:00
dependabot[bot] c560a09904 build(deps-dev): bump electron from 25.2.0 to 25.8.4
Bumps [electron](https://github.com/electron/electron) from 25.2.0 to 25.8.4.
- [Release notes](https://github.com/electron/electron/releases)
- [Changelog](https://github.com/electron/electron/blob/main/docs/breaking-changes.md)
- [Commits](https://github.com/electron/electron/compare/v25.2.0...v25.8.4)

---
updated-dependencies:
- dependency-name: electron
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-05 17:37:26 +00:00
士子☀️ df66a92989 Merge pull request #46 from caorushizi/feat/v2.1.0
m3u8
2023-08-22 14:49:01 +08:00
士子☀️ 52c9611e49 m3u8 2023-08-07 23:54:19 +08:00
士子☀️ 4018112a1d 优化二进制调用逻辑 2023-08-02 21:26:46 +08:00
士子☀️ 633a257e65 优化表单 2023-08-01 23:49:22 +08:00
caorushizi 0666d41226 工程优化 2023-07-29 14:14:37 +08:00
士子☀️ c2cfe55e24 Merge pull request #43 from caorushizi/dev/2.1.0 2023-07-29 13:43:37 +08:00
士子☀️ cb7fbddd7a 工程优化 2023-07-29 13:41:16 +08:00
士子☀️ 135d9fed1b 工程优化 2023-07-29 10:39:27 +08:00
士子☀️ 267aedc594 工程优化 2023-07-29 09:24:11 +08:00
士子☀️ 325d0da930 工程优化 2023-07-29 00:28:01 +08:00
士子☀️ 615bc74d15 Merge pull request #42 from caorushizi/dev/2.1.0 2023-07-27 17:59:32 +08:00
士子☀️ 1ca6935d36 download form. 2023-07-24 23:49:10 +08:00
士子☀️ 3bfb7139d3 download form. 2023-07-22 12:56:56 +08:00
士子☀️ 14d44765e5 form name 2023-07-22 00:03:58 +08:00
士子☀️ 807dd2d920 request 2023-07-21 23:39:02 +08:00
士子☀️ c9a0a7f7c2 request 2023-07-21 23:31:07 +08:00
士子☀️ a3eea6d501 v2.1.0 2023-07-20 23:25:33 +08:00
士子☀️ 4ce7dcac1b Merge pull request #38 from caorushizi/dev 2023-07-18 23:51:35 +08:00
士子☀️ 096762f24c some thing 2023-07-18 23:49:03 +08:00
士子☀️ baf358d223 something 2023-07-18 23:44:22 +08:00
士子☀️ e72973346b add: get web request. 2023-07-12 00:30:15 +08:00
士子☀️ 41258ecee8 add: get web request response. 2023-07-11 22:48:14 +08:00
士子☀️ b6a5be152a Merge pull request #37 from caorushizi/dev0709 2023-07-09 15:39:55 +08:00
士子☀️ d5d45c4935 fix: download use proxy. 2023-07-09 15:38:48 +08:00
士子☀️ 81eb4ecf09 Merge pull request #36 from caorushizi/dev0709 2023-07-09 15:09:23 +08:00
士子☀️ 5a4cc8c449 bin dir 2023-07-09 15:07:57 +08:00
士子☀️ e7ab664310 release: v2.0.2 2023-07-09 14:54:21 +08:00
士子☀️ 3cb2fa27b9 release: v2.0.2 2023-07-09 14:18:41 +08:00
士子☀️ e29e41aa4c release: v2.0.2 2023-07-09 14:01:15 +08:00
士子☀️ cc62613640 Merge pull request #35 from caorushizi/release/v2.0.2 2023-07-09 13:53:19 +08:00
士子☀️ 2720bcc685 release: v2.0.2 2023-07-09 13:52:40 +08:00
士子☀️ c8ac4182fc Merge pull request #34 from caorushizi/release/v2.0.2 2023-07-09 13:25:36 +08:00
士子☀️ 55b70d3e6d release: v2.0.2 2023-07-09 13:24:06 +08:00
士子☀️ a19765b0d3 fix: browser loading status. 2023-07-08 23:05:13 +08:00
士子☀️ 5c7b65385a remove postinstall 2023-07-08 16:34:34 +08:00
caorushizi b6b84269a3 fix: mac app. 2023-07-08 15:55:12 +08:00
士子☀️ e44cb249d0 Merge pull request #30 from caorushizi/feat/v2.0.2 2023-07-08 12:11:51 +08:00
士子☀️ 8bea071865 release size. 2023-07-08 12:00:50 +08:00
caorushizi a782652fca fix: tray icon. 2023-07-06 22:49:11 +08:00
caorushizi 3a02803d3c fix: mac download. 2023-07-06 22:16:28 +08:00
士子☀️ 263a08ab4c Merge pull request #29 from caorushizi/feat/v2.0.2 2023-07-06 00:32:55 +08:00
士子☀️ ecdbd985ce feat: tray context menu. 2023-07-06 00:32:05 +08:00
士子☀️ dd403564cc docs: addition function. 2023-07-06 00:15:57 +08:00
士子☀️ 69d741b39a Merge pull request #28 from caorushizi/dev 2023-07-05 23:53:59 +08:00
士子☀️ 4c9c2e2d68 add: tray icon. 2023-07-05 23:52:38 +08:00
士子☀️ 8660701340 download list. 2023-07-05 22:48:41 +08:00
士子☀️ 341c5570af support live mode. 2023-07-05 01:13:29 +08:00
士子☀️ ee12753818 Update README.md 2023-07-04 12:56:52 +08:00
士子☀️ 055638278c feat: something 2023-07-04 07:52:43 +08:00
士子☀️ bf06ff6482 docs: dark mode. 2023-07-02 15:32:34 +08:00
士子☀️ 459a5bc5b7 docs: comments dark theme. 2023-07-02 14:08:04 +08:00
士子☀️ a93f18037c release: v2.0.1 2023-07-02 13:50:22 +08:00
士子☀️ 67b5218002 release: v2.0.1 2023-07-02 13:38:46 +08:00
士子☀️ d3c745dda4 docs: update. 2023-07-02 13:19:31 +08:00
士子☀️ e694818f8f docs: support dark mode. 2023-07-02 13:10:30 +08:00
士子☀️ 729d7645e1 docs 2023-07-02 12:30:58 +08:00
士子☀️ 795e21df9c docs: content done. 2023-07-02 01:22:14 +08:00
士子☀️ bdc15e6c50 feat: max runner. 2023-07-01 23:02:42 +08:00
士子☀️ c3398ec572 baidu 2023-07-01 22:08:48 +08:00
士子☀️ 6b38b348fc actions 2023-07-01 21:37:43 +08:00
士子☀️ d650529842 actions 2023-07-01 21:32:21 +08:00
士子☀️ 2094408f52 actions 2023-07-01 21:28:26 +08:00
士子☀️ 89cb8b3a3a actions 2023-07-01 21:24:36 +08:00
士子☀️ 7a2d546972 actions. 2023-07-01 21:21:57 +08:00
士子☀️ 69e801ba2b Merge pull request #25 from caorushizi/dev
Dev
2023-07-01 21:16:54 +08:00
士子☀️ 14edc27ed1 add: docs and deploy. 2023-07-01 21:14:45 +08:00
士子☀️ 6f7fa7f067 add: docs 2023-07-01 20:15:40 +08:00
caorushizi a5a1c02e10 update: mac downloader 2023-07-01 19:01:51 +08:00
士子☀️ ce08cbce4b feat: some feature. 2023-07-01 18:12:35 +08:00
士子☀️ e03a5d38bb video header & web extension 2023-07-01 14:40:49 +08:00
士子☀️ 720db5a476 video headers & params format 2023-07-01 01:27:04 +08:00
士子☀️ e97783b08e Merge branch 'dev' of https://github.com/caorushizi/m3u8-downloader into dev 2023-06-30 00:45:34 +08:00
士子☀️ 12566f8668 add webview preload script. 2023-06-30 00:44:47 +08:00
caorushizi d686819417 npmrc 2023-06-29 19:26:47 +08:00
士子☀️ ea7b4a77af feat: prettier & web extension. 2023-06-28 23:53:46 +08:00
士子☀️ 6427a06879 test: do somthing. 2023-06-27 23:54:43 +08:00
士子☀️ f2f7a50e95 refactor: window service 2023-06-27 22:22:42 +08:00
caorushizi fbc57ebfca fix: webContents is null. 2023-06-27 11:46:55 +08:00
士子☀️ 26a5681dab feat: web extension. 2023-06-26 23:34:54 +08:00
士子☀️ 4640ff51e8 feat: add web extension. 2023-06-26 00:59:36 +08:00
士子☀️ b3b58680e0 release: v2.0.0 2023-06-24 15:29:27 +08:00
士子☀️ d1b75df87d Merge pull request #22 from caorushizi/development
fix: mac active.
2023-06-23 22:10:35 +08:00
caorushizi 4b4e1b9f54 fix: mac active. 2023-06-23 22:05:47 +08:00
士子☀️ 8ebb550270 Merge pull request #21 from caorushizi/development
release: v2.0.0-beta.7
2023-06-23 21:52:50 +08:00
士子☀️ 6b93954246 release: v2.0.0-beta.7 2023-06-23 21:48:46 +08:00
士子☀️ 550d7ebd4b release: v2.0.0-beta.7 2023-06-23 21:18:29 +08:00
caorushizi 3f331e5d3d feat: package.json 2023-06-23 21:12:54 +08:00
士子☀️ 020f921af8 release v2.0.0-beta.6 2023-06-23 10:44:58 +08:00
士子☀️ efa72ce12b release: v2.0.0-beta.6 2023-06-23 09:39:41 +08:00
士子☀️ 38ead633a5 release: v2.0.0-beta.6 2023-06-23 09:29:50 +08:00
士子☀️ 3eb1d0ae99 fix: get video source & dark mode 2023-06-22 21:39:43 +08:00
士子☀️ 7bed4ed335 update dependencies version. 2023-06-22 16:23:48 +08:00
士子☀️ b357d41f23 add: dark mode. 2023-06-22 15:58:48 +08:00
士子☀️ 3834603b0a update dependencies version. 2023-06-22 12:40:33 +08:00
士子☀️ f38ba108a3 add adblocker 2023-06-22 11:33:37 +08:00
士子☀️ 7ceda3d73f readme 2023-06-21 23:53:03 +08:00
士子☀️ aee57b6f98 feat: set dev tool load. 2023-06-20 23:28:47 +08:00
士子☀️ f9d49bd55f feat: restore browser state. 2023-06-20 22:49:07 +08:00
士子☀️ 3bb082473a Merge branch 'master' of https://github.com/caorushizi/m3u8-downloader 2023-06-20 22:01:23 +08:00
士子☀️ 31b6726fe5 fix: direct download. 2023-06-20 22:01:05 +08:00
士子☀️ 348b41b0dd Update README.md 2023-06-19 23:11:36 +08:00
士子☀️ d4bbfa0516 release: beta5 2023-06-18 18:38:38 +08:00
士子☀️ b2af9b3d25 release: 2.0.0-beta.5 2023-06-18 18:25:26 +08:00
caorushizi ded93a4f0b test 2023-06-18 18:04:59 +08:00
caorushizi d43f57565b feat: add video player. 2023-06-18 17:59:39 +08:00
caorushizi 34cf661fb2 feat: add video player 2023-06-18 17:05:05 +08:00
士子☀️ 91cfb883b6 feat: add video player. 2023-06-18 15:06:15 +08:00
士子☀️ 1cb7deb376 player 2023-06-17 21:24:54 +08:00
caorushizi 70933c63bb pack 2023-06-17 19:29:25 +08:00
caorushizi 5723b9edd0 player 2023-06-17 14:15:50 +08:00
士子☀️ 65f37a9c66 main 2023-06-17 13:08:45 +08:00
士子☀️ 57516793ab main 2023-06-17 02:42:41 +08:00
士子☀️ afecc5ac12 rename url 2023-06-17 01:16:53 +08:00
士子☀️ 3331564155 Merge pull request #20 from caorushizi/dev-server
feat: add video server
2023-06-17 00:13:54 +08:00
士子☀️ 19ce7b9906 add 2023-06-17 00:12:54 +08:00
士子☀️ 40f39340f0 add mobile. 2023-06-16 23:20:20 +08:00
士子☀️ f085bcacf7 add mobile 2023-06-11 02:29:53 +08:00
士子☀️ dbd4e73b6e feat: add mobile player. 2023-06-10 17:23:31 +08:00
士子☀️ b35e6b3315 feat: add video player. 2023-06-10 16:56:02 +08:00
士子☀️ 3c603a67dd feat: add video player 2023-06-10 11:33:35 +08:00
士子☀️ 8ff5abf5d8 feat: add video server 2023-06-08 01:22:59 +08:00
士子☀️ 0fdbd39393 fix: windows address url. 2023-06-07 01:02:22 +08:00
caorushizi df93770128 test 2023-06-04 00:40:39 +08:00
caorushizi b61a935068 test 2023-06-03 23:07:42 +08:00
士子☀️ 95e96b1057 优化素材提取页交互,优化打点逻辑,优化页面切换时的问题 2023-05-28 19:18:36 +08:00
士子☀️ 3dd325a280 Update README.md 2023-05-06 09:54:08 +08:00
士子☀️ bbe922df74 Update README.md 2023-05-06 09:53:03 +08:00
caorushizi e31eddfd2e 2.0.0-beta.4 2023-05-05 11:25:10 +08:00
caorushizi bbb9f5798b fix: peocess.env 2023-05-05 10:20:10 +08:00
caorushizi b634cf056d fix: env file. 2023-05-05 09:45:38 +08:00
士子☀️ 2ede22b50a github action pnpm version 2023-05-05 01:15:29 +08:00
士子☀️ a4efd83f7a build and release 2023-05-05 01:10:57 +08:00
caorushizi c3ebced763 macos pack 2023-05-04 23:32:03 +08:00
caorushizi 6cb6621df1 platform: add macos 2023-05-04 23:16:13 +08:00
士子☀️ 4e5febba8b something 2023-04-22 19:47:10 +08:00
士子☀️ 1fb787d4ea 手动添加链接;某些视频网站跳转 about:blank ;修改下载名称 2023-04-22 17:29:26 +08:00
士子☀️ f24ddaa55e add favorite 2023-04-22 14:33:57 +08:00
士子☀️ 66542a0003 talking data version 2023-04-17 23:04:17 +08:00
士子☀️ f8a8e1d3e6 不展示menu 2023-04-15 22:22:34 +08:00
士子☀️ c1873b8c6d 在新页面中打开浏览器 2023-04-15 21:30:15 +08:00
士子☀️ 07dceb2704 在新页面中打开浏览器 2023-04-15 21:05:07 +08:00
士子☀️ ceec042ffd 在新页面中打开浏览器 2023-04-15 16:45:39 +08:00
士子☀️ 2a47f255ee 升级antd,下载完成后删除原始文件 2023-04-14 00:04:44 +08:00
士子☀️ 1f899e6c6d env 2023-04-02 15:07:56 +08:00
士子☀️ f0686bb18c release 2023-04-01 20:44:51 +08:00
士子☀️ b321dc06e9 app version 2023-04-01 19:11:55 +08:00
士子☀️ 5f7c6e846b updater 2023-04-01 11:03:19 +08:00
士子☀️ 2d71475a48 Merge branch 'master' of https://github.com/caorushizi/m3u8-downloader 2023-04-01 10:55:55 +08:00
士子☀️ cfdeb4a1a8 updater 2023-04-01 10:55:36 +08:00
士子☀️ 5d3abdefdc Create .github/dependabot.yml 2023-04-01 10:16:21 +08:00
士子☀️ abcff22f3e 转换为音频 2023-03-31 23:27:45 +08:00
士子☀️ 7d4ca4d758 ipcrenderer 事件监听 2023-03-31 21:01:07 +08:00
caorushizi 9b44b2f31f 2.0 优化功能 2023-03-31 20:27:28 +08:00
士子☀️ 55bd8da894 feature: 完善首页、视频获取逻辑 2023-03-31 00:37:18 +08:00
士子☀️ e8c7abaa2f 修复事件监听&完善下载页面交互 2023-03-30 01:05:02 +08:00
士子☀️ 1702b9beac update 2023-03-28 23:49:41 +08:00
士子☀️ de25052980 暂停下载逻辑 2023-03-27 23:47:10 +08:00
士子☀️ 03700ed4bb readme 2023-03-26 20:48:18 +08:00
士子☀️ e0147a4a6e readme 2023-03-26 20:41:55 +08:00
士子☀️ 281fd07e23 Merge pull request #15 from caorushizi/dev
Dev
2023-03-26 20:34:14 +08:00
士子☀️ 1d7a0e62e5 download. 2023-03-26 20:29:20 +08:00
士子☀️ e4dcdb9422 download. 2023-03-26 19:22:29 +08:00
士子☀️ f035bb09b4 download. 2023-03-26 17:59:54 +08:00
士子☀️ 869c6497e9 download. 2023-03-26 15:54:43 +08:00
士子☀️ 151ed1ce0d download list progress. 2023-03-26 01:12:49 +08:00
士子☀️ bab349da9b download list. 2023-03-25 20:17:02 +08:00
士子☀️ ac8f9d2955 home page. 2023-03-25 16:00:06 +08:00
士子☀️ 0f2670069f readme. 2023-03-25 12:15:38 +08:00
士子☀️ 0af3d32337 download list. 2023-03-25 12:13:30 +08:00
士子☀️ f5a22f8393 config page. 2023-03-25 11:39:40 +08:00
士子☀️ 769a82e7ed setting form. 2023-03-25 00:08:23 +08:00
caorushizi 3985af0042 something 2023-03-24 20:09:18 +08:00
士子☀️ dca0e0a84b add electron extensions. 2023-03-24 00:29:27 +08:00
士子☀️ 233296ba3e receive 2023-03-23 00:22:37 +08:00
士子☀️ 2bc4fe0592 readme 2023-03-22 00:13:24 +08:00
士子☀️ c22245e296 source extract. 2023-03-22 00:11:15 +08:00
士子☀️ 29de2fc81c source extract. 2023-03-20 01:09:08 +08:00
士子☀️ bd27aefe8a source extract. 2023-03-20 00:50:08 +08:00
士子☀️ 722cabba57 source extract. 2023-03-19 19:23:35 +08:00
士子☀️ 3468c8d5e6 new branch. 2023-03-19 12:16:37 +08:00
caorushizi b3cc83f8cd new ui 2023-01-14 12:34:26 +08:00
caorushizi f6a1ca03ac new ui 2023-01-13 11:48:44 +08:00
士子☀️ 516ac72c3e feature: 修改页面提示逻辑 2022-12-28 00:07:53 +08:00
士子☀️ c068bde0a8 feature: 新增插件 2022-12-26 23:38:04 +08:00
士子☀️ ca3ed53a59 feature: 样式交互优化 2022-12-25 23:59:01 +08:00
士子☀️ 04c05ee15e feture: 优化样式交互 2022-12-25 20:48:31 +08:00
士子☀️ 60d27be739 style: eslint 修正 2022-12-25 15:11:06 +08:00
士子☀️ 259fe5f447 style: eslint 修正 2022-12-25 14:30:24 +08:00
士子☀️ 8d9b7fc9dc style: eslint 修正 2022-12-25 13:22:18 +08:00
士子☀️ d5d282147d style: eslint 修正 2022-12-24 17:51:28 +08:00
士子☀️ 08f7f66154 revert: 删除mediago-node 2022-12-23 22:15:26 +08:00
士子☀️ f702f847e6 style: 修正代码提交规范 2022-12-23 22:11:12 +08:00
士子☀️ b9b87cf354 master 2022-12-22 23:14:59 +08:00
士子☀️ a81b9a37ab master 2022-12-22 16:09:58 +08:00
士子☀️ 64174ef374 master 2022-12-18 23:20:34 +08:00
士子☀️ a8b3a9ee1a master 2022-12-17 00:30:53 +08:00
diaozhenyuan 7be1a7907d master 2022-12-16 21:14:14 +08:00
diaozhenyuan 05d207f34d master 2022-12-16 18:49:58 +08:00
diaozhenyuan 26be46b038 master 2022-12-16 18:02:24 +08:00
士子☀️ 47826f1f72 master 2022-12-15 23:27:59 +08:00
士子☀️ f7428f811a master 2022-12-12 22:55:24 +08:00
士子☀️ 3aa8577a38 master 2022-12-11 19:10:44 +08:00
士子☀️ 8b7965dbcb master 2022-12-11 02:54:46 +08:00
士子☀️ 006cb4b13c master 2022-12-10 19:14:22 +08:00
士子☀️ ecb8d6b387 master 2022-12-10 18:52:10 +08:00
士子☀️ b57b05fe1d master 2022-12-10 18:23:47 +08:00
士子☀️ 1e9969857d Merge pull request #13 from caorushizi/dev
Dev
2022-12-10 18:01:03 +08:00
士子☀️ af89dd2694 dev 2022-12-06 23:04:38 +08:00
士子☀️ e418e05ab1 dev 2022-11-29 23:34:31 +08:00
士子☀️ a8d8a7aca7 dev 2022-11-29 23:31:30 +08:00
士子☀️ 4c7226cda1 dev 2022-11-26 00:15:27 +08:00
士子☀️ 91b5ee4423 dev 2022-11-26 00:15:05 +08:00
士子☀️ f8d7148b9e Dev 2022-11-08 00:07:41 +08:00
士子☀️ 0f0687b5c9 dev 2022-11-06 23:36:28 +08:00
士子☀️ 1384cd4c6e dev 2022-11-06 12:41:35 +08:00
士子☀️ 4c5c78d0e4 dev 2022-11-06 12:15:07 +08:00
士子☀️ 551abb4496 dev 2022-10-30 21:49:32 +08:00
士子☀️ 8af8824c3e dev 2022-10-30 20:20:32 +08:00
士子☀️ c01c085ac1 dev 2022-10-30 01:46:39 +08:00
士子☀️ 8668acdd6d dev 2022-10-27 00:13:10 +08:00
士子☀️ 03567ed36d 重构 2022-10-24 00:10:10 +08:00
caorushizi dcfea2cfb3 整理项目文件 2022-05-01 01:01:05 +08:00
caorushizi 3c4e6c8240 整理项目文件 2022-04-30 23:23:38 +08:00
caorushizi 9e93426c38 2 2022-04-20 23:53:45 +08:00
caorushizi 5c698e2e9b 1 2022-04-19 23:34:58 +08:00
caorushizi b174e14fbd process 2022-04-19 23:27:09 +08:00
caorushizi 19e84cd415 downloader 2022-04-19 01:13:12 +08:00
caorushizi 73a9b3fd72 downloader 2022-04-19 01:12:33 +08:00
caorushizi 64a938879d downloader 2022-04-17 23:15:38 +08:00
caorushizi 66b9a9677b 重构文件目录 2022-04-17 01:55:37 +08:00
士子☀️ 39616244d9 mono repo. 2022-04-11 23:14:48 +08:00
士子☀️ 990846515f Update README.md 2022-02-06 21:32:25 +08:00
caorushizi 94777aead3 update readme.md 2022-02-05 16:59:13 +08:00
caorushizi 5275d3bfd3 删除视频数据打点 2022-02-05 16:43:06 +08:00
士子☀️ 73ae0ad083 Update README.md 2022-01-27 11:38:36 +08:00
caorushizi 5ed6e84a14 Merge branch 'master' of https://github.com/caorushizi/m3u8-downloader 2022-01-27 00:22:22 +08:00
caorushizi ed45cd8d73 README.md 2022-01-27 00:21:36 +08:00
士子☀️ f393b99cb5 Update README.md 2022-01-27 00:07:56 +08:00
caorushizi 6638600ffa 修复开发环境中没有注入环境变量导致无法运行 2022-01-26 23:53:54 +08:00
士子☀️ 4d5cae3b0c Update build.js 2022-01-26 13:38:31 +08:00
caorushizi e846390d04 添加数据统计许可 2022-01-25 23:52:07 +08:00
caorushizi 6e6b7315ca 主进程代码优化 2022-01-24 23:39:43 +08:00
caorushizi 5760855516 主进程代码优化 2022-01-24 00:07:45 +08:00
caorushizi db956ecd89 主进程代码优化 2022-01-23 23:53:55 +08:00
caorushizi 56663aa26b 主进程代码优化 2022-01-23 19:34:57 +08:00
caorushizi 3358a19185 主进程代码优化 2022-01-23 14:27:14 +08:00
caorushizi 02d061be9f 主进程代码优化 2022-01-23 01:38:09 +08:00
caorushizi 90952299cc 主进程代码优化 2022-01-23 01:37:17 +08:00
caorushizi af21763eca feature: 修复一些问题 2022-01-08 17:41:44 +08:00
caorushizi 71739a3ffb feature: 修复一些问题 2022-01-08 17:19:45 +08:00
caorushizi db3becb071 feature: 修复一些问题 2022-01-08 13:28:37 +08:00
caorushizi a458f69990 feature: 清理代码。 2022-01-01 02:13:23 +08:00
caorushizi 82cf627488 feature: 自动升级。 2021-12-31 22:58:00 +08:00
caorushizi e00bd5dab0 feature: 修复一些问题 2021-12-31 01:41:50 +08:00
caorushizi 0a22fa4460 feature: 清空列表的问题 2021-12-30 00:33:12 +08:00
caorushizi 7d97a9d5f0 feature: 清理代码 2021-12-30 00:19:35 +08:00
caorushizi 4456130366 feature: 修复打包白屏;消息点击tab才消失;清空所有没反应; 2021-12-30 00:16:31 +08:00
caorushizi 24cfcb6c4c feature: 更换交互方式 2021-12-27 00:02:25 +08:00
caorushizi 82dadbf0da feature: 更换交互方式 2021-12-26 13:36:38 +08:00
caorushizi ef65fb879d fix: electron 16. 2021-12-12 19:39:29 +08:00
caorushizi b9d443d2f5 fix: electron 16. 2021-12-11 16:21:23 +08:00
caorushizi 6e1a90b6dd fix: electron 16. 2021-12-11 15:18:56 +08:00
caorushizi ad1f727caf fix: electron 16. 2021-12-11 00:53:30 +08:00
caorushizi ec9c461504 fix: react hooks. 2021-12-05 23:11:48 +08:00
caorushizi bcac2c605f fix: react hooks. 2021-12-05 22:38:01 +08:00
士子☀️ ea5be3343b feat: react hooks. 2021-12-05 22:19:32 +08:00
士子☀️ 00eaa3974a feat: react hooks. 2021-12-05 21:03:14 +08:00
caorushizi dc2fcc61c6 fix: react hooks. 2021-12-05 18:33:15 +08:00
caorushizi 3eba3ce0eb fix: react hooks. 2021-12-05 03:20:28 +08:00
caorushizi 195b17e54e fix: build script. 2021-08-23 23:12:27 +08:00
caorushizi 064d64c743 fix: build script. 2021-08-21 21:29:55 +08:00
caorushizi 5d4349fa88 fix: build script. 2021-08-21 15:27:22 +08:00
caorushizi a55a230be8 fix: 代理设置。 2021-08-21 00:15:09 +08:00
caorushizi 5e696f7f8f fix: 删除测试代码。 2021-08-19 22:43:27 +08:00
caorushizi 2330aadf7c fix: 删除 terminal 页面。 2021-08-16 01:39:27 +08:00
caorushizi 468ca63b39 fix: 调整目录结构 2021-08-15 15:30:12 +08:00
caorushizi 8286fe2591 terminal page. 2021-08-15 12:33:07 +08:00
caorushizi 03703f2631 fix: 调整目录结构 2021-08-15 01:19:06 +08:00
caorushizi 17b42f0f45 fix: 调整目录结构 2021-08-14 23:56:48 +08:00
caorushizi 7045790fe0 fix: 调整目录结构 2021-08-14 22:40:30 +08:00
caorushizi e122d1b820 fix: 调整目录结构 2021-08-14 17:15:41 +08:00
caorushizi 3fda15fd4a fix: clean up dep. 2021-05-11 00:40:37 +08:00
caorushizi f40b278024 fix: clean up code. 2021-05-09 02:18:11 +08:00
caorushizi e60994e277 fix: clean up code. 2021-05-06 23:09:44 +08:00
caorushizi 639d80f3d6 fix: 拖拽 m3u8 下载 2021-05-04 15:21:47 +08:00
diaozhenyuan ae262c311d fix: 添加todo 2021-05-03 13:21:43 +08:00
diaozhenyuan 16ccf321ba fix: 设置代理;设置日志输出; 2021-05-03 13:12:30 +08:00
diaozhenyuan 5a73070632 fix: 添加 mac 上关闭和最小化按钮 2021-05-03 00:58:23 +08:00
caorushizi 1af5afa7a7 fix: 没有收藏的时候样式 2021-05-02 23:11:50 +08:00
diaozhenyuan aa62389bea fix: mac 上使用 2021-05-02 13:07:21 +08:00
士子☀️ 40dc614927 Update README.md 2021-04-30 13:01:10 +08:00
caorushizi 143aeafd43 fix: 🛠 修复软件无法最小化的问题 2021-04-29 23:42:08 +08:00
caorushizi df8a1ba7e3 fix: 🛠 完成详情修改 2021-04-28 01:14:59 +08:00
caorushizi d649aed29f fix: 🛠 添加收藏不可用 2021-04-28 00:47:24 +08:00
caorushizi 8bae5ac9bd update: 🛠 添加埋点 2021-04-28 00:36:33 +08:00
caorushizi 3053d33167 Merge remote-tracking branch 'origin/master' 2021-04-28 00:07:27 +08:00
caorushizi 64f34daeb2 update: 新建下载时解析 headers,修复了一些问题 2021-04-28 00:07:09 +08:00
士子☀️ 240fb0e749 Update README.md 2021-04-27 13:06:27 +08:00
caorushizi f87ae3a54d update: 🥳 v1.0.3 2021-04-27 02:25:14 +08:00
caorushizi 4ad749f191 update: 🥳 修复若干问题 2021-04-27 02:18:50 +08:00
caorushizi fc12c35095 update: 🥳 修复若干问题 2021-04-27 01:52:10 +08:00
caorushizi a95176c2a7 update: 🛠 修复了一些问题 2021-04-26 00:53:57 +08:00
caorushizi 4dd0ae6415 update: 🛠 修复了一些问题 2021-04-26 00:33:08 +08:00
caorushizi 94ab7ef96d update: 🛠 修复了一些问题 2021-04-26 00:32:19 +08:00
caorushizi f115602f8d update: 🛠 修复了一些问题 2021-04-25 22:40:35 +08:00
caorushizi a994e43e54 update: 🛠 修复了一些问题 2021-04-24 23:41:59 +08:00
caorushizi 5aa66809aa update: 🛠 修复了一些问题 2021-04-24 23:07:10 +08:00
caorushizi c4b0026ccf update: 🛠 生产环境变量 2021-04-24 00:04:20 +08:00
caorushizi 78a5f0309f update: 🛠 删除无用的文件。 2021-04-23 22:38:27 +08:00
caorushizi 45a49ee245 update: 🛠 删除无用的文件。 2021-04-19 23:12:05 +08:00
caorushizi fcafd18a70 update: 🛠 修改 README.md 2021-04-19 00:28:40 +08:00
caorushizi 777f4d9af4 feat: 删除 devtools 2021-04-18 16:10:20 +08:00
caorushizi 2f306eb497 feat: 🛠 完成下载 2021-04-18 01:05:02 +08:00
caorushizi 9038e1d986 feat: 🛠 完成下载 2021-04-18 00:41:35 +08:00
caorushizi 9ecd915905 feat: 🛠 修复打包过程中的问题 2021-04-17 21:09:03 +08:00
caorushizi 468dd405d1 feat: 继续开发 2021-04-17 19:59:30 +08:00
caorushizi 579c142684 feat: 添加 ts 支持 2021-04-17 18:24:49 +08:00
caorushizi 217dbcf8ca feat: 添加 ts 支持 2021-04-17 12:41:26 +08:00
caorushizi c9c5a1f94f feat: 继续开发 2021-04-17 12:30:02 +08:00
caorushizi 556b8c460e feat: 继续开发 2021-04-17 01:32:15 +08:00
caorushizi caaad80a71 feat: 完成下载列表 2021-04-16 00:32:11 +08:00
caorushizi a7b195da98 feat: 完成下载列表 2021-04-16 00:25:11 +08:00
caorushizi 22642616de feat: 🎞 添加 mobx 2021-04-15 02:06:22 +08:00
caorushizi 1298990e24 feat: 🎞 完成下载 2021-04-15 00:39:17 +08:00
caorushizi c4222aecd8 feat: 🎞 完成下载 2021-04-14 00:38:46 +08:00
caorushizi e55e7ab87a feat: 🎞 更换页面交互逻辑 2021-04-12 00:04:25 +08:00
caorushizi 42198d5759 feat: 🎞 重新安装 eslint 2021-04-11 03:47:38 +08:00
caorushizi 62a28d6d11 feat: 🎞 重新安装 eslint 2021-04-11 03:46:27 +08:00
caorushizi dc5583ebf7 feat: 🥳 代码格式化 2021-04-11 03:06:01 +08:00
caorushizi 0b78c54db3 feat: 添加 ts 支持 2021-04-11 02:47:58 +08:00
caorushizi 8de04e2392 feat: 🥳 恢复原先的布局 2021-04-11 00:42:46 +08:00
caorushizi c8515580c4 feat: 🥳 恢复原先的布局 2021-04-10 15:41:51 +08:00
士子☀️ 9fada5c801 Merge pull request #6 from caorushizi/feat/vite
Feat/vite
2021-04-10 12:24:17 +08:00
caorushizi 3c400ec811 feat: 🥳 恢复原先的布局 2021-04-10 12:22:50 +08:00
caorushizi e95798b52f feat: ✈ 添加 plop 2021-04-06 23:45:52 +08:00
caorushizi 0ffab614e4 feat: ✈ 添加 plop 2021-04-05 23:23:36 +08:00
caorushizi 2bc22e183a feat: 🚄 重大修改版本 2021-04-05 01:27:36 +08:00
caorushizi 3fafd34377 feat: 🚄 重大修改版本 2021-04-04 00:06:33 +08:00
caorushizi 67c309c32e feat: ♥ 生产版本构建 2021-03-21 21:28:42 +08:00
caorushizi b8194808a4 feat: ♥ 生产版本构建 2021-03-21 20:58:49 +08:00
caorushizi a615ba3f66 feat: ♥ 生产版本构建 2021-03-21 20:53:18 +08:00
caorushizi 8aaf2b8a1b feat: ♥ 生产版本构建 2021-03-21 20:20:28 +08:00
士子☀️ 77dc7acc62 Create README.md 2021-03-21 12:14:11 +08:00
caorushizi a1d65c72e5 feat: 👓 调整目录结构 2021-03-21 11:57:55 +08:00
caorushizi 6ae207d992 feat: 📦 使用窗口管理 2021-03-21 11:15:52 +08:00
caorushizi d7aa452b90 feat: add env files. 2021-03-21 10:08:29 +08:00
caorushizi b94efad619 feat: add env files. 2021-03-20 21:39:15 +08:00
caorushizi 61c0ad6552 feat: add env files. 2021-03-20 20:28:38 +08:00
caorushizi 8ad8cdca4c feat: add env files. 2021-03-20 18:57:14 +08:00
caorushizi 3c4aebbbd1 feat: fix typescript error. 2021-03-20 17:46:53 +08:00
caorushizi d4202158ba feat: fix typescript error. 2021-03-20 17:46:15 +08:00
caorushizi 43a586ed89 feat: vite2 2021-03-20 17:12:44 +08:00
caorushizi 3f3efdace8 feat: vite2 2021-03-20 16:10:39 +08:00
士子☀️ 10f91f6371 Merge pull request #4 from caorushizi/pending
🚀 更新一个版本
2021-03-07 15:50:36 +08:00
caorushizi ddfed0c712 🚀 更新一个版本 2021-03-07 15:49:12 +08:00
士子☀️ 59221265d9 Merge pull request #3 from caorushizi/pending
Pending
2021-03-07 15:46:19 +08:00
caorushizi d8c1658ee9 🚀 更新一个版本 2021-03-07 15:45:34 +08:00
caorushizi 65d9f9589d 🚀 更新一个版本 2021-03-07 00:34:32 +08:00
caorushizi f34deaa251 🚀 更新一个版本 2021-03-06 23:05:08 +08:00
caorushizi eaa0e4e845 __bin__ 2021-02-22 00:19:29 +08:00
士子☀️ 59b4ca3c2d Merge pull request #2 from caorushizi/pending
Pending
2021-02-21 19:04:15 +08:00
caorushizi 44818dcd86 something 2021-02-21 19:02:27 +08:00
caorushizi b7e2604862 yarn.lock 2021-02-21 02:06:13 +08:00
caorushizi 9ed9db4aaa 环境变量 2021-02-21 02:04:37 +08:00
caorushizi a356e72e27 环境变量 2021-02-21 00:04:56 +08:00
士子☀️ 2c1bb4f0f2 Merge pull request #1 from caorushizi/pending
Pending
2021-02-18 23:51:38 +08:00
caorushizi 80d550f2ef 修改选择方式 2021-02-18 23:50:45 +08:00
caorushizi a6db4f5d81 修改选择方式 2021-02-18 23:07:49 +08:00
caorushizi 7d8a7297ed 修改选择方式 2021-02-18 23:04:34 +08:00
caorushizi 1505b6484b update README.md 2021-02-17 20:11:26 +08:00
caorushizi 3f76f79491 修复打包时出错 2021-02-14 20:49:21 +08:00
caorushizi d168f51214 修复打包时出错 2021-02-13 01:46:24 +08:00
caorushizi 384f0eb29d 优化 ffmpeg 下载 2021-02-13 01:09:25 +08:00
caorushizi e07aa5c453 优化 ffmpeg 下载 2021-02-12 23:38:34 +08:00
caorushizi 9cd290e60c 优化软件初始化过程,自动下载环境依赖的二进制 2021-02-11 21:46:13 +08:00
caorushizi d98ec3438c 调整页面结构 2021-02-06 02:11:46 +08:00
caorushizi 226211d610 清理无用的包 2021-02-05 23:27:36 +08:00
caorushizi 9d6755858e 优化下载流程,支持m3u8_DL 2021-02-05 17:47:56 +08:00
caorushizi 682084e7f4 添加埋点,修改样式 2021-02-05 11:23:27 +08:00
caorushizi a068e5cd45 新增浏览器窗口 2021-02-05 09:23:17 +08:00
caorushizi 5dae6a4efa README.md 2021-02-04 21:29:44 +08:00
caorushizi 7d0ab847a7 修改样式 2021-02-04 18:34:10 +08:00
caorushizi b66a8d8ada 添加 talkingdata ,使用西瓜播放器 2021-02-04 00:02:38 +08:00
caorushizi 60f7e9ea9d 添加下载时 headers 2021-02-03 01:03:55 +08:00
caorushizi 06faf8cd83 使用 fluent ui 2021-02-02 10:37:30 +08:00
caorushizi d126bd0c7e webview 2021-02-01 07:16:11 +08:00
caorushizi 280dff1ed2 koa 2021-01-31 18:37:25 +08:00
caorushizi 633c103a76 exec 2021-01-31 07:51:51 +08:00
caorushizi e815e8bc72 first commit. 2021-01-31 06:03:24 +08:00
caorushizi a12632549c init. 2021-01-31 02:38:14 +08:00
781 changed files with 15158 additions and 87069 deletions
File diff suppressed because it is too large Load Diff
@@ -1,127 +0,0 @@
# React Best Practices
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
## Structure
- `rules/` - Individual rule files (one per rule)
- `_sections.md` - Section metadata (titles, impacts, descriptions)
- `_template.md` - Template for creating new rules
- `area-description.md` - Individual rule files
- `src/` - Build scripts and utilities
- `metadata.json` - Document metadata (version, organization, abstract)
- **`AGENTS.md`** - Compiled output (generated)
- **`test-cases.json`** - Test cases for LLM evaluation (generated)
## Getting Started
1. Install dependencies:
```bash
pnpm install
```
2. Build AGENTS.md from rules:
```bash
pnpm build
```
3. Validate rule files:
```bash
pnpm validate
```
4. Extract test cases:
```bash
pnpm extract-tests
```
## Creating a New Rule
1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
- `async-` for Eliminating Waterfalls (Section 1)
- `bundle-` for Bundle Size Optimization (Section 2)
- `server-` for Server-Side Performance (Section 3)
- `client-` for Client-Side Data Fetching (Section 4)
- `rerender-` for Re-render Optimization (Section 5)
- `rendering-` for Rendering Performance (Section 6)
- `js-` for JavaScript Performance (Section 7)
- `advanced-` for Advanced Patterns (Section 8)
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
## Rule File Structure
Each rule file should follow this structure:
````markdown
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description
tags: tag1, tag2, tag3
---
## Rule Title Here
Brief explanation of the rule and why it matters.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example
```
````
**Correct (description of what's right):**
```typescript
// Good code example
```
Optional explanatory text after examples.
Reference: [Link](https://example.com)
## File Naming Convention
- Files starting with `_` are special (excluded from build)
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
- Section is automatically inferred from filename prefix
- Rules are sorted alphabetically by title within each section
- IDs (e.g., 1.1, 1.2) are auto-generated during build
## Impact Levels
- `CRITICAL` - Highest priority, major performance gains
- `HIGH` - Significant performance improvements
- `MEDIUM-HIGH` - Moderate-high gains
- `MEDIUM` - Moderate performance improvements
- `LOW-MEDIUM` - Low-medium gains
- `LOW` - Incremental improvements
## Scripts
- `pnpm build` - Compile rules into AGENTS.md
- `pnpm validate` - Validate all rule files
- `pnpm extract-tests` - Extract test cases for LLM evaluation
- `pnpm dev` - Build and validate
## Contributing
When adding or modifying rules:
1. Use the correct filename prefix for your section
2. Follow the `_template.md` structure
3. Include clear bad/good examples with explanations
4. Add appropriate tags
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
6. Rules are automatically sorted by title - no need to manage numbers!
## Acknowledgments
Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
@@ -1,148 +0,0 @@
---
name: vercel-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
# Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 67 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
| -------- | ------------------------- | ----------- | ------------ |
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 3 | Server-Side Performance | HIGH | `server-` |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
| 6 | Rendering Performance | MEDIUM | `rendering-` |
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
| 8 | Advanced Patterns | LOW | `advanced-` |
## Quick Reference
### 1. Eliminating Waterfalls (CRITICAL)
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content
### 2. Bundle Size Optimization (CRITICAL)
- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed
### 3. Server-Side Performance (HIGH)
- `server-auth-actions` - Authenticate server actions like API routes
- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-cache-lru` - Use LRU cache for cross-request caching
- `server-dedup-props` - Avoid duplicate serialization in RSC props
- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
- `server-serialization` - Minimize data passed to client components
- `server-parallel-fetching` - Restructure components to parallelize fetches
- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
- `server-after-nonblocking` - Use after() for non-blocking operations
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
- `client-swr-dedup` - Use SWR for automatic request deduplication
- `client-event-listeners` - Deduplicate global event listeners
- `client-passive-event-listeners` - Use passive listeners for scroll
- `client-localstorage-schema` - Version and minimize localStorage data
### 5. Re-render Optimization (MEDIUM)
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
- `rerender-memo` - Extract expensive work into memoized components
- `rerender-memo-with-default-value` - Hoist default non-primitive props
- `rerender-dependencies` - Use primitive dependencies in effects
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
- `rerender-derived-state-no-effect` - Derive state during render, not effects
- `rerender-functional-setstate` - Use functional setState for stable callbacks
- `rerender-lazy-state-init` - Pass function to useState for expensive values
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
- `rerender-transitions` - Use startTransition for non-urgent updates
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
- `rerender-no-inline-components` - Don't define components inside components
### 6. Rendering Performance (MEDIUM)
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
- `rendering-content-visibility` - Use content-visibility for long lists
- `rendering-hoist-jsx` - Extract static JSX outside components
- `rendering-svg-precision` - Reduce SVG coordinate precision
- `rendering-hydration-no-flicker` - Use inline script for client-only data
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
- `rendering-activity` - Use Activity component for show/hide
- `rendering-conditional-render` - Use ternary, not && for conditionals
- `rendering-usetransition-loading` - Prefer useTransition for loading state
- `rendering-resource-hints` - Use React DOM resource hints for preloading
- `rendering-script-defer-async` - Use defer or async on script tags
### 7. JavaScript Performance (LOW-MEDIUM)
- `js-batch-dom-css` - Group CSS changes via classes or cssText
- `js-index-maps` - Build Map for repeated lookups
- `js-cache-property-access` - Cache object properties in loops
- `js-cache-function-results` - Cache function results in module-level Map
- `js-cache-storage` - Cache localStorage/sessionStorage reads
- `js-combine-iterations` - Combine multiple filter/map into one loop
- `js-length-check-first` - Check array length before expensive comparison
- `js-early-exit` - Return early from functions
- `js-hoist-regexp` - Hoist RegExp creation outside loops
- `js-min-max-loop` - Use loop for min/max instead of sort
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
- `js-tosorted-immutable` - Use toSorted() for immutability
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
- `js-request-idle-callback` - Defer non-critical work to browser idle time
### 8. Advanced Patterns (LOW)
- `advanced-event-handler-refs` - Store event handlers in refs
- `advanced-init-once` - Initialize app once per app load
- `advanced-use-latest` - useLatest for stable callback refs
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/async-parallel.md
rules/bundle-barrel-imports.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
@@ -1,46 +0,0 @@
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Eliminating Waterfalls (async)
**Impact:** CRITICAL
**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
## 2. Bundle Size Optimization (bundle)
**Impact:** CRITICAL
**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
## 3. Server-Side Performance (server)
**Impact:** HIGH
**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
## 4. Client-Side Data Fetching (client)
**Impact:** MEDIUM-HIGH
**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
## 5. Re-render Optimization (rerender)
**Impact:** MEDIUM
**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
## 6. Rendering Performance (rendering)
**Impact:** MEDIUM
**Description:** Optimizing the rendering process reduces the work the browser needs to do.
## 7. JavaScript Performance (js)
**Impact:** LOW-MEDIUM
**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
## 8. Advanced Patterns (advanced)
**Impact:** LOW
**Description:** Advanced patterns for specific cases that require careful implementation.
@@ -1,28 +0,0 @@
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description of impact (e.g., "20-50% improvement")
tags: tag1, tag2
---
## Rule Title Here
**Impact: MEDIUM (optional impact description)**
Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example here
const bad = example();
```
**Correct (description of what's right):**
```typescript
// Good code example here
const good = example();
```
Reference: [Link to documentation or resource](https://example.com)
@@ -1,55 +0,0 @@
---
title: Store Event Handlers in Refs
impact: LOW
impactDescription: stable subscriptions
tags: advanced, hooks, refs, event-handlers, optimization
---
## Store Event Handlers in Refs
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
**Incorrect (re-subscribes on every render):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
useEffect(() => {
window.addEventListener(event, handler);
return () => window.removeEventListener(event, handler);
}, [event, handler]);
}
```
**Correct (stable subscription):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
}, [handler]);
useEffect(() => {
const listener = (e) => handlerRef.current(e);
window.addEventListener(event, listener);
return () => window.removeEventListener(event, listener);
}, [event]);
}
```
**Alternative: use `useEffectEvent` if you're on latest React:**
```tsx
import { useEffectEvent } from "react";
function useWindowEvent(event: string, handler: (e) => void) {
const onEvent = useEffectEvent(handler);
useEffect(() => {
window.addEventListener(event, onEvent);
return () => window.removeEventListener(event, onEvent);
}, [event]);
}
```
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
@@ -1,42 +0,0 @@
---
title: Initialize App Once, Not Per Mount
impact: LOW-MEDIUM
impactDescription: avoids duplicate init in development
tags: initialization, useEffect, app-startup, side-effects
---
## Initialize App Once, Not Per Mount
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
**Incorrect (runs twice in dev, re-runs on remount):**
```tsx
function Comp() {
useEffect(() => {
loadFromStorage();
checkAuthToken();
}, []);
// ...
}
```
**Correct (once per app load):**
```tsx
let didInit = false;
function Comp() {
useEffect(() => {
if (didInit) return;
didInit = true;
loadFromStorage();
checkAuthToken();
}, []);
// ...
}
```
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
@@ -1,39 +0,0 @@
---
title: useEffectEvent for Stable Callback Refs
impact: LOW
impactDescription: prevents effect re-runs
tags: advanced, hooks, useEffectEvent, refs, optimization
---
## useEffectEvent for Stable Callback Refs
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
**Incorrect (effect re-runs on every callback change):**
```tsx
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState("");
useEffect(() => {
const timeout = setTimeout(() => onSearch(query), 300);
return () => clearTimeout(timeout);
}, [query, onSearch]);
}
```
**Correct (using React's useEffectEvent):**
```tsx
import { useEffectEvent } from "react";
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState("");
const onSearchEvent = useEffectEvent(onSearch);
useEffect(() => {
const timeout = setTimeout(() => onSearchEvent(query), 300);
return () => clearTimeout(timeout);
}, [query]);
}
```
@@ -1,38 +0,0 @@
---
title: Prevent Waterfall Chains in API Routes
impact: CRITICAL
impactDescription: 2-10× improvement
tags: api-routes, server-actions, waterfalls, parallelization
---
## Prevent Waterfall Chains in API Routes
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
**Incorrect (config waits for auth, data waits for both):**
```typescript
export async function GET(request: Request) {
const session = await auth();
const config = await fetchConfig();
const data = await fetchData(session.user.id);
return Response.json({ data, config });
}
```
**Correct (auth and config start immediately):**
```typescript
export async function GET(request: Request) {
const sessionPromise = auth();
const configPromise = fetchConfig();
const session = await sessionPromise;
const [config, data] = await Promise.all([
configPromise,
fetchData(session.user.id),
]);
return Response.json({ data, config });
}
```
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
@@ -1,37 +0,0 @@
---
title: Check Cheap Conditions Before Async Flags
impact: HIGH
impactDescription: avoids unnecessary async work when a synchronous guard already fails
tags: async, await, feature-flags, short-circuit, conditional
---
## Check Cheap Conditions Before Async Flags
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
**Incorrect:**
```typescript
const someFlag = await getFlag();
if (someFlag && someCondition) {
// ...
}
```
**Correct:**
```typescript
if (someCondition) {
const someFlag = await getFlag();
if (someFlag) {
// ...
}
}
```
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
@@ -1,82 +0,0 @@
---
title: Defer Await Until Needed
impact: HIGH
impactDescription: avoids blocking unused code paths
tags: async, await, conditional, optimization
---
## Defer Await Until Needed
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
**Incorrect (blocks both branches):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId);
if (skipProcessing) {
// Returns immediately but still waited for userData
return { skipped: true };
}
// Only this branch uses userData
return processUserData(userData);
}
```
**Correct (only blocks when needed):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) {
// Returns immediately without waiting
return { skipped: true };
}
// Fetch only when needed
const userData = await fetchUserData(userId);
return processUserData(userData);
}
```
**Another example (early return optimization):**
```typescript
// Incorrect: always fetches permissions
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId);
const resource = await getResource(resourceId);
if (!resource) {
return { error: "Not found" };
}
if (!permissions.canEdit) {
return { error: "Forbidden" };
}
return await updateResourceData(resource, permissions);
}
// Correct: fetches only when needed
async function updateResource(resourceId: string, userId: string) {
const resource = await getResource(resourceId);
if (!resource) {
return { error: "Not found" };
}
const permissions = await fetchPermissions(userId);
if (!permissions.canEdit) {
return { error: "Forbidden" };
}
return await updateResourceData(resource, permissions);
}
```
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
@@ -1,52 +0,0 @@
---
title: Dependency-Based Parallelization
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, dependencies, better-all
---
## Dependency-Based Parallelization
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
**Incorrect (profile waits for config unnecessarily):**
```typescript
const [user, config] = await Promise.all([fetchUser(), fetchConfig()]);
const profile = await fetchProfile(user.id);
```
**Correct (config and profile run in parallel):**
```typescript
import { all } from "better-all";
const { user, config, profile } = await all({
async user() {
return fetchUser();
},
async config() {
return fetchConfig();
},
async profile() {
return fetchProfile((await this.$.user).id);
},
});
```
**Alternative without extra dependencies:**
We can also create all the promises first, and do `Promise.all()` at the end.
```typescript
const userPromise = fetchUser();
const profilePromise = userPromise.then((user) => fetchProfile(user.id));
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise,
]);
```
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
@@ -1,28 +0,0 @@
---
title: Promise.all() for Independent Operations
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, promises, waterfalls
---
## Promise.all() for Independent Operations
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
**Incorrect (sequential execution, 3 round trips):**
```typescript
const user = await fetchUser();
const posts = await fetchPosts();
const comments = await fetchComments();
```
**Correct (parallel execution, 1 round trip):**
```typescript
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments(),
]);
```
@@ -1,99 +0,0 @@
---
title: Strategic Suspense Boundaries
impact: HIGH
impactDescription: faster initial paint
tags: async, suspense, streaming, layout-shift
---
## Strategic Suspense Boundaries
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
**Incorrect (wrapper blocked by data fetching):**
```tsx
async function Page() {
const data = await fetchData(); // Blocks entire page
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
);
}
```
The entire layout waits for data even though only the middle section needs it.
**Correct (wrapper shows immediately, data streams in):**
```tsx
function Page() {
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
);
}
async function DataDisplay() {
const data = await fetchData(); // Only blocks this component
return <div>{data.content}</div>;
}
```
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
**Alternative (share promise across components):**
```tsx
function Page() {
// Start fetch immediately, but don't await
const dataPromise = fetchData();
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<Suspense fallback={<Skeleton />}>
<DataDisplay dataPromise={dataPromise} />
<DataSummary dataPromise={dataPromise} />
</Suspense>
<div>Footer</div>
</div>
);
}
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise); // Unwraps the promise
return <div>{data.content}</div>;
}
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise); // Reuses the same promise
return <div>{data.summary}</div>;
}
```
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
**When NOT to use this pattern:**
- Critical data needed for layout decisions (affects positioning)
- SEO-critical content above the fold
- Small, fast queries where suspense overhead isn't worth it
- When you want to avoid layout shift (loading → content jump)
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
@@ -1,60 +0,0 @@
---
title: Avoid Barrel File Imports
impact: CRITICAL
impactDescription: 200-800ms import cost, slow builds
tags: bundle, imports, tree-shaking, barrel-files, performance
---
## Avoid Barrel File Imports
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
**Incorrect (imports entire library):**
```tsx
import { Check, X, Menu } from "lucide-react";
// Loads 1,583 modules, takes ~2.8s extra in dev
// Runtime cost: 200-800ms on every cold start
import { Button, TextField } from "@mui/material";
// Loads 2,225 modules, takes ~4.2s extra in dev
```
**Correct - Next.js 13.5+ (recommended):**
```js
// next.config.js - automatically optimizes barrel imports at build time
module.exports = {
experimental: {
optimizePackageImports: ["lucide-react", "@mui/material"],
},
};
```
```tsx
// Keep the standard imports - Next.js transforms them to direct imports
import { Check, X, Menu } from "lucide-react";
// Full TypeScript support, no manual path wrangling
```
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
**Correct - Direct imports (non-Next.js projects):**
```tsx
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
// Loads only what you use
```
> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
@@ -1,37 +0,0 @@
---
title: Conditional Module Loading
impact: HIGH
impactDescription: loads large data only when needed
tags: bundle, conditional-loading, lazy-loading
---
## Conditional Module Loading
Load large data or modules only when a feature is activated.
**Example (lazy-load animation frames):**
```tsx
function AnimationPlayer({
enabled,
setEnabled,
}: {
enabled: boolean;
setEnabled: React.Dispatch<React.SetStateAction<boolean>>;
}) {
const [frames, setFrames] = useState<Frame[] | null>(null);
useEffect(() => {
if (enabled && !frames && typeof window !== "undefined") {
import("./animation-frames.js")
.then((mod) => setFrames(mod.frames))
.catch(() => setEnabled(false));
}
}, [enabled, frames, setEnabled]);
if (!frames) return <Skeleton />;
return <Canvas frames={frames} />;
}
```
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
@@ -1,49 +0,0 @@
---
title: Defer Non-Critical Third-Party Libraries
impact: MEDIUM
impactDescription: loads after hydration
tags: bundle, third-party, analytics, defer
---
## Defer Non-Critical Third-Party Libraries
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
**Incorrect (blocks initial bundle):**
```tsx
import { Analytics } from "@vercel/analytics/react";
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
);
}
```
**Correct (loads after hydration):**
```tsx
import dynamic from "next/dynamic";
const Analytics = dynamic(
() => import("@vercel/analytics/react").then((m) => m.Analytics),
{ ssr: false },
);
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
);
}
```
@@ -1,35 +0,0 @@
---
title: Dynamic Imports for Heavy Components
impact: CRITICAL
impactDescription: directly affects TTI and LCP
tags: bundle, dynamic-import, code-splitting, next-dynamic
---
## Dynamic Imports for Heavy Components
Use `next/dynamic` to lazy-load large components not needed on initial render.
**Incorrect (Monaco bundles with main chunk ~300KB):**
```tsx
import { MonacoEditor } from "./monaco-editor";
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />;
}
```
**Correct (Monaco loads on demand):**
```tsx
import dynamic from "next/dynamic";
const MonacoEditor = dynamic(
() => import("./monaco-editor").then((m) => m.MonacoEditor),
{ ssr: false },
);
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />;
}
```
@@ -1,46 +0,0 @@
---
title: Preload Based on User Intent
impact: MEDIUM
impactDescription: reduces perceived latency
tags: bundle, preload, user-intent, hover
---
## Preload Based on User Intent
Preload heavy bundles before they're needed to reduce perceived latency.
**Example (preload on hover/focus):**
```tsx
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
if (typeof window !== "undefined") {
void import("./monaco-editor");
}
};
return (
<button onMouseEnter={preload} onFocus={preload} onClick={onClick}>
Open Editor
</button>
);
}
```
**Example (preload when feature flag is enabled):**
```tsx
function FlagsProvider({ children, flags }: Props) {
useEffect(() => {
if (flags.editorEnabled && typeof window !== "undefined") {
void import("./monaco-editor").then((mod) => mod.init());
}
}, [flags.editorEnabled]);
return (
<FlagsContext.Provider value={flags}>{children}</FlagsContext.Provider>
);
}
```
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
@@ -1,78 +0,0 @@
---
title: Deduplicate Global Event Listeners
impact: LOW
impactDescription: single listener for N components
tags: client, swr, event-listeners, subscription
---
## Deduplicate Global Event Listeners
Use `useSWRSubscription()` to share global event listeners across component instances.
**Incorrect (N instances = N listeners):**
```tsx
function useKeyboardShortcut(key: string, callback: () => void) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === key) {
callback();
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [key, callback]);
}
```
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
**Correct (N instances = 1 listener):**
```tsx
import useSWRSubscription from "swr/subscription";
// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>();
function useKeyboardShortcut(key: string, callback: () => void) {
// Register this callback in the Map
useEffect(() => {
if (!keyCallbacks.has(key)) {
keyCallbacks.set(key, new Set());
}
keyCallbacks.get(key)!.add(callback);
return () => {
const set = keyCallbacks.get(key);
if (set) {
set.delete(callback);
if (set.size === 0) {
keyCallbacks.delete(key);
}
}
};
}, [key, callback]);
useSWRSubscription("global-keydown", () => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && keyCallbacks.has(e.key)) {
keyCallbacks.get(e.key)!.forEach((cb) => cb());
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
});
}
function Profile() {
// Multiple shortcuts will share the same listener
useKeyboardShortcut("p", () => {
/* ... */
});
useKeyboardShortcut("k", () => {
/* ... */
});
// ...
}
```
@@ -1,77 +0,0 @@
---
title: Version and Minimize localStorage Data
impact: MEDIUM
impactDescription: prevents schema conflicts, reduces storage size
tags: client, localStorage, storage, versioning, data-minimization
---
## Version and Minimize localStorage Data
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
**Incorrect:**
```typescript
// No version, stores everything, no error handling
localStorage.setItem("userConfig", JSON.stringify(fullUserObject));
const data = localStorage.getItem("userConfig");
```
**Correct:**
```typescript
const VERSION = "v2";
function saveConfig(config: { theme: string; language: string }) {
try {
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config));
} catch {
// Throws in incognito/private browsing, quota exceeded, or disabled
}
}
function loadConfig() {
try {
const data = localStorage.getItem(`userConfig:${VERSION}`);
return data ? JSON.parse(data) : null;
} catch {
return null;
}
}
// Migration from v1 to v2
function migrate() {
try {
const v1 = localStorage.getItem("userConfig:v1");
if (v1) {
const old = JSON.parse(v1);
saveConfig({
theme: old.darkMode ? "dark" : "light",
language: old.lang,
});
localStorage.removeItem("userConfig:v1");
}
} catch {}
}
```
**Store minimal fields from server responses:**
```typescript
// User object has 20+ fields, only store what UI needs
function cachePrefs(user: FullUser) {
try {
localStorage.setItem(
"prefs:v1",
JSON.stringify({
theme: user.preferences.theme,
notifications: user.preferences.notifications,
}),
);
} catch {}
}
```
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
@@ -1,48 +0,0 @@
---
title: Use Passive Event Listeners for Scrolling Performance
impact: MEDIUM
impactDescription: eliminates scroll delay caused by event listeners
tags: client, event-listeners, scrolling, performance, touch, wheel
---
## Use Passive Event Listeners for Scrolling Performance
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
**Incorrect:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
document.addEventListener("touchstart", handleTouch);
document.addEventListener("wheel", handleWheel);
return () => {
document.removeEventListener("touchstart", handleTouch);
document.removeEventListener("wheel", handleWheel);
};
}, []);
```
**Correct:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
document.addEventListener("touchstart", handleTouch, { passive: true });
document.addEventListener("wheel", handleWheel, { passive: true });
return () => {
document.removeEventListener("touchstart", handleTouch);
document.removeEventListener("wheel", handleWheel);
};
}, []);
```
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
@@ -1,56 +0,0 @@
---
title: Use SWR for Automatic Deduplication
impact: MEDIUM-HIGH
impactDescription: automatic deduplication
tags: client, swr, deduplication, data-fetching
---
## Use SWR for Automatic Deduplication
SWR enables request deduplication, caching, and revalidation across component instances.
**Incorrect (no deduplication, each instance fetches):**
```tsx
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("/api/users")
.then((r) => r.json())
.then(setUsers);
}, []);
}
```
**Correct (multiple instances share one request):**
```tsx
import useSWR from "swr";
function UserList() {
const { data: users } = useSWR("/api/users", fetcher);
}
```
**For immutable data:**
```tsx
import { useImmutableSWR } from "@/lib/swr";
function StaticContent() {
const { data } = useImmutableSWR("/api/config", fetcher);
}
```
**For mutations:**
```tsx
import { useSWRMutation } from "swr/mutation";
function UpdateButton() {
const { trigger } = useSWRMutation("/api/user", updateUser);
return <button onClick={() => trigger()}>Update</button>;
}
```
Reference: [https://swr.vercel.app](https://swr.vercel.app)
@@ -1,110 +0,0 @@
---
title: Avoid Layout Thrashing
impact: MEDIUM
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
tags: javascript, dom, css, performance, reflow, layout-thrashing
---
## Avoid Layout Thrashing
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
**This is OK (browser batches style changes):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = "100px";
element.style.height = "200px";
element.style.backgroundColor = "blue";
element.style.border = "1px solid black";
}
```
**Incorrect (interleaved reads and writes force reflows):**
```typescript
function layoutThrashing(element: HTMLElement) {
element.style.width = "100px";
const width = element.offsetWidth; // Forces reflow
element.style.height = "200px";
const height = element.offsetHeight; // Forces another reflow
}
```
**Correct (batch writes, then read once):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Batch all writes together
element.style.width = "100px";
element.style.height = "200px";
element.style.backgroundColor = "blue";
element.style.border = "1px solid black";
// Read after all writes are done (single reflow)
const { width, height } = element.getBoundingClientRect();
}
```
**Correct (batch reads, then writes):**
```typescript
function avoidThrashing(element: HTMLElement) {
// Read phase - all layout queries first
const rect1 = element.getBoundingClientRect();
const offsetWidth = element.offsetWidth;
const offsetHeight = element.offsetHeight;
// Write phase - all style changes after
element.style.width = "100px";
element.style.height = "200px";
}
```
**Better: use CSS classes**
```css
.highlighted-box {
width: 100px;
height: 200px;
background-color: blue;
border: 1px solid black;
}
```
```typescript
function updateElementStyles(element: HTMLElement) {
element.classList.add("highlighted-box");
const { width, height } = element.getBoundingClientRect();
}
```
**React example:**
```tsx
// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = "100px";
const width = ref.current.offsetWidth; // Forces layout
ref.current.style.height = "200px";
}
}, [isHighlighted]);
return <div ref={ref}>Content</div>;
}
// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
return <div className={isHighlighted ? "highlighted-box" : ""}>Content</div>;
}
```
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
@@ -1,80 +0,0 @@
---
title: Cache Repeated Function Calls
impact: MEDIUM
impactDescription: avoid redundant computation
tags: javascript, cache, memoization, performance
---
## Cache Repeated Function Calls
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
**Incorrect (redundant computation):**
```typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// slugify() called 100+ times for same project names
const slug = slugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Correct (cached results):**
```typescript
// Module-level cache
const slugifyCache = new Map<string, string>()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// Computed only once per unique project name
const slug = cachedSlugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Simpler pattern for single-value functions:**
```typescript
let isLoggedInCache: boolean | null = null;
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache;
}
isLoggedInCache = document.cookie.includes("auth=");
return isLoggedInCache;
}
// Clear cache when auth changes
function onAuthChange() {
isLoggedInCache = null;
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
@@ -1,28 +0,0 @@
---
title: Cache Property Access in Loops
impact: LOW-MEDIUM
impactDescription: reduces lookups
tags: javascript, loops, optimization, caching
---
## Cache Property Access in Loops
Cache object property lookups in hot paths.
**Incorrect (3 lookups × N iterations):**
```typescript
for (let i = 0; i < arr.length; i++) {
process(obj.config.settings.value);
}
```
**Correct (1 lookup total):**
```typescript
const value = obj.config.settings.value;
const len = arr.length;
for (let i = 0; i < len; i++) {
process(value);
}
```
@@ -1,70 +0,0 @@
---
title: Cache Storage API Calls
impact: LOW-MEDIUM
impactDescription: reduces expensive I/O
tags: javascript, localStorage, storage, caching, performance
---
## Cache Storage API Calls
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
**Incorrect (reads storage on every call):**
```typescript
function getTheme() {
return localStorage.getItem("theme") ?? "light";
}
// Called 10 times = 10 storage reads
```
**Correct (Map cache):**
```typescript
const storageCache = new Map<string, string | null>();
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key));
}
return storageCache.get(key);
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value);
storageCache.set(key, value); // keep cache in sync
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
**Cookie caching:**
```typescript
let cookieCache: Record<string, string> | null = null;
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split("; ").map((c) => c.split("=")),
);
}
return cookieCache[name];
}
```
**Important (invalidate on external changes):**
If storage can change externally (another tab, server-set cookies), invalidate cache:
```typescript
window.addEventListener("storage", (e) => {
if (e.key) storageCache.delete(e.key);
});
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
storageCache.clear();
}
});
```
@@ -1,32 +0,0 @@
---
title: Combine Multiple Array Iterations
impact: LOW-MEDIUM
impactDescription: reduces iterations
tags: javascript, arrays, loops, performance
---
## Combine Multiple Array Iterations
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
**Incorrect (3 iterations):**
```typescript
const admins = users.filter((u) => u.isAdmin);
const testers = users.filter((u) => u.isTester);
const inactive = users.filter((u) => !u.isActive);
```
**Correct (1 iteration):**
```typescript
const admins: User[] = [];
const testers: User[] = [];
const inactive: User[] = [];
for (const user of users) {
if (user.isAdmin) admins.push(user);
if (user.isTester) testers.push(user);
if (!user.isActive) inactive.push(user);
}
```
@@ -1,50 +0,0 @@
---
title: Early Return from Functions
impact: LOW-MEDIUM
impactDescription: avoids unnecessary computation
tags: javascript, functions, optimization, early-return
---
## Early Return from Functions
Return early when result is determined to skip unnecessary processing.
**Incorrect (processes all items even after finding answer):**
```typescript
function validateUsers(users: User[]) {
let hasError = false;
let errorMessage = "";
for (const user of users) {
if (!user.email) {
hasError = true;
errorMessage = "Email required";
}
if (!user.name) {
hasError = true;
errorMessage = "Name required";
}
// Continues checking all users even after error found
}
return hasError ? { valid: false, error: errorMessage } : { valid: true };
}
```
**Correct (returns immediately on first error):**
```typescript
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: "Email required" };
}
if (!user.name) {
return { valid: false, error: "Name required" };
}
}
return { valid: true };
}
```
@@ -1,55 +0,0 @@
---
title: Use flatMap to Map and Filter in One Pass
impact: LOW-MEDIUM
impactDescription: eliminates intermediate array
tags: javascript, arrays, flatMap, filter, performance
---
## Use flatMap to Map and Filter in One Pass
**Impact: LOW-MEDIUM (eliminates intermediate array)**
Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
**Incorrect (2 iterations, intermediate array):**
```typescript
const userNames = users
.map((user) => (user.isActive ? user.name : null))
.filter(Boolean);
```
**Correct (1 iteration, no intermediate array):**
```typescript
const userNames = users.flatMap((user) => (user.isActive ? [user.name] : []));
```
**More examples:**
```typescript
// Extract valid emails from responses
// Before
const emails = responses
.map((r) => (r.success ? r.data.email : null))
.filter(Boolean);
// After
const emails = responses.flatMap((r) => (r.success ? [r.data.email] : []));
// Parse and filter valid numbers
// Before
const numbers = strings.map((s) => parseInt(s, 10)).filter((n) => !isNaN(n));
// After
const numbers = strings.flatMap((s) => {
const n = parseInt(s, 10);
return isNaN(n) ? [] : [n];
});
```
**When to use:**
- Transforming items while filtering some out
- Conditional mapping where some inputs produce no output
- Parsing/validating where invalid inputs should be skipped
@@ -1,45 +0,0 @@
---
title: Hoist RegExp Creation
impact: LOW-MEDIUM
impactDescription: avoids recreation
tags: javascript, regexp, optimization, memoization
---
## Hoist RegExp Creation
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
**Incorrect (new RegExp every render):**
```tsx
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Correct (memoize or hoist):**
```tsx
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Warning (global regex has mutable state):**
Global regex (`/g`) has mutable `lastIndex` state:
```typescript
const regex = /foo/g;
regex.test("foo"); // true, lastIndex = 3
regex.test("foo"); // false, lastIndex = 0
```
@@ -1,37 +0,0 @@
---
title: Build Index Maps for Repeated Lookups
impact: LOW-MEDIUM
impactDescription: 1M ops to 2K ops
tags: javascript, map, indexing, optimization, performance
---
## Build Index Maps for Repeated Lookups
Multiple `.find()` calls by the same key should use a Map.
**Incorrect (O(n) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
return orders.map((order) => ({
...order,
user: users.find((u) => u.id === order.userId),
}));
}
```
**Correct (O(1) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
const userById = new Map(users.map((u) => [u.id, u]));
return orders.map((order) => ({
...order,
user: userById.get(order.userId),
}));
}
```
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
@@ -1,50 +0,0 @@
---
title: Early Length Check for Array Comparisons
impact: MEDIUM-HIGH
impactDescription: avoids expensive operations when lengths differ
tags: javascript, arrays, performance, optimization, comparison
---
## Early Length Check for Array Comparisons
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
**Incorrect (always runs expensive comparison):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
return current.sort().join() !== original.sort().join();
}
```
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
**Correct (O(1) length check first):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true;
}
// Only sort when lengths match
const currentSorted = current.toSorted();
const originalSorted = original.toSorted();
for (let i = 0; i < currentSorted.length; i++) {
if (currentSorted[i] !== originalSorted[i]) {
return true;
}
}
return false;
}
```
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
- It avoids mutating the original arrays
- It returns early when a difference is found
@@ -1,82 +0,0 @@
---
title: Use Loop for Min/Max Instead of Sort
impact: LOW
impactDescription: O(n) instead of O(n log n)
tags: javascript, arrays, performance, sorting, algorithms
---
## Use Loop for Min/Max Instead of Sort
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
**Incorrect (O(n log n) - sort to find latest):**
```typescript
interface Project {
id: string;
name: string;
updatedAt: number;
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt);
return sorted[0];
}
```
Sorts the entire array just to find the maximum value.
**Incorrect (O(n log n) - sort for oldest and newest):**
```typescript
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt);
return { oldest: sorted[0], newest: sorted[sorted.length - 1] };
}
```
Still sorts unnecessarily when only min/max are needed.
**Correct (O(n) - single loop):**
```typescript
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null;
let latest = projects[0];
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i];
}
}
return latest;
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null };
let oldest = projects[0];
let newest = projects[0];
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i];
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i];
}
return { oldest, newest };
}
```
Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
```typescript
const numbers = [5, 2, 8, 1, 9];
const min = Math.min(...numbers);
const max = Math.max(...numbers);
```
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
@@ -1,106 +0,0 @@
---
title: Defer Non-Critical Work with requestIdleCallback
impact: MEDIUM
impactDescription: keeps UI responsive during background tasks
tags: javascript, performance, idle, scheduling, analytics
---
## Defer Non-Critical Work with requestIdleCallback
**Impact: MEDIUM (keeps UI responsive during background tasks)**
Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
**Incorrect (blocks main thread during user interaction):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query);
setResults(results);
// These block the main thread immediately
analytics.track("search", { query });
saveToRecentSearches(query);
prefetchTopResults(results.slice(0, 3));
}
```
**Correct (defers non-critical work to idle time):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query);
setResults(results);
// Defer non-critical work to idle periods
requestIdleCallback(() => {
analytics.track("search", { query });
});
requestIdleCallback(() => {
saveToRecentSearches(query);
});
requestIdleCallback(() => {
prefetchTopResults(results.slice(0, 3));
});
}
```
**With timeout for required work:**
```typescript
// Ensure analytics fires within 2 seconds even if browser stays busy
requestIdleCallback(
() => analytics.track("page_view", { path: location.pathname }),
{ timeout: 2000 },
);
```
**Chunking large tasks:**
```typescript
function processLargeDataset(items: Item[]) {
let index = 0;
function processChunk(deadline: IdleDeadline) {
// Process items while we have idle time (aim for <50ms chunks)
while (index < items.length && deadline.timeRemaining() > 0) {
processItem(items[index]);
index++;
}
// Schedule next chunk if more items remain
if (index < items.length) {
requestIdleCallback(processChunk);
}
}
requestIdleCallback(processChunk);
}
```
**With fallback for unsupported browsers:**
```typescript
const scheduleIdleWork =
window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1));
scheduleIdleWork(() => {
// Non-critical work
});
```
**When to use:**
- Analytics and telemetry
- Saving state to localStorage/IndexedDB
- Prefetching resources for likely next actions
- Processing non-urgent data transformations
- Lazy initialization of non-critical features
**When NOT to use:**
- User-initiated actions that need immediate feedback
- Rendering updates the user is waiting for
- Time-sensitive operations
@@ -1,24 +0,0 @@
---
title: Use Set/Map for O(1) Lookups
impact: LOW-MEDIUM
impactDescription: O(n) to O(1)
tags: javascript, set, map, data-structures, performance
---
## Use Set/Map for O(1) Lookups
Convert arrays to Set/Map for repeated membership checks.
**Incorrect (O(n) per check):**
```typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
```
**Correct (O(1) per check):**
```typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
```
@@ -1,57 +0,0 @@
---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM-HIGH
impactDescription: prevents mutation bugs in React state
tags: javascript, arrays, immutability, react, state, mutation
---
## Use toSorted() Instead of sort() for Immutability
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
**Incorrect (mutates original array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Correct (creates new array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
```typescript
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value);
```
**Other immutable array methods:**
- `.toSorted()` - immutable sort
- `.toReversed()` - immutable reverse
- `.toSpliced()` - immutable splice
- `.with()` - immutable element replacement
@@ -1,26 +0,0 @@
---
title: Use Activity Component for Show/Hide
impact: MEDIUM
impactDescription: preserves state/DOM
tags: rendering, activity, visibility, state-preservation
---
## Use Activity Component for Show/Hide
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
**Usage:**
```tsx
import { Activity } from "react";
function Dropdown({ isOpen }: Props) {
return (
<Activity mode={isOpen ? "visible" : "hidden"}>
<ExpensiveMenu />
</Activity>
);
}
```
Avoids expensive re-renders and state loss.
@@ -1,38 +0,0 @@
---
title: Animate SVG Wrapper Instead of SVG Element
impact: LOW
impactDescription: enables hardware acceleration
tags: rendering, svg, css, animation, performance
---
## Animate SVG Wrapper Instead of SVG Element
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
**Incorrect (animating SVG directly - no hardware acceleration):**
```tsx
function LoadingSpinner() {
return (
<svg className="animate-spin" width="24" height="24" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
);
}
```
**Correct (animating wrapper div - hardware accelerated):**
```tsx
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg width="24" height="24" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
);
}
```
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
@@ -1,32 +0,0 @@
---
title: Use Explicit Conditional Rendering
impact: LOW
impactDescription: prevents rendering 0 or NaN
tags: rendering, conditional, jsx, falsy-values
---
## Use Explicit Conditional Rendering
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
**Incorrect (renders "0" when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return <div>{count && <span className="badge">{count}</span>}</div>;
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
**Correct (renders nothing when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return <div>{count > 0 ? <span className="badge">{count}</span> : null}</div>;
}
// When count = 0, renders: <div></div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
@@ -1,38 +0,0 @@
---
title: CSS content-visibility for Long Lists
impact: HIGH
impactDescription: faster initial render
tags: rendering, css, content-visibility, long-lists
---
## CSS content-visibility for Long Lists
Apply `content-visibility: auto` to defer off-screen rendering.
**CSS:**
```css
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
```
**Example:**
```tsx
function MessageList({ messages }: { messages: Message[] }) {
return (
<div className="overflow-y-auto h-screen">
{messages.map((msg) => (
<div key={msg.id} className="message-item">
<Avatar user={msg.author} />
<div>{msg.content}</div>
</div>
))}
</div>
);
}
```
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
@@ -1,36 +0,0 @@
---
title: Hoist Static JSX Elements
impact: LOW
impactDescription: avoids re-creation
tags: rendering, jsx, static, optimization
---
## Hoist Static JSX Elements
Extract static JSX outside components to avoid re-creation.
**Incorrect (recreates element every render):**
```tsx
function LoadingSkeleton() {
return <div className="animate-pulse h-20 bg-gray-200" />;
}
function Container() {
return <div>{loading && <LoadingSkeleton />}</div>;
}
```
**Correct (reuses same element):**
```tsx
const loadingSkeleton = <div className="animate-pulse h-20 bg-gray-200" />;
function Container() {
return <div>{loading && loadingSkeleton}</div>;
}
```
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
@@ -1,72 +0,0 @@
---
title: Prevent Hydration Mismatch Without Flickering
impact: MEDIUM
impactDescription: avoids visual flicker and hydration errors
tags: rendering, ssr, hydration, localStorage, flicker
---
## Prevent Hydration Mismatch Without Flickering
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
**Incorrect (breaks SSR):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
const theme = localStorage.getItem("theme") || "light";
return <div className={theme}>{children}</div>;
}
```
Server-side rendering will fail because `localStorage` is undefined.
**Incorrect (visual flickering):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState("light");
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem("theme");
if (stored) {
setTheme(stored);
}
}, []);
return <div className={theme}>{children}</div>;
}
```
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
**Correct (no flicker, no hydration mismatch):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<div id="theme-wrapper">{children}</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
);
}
```
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
@@ -1,26 +0,0 @@
---
title: Suppress Expected Hydration Mismatches
impact: LOW-MEDIUM
impactDescription: avoids noisy hydration warnings for known differences
tags: rendering, hydration, ssr, nextjs
---
## Suppress Expected Hydration Mismatches
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these _expected_ mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Dont overuse it.
**Incorrect (known mismatch warnings):**
```tsx
function Timestamp() {
return <span>{new Date().toLocaleString()}</span>;
}
```
**Correct (suppress expected mismatch only):**
```tsx
function Timestamp() {
return <span suppressHydrationWarning>{new Date().toLocaleString()}</span>;
}
```
@@ -1,89 +0,0 @@
---
title: Use React DOM Resource Hints
impact: HIGH
impactDescription: reduces load time for critical resources
tags: rendering, preload, preconnect, prefetch, resource-hints
---
## Use React DOM Resource Hints
**Impact: HIGH (reduces load time for critical resources)**
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
- **`preloadModule(href)`**: Fetch an ES module you'll use soon
- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
- **`preinitModule(href)`**: Fetch and evaluate an ES module
**Example (preconnect to third-party APIs):**
```tsx
import { preconnect, prefetchDNS } from "react-dom";
export default function App() {
prefetchDNS("https://analytics.example.com");
preconnect("https://api.example.com");
return <main>{/* content */}</main>;
}
```
**Example (preload critical fonts and styles):**
```tsx
import { preload, preinit } from "react-dom";
export default function RootLayout({ children }) {
// Preload font file
preload("/fonts/inter.woff2", {
as: "font",
type: "font/woff2",
crossOrigin: "anonymous",
});
// Fetch and apply critical stylesheet immediately
preinit("/styles/critical.css", { as: "style" });
return (
<html>
<body>{children}</body>
</html>
);
}
```
**Example (preload modules for code-split routes):**
```tsx
import { preloadModule, preinitModule } from "react-dom";
function Navigation() {
const preloadDashboard = () => {
preloadModule("/dashboard.js", { as: "script" });
};
return (
<nav>
<a href="/dashboard" onMouseEnter={preloadDashboard}>
Dashboard
</a>
</nav>
);
}
```
**When to use each:**
| API | Use case |
| --------------- | ------------------------------------------- |
| `prefetchDNS` | Third-party domains you'll connect to later |
| `preconnect` | APIs or CDNs you'll fetch from immediately |
| `preload` | Critical resources needed for current page |
| `preloadModule` | JS modules for likely next navigation |
| `preinit` | Stylesheets/scripts that must execute early |
| `preinitModule` | ES modules that must execute early |
Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
@@ -1,71 +0,0 @@
---
title: Use defer or async on Script Tags
impact: HIGH
impactDescription: eliminates render-blocking
tags: rendering, script, defer, async, performance
---
## Use defer or async on Script Tags
**Impact: HIGH (eliminates render-blocking)**
Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
**Incorrect (blocks rendering):**
```tsx
export default function Document() {
return (
<html>
<head>
<script src="https://example.com/analytics.js" />
<script src="/scripts/utils.js" />
</head>
<body>{/* content */}</body>
</html>
);
}
```
**Correct (non-blocking):**
```tsx
export default function Document() {
return (
<html>
<head>
{/* Independent script - use async */}
<script src="https://example.com/analytics.js" async />
{/* DOM-dependent script - use defer */}
<script src="/scripts/utils.js" defer />
</head>
<body>{/* content */}</body>
</html>
);
}
```
**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
```tsx
import Script from "next/script";
export default function Page() {
return (
<>
<Script
src="https://example.com/analytics.js"
strategy="afterInteractive"
/>
<Script src="/scripts/utils.js" strategy="beforeInteractive" />
</>
);
}
```
Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
@@ -1,28 +0,0 @@
---
title: Optimize SVG Precision
impact: LOW
impactDescription: reduces file size
tags: rendering, svg, optimization, svgo
---
## Optimize SVG Precision
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
**Incorrect (excessive precision):**
```svg
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
```
**Correct (1 decimal place):**
```svg
<path d="M 10.3 20.8 L 30.9 40.2" />
```
**Automate with SVGO:**
```bash
npx svgo --precision=1 --multipass icon.svg
```
@@ -1,75 +0,0 @@
---
title: Use useTransition Over Manual Loading States
impact: LOW
impactDescription: reduces re-renders and improves code clarity
tags: rendering, transitions, useTransition, loading, state
---
## Use useTransition Over Manual Loading States
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
**Incorrect (manual loading state):**
```tsx
function SearchResults() {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const handleSearch = async (value: string) => {
setIsLoading(true);
setQuery(value);
const data = await fetchResults(value);
setResults(data);
setIsLoading(false);
};
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isLoading && <Spinner />}
<ResultsList results={results} />
</>
);
}
```
**Correct (useTransition with built-in pending state):**
```tsx
import { useTransition, useState } from "react";
function SearchResults() {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const [isPending, startTransition] = useTransition();
const handleSearch = (value: string) => {
setQuery(value); // Update input immediately
startTransition(async () => {
// Fetch and update results
const data = await fetchResults(value);
setResults(data);
});
};
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
);
}
```
**Benefits:**
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
- **Error resilience**: Pending state correctly resets even if the transition throws
- **Better responsiveness**: Keeps the UI responsive during updates
- **Interrupt handling**: New transitions automatically cancel pending ones
Reference: [useTransition](https://react.dev/reference/react/useTransition)
@@ -1,39 +0,0 @@
---
title: Defer State Reads to Usage Point
impact: MEDIUM
impactDescription: avoids unnecessary subscriptions
tags: rerender, searchParams, localStorage, optimization
---
## Defer State Reads to Usage Point
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
**Incorrect (subscribes to all searchParams changes):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const searchParams = useSearchParams();
const handleShare = () => {
const ref = searchParams.get("ref");
shareChat(chatId, { ref });
};
return <button onClick={handleShare}>Share</button>;
}
```
**Correct (reads on demand, no subscription):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const handleShare = () => {
const params = new URLSearchParams(window.location.search);
const ref = params.get("ref");
shareChat(chatId, { ref });
};
return <button onClick={handleShare}>Share</button>;
}
```
@@ -1,45 +0,0 @@
---
title: Narrow Effect Dependencies
impact: LOW
impactDescription: minimizes effect re-runs
tags: rerender, useEffect, dependencies, optimization
---
## Narrow Effect Dependencies
Specify primitive dependencies instead of objects to minimize effect re-runs.
**Incorrect (re-runs on any user field change):**
```tsx
useEffect(() => {
console.log(user.id);
}, [user]);
```
**Correct (re-runs only when id changes):**
```tsx
useEffect(() => {
console.log(user.id);
}, [user.id]);
```
**For derived state, compute outside effect:**
```tsx
// Incorrect: runs on width=767, 766, 765...
useEffect(() => {
if (width < 768) {
enableMobileMode();
}
}, [width]);
// Correct: runs only on boolean transition
const isMobile = width < 768;
useEffect(() => {
if (isMobile) {
enableMobileMode();
}
}, [isMobile]);
```
@@ -1,40 +0,0 @@
---
title: Calculate Derived State During Rendering
impact: MEDIUM
impactDescription: avoids redundant renders and state drift
tags: rerender, derived-state, useEffect, state
---
## Calculate Derived State During Rendering
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
**Incorrect (redundant state and effect):**
```tsx
function Form() {
const [firstName, setFirstName] = useState("First");
const [lastName, setLastName] = useState("Last");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);
return <p>{fullName}</p>;
}
```
**Correct (derive during render):**
```tsx
function Form() {
const [firstName, setFirstName] = useState("First");
const [lastName, setLastName] = useState("Last");
const fullName = firstName + " " + lastName;
return <p>{fullName}</p>;
}
```
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
@@ -1,29 +0,0 @@
---
title: Subscribe to Derived State
impact: MEDIUM
impactDescription: reduces re-render frequency
tags: rerender, derived-state, media-query, optimization
---
## Subscribe to Derived State
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
**Incorrect (re-renders on every pixel change):**
```tsx
function Sidebar() {
const width = useWindowWidth(); // updates continuously
const isMobile = width < 768;
return <nav className={isMobile ? "mobile" : "desktop"} />;
}
```
**Correct (re-renders only when boolean changes):**
```tsx
function Sidebar() {
const isMobile = useMediaQuery("(max-width: 767px)");
return <nav className={isMobile ? "mobile" : "desktop"} />;
}
```
@@ -1,77 +0,0 @@
---
title: Use Functional setState Updates
impact: MEDIUM
impactDescription: prevents stale closures and unnecessary callback recreations
tags: react, hooks, useState, useCallback, callbacks, closures
---
## Use Functional setState Updates
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
**Incorrect (requires state as dependency):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems);
// Callback must depend on items, recreated on every items change
const addItems = useCallback(
(newItems: Item[]) => {
setItems([...items, ...newItems]);
},
[items],
); // ❌ items dependency causes recreations
// Risk of stale closure if dependency is forgotten
const removeItem = useCallback((id: string) => {
setItems(items.filter((item) => item.id !== id));
}, []); // ❌ Missing items dependency - will use stale items!
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />;
}
```
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
**Correct (stable callbacks, no stale closures):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems);
// Stable callback, never recreated
const addItems = useCallback((newItems: Item[]) => {
setItems((curr) => [...curr, ...newItems]);
}, []); // ✅ No dependencies needed
// Always uses latest state, no stale closure risk
const removeItem = useCallback((id: string) => {
setItems((curr) => curr.filter((item) => item.id !== id));
}, []); // ✅ Safe and stable
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />;
}
```
**Benefits:**
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
2. **No stale closures** - Always operates on the latest state value
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
**When to use functional updates:**
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
**When direct updates are fine:**
- Setting state to a static value: `setCount(0)`
- Setting state from props/arguments only: `setName(newName)`
- State doesn't depend on previous value
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
@@ -1,58 +0,0 @@
---
title: Use Lazy State Initialization
impact: MEDIUM
impactDescription: wasted computation on every render
tags: react, hooks, useState, performance, initialization
---
## Use Lazy State Initialization
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
**Incorrect (runs on every render):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items));
const [query, setQuery] = useState("");
// When query changes, buildSearchIndex runs again unnecessarily
return <SearchResults index={searchIndex} query={query} />;
}
function UserProfile() {
// JSON.parse runs on every render
const [settings, setSettings] = useState(
JSON.parse(localStorage.getItem("settings") || "{}"),
);
return <SettingsForm settings={settings} onChange={setSettings} />;
}
```
**Correct (runs only once):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs ONLY on initial render
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items));
const [query, setQuery] = useState("");
return <SearchResults index={searchIndex} query={query} />;
}
function UserProfile() {
// JSON.parse runs only on initial render
const [settings, setSettings] = useState(() => {
const stored = localStorage.getItem("settings");
return stored ? JSON.parse(stored) : {};
});
return <SettingsForm settings={settings} onChange={setSettings} />;
}
```
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
@@ -1,36 +0,0 @@
---
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
impact: MEDIUM
impactDescription: restores memoization by using a constant for default value
tags: rerender, memo, optimization
---
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
To address this issue, extract the default value into a constant.
**Incorrect (`onClick` has different values on every rerender):**
```tsx
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
**Correct (stable default value):**
```tsx
const NOOP = () => {};
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
@@ -1,44 +0,0 @@
---
title: Extract to Memoized Components
impact: MEDIUM
impactDescription: enables early returns
tags: rerender, memo, useMemo, optimization
---
## Extract to Memoized Components
Extract expensive work into memoized components to enable early returns before computation.
**Incorrect (computes avatar even when loading):**
```tsx
function Profile({ user, loading }: Props) {
const avatar = useMemo(() => {
const id = computeAvatarId(user);
return <Avatar id={id} />;
}, [user]);
if (loading) return <Skeleton />;
return <div>{avatar}</div>;
}
```
**Correct (skips computation when loading):**
```tsx
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user]);
return <Avatar id={id} />;
});
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />;
return (
<div>
<UserAvatar user={user} />
</div>
);
}
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
@@ -1,45 +0,0 @@
---
title: Put Interaction Logic in Event Handlers
impact: MEDIUM
impactDescription: avoids effect re-runs and duplicate side effects
tags: rerender, useEffect, events, side-effects, dependencies
---
## Put Interaction Logic in Event Handlers
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
**Incorrect (event modeled as state + effect):**
```tsx
function Form() {
const [submitted, setSubmitted] = useState(false);
const theme = useContext(ThemeContext);
useEffect(() => {
if (submitted) {
post("/api/register");
showToast("Registered", theme);
}
}, [submitted, theme]);
return <button onClick={() => setSubmitted(true)}>Submit</button>;
}
```
**Correct (do it in the handler):**
```tsx
function Form() {
const theme = useContext(ThemeContext);
function handleSubmit() {
post("/api/register");
showToast("Registered", theme);
}
return <button onClick={handleSubmit}>Submit</button>;
}
```
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
@@ -1,83 +0,0 @@
---
title: Don't Define Components Inside Components
impact: HIGH
impactDescription: prevents remount on every render
tags: rerender, components, remount, performance
---
## Don't Define Components Inside Components
**Impact: HIGH (prevents remount on every render)**
Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
A common reason developers do this is to access parent variables without passing props. Always pass props instead.
**Incorrect (remounts on every render):**
```tsx
function UserProfile({ user, theme }) {
// Defined inside to access `theme` - BAD
const Avatar = () => (
<img
src={user.avatarUrl}
className={theme === "dark" ? "avatar-dark" : "avatar-light"}
/>
);
// Defined inside to access `user` - BAD
const Stats = () => (
<div>
<span>{user.followers} followers</span>
<span>{user.posts} posts</span>
</div>
);
return (
<div>
<Avatar />
<Stats />
</div>
);
}
```
Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
**Correct (pass props instead):**
```tsx
function Avatar({ src, theme }: { src: string; theme: string }) {
return (
<img
src={src}
className={theme === "dark" ? "avatar-dark" : "avatar-light"}
/>
);
}
function Stats({ followers, posts }: { followers: number; posts: number }) {
return (
<div>
<span>{followers} followers</span>
<span>{posts} posts</span>
</div>
);
}
function UserProfile({ user, theme }) {
return (
<div>
<Avatar src={user.avatarUrl} theme={theme} />
<Stats followers={user.followers} posts={user.posts} />
</div>
);
}
```
**Symptoms of this bug:**
- Input fields lose focus on every keystroke
- Animations restart unexpectedly
- `useEffect` cleanup/setup runs on every parent render
- Scroll position resets inside the component
@@ -1,35 +0,0 @@
---
title: Do not wrap a simple expression with a primitive result type in useMemo
impact: LOW-MEDIUM
impactDescription: wasted computation on every render
tags: rerender, useMemo, optimization
---
## Do not wrap a simple expression with a primitive result type in useMemo
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
**Incorrect:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = useMemo(() => {
return user.isLoading || notifications.isLoading;
}, [user.isLoading, notifications.isLoading]);
if (isLoading) return <Skeleton />;
// return some markup
}
```
**Correct:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = user.isLoading || notifications.isLoading;
if (isLoading) return <Skeleton />;
// return some markup
}
```
@@ -1,64 +0,0 @@
---
title: Split Combined Hook Computations
impact: MEDIUM
impactDescription: avoids recomputing independent steps
tags: rerender, useMemo, useEffect, dependencies, optimization
---
## Split Combined Hook Computations
When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
**Incorrect (changing `sortOrder` recomputes filtering):**
```tsx
const sortedProducts = useMemo(() => {
const filtered = products.filter((p) => p.category === category);
const sorted = filtered.toSorted((a, b) =>
sortOrder === "asc" ? a.price - b.price : b.price - a.price,
);
return sorted;
}, [products, category, sortOrder]);
```
**Correct (filtering only recomputes when products or category change):**
```tsx
const filteredProducts = useMemo(
() => products.filter((p) => p.category === category),
[products, category],
);
const sortedProducts = useMemo(
() =>
filteredProducts.toSorted((a, b) =>
sortOrder === "asc" ? a.price - b.price : b.price - a.price,
),
[filteredProducts, sortOrder],
);
```
This pattern also applies to `useEffect` when combining unrelated side effects:
**Incorrect (both effects run when either dependency changes):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname);
document.title = `${pageTitle} | My App`;
}, [pathname, pageTitle]);
```
**Correct (effects run independently):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname);
}, [pathname]);
useEffect(() => {
document.title = `${pageTitle} | My App`;
}, [pageTitle]);
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
@@ -1,40 +0,0 @@
---
title: Use Transitions for Non-Urgent Updates
impact: MEDIUM
impactDescription: maintains UI responsiveness
tags: rerender, transitions, startTransition, performance
---
## Use Transitions for Non-Urgent Updates
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
**Incorrect (blocks UI on every scroll):**
```tsx
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const handler = () => setScrollY(window.scrollY);
window.addEventListener("scroll", handler, { passive: true });
return () => window.removeEventListener("scroll", handler);
}, []);
}
```
**Correct (non-blocking updates):**
```tsx
import { startTransition } from "react";
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const handler = () => {
startTransition(() => setScrollY(window.scrollY));
};
window.addEventListener("scroll", handler, { passive: true });
return () => window.removeEventListener("scroll", handler);
}, []);
}
```
@@ -1,59 +0,0 @@
---
title: Use useDeferredValue for Expensive Derived Renders
impact: MEDIUM
impactDescription: keeps input responsive during heavy computation
tags: rerender, useDeferredValue, optimization, concurrent
---
## Use useDeferredValue for Expensive Derived Renders
When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
**Incorrect (input feels laggy while filtering):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState("");
const filtered = items.filter((item) => fuzzyMatch(item, query));
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<ResultsList results={filtered} />
</>
);
}
```
**Correct (input stays snappy, results render when ready):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const filtered = useMemo(
() => items.filter((item) => fuzzyMatch(item, deferredQuery)),
[items, deferredQuery],
);
const isStale = query !== deferredQuery;
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.7 : 1 }}>
<ResultsList results={filtered} />
</div>
</>
);
}
```
**When to use:**
- Filtering/searching large lists
- Expensive visualizations (charts, graphs) reacting to input
- Any derived state that causes noticeable render delays
**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
@@ -1,73 +0,0 @@
---
title: Use useRef for Transient Values
impact: MEDIUM
impactDescription: avoids unnecessary re-renders on frequent updates
tags: rerender, useref, state, performance
---
## Use useRef for Transient Values
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
**Incorrect (renders every update):**
```tsx
function Tracker() {
const [lastX, setLastX] = useState(0);
useEffect(() => {
const onMove = (e: MouseEvent) => setLastX(e.clientX);
window.addEventListener("mousemove", onMove);
return () => window.removeEventListener("mousemove", onMove);
}, []);
return (
<div
style={{
position: "fixed",
top: 0,
left: lastX,
width: 8,
height: 8,
background: "black",
}}
/>
);
}
```
**Correct (no re-render for tracking):**
```tsx
function Tracker() {
const lastXRef = useRef(0);
const dotRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const onMove = (e: MouseEvent) => {
lastXRef.current = e.clientX;
const node = dotRef.current;
if (node) {
node.style.transform = `translateX(${e.clientX}px)`;
}
};
window.addEventListener("mousemove", onMove);
return () => window.removeEventListener("mousemove", onMove);
}, []);
return (
<div
ref={dotRef}
style={{
position: "fixed",
top: 0,
left: 0,
width: 8,
height: 8,
background: "black",
transform: "translateX(0px)",
}}
/>
);
}
```
@@ -1,74 +0,0 @@
---
title: Use after() for Non-Blocking Operations
impact: MEDIUM
impactDescription: faster response times
tags: server, async, logging, analytics, side-effects
---
## Use after() for Non-Blocking Operations
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
**Incorrect (blocks response):**
```tsx
import { logUserAction } from "@/app/utils";
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request);
// Logging blocks the response
const userAgent = request.headers.get("user-agent") || "unknown";
await logUserAction({ userAgent });
return new Response(JSON.stringify({ status: "success" }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
```
**Correct (non-blocking):**
```tsx
import { after } from "next/server";
import { headers, cookies } from "next/headers";
import { logUserAction } from "@/app/utils";
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request);
// Log after response is sent
after(async () => {
const userAgent = (await headers()).get("user-agent") || "unknown";
const sessionCookie =
(await cookies()).get("session-id")?.value || "anonymous";
logUserAction({ sessionCookie, userAgent });
});
return new Response(JSON.stringify({ status: "success" }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
```
The response is sent immediately while logging happens in the background.
**Common use cases:**
- Analytics tracking
- Audit logging
- Sending notifications
- Cache invalidation
- Cleanup tasks
**Important notes:**
- `after()` runs even if the response fails or redirects
- Works in Server Actions, Route Handlers, and Server Components
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
@@ -1,96 +0,0 @@
---
title: Authenticate Server Actions Like API Routes
impact: CRITICAL
impactDescription: prevents unauthorized access to server mutations
tags: server, server-actions, authentication, security, authorization
---
## Authenticate Server Actions Like API Routes
**Impact: CRITICAL (prevents unauthorized access to server mutations)**
Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
**Incorrect (no authentication check):**
```typescript
"use server";
export async function deleteUser(userId: string) {
// Anyone can call this! No auth check
await db.user.delete({ where: { id: userId } });
return { success: true };
}
```
**Correct (authentication inside the action):**
```typescript
"use server";
import { verifySession } from "@/lib/auth";
import { unauthorized } from "@/lib/errors";
export async function deleteUser(userId: string) {
// Always check auth inside the action
const session = await verifySession();
if (!session) {
throw unauthorized("Must be logged in");
}
// Check authorization too
if (session.user.role !== "admin" && session.user.id !== userId) {
throw unauthorized("Cannot delete other users");
}
await db.user.delete({ where: { id: userId } });
return { success: true };
}
```
**With input validation:**
```typescript
"use server";
import { verifySession } from "@/lib/auth";
import { z } from "zod";
const updateProfileSchema = z.object({
userId: z.string().uuid(),
name: z.string().min(1).max(100),
email: z.string().email(),
});
export async function updateProfile(data: unknown) {
// Validate input first
const validated = updateProfileSchema.parse(data);
// Then authenticate
const session = await verifySession();
if (!session) {
throw new Error("Unauthorized");
}
// Then authorize
if (session.user.id !== validated.userId) {
throw new Error("Can only update own profile");
}
// Finally perform the mutation
await db.user.update({
where: { id: validated.userId },
data: {
name: validated.name,
email: validated.email,
},
});
return { success: true };
}
```
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
@@ -1,41 +0,0 @@
---
title: Cross-Request LRU Caching
impact: HIGH
impactDescription: caches across requests
tags: server, cache, lru, cross-request
---
## Cross-Request LRU Caching
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
**Implementation:**
```typescript
import { LRUCache } from "lru-cache";
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 5 * 60 * 1000, // 5 minutes
});
export async function getUser(id: string) {
const cached = cache.get(id);
if (cached) return cached;
const user = await db.user.findUnique({ where: { id } });
cache.set(id, user);
return user;
}
// Request 1: DB query, result cached
// Request 2: cache hit, no DB query
```
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
@@ -1,76 +0,0 @@
---
title: Per-Request Deduplication with React.cache()
impact: MEDIUM
impactDescription: deduplicates within request
tags: server, cache, react-cache, deduplication
---
## Per-Request Deduplication with React.cache()
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
**Usage:**
```typescript
import { cache } from "react";
export const getCurrentUser = cache(async () => {
const session = await auth();
if (!session?.user?.id) return null;
return await db.user.findUnique({
where: { id: session.user.id },
});
});
```
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
**Avoid inline objects as arguments:**
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
**Incorrect (always cache miss):**
```typescript
const getUser = cache(async (params: { uid: number }) => {
return await db.user.findUnique({ where: { id: params.uid } });
});
// Each call creates new object, never hits cache
getUser({ uid: 1 });
getUser({ uid: 1 }); // Cache miss, runs query again
```
**Correct (cache hit):**
```typescript
const getUser = cache(async (uid: number) => {
return await db.user.findUnique({ where: { id: uid } });
});
// Primitive args use value equality
getUser(1);
getUser(1); // Cache hit, returns cached result
```
If you must pass objects, pass the same reference:
```typescript
const params = { uid: 1 };
getUser(params); // Query runs
getUser(params); // Cache hit (same reference)
```
**Next.js-Specific Note:**
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
- Database queries (Prisma, Drizzle, etc.)
- Heavy computations
- Authentication checks
- File system operations
- Any non-fetch async work
Use `React.cache()` to deduplicate these operations across your component tree.
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
@@ -1,65 +0,0 @@
---
title: Avoid Duplicate Serialization in RSC Props
impact: LOW
impactDescription: reduces network payload by avoiding duplicate serialization
tags: server, rsc, serialization, props, client-components
---
## Avoid Duplicate Serialization in RSC Props
**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
**Incorrect (duplicates array):**
```tsx
// RSC: sends 6 strings (2 arrays × 3 items)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
```
**Correct (sends 3 strings):**
```tsx
// RSC: send once
<ClientList usernames={usernames} />;
// Client: transform there
("use client");
const sorted = useMemo(() => [...usernames].sort(), [usernames]);
```
**Nested deduplication behavior:**
Deduplication works recursively. Impact varies by data type:
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
```tsx
// string[] - duplicates everything
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
// object[] - duplicates array structure only
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
```
**Operations breaking deduplication (create new references):**
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
**More examples:**
```tsx
// ❌ Bad
<C users={users} active={users.filter(u => u.active)} />
<C product={product} productName={product.name} />
// ✅ Good
<C users={users} />
<C product={product} />
// Do filtering/destructuring in client
```
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
@@ -1,145 +0,0 @@
---
title: Hoist Static I/O to Module Level
impact: HIGH
impactDescription: avoids repeated file/network I/O per request
tags: server, io, performance, next.js, route-handlers, og-image
---
## Hoist Static I/O to Module Level
**Impact: HIGH (avoids repeated file/network I/O per request)**
When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
**Incorrect (reads font file on every request):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
export async function GET(request: Request) {
// Runs on EVERY request - expensive!
const fontData = await fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = await fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Correct (loads once at module initialization):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
// Module-level: runs ONCE when module is first imported
const fontData = fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
export async function GET(request: Request) {
// Await the already-started promises
const [font, logo] = await Promise.all([fontData, logoData])
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logo} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: font }] }
)
}
```
**Correct (synchronous fs at module level):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
import { readFileSync } from 'fs'
import { join } from 'path'
// Synchronous read at module level - blocks only during module init
const fontData = readFileSync(
join(process.cwd(), 'public/fonts/Inter.ttf')
)
const logoData = readFileSync(
join(process.cwd(), 'public/images/logo.png')
)
export async function GET(request: Request) {
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Incorrect (reads config on every call):**
```typescript
import fs from "node:fs/promises";
export async function processRequest(data: Data) {
const config = JSON.parse(await fs.readFile("./config.json", "utf-8"));
const template = await fs.readFile("./template.html", "utf-8");
return render(template, data, config);
}
```
**Correct (hoists config and template to module level):**
```typescript
import fs from "node:fs/promises";
const configPromise = fs.readFile("./config.json", "utf-8").then(JSON.parse);
const templatePromise = fs.readFile("./template.html", "utf-8");
export async function processRequest(data: Data) {
const [config, template] = await Promise.all([
configPromise,
templatePromise,
]);
return render(template, data, config);
}
```
When to use this pattern:
- Loading fonts for OG image generation
- Loading static logos, icons, or watermarks
- Reading configuration files that don't change at runtime
- Loading email templates or other static templates
- Any static asset that's the same across all requests
When not to use this pattern:
- Assets that vary per request or user
- Files that may change during runtime (use caching with TTL instead)
- Large files that would consume too much memory if kept loaded
- Sensitive data that shouldn't persist in memory
With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
@@ -1,83 +0,0 @@
---
title: Parallel Data Fetching with Component Composition
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, composition
---
## Parallel Data Fetching with Component Composition
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
**Incorrect (Sidebar waits for Page's fetch to complete):**
```tsx
export default async function Page() {
const header = await fetchHeader();
return (
<div>
<div>{header}</div>
<Sidebar />
</div>
);
}
async function Sidebar() {
const items = await fetchSidebarItems();
return <nav>{items.map(renderItem)}</nav>;
}
```
**Correct (both fetch simultaneously):**
```tsx
async function Header() {
const data = await fetchHeader();
return <div>{data}</div>;
}
async function Sidebar() {
const items = await fetchSidebarItems();
return <nav>{items.map(renderItem)}</nav>;
}
export default function Page() {
return (
<div>
<Header />
<Sidebar />
</div>
);
}
```
**Alternative with children prop:**
```tsx
async function Header() {
const data = await fetchHeader();
return <div>{data}</div>;
}
async function Sidebar() {
const items = await fetchSidebarItems();
return <nav>{items.map(renderItem)}</nav>;
}
function Layout({ children }: { children: ReactNode }) {
return (
<div>
<Header />
{children}
</div>
);
}
export default function Page() {
return (
<Layout>
<Sidebar />
</Layout>
);
}
```
@@ -1,32 +0,0 @@
---
title: Parallel Nested Data Fetching
impact: CRITICAL
impactDescription: eliminates server-side waterfalls
tags: server, rsc, parallel-fetching, promise-chaining
---
## Parallel Nested Data Fetching
When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
**Incorrect (a single slow item blocks all nested fetches):**
```tsx
const chats = await Promise.all(chatIds.map((id) => getChat(id)));
const chatAuthors = await Promise.all(
chats.map((chat) => getUser(chat.author)),
);
```
If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
**Correct (each item chains its own nested fetch):**
```tsx
const chatAuthors = await Promise.all(
chatIds.map((id) => getChat(id).then((chat) => getUser(chat.author))),
);
```
Each item independently chains `getChat``getUser`, so a slow chat doesn't block author fetches for the others.
@@ -1,38 +0,0 @@
---
title: Minimize Serialization at RSC Boundaries
impact: HIGH
impactDescription: reduces data transfer size
tags: server, rsc, serialization, props
---
## Minimize Serialization at RSC Boundaries
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
**Incorrect (serializes all 50 fields):**
```tsx
async function Page() {
const user = await fetchUser(); // 50 fields
return <Profile user={user} />;
}
("use client");
function Profile({ user }: { user: User }) {
return <div>{user.name}</div>; // uses 1 field
}
```
**Correct (serializes only 1 field):**
```tsx
async function Page() {
const user = await fetchUser();
return <Profile name={user.name} />;
}
("use client");
function Profile({ name }: { name: string }) {
return <div>{name}</div>;
}
```
+40
View File
@@ -0,0 +1,40 @@
acodec
adblocker
ahooks
antd
behaviour
bili
bilibili
bodys
cancle
cliqz
commitlint
Conpty
consola
conventionalcommits
datetime
DDTHH
execa
immer
inversify
KHTML
languagedetector
localforage
mediago
metas
nocheck
optimizelegibility
pinia
redownload
Redownload
reduxjs
Sider
stylelint
svgz
TDAPP
tiptap
typeorm
vuedraggable
vuejs
watting
Watting
-22
View File
@@ -1,22 +0,0 @@
**/node_modules
**/build
**/dist
**/release
**/.turbo
**/.git
**/.claude
**/.deps
*.md
# Go build artifacts
apps/core/bin/
apps/core/server
# Electron source (not needed, but keep package.json files for workspace/build)
apps/electron/src/
apps/electron/scripts/
docs/
# OS files
.DS_Store
**/.DS_Store
+15 -15
View File
@@ -1,15 +1,15 @@
# http://editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = 80
trim_trailing_whitespace = true
[*.md]
max_line_length = 0
trim_trailing_whitespace = false
# http://editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = 80
trim_trailing_whitespace = true
[*.md]
max_line_length = 0
trim_trailing_whitespace = false
+3 -2
View File
@@ -1,3 +1,4 @@
APP_NAME=mediago-community
APP_ID=mediago.caorushizi.cn
APP_NAME=mediago
APP_ID=mediago.ziying.site
APP_COPYRIGHT=caorushizi
APP_VERSION=2.2.1
+2 -1
View File
@@ -1,5 +1,6 @@
APP_TD_APPID=
APP_SENTRY_DSN=
APP_CLARITY_APPID=
GH_TOKEN=
LOAD_DEVTOOLS=
DEBUG_PLUGINS=true
+2 -1
View File
@@ -1,4 +1,5 @@
APP_TD_APPID=
APP_SENTRY_DSN=
APP_CLARITY_APPID=
GH_TOKEN=
DEBUG_PLUGINS=false
-3
View File
@@ -1,3 +0,0 @@
# Shell scripts MUST keep LF endings — CRLF from Windows checkouts breaks
# /bin/sh inside Linux containers (`/bin/sh^M: bad interpreter`).
*.sh text eol=lf
-58
View File
@@ -1,58 +0,0 @@
# GitHub Copilot Instruction: Code Review and Optimization
## Role and Objective
You are a **top-tier software architect and performance optimization expert**.
Your goal is to help me — a senior TypeScript full-stack engineer — elevate the quality of my code to a new level.
When reviewing my code, **do not explain basic concepts**. I need **precise, deep, and forward-thinking insights**.
Your core mission is **optimization**, including but not limited to:
- **Performance improvement**: Identify and optimize performance bottlenecks, reduce unnecessary computation and resource consumption.
- **Code refactoring**: Suggest more elegant and efficient implementations to improve code structure.
- **Design patterns**: Identify opportunities to apply or refine design patterns to enhance scalability and maintainability.
- **Best practices**: Ensure the code adheres to the latest best practices for the TypeScript ecosystem (Node.js, React, API layers, build pipelines).
- **Potential risks**: Anticipate and highlight deep issues such as concurrency problems, security vulnerabilities, or resource leaks.
---
## Review Perspective and Principles
1. **High-Standard Review**
Review the code as if it were going to **production for millions of users** and needs to be **maintained long-term**.
2. **Deep Analysis, Not Surface Advice**
Dont focus on trivial issues like typos or syntax sugar.
Instead, explain **why** a refactor or change matters — e.g.:
> “Switching from a synchronous file read to `fs.promises` can free the event loop, improving throughput under load.”
3. **Performance First**
- Evaluate time and space complexity; suggest algorithmic or structural improvements.
- Examine I/O, database queries, and network calls for efficiency — recommend batching, caching, or async processing.
- Recommend appropriate data structures or API strategies for scalability (e.g., pagination, streaming responses).
4. **Architecture and Design**
- Follow **SOLID** principles. Explicitly identify violations and propose refactoring approaches.
- Encourage **composition over inheritance** and **dependency injection**.
- Suggest modularization and clear separation between layers (e.g., API, service, repository, UI).
5. **Code Style and Standards**
- Code must be clear, consistent, and self-explanatory.
- Follow the projects existing conventions unless the change brings substantial clarity or performance gain.
- For complex logic, suggest adding comments explaining the **rationale (“why”)**, not just the **action (“what”)**.
---
## Specific Instructions
- **When reviewing code, include the optimized code snippet directly**, with short comments highlighting key changes and their reasoning.
- **If you find potential bugs or unhandled edge cases**, explicitly point them out and provide a fix suggestion.
- **Avoid subjective stylistic comments** unless they impact clarity, performance, or maintainability.
- **When I ask “Can this code be optimized?”**, provide a holistic evaluation covering performance, readability, scalability, and maintainability.
---
At the end of every response, please add:
> “AI-generated suggestions may contain errors; use your own judgment when applying them.”
-72
View File
@@ -1,72 +0,0 @@
# build.yml
# Workflow's name
name: Build MediaGo App
# Workflow's trigger
on:
workflow_dispatch:
# Workflow's jobs
jobs:
# job's id
release:
# job's name
name: build and release electron app
# the type of machine to run the job on
runs-on: ${{ matrix.os }}
# create a build matrix for jobs
strategy:
fail-fast: false
matrix:
os: [windows-latest, macos-latest, macos-15-intel, ubuntu-latest]
# create steps
steps:
- name: Check out git repository
uses: actions/checkout@v6
- uses: pnpm/action-setup@v5
with:
version: "10.15.0"
run_install: false
- name: Install Node.js
uses: actions/setup-node@v6
with:
node-version: "24.14.0"
cache: "pnpm"
- name: Install Python
uses: actions/setup-python@v6
with:
python-version: "3.10"
- name: Setup Go
uses: actions/setup-go@v6
with:
go-version: "1.25.0"
cache-dependency-path: |
apps/core/go.sum
- name: Install swag
run: go install github.com/swaggo/swag/cmd/swag@latest
- name: Install dependencies
run: pnpm install
- name: Download third-party deps
run: pnpm deps:download
- name: Build & release app
run: pnpm release:electron
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}
APP_TD_APPID: ${{ secrets.APP_TD_APPID }}
- uses: actions/upload-artifact@v6
with:
name: mediago-${{ matrix.os }}
path: apps/electron/release/mediago-*
-153
View File
@@ -1,153 +0,0 @@
name: Build & Push Docker Image
on:
workflow_dispatch:
inputs:
tag:
description: "Image tag to publish under (e.g. 3.5.0 to rebuild a released version, or 3.5.0-fix.1 for a side-by-side). Leave blank for dev-<run_id>."
required: false
type: string
push_latest:
description: "Also tag the resulting image as `latest` (use when rebuilding a stable release)."
required: false
type: boolean
default: false
push:
tags:
- "v*"
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
# Docker Hub mirror — same image, different registry. Credentials
# come from the DOCKERHUB_USERNAME / DOCKERHUB_TOKEN secrets (token,
# not account password). If either secret is empty, the Docker Hub
# login step is skipped and only GHCR gets pushed.
DOCKERHUB_IMAGE: caorushizi/mediago
jobs:
docker:
name: Build and push multi-arch image
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# GitHub Actions forbids `secrets.*` inside `if:` expressions
# directly — it fails with `Unrecognized named-value: 'secrets'`.
# The blessed workaround: pull the secret through `env:` (which
# IS allowed) inside a single check step, write a boolean to
# step outputs, and have every downstream step guard on the
# output instead of the raw secret.
- name: Detect Docker Hub credentials
id: dockerhub
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
run: |
if [ -n "$DOCKERHUB_USERNAME" ] && [ -n "$DOCKERHUB_TOKEN" ]; then
echo "enabled=true" >> "$GITHUB_OUTPUT"
else
echo "enabled=false" >> "$GITHUB_OUTPUT"
fi
# Only log in (and later push) to Docker Hub when both secrets are
# configured. Lets forks / trial runs without Docker Hub
# credentials still build-and-push to GHCR.
- name: Login to Docker Hub
if: steps.dockerhub.outputs.enabled == 'true'
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
# Compose the list of target images based on which registries we
# actually have credentials for. Without this, metadata-action
# would always generate Docker Hub tags and build-push-action
# would then fail with 401 on forks that haven't set the secrets.
- name: Resolve image targets
id: targets
run: |
{
echo "images<<EOF"
echo "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
if [ "${{ steps.dockerhub.outputs.enabled }}" = "true" ]; then
echo "${{ env.DOCKERHUB_IMAGE }}"
fi
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ steps.targets.outputs.images }}
tags: |
# 1. Manual rebuild with an explicit tag (e.g. `3.5.0`, `3.5.0-fix.1`)
type=raw,value=${{ inputs.tag }},enable=${{ inputs.tag != '' }}
# 2. Tag push: v1.0.0 → 1.0.0
type=semver,pattern={{version}}
# 3. `latest`: on stable semver tag pushes, or when the manual
# rebuild explicitly asks for it
type=raw,value=latest,enable=${{ (startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta')) || inputs.push_latest }}
# 4. Fallback for manual triggers with no custom tag
type=raw,value=dev-${{ github.run_id }},enable=${{ !startsWith(github.ref, 'refs/tags/') && inputs.tag == '' }}
- name: Build and push
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
# `metadata-action` already emits the standard OCI labels
# (image.title / description / source / licenses / version /
# revision / created). `revision` uses github.sha, so two
# builds that re-use a tag are distinguishable via
# `docker inspect`.
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Build Summary
run: |
echo "### 🎉 Docker Image Published" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Registries:**" >> $GITHUB_STEP_SUMMARY
echo "- \`${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
if [ "${{ steps.dockerhub.outputs.enabled }}" = "true" ]; then
echo "- \`docker.io/${{ env.DOCKERHUB_IMAGE }}\`" >> $GITHUB_STEP_SUMMARY
fi
echo "**Platforms:** linux/amd64, linux/arm64" >> $GITHUB_STEP_SUMMARY
echo "**Version:** \`${{ steps.meta.outputs.version }}\`" >> $GITHUB_STEP_SUMMARY
echo "**Commit:** \`${{ github.sha }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Tags:**" >> $GITHUB_STEP_SUMMARY
echo "${{ steps.meta.outputs.tags }}" | while read tag; do
echo "- \`${tag}\`" >> $GITHUB_STEP_SUMMARY
done
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Pull:**" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
echo "docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }}" >> $GITHUB_STEP_SUMMARY
if [ "${{ steps.dockerhub.outputs.enabled }}" = "true" ]; then
echo "docker pull ${{ env.DOCKERHUB_IMAGE }}:${{ steps.meta.outputs.version }}" >> $GITHUB_STEP_SUMMARY
fi
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
+63
View File
@@ -0,0 +1,63 @@
# build.yml
# Workflow's name
name: Build Downloader App.
# Workflow's trigger
on:
push:
branches:
- master
# Workflow's jobs
jobs:
# job's id
release:
# job's name
name: build and release electron app
# the type of machine to run the job on
runs-on: ${{ matrix.os }}
# create a build matrix for jobs
strategy:
fail-fast: false
matrix:
os: [windows-latest, macos-latest, ubuntu-latest]
# create steps
steps:
# step1: check out repository
- name: Check out git repository
uses: actions/checkout@v4
# step2: install node env
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: 20
# step4: install python env
- name: Install Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
# step5: install pnpm env
- uses: pnpm/action-setup@v3
with:
version: latest
run_install: true
standalone: true
- name: Build & release app
run: pnpm run release
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}
APP_TD_APPID: ${{ secrets.APP_TD_APPID }}
APP_CLARITY_APPID: ${{ secrets.APP_CLARITY_APPID}}
- uses: actions/upload-artifact@v4
with:
name: mediago-${{ matrix.os }}
path: packages/main/release/mediago-setup-*
@@ -1,10 +1,7 @@
name: Deploy MediaGo Docs
name: Deploy Downloader Docs.
on:
push:
paths:
- "docs/**"
- ".github/workflows/build-docs.yml"
branches: ["master"]
workflow_dispatch:
@@ -21,39 +18,34 @@ concurrency:
env:
BUCKET: downloader-docs
ENDPOINT: oss-cn-beijing.aliyuncs.com
ACCESS_KEY: LTAI5tDrRjFUAvufpCJioz3b
ACCESS_KEY: LTAI5tLckcUrBtj7bCiUYwWz
ACCESS_KEY_SECRET: ${{ secrets.ACCESS_KEY_SECRET }}
jobs:
build:
name: Build Docs
name: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- uses: pnpm/action-setup@v5
with:
version: "10.15.0"
run_install: false
standalone: true
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version: "24.14.0"
cache: "pnpm"
node-version: 20
- name: Install dependencies
run: pnpm install
- uses: pnpm/action-setup@v3
with:
version: latest
run_install: true
- name: Build with Vitepress
run: pnpm docs:build
run: pnpm run docs:build
- name: Install Alibaba Cloud ossutil
- name: Install Alibaba Cloud OSSUTIL
run: wget http://gosspublic.alicdn.com/ossutil/1.6.10/ossutil64 && chmod +x ossutil64
- name: Configure Alibaba Cloud ossutil
- name: Configure Alibaba Cloud OSSUTIL
run: ./ossutil64 config -i ${ACCESS_KEY} -k ${ACCESS_KEY_SECRET} -e ${ENDPOINT} -c .ossutilconfig
- name: Upload the web folder to the chosen OSS bucket
+1 -17
View File
@@ -2,21 +2,5 @@ node_modules
*.local
.idea
.parcel-cache
.vitepress
*.tsno.mjs
.DS_Store
log
.turbo
.claude
.store
release
go.work.sum
apps/core/bin/
apps/electron/bin/
apps/main/bin/
.deps/
tmp/
# Local planning notes that should not be published with the open-source repo.
docs/.vitepress/seo-keyword-map*.md
docs/.vitepress/private/
+13
View File
@@ -0,0 +1,13 @@
{
"extends": [
"development"
],
"hints": {
"axe/text-alternatives": [
"default",
{
"image-alt": "off"
}
]
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no -- commitlint --edit ${1}
npm run commitlint ${1}
+4 -1
View File
@@ -1 +1,4 @@
lint-staged
#!/usr/bin/env sh
. "$(dirname "$0")/_/husky.sh"
npx tsx ./scripts/pre-commit.ts
+3
View File
@@ -0,0 +1,3 @@
registry=https://registry.npmmirror.com
electron_mirror=https://npmmirror.com/mirrors/electron/
package-manager=pnpm
-24
View File
@@ -1,24 +0,0 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"printWidth": 80,
"indentStyle": "space",
"indentWidth": 2,
"endOfLine": "lf",
"sortPackageJson": false,
"ignorePatterns": [
"build",
"dist",
"release",
"coverage",
"docs/.vitepress/cache",
"docs/.vitepress/dist"
],
"overrides": [
{
"files": ["*.md"],
"options": {
"proseWrap": "preserve"
}
}
]
}
-53
View File
@@ -1,53 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/npm/oxlint/configuration_schema.json",
"categories": {
"correctness": "error",
"suspicious": "warn",
"perf": "warn",
"pedantic": "off",
"style": "off",
"restriction": "off",
"nursery": "off"
},
"rules": {
"no-unused-vars": "error",
"no-console": "warn",
"no-debugger": "error",
"no-duplicate-imports": "error",
"eqeqeq": "warn",
"typescript/no-explicit-any": "warn",
"typescript/no-non-null-assertion": "warn",
"import/no-duplicates": "error",
"import/no-self-import": "error",
"unicorn/no-null": "off",
"unicorn/prefer-node-protocol": "error"
},
"overrides": [
{
"files": ["**/*.tsx", "**/*.jsx"],
"rules": {
"react/jsx-no-duplicate-props": "error",
"react/no-direct-mutation-state": "error",
"react/jsx-key": "error",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
},
{
"files": ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts"],
"rules": {
"no-console": "off",
"typescript/no-explicit-any": "off"
}
}
],
"ignorePatterns": [
"node_modules",
"build",
"dist",
"release",
"*.min.js",
"docs/.vitepress/cache",
"docs/.vitepress/dist"
]
}
+3
View File
@@ -0,0 +1,3 @@
# Ignore artifacts:
build
coverage
+1
View File
@@ -0,0 +1 @@
{}
-4
View File
@@ -1,4 +0,0 @@
{
"recommendations": ["oxc.oxc-vscode", "EditorConfig.EditorConfig"],
"unwantedRecommendations": ["esbenp.prettier-vscode"]
}
-15
View File
@@ -1,15 +0,0 @@
{
"cSpell.words": ["intlify", "unplugin", "vitepress", "waline"],
"oxc.enable": true,
"oxc.lint.enable": true,
"oxc.fmt.experimental": true,
"editor.defaultFormatter": "oxc.oxc-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.oxc": "explicit"
},
"prettier.enable": false,
"[go]": {
"editor.defaultFormatter": "golang.go"
}
}
-21
View File
@@ -1,21 +0,0 @@
# Repository Guidelines
## Project Structure & Module Organization
MediaGo is a pnpm/turborepo monorepo. Feature apps live in `apps/` (`frontend-main`, `frontend-mobile`, `backend-web`, `backend-electron`) for the user surfaces and API. Reusable logic stays in `packages/` (`shared` for cross-runtime helpers, `backend` for orchestration, `main` for Electron packaging). Long-form docs and assets sit in `docs/`, `images/`, and `docker/`. End-to-end checks live in `tests/`.
## Build, Test, and Development Commands
Run `pnpm install` once per clone. Use `pnpm dev` for the unified desktop + web experience, or scope to `pnpm dev:web` / `pnpm dev:electron`. `pnpm build` triggers the production Turborepo pipeline; `pnpm build:web-release` plus `pnpm build:docker` produce the deployable web bundle. Keep the codebase healthy with `pnpm lint`, `pnpm lint:fix`, `pnpm format`, and verify types through `pnpm types`.
## Coding Style & Naming Conventions
Target modern TypeScript with ES modules, two-space indentation, UTF-8, and LF endings per `.editorconfig`. Components, hooks, and services adopt PascalCase (e.g. `UserPreferencesPanel.tsx`). Utilities and helpers stay camelCase, and constants use SCREAMING_SNAKE_CASE. Always run `pnpm format` before committing; reserve comments for clarifying complex logic.
## Testing Guidelines
Integration suites live under `tests/*.test.ts` and execute via `pnpm test` using the Node `tsx` runner. Name files descriptively like `download.queue.integration.test.ts`. Mock external services, prefer shared fixtures in `tests/fixtures/`, and cover happy path, recovery, and edge behaviors when touching runtime code.
## Commit & Pull Request Guidelines
Follow Conventional Commits (e.g. `feat(frontend-main): add download queue UI`) and use `pnpm commit` (Commitizen) to stay compliant. Pull requests should summarize the change, link issues with `Closes #123`, note local test runs (`pnpm test`), and attach screenshots or recordings for UI updates. Call out new environment variables, migrations, or follow-up tasks so reviewers can reproduce the setup quickly.
-93
View File
@@ -1,93 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
MediaGo is a cross-platform video downloader supporting m3u8/HLS streams. The codebase is a pnpm monorepo with three products:
1. **Desktop app** (`apps/electron` + `apps/ui`) — Electron wrapper that launches Go Core as a subprocess
2. **Web server** (`apps/server` + `apps/ui`) — Node.js launcher that spawns Go Core as a subprocess
3. **Video player** (`apps/core` + `apps/player-ui`) — Player UI embedded in Go Core for video playback
All three products share the Go Core backend (`apps/core`) for download orchestration.
## Common Commands
```bash
pnpm install # Install all dependencies (run once per clone)
pnpm dev:electron # Start Electron desktop dev environment (HMR)
pnpm dev:server # Start server dev environment (HMR)
pnpm build:electron # Production build for Electron
pnpm build:web # Build UI only (server mode)
pnpm core:dev # Start Go Core dev server (port 9900)
pnpm core:build # Compile Go Core binary
pnpm player:dev # Start Player dev (alias for core:dev)
pnpm player:build # Build Player (alias for core:build)
pnpm deps:download # Download third-party tools (ffmpeg, BBDown, etc.)
pnpm deps:download:all # Download tools for all platforms
pnpm lint # Lint with oxlint
pnpm lint:fix # Auto-fix lint issues
pnpm format # Format with oxfmt
pnpm format:check # Check formatting without modifying
pnpm check # Full check: lint + format + type check
pnpm type:check # TypeScript type checking via Turborepo
pnpm pack:electron # Build + package Electron distributable
```
Commits use Conventional Commits format (e.g. `feat(electron): add queue UI`).
## Architecture
### Monorepo Layout
**Apps:**
- **`apps/core/`** — Go (Gin) REST API backend for download orchestration. Runs on port 9900. Uses SQLite (GORM), SSE for real-time events, PTY for capturing download tool output. Built with Gulp + Go cross-compilation.
- **`apps/electron/`** — Electron main process (tsdown build, inversify DI). Launches Go Core via `@mediago/service-runner`.
- **`apps/server/`** — Node.js launcher (tsdown build). Spawns Go Core via `@mediago/service-runner`.
- **`apps/ui/`** — Shared React 19 frontend (Vite 8, Ant Design 6, Zustand, TailwindCSS 4, i18next). Used by both Electron and server targets.
- **`apps/player-ui/`** — React 19 frontend for player (Vite 8, shadcn/ui, video.js, TailwindCSS 4). Built assets are embedded into Go Core via `//go:embed`.
**Packages:**
- **`packages/shared/common/`** — Platform-agnostic shared types, constants, and utilities
- **`packages/core-sdk/`** — TypeScript SDK for Go Core REST API (Axios, SSE via eventsource)
- **`packages/electron-preload/`** — Electron preload scripts for IPC bridge
- **`packages/browser-extension/`** — Browser extension (Lit web components)
- **`docs/`** — VitePress documentation (Chinese, English, Japanese)
### Multi-Target Build
The `APP_TARGET` env var (`electron` | `server`) controls which backend the UI builds against. Both targets share the same React UI but connect via different transports:
- **Electron**: IPC bridge (preload) + Go Core direct (via `@mediago/core-sdk`)
- **Server/Web**: HTTP/WebSocket + Go Core direct (via `@mediago/core-sdk`)
The UI adapter layer (`apps/ui/src/hooks/adapters/`) abstracts this: `electron.ts` provides IPC bridge in desktop mode, `platform-stubs.ts` provides no-op stubs in web mode, and `index.ts` exports `platformApi` which selects the appropriate adapter.
### Key Patterns
- **Go Core as subprocess**: Both Electron and server apps launch Go Core via `@mediago/service-runner`, which manages the process lifecycle and port allocation
- **Dependency Injection**: inversify with `@inversifyjs/binding-decorators` in Electron backend
- **State Management**: Zustand in the UI
- **Real-time events**: Go Core emits SSE events (`/api/events`); the UI's `api/events.ts` subscribes and dispatches to React via a listener pattern
- **TypeScript**: Strict mode with experimental decorators and decorator metadata enabled
- **Module format**: ES Modules everywhere
## Tooling
- **Package manager**: pnpm 10.15.0 (enforced via `packageManager` field)
- **Build orchestration**: Turborepo
- **App bundling**: tsdown for Node/Electron, Vite 8 for UI apps
- **Go builds**: Gulp orchestrating `go build` / `go run` in `apps/core`
- **Linter**: oxlint (config in `.oxlintrc.json`)
- **Formatter**: oxfmt (config in `.oxfmtrc.json`)
- **Pre-commit**: husky + lint-staged (runs oxlint --fix + oxfmt --write on staged files)
- **Electron packaging**: electron-builder
## Style Conventions
- TypeScript, ES modules, 2-space indentation, UTF-8, LF endings
- Components: PascalCase. Utilities: camelCase. Constants: SCREAMING_SNAKE_CASE
- UI port: 8555 (strict). Go Core port: 9900. Player UI port: 8556
-96
View File
@@ -1,96 +0,0 @@
# Contributing to MediaGo
Thanks for your interest in hacking on MediaGo! This doc covers everything
you need to get a local dev build running. For user-facing usage, see the
main [README](./README.md).
## Prerequisites
- **Node.js** ≥ 20 — install from [nodejs.org](https://nodejs.org/)
- **pnpm** ≥ 10 — `npm i -g pnpm`
- **Go** ≥ 1.22 — only needed if you're working on the Go Core backend
(`apps/core/`). Install from [go.dev](https://go.dev/dl/).
## Clone & install
```shell
git clone https://github.com/caorushizi/mediago.git
cd mediago
pnpm install
```
## Repository layout
MediaGo is a pnpm + Turborepo monorepo with three products that share the
same Go Core backend:
```
apps/
core/ Go backend (download orchestration, SSE, REST API)
electron/ Electron desktop main process
server/ Node.js launcher for the self-hosted web build
ui/ Shared React 19 frontend (Electron + Web)
player-ui/ React frontend embedded inside Go Core for playback
packages/
shared/common/ Cross-platform types, constants, i18n resources
core-sdk/ TypeScript SDK for the Go Core REST API
electron-preload/
mediago-extension/ Browser extension (Chrome / Edge)
docs/ VitePress site (zh / en / jp)
extra/ Vendored binaries (e.g. aria2)
scripts/ Dep downloaders, extension packager, etc.
```
Deeper architecture notes live in [`CLAUDE.md`](./CLAUDE.md).
## Everyday commands
```shell
# Download third-party binaries (ffmpeg, yt-dlp, N_m3u8DL-RE, BBDown,
# aria2, mediago-core) for the current platform — run once per clone
pnpm deps:download
# Run the Electron desktop app in dev mode (HMR)
pnpm dev:electron
# Run the self-hosted web server in dev mode
pnpm dev:server
# Build an unpacked Electron directory (fast, for smoke-testing layout)
pnpm pack:electron
# Build full Electron installers for distribution (.exe / .dmg / .deb)
pnpm release:electron
# Lint + format + type-check (what CI runs)
pnpm check
```
The self-hosted web server doesn't have a dedicated packaging script — it
ships via the Docker image published to GHCR, or you can run the build
output (`pnpm -F @mediago/server build`) directly under Node.
## Commit style
This repo uses [Conventional Commits](https://www.conventionalcommits.org/).
Typical shapes:
```
feat(ui): add dark-mode toggle to settings page
fix(core): resume m3u8 downloads after process restart
refactor(extension): split options hook per card
chore(deps): bump axios from 1.14.0 to 1.15.0
```
Commits are lint-staged on commit (oxlint --fix + oxfmt --write on
staged files). Type checks run via `turbo type:check`.
## Pull requests
- Open PRs against the `master` branch.
- Keep each PR focused — one feature / fix per PR if possible.
- Include a short "why" in the description; the "what" is in the diff.
- If the change is user-visible, a line in the PR description that would
fit in a release note is appreciated.
Thanks for contributing! 🚀
-117
View File
@@ -1,117 +0,0 @@
# Build context: repository root
# docker build -t mediago .
# ===== Stage 1: Node Builder (runs natively on build machine) =====
FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS node-builder
RUN apt-get update && apt-get install -y --no-install-recommends unzip && rm -rf /var/lib/apt/lists/*
RUN corepack enable && corepack prepare pnpm@10.15.0 --activate
# Map Docker TARGETARCH to Node arch naming for deps download
ARG TARGETARCH
RUN if [ "$TARGETARCH" = "amd64" ]; then \
echo "linux-x64" > /tmp/deps-platform; \
else \
echo "linux-${TARGETARCH}" > /tmp/deps-platform; \
fi
WORKDIR /src
# Install dependencies — copy all workspace package.json files first for caching
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json .npmrc* ./
COPY apps/ui/package.json apps/ui/package.json
COPY apps/player-ui/package.json apps/player-ui/package.json
COPY apps/server/package.json apps/server/package.json
COPY apps/core/package.json apps/core/package.json
COPY apps/electron/package.json apps/electron/package.json
COPY packages/ packages/
RUN pnpm install --frozen-lockfile
# Copy source files and root configs needed by builds
COPY tsconfig*.json turbo.json .env* ./
COPY apps/ui/ apps/ui/
COPY apps/player-ui/ apps/player-ui/
COPY apps/electron/app/package.json apps/electron/app/package.json
COPY scripts/ scripts/
# Vendored binaries (aria2 in particular). `scripts/download-deps.ts`
# treats `source: "local"` entries by copying from `extra/<tool>/<os>/<arch>/`
# into `.deps/`; without this COPY they silently get skipped and the
# resulting image ships with no aria2c.
COPY extra/ extra/
# Build player-ui (will be embedded in Go core binary)
RUN pnpm --filter @mediago/player-ui run build
# Build web UI for server mode
ENV APP_TARGET=server
ENV NODE_ENV=production
RUN pnpm build:web
# Download third-party tools for TARGET platform
RUN pnpm deps:download --platform $(cat /tmp/deps-platform)
# ===== Stage 2: Go Builder =====
FROM --platform=$BUILDPLATFORM golang:1.25-bookworm AS go-builder
ARG TARGETOS=linux
ARG TARGETARCH=amd64
WORKDIR /src
# Cache Go module downloads
COPY apps/core/go.mod apps/core/go.sum apps/core/
RUN cd apps/core && go mod download
# Copy Go source
COPY apps/core/ apps/core/
# Copy player-ui dist into assets for go:embed
COPY --from=node-builder /src/apps/player-ui/dist apps/core/assets/player/
# Ensure all dependencies are downloaded (go.sum may have been updated)
RUN cd apps/core && go mod download
# Build Go core binary (cross-compile, no CGO)
RUN cd apps/core && \
CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
go build -trimpath -ldflags="-s -w" -o /out/mediago-core ./cmd/server
# ===== Stage 3: Runtime =====
FROM debian:bookworm-slim
RUN apt-get update && \
apt-get install -y --no-install-recommends ca-certificates libicu72 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Core binary
COPY --from=go-builder /out/mediago-core /usr/local/bin/mediago-core
# Web UI static files
COPY --from=node-builder /src/apps/ui/build/server /app/static
# Third-party tools — copy from the platform-specific directory
ARG TARGETARCH
COPY --from=node-builder /src/.deps/linux-* /app/deps-tmp/
RUN mkdir -p /app/deps && \
if [ -d /app/deps-tmp ]; then \
find /app/deps-tmp -type f -exec cp {} /app/deps/ \; ; \
fi && \
chmod +x /app/deps/* 2>/dev/null || true && \
rm -rf /app/deps-tmp
RUN mkdir -p /app/mediago/data /app/mediago/logs /app/mediago/downloads
# Entrypoint script — isolates the invocation flags from the Dockerfile
# so editing the default args doesn't require rebuilding the full image
# layer and so callers can still append overrides via `docker run`.
COPY scripts/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
EXPOSE 8899
VOLUME ["/app/mediago"]
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
-170
View File
@@ -1,170 +0,0 @@
<div align="center">
<h1>MediaGo</h1>
<a href="https://downloader.caorushizi.cn/en/guides.html?form=github">Quick Start</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://downloader.caorushizi.cn/en?form=github">Website</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://downloader.caorushizi.cn/en/documents.html?form=github">Docs</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://github.com/caorushizi/mediago/discussions">Discussions</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://discord.gg/yxWBVRWGqM">Discord</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://www.reddit.com/r/MediaGo_Studio/">Reddit</a>
<br>
<a href="https://github.com/caorushizi/mediago/blob/master/README.zh.md">中文</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://github.com/caorushizi/mediago/blob/master/README.jp.md">日本語</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://github.com/caorushizi/mediago/blob/master/README.it.md">Italiano</a>
<br>
<img alt="GitHub Downloads (all assets, all releases)" src="https://img.shields.io/github/downloads/caorushizi/mediago/total">
<img alt="GitHub Downloads (all assets, latest release)" src="https://img.shields.io/github/downloads/caorushizi/mediago/latest/total">
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/caorushizi/mediago">
<img alt="GitHub forks" src="https://img.shields.io/github/forks/caorushizi/mediago">
<img alt="GitCode" src="https://gitcode.com/caorushizi/mediago/star/badge.svg">
<br>
<a href="https://trendshift.io/repositories/11083" target="_blank">
<img src="https://trendshift.io/api/badge/repositories/11083" alt="caorushizi%2Fmediago | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/>
</a>
<hr />
</div>
A cross-platform video downloader with built-in sniffing — point it at a
page, pick what you want, and save. No packet capture, no browser
extensions to configure, no fiddling with command-line tools.
The app UI currently ships with English, Simplified Chinese, and Italian.
## ✨ What's inside
### 🌐 Browser extension for Chrome / Edge
See something you want on any site → click the extension → send it to
MediaGo. Detects video resources automatically, shows the count on the
toolbar badge, works with most mainstream video platforms including
YouTube, Bilibili and more. Ships bundled with the Desktop app — open
**Settings → More Settings → Browser extension directory** to find the
install folder.
### 🎬 YouTube and 1000+ sites
Powered by yt-dlp under the hood. Supports YouTube, Twitter/X, Instagram,
Reddit and [over a thousand more video sites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md).
### 🦞 AI assistants can download for you — OpenClaw Skill
Using Claude Code, Cursor or another AI coding assistant? Install the
MediaGo skill and just say _"please download this video: &lt;url&gt;"_.
The AI handles the rest.
```shell
npx clawhub@latest install mediago
```
### 🔌 Works with other tools
MediaGo exposes a full HTTP API — scripts, automation tools and other
apps can create download tasks, query progress and manage the list
directly. The browser extension uses this same API to talk to the desktop
app; anyone else can tap in too.
### 🎞️ Built-in format conversion
After a download finishes, convert it to another format or quality
without leaving MediaGo. No more opening a separate tool for ffmpeg.
### 🐳 One-line Docker deployment
Headless install on your server, then access the web UI from anywhere on
the same network:
```shell
docker run -d --name mediago -p 8899:8899 -v /path/to/mediago:/app/mediago caorushizi/mediago:3.5.0
```
Available on [Docker Hub](https://hub.docker.com/r/caorushizi/mediago) and GHCR (`ghcr.io/caorushizi/mediago`) — same image, pick whichever registry is faster for you. Supports both Intel / AMD (amd64) and ARM (arm64). On the desktop build,
MediaGo listens on both `127.0.0.1` and your LAN IP out of the box, so
phones and tablets on the same Wi-Fi can open the web UI too.
## 📷 Screenshots
![Home](./images/home_en.png)
![Home — dark mode](./images/home-dark_en.png)
![Settings](./images/settings_en.png)
![Resource extraction](./images/browser_en.png)
## 📥 Download
### v3.5.0 (stable)
- [Windows — installer](https://github.com/caorushizi/mediago/releases/download/v3.5.0/mediago-community-setup-win32-x64-3.5.0.exe)
- [Windows — portable](https://github.com/caorushizi/mediago/releases/download/v3.5.0/mediago-community-portable-win32-x64-3.5.0.exe)
- [macOS — Apple Silicon (arm64)](https://github.com/caorushizi/mediago/releases/download/v3.5.0/mediago-community-setup-darwin-arm64-3.5.0.dmg)
- [macOS — Intel (x64)](https://github.com/caorushizi/mediago/releases/download/v3.5.0/mediago-community-setup-darwin-x64-3.5.0.dmg)
- [Linux (deb)](https://github.com/caorushizi/mediago/releases/download/v3.5.0/mediago-community-setup-linux-amd64-3.5.0.deb)
- [**Docker Hub**](https://hub.docker.com/r/caorushizi/mediago): `docker run -d --name mediago -p 8899:8899 -v /path/to/mediago:/app/mediago caorushizi/mediago:3.5.0`
- **GHCR**: `docker run -d --name mediago -p 8899:8899 -v /path/to/mediago:/app/mediago ghcr.io/caorushizi/mediago:3.5.0`
Browsing older releases? See the [GitHub Releases page](https://github.com/caorushizi/mediago/releases).
### 🪄 One-click Docker deployment via BT Panel
1. Install [BT Panel](https://www.bt.cn/new/download.html?r=dk_mediago) using the official script.
2. Log in to the panel, click **Docker** in the sidebar and finish the
Docker service setup (just follow the prompts).
3. Find **MediaGo** in the app store, click **Install**, configure your
domain, and you're done.
## 📝 What's new in v3.5.0
- **🌐 Browser extension** — sniff videos on any site, send to MediaGo
in one click
- **🎬 YouTube + 1000+ sites** — powered by yt-dlp
- **🦞 OpenClaw Skill** — download videos via AI coding assistants
- **🔌 HTTP API** — integrate with scripts, automation and third-party tools
- **🎞️ In-app format conversion** — choose output format and quality
- **🐳 Simpler Docker deployment** — mount a single folder, multi-arch images on GHCR
- **⚡ Faster startup** — backend rewrite, lower memory footprint, built-in video player
## 🛠️ Built with
[![React](https://img.shields.io/badge/React-20232A?logo=react&logoColor=61DAFB)](https://react.dev/)
[![Electron](https://img.shields.io/badge/Electron-191970?logo=electron&logoColor=white)](https://www.electronjs.org)
[![Vite](https://img.shields.io/badge/Vite-646CFF?logo=vite&logoColor=white)](https://vitejs.dev)
[![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Tailwind CSS](https://img.shields.io/badge/Tailwind_CSS-06B6D4?logo=tailwindcss&logoColor=white)](https://tailwindcss.com)
[![shadcn/ui](https://img.shields.io/badge/shadcn%2Fui-000?logo=shadcnui&logoColor=white)](https://ui.shadcn.com/)
[![Go](https://img.shields.io/badge/Go-00ADD8?logo=go&logoColor=white)](https://go.dev/)
[![Ant Design](https://img.shields.io/badge/Ant_Design-0170FE?logo=antdesign&logoColor=white)](https://ant.design)
## 🙏 Acknowledgements
- [N_m3u8DL-RE](https://github.com/nilaoda/N_m3u8DL-RE)
- [BBDown](https://github.com/nilaoda/BBDown)
- [yt-dlp](https://github.com/yt-dlp/yt-dlp)
- [aria2](https://aria2.github.io/)
- [mediago-core](https://github.com/caorushizi/mediago-core)
## ⚖️ Disclaimer
> **This project is for educational and research purposes only. Do not use it for any commercial or illegal purposes.**
>
> 1. All code and functionality provided by this project are intended solely as a reference for learning about streaming media technologies. Users must comply with the laws and regulations of their jurisdiction.
> 2. Any content downloaded using this project remains the property of its original copyright holders. Users should delete downloaded content within 24 hours or obtain proper authorization.
> 3. The developers of this project are not responsible for any actions taken by users, including but not limited to downloading copyrighted content or impacting third-party platforms.
> 4. Using this project for mass scraping, disrupting platform services, or any activity that infringes upon the legitimate rights of others is strictly prohibited.
> 5. By using this project you acknowledge that you have read and agree to this disclaimer. If you do not agree, stop using the project and delete it immediately.
---
> Building from source? See [CONTRIBUTING.md](./CONTRIBUTING.md).
>
> Translating MediaGo? See [TRANSLATION.md](./TRANSLATION.md).

Some files were not shown because too many files have changed in this diff Show More