@shipstatic/ship 0.2.8 → 0.3.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 +29 -29
- package/dist/browser.d.ts +19 -19
- package/dist/browser.js +3 -3
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +27 -27
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.bash +3 -3
- package/dist/completions/ship.fish +6 -6
- package/dist/completions/ship.zsh +5 -5
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -19
- package/dist/index.d.ts +19 -19
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -38,7 +38,7 @@ _ship_completions() {
|
|
|
38
38
|
;;
|
|
39
39
|
esac
|
|
40
40
|
;;
|
|
41
|
-
"
|
|
41
|
+
"domains")
|
|
42
42
|
case "${COMP_WORDS[2]}" in
|
|
43
43
|
"set")
|
|
44
44
|
if [[ ${COMP_CWORD} -eq 4 ]]; then
|
|
@@ -49,7 +49,7 @@ _ship_completions() {
|
|
|
49
49
|
;;
|
|
50
50
|
"get"|"remove")
|
|
51
51
|
if [[ ${COMP_CWORD} -eq 3 ]]; then
|
|
52
|
-
# Would ideally complete
|
|
52
|
+
# Would ideally complete domain names, but keep simple
|
|
53
53
|
COMPREPLY=()
|
|
54
54
|
return
|
|
55
55
|
fi
|
|
@@ -94,7 +94,7 @@ _ship_completions() {
|
|
|
94
94
|
|
|
95
95
|
# Top-level commands
|
|
96
96
|
if [[ ${COMP_CWORD} -eq 1 ]]; then
|
|
97
|
-
completions="ping whoami deployments
|
|
97
|
+
completions="ping whoami deployments domains account completion"
|
|
98
98
|
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
99
99
|
return
|
|
100
100
|
fi
|
|
@@ -34,7 +34,7 @@ end
|
|
|
34
34
|
complete -c ship -f -n '__fish_use_subcommand' -a 'ping' -d 'Check API connectivity'
|
|
35
35
|
complete -c ship -f -n '__fish_use_subcommand' -a 'whoami' -d 'Get current account information'
|
|
36
36
|
complete -c ship -f -n '__fish_use_subcommand' -a 'deployments' -d 'Manage deployments'
|
|
37
|
-
complete -c ship -f -n '__fish_use_subcommand' -a '
|
|
37
|
+
complete -c ship -f -n '__fish_use_subcommand' -a 'domains' -d 'Manage domains'
|
|
38
38
|
complete -c ship -f -n '__fish_use_subcommand' -a 'account' -d 'Manage account'
|
|
39
39
|
complete -c ship -f -n '__fish_use_subcommand' -a 'completion' -d 'Setup shell completion'
|
|
40
40
|
|
|
@@ -57,11 +57,11 @@ complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'remove' -d
|
|
|
57
57
|
complete -c ship -l no-path-detect -d 'Disable automatic path optimization and flattening'
|
|
58
58
|
complete -c ship -l no-spa-detect -d 'Disable automatic SPA detection and configuration'
|
|
59
59
|
|
|
60
|
-
#
|
|
61
|
-
complete -c ship -f -n '__fish_seen_subcommand_from
|
|
62
|
-
complete -c ship -f -n '__fish_seen_subcommand_from
|
|
63
|
-
complete -c ship -f -n '__fish_seen_subcommand_from
|
|
64
|
-
complete -c ship -f -n '__fish_seen_subcommand_from
|
|
60
|
+
# Domains subcommands
|
|
61
|
+
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'list' -d 'List all domains'
|
|
62
|
+
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'get' -d 'Show domain information'
|
|
63
|
+
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'set' -d 'Create or update domain pointing to deployment'
|
|
64
|
+
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'remove' -d 'Delete domain permanently'
|
|
65
65
|
|
|
66
66
|
# Account subcommands
|
|
67
67
|
complete -c ship -f -n '__fish_seen_subcommand_from account' -a 'get' -d 'Show account information'
|
|
@@ -47,7 +47,7 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
47
47
|
;;
|
|
48
48
|
esac
|
|
49
49
|
;;
|
|
50
|
-
"
|
|
50
|
+
"domains")
|
|
51
51
|
case "${words[3]}" in
|
|
52
52
|
"set")
|
|
53
53
|
if [[ $CURRENT -eq 5 ]]; then
|
|
@@ -57,14 +57,14 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
57
57
|
;;
|
|
58
58
|
"get"|"remove")
|
|
59
59
|
if [[ $CURRENT -eq 4 ]]; then
|
|
60
|
-
# Would ideally complete
|
|
60
|
+
# Would ideally complete domain names, but keep simple
|
|
61
61
|
return
|
|
62
62
|
fi
|
|
63
63
|
;;
|
|
64
64
|
*)
|
|
65
65
|
if [[ $CURRENT -eq 3 ]]; then
|
|
66
|
-
completions=("list:List all
|
|
67
|
-
_describe '
|
|
66
|
+
completions=("list:List all domains" "get:Show domain information" "set:Create or update domain pointing to deployment" "remove:Delete domain permanently")
|
|
67
|
+
_describe 'domains commands' completions
|
|
68
68
|
return
|
|
69
69
|
fi
|
|
70
70
|
;;
|
|
@@ -101,7 +101,7 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
101
101
|
|
|
102
102
|
# Top-level commands
|
|
103
103
|
if [[ $CURRENT -eq 2 ]]; then
|
|
104
|
-
completions=("ping:Check API connectivity" "whoami:Get current account information" "deployments:Manage deployments" "
|
|
104
|
+
completions=("ping:Check API connectivity" "whoami:Get current account information" "deployments:Manage deployments" "domains:Manage domains" "account:Manage account" "completion:Setup shell completion")
|
|
105
105
|
_describe 'commands' completions
|
|
106
106
|
return
|
|
107
107
|
fi
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var He=Object.create;var te=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var x=(o,e)=>()=>(o&&(e=o(o=0)),e);var I=(o,e)=>{for(var t in e)te(o,t,{get:e[t],enumerable:!0})},ee=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Je(e))!We.call(o,i)&&i!==t&&te(o,i,{get:()=>e[i],enumerable:!(n=Ge(e,i))||n.enumerable});return o},p=(o,e,t)=>(ee(o,e,"default"),t&&ee(t,e,"default")),A=(o,e,t)=>(t=o!=null?He(Ve(o)):{},ee(e||!o||!o.__esModule?te(t,"default",{value:o,enumerable:!0}):t,o)),Ye=o=>ee(te({},"__esModule",{value:!0}),o);var Ae={};I(Ae,{__setTestEnvironment:()=>j,getENV:()=>h});function j(o){de=o}function Xe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function h(){return de||Xe()}var de,C=x(()=>{"use strict";de=null});var Re={};I(Re,{loadConfig:()=>L});function De(o){try{return tt.parse(o)}catch(e){if(e instanceof z.z.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw re.ShipError.config(`Configuration validation failed${n}: ${t.message}`)}throw re.ShipError.config("Configuration validation failed")}}async function ot(o){try{if(h()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(ye,{searchPlaces:[`.${ye}rc`,"package.json",`${t.homedir()}/.${ye}rc`],stopDir:t.homedir()}),i;if(o?i=n.load(o):i=n.search(),i&&i.config)return De(i.config)}catch(e){if(e instanceof re.ShipError)throw e}return{}}async function L(o){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 ot(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return De(n)}var z,re,ye,tt,se=x(()=>{"use strict";z=require("zod"),re=require("@shipstatic/types");C();ye="ship",tt=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict()});async function it(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let r=Math.ceil(o.size/2097152),s=0,c=new e.ArrayBuffer,f=new FileReader,S=()=>{let g=s*2097152,a=Math.min(g+2097152,o.size);f.readAsArrayBuffer(o.slice(g,a))};f.onload=g=>{let a=g.target?.result;if(!a){n(O.ShipError.business("Failed to read file chunk"));return}c.append(a),s++,s<r?S():t({md5:c.end()})},f.onerror=()=>{n(O.ShipError.business("Failed to calculate MD5: FileReader error"))},S()})}async function rt(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",c=>i(O.ShipError.business(`Failed to read file for MD5: ${c.message}`))),s.on("data",c=>r.update(c)),s.on("end",()=>n({md5:r.digest("hex")}))})}async function R(o){let e=h();if(e==="browser"){if(!(o instanceof Blob))throw O.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return it(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw O.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return rt(o)}throw O.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var O,G=x(()=>{"use strict";C();O=require("@shipstatic/types")});function _(o){we=o}function U(){if(we===null)throw $e.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return we}var $e,we,q=x(()=>{"use strict";$e=require("@shipstatic/types"),we=null});function B(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if((0,Oe.isJunk)(n))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 Oe,pe,le=x(()=>{"use strict";Oe=require("junk"),pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(o){if(!o||o.length===0)return"";let e=o.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)),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i;r++){let s=t[0][r];if(t.every(c=>c[r]===s))n.push(s);else break}return n.join("/")}function ce(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=x(()=>{"use strict"});function N(o,e={}){if(e.flatten===!1)return o.map(n=>({path:ce(n),name:Pe(n)}));let t=at(o);return o.map(n=>{let i=ce(n);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=Pe(n)),{path:i,name:Pe(n)}})}function at(o){if(!o.length)return"";let t=o.map(r=>ce(r)).map(r=>r.split("/")),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i-1;r++){let s=t[0][r];if(t.every(c=>c[r]===s))n.push(s);else break}return n.join("/")}function Pe(o){return o.split(/[/\\]/).pop()||o}var fe=x(()=>{"use strict";ve()});function Be(o){let e=[];try{let t=k.readdirSync(o);for(let n of t){let i=P.join(o,n),r=k.statSync(i);if(r.isDirectory()){let s=Be(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function X(o,e={}){if(h()!=="node")throw $.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(m=>{let u=P.resolve(m);try{return k.statSync(u).isDirectory()?Be(u):[u]}catch{throw $.ShipError.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=B(n);if(i.length===0)return[];let r=o.map(m=>P.resolve(m)),s=Ue(r.map(m=>{try{return k.statSync(m).isDirectory()?m:P.dirname(m)}catch{return P.dirname(m)}})),c=i.map(m=>{if(s&&s.length>0){let u=P.relative(s,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return P.basename(m)}),f=N(c,{flatten:e.pathDetect!==!1}),S=[],g=0,a=U();for(let m=0;m<i.length;m++){let u=i[m],F=f[m].path;try{let T=k.statSync(u);if(T.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(T.size>a.maxFileSize)throw $.ShipError.business(`File ${u} is too large. Maximum allowed size is ${a.maxFileSize/(1024*1024)}MB.`);if(g+=T.size,g>a.maxTotalSize)throw $.ShipError.business(`Total deploy size is too large. Maximum allowed is ${a.maxTotalSize/(1024*1024)}MB.`);let ue=k.readFileSync(u),{md5:je}=await R(ue);if(F.includes("\0")||F.includes("/../")||F.startsWith("../")||F.endsWith("/.."))throw $.ShipError.business(`Security error: Unsafe file path "${F}" for file: ${u}`);S.push({path:F,content:ue,size:ue.length,md5:je})}catch(T){if(T instanceof $.ShipError&&T.isClientError&&T.isClientError())throw T;console.error(`Could not process file ${u}:`,T)}}if(S.length>a.maxFilesCount)throw $.ShipError.business(`Too many files to deploy. Maximum allowed is ${a.maxFilesCount} files.`);return S}var $,k,P,Ce=x(()=>{"use strict";C();G();le();$=require("@shipstatic/types");q();fe();ve();k=A(require("fs"),1),P=A(require("path"),1)});async function Ne(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(C(),Ae));if(t()!=="browser")throw Ee.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(o)?o:Array.from(o),i=n.map(a=>a.webkitRelativePath||a.name),r=N(i,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<n.length;a++){let m=n[a],u=r[a].path;if(u.includes("..")||u.includes("\0"))throw Ee.ShipError.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);s.push({file:m,relativePath:u})}let c=s.map(a=>a.relativePath),f=B(c),S=new Set(f),g=[];for(let a of s){if(!S.has(a.relativePath))continue;let{md5:m}=await R(a.file);g.push({content:a.file,path:a.relativePath,size:a.file.size,md5:m})}return g}var Ee,Ie=x(()=>{"use strict";G();Ee=require("@shipstatic/types");le();fe()});var _e={};I(_e,{convertBrowserInput:()=>Me,convertDeployInput:()=>pt,convertNodeInput:()=>Fe});function ze(o,e={}){let t=U();if(!e.skipEmptyCheck&&o.length===0)throw v.ShipError.business("No files to deploy.");if(o.length>t.maxFilesCount)throw v.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let n=0;for(let i of o){if(i.size>t.maxFileSize)throw v.ShipError.business(`File ${i.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(n+=i.size,n>t.maxTotalSize)throw v.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Le(o,e){if(e==="node"){if(!Array.isArray(o))throw v.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw v.ShipError.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw v.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw v.ShipError.business("No files selected in HTMLInputElement")}function Ke(o){let e=o.map(t=>({name:t.path,size:t.size}));return ze(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function Fe(o,e={}){Le(o,"node");let t=await X(o,e);return Ke(t)}async function Me(o,e={}){Le(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw v.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw v.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),ze(t);let n=await Ne(t,e);return Ke(n)}async function pt(o,e={},t){let n=h();if(n!=="node"&&n!=="browser")throw v.ShipError.business("Unsupported execution environment.");let i;if(n==="node")if(typeof o=="string")i=await Fe([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))i=await Fe(o,e);else throw v.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await Me(o,e);return i}var v,qe=x(()=>{"use strict";v=require("@shipstatic/types");C();Ce();Ie();q()});var Q={};I(Q,{ApiHttp:()=>D,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Z,ShipError:()=>b.ShipError,ShipErrorType:()=>b.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>R,createAccountResource:()=>W,createAliasResource:()=>V,createDeploymentResource:()=>J,createTokenResource:()=>Y,default:()=>xe,filterJunk:()=>B,getCurrentConfig:()=>U,getENV:()=>h,loadConfig:()=>L,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>N,pluralize:()=>Se,processFilesForNode:()=>X,resolveConfig:()=>K,setConfig:()=>_,setPlatformConfig:()=>_});module.exports=Ye(Q);var d={};I(d,{ApiHttp:()=>D,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Z,ShipError:()=>b.ShipError,ShipErrorType:()=>b.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>R,createAccountResource:()=>W,createAliasResource:()=>V,createDeploymentResource:()=>J,createTokenResource:()=>Y,default:()=>xe,filterJunk:()=>B,getCurrentConfig:()=>U,getENV:()=>h,loadConfig:()=>L,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>N,pluralize:()=>Se,processFilesForNode:()=>X,resolveConfig:()=>K,setConfig:()=>_,setPlatformConfig:()=>_});var ie=A(require("mime-types"),1),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 n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let r of i)try{r(...t)}catch(s){n.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,n)=>{t.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};C();var ne="/deployments",Te="/ping",E="/aliases",Ze="/config",Qe="/account",he="/tokens",et="/spa-check",D=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={},n){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,n);let c=this.safeClone(s),f=this.safeClone(s);return this.emit("response",c,e),await this.parseResponse(f)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,n),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 n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${t} failed due to API error`;throw e.status===401?w.ShipError.authentication(i):w.ShipError.api(i,e.status,n.code,n)}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}${Te}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Te}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Ze}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:n,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:n,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ne}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ne}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ne}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ne}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t,n){let i={deployment:t};n&&n.length>0&&(i.tags=n);let r={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},s=this.getAuthHeaders(r.headers),c={...r,headers:s,credentials:this.needsCredentials(s)?"include":void 0};this.emit("request",`${this.apiUrl}${E}/${encodeURIComponent(e)}`,c);try{let f=await fetch(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,c);f.ok||await this.handleResponseError(f,"Set Alias");let S=this.safeClone(f),g=this.safeClone(f);return this.emit("response",S,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),{...await this.parseResponse(g),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Alias"),f}}async getAlias(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.request(`${this.apiUrl}${E}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async confirmAlias(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Alias")}async getAliasDns(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Alias DNS")}async getAliasRecords(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Alias Records")}async getAliasShare(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Alias Share")}async getAccount(){return await this.request(`${this.apiUrl}${Qe}`,{method:"GET"},"Get Account")}async createToken(e,t){let n={};return e!==void 0&&(n.ttl=e),t&&t.length>0&&(n.tags=t),await this.request(`${this.apiUrl}${he}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${he}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${he}/${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 n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${et}`,{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:n,headers:i}=await this.createNodeBody(e,t);return{requestBody:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),requestHeaders:i}}else throw w.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let n=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),c=new File([r.content],r.path,{type:s});n.append("files[]",c),i.push(r.md5)}return n.append("checksums",JSON.stringify(i)),t&&t.length>0&&n.append("tags",JSON.stringify(t)),n}async createNodeBody(e,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),s=new n,c=[];for(let a of e){let m=ie.lookup(a.path)||"application/octet-stream",u;if(Buffer.isBuffer(a.content))u=new i([a.content],a.path,{type:m});else if(typeof Blob<"u"&&a.content instanceof Blob)u=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 F=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",u,F),c.push(a.md5)}s.append("checksums",JSON.stringify(c)),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"?ie.lookup(e)||"application/octet-stream":ie.lookup(e.name)||e.type||"application/octet-stream"}};var ke=require("@shipstatic/types");C();async function nt(o){let e=h();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(se(),Re));return t(o)}else return{}}function K(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||ke.DEFAULT_API,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function H(o,e){let t={...o};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 ge=require("@shipstatic/types");G();async function st(){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:n}=await R(t);return{path:ge.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:n}}async function be(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===ge.DEPLOYMENT_CONFIG_FILENAME))return o;try{if(await e.checkSPA(o)){let i=await st();return[...o,i]}}catch{}return o}function J(o,e,t,n){return{create:async(i,r={})=>{t&&await t();let s=e?H(r,e):r,c=o();if(!n)throw new Error("processInput function is not provided.");let f=await n(i,s);return f=await be(f,c,s),await c.deploy(f,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async i=>{t&&await t(),await o().removeDeployment(i)},get:async i=>(t&&await t(),o().getDeployment(i))}}function V(o,e){return{set:async(t,n,i)=>(e&&await e(),o().setAlias(t,n,i)),get:async t=>(e&&await e(),o().getAlias(t)),list:async()=>(e&&await e(),o().listAliases()),remove:async t=>{e&&await e(),await o().removeAlias(t)},confirm:async t=>(e&&await e(),o().confirmAlias(t)),dns:async t=>(e&&await e(),o().getAliasDns(t)),records:async t=>(e&&await e(),o().getAliasRecords(t)),share:async t=>(e&&await e(),o().getAliasShare(t))}}function W(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}function Y(o,e){return{create:async(t,n)=>(e&&await e(),o().createToken(t,n)),list:async()=>(e&&await e(),o().listTokens()),remove:async t=>{e&&await e(),await o().removeToken(t)}}}var M=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new D({...e,...t});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=J(i,this.clientOptions,n,(r,s)=>this.processInput(r,s)),this._aliases=V(i,n),this._account=W(i,n),this._tokens=Y(i,n)}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 aliases(){return this._aliases}get account(){return this._account}get tokens(){return this._tokens}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");C();se();q();var l={};I(l,{ApiHttp:()=>D,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>M,ShipError:()=>b.ShipError,ShipErrorType:()=>b.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>R,createAccountResource:()=>W,createAliasResource:()=>V,createDeploymentResource:()=>J,createTokenResource:()=>Y,filterJunk:()=>B,getENV:()=>h,loadConfig:()=>nt,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>N,pluralize:()=>Se,resolveConfig:()=>K});var y={};p(y,require("@shipstatic/types"));p(l,y);var ae=require("@shipstatic/types");G();function Se(o,e,t,n=!0){let i=o===1?e:t;return n?`${o} ${i}`:i}le();fe();C();var b=require("@shipstatic/types");p(d,l);se();q();q();Ce();C();var Z=class extends M{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 K(e,{})}async loadFullConfig(){try{let e=await L(this.clientOptions.configFile),t=K(this.clientOptions,e),n=new D({...this.clientOptions,...t});this.replaceHttpClient(n);let i=await this.http.getConfig();_(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:n}=await Promise.resolve().then(()=>(qe(),_e));return n(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},xe=Z;p(Q,d,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,JUNK_DIRECTORIES,Ship,ShipError,ShipErrorType,__setTestEnvironment,calculateMD5,createAccountResource,createAliasResource,createDeploymentResource,createTokenResource,filterJunk,getCurrentConfig,getENV,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setConfig,setPlatformConfig});
|
|
1
|
+
"use strict";var He=Object.create;var te=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var F=(o,e)=>()=>(o&&(e=o(o=0)),e);var I=(o,e)=>{for(var t in e)te(o,t,{get:e[t],enumerable:!0})},ee=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Je(e))!We.call(o,i)&&i!==t&&te(o,i,{get:()=>e[i],enumerable:!(n=Ge(e,i))||n.enumerable});return o},p=(o,e,t)=>(ee(o,e,"default"),t&&ee(t,e,"default")),x=(o,e,t)=>(t=o!=null?He(Ve(o)):{},ee(e||!o||!o.__esModule?te(t,"default",{value:o,enumerable:!0}):t,o)),Ye=o=>ee(te({},"__esModule",{value:!0}),o);var xe={};I(xe,{__setTestEnvironment:()=>j,getENV:()=>h});function j(o){ue=o}function Xe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function h(){return ue||Xe()}var ue,P=F(()=>{"use strict";ue=null});var ke={};I(ke,{loadConfig:()=>L});function Re(o){try{return tt.parse(o)}catch(e){if(e instanceof z.z.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw re.ShipError.config(`Configuration validation failed${n}: ${t.message}`)}throw re.ShipError.config("Configuration validation failed")}}async function ot(o){try{if(h()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(ye,{searchPlaces:[`.${ye}rc`,"package.json",`${t.homedir()}/.${ye}rc`],stopDir:t.homedir()}),i;if(o?i=n.load(o):i=n.search(),i&&i.config)return Re(i.config)}catch(e){if(e instanceof re.ShipError)throw e}return{}}async function L(o){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 ot(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Re(n)}var z,re,ye,tt,se=F(()=>{"use strict";z=require("zod"),re=require("@shipstatic/types");P();ye="ship",tt=z.z.object({apiUrl:z.z.string().url().optional(),apiKey:z.z.string().optional(),deployToken:z.z.string().optional()}).strict()});async function it(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let r=Math.ceil(o.size/2097152),s=0,l=new e.ArrayBuffer,f=new FileReader,S=()=>{let g=s*2097152,a=Math.min(g+2097152,o.size);f.readAsArrayBuffer(o.slice(g,a))};f.onload=g=>{let a=g.target?.result;if(!a){n(A.ShipError.business("Failed to read file chunk"));return}l.append(a),s++,s<r?S():t({md5:l.end()})},f.onerror=()=>{n(A.ShipError.business("Failed to calculate MD5: FileReader error"))},S()})}async function rt(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",l=>i(A.ShipError.business(`Failed to read file for MD5: ${l.message}`))),s.on("data",l=>r.update(l)),s.on("end",()=>n({md5:r.digest("hex")}))})}async function k(o){let e=h();if(e==="browser"){if(!(o instanceof Blob))throw A.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return it(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw A.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return rt(o)}throw A.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var A,G=F(()=>{"use strict";P();A=require("@shipstatic/types")});function _(o){we=o}function U(){if(we===null)throw Oe.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return we}var Oe,we,q=F(()=>{"use strict";Oe=require("@shipstatic/types"),we=null});function N(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if((0,Ae.isJunk)(n))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 Ae,pe,ce=F(()=>{"use strict";Ae=require("junk"),pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(o){if(!o||o.length===0)return"";let e=o.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)),n=[],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))n.push(s);else break}return n.join("/")}function le(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var De=F(()=>{"use strict"});function B(o,e={}){if(e.flatten===!1)return o.map(n=>({path:le(n),name:ve(n)}));let t=at(o);return o.map(n=>{let i=le(n);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=ve(n)),{path:i,name:ve(n)}})}function at(o){if(!o.length)return"";let t=o.map(r=>le(r)).map(r=>r.split("/")),n=[],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))n.push(s);else break}return n.join("/")}function ve(o){return o.split(/[/\\]/).pop()||o}var fe=F(()=>{"use strict";De()});function Ne(o){let e=[];try{let t=b.readdirSync(o);for(let n of t){let i=v.join(o,n),r=b.statSync(i);if(r.isDirectory()){let s=Ne(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function X(o,e={}){if(h()!=="node")throw O.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(m=>{let d=v.resolve(m);try{return b.statSync(d).isDirectory()?Ne(d):[d]}catch{throw O.ShipError.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=N(n);if(i.length===0)return[];let r=o.map(m=>v.resolve(m)),s=Ue(r.map(m=>{try{return b.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=B(l,{flatten:e.pathDetect!==!1}),S=[],g=0,a=U();for(let m=0;m<i.length;m++){let d=i[m],E=f[m].path;try{let T=b.statSync(d);if(T.size===0){console.warn(`Skipping empty file: ${d}`);continue}if(T.size>a.maxFileSize)throw O.ShipError.business(`File ${d} is too large. Maximum allowed size is ${a.maxFileSize/(1024*1024)}MB.`);if(g+=T.size,g>a.maxTotalSize)throw O.ShipError.business(`Total deploy size is too large. Maximum allowed is ${a.maxTotalSize/(1024*1024)}MB.`);let de=b.readFileSync(d),{md5:je}=await k(de);if(E.includes("\0")||E.includes("/../")||E.startsWith("../")||E.endsWith("/.."))throw O.ShipError.business(`Security error: Unsafe file path "${E}" for file: ${d}`);S.push({path:E,content:de,size:de.length,md5:je})}catch(T){if(T instanceof O.ShipError&&T.isClientError&&T.isClientError())throw T;console.error(`Could not process file ${d}:`,T)}}if(S.length>a.maxFilesCount)throw O.ShipError.business(`Too many files to deploy. Maximum allowed is ${a.maxFilesCount} files.`);return S}var O,b,v,Pe=F(()=>{"use strict";P();G();ce();O=require("@shipstatic/types");q();fe();De();b=x(require("fs"),1),v=x(require("path"),1)});async function Be(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(P(),xe));if(t()!=="browser")throw Ce.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(o)?o:Array.from(o),i=n.map(a=>a.webkitRelativePath||a.name),r=B(i,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<n.length;a++){let m=n[a],d=r[a].path;if(d.includes("..")||d.includes("\0"))throw Ce.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=N(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 Ce,Ie=F(()=>{"use strict";G();Ce=require("@shipstatic/types");ce();fe()});var _e={};I(_e,{convertBrowserInput:()=>Me,convertDeployInput:()=>pt,convertNodeInput:()=>Ee});function ze(o,e={}){let t=U();if(!e.skipEmptyCheck&&o.length===0)throw D.ShipError.business("No files to deploy.");if(o.length>t.maxFilesCount)throw D.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let n=0;for(let i of o){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(n+=i.size,n>t.maxTotalSize)throw D.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Le(o,e){if(e==="node"){if(!Array.isArray(o))throw D.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw D.ShipError.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw D.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw D.ShipError.business("No files selected in HTMLInputElement")}function Ke(o){let e=o.map(t=>({name:t.path,size:t.size}));return ze(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function Ee(o,e={}){Le(o,"node");let t=await X(o,e);return Ke(t)}async function Me(o,e={}){Le(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw D.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}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),ze(t);let n=await Be(t,e);return Ke(n)}async function pt(o,e={},t){let n=h();if(n!=="node"&&n!=="browser")throw D.ShipError.business("Unsupported execution environment.");let i;if(n==="node")if(typeof o=="string")i=await Ee([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))i=await Ee(o,e);else throw D.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await Me(o,e);return i}var D,qe=F(()=>{"use strict";D=require("@shipstatic/types");P();Pe();Ie();q()});var Q={};I(Q,{ApiHttp:()=>R,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Z,ShipError:()=>$.ShipError,ShipErrorType:()=>$.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>k,createAccountResource:()=>W,createDeploymentResource:()=>J,createDomainResource:()=>V,createTokenResource:()=>Y,default:()=>Fe,filterJunk:()=>N,getCurrentConfig:()=>U,getENV:()=>h,loadConfig:()=>L,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>B,pluralize:()=>Se,processFilesForNode:()=>X,resolveConfig:()=>K,setConfig:()=>_,setPlatformConfig:()=>_});module.exports=Ye(Q);var u={};I(u,{ApiHttp:()=>R,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>Z,ShipError:()=>$.ShipError,ShipErrorType:()=>$.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>k,createAccountResource:()=>W,createDeploymentResource:()=>J,createDomainResource:()=>V,createTokenResource:()=>Y,default:()=>Fe,filterJunk:()=>N,getCurrentConfig:()=>U,getENV:()=>h,loadConfig:()=>L,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>B,pluralize:()=>Se,processFilesForNode:()=>X,resolveConfig:()=>K,setConfig:()=>_,setPlatformConfig:()=>_});var ie=x(require("mime-types"),1),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 n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let r of i)try{r(...t)}catch(s){n.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,n)=>{t.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};P();var ne="/deployments",Te="/ping",C="/domains",Ze="/config",Qe="/account",he="/tokens",et="/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={},n){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,n);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,n),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 n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${t} failed due to API error`;throw e.status===401?w.ShipError.authentication(i):w.ShipError.api(i,e.status,n.code,n)}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}${Te}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Te}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Ze}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:n,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:n,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ne}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ne}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ne}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ne}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,n){let i={deployment:t};n&&n.length>0&&(i.tags=n);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}${Qe}`,{method:"GET"},"Get Account")}async createToken(e,t){let n={};return e!==void 0&&(n.ttl=e),t&&t.length>0&&(n.tags=t),await this.request(`${this.apiUrl}${he}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${he}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${he}/${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 n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${et}`,{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:n,headers:i}=await this.createNodeBody(e,t);return{requestBody:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),requestHeaders:i}}else throw w.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let n=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});n.append("files[]",l),i.push(r.md5)}return n.append("checksums",JSON.stringify(i)),t&&t.length>0&&n.append("tags",JSON.stringify(t)),n}async createNodeBody(e,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),s=new n,l=[];for(let a of e){let m=ie.lookup(a.path)||"application/octet-stream",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"?ie.lookup(e)||"application/octet-stream":ie.lookup(e.name)||e.type||"application/octet-stream"}};var be=require("@shipstatic/types");P();async function nt(o){let e=h();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(se(),ke));return t(o)}else return{}}function K(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||be.DEFAULT_API,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function H(o,e){let t={...o};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 ge=require("@shipstatic/types");G();async function st(){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:n}=await k(t);return{path:ge.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:n}}async function $e(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===ge.DEPLOYMENT_CONFIG_FILENAME))return o;try{if(await e.checkSPA(o)){let i=await st();return[...o,i]}}catch{}return o}function J(o,e,t,n){return{create:async(i,r={})=>{t&&await t();let s=e?H(r,e):r,l=o();if(!n)throw new Error("processInput function is not provided.");let f=await n(i,s);return f=await $e(f,l,s),await l.deploy(f,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async i=>{t&&await t(),await o().removeDeployment(i)},get:async i=>(t&&await t(),o().getDeployment(i))}}function V(o,e){return{set:async(t,n,i)=>(e&&await e(),o().setDomain(t,n,i)),get:async t=>(e&&await e(),o().getDomain(t)),list:async()=>(e&&await e(),o().listDomains()),remove:async t=>{e&&await e(),await o().removeDomain(t)},confirm:async t=>(e&&await e(),o().confirmDomain(t)),dns:async t=>(e&&await e(),o().getDomainDns(t)),records:async t=>(e&&await e(),o().getDomainRecords(t)),share:async t=>(e&&await e(),o().getDomainShare(t))}}function W(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}function Y(o,e){return{create:async(t,n)=>(e&&await e(),o().createToken(t,n)),list:async()=>(e&&await e(),o().listTokens()),remove:async t=>{e&&await e(),await o().removeToken(t)}}}var M=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new R({...e,...t});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=J(i,this.clientOptions,n,(r,s)=>this.processInput(r,s)),this._domains=V(i,n),this._account=W(i,n),this._tokens=Y(i,n)}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}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();q();var c={};I(c,{ApiHttp:()=>R,DEFAULT_API:()=>ae.DEFAULT_API,JUNK_DIRECTORIES:()=>pe,Ship:()=>M,ShipError:()=>$.ShipError,ShipErrorType:()=>$.ShipErrorType,__setTestEnvironment:()=>j,calculateMD5:()=>k,createAccountResource:()=>W,createDeploymentResource:()=>J,createDomainResource:()=>V,createTokenResource:()=>Y,filterJunk:()=>N,getENV:()=>h,loadConfig:()=>nt,mergeDeployOptions:()=>H,optimizeDeployPaths:()=>B,pluralize:()=>Se,resolveConfig:()=>K});var y={};p(y,require("@shipstatic/types"));p(c,y);var ae=require("@shipstatic/types");G();function Se(o,e,t,n=!0){let i=o===1?e:t;return n?`${o} ${i}`:i}ce();fe();P();var $=require("@shipstatic/types");p(u,c);se();q();q();Pe();P();var Z=class extends M{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 K(e,{})}async loadFullConfig(){try{let e=await L(this.clientOptions.configFile),t=K(this.clientOptions,e),n=new R({...this.clientOptions,...t});this.replaceHttpClient(n);let i=await this.http.getConfig();_(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:n}=await Promise.resolve().then(()=>(qe(),_e));return n(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Fe=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});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|