const fetch = require("node-fetch");
const fs = require("node:fs");
const crypto = require("node:crypto");
const API = process.env.AF_API;
const TOKEN = process.env.AF_TOKEN;
const ORG = process.env.AF_ORG;
async function registerWork(audioPath, title, creators, externalUserRef) {
const auth = { Authorization: `Bearer ${TOKEN}` };
const idempotencyKey = crypto.randomUUID();
const init = await (await fetch(`${API}/v1/organizations/${ORG}/works/init`, {
headers: { ...auth, "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
filename: require("node:path").basename(audioPath),
external_user_ref: externalUserRef,
await fetch(init.upload_url, { method: "PUT", body: fs.readFileSync(audioPath) });
const quote = await (await fetch(`${API}/v1/organizations/${ORG}/works/prepare`, {
method: "POST", headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({ job_id: init.job_id }),
if (!quote.is_valid) throw new Error("Dry-run failed");
console.log(`Total: ${quote.total_price_credits} credits`);
const tx = await (await fetch(`${API}/v1/organizations/${ORG}/works/confirm`, {
method: "POST", headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({ job_id: init.job_id }),
return tx.transaction_id; // wait for the webhook