Bundles
번들은 Capgo의 핵심 업데이트 패키지입니다. 각 번들에는 앱 콘텐츠를 구성하는 웹 자산(HTML, CSS, JS)이 포함되어 있습니다. API 번들을 사용하면 이러한 업데이트 패키지 나열 및 삭제를 포함하여 관리할 수 있습니다.
번들 이해하기
Section titled “번들 이해하기”번들은 앱 웹 콘텐츠의 특정 번들(버전)을 나타내며 다음을 포함합니다.
- 번들(버전): 번들의 의미론적 버전 번호
- 체크섬: 번들 무결성을 확인하기 위한 고유 해시
- 저장 정보: 번들이 저장되는 위치와 방법에 대한 세부정보
- 기본 요구 사항: 최소 기본 앱 버전 요구 사항
- 메타데이터: 생성 시간, 소유권, 기타 추적 정보
수동 번들 생성(CLI 제외)
Section titled “수동 번들 생성(CLI 제외)”Capgo CLI을 사용하지 않고 수동으로 번들을 생성하고 업로드하는 방법은 다음과 같습니다.
1단계: 앱 구축
Section titled “1단계: 앱 구축”먼저 앱의 웹 자산을 구축합니다.
npm run build2단계: Capgo CLI과 동일한 패키지를 사용하여 번들 Zip 생성
Section titled “2단계: Capgo CLI과 동일한 패키지를 사용하여 번들 Zip 생성”중요: 호환성을 보장하기 위해 Capgo CLI가 내부적으로 사용하는 것과 정확히 동일한 JavaScript 패키지를 사용하십시오.
필수 패키지 설치
Section titled “필수 패키지 설치”npm install adm-zip @tomasklaen/checksumJavaScript을 사용하여 Zip 번들 생성(Capgo CLI과 동일)
Section titled “JavaScript을 사용하여 Zip 번들 생성(Capgo CLI과 동일)”참고: 아래 예에서 version는 API에서 사용되는 번들(버전) 이름을 나타냅니다.
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 체크섬 계산
Section titled “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단계: 스토리지에 번들 업로드
Section titled “4단계: 스토리지에 번들 업로드”웹에서 액세스할 수 있는 저장소에 zip 파일을 업로드하세요.
# 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"중요: 번들은 HTTPS URL을 통해 공개적으로 액세스 가능해야 합니다(인증 필요 없음). Capgo의 서버는 이 URL에서 번들을 다운로드해야 합니다.
유효한 공개 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에 번들 등록
Section titled “5단계: Capgo API에 번들 등록”직접 API 호출을 사용하여 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 매개변수
Section titled “API 매개변수”| 매개변수 | 설명 | 필수 |
|---|---|---|
app_id | 앱 식별자 | 예 |
version | 번들(버전) 의미 버전(예: “1.2.3”) | 예 |
external_url | 공개적으로 액세스 가능 번들을 다운로드할 수 있는 HTTPS URL(인증 필요 없음) | 예 |
checksum | zip 파일의 SHA256 체크섬 | 예 |
번들 구조 요구사항
Section titled “번들 구조 요구사항”번들 zip은 다음 요구 사항을 따라야 합니다.
- 루트 인덱스 파일: 루트 수준에
index.html이 있어야 합니다. - Capacitor 통합: 앱 코드에서
notifyAppReady()을 호출해야 합니다. - 자산 경로: 모든 자산에 대해 상대 경로를 사용합니다.
유효한 번들 구조
Section titled “유효한 번들 구조”bundle.zip├── index.html├── assets/│ ├── app.js│ └── styles.css└── images/완전한 수동 작업흐름 예시
Section titled “완전한 수동 작업흐름 예시”압축, 체크섬 및 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-fetch체크섬 확인
Section titled “체크섬 확인”JavaScript 체크섬 계산(Capgo CLI과 동일)
Section titled “JavaScript 체크섬 계산(Capgo CLI과 동일)”Capgo CLI가 내부적으로 사용하는 것과 정확히 동일한 패키지 및 방법을 사용하십시오.
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();```### 체크섬 중요성
- **번들 무결성**: 전송 중에 번들이 손상되지 않았는지 확인합니다.- **API 확인**: Capgo는 번들을 수락하기 전에 체크섬을 확인합니다.- **플러그인 확인**: 모바일 플러그인은 업데이트를 적용하기 전에 체크섬을 확인합니다.
## 모범 사례
1. **번들(버전) 관리**: 의미론적 버전 관리를 일관되게 사용합니다.2. **스토리지 최적화**: 사용하지 않는 번들을 주기적으로 제거3. **번들(버전) 호환성**: 적절한 최소 기본 버전 요구 사항을 설정합니다.4. **백업 전략**: 중요한 번들(버전)의 백업을 유지합니다.
## 엔드포인트
### 받기
`https://api.capgo.app/bundle/`
번들 정보를 검색합니다. 페이지당 50개의 번들을 반환합니다.
#### 쿼리 매개변수- `app_id`: 필수입니다. 앱의 ID- `page`: 선택 사항입니다. 페이지 매김을 위한 페이지 번호
#### 응답 유형
```typescriptinterface 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"{ "data": [ { "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/
앱의 번들 하나 또는 모두를 삭제합니다. 이 작업은 취소할 수 없으므로 주의하여 사용하세요.
쿼리 매개변수
Section titled “쿼리 매개변수”특정 번들을 삭제하려면:
interface BundleDelete { app_id: string version: string}모든 번들을 삭제하려면:
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"}https://api.capgo.app/bundle/
외부 URL을 사용하여 새 번들을 생성합니다.
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(메타데이터)
Section titled “POST(메타데이터)”https://api.capgo.app/bundle/metadata
링크 및 댓글 정보와 같은 번들 메타데이터를 업데이트합니다.
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"}https://api.capgo.app/bundle/
번들을 특정 채널로 설정합니다. 이는 배포용 채널에 번들(버전)을 연결합니다.
interface SetChannelBody { app_id: string version_id: number // bundle (version) id channel_id: number}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"}일반적인 오류 시나리오 및 대응:
// Bundle not found{ "error": "Bundle not found", "status": "KO"}
// Invalid bundle (version) format{ "error": "Invalid version format", "status": "KO"}
// Storage error{ "error": "Failed to delete bundle from storage", "status": "KO"}
// Permission denied{ "error": "Insufficient permissions to manage bundles", "status": "KO"}일반적인 사용 사례
Section titled “일반적인 사용 사례”- 이전 번들 정리(버전)
// 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"}스토리지 고려 사항
Section titled “스토리지 고려 사항”- 보존 정책: 이전 번들을 보관할 기간을 정의합니다.
- 크기 관리: 번들 크기 및 스토리지 사용량 모니터링
- 백업 전략: 중요한 번들(버전) 백업을 고려하세요.
- 비용 최적화: 불필요한 번들을 제거하여 스토리지 비용 최적화