effing-cloud 0.8.5 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +16 -13
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,20 +1,23 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as un}from"module";import{Command as fn}from"commander";import ve from"os";import I from"process";import{spawn as D}from"child_process";import{createRequire as $e}from"module";import ge from"process";var me="https://cloud.effing.dev";function he(){return(ge.env.EFFING_CLOUD_WEB_BASE_URL??me).replace(/\/$/,"")}async function x(e,n={}){let{expectedStatus:t,...o}=n,r=await fetch(`${he()}${e}`,o);if(t!==void 0&&r.status!==t){let i=await r.text();throw new Error(`Request failed \u2014 ${r.status} ${r.statusText}: ${i}`)}return r}import v from"fs";import M from"os";import E from"path";var N=class extends Error{constructor(){super("Your saved credentials are from a pre-release version. Please run `effing-cloud login` again."),this.name="LegacyCredentialsError"}};function j(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??E.join(M.homedir(),"AppData","Local");return E.join(n,"effing-cloud","credentials.json")}let e=process.env.XDG_CONFIG_HOME??E.join(M.homedir(),".config");return E.join(e,"effing-cloud","credentials.json")}function m(){let e=j(),n;try{n=v.readFileSync(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let t;try{t=JSON.parse(n)}catch{return null}if(!t||typeof t!="object")return null;let o=t;if("accounts"in o&&o.version===1)return we(o);if(typeof o.apiKey=="string"){try{v.unlinkSync(e)}catch{}throw new N}return null}function _(e){let n=j();if(v.mkdirSync(E.dirname(n),{recursive:!0,mode:448}),v.writeFileSync(n,JSON.stringify(e,null,2)+`
3
- `,{mode:384}),process.platform!=="win32")try{v.chmodSync(n,384)}catch{}return n}function L(){try{return v.unlinkSync(j()),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Y(e){let n=m()??ye(),t=n.accounts[e.slug],o=Object.keys(n.accounts).length===0;return n.accounts[e.slug]={apiKey:e.apiKey,name:e.name},(o||!n.default)&&(n.default=e.slug),_(n),{previousApiKey:t?.apiKey??null,wasFirst:o,existed:!!t}}function W(e){let n=m();if(!n)return{newDefault:null,remaining:0};if(!n.accounts[e])return{newDefault:n.default,remaining:J(n)};delete n.accounts[e];let t=J(n);return t===0?(L(),{newDefault:null,remaining:0}):(n.default===e&&(n.default=Object.keys(n.accounts)[0]??null),_(n),{newDefault:n.default,remaining:t})}function q(e){let n=m();if(!n||!n.accounts[e])throw new Error(`No credentials for account '${e}'. Run \`effing-cloud login\` to add it, or \`effing-cloud accounts\` to list available ones.`);return n.default=e,_(n),n}function ye(){return{version:1,default:null,accounts:{}}}function J(e){return Object.keys(e.accounts).length}function we(e){let n=e.accounts;if(!n||typeof n!="object")return null;let t={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let s=i;typeof s.apiKey!="string"||typeof s.name!="string"||(t[r]={apiKey:s.apiKey,name:s.name})}return{version:1,default:typeof e.default=="string"&&t[e.default]?e.default:null,accounts:t}}async function R(e){try{await x("/cli-auth/logout",{method:"POST",headers:{Authorization:`Bearer ${e}`}})}catch{}}import be from"process";function l(e){return async(...n)=>{try{await e(...n)}catch(t){console.error(t.message),be.exitCode=1}}}var Se=$e(import.meta.url),{version:Ce}=Se("../package.json");function H(e){e.command("login").description("Authenticate with Effing Cloud via your browser").option("--no-browser","don't try to open the browser automatically").action(l(xe))}async function xe(e){let n=await Ee();console.log(`
2
+ import{createRequire as yn}from"module";import{Command as wn}from"commander";import nt from"os";import X from"process";import{spawn as H}from"child_process";import{createRequire as ot}from"module";import Xe from"process";var Ze="https://cloud.effing.dev";function Qe(){return(Xe.env.EFFING_CLOUD_WEB_BASE_URL??Ze).replace(/\/$/,"")}async function P(e,t={}){let{expectedStatus:o,...n}=t,r=await fetch(`${Qe()}${e}`,n);if(o!==void 0&&r.status!==o){let s=await r.text();throw new Error(`Request failed \u2014 ${r.status} ${r.statusText}: ${s}`)}return r}import R from"fs";import ie from"os";import T from"path";var J=class extends Error{constructor(){super("Your saved credentials are from a pre-release version. Please run `effing-cloud login` again."),this.name="LegacyCredentialsError"}};function k(){if(process.platform==="win32"){let t=process.env.LOCALAPPDATA??T.join(ie.homedir(),"AppData","Local");return T.join(t,"effing-cloud","credentials.json")}let e=process.env.XDG_CONFIG_HOME??T.join(ie.homedir(),".config");return T.join(e,"effing-cloud","credentials.json")}function E(){let e=k(),t;try{t=R.readFileSync(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let o;try{o=JSON.parse(t)}catch{return null}if(!o||typeof o!="object")return null;let n=o;if("accounts"in n&&n.version===1)return et(n);if(typeof n.apiKey=="string"){try{R.unlinkSync(e)}catch{}throw new J}return null}function Y(e){let t=k();if(R.mkdirSync(T.dirname(t),{recursive:!0,mode:448}),R.writeFileSync(t,JSON.stringify(e,null,2)+`
3
+ `,{mode:384}),process.platform!=="win32")try{R.chmodSync(t,384)}catch{}return t}function W(){try{return R.unlinkSync(k()),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function ce(e){let t=E()??Ve(),o=t.accounts[e.slug],n=Object.keys(t.accounts).length===0;return t.accounts[e.slug]={apiKey:e.apiKey,name:e.name},(n||!t.default)&&(t.default=e.slug),Y(t),{previousApiKey:o?.apiKey??null,wasFirst:n,existed:!!o}}function le(e){let t=E();if(!t)return{newDefault:null,remaining:0};if(!t.accounts[e])return{newDefault:t.default,remaining:ae(t)};delete t.accounts[e];let o=ae(t);return o===0?(W(),{newDefault:null,remaining:0}):(t.default===e&&(t.default=Object.keys(t.accounts)[0]??null),Y(t),{newDefault:t.default,remaining:o})}function ue(e){let t=E();if(!t||!t.accounts[e])throw new Error(`No credentials for account '${e}'. Run \`effing-cloud login\` to add it, or \`effing-cloud accounts\` to list available ones.`);return t.default=e,Y(t),t}function Ve(){return{version:1,default:null,accounts:{}}}function ae(e){return Object.keys(e.accounts).length}function et(e){let t=e.accounts;if(!t||typeof t!="object")return null;let o={};for(let[r,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let i=s;typeof i.apiKey!="string"||typeof i.name!="string"||(o[r]={apiKey:i.apiKey,name:i.name})}return{version:1,default:typeof e.default=="string"&&o[e.default]?e.default:null,accounts:o}}async function j(e){try{await P("/cli-auth/logout",{method:"POST",headers:{Authorization:`Bearer ${e}`}})}catch{}}import tt from"process";function p(e){return async(...t)=>{try{await e(...t)}catch(o){console.error(o.message),tt.exitCode=1}}}var rt=ot(import.meta.url),{version:st}=rt("../package.json");function fe(e){e.command("login").description("Authenticate with Effing Cloud via your browser").option("--no-browser","don't try to open the browser automatically").action(p(it))}async function it(e){let t=await at();console.log(`
4
4
  Open the following URL in your browser to authorize this device:
5
- `),console.log(` ${n.browserUrl}
6
- `),e.browser&&I.stdout.isTTY&&Ae(n.browserUrl),console.log("Waiting for approval...");let{apiKey:t,account:o}=await je(n),{previousApiKey:r,existed:i,wasFirst:s}=Y({slug:o.slug,name:o.name,apiKey:t});r&&await R(r),console.log(i?`
7
- Re-authorized "${o.name}" (${o.slug}).`:s?`
8
- Logged in as "${o.name}" (${o.slug}). Set as default account.`:`
9
- Added account "${o.name}" (${o.slug}). Run \`effing-cloud use ${o.slug}\` to make it your default.`)}async function Ee(){return await(await x("/cli-auth/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientName:"effing-cloud-cli",clientVersion:Ce,hostname:ve.hostname()}),expectedStatus:200})).json()}async function je(e){let n=new Date(e.expiresAt).getTime(),t=!0;for(;Date.now()<n;){t||await Re(e.pollIntervalMs),t=!1;let o=await x("/cli-auth/poll",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliToken:e.cliToken})});if(o.status===404)throw new Error("Authorization session not found. Please run `effing-cloud login` again.");if(!o.ok){let i=await o.text();throw new Error(`Polling failed \u2014 ${o.status} ${o.statusText}: ${i}`)}let r=await o.json();if(r.status!=="pending"){if(r.status==="denied")throw new Error("Authorization denied.");if(r.status==="expired")throw new Error("Authorization session expired.");if(r.status==="consumed")throw new Error("This authorization session was already used. Run `effing-cloud login` again.");if(r.status==="approved")return{apiKey:r.apiKey,account:r.account}}}throw new Error("Authorization session expired before approval.")}function Re(e){return new Promise(n=>setTimeout(n,e))}function Ae(e){try{I.platform==="darwin"?D("open",[e],{detached:!0,stdio:"ignore"}).unref():I.platform==="win32"?D("cmd.exe",["/c","start","",e],{detached:!0,stdio:"ignore"}).unref():D("xdg-open",[e],{detached:!0,stdio:"ignore"}).unref()}catch{}}function V(e){e.command("logout").description("Sign out and remove saved credentials").option("--account <slug>","log out of a specific account").option("--all","log out of every account").action(l(Ue))}async function Ue(e){let n=m();if(!n||Object.keys(n.accounts).length===0){console.log("Not logged in.");return}if(e.all){let o=Object.entries(n.accounts);await Promise.all(o.map(([,r])=>R(r.apiKey))),L(),console.log(`Logged out of ${o.length} account(s).`);return}if(e.account){await X(e.account,n.accounts[e.account]?.apiKey);return}let t=Object.keys(n.accounts);if(t.length===1){await X(t[0],n.accounts[t[0]].apiKey);return}throw new Error(`Multiple accounts configured: ${t.sort().join(", ")}. Pass --account <slug> to remove one or --all to remove every account.`)}async function X(e,n){if(!n)throw new Error(`No credentials for account '${e}'.`);await R(n);let{newDefault:t,remaining:o}=W(e);console.log(o===0?`Logged out of '${e}'. No accounts remain.`:t&&t!==e?`Logged out of '${e}'. Default account is now '${t}'.`:`Logged out of '${e}'.`)}import ke from"process";function Q(e){e.command("accounts").description("List accounts you've logged in to").action(l(Oe))}function Oe(){let e=m(),n=e?Object.entries(e.accounts):[];if(n.length===0){console.log("No accounts. Run `effing-cloud login`.");return}n.sort(([o],[r])=>o.localeCompare(r));let t=Math.max(...n.map(([o])=>o.length));for(let[o,r]of n){let i=e?.default===o?"*":" ";console.log(`${i} ${o.padEnd(t)} ${r.name}`)}ke.env.EFFING_CLOUD_API_KEY&&console.log(`
10
- EFFING_CLOUD_API_KEY is set and takes precedence over all profiles.`)}function Z(e){e.command("use <account>").description("Set the default account for subsequent commands").action(l(n=>{let o=q(n).accounts[n];console.log(`Default account is now "${o.name}" (${n}).`)}))}import qe from"process";import A from"path";import B from"fs";import{pathToFileURL as Pe}from"url";import{randomBytes as Fe}from"crypto";import{build as Ke}from"esbuild";import{z as b}from"zod";var T=b.union([b.string(),b.array(b.string())]),Ne=b.object({project:b.string().min(1),images:T.optional(),annies:T.optional(),effies:T.optional(),dev:b.unknown().optional()});var _e=["effing.config.ts","effing.config.mts","effing.config.js","effing.config.mjs"],Le=["effing-cloud.config.ts","effing-cloud.config.mts","effing-cloud.config.js"];function De(e,n){if(n){let t=A.isAbsolute(n)?n:A.resolve(e,n);if(!B.existsSync(t))throw new Error(`Config file not found: ${t}`);return t}for(let t of[..._e,...Le]){let o=A.resolve(e,t);if(B.existsSync(o))return o}throw new Error(`No effing.config.ts found in ${e}. Create one with \`export default defineConfig({ project: "...", ... })\` or pass --config <path>.`)}function Ie(){return{name:"effing-define-config-stub",setup(e){e.onResolve({filter:/^(@effing\/dev|effing-cloud)$/},n=>({path:n.path,namespace:"effing-define-config-stub"})),e.onLoad({filter:/.*/,namespace:"effing-define-config-stub"},()=>({contents:"export const defineConfig = (c) => c;",loader:"js"}))}}}async function $(e,n){let t=De(e,n),o=A.dirname(t),r=A.join(o,`.effing.config.${Fe(4).toString("hex")}.mjs`);try{await Ke({entryPoints:[t],outfile:r,bundle:!0,format:"esm",platform:"node",target:"node22",packages:"external",plugins:[Ie()],logLevel:"silent"});let i=await import(Pe(r).href),s=Ne.safeParse(i.default);if(!s.success)throw new Error(`Invalid config in ${t}:
11
- ${s.error.message}`);return{config:s.data,configPath:t,configDir:o}}finally{await B.promises.unlink(r).catch(()=>{})}}import Te from"path";import{build as Be}from"esbuild";import{glob as ze}from"tinyglobby";var Ge={image:"images",annie:"annies",effie:"effies"};async function ee(e){let{configDir:n,config:t}=e,o={image:await z(n,t.images),annie:await z(n,t.annies),effie:await z(n,t.effies)};if(o.image.length+o.annie.length+o.effie.length===0)throw new Error(`No modules matched the globs in the config. Set images/annies/effies to paths that exist relative to ${n}.`);let i=Me(o),s=await Be({stdin:{contents:i,resolveDir:n,loader:"ts",sourcefile:"effing-entry.ts"},bundle:!0,format:"esm",platform:"node",target:"node22",external:["node:*","@effing/skia","@napi-rs/canvas","@effing/fn"],write:!1,logLevel:"silent"});if(s.outputFiles.length!==1)throw new Error(`esbuild produced ${s.outputFiles.length} output files; expected 1`);let a=s.outputFiles[0].contents,f=new ArrayBuffer(a.byteLength),d=new Uint8Array(f);d.set(a);let g={modules:{image:o.image.map(c=>c.id),annie:o.annie.map(c=>c.id),effie:o.effie.map(c=>c.id)}};return{bundle:d,manifest:g}}async function z(e,n){if(!n)return[];let t=Array.isArray(n)?n:[n],o=await ze(t,{cwd:e,absolute:!0}),r=new Map;for(let i of o){let s=Te.basename(i).split(".")[0],a=r.get(s);if(a&&a!==i)throw new Error(`Duplicate module id "${s}" \u2014 matched by both ${a} and ${i}. Module ids must be unique per kind.`);r.set(s,i)}return[...r.entries()].map(([i,s])=>({id:i,absPath:s})).sort((i,s)=>i.id.localeCompare(s.id))}function Me(e){let n=[],t=(o,r)=>`_${o}_${r}`;for(let o of["image","annie","effie"])e[o].forEach((r,i)=>{let s=t(o,i);n.push(`import { propsSchema as ${s}_ps, previewProps as ${s}_pp, runner as ${s}_r } from ${JSON.stringify(r.absPath)};`)});for(let o of["image","annie","effie"]){let r=Ge[o];n.push(`export const ${r} = {`),e[o].forEach((i,s)=>{let a=t(o,s);n.push(` ${JSON.stringify(i.id)}: { propsSchema: ${a}_ps, previewProps: ${a}_pp, runner: ${a}_r },`)}),n.push("};")}return n.join(`
12
- `)}import Je from"process";var Ye="https://fn.effing.dev";function U(){return(Je.env.EFFING_CLOUD_FN_BASE_URL??Ye).replace(/\/$/,"")}var y=class extends Error{constructor(t,o){super(t);this.status=o}status};async function h(e,n){let{apiKey:t,expectedStatus:o=200,headers:r,...i}=n,s=await fetch(`${U()}${e}`,{...i,headers:{...r,Authorization:`Bearer ${t}`}});if(s.status!==o){let a=await s.text();throw new y(`Request failed \u2014 ${s.status} ${s.statusText}: ${a}`,s.status)}return s}import ne from"process";function w(e={}){let n=ne.env.EFFING_CLOUD_API_KEY;if(n)return e.accountFlag&&console.error(`Warning: EFFING_CLOUD_API_KEY is set and takes precedence; ignoring --account '${e.accountFlag}'. Unset the variable to use stored credentials.`),{kind:"env",apiKey:n};let t=m();if(!t||Object.keys(t.accounts).length===0)throw new Error("Not logged in. Run `effing-cloud login`.");let o=We(t,e);if(!o){let i=Object.keys(t.accounts).sort().join(", ");throw new Error(`Multiple accounts available: ${i}. Use --account, EFFING_CLOUD_ACCOUNT, or \`effing-cloud use <slug>\`.`)}let r=t.accounts[o];if(!r){let i=Object.keys(t.accounts).sort().join(", ");throw new Error(`No credentials for account '${o}'. Available: ${i}. Run \`effing-cloud login\` to add it.`)}return{kind:"profile",slug:o,name:r.name,apiKey:r.apiKey}}function We(e,n){let t=n.accountFlag??ne.env.EFFING_CLOUD_ACCOUNT??null;if(t)return t;if(e.default)return e.default;let o=Object.keys(e.accounts);return o.length===1?o[0]:null}function oe(e){e.command("deploy").description("Bundle and deploy your @effing/fn functions to Effing Cloud").option("-c, --config <path>","path to the effing.config.ts file").option("-a, --account <slug>","account slug to deploy to").option("--dry-run","bundle without uploading \u2014 prints the manifest and bundle size",!1).option("--json","print the result as JSON on stdout (progress goes to stderr)").action(l(He))}async function He(e){let n=e.json?console.error:console.log,{config:t,configDir:o,configPath:r}=await $(qe.cwd(),e.config);n(`Loaded config from ${r}`);let i=e.dryRun?null:w({accountFlag:e.account});i?.kind==="profile"&&n(`Deploying to "${i.name}" (${i.slug}).`);let{bundle:s,manifest:a}=await ee({configDir:o,config:t}),f=a.modules.image.length+a.modules.annie.length+a.modules.effie.length;if(n(`Bundled ${f} module(s) \u2014 image: ${a.modules.image.length}, annie: ${a.modules.annie.length}, effie: ${a.modules.effie.length} (${s.byteLength} bytes)`),e.dryRun||!i){if(e.json){console.log(JSON.stringify({dryRun:!0,project:t.project,bundleSize:s.byteLength,manifest:a},null,2));return}console.log("Dry run \u2014 skipping upload. Manifest:"),console.log(JSON.stringify(a,null,2));return}let d=new FormData;d.append("project",t.project),d.append("manifest",JSON.stringify(a)),d.append("bundle",new Blob([s],{type:"application/javascript"}),"bundle.js");let c=await(await h("/-/deployments",{method:"POST",body:d,apiKey:i.apiKey,expectedStatus:201})).json();if(e.json){console.log(JSON.stringify({dryRun:!1,project:t.project,id:c.id,version:c.version,bundleHash:c.bundleHash,bundleSize:c.bundleSize,previews:(c.previews??[]).map(({kind:u,id:C,url:K})=>({kind:u,id:C,url:K}))},null,2));return}if(console.log(`Deployed ${t.project} \u2014 version ${c.version}, deployment ${c.id}, hash ${c.bundleHash}, ${c.bundleSize} bytes`),c.previews&&c.previews.length>0){console.log(`
13
- Previews:`);for(let u of c.previews)console.log(` ${u.kind}/${u.id} ${u.url}`)}}import{serialize as ce}from"@effing/serde";import Xe from"process";import{z as S}from"zod";var k=["image","annie","effie"];function O(e){if(!k.includes(e))throw new Error(`Invalid kind '${e}'. Expected one of: ${k.join(", ")}.`);return e}var Ve=[{width:1080,height:1080,label:"1:1"},{width:1080,height:1350,label:"4:5"},{width:1080,height:1920,label:"9:16"}],Qe=S.object({resolutions:S.array(S.object({label:S.string(),width:S.number().int().positive(),height:S.number().int().positive()})).nonempty().optional()}),te=8192;function Ze(e,n){for(let[i,s]of[["--width",n.width],["--height",n.height]])if(s!==void 0){if(!Number.isInteger(s))throw new Error(`${i} must be an integer.`);if(s<1||s>te)throw new Error(`${i} must be between 1 and ${te}.`)}let t=Qe.safeParse(e??{});if(!t.success)throw new Error(`Invalid dev.resolutions in the config:
14
- ${t.error.message}`);let o=t.data.resolutions??Ve;if(n.resolution!==void 0){if(n.width!==void 0||n.height!==void 0)throw new Error("--resolution cannot be combined with --width/--height.");let i=o.find(s=>s.label===n.resolution);if(!i)throw new Error(`Unknown resolution '${n.resolution}'. Available: ${o.map(s=>s.label).join(", ")}.`);return{width:i.width,height:i.height}}let r=o[0];return{width:n.width??r.width,height:n.height??r.height}}var re=64,ie=256;function en(e){if(e.length>re)throw new Error(`Too many --tag entries (${e.length}): the server allows at most ${re} tags per run.`);let n=new Set,t=new Set;for(let o of e){if(o==="")throw new Error("--tag entries must be non-empty.");if(o.length>ie)throw new Error(`--tag "${o}" exceeds ${ie} characters.`);if(n.has(o))throw new Error(`Duplicate tag "${o}": each tag may only appear once.`);n.add(o);let r=o.indexOf(":");if(r!==-1){let i=o.slice(0,r);if(t.has(i))throw new Error(`Duplicate tag name "${i}": each tag name may only appear once.`);t.add(i)}}return e}async function G(e,n){let o=await(await h(`/-/projects/${encodeURIComponent(e)}/url-secret`,{apiKey:n})).json();if(typeof o.urlSecret!="string")throw new Error("Response missing urlSecret");let r=o.account?.slug;return{urlSecret:o.urlSecret,accountSlug:typeof r=="string"?r:void 0}}async function nn(e,n){let{urlSecret:t,accountSlug:o}=await G(e,n);if(o===void 0)throw new Error("The url-secret response has no account slug: the fn service predates the `url`/`urls` commands. Redeploy the fn service to use them.");return{urlSecret:t,accountSlug:o}}async function ae(e,n){try{let s=await h(`/-/deployments/active?project=${encodeURIComponent(e)}`,{apiKey:n});return se(await s.json())}catch(s){if(!(s instanceof y)||s.status!==404)throw s}let t=await h(`/-/deployments?project=${encodeURIComponent(e)}`,{apiKey:n}),{deployments:o}=await t.json();if(!o||o.length===0)throw new Error(`No deployments found for project "${e}".`);let r=o.reduce((s,a)=>a.version>s.version?a:s),i=await h(`/-/deployments/${encodeURIComponent(r.id)}`,{apiKey:n});return se(await i.json())}function se(e){let{modules:n}=e;if(n===null||typeof n!="object")throw new Error("Deployment response missing modules");return n}function P(e,n){return e.option("-c, --config <path>","path to the effing.config.ts file").option("-a, --account <slug>","account slug to read from").option("--project <slug>","project slug (default: the config's project)").option("-w, --width <number>","width in pixels",t=>parseInt(t,10)).option("--height <number>","height in pixels",t=>parseInt(t,10)).option("-r, --resolution <label>",'pick bounds from a dev.resolutions preset by label (e.g. "9:16")').option("-t, --tag <tag>",`tag runs served by ${n}, as "name:value" or a bare tag (repeatable)`,(t,o)=>[...o,t],[])}async function F(e){let n,t;if(e.project!==void 0)t=e.project;else{let{config:f}=await $(Xe.cwd(),e.config);t=f.project,n=f.dev}let o=Ze(n,e),r=en(e.tag),i=w({accountFlag:e.account});i.kind==="profile"&&console.error(`Reading from "${i.name}" (${i.slug}).`);let{urlSecret:s,accountSlug:a}=await nn(t,i.apiKey);if(e.account!==void 0&&a!==e.account){let f=i.kind==="env"?"EFFING_CLOUD_API_KEY takes precedence over --account; unset it or drop the flag.":"Run `effing-cloud login` to refresh the stored credentials.";throw new Error(`--account '${e.account}' does not match the API key's account '${a}'. ${f}`)}return{projectSlug:t,bounds:o,tags:r,apiKey:i.apiKey,urlSecret:s,accountSlug:a}}function le(e){P(e.command("url <kind> <id>").description("Print a signed production fn URL (kind: image|annie|effie); without --props it renders the module's previewProps"),"this URL").option("-p, --props <json>","props as a JSON object (default: the module's previewProps); the server camelizes keys, so image_url arrives as imageUrl").action(l(on))}async function on(e,n,t){let o=O(e),r=t.props===void 0?null:tn(t.props),{projectSlug:i,bounds:s,tags:a,urlSecret:f,accountSlug:d}=await F(t),g=`${U()}/${d}/${i}/${o}`;if(r===null){console.error("No --props given \u2014 printing a preview URL (renders the module's previewProps).");let c=a.length>0?{id:n,bounds:s,tags:a}:{id:n,bounds:s},u=await ce(c,f);console.log(`${g}/preview/${u}`)}else{let c=a.length>0?{id:n,props:r,bounds:s,tags:a}:{id:n,props:r,bounds:s},u=await ce(c,f);console.log(`${g}/${u}`)}}function tn(e){if(e==="")return{};let n;try{n=JSON.parse(e)}catch(t){let o=t instanceof Error?t.message:String(t);throw new Error(`--props is not valid JSON: ${o}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("--props must be a JSON object.");return n}import{serialize as rn}from"@effing/serde";function ue(e){P(e.command("urls [kind]").description("Print signed preview URLs for all fns in the active deployment, optionally filtered by kind"),"these URLs").option("--json","print the URLs as JSON").action(l(sn))}async function sn(e,n){let t=e===void 0?k:[O(e)],{projectSlug:o,bounds:r,tags:i,apiKey:s,urlSecret:a,accountSlug:f}=await F(n),d=await ae(o,s),g=[];for(let c of t)for(let u of d[c]??[]){let C=i.length>0?{id:u,bounds:r,tags:i}:{id:u,bounds:r},K=await rn(C,a),pe=`${U()}/${f}/${o}/${c}/preview/${K}`;g.push({kind:c,id:u,url:pe})}if(n.json)console.log(JSON.stringify({account:f,project:o,urls:g},null,2));else for(let{kind:c,id:u,url:C}of g)console.log(`${c}/${u} ${C}`);g.length===0&&console.error(e===void 0?"The active deployment has no fns.":`The active deployment has no ${e} fns.`)}import an from"process";function fe(e){e.command("url-secret [project]").description("Print the URL-signing secret for a project").option("-c, --config <path>","path to the effing.config.ts file").option("-a, --account <slug>","account slug to read from").action(l(cn))}async function cn(e,n){let t=e;if(!t){let{config:i}=await $(an.cwd(),n.config);t=i.project}let o=w({accountFlag:n.account});o.kind==="profile"&&console.error(`Reading from "${o.name}" (${o.slug}).`);let{urlSecret:r}=await G(t,o.apiKey);console.log(r)}function de(e){e.command("whoami").description("Check the API key in use and print the account it belongs to").option("-a, --account <slug>","account slug to check").option("--json","print the result as JSON").action(l(ln))}async function ln(e){let n=w({accountFlag:e.account}),t=n.kind==="env"?"EFFING_CLOUD_API_KEY":`profile '${n.slug}' in ${j()}`,r=await(await h("/-/whoami",{apiKey:n.apiKey}).catch(a=>{throw a instanceof y&&(a.status===401||a.status===403)?new Error(`The API key from ${t} was rejected. ${a.message}`):a instanceof y&&a.status===404?new Error("The fn service predates the `whoami` command. Redeploy the fn service to use it."):a})).json(),i=r.account;if(typeof i?.slug!="string"||typeof i.name!="string")throw new Error("Response missing account");let s=typeof r.apiKey?.project=="string"?r.apiKey.project:null;if(e.json){console.log(JSON.stringify({account:{slug:i.slug,name:i.name},apiKey:{id:r.apiKey?.id??null,name:r.apiKey?.name??null,project:s},source:n.kind==="env"?"env":"profile",profile:n.kind==="profile"?n.slug:null},null,2));return}console.log(`Account: "${i.name}" (${i.slug})`),r.apiKey?.name&&console.log(`API key: ${r.apiKey.name}`),console.log(`Scope: ${s===null?"whole account":`project '${s}' only`}`),console.log(`Source: ${t}`),n.kind==="profile"&&n.slug!==i.slug&&console.error(`Warning: the stored profile '${n.slug}' holds a key for '${i.slug}'. Run \`effing-cloud login\` to refresh it.`)}var dn=un(import.meta.url),{version:pn}=dn("../package.json"),p=new fn;p.name("effing-cloud").description("CLI for the Effing Cloud platform").version(pn).addHelpText("afterAll",`
5
+ `),console.log(` ${t.browserUrl}
6
+ `),e.browser&&X.stdout.isTTY&&ut(t.browserUrl),console.log("Waiting for approval...");let{apiKey:o,account:n}=await ct(t),{previousApiKey:r,existed:s,wasFirst:i}=ce({slug:n.slug,name:n.name,apiKey:o});r&&await j(r),console.log(s?`
7
+ Re-authorized "${n.name}" (${n.slug}).`:i?`
8
+ Logged in as "${n.name}" (${n.slug}). Set as default account.`:`
9
+ Added account "${n.name}" (${n.slug}). Run \`effing-cloud use ${n.slug}\` to make it your default.`)}async function at(){return await(await P("/cli-auth/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientName:"effing-cloud-cli",clientVersion:st,hostname:nt.hostname()}),expectedStatus:200})).json()}async function ct(e){let t=new Date(e.expiresAt).getTime(),o=!0;for(;Date.now()<t;){o||await lt(e.pollIntervalMs),o=!1;let n=await P("/cli-auth/poll",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliToken:e.cliToken})});if(n.status===404)throw new Error("Authorization session not found. Please run `effing-cloud login` again.");if(!n.ok){let s=await n.text();throw new Error(`Polling failed \u2014 ${n.status} ${n.statusText}: ${s}`)}let r=await n.json();if(r.status!=="pending"){if(r.status==="denied")throw new Error("Authorization denied.");if(r.status==="expired")throw new Error("Authorization session expired.");if(r.status==="consumed")throw new Error("This authorization session was already used. Run `effing-cloud login` again.");if(r.status==="approved")return{apiKey:r.apiKey,account:r.account}}}throw new Error("Authorization session expired before approval.")}function lt(e){return new Promise(t=>setTimeout(t,e))}function ut(e){try{X.platform==="darwin"?H("open",[e],{detached:!0,stdio:"ignore"}).unref():X.platform==="win32"?H("cmd.exe",["/c","start","",e],{detached:!0,stdio:"ignore"}).unref():H("xdg-open",[e],{detached:!0,stdio:"ignore"}).unref()}catch{}}function pe(e){e.command("logout").description("Sign out and remove saved credentials").option("--account <slug>","log out of a specific account").option("--all","log out of every account").action(p(ft))}async function ft(e){let t=E();if(!t||Object.keys(t.accounts).length===0){console.log("Not logged in.");return}if(e.all){let n=Object.entries(t.accounts);await Promise.all(n.map(([,r])=>j(r.apiKey))),W(),console.log(`Logged out of ${n.length} account(s).`);return}if(e.account){await de(e.account,t.accounts[e.account]?.apiKey);return}let o=Object.keys(t.accounts);if(o.length===1){await de(o[0],t.accounts[o[0]].apiKey);return}throw new Error(`Multiple accounts configured: ${o.sort().join(", ")}. Pass --account <slug> to remove one or --all to remove every account.`)}async function de(e,t){if(!t)throw new Error(`No credentials for account '${e}'.`);await j(t);let{newDefault:o,remaining:n}=le(e);console.log(n===0?`Logged out of '${e}'. No accounts remain.`:o&&o!==e?`Logged out of '${e}'. Default account is now '${o}'.`:`Logged out of '${e}'.`)}import dt from"process";function ge(e){e.command("accounts").description("List accounts you've logged in to").action(p(pt))}function pt(){let e=E(),t=e?Object.entries(e.accounts):[];if(t.length===0){console.log("No accounts. Run `effing-cloud login`.");return}t.sort(([n],[r])=>n.localeCompare(r));let o=Math.max(...t.map(([n])=>n.length));for(let[n,r]of t){let s=e?.default===n?"*":" ";console.log(`${s} ${n.padEnd(o)} ${r.name}`)}dt.env.EFFING_CLOUD_API_KEY&&console.log(`
10
+ EFFING_CLOUD_API_KEY is set and takes precedence over all profiles.`)}function me(e){e.command("use <account>").description("Set the default account for subsequent commands").action(p(t=>{let n=ue(t).accounts[t];console.log(`Default account is now "${n.name}" (${t}).`)}))}import Nt from"process";import F from"path";import Q from"fs";import{pathToFileURL as gt}from"url";import{randomBytes as mt}from"crypto";import{build as ht}from"esbuild";import{z as v}from"zod";var Z=v.union([v.string(),v.array(v.string())]),yt=v.object({project:v.string().min(1),images:Z.optional(),annies:Z.optional(),effies:Z.optional(),dev:v.unknown().optional()});var wt=["effing.config.ts","effing.config.mts","effing.config.js","effing.config.mjs"],bt=["effing-cloud.config.ts","effing-cloud.config.mts","effing-cloud.config.js"];function Et(e,t){if(t){let o=F.isAbsolute(t)?t:F.resolve(e,t);if(!Q.existsSync(o))throw new Error(`Config file not found: ${o}`);return o}for(let o of[...wt,...bt]){let n=F.resolve(e,o);if(Q.existsSync(n))return n}throw new Error(`No effing.config.ts found in ${e}. Create one with \`export default defineConfig({ project: "...", ... })\` or pass --config <path>.`)}function St(){return{name:"effing-define-config-stub",setup(e){e.onResolve({filter:/^(@effing\/dev|effing-cloud)$/},t=>({path:t.path,namespace:"effing-define-config-stub"})),e.onLoad({filter:/.*/,namespace:"effing-define-config-stub"},()=>({contents:"export const defineConfig = (c) => c;",loader:"js"}))}}}async function O(e,t){let o=Et(e,t),n=F.dirname(o),r=F.join(n,`.effing.config.${mt(4).toString("hex")}.mjs`);try{await ht({entryPoints:[o],outfile:r,bundle:!0,format:"esm",platform:"node",target:"node22",packages:"external",plugins:[St()],logLevel:"silent"});let s=await import(gt(r).href),i=yt.safeParse(s.default);if(!i.success)throw new Error(`Invalid config in ${o}:
11
+ ${i.error.message}`);return{config:i.data,configPath:o,configDir:n}}finally{await Q.promises.unlink(r).catch(()=>{})}}import $t from"path";import{build as At}from"esbuild";import{glob as vt}from"tinyglobby";var Ct={image:"images",annie:"annies",effie:"effies"};async function he(e){let{configDir:t,config:o}=e,n={image:await V(t,o.images),annie:await V(t,o.annies),effie:await V(t,o.effies)};if(n.image.length+n.annie.length+n.effie.length===0)throw new Error(`No modules matched the globs in the config. Set images/annies/effies to paths that exist relative to ${t}.`);let s=Ut(n),i=await At({stdin:{contents:s,resolveDir:t,loader:"ts",sourcefile:"effing-entry.ts"},bundle:!0,format:"esm",platform:"node",target:"node22",external:["node:*","@effing/skia","@napi-rs/canvas","@effing/fn"],write:!1,logLevel:"silent"});if(i.outputFiles.length!==1)throw new Error(`esbuild produced ${i.outputFiles.length} output files; expected 1`);let a=i.outputFiles[0].contents,d=new ArrayBuffer(a.byteLength),f=new Uint8Array(d);f.set(a);let l={modules:{image:n.image.map(c=>c.id),annie:n.annie.map(c=>c.id),effie:n.effie.map(c=>c.id)}};return{bundle:f,manifest:l}}async function V(e,t){if(!t)return[];let o=Array.isArray(t)?t:[t],n=await vt(o,{cwd:e,absolute:!0}),r=new Map;for(let s of n){let i=$t.basename(s).split(".")[0],a=r.get(i);if(a&&a!==s)throw new Error(`Duplicate module id "${i}" \u2014 matched by both ${a} and ${s}. Module ids must be unique per kind.`);r.set(i,s)}return[...r.entries()].map(([s,i])=>({id:s,absPath:i})).sort((s,i)=>s.id.localeCompare(i.id))}function Ut(e){let t=[],o=(n,r)=>`_${n}_${r}`;for(let n of["image","annie","effie"])e[n].forEach((r,s)=>{let i=o(n,s);t.push(`import { propsSchema as ${i}_ps, previewProps as ${i}_pp, runner as ${i}_r } from ${JSON.stringify(r.absPath)};`)});for(let n of["image","annie","effie"]){let r=Ct[n];t.push(`export const ${r} = {`),e[n].forEach((s,i)=>{let a=o(n,i);t.push(` ${JSON.stringify(s.id)}: { propsSchema: ${a}_ps, previewProps: ${a}_pp, runner: ${a}_r },`)}),t.push("};")}return t.join(`
12
+ `)}import xt from"process";var Rt="https://fn.effing.dev";function I(){return(xt.env.EFFING_CLOUD_FN_BASE_URL??Rt).replace(/\/$/,"")}var $=class extends Error{constructor(o,n){super(o);this.status=n}status};async function S(e,t){let{apiKey:o,expectedStatus:n=200,headers:r,...s}=t,i=await fetch(`${I()}${e}`,{...s,headers:{...r,Authorization:`Bearer ${o}`}});if(i.status!==n){let a=await i.text();throw new $(`Request failed \u2014 ${i.status} ${i.statusText}: ${a}`,i.status)}return i}import ye from"process";function y(e={}){let t=ye.env.EFFING_CLOUD_API_KEY;if(t)return e.accountFlag&&console.error(`Warning: EFFING_CLOUD_API_KEY is set and takes precedence; ignoring --account '${e.accountFlag}'. Unset the variable to use stored credentials.`),{kind:"env",apiKey:t};let o=E();if(!o||Object.keys(o.accounts).length===0)throw new Error("Not logged in. Run `effing-cloud login`.");let n=Ot(o,e);if(!n){let s=Object.keys(o.accounts).sort().join(", ");throw new Error(`Multiple accounts available: ${s}. Use --account, EFFING_CLOUD_ACCOUNT, or \`effing-cloud use <slug>\`.`)}let r=o.accounts[n];if(!r){let s=Object.keys(o.accounts).sort().join(", ");throw new Error(`No credentials for account '${n}'. Available: ${s}. Run \`effing-cloud login\` to add it.`)}return{kind:"profile",slug:n,name:r.name,apiKey:r.apiKey}}function Ot(e,t){let o=t.accountFlag??ye.env.EFFING_CLOUD_ACCOUNT??null;if(o)return o;if(e.default)return e.default;let n=Object.keys(e.accounts);return n.length===1?n[0]:null}function we(e){e.command("deploy").description("Bundle and deploy your @effing/fn functions to Effing Cloud").option("-c, --config <path>","path to the effing.config.ts file").option("-a, --account <slug>","account slug to deploy to").option("--dry-run","bundle without uploading \u2014 prints the manifest and bundle size",!1).option("--json","print the result as JSON on stdout (progress goes to stderr)").action(p(_t))}async function _t(e){let t=e.json?console.error:console.log,{config:o,configDir:n,configPath:r}=await O(Nt.cwd(),e.config);t(`Loaded config from ${r}`);let s=e.dryRun?null:y({accountFlag:e.account});s?.kind==="profile"&&t(`Deploying to "${s.name}" (${s.slug}).`);let{bundle:i,manifest:a}=await he({configDir:n,config:o}),d=a.modules.image.length+a.modules.annie.length+a.modules.effie.length;if(t(`Bundled ${d} module(s) \u2014 image: ${a.modules.image.length}, annie: ${a.modules.annie.length}, effie: ${a.modules.effie.length} (${i.byteLength} bytes)`),e.dryRun||!s){if(e.json){console.log(JSON.stringify({dryRun:!0,project:o.project,bundleSize:i.byteLength,manifest:a},null,2));return}console.log("Dry run \u2014 skipping upload. Manifest:"),console.log(JSON.stringify(a,null,2));return}let f=new FormData;f.append("project",o.project),f.append("manifest",JSON.stringify(a)),f.append("bundle",new Blob([i],{type:"application/javascript"}),"bundle.js");let c=await(await S("/-/deployments",{method:"POST",body:f,apiKey:s.apiKey,expectedStatus:201})).json();if(e.json){console.log(JSON.stringify({dryRun:!1,project:o.project,id:c.id,version:c.version,bundleHash:c.bundleHash,bundleSize:c.bundleSize,previews:(c.previews??[]).map(({kind:u,id:g,url:m})=>({kind:u,id:g,url:m}))},null,2));return}if(console.log(`Deployed ${o.project} \u2014 version ${c.version}, deployment ${c.id}, hash ${c.bundleHash}, ${c.bundleSize} bytes`),c.previews&&c.previews.length>0){console.log(`
13
+ Previews:`);for(let u of c.previews)console.log(` ${u.kind}/${u.id} ${u.url}`)}}import{serialize as ve}from"@effing/serde";import Pt from"process";import{z as N}from"zod";var L=["image","annie","effie"];function D(e){if(!L.includes(e))throw new Error(`Invalid kind '${e}'. Expected one of: ${L.join(", ")}.`);return e}var Tt=[{width:1080,height:1080,label:"1:1"},{width:1080,height:1350,label:"4:5"},{width:1080,height:1920,label:"9:16"}],kt=N.object({resolutions:N.array(N.object({label:N.string(),width:N.number().int().positive(),height:N.number().int().positive()})).nonempty().optional()}),be=8192;function jt(e,t){for(let[s,i]of[["--width",t.width],["--height",t.height]])if(i!==void 0){if(!Number.isInteger(i))throw new Error(`${s} must be an integer.`);if(i<1||i>be)throw new Error(`${s} must be between 1 and ${be}.`)}let o=kt.safeParse(e??{});if(!o.success)throw new Error(`Invalid dev.resolutions in the config:
14
+ ${o.error.message}`);let n=o.data.resolutions??Tt;if(t.resolution!==void 0){if(t.width!==void 0||t.height!==void 0)throw new Error("--resolution cannot be combined with --width/--height.");let s=n.find(i=>i.label===t.resolution);if(!s)throw new Error(`Unknown resolution '${t.resolution}'. Available: ${n.map(i=>i.label).join(", ")}.`);return{width:s.width,height:s.height}}let r=n[0];return{width:t.width??r.width,height:t.height??r.height}}var Ee=64,Se=256;function Ft(e){if(e.length>Ee)throw new Error(`Too many --tag entries (${e.length}): the server allows at most ${Ee} tags per run.`);let t=new Set,o=new Set;for(let n of e){if(n==="")throw new Error("--tag entries must be non-empty.");if(n.length>Se)throw new Error(`--tag "${n}" exceeds ${Se} characters.`);if(t.has(n))throw new Error(`Duplicate tag "${n}": each tag may only appear once.`);t.add(n);let r=n.indexOf(":");if(r!==-1){let s=n.slice(0,r);if(o.has(s))throw new Error(`Duplicate tag name "${s}": each tag name may only appear once.`);o.add(s)}}return e}async function ee(e,t){let n=await(await S(`/-/projects/${encodeURIComponent(e)}/url-secret`,{apiKey:t})).json();if(typeof n.urlSecret!="string")throw new Error("Response missing urlSecret");let r=n.account?.slug;return{urlSecret:n.urlSecret,accountSlug:typeof r=="string"?r:void 0}}async function It(e,t){let{urlSecret:o,accountSlug:n}=await ee(e,t);if(n===void 0)throw new Error("The url-secret response has no account slug: the fn service predates the `url`/`urls` commands. Redeploy the fn service to use them.");return{urlSecret:o,accountSlug:n}}async function Ae(e,t){try{let i=await S(`/-/deployments/active?project=${encodeURIComponent(e)}`,{apiKey:t});return $e(await i.json())}catch(i){if(!(i instanceof $)||i.status!==404)throw i}let o=await S(`/-/deployments?project=${encodeURIComponent(e)}`,{apiKey:t}),{deployments:n}=await o.json();if(!n||n.length===0)throw new Error(`No deployments found for project "${e}".`);let r=n.reduce((i,a)=>a.version>i.version?a:i),s=await S(`/-/deployments/${encodeURIComponent(r.id)}`,{apiKey:t});return $e(await s.json())}function $e(e){let{modules:t}=e;if(t===null||typeof t!="object")throw new Error("Deployment response missing modules");return t}function K(e,t){return e.option("-c, --config <path>","path to the effing.config.ts file").option("-a, --account <slug>","account slug to read from").option("--project <slug>","project slug (default: the config's project)").option("-w, --width <number>","width in pixels",o=>parseInt(o,10)).option("--height <number>","height in pixels",o=>parseInt(o,10)).option("-r, --resolution <label>",'pick bounds from a dev.resolutions preset by label (e.g. "9:16")').option("-t, --tag <tag>",`tag runs served by ${t}, as "name:value" or a bare tag (repeatable)`,(o,n)=>[...n,o],[])}async function B(e){let t,o;if(e.project!==void 0)o=e.project;else{let{config:d}=await O(Pt.cwd(),e.config);o=d.project,t=d.dev}let n=jt(t,e),r=Ft(e.tag),s=y({accountFlag:e.account});s.kind==="profile"&&console.error(`Reading from "${s.name}" (${s.slug}).`);let{urlSecret:i,accountSlug:a}=await It(o,s.apiKey);if(e.account!==void 0&&a!==e.account){let d=s.kind==="env"?"EFFING_CLOUD_API_KEY takes precedence over --account; unset it or drop the flag.":"Run `effing-cloud login` to refresh the stored credentials.";throw new Error(`--account '${e.account}' does not match the API key's account '${a}'. ${d}`)}return{projectSlug:o,bounds:n,tags:r,apiKey:s.apiKey,urlSecret:i,accountSlug:a}}function Ce(e){K(e.command("url <kind> <id>").description("Print a signed production fn URL (kind: image|annie|effie); without --props it renders the module's previewProps"),"this URL").option("-p, --props <json>","props as a JSON object (default: the module's previewProps); the server camelizes keys, so image_url arrives as imageUrl").action(p(Lt))}async function Lt(e,t,o){let n=D(e),r=o.props===void 0?null:Dt(o.props),{projectSlug:s,bounds:i,tags:a,urlSecret:d,accountSlug:f}=await B(o),l=`${I()}/${f}/${s}/${n}`;if(r===null){console.error("No --props given \u2014 printing a preview URL (renders the module's previewProps).");let c=a.length>0?{id:t,bounds:i,tags:a}:{id:t,bounds:i},u=await ve(c,d);console.log(`${l}/preview/${u}`)}else{let c=a.length>0?{id:t,props:r,bounds:i,tags:a}:{id:t,props:r,bounds:i},u=await ve(c,d);console.log(`${l}/${u}`)}}function Dt(e){if(e==="")return{};let t;try{t=JSON.parse(e)}catch(o){let n=o instanceof Error?o.message:String(o);throw new Error(`--props is not valid JSON: ${n}`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("--props must be a JSON object.");return t}import{serialize as Kt}from"@effing/serde";function Ue(e){K(e.command("urls [kind]").description("Print signed preview URLs for all fns in the active deployment, optionally filtered by kind"),"these URLs").option("--json","print the URLs as JSON").action(p(Bt))}async function Bt(e,t){let o=e===void 0?L:[D(e)],{projectSlug:n,bounds:r,tags:s,apiKey:i,urlSecret:a,accountSlug:d}=await B(t),f=await Ae(n,i),l=[];for(let c of o)for(let u of f[c]??[]){let g=s.length>0?{id:u,bounds:r,tags:s}:{id:u,bounds:r},m=await Kt(g,a),A=`${I()}/${d}/${n}/${c}/preview/${m}`;l.push({kind:c,id:u,url:A})}if(t.json)console.log(JSON.stringify({account:d,project:n,urls:l},null,2));else for(let{kind:c,id:u,url:g}of l)console.log(`${c}/${u} ${g}`);l.length===0&&console.error(e===void 0?"The active deployment has no fns.":`The active deployment has no ${e} fns.`)}import Mt from"process";function xe(e){e.command("url-secret [project]").description("Print the URL-signing secret for a project").option("-c, --config <path>","path to the effing.config.ts file").option("-a, --account <slug>","account slug to read from").action(p(zt))}async function zt(e,t){let o=e;if(!o){let{config:s}=await O(Mt.cwd(),t.config);o=s.project}let n=y({accountFlag:t.account});n.kind==="profile"&&console.error(`Reading from "${n.name}" (${n.slug}).`);let{urlSecret:r}=await ee(o,n.apiKey);console.log(r)}function Re(e){e.command("whoami").description("Check the API key in use and print the account it belongs to").option("-a, --account <slug>","account slug to check").option("--json","print the result as JSON").action(p(Gt))}async function Gt(e){let t=y({accountFlag:e.account}),o=t.kind==="env"?"EFFING_CLOUD_API_KEY":`profile '${t.slug}' in ${k()}`,r=await(await S("/-/whoami",{apiKey:t.apiKey}).catch(a=>{throw a instanceof $&&(a.status===401||a.status===403)?new Error(`The API key from ${o} was rejected. ${a.message}`):a instanceof $&&a.status===404?new Error("The fn service predates the `whoami` command. Redeploy the fn service to use it."):a})).json(),s=r.account;if(typeof s?.slug!="string"||typeof s.name!="string")throw new Error("Response missing account");let i=typeof r.apiKey?.project=="string"?r.apiKey.project:null;if(e.json){console.log(JSON.stringify({account:{slug:s.slug,name:s.name},apiKey:{id:r.apiKey?.id??null,name:r.apiKey?.name??null,project:i},source:t.kind==="env"?"env":"profile",profile:t.kind==="profile"?t.slug:null},null,2));return}console.log(`Account: "${s.name}" (${s.slug})`),r.apiKey?.name&&console.log(`API key: ${r.apiKey.name}`),console.log(`Scope: ${i===null?"whole account":`project '${i}' only`}`),console.log(`Source: ${o}`),t.kind==="profile"&&t.slug!==s.slug&&console.error(`Warning: the stored profile '${t.slug}' holds a key for '${s.slug}'. Run \`effing-cloud login\` to refresh it.`)}import nn from"fs";import Ge from"path";import U from"process";import{setTimeout as on}from"timers/promises";import{InvalidArgumentError as rn}from"commander";import te from"fs";import qt from"path";import Jt from"process";import{setTimeout as Yt}from"timers/promises";var Oe="https://ass.effing.dev";function z(){let e=Jt.env.EFFING_CLOUD_ASS_BASE_URL?.trim()||Oe,t=null;try{t=new URL(e)}catch{}if(!t||t.protocol!=="http:"&&t.protocol!=="https:"||t.search!==""||t.hash!==""||t.username!==""||t.password!==""||e.includes("?")||e.includes("#"))throw new Error(`EFFING_CLOUD_ASS_BASE_URL must be an http:// or https:// URL without credentials, a query or a fragment, like ${Oe}.`);return e.replace(/\/+$/,"")}var _e=100*1024*1024,Pe={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",avif:"image/avif",qoi:"image/qoi",mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2"};function oe(e){let t=qt.extname(e).slice(1).toLowerCase();return Pe[t]??null}function Te(){return Object.keys(Pe)}var b=class extends Error{constructor(o,n,r){super(o);this.status=n;this.code=r}status;code},ne=class extends Error{},M=class extends Error{constructor(){super("Interrupted.")}},Wt={UNAUTHORIZED:"Run `effing-cloud login`, or check EFFING_CLOUD_API_KEY.",QUOTA_EXCEEDED:"Run `effing-cloud ass list` to see what is stored and `effing-cloud ass rm <assetId>` to free space.",PROJECT_SCOPED_KEY:"ASS needs an account-wide API key: set EFFING_CLOUD_API_KEY to one (create it on the Credentials page of the Effing Cloud console), or unset it to use your `effing-cloud login` credentials."},Ht=3,Xt=5,ke=60,Ne=30;async function G(e,t){let{apiKey:o,expectedStatus:n=200,headers:r,stopRetrying:s,interrupt:i,...a}=t,d=i??s,f=z();for(let l=0;;l++){if(i?.aborted)throw new M;let c,u,g=Zt(i);try{c=await fetch(`${f}${e}`,{signal:g.signal,...a,headers:{...r,Authorization:`Bearer ${o}`}}),u=await c.text()}catch(m){if(i?.aborted)throw new M;let A=m.name==="TimeoutError"?`no answer within ${ke} seconds`:je(m);throw new ne(`Could not reach ${f}: ${A}`)}finally{g.done()}if(c.status===n)try{return JSON.parse(u)}catch{throw new Error(`Unexpected response from ASS: ${re(u,200)}`)}if(!(c.status===429&&l<Ht&&!d?.aborted&&(await Yt(Qt(c.headers.get("Retry-After")),void 0,{signal:d}).catch(()=>{}),!d?.aborted)))throw Vt(c,u)}}function Zt(e){let t=AbortSignal.timeout(ke*1e3);if(!e)return{signal:t,done:()=>{}};let o=new AbortController,n=()=>o.abort(t.reason),r=()=>o.abort(e.reason);return t.addEventListener("abort",n),e.addEventListener("abort",r),{signal:o.signal,done:()=>{t.removeEventListener("abort",n),e.removeEventListener("abort",r)}}}function Qt(e){let t=e===null||e.trim()===""?NaN:Number(e);return!Number.isFinite(t)||t<0?1e3:Math.min(t,Xt)*1e3}function je(e){let t=e.cause;return typeof t?.message=="string"&&t.message!==""?t.message:typeof t?.code=="string"&&t.code!==""?t.code:e.message}function Vt(e,t){let o=null;try{o=JSON.parse(t)}catch{}let{error:n,code:r}=o??{};if(typeof n=="string"){let s=typeof r=="string"?r:null,i=s?Wt[s]:void 0,a=i?`${C(n)} ${i}`:n;return new b(a,e.status,s)}return new b(`Request failed \u2014 ${e.status} ${e.statusText}: ${re(t)}`,e.status,null)}function C(e){return/[.!?]$/.test(e)?e:`${e}.`}function re(e,t=500){return e.length>t?`${e.slice(0,t)}\u2026`:e}async function Fe(e,t,o={}){let n=await G("/-/uploads",{apiKey:e,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),expectedStatus:201,stopRetrying:o.stopRetrying})??{};if(typeof n.assetId!="string"||typeof n.uploadUrl!="string"||typeof n.url!="string"||n.headers===null||typeof n.headers!="object")throw new Error("Unexpected response from ASS: the upload is missing its URL or headers.");return{assetId:n.assetId,uploadUrl:n.uploadUrl,method:typeof n.method=="string"?n.method:"PUT",headers:n.headers,expiresAt:typeof n.expiresAt=="string"?n.expiresAt:"",url:n.url}}async function Ie(e,t,o,n){let r=await en(t);if(n?.aborted)throw new Error("Upload interrupted.");let s=r instanceof Blob?r.size:r.byteLength;if(s!==o)throw new Error(`${t} changed while uploading (was ${o} bytes, now ${s}).`);let i=new AbortController,a=()=>i.abort();n?.addEventListener("abort",a);let d=!1,f=setTimeout(()=>{d=!0,i.abort()},Ne*6e4),l,c="";try{l=await fetch(e.uploadUrl,{method:e.method,headers:e.headers,body:r,signal:i.signal}),l.ok?await l.body?.cancel():c=await l.text().catch(u=>{if(i.signal.aborted)throw u;return""})}catch(u){throw d?new Error(`Uploading the file to storage failed: it didn't finish within ${Ne} minutes.`):n?.aborted?new Error("Upload interrupted."):u.cause?.name==="NotReadableError"?new Error(`${t} changed while uploading.`):new Error(`Uploading the file to storage failed: ${je(u)}`)}finally{clearTimeout(f),n?.removeEventListener("abort",a)}if(!l.ok){let u=tn(c),g=l.status===403&&/expired/i.test(u);throw new Error(`Uploading the file to storage failed \u2014 ${l.status} ${l.statusText}`+(u?`: ${u}`:"")+(g?" (the upload URL expired; run the command again)":""))}}async function en(e){return typeof te.openAsBlob=="function"?te.openAsBlob(e):te.promises.readFile(e)}function tn(e){let t=/<Code>([^<]*)<\/Code>/.exec(e)?.[1],o=/<Message>([^<]*)<\/Message>/.exec(e)?.[1];return t||o?[t,o].filter(Boolean).join(" "):re(e.trim(),200)}async function Le(e,t,o={}){return Be(await G(`/-/uploads/${encodeURIComponent(t)}/complete`,{apiKey:e,method:"POST",interrupt:o.interrupt}))}async function De(e,t={}){let o=new URLSearchParams;t.cursor!==void 0&&o.set("cursor",t.cursor),t.limit!==void 0&&o.set("limit",String(t.limit));let n=o.toString(),r=n?`?${n}`:"",s=await G(`/-/assets${r}`,{apiKey:e})??{};if(!Array.isArray(s.assets)||typeof s.usedBytes!="number"||typeof s.quotaBytes!="number")throw new Error("Unexpected response from ASS: the asset list is malformed.");return{assets:s.assets.map(Be),usedBytes:s.usedBytes,...typeof s.reservedBytes=="number"?{reservedBytes:s.reservedBytes}:{},quotaBytes:s.quotaBytes,nextCursor:typeof s.nextCursor=="string"?s.nextCursor:null}}async function Ke(e,t){let o=await G(`/-/assets/${encodeURIComponent(t)}`,{apiKey:e,method:"DELETE"});return{id:typeof o?.id=="string"?o.id:t}}function Be(e){let t=e??{};if(typeof t.id!="string"||typeof t.filename!="string"||typeof t.contentType!="string"||typeof t.sizeBytes!="number"||typeof t.url!="string"||typeof t.createdAt!="string")throw new Error("Unexpected response from ASS: an asset is malformed.");return{id:t.id,filename:t.filename,contentType:t.contentType,sizeBytes:t.sizeBytes,url:t.url,createdAt:t.createdAt}}var Me=100;function qe(e){let t=e.command("ass").description("Store files (audio, images, video, fonts) at public URLs on ass.effing.dev for your fns and effies to use").addHelpText("afterAll",`
15
+ Environment (ass):
16
+ EFFING_CLOUD_ASS_BASE_URL ASS base URL instead of https://ass.effing.dev; it
17
+ must serve the ASS API under /-/ like the edge Worker`);t.command("upload <file>").description("Upload a file and print its public URL").option("-a, --account <slug>","account slug to upload to").option("--name <filename>","file name in the URL (default: the file's own name)").option("--content-type <type>","content type to serve the file with (default: from the file extension)").option("--json","print the uploaded asset as JSON on stdout (progress goes to stderr)").action(p(an)),t.command("list").description("List the account's assets, newest first, with storage used and quota").option("-a, --account <slug>","account slug to list").option("--limit <number>","list at most this many assets (default: all)",sn).option("--cursor <cursor>","continue a listing from the nextCursor of an earlier one").option("--json","print the assets as JSON").action(p(gn)),t.command("rm <assetId>").description("Delete an asset. Its URL stops working within an hour, and fns that use it will break").option("-a, --account <slug>","account slug to delete from").option("--json","print the result as JSON").action(p(mn))}function sn(e){let t=Number(e);if(!/^\d+$/.test(e.trim())||!Number.isSafeInteger(t)||t<1)throw new rn("must be a positive whole number.");return t}async function an(e,t){let o=dn(e),n=t.name??Ge.basename(e),r=pn(n,e,t.contentType);z();let{apiKey:s}=y({accountFlag:t.account}),i=new AbortController,a=!0,d=()=>{i.abort(),console.error(a?"Interrupted; the upload is cancelled as soon as it has been created\u2026":"Interrupted; stopping the upload\u2026")};U.once("SIGINT",d);let f,l=null;try{try{f=await Fe(s,{filename:n,contentType:r,sizeBytes:o},{stopRetrying:i.signal})}catch(h){let _=q(h)?`${C(h.message)} If the upload was created anyway, the ${x(o)} it reserves are released within an hour.`:h.message;if(!i.signal.aborted)throw new Error(_);console.error(_),U.exitCode=130;return}a=!1,i.signal.aborted||console.error(`Uploading ${e} (${x(o)}, ${r}) as asset ${f.assetId}\u2026`);try{await Ie(f,e,o,i.signal)}catch(h){l={error:h}}}finally{U.off("SIGINT",d)}let{assetId:c}=f;if(l||i.signal.aborted){let h=l?l.error.message:"Upload interrupted.";i.signal.aborted&&console.error(`Interrupted; cancelling asset ${c}\u2026`);let _=`${C(h)} ${await se(s,c)}`;if(!i.signal.aborted)throw new Error(_);console.error(_),U.exitCode=130;return}let u=new AbortController,g=()=>{u.abort(),console.error(`Interrupted; stopping the completion of asset ${c}\u2026`)};U.once("SIGINT",g);let m;try{m=await cn(s,c,u.signal)}finally{U.off("SIGINT",g)}if(u.signal.aborted){await ln(s,c,m),U.exitCode=130;return}if("error"in m){let h=m.error;throw m.maybeCompleted?new Error(`${C(h.message)} ${Ye(c)}`):h instanceof b&&h.code?.startsWith("ACCOUNT_")?h:new Error(`${C(fn(h))} ${await se(s,c)}`)}let{asset:A}=m;if(t.json){console.log(JSON.stringify(He(A),null,2));return}console.error(`Uploaded asset ${A.id}.`),console.log(A.url)}var Je=[250,1e3];async function cn(e,t,o){let n=!1;for(let r=0;;r++)try{return{asset:await Le(e,t,{interrupt:o})}}catch(s){let i=q(s);n||=i;let a=i||s instanceof b&&(s.status===429||s.code==="UPLOAD_CHANGED"),d=Je[r];if(d===void 0||!a||o.aborted)return{error:s,maybeCompleted:n};if(await on(d,void 0,{signal:o}).catch(()=>{}),o.aborted)return{error:s,maybeCompleted:n}}}function Ye(e){return`The upload may have been completed anyway: check \`effing-cloud ass list\` for asset ${e}. If it isn't listed, \`effing-cloud ass rm ${e}\` removes whatever of it reached storage; the space it holds is freed then, or up to an hour later if a completion of it may still be running.`}async function ln(e,t,o){if("asset"in o){let{asset:r}=o;console.error(`Interrupted, but the upload had already been completed: asset ${r.id} is published at ${r.url}. \`effing-cloud ass rm ${r.id}\` deletes it.`);return}if(o.maybeCompleted){console.error(`Upload interrupted. ${Ye(t)}`);return}let n=o.error;if(n instanceof b&&n.code?.startsWith("ACCOUNT_")){console.error(n.message);return}console.error(`Interrupted; cancelling asset ${t}\u2026`),console.error(`Upload interrupted. ${await se(e,t)}`)}async function We(e,t){for(let o=0;;o++)try{return await Ke(e,t)}catch(n){let r=Je[o];if(r===void 0||!q(n))throw n;await new Promise(s=>setTimeout(s,r))}}function q(e){return e instanceof b?e.code==="NOT_CONFIGURED"?!1:e.status<400||e.status>=500:!0}var un={NOT_UPLOADED:"The file didn't reach storage.",SIZE_MISMATCH:"Storage received a different number of bytes than the file has.",UPLOAD_CHANGED:"The file in storage changed while the upload was being completed.",QUOTA_EXCEEDED:"The file no longer fits in the account's storage quota. Run `effing-cloud ass list` to see what is stored and `effing-cloud ass rm <assetId>` to free space."};function fn(e){let t=e instanceof b?e.code:null;return t&&un[t]||e.message}async function se(e,t){let o="The upload was cancelled; nothing was stored.";try{return await We(e,t),o}catch(n){if(n instanceof b){if(n.code==="NOT_FOUND")return o;if(n.code==="ACCOUNT_NOT_FOUND")return"The account no longer exists.";if(n.code?.startsWith("ACCOUNT_"))return"The account isn't active, so the upload can't be cancelled; the storage it reserves is released within an hour."}return`Cancelling the upload failed; run \`effing-cloud ass rm ${t}\` to release the storage it holds.`}}function dn(e){let t;try{t=nn.statSync(e)}catch(o){throw o.code==="ENOENT"?new Error(`File not found: ${e}`):o}if(!t.isFile())throw new Error(`Not a file: ${e}`);if(t.size===0)throw new Error(`${e} is empty.`);if(t.size>_e)throw new Error(`${e} is too large (${x(t.size)}): files can be at most 100 MiB.`);return t.size}function pn(e,t,o){if(o!==void 0)return o.trim().toLowerCase();let n=oe(t),r=oe(e);if(n&&r&&n!==r)throw new Error(`${Ge.basename(t)} looks like ${n} but --name ${e} like ${r}. Pass --content-type to say which it is.`);let s=n??r;if(s)return s;throw new Error(`Can't tell the content type of ${e} from its extension. Pass --content-type, or use a file with one of these extensions: ${Te().join(", ")}.`)}async function gn(e){let t=y({accountFlag:e.account}),o=[],n,r=e.cursor;do{let i=e.limit===void 0?Me:e.limit-o.length;n=await De(t.apiKey,{cursor:r,limit:Math.min(i,Me)}),o.push(...n.assets),r=n.nextCursor??void 0}while(r!==void 0&&n.assets.length>0&&(e.limit===void 0||o.length<e.limit));if(e.json){console.log(JSON.stringify({assets:o.map(He),usedBytes:n.usedBytes,reservedBytes:n.reservedBytes??0,quotaBytes:n.quotaBytes,nextCursor:n.nextCursor},null,2));return}if(o.length===0)console.error(e.cursor===void 0?"No assets.":"No more assets.");else{let i=o.map(f=>x(f.sizeBytes)),a=i.reduce((f,l)=>Math.max(f,l.length),0),d=o.reduce((f,l)=>Math.max(f,l.contentType.length),0);o.forEach((f,l)=>{console.log([f.id,i[l].padStart(a),f.contentType.padEnd(d),hn(f.createdAt),f.url].join(" "))})}let s=n.reservedBytes??0;console.error(`Storage: ${x(n.usedBytes)} of ${x(n.quotaBytes)} used`+(s>0?`, ${x(s)} reserved by uploads and deletions in progress.`:".")),n.nextCursor!==null&&console.error(`More assets: run again with --cursor ${n.nextCursor}`)}async function mn(e,t){z();let o=y({accountFlag:t.account}),n;try{({id:n}=await We(o.apiKey,e))}catch(r){throw q(r)?new Error(`${C(r.message)} The asset may not have been deleted; \`effing-cloud ass rm ${e}\` is safe to run again.`):r}if(t.json){console.log(JSON.stringify({id:n,deleted:!0},null,2));return}console.log(`Deleted asset ${n}. Its URL stops working within an hour; fns that use it will break.`)}function He(e){return{id:e.id,filename:e.filename,contentType:e.contentType,sizeBytes:e.sizeBytes,url:e.url,createdAt:e.createdAt}}function hn(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:`${t.toISOString().slice(0,16).replace("T"," ")} UTC`}var ze=["B","KiB","MiB","GiB","TiB"];function x(e){let t=0,o=e;for(;;){let n=t===0?o:o<10?Math.round(o*10)/10:Math.round(o);if(n<1024||t===ze.length-1)return`${n} ${ze[t]}`;o/=1024,t++}}var bn=yn(import.meta.url),{version:En}=bn("../package.json"),w=new wn;w.name("effing-cloud").description("CLI for the Effing Cloud platform").version(En).addHelpText("afterAll",`
15
18
  Environment:
16
19
  EFFING_CLOUD_API_KEY API key to use instead of the credentials saved by
17
20
  \`effing-cloud login\`; takes precedence over --account and
18
21
  EFFING_CLOUD_ACCOUNT. For CI and scripts, create a key on the
19
22
  Credentials page of the Effing Cloud console.
20
- EFFING_CLOUD_ACCOUNT slug of the saved account to use, like --account`);H(p);V(p);Q(p);Z(p);oe(p);le(p);ue(p);fe(p);de(p);p.parse();
23
+ EFFING_CLOUD_ACCOUNT slug of the saved account to use, like --account`);fe(w);pe(w);ge(w);me(w);we(w);Ce(w);Ue(w);xe(w);Re(w);qe(w);w.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effing-cloud",
3
- "version": "0.8.5",
3
+ "version": "0.9.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,7 +20,7 @@
20
20
  "access": "public"
21
21
  },
22
22
  "dependencies": {
23
- "@effing/serde": "^0.48.2",
23
+ "@effing/serde": "^0.49.0",
24
24
  "commander": "^13.1.0",
25
25
  "esbuild": "^0.28.2",
26
26
  "tinyglobby": "^0.2.17",