apify-cli 1.10.1-beta.47 → 1.10.1-beta.49

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.
@@ -1,4 +1,4 @@
1
- import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,closeSync as w,constants as T,copyFileSync as E,createWriteStream as D,existsSync as O,fstat as k,mkdirSync as A,openSync as j,readFileSync as M,readdirSync as N,realpathSync as ee,renameSync as P,rmSync as F,statSync as te,unlinkSync as ne,writeFileSync as I,writeSync as re}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce}from"node:os";import le,{isCI as ue}from"ci-info";import{ACTOR_ENV_VARS as L,ACTOR_JOB_STATUSES as R,ACTOR_JOB_TERMINAL_STATUSES as de,ACTOR_JOB_TYPES as z,ACTOR_NAME as fe,ACTOR_SOURCE_TYPES as pe,APIFY_ENV_VARS as B,KEY_VALUE_STORE_KEYS as me,LOCAL_ACTOR_ENV_VARS as he,LOCAL_STORAGE_SUBDIRS as ge,MAX_MULTIFILE_BYTES as _e,META_ORIGINS as ve,SOURCE_FILE_FORMATS as ye}from"@apify/consts";import{jaroWinkler as be}from"@skyra/jaro-winkler";import xe from"js-levenshtein";import{ApifyApiError as Se,ApifyClient as Ce,DownloadItemsFormat as V}from"apify-client";import we,{AxiosHeaders as Te}from"axios";import{createHmacSignature as Ee,cryptoRandomObjectId as De}from"@apify/utilities";import{access as Oe,appendFile as ke,mkdir as H,readFile as U,readdir as Ae,rename as je,rm as Me,stat as W,symlink as Ne,unlink as Pe,writeFile as G}from"node:fs/promises";import{setTimeout as Fe}from"node:timers/promises";import{Result as Ie,err as Le,none as Re,ok as ze,some as Be}from"@sapphire/result";import{execa as Ve}from"execa";import He from"configparser";import Ue from"@inquirer/input";import We from"which";import{execSync as Ge,spawn as Ke}from"node:child_process";import{DurationFormatter as qe,Time as Je,TimeTypes as Ye}from"@sapphire/duration";import{Timestamp as Xe}from"@sapphire/timestamp";import Ze from"adm-zip";import Qe from"ajv/dist/2019.js";import{ZipArchive as $e}from"archiver";import et from"escape-string-regexp";import tt from"ignore";import{getEncoding as nt}from"istextorbinary";import rt,{Mime as it}from"mime";import at from"mime/types/other.js";import ot from"mime/types/standard.js";import{glob as st}from"tinyglobby";import{calculateRunDynamicMemory as ct}from"@apify/actor-memory-expression";import{Separator as lt,createPrompt as ut,isEnterKey as dt,makeTheme as ft,useKeypress as pt,usePrefix as mt,useState as ht}from"@inquirer/core";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import{pipeline as St}from"node:stream/promises";import{MemoryStorage as Ct}from"@crawlee/memory-storage";import wt from"cli-table3";import{downloadTemplate as Tt}from"giget";import Et from"jju";import Dt from"open";import{fetchManifest as Ot,manifestUrl as kt,wrapperManifestUrl as At}from"@apify/actor-templates";import jt from"computer-name";import Mt from"@inquirer/password";import{createServer as Nt}from"node:http";import{createHash as Pt,randomBytes as Ft}from"node:crypto";import It from"@inquirer/select";import Lt from"node:assert";import{ReadStream as Rt}from"node:tty";import zt from"detect-indent";import{fileURLToPath as Bt}from"node:url";import Vt from"@root/walk";import Ht from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ut=null;function useCLIMetadata(){if(Ut)return Ut;let e=detectInstallMethod(),t=getRuntimeInfo();return Ut={version:`1.10.1-beta.47`,hash:`aaf28e2701ea87127cb5456ed616a16b400f4f32`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ut.installPath=c(process.execPath)),Ut}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Wt=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
1
+ import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,closeSync as w,constants as T,copyFileSync as E,createWriteStream as D,existsSync as O,fstat as k,mkdirSync as A,openSync as j,readFileSync as M,readdirSync as N,realpathSync as ee,renameSync as P,rmSync as F,statSync as te,unlinkSync as ne,writeFileSync as I,writeSync as re}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce}from"node:os";import le,{isCI as ue}from"ci-info";import{ACTOR_ENV_VARS as L,ACTOR_JOB_STATUSES as R,ACTOR_JOB_TERMINAL_STATUSES as de,ACTOR_JOB_TYPES as z,ACTOR_NAME as fe,ACTOR_SOURCE_TYPES as pe,APIFY_ENV_VARS as B,KEY_VALUE_STORE_KEYS as me,LOCAL_ACTOR_ENV_VARS as he,LOCAL_STORAGE_SUBDIRS as ge,MAX_MULTIFILE_BYTES as _e,META_ORIGINS as ve,SOURCE_FILE_FORMATS as ye}from"@apify/consts";import{jaroWinkler as be}from"@skyra/jaro-winkler";import xe from"js-levenshtein";import{ApifyApiError as Se,ApifyClient as Ce,DownloadItemsFormat as V}from"apify-client";import we,{AxiosHeaders as Te}from"axios";import{createHmacSignature as Ee,cryptoRandomObjectId as De}from"@apify/utilities";import{access as Oe,appendFile as ke,mkdir as H,readFile as U,readdir as Ae,rename as je,rm as Me,stat as W,symlink as Ne,unlink as Pe,writeFile as G}from"node:fs/promises";import{setTimeout as Fe}from"node:timers/promises";import{Result as Ie,err as Le,none as Re,ok as ze,some as Be}from"@sapphire/result";import{execa as Ve}from"execa";import He from"configparser";import Ue from"@inquirer/input";import We from"which";import{execSync as Ge,spawn as Ke}from"node:child_process";import{DurationFormatter as qe,Time as Je,TimeTypes as Ye}from"@sapphire/duration";import{Timestamp as Xe}from"@sapphire/timestamp";import Ze from"adm-zip";import Qe from"ajv/dist/2019.js";import{ZipArchive as $e}from"archiver";import et from"escape-string-regexp";import tt from"ignore";import{getEncoding as nt}from"istextorbinary";import rt,{Mime as it}from"mime";import at from"mime/types/other.js";import ot from"mime/types/standard.js";import{glob as st}from"tinyglobby";import{calculateRunDynamicMemory as ct}from"@apify/actor-memory-expression";import{Separator as lt,createPrompt as ut,isEnterKey as dt,makeTheme as ft,useKeypress as pt,usePrefix as mt,useState as ht}from"@inquirer/core";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import{pipeline as St}from"node:stream/promises";import{MemoryStorage as Ct}from"@crawlee/memory-storage";import wt from"cli-table3";import{downloadTemplate as Tt}from"giget";import Et from"jju";import Dt from"open";import{fetchManifest as Ot,manifestUrl as kt,wrapperManifestUrl as At}from"@apify/actor-templates";import jt from"computer-name";import Mt from"@inquirer/password";import{createServer as Nt}from"node:http";import{createHash as Pt,randomBytes as Ft}from"node:crypto";import It from"@inquirer/select";import Lt from"node:assert";import{ReadStream as Rt}from"node:tty";import zt from"detect-indent";import{fileURLToPath as Bt}from"node:url";import Vt from"@root/walk";import Ht from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ut=null;function useCLIMetadata(){if(Ut)return Ut;let e=detectInstallMethod(),t=getRuntimeInfo();return Ut={version:`1.10.1-beta.49`,hash:`7a6fd6c733185edd36b89b031d59590cd78ba54f`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ut.installPath=c(process.execPath)),Ut}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Wt=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
2
2
  `)}function windowsCmdWrapperScript(e){return[`@echo off`,`setlocal`,`set "APIFY_CLI_ENTRYPOINT=${e}"`,`"%~dp0apify-cli.exe" %*`,``].join(`\r
3
3
  `)}function windowsPowershellWrapperScript(e){return[`#!/usr/bin/env pwsh`,`$prev = $env:APIFY_CLI_ENTRYPOINT`,`$env:APIFY_CLI_ENTRYPOINT = "${e}"`,`try {`,` & "$PSScriptRoot\\apify-cli.exe" @args`,`} finally {`,` $env:APIFY_CLI_ENTRYPOINT = $prev`,`}`,`exit $LASTEXITCODE`,``].join(`\r
4
4
  `)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{I(i,n),r!==void 0&&C(i,r),P(i,t)}catch(e){try{F(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{E(t,i),r!==void 0&&C(i,r),P(i,n)}catch(e){try{F(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Wt)atomicWriteSync(u(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(u(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(u(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=c(e.execPath),i=s(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Wt){let t=u(r,`${e}.exe.old`);if(O(t))try{F(t,{force:!0}),cliDebugPrint(`[migration] removed stale legacy binary`,t)}catch(e){cliDebugPrint(`[migration] failed to remove stale legacy binary`,{stalePath:t,err:e})}}if(i===`apify-cli`||!Wt.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=u(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n){for(let t of Wt){let n=u(r,`${t}.exe`);if(O(n))try{p(n)===p(e.execPath)?(P(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):F(n,{force:!0})}catch(e){try{P(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{F(t,{force:!0}),cliDebugPrint(`[migration] removed upgrade script, it will be re-downloaded on the next upgrade`)}catch(e){cliDebugPrint(`[migration] failed to remove upgrade script`,{upgradeScriptPath:t,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Gt;function getMaxLineWidth(){if(Gt)return Gt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Gt=e;else if(!process.stdout.isTTY)Gt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Gt=e<1?80:e<40?40:e}return Gt}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
@@ -49,7 +49,7 @@ Common package structures:
49
49
  `)}\n`,{flag:`a`})):I(n,`${i.join(`
50
50
  `)}\n`,{flag:`w`}))},$n=new it(ot,at).define({"application/gzip":[`tgz`],"text/typescript":[`ts`,`tsx`,`mts`]},!0),getSourceFileFormat=(e,t)=>{let n=$n.getType(e);return n?n.startsWith(`text/`)||n.includes(`javascript`)||n.includes(`json`)||n.includes(`xml`)||n.includes(`application/node`)||n.includes(`application/toml`)||n.includes(`application/x-sh`)||n.includes(`application/x-httpd-php`)?ye.TEXT:ye.BASE64:nt(t)===`binary`?ye.BASE64:ye.TEXT},createSourceFiles=async(e,t)=>e.map(e=>{let n=M(u(t,e)),r=getSourceFileFormat(e,n);return{name:e,format:r,content:r===ye.TEXT?n.toString(`utf8`):n.toString(`base64`)}}),getGitignoreFallbackFilter=async e=>{let t=await st(`**/.gitignore`,{dot:!0,cwd:e,ignore:[`.git/**`],expandDirectories:!1}),n=[];for(let r of t){let t=c(r),i=await U(u(e,r),`utf-8`);n.push({dir:t===`.`?``:t,ig:Yn().add(i)})}let r=c(e);for(;r!==c(r)&&!O(u(r,`.git`));){let t=u(r,`.gitignore`);if(O(t))try{let i=await U(t,`utf-8`),a=f(r,e);n.push({dir:``,ig:Yn().add(i),ancestorPrefix:a})}catch{}r=c(r)}return n.length===0?e=>e:e=>e.filter(e=>{for(let{dir:t,ig:r,ancestorPrefix:i}of n){let n;if(n=t?e.startsWith(`${t}/`)?e.slice(t.length+1):null:i?`${i}/${e}`:e,n!==null&&r.ignores(n))return!1}return!0})},parseActorIgnore=async e=>{let t=u(e,`.actorignore`);if(!O(t))return{excludeFilter:null,forceIncludePatterns:[]};let n=(await U(t,`utf-8`)).split(`
51
51
  `),r=[],i=[];for(let e of n){let t=e.trim();t&&!t.startsWith(`#`)&&(t.startsWith(`!`)?i.push(t.slice(1)):r.push(t))}return{excludeFilter:r.length>0?e=>{let t=Yn().add(r);return e.filter(e=>!t.ignores(e))}:null,forceIncludePatterns:i}},getActorLocalFilePaths=async t=>{let n=t??e.cwd(),r=[`.git/**`,`apify_storage`,`node_modules`,`storage`,`crawlee_storage`],{excludeFilter:i,forceIncludePatterns:a}=await parseActorIgnore(n),gitIgnoreFilter=null;try{let e=Ge(`git ls-files --others --ignored --exclude-standard --directory`,{cwd:n,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
52
- `).filter(Boolean);if(e.length>0){let t=Yn().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await st([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=Yn().add(a),t=s.filter(t=>e.ignores(t)),n=new Set(c);for(let e of t)n.add(e);c=[...n]}let l=s.filter(e=>e===`.actor`||e.startsWith(`.actor/`));if(l.length>0){let e=new Set(c);for(let t of l)e.add(t);c=[...e]}return c},createActZip=async(e,t,n)=>{O(e)&&await deleteFile(e);let r=D(e),i=new $e({zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(u(n,e),{name:e})),await i.finalize()},getLocalInput=(e,t)=>{let n=t??me.INPUT,r=p(e,getLocalKeyValueStorePath());if(!O(r))return;let i=readKvsRecordMetadata(r,n);if(i){let e=i.filename??encodeRecordKey(n);if(O(u(r,e)))return{body:M(u(r,e)),contentType:i.contentType,fileName:e}}let a=N(r).find(e=>!!e.match(inputFileRegExp(n)));return a?{body:M(u(r,a)),contentType:$n.getType(a),fileName:a}:void 0},purgeDefaultQueue=async()=>{await rimrafPromised(p(e.cwd(),getLocalRequestQueuePath()))},purgeDefaultDataset=async()=>{await rimrafPromised(p(e.cwd(),getLocalDatasetPath()))},purgeDefaultKeyValueStore=async(...t)=>{let n=p(e.cwd(),getLocalKeyValueStorePath());if(!O(n))return;let r=N(n),i=t.length>0?t:[me.INPUT],a=i.map(inputFileRegExp),s=new Set(i.flatMap(e=>[recordMetadataFileName(e),readKvsRecordMetadata(n,e)?.filename])),c=[];r.forEach(e=>{!s.has(e)&&!a.some(t=>t.test(e))&&c.push(deleteFile(u(n,e)))}),await Promise.all(c)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new Ce({baseUrl:e.env.APIFY_CLIENT_BASE_URL});if(de.includes(a)){if(e.env.APIFY_NO_LOGS_IN_TESTS)return;let t=await s.log(i).get();e.stderr.write(t);return}return new Promise(async t=>{let r=await s.log(i).stream();if(!r){t(`no-logs`);return}let a=null;r.on(`data`,t=>{e.env.APIFY_NO_LOGS_IN_TESTS||e.stderr.write(t.toString())}),r.once(`end`,()=>{t(`finished`),a&&clearTimeout(a)}),n!==void 0&&(a=setTimeout(()=>{r.destroy(),t(`timeouts`)},n))})},checkIfStorageIsEmpty=async t=>{let n=t||me.INPUT,r=getLocalStorageDir().replaceAll(`\\`,`/`),i=getLocalKeyValueStorePath().replaceAll(`\\`,`/`);return(await st([`${r}/**`,...[n,`${Kn}${n}`].flatMap(e=>[`!${i}/${e}`,`!${i}/${e}.*`])],{cwd:e.cwd()})).length===0},validateActorName=e=>{if(!fe.REGEX.test(e))throw Error(`The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).`);if(e.length<fe.MIN_LENGTH)throw Error(`The Actor name must be at least 3 characters long.`);if(e.length>fe.MAX_LENGTH)throw Error(`The Actor name must be a maximum of 30 characters long.`)},validateActorNameForPrompt=e=>{try{validateActorName(e)}catch(e){return e.message}return!0},sanitizeActorName=e=>{let t=e.replaceAll(/[^a-zA-Z0-9-]/g,`-`);return t.length<fe.MIN_LENGTH&&(t=`${t}-apify-actor`),t=t.replaceAll(/^-+/g,``).replaceAll(/-+$/g,``),t.slice(0,fe.MAX_LENGTH)},isPythonVersionSupported=e=>x(e,`^${dn}`),isNodeVersionSupported=e=>{let t=b(cn);return y(e,t)},downloadZip=async e=>{let t=await we.get(e,{responseType:`arraybuffer`,validateStatus:()=>!0,headers:{"User-Agent":`Apify CLI/${useCLIMetadata().version} (https://github.com/apify/apify-cli)`}});if(t.status<200||t.status>=300){let n=Buffer.from(t.data).toString(`utf8`).trim().slice(0,500);throw Error(`Failed to download the archive from ${e} (HTTP ${t.status}).${n?`\nServer response: ${n}`:``}`)}let n=Buffer.from(t.data);if(n.subarray(0,2).toString()!==`PK`)throw Error(`The file downloaded from ${e} is not a valid zip archive - a proxy or firewall likely intercepted the download. Check your network or try a different one.`);return new Ze(n)},downloadAndUnzip=async({url:e,pathTo:t})=>{(await downloadZip(e)).extractAllTo(t,!0)},q=new Xe(`YYYY-MM-DD [at] HH:mm:ss`),er=new Xe(`YYYY-MM-DD[
52
+ `).filter(Boolean);if(e.length>0){let t=Yn().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await st([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=Yn().add(a),t=s.filter(t=>e.ignores(t)),n=new Set(c);for(let e of t)n.add(e);c=[...n]}let l=s.filter(e=>e===`.actor`||e.startsWith(`.actor/`));if(l.length>0){let e=new Set(c);for(let t of l)e.add(t);c=[...e]}return c},createActZip=async(e,t,n)=>{O(e)&&await deleteFile(e);let r=D(e),i=new $e({zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(u(n,e),{name:e})),await i.finalize()},getLocalInput=(e,t)=>{let n=t??me.INPUT,r=p(e,getLocalKeyValueStorePath());if(!O(r))return;let i=readKvsRecordMetadata(r,n);if(i){let e=i.filename??encodeRecordKey(n);if(O(u(r,e)))return{body:M(u(r,e)),contentType:i.contentType,fileName:e}}let a=N(r).find(e=>!!e.match(inputFileRegExp(n)));return a?{body:M(u(r,a)),contentType:$n.getType(a),fileName:a}:void 0},purgeDefaultQueue=async()=>{await rimrafPromised(p(e.cwd(),getLocalRequestQueuePath()))},purgeDefaultDataset=async()=>{await rimrafPromised(p(e.cwd(),getLocalDatasetPath()))},purgeDefaultKeyValueStore=async(...t)=>{let n=p(e.cwd(),getLocalKeyValueStorePath());if(!O(n))return;let r=N(n),i=t.length>0?t:[me.INPUT],a=i.map(inputFileRegExp),s=new Set(i.flatMap(e=>[recordMetadataFileName(e),readKvsRecordMetadata(n,e)?.filename])),c=[];r.forEach(e=>{!s.has(e)&&!a.some(t=>t.test(e))&&c.push(deleteFile(u(n,e)))}),await Promise.all(c)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new Ce({baseUrl:e.env.APIFY_CLIENT_BASE_URL});if(de.includes(a)){if(e.env.APIFY_NO_LOGS_IN_TESTS)return;let t=await s.log(i).get();e.stderr.write(t);return}return new Promise(async t=>{let r=await s.log(i).stream();if(!r){t(`no-logs`);return}let a=null;r.on(`data`,t=>{e.env.APIFY_NO_LOGS_IN_TESTS||e.stderr.write(t.toString())}),r.once(`end`,()=>{t(`finished`),a&&clearTimeout(a)}),n!==void 0&&(a=setTimeout(()=>{r.destroy(),t(`timeouts`)},n))})},checkIfStorageIsEmpty=async t=>{let n=t||me.INPUT,r=getLocalStorageDir().replaceAll(`\\`,`/`),i=getLocalKeyValueStorePath().replaceAll(`\\`,`/`);return(await st([`${r}/**`,...[n,`${Kn}${n}`].flatMap(e=>[`!${i}/${e}`,`!${i}/${e}.*`])],{cwd:e.cwd()})).length===0},validateActorName=e=>{if(!fe.REGEX.test(e))throw Error(`The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).`);if(e.length<fe.MIN_LENGTH)throw Error(`The Actor name must be at least ${fe.MIN_LENGTH} characters long.`);if(e.length>fe.MAX_LENGTH)throw Error(`The Actor name must be at most ${fe.MAX_LENGTH} characters long.`)},validateActorNameForPrompt=e=>{try{validateActorName(e)}catch(e){return e.message}return!0},sanitizeActorName=e=>{let t=e.replaceAll(/[^a-zA-Z0-9-]/g,`-`);return t.length<fe.MIN_LENGTH&&(t=`${t}-apify-actor`),t=t.replaceAll(/^-+/g,``).replaceAll(/-+$/g,``),t.slice(0,fe.MAX_LENGTH)},isPythonVersionSupported=e=>x(e,`^${dn}`),isNodeVersionSupported=e=>{let t=b(cn);return y(e,t)},downloadZip=async e=>{let t=await we.get(e,{responseType:`arraybuffer`,validateStatus:()=>!0,headers:{"User-Agent":`Apify CLI/${useCLIMetadata().version} (https://github.com/apify/apify-cli)`}});if(t.status<200||t.status>=300){let n=Buffer.from(t.data).toString(`utf8`).trim().slice(0,500);throw Error(`Failed to download the archive from ${e} (HTTP ${t.status}).${n?`\nServer response: ${n}`:``}`)}let n=Buffer.from(t.data);if(n.subarray(0,2).toString()!==`PK`)throw Error(`The file downloaded from ${e} is not a valid zip archive - a proxy or firewall likely intercepted the download. Check your network or try a different one.`);return new Ze(n)},downloadAndUnzip=async({url:e,pathTo:t})=>{(await downloadZip(e)).extractAllTo(t,!0)},q=new Xe(`YYYY-MM-DD [at] HH:mm:ss`),er=new Xe(`YYYY-MM-DD[
53
53
  ]HH:mm:ss`),tr=new Xe(`YYYY-MM-DD`),nr=new qe,rr=new qe({[Ye.Day]:{DEFAULT:`d`},[Ye.Hour]:{DEFAULT:`h`},[Ye.Minute]:{DEFAULT:`m`},[Ye.Month]:{DEFAULT:`M`},[Ye.Second]:{DEFAULT:`s`},[Ye.Week]:{DEFAULT:`w`},[Ye.Year]:{DEFAULT:`y`}});function objectGroupBy(e,t){if(`groupBy`in Object)return Object.groupBy(e,t);let n={},r=0;for(let i of e){let e=t(i,r++);n[e]||(n[e]=[]),n[e].push(i)}return n}function printJsonToStdout(e){console.log(JSON.stringify(e,null,2))}const userHomeDir=()=>e.env.HOME??se(),tildify=e=>{let t=userHomeDir();return t&&e.startsWith(t)?e.replace(t,`~`):e};function detectShell(){let t=e.env.SHELL??``;return t.includes(`zsh`)?`zsh`:t.includes(`bash`)?`bash`:t.includes(`fish`)?`fish`:`unknown`}function shellConfigFile(t,n){switch(n){case`bash`:{let n=[u(t,`.bashrc`),u(t,`.bash_profile`)];e.env.XDG_CONFIG_HOME&&n.push(u(e.env.XDG_CONFIG_HOME,`.bashrc`),u(e.env.XDG_CONFIG_HOME,`.bash_profile`),u(e.env.XDG_CONFIG_HOME,`bashrc`),u(e.env.XDG_CONFIG_HOME,`bash_profile`));for(let e of n)if(O(e))return e;return null}case`zsh`:{let n=e.env.ZDOTDIR||t||userHomeDir();return u(n,`.zshrc`)}case`fish`:return u(t,`.config`,`fish`,`config.fish`);case`unknown`:return null}}function parseWaitForFinishMillis(e){if(e===void 0)return;let t=Number.parseInt(e,10);if(!(!Number.isFinite(t)||t<0))return t*1e3}const ir=[`Apify collects telemetry data about general usage of Apify CLI to help us improve the product.`,`This feature is enabled by default, and you can disable it by setting the "APIFY_CLI_DISABLE_TELEMETRY" environment variable to "1", or by running "apify telemetry disable".`,`You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry.`].join(`
54
54
  `);function createAnonymousId(){return`CLI:${De()}`}async function migrateStateV0ToV1(e){if(e.version&&e.version>=1)return!1;let t=e,n=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0},e=>{n.id&&t.distinctId===n.id?(e.anonymousId=createAnonymousId(),e.userId=n.id):e.anonymousId=t.distinctId}),!0}async function useTelemetryState(){let e=TELEMETRY_FILE_PATH();if(!O(e)){let e=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0,anonymousId:createAnonymousId(),userId:e.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||[`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&info({message:ir}),useTelemetryState()}let t=JSON.parse(M(e,`utf-8`));return await migrateStateV0ToV1(t)?useTelemetryState():t}function updateTelemetryState(e,t){let n={...e};t?.(n);let r=TELEMETRY_FILE_PATH(),i=c(r);A(i,{recursive:!0}),I(TELEMETRY_FILE_PATH(),JSON.stringify(n,null,` `))}async function updateUserId(e){updateTelemetryState(await useTelemetryState(),t=>{t.userId=e})}async function checkAndUpdateLastCommand(e){try{let t=await useTelemetryState(),n=Date.now(),r=t.lastCommand===e&&n-(t.lastCommandTimestamp??0)<1e4;return updateTelemetryState(t,t=>{t.lastCommand=e,t.lastCommandTimestamp=n}),r}catch{return!1}}async function updateTelemetryEnabled(e){updateTelemetryState(await useTelemetryState(),t=>{t.enabled=e})}async function useTelemetryEnabled(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&![`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return cliDebugPrint(`telemetry`,`disabled by env variable`),!1;let e=await useTelemetryState();return cliDebugPrint(`telemetry state`,{telemetryState:e}),e.enabled}async function useTelemetryIdentifiers(){let e=await useTelemetryState();return{anonymousId:e.anonymousId,userId:e.userId}}const ar=useCLIMetadata(),or=ar.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:ar.version,build:ar.hash},library:{name:`apify-cli`,version:ar.version},os:{name:ar.platform},userAgent:vn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:(/* @__PURE__ */ new Date()).toISOString(),userId:n.userId,writeKey:or};if(cliDebugPrint(`trackEvent`,r),!await useTelemetryEnabled()){cliDebugPrint(`trackEvent`,`telemetry disabled`);return}try{let e=await fetch(`https://api.segment.io/v1/track`,{method:`POST`,body:JSON.stringify(r)});if(!e.ok){cliDebugPrint(`trackEvent`,`failed to send event`,await e.text());return}cliDebugPrint(`trackEvent`,`event sent`)}catch(e){cliDebugPrint(`trackEvent`,`failed to send event`,e)}}function shouldSkipRentalSunsetNotice({now:e,isCi:t,skipEnvValue:n}){return!!(n&&![`0`,`false`].includes(n)||t||e>=an)}function wasNotifiedRecently(e,t,n){return!e?.lastNotifiedAt||e.username!==t?!1:n-e.lastNotifiedAt<864e5}function renderRentalSunsetNotice(e){let n=e===1?`rental Actor`:`rental Actors`;return[t.bold(`Rental model sunset`),``,`You have ${e} ${n} published in Apify Store. Apify is sunsetting the rental pricing model.`,``,` ${t.bold(`April 1, 2026`)} Publishing new rental Actors and pricing changes on existing ones were disabled.`,` ${t.bold(`October 1, 2026`)} Rental Actors are fully retired. All remaining Actors move to pay-per-usage pricing.`,``,`Switch your ${n} to pay-per-event before October 1 to keep control over what you charge.`,`This guide walks through picking events, setting prices, and shipping the change:`,` ${t.cyan(`https://blog.apify.com/migrating-to-pay-per-event-pricing/`)}`,``,`Questions? Ask in the ${t.cyan(`#project-rentals`)} channel on Apify Discord:`,` ${t.cyan(`https://apify.com/discord`)}`,``,t.dim(`To silence this notice, set APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE=1.`),``].join(`
55
55
  `)}function getLocalUsername(){return getCurrentProfile()?.username}async function fetchRentalActorCount(t){let n=useCLIMetadata(),r=new URL(`/v2/store`,e.env.APIFY_CLIENT_BASE_URL||`https://api.apify.com`);try{let{data:e}=await we.get(r.href,{params:{username:t,pricingModel:`FLAT_PRICE_PER_MONTH`,limit:1},timeout:3e3,headers:{...un,"User-Agent":`Apify CLI/${n.version} (https://github.com/apify/apify-cli)`}});return typeof e?.data?.total==`number`?e.data.total:(cliDebugPrint(`useRentalSunsetNotice`,`Store response has no data.total`,{body:e}),null)}catch(e){return cliDebugPrint(`useRentalSunsetNotice`,`Failed to look up rental Actors`,e),null}}async function resolveRentalActorCount(e,t,n){let r=e?.username===t?e:void 0;return r&&n-r.lastChecked<864e5?{rentalActorCount:r.rentalActorCount,lastChecked:r.lastChecked,fromCache:!0}:{rentalActorCount:await fetchRentalActorCount(t)??r?.rentalActorCount??0,lastChecked:n,fromCache:!1}}async function useRentalSunsetNotice(){try{let t=Date.now(),n=useLocalState();if(shouldSkipRentalSunsetNotice({now:t,isCi:ue,skipEnvValue:e.env.APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE}))return;let r=getLocalUsername();if(!r){cliDebugPrint(`useRentalSunsetNotice`,`Not logged in, skipping the check`);return}if(wasNotifiedRecently(n.rentalSunset,r,t))return;let{rentalActorCount:i,lastChecked:a,fromCache:s}=await resolveRentalActorCount(n.rentalSunset,r,t),c=i>0;if(s&&!c||(updateLocalState(n,e=>{e.rentalSunset={lastChecked:a,username:r,rentalActorCount:i,...c?{lastNotifiedAt:t}:{}}}),!c))return;simpleLog({message:``}),warning({message:renderRentalSunsetNotice(i)})}catch(e){cliDebugPrint(`useRentalSunsetNotice`,`Failed to run the rental sunset check`,e)}}function camelCaseString(e){return e.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}function kebabCaseString(e){return e.replace(/[\s_]+/g,`-`)}function camelCaseToKebabCase(e){return e.replace(/([A-Z])/g,`-$1`).toLowerCase()}const sr={type:`boolean`,multiple:!1,short:`h`},cr={type:`boolean`,multiple:!1},lr={type:`string`,multiple:!1},ur={type:`string`,multiple:!1},dr=`user-agent`,fr=/* @__PURE__ */ new Set([`apify`]);function sanitizeUserAgentValue(e){if(typeof e!=`string`)return;let t=e.replace(/[\u0000-\u001f\u007f]/g,``).trim();if(t)return t.length>256?t.slice(0,256):t}function resolveUserAgentForTelemetry(e,t){return sanitizeUserAgentValue(e)??sanitizeUserAgentValue(t)}const J=/* @__PURE__ */ new Map,pr=[`init`,`run`,`push`,`actors push`,`pull`,`actors pull`,`call`,`actors call`,`actors start`];var ApifyCommand=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static enableProfileFlag=!1;static name;static shortDescription;static description;static examples;static docsUrl;static interactive;static interactiveNote;static group;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;commandString;aliasUsed;subcommandAliasUsed;skipTelemetry=!1;skipNotices=!1;constructor(e,t,n,r){this.entrypoint=e,this.commandString=t,this.aliasUsed=n,this.subcommandAliasUsed=r;let i=useCLIMetadata();this.telemetryData.installMethod=i.installMethod,this.telemetryData.osArch=i.arch,this.telemetryData.runtime=i.runtime.runtime,this.telemetryData.runtimeVersion=i.runtime.version,this.telemetryData.runtimeNodeVersion=i.runtime.nodeVersion??i.runtime.version,this.telemetryData.commandString=t,this.telemetryData.entrypoint=e;let a=detectCi();this.telemetryData.aiAgent=detectAiAgent(),this.telemetryData.isCi=a.isCi,this.telemetryData.ciProvider=a.ciProvider,this.telemetryData.isInteractive=detectIsInteractive()}get ctor(){return this.constructor}pluralString(e,t,n){return e===1?t:n}static printHelp(){console.log(renderHelpForCommand(this)),e.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(t){let n=Date.now(),{values:r,positionals:i,tokens:a}=t;if(r.help&&this.ctor.printHelp(),fr.has(this.entrypoint)){let t=r[dr],n=resolveUserAgentForTelemetry(typeof t==`string`?t:void 0,e.env.APIFY_CLI_USER_AGENT);n&&(this.telemetryData.userAgent=n)}this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof r.json==`boolean`?this.flags.json=r.json:this.flags.json=!1,this.flags.json&&keepStdoutClean());let s=/* @__PURE__ */ new Map;if(this.ctor.args){let e=0;for(let[t,n]of Object.entries(this.ctor.args)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let r=camelCaseString(t),a=i[e++];a?(n.argTag,this.args[r]=String(a),a===`-`&&n.stdin&&(this.args[r]=this._handleStdin(n.stdin)),n.catchAll&&(this.args[r]=i.slice(e-1).join(` `))):n.required&&s.set(t,n)}}if(s.size){e.exitCode=1,this._printMissingRequiredArgs(s);return}this._parseFlags(r,a);try{this.ctor.enableProfileFlag&&typeof r.profile==`string`&&(this.flags.profile=r.profile,await selectProfile(r.profile)),await this.run()}catch(t){error({message:t.message}),e.exitCode||=1}finally{!this.telemetryData.actorLanguage&&pr.includes(this.commandString)&&(await useCwdProject()).inspect(e=>{e.type===0?(this.telemetryData.actorLanguage=`javascript`,this.telemetryData.actorRuntime=e.runtime.runtimeShorthand||`node`,this.telemetryData.actorRuntimeVersion=e.runtime.version):(e.type===1||e.type===2)&&(this.telemetryData.actorLanguage=`python`,this.telemetryData.actorRuntime=`python`,this.telemetryData.actorRuntimeVersion=e.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof e.exitCode==`number`?e.exitCode:0,this.telemetryData.durationMs=Date.now()-n,this.telemetryData.wasRetried=await checkAndUpdateLastCommand(this.commandString),await trackEvent(`cli_command`,this.telemetryData)),!this.skipNotices&&!e.exitCode&&await useRentalSunsetNotice()}}_userFlagNameToRegisteredName(e,t){let n=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),r=n;n.startsWith(`no-`)&&(r=n.slice(3));let i=/* @__PURE__ */ new Set;for(let e of t.aliases??[])i.add(kebabCaseString(camelCaseToKebabCase(e)).toLowerCase());return{baseFlagName:r,rawBaseFlagName:n,allMatchers:[r,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();return t.startsWith(`no-`)&&(t=t.slice(3)),t}_parseFlags(e,n){if(!this.ctor.flags)return;let r=/* @__PURE__ */ new Map,i;for(let[a,s]of Object.entries(this.ctor.flags)){if(typeof s==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let{allMatchers:c,baseFlagName:l,rawBaseFlagName:u}=this._userFlagNameToRegisteredName(a,s),f=camelCaseString(u),p=n.some(e=>e.kind===`option`&&e.name===l);if(s.exclusive?.length){let e=r.get(l)??/* @__PURE__ */ new Set;for(let t of s.exclusive)e.add(this._commandFlagKeyToKebabCaseRegisteredName(t));r.set(l,e);for(let e of s.exclusive){let t=this._commandFlagKeyToKebabCaseRegisteredName(e),n=r.get(t)??/* @__PURE__ */ new Set;n.add(l),r.set(t,n)}}let m=c.filter(t=>Object.hasOwn(e,t));if(m.length>1)throw new Qt({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(h===void 0&&s.required)throw new Qt({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0]}});if(Array.isArray(h)){if(h.length>1)throw new Qt({code:3,command:this.ctor,metadata:{flag:l}});h=h[0]}if(p&&typeof h==`string`&&h.startsWith(`=`)&&(h=h.slice(1)),h!==void 0)switch(s.flagTag){case`boolean`:this.flags[f]=u.startsWith(`no-`)?!h:h;break;case`integer`:{let e=Number(h);if(Number.isNaN(e)||!Number.isInteger(e))throw new Qt({code:4,command:this.ctor,metadata:{flag:l,value:String(h)}});this.flags[f]=e;break}default:if(this.flags[f]=h,h===`-`&&s.stdin){if(i)throw new Qt({code:8,command:this.ctor,metadata:{firstUse:i,secondUse:l}});i=l,this.flags[f]=this._handleStdin(s.stdin)}}else s.hasDefault!==void 0&&(this.flags[f]=s.hasDefault);if(this.flags[f]!=null&&s.choices&&!s.choices.includes(this.flags[f]))throw new Qt({code:5,command:this.ctor,metadata:{flag:l,choices:s.choices.map(e=>t.white.bold(e)).join(`, `)}});if(this.flags[f]==null&&(s.required||h!=null))throw new Qt({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0],providedButReceivedNoValue:!!h}})}let a=[];for(let[t,n]of r)if(e[t]!=null)for(let r of n){if(e[r]==null)continue;let n=e[t][0],i=e[r][0],flagRepresentation=(e,t)=>typeof t==`boolean`?t?`--${e}`:`--no-${e}`:`--${e}=${t}`;a.push([flagRepresentation(t,n),flagRepresentation(r,i)]);break}if(a.length)throw new Qt({code:7,command:this.ctor,metadata:{flagPairs:a}})}_printMissingRequiredArgs(e){let a;try{a=selectiveRenderHelpForCommand(this.ctor,{showUsageString:!0})}catch{}let s=r([...e.keys()].join(`
@@ -246,4 +246,4 @@ When no path is provided, validates all schemas found in '${K}':
246
246
  - Dataset schema (from "storages.dataset")
247
247
  - Output schema (from "output")
248
248
  - Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${K}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});if(e){n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${K}'`}`});let t=new Xn({strict:!1});_t(t,e),success({message:`Input schema is valid.`})}}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${K}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${K}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Li=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],Ri=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Li as n,processVersionCheck as r,Ri as t};
249
- //# sourceMappingURL=_register-JSkXnn0S.js.map
249
+ //# sourceMappingURL=_register-B65HK9s1.js.map