Technical Documentation: misskey-dev/misskey
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`README.md`)
Thanks
Thanks to Sentry for providing the error tracking platform that helps us catch unexpected errors.
Thanks to Chromatic for providing the visual testing platform that helps us review UI changes and catch visual regressions.
Thanks to Codecov for providing the code coverage platform that helps us improve our test coverage.
Thanks to Crowdin for providing the localization platform that helps us translate Misskey into many languages.
Thanks to Docker for providing the container platform that helps us run Misskey in production.
Overview (`locales/README.md`)
**DO NOT edit locale files** except `ja-JP.yml`.
When you add text to the ja-JP file (of misskey-dev/misskey), it will automatically be applied to other language files.
Translations added in ja-JP file should contain the original Japanese strings.
Please see Contribution guide for more information.
Overview (`packages-private/README.md`)
packages-private
packages-private は、CIなどで使用するためのユーティリティなどを格納する場所です。この配下にあるものは**プロダクションの /packages**の依存となるものではありません。
パッケージ一覧
| パッケージ | 用途 |
|---|---|
diagnostics-shared |
計測系パッケージが共有する統計・書式整形・V8 heap snapshot解析のユーティリティ |
diagnostics-backend |
バックエンドのメモリ使用量をbase/headで比較し、PRコメント用のMarkdownを生成する |
diagnostics-frontend |
フロントエンドをブラウザで起動した際のメトリクスと生成されたchunk情報等をbase/headで比較する |
changelog-checker |
CHANGELOG.md の追記内容を検証する |
GitHub Actionsからの呼び出し方
ワークフロー側にロジックを持たせず、各パッケージのnpm scriptを呼ぶだけにしている。
CLIに渡すパスはすべて呼び出し側のカレントディレクトリ基準で解決されるため、
ワークフローからは $GITHUB_WORKSPACE / $RUNNER_TEMP を使った絶対パスを渡すこと。
- name: Generate report
working-directory: head
run: >-
pnpm --filter diagnostics-frontend run render-md
"$GITHUB_WORKSPACE/base" "$GITHUB_WORKSPACE/head"
"$REPORT_DIR/base-bundle-stats.json" "$REPORT_DIR/head-bundle-stats.json"
"$REPORT_DIR/base-browser.json" "$REPORT_DIR/head-browser.json"
"$REPORT_DIR/report.md"base/head を比較する計測では、head側のチェックアウトにあるハーネスで両方を計測する
(計測コードの差分ではなくビルド成果物の差分だけが結果に出るようにするため)。
Overview (`.claude/agents/README.md`)
`.claude/agents/` — プロジェクト固有のサブエージェント
Misskey の特定領域に特化したレビュー / 調査エージェントを .claude/agents/<name>.md 形式で配置する。
frontmatter (name + description + tools) は、Claude が 自動でエージェントを呼び出すか判断する 唯一の手がかりになる。description は 起動判断に効くドメイン・パス・ファイル種別・固有チェックに絞って簡潔に 書く (動詞 + 対象 + トリガー条件)。本文 checklist 項目を網羅的に列挙するのではなく、他の reviewer と区別できる高シグナル語を選ぶ。
実装済エージェントの一覧は本ファイルでは管理しない (腐敗するため)。各 <name>.md の frontmatter が自己説明として機能する。
他のレビュー手段との使い分け
レビュー面を増やしすぎないよう、役割を分ける:
- この
.claude/agents/の 2 つ: backend endpoint / Vue SFC の Misskey 固有・機械的チェック (endpoint-list 登録漏れ・misskey-js 再生成漏れ・ja-JP.yml 限定・Storybook 併設 等)。
別コンテキストで差分を機械走査する価値がある領域に限定する pr-review-toolkitプラグイン (code-reviewer / silent-failure-hunter 等): 言語非依存の一般的なコード品質・バグ・設計レビュー。Misskey 固有規約は見ないworking-on-*skill の checklist: コードを 書いている最中 の自己チェック (レビュー専用ではなく実装ガイド)
Misskey 固有規約の機械チェックは本 agent、一般品質は pr-review-toolkit、実装中ガイドは skill、と棲み分ける。
構成方針
toolsは 編集権限なし (Edit/Write を渡さない) に絞り、PR baseline (git merge-base origin/develop HEAD) との差分から自動的にレビュー対象を抽出する設計- 差分抽出は
git merge-base origin/develop HEADを baseline にする (PR / ブランチ全体を見るため)。git diff HEAD単体は 未コミット差分しか取れず、コミット済の PR では空になって誤判定する ので使わない descriptionは呼び出し判断の手がかりであると同時に、(呼ばれなくても) Task ツール起動のたびに常時ロードされる。他で代替できない高シグナルなトリガー語に絞って簡潔に 書く (汎用 reviewer と被る語や冗長な列挙は context-budget 上の overhead になるだけで発見性に寄与しない)。健全性は /harness-audit / context-budget skill で確認できる- 規約の 正本は
.claude/skills/*/references/側。agent の checklist はその 派生コピー (subagent が skill を読まなくても動くよう自己完結させる)。規約を変えるときは references を先に直し agent を追従させる ── 両者の食い違いは同期漏れなので references を正とする
新規エージェントを追加する場合
.claude/agents/<name>.mdに YAML frontmatter (name/description/tools) と本文 Markdown を書くdescriptionは呼び出し判断に使われるため、対象ドメイン・主要チェック項目・トリガー条件を挙げる。ただし常時ロードされるので 高シグナル語に絞って簡潔に (構成方針の該当項目を参照)- レビュー専門なら
tools: Read, Grep, Glob, Bashに絞る (Edit/Write を渡さない)。Bashは任意のシェルコマンドを実行できる強力な権限である点に注意: レビュー用途ではgit diff/git ls-files/grep/sed等の 読み取り系コマンドに限定して使う こと。書き込み・削除・ネットワーク送信を伴う操作は本文中の例示・指示に含めないこと (エージェント本文がガードレールになる) - 主要参照ファイルへのリンクは、各エージェント markdown からの相対パスで貼る (
../../packages/backend/...のような形)。絶対パスは contributor のホームディレクトリ依存になるので使わない
Overview (`.claude/commands/README.md`)
`.claude/commands/` — プロジェクト固有のスラッシュコマンド
Misskey 開発で繰り返し使うワークフローを /command-name で呼び出せるよう、.claude/commands/<name>.md 形式で配置している。
実装済コマンドの一覧は本ファイルでは管理しない (腐敗するため)。各 <name>.md の frontmatter (description) が自己説明として機能する。
現状残っているのは ECC (everything-claude-code) 由来の MIT ライセンスコマンドのみで、Misskey 固有のスラッシュコマンドは廃止して .claude/skills/ 配下のスキルに統合した。MIT 出典は .claude/THIRD_PARTY_LICENSES.md を参照。
設計方針
- Misskey 固有のワークフローは原則
.claude/skills/に統合する (description で自動索引されるため。コマンドはユーザーが/nameでタイプしないと起動しない) - 既存の
superpowers/pr-review-toolkitなどのプラグイン提供スラッシュコマンドで足りる場合は新規追加しない
新規コマンドを追加する場合 (どうしてもスキルでは表現できない時のみ)
- frontmatter には最低限
descriptionを指定する。引数を取るならargument-hint、可能ならallowed-toolsも指定する (permission prompt を最小化するため) - 長時間ビルド (2 分超) を伴うコマンドはインライン
!`<cmd>`を使わず、本文でBashツール呼び出し時のtimeoutを指示する - 主要参照ファイルへのリンクは、各コマンド markdown からの相対パスで貼る。絶対パスは contributor のホームディレクトリ依存になるので使わない
Overview (`.claude/skills/README.md`)
`.claude/skills/` — プロジェクト固有のカスタムスキル
Misskey 固有の繰り返しタスクを Claude にスムーズに実行させるための カスタムスキル を .claude/skills/<name>/SKILL.md 形式で配置する。
frontmatter (name + description) は、Claude が 自動でスキルを呼び出すか判断する 唯一の手がかりになる。description には用途を具体的かつ網羅的に書き、pushy なトリガー語 (例: "Use whenever ...", "Must be consulted before any ...") で発見されやすくする。
実装済スキルの一覧は本ファイルでは管理しない (腐敗するため)。各サブディレクトリの SKILL.md の frontmatter が自己説明として機能する。
構成方針
Anthropic 公式の Agent Skills ベストプラクティス に従い、以下の構造を採用する:
- SKILL.md 本体は 500 行以下 (理想は 30-80 行の索引)
- 詳細は
references/tasks/(手順) とreferences/knowledge/(規約・背景知識) に分離 (progressive disclosure) - リンクは原則 references への 1 段リンク に留める (例外: 他 skill / agent への導線は可)
- ファイルシステム上の references は読まれるまでゼロコンテキストコスト
ECC (everything-claude-code) 由来の MIT スキルが含まれる場合は、ファイル冒頭の SPDX ヘッダー + .claude/THIRD_PARTY_LICENSES.md §1 に出典を記載する。
新規スキルを追加する場合
.claude/skills/<name>/SKILL.mdに YAML frontmatter (name+description) と本文 Markdown を書く- description は 三人称の "Use when ..." 形式 で、主要キーワード網羅。pushy なトリガー語 ("Must be consulted before ...") を入れる
disable-model-invocation: trueは付けない (auto-invoke させたいため)- 主要参照ファイルへのリンクは、各 markdown ファイルからの相対パスで貼る (
../../../../packages/backend/...のような形)。絶対パスは contributor のホームディレクトリ依存になるので使わない - 詳細を分ける場合は
references/tasks/(手順) /references/knowledge/(知識) の二分に従う - スキル作成は
/skill-creator(公式の skill-creator スキル) のガイドを経由するのが推奨
関連
- 各スキルの description で自動索引される設計のため、実装済スキルの手書き索引 (一覧表) は本ファイルにも
AGENTS.mdにも持たない方針 (手書き索引は腐敗するため、frontmatter の description を唯一の索引とする) - スキルそのものの健全性検査は /harness-audit で採点できる
Overview (`packages/icons-subsetter/README.md`)
これは何
フロントエンドの各パッケージで使用されているtabler iconsのclassをスキャンし、使用されているiconのみを抽出するツールです。
なお、サブセット版に無いアイコンが呼び出された場合は本物のtabler icons フォントにフォールバックするようになっています。
このツールは本番ビルド時にのみ使用されます(開発モードでも最初の1回だけビルドが走りますが、これは型エラーを抑制するためにファイルを置いておく用の措置です)
現時点では src/generator.ts の filesToScan にスキャン対象のファイルが書かれています。もしこれに当てはまらないファイルをサブセットのスキャン対象とする場合はこの部分を適宜修正してください。
使い方
pnpm buildOverview (`packages/misskey-js/README.md`)
misskey.js
Strongly-typed official Misskey SDK for browsers/Node.js.
JavaScript(TypeScript)用の公式MisskeySDKです。ブラウザ/Node.js上で動作します。
以下が提供されています:
- ユーザー認証
- APIリクエスト
- ストリーミング
- ユーティリティ関数
- Misskeyの各種型定義
対応するMisskeyのバージョンは12以上です。
Install
npm i misskey-jsUsage
インポートは以下のようにまとめて行うと便利です。
import * as Misskey from 'misskey-js';便宜上、以後のコード例は上記のように* as Misskeyとしてインポートしている前提のものになります。
ただし、このインポート方法だとTree-Shakingできなくなるので、コードサイズが重要なユースケースでは以下のような個別インポートをお勧めします。
import { api as misskeyApi } from 'misskey-js';Authenticate
todo
API request
APIを利用する際は、利用するサーバーの情報とアクセストークンを与えてAPIClientクラスのインスタンスを初期化し、そのインスタンスのrequestメソッドを呼び出してリクエストを行います。
const cli = new Misskey.api.APIClient({
origin: 'https://misskey.test',
credential: 'TOKEN',
});
const meta = await cli.request('meta', { detail: true });requestの第一引数には呼び出すエンドポイント名、第二引数にはパラメータオブジェクトを渡します。レスポンスはPromiseとして返ります。
Streaming
misskey.jsのストリーミングでは、二つのクラスが提供されます。
ひとつは、ストリーミングのコネクション自体を司るStreamクラスと、もうひとつはストリーミング上のチャンネルの概念を表すChannelクラスです。
ストリーミングを利用する際は、まずStreamクラスのインスタンスを初期化し、その後でStreamインスタンスのメソッドを利用してChannelクラスのインスタンスを取得する形になります。
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
const mainChannel = stream.useChannel('main');
mainChannel.on('notification', notification => {
console.log('notification received', notification);
});コネクションが途切れても自動で再接続されます。
チャンネルへの接続
チャンネルへの接続はStreamクラスのuseChannelメソッドを使用します。
パラメータなし
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
const mainChannel = stream.useChannel('main');パラメータあり
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
const chatChannel = stream.useChannel('chat', {
other: 'xxxxxxxxxx',
});チャンネルから切断
Channelクラスのdisposeメソッドを呼び出します。
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
const mainChannel = stream.useChannel('main');
mainChannel.dispose();メッセージの受信
ChannelクラスはEventEmitterを継承しており、メッセージがサーバーから受信されると受け取ったイベント名でペイロードをemitします。
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
const mainChannel = stream.useChannel('main');
mainChannel.on('notification', notification => {
console.log('notification received', notification);
});メッセージの送信
Channelクラスのsendメソッドを使用してメッセージをサーバーに送信することができます。
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
const chatChannel = stream.useChannel('chat', {
other: 'xxxxxxxxxx',
});
chatChannel.send('read', {
id: 'xxxxxxxxxx'
});コネクション確立イベント
Streamクラスの_connected_イベントが利用可能です。
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
stream.on('_connected_', () => {
console.log('connected');
});コネクション切断イベント
Streamクラスの_disconnected_イベントが利用可能です。
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
stream.on('_disconnected_', () => {
console.log('disconnected');
});コネクションの状態
Streamクラスのstateプロパティで確認できます。
initializing: 接続確立前connected: 接続完了reconnecting: 再接続中
Overview (`packages/backend/test-federation/README.md`)
test-federation
Test federation between two Misskey servers: a.test and b.test.
Before testing, you need to build the entire project, and change working directory to here:
pnpm build
cd packages/backend/test-federationFirst, you need to start servers by executing following commands:
bash ./setup.sh
NODE_VERSION=26.13.1 docker compose up --scale tester=0Then you can run all tests by a following command:
NODE_VERSION=26.13.1 docker compose run --no-deps --rm testerFor testing a specific file, run a following command:
NODE_VERSION=26.13.1 docker compose run --no-deps --rm tester -- pnpm -F backend test:fed packages/backend/test-federation/test/user.test.tsOverview (`packages/misskey-js/generator/README.md`)
misskey-js向け型生成モジュール
バックエンドが吐き出すOpenAPI準拠のapi.jsonからmisskey-jsで使用される型エイリアスを生成するためのモジュールです。
このモジュールはmisskey-jsそのものにバンドルされることは想定しておらず、生成物をmisskey-jsのsrc配下にコピーして使用することを想定しています。
使い方
まず、Misskeyのバックエンドからapi.jsonを取得する必要があります。任意のMisskeyインスタンスの/api-docからダウンロードしても良いですし、
backendモジュール配下でpnpm generate-api-jsonを実行しても良いでしょう。
api.jsonを入手したら、このファイルがあるディレクトリに置いてください。
その後、以下コマンドを実行します。
pnpm generate上記を実行することで、./builtディレクトリ配下にtsファイルが生成されます。
Overview (`packages/backend/src/misc/prelude/README.md`)
Prelude
このディレクトリのコードはJavaScriptの表現能力を補うためのコードです。
Misskey固有の処理とは独立したコードの集まりですが、Misskeyのコードを読みやすくすることを目的としています。
Contributing Activitypub (`docs/contributing/activitypub.md`)
ActivityPub
ActivityPub のペイロードを変更する人向け。
Additional things for ActivityPub payload changes
This section is specific to misskey-dev implementation. Other fork or implementation may take different way. A significant difference is that non-"misskey-dev" extension is not described in the misskey-hub's document.
If PR includes changes to ActivityPub payload, please reflect it in misskey-hub's document by sending PR.
The name of purporsed extension property (referred as "extended property" in later) to ActivityPub shall be prefixed by _misskey_. (i.e. _misskey_quote)
The extended property in packages/backend/src/core/activitypub/type.ts must be declared as optional because ActivityPub payloads that comes from older Misskey or other implementation may not contain it.
The extended property must be included in the context definition. Context is defined in packages/backend/src/core/activitypub/misc/contexts.ts.
The key shall be same as the name of extended property, and the value shall be same as "short IRI".
"Short IRI" is defined in misskey-hub's document, but usually takes form of misskey:<name of extended property>. (i.e. misskey:_misskey_quote)
One should not add property that has defined before by other implementation, or add custom variant value to "well-known" property.
Contributing Backend (`docs/contributing/backend.md`)
Backend
バックエンド・データベースの実装・レビューを行う人向け。
Nest
Nest Service Circular dependency / Nestでサービスの循環参照でエラーが起きた場合
forwardRef
まずは簡単にforwardRefを試してみる
export class FooService {
constructor(
@Inject(forwardRef(() => BarService))
private barService: BarService
) {
}
}OnModuleInit
できなければOnModuleInitを使う
moduleRef.get(BarService.name) は文字列トークンで解決するため、BarService の通常の登録に加え、同じモジュールの providers に alias を登録する必要がある。Misskey では CoreModule に登録している。
providers: [
BarService,
{ provide: BarService.name, useExisting: BarService },
],import { Injectable, OnModuleInit } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { BarService } from '@/core/BarService';
@Injectable()
export class FooService implements OnModuleInit {
private barService: BarService // constructorから移動してくる
constructor(
private moduleRef: ModuleRef,
) {
}
async onModuleInit() {
this.barService = this.moduleRef.get(BarService.name);
}
public async niceMethod() {
return await this.barService.incredibleMethod({ hoge: 'fuga' });
}
}Service Unit Test
テストでonModuleInitを呼び出す必要がある
// import ...
describe('test', () => {
let app: TestingModule;
let fooService: FooService; // for test case
let barService: BarService; // for test case
beforeEach(async () => {
app = await Test.createTestingModule({
imports: ...,
providers: [
FooService,
{ // mockする (mockは必須ではないかもしれない)
provide: BarService,
useFactory: () => ({
incredibleMethod: jest.fn(),
}),
},
{ // Provideにする
provide: BarService.name,
useExisting: BarService,
},
],
})
.useMocker(...
.compile();
fooService = app.get<FooService>(FooService);
barService = app.get<BarService>(BarService) as jest.Mocked<BarService>;
// onModuleInitを実行する
await fooService.onModuleInit();
});
test('nice', async () => {
await fooService.niceMethod();
expect(barService.incredibleMethod).toHaveBeenCalled();
expect(barService.incredibleMethod.mock.lastCall![0])
.toEqual({ hoge: 'fuga' });
});
})Misskey.jsの型生成
pnpm build-misskey-js-with-typesSQL / TypeORM
INSERTするときにはsaveではなくinsertを使用する
#6441
placeholder
SQLをクエリビルダで組み立てる際、使用するプレースホルダは重複してはならない
例えば
query.andWhere(new Brackets(qb => {
for (const type of ps.fileType) {
qb.orWhere(`:type = ANY(note.attachedFileTypes)`, { type: type });
}
}));と書くと、ループ中でtypeというプレースホルダが複数回使われてしまいおかしくなる
だから次のようにする必要がある
query.andWhere(new Brackets(qb => {
for (const type of ps.fileType) {
const i = ps.fileType.indexOf(type);
qb.orWhere(`:type${i} = ANY(note.attachedFileTypes)`, { [`type${i}`]: type });
}
}));Not `null` in TypeORM
const foo = await Foos.findOne({
bar: Not(null)
});のようなクエリ(barがnullではない)は期待通りに動作しない。
次のようにします:
const foo = await Foos.findOne({
bar: Not(IsNull())
});`null` in SQL
SQLを発行する際、パラメータがnullになる可能性のある場合はSQL文を出し分けなければならない
例えば
query.where('file.folderId = :folderId', { folderId: ps.folderId });という処理で、ps.folderIdがnullだと結果的にfile.folderId = nullのようなクエリが発行されてしまい、これは正しいSQLではないので期待した結果が得られない
だから次のようにする必要がある
if (ps.folderId) {
query.where('file.folderId = :folderId', { folderId: ps.folderId });
} else {
query.where('file.folderId IS NULL');
}`[]` in SQL
SQLを発行する際、INのパラメータが[](空の配列)になる可能性のある場合はSQL文を出し分けなければならない
例えば
const users = await Users.find({
id: In(userIds)
});という処理で、userIdsが[]だと結果的にuser.id IN ()のようなクエリが発行されてしまい、これは正しいSQLではないので期待した結果が得られない
だから次のようにする必要がある
const users = userIds.length > 0 ? await Users.find({
id: In(userIds)
}) : [];配列のインデックス in SQL
SQLでは配列のインデックスは1始まり。[a, b, c]の aにアクセスしたいなら[0]ではなく[1]と書く
null IN
nullが含まれる可能性のあるカラムにINするときは、そのままだとおかしくなるのでORなどでnullのハンドリングをしよう。
enumの削除は気をつける
enumの列挙の内容の削除は、その値をもつレコードを全て削除しないといけない
削除が重たかったり不可能だったりする場合は、削除しないでおく
Migration作成方法
リポジトリルートから:
pnpm --filter backend exec typeorm migration:generate -d ormconfig.js -o --esm migration/<PascalName>- ワークスペースにインストール済みの TypeORM CLI を使う。設定ファイルと出力先は
packages/backend/基準で解決され、生成ファイルはpackages/backend/migration/に配置される - 作成されたスクリプトは不必要な変更を含むため除去してください
-o(--outputJs) で JS 形式、--esmで ESM 形式に生成する。Misskey の既存 migration はすべて ESM JS なので両方のオプションが必要
Contributing Coding Guidelines (`docs/contributing/coding-guidelines.md`)
Coding guidelines
実装する人向けの共通規約・設計方針。領域固有の規約は Frontend・Backend を参照する。
Misskeyのドメイン固有の概念は`Mi`をprefixする
例えばGoogleが自社サービスをMap、Earth、DriveではなくGoogle Map、Google Earth、Google Driveのように命名するのと同じ
コード上でMisskeyのドメイン固有の概念にはMiをprefixすることで、他のドメインの同様の概念と区別できるほか、名前の衝突を防ぐ。
ただし、文脈上Misskeyのものを指すことが明らかであり、名前の衝突の恐れがない場合は、一時的なローカル変数に限ってMiを省略してもよい。
JSONのimportに気を付けよう
TypeScriptでjsonをimportすると、tscでコンパイルするときにそのjsonファイルも一緒にdistディレクトリに吐き出されてしまう。この挙動により、意図せずファイルの書き換えが発生することがあるので、jsonをimportするときは書き換えられても良いものかどうか確認すること。書き換えされて欲しくない場合は、importで読み込むのではなく、fs.readFileSyncなどの関数を使って読み込むようにすればよい。
命名規則
本来それが略称であっても、通常それでひとつのワードとして用いられるものは、略称として扱わない。
例: IP address
Good: ipAddress / IpAddress
Bad: IPAddress
例: User ID
Good: userId / UserId
Bad: userID / UserID
例: XMLなHTTPのRequest
Good: xmlHttpRequest / XmlHttpRequest
Bad: XMLHttpRequest / XMLHTTPRequest
関数化の基準
汎用性が低く(例えばそれを関数化したとしてもその呼び出しが元の場所一か所しか存在しない)、内容も短い処理(例えば10行以下)は、かえって読みにくくなるため、関数化しない。
また、関数化する場合でも、呼び出しがある特定のスコープに限られる場合は、そのスコープ内に閉じ込めた方が分かりやすく簡潔になる場合がある(ただし本来その処理に不要であっても、構造上親のスコープにある関係のない変数や引数にもアクセスできるようになるため、必ずしもそうすれば設計上綺麗になるというわけでもない。状況に応じて判断すべし)。
Bad:
function withBrankets(x) {
return `(${x})`;
}
function formatPercent(x) {
return `${x}%`;
}
function formatValue(x) {
return withBrankets(formatPercent(x));
}
function showData(a, b) {
console.log(formatValue(a));
console.log(formatValue(b));
}Good:
function formatValue(x) {
return `(${x}%)`;
}
function showData(a, b) {
console.log(formatValue(a));
console.log(formatValue(b));
}or
function showData(a, b) {
function formatValue(x) {
return `(${x}%)`;
}
console.log(formatValue(a));
console.log(formatValue(b));
}or
function showData(a, b) {
console.log(`(${a}%)`);
console.log(`(${b}%)`);
}indexというファイル名を使うな
ESMではディレクトリインポートは廃止されているのと、ディレクトリインポートせずともファイル名が index だと何故か一部のライブラリ?でディレクトリインポートだと見做されてエラーになる
考え方
DRYに囚われるな
必要なのは一般化ではなく抽象化と考えます。
盲信せず、誤った・不必要な共通化は避け、それが自然だと感じる場合は重複させる勇気を持ちましょう。
Misskeyを複雑にしない実装
それがいくら複雑であっても、Misskey固有のコンテキストと関心が分離されている(もしくは事実上分離されていると見做すことができる)実装であれば、それはMisskeyのコードベースに対する複雑性に影響を与えないと考えます。
例えるなら、VueやAiScriptといったMisskeyが使用しているライブラリの内部実装がいくら複雑だったとしても、「それを使用しているからMisskeyの実装は複雑である」ということにはならないのと同じです。
Misskeyのドメイン知識から関心が分離されているということは、Misskeyの実装について考える時にそれらの内部実装を考慮する必要が無く、認知負荷を増やさないからです。
また重要な点は、その実装が、Misskeyリポジトリの外部にあるか・内部にあるかということや、Misskeyがメンテナンスするものか・第三者がメンテナンスするものかといったことは複雑性を考える上ではほとんど無視できるという点です。
もちろんその実装がMisskeyリポジトリにあり、Misskeyがメンテナンスしなければならないものは、保守のコストはかかります。
しかし、Misskeyの本質的な設計・実装という観点で見たときは、その実装は実質的に外部ライブラリのように振る舞います。
換言すれば「たまたまMisskeyの開発者と同じ人たちがメンテナンスしているし、たまたまMisskeyのリポジトリ内に置いてあるだけの外部ライブラリ」です。
そのため、実装をなるべくMisskeyのドメイン知識から独立したものにすれば、Misskeyのコードベースの複雑性を上げることなく機能実装を行うことができ、お得であると言えます。
もちろんそれにこだわって、些細な実装でもそのように分離してしまうとかえって認知負荷が増えたり、実装量が増えてメリットをデメリットが上回る場合もあるので、ケースバイケースではあります。
AIに誤解されにくいコードを書こう
AI(LLM)によるレビューやコーディング補助時にハルシネーションのもとになるので、AIが誤解・混乱しそうなコードは避けるかコメントを残そう。
AIにとって分かりやすいコードは、結果的に人間にとっても分かりやすいコードに繋がります。
Contributing Development (`docs/contributing/development.md`)
Development
開発環境を準備・起動する人向け。
Setup
Before developing, you have to set up environment. Misskey requires Redis, PostgreSQL, and FFmpeg.
You would want to install Meilisearch to experiment related features. Technically, meilisearch is not strict requirement, but some features and tests require it.
There are a few ways to proceed.
Use system-wide software
You could install them in system-wide (such as from package manager).
Use `docker compose`
From the repository root, you could obtain middleware containers by typing docker compose -f compose.local-db.yml up -d.
Use Devcontainer
Devcontainer also has necessary setting. This method can be done by connecting from VSCode.
Instead of running pnpm locally, you can use Dev Container to set up your development environment.
To use Dev Container, open the project directory on VSCode with Dev Containers installed.
Note: If you are using Windows, please clone the repository with WSL. Using Git for Windows will result in broken files due to the difference in how newlines are handled.
It will run the following command automatically inside the container.
git submodule update --init
pnpm install --frozen-lockfile
cp .devcontainer/devcontainer.yml .config/default.yml
pnpm build
pnpm migrateAfter finishing the migration, you can proceed.
Cloudflare tunnel
Cloudflare tunnelを使うとローカルのMisskeyサーバーをインターネットに公開できます。
HTTPSでしか動作しない機能を検証したい時や、スマホなど別のデバイスからローカルのMisskeyサーバーを検証したい時に便利です。
Cloudflare warpと併用する際のtips
cloudflared (Cloudflare Tunnel) は region1.v2.argotunnel.com / region2.v2.argotunnel.com に QUIC/HTTP2 でアウトバウンド接続するのですが、WARP を有効化するとこのトラフィックが WARP 経由になってループ/切断します。これら 2 ホストを WARP のトンネル除外(split tunnel)に追加することで、cloudflared だけは WARP をバイパスして直接 Cloudflare エッジへ接続できるようになります。
Start developing
During development, it is useful to use the
pnpm devcommand.
- Server-side source files and automatically builds them if they are modified. Automatically start the server process(es).
- Service Worker is watched by esbuild.
- Vite HMR (just the
vitecommand) is available. The behavior may be different from production. - Vite runs behind the backend (the backend will proxy Vite at /vite and /embed_vite except for websocket used for HMR).
- You can see Misskey by accessing
http://localhost:3000(Replace3000with the port configured withportin .config/default.yml).
Environment Variable
MISSKEY_CONFIG_YML: Specify the file path of config.yml instead of default.yml (e.g.2nd.yml).MISSKEY_WEBFINGER_USE_HTTP: If it's set true, WebFinger requests will be http instead of https, useful for testing federation between servers in localhost. NEVER USE IN PRODUCTION.
How to resolve conflictions occurred at pnpm-lock.yaml?
Just execute pnpm to fix it.
Contributing Frontend (`docs/contributing/frontend.md`)
Frontend
フロントエンドの実装・レビューを行う人向け。
Vue
Misskey uses Vue(v3) as its front-end framework.
- Use TypeScript.
- When creating a new component, please use the Composition API (with
<script setup>,ref, andcomputed) instead of the Options API.- Some of the existing components are implemented in the Options API, but it is an old implementation. Refactors that migrate those components to the Composition API are also welcome.
Tabler Icons
アイコンは、Production Build時に使用されていないものが削除されるようになっています。
アイコンを動的に設定する際には、 ti-${someVal} のような、アイコン名のみを動的に変化させる実装を行わないでください。
必ず ti-xxx のような完全なクラス名を含めるようにしてください。
nirax
niraxは、Misskeyで使用しているオリジナルのフロントエンドルーティングシステムです。
vue-routerから影響を多大に受けているので、まずはvue-routerについて学ぶことをお勧めします。
ルート定義
ルート定義は、以下の形式のオブジェクトの配列です。
{
name?: string;
path: string;
component: Component;
query?: Record<string, string>;
loginRequired?: boolean;
hash?: string;
children?: RouteDef[];
}[!WARNING]
現状、ルートは定義された順に評価されます。
たとえば、/foo/:idルート定義の次に/foo/barルート定義がされていた場合、後者がマッチすることはありません。
複数のルーター
vue-routerとの最大の違いは、niraxは複数のルーターが存在することを許可している点です。
これにより、アプリ内ウィンドウでブラウザとは個別にルーティングすることなどが可能になります。
Storybook
Misskey uses Storybook for UI development.
Setup & Run
Setup
pnpm --filter misskey-js buildRun
pnpm --filter frontend storybook-devUsage
For components matched by the glob allowlist in packages/frontend/.storybook/generate.tsx, the story file (for example, MyComponent.stories.ts for MyComponent.vue) will be automatically generated by the compiled .storybook/generate.js script.
If your new component is not matched by the allowlist, add it to the components list in generate.tsx. Creating a .stories.impl.ts file alone does not add a component to the generation targets.
You can override the default story by creating a impl story file (MyComponent.stories.impl.ts).
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { StoryObj } from '@storybook/vue3';
import MyComponent from './MyComponent.vue';
export const Default = {
render(args) {
return {
components: {
MyComponent,
},
setup() {
return {
args,
};
},
computed: {
props() {
return {
...this.args,
};
},
},
template: '<MyComponent v-bind="props" />',
};
},
args: {
foo: 'bar',
},
parameters: {
layout: 'centered',
},
} satisfies StoryObj<typeof MyComponent>;If you want to opt-out from the automatic generation, create a MyComponent.stories.impl.ts file and add the following line to the file.
import MyComponent from './MyComponent.vue';
void MyComponent;You can override the component meta by creating a meta story file (MyComponent.stories.meta.ts).
export const argTypes = {
scale: {
control: {
type: 'range',
min: 1,
max: 4,
},
},
};Also, you can use msw to mock API requests in the storybook. Creating a MyComponent.stories.msw.ts file to define the mock handlers.
import { HttpResponse, http } from 'msw';
export const handlers = [
http.post('/api/notes/timeline', ({ request }) => {
return HttpResponse.json([]);
}),
];After changing the allowlist or adding, editing, or removing the above files, run pnpm --filter frontend build-storybook-pre from the repository root to compile and run the generator again.
コネクションには`markRaw`せよ
Vueのコンポーネントのdataオプションとしてmisskey.jsのコネクションを設定するとき、必ずmarkRawでラップしてください。インスタンスが不必要にリアクティブ化されることで、misskey.js内の処理で不具合が発生するとともに、パフォーマンス上の問題にも繋がる。なお、Composition APIを使う場合はこの限りではない(リアクティブ化はマニュアルなため)。
コンポーネントのスタイル定義でmarginを持たせない
コンポーネント自身がmarginを設定するのは問題の元となることはよく知られている
marginはそのコンポーネントを使う側が設定する
HTMLのクラス名で follow という単語は使わない
広告ブロッカーで誤ってブロックされる
CSS Recipe
Lighten CSS vars
color: hsl(from var(--MI_THEME-accent) h s calc(l + 10));Darken CSS vars
color: hsl(from var(--MI_THEME-accent) h s calc(l - 10));Add alpha to CSS vars
color: color(from var(--MI_THEME-accent) srgb r g b / 0.5);Contributing Maintainer Guide (`docs/contributing/maintainer-guide.md`)
Maintainer guide
Issue のトリアージ、レビュー、デプロイ、リリースを行うメンテナー向け。
Issue assignment
To the Committers: you should not assign someone on the Issue before the Final Decision.
How issues are triaged
The Committers may:
- close an issue that is not reproducible on latest stable release,
- merge an issue into another issue,
- split an issue into multiple issues,
- or re-open that has been closed for some reason which is not applicable anymore.
@syuilo reserves the Final Decision rights including whether the project will implement feature and how to implement, these rights are not always exercised.
Reviewers guide
Be willing to comment on the good points and not just the things you want fixed 💯
読んでおくといいやつ
- https://blog.lacolaco.net/posts/1e2cf439b3c2/
- https://konifar-zatsu.hatenadiary.jp/entry/2024/11/05/192421
Review perspective
- Scope
- Are the goals of the PR clear?
- Is the granularity of the PR appropriate?
- Security
- Does merging this PR create a vulnerability?
- Performance
- Will merging this PR cause unexpected performance degradation?
- Is there a more efficient way?
- Testing
- Does the test ensure the expected behavior?
- Are there any omissions or gaps?
- Does it check for anomalies?
Security Advisory
報告者向けの案内は SECURITY.md を参照。
For misskey-dev member
修正PRがdevelopに追従されていないとマージできないので、マージできなかったら
Could you merge or rebase onto upstream develop branch?
などと伝える。
Deploy
The /deploy command by issue comment can be used to deploy the contents of a PR to the preview environment.
/deploy sha=<commit hash>An actual domain will be assigned so you can test the federation.
Merge
Release
Release Instructions
- Commit version changes in the
developbranch (package.json) - Create a release PR.
- Into
masterfromdevelopbranch. - The title must be in the format
Release: x.y.z.x.y.zis the new version you are trying to release.
- Into
- Deploy and perform a simple QA check. Also verify that the tests passed.
- Merge it. (Do not squash commit)
- Create a release of GitHub
- The target branch must be
master - The tag name must be the version
- The target branch must be
[!NOTE]
Why this instruction is necessary:
- To perform final QA checks
- To distribute responsibility
- To check direct commits to develop
- To celebrate the release together 🎉
Contributing Testing (`docs/contributing/testing.md`)
Testing
変更の検証・テストの追加を行う人向け。
You can run non-backend tests by executing following commands:
pnpm --filter frontend test
pnpm --filter misskey-js testBackend tests require manual preparation of servers. See the next section for more on this.
Backend
There are three types of test codes for the backend:
- Unit tests:
/packages/backend/test/unit - Single-server E2E tests:
/packages/backend/test/e2e - Multiple-server E2E tests:
/packages/backend/test-federation
Running Unit Tests or Single-server E2E Tests
- Create a config file:
cp .github/misskey/test.yml .config/- Start DB and Redis servers for testing:
docker compose -f packages/backend/test/compose.yml upInstead, you can prepare an empty (data can be erased) DB and edit .config/test.yml appropriately.
- Run all tests:
pnpm --filter backend test # unit tests
pnpm --filter backend test:e2e # single-server E2E testsIf you want to run a specific test, run as a following command:
pnpm --filter backend test -- packages/backend/test/unit/activitypub.ts
pnpm --filter backend test:e2e -- packages/backend/test/e2e/nodeinfo.tsRunning Multiple-server E2E Tests
See /packages/backend/test-federation/README.md.
Continuous integration
Misskey uses GitHub Actions for executing automated tests.
Configuration files are located in /.github/workflows.
Packages Misskey Js Docs CONTRIBUTING.En (`packages/misskey-js/docs/CONTRIBUTING.en.md`)
Contribution guide
:v: Thanks for your contributions :v:
ℹ️ Important: This project uses Japanese as its major language, but you do not need to translate and write the Issues/PRs in Japanese.
Also, you might receive comments on your Issue/PR in Japanese, but you do not need to reply to them in Japanese as well.
The accuracy of translation into Japanese is not high, so it will be easier for us to understand if you write it in the original language.
It will also allow the reader to use the translation tool of their preference if necessary.
Issues
Before creating an issue, please check the following:
- To avoid duplication, please search for similar issues before creating a new issue.
- Do not use Issues as a question.
- Issues should only be used to feature requests, suggestions, and report problems.
- Please ask questions in GitHub Discussions or Discord.
Creating a PR
Thank you for your PR! Before creating a PR, please check the following:
- If possible, prefix the title with a keyword that identifies the type of this PR, as shown below.
- fix / refactor / feat / enhance / perf / chore etc.
- Also, make sure that the granularity of this PR is appropriate. Please do not include more than one type of change or interest in a single PR.
- If there is an Issue which will be resolved by this PR, please include a reference to the Issue in the text.
- Please add the summary of the changes to
CHANGELOG.md. However, this is not necessary for changes that do not affect the users, such as refactoring. - Check if there are any documents that need to be created or updated due to this change.
- If you have added a feature or fixed a bug, please add a test case if possible.
- Please make sure that tests and Lint are passed in advance.
- You can run it with
npm run testandnpm run lint.
- You can run it with
- Run
npm run apito update the API report and commit it if there are any diffs.
Thanks for your cooperation 🤗
--- METRICS ---
- Files Extracted: 19
- Estimated Token Budget: ~9662 tokens
- Canonical Reference: https://codewiki.google/github.com/misskey-dev/misskey