registerCloudflareWorker function
Register a generated Worker class className in the Worker entrypoint entry.
Ensures the named import of className from importPath and inserts
new [className]() into m.deploy([...]) if it is not registered yet.
Shows a warning if the other entrypoint (edge/region) also registers it.
Returns false if entry does not exist or the deploy array cannot be found.
生成したWorkerクラスclassNameをWorkerのエントリファイルentryに登録します。
importPathからのclassNameの名前付きimportを保証し、未登録の場合は
m.deploy([...])にnew [className]()を挿入します。
もう一方のエントリファイル(edge/region)にも登録されている場合は警告を表示します。
entryが存在しない場合やdeploy配列が見つからない場合はfalseを返します。
Implementation
Future<bool> registerCloudflareWorker({
required String entry,
required String className,
required String importPath,
}) async {
final file = File(entry);
if (!file.existsSync()) {
error(
"The file `$entry` does not exist. Run `katana apply` to initialize Cloudflare Workers first. `$entry`が存在しません。先に`katana apply`でCloudflare Workersを初期化してください。",
);
return false;
}
final original = await file.readAsString();
var source = original;
if (!CloudflareSourceUtils.containsFunctionCall(source, "new $className")) {
final updated = CloudflareSourceUtils.insertDeployFunctions(
source,
[" new $className(),"],
);
if (updated == null) {
error(
"Could not find the Cloudflare deploy array in `$entry`. Please register `new $className()` manually. `$entry`のdeploy配列が見つかりません。`new $className()`を手動で登録してください。",
);
return false;
}
source = updated;
}
source = CloudflareSourceUtils.ensureNamedImport(
source,
name: className,
from: importPath,
);
if (source != original) {
await file.writeAsString(source);
label("Registered `$className` in `$entry`.");
}
final other = entry == cloudflareRegionEntryPath
? cloudflareEdgeEntryPath
: cloudflareRegionEntryPath;
final otherFile = File(other);
if (otherFile.existsSync() &&
CloudflareSourceUtils.containsFunctionCall(
otherFile.readAsStringSync(),
"new $className",
)) {
label(
"WARNING: `$className` is also registered in `$other`. Remove it from either entrypoint if it is not intended. `$className`は`$other`にも登録されています。意図しない場合はどちらかから削除してください。",
);
}
return true;
}