@shipstatic/ship 0.3.2 → 0.3.3
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 +52 -1
- package/dist/browser.d.ts +91 -1
- package/dist/browser.js +3 -3
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +21 -21
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +91 -1
- package/dist/index.d.ts +91 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Je=Object.create;var te=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var x=(n,e)=>()=>(n&&(e=n(n=0)),e);var z=(n,e)=>{for(var t in e)te(n,t,{get:e[t],enumerable:!0})},ee=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of We(e))!Xe.call(n,i)&&i!==t&&te(n,i,{get:()=>e[i],enumerable:!(o=Ve(e,i))||o.enumerable});return n},p=(n,e,t)=>(ee(n,e,"default"),t&&ee(t,e,"default")),F=(n,e,t)=>(t=n!=null?Je(Ye(n)):{},ee(e||!n||!n.__esModule?te(t,"default",{value:n,enumerable:!0}):t,n)),Ze=n=>ee(te({},"__esModule",{value:!0}),n);var Re={};z(Re,{__setTestEnvironment:()=>j,getENV:()=>h});function j(n){ye=n}function Qe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function h(){return ye||Qe()}var ye,P=x(()=>{"use strict";ye=null});function L(n){we=n}function b(){if(we===null)throw ke.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return we}var ke,we,U=x(()=>{"use strict";ke=require("@shipstatic/types"),we=null});var Oe={};z(Oe,{loadConfig:()=>K});function $e(n){try{return ot.parse(n)}catch(e){if(e instanceof M.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw re.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw re.ShipError.config("Configuration validation failed")}}async function it(n){try{if(h()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(Se,{searchPlaces:[`.${Se}rc`,"package.json",`${t.homedir()}/.${Se}rc`],stopDir:t.homedir()}),i;if(n?i=o.load(n):i=o.search(),i&&i.config)return $e(i.config)}catch(e){if(e instanceof re.ShipError)throw e}return{}}async function K(n){if(h()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await it(n),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return $e(o)}var M,re,Se,ot,se=x(()=>{"use strict";M=require("zod"),re=require("@shipstatic/types");P();Se="ship",ot=M.z.object({apiUrl:M.z.string().url().optional(),apiKey:M.z.string().optional(),deployToken:M.z.string().optional()}).strict()});async function st(n){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let r=Math.ceil(n.size/2097152),s=0,l=new e.ArrayBuffer,f=new FileReader,S=()=>{let g=s*2097152,a=Math.min(g+2097152,n.size);f.readAsArrayBuffer(n.slice(g,a))};f.onload=g=>{let a=g.target?.result;if(!a){o(N.ShipError.business("Failed to read file chunk"));return}l.append(a),s++,s<r?S():t({md5:l.end()})},f.onerror=()=>{o(N.ShipError.business("Failed to calculate MD5: FileReader error"))},S()})}async function at(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let o=e.createHash("md5");return o.update(n),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,i)=>{let r=e.createHash("md5"),s=t.createReadStream(n);s.on("error",l=>i(N.ShipError.business(`Failed to read file for MD5: ${l.message}`))),s.on("data",l=>r.update(l)),s.on("end",()=>o({md5:r.digest("hex")}))})}async function k(n){let e=h();if(e==="browser"){if(!(n instanceof Blob))throw N.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return st(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw N.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return at(n)}throw N.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var N,G=x(()=>{"use strict";P();N=require("@shipstatic/types")});function B(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let o=t[t.length-1];if((0,Ne.isJunk)(o))return!1;let i=t.slice(0,-1);for(let r of i)if(pe.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var Ne,pe,ce=x(()=>{"use strict";Ne=require("junk"),pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Be(n){if(!n||n.length===0)return"";let e=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),o=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i;r++){let s=t[0][r];if(t.every(l=>l[r]===s))o.push(s);else break}return o.join("/")}function le(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Pe=x(()=>{"use strict"});function I(n,e={}){if(e.flatten===!1)return n.map(o=>({path:le(o),name:Ce(o)}));let t=ct(n);return n.map(o=>{let i=le(o);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=Ce(o)),{path:i,name:Ce(o)}})}function ct(n){if(!n.length)return"";let t=n.map(r=>le(r)).map(r=>r.split("/")),o=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i-1;r++){let s=t[0][r];if(t.every(l=>l[r]===s))o.push(s);else break}return o.join("/")}function Ce(n){return n.split(/[/\\]/).pop()||n}var fe=x(()=>{"use strict";Pe()});function Ie(n){let e=[];try{let t=$.readdirSync(n);for(let o of t){let i=v.join(n,o),r=$.statSync(i);if(r.isDirectory()){let s=Ie(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function X(n,e={}){if(h()!=="node")throw A.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let d=v.resolve(m);try{return $.statSync(d).isDirectory()?Ie(d):[d]}catch{throw A.ShipError.file(`Path does not exist: ${m}`,m)}}),o=[...new Set(t)],i=B(o);if(i.length===0)return[];let r=n.map(m=>v.resolve(m)),s=Be(r.map(m=>{try{return $.statSync(m).isDirectory()?m:v.dirname(m)}catch{return v.dirname(m)}})),l=i.map(m=>{if(s&&s.length>0){let d=v.relative(s,m);if(d&&typeof d=="string"&&!d.startsWith(".."))return d.replace(/\\/g,"/")}return v.basename(m)}),f=I(l,{flatten:e.pathDetect!==!1}),S=[],g=0,a=b();for(let m=0;m<i.length;m++){let d=i[m],E=f[m].path;try{let T=$.statSync(d);if(T.size===0){console.warn(`Skipping empty file: ${d}`);continue}if(T.size>a.maxFileSize)throw A.ShipError.business(`File ${d} is too large. Maximum allowed size is ${a.maxFileSize/(1024*1024)}MB.`);if(g+=T.size,g>a.maxTotalSize)throw A.ShipError.business(`Total deploy size is too large. Maximum allowed is ${a.maxTotalSize/(1024*1024)}MB.`);let de=$.readFileSync(d),{md5:Ge}=await k(de);if(E.includes("\0")||E.includes("/../")||E.startsWith("../")||E.endsWith("/.."))throw A.ShipError.business(`Security error: Unsafe file path "${E}" for file: ${d}`);S.push({path:E,content:de,size:de.length,md5:Ge})}catch(T){if(T instanceof A.ShipError&&T.isClientError&&T.isClientError())throw T;console.error(`Could not process file ${d}:`,T)}}if(S.length>a.maxFilesCount)throw A.ShipError.business(`Too many files to deploy. Maximum allowed is ${a.maxFilesCount} files.`);return S}var A,$,v,Ee=x(()=>{"use strict";P();G();ce();A=require("@shipstatic/types");U();fe();Pe();$=F(require("fs"),1),v=F(require("path"),1)});async function ze(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(P(),Re));if(t()!=="browser")throw xe.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let o=Array.isArray(n)?n:Array.from(n),i=o.map(a=>a.webkitRelativePath||a.name),r=I(i,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<o.length;a++){let m=o[a],d=r[a].path;if(d.includes("..")||d.includes("\0"))throw xe.ShipError.business(`Security error: Unsafe file path "${d}" for file: ${m.name}`);s.push({file:m,relativePath:d})}let l=s.map(a=>a.relativePath),f=B(l),S=new Set(f),g=[];for(let a of s){if(!S.has(a.relativePath))continue;let{md5:m}=await k(a.file);g.push({content:a.file,path:a.relativePath,size:a.file.size,md5:m})}return g}var xe,Le=x(()=>{"use strict";G();xe=require("@shipstatic/types");ce();fe()});var je={};z(je,{convertBrowserInput:()=>qe,convertDeployInput:()=>lt,convertNodeInput:()=>Fe});function Me(n,e={}){let t=b();if(!e.skipEmptyCheck&&n.length===0)throw D.ShipError.business("No files to deploy.");if(n.length>t.maxFilesCount)throw D.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let o=0;for(let i of n){if(i.size>t.maxFileSize)throw D.ShipError.business(`File ${i.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(o+=i.size,o>t.maxTotalSize)throw D.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ke(n,e){if(e==="node"){if(!Array.isArray(n))throw D.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw D.ShipError.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw D.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&n instanceof HTMLInputElement&&!n.files)throw D.ShipError.business("No files selected in HTMLInputElement")}function _e(n){let e=n.map(t=>({name:t.path,size:t.size}));return Me(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function Fe(n,e={}){Ke(n,"node");let t=await X(n,e);return _e(t)}async function qe(n,e={}){Ke(n,"browser");let t;if(n instanceof HTMLInputElement)t=Array.from(n.files);else if(typeof n=="object"&&n!==null&&typeof n.length=="number"&&typeof n.item=="function")t=Array.from(n);else if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw D.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=n}else throw D.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),Me(t);let o=await ze(t,e);return _e(o)}async function lt(n,e={},t){let o=h();if(o!=="node"&&o!=="browser")throw D.ShipError.business("Unsupported execution environment.");let i;if(o==="node")if(typeof n=="string")i=await Fe([n],e);else if(Array.isArray(n)&&n.every(r=>typeof r=="string"))i=await Fe(n,e);else throw D.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await qe(n,e);return i}var D,He=x(()=>{"use strict";D=require("@shipstatic/types");P();Ee();Le();U()});var Q={};z(Q,{ApiHttp:()=>R,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Z,ShipError:()=>O.ShipError,ShipErrorType:()=>O.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>k,createAccountResource:()=>W,createDeploymentResource:()=>J,createDomainResource:()=>V,createTokenResource:()=>Y,default:()=>Te,filterJunk:()=>B,getCurrentConfig:()=>b,getENV:()=>h,loadConfig:()=>K,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>I,pluralize:()=>ve,processFilesForNode:()=>X,resolveConfig:()=>_,setConfig:()=>L,setPlatformConfig:()=>L});module.exports=Ze(Q);var u={};z(u,{ApiHttp:()=>R,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Z,ShipError:()=>O.ShipError,ShipErrorType:()=>O.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>k,createAccountResource:()=>W,createDeploymentResource:()=>J,createDomainResource:()=>V,createTokenResource:()=>Y,default:()=>Te,filterJunk:()=>B,getCurrentConfig:()=>b,getENV:()=>h,loadConfig:()=>K,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>I,pluralize:()=>ve,processFilesForNode:()=>X,resolveConfig:()=>_,setConfig:()=>L,setPlatformConfig:()=>L});var ue=F(require("mime-db"),1),he={};for(let n in ue.default){let e=ue.default[n];e&&e.extensions&&e.extensions.forEach(t=>{he[t]||(he[t]=n)})}function ne(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return he[e]||"application/octet-stream"}var w=require("@shipstatic/types");var oe=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let o=this.handlers.get(e);o&&(o.delete(t),o.size===0&&this.handlers.delete(e))}emit(e,...t){let o=this.handlers.get(e);if(!o)return;let i=Array.from(o);for(let r of i)try{r(...t)}catch(s){o.delete(r),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,o)=>{t.forEach(i=>{e.on(o,i)})})}clear(){this.handlers.clear()}};P();var ie="/deployments",be="/ping",C="/domains",et="/config",tt="/account",ge="/tokens",nt="/spa-check",R=class extends oe{constructor(e){super(),this.apiUrl=e.apiUrl||w.DEFAULT_API,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},o){let i=this.getAuthHeaders(t.headers),r={...t,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,r);try{let s=await fetch(e,r);s.ok||await this.handleResponseError(s,o);let l=this.safeClone(s),f=this.safeClone(s);return this.emit("response",l,e),await this.parseResponse(f)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,o),s}}getAuthHeaders(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let o={};try{e.headers.get("content-type")?.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let i=o.message||o.error||`${t} failed due to API error`;throw e.status===401?w.ShipError.authentication(i):w.ShipError.api(i,e.status,o.code,o)}handleFetchError(e,t){throw e.name==="AbortError"?w.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?w.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof w.ShipError?e:w.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${be}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${be}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${et}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:o,requestHeaders:i}=await this.prepareRequestPayload(e,t.tags),r={};t.deployToken?r={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(r={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:o,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ie}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ie}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ie}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ie}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,o){let i={deployment:t};o&&o.length>0&&(i.tags=o);let r={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},s=this.getAuthHeaders(r.headers),l={...r,headers:s,credentials:this.needsCredentials(s)?"include":void 0};this.emit("request",`${this.apiUrl}${C}/${encodeURIComponent(e)}`,l);try{let f=await fetch(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,l);f.ok||await this.handleResponseError(f,"Set Domain");let S=this.safeClone(f),g=this.safeClone(f);return this.emit("response",S,`${this.apiUrl}${C}/${encodeURIComponent(e)}`),{...await this.parseResponse(g),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${C}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${C}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${tt}`,{method:"GET"},"Get Account")}async createToken(e,t){let o={};return e!==void 0&&(o.ttl=e),t&&t.length>0&&(o.tags=t),await this.request(`${this.apiUrl}${ge}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${ge}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${ge}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))o=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)o=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)o=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:o};return(await this.request(`${this.apiUrl}${nt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw w.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw w.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(h()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(h()==="node"){let{body:o,headers:i}=await this.createNodeBody(e,t);return{requestBody:o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength),requestHeaders:i}}else throw w.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let o=new FormData,i=[];for(let r of e){if(!(r.content instanceof File||r.content instanceof Blob))throw w.ShipError.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let s=this.getBrowserContentType(r.content instanceof File?r.content:r.path),l=new File([r.content],r.path,{type:s});o.append("files[]",l),i.push(r.md5)}return o.append("checksums",JSON.stringify(i)),t&&t.length>0&&o.append("tags",JSON.stringify(t)),o}async createNodeBody(e,t){let{FormData:o,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),s=new o,l=[];for(let a of e){let m=ne(a.path),d;if(Buffer.isBuffer(a.content))d=new i([a.content],a.path,{type:m});else if(typeof Blob<"u"&&a.content instanceof Blob)d=new i([a.content],a.path,{type:m});else throw w.ShipError.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let E=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",d,E),l.push(a.md5)}s.append("checksums",JSON.stringify(l)),t&&t.length>0&&s.append("tags",JSON.stringify(t));let f=new r(s),S=[];for await(let a of f.encode())S.push(Buffer.from(a));let g=Buffer.concat(S);return{body:g,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(g).toString()}}}getBrowserContentType(e){return typeof e=="string"?ne(e):e.type||ne(e.name)}};U();var Ae=require("@shipstatic/types");P();async function rt(n){let e=h();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(se(),Oe));return t(n)}else return{}}function _(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||Ae.DEFAULT_API,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},o={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(o.apiKey=t.apiKey),t.deployToken!==void 0&&(o.deployToken=t.deployToken),o}function H(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}var De=require("@shipstatic/types");G();async function pt(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:o}=await k(t);return{path:De.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:o}}async function Ue(n,e,t){if(t.spaDetect===!1||n.some(o=>o.path===De.DEPLOYMENT_CONFIG_FILENAME))return n;try{if(await e.checkSPA(n)){let i=await pt();return[...n,i]}}catch{}return n}function J(n,e,t,o){return{create:async(i,r={})=>{t&&await t();let s=e?H(r,e):r,l=n();if(!o)throw new Error("processInput function is not provided.");let f=await o(i,s);return f=await Ue(f,l,s),await l.deploy(f,s)},list:async()=>(t&&await t(),n().listDeployments()),remove:async i=>{t&&await t(),await n().removeDeployment(i)},get:async i=>(t&&await t(),n().getDeployment(i))}}function V(n,e){return{set:async(t,o,i)=>(e&&await e(),n().setDomain(t,o,i)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function W(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function Y(n,e){return{create:async(t,o)=>(e&&await e(),n().createToken(t,o)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var q=class{constructor(e={}){this.initPromise=null;this._config=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new R({...e,...t});let o=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=J(i,this.clientOptions,o,(r,s)=>this.processInput(r,s)),this._domains=V(i,o),this._account=W(i,o),this._tokens=Y(i,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=b(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}};var me=require("@shipstatic/types");P();se();U();var c={};z(c,{ApiHttp:()=>R,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>q,ShipError:()=>O.ShipError,ShipErrorType:()=>O.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>k,createAccountResource:()=>W,createDeploymentResource:()=>J,createDomainResource:()=>V,createTokenResource:()=>Y,filterJunk:()=>B,getENV:()=>h,loadConfig:()=>rt,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>I,pluralize:()=>ve,resolveConfig:()=>_});var y={};p(y,require("@shipstatic/types"));p(c,y);var ae=require("@shipstatic/types");G();function ve(n,e,t,o=!0){let i=n===1?e:t;return o?`${n} ${i}`:i}ce();fe();P();var O=require("@shipstatic/types");p(u,c);se();U();U();Ee();P();var Z=class extends q{constructor(e={}){if(h()!=="node")throw me.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return _(e,{})}async loadFullConfig(){try{let e=await K(this.clientOptions.configFile),t=_(this.clientOptions,e),o=new R({...this.clientOptions,...t});this.replaceHttpClient(o);let i=await this.http.getConfig();L(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw me.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw me.ShipError.business("No files to deploy.");let{convertDeployInput:o}=await Promise.resolve().then(()=>(He(),je));return o(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Te=Z;p(Q,u,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,JUNK_DIRECTORIES,Ship,ShipError,ShipErrorType,__setTestEnvironment,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,filterJunk,getCurrentConfig,getENV,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setConfig,setPlatformConfig});
|
|
1
|
+
"use strict";var Qe=Object.create;var ie=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var nt=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var x=(n,e)=>()=>(n&&(e=n(n=0)),e);var z=(n,e)=>{for(var t in e)ie(n,t,{get:e[t],enumerable:!0})},ne=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of tt(e))!it.call(n,r)&&r!==t&&ie(n,r,{get:()=>e[r],enumerable:!(i=et(e,r))||i.enumerable});return n},l=(n,e,t)=>(ne(n,e,"default"),t&&ne(t,e,"default")),v=(n,e,t)=>(t=n!=null?Qe(nt(n)):{},ne(e||!n||!n.__esModule?ie(t,"default",{value:n,enumerable:!0}):t,n)),ot=n=>ne(ie({},"__esModule",{value:!0}),n);var ke={};z(ke,{__setTestEnvironment:()=>H,getENV:()=>y});function H(n){Se=n}function rt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return Se||rt()}var Se,T=x(()=>{"use strict";Se=null});function U(n){we=n}function I(){if(we===null)throw Ne.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return we}var Ne,we,M=x(()=>{"use strict";Ne=require("@shipstatic/types"),we=null});var _e={};z(_e,{loadConfig:()=>K});function Le(n){try{return lt.parse(n)}catch(e){if(e instanceof B.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw ae.ShipError.config(`Configuration validation failed${i}: ${t.message}`)}throw ae.ShipError.config("Configuration validation failed")}}async function ct(n){try{if(y()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(Fe,{searchPlaces:[`.${Fe}rc`,"package.json",`${t.homedir()}/.${Fe}rc`],stopDir:t.homedir()}),r;if(n?r=i.load(n):r=i.search(),r&&r.config)return Le(r.config)}catch(e){if(e instanceof ae.ShipError)throw e}return{}}async function K(n){if(y()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ct(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Le(i)}var B,ae,Fe,lt,pe=x(()=>{"use strict";B=require("zod"),ae=require("@shipstatic/types");T();Fe="ship",lt=B.z.object({apiUrl:B.z.string().url().optional(),apiKey:B.z.string().optional(),deployToken:B.z.string().optional()}).strict()});async function mt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),s=0,a=new e.ArrayBuffer,f=new FileReader,D=()=>{let E=s*2097152,p=Math.min(E+2097152,n.size);f.readAsArrayBuffer(n.slice(E,p))};f.onload=E=>{let p=E.target?.result;if(!p){i(N.ShipError.business("Failed to read file chunk"));return}a.append(p),s++,s<o?D():t({md5:a.end()})},f.onerror=()=>{i(N.ShipError.business("Failed to calculate MD5: FileReader error"))},D()})}async function dt(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,r)=>{let o=e.createHash("md5"),s=t.createReadStream(n);s.on("error",a=>r(N.ShipError.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>o.update(a)),s.on("end",()=>i({md5:o.digest("hex")}))})}async function b(n){let e=y();if(e==="browser"){if(!(n instanceof Blob))throw N.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return mt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw N.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return dt(n)}throw N.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var N,J=x(()=>{"use strict";T();N=require("@shipstatic/types")});function L(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if((0,Be.isJunk)(i))return!1;let r=t.slice(0,-1);for(let o of r)if(ce.some(s=>o.toLowerCase()===s.toLowerCase()))return!1;return!0})}var Be,ce,fe=x(()=>{"use strict";Be=require("junk"),ce=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ke(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function me(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Pe=x(()=>{"use strict"});function _(n,e={}){if(e.flatten===!1)return n.map(i=>({path:me(i),name:Ce(i)}));let t=ht(n);return n.map(i=>{let r=me(i);if(t){let o=t.endsWith("/")?t:`${t}/`;r.startsWith(o)&&(r=r.substring(o.length))}return r||(r=Ce(i)),{path:r,name:Ce(i)}})}function ht(n){if(!n.length)return"";let t=n.map(o=>me(o)).map(o=>o.split("/")),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r-1;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function Ce(n){return n.split(/[/\\]/).pop()||n}var de=x(()=>{"use strict";Pe()});function qe(n){let e=[];try{let t=$.readdirSync(n);for(let i of t){let r=F.join(n,i),o=$.statSync(r);if(o.isDirectory()){let s=qe(r);e.push(...s)}else o.isFile()&&e.push(r)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function Q(n,e={}){if(y()!=="node")throw k.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let d=F.resolve(m);try{return $.statSync(d).isDirectory()?qe(d):[d]}catch{throw k.ShipError.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],r=L(i);if(r.length===0)return[];let o=n.map(m=>F.resolve(m)),s=Ke(o.map(m=>{try{return $.statSync(m).isDirectory()?m:F.dirname(m)}catch{return F.dirname(m)}})),a=r.map(m=>{if(s&&s.length>0){let d=F.relative(s,m);if(d&&typeof d=="string"&&!d.startsWith(".."))return d.replace(/\\/g,"/")}return F.basename(m)}),f=_(a,{flatten:e.pathDetect!==!1}),D=[],E=0,p=I();for(let m=0;m<r.length;m++){let d=r[m],C=f[m].path;try{let R=$.statSync(d);if(R.size===0){console.warn(`Skipping empty file: ${d}`);continue}if(R.size>p.maxFileSize)throw k.ShipError.business(`File ${d} is too large. Maximum allowed size is ${p.maxFileSize/(1024*1024)}MB.`);if(E+=R.size,E>p.maxTotalSize)throw k.ShipError.business(`Total deploy size is too large. Maximum allowed is ${p.maxTotalSize/(1024*1024)}MB.`);let ye=$.readFileSync(d),{md5:Ze}=await b(ye);if(C.includes("\0")||C.includes("/../")||C.startsWith("../")||C.endsWith("/.."))throw k.ShipError.business(`Security error: Unsafe file path "${C}" for file: ${d}`);D.push({path:C,content:ye,size:ye.length,md5:Ze})}catch(R){if(R instanceof k.ShipError&&R.isClientError&&R.isClientError())throw R;console.error(`Could not process file ${d}:`,R)}}if(D.length>p.maxFilesCount)throw k.ShipError.business(`Too many files to deploy. Maximum allowed is ${p.maxFilesCount} files.`);return D}var k,$,F,Ie=x(()=>{"use strict";T();J();fe();k=require("@shipstatic/types");M();de();Pe();$=v(require("fs"),1),F=v(require("path"),1)});async function Ve(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(T(),ke));if(t()!=="browser")throw be.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let i=Array.isArray(n)?n:Array.from(n),r=i.map(p=>p.webkitRelativePath||p.name),o=_(r,{flatten:e.pathDetect!==!1}),s=[];for(let p=0;p<i.length;p++){let m=i[p],d=o[p].path;if(d.includes("..")||d.includes("\0"))throw be.ShipError.business(`Security error: Unsafe file path "${d}" for file: ${m.name}`);s.push({file:m,relativePath:d})}let a=s.map(p=>p.relativePath),f=L(a),D=new Set(f),E=[];for(let p of s){if(!D.has(p.relativePath))continue;let{md5:m}=await b(p.file);E.push({content:p.file,path:p.relativePath,size:p.file.size,md5:m})}return E}var be,je=x(()=>{"use strict";J();be=require("@shipstatic/types");fe();de()});var We={};z(We,{convertBrowserInput:()=>Ye,convertDeployInput:()=>St,convertNodeInput:()=>$e});function He(n,e={}){let t=I();if(!e.skipEmptyCheck&&n.length===0)throw w.ShipError.business("No files to deploy.");if(n.length>t.maxFilesCount)throw w.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let r of n){if(r.size>t.maxFileSize)throw w.ShipError.business(`File ${r.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=r.size,i>t.maxTotalSize)throw w.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ge(n,e){if(e==="node"){if(!Array.isArray(n))throw w.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw w.ShipError.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw w.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&n instanceof HTMLInputElement&&!n.files)throw w.ShipError.business("No files selected in HTMLInputElement")}function Je(n){let e=n.map(t=>({name:t.path,size:t.size}));return He(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function $e(n,e={}){Ge(n,"node");let t=await Q(n,e);return Je(t)}async function Ye(n,e={}){Ge(n,"browser");let t;if(n instanceof HTMLInputElement)t=Array.from(n.files);else if(typeof n=="object"&&n!==null&&typeof n.length=="number"&&typeof n.item=="function")t=Array.from(n);else if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw w.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=n}else throw w.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(r=>r.size===0?(console.warn(`Skipping empty file: ${r.name}`),!1):!0),He(t);let i=await Ve(t,e);return Je(i)}async function St(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw w.ShipError.business("Unsupported execution environment.");let r;if(i==="node")if(typeof n=="string")r=await $e([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))r=await $e(n,e);else throw w.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else r=await Ye(n,e);return r}var w,Xe=x(()=>{"use strict";w=require("@shipstatic/types");T();Ie();je();M()});var te={};z(te,{ApiHttp:()=>A,DEFAULT_API:()=>le.DEFAULT_API,FILE_VALIDATION_STATUS:()=>u,JUNK_DIRECTORIES:()=>ce,Ship:()=>ee,ShipError:()=>O.ShipError,ShipErrorType:()=>O.ShipErrorType,__setTestEnvironment:()=>H,allValidFilesReady:()=>Ae,calculateMD5:()=>b,createAccountResource:()=>X,createDeploymentResource:()=>Y,createDomainResource:()=>W,createTokenResource:()=>Z,default:()=>Oe,filterJunk:()=>L,formatFileSize:()=>j,getCurrentConfig:()=>I,getENV:()=>y,getValidFiles:()=>ue,loadConfig:()=>K,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>_,pluralize:()=>Te,processFilesForNode:()=>Q,resolveConfig:()=>q,setConfig:()=>U,setPlatformConfig:()=>U,validateFiles:()=>Re});module.exports=ot(te);var h={};z(h,{ApiHttp:()=>A,DEFAULT_API:()=>le.DEFAULT_API,FILE_VALIDATION_STATUS:()=>u,JUNK_DIRECTORIES:()=>ce,Ship:()=>ee,ShipError:()=>O.ShipError,ShipErrorType:()=>O.ShipErrorType,__setTestEnvironment:()=>H,allValidFilesReady:()=>Ae,calculateMD5:()=>b,createAccountResource:()=>X,createDeploymentResource:()=>Y,createDomainResource:()=>W,createTokenResource:()=>Z,default:()=>Oe,filterJunk:()=>L,formatFileSize:()=>j,getCurrentConfig:()=>I,getENV:()=>y,getValidFiles:()=>ue,loadConfig:()=>K,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>_,pluralize:()=>Te,processFilesForNode:()=>Q,resolveConfig:()=>q,setConfig:()=>U,setPlatformConfig:()=>U,validateFiles:()=>Re});var ge=v(require("mime-db"),1),Ee={};for(let n in ge.default){let e=ge.default[n];e&&e.extensions&&e.extensions.forEach(t=>{Ee[t]||(Ee[t]=n)})}function oe(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return Ee[e]||"application/octet-stream"}var S=require("@shipstatic/types");var re=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let r=Array.from(i);for(let o of r)try{o(...t)}catch(s){i.delete(o),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(r=>{e.on(i,r)})})}clear(){this.handlers.clear()}};T();var se="/deployments",Me="/ping",P="/domains",st="/config",at="/account",De="/tokens",pt="/spa-check",A=class extends re{constructor(e){super(),this.apiUrl=e.apiUrl||S.DEFAULT_API,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let r=this.getAuthHeaders(t.headers),o={...t,headers:r,credentials:this.needsCredentials(r)?"include":void 0};this.emit("request",e,o);try{let s=await fetch(e,o);s.ok||await this.handleResponseError(s,i);let a=this.safeClone(s),f=this.safeClone(s);return this.emit("response",a,e),await this.parseResponse(f)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,i),s}}getAuthHeaders(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let r=i.message||i.error||`${t} failed due to API error`;throw e.status===401?S.ShipError.authentication(r):S.ShipError.api(r,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?S.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?S.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof S.ShipError?e:S.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Me}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Me}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${st}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:r}=await this.prepareRequestPayload(e,t.tags),o={};t.deployToken?o={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(o={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:i,headers:{...r,...o},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${se}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${se}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${se}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${se}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,i){let r={deployment:t};i&&i.length>0&&(r.tags=i);let o={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},s=this.getAuthHeaders(o.headers),a={...o,headers:s,credentials:this.needsCredentials(s)?"include":void 0};this.emit("request",`${this.apiUrl}${P}/${encodeURIComponent(e)}`,a);try{let f=await fetch(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,a);f.ok||await this.handleResponseError(f,"Set Domain");let D=this.safeClone(f),E=this.safeClone(f);return this.emit("response",D,`${this.apiUrl}${P}/${encodeURIComponent(e)}`),{...await this.parseResponse(E),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${P}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${P}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${at}`,{method:"GET"},"Get Account")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t&&t.length>0&&(i.tags=t),await this.request(`${this.apiUrl}${De}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${De}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${De}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let r={files:e.map(s=>s.path),index:i};return(await this.request(`${this.apiUrl}${pt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw S.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw S.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(y()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(y()==="node"){let{body:i,headers:r}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:r}}else throw S.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let i=new FormData,r=[];for(let o of e){if(!(o.content instanceof File||o.content instanceof Blob))throw S.ShipError.file(`Unsupported file.content type for browser FormData: ${o.path}`,o.path);let s=this.getBrowserContentType(o.content instanceof File?o.content:o.path),a=new File([o.content],o.path,{type:s});i.append("files[]",a),r.push(o.md5)}return i.append("checksums",JSON.stringify(r)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:r}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),s=new i,a=[];for(let p of e){let m=oe(p.path),d;if(Buffer.isBuffer(p.content))d=new r([p.content],p.path,{type:m});else if(typeof Blob<"u"&&p.content instanceof Blob)d=new r([p.content],p.path,{type:m});else throw S.ShipError.file(`Unsupported file.content type for Node.js FormData: ${p.path}`,p.path);let C=p.path.startsWith("/")?p.path:"/"+p.path;s.append("files[]",d,C),a.push(p.md5)}s.append("checksums",JSON.stringify(a)),t&&t.length>0&&s.append("tags",JSON.stringify(t));let f=new o(s),D=[];for await(let p of f.encode())D.push(Buffer.from(p));let E=Buffer.concat(D);return{body:E,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(E).toString()}}}getBrowserContentType(e){return typeof e=="string"?oe(e):e.type||oe(e.name)}};M();var ze=require("@shipstatic/types");T();async function ft(n){let e=y();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(pe(),_e));return t(n)}else return{}}function q(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||ze.DEFAULT_API,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function G(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}var ve=require("@shipstatic/types");J();async function ut(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await b(t);return{path:ve.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:i}}async function Ue(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===ve.DEPLOYMENT_CONFIG_FILENAME))return n;try{if(await e.checkSPA(n)){let r=await ut();return[...n,r]}}catch{}return n}function Y(n,e,t,i){return{create:async(r,o={})=>{t&&await t();let s=e?G(o,e):o,a=n();if(!i)throw new Error("processInput function is not provided.");let f=await i(r,s);return f=await Ue(f,a,s),await a.deploy(f,s)},list:async()=>(t&&await t(),n().listDeployments()),remove:async r=>{t&&await t(),await n().removeDeployment(r)},get:async r=>(t&&await t(),n().getDeployment(r))}}function W(n,e){return{set:async(t,i,r)=>(e&&await e(),n().setDomain(t,i,r)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function X(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function Z(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var V=class{constructor(e={}){this.initPromise=null;this._config=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new A({...e,...t});let i=()=>this.ensureInitialized(),r=()=>this.http;this._deployments=Y(r,this.clientOptions,i,(o,s)=>this.processInput(o,s)),this._domains=W(r,i),this._account=X(r,i),this._tokens=Z(r,i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=I(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}};var he=require("@shipstatic/types");T();pe();M();var c={};z(c,{ApiHttp:()=>A,DEFAULT_API:()=>le.DEFAULT_API,FILE_VALIDATION_STATUS:()=>u,JUNK_DIRECTORIES:()=>ce,Ship:()=>V,ShipError:()=>O.ShipError,ShipErrorType:()=>O.ShipErrorType,__setTestEnvironment:()=>H,allValidFilesReady:()=>Ae,calculateMD5:()=>b,createAccountResource:()=>X,createDeploymentResource:()=>Y,createDomainResource:()=>W,createTokenResource:()=>Z,filterJunk:()=>L,formatFileSize:()=>j,getENV:()=>y,getValidFiles:()=>ue,loadConfig:()=>ft,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>_,pluralize:()=>Te,resolveConfig:()=>q,validateFiles:()=>Re});var g={};l(g,require("@shipstatic/types"));l(c,g);var le=require("@shipstatic/types");J();function Te(n,e,t,i=!0){let r=n===1?e:t;return i?`${n} ${r}`:r}fe();de();T();var xe=v(require("mime-db"),1),yt=new Set(Object.keys(xe.default)),gt=new Map(Object.entries(xe.default).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)])),u={PENDING:"pending",PROCESSING_ERROR:"processing_error",EMPTY_FILE:"empty_file",VALIDATION_FAILED:"validation_failed",READY:"ready"};function j(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,r)).toFixed(e))+" "+i[r]}function Et(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],r=gt.get(e);if(r&&!r.has(i))return!1}return!0}function Re(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(s=>({...s,status:u.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let r=0;for(let o of n){let s=u.READY,a="Ready for upload";o.status===u.PROCESSING_ERROR?(s=u.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(s=u.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("..")?(s=u.VALIDATION_FAILED,a="Invalid file name. File name contains invalid characters",t.push(`${o.name}: ${a}`)):o.name.includes("\0")?(s=u.VALIDATION_FAILED,a="Invalid file name. File name contains invalid characters",t.push(`${o.name}: ${a}`)):o.size<=0?(s=u.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(s=u.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):e.allowedMimeTypes.some(f=>o.type.startsWith(f))?yt.has(o.type)?Et(o.name,o.type)?o.size>e.maxFileSize?(s=u.VALIDATION_FAILED,a=`File size (${j(o.size)}) exceeds limit of ${j(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(r+=o.size,r>e.maxTotalSize&&(s=u.VALIDATION_FAILED,a=`Total size would exceed limit of ${j(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(s=u.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(s=u.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):(s=u.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)),i.push({...o,status:s,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==u.READY&&a.status!==u.PENDING),s="Validation Failed";return o?.status===u.PROCESSING_ERROR?s="Processing Error":o?.status===u.EMPTY_FILE?s="Empty File":o?.statusMessage?.includes("File name cannot be empty")||o?.statusMessage?.includes("Invalid file name")?s="Invalid File Name":o?.statusMessage?.includes("File size must be positive")?s="Invalid File Size":o?.statusMessage?.includes("MIME type is required")?s="Missing MIME Type":o?.statusMessage?.includes("Invalid MIME type")?s="Invalid MIME Type":o?.statusMessage?.includes("not allowed")?s="Invalid File Type":o?.statusMessage?.includes("extension does not match")?s="Extension Mismatch":o?.statusMessage?.includes("Total size")?s="Total Size Exceeded":o?.statusMessage?.includes("exceeds limit")&&(s="File Too Large"),{files:i.map(a=>({...a,status:u.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function ue(n){return n.filter(e=>e.status===u.READY)}function Ae(n){return ue(n).length>0}var O=require("@shipstatic/types");l(h,c);pe();M();M();Ie();T();var ee=class extends V{constructor(e={}){if(y()!=="node")throw he.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return q(e,{})}async loadFullConfig(){try{let e=await K(this.clientOptions.configFile),t=q(this.clientOptions,e),i=new A({...this.clientOptions,...t});this.replaceHttpClient(i);let r=await this.http.getConfig();U(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw he.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw he.ShipError.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Xe(),We));return i(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Oe=ee;l(te,h,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,FILE_VALIDATION_STATUS,JUNK_DIRECTORIES,Ship,ShipError,ShipErrorType,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,filterJunk,formatFileSize,getCurrentConfig,getENV,getValidFiles,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setConfig,setPlatformConfig,validateFiles});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|