@shipstatic/ship 0.6.1 → 0.6.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/dist/browser.d.ts +3 -2
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +2 -2
- 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 +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -426,13 +426,14 @@ declare const JUNK_DIRECTORIES: readonly ["__MACOSX", ".Trashes", ".fseventsd",
|
|
|
426
426
|
*
|
|
427
427
|
* A path is filtered out if any of these conditions are met:
|
|
428
428
|
* 1. The basename is identified as junk by the 'junk' package (e.g., .DS_Store, Thumbs.db)
|
|
429
|
-
* 2. Any path segment
|
|
429
|
+
* 2. Any path segment starts with a dot (e.g., .env, .git, .htaccess)
|
|
430
|
+
* Exception: `.well-known` is allowed (RFC 8615 — ACME, security.txt, app links)
|
|
430
431
|
* 3. Any path segment exceeds 255 characters (filesystem limit)
|
|
431
432
|
* 4. Any directory segment in the path matches an entry in JUNK_DIRECTORIES (case-insensitive)
|
|
432
433
|
*
|
|
433
434
|
* All path separators are normalized to forward slashes for consistent cross-platform behavior.
|
|
434
435
|
*
|
|
435
|
-
*
|
|
436
|
+
* Dot files are filtered for security — they typically contain sensitive configuration
|
|
436
437
|
* (.env, .git) or are not meant to be served publicly. This matches server-side filtering.
|
|
437
438
|
*
|
|
438
439
|
* @param filePaths - An array of file path strings to filter
|
package/dist/index.d.ts
CHANGED
|
@@ -426,13 +426,14 @@ declare const JUNK_DIRECTORIES: readonly ["__MACOSX", ".Trashes", ".fseventsd",
|
|
|
426
426
|
*
|
|
427
427
|
* A path is filtered out if any of these conditions are met:
|
|
428
428
|
* 1. The basename is identified as junk by the 'junk' package (e.g., .DS_Store, Thumbs.db)
|
|
429
|
-
* 2. Any path segment
|
|
429
|
+
* 2. Any path segment starts with a dot (e.g., .env, .git, .htaccess)
|
|
430
|
+
* Exception: `.well-known` is allowed (RFC 8615 — ACME, security.txt, app links)
|
|
430
431
|
* 3. Any path segment exceeds 255 characters (filesystem limit)
|
|
431
432
|
* 4. Any directory segment in the path matches an entry in JUNK_DIRECTORIES (case-insensitive)
|
|
432
433
|
*
|
|
433
434
|
* All path separators are normalized to forward slashes for consistent cross-platform behavior.
|
|
434
435
|
*
|
|
435
|
-
*
|
|
436
|
+
* Dot files are filtered for security — they typically contain sensitive configuration
|
|
436
437
|
* (.env, .git) or are not meant to be served publicly. This matches server-side filtering.
|
|
437
438
|
*
|
|
438
439
|
* @param filePaths - An array of file path strings to filter
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Re=Object.defineProperty;var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ie=(n,e)=>{for(var t in e)Re(n,t,{get:e[t],enumerable:!0})};function x(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function N(n){let e=n.lastIndexOf(".");if(e===-1||e===n.length-1)return!1;let t=n.slice(e+1).toLowerCase();return Pe.has(t)}function Ye(n){if(!n.startsWith(w))throw l.validation(`API key must start with "${w}"`);if(n.length!==ae)throw l.validation(`API key must be ${ae} characters total (${w} + ${z} hex chars)`);let e=n.slice(w.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`API key must contain ${z} hexadecimal characters after "${w}" prefix`)}function We(n){if(!n.startsWith(T))throw l.validation(`Deploy token must start with "${T}"`);if(n.length!==le)throw l.validation(`Deploy token must be ${le} characters total (${T} + ${H} hex chars)`);let e=n.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`Deploy token must contain ${H} hexadecimal characters after "${T}" prefix`)}function Je(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw l.validation("API URL must not contain a path");if(e.search||e.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(e){throw x(e)?e:l.validation("API URL must be a valid URL")}}function Xe(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function pe(n,e){return n.endsWith(`.${e}`)}function Qe(n,e){return!pe(n,e)}function Ze(n,e){return pe(n,e)?n.slice(0,-(e.length+1)):null}function et(n,e){return`https://${n}.${e||"shipstatic.com"}`}function tt(n){return`https://${n}`}function ot(n){return!n||n.length===0?null:JSON.stringify(n)}function st(n){if(!n)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}var He,Ve,je,f,K,l,Pe,w,z,ae,qe,T,H,le,Ge,V,$,y,nt,it,D=A(()=>{"use strict";He={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ve={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},je={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));K={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},l=class n extends Error{type;status;details;constructor(e,t,i,o){super(t),this.type=e,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let e=this.type===f.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new n(e.error,e.message,e.status,e.details)}static validation(e,t){return new n(f.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(f.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(f.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(f.Authentication,e,401,t)}static business(e,t=400){return new n(f.Business,e,t)}static network(e,t){return new n(f.Network,e,void 0,{cause:t})}static cancelled(e){return new n(f.Cancelled,e)}static file(e,t){return new n(f.File,e,void 0,{filePath:t})}static config(e,t){return new n(f.Config,e,void 0,t)}static api(e,t=500){return new n(f.Api,e,t)}static database(e,t=500){return new n(f.Api,e,t)}static storage(e,t=500){return new n(f.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return K.client.has(this.type)}isNetworkError(){return K.network.has(this.type)}isAuthError(){return K.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(e){return this.type===e}};Pe=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);w="ship-",z=64,ae=w.length+z,qe=4,T="token-",H=64,le=T.length+H,Ge={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},V="ship.json";$="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};nt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},it=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function q(n){j=n}function b(){if(j===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return j}var j,O=A(()=>{"use strict";D();j=null});function ht(n){Y=n}function be(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return Y||be()}var Y,I=A(()=>{"use strict";Y=null});async function Oe(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let s=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,r=new FileReader,u=()=>{let p=a*2097152,d=Math.min(p+2097152,n.size);r.readAsArrayBuffer(n.slice(p,d))};r.onload=p=>{let d=p.target?.result;if(!d){i(l.business("Failed to read file chunk"));return}c.append(d),a++,a<s?u():t({md5:c.end()})},r.onerror=()=>{i(l.business("Failed to calculate MD5: FileReader error"))},u()})}async function ke(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,o)=>{let s=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(l.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>s.update(c)),a.on("end",()=>i({md5:s.digest("hex")}))})}async function _(n){let e=C();if(e==="browser"){if(!(n instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Oe(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ke(n)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var U=A(()=>{"use strict";I();D()});import{isJunk as _e}from"junk";function De(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(_e(i))return!1;for(let s of t)if(s.startsWith(".")||s.length>255)return!1;let o=t.slice(0,-1);for(let s of o)if(Ue.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ue,X=A(()=>{"use strict";Ue=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Se(n){if(!n||n.length===0)return"";let e=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function M(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Q=A(()=>{"use strict"});function Ee(n,e={}){if(e.flatten===!1)return n.map(i=>({path:M(i),name:Z(i)}));let t=Be(n);return n.map(i=>{let o=M(i);if(t){let s=t.endsWith("/")?t:`${t}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=Z(i)),{path:o,name:Z(i)}})}function Be(n){if(!n.length)return"";let t=n.map(s=>M(s)).map(s=>s.split("/")),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o-1;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function Z(n){return n.split(/[/\\]/).pop()||n}var ee=A(()=>{"use strict";Q()});function te(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,o)).toFixed(e))+" "+i[o]}function ne(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function qt(n,e){let t=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return t.push(r),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(r),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let u=y.READY,p="Ready for upload",d=r.name?ne(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===y.PROCESSING_ERROR)u=y.VALIDATION_FAILED,p=r.statusMessage||"File failed during processing",t.push({file:r.name,message:p});else if(r.size===0){u=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:p}),o.push({...r,status:u,statusMessage:p});continue}else r.size<0?(u=y.VALIDATION_FAILED,p="File size must be positive",t.push({file:r.name,message:p})):!r.name||r.name.trim().length===0?(u=y.VALIDATION_FAILED,p="File name cannot be empty",t.push({file:r.name||"(empty)",message:p})):r.name.includes("\0")?(u=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",t.push({file:r.name,message:p})):d.valid?N(r.name)?(u=y.VALIDATION_FAILED,p=`File extension not allowed: "${r.name}"`,t.push({file:r.name,message:p})):r.size>e.maxFileSize?(u=y.VALIDATION_FAILED,p=`File size (${te(r.size)}) exceeds limit of ${te(e.maxFileSize)}`,t.push({file:r.name,message:p})):(s+=r.size,s>e.maxTotalSize&&(u=y.VALIDATION_FAILED,p=`Total size would exceed limit of ${te(e.maxTotalSize)}`,t.push({file:r.name,message:p}))):(u=y.VALIDATION_FAILED,p=d.reason||"Invalid file name",t.push({file:r.name,message:p}));o.push({...r,status:u,statusMessage:p})}t.length>0&&(o=o.map(r=>r.status===y.EXCLUDED?r:{...r,status:y.VALIDATION_FAILED,statusMessage:r.status===y.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(r=>r.status===y.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function Me(n){return n.filter(e=>e.status===y.READY)}function Gt(n){return Me(n).length>0}var ie=A(()=>{"use strict";D()});function Ae(n,e){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${n}" for file: ${e}`)}function ve(n,e){let t=ne(n);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(N(n))throw l.business(`File extension not allowed: "${e}"`)}var oe=A(()=>{"use strict";D();ie()});var we={};Ie(we,{processFilesForNode:()=>xe});import*as E from"fs";import*as S from"path";function Ce(n,e=new Set){let t=[],i=E.realpathSync(n);if(e.has(i))return t;e.add(i);let o=E.readdirSync(n);for(let s of o){let a=S.join(n,s),c=E.statSync(a);if(c.isDirectory()){let r=Ce(a,e);t.push(...r)}else c.isFile()&&t.push(a)}return t}async function xe(n,e={}){if(C()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let g=S.resolve(h);try{return E.statSync(g).isDirectory()?Ce(g):[g]}catch{throw l.file(`Path does not exist: ${h}`,h)}}),i=[...new Set(t)],o=De(i);if(o.length===0)return[];let s=n.map(h=>S.resolve(h)),a=Se(s.map(h=>{try{return E.statSync(h).isDirectory()?h:S.dirname(h)}catch{return S.dirname(h)}})),c=o.map(h=>{if(a&&a.length>0){let g=S.relative(a,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return S.basename(h)}),r=Ee(c,{flatten:e.pathDetect!==!1}),u=[],p=0,d=b();for(let h=0;h<o.length;h++){let g=o[h],P=r[h].path;try{Ae(P,g);let v=E.statSync(g);if(v.size===0)continue;if(ve(P,g),v.size>d.maxFileSize)throw l.business(`File ${g} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(p+=v.size,p>d.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let F=E.readFileSync(g),{md5:Te}=await _(F);u.push({path:P,content:F,size:F.length,md5:Te})}catch(v){if(x(v))throw v;let F=v instanceof Error?v.message:String(v);throw l.file(`Failed to read file "${g}": ${F}`,g)}}if(u.length>d.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return u}var se=A(()=>{"use strict";I();U();X();oe();D();O();ee();Q()});D();var L=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 o=Array.from(i);for(let s of o)try{s(...t)}catch(a){i.delete(s),e!=="error"&&setTimeout(()=>{a instanceof Error?this.emit("error",a,String(e)):this.emit("error",new Error(String(a)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(o=>{e.on(i,o)})})}clear(){this.handlers.clear()}};var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Fe=3e4,R=class extends L{constructor(e){super(),this.apiUrl=e.apiUrl||$,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Fe,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:s,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:s};this.emit("request",e,c);try{let r=await fetch(e,c);return a(),r.ok||await this.handleResponseError(r,i),this.emit("response",this.safeClone(r),e),{data:await this.parseResponse(this.safeClone(r)),status:r.status}}catch(r){a();let u=r instanceof Error?r:new Error(String(r));this.emit("error",u,e),this.handleFetchError(r,i)}}async request(e,t,i){let{data:o}=await this.executeRequest(e,t,i);return o}async requestWithStatus(e,t,i){return this.executeRequest(e,t,i)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);if(e){let o=()=>t.abort();e.addEventListener("abort",o),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(i)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,t){let i={};try{if(e.headers.get("content-type")?.includes("application/json")){let a=await e.json();if(a&&typeof a=="object"){let c=a;typeof c.message=="string"&&(i.message=c.message),typeof c.error=="string"&&(i.error=c.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let o=i.message||i.error||`${t} failed`;throw e.status===401?l.authentication(o):l.api(o,e.status)}handleFetchError(e,t){throw x(e)?e:e instanceof Error&&e.name==="AbortError"?l.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?l.network(`${t} failed: ${e.message}`,e):e instanceof Error?l.business(`${t} failed: ${e.message}`):l.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw l.business("No files to deploy");for(let a of e)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),s={};return t.deployToken?s.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`),t.caller&&(s["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${m.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...s},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let o={};t&&(o.deployment=t),i!==void 0&&(o.labels=i);let{data:s,status:a}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...s,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.labels=t),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let t=e.find(a=>a.path==="index.html"||a.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 o={files:e.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};D();O();D();D();function G(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||$,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 ce(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.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}D();U();async function Ne(){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 _(t);return{path:V,content:t,size:e.length,md5:i}}async function ue(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===V))return n;try{if(await e.checkSPA(n)){let o=await Ne();return[...n,o]}}catch{}return n}function de(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:s}=n;return{create:async(a,c={})=>{await t();let r=o?ce(c,o):c;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw l.config("processInput function is not provided.");let u=e(),p=await i(a,r);return p=await ue(p,u,r),u.deploy(p,r)},list:async()=>(await t(),e().listDeployments()),get:async a=>(await t(),e().getDeployment(a)),set:async(a,c)=>(await t(),e().updateDeploymentLabels(a,c.labels)),remove:async a=>{await t(),await e().removeDeployment(a)}}}function fe(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>(await t(),e().setDomain(i,o.deployment,o.labels)),list:async()=>(await t(),e().listDomains()),get:async i=>(await t(),e().getDomain(i)),remove:async i=>{await t(),await e().removeDomain(i)},verify:async i=>(await t(),e().verifyDomain(i)),validate:async i=>(await t(),e().validateDomain(i)),dns:async i=>(await t(),e().getDomainDns(i)),records:async i=>(await t(),e().getDomainRecords(i)),share:async i=>(await t(),e().getDomainShare(i))}}function me(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function he(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.labels)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}var B=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new R({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=de({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=fe(i),this._account=me(i),this._tokens=he(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=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}setDeployToken(e){if(!e||typeof e!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};D();I();D();I();import{z as k}from"zod";var W="ship",$e=k.object({apiUrl:k.string().url().optional(),apiKey:k.string().optional(),deployToken:k.string().optional()}).strict();function ye(n){try{return $e.parse(n)}catch(e){if(e instanceof k.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${i}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function Le(n){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(W,{searchPlaces:[`.${W}rc`,"package.json",`${t.homedir()}/.${W}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return ye(o.config)}catch(e){if(x(e))throw e}return{}}async function J(n){if(C()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Le(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return ye(i)}O();D();async function ge(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),a=new i,c=[];for(let d of n){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let h=new o([d.content],d.path,{type:"application/octet-stream"});a.append("files[]",h),c.push(d.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let r=new s(a),u=[];for await(let d of r.encode())u.push(Buffer.from(d));let p=Buffer.concat(u);return{body:p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(p).toString()}}}U();function Ut(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}X();ee();I();ie();oe();D();O();se();var re=class extends B{constructor(e={}){if(C()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return G(e,{})}async loadFullConfig(){try{let e=await J(this.clientOptions.configFile),t=G(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new R({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();q(o)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw l.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(se(),we));return o(i,t)}getDeployBodyCreator(){return ge}},Ke=re;export{z as API_KEY_HEX_LENGTH,qe as API_KEY_HINT_LENGTH,w as API_KEY_PREFIX,ae as API_KEY_TOTAL_LENGTH,je as AccountPlan,R as ApiHttp,Ge as AuthMethod,Pe as BLOCKED_EXTENSIONS,$ as DEFAULT_API,V as DEPLOYMENT_CONFIG_FILENAME,H as DEPLOY_TOKEN_HEX_LENGTH,T as DEPLOY_TOKEN_PREFIX,le as DEPLOY_TOKEN_TOTAL_LENGTH,He as DeploymentStatus,Ve as DomainStatus,f as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,Ue as JUNK_DIRECTORIES,nt as LABEL_CONSTRAINTS,it as LABEL_PATTERN,re as Ship,l as ShipError,ht as __setTestEnvironment,Gt as allValidFilesReady,_ as calculateMD5,me as createAccountResource,de as createDeploymentResource,fe as createDomainResource,he as createTokenResource,Ke as default,st as deserializeLabels,Ze as extractSubdomain,De as filterJunk,te as formatFileSize,et as generateDeploymentUrl,tt as generateDomainUrl,b as getCurrentConfig,C as getENV,Me as getValidFiles,N as isBlockedExtension,Qe as isCustomDomain,Xe as isDeployment,pe as isPlatformDomain,x as isShipError,J as loadConfig,ce as mergeDeployOptions,Ee as optimizeDeployPaths,Ut as pluralize,xe as processFilesForNode,G as resolveConfig,ot as serializeLabels,q as setPlatformConfig,Ye as validateApiKey,Je as validateApiUrl,ve as validateDeployFile,Ae as validateDeployPath,We as validateDeployToken,ne as validateFileName,qt as validateFiles};
|
|
1
|
+
var Re=Object.defineProperty;var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ie=(n,e)=>{for(var t in e)Re(n,t,{get:e[t],enumerable:!0})};function w(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function N(n){let e=n.lastIndexOf(".");if(e===-1||e===n.length-1)return!1;let t=n.slice(e+1).toLowerCase();return Pe.has(t)}function Ye(n){if(!n.startsWith(x))throw l.validation(`API key must start with "${x}"`);if(n.length!==ae)throw l.validation(`API key must be ${ae} characters total (${x} + ${z} hex chars)`);let e=n.slice(x.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`API key must contain ${z} hexadecimal characters after "${x}" prefix`)}function We(n){if(!n.startsWith(T))throw l.validation(`Deploy token must start with "${T}"`);if(n.length!==le)throw l.validation(`Deploy token must be ${le} characters total (${T} + ${H} hex chars)`);let e=n.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`Deploy token must contain ${H} hexadecimal characters after "${T}" prefix`)}function Je(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw l.validation("API URL must not contain a path");if(e.search||e.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(e){throw w(e)?e:l.validation("API URL must be a valid URL")}}function Xe(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function pe(n,e){return n.endsWith(`.${e}`)}function Qe(n,e){return!pe(n,e)}function Ze(n,e){return pe(n,e)?n.slice(0,-(e.length+1)):null}function et(n,e){return`https://${n}.${e||"shipstatic.com"}`}function tt(n){return`https://${n}`}function ot(n){return!n||n.length===0?null:JSON.stringify(n)}function st(n){if(!n)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}var He,Ve,je,f,K,l,Pe,x,z,ae,qe,T,H,le,Ge,V,$,y,nt,it,D=A(()=>{"use strict";He={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ve={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},je={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));K={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},l=class n extends Error{type;status;details;constructor(e,t,i,o){super(t),this.type=e,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let e=this.type===f.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new n(e.error,e.message,e.status,e.details)}static validation(e,t){return new n(f.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(f.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(f.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(f.Authentication,e,401,t)}static business(e,t=400){return new n(f.Business,e,t)}static network(e,t){return new n(f.Network,e,void 0,{cause:t})}static cancelled(e){return new n(f.Cancelled,e)}static file(e,t){return new n(f.File,e,void 0,{filePath:t})}static config(e,t){return new n(f.Config,e,void 0,t)}static api(e,t=500){return new n(f.Api,e,t)}static database(e,t=500){return new n(f.Api,e,t)}static storage(e,t=500){return new n(f.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return K.client.has(this.type)}isNetworkError(){return K.network.has(this.type)}isAuthError(){return K.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(e){return this.type===e}};Pe=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);x="ship-",z=64,ae=x.length+z,qe=4,T="token-",H=64,le=T.length+H,Ge={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},V="ship.json";$="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};nt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},it=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function q(n){j=n}function b(){if(j===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return j}var j,O=A(()=>{"use strict";D();j=null});function ht(n){Y=n}function be(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return Y||be()}var Y,I=A(()=>{"use strict";Y=null});async function Oe(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let s=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,r=new FileReader,u=()=>{let p=a*2097152,d=Math.min(p+2097152,n.size);r.readAsArrayBuffer(n.slice(p,d))};r.onload=p=>{let d=p.target?.result;if(!d){i(l.business("Failed to read file chunk"));return}c.append(d),a++,a<s?u():t({md5:c.end()})},r.onerror=()=>{i(l.business("Failed to calculate MD5: FileReader error"))},u()})}async function ke(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,o)=>{let s=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(l.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>s.update(c)),a.on("end",()=>i({md5:s.digest("hex")}))})}async function _(n){let e=C();if(e==="browser"){if(!(n instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Oe(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ke(n)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var U=A(()=>{"use strict";I();D()});import{isJunk as _e}from"junk";function De(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(_e(i))return!1;for(let s of t)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let o=t.slice(0,-1);for(let s of o)if(Ue.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ue,X=A(()=>{"use strict";Ue=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Se(n){if(!n||n.length===0)return"";let e=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function M(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Q=A(()=>{"use strict"});function Ee(n,e={}){if(e.flatten===!1)return n.map(i=>({path:M(i),name:Z(i)}));let t=Be(n);return n.map(i=>{let o=M(i);if(t){let s=t.endsWith("/")?t:`${t}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=Z(i)),{path:o,name:Z(i)}})}function Be(n){if(!n.length)return"";let t=n.map(s=>M(s)).map(s=>s.split("/")),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o-1;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function Z(n){return n.split(/[/\\]/).pop()||n}var ee=A(()=>{"use strict";Q()});function te(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,o)).toFixed(e))+" "+i[o]}function ne(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function qt(n,e){let t=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return t.push(r),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(r),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let u=y.READY,p="Ready for upload",d=r.name?ne(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===y.PROCESSING_ERROR)u=y.VALIDATION_FAILED,p=r.statusMessage||"File failed during processing",t.push({file:r.name,message:p});else if(r.size===0){u=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:p}),o.push({...r,status:u,statusMessage:p});continue}else r.size<0?(u=y.VALIDATION_FAILED,p="File size must be positive",t.push({file:r.name,message:p})):!r.name||r.name.trim().length===0?(u=y.VALIDATION_FAILED,p="File name cannot be empty",t.push({file:r.name||"(empty)",message:p})):r.name.includes("\0")?(u=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",t.push({file:r.name,message:p})):d.valid?N(r.name)?(u=y.VALIDATION_FAILED,p=`File extension not allowed: "${r.name}"`,t.push({file:r.name,message:p})):r.size>e.maxFileSize?(u=y.VALIDATION_FAILED,p=`File size (${te(r.size)}) exceeds limit of ${te(e.maxFileSize)}`,t.push({file:r.name,message:p})):(s+=r.size,s>e.maxTotalSize&&(u=y.VALIDATION_FAILED,p=`Total size would exceed limit of ${te(e.maxTotalSize)}`,t.push({file:r.name,message:p}))):(u=y.VALIDATION_FAILED,p=d.reason||"Invalid file name",t.push({file:r.name,message:p}));o.push({...r,status:u,statusMessage:p})}t.length>0&&(o=o.map(r=>r.status===y.EXCLUDED?r:{...r,status:y.VALIDATION_FAILED,statusMessage:r.status===y.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(r=>r.status===y.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function Me(n){return n.filter(e=>e.status===y.READY)}function Gt(n){return Me(n).length>0}var ie=A(()=>{"use strict";D()});function Ae(n,e){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${n}" for file: ${e}`)}function ve(n,e){let t=ne(n);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(N(n))throw l.business(`File extension not allowed: "${e}"`)}var oe=A(()=>{"use strict";D();ie()});var xe={};Ie(xe,{processFilesForNode:()=>we});import*as E from"fs";import*as S from"path";function Ce(n,e=new Set){let t=[],i=E.realpathSync(n);if(e.has(i))return t;e.add(i);let o=E.readdirSync(n);for(let s of o){let a=S.join(n,s),c=E.statSync(a);if(c.isDirectory()){let r=Ce(a,e);t.push(...r)}else c.isFile()&&t.push(a)}return t}async function we(n,e={}){if(C()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let g=S.resolve(h);try{return E.statSync(g).isDirectory()?Ce(g):[g]}catch{throw l.file(`Path does not exist: ${h}`,h)}}),i=[...new Set(t)],o=De(i);if(o.length===0)return[];let s=n.map(h=>S.resolve(h)),a=Se(s.map(h=>{try{return E.statSync(h).isDirectory()?h:S.dirname(h)}catch{return S.dirname(h)}})),c=o.map(h=>{if(a&&a.length>0){let g=S.relative(a,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return S.basename(h)}),r=Ee(c,{flatten:e.pathDetect!==!1}),u=[],p=0,d=b();for(let h=0;h<o.length;h++){let g=o[h],P=r[h].path;try{Ae(P,g);let v=E.statSync(g);if(v.size===0)continue;if(ve(P,g),v.size>d.maxFileSize)throw l.business(`File ${g} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(p+=v.size,p>d.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let F=E.readFileSync(g),{md5:Te}=await _(F);u.push({path:P,content:F,size:F.length,md5:Te})}catch(v){if(w(v))throw v;let F=v instanceof Error?v.message:String(v);throw l.file(`Failed to read file "${g}": ${F}`,g)}}if(u.length>d.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return u}var se=A(()=>{"use strict";I();U();X();oe();D();O();ee();Q()});D();var L=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 o=Array.from(i);for(let s of o)try{s(...t)}catch(a){i.delete(s),e!=="error"&&setTimeout(()=>{a instanceof Error?this.emit("error",a,String(e)):this.emit("error",new Error(String(a)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(o=>{e.on(i,o)})})}clear(){this.handlers.clear()}};var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Fe=3e4,R=class extends L{constructor(e){super(),this.apiUrl=e.apiUrl||$,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Fe,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:s,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:s};this.emit("request",e,c);try{let r=await fetch(e,c);return a(),r.ok||await this.handleResponseError(r,i),this.emit("response",this.safeClone(r),e),{data:await this.parseResponse(this.safeClone(r)),status:r.status}}catch(r){a();let u=r instanceof Error?r:new Error(String(r));this.emit("error",u,e),this.handleFetchError(r,i)}}async request(e,t,i){let{data:o}=await this.executeRequest(e,t,i);return o}async requestWithStatus(e,t,i){return this.executeRequest(e,t,i)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);if(e){let o=()=>t.abort();e.addEventListener("abort",o),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(i)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,t){let i={};try{if(e.headers.get("content-type")?.includes("application/json")){let a=await e.json();if(a&&typeof a=="object"){let c=a;typeof c.message=="string"&&(i.message=c.message),typeof c.error=="string"&&(i.error=c.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let o=i.message||i.error||`${t} failed`;throw e.status===401?l.authentication(o):l.api(o,e.status)}handleFetchError(e,t){throw w(e)?e:e instanceof Error&&e.name==="AbortError"?l.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?l.network(`${t} failed: ${e.message}`,e):e instanceof Error?l.business(`${t} failed: ${e.message}`):l.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw l.business("No files to deploy");for(let a of e)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),s={};return t.deployToken?s.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`),t.caller&&(s["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${m.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...s},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let o={};t&&(o.deployment=t),i!==void 0&&(o.labels=i);let{data:s,status:a}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...s,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.labels=t),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let t=e.find(a=>a.path==="index.html"||a.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 o={files:e.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};D();O();D();D();function G(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||$,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 ce(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.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}D();U();async function Ne(){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 _(t);return{path:V,content:t,size:e.length,md5:i}}async function ue(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===V))return n;try{if(await e.checkSPA(n)){let o=await Ne();return[...n,o]}}catch{}return n}function de(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:s}=n;return{create:async(a,c={})=>{await t();let r=o?ce(c,o):c;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw l.config("processInput function is not provided.");let u=e(),p=await i(a,r);return p=await ue(p,u,r),u.deploy(p,r)},list:async()=>(await t(),e().listDeployments()),get:async a=>(await t(),e().getDeployment(a)),set:async(a,c)=>(await t(),e().updateDeploymentLabels(a,c.labels)),remove:async a=>{await t(),await e().removeDeployment(a)}}}function fe(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>(await t(),e().setDomain(i,o.deployment,o.labels)),list:async()=>(await t(),e().listDomains()),get:async i=>(await t(),e().getDomain(i)),remove:async i=>{await t(),await e().removeDomain(i)},verify:async i=>(await t(),e().verifyDomain(i)),validate:async i=>(await t(),e().validateDomain(i)),dns:async i=>(await t(),e().getDomainDns(i)),records:async i=>(await t(),e().getDomainRecords(i)),share:async i=>(await t(),e().getDomainShare(i))}}function me(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function he(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.labels)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}var B=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new R({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=de({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=fe(i),this._account=me(i),this._tokens=he(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=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}setDeployToken(e){if(!e||typeof e!="string")throw l.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw l.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};D();I();D();I();import{z as k}from"zod";var W="ship",$e=k.object({apiUrl:k.string().url().optional(),apiKey:k.string().optional(),deployToken:k.string().optional()}).strict();function ye(n){try{return $e.parse(n)}catch(e){if(e instanceof k.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${i}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function Le(n){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(W,{searchPlaces:[`.${W}rc`,"package.json",`${t.homedir()}/.${W}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return ye(o.config)}catch(e){if(w(e))throw e}return{}}async function J(n){if(C()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Le(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return ye(i)}O();D();async function ge(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),a=new i,c=[];for(let d of n){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let h=new o([d.content],d.path,{type:"application/octet-stream"});a.append("files[]",h),c.push(d.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let r=new s(a),u=[];for await(let d of r.encode())u.push(Buffer.from(d));let p=Buffer.concat(u);return{body:p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(p).toString()}}}U();function Ut(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}X();ee();I();ie();oe();D();O();se();var re=class extends B{constructor(e={}){if(C()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return G(e,{})}async loadFullConfig(){try{let e=await J(this.clientOptions.configFile),t=G(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new R({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();q(o)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw l.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(se(),xe));return o(i,t)}getDeployBodyCreator(){return ge}},Ke=re;export{z as API_KEY_HEX_LENGTH,qe as API_KEY_HINT_LENGTH,x as API_KEY_PREFIX,ae as API_KEY_TOTAL_LENGTH,je as AccountPlan,R as ApiHttp,Ge as AuthMethod,Pe as BLOCKED_EXTENSIONS,$ as DEFAULT_API,V as DEPLOYMENT_CONFIG_FILENAME,H as DEPLOY_TOKEN_HEX_LENGTH,T as DEPLOY_TOKEN_PREFIX,le as DEPLOY_TOKEN_TOTAL_LENGTH,He as DeploymentStatus,Ve as DomainStatus,f as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,Ue as JUNK_DIRECTORIES,nt as LABEL_CONSTRAINTS,it as LABEL_PATTERN,re as Ship,l as ShipError,ht as __setTestEnvironment,Gt as allValidFilesReady,_ as calculateMD5,me as createAccountResource,de as createDeploymentResource,fe as createDomainResource,he as createTokenResource,Ke as default,st as deserializeLabels,Ze as extractSubdomain,De as filterJunk,te as formatFileSize,et as generateDeploymentUrl,tt as generateDomainUrl,b as getCurrentConfig,C as getENV,Me as getValidFiles,N as isBlockedExtension,Qe as isCustomDomain,Xe as isDeployment,pe as isPlatformDomain,w as isShipError,J as loadConfig,ce as mergeDeployOptions,Ee as optimizeDeployPaths,Ut as pluralize,we as processFilesForNode,G as resolveConfig,ot as serializeLabels,q as setPlatformConfig,Ye as validateApiKey,Je as validateApiUrl,ve as validateDeployFile,Ae as validateDeployPath,We as validateDeployToken,ne as validateFileName,qt as validateFiles};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|