此示例使用 git-repo-per-sandbox 沙盒 SDK 模板,并着重介绍 Artifacts 特有的部分。
从使用 create cloudflare 的模板开始,如在沙盒上运行 Claude Code 中所示。然后使用下面针对性的代码片段来适应 Artifacts 流程。
- 通过 ID 创建或重用沙盒。
- 使用相同的 ID 创建或重用 Artifacts 仓库。
- 将已认证的 Git 远程连接作为
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 仓库。请使用您自己的唯一事实来源(source of truth)来决定此请求是应该创建一个新仓库还是加载一个现有的仓库。
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);将写入令牌转换为已认证的 Git 远程连接,然后将其作为环境变量存储在沙盒中。
使用短期令牌,并且仅在沙盒会话被授权推送更改后才将其传入沙盒。
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),
});沙盒内运行的代码随后即可在 git clone、git fetch、git pull 或 git push 中使用 ARTIFACTS_GIT_REMOTE。