@shipstatic/ship 0.5.0 → 0.5.2
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 +3 -3
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +5 -5
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.bash +31 -21
- package/dist/completions/ship.fish +20 -7
- package/dist/completions/ship.zsh +30 -21
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -22,16 +22,14 @@ _ship_completions() {
|
|
|
22
22
|
COMPREPLY=( $(compgen -f -- "${current_word}") )
|
|
23
23
|
return
|
|
24
24
|
;;
|
|
25
|
-
"get"|"remove")
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
return
|
|
30
|
-
fi
|
|
25
|
+
"get"|"set"|"remove")
|
|
26
|
+
# Deployment ID position
|
|
27
|
+
COMPREPLY=()
|
|
28
|
+
return
|
|
31
29
|
;;
|
|
32
30
|
*)
|
|
33
31
|
if [[ ${COMP_CWORD} -eq 2 ]]; then
|
|
34
|
-
completions="list create get remove"
|
|
32
|
+
completions="list create get set remove"
|
|
35
33
|
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
36
34
|
return
|
|
37
35
|
fi
|
|
@@ -41,22 +39,34 @@ _ship_completions() {
|
|
|
41
39
|
"domains")
|
|
42
40
|
case "${COMP_WORDS[2]}" in
|
|
43
41
|
"set")
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
42
|
+
# Domain name or deployment ID positions
|
|
43
|
+
COMPREPLY=()
|
|
44
|
+
return
|
|
45
|
+
;;
|
|
46
|
+
"get"|"validate"|"verify"|"remove")
|
|
47
|
+
# Domain name position
|
|
48
|
+
COMPREPLY=()
|
|
49
|
+
return
|
|
49
50
|
;;
|
|
50
|
-
|
|
51
|
-
if [[ ${COMP_CWORD} -eq
|
|
52
|
-
|
|
53
|
-
COMPREPLY=()
|
|
51
|
+
*)
|
|
52
|
+
if [[ ${COMP_CWORD} -eq 2 ]]; then
|
|
53
|
+
completions="list get set validate verify remove"
|
|
54
|
+
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
54
55
|
return
|
|
55
56
|
fi
|
|
56
57
|
;;
|
|
58
|
+
esac
|
|
59
|
+
;;
|
|
60
|
+
"tokens")
|
|
61
|
+
case "${COMP_WORDS[2]}" in
|
|
62
|
+
"remove")
|
|
63
|
+
# Token ID position
|
|
64
|
+
COMPREPLY=()
|
|
65
|
+
return
|
|
66
|
+
;;
|
|
57
67
|
*)
|
|
58
68
|
if [[ ${COMP_CWORD} -eq 2 ]]; then
|
|
59
|
-
completions="list
|
|
69
|
+
completions="list create remove"
|
|
60
70
|
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
61
71
|
return
|
|
62
72
|
fi
|
|
@@ -79,7 +89,7 @@ _ship_completions() {
|
|
|
79
89
|
;;
|
|
80
90
|
esac
|
|
81
91
|
|
|
82
|
-
# Delegate for commands that expect files
|
|
92
|
+
# Delegate for commands that expect files
|
|
83
93
|
if [[ "$prev_word" == "create" || "$prev_word" == "--config" ]]; then
|
|
84
94
|
COMPREPLY=( $(compgen -f -- "${current_word}") )
|
|
85
95
|
return
|
|
@@ -87,14 +97,14 @@ _ship_completions() {
|
|
|
87
97
|
|
|
88
98
|
# Flag completion
|
|
89
99
|
if [[ "$current_word" == --* ]]; then
|
|
90
|
-
completions="--api-key --config --api-url --no-path-detect --no-spa-detect --json --no-color --version --help"
|
|
100
|
+
completions="--api-key --deploy-token --config --api-url --label --no-path-detect --no-spa-detect --json --no-color --version --help"
|
|
91
101
|
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
92
102
|
return
|
|
93
103
|
fi
|
|
94
104
|
|
|
95
105
|
# Top-level commands
|
|
96
106
|
if [[ ${COMP_CWORD} -eq 1 ]]; then
|
|
97
|
-
completions="ping whoami deployments domains account completion"
|
|
107
|
+
completions="ping whoami deployments domains tokens account config completion"
|
|
98
108
|
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
99
109
|
return
|
|
100
110
|
fi
|
|
@@ -104,4 +114,4 @@ _ship_completions() {
|
|
|
104
114
|
}
|
|
105
115
|
|
|
106
116
|
# Register the completion function for the 'ship' command
|
|
107
|
-
complete -F _ship_completions ship
|
|
117
|
+
complete -F _ship_completions ship
|
|
@@ -35,34 +35,47 @@ complete -c ship -f -n '__fish_use_subcommand' -a 'ping' -d 'Check API connectiv
|
|
|
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
37
|
complete -c ship -f -n '__fish_use_subcommand' -a 'domains' -d 'Manage domains'
|
|
38
|
+
complete -c ship -f -n '__fish_use_subcommand' -a 'tokens' -d 'Manage deploy tokens'
|
|
38
39
|
complete -c ship -f -n '__fish_use_subcommand' -a 'account' -d 'Manage account'
|
|
40
|
+
complete -c ship -f -n '__fish_use_subcommand' -a 'config' -d 'Create or update configuration'
|
|
39
41
|
complete -c ship -f -n '__fish_use_subcommand' -a 'completion' -d 'Setup shell completion'
|
|
40
42
|
|
|
41
43
|
# Global options
|
|
42
44
|
complete -c ship -l api-key -d 'API key for authentication' -x
|
|
45
|
+
complete -c ship -l deploy-token -d 'Deploy token for single-use deployments' -x
|
|
43
46
|
complete -c ship -l config -d 'Custom config file path' -r
|
|
44
47
|
complete -c ship -l api-url -d 'API URL (for development)' -x
|
|
48
|
+
complete -c ship -l label -d 'Label (can be repeated)' -x
|
|
45
49
|
complete -c ship -l json -d 'Output results in JSON format'
|
|
46
50
|
complete -c ship -l no-color -d 'Disable colored output'
|
|
51
|
+
complete -c ship -l no-path-detect -d 'Disable automatic path optimization and flattening'
|
|
52
|
+
complete -c ship -l no-spa-detect -d 'Disable automatic SPA detection and configuration'
|
|
47
53
|
complete -c ship -l version -d 'Show version information'
|
|
48
54
|
complete -c ship -l help -d 'Display help for command'
|
|
49
55
|
|
|
50
56
|
# Deployments subcommands
|
|
51
57
|
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'list' -d 'List all deployments'
|
|
52
|
-
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'create' -d 'Create deployment from
|
|
58
|
+
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'create' -d 'Create deployment from directory'
|
|
53
59
|
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'get' -d 'Show deployment information'
|
|
60
|
+
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'set' -d 'Set deployment labels'
|
|
54
61
|
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'remove' -d 'Delete deployment permanently'
|
|
55
62
|
|
|
56
|
-
# Deployments create options
|
|
57
|
-
complete -c ship -l no-path-detect -d 'Disable automatic path optimization and flattening'
|
|
58
|
-
complete -c ship -l no-spa-detect -d 'Disable automatic SPA detection and configuration'
|
|
59
|
-
|
|
60
63
|
# Domains subcommands
|
|
61
64
|
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'list' -d 'List all domains'
|
|
62
65
|
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
|
|
66
|
+
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'set' -d 'Create domain, link to deployment, or update labels'
|
|
67
|
+
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'validate' -d 'Check if domain name is valid and available'
|
|
68
|
+
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'verify' -d 'Trigger DNS verification for external domain'
|
|
64
69
|
complete -c ship -f -n '__fish_seen_subcommand_from domains' -a 'remove' -d 'Delete domain permanently'
|
|
65
70
|
|
|
71
|
+
# Tokens subcommands
|
|
72
|
+
complete -c ship -f -n '__fish_seen_subcommand_from tokens' -a 'list' -d 'List all deploy tokens'
|
|
73
|
+
complete -c ship -f -n '__fish_seen_subcommand_from tokens' -a 'create' -d 'Create a new deploy token'
|
|
74
|
+
complete -c ship -f -n '__fish_seen_subcommand_from tokens' -a 'remove' -d 'Delete token permanently'
|
|
75
|
+
|
|
76
|
+
# Tokens create options
|
|
77
|
+
complete -c ship -l ttl -d 'Time to live in seconds' -x
|
|
78
|
+
|
|
66
79
|
# Account subcommands
|
|
67
80
|
complete -c ship -f -n '__fish_seen_subcommand_from account' -a 'get' -d 'Show account information'
|
|
68
81
|
|
|
@@ -71,4 +84,4 @@ complete -c ship -f -n '__fish_seen_subcommand_from completion' -a 'install' -d
|
|
|
71
84
|
complete -c ship -f -n '__fish_seen_subcommand_from completion' -a 'uninstall' -d 'Uninstall shell completion script'
|
|
72
85
|
|
|
73
86
|
# File completion for appropriate commands (only when not a path is being typed)
|
|
74
|
-
complete -c ship -F -n '__ship_needs_file and not __ship_is_path'
|
|
87
|
+
complete -c ship -F -n '__ship_needs_file and not __ship_is_path'
|
|
@@ -5,15 +5,15 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
5
5
|
_ship() {
|
|
6
6
|
local -a completions
|
|
7
7
|
local state line
|
|
8
|
-
|
|
8
|
+
|
|
9
9
|
# Only proceed if we're actually in a completion context
|
|
10
10
|
if [[ -z ${words-} ]]; then
|
|
11
11
|
return 1
|
|
12
12
|
fi
|
|
13
|
-
|
|
13
|
+
|
|
14
14
|
# The word being completed
|
|
15
15
|
local current_word="${words[CURRENT]}"
|
|
16
|
-
# The previous word
|
|
16
|
+
# The previous word
|
|
17
17
|
local prev_word="${words[CURRENT-1]}"
|
|
18
18
|
|
|
19
19
|
# --- File Path Logic ---
|
|
@@ -32,15 +32,13 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
32
32
|
_files
|
|
33
33
|
return
|
|
34
34
|
;;
|
|
35
|
-
"get"|"remove")
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
return
|
|
39
|
-
fi
|
|
35
|
+
"get"|"set"|"remove")
|
|
36
|
+
# Deployment ID position
|
|
37
|
+
return
|
|
40
38
|
;;
|
|
41
39
|
*)
|
|
42
40
|
if [[ $CURRENT -eq 3 ]]; then
|
|
43
|
-
completions=("list:List all deployments" "create:Create deployment from
|
|
41
|
+
completions=("list:List all deployments" "create:Create deployment from directory" "get:Show deployment information" "set:Set deployment labels" "remove:Delete deployment permanently")
|
|
44
42
|
_describe 'deployments commands' completions
|
|
45
43
|
return
|
|
46
44
|
fi
|
|
@@ -50,21 +48,32 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
50
48
|
"domains")
|
|
51
49
|
case "${words[3]}" in
|
|
52
50
|
"set")
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
51
|
+
# Domain name or deployment ID positions
|
|
52
|
+
return
|
|
53
|
+
;;
|
|
54
|
+
"get"|"validate"|"verify"|"remove")
|
|
55
|
+
# Domain name position
|
|
56
|
+
return
|
|
57
57
|
;;
|
|
58
|
-
|
|
59
|
-
if [[ $CURRENT -eq
|
|
60
|
-
|
|
58
|
+
*)
|
|
59
|
+
if [[ $CURRENT -eq 3 ]]; then
|
|
60
|
+
completions=("list:List all domains" "get:Show domain information" "set:Create domain, link to deployment, or update labels" "validate:Check if domain name is valid and available" "verify:Trigger DNS verification for external domain" "remove:Delete domain permanently")
|
|
61
|
+
_describe 'domains commands' completions
|
|
61
62
|
return
|
|
62
63
|
fi
|
|
63
64
|
;;
|
|
65
|
+
esac
|
|
66
|
+
;;
|
|
67
|
+
"tokens")
|
|
68
|
+
case "${words[3]}" in
|
|
69
|
+
"remove")
|
|
70
|
+
# Token ID position
|
|
71
|
+
return
|
|
72
|
+
;;
|
|
64
73
|
*)
|
|
65
74
|
if [[ $CURRENT -eq 3 ]]; then
|
|
66
|
-
completions=("list:List all
|
|
67
|
-
_describe '
|
|
75
|
+
completions=("list:List all deploy tokens" "create:Create a new deploy token" "remove:Delete token permanently")
|
|
76
|
+
_describe 'tokens commands' completions
|
|
68
77
|
return
|
|
69
78
|
fi
|
|
70
79
|
;;
|
|
@@ -94,14 +103,14 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
94
103
|
|
|
95
104
|
# Flag completion
|
|
96
105
|
if [[ "$current_word" == --* ]]; then
|
|
97
|
-
completions=("--api-key:API key for authentication" "--config:Custom config file path" "--api-url:API URL (for development)" "--no-path-detect:Disable automatic path optimization and flattening" "--no-spa-detect:Disable automatic SPA detection and configuration" "--json:Output results in JSON format" "--no-color:Disable colored output" "--version:Show version information" "--help:Display help for command")
|
|
106
|
+
completions=("--api-key:API key for authentication" "--deploy-token:Deploy token for single-use deployments" "--config:Custom config file path" "--api-url:API URL (for development)" "--label:Label (can be repeated)" "--no-path-detect:Disable automatic path optimization and flattening" "--no-spa-detect:Disable automatic SPA detection and configuration" "--json:Output results in JSON format" "--no-color:Disable colored output" "--version:Show version information" "--help:Display help for command")
|
|
98
107
|
_describe 'options' completions
|
|
99
108
|
return
|
|
100
109
|
fi
|
|
101
110
|
|
|
102
111
|
# Top-level commands
|
|
103
112
|
if [[ $CURRENT -eq 2 ]]; then
|
|
104
|
-
completions=("ping:Check API connectivity" "whoami:Get current account information" "deployments:Manage deployments" "domains:Manage domains" "account:Manage account" "completion:Setup shell completion")
|
|
113
|
+
completions=("ping:Check API connectivity" "whoami:Get current account information" "deployments:Manage deployments" "domains:Manage domains" "tokens:Manage deploy tokens" "account:Manage account" "config:Create or update configuration" "completion:Setup shell completion")
|
|
105
114
|
_describe 'commands' completions
|
|
106
115
|
return
|
|
107
116
|
fi
|
|
@@ -114,4 +123,4 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
114
123
|
if (( ${+functions[compdef]} )); then
|
|
115
124
|
compdef _ship ship
|
|
116
125
|
fi
|
|
117
|
-
fi
|
|
126
|
+
fi
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Me=Object.create;var _=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var Se=(n,e)=>{for(var t in e)_(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Be(e))!je.call(n,o)&&o!==t&&_(n,o,{get:()=>e[o],enumerable:!(i=Ue(e,o))||i.enumerable});return n};var E=(n,e,t)=>(t=n!=null?Me(Ke(n)):{},Ae(e||!n||!n.__esModule?_(t,"default",{value:n,enumerable:!0}):t,n)),ze=n=>Ae(_({},"__esModule",{value:!0}),n);function w(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function ee(n){return B.some(e=>n===e||n.startsWith(e))}function Ye(n){if(!n.startsWith(R))throw p.validation(`API key must start with "${R}"`);if(n.length!==Q)throw p.validation(`API key must be ${Q} characters total (${R} + ${M} hex chars)`);let e=n.slice(R.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${M} hexadecimal characters after "${R}" prefix`)}function We(n){if(!n.startsWith(I))throw p.validation(`Deploy token must start with "${I}"`);if(n.length!==Z)throw p.validation(`Deploy token must be ${Z} characters total (${I} + ${U} hex chars)`);let e=n.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${U} hexadecimal characters after "${I}" prefix`)}function Je(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw w(e)?e:p.validation("API URL must be a valid URL")}}function Xe(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,e){return n.endsWith(`.${e}`)}function Qe(n,e){return!te(n,e)}function Ze(n,e){return te(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)try{let e=JSON.parse(n);return Array.isArray(e)&&e.length>0?e:void 0}catch{return}}var Ve,He,qe,m,X,p,B,R,M,Q,I,U,Z,Ge,K,N,y,nt,it,x=T(()=>{"use strict";Ve={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},He={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},qe={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"})(m||(m={}));X={client:new Set([m.Business,m.Config,m.File,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},p=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===m.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(m.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(m.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(m.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(m.Authentication,e,401,t)}static business(e,t=400){return new n(m.Business,e,t)}static network(e,t){return new n(m.Network,e,void 0,{cause:t})}static cancelled(e){return new n(m.Cancelled,e)}static file(e,t){return new n(m.File,e,void 0,{filePath:t})}static config(e,t){return new n(m.Config,e,void 0,t)}static api(e,t=500){return new n(m.Api,e,t)}static database(e,t=500){return new n(m.Api,e,t)}static storage(e,t=500){return new n(m.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return X.client.has(this.type)}isNetworkError(){return X.network.has(this.type)}isAuthError(){return X.auth.has(this.type)}isValidationError(){return this.type===m.Validation}isFileError(){return this.type===m.File}isConfigError(){return this.type===m.Config}isType(e){return this.type===e}};B=["text/html","text/css","text/plain","text/markdown","text/xml","text/csv","text/tab-separated-values","text/yaml","text/vcard","text/mdx","text/x-mdx","text/vtt","text/srt","text/calendar","text/javascript","text/typescript","application/x-typescript","text/tsx","text/jsx","text/x-scss","text/x-sass","text/less","text/x-less","text/stylus","text/x-vue","text/x-svelte","text/x-sql","text/x-diff","text/x-patch","text/x-protobuf","text/x-ini","text/x-tex","text/x-latex","text/x-bibtex","text/x-r-markdown","image/","audio/","video/","font/","application/javascript","application/ecmascript","application/x-javascript","application/wasm","application/json","application/ld+json","application/geo+json","application/manifest+json","application/x-ipynb+json","application/x-ndjson","application/ndjson","text/x-ndjson","application/jsonl","text/jsonl","application/json5","text/json5","application/schema+json","application/source-map","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/feed+json","application/vnd.google-earth.kml+xml","application/yaml","application/toml","application/pdf","application/x-subrip","application/sql","application/graphql","application/graphql+json","application/x-protobuf","application/x-ini","application/x-tex","application/x-bibtex","model/gltf+json","model/gltf-binary","application/mp4","application/font-woff","application/font-woff2","application/x-font-woff","application/x-woff","application/vnd.ms-fontobject","application/x-font-ttf","application/x-font-truetype","application/x-font-otf","application/x-font-opentype"];R="ship-",M=64,Q=R.length+M,I="token-",U=64,Z=I.length+U,Ge={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},K="ship.json";N="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 z(n){ne=n}function O(){if(ne===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,$=T(()=>{"use strict";x();ne=null});function ve(n){ie=n}function at(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function S(){return ie||at()}var ie,b=T(()=>{"use strict";ie=null});async function pt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let r=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,s=new FileReader,f=()=>{let l=a*2097152,u=Math.min(l+2097152,n.size);s.readAsArrayBuffer(n.slice(l,u))};s.onload=l=>{let u=l.target?.result;if(!u){i(p.business("Failed to read file chunk"));return}c.append(u),a++,a<r?f():t({md5:c.end()})},s.onerror=()=>{i(p.business("Failed to calculate MD5: FileReader error"))},f()})}async function lt(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 r=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(p.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>r.update(c)),a.on("end",()=>i({md5:r.digest("hex")}))})}async function L(n){let e=S();if(e==="browser"){if(!(n instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return pt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return lt(n)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var H=T(()=>{"use strict";b();x()});function Te(n){try{return ut.parse(n)}catch(e){if(e instanceof F.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw p.config(`Configuration validation failed${i}: ${t.message}`)}throw p.config("Configuration validation failed")}}async function ft(n){try{if(S()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(le,{searchPlaces:[`.${le}rc`,"package.json",`${t.homedir()}/.${le}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Te(o.config)}catch(e){if(w(e))throw e}return{}}async function G(n){if(S()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ft(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Te(i)}var F,le,ut,ce=T(()=>{"use strict";F=require("zod");x();b();le="ship",ut=F.z.object({apiUrl:F.z.string().url().optional(),apiKey:F.z.string().optional(),deployToken:F.z.string().optional()}).strict()});function me(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if((0,Ie.isJunk)(i))return!1;for(let r of t)if(r.startsWith(".")||r.length>255)return!1;let o=t.slice(0,-1);for(let r of o)if(Pe.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ie,Pe,de=T(()=>{"use strict";Ie=require("junk"),Pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function be(n){if(!n||n.length===0)return"";let e=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=T(()=>{"use strict"});function ge(n,e={}){if(e.flatten===!1)return n.map(i=>({path:Y(i),name:ye(i)}));let t=dt(n);return n.map(i=>{let o=Y(i);if(t){let r=t.endsWith("/")?t:`${t}/`;o.startsWith(r)&&(o=o.substring(r.length))}return o||(o=ye(i)),{path:o,name:ye(i)}})}function dt(n){if(!n.length)return"";let t=n.map(r=>Y(r)).map(r=>r.split("/")),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o-1;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var xe=T(()=>{"use strict";he()});var $e={};Se($e,{processFilesForNode:()=>De});function Ne(n,e=new Set){let t=[],i=A.realpathSync(n);if(e.has(i))return t;e.add(i);let o=A.readdirSync(n);for(let r of o){let a=D.join(n,r),c=A.statSync(a);if(c.isDirectory()){let s=Ne(a,e);t.push(...s)}else c.isFile()&&t.push(a)}return t}async function De(n,e={}){if(S()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(d=>{let g=D.resolve(d);try{return A.statSync(g).isDirectory()?Ne(g):[g]}catch{throw p.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(t)],o=me(i);if(o.length===0)return[];let r=n.map(d=>D.resolve(d)),a=be(r.map(d=>{try{return A.statSync(d).isDirectory()?d:D.dirname(d)}catch{return D.dirname(d)}})),c=o.map(d=>{if(a&&a.length>0){let g=D.relative(a,d);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return D.basename(d)}),s=ge(c,{flatten:e.pathDetect!==!1}),f=[],l=0,u=O();for(let d=0;d<o.length;d++){let g=o[d],v=s[d].path;try{let C=A.statSync(g);if(C.size===0)continue;if(C.size>u.maxFileSize)throw p.business(`File ${g} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(l+=C.size,l>u.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let k=A.readFileSync(g),{md5:_e}=await L(k);if(v.includes("\0")||v.includes("/../")||v.startsWith("../")||v.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${v}" for file: ${g}`);f.push({path:v,content:k,size:k.length,md5:_e})}catch(C){if(w(C))throw C;let k=C instanceof Error?C.message:String(C);throw p.file(`Failed to read file "${g}": ${k}`,g)}}if(f.length>u.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return f}var A,D,Ee=T(()=>{"use strict";b();H();de();x();$();xe();he();A=E(require("fs"),1),D=E(require("path"),1)});var St={};Se(St,{ALLOWED_MIME_TYPES:()=>B,API_KEY_HEX_LENGTH:()=>M,API_KEY_PREFIX:()=>R,API_KEY_TOTAL_LENGTH:()=>Q,AccountPlan:()=>qe,ApiHttp:()=>P,AuthMethod:()=>Ge,DEFAULT_API:()=>N,DEPLOYMENT_CONFIG_FILENAME:()=>K,DEPLOY_TOKEN_HEX_LENGTH:()=>U,DEPLOY_TOKEN_PREFIX:()=>I,DEPLOY_TOKEN_TOTAL_LENGTH:()=>Z,DeploymentStatus:()=>Ve,DomainStatus:()=>He,ErrorType:()=>m,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Pe,LABEL_CONSTRAINTS:()=>nt,LABEL_PATTERN:()=>it,Ship:()=>J,ShipError:()=>p,__setTestEnvironment:()=>ve,allValidFilesReady:()=>Et,calculateMD5:()=>L,createAccountResource:()=>ae,createDeploymentResource:()=>se,createDomainResource:()=>re,createTokenResource:()=>pe,default:()=>Le,deserializeLabels:()=>st,extractSubdomain:()=>Ze,filterJunk:()=>me,formatFileSize:()=>W,generateDeploymentUrl:()=>et,generateDomainUrl:()=>tt,getCurrentConfig:()=>O,getENV:()=>S,getValidFiles:()=>ke,isAllowedMimeType:()=>ee,isCustomDomain:()=>Qe,isDeployment:()=>Xe,isPlatformDomain:()=>te,isShipError:()=>w,loadConfig:()=>G,mergeDeployOptions:()=>oe,optimizeDeployPaths:()=>ge,pluralize:()=>mt,processFilesForNode:()=>De,resolveConfig:()=>V,serializeLabels:()=>ot,setPlatformConfig:()=>z,validateApiKey:()=>Ye,validateApiUrl:()=>Je,validateDeployToken:()=>We,validateFiles:()=>Dt});module.exports=ze(St);x();var j=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 r of o)try{r(...t)}catch(a){i.delete(r),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 h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},rt=3e4,P=class extends j{constructor(e){super(),this.apiUrl=e.apiUrl||N,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??rt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:r};this.emit("request",e,c);try{let s=await fetch(e,c);return a(),s.ok||await this.handleResponseError(s,i),this.emit("response",this.safeClone(s),e),{data:await this.parseResponse(this.safeClone(s)),status:s.status}}catch(s){a();let f=s instanceof Error?s:new Error(String(s));this.emit("error",f,e),this.handleFetchError(s,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?p.authentication(o):p.api(o,e.status)}handleFetchError(e,t){throw w(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${t} failed: ${e.message}`,e):e instanceof Error?p.business(`${t} failed: ${e.message}`):p.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw p.business("No files to deploy");for(let a of e)if(!a.md5)throw p.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),r={};return t.deployToken?r.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(r.Authorization=`Bearer ${t.apiKey}`),t.caller&&(r["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${h.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...r},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${h.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}${h.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:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${h.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainLabels(e,t){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update domain labels")}async removeDomain(e){await this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${h.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}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${h.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${h.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${h.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping")}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}${h.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};x();$();x();x();function V(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||N,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 oe(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}x();H();async function ct(){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 L(t);return{path:K,content:t,size:e.length,md5:i}}async function Ce(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===K))return n;try{if(await e.checkSPA(n)){let o=await ct();return[...n,o]}}catch{}return n}function se(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:r}=n;return{create:async(a,c={})=>{await t();let s=o?oe(c,o):c;if(r&&!r()&&!s.deployToken&&!s.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw p.config("processInput function is not provided.");let f=e(),l=await i(a,s);return l=await Ce(l,f,s),f.deploy(l,s)},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 re(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>{await t();let{deployment:r,labels:a}=o;return r===void 0&&a&&a.length>0?e().updateDomainLabels(i,a):e().setDomain(i,r,a)},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 ae(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function pe(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 q=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 P({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=se({...i,processInput:(o,r)=>this.processInput(o,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=re(i),this._account=ae(i),this._tokens=pe(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=O(),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 p.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 p.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}};x();b();ce();$();x();var ue=E(require("mime-db"),1),fe={};for(let n in ue.default){let e=ue.default[n];e&&e.extensions&&e.extensions.forEach(t=>{fe[t]||(fe[t]=n)})}function we(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return fe[e]||"application/octet-stream"}async function Re(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),a=new i,c=[];for(let u of n){let d=we(u.path),g;if(Buffer.isBuffer(u.content))g=new o([u.content],u.path,{type:d});else if(typeof Blob<"u"&&u.content instanceof Blob)g=new o([u.content],u.path,{type:d});else throw p.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw p.file(`File missing md5 checksum: ${u.path}`,u.path);let v=u.path.startsWith("/")?u.path:"/"+u.path;a.append("files[]",g,v),c.push(u.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let s=new r(a),f=[];for await(let u of s.encode())f.push(Buffer.from(u));let l=Buffer.concat(f);return{body:l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),headers:{"Content-Type":s.contentType,"Content-Length":Buffer.byteLength(l).toString()}}}H();function mt(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}de();xe();b();x();var Oe=E(require("mime-db"),1),Fe=Oe.default,ht=new Set(Object.keys(Fe)),yt=new Map(Object.entries(Fe).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function W(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 gt(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 xt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],o=yt.get(e);if(o&&!o.has(i))return!1}return!0}function Dt(n,e){let t=[],i=[],o=[];if(n.length===0){let s={file:"(no files)",message:"At least one file must be provided"};return t.push(s),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let s={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(s),{files:n.map(f=>({...f,status:y.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let r=0;for(let s of n){let f=y.READY,l="Ready for upload",u=s.name?gt(s.name):{valid:!1,reason:"File name cannot be empty"};if(s.status===y.PROCESSING_ERROR)f=y.VALIDATION_FAILED,l=s.statusMessage||"File failed during processing",t.push({file:s.name,message:l});else if(s.size===0){f=y.EXCLUDED,l="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:s.name,message:l}),o.push({...s,status:f,statusMessage:l});continue}else s.size<0?(f=y.VALIDATION_FAILED,l="File size must be positive",t.push({file:s.name,message:l})):!s.name||s.name.trim().length===0?(f=y.VALIDATION_FAILED,l="File name cannot be empty",t.push({file:s.name||"(empty)",message:l})):s.name.includes("\0")?(f=y.VALIDATION_FAILED,l="File name contains invalid characters (null byte)",t.push({file:s.name,message:l})):u.valid?!s.type||s.type.trim().length===0?(f=y.VALIDATION_FAILED,l="File MIME type is required",t.push({file:s.name,message:l})):ee(s.type)?!B.some(d=>s.type===d)&&!ht.has(s.type)?(f=y.VALIDATION_FAILED,l=`Invalid MIME type "${s.type}"`,t.push({file:s.name,message:l})):xt(s.name,s.type)?s.size>e.maxFileSize?(f=y.VALIDATION_FAILED,l=`File size (${W(s.size)}) exceeds limit of ${W(e.maxFileSize)}`,t.push({file:s.name,message:l})):(r+=s.size,r>e.maxTotalSize&&(f=y.VALIDATION_FAILED,l=`Total size would exceed limit of ${W(e.maxTotalSize)}`,t.push({file:s.name,message:l}))):(f=y.VALIDATION_FAILED,l="File extension does not match MIME type",t.push({file:s.name,message:l})):(f=y.VALIDATION_FAILED,l=`File type "${s.type}" is not allowed`,t.push({file:s.name,message:l})):(f=y.VALIDATION_FAILED,l=u.reason||"Invalid file name",t.push({file:s.name,message:l}));o.push({...s,status:f,statusMessage:l})}t.length>0&&(o=o.map(s=>s.status===y.EXCLUDED?s:{...s,status:y.VALIDATION_FAILED,statusMessage:s.status===y.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(s=>s.status===y.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function ke(n){return n.filter(e=>e.status===y.READY)}function Et(n){return ke(n).length>0}x();ce();$();Ee();b();var J=class extends q{constructor(e={}){if(S()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return V(e,{})}async loadFullConfig(){try{let e=await G(this.clientOptions.configFile),t=V(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new P({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();z(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(r=>typeof r=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw p.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(Ee(),$e));return o(i,t)}getDeployBodyCreator(){return Re}},Le=J;0&&(module.exports={ALLOWED_MIME_TYPES,API_KEY_HEX_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isAllowedMimeType,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployToken,validateFiles});
|
|
1
|
+
"use strict";var Me=Object.create;var _=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var Se=(n,e)=>{for(var t in e)_(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Be(e))!je.call(n,o)&&o!==t&&_(n,o,{get:()=>e[o],enumerable:!(i=Ue(e,o))||i.enumerable});return n};var E=(n,e,t)=>(t=n!=null?Me(Ke(n)):{},Ae(e||!n||!n.__esModule?_(t,"default",{value:n,enumerable:!0}):t,n)),ze=n=>Ae(_({},"__esModule",{value:!0}),n);function w(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function ee(n){return B.some(e=>n===e||n.startsWith(e))}function We(n){if(!n.startsWith(R))throw p.validation(`API key must start with "${R}"`);if(n.length!==Q)throw p.validation(`API key must be ${Q} characters total (${R} + ${M} hex chars)`);let e=n.slice(R.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${M} hexadecimal characters after "${R}" prefix`)}function Je(n){if(!n.startsWith(I))throw p.validation(`Deploy token must start with "${I}"`);if(n.length!==Z)throw p.validation(`Deploy token must be ${Z} characters total (${I} + ${U} hex chars)`);let e=n.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${U} hexadecimal characters after "${I}" prefix`)}function Xe(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw w(e)?e:p.validation("API URL must be a valid URL")}}function Qe(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,e){return n.endsWith(`.${e}`)}function Ze(n,e){return!te(n,e)}function et(n,e){return te(n,e)?n.slice(0,-(e.length+1)):null}function tt(n,e){return`https://${n}.${e||"shipstatic.com"}`}function nt(n){return`https://${n}`}function st(n){return!n||n.length===0?null:JSON.stringify(n)}function rt(n){if(n)try{let e=JSON.parse(n);return Array.isArray(e)&&e.length>0?e:void 0}catch{return}}var Ve,He,qe,m,X,p,B,R,M,Q,Ge,I,U,Z,Ye,K,k,y,it,ot,x=T(()=>{"use strict";Ve={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},He={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},qe={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"})(m||(m={}));X={client:new Set([m.Business,m.Config,m.File,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},p=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===m.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(m.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(m.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(m.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(m.Authentication,e,401,t)}static business(e,t=400){return new n(m.Business,e,t)}static network(e,t){return new n(m.Network,e,void 0,{cause:t})}static cancelled(e){return new n(m.Cancelled,e)}static file(e,t){return new n(m.File,e,void 0,{filePath:t})}static config(e,t){return new n(m.Config,e,void 0,t)}static api(e,t=500){return new n(m.Api,e,t)}static database(e,t=500){return new n(m.Api,e,t)}static storage(e,t=500){return new n(m.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return X.client.has(this.type)}isNetworkError(){return X.network.has(this.type)}isAuthError(){return X.auth.has(this.type)}isValidationError(){return this.type===m.Validation}isFileError(){return this.type===m.File}isConfigError(){return this.type===m.Config}isType(e){return this.type===e}};B=["text/html","text/css","text/plain","text/markdown","text/xml","text/csv","text/tab-separated-values","text/yaml","text/vcard","text/mdx","text/x-mdx","text/vtt","text/srt","text/calendar","text/javascript","text/typescript","application/x-typescript","text/tsx","text/jsx","text/x-scss","text/x-sass","text/less","text/x-less","text/stylus","text/x-vue","text/x-svelte","text/x-sql","text/x-diff","text/x-patch","text/x-protobuf","text/x-ini","text/x-tex","text/x-latex","text/x-bibtex","text/x-r-markdown","image/","audio/","video/","font/","application/javascript","application/ecmascript","application/x-javascript","application/wasm","application/json","application/ld+json","application/geo+json","application/manifest+json","application/x-ipynb+json","application/x-ndjson","application/ndjson","text/x-ndjson","application/jsonl","text/jsonl","application/json5","text/json5","application/schema+json","application/source-map","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/feed+json","application/vnd.google-earth.kml+xml","application/yaml","application/toml","application/pdf","application/x-subrip","application/sql","application/graphql","application/graphql+json","application/x-protobuf","application/x-ini","application/x-tex","application/x-bibtex","model/gltf+json","model/gltf-binary","application/mp4","application/font-woff","application/font-woff2","application/x-font-woff","application/x-woff","application/vnd.ms-fontobject","application/x-font-ttf","application/x-font-truetype","application/x-font-otf","application/x-font-opentype"];R="ship-",M=64,Q=R.length+M,Ge=4,I="token-",U=64,Z=I.length+U,Ye={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},K="ship.json";k="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};it={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},ot=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function z(n){ne=n}function O(){if(ne===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,$=T(()=>{"use strict";x();ne=null});function ve(n){ie=n}function pt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function S(){return ie||pt()}var ie,b=T(()=>{"use strict";ie=null});async function lt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let r=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,s=new FileReader,f=()=>{let l=a*2097152,u=Math.min(l+2097152,n.size);s.readAsArrayBuffer(n.slice(l,u))};s.onload=l=>{let u=l.target?.result;if(!u){i(p.business("Failed to read file chunk"));return}c.append(u),a++,a<r?f():t({md5:c.end()})},s.onerror=()=>{i(p.business("Failed to calculate MD5: FileReader error"))},f()})}async function ct(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 r=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(p.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>r.update(c)),a.on("end",()=>i({md5:r.digest("hex")}))})}async function L(n){let e=S();if(e==="browser"){if(!(n instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return lt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ct(n)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var H=T(()=>{"use strict";b();x()});function Te(n){try{return ft.parse(n)}catch(e){if(e instanceof F.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw p.config(`Configuration validation failed${i}: ${t.message}`)}throw p.config("Configuration validation failed")}}async function mt(n){try{if(S()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(le,{searchPlaces:[`.${le}rc`,"package.json",`${t.homedir()}/.${le}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Te(o.config)}catch(e){if(w(e))throw e}return{}}async function G(n){if(S()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await mt(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Te(i)}var F,le,ft,ce=T(()=>{"use strict";F=require("zod");x();b();le="ship",ft=F.z.object({apiUrl:F.z.string().url().optional(),apiKey:F.z.string().optional(),deployToken:F.z.string().optional()}).strict()});function me(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if((0,Ie.isJunk)(i))return!1;for(let r of t)if(r.startsWith(".")||r.length>255)return!1;let o=t.slice(0,-1);for(let r of o)if(Pe.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ie,Pe,de=T(()=>{"use strict";Ie=require("junk"),Pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function be(n){if(!n||n.length===0)return"";let e=n.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=T(()=>{"use strict"});function ge(n,e={}){if(e.flatten===!1)return n.map(i=>({path:Y(i),name:ye(i)}));let t=ht(n);return n.map(i=>{let o=Y(i);if(t){let r=t.endsWith("/")?t:`${t}/`;o.startsWith(r)&&(o=o.substring(r.length))}return o||(o=ye(i)),{path:o,name:ye(i)}})}function ht(n){if(!n.length)return"";let t=n.map(r=>Y(r)).map(r=>r.split("/")),i=[],o=Math.min(...t.map(r=>r.length));for(let r=0;r<o-1;r++){let a=t[0][r];if(t.every(c=>c[r]===a))i.push(a);else break}return i.join("/")}function ye(n){return n.split(/[/\\]/).pop()||n}var xe=T(()=>{"use strict";he()});var $e={};Se($e,{processFilesForNode:()=>De});function ke(n,e=new Set){let t=[],i=A.realpathSync(n);if(e.has(i))return t;e.add(i);let o=A.readdirSync(n);for(let r of o){let a=D.join(n,r),c=A.statSync(a);if(c.isDirectory()){let s=ke(a,e);t.push(...s)}else c.isFile()&&t.push(a)}return t}async function De(n,e={}){if(S()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(d=>{let g=D.resolve(d);try{return A.statSync(g).isDirectory()?ke(g):[g]}catch{throw p.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(t)],o=me(i);if(o.length===0)return[];let r=n.map(d=>D.resolve(d)),a=be(r.map(d=>{try{return A.statSync(d).isDirectory()?d:D.dirname(d)}catch{return D.dirname(d)}})),c=o.map(d=>{if(a&&a.length>0){let g=D.relative(a,d);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return D.basename(d)}),s=ge(c,{flatten:e.pathDetect!==!1}),f=[],l=0,u=O();for(let d=0;d<o.length;d++){let g=o[d],v=s[d].path;try{let C=A.statSync(g);if(C.size===0)continue;if(C.size>u.maxFileSize)throw p.business(`File ${g} is too large. Maximum allowed size is ${u.maxFileSize/(1024*1024)}MB.`);if(l+=C.size,l>u.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${u.maxTotalSize/(1024*1024)}MB.`);let N=A.readFileSync(g),{md5:_e}=await L(N);if(v.includes("\0")||v.includes("/../")||v.startsWith("../")||v.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${v}" for file: ${g}`);f.push({path:v,content:N,size:N.length,md5:_e})}catch(C){if(w(C))throw C;let N=C instanceof Error?C.message:String(C);throw p.file(`Failed to read file "${g}": ${N}`,g)}}if(f.length>u.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${u.maxFilesCount} files.`);return f}var A,D,Ee=T(()=>{"use strict";b();H();de();x();$();xe();he();A=E(require("fs"),1),D=E(require("path"),1)});var At={};Se(At,{ALLOWED_MIME_TYPES:()=>B,API_KEY_HEX_LENGTH:()=>M,API_KEY_HINT_LENGTH:()=>Ge,API_KEY_PREFIX:()=>R,API_KEY_TOTAL_LENGTH:()=>Q,AccountPlan:()=>qe,ApiHttp:()=>P,AuthMethod:()=>Ye,DEFAULT_API:()=>k,DEPLOYMENT_CONFIG_FILENAME:()=>K,DEPLOY_TOKEN_HEX_LENGTH:()=>U,DEPLOY_TOKEN_PREFIX:()=>I,DEPLOY_TOKEN_TOTAL_LENGTH:()=>Z,DeploymentStatus:()=>Ve,DomainStatus:()=>He,ErrorType:()=>m,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Pe,LABEL_CONSTRAINTS:()=>it,LABEL_PATTERN:()=>ot,Ship:()=>J,ShipError:()=>p,__setTestEnvironment:()=>ve,allValidFilesReady:()=>St,calculateMD5:()=>L,createAccountResource:()=>ae,createDeploymentResource:()=>se,createDomainResource:()=>re,createTokenResource:()=>pe,default:()=>Le,deserializeLabels:()=>rt,extractSubdomain:()=>et,filterJunk:()=>me,formatFileSize:()=>W,generateDeploymentUrl:()=>tt,generateDomainUrl:()=>nt,getCurrentConfig:()=>O,getENV:()=>S,getValidFiles:()=>Ne,isAllowedMimeType:()=>ee,isCustomDomain:()=>Ze,isDeployment:()=>Qe,isPlatformDomain:()=>te,isShipError:()=>w,loadConfig:()=>G,mergeDeployOptions:()=>oe,optimizeDeployPaths:()=>ge,pluralize:()=>dt,processFilesForNode:()=>De,resolveConfig:()=>V,serializeLabels:()=>st,setPlatformConfig:()=>z,validateApiKey:()=>We,validateApiUrl:()=>Xe,validateDeployToken:()=>Je,validateFiles:()=>Et});module.exports=ze(At);x();var j=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 r of o)try{r(...t)}catch(a){i.delete(r),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 h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},at=3e4,P=class extends j{constructor(e){super(),this.apiUrl=e.apiUrl||k,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??at,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:r};this.emit("request",e,c);try{let s=await fetch(e,c);return a(),s.ok||await this.handleResponseError(s,i),this.emit("response",this.safeClone(s),e),{data:await this.parseResponse(this.safeClone(s)),status:s.status}}catch(s){a();let f=s instanceof Error?s:new Error(String(s));this.emit("error",f,e),this.handleFetchError(s,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?p.authentication(o):p.api(o,e.status)}handleFetchError(e,t){throw w(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${t} failed: ${e.message}`,e):e instanceof Error?p.business(`${t} failed: ${e.message}`):p.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw p.business("No files to deploy");for(let a of e)if(!a.md5)throw p.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),r={};return t.deployToken?r.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(r.Authorization=`Bearer ${t.apiKey}`),t.caller&&(r["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${h.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...r},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${h.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}${h.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:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${h.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainLabels(e,t){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update domain labels")}async removeDomain(e){await this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${h.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}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${h.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${h.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${h.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping")}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}${h.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};x();$();x();x();function V(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||k,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 oe(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}x();H();async function ut(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await L(t);return{path:K,content:t,size:e.length,md5:i}}async function Ce(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===K))return n;try{if(await e.checkSPA(n)){let o=await ut();return[...n,o]}}catch{}return n}function se(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:r}=n;return{create:async(a,c={})=>{await t();let s=o?oe(c,o):c;if(r&&!r()&&!s.deployToken&&!s.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw p.config("processInput function is not provided.");let f=e(),l=await i(a,s);return l=await Ce(l,f,s),f.deploy(l,s)},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 re(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>{await t();let{deployment:r,labels:a}=o;return r===void 0&&a&&a.length>0?e().updateDomainLabels(i,a):e().setDomain(i,r,a)},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 ae(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function pe(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 q=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 P({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=se({...i,processInput:(o,r)=>this.processInput(o,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=re(i),this._account=ae(i),this._tokens=pe(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=O(),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 p.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 p.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}};x();b();ce();$();x();var ue=E(require("mime-db"),1),fe={};for(let n in ue.default){let e=ue.default[n];e&&e.extensions&&e.extensions.forEach(t=>{fe[t]||(fe[t]=n)})}function we(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return fe[e]||"application/octet-stream"}async function Re(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),a=new i,c=[];for(let u of n){let d=we(u.path),g;if(Buffer.isBuffer(u.content))g=new o([u.content],u.path,{type:d});else if(typeof Blob<"u"&&u.content instanceof Blob)g=new o([u.content],u.path,{type:d});else throw p.file(`Unsupported file.content type for Node.js: ${u.path}`,u.path);if(!u.md5)throw p.file(`File missing md5 checksum: ${u.path}`,u.path);let v=u.path.startsWith("/")?u.path:"/"+u.path;a.append("files[]",g,v),c.push(u.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let s=new r(a),f=[];for await(let u of s.encode())f.push(Buffer.from(u));let l=Buffer.concat(f);return{body:l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),headers:{"Content-Type":s.contentType,"Content-Length":Buffer.byteLength(l).toString()}}}H();function dt(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}de();xe();b();x();var Oe=E(require("mime-db"),1),Fe=Oe.default,yt=new Set(Object.keys(Fe)),gt=new Map(Object.entries(Fe).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function W(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 xt(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 Dt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],o=gt.get(e);if(o&&!o.has(i))return!1}return!0}function Et(n,e){let t=[],i=[],o=[];if(n.length===0){let s={file:"(no files)",message:"At least one file must be provided"};return t.push(s),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let s={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(s),{files:n.map(f=>({...f,status:y.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let r=0;for(let s of n){let f=y.READY,l="Ready for upload",u=s.name?xt(s.name):{valid:!1,reason:"File name cannot be empty"};if(s.status===y.PROCESSING_ERROR)f=y.VALIDATION_FAILED,l=s.statusMessage||"File failed during processing",t.push({file:s.name,message:l});else if(s.size===0){f=y.EXCLUDED,l="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:s.name,message:l}),o.push({...s,status:f,statusMessage:l});continue}else s.size<0?(f=y.VALIDATION_FAILED,l="File size must be positive",t.push({file:s.name,message:l})):!s.name||s.name.trim().length===0?(f=y.VALIDATION_FAILED,l="File name cannot be empty",t.push({file:s.name||"(empty)",message:l})):s.name.includes("\0")?(f=y.VALIDATION_FAILED,l="File name contains invalid characters (null byte)",t.push({file:s.name,message:l})):u.valid?!s.type||s.type.trim().length===0?(f=y.VALIDATION_FAILED,l="File MIME type is required",t.push({file:s.name,message:l})):ee(s.type)?!B.some(d=>s.type===d)&&!yt.has(s.type)?(f=y.VALIDATION_FAILED,l=`Invalid MIME type "${s.type}"`,t.push({file:s.name,message:l})):Dt(s.name,s.type)?s.size>e.maxFileSize?(f=y.VALIDATION_FAILED,l=`File size (${W(s.size)}) exceeds limit of ${W(e.maxFileSize)}`,t.push({file:s.name,message:l})):(r+=s.size,r>e.maxTotalSize&&(f=y.VALIDATION_FAILED,l=`Total size would exceed limit of ${W(e.maxTotalSize)}`,t.push({file:s.name,message:l}))):(f=y.VALIDATION_FAILED,l="File extension does not match MIME type",t.push({file:s.name,message:l})):(f=y.VALIDATION_FAILED,l=`File type "${s.type}" is not allowed`,t.push({file:s.name,message:l})):(f=y.VALIDATION_FAILED,l=u.reason||"Invalid file name",t.push({file:s.name,message:l}));o.push({...s,status:f,statusMessage:l})}t.length>0&&(o=o.map(s=>s.status===y.EXCLUDED?s:{...s,status:y.VALIDATION_FAILED,statusMessage:s.status===y.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(s=>s.status===y.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function Ne(n){return n.filter(e=>e.status===y.READY)}function St(n){return Ne(n).length>0}x();ce();$();Ee();b();var J=class extends q{constructor(e={}){if(S()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return V(e,{})}async loadFullConfig(){try{let e=await G(this.clientOptions.configFile),t=V(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new P({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();z(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(r=>typeof r=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw p.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(Ee(),$e));return o(i,t)}getDeployBodyCreator(){return Re}},Le=J;0&&(module.exports={ALLOWED_MIME_TYPES,API_KEY_HEX_LENGTH,API_KEY_HINT_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isAllowedMimeType,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployToken,validateFiles});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|