この例では、git-repo-per-sandbox の Sandbox SDK テンプレートを使い、Artifacts 固有の部分を取り上げます。
Sandbox で Claude Code を実行する に示すとおり、create cloudflare でテンプレートから始めます。そのあと、次の抜粋で Artifacts の流れに合わせます。
- ID でサンドボックスを作成または再利用します。
- 同じ ID で Artifacts リポジトリを作成または再利用します。
- 認証済みの Git remote を、
ARTIFACTS_GIT_REMOTEとしてサンドボックスに渡します。
npm create cloudflare@latest -- repo-per-sandbox --template=cloudflare/sandbox-sdk/examples/git-repo-per-sandboxyarn create cloudflare repo-per-sandbox --template=cloudflare/sandbox-sdk/examples/git-repo-per-sandboxpnpm create cloudflare@latest repo-per-sandbox --template=cloudflare/sandbox-sdk/examples/git-repo-per-sandboxcd repo-per-sandboxこのテンプレートは、サンドボックス ID ごとに Artifacts リポジトリを 1 つ保持します。このリクエストで新しいリポジトリを作るか、既存のものを読み込むかは、独自の信頼できる情報源で判断します。
let defaultBranch;
let remote;
let token;
const sandboxWasJustCreated = true; // for example, set this when you create a new sandbox record
if (sandboxWasJustCreated) {
const created = await env.ARTIFACTS.create(sandboxId);
defaultBranch = created.defaultBranch;
remote = created.remote;
token = created.token;
} else {
const repo = await env.ARTIFACTS.get(sandboxId);
defaultBranch = repo.defaultBranch;
remote = repo.remote;
token = (await repo.createToken("write", 3600)).plaintext;
}let defaultBranch: string;
let remote: string;
let token: string;
const sandboxWasJustCreated = true; // for example, set this when you create a new sandbox record
if (sandboxWasJustCreated) {
const created = await env.ARTIFACTS.create(sandboxId);
defaultBranch = created.defaultBranch;
remote = created.remote;
token = created.token;
} else {
const repo = await env.ARTIFACTS.get(sandboxId);
defaultBranch = repo.defaultBranch;
remote = repo.remote;
token = (await repo.createToken("write", 3600)).plaintext;
}テンプレートはすでにリポジトリ名を把握しているので、list() のページを走査するのではなく、直接取得から始めます。ここでの広い catch ブロックは避けてください。見つからないリポジトリ、認証、検証の失敗が、同じ再試行メッセージに隠れてしまいます。
リポジトリ作成と競合しうる流れなら、スローされたエラーを確認したうえで、アプリケーション側で再試行を処理します。
サンドボックスにも同じ ID を使います。
import { getSandbox } from "@cloudflare/sandbox";
const sandbox = getSandbox(env.Sandbox, sandboxId);import { getSandbox } from "@cloudflare/sandbox";
const sandbox = getSandbox(env.Sandbox, sandboxId);write トークンを認証済み Git remote に変換し、サンドボックス内の環境変数として保存します。
短命なトークンを使い、サンドボックスセッションが変更のプッシュを認可されたあとでのみ、サンドボックスに渡します。
function toAuthenticatedRemote(remote, token) {
const tokenSecret = token.split("?expires=")[0];
return `https://x:${tokenSecret}@${remote.slice("https://".length)}`;
}
await sandbox.setEnvVars({
ARTIFACTS_GIT_REMOTE: toAuthenticatedRemote(remote, token),
});function toAuthenticatedRemote(remote: string, token: string) {
const tokenSecret = token.split("?expires=")[0];
return `https://x:${tokenSecret}@${remote.slice("https://".length)}`;
}
await sandbox.setEnvVars({
ARTIFACTS_GIT_REMOTE: toAuthenticatedRemote(remote, token),
});サンドボックス内で動くコードは、ARTIFACTS_GIT_REMOTE を git clone、git fetch、git pull、git push と組み合わせて使えます。