@shipstatic/ship 3.6.1 → 3.7.0-beta.0
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.
- package/README.md +12 -2
- package/THIRD-PARTY-LICENSES.md +1 -1
- package/dist/browser.d.ts +91 -33
- package/dist/browser.js +2 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +57 -56
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +91 -33
- package/dist/index.d.ts +91 -33
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"use strict";var wt=Object.create;var B=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xe=(e,t)=>{for(var n in t)B(e,n,{get:t[n],enumerable:!0})},qe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ct(t))!Mt.call(e,o)&&o!==n&&B(e,o,{get:()=>t[o],enumerable:!(r=vt(t,o))||r.enumerable});return e};var O=(e,t,n)=>(n=e!=null?wt(Ft(e)):{},qe(t||!e||!e.__esModule?B(n,"default",{value:e,enumerable:!0}):n,e)),Ut=e=>qe(B({},"__esModule",{value:!0}),e);function Bt(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(Je).includes(t)?t:void 0}function ue(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>N.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${N.MAX_LENGTH} characters.`);return t}function Qe(e){return e.members+e.invitations}function Vt(e,t){let n=Math.max(0,Qe(e)-t.members),r=Math.max(0,e.members-t.members),o={members:r,invitations:n-r,customDomains:e.customDomains-t.customDomains,platformDomains:e.platformDomains-t.platformDomains};return Object.fromEntries(Object.entries(o).filter(([,i])=>i>0))}function Ze(e){return tt(["members","customDomains","platformDomains"].filter(t=>(e[t]??0)>0).map(t=>et(t,e[t]??0)))}function Kt(e){let t=Ze(e),n=e.invitations??0;return tt([...t?[`remove ${t}`]:[],...n>0?[`cancel ${et("invitations",n)}`]:[]])}function Xt(e){return e.name?.trim()||e.email}function qt(e){return e.name?.trim().split(" ")[0]||e.email}function Zt(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function M(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function en(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function me(e,t){let n=en(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function de(e){return nt.test(e)}function U(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>V.has(n))}function rt(e){return e.startsWith(fe.PREFIX)?A.API_KEY:e.startsWith(he.PREFIX)?A.DEPLOY_TOKEN:e.startsWith(ye.PREFIX)?A.OAUTH:A.OPAQUE}function sn(e){return e.slice(0,ae.length).toLowerCase()!==ae?null:e.slice(ae.length)||null}function ge(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw s.config(`invalid JSON format in config: ${r.message}`,{filePath:S})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${S} must contain a JSON object`,{filePath:S})}function Te(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function ot(e){Te(e,fe,"API key")}function it(e){Te(e,he,"Deploy token")}function st(e){Te(e,ye,"OAuth access token")}function K(e){switch(rt(e)){case A.API_KEY:ot(e);return;case A.DEPLOY_TOKEN:it(e);return;case A.OAUTH:st(e);return;case A.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function De(e){if(!e||e.length>x.MAX_LENGTH||!x.PATTERN.test(e))throw s.validation(`Caller must be 1-${x.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function ln(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw M(t)?t:s.validation("API URL must be a valid URL")}}function cn(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function j(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<C.MIN_SECONDS||e>C.MAX_SECONDS)throw s.validation(`TTL must be between ${C.MIN_SECONDS} and ${C.MAX_SECONDS} seconds`);return e}}function ct(e){let t=e?`/${e}`:"",n=r=>`${t}${r}`;return{dashboard:()=>t||"/",newSite:()=>n("/new"),deployments:Object.assign(()=>n("/deployments"),{upload:()=>n("/deployments/upload")}),domains:Object.assign(()=>n("/domains"),{connect:r=>n(`/domains/${r}/connect`),deployment:r=>n(`/domains/${r}/deployment`)}),settings:r=>n(r?`/settings#${r}`:"/settings"),claim:r=>n(`/claim/${r}`),settingsAfterBilling:()=>n(`/settings?${Ye("portal")}`),upgrade:r=>n(r?`/upgrade/${r}`:"/upgrade"),success:()=>n("/success"),successAfterCheckout:()=>n(`/success?${Ye("checkout")}`),apiKey:()=>n("/api-key")}}function dn(e){let t=new URLSearchParams(e);for(let[n,[r,o]]of Object.entries(lt))if(t.get(r)===o)return n;return null}function X(e){let t=e.split(/[?#]/)[0].toLowerCase(),[n="",r=""]=t.split("/").filter(Boolean);return fn(n)?{kind:"door",door:n}:n===un?{kind:"admin"}:n===""||We(n)?{kind:"account",account:null,section:n===""?null:n}:{kind:"account",account:n,section:We(r)?r:null}}function hn(e){let t=X(e);return t.kind==="account"?t.account:null}function pt(e){let t=X(e);return t.kind==="door"?t.door:null}function yn(e){return ut(e)?"claim":pt(e)==="invitation"?"invite":mt(e)?"upgrade":null}function dt(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return ce(t,"minute");let n=Math.round(e/3600);return n<48?ce(n,"hour"):ce(Math.round(e/86400),"day")}function Dn(e,t=Date.now()/1e3){let n=e-t;return n>0?dt(n):null}function ce(e,t){return`${e} ${t}${e===1?"":"s"}`}function w(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(n));return`${Number.parseFloat((e/n**o).toFixed(t))} ${r[o]}`}function Se(e,t){return e.endsWith(`.${t}`)}function An(e,t){return!Se(e,t)}function Rn(e,t){return Se(e,t)?e.slice(0,-(t.length+1)):null}function In(e){return`https://${e}`}function Nn(e){return`https://${e}`}function ht(e){if(typeof e!="string")throw s.validation("Labels must be strings");let t=e.trim().toLowerCase();if(t.length<I.MIN_LENGTH)throw s.validation(`Labels must be at least ${I.MIN_LENGTH} characters long`);if(t.length>I.MAX_LENGTH)throw s.validation(`Labels must be no more than ${I.MAX_LENGTH} characters long`);if(!ft.test(t))throw s.validation("Labels use letters and numbers, with . _ or - between them, and can have one : between a key and a value, like env:production");return t}function b(e){if(e==null)return;if(!Array.isArray(e))throw s.validation("Labels must be an array");if(e.length>I.MAX_COUNT)throw s.validation(`Maximum ${I.MAX_COUNT} labels allowed`);let t=e.map(ht);if(new Set(t).size!==t.length)throw s.validation("Duplicate labels are not allowed");return t}function bn(e){return!e||e.length===0?null:JSON.stringify(e)}function Ln(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Ae(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>P.COMMAND_MAX_LENGTH)throw s.validation(`Build command must be between 1 and ${P.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw s.validation("Build command must be a single line");return t}function Re(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>P.OUTPUT_DIR_MAX_LENGTH)throw s.validation(`Output folder must be between 1 and ${P.OUTPUT_DIR_MAX_LENGTH} characters`);if(!P.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw s.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function Y(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<F.MIN_LENGTH||t.length>F.MAX_LENGTH)throw s.validation(`Password must be between ${F.MIN_LENGTH} and ${F.MAX_LENGTH} characters`);return t}var kt,Je,$t,Ht,Gt,N,zt,pe,et,tt,jt,d,E,Yt,u,Wt,se,Jt,Qt,s,tn,nn,nt,V,rn,z,fe,he,ye,x,on,A,ae,an,S,Ee,k,C,at,pn,un,lt,Ye,le,mn,fn,We,ut,mt,q,_,En,gn,Tn,Sn,h,I,ft,P,F,f=D(()=>{"use strict";kt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Je={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},$t={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},Ht={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},Gt="troubleshooting",N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};zt={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"};pe={deployments:{one:"deployment",many:"deployments"},platformDomains:{one:"ShipStatic domain",many:"ShipStatic domains"},customDomains:{one:"custom domain",many:"custom domains"},members:{one:"member",many:"members"},invitations:{one:"invitation",many:"invitations"}};et=(e,t)=>`${t} ${t===1?pe[e].one:pe[e].many}`,tt=e=>e.length>1?`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`:e[0]??"",jt={PAUSED:"paused",UNKNOWN:"unknown"};d={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},E={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},Yt={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},u={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Wt=new Set([u.Network,u.Timeout,u.Cancelled,u.File,u.Config]),se={client:new Set([u.Build,u.Business,u.Cancelled,u.Config,u.File,u.Forbidden,u.NotFound,u.RateLimit,u.Validation]),network:new Set([u.Network,u.Timeout]),auth:new Set([u.Authentication])},Jt=new Set(Object.values(u).filter(e=>!Wt.has(e))),Qt=200;s=class e extends Error{type;status;details;constructor(t,n,r,o){super(n),this.type=t,this.status=r,this.details=o,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===u.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,o,i;try{if(t.headers.get("content-type")?.includes("application/json")){let m=await t.json();if(m&&typeof m=="object"){let c=m;typeof c.message=="string"?r=c.message:typeof c.error=="string"&&(r=c.error),o=c.details,typeof c.error=="string"&&Jt.has(c.error)&&(i=c.error)}}else{let m=(await t.text()).trim();m&&!m.startsWith("<")&&m.length<=Qt&&(r=m)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),m=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(m)&&m>=0){let c=o&&typeof o=="object"?o:{};c.retryAfter===void 0&&(o={...c,retryAfter:m})}}r=r||`${n||"Request"} failed with status ${t.status}`;let p=i??(t.status===401?u.Authentication:t.status===403?u.Forbidden:t.status===429?u.RateLimit:u.Api);return new e(p,r,t.status,o)}static fromFetchError(t,n){if(M(t))return t;let r=n||"Request",o=t?.name;return o==="AbortError"?e.cancelled(`${r} was cancelled`):o==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?Zt(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(u.Api,`${r} failed: ${t.message}`):new e(u.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(u.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(u.NotFound,r,404)}static forbidden(t,n){return new e(u.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(u.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(u.Authentication,t,401,n)}static business(t,n=400,r){return new e(u.Business,t,n,r)}static network(t,n){return new e(u.Network,t,void 0,n)}static timeout(t,n){return new e(u.Timeout,t,void 0,n)}static cancelled(t,n){return new e(u.Cancelled,t,void 0,n)}static file(t,n){return new e(u.File,t,void 0,n)}static config(t,n){return new e(u.Config,t,void 0,n)}static api(t,n=500,r){return new e(u.Api,t,n,r)}static maintenance(t,n){return new e(u.Maintenance,t,503,n)}static build(t,n){return new e(u.Build,t,422,n)}isClientError(){return se.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return se.network.has(this.type)}isAuthError(){return se.auth.has(this.type)}isType(t){return this.type===t}};tn=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],nn=tn.map(e=>`.${e}`).join(","),nt=/[\x00-\x1f\x7f#?%\\<>"]/;V=new Set(["node_modules","package.json"]);rn="/auth",z={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},fe={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},he={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},ye={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},x={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},on="X-Account",A={API_KEY:z.API_KEY,DEPLOY_TOKEN:z.TOKEN,OAUTH:z.OAUTH,OPAQUE:"opaque"};ae="bearer ";an={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},S="ship.json",Ee={rewrites:[{source:"/(.*)",destination:"/index.html"}]},k={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};C={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};at={new:{owner:!1},deployments:{owner:!1},domains:{owner:!1},settings:{owner:!1},claim:{owner:!1},upgrade:{owner:!0},success:{owner:!0},"api-key":{owner:!0}},pn=["login","register","logout","invitation","consent"],un="admin",lt={checkout:["upgrading","true"],portal:["billing","returned"]},Ye=e=>lt[e].join("="),le=(e,t)=>t?`${e}?next=${encodeURIComponent(t)}`:e;mn={login:({token:e,next:t}={})=>le(e?`/login/${e}`:"/login",t),register:({next:e}={})=>le("/register",e),logout:({next:e}={})=>le("/logout",e),invitation:e=>`/invitation/${e}`,consent:()=>"/consent"};fn=e=>pn.includes(e),We=e=>Object.hasOwn(at,e);ut=e=>{let t=X(e);return t.kind==="account"&&t.section==="claim"},mt=e=>{let t=X(e);return t.kind==="account"&&t.section==="upgrade"};q="https://api.shipstatic.com",_={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},En="SHIP_VIA",gn=`https://my.shipstatic.com${ct().apiKey()}`,Tn=4320*60;Sn=["account.create","account.update","account.delete","account.key.generate","account.plan.transition","deployment.create","deployment.update","deployment.delete","deployment.claim","domain.create","domain.update","domain.delete","domain.verify","token.create","token.consume","token.delete","member.join","member.leave","consent.grant"],h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};I={MIN_LENGTH:3,MAX_LENGTH:63,MAX_COUNT:10},ft=/^[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[a-z0-9]+(?:[._-][a-z0-9]+)*)?$/;P={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};F={MIN_LENGTH:6,MAX_LENGTH:128}});async function Mn(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let o=0;o<e.size;o+=r){let i=Math.min(o+r,e.size);n.append(await e.slice(o,i).arrayBuffer())}return{md5:n.end()}}async function Un(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function kn(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,o)=>{let i=t("md5"),l=n(e);l.on("error",p=>o(s.file(`Failed to read file for MD5: ${p.message}`,{filePath:e}))),l.on("data",p=>i.update(p)),l.on("end",()=>r({md5:i.digest("hex")}))})}async function H(e){if(e instanceof Blob)return Mn(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return Un(e);if(typeof e=="string")return kn(e);throw s.business("Invalid input for MD5 calculation")}var J=D(()=>{"use strict";f()});function Bn(e){xe=e}function zn(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return xe||zn()}var xe,G=D(()=>{"use strict";xe=null});function At(e){if(!e||e.length===0)return"";let t=e.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(i=>i.split("/").filter(Boolean)),r=[],o=Math.min(...n.map(i=>i.length));for(let i=0;i<o;i++){let l=n[0][i];if(n.every(p=>p[i]===l))r.push(l);else break}return r.join("/")}function ee(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var we=D(()=>{"use strict"});function Ce(e,t={}){if(t.flatten===!1)return e.map(r=>({path:ee(r),name:ve(r)}));let n=jn(e);return e.map(r=>{let o=ee(r);if(n){let i=n.endsWith("/")?n:`${n}/`;o.startsWith(i)&&(o=o.substring(i.length))}return o||(o=ve(r)),{path:o,name:ve(r)}})}function jn(e){if(!e.length)return"";let n=e.map(i=>ee(i)).map(i=>i.split("/")),r=[],o=Math.min(...n.map(i=>i.length));for(let i=0;i<o-1;i++){let l=n[0][i];if(n.every(p=>p[i]===l))r.push(l);else break}return r.join("/")}function ve(e){return e.split(/[/\\]/).pop()||e}var Fe=D(()=>{"use strict";we()});function Me(e,t,n){let r=t.suggestions?.[n];return r?`${e} ${r}`:e}function ne(e,t){return Xn.find(n=>n.broken(e,t))}var Xn,v,Ue=D(()=>{"use strict";f();ke();Xn=[{name:"name",broken:({path:e})=>!te(e).valid,sentence:({path:e})=>te(e).reason??`File name "${e}" is invalid.`},{name:"extension",broken:({path:e},t)=>me(e,t.blockedExtensions??[]),sentence:({path:e})=>`File "${e}" has an extension that is not allowed.`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>Me(`File "${e}" is too large. Maximum ${w(t.maxFileSize)} allowed.`,t,"maxFileSize")},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>Me(`Files add up to ${w(e)}. Maximum ${w(t.maxTotalSize)} allowed.`,t,"maxTotalSize")}],v={name:"filesCount",broken:(e,t)=>e>t.maxFilesCount,sentence:(e,t)=>Me(`Too many files (${e}). Maximum ${t.maxFilesCount} files allowed.`,t,"maxFilesCount")}});function te(e){let t=o=>({valid:!1,reason:`File name "${e}" ${o}.`});if(de(e))return t("contains unsafe characters");if(e.startsWith(" ")||e.endsWith(" "))return t("cannot start or end with spaces");if(e.endsWith("."))return t("cannot end with dots");let n=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,r=e.split("/").pop()||e;return n.test(r)?t("uses a reserved system name"):e.includes("..")?t("contains a path traversal pattern"):{valid:!0}}function qn(e,t){let n=[],r=[],o=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided."};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(U(a.name))return n.push({file:a.name,message:"Unbuilt project detected. Deploy your build output (dist/, build/, out/), not the project folder."}),{files:e.map(m=>({...m,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(v.broken(e.length,t)){let a={file:`(${e.length} files)`,message:v.sentence(e.length,t)};return n.push(a),{files:e.map(m=>({...m,status:h.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let i=0;for(let a of e){let m=h.READY,c="Ready for upload";if(a.status===h.PROCESSING_ERROR)m=h.VALIDATION_FAILED,c=a.statusMessage||`File "${a.name}" could not be read.`,n.push({file:a.name,message:c});else if(a.size===0){m=h.EXCLUDED,c=`File "${a.name}" is empty, so it is excluded.`,r.push({file:a.name,message:c}),o.push({...a,status:m,statusMessage:c});continue}else if(a.size<0)m=h.VALIDATION_FAILED,c=`File "${a.name}" reports a negative size.`,n.push({file:a.name,message:c});else if(!a.name||a.name.trim().length===0)m=h.VALIDATION_FAILED,c="File name cannot be empty.",n.push({file:a.name||"(empty)",message:c});else if(a.name.includes("\0"))m=h.VALIDATION_FAILED,c=`File name "${a.name}" contains invalid characters (null byte).`,n.push({file:a.name,message:c});else{let y={path:a.name,size:a.size,totalSize:i+a.size},R=ne(y,t);R?(m=h.VALIDATION_FAILED,c=R.sentence(y,t),n.push({file:R.name==="totalSize"?`(${e.length} files)`:a.name,message:c})):i=y.totalSize}o.push({...a,status:m,statusMessage:c})}n.length>0&&(o=o.map(a=>a.status===h.EXCLUDED?a:{...a,status:h.VALIDATION_FAILED,statusMessage:a.status===h.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?o.filter(a=>a.status===h.READY):[],p=n.length===0;return{files:o,validFiles:l,errors:n,warnings:r,canDeploy:p}}function Rt(e){return e.filter(t=>t.status===h.READY)}function Yn(e){return Rt(e).length>0}var ke=D(()=>{"use strict";f();Ue();f()});function $e(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&U(r)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let o=r[r.length-1];if((0,It.isJunk)(o))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let i=r.slice(0,-1);for(let l of i)if(Nt.some(p=>l.toLowerCase()===p.toLowerCase()))return!1;return!0})}var It,Nt,He=D(()=>{"use strict";f();It=require("junk"),Nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ge(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Be(e,t){let n=ne(e,t);if(n)throw s.business(n.sentence(e,t))}function ze(e,t){if(v.broken(e,t))throw s.business(v.sentence(e,t))}var Ve=D(()=>{"use strict";f();Ue()});async function bt(e,t={},n){let r=!!(t.build||t.prerender),o=Ce(e.map(c=>c.path),{flatten:t.pathDetect!==!1}).map(c=>c.path),i=new Set($e(o,{allowUnbuilt:r})),l=e.map((c,y)=>({source:c,deployPath:o[y]})).filter(({deployPath:c})=>i.has(c));if(l.length===0)return[];let p=r?null:Jn(n),a=[],m=0;for(let{source:c,deployPath:y}of l){if(p&&Ge(y,c.origin),c.size===0)continue;p&&(m+=c.size,Be({path:y,size:c.size,totalSize:m},p));let R=await c.read(),{md5:oe}=await H(R);a.push({path:y,content:R,size:c.size,md5:oe})}return p&&ze(a.length,p),a}function Jn(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var Lt=D(()=>{"use strict";f();Fe();He();J();Ve()});var xt={};Xe(xt,{processFilesForNode:()=>Ke});function Ot(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let o of T.readdirSync(e)){let i=g.join(e,o),l=T.statSync(i);l.isDirectory()?n.push(...Ot(i,t)):l.isFile()&&n.push({absPath:i,size:l.size})}return n}async function Qn(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function Zn(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(o=>V.has(o));if(r)throw s.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(M(r))throw r}}}async function Ke(e,t={},n){if(L()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");Zn(e);let r=e.flatMap(p=>{let a=g.resolve(p);try{let m=T.statSync(a);return m.isDirectory()?Ot(a):[{absPath:a,size:m.size}]}catch{throw s.file(`Path does not exist: ${p}`,{filePath:p})}}),o=new Map(r.map(p=>[p.absPath,p.size])),i=At(e.map(p=>g.resolve(p)).map(p=>{try{return T.statSync(p).isDirectory()?p:g.dirname(p)}catch{return g.dirname(p)}})),l=[...o].map(([p,a])=>({path:er(p,i),origin:p,size:a,read:()=>Qn(p)}));return bt(l,t,n)}function er(e,t){if(t&&t.length>0){let n=g.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return g.basename(e)}var T,g,je=D(()=>{"use strict";T=O(require("fs"),1),g=O(require("path"),1);f();Lt();G();we()});var tr={};Xe(tr,{ACCOUNT_HEADER:()=>on,API_KEY:()=>fe,API_PATHS:()=>d,AUTH_BASE_PATH:()=>rn,AccountPlan:()=>zt,AccountRefusal:()=>jt,ApiHttp:()=>$,AuthMethod:()=>z,BUILD_SETTINGS:()=>P,CALLER:()=>x,DEFAULT_API:()=>q,DEPLOYMENT_CONFIG_FILENAME:()=>S,DEPLOY_FIELDS:()=>E,DEPLOY_FILE_GRAMMAR:()=>Yt,DEPLOY_TOKEN:()=>he,DeploymentStatus:()=>kt,DeploymentVia:()=>Je,DomainStatus:()=>$t,DomainVerification:()=>Ht,ErrorType:()=>u,FILE_VALIDATION_STATUS:()=>h,FileValidationStatus:()=>h,IDEMPOTENCY_KEY_CONSTRAINTS:()=>N,JUNK_DIRECTORIES:()=>Nt,LABEL_CONSTRAINTS:()=>I,LABEL_PATTERN:()=>ft,MY_API_KEY_URL:()=>gn,OAUTH_TOKEN:()=>ye,OAuthScope:()=>an,PASSWORD_CONSTRAINTS:()=>F,PUBLIC_DEPLOYMENT_TTL_SECONDS:()=>Tn,SECTIONS:()=>at,SETUP_TROUBLESHOOTING_ANCHOR:()=>Gt,SHIP_ENV:()=>_,SHIP_VIA_ENV:()=>En,SPA_CHECK_CONSTRAINTS:()=>k,SPA_DEFAULT_CONFIG:()=>Ee,Ship:()=>re,ShipError:()=>s,TTL_CONSTRAINTS:()=>C,TokenKind:()=>A,UNBUILT_PROJECT_MARKERS:()=>V,UNSAFE_FILENAME_CHARS:()=>nt,USAGE_KIND:()=>pe,USER_VISIBLE_EVENTS:()=>Sn,WEB_FILE_ACCEPT:()=>nn,__setTestEnvironment:()=>Bn,accountOfPath:()=>hn,allValidFilesReady:()=>Yn,assertShipJsonSyntax:()=>ge,billingReturnOf:()=>dn,calculateMD5:()=>H,classifyToken:()=>rt,consolePaths:()=>ct,countPhrase:()=>Ze,createAccountResource:()=>Le,createDeploymentResource:()=>Ne,createDomainResource:()=>be,createTokenResource:()=>Oe,default:()=>Pt,deserializeLabels:()=>Ln,doorOf:()=>pt,doors:()=>mn,errandOf:()=>yn,excessOver:()=>Vt,extractSubdomain:()=>Rn,filterJunk:()=>$e,fitPhrase:()=>Kt,formatDuration:()=>dt,formatFileSize:()=>w,formatTimeRemaining:()=>Dn,generateDeploymentUrl:()=>In,generateDomainUrl:()=>Nn,getENV:()=>L,getValidFiles:()=>Rt,hasUnbuiltMarker:()=>U,hasUnsafeChars:()=>de,isBlockedExtension:()=>me,isClaimPath:()=>ut,isCustomDomain:()=>An,isDeployment:()=>cn,isPlatformDomain:()=>Se,isShipError:()=>M,isUpgradePath:()=>mt,normalizeVia:()=>Bt,optimizeDeployPaths:()=>Ce,personName:()=>Xt,personShortName:()=>qt,placesTaken:()=>Qe,pluralize:()=>Wn,processFilesForNode:()=>Ke,readBearerValue:()=>sn,serializeLabels:()=>bn,validateApiKey:()=>ot,validateApiUrl:()=>ln,validateBuildCommand:()=>Ae,validateCaller:()=>De,validateDeployCount:()=>ze,validateDeployFile:()=>Be,validateDeployPath:()=>Ge,validateDeployToken:()=>it,validateFileName:()=>te,validateFiles:()=>qn,validateIdempotencyKey:()=>ue,validateLabel:()=>ht,validateLabels:()=>b,validateOAuthToken:()=>st,validateOutputDir:()=>Re,validatePassword:()=>Y,validateToken:()=>K,validateTtl:()=>j});module.exports=Ut(tr);f();f();f();var W=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let o=Array.from(r);for(let i of o)try{i(...n)}catch(l){r.delete(i),t!=="error"&&setTimeout(()=>{let p=l instanceof Error?l:new Error(String(l));this.emit("error",p,String(t))},0)}}};var On=3e4,xn=2,Pn=300,_n=2e3,wn=new Set([500,502,503,504]);function vn(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let o=()=>{clearTimeout(l),t?.removeEventListener("abort",i)},i=()=>{o(),r(t?.reason)},l=setTimeout(()=>{o(),n()},e);t?.addEventListener("abort",i)})}var yt=3e5,Cn=3e5,Fn=yt+Cn,$=class extends W{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||q,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??On,this.maxRetries=Math.max(0,n.maxRetries??xn),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||d.DEPLOYMENTS,timeout:n.timeout??yt,buildTimeout:n.timeout??Fn}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,o,i=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,o,i)}catch(p){let a=s.fromFetchError(p,o);if(l>=this.maxRetries||!this.isRetryable(a,r))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let m=Math.min(_n,Pn*2**l);try{await vn(Math.random()*m,r.signal)}catch(c){let y=s.fromFetchError(c,o);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(u.Maintenance)||n.isType(u.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&wn.has(n.status)))return!1;let i=(r.method??"GET").toUpperCase();return i==="GET"||i==="HEAD"?!0:i==="PUT"||i==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=N.HEADER.toLowerCase();return Object.keys(n).some(o=>o.toLowerCase()===r)}async attemptOnce(n,r,o,i=this.timeout){let l=()=>{};try{let p=await this.mergeHeaders(r.headers),a=this.createTimeoutSignal(r.signal,i);l=a.cleanup;let m={...r,headers:p,credentials:this.session&&!p.Authorization?"include":void 0,signal:a.signal};this.emit("request",n,m);let c=await this.fetch(n,m);if(l(),!c.ok)throw await s.fromHttpResponse(c,o);return this.emit("response",this.safeClone(c),n),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(p){throw l(),s.fromFetchError(p,o)}}async request(n,r,o,i){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,o,i);return l}async requestWithStatus(n,r,o){return this.executeRequest(`${this.apiUrl}${n}`,r,o)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[x.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let o=new AbortController,i=setTimeout(()=>o.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>o.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&o.abort(n.reason)),{signal:o.signal,cleanup:()=>{clearTimeout(i),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function Et(e,t={}){let{labels:n,via:r,password:o,ttl:i,flags:l,captcha:p}=t,a=new FormData,m=[];for(let c of e){if(typeof c.content=="string"||c.content===null||c.content===void 0)throw s.file(`Unsupported file.content type: ${c.path}`,{filePath:c.path});if(!c.md5)throw s.file(`File missing md5 checksum: ${c.path}`,{filePath:c.path});a.append(E.FILES,new File([c.content],c.path,{type:"application/octet-stream"})),m.push(c.md5)}return a.append(E.CHECKSUMS,JSON.stringify(m)),n&&n.length>0&&a.append(E.LABELS,JSON.stringify(n)),r&&a.append(E.VIA,r),o&&a.append(E.PASSWORD,o),i!==void 0&&a.append(E.TTL,String(i)),l?.build&&a.append(E.BUILD,"true"),l?.prerender&&a.append(E.PRERENDER,"true"),l?.spa&&a.append(E.SPA,"true"),l?.buildCommand&&a.append(E.BUILD_COMMAND,l.buildCommand),l?.outputDir&&a.append(E.OUTPUT_DIR,l.outputDir),p&&a.append(E.CAPTCHA,p),a}f();J();async function $n(){let e=JSON.stringify(Ee,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await H(t);return{path:S,content:t,size:e.length,md5:n}}async function Hn(e,t,n){let r=e.find(p=>p.path===k.INDEX_FILE||p.path===`/${k.INDEX_FILE}`);if(!r||r.size>k.MAX_INDEX_BYTES)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))o=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)o=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)o=await r.content.text();else return!1;let i={files:e.map(p=>p.path),index:o};return(await t.request(d.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:n??null},"SPA check")).isSPA}async function gt(e,t,n){return n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===S)?e:await Hn(e,t,n.signal)?[...e,await $n()]:e}f();f();async function Tt(e){let t=e.find(o=>o.path===S||o.path===`/${S}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");ge(r)}var Q={"Content-Type":"application/json"},Gn="sdk";function Ie(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function Ne(e){let{getApi:t,processInput:n}=e;return{upload:async(r,o={})=>{if(!n)throw s.config("processInput function is not provided.");let i=t(),l=await n(r,o),p=await gt(l,i,o);if(!p.length)throw s.business("No files to deploy");for(let ie of p)if(!ie.md5)throw s.file(`MD5 checksum missing for file: ${ie.path}`,{filePath:ie.path});Y(o.password);let a=j(o.ttl),m=ue(o.idempotencyKey),c=b(o.labels);await Tt(p);let y=Ae(o.buildCommand),R=Re(o.outputDir),oe=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa,buildCommand:y,outputDir:R}:void 0,_t=await Et(p,{labels:c,via:o.via??Gn,password:o.password,ttl:a,flags:oe,captcha:o.captcha});return i.request(i.deploy.endpoint,{method:"POST",body:_t,...m?{headers:{[N.HEADER]:m}}:{},signal:o.signal||null},"Deploy",o.build||o.prerender?i.deploy.buildTimeout:i.deploy.timeout)},list:async r=>t().request(`${d.DEPLOYMENTS}${Ie(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(d.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,o)=>t().request(d.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:Q,body:JSON.stringify({labels:b(o.labels)})},"Update deployment labels"),delete:async r=>t().request(d.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function be(e){let{getApi:t}=e;return{set:async(n,r={})=>{let o=b(r.labels),i={};r.deployment&&(i.deployment=r.deployment),o!==void 0&&(i.labels=o);let{data:l,status:p}=await t().requestWithStatus(d.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:Q,body:JSON.stringify(i)},"Set domain");return{...l,isCreate:p===201}},list:async n=>t().request(`${d.DOMAINS}${Ie(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(d.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(d.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(d.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(d.DOMAINS_VALIDATE,{method:"POST",headers:Q,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(d.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(d.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(d.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Le(e){let{getApi:t}=e;return{get:async()=>t().request(d.ACCOUNT,{method:"GET"},"Get account")}}function Oe(e){let{getApi:t}=e;return{create:async(n={})=>{let r=j(n.ttl),o=b(n.labels),i={};return r!==void 0&&(i.ttl=r),o!==void 0&&(i.labels=o),t().request(d.TOKENS,{method:"POST",headers:Q,body:JSON.stringify(i)},"Create token")},list:async n=>t().request(`${d.TOKENS}${Ie(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(d.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(d.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var Z=class{constructor(t={}){this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&De(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(K(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new $({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Ne({...n,processInput:async(r,o)=>this.processInput(r,o,await this.getLimits({signal:o.signal}))}),this.domains=be(n),this.account=Le(n),this.tokens=Oe(n)}async ping(){return this.http.request(d.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(t={}){return this.http.request(d.LIMITS,{method:"GET",signal:t.signal??null},"Get limits")}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");K(t),this.credential=t;return}if(typeof t!="function")throw s.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};G();f();var _e=require("zod");var Pe=require("zod"),Dt={apiUrl:Pe.z.string().url().optional(),token:Pe.z.string().min(1).optional()};G();var Vn=_e.z.object(Dt).strict(),Kn={apiUrl:_.API_URL,token:_.TOKEN};function St(){if(L()!=="node")return{};let e={apiUrl:process.env[_.API_URL]||void 0,token:process.env[_.TOKEN]||void 0};try{return Vn.parse(e)}catch(t){if(t instanceof _e.z.ZodError){let n=t.issues[0],r=n.path[0],o=(r&&Kn[r])??"SHIP environment configuration";throw s.config(`Invalid ${o}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();Fe();G();ke();He();J();Ve();function Wn(e,t,n,r=!0){let o=e===1?t:n;return r?`${e} ${o}`:o}je();var re=class extends Z{constructor(t={}){if(L()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=St();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n,r){let o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(l=>typeof l=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(je(),xt));return i(o,n,r)}},Pt=re;0&&(module.exports={ACCOUNT_HEADER,API_KEY,API_PATHS,AUTH_BASE_PATH,AccountPlan,AccountRefusal,ApiHttp,AuthMethod,BUILD_SETTINGS,CALLER,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_FIELDS,DEPLOY_FILE_GRAMMAR,DEPLOY_TOKEN,DeploymentStatus,DeploymentVia,DomainStatus,DomainVerification,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,IDEMPOTENCY_KEY_CONSTRAINTS,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,MY_API_KEY_URL,OAUTH_TOKEN,OAuthScope,PASSWORD_CONSTRAINTS,PUBLIC_DEPLOYMENT_TTL_SECONDS,SECTIONS,SETUP_TROUBLESHOOTING_ANCHOR,SHIP_ENV,SHIP_VIA_ENV,SPA_CHECK_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,TTL_CONSTRAINTS,TokenKind,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,USAGE_KIND,USER_VISIBLE_EVENTS,WEB_FILE_ACCEPT,__setTestEnvironment,accountOfPath,allValidFilesReady,assertShipJsonSyntax,billingReturnOf,calculateMD5,classifyToken,consolePaths,countPhrase,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,doorOf,doors,errandOf,excessOver,extractSubdomain,filterJunk,fitPhrase,formatDuration,formatFileSize,formatTimeRemaining,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isClaimPath,isCustomDomain,isDeployment,isPlatformDomain,isShipError,isUpgradePath,normalizeVia,optimizeDeployPaths,personName,personShortName,placesTaken,pluralize,processFilesForNode,readBearerValue,serializeLabels,validateApiKey,validateApiUrl,validateBuildCommand,validateCaller,validateDeployCount,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validateIdempotencyKey,validateLabel,validateLabels,validateOAuthToken,validateOutputDir,validatePassword,validateToken,validateTtl});
|
|
1
|
+
"use strict";var Wt=Object.create;var X=Object.defineProperty;var Jt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,en=Object.prototype.hasOwnProperty;var A=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>{for(var n in t)X(e,n,{get:t[n],enumerable:!0})},st=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Qt(t))!en.call(e,r)&&r!==n&&X(e,r,{get:()=>t[r],enumerable:!(o=Jt(t,r))||o.enumerable});return e};var O=(e,t,n)=>(n=e!=null?Wt(Zt(e)):{},st(t||!e||!e.__esModule?X(n,"default",{value:e,enumerable:!0}):n,e)),tn=e=>st(X({},"__esModule",{value:!0}),e);function an(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(ct).includes(t)?t:void 0}function ge(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>M.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${M.MAX_LENGTH} characters.`);return t}function pt(e){return e.members+e.invitations}function cn(e,t){let n=Math.max(0,pt(e)-t.members),o=Math.max(0,e.members-t.members),r={members:o,invitations:n-o,customDomains:e.customDomains-t.customDomains,platformDomains:e.platformDomains-t.platformDomains};return Object.fromEntries(Object.entries(r).filter(([,i])=>i>0))}function ut(e){return mt(["members","customDomains","platformDomains"].filter(t=>(e[t]??0)>0).map(t=>dt(t,e[t]??0)))}function pn(e){let t=ut(e),n=e.invitations??0;return mt([...t?[`remove ${t}`]:[],...n>0?[`cancel ${dt("invitations",n)}`]:[]])}function dn(e){return e.name?.trim()||e.email}function mn(e){return e.name?.trim().split(" ")[0]||e.email}function gn(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function U(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Tn(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function Te(e,t){let n=Tn(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function De(e){return ft.test(e)}function k(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>J.has(n))}function ht(e){return e.startsWith(Se.PREFIX)?R.API_KEY:e.startsWith(Ae.PREFIX)?R.DEPLOY_TOKEN:e.startsWith(Re.PREFIX)?R.OAUTH:R.OPAQUE}function In(e){return e.slice(0,fe.length).toLowerCase()!==fe?null:e.slice(fe.length)||null}function be(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(o){throw s.config(`invalid JSON format in config: ${o.message}`,{filePath:T})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${T} must contain a JSON object`,{filePath:T})}function Ne(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let o=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(o))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function yt(e){Ne(e,Se,"API key")}function Et(e){Ne(e,Ae,"Deploy token")}function gt(e){Ne(e,Re,"OAuth access token")}function Q(e){switch(ht(e)){case R.API_KEY:yt(e);return;case R.DEPLOY_TOKEN:Et(e);return;case R.OAUTH:gt(e);return;case R.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function Le(e){if(!e||e.length>x.MAX_LENGTH||!x.PATTERN.test(e))throw s.validation(`Caller must be 1-${x.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Nn(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw U(t)?t:s.validation("API URL must be a valid URL")}}function Ln(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function Z(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<F.MIN_SECONDS||e>F.MAX_SECONDS)throw s.validation(`TTL must be between ${F.MIN_SECONDS} and ${F.MAX_SECONDS} seconds`);return e}}function St(e){let t=e?`/${e}`:"",n=o=>`${t}${o}`;return{dashboard:()=>t||"/",newSite:()=>n("/new"),deployments:Object.assign(()=>n("/deployments"),{upload:()=>n("/deployments/upload")}),domains:Object.assign(()=>n("/domains"),{connect:o=>n(`/domains/${o}/connect`),deployment:o=>n(`/domains/${o}/deployment`)}),settings:o=>n(o?`/settings#${o}`:"/settings"),claim:o=>n(`/claim/${o}`),settingsAfterBilling:()=>n(`/settings?${at("portal")}`),upgrade:o=>n(o?`/upgrade/${o}`:"/upgrade"),success:()=>n("/success"),successAfterCheckout:()=>n(`/success?${at("checkout")}`),apiKey:()=>n("/api-key")}}function wn(e){let t=new URLSearchParams(e);for(let[n,[o,r]]of Object.entries(Dt))if(t.get(o)===r)return n;return null}function ee(e){let t=e.split(/[?#]/)[0].toLowerCase(),[n="",o=""]=t.split("/").filter(Boolean);return vn(n)?{kind:"door",door:n}:n===xn?{kind:"admin"}:n===""||lt(n)?{kind:"account",account:null,section:n===""?null:n}:{kind:"account",account:n,section:lt(o)?o:null}}function Fn(e){let t=ee(e);return t.kind==="account"?t.account:null}function At(e){let t=ee(e);return t.kind==="door"?t.door:null}function Cn(e){return Rt(e)?"claim":At(e)==="invitation"?"invite":It(e)?"upgrade":null}function bt(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return he(t,"minute");let n=Math.round(e/3600);return n<48?he(n,"hour"):he(Math.round(e/86400),"day")}function $n(e,t=Date.now()/1e3){let n=e-t;return n>0?bt(n):null}function he(e,t){return`${e} ${t}${e===1?"":"s"}`}function I(e,t=1){if(e===0)return"0 Bytes";let n=1024,o=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(n));return`${Number.parseFloat((e/n**r).toFixed(t))} ${o[r]}`}function Oe(e,t){return e.endsWith(`.${t}`)}function Bn(e,t){return!Oe(e,t)}function Gn(e,t){return Oe(e,t)?e.slice(0,-(t.length+1)):null}function zn(e){return`https://${e}`}function Vn(e){return`https://${e}`}function Lt(e){if(typeof e!="string")throw s.validation("Labels must be strings");let t=e.trim().toLowerCase();if(t.length<b.MIN_LENGTH)throw s.validation(`Labels must be at least ${b.MIN_LENGTH} characters long`);if(t.length>b.MAX_LENGTH)throw s.validation(`Labels must be no more than ${b.MAX_LENGTH} characters long`);if(!Nt.test(t))throw s.validation("Labels use letters and numbers, with . _ or - between them, and can have one : between a key and a value, like env:production");return t}function N(e){if(e==null)return;if(!Array.isArray(e))throw s.validation("Labels must be an array");if(e.length>b.MAX_COUNT)throw s.validation(`Maximum ${b.MAX_COUNT} labels allowed`);let t=e.map(Lt);if(new Set(t).size!==t.length)throw s.validation("Duplicate labels are not allowed");return t}function jn(e){return!e||e.length===0?null:JSON.stringify(e)}function Kn(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function xe(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>P.COMMAND_MAX_LENGTH)throw s.validation(`Build command must be between 1 and ${P.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw s.validation("Build command must be a single line");return t}function Pe(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>P.OUTPUT_DIR_MAX_LENGTH)throw s.validation(`Output folder must be between 1 and ${P.OUTPUT_DIR_MAX_LENGTH} characters`);if(!P.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw s.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function ne(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<C.MIN_LENGTH||t.length>C.MAX_LENGTH)throw s.validation(`Password must be between ${C.MIN_LENGTH} and ${C.MAX_LENGTH} characters`);return t}var nn,ct,on,rn,sn,M,Ee,ln,ye,dt,mt,un,m,g,fn,u,hn,me,yn,En,s,Dn,Sn,ft,J,An,q,Se,Ae,Re,x,Rn,R,fe,bn,T,Ie,$,F,Tt,On,xn,Dt,at,W,Pn,_n,vn,lt,Rt,It,te,_,Mn,Un,kn,Hn,y,b,Nt,P,C,f=A(()=>{"use strict";nn={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ct={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},on={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},rn={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},sn="troubleshooting",M={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60},Ee={MAX_BYTES:64*1024*1024,PART_OVERHEAD:256};ln={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"};ye={deployments:{one:"deployment",many:"deployments"},platformDomains:{one:"ShipStatic domain",many:"ShipStatic domains"},customDomains:{one:"custom domain",many:"custom domains"},members:{one:"member",many:"members"},invitations:{one:"invitation",many:"invitations"}};dt=(e,t)=>`${t} ${t===1?ye[e].one:ye[e].many}`,mt=e=>e.length>1?`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`:e[0]??"",un={PAUSED:"paused",UNKNOWN:"unknown"};m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DEPLOYMENT_FILES:e=>`/deployments/${e}/files`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},g={FILES:"files[]",MANIFEST:"manifest",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},fn={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},u={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},hn=new Set([u.Network,u.Timeout,u.Cancelled,u.File,u.Config]),me={client:new Set([u.Build,u.Business,u.Cancelled,u.Config,u.File,u.Forbidden,u.NotFound,u.RateLimit,u.Validation]),network:new Set([u.Network,u.Timeout]),auth:new Set([u.Authentication])},yn=new Set(Object.values(u).filter(e=>!hn.has(e))),En=200;s=class e extends Error{type;status;details;constructor(t,n,o,r){super(n),this.type=t,this.status=o,this.details=r,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===u.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let o,r,i;try{if(t.headers.get("content-type")?.includes("application/json")){let d=await t.json();if(d&&typeof d=="object"){let p=d;typeof p.message=="string"?o=p.message:typeof p.error=="string"&&(o=p.error),r=p.details,typeof p.error=="string"&&yn.has(p.error)&&(i=p.error)}}else{let d=(await t.text()).trim();d&&!d.startsWith("<")&&d.length<=En&&(o=d)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),d=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let p=r&&typeof r=="object"?r:{};p.retryAfter===void 0&&(r={...p,retryAfter:d})}}o=o||`${n||"Request"} failed with status ${t.status}`;let c=i??(t.status===401?u.Authentication:t.status===403?u.Forbidden:t.status===429?u.RateLimit:u.Api);return new e(c,o,t.status,r)}static fromFetchError(t,n){if(U(t))return t;let o=n||"Request",r=t?.name;return r==="AbortError"?e.cancelled(`${o} was cancelled`):r==="TimeoutError"?e.timeout(`${o} timed out`,{cause:t}):t instanceof Error?gn(t)?e.network(`${o} failed: ${t.message}`,{cause:t}):new e(u.Api,`${o} failed: ${t.message}`):new e(u.Api,`${o} failed: Unknown error`)}static validation(t,n){return new e(u.Validation,t,400,n)}static notFound(t,n){let o=n?`${t} ${n} not found`:`${t} not found`;return new e(u.NotFound,o,404)}static forbidden(t,n){return new e(u.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(u.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(u.Authentication,t,401,n)}static business(t,n=400,o){return new e(u.Business,t,n,o)}static network(t,n){return new e(u.Network,t,void 0,n)}static timeout(t,n){return new e(u.Timeout,t,void 0,n)}static cancelled(t,n){return new e(u.Cancelled,t,void 0,n)}static file(t,n){return new e(u.File,t,void 0,n)}static config(t,n){return new e(u.Config,t,void 0,n)}static api(t,n=500,o){return new e(u.Api,t,n,o)}static maintenance(t,n){return new e(u.Maintenance,t,503,n)}static build(t,n){return new e(u.Build,t,422,n)}isClientError(){return me.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return me.network.has(this.type)}isAuthError(){return me.auth.has(this.type)}isType(t){return this.type===t}};Dn=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],Sn=Dn.map(e=>`.${e}`).join(","),ft=/[\x00-\x1f\x7f#?%\\<>"]/;J=new Set(["node_modules","package.json"]);An="/auth",q={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},Se={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},Ae={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},Re={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},x={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},Rn="X-Account",R={API_KEY:q.API_KEY,DEPLOY_TOKEN:q.TOKEN,OAUTH:q.OAUTH,OPAQUE:"opaque"};fe="bearer ";bn={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},T="ship.json",Ie={rewrites:[{source:"/(.*)",destination:"/index.html"}]},$={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};F={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};Tt={new:{owner:!1},deployments:{owner:!1},domains:{owner:!1},settings:{owner:!1},claim:{owner:!1},upgrade:{owner:!0},success:{owner:!0},"api-key":{owner:!0}},On=["login","register","logout","invitation","consent"],xn="admin",Dt={checkout:["upgrading","true"],portal:["billing","returned"]},at=e=>Dt[e].join("="),W=(e,t)=>t?`${e}?next=${encodeURIComponent(t)}`:e;Pn=Object.assign(({next:e}={})=>W("/login",e),{link:({token:e,next:t})=>W(`/login/link/${e}`,t)}),_n={login:Pn,register:({next:e}={})=>W("/register",e),logout:({next:e}={})=>W("/logout",e),invitation:e=>`/invitation/${e}`,consent:()=>"/consent"};vn=e=>On.includes(e),lt=e=>Object.hasOwn(Tt,e);Rt=e=>{let t=ee(e);return t.kind==="account"&&t.section==="claim"},It=e=>{let t=ee(e);return t.kind==="account"&&t.section==="upgrade"};te="https://api.shipstatic.com",_={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},Mn="SHIP_VIA",Un=`https://my.shipstatic.com${St().apiKey()}`,kn=4320*60;Hn=["account.create","account.update","account.delete","account.key.generate","account.plan.transition","deployment.create","deployment.update","deployment.delete","deployment.claim","domain.create","domain.update","domain.delete","domain.verify","token.create","token.consume","token.delete","member.join","member.leave","consent.grant"],y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};b={MIN_LENGTH:3,MAX_LENGTH:63,MAX_COUNT:10},Nt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[a-z0-9]+(?:[._-][a-z0-9]+)*)?$/;P={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};C={MIN_LENGTH:6,MAX_LENGTH:128}});async function so(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,o=2097152;for(let r=0;r<e.size;r+=o){let i=Math.min(r+o,e.size);n.append(await e.slice(r,i).arrayBuffer())}return{md5:n.end()}}async function ao(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function lo(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((o,r)=>{let i=t("md5"),l=n(e);l.on("error",c=>r(s.file(`Failed to read file for MD5: ${c.message}`,{filePath:e}))),l.on("data",c=>i.update(c)),l.on("end",()=>o({md5:i.digest("hex")}))})}async function G(e){if(e instanceof Blob)return so(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return ao(e);if(typeof e=="string")return lo(e);throw s.business("Invalid input for MD5 calculation")}var re=A(()=>{"use strict";f()});function mo(e){$e=e}function fo(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return $e||fo()}var $e,z=A(()=>{"use strict";$e=null});function Ht(e){if(!e||e.length===0)return"";let t=e.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(i=>i.split("/").filter(Boolean)),o=[],r=Math.min(...n.map(i=>i.length));for(let i=0;i<r;i++){let l=n[0][i];if(n.every(c=>c[i]===l))o.push(l);else break}return o.join("/")}function ae(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ge=A(()=>{"use strict"});function Ve(e,t={}){if(t.flatten===!1)return e.map(o=>({path:ae(o),name:ze(o)}));let n=Eo(e);return e.map(o=>{let r=ae(o);if(n){let i=n.endsWith("/")?n:`${n}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=ze(o)),{path:r,name:ze(o)}})}function Eo(e){if(!e.length)return"";let n=e.map(i=>ae(i)).map(i=>i.split("/")),o=[],r=Math.min(...n.map(i=>i.length));for(let i=0;i<r-1;i++){let l=n[0][i];if(n.every(c=>c[i]===l))o.push(l);else break}return o.join("/")}function ze(e){return e.split(/[/\\]/).pop()||e}var je=A(()=>{"use strict";Ge()});function Ke(e,t,n){let o=t.suggestions?.[n];return o?`${e} ${o}`:e}function ce(e,t){return go.find(n=>n.broken(e,t))}var go,w,Ye=A(()=>{"use strict";f();Xe();go=[{name:"name",broken:({path:e})=>!le(e).valid,sentence:({path:e})=>le(e).reason??`File name "${e}" is invalid.`},{name:"extension",broken:({path:e},t)=>Te(e,t.blockedExtensions??[]),sentence:({path:e})=>`File "${e}" has an extension that is not allowed.`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>Ke(`File "${e}" is too large. Maximum ${I(t.maxFileSize)} allowed.`,t,"maxFileSize")},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>Ke(`Files add up to ${I(e)}. Maximum ${I(t.maxTotalSize)} allowed.`,t,"maxTotalSize")}],w={name:"filesCount",broken:(e,t)=>e>t.maxFilesCount,sentence:(e,t)=>Ke(`Too many files (${e}). Maximum ${t.maxFilesCount} files allowed.`,t,"maxFilesCount")}});function le(e){let t=r=>({valid:!1,reason:`File name "${e}" ${r}.`});if(De(e))return t("contains unsafe characters");if(e.startsWith(" ")||e.endsWith(" "))return t("cannot start or end with spaces");if(e.endsWith("."))return t("cannot end with dots");let n=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,o=e.split("/").pop()||e;return n.test(o)?t("uses a reserved system name"):e.includes("..")?t("contains a path traversal pattern"):{valid:!0}}function To(e,t){let n=[],o=[],r=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided."};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(k(a.name))return n.push({file:a.name,message:"Unbuilt project detected. Deploy your build output (dist/, build/, out/), not the project folder."}),{files:e.map(d=>({...d,status:y.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(w.broken(e.length,t)){let a={file:`(${e.length} files)`,message:w.sentence(e.length,t)};return n.push(a),{files:e.map(d=>({...d,status:y.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let i=0;for(let a of e){let d=y.READY,p="Ready for upload";if(a.status===y.PROCESSING_ERROR)d=y.VALIDATION_FAILED,p=a.statusMessage||`File "${a.name}" could not be read.`,n.push({file:a.name,message:p});else if(a.size===0){d=y.EXCLUDED,p=`File "${a.name}" is empty, so it is excluded.`,o.push({file:a.name,message:p}),r.push({...a,status:d,statusMessage:p});continue}else if(a.size<0)d=y.VALIDATION_FAILED,p=`File "${a.name}" reports a negative size.`,n.push({file:a.name,message:p});else if(!a.name||a.name.trim().length===0)d=y.VALIDATION_FAILED,p="File name cannot be empty.",n.push({file:a.name||"(empty)",message:p});else if(a.name.includes("\0"))d=y.VALIDATION_FAILED,p=`File name "${a.name}" contains invalid characters (null byte).`,n.push({file:a.name,message:p});else{let h={path:a.name,size:a.size,totalSize:i+a.size},E=ce(h,t);E?(d=y.VALIDATION_FAILED,p=E.sentence(h,t),n.push({file:E.name==="totalSize"?`(${e.length} files)`:a.name,message:p})):i=h.totalSize}r.push({...a,status:d,statusMessage:p})}n.length>0&&(r=r.map(a=>a.status===y.EXCLUDED?a:{...a,status:y.VALIDATION_FAILED,statusMessage:a.status===y.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?r.filter(a=>a.status===y.READY):[],c=n.length===0;return{files:r,validFiles:l,errors:n,warnings:o,canDeploy:c}}function Bt(e){return e.filter(t=>t.status===y.READY)}function Do(e){return Bt(e).length>0}var Xe=A(()=>{"use strict";f();Ye();f()});function qe(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(o=>o&&k(o)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let o=n.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let r=o[o.length-1];if((0,Gt.isJunk)(r))return!1;for(let l of o)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let i=o.slice(0,-1);for(let l of i)if(zt.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Gt,zt,We=A(()=>{"use strict";f();Gt=require("junk"),zt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Je(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Qe(e,t){let n=ce(e,t);if(n)throw s.business(n.sentence(e,t))}function Ze(e,t){if(w.broken(e,t))throw s.business(w.sentence(e,t))}var et=A(()=>{"use strict";f();Ye()});async function Vt(e,t={},n){let o=!!(t.build||t.prerender),r=Ve(e.map(p=>p.path),{flatten:t.pathDetect!==!1}).map(p=>p.path),i=new Set(qe(r,{allowUnbuilt:o})),l=e.map((p,h)=>({source:p,deployPath:r[h]})).filter(({deployPath:p})=>i.has(p));if(l.length===0)return[];let c=o?null:Ao(n),a=[],d=0;for(let{source:p,deployPath:h}of l){if(c&&Je(h,p.origin),p.size===0)continue;c&&(d+=p.size,Qe({path:h,size:p.size,totalSize:d},c));let E=await p.read(),{md5:V}=await G(E);a.push({path:h,content:E,size:p.size,md5:V})}return c&&Ze(a.length,c),a}function Ao(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var jt=A(()=>{"use strict";f();je();We();re();et()});var Yt={};it(Yt,{processFilesForNode:()=>tt});function Kt(e,t=new Set){let n=[],o=S.realpathSync(e);if(t.has(o))return n;t.add(o);for(let r of S.readdirSync(e)){let i=D.join(e,r),l=S.statSync(i);l.isDirectory()?n.push(...Kt(i,t)):l.isFile()&&n.push({absPath:i,size:l.size})}return n}async function Ro(e){try{return S.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function Io(e){for(let t of e){let n=D.resolve(t);try{if(S.statSync(n).isDirectory()){let o=S.readdirSync(n).find(r=>J.has(r));if(o)throw s.business(`"${o}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(o){if(U(o))throw o}}}async function tt(e,t={},n){if(L()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");Io(e);let o=e.flatMap(c=>{let a=D.resolve(c);try{let d=S.statSync(a);return d.isDirectory()?Kt(a):[{absPath:a,size:d.size}]}catch{throw s.file(`Path does not exist: ${c}`,{filePath:c})}}),r=new Map(o.map(c=>[c.absPath,c.size])),i=Ht(e.map(c=>D.resolve(c)).map(c=>{try{return S.statSync(c).isDirectory()?c:D.dirname(c)}catch{return D.dirname(c)}})),l=[...r].map(([c,a])=>({path:bo(c,i),origin:c,size:a,read:()=>Ro(c)}));return Vt(l,t,n)}function bo(e,t){if(t&&t.length>0){let n=D.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return D.basename(e)}var S,D,nt=A(()=>{"use strict";S=O(require("fs"),1),D=O(require("path"),1);f();jt();z();Ge()});var No={};it(No,{ACCOUNT_HEADER:()=>Rn,API_KEY:()=>Se,API_PATHS:()=>m,AUTH_BASE_PATH:()=>An,AccountPlan:()=>ln,AccountRefusal:()=>un,ApiHttp:()=>H,AuthMethod:()=>q,BUILD_SETTINGS:()=>P,CALLER:()=>x,DEFAULT_API:()=>te,DEPLOYMENT_CONFIG_FILENAME:()=>T,DEPLOY_FIELDS:()=>g,DEPLOY_FILE_GRAMMAR:()=>fn,DEPLOY_REQUEST_CONSTRAINTS:()=>Ee,DEPLOY_TOKEN:()=>Ae,DeploymentStatus:()=>nn,DeploymentVia:()=>ct,DomainStatus:()=>on,DomainVerification:()=>rn,ErrorType:()=>u,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,IDEMPOTENCY_KEY_CONSTRAINTS:()=>M,JUNK_DIRECTORIES:()=>zt,LABEL_CONSTRAINTS:()=>b,LABEL_PATTERN:()=>Nt,MY_API_KEY_URL:()=>Un,OAUTH_TOKEN:()=>Re,OAuthScope:()=>bn,PASSWORD_CONSTRAINTS:()=>C,PUBLIC_DEPLOYMENT_TTL_SECONDS:()=>kn,SECTIONS:()=>Tt,SETUP_TROUBLESHOOTING_ANCHOR:()=>sn,SHIP_ENV:()=>_,SHIP_VIA_ENV:()=>Mn,SPA_CHECK_CONSTRAINTS:()=>$,SPA_DEFAULT_CONFIG:()=>Ie,Ship:()=>pe,ShipError:()=>s,TTL_CONSTRAINTS:()=>F,TokenKind:()=>R,UNBUILT_PROJECT_MARKERS:()=>J,UNSAFE_FILENAME_CHARS:()=>ft,UPLOAD_FLOOR_BITS_PER_SECOND:()=>Zn,USAGE_KIND:()=>ye,USER_VISIBLE_EVENTS:()=>Hn,WEB_FILE_ACCEPT:()=>Sn,__setTestEnvironment:()=>mo,accountOfPath:()=>Fn,allValidFilesReady:()=>Do,assertShipJsonSyntax:()=>be,billingReturnOf:()=>wn,calculateMD5:()=>G,classifyToken:()=>ht,consolePaths:()=>St,countPhrase:()=>ut,createAccountResource:()=>Ue,createDeploymentResource:()=>Ce,createDomainResource:()=>Me,createTokenResource:()=>ke,default:()=>Xt,deserializeLabels:()=>Kn,doorOf:()=>At,doors:()=>_n,errandOf:()=>Cn,excessOver:()=>cn,extractSubdomain:()=>Gn,filterJunk:()=>qe,fitPhrase:()=>pn,formatDuration:()=>bt,formatFileSize:()=>I,formatTimeRemaining:()=>$n,generateDeploymentUrl:()=>zn,generateDomainUrl:()=>Vn,getENV:()=>L,getValidFiles:()=>Bt,hasUnbuiltMarker:()=>k,hasUnsafeChars:()=>De,isBlockedExtension:()=>Te,isClaimPath:()=>Rt,isCustomDomain:()=>Bn,isDeployment:()=>Ln,isPlatformDomain:()=>Oe,isShipError:()=>U,isUpgradePath:()=>It,normalizeVia:()=>an,optimizeDeployPaths:()=>Ve,personName:()=>dn,personShortName:()=>mn,placesTaken:()=>pt,pluralize:()=>So,processFilesForNode:()=>tt,readBearerValue:()=>In,serializeLabels:()=>jn,validateApiKey:()=>yt,validateApiUrl:()=>Nn,validateBuildCommand:()=>xe,validateCaller:()=>Le,validateDeployCount:()=>Ze,validateDeployFile:()=>Qe,validateDeployPath:()=>Je,validateDeployToken:()=>Et,validateFileName:()=>le,validateFiles:()=>To,validateIdempotencyKey:()=>ge,validateLabel:()=>Lt,validateLabels:()=>N,validateOAuthToken:()=>gt,validateOutputDir:()=>Pe,validatePassword:()=>ne,validateToken:()=>Q,validateTtl:()=>Z});module.exports=tn(No);f();f();f();var oe=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let o=this.handlers.get(t);o&&(o.delete(n),o.size===0&&this.handlers.delete(t))}emit(t,...n){let o=this.handlers.get(t);if(!o)return;let r=Array.from(o);for(let i of r)try{i(...n)}catch(l){o.delete(i),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};var Yn=3e4,Xn=2,qn=300,Wn=2e3,Jn=new Set([500,502,503,504]);function Qn(e,t){return new Promise((n,o)=>{if(t?.aborted){o(t.reason);return}let r=()=>{clearTimeout(l),t?.removeEventListener("abort",i)},i=()=>{r(),o(t?.reason)},l=setTimeout(()=>{r(),n()},e);t?.addEventListener("abort",i)})}var Zn=25e5,Ot=3e5,eo=3e5,to=Ot+eo,H=class extends oe{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||te,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Yn,this.maxRetries=Math.max(0,n.maxRetries??Xn),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??Ot,buildTimeout:n.timeout??to}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,o,r,i=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,o,r,i)}catch(c){let a=s.fromFetchError(c,r);if(l>=this.maxRetries||!this.isRetryable(a,o))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let d=Math.min(Wn,qn*2**l);try{await Qn(Math.random()*d,o.signal)}catch(p){let h=s.fromFetchError(p,r);throw this.emit("error",h,n),h}}}isRetryable(n,o){if(o.signal?.aborted||n.isType(u.Maintenance)||n.isType(u.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&Jn.has(n.status)))return!1;let i=(o.method??"GET").toUpperCase();return i==="GET"||i==="HEAD"||o.idempotent===!0}async attemptOnce(n,o,r,i=this.timeout){let l=()=>{};try{let{idempotent:c,...a}=o,d=await this.mergeHeaders(a.headers),p=this.createTimeoutSignal(a.signal,i);l=p.cleanup;let h={...a,headers:d,credentials:this.session&&!d.Authorization?"include":void 0,signal:p.signal};this.emit("request",n,h);let E=await this.fetch(n,h);if(l(),!E.ok)throw await s.fromHttpResponse(E,r);return this.emit("response",this.safeClone(E),n),{data:await this.parseResponse(this.safeClone(E)),status:E.status}}catch(c){throw l(),s.fromFetchError(c,r)}}async request(n,o,r,i){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,o,r,i);return l}async requestWithStatus(n,o,r,i){return this.executeRequest(`${this.apiUrl}${n}`,o,r,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[x.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,o=this.timeout){let r=new AbortController,i=setTimeout(()=>r.abort(new DOMException(`Timed out after ${o}ms`,"TimeoutError")),o),l=n?()=>r.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&r.abort(n.reason)),{signal:r.signal,cleanup:()=>{clearTimeout(i),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();function xt(e){return e.map(t=>{if(!t.md5)throw s.file(`MD5 missing for file: ${t.path}`,{filePath:t.path});return{path:t.path,size:t.size,md5:t.md5}})}function Pt(e,t={}){let{labels:n,via:o,password:r,ttl:i,flags:l,captcha:c}=t,a=[[g.MANIFEST,JSON.stringify(e)]];return n&&n.length>0&&a.push([g.LABELS,JSON.stringify(n)]),o&&a.push([g.VIA,o]),r&&a.push([g.PASSWORD,r]),i!==void 0&&a.push([g.TTL,String(i)]),l?.build&&a.push([g.BUILD,"true"]),l?.prerender&&a.push([g.PRERENDER,"true"]),l?.spa&&a.push([g.SPA,"true"]),l?.buildCommand&&a.push([g.BUILD_COMMAND,l.buildCommand]),l?.outputDir&&a.push([g.OUTPUT_DIR,l.outputDir]),c&&a.push([g.CAPTCHA,c]),a}function _t(e,t){for(let n of t){if(typeof n.content=="string"||n.content===null||n.content===void 0)throw s.file(`Unsupported file.content type: ${n.path}`,{filePath:n.path});e.append(g.FILES,new File([n.content],n.path,{type:"application/octet-stream"}))}}function wt(e,t){let n=new FormData;_t(n,e);for(let[o,r]of t)n.append(o,r);return n}function vt(e){let t=new FormData;return _t(t,e),t}f();var{MAX_BYTES:_e,PART_OVERHEAD:B}=Ee,Ft=new TextEncoder;function no(e){return Ft.encode(e.replace(/\r\n|\r|\n/g,`\r
|
|
2
|
+
`)).length}function oo(e){return Ft.encode(e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")).length}function Ct(e){return e.size+oo(e.path)+B}function ro(e,t){return t.reduce((o,[,r])=>o+no(r)+B,e.reduce((o,r)=>o+Ct(r),0))+B}var io=`A project sent for building can be at most ${I(_e)}.`;function we(e,t,n){if(ro(e,t)<=_e)return{declaration:e,fills:[]};if(n)throw s.validation(io);let o=e.filter(c=>c.path===T),r=[],i=[],l=B;for(let c of e){if(c.path===T)continue;let a=Ct(c);i.length>0&&l+a>_e&&(r.push(i),i=[],l=B),i.push(c),l+=a}return i.length>0&&r.push(i),{declaration:o,fills:r}}f();re();async function co(){let e=JSON.stringify(Ie,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await G(t);return{path:T,content:t,size:e.length,md5:n}}async function po(e,t,n){let o=e.find(c=>c.path===$.INDEX_FILE||c.path===`/${$.INDEX_FILE}`);if(!o||o.size>$.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))r=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)r=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)r=await o.content.text();else return!1;let i={files:e.map(c=>c.path),index:r};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:n??null},"SPA check")).isSPA}async function ve(e,t,n){return e.some(o=>o.path===T)?e:await po(e,t,n)?[...e,await co()]:e}async function Mt(e,t,n){return n.spaDetect===!1||n.spa||n.build||n.prerender?e:ve(e,t,n.signal)}f();f();async function Ut(e){let t=e.find(r=>r.path===T||r.path===`/${T}`);if(!t)return;let n=t.content,o=typeof n.text=="function"?await n.text():t.content.toString("utf8");be(o)}var ie={"Content-Type":"application/json"},uo="sdk";function Fe(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function Ce(e){let{getApi:t,processInput:n}=e;return{upload:async(o,r={})=>{if(!n)throw s.config("processInput function is not provided.");let i=t(),l=await n(o,r),c=await Mt(l,i,r);if(!c.length)throw s.business("No files to deploy");let a=ne(r.password),d=Z(r.ttl),p=ge(r.idempotencyKey),h=N(r.labels);await Ut(c);let E=xe(r.buildCommand),V=Pe(r.outputDir),j=!!(r.build||r.prerender),ot=(de,v)=>Pt(xt(de),{labels:h,via:r.via??uo,password:a,ttl:d,flags:j||v?{build:r.build,prerender:r.prerender,spa:v,buildCommand:E,outputDir:V}:void 0,captcha:r.captcha}),K=ot(c,r.spa),Y=we(c,K,j);r.spa&&!j&&Y.fills.length>0&&(c=await ve(c,i,r.signal),K=ot(c,!1),Y=we(c,K,!1));let rt=r.signal||null,ue=await i.requestWithStatus(i.deploy.endpoint,{method:"POST",body:wt(Y.declaration,K),...p?{headers:{[M.HEADER]:p}}:{},signal:rt,idempotent:p!==void 0},"Deploy",j?i.deploy.buildTimeout:i.deploy.timeout);if(ue.status!==202)return ue.data;let qt=m.DEPLOYMENT_FILES(encodeURIComponent(ue.data.deployment));for(let de of Y.fills){let v=await i.requestWithStatus(qt,{method:"POST",body:vt(de),signal:rt,idempotent:!0},"Deploy",i.deploy.timeout);if(v.status!==202)return v.data}throw s.api("Every file was sent, but the deployment did not go live. Deploy again.")},list:async o=>t().request(`${m.DEPLOYMENTS}${Fe(o)}`,{method:"GET"},"List deployments"),get:async o=>t().request(m.DEPLOYMENT(encodeURIComponent(o)),{method:"GET"},"Get deployment"),set:async(o,r)=>t().request(m.DEPLOYMENT(encodeURIComponent(o)),{method:"PATCH",headers:ie,body:JSON.stringify({labels:N(r.labels)})},"Update deployment labels"),delete:async o=>t().request(m.DEPLOYMENT(encodeURIComponent(o)),{method:"DELETE"},"Delete deployment")}}function Me(e){let{getApi:t}=e;return{set:async(n,o={})=>{let r=N(o.labels),i={};o.deployment&&(i.deployment=o.deployment),r!==void 0&&(i.labels=r);let{data:l,status:c}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:ie,body:JSON.stringify(i)},"Set domain");return{...l,isCreate:c===201}},list:async n=>t().request(`${m.DOMAINS}${Fe(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:ie,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Ue(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function ke(e){let{getApi:t}=e;return{create:async(n={})=>{let o=Z(n.ttl),r=N(n.labels),i={};return o!==void 0&&(i.ttl=o),r!==void 0&&(i.labels=r),t().request(m.TOKENS,{method:"POST",headers:ie,body:JSON.stringify(i)},"Create token")},list:async n=>t().request(`${m.TOKENS}${Fe(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var se=class{constructor(t={}){this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&Le(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(Q(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new H({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Ce({...n,processInput:async(o,r)=>this.processInput(o,r,await this.getLimits({signal:r.signal}))}),this.domains=Me(n),this.account=Ue(n),this.tokens=ke(n)}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(t={}){return this.http.request(m.LIMITS,{method:"GET",signal:t.signal??null},"Get limits")}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");Q(t),this.credential=t;return}if(typeof t!="function")throw s.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};z();f();var Be=require("zod");var He=require("zod"),kt={apiUrl:He.z.string().url().optional(),token:He.z.string().min(1).optional()};z();var ho=Be.z.object(kt).strict(),yo={apiUrl:_.API_URL,token:_.TOKEN};function $t(){if(L()!=="node")return{};let e={apiUrl:process.env[_.API_URL]||void 0,token:process.env[_.TOKEN]||void 0};try{return ho.parse(e)}catch(t){if(t instanceof Be.z.ZodError){let n=t.issues[0],o=n.path[0],r=(o&&yo[o])??"SHIP environment configuration";throw s.config(`Invalid ${r}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();je();z();Xe();We();re();et();function So(e,t,n,o=!0){let r=e===1?t:n;return o?`${e} ${r}`:r}nt();var pe=class extends se{constructor(t={}){if(L()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=$t();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n,o){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(l=>typeof l=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(nt(),Yt));return i(r,n,o)}},Xt=pe;0&&(module.exports={ACCOUNT_HEADER,API_KEY,API_PATHS,AUTH_BASE_PATH,AccountPlan,AccountRefusal,ApiHttp,AuthMethod,BUILD_SETTINGS,CALLER,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_FIELDS,DEPLOY_FILE_GRAMMAR,DEPLOY_REQUEST_CONSTRAINTS,DEPLOY_TOKEN,DeploymentStatus,DeploymentVia,DomainStatus,DomainVerification,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,IDEMPOTENCY_KEY_CONSTRAINTS,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,MY_API_KEY_URL,OAUTH_TOKEN,OAuthScope,PASSWORD_CONSTRAINTS,PUBLIC_DEPLOYMENT_TTL_SECONDS,SECTIONS,SETUP_TROUBLESHOOTING_ANCHOR,SHIP_ENV,SHIP_VIA_ENV,SPA_CHECK_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,TTL_CONSTRAINTS,TokenKind,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,UPLOAD_FLOOR_BITS_PER_SECOND,USAGE_KIND,USER_VISIBLE_EVENTS,WEB_FILE_ACCEPT,__setTestEnvironment,accountOfPath,allValidFilesReady,assertShipJsonSyntax,billingReturnOf,calculateMD5,classifyToken,consolePaths,countPhrase,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,doorOf,doors,errandOf,excessOver,extractSubdomain,filterJunk,fitPhrase,formatDuration,formatFileSize,formatTimeRemaining,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isClaimPath,isCustomDomain,isDeployment,isPlatformDomain,isShipError,isUpgradePath,normalizeVia,optimizeDeployPaths,personName,personShortName,placesTaken,pluralize,processFilesForNode,readBearerValue,serializeLabels,validateApiKey,validateApiUrl,validateBuildCommand,validateCaller,validateDeployCount,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validateIdempotencyKey,validateLabel,validateLabels,validateOAuthToken,validateOutputDir,validatePassword,validateToken,validateTtl});
|
|
2
3
|
|
|
3
4
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
5
|
const originalExports = module.exports;
|