feat(desktop): propose typo fixes inside the suggestion popup and make suggestions snappier
While suggestions are on, typos are no longer replaced silently. The popup shows the fix next to the candidate and applies it only when the candidate is accepted. The per-minute request cap rises from 6 to 20 so suggestions keep appearing after accepting one and continuing to type.
This commit is contained in:
parent
d63854db67
commit
f5ae4c8c04
38 changed files with 1239 additions and 660 deletions
|
|
@ -1,259 +0,0 @@
|
|||
// scripts/ci/publish-gitlab-release.mjs
|
||||
// 태그 파이프라인의 release 스테이지에서 실행:
|
||||
// 1) package-windows / package-macos artifacts를 GitLab Generic Package Registry에 업로드
|
||||
// - 버전별 경로: packages/generic/d3ro-voice/<version>/<file>
|
||||
// - latest 경로: packages/generic/d3ro-voice/latest/<file> (electron-updater feed)
|
||||
// 2) GitLab Release 생성 + asset 링크 연결
|
||||
//
|
||||
// agent-switchboard-client의 publish-gitlab-release.mjs 패턴을 D3RO에 맞게 단순화.
|
||||
// (Ed25519 update-policy 서명 체계는 후속 단계 — 현재는 latest.yml 기반)
|
||||
//
|
||||
// 필요 env: CI_API_V4_URL, CI_PROJECT_ID, CI_JOB_TOKEN, CI_COMMIT_TAG
|
||||
|
||||
import { createReadStream, readFileSync } from "node:fs";
|
||||
import { readFile, readdir, stat } from "node:fs/promises";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { basename, join } from "node:path";
|
||||
import process from "node:process";
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
const apiUrl = required("CI_API_V4_URL").replace(/\/+$/, "");
|
||||
const projectId = required("CI_PROJECT_ID");
|
||||
const jobToken = required("CI_JOB_TOKEN");
|
||||
const tag = required("CI_COMMIT_TAG");
|
||||
const version = tag.replace(/^v/, "");
|
||||
const packageName = "d3ro-voice";
|
||||
|
||||
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version)) {
|
||||
throw new Error(`Unsupported release tag: ${tag}`);
|
||||
}
|
||||
|
||||
const productVersion = JSON.parse(
|
||||
await readFile(fileURLToPath(new URL("../../release/product-version.json", import.meta.url)), "utf8"),
|
||||
);
|
||||
if (tag !== `v${productVersion.version}` || !/^\d+\.\d+\.\d+$/.test(version)) {
|
||||
throw new Error(`Release tag ${tag} does not match stable product version v${productVersion.version}.`);
|
||||
}
|
||||
|
||||
// electron-builder output: apps/desktop/release/<version>/
|
||||
const releaseDirectory = fileURLToPath(new URL(`../../apps/desktop/release/${version}/`, import.meta.url));
|
||||
|
||||
// 업로드 대상 수집 — 설치파일 + 업데이터 메타데이터만 (unpacked 디렉토리 제외)
|
||||
const ASSET_PATTERN = /(\.exe|\.dmg|\.zip|\.blockmap|^(latest|alpha|beta)(-mac|-linux)?\.yml)$/;
|
||||
|
||||
const files = [];
|
||||
for (const name of await readdir(releaseDirectory)) {
|
||||
if (!ASSET_PATTERN.test(name)) continue;
|
||||
const path = join(releaseDirectory, name);
|
||||
if ((await stat(path)).isFile()) files.push({ name, path });
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error(`No release assets found in ${releaseDirectory}`);
|
||||
}
|
||||
|
||||
const hasWindows = files.some((file) => file.name.endsWith(".exe"));
|
||||
if (!hasWindows) {
|
||||
throw new Error(`Windows installer is missing for ${tag}.`);
|
||||
}
|
||||
// latest.yml은 자동 업데이트 feed의 핵심 — 없으면 electron-builder publish 설정 회귀
|
||||
if (!files.some((file) => file.name === "latest.yml")) {
|
||||
throw new Error(
|
||||
`latest.yml is missing for ${tag} — check electron-builder.yml publish config.`,
|
||||
);
|
||||
}
|
||||
const hasMac = files.some((file) => file.name.endsWith(".dmg"));
|
||||
if (!hasMac) {
|
||||
// mac runner 미등록/실패 시에도 Windows 단독 릴리스는 진행 (경고만)
|
||||
process.stdout.write(`WARNING: macOS artifacts missing for ${tag} — Windows-only release.\n`);
|
||||
}
|
||||
|
||||
const packageBaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/packages/generic/${packageName}/${version}`;
|
||||
const latestPackageBaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/packages/generic/${packageName}/latest`;
|
||||
|
||||
const links = [];
|
||||
const sortedFiles = files.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
// 1) 버전별 패키지 업로드
|
||||
for (const file of sortedFiles) {
|
||||
const registryName = safeAssetName(file.name);
|
||||
const uploadUrl = `${packageBaseUrl}/${encodeURIComponent(registryName)}`;
|
||||
await uploadFile(file, uploadUrl, "versioned package");
|
||||
links.push({
|
||||
name: file.name,
|
||||
url: uploadUrl,
|
||||
direct_asset_path: `/${registryName}`,
|
||||
link_type: isUpdateMetadata(file.name) ? "other" : "package",
|
||||
});
|
||||
}
|
||||
|
||||
// 2) latest 패키지 갱신. 설치파일과 blockmap을 먼저 올리고, update metadata를
|
||||
// 마지막에 게시한다. 기존 latest를 선삭제하지 않으므로 배포 중에도 이전
|
||||
// 설치본이 404를 받지 않는다. 중복 업로드가 금지된 인스턴스라면 metadata
|
||||
// 전환 전에 실패해 기존 feed가 그대로 보존된다.
|
||||
const latestFiles = [...sortedFiles].sort((a, b) => {
|
||||
const metadataOrder = Number(isUpdateMetadata(a.name)) - Number(isUpdateMetadata(b.name));
|
||||
return metadataOrder || a.name.localeCompare(b.name);
|
||||
});
|
||||
for (const file of latestFiles) {
|
||||
const registryName = safeAssetName(file.name);
|
||||
await uploadFile(file, `${latestPackageBaseUrl}/${encodeURIComponent(registryName)}`, "latest package");
|
||||
}
|
||||
|
||||
for (const file of latestFiles.filter((candidate) => isYamlUpdateMetadata(candidate.name))) {
|
||||
validateUpdateMetadataReferences(file, latestFiles);
|
||||
}
|
||||
for (const file of latestFiles.filter((candidate) => isUpdateMetadata(candidate.name))) {
|
||||
await verifyPublicLatestFile(file, latestPackageBaseUrl);
|
||||
}
|
||||
|
||||
// 3) GitLab Release 생성 또는 재시도 시 안전하게 갱신
|
||||
const description = await buildDescription();
|
||||
const releaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/releases`;
|
||||
await upsertRelease(releaseUrl, description, links);
|
||||
|
||||
process.stdout.write(`Created ${tag} with ${links.length} release assets.\n`);
|
||||
|
||||
// ── 헬퍼 ────────────────────────────────────────────────────
|
||||
|
||||
function required(name) {
|
||||
const value = process.env[name]?.trim();
|
||||
if (!value) throw new Error(`${name} is required.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function safeAssetName(name) {
|
||||
return basename(name).replace(/[^A-Za-z0-9._-]+/g, "-");
|
||||
}
|
||||
|
||||
function isUpdateMetadata(name) {
|
||||
return /(?:\.blockmap$|^(?:latest|alpha|beta)(?:-mac|-linux)?\.yml$)/.test(name);
|
||||
}
|
||||
|
||||
function isYamlUpdateMetadata(name) {
|
||||
return /^(?:latest|alpha|beta)(?:-mac|-linux)?\.yml$/.test(name);
|
||||
}
|
||||
|
||||
async function buildDescription() {
|
||||
const changelog = await readFile(
|
||||
fileURLToPath(new URL("../../CHANGELOG.md", import.meta.url)),
|
||||
"utf8",
|
||||
);
|
||||
const section = extractChangelogSection(changelog, version);
|
||||
if (!section) throw new Error(`CHANGELOG.md is missing a ${version} release section.`);
|
||||
return section;
|
||||
}
|
||||
|
||||
function extractChangelogSection(changelog, targetVersion) {
|
||||
const lines = changelog.split("\n");
|
||||
// 버전 뒤 경계 필수 — "0.1.0"이 "0.1.0-alpha" 섹션에 오매칭되지 않게
|
||||
const escaped = targetVersion.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const headerPattern = new RegExp(`^##\\s+\\[?v?${escaped}(?:\\]|\\s|$)`);
|
||||
const start = lines.findIndex((line) => headerPattern.test(line));
|
||||
if (start === -1) return null;
|
||||
let end = lines.length;
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
if (/^##\s+/.test(lines[i])) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return lines.slice(start, end).join("\n").trim();
|
||||
}
|
||||
|
||||
async function uploadFile(file, uploadUrl, target) {
|
||||
process.stdout.write(`Uploading ${file.name} to ${target}...\n`);
|
||||
const response = await globalThis.fetch(uploadUrl, {
|
||||
method: "PUT",
|
||||
headers: { "JOB-TOKEN": jobToken },
|
||||
body: createReadStream(file.path),
|
||||
duplex: "half",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`${target} upload failed for ${file.name}: HTTP ${response.status} ${await response.text()}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateUpdateMetadataReferences(metadataFile, uploadedFiles) {
|
||||
const text = readFileSyncUtf8(metadataFile.path);
|
||||
const uploadedNames = new Set(uploadedFiles.map((file) => safeAssetName(file.name)));
|
||||
const references = [...text.matchAll(/^\s*(?:-\s+url:|path:)\s*["']?([^"'\r\n]+?)["']?\s*$/gm)]
|
||||
.map((match) => basename(match[1].trim()));
|
||||
if (references.length === 0) {
|
||||
throw new Error(`${metadataFile.name} does not reference a release artifact.`);
|
||||
}
|
||||
for (const reference of references) {
|
||||
if (!uploadedNames.has(reference)) {
|
||||
throw new Error(`${metadataFile.name} references missing release artifact ${reference}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readFileSyncUtf8(path) {
|
||||
return readFileSync(path, "utf8");
|
||||
}
|
||||
|
||||
async function verifyPublicLatestFile(file, packageBaseUrl) {
|
||||
const publicUrl = `${packageBaseUrl}/${encodeURIComponent(safeAssetName(file.name))}?release=${encodeURIComponent(tag)}`;
|
||||
const response = await globalThis.fetch(publicUrl, { cache: "no-store" });
|
||||
if (!response.ok) {
|
||||
throw new Error(`Public updater verification failed for ${file.name}: HTTP ${response.status}`);
|
||||
}
|
||||
const expected = await readFile(file.path);
|
||||
const actual = Buffer.from(await response.arrayBuffer());
|
||||
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
|
||||
throw new Error(`Public updater verification returned stale or altered ${file.name}.`);
|
||||
}
|
||||
process.stdout.write(`Verified public latest metadata ${file.name}.\n`);
|
||||
}
|
||||
|
||||
async function upsertRelease(releaseUrl, description, desiredLinks) {
|
||||
const headers = { "JOB-TOKEN": jobToken, "Content-Type": "application/json" };
|
||||
const existingUrl = `${releaseUrl}/${encodeURIComponent(tag)}`;
|
||||
const existingResponse = await globalThis.fetch(existingUrl, { headers });
|
||||
|
||||
if (existingResponse.status === 404) {
|
||||
const createResponse = await globalThis.fetch(releaseUrl, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
name: `D3RO Voice ${tag}`,
|
||||
tag_name: tag,
|
||||
description,
|
||||
assets: { links: desiredLinks },
|
||||
}),
|
||||
});
|
||||
if (!createResponse.ok) {
|
||||
throw new Error(`Release creation failed: HTTP ${createResponse.status} ${await createResponse.text()}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!existingResponse.ok) {
|
||||
throw new Error(`Release lookup failed: HTTP ${existingResponse.status} ${await existingResponse.text()}`);
|
||||
}
|
||||
|
||||
const existing = await existingResponse.json();
|
||||
const updateResponse = await globalThis.fetch(existingUrl, {
|
||||
method: "PUT",
|
||||
headers,
|
||||
body: JSON.stringify({ name: `D3RO Voice ${tag}`, description }),
|
||||
});
|
||||
if (!updateResponse.ok) {
|
||||
throw new Error(`Release update failed: HTTP ${updateResponse.status} ${await updateResponse.text()}`);
|
||||
}
|
||||
|
||||
const existingLinks = Array.isArray(existing?.assets?.links) ? existing.assets.links : [];
|
||||
for (const desired of desiredLinks) {
|
||||
const match = existingLinks.find((link) => link?.name === desired.name);
|
||||
const linksBase = `${existingUrl}/assets/links`;
|
||||
const response = await globalThis.fetch(match ? `${linksBase}/${encodeURIComponent(match.id)}` : linksBase, {
|
||||
method: match ? "PUT" : "POST",
|
||||
headers,
|
||||
body: JSON.stringify(desired),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Release link upsert failed for ${desired.name}: HTTP ${response.status} ${await response.text()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,316 +0,0 @@
|
|||
// scripts/ci/publish-updater-release.mjs
|
||||
// 자동 업데이트 채널(latest)에 디스크톱 설치본을 게시한다.
|
||||
//
|
||||
// 전제: 설치본이 Cloudflare 업로드 한도(100MiB) 아래여야 한다. 그래서 로컬 AI
|
||||
// 런타임(사이드카/ffmpeg)은 설치본에 넣지 않고, 앱이 처음 필요할 때
|
||||
// `runtime-latest`에서 내려받는다(RuntimeProvisioner, `npm run release:portable`가 게시).
|
||||
//
|
||||
// 정책 예외(명시):
|
||||
// - 이 채널은 일반적으로 Authenticode 서명을 요구한다. 서명 인증서가 준비되기 전까지
|
||||
// 업데이트를 전달할 수 없어, **무서명 빌드를 명시적 승인(--ack-unsigned)으로만** 게시한다.
|
||||
// - 검증되지 않은 서명을 조용히 게시하지 않는다: 승인 플래그가 없으면 즉시 실패한다.
|
||||
//
|
||||
// 사용:
|
||||
// npm run build --workspace=@d3ro/desktop
|
||||
// node scripts/ci/publish-updater-release.mjs --build --ack-unsigned
|
||||
// node scripts/ci/publish-updater-release.mjs --check # 게시 예정만 확인
|
||||
|
||||
import credentialHelpers from '../lib/credentials.cjs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
RUNTIME_MIN_VERSION_SOURCE,
|
||||
WINDOWS_X64_TARGET,
|
||||
assertRuntimeFeedCompatible,
|
||||
parseRuntimeMinVersions,
|
||||
} from './lib/runtime-feed-gate.mjs'
|
||||
import { assertValidUpdatePolicy } from './lib/update-policy-schema.mjs'
|
||||
|
||||
const { forgejoAuthorization } = credentialHelpers
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
||||
const desktopDir = join(root, 'apps', 'desktop')
|
||||
const args = process.argv.slice(2)
|
||||
const check = args.includes('--check')
|
||||
const ackUnsigned = args.includes('--ack-unsigned')
|
||||
const build = args.includes('--build')
|
||||
|
||||
const FEED = 'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice'
|
||||
/** Cloudflare 업로드 본문 한도 (실측: 110MiB → 413) */
|
||||
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024
|
||||
|
||||
const version = JSON.parse(
|
||||
readFileSync(join(root, 'release', 'product-version.json'), 'utf8'),
|
||||
).version
|
||||
const releaseDir = join(desktopDir, 'release', version)
|
||||
|
||||
if (build) {
|
||||
const appDir = join(releaseDir, 'win-unpacked')
|
||||
|
||||
// 1) 먼저 unpacked 트리빌드한다.
|
||||
console.log('[updater] electron-builder --dir (앱 전용 — 런타임 제외)')
|
||||
const result = spawnSync(
|
||||
'npx',
|
||||
[
|
||||
'electron-builder',
|
||||
'--win',
|
||||
'dir',
|
||||
'--x64',
|
||||
'--config',
|
||||
'electron-builder.yml',
|
||||
'--publish',
|
||||
'never',
|
||||
'-c.win.forceCodeSigning=false',
|
||||
'-c.npmRebuild=false',
|
||||
],
|
||||
{ cwd: desktopDir, stdio: 'inherit', shell: process.platform === 'win32' },
|
||||
)
|
||||
if (result.status !== 0) {
|
||||
console.error(`[updater] 빌드 실패 (exit ${result.status ?? 'null'})`)
|
||||
process.exit(result.status ?? 1)
|
||||
}
|
||||
|
||||
// 2) 네이티브 모듈 ABI 보장 + 검증 (호스트 Node ABI가 섞이면 이 시작조차 못 한다)
|
||||
runNodeScript('scripts/ci/fix-native-abi.mjs', ['--dir', appDir])
|
||||
runNodeScript('scripts/ci/verify-native-abi.mjs', ['--dir', appDir])
|
||||
|
||||
// electron-updater 설정 파일을 보장한다(없으면 자동 업데이트가 동작하지 않는다)
|
||||
runNodeScript('scripts/ci/write-app-update-yml.mjs', ['--dir', appDir])
|
||||
|
||||
// 3) 검증된 트리에서 설치본 생성 (--prepackaged = 재빌드 없이 그대로 패키징)
|
||||
console.log('[updater] electron-builder --prepackaged (NSIS x64)')
|
||||
const packageResult = spawnSync(
|
||||
'npx',
|
||||
[
|
||||
'electron-builder',
|
||||
'--prepackaged',
|
||||
appDir,
|
||||
'--win',
|
||||
'nsis',
|
||||
'--x64',
|
||||
'--config',
|
||||
'electron-builder.yml',
|
||||
'--publish',
|
||||
'never',
|
||||
'-c.win.forceCodeSigning=false',
|
||||
'-c.npmRebuild=false',
|
||||
],
|
||||
{ cwd: desktopDir, stdio: 'inherit', shell: process.platform === 'win32' },
|
||||
)
|
||||
if (packageResult.status !== 0) {
|
||||
console.error(`[updater] 설치본 생성 실패 (exit ${packageResult.status ?? 'null'})`)
|
||||
process.exit(packageResult.status ?? 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** 이 스크립트와 같은 Node로 CI 스크립트를 실행한다 */
|
||||
function runNodeScript(relativePath, scriptArgs) {
|
||||
console.log(`[updater] $ node ${relativePath} ${scriptArgs.join(' ')}`)
|
||||
const result = spawnSync(process.execPath, [join(root, relativePath), ...scriptArgs], {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
if (result.status !== 0) {
|
||||
console.error(`[updater] ${relativePath} 실패 (exit ${result.status ?? 'null'})`)
|
||||
process.exit(result.status ?? 1)
|
||||
}
|
||||
}
|
||||
|
||||
const metadataPath = join(releaseDir, 'latest.yml')
|
||||
if (!existsSync(metadataPath)) {
|
||||
console.error(
|
||||
`[updater] latest.yml이 없습니다: ${metadataPath}\n --build로 먼저 빌드하세요.`,
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const candidates = readdirSync(releaseDir).filter(
|
||||
(name) => /\.exe$/.test(name) && !/__uninstaller|apponly/i.test(name),
|
||||
)
|
||||
const installer = candidates.find((name) => name.includes('Setup')) ?? candidates[0]
|
||||
if (!installer) {
|
||||
console.error(`[updater] 설치본을 찾을 수 없습니다: ${releaseDir}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const installerPath = join(releaseDir, installer)
|
||||
const blockmapPath = `${installerPath}.blockmap`
|
||||
const policyPath = join(root, 'release', 'update-policy.json')
|
||||
|
||||
// 원격 정책은 오타 하나로 킬 스위치·staged rollout 이 조용히 꺼질 수 있다 — 올리기 전에 엄격히 검증한다.
|
||||
if (existsSync(policyPath)) {
|
||||
try {
|
||||
assertValidUpdatePolicy(readFileSync(policyPath), 'release/update-policy.json')
|
||||
} catch (error) {
|
||||
console.error(`[updater] ${error instanceof Error ? error.message : String(error)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
const payloads = [
|
||||
{ name: installer, path: installerPath, type: 'application/octet-stream' },
|
||||
{ name: `${installer}.blockmap`, path: blockmapPath, type: 'application/octet-stream' },
|
||||
{ name: 'latest.yml', path: metadataPath, type: 'text/yaml' },
|
||||
{ name: 'update-policy.json', path: policyPath, type: 'application/json' },
|
||||
].filter((payload) => existsSync(payload.path))
|
||||
|
||||
const installerSize = statSync(installerPath).size
|
||||
console.log(
|
||||
[
|
||||
`[updater] 버전 ${version}`,
|
||||
` 설치본 : ${installer} (${(installerSize / 1048576).toFixed(1)}MiB)`,
|
||||
` 한도 : ${(MAX_UPLOAD_BYTES / 1048576).toFixed(0)}MiB (Cloudflare 업로드 본문 한도)`,
|
||||
].join('\n'),
|
||||
)
|
||||
|
||||
if (installerSize > MAX_UPLOAD_BYTES) {
|
||||
console.error(
|
||||
[
|
||||
'[updater] 설치본이 업로드 한도를 넘습니다 — 게시할 수 없습니다.',
|
||||
' 런타임(사이드카/ffmpeg)을 설치본에 다시 넣지 않았는지 확인하세요:',
|
||||
' `apps/desktop/electron-builder.yml`의 extraResources / files / asarUnpack.',
|
||||
].join('\n'),
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// 설치본에 app-update.yml이 없으면 electron-updater가 설정을 읽지 못해 자동 업데이트가 죽는다.
|
||||
const packagedUpdateConfig = join(releaseDir, 'win-unpacked', 'resources', 'app-update.yml')
|
||||
if (!existsSync(packagedUpdateConfig)) {
|
||||
console.error('[updater] app-update.yml 누락 — write-app-update-yml.mjs를 먼저 실행하세요.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const metadata = readFileSync(metadataPath, 'utf8')
|
||||
if (!metadata.includes(`version: ${version}`)) {
|
||||
console.error('[updater] latest.yml의 버전이 product-version.json과 다릅니다.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const targets = [`${FEED}/${version}`, `${FEED}/latest`]
|
||||
|
||||
// 앱이 요구하는 런타임(RUNTIME_MIN_VERSION)을 runtime-latest 가 아직 제공하지 못하면, 이 설치본으로
|
||||
// 업데이트한 사용자는 로컬 STT 엔진을 쓸 수 없다. latest.yml 을 올리기 전에 fail-closed 로 확인한다.
|
||||
try {
|
||||
const runtime = await assertRuntimeFeedCompatible({
|
||||
url: `${FEED}/runtime-latest/runtime.json`,
|
||||
fetchImpl: (url, init) => fetch(url, init),
|
||||
minVersions: parseRuntimeMinVersions(readFileSync(join(root, RUNTIME_MIN_VERSION_SOURCE), 'utf8')),
|
||||
target: WINDOWS_X64_TARGET,
|
||||
})
|
||||
console.log(`[updater] runtime-latest ${runtime.version} 이 이 빌드의 최소 런타임 요구를 만족합니다.`)
|
||||
} catch (error) {
|
||||
console.error(`[updater] ${error instanceof Error ? error.message : String(error)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (check) {
|
||||
console.log('[updater] (check) 게시 예정:')
|
||||
for (const target of targets) {
|
||||
for (const payload of payloads) {
|
||||
console.log(` PUT ${target}/${payload.name} (${statSync(payload.path).size} bytes)`)
|
||||
}
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (!ackUnsigned) {
|
||||
console.error(
|
||||
[
|
||||
'[updater] 무서명 빌드를 stable 채널에 게시하려면 명시적 승인이 필요합니다.',
|
||||
' 서명 인증서가 준비되면 이 플래그 없이 게시하세요(권장).',
|
||||
' 승인: --ack-unsigned',
|
||||
].join('\n'),
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const authorization = forgejoAuthorization()
|
||||
|
||||
/**
|
||||
* 원격 파일이 로컬 바이트와 같은지 판단한다.
|
||||
* Forgejo generic registry는 HEAD를 405로 거부하고 해시도 주지 않으므로,
|
||||
* Range GET으로 크기를 본 뒤 1MiB 이하는 실제 바이트까지 비교한다.
|
||||
* (크기만 비교하면 버전 문자열만 바뀐 latest.yml 같은 메타데이터를 놓친다 — 실측 사고.)
|
||||
*/
|
||||
async function remoteIsIdentical(url, body, fetchImpl) {
|
||||
const probe = await fetchImpl(url, { headers: { Range: 'bytes=0-0' } }).catch(() => null)
|
||||
if (!probe?.ok) return false
|
||||
const contentRange = probe.headers.get('content-range')
|
||||
const remoteSize = contentRange ? Number(contentRange.split('/')[1]) : NaN
|
||||
if (!Number.isFinite(remoteSize) || remoteSize !== body.length) return false
|
||||
if (body.length > 1024 * 1024) return true
|
||||
const full = await fetchImpl(url).catch(() => null)
|
||||
if (!full?.ok) return false
|
||||
const remoteBytes = Buffer.from(await full.arrayBuffer())
|
||||
return remoteBytes.length === body.length && remoteBytes.equals(body)
|
||||
}
|
||||
|
||||
async function forgejoFetch(url, init = {}) {
|
||||
return fetch(url, {
|
||||
...init,
|
||||
headers: { Authorization: authorization, ...(init.headers ?? {}) },
|
||||
})
|
||||
}
|
||||
|
||||
console.log(
|
||||
[
|
||||
'[updater] 경고: 무서명 설치본을 stable(latest) 채널에 게시합니다.',
|
||||
' - electron-updater는 app-update.yml에 publisherName이 없으면 서명 검증을 건너뛰므로',
|
||||
' 설치 자체는 정상 동작합니다.',
|
||||
' - 인증서가 준비되면 이 버전보다 높은 버전으로 서명 게시하여 대체하세요.',
|
||||
].join('\n'),
|
||||
)
|
||||
|
||||
for (const target of targets) {
|
||||
for (const payload of payloads) {
|
||||
const url = `${target}/${encodeURIComponent(payload.name)}`
|
||||
const body = await readFile(payload.path)
|
||||
|
||||
// Forgejo generic registry는 HEAD를 405로 거부하고 해시도 주지 않는다.
|
||||
// 크기만 비교하면 버전 문자열만 바뀐 latest.yml을 "동일"로 오판한다 — 내용까지 비교한다.
|
||||
if (await remoteIsIdentical(url, body, forgejoFetch)) {
|
||||
console.log(`[updater] 이미 동일한 파일이 있습니다(건너): ${url}`)
|
||||
continue
|
||||
}
|
||||
|
||||
// 메타데이터는 최신을 가리켜야 하므로 기존 파일을 지우고 쓴다(PUT은 409를 돌려준다).
|
||||
const existing = await forgejoFetch(url, { headers: { Range: 'bytes=0-0' } }).catch(() => null)
|
||||
if (existing?.ok) {
|
||||
await forgejoFetch(url, { method: 'DELETE' }).catch(() => null)
|
||||
}
|
||||
|
||||
const response = await forgejoFetch(url, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': payload.type },
|
||||
body,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const hint =
|
||||
response.status === 409
|
||||
? ' (409: 같은 경로에 다른 내용이 이미 있음 — 게시된 버전을 덮어쓰지 않습니다)'
|
||||
: response.status === 413
|
||||
? ' (413: Cloudflare 업로드 한도 초과 — 런타임 분리 확인)'
|
||||
: ''
|
||||
console.error(
|
||||
`[updater] 업로드 실패 (HTTP ${response.status}): ${target}/${payload.name}${hint}`,
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`[updater] uploaded ${target}/${payload.name}`)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
[
|
||||
'',
|
||||
`[updater] 게시 완료: ${version}`,
|
||||
` 피드 : ${FEED}/latest`,
|
||||
` 메타 : ${FEED}/latest/latest.yml`,
|
||||
' 기존 설치본(canonical feed 사용)은 다음 업데이트 확인 때 이 버전을 받습니다.',
|
||||
' legacy GitLab mirror를 보는 1.0.x 이하 설치는 1회 수동 설치가 필요합니다.',
|
||||
].join('\n'),
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue