Bundle
复制包含安装步骤和该插件完整 Markdown 指南的配置 prompt。
Bundle 是 Capgo 中的核心更新包。每个 Bundle 都包含构成应用内容的 Web 资源(HTML、CSS、JS)。通过 Bundles API,你可以管理这些更新包,包括列出和删除它们。
了解 Bundle
标题为“了解 Bundle”的章节一个 Bundle 代表应用 Web 内容的一个特定版本,包含:
- Bundle(版本): 语义化版本号 用于该 Bundle
- 校验和: 用于验证 bundle 完整性的唯一哈希值
- 存储信息: 关于 bundle 存储位置及方式的详情
- 原生要求: 原生 App 最低版本要求
- 元数据: 创建时间、所有权及其他追踪信息
手动创建 Bundle(不使用 CLI)
标题为“手动创建 Bundle(不使用 CLI)”的部分以下是在不使用 Capgo CLI 的情况下,手动创建并上传 bundle 的步骤:
第 1 步:构建您的 App
第 1 步:构建您的 App首先,构建 App 的 Web 资源:
npm run build步骤 2:使用与 Capgo CLI 相同的包创建 Bundle Zip
第 2 步:使用与 Capgo CLI 相同的包创建 Bundle Zip重要提示:请使用与 Capgo CLI 内部完全一致的 JavaScript 包,以确保兼容性。
安装所需依赖包
安装所需依赖包npm install adm-zip @tomasklaen/checksum使用 JavaScript 创建 Zip Bundle(与 Capgo CLI 相同)
章节标题:“使用 JavaScript 创建 Zip Bundle(与 Capgo CLI 相同)”注意:在以下示例中, version 指的是 API 使用的 bundle(版本)名称。
const fs = require('node:fs');const path = require('node:path');const os = require('node:os');const AdmZip = require('adm-zip');const { checksum: getChecksum } = require('@tomasklaen/checksum');
// Exact same implementation as Capgo CLIfunction zipFileUnix(filePath) { const zip = new AdmZip(); zip.addLocalFolder(filePath); return zip.toBuffer();}
async function zipFileWindows(filePath) { console.log('Zipping file windows mode'); const zip = new AdmZip();
const addToZip = (folderPath, zipPath) => { const items = fs.readdirSync(folderPath);
for (const item of items) { const itemPath = path.join(folderPath, item); const stats = fs.statSync(itemPath);
if (stats.isFile()) { const fileContent = fs.readFileSync(itemPath); zip.addFile(path.join(zipPath, item).split(path.sep).join('/'), fileContent); } else if (stats.isDirectory()) { addToZip(itemPath, path.join(zipPath, item)); } } };
addToZip(filePath, ''); return zip.toBuffer();}
// Main zipFile function (exact same logic as CLI)async function zipFile(filePath) { if (os.platform() === 'win32') { return zipFileWindows(filePath); } else { return zipFileUnix(filePath); }}
async function createBundle(inputPath, outputPath, version) { // Create zip using exact same method as Capgo CLI const zipped = await zipFile(inputPath);
// Write to file fs.writeFileSync(outputPath, zipped);
// Calculate checksum using exact same package as CLI const checksum = await getChecksum(zipped, 'sha256');
return { filename: path.basename(outputPath), version: version, size: zipped.length, checksum: checksum };}
// Usageasync function main() { try { const result = await createBundle('./dist', './my-app-1.2.3.zip', '1.2.3'); console.log('Bundle info:', JSON.stringify(result, null, 2)); } catch (error) { console.error('Error creating bundle:', error); }}
main();步骤 3:使用与 CLI 相同的包计算 SHA256 Checksum
章节标题:“步骤 3:使用与 CLI 相同的包计算 SHA256 校验和”const fs = require('node:fs');const { checksum: getChecksum } = require('@tomasklaen/checksum');
async function calculateChecksum(filePath) { const fileBuffer = fs.readFileSync(filePath); // Use exact same package and method as Capgo CLI const checksum = await getChecksum(fileBuffer, 'sha256'); return checksum;}
// Usageasync function main() { const checksum = await calculateChecksum('./my-app-1.2.3.zip'); console.log('Checksum:', checksum);}
main();步骤 4:将 Bundle 上传至您的存储服务
章节标题:“步骤 4:上传 Bundle 到你的存储”将你的 zip 文件上传到任意可通过 Web 访问的存储:
# Example: Upload to your server via scpscp my-app-1.2.3.zip user@your-server.com:/var/www/bundles/
# Example: Upload to S3 using AWS CLIaws s3 cp my-app-1.2.3.zip s3://your-bucket/bundles/
# Example: Upload via curl to a custom endpointcurl -X POST https://your-storage-api.com/upload \ -H "Authorization: Bearer YOUR_TOKEN" \ -F "file=@my-app-1.2.3.zip"重要提示: 您的 bundle 必须 可通过 HTTPS URL 公开访问 (无需身份验证)。Capgo 的服务器需要从该 URL 下载 bundle。
有效的公开 URL 示例:
https://your-storage.com/bundles/my-app-1.2.3.ziphttps://github.com/username/repo/releases/download/v1.2.3/bundle.ziphttps://cdn.jsdelivr.net/gh/username/repo@v1.2.3/dist.zip
步骤 5:在 Capgo API 中注册 Bundle
标题为“第 5 步:使用 API 向 Capgo 注册 Bundle”的章节使用直接的 API 调用将外部 bundle 注册到 Capgo:
async function registerWithCapgo(appId, version, bundleUrl, checksum, apiKey) { const fetch = require('node-fetch');
// Create bundle (version) const response = await fetch('https://api.capgo.app/bundle/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'authorization': apiKey }, body: JSON.stringify({ app_id: appId, version: version, external_url: bundleUrl, checksum: checksum }) });
if (!response.ok) { throw new Error(`Failed to create bundle: ${response.statusText}`); }
const data = await response.json(); console.log('Bundle created:', data);
return data;}API 参数
标题为“API 参数”的章节| 参数 | 描述 | 必填 |
|---|---|---|
app_id | 应用标识符 | 是 |
version | Bundle(版本) 语义化版本号 (例如 “1.2.3”) | 是 |
external_url | 可公开访问 可下载 bundle 的 HTTPS URL(无需认证) | 是 |
checksum | zip 文件的 SHA256 校验和 | 是 |
Bundle 结构要求
标题为“Bundle 结构要求”的部分您的 bundle zip 必须符合以下要求:
- 根目录索引文件:必须包含
index.html在根层级 - Capacitor 集成:必须调用
notifyAppReady()在您的应用 code 中 - 资源路径:所有资源请使用相对路径
有效的 Bundle 结构
“有效 Bundle 结构”章节bundle.zip├── index.html├── assets/│ ├── app.js│ └── styles.css└── images/完整手动工作流示例
“完整手动工作流示例”章节用于压缩、校验并上传至 Capgo 的简单 Node.js 脚本:
const fs = require('node:fs');const os = require('node:os');const AdmZip = require('adm-zip');const { checksum: getChecksum } = require('@tomasklaen/checksum');const fetch = require('node-fetch');
async function deployToCapgo() { const APP_ID = 'com.example.app'; const VERSION = '1.2.3'; const BUNDLE_URL = 'https://your-storage.com/bundles/app-1.2.3.zip'; const API_KEY = process.env.CAPGO_API_KEY;
// 1. Create zip (same as Capgo CLI) const zip = new AdmZip(); zip.addLocalFolder('./dist'); const zipped = zip.toBuffer();
// 2. Calculate checksum (same as Capgo CLI) const checksum = await getChecksum(zipped, 'sha256'); console.log('Checksum:', checksum);
// 3. Upload to your storage (replace with your upload logic) // fs.writeFileSync('./bundle.zip', zipped); // ... upload bundle.zip to your storage ...
// 4. Register with Capgo API const response = await fetch('https://api.capgo.app/bundle/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'authorization': API_KEY }, body: JSON.stringify({ app_id: APP_ID, version: VERSION, external_url: BUNDLE_URL, checksum: checksum }) });
if (!response.ok) { throw new Error(`Failed: ${response.statusText}`); }
console.log('Bundle registered with Capgo!');}
deployToCapgo().catch(console.error);安装依赖:
npm install adm-zip @tomasklaen/checksum node-fetchChecksum 校验
“校验和验证”章节JavaScript Checksum 计算(与 Capgo CLI 一致)
“JavaScript 校验和计算 (与 Capgo CLI 一致)”章节请使用与 Capgo CLI 内部完全相同的 package 和 method:
const fs = require('node:fs');const { checksum: getChecksum } = require('@tomasklaen/checksum');
async function calculateChecksum(filePath) { const fileBuffer = fs.readFileSync(filePath); // Use exact same package and method as Capgo CLI const checksum = await getChecksum(fileBuffer, 'sha256'); return checksum;}
// Verify checksum matchesasync function verifyChecksum(filePath, expectedChecksum) { const actualChecksum = await calculateChecksum(filePath); const isValid = actualChecksum === expectedChecksum;
console.log(`File: ${filePath}`); console.log(`Expected: ${expectedChecksum}`); console.log(`Actual: ${actualChecksum}`); console.log(`Valid: ${isValid}`);
return isValid;}
// Usageasync function main() { const bundleChecksum = await calculateChecksum('./my-app-1.2.3.zip'); console.log('SHA256 Checksum:', bundleChecksum);}
main();Checksum 的重要性
“校验和的重要性”章节- Bundle 完整性: 确保 bundle 在传输过程中未损坏
- API 验证: Capgo 在接收 bundle 前会验证校验和
- Plugin 验证: 移动端插件在应用更新前会校验 checksum
最佳实践
标题为“最佳实践”的章节- Bundle(版本)管理:使用 语义化版本 始终如一地
- 存储优化: 定期清理不再使用的 bundle
- Bundle(版本)兼容性: 设置合理的最低 Native 版本要求
- 备份策略: 备份关键 bundle (版本)
GET
“GET”章节https://api.capgo.app/bundle/
获取 bundle 信息。不使用过滤器时,每页返回 50 个 bundle。使用 version 或 id,则返回包含零个或一个 bundle 的相同 JSON 数组结构。
查询参数
标题为“查询参数”的章节app_id:必填。您的应用 IDpage:可选。用于分页的页码(当version或id已设置)version: 可选。精确的 bundle 版本名称 (app_versions.name,例如1.2.3)。返回包含零个或一个元素的 JSON 数组。id: 可选。数字 bundle id (app_versions.id)。返回包含零个或一个元素的 JSON 数组。
使用与分页列表相同的 authorization header 和 API 键进行 app scoping。被 query-schema 校验拒绝的值将返回 invalid_query 错误。
检查版本是否存在 (CI)
标题为“检查版本是否存在 (CI)”的章节在 upload 或分配 channel 前,如果需要用 HTTP 检查代替 CLI,请使用此接口:
curl -H "authorization: YOUR_API_KEY" \ "https://api.capgo.app/bundle/?app_id=com.example.app&version=1.2.3"非空 JSON 数组表示该 app 已存在此版本;空数组则表示不存在。
在 upload 工作流中,Capgo CLI 标志 bundle upload --version-exists-ok 当目标版本已存在时,它已经会成功退出,这覆盖了许多无需调用此 endpoint 的 CI 任务。
响应类型
标题为“响应类型”的章节interface Bundle { app_id: string bucket_id: string | null checksum: string | null created_at: string | null deleted: boolean external_url: string | null id: number minUpdateVersion: string | null name: string native_packages: Json[] | null owner_org: string r2_path: string | null session_key: string | null storage_provider: string updated_at: string | null user_id: string | null}请求示例
标题为“请求示例”的章节# Get all bundlescurl -H "authorization: your-api-key" \ "https://api.capgo.app/bundle/?app_id=app_123"
# Get next pagecurl -H "authorization: your-api-key" \ "https://api.capgo.app/bundle/?app_id=app_123&page=1"
# Look up one bundle by version namecurl -H "authorization: your-api-key" \ "https://api.capgo.app/bundle/?app_id=app_123&version=1.0.0"
# Look up one bundle by idcurl -H "authorization: your-api-key" \ "https://api.capgo.app/bundle/?app_id=app_123&id=456"响应示例
标题为“响应示例”的章节[ { "id": 1, "app_id": "app_123", "name": "1.0.0", "checksum": "abc123...", "minUpdateVersion": "1.0.0", "storage_provider": "r2", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z", "deleted": false, "owner_org": "org_123", "user_id": "user_123" }]https://api.capgo.app/bundle/
删除应用的一个或所有 bundle。请谨慎操作,此操作无法撤销。
查询参数
标题为“查询参数”的章节若要删除特定的 bundle:
interface BundleDelete { app_id: string version: string}若要删除所有 bundle:
interface BundleDeleteAll { app_id: string}请求示例
标题为“请求示例”的章节# Delete specific bundlecurl -X DELETE \ -H "authorization: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "app_id": "app_123", "version": "1.0.0" }' \ https://api.capgo.app/bundle/
# Delete all bundlescurl -X DELETE \ -H "authorization: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "app_id": "app_123" }' \ https://api.capgo.app/bundle/成功响应
“成功响应”章节{ "status": "ok"}POST
标题为“POST”的章节https://api.capgo.app/bundle/
使用外部 URL 创建新 bundle。
请求体
标题为“请求体”的章节interface CreateBundleBody { app_id: string version: string external_url: string // Must be publicly accessible HTTPS URL checksum: string}请求示例
标题为“请求示例”的章节curl -X POST \ -H "authorization: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "app_id": "com.example.app", "version": "1.2.3", "external_url": "https://your-storage.com/bundles/app-1.2.3.zip", "checksum": "a1b2c3d4e5f6789abcdef123456789abcdef123456789abcdef123456789abcd" }' \ https://api.capgo.app/bundle/成功响应
“成功响应”章节{ "status": "ok"}POST (元数据)
标题为 “POST (Metadata)” 的章节https://api.capgo.app/bundle/metadata
更新 bundle 的元数据,例如链接和注释信息。
请求体
标题为“请求体”的章节interface UpdateMetadataBody { app_id: string version_id: number // bundle (version) id link?: string comment?: string}请求示例
标题为“请求示例”的章节curl -X POST \ -H "authorization: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "app_id": "app_123", "version_id": 456, "link": "https://github.com/myorg/myapp/releases/tag/v1.0.0", "comment": "Fixed critical bug in authentication" }' \ https://api.capgo.app/bundle/metadata成功响应
“成功响应”章节{ "status": "success"}PUT
“PUT”章节https://api.capgo.app/bundle/
将 bundle 设置到特定 channel。这将 bundle (版本) 与用于分发的 channel 进行关联。
请求体
标题为“请求体”的章节interface SetChannelBody { app_id: string version_id: number // bundle (version) id channel_id: number target?: "auto" | "stable" | "rollout" // default: auto}target 当 channel 配置了渐进式发布 (progressive rollout) 时,控制 bundle 的关联位置:
auto— 配置了渐进式发布时的发布目标;否则为 stable (默认值)。rollout— 始终设置发布目标;stable 回退机制保持不变。stable— 替换 stable 回退机制 (紧急出口)。
请求示例
标题为“请求示例”的章节curl -X PUT \ -H "authorization: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "app_id": "app_123", "version_id": 456, "channel_id": 789 }' \ https://api.capgo.app/bundle/成功响应
“成功响应”章节{ "status": "success", "message": "Bundle 1.0.0 set to channel production"}错误处理
“错误处理”章节所有错误均采用以下文档中描述的标准错误格式: API 概览.
常见的错误场景及其响应:
// app_id is not a reverse-domain identifier{ "error": "invalid_app_id", "message": "App ID must be a reverse domain string", "moreInfo": { "app_id": "my app" }}
// Deleting a bundle without access to the app{ "error": "cannot_delete_bundle", "message": "You can't access this app", "moreInfo": { "app_id": "com.example.app" }}
// Deleting a bundle that a channel still uses{ "error": "cannot_delete_linked_version", "message": "Cannot delete a bundle linked to a channel", "moreInfo": { "app_id": "com.example.app", "version": "1.0.0" }}
// Creating a bundle whose version is not valid semver{ "error": "invalid_version_format", "message": "Version must be valid semver format (e.g., 1.0.0, 1.0.0-alpha.1)", "moreInfo": { "version": "v1" }}
// Setting a channel to a bundle that does not exist{ "error": "cannot_find_version", "message": "Cannot find version", "moreInfo": {}}常见用例
“常见用例”章节- 清理旧 Bundle (版本)
// Delete outdated beta bundles (versions){ "app_id": "app_123", "version": "1.0.0-beta.1"}- 应用重置
// Remove all bundles to start fresh{ "app_id": "app_123"}存储注意事项
标题为“存储注意事项”的章节- 保留策略: 定义旧 bundle 的保留时长
- 容量管理: 监控 bundle 大小和存储占用
- 备份策略: 考虑备份关键 bundle (版本)
- 成本优化: 删除不必要的 bundle 以优化存储成本
从 Bundles 继续
“从 Bundles 继续”章节如果你正在使用 Bundle 要规划存储和文件处理,请将其与 @capgo/capacitor-data-storage-sqlite 关于 @capgo/capacitor-data-storage-sqlite 中的实现细节, 使用 @capgo/capacitor-data-storage-sqlite 关于使用 @capgo/capacitor-data-storage-sqlite 的原生能力, @capgo/capacitor-file 关于 @capgo/capacitor-file 中的实现细节, 使用 @capgo/capacitor-file 用于“使用 @capgo/capacitor-file”中的原生能力,以及 @capgo/capacitor-uploader 了解 @capgo/capacitor-uploader. 的实现细节