Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cfw

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cfw - npm Package Compare versions

Comparing version 0.1.2 to 0.1.3

2

cfw.js
#!/usr/bin/env node
import e from"sade";import t from"kleur";import{send as r}from"httpie";import*as n from"fs";import{homedir as i}from"os";import{promisify as o}from"util";import{createRequire as s}from"module";import{resolve as a,parse as l,join as c}from"path";import{klona as d}from"klona/json";function u(e,t={}){return e.token?t.Authorization=`Bearer ${e.token}`:(t["X-Auth-Key"]=e.authkey,t["X-Auth-Email"]=e.email),t}function f(e,t,n={}){return r(e,"https://api.cloudflare.com/client/v4"+t,n).then((e=>e.data))}const m=" ~> ",p=" ".repeat(6),g=t.bold("[CFW]");function w(e,r){console.log(t[e](g),r.includes("\n")?r.replace(/(\r?\n)/g,"$1"+p):r)}const h=e=>w("white",e),y=e=>w("green",e),k=e=>w("yellow",e);function $(e,t=1){w("red",e),process.exit(t)}const b=t.dim().bold;function v(e,t){return(t.only||t.ignore)&&(e+=`\nPerhaps the ${b("--only")} or ${b("--ignore")} flag needs adjusting`),k(e)}function T(e){return t.italic().dim(` (${e}ms)`)}function E(e,r,n){let i="•",o=t.dim,s=null!=r?T(r):"";n?(i="+",o=t.green().dim):null!=n&&(i="-",o=t.red().dim),console.log(o(p+i+` "${e}"`)+s)}async function D(e,r){let n=0,i=e.length;if(i===n)return;const o=await import("esbuild");let s=await o.formatMessages(e,{terminalWidth:process.stdout.columns,kind:r?"error":"warning",color:t.enabled}),a=/\x1b\[32m/g,l=r?"":"",c=r?t.red:t.yellow,d=`Build ${r?"failed":"finished"} with`;for(d+=" "+t.underline(i)+" ",d+=r?"error":"warning",d+=1===i?":":"s:",d+="\n\n";n<i;n++)d+=t.bold().inverse(c(" "+e[n].location.file+" "))+" "+e[n].text,d+=s[n].substring(s[n].indexOf("\n")).replace(a,l);n=d.length,"\n"===d[--n]&&(d=d.substring(0,n)),(r?$:k)(d)}function W(e,t){return f("GET",`/accounts/${e.accountid}/workers/scripts/${t}/secrets`,{headers:u(e)}).catch((e=>{$(`Error fetching "${t}" secrets!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}function C(e,t,r,n){return f("PUT",`/accounts/${e.accountid}/workers/scripts/${t}/secrets`,{headers:u(e),body:{type:"secret_text",text:n,name:r}}).catch((e=>{$(`Error creating new "${t}" secret!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}function O(e,t,r,n){return f("DELETE",`/accounts/${e.accountid}/workers/scripts/${t}/secrets/${r}`,{headers:u(e)}).catch((e=>{let{data:i,message:o}=e;if(n&&i&&i.errors&&10056===i.errors[0].code)return i;$(`Error deleting "${t}/${r}" secret!\n${JSON.stringify(i||o,null,2)}`)}))}const L=o(n.writeFile),_=o(n.readFile),A=o(n.rmdir),x=o(n.readdir),j=n.existsSync;function N(e,t,r){return(r?j(e):!!e)||$(t)}function U(e){return new Set(Array.isArray(e)?e:e.split(","))}const F=s(import.meta.url);async function R(e,t="."){if(!j(e=a(t,e)))return!1;try{var r=F(e)}catch{r=await import(e).catch((()=>!1))}finally{return r||$(`Error loading "${e}" file`)}}async function S(e){let t;return(t=await R("cfw.js",e))||(t=await R("cfw.mjs",e))||(t=await R("cfw.cjs",e))||(t=await R("cfw.json",e))?t:(t=await R("package.json",e))?t.cfw:void 0}async function K(e,t,r){let n=r?e:c(e,t),i=await S(n)||{};return{cfw:i,name:i.name||t,input:c(n,i.entry||"index.js"),abs:n}}async function P(e,t){t.cwd=a(t.cwd);let r,n,i=a(t.cwd,e);N(i,`Workers directory does not exist: "${i}"`,!0);let{cwd:o,single:s,only:c,ignore:d}=t;if(s){let e=t.dir;"."===e&&(e=l(o).base);let r=await K(i,e,!0);return(n=await S(o))&&(Object.assign(r.cfw,n),n.name&&(r.name=n.name),t.profile&&(r.cfw.profile=t.profile)),[r]}let u=await x(i).then((e=>Promise.all(e.map((e=>K(i,e))))));return c?(r=U(c),u.filter((e=>r.has(e.name)))):d?(r=U(d),u.filter((e=>!r.has(e.name)))):u}async function M(e,t){let{CLOUDFLARE_ZONEID:r,CLOUDFLARE_ACCOUNTID:n,CLOUDFLARE_AUTH_EMAIL:o,CLOUDFLARE_AUTH_KEY:s,CLOUDFLARE_TOKEN:a}=process.env,l=o||e.email,d=s||e.authkey,u=n||e.accountid,f=r||e.zoneid,m=a||e.token;if((m||d&&l)&&u&&f)return{authkey:d,accountid:u,email:l,token:m,zoneid:f};if(e.profile){let t=await async function(e="default"){let t=c(i(),".cfw","config");N(t,`Missing "${t}" config file`,!0);let r,n,o={},s=0,a=/^\[(.*)\]$/,l=(await _(t,"utf8")).split(/(\r?\n)+/g);for(;s<l.length;s++)if(l[s].startsWith("#")||!l[s].trim().length);else if(a.test(l[s]))n=a.exec(l[s])[1],r=o[n]={};else{let[e,t]=l[s].split("=");r[e.trim()]=t.trim()}let d=o[e];return N(d,`The "${e}" profile is not defined`),d}(e.profile);Object.keys(t).forEach((e=>{!l&&/CLOUDFLARE_AUTH_EMAIL/i.test(e)&&(l=t[e]),!u&&/CLOUDFLARE_ACCOUNTID/i.test(e)&&(u=t[e]),!d&&/CLOUDFLARE_AUTH_KEY/i.test(e)&&(d=t[e]),!f&&/CLOUDFLARE_ZONEID/i.test(e)&&(f=t[e]),!m&&/CLOUDFLARE_TOKEN/i.test(e)&&(m=t[e])}))}return N(f||t,'Missing Cloudflare "zoneid" value!'),N(u,'Missing Cloudflare "accountid" value!'),m||d&&l||(d||l?(N(l,'Missing Cloudflare "email" value!'),N(d,'Missing Cloudflare "authkey" value!')):$('Missing Cloudflare "token" value or "email" + "authkey" combo!')),{authkey:d,accountid:u,email:l,token:m,zoneid:f}}const I=()=>Math.random().toString(36).slice(2);function J(e,t,r){return f("POST",`/zones/${e.zoneid}/workers/routes`,{headers:u(e,{"Content-Type":"application/javascript"}),body:{pattern:t,script:r}}).catch((e=>{let{data:r,message:n}=e;r&&r.errors&&10020===r.errors[0].code||$(`Error setting "${t}" route pattern!\n${JSON.stringify(r||n,null,2)}`)}))}async function z(e,t,r,n){const i="----"+I()+I(),o=function(e,t){let r,n,i="",o="\r\n",s="--"+e;for(r in t)n=t[r],i+=s+o,i+=`Content-Disposition: form-data; name="${r}"`,n.filename&&(i+=`; filename="${n.filename}"`),n.type&&(i+=`\r\nContent-Type: ${n.type}`),i+=o+o+n.value+o;return i+s+"--"}(i,{script:{type:"application/javascript",value:r},metadata:{type:"application/json",value:n?JSON.stringify(n):'{"body_part": "script","bindings":[]}'}});return f("PUT",`/accounts/${e.accountid}/workers/scripts/${t}`,{headers:u(e,{"Content-Type":`multipart/form-data; boundary=${i}`}),body:o}).catch((e=>{$(`Error uploading "${t}" script!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}const V={env:"plain_text",wasm:"wasm_module",secret:"secret_text",kv:"kv_namespace"};function q(e,t){let r=t.indexOf(":"),n=t.substring(0,r),i=t.substring(r+1),o=V[n.toLowerCase()];return o||$(`Unknown binding hint: "${n}"`),"wasm_module"===o?{type:o,name:e,part:"wasm"}:"kv_namespace"===o?{type:o,name:e,namespace_id:i}:{type:o,name:e,text:i}}function B(e){let t,r=[];for(t in e)r.push(q(t,e[t]));if(r.length)return{body_part:"script",bindings:r}}const H={bundle:!0,format:"esm",charset:"utf8",sourcemap:!1,outfile:"<injected>",entryPoints:["<injected>"],logLevel:"silent",resolveExtensions:[".tsx",".ts",".jsx",".mjs",".js",".json"],mainFields:["worker","browser","module","jsnext","main"],conditions:["worker","browser","import","production"]};e("cfw").version("0.1.1").option("-C, --cwd","The relative working directory",".").option("-P, --profile","The CFW account profile to load").command("build [dir] [output]").describe("Compile the Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to build; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r,n){n.dir=e||n.dir;let i=await P(n.dir,n);if(!i.length)return v("Nothing to build!",n);let o=r||"build";r=a(n.cwd,o),e=a(n.cwd,n.dir),j(r)&&(k(`Removing existing "${o}" directory`),await A(r,{recursive:!0}));const s=await import("esbuild");let l=t.cyan(m),u=t.bold(i.length),f=1===i.length?"":"s";h(`Building ${u} worker${f}:`);for(let e of i){let i=d(H),{name:o,input:a,cfw:u}=e;if(i.entryPoints=[a],"function"==typeof u.build){u.build(i);let e=[];if(i.splitting&&e.push("splitting"),(i.external||[]).length&&e.push("external"),"esm"!==i.format&&e.push("format"),i.sourcemap&&e.push("sourcemap"),e.length){let r="\n "+t.dim().red("- "),n="Invalid configuration customization!\nPlease revert or remove the following keys:";return e.forEach((e=>n+=r+e)),$(n)}}let f=c(r,n.single?"":o);i.outfile=c(f,"index.js");try{var p=Date.now(),g=await s.build(i)}catch(e){let{errors:t}=e;return await D(t,!0)}delete u.entry,await L(c(f,"cfw.json"),JSON.stringify({name:o,...u},null,2)),console.log(l+o+T(Date.now()-p)),await D(g.warnings)}y(`Build complete!\nYour worker${f} ${1===i.length?"is":"are"} ready for deployment 🎉`)})).command("deploy [output]").describe("Deploy the built Worker(s) – requires you `build` first.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to build; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r){let n=e||"build",i=await P(n,r);if(!i.length)return v("Nothing to deploy!",r);let o=t.cyan(m),s=t.bold(i.length),a=1===i.length?"":"s";h(`Deploying ${s} worker${a}:`);for(let e of i){let{name:t,input:n,cfw:i}=e;i.profile=i.profile||r.profile,N(n,`Worker input does not exist: "${n}"`,!0);let s=await M(i),a=i.globals&&B(i.globals),l=await _(n),c=Date.now();await z(s,t,l,a),console.log(o+t+T(Date.now()-c)),i.routes&&await Promise.all(i.routes.map((e=>{let r=Date.now(),n=e.startsWith("!"),i=e.substring(+n);return J(s,i,n?null:t).then((()=>{E(i,Date.now()-r,!n)}))})))}y(`Deployment complete!\nAll items within "${n}" uploaded 🎉`)})).command("secrets list").alias("secrets ls").describe("List the names of secrets attached to Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to query; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e){let r=await P(e.dir,e);if(!r.length)return v("No workers found!",e);let n=t.bold(r.length),i=1===r.length?"":"s";h(`Fetching secrets for ${n} worker${i}:`);let o=t.cyan(m);for(let n of r){let{name:r,cfw:i}=n;i.profile=i.profile||e.profile;let s=await M(i),a=await W(s,r);if(console.log(o+`"${r}" secrets:`),a.result.length)for(let e of a.result)E(e.name);else console.log(p+t.italic().dim(" None"))}y(`Retrieved worker${i?"s'":"'s"} secrets`)})).command("secrets create <name> <value>").alias("secrets new","secrets add","secrets put").describe("Create a new secret for the Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to query; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r,n){let i=await P(n.dir,n);if(!i.length)return v("No workers found!",n);let o=t.cyan(m),s=t.bold(i.length),a=1===i.length?"":"s",l=[];h(`Adding secret "${e}" value to ${s} worker${a}:`);for(let t of i){let{name:i,cfw:s}=t;s.profile=s.profile||n.profile;let a=await M(s);l.push((()=>{let t=Date.now();return C(a,i,e,r).then((e=>{e.success&&console.log(o+i+T(Date.now()-t))}))}))}await Promise.all(l.map((e=>e()))),y(`Added secret to worker${a}`)})).command("secrets destroy <name>").alias("secrets delete","secrets rm").describe("Remove a secret from the Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to query; overrides `--ignore` list!").option("-q, --quiet","Do not throw error if Worker is missing secret").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r){let n=await P(r.dir,r);if(!n.length)return v("No workers found!",r);let i=t.bold(n.length),o=1===n.length?"":"s",s=[];h(`Removing "${e}" secret from ${i} worker${o}:`);for(let i of n){let{name:n,cfw:o}=i;o.profile=o.profile||r.profile;let a=await M(o);s.push((()=>{let i=Date.now();return O(a,n,e,!!r.quiet).then((e=>{let r=(e.success?t.cyan:t.red)(m);console.log(r+n+T(Date.now()-i))}))}))}await Promise.all(s.map((e=>e()))),y(`Removed secret from worker${o}`)})).command("kv namespaces list").describe("List all KV namespaces").alias("kv ns list","kv ns ls").action((async function(e){const r=await M(e,!0);h("Retrieving KV namespaces:");const n=await function(e){return f("GET",`/accounts/${e.accountid}/storage/kv/namespaces?per_page=100&order=title`,{headers:u(e)})}(r),i=" ",o=t.dim().bold().italic;y(o("ID")+" ".repeat(30)+i+o("Title"));let s=0,a=n.result,l="";for(;s<a.length;s++)l&&(l+="\n"),l+=(a[s].supports_url_encoding?t.cyan:t.red)(m),l+=a[s].id+i+a[s].title;console.log(l)})).command("kv namespaces create <title>").describe("Create a new KV namespace").alias("kv ns create","kv ns new").action((async function(e,r){const n=await M(r,!0);h("Creating new KV namespace:");const i=await function(e,t){return f("POST",`/accounts/${e.accountid}/storage/kv/namespaces`,{headers:u(e),body:{title:t}}).catch((e=>{$(`Error creating "${t}" namespace!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}(n,e);if(!i)return $("Error creating namespace");console.log(t.cyan(m)+`"${i.result.title}" `+t.italic().dim(`(ID: ${i.result.id})`)),y("KV namespace created!")})).command("kv namespaces destroy <id>").describe("Destroy a KV namespace").alias("kv ns delete","kv ns rm").action((async function(e,t){const r=await M(t,!0);k("Deleting KV namespace");const n=await function(e,t){return f("DELETE",`/accounts/${e.accountid}/storage/kv/namespaces/${t}`,{headers:u(e)}).catch((e=>{$(`Error removing "${t}" namespace!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}(r,e);if(!n||!n.success)return $("Error deleting namespace");y("KV namespace deleted!")})).parse(process.argv);
import e from"sade";import t from"kleur";import{send as r}from"httpie";import*as n from"fs";import{homedir as i}from"os";import{promisify as o}from"util";import{createRequire as s}from"module";import{resolve as a,parse as l,join as c}from"path";import{klona as d}from"klona/json";function u(e,t={}){return e.token?t.Authorization=`Bearer ${e.token}`:(t["X-Auth-Key"]=e.authkey,t["X-Auth-Email"]=e.email),t}function f(e,t,n={}){return r(e,"https://api.cloudflare.com/client/v4"+t,n).then((e=>e.data))}const m=" ~> ",p=" ".repeat(6),g=t.bold("[CFW]");function w(e,r){console.log(t[e](g),r.includes("\n")?r.replace(/(\r?\n)/g,"$1"+p):r)}const h=e=>w("white",e),y=e=>w("green",e),k=e=>w("yellow",e);function $(e,t=1){w("red",e),process.exit(t)}const b=t.dim().bold;function v(e,t){return(t.only||t.ignore)&&(e+=`\nPerhaps the ${b("--only")} or ${b("--ignore")} flag needs adjusting`),k(e)}function T(e){return t.italic().dim(` (${e}ms)`)}function E(e,r,n){let i="•",o=t.dim,s=null!=r?T(r):"";n?(i="+",o=t.green().dim):null!=n&&(i="-",o=t.red().dim),console.log(o(p+i+` "${e}"`)+s)}async function D(e,r){let n=0,i=e.length;if(i===n)return;const o=await import("esbuild");let s=await o.formatMessages(e,{terminalWidth:process.stdout.columns,kind:r?"error":"warning",color:t.enabled}),a=/\x1b\[32m/g,l=r?"":"",c=r?t.red:t.yellow,d=`Build ${r?"failed":"finished"} with`;for(d+=" "+t.underline(i)+" ",d+=r?"error":"warning",d+=1===i?":":"s:",d+="\n\n";n<i;n++)d+=t.bold().inverse(c(" "+e[n].location.file+" "))+" "+e[n].text,d+=s[n].substring(s[n].indexOf("\n")).replace(a,l);n=d.length,"\n"===d[--n]&&(d=d.substring(0,n)),(r?$:k)(d)}function W(e,t){return f("GET",`/accounts/${e.accountid}/workers/scripts/${t}/secrets`,{headers:u(e)}).catch((e=>{$(`Error fetching "${t}" secrets!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}function C(e,t,r,n){return f("PUT",`/accounts/${e.accountid}/workers/scripts/${t}/secrets`,{headers:u(e),body:{type:"secret_text",text:n,name:r}}).catch((e=>{$(`Error creating new "${t}" secret!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}function O(e,t,r,n){return f("DELETE",`/accounts/${e.accountid}/workers/scripts/${t}/secrets/${r}`,{headers:u(e)}).catch((e=>{let{data:i,message:o}=e;if(n&&i&&i.errors&&10056===i.errors[0].code)return i;$(`Error deleting "${t}/${r}" secret!\n${JSON.stringify(i||o,null,2)}`)}))}const L=o(n.writeFile),_=o(n.readFile),A=o(n.rmdir),x=o(n.readdir),j=n.existsSync;function N(e,t,r){return(r?j(e):!!e)||$(t)}function U(e){return new Set(Array.isArray(e)?e:e.split(","))}const F=s(import.meta.url);async function R(e,t="."){if(!j(e=a(t,e)))return!1;try{var r=F(e)}catch{r=await import(e).catch((()=>!1))}finally{return r||$(`Error loading "${e}" file`)}}async function S(e){let t;return(t=await R("cfw.js",e))||(t=await R("cfw.mjs",e))||(t=await R("cfw.cjs",e))||(t=await R("cfw.json",e))?t:(t=await R("package.json",e))?t.cfw:void 0}async function K(e,t,r){let n=r?e:c(e,t),i=await S(n)||{};return{cfw:i,name:i.name||t,input:c(n,i.entry||"index.js"),abs:n}}async function P(e,t){t.cwd=a(t.cwd);let r,n,i=a(t.cwd,e);N(i,`Workers directory does not exist: "${i}"`,!0);let{cwd:o,single:s,only:c,ignore:d}=t;if(s){let e=t.dir;"."===e&&(e=l(o).base);let r=await K(i,e,!0);return(n=await S(o))&&(Object.assign(r.cfw,n),n.name&&(r.name=n.name),t.profile&&(r.cfw.profile=t.profile)),[r]}let u=await x(i,{withFileTypes:!0}).then((e=>Promise.all(e.filter((e=>e.isDirectory())).map((e=>K(i,e.name))))));return c?(r=U(c),u.filter((e=>r.has(e.name)))):d?(r=U(d),u.filter((e=>!r.has(e.name)))):u}async function M(e,t){let{CLOUDFLARE_ZONEID:r,CLOUDFLARE_ACCOUNTID:n,CLOUDFLARE_AUTH_EMAIL:o,CLOUDFLARE_AUTH_KEY:s,CLOUDFLARE_TOKEN:a}=process.env,l=o||e.email,d=s||e.authkey,u=n||e.accountid,f=r||e.zoneid,m=a||e.token;if((m||d&&l)&&u&&f)return{authkey:d,accountid:u,email:l,token:m,zoneid:f};if(e.profile){let t=await async function(e="default"){let t=c(i(),".cfw","config");N(t,`Missing "${t}" config file`,!0);let r,n,o={},s=0,a=/^\[(.*)\]$/,l=(await _(t,"utf8")).split(/(\r?\n)+/g);for(;s<l.length;s++)if(l[s].startsWith("#")||!l[s].trim().length);else if(a.test(l[s]))n=a.exec(l[s])[1],r=o[n]={};else{let[e,t]=l[s].split("=");r[e.trim()]=t.trim()}let d=o[e];return N(d,`The "${e}" profile is not defined`),d}(e.profile);Object.keys(t).forEach((e=>{!l&&/CLOUDFLARE_AUTH_EMAIL/i.test(e)&&(l=t[e]),!u&&/CLOUDFLARE_ACCOUNTID/i.test(e)&&(u=t[e]),!d&&/CLOUDFLARE_AUTH_KEY/i.test(e)&&(d=t[e]),!f&&/CLOUDFLARE_ZONEID/i.test(e)&&(f=t[e]),!m&&/CLOUDFLARE_TOKEN/i.test(e)&&(m=t[e])}))}return N(f||t,'Missing Cloudflare "zoneid" value!'),N(u,'Missing Cloudflare "accountid" value!'),m||d&&l||(d||l?(N(l,'Missing Cloudflare "email" value!'),N(d,'Missing Cloudflare "authkey" value!')):$('Missing Cloudflare "token" value or "email" + "authkey" combo!')),{authkey:d,accountid:u,email:l,token:m,zoneid:f}}const I=()=>Math.random().toString(36).slice(2);function J(e,t,r){return f("POST",`/zones/${e.zoneid}/workers/routes`,{headers:u(e,{"Content-Type":"application/javascript"}),body:{pattern:t,script:r}}).catch((e=>{let{data:r,message:n}=e;r&&r.errors&&10020===r.errors[0].code||$(`Error setting "${t}" route pattern!\n${JSON.stringify(r||n,null,2)}`)}))}async function z(e,t,r,n){const i="----"+I()+I(),o=function(e,t){let r,n,i="",o="\r\n",s="--"+e;for(r in t)n=t[r],i+=s+o,i+=`Content-Disposition: form-data; name="${r}"`,n.filename&&(i+=`; filename="${n.filename}"`),n.type&&(i+=`\r\nContent-Type: ${n.type}`),i+=o+o+n.value+o;return i+s+"--"}(i,{script:{type:"application/javascript",value:r},metadata:{type:"application/json",value:n?JSON.stringify(n):'{"body_part": "script","bindings":[]}'}});return f("PUT",`/accounts/${e.accountid}/workers/scripts/${t}`,{headers:u(e,{"Content-Type":`multipart/form-data; boundary=${i}`}),body:o}).catch((e=>{$(`Error uploading "${t}" script!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}const V={env:"plain_text",wasm:"wasm_module",secret:"secret_text",kv:"kv_namespace"};function q(e,t){let r=t.indexOf(":"),n=t.substring(0,r),i=t.substring(r+1),o=V[n.toLowerCase()];return o||$(`Unknown binding hint: "${n}"`),"wasm_module"===o?{type:o,name:e,part:"wasm"}:"kv_namespace"===o?{type:o,name:e,namespace_id:i}:{type:o,name:e,text:i}}function B(e){let t,r=[];for(t in e)r.push(q(t,e[t]));if(r.length)return{body_part:"script",bindings:r}}const H={bundle:!0,format:"esm",charset:"utf8",sourcemap:!1,outfile:"<injected>",entryPoints:["<injected>"],logLevel:"silent",resolveExtensions:[".tsx",".ts",".jsx",".mjs",".js",".json"],mainFields:["worker","browser","module","jsnext","main"],conditions:["worker","browser","import","production"]};e("cfw").version("0.1.2").option("-C, --cwd","The relative working directory",".").option("-P, --profile","The CFW account profile to load").command("build [dir] [output]").describe("Compile the Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to build; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r,n){n.dir=e||n.dir;let i=await P(n.dir,n);if(!i.length)return v("Nothing to build!",n);let o=r||"build";r=a(n.cwd,o),e=a(n.cwd,n.dir),j(r)&&(k(`Removing existing "${o}" directory`),await A(r,{recursive:!0}));const s=await import("esbuild");let l=t.cyan(m),u=t.bold(i.length),f=1===i.length?"":"s";h(`Building ${u} worker${f}:`);for(let e of i){let i=d(H),{name:o,input:a,cfw:u}=e;if(i.entryPoints=[a],"function"==typeof u.build){u.build(i);let e=[];if(i.splitting&&e.push("splitting"),(i.external||[]).length&&e.push("external"),"esm"!==i.format&&e.push("format"),i.sourcemap&&e.push("sourcemap"),e.length){let r="\n "+t.dim().red("- "),n="Invalid configuration customization!\nPlease revert or remove the following keys:";return e.forEach((e=>n+=r+e)),$(n)}}let f=c(r,n.single?"":o);i.outfile=c(f,"index.js");try{var p=Date.now(),g=await s.build(i)}catch(e){let{errors:t}=e;return await D(t,!0)}delete u.entry,await L(c(f,"cfw.json"),JSON.stringify({name:o,...u},null,2)),console.log(l+o+T(Date.now()-p)),await D(g.warnings)}y(`Build complete!\nYour worker${f} ${1===i.length?"is":"are"} ready for deployment 🎉`)})).command("deploy [output]").describe("Deploy the built Worker(s) – requires you `build` first.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to build; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r){let n=e||"build",i=await P(n,r);if(!i.length)return v("Nothing to deploy!",r);let o=t.cyan(m),s=t.bold(i.length),a=1===i.length?"":"s";h(`Deploying ${s} worker${a}:`);for(let e of i){let{name:t,input:n,cfw:i}=e;i.profile=i.profile||r.profile,N(n,`Worker input does not exist: "${n}"`,!0);let s=await M(i),a=i.globals&&B(i.globals),l=await _(n),c=Date.now();await z(s,t,l,a),console.log(o+t+T(Date.now()-c)),i.routes&&await Promise.all(i.routes.map((e=>{let r=Date.now(),n=e.startsWith("!"),i=e.substring(+n);return J(s,i,n?null:t).then((()=>{E(i,Date.now()-r,!n)}))})))}y(`Deployment complete!\nAll items within "${n}" uploaded 🎉`)})).command("secrets list").alias("secrets ls").describe("List the names of secrets attached to Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to query; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e){let r=await P(e.dir,e);if(!r.length)return v("No workers found!",e);let n=t.bold(r.length),i=1===r.length?"":"s";h(`Fetching secrets for ${n} worker${i}:`);let o=t.cyan(m);for(let n of r){let{name:r,cfw:i}=n;i.profile=i.profile||e.profile;let s=await M(i),a=await W(s,r);if(console.log(o+`"${r}" secrets:`),a.result.length)for(let e of a.result)E(e.name);else console.log(p+t.italic().dim(" None"))}y(`Retrieved worker${i?"s'":"'s"} secrets`)})).command("secrets create <name> <value>").alias("secrets new","secrets add","secrets put").describe("Create a new secret for the Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to query; overrides `--ignore` list!").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r,n){let i=await P(n.dir,n);if(!i.length)return v("No workers found!",n);let o=t.cyan(m),s=t.bold(i.length),a=1===i.length?"":"s",l=[];h(`Adding secret "${e}" value to ${s} worker${a}:`);for(let t of i){let{name:i,cfw:s}=t;s.profile=s.profile||n.profile;let a=await M(s);l.push((()=>{let t=Date.now();return C(a,i,e,r).then((e=>{e.success&&console.log(o+i+T(Date.now()-t))}))}))}await Promise.all(l.map((e=>e()))),y(`Added secret to worker${a}`)})).command("secrets destroy <name>").alias("secrets delete","secrets rm").describe("Remove a secret from the Worker(s) within a directory.").option("-d, --dir","The directory containing Worker scripts","workers").option("-o, --only","The list of Worker names to query; overrides `--ignore` list!").option("-q, --quiet","Do not throw error if Worker is missing secret").option("-i, --ignore","The list of Worker names to skip").option("-s, --single","The target is a single Worker").action((async function(e,r){let n=await P(r.dir,r);if(!n.length)return v("No workers found!",r);let i=t.bold(n.length),o=1===n.length?"":"s",s=[];h(`Removing "${e}" secret from ${i} worker${o}:`);for(let i of n){let{name:n,cfw:o}=i;o.profile=o.profile||r.profile;let a=await M(o);s.push((()=>{let i=Date.now();return O(a,n,e,!!r.quiet).then((e=>{let r=(e.success?t.cyan:t.red)(m);console.log(r+n+T(Date.now()-i))}))}))}await Promise.all(s.map((e=>e()))),y(`Removed secret from worker${o}`)})).command("kv namespaces list").describe("List all KV namespaces").alias("kv ns list","kv ns ls").action((async function(e){const r=await M(e,!0);h("Retrieving KV namespaces:");const n=await function(e){return f("GET",`/accounts/${e.accountid}/storage/kv/namespaces?per_page=100&order=title`,{headers:u(e)})}(r),i=" ",o=t.dim().bold().italic;y(o("ID")+" ".repeat(30)+i+o("Title"));let s=0,a=n.result,l="";for(;s<a.length;s++)l&&(l+="\n"),l+=(a[s].supports_url_encoding?t.cyan:t.red)(m),l+=a[s].id+i+a[s].title;console.log(l)})).command("kv namespaces create <title>").describe("Create a new KV namespace").alias("kv ns create","kv ns new").action((async function(e,r){const n=await M(r,!0);h("Creating new KV namespace:");const i=await function(e,t){return f("POST",`/accounts/${e.accountid}/storage/kv/namespaces`,{headers:u(e),body:{title:t}}).catch((e=>{$(`Error creating "${t}" namespace!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}(n,e);if(!i)return $("Error creating namespace");console.log(t.cyan(m)+`"${i.result.title}" `+t.italic().dim(`(ID: ${i.result.id})`)),y("KV namespace created!")})).command("kv namespaces destroy <id>").describe("Destroy a KV namespace").alias("kv ns delete","kv ns rm").action((async function(e,t){const r=await M(t,!0);k("Deleting KV namespace");const n=await function(e,t){return f("DELETE",`/accounts/${e.accountid}/storage/kv/namespaces/${t}`,{headers:u(e)}).catch((e=>{$(`Error removing "${t}" namespace!\n${JSON.stringify(e.data||e.message,null,2)}`)}))}(r,e);if(!n||!n.success)return $("Error deleting namespace");y("KV namespace deleted!")})).parse(process.argv);
{
"name": "cfw",
"version": "0.1.2",
"version": "0.1.3",
"repository": "lukeed/cfw",

@@ -5,0 +5,0 @@ "description": "WIP",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc