#!/usr/bin/env node // Node 22+; no packages. POST spends API credits; GET polling does not. // Persist ARTWORK_IDEMPOTENCY_KEY and original inputs BEFORE invoking this example. // Direct admission is backwards compatible and chargeable. For confirmed PDF totals, // use POST /quote plus both confirmation headers as documented in quickstart.md. // node submit.cjs /local/artwork.png 254 127 mm const fs = require("node:fs"); const { setTimeout: sleep } = require("node:timers/promises"); const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; async function main() { const [file, width, height, unit, extra] = process.argv.slice(2); const key = process.env.ARTWORK_API_KEY || ""; const idem = process.env.ARTWORK_IDEMPOTENCY_KEY || ""; const base = new URL(process.env.ARTWORK_API_BASE_URL); if (!/^[!-~]+$/.test(key) || !/^[!-~]{1,200}$/.test(idem)) throw Error( "Set API key and persisted owner-generated idempotency key in the environment.", ); if ( base.username || base.password || base.search || base.hash || base.pathname !== "/" || (base.protocol !== "https:" && !( base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname) )) ) throw Error( "HTTPS origin required; HTTP only for loopback test fixtures. No credentials, query or path.", ); if ( !file || extra || !["in", "mm"].includes(unit) || ![width, height].every((v) => Number.isFinite(Number(v)) && Number(v) > 0) ) throw Error("Usage: node submit.cjs LOCAL_FILE WIDTH HEIGHT in|mm"); const raw = fs.readFileSync(file); if (!raw.length || raw.length > 25 * 1024 * 1024) throw Error("File must be nonempty and at most 25 MiB."); const deadline = Date.now() + 180000; async function pause(seconds) { if ( !Number.isFinite(seconds) || seconds < 0 || Date.now() + seconds * 1000 >= deadline ) throw Error( "Retry budget exhausted; preserve original key/inputs and inspect dashboard.", ); await sleep(seconds * 1000); } async function request(method, route) { if (!/^\/api\/v1\/artwork-checks(?:\/[0-9a-f-]{36})?$/i.test(route)) throw Error("Unexpected route; refusing to forward credentials."); for (let attempt = 0; attempt < 5; attempt++) { const remaining = deadline - Date.now(); if (remaining <= 0) throw Error("Time budget exhausted; preserve original key and inputs."); const headers = { Authorization: "Bearer " + key, Accept: "application/json", }; let body; if (method === "POST") { headers["Idempotency-Key"] = idem; body = new FormData(); body.set("file", new Blob([raw]), "artwork"); body.set("width", width); body.set("height", height); body.set("unit", unit); } let response; try { response = await fetch(new URL(route, base), { method, headers, body, redirect: "manual", signal: AbortSignal.timeout(Math.min(20000, remaining)), }); } catch { /* Ambiguous failure: same original bytes/options/key, never a new charge key. */ } if (response?.ok) { try { return await response.json(); } catch { /* Response body loss is ambiguous too. */ } } else if (response && ![429, 503].includes(response.status)) { let requestId = ""; try { const data = await response.json(); if (UUID.test(data.request_id)) requestId = data.request_id; } catch {} throw Error( `HTTP ${response.status}; stop and resolve before retrying. Request ID: ${requestId}`, ); } if (attempt === 4) throw Error( "Retry attempts exhausted. Keep original key/inputs; inspect dashboard. No automatic purchase or new submission.", ); let wait = Math.min(2 ** attempt, 8); const retryAfter = response?.headers.get("Retry-After"); if (retryAfter) { const seconds = /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) : (Date.parse(retryAfter) - Date.now()) / 1000; if (!Number.isFinite(seconds)) throw Error( "Invalid Retry-After; stop safely and inspect dashboard.", ); wait = Math.max(wait, seconds); } await pause(wait); } } const accepted = await request("POST", "/api/v1/artwork-checks"); if (!UUID.test(accepted.id)) throw Error( "Unexpected check ID; inspect dashboard without creating another check.", ); console.log("Check:", accepted.id); const route = "/api/v1/artwork-checks/" + accepted.id; for (let poll = 0; poll < 12; poll++) { const detail = await request("GET", route); if (detail.processing_status === "completed") { const readiness = detail.report?.readiness; console.log( "completed", ["no_flags", "issues_found", "inconclusive"].includes(readiness) ? readiness : "report unavailable", ); return; } if (detail.processing_status === "failed") throw Error( "Check failed; stop polling. Inspect dashboard reservation status; do not resubmit automatically.", ); if (!["queued", "running"].includes(detail.processing_status)) throw Error( "Unexpected status; inspect dashboard without creating another check.", ); if (poll < 11) await pause(Math.min(2 ** poll, 8)); } throw Error( "Polling budget exhausted. Resume GET for this check; never create a new key to poll.", ); } // Only controlled messages are emitted; never print raw provider/network exceptions. main().catch((error) => { const safe = /^(Set API|HTTPS origin|Usage:|File must|Retry |Time budget|Unexpected |HTTP \d|Invalid Retry|Check failed|Polling budget)/.test( error.message, ); console.error( safe ? error.message : "Example stopped safely. Preserve key and original inputs; check dashboard. No raw errors logged.", ); process.exitCode = 1; });