import * as NodeFSP from "node:fs/promises"; import * as NodeURL from "node:url"; import { parseAndroidApkReleaseTag, resolveAndroidApkRepository, } from "./lib/android-apk-release.ts"; export async function publishForkApk(options: { tag: string; commit: string; token: string; repositoryUrl: string; apk: Blob; checksum: Blob; request?: typeof fetch; body?: string; }) { const versionCode = parseAndroidApkReleaseTag(options.tag); const request = options.request ?? fetch; const endpoint = resolveAndroidApkRepository(options.repositoryUrl).apiUrl; const authorization = `token ${options.token}`; const send = async (url: string, init: RequestInit) => { const response = await request(url, { ...init, redirect: "error", headers: { ...init.headers, Authorization: authorization }, }); if (!response.ok) throw new Error(`Release request failed: HTTP ${response.status}`); return response; }; const created = await send(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tag_name: options.tag, target_commitish: options.commit, name: `Android APK ยท build ${versionCode}`, body: options.body ?? "Download the APK below and open it on Android to install. This is a signed fork build; updates require the same signing key. The SHA-256 checksum is attached alongside the APK.", draft: true, prerelease: false, }), }); const release: unknown = await created.json(); if ( typeof release !== "object" || release === null || !("id" in release) || typeof release.id !== "number" || !Number.isSafeInteger(release.id) || release.id <= 0 ) throw new Error("Release API did not return a valid release ID."); const filename = `t3code-${options.tag}.apk`; for (const [name, file] of [ [filename, options.apk], [`${filename}.sha256`, options.checksum], ] as const) { const form = new FormData(); form.append("attachment", file, name); await send(`${endpoint}/${release.id}/assets?name=${encodeURIComponent(name)}`, { method: "POST", body: form, }); } await send(`${endpoint}/${release.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ draft: false }), }); } if (process.argv[1] && import.meta.url === NodeURL.pathToFileURL(process.argv[1]).href) { const tag = process.env.T3CODE_APK_RELEASE_TAG; const token = process.env.APK_RELEASE_TOKEN; const commit = process.env.APK_RELEASE_COMMIT; const repositoryUrl = process.env.T3CODE_APK_REPOSITORY_URL; if (!tag || !token || !commit || !repositoryUrl) throw new Error("Missing APK release tag, token, commit, or repository URL."); parseAndroidApkReleaseTag(tag); await publishForkApk({ tag, token, commit, repositoryUrl, apk: new Blob([await NodeFSP.readFile(`release/t3code-${tag}.apk`)], { type: "application/vnd.android.package-archive", }), checksum: new Blob([await NodeFSP.readFile(`release/t3code-${tag}.apk.sha256`)], { type: "text/plain", }), }); }