apify-cli 1.14.1-beta.0 → 1.14.1-beta.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.
|
@@ -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{appendFileSync as a,chmodSync as s,closeSync as c,constants as l,copyFileSync as u,createWriteStream as f,existsSync as p,fstat as m,lstatSync as h,mkdirSync as g,openSync as _,readFileSync as v,readdirSync as y,readlinkSync as b,realpathSync as x,renameSync as S,rmSync as C,statSync as w,unlinkSync as T,writeFileSync as E,writeSync as D}from"node:fs";import{ApifyApiError as O,ApifyClient as k,DownloadItemsFormat as A}from"apify-client";import j,{AxiosHeaders as M}from"axios";import{ACTOR_ENV_VARS as N,ACTOR_JOB_STATUSES as P,ACTOR_JOB_TERMINAL_STATUSES as ee,ACTOR_JOB_TYPES as F,ACTOR_NAME as te,ACTOR_SOURCE_TYPES as ne,APIFY_ENV_VARS as I,KEY_VALUE_STORE_KEYS as re,LOCAL_ACTOR_ENV_VARS as ie,LOCAL_STORAGE_SUBDIRS as ae,MAX_MULTIFILE_BYTES as oe,META_ORIGINS as se,SOURCE_FILE_FORMATS as ce}from"@apify/consts";import{createHmacSignature as le,cryptoRandomObjectId as L}from"@apify/utilities";import{homedir as ue,platform as de,tmpdir as fe}from"node:os";import R,{basename as pe,dirname as z,isAbsolute as me,join as B,posix as he,relative as V,resolve as H,sep as ge}from"node:path";import _e,{isCI as ve}from"ci-info";import{access as ye,appendFile as be,mkdir as U,mkdtemp as xe,readFile as Se,readdir as Ce,rename as we,rm as Te,stat as W,symlink as Ee,unlink as De,writeFile as G}from"node:fs/promises";import{setTimeout as Oe}from"node:timers/promises";import{execa as K}from"execa";import ke from"which";import{once as Ae}from"node:events";import{inspect as je,parseArgs as Me,promisify as Ne}from"node:util";import{Result as Pe,err as Fe,none as Ie,ok as Le,some as Re}from"@sapphire/result";import{gt as ze,gte as Be,minVersion as Ve,satisfies as He}from"semver";import Ue from"string-width";import We from"strip-ansi";import{jaroWinkler as Ge}from"@skyra/jaro-winkler";import Ke from"js-levenshtein";import{execFileSync as qe,execSync as Je,spawn as Ye}from"node:child_process";import{finished as Xe,pipeline as Ze}from"node:stream/promises";import{DurationFormatter as Qe,Time as $e,TimeTypes as et}from"@sapphire/duration";import{Timestamp as tt}from"@sapphire/timestamp";import nt from"adm-zip";import rt from"ajv/dist/2019.js";import{TarArchive as it,ZipArchive as at}from"archiver";import ot from"escape-string-regexp";import st from"ignore";import{getEncoding as ct}from"istextorbinary";import lt,{Mime as ut}from"mime";import dt from"mime/types/other.js";import ft from"mime/types/standard.js";import{glob as pt}from"tinyglobby";import mt from"configparser";import ht from"@inquirer/input";import{Separator as gt,createPrompt as _t,isEnterKey as vt,makeTheme as yt,useKeypress as bt,usePrefix as xt,useState as St}from"@inquirer/core";import{compile as Ct}from"json-schema-to-typescript";import{validateInputSchema as wt,validateInputUsingValidator as Tt}from"@apify/input_schema";import{getDatasetSchemaValidator as Et,getKeyValueStoreSchemaValidator as Dt,getOutputSchemaValidator as Ot}from"@apify/json_schemas";import{MemoryStorage as kt}from"@crawlee/memory-storage";import At from"cli-table3";import{downloadTemplate as jt}from"giget";import Mt from"jju";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"open";import{fetchManifest as Lt,manifestUrl as Rt,wrapperManifestUrl as zt}from"@apify/actor-templates";import Bt from"@inquirer/checkbox";import Vt from"computer-name";import Ht from"@inquirer/password";import{createServer as Ut}from"node:http";import Wt from"@inquirer/select";import Gt from"node:assert";import{ReadStream as Kt}from"node:tty";import qt from"detect-indent";import{fileURLToPath as Jt}from"node:url";import Yt from"@root/walk";import Xt from"handlebars";var Zt={node:`>=22`};const Qt=`storage`,$t={$schema:`https://apify.com/schemas/v1/actor.ide.json`,actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},en=Date.UTC(2026,9,1),tn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=B(ue(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?B(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),ACTOR_RUNTIME_CONFIG_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`actor-runtime`,`config.json`),nn=`apify.json`,rn=`.actor`,q=B(rn,`actor.json`),an=Zt.node,on=_e.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,sn={"X-Apify-Request-Origin":_e.isCI?se.CI:se.CLI,...on&&{"X-Apify-Github-Actions-Run-Url":on}},cn=`3.11.0`,updateLocalJson=async(e,t={},n=null)=>{let r=await Se(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await G(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(ge).reduce((e,t)=>(e=B(e,t),p(e)||g(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Te(e,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})))},deleteFile=async e=>{(await W(e)).isFile()&&await De(e)};function ensureApifyDirectory(e){let t=z(e);g(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>W(B(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0);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 cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}let ln;function parseAuthFile(){if(!p(AUTH_FILE_PATH()))return{};try{let e=JSON.parse(v(AUTH_FILE_PATH(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?null:e}catch{return null}}function readAuthFile(){return parseAuthFile()??{}}function writeAuthFile(e){atomicWriteJson(AUTH_FILE_PATH(),e)}function atomicWriteJson(e,t){ensureApifyDirectory(e);let n=`${e}.tmp-${L(8)}`;try{E(n,JSON.stringify(t,null,` `),{mode:384}),S(n,e)}catch(e){throw C(n,{force:!0}),e}}function v1Profile(e){return{...typeof e.username==`string`?{username:e.username}:{},name:null,...typeof e.organizationOwnerUserId==`string`?{organizationOwnerUserId:e.organizationOwnerUserId}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:null}}function toV2(e){let t={version:2,profiles:{}};return typeof e.id==`string`&&(t.activeProfile=e.id,t.profiles[e.id]=v1Profile(e)),typeof e.token==`string`&&(t.token=e.token),typeof e.proxy?.password==`string`&&(t.proxy={password:e.proxy.password}),t}const un={1:toV2};async function migrateAuthFile(){return ln??=(async()=>{try{let e=parseAuthFile();if(!e||Object.keys(e).length===0)return;let t=typeof e.version==`number`?e.version:1;if(t>=2)return;let n=e;for(let e=t;e<2;e++){let t=un[e];if(!t)throw Error(`No migration step from auth file version ${e}.`);n=t(n)}writeAuthFile(n)}catch(e){cliDebugPrint(`auth-file`,`auth file migration failed`,e),warning({message:`Your stored login cannot be read until ${AUTH_FILE_PATH()} is updated to the current format, and the update failed. Make the directory it is in writable, then run the command again. Set APIFY_CLI_DEBUG=1 to see why.`})}})(),ln}function assertSupportedAuthFileVersion(){let{version:e}=readAuthFile();if(typeof e==`number`&&e>2)throw Error(`Your credentials in ${AUTH_FILE_PATH()} were written by a newer Apify CLI. It uses auth file version ${e} and this one reads 2. Upgrade the CLI, or run "apify logout" to discard them.`)}async function ensureAuthFileCurrent(){await migrateAuthFile(),assertSupportedAuthFileVersion()}function lookUpActiveProfile(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?{profile:{id:t.id,...v1Profile(t)}}:{}}if(!e.activeProfile)return{};let t=e.profiles?.[e.activeProfile];return t?{profile:{id:e.activeProfile,...t}}:{missingProfile:e.activeProfile}}function profileLabel(e){return e.name??e.username??e.id}function listProfiles(){let e=readAuthFile();if(e.version!==2){let{profile:e}=lookUpActiveProfile();return e?[e]:[]}return Object.entries(e.profiles??{}).map(([e,t])=>({id:e,...t}))}function matchProfiles(e){let t=listProfiles(),n=t.find(({id:t})=>t===e);return n?[n]:t.filter(t=>profileLabel(t)===e)}function lookUpProfile(e){let t=listProfiles().find(({id:t})=>t===e);return t?{profile:t}:{missingProfile:e}}function setActiveProfile(e){let t=readAuthFile();t.profiles?.[e]&&(t.activeProfile=e,writeAuthFile(t))}function getActiveProfile(){return lookUpActiveProfile().profile}function getActiveProfileId(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?t.id:void 0}return e.activeProfile}function readProfileSecret(e,t){let n=readAuthFile().profiles?.[e];if(n)switch(t){case`token`:return n.token;case`refresh-token`:return n.refreshToken;default:return n.proxy?.password}}function writeProfileSecret(e,t,n){updateProfile(e,e=>setProfileSecret(e,t,n))}function clearProfileFileSecrets(e){let t=readAuthFile().profiles?.[e];(t?.token!==void 0||t?.proxy!==void 0||t?.refreshToken!==void 0)&&updateProfile(e,e=>{delete e.token,delete e.proxy,delete e.refreshToken})}function setProfileSecret(e,t,n){t===`token`?e.token=n:t===`refresh-token`?e.refreshToken=n:e.proxy={...e.proxy,password:n}}function deleteProfileSecret(e,t){readProfileSecret(e,t)!==void 0&&updateProfile(e,e=>{t===`token`?delete e.token:t===`refresh-token`?delete e.refreshToken:delete e.proxy})}function updateProfile(e,t){let n=readAuthFile(),r=n.profiles?.[e];r&&(t(r),writeAuthFile(n))}function updateProfileAuth(e,t){updateProfile(e,e=>{e.authMethod=t.authMethod,e.expiresAt=t.expiresAt,e.hasRefreshToken=t.hasRefreshToken,t.oauth?e.oauth=t.oauth:delete e.oauth})}function upsertProfile(e,t){assertSupportedAuthFileVersion();let n=readAuthFile(),r=n.version===2?n:{version:2};r.profiles??={},delete r.token,delete r.proxy;let i=r.profiles[e];r.profiles[e]={...t,...i?.token?{token:i.token}:{},...i?.proxy?{proxy:i.proxy}:{},...i?.refreshToken?{refreshToken:i.refreshToken}:{}},r.activeProfile=e,writeAuthFile(r)}function removeProfile(e){let t=readAuthFile();if(t.version!==2)return discardAuthFile(),{};let n=e??t.activeProfile,r=n?t.profiles?.[n]:void 0,i=n&&r?{id:n,...r}:void 0;if(n&&t.profiles&&delete t.profiles[n],n!==t.activeProfile){writeAuthFile(t);let e=t.activeProfile?t.profiles?.[t.activeProfile]:void 0;return{removed:i,active:e&&{id:t.activeProfile,...e}}}delete t.activeProfile,delete t.token,delete t.proxy;let[a]=Object.entries(t.profiles??{}).sort(([,e],[,t])=>(t.loggedInAt??``).localeCompare(e.loggedInAt??``)).map(([e])=>e);return a?(t.activeProfile=a,writeAuthFile(t),{removed:i,active:{id:a,...t.profiles[a]}}):(discardAuthFile(),{removed:i})}function removeAllProfiles(){discardAuthFile()}function discardAuthFile(){C(AUTH_FILE_PATH(),{force:!0,maxRetries:10,retryDelay:100})}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=x(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 dn=null;function useCLIMetadata(){if(dn)return dn;let e=detectInstallMethod(),t=getRuntimeInfo();return dn={version:`1.14.1-beta.0`,hash:`f000375deeb569854733efa3ca279fb07fd3b14a`,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`&&(dn.installPath=z(process.execPath)),dn}const fn=`com.apify.cli`,pn=[`token`,`proxy-password`,`refresh-token`];function keyringKey(e,t){return{service:`${fn}.${t}`,account:e}}function legacyKeyringKey(e){return{service:fn,account:e}}let mn,hn,gn,_n;async function loadKeyringModule(){return mn===void 0&&(mn=await importKeyringModule()),mn}async function importKeyringModule(){if(useCLIMetadata().installMethod===`bundle`)try{let e=await import(`__APIFY_KEYRING_NATIVE_SUBPACKAGE__`),t=e.Entry??e.default?.Entry;return t?{Entry:t}:null}catch(e){return cliDebugPrint(`credentials`,`failed to load bundled keyring`,e),null}try{return await import(`@napi-rs/keyring`)}catch(e){return cliDebugPrint(`credentials`,`failed to load @napi-rs/keyring`,e),null}}async function getBackend(){return hn||(hn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`?`file`:await loadKeyringModule()?`keyring`:`file`)(),hn)}function stripProxyPassword(e){e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy)}async function getKeyringEntry({service:e,account:t}){let n=await loadKeyringModule();return n?new n.Entry(e,t):null}async function readKeyring(e){try{let t=await getKeyringEntry(e);return t?t.getPassword()??void 0:void 0}catch(t){cliDebugPrint(`credentials`,`failed to read ${e.service}/${e.account} from keyring`,t);return}}async function writeKeyring(e,t){let n=await getKeyringEntry(e);if(!n)throw Error(`OS keyring is not available.`);n.setPassword(t)}async function deleteKeyring(e){try{let t=await getKeyringEntry(e);return t&&t.deletePassword(),null}catch(t){return cliDebugPrint(`credentials`,`failed to delete ${e.service}/${e.account} from keyring`,t),await readKeyring(e)===void 0?null:{key:e,error:t}}}async function backendFor(e){return readProfileSecret(e,`token`)===void 0?getBackend():`file`}async function getSecret(e,t){return await backendFor(e)===`keyring`?await readKeyring(keyringKey(e,t))??readProfileSecret(e,t):readProfileSecret(e,t)}async function setSecret(e,t,n,r={}){let i=await backendFor(e),a=t===`token`?await getBackend():i;if(!(r.skipIfUnchanged&&i===a&&await getSecret(e,t)===n)){if(a===`keyring`)try{await writeKeyring(keyringKey(e,t),n),t===`token`&&clearProfileFileSecrets(e);return}catch(n){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,n),t===`token`&&await moveKeyringSecretsToFile(e)}writeProfileSecret(e,t,n)}}async function moveKeyringSecretsToFile(e){for(let t of pn){if(t===`token`)continue;let n=await readKeyring(keyringKey(e,t));n!==void 0&&(writeProfileSecret(e,t,n),readProfileSecret(e,t)===n&&await deleteKeyring(keyringKey(e,t)))}}async function deleteSecret(e,t){let n=await backendFor(e)===`keyring`?await deleteKeyring(keyringKey(e,t)):null;return deleteProfileSecret(e,t),n}async function clearKeyringSecrets(e,{keepLegacy:t=!1}={}){let n=[];for(let r of pn)e&&n.push(await deleteKeyring(keyringKey(e,r))),t||n.push(await deleteKeyring(legacyKeyringKey(r)));return n.filter(e=>e!==null)}function describeLeftovers(e){return e.map(({key:e})=>`${e.service}/${e.account}`).join(`, `)}function leftoverReasons(e){let t=e.map(({error:e})=>e instanceof Error?e.message:String(e));return[...new Set(t)].join(` `)}async function ensureMigrated(){return gn||(gn=(async()=>{try{let e=readAuthFile();if(typeof e.version==`number`&&e.version>2||!e.token&&!e.proxy?.password||await getBackend()===`file`)return;try{e.token&&await writeKeyring(legacyKeyringKey(`token`),e.token),e.proxy?.password&&await writeKeyring(legacyKeyringKey(`proxy-password`),e.proxy.password)}catch(e){cliDebugPrint(`credentials`,`keyring write failed during migration; keeping secrets in the file`,e);return}delete e.token,stripProxyPassword(e),writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),gn)}async function dropUnkeyedSecrets(e){for(let e of pn)await deleteKeyring(legacyKeyringKey(e));(e.token!==void 0||e.proxy!==void 0)&&(delete e.token,delete e.proxy,writeAuthFile(e))}async function keyKeyringSecrets(e){let t;for(let n of pn){let r=legacyKeyringKey(n),i=await readKeyring(r);if(i!==void 0){if(t??=await readKeyring(keyringKey(e,`token`))===void 0,!t||await getSecret(e,n)!==void 0)await deleteKeyring(r);else{if(await backendFor(e)===`keyring`){let t=keyringKey(e,n);try{await writeKeyring(t,i),await readKeyring(t)===i&&await deleteKeyring(r);continue}catch(e){cliDebugPrint(`credentials`,`keyring write failed while keying secrets by user`,e)}}writeProfileSecret(e,n,i),readProfileSecret(e,n)===i&&await deleteKeyring(r)}}}}function keyFileSecrets(e,t){let n=t.profiles?.[e];if(!n)return;let{token:r}=t,i=t.proxy?.password;(r!==void 0||i!==void 0)&&(r!==void 0&&(n.token=r),i!==void 0&&(n.proxy={password:i}),delete t.token,delete t.proxy,writeAuthFile(t))}async function ensureSecretsKeyed(){return _n??=(async()=>{try{let e=readAuthFile();if(e.version!==2)return;let t=e.activeProfile;if(!t){await dropUnkeyedSecrets(e);return}keyFileSecrets(t,e),await backendFor(t)===`keyring`&&await keyKeyringSecrets(t)}catch(e){cliDebugPrint(`credentials`,`keying secrets by user failed`,e)}})(),_n}async function ensureCredentialsCurrent(){await ensureMigrated(),await ensureAuthFileCurrent(),await ensureSecretsKeyed()}const vn=`full_api_access`,yn=3e5,bn=3e4;function readUrlEnv(t,n){let r=e.env[t];if(!r)return n;let i=r.replace(/\/+$/,``);if(!URL.canParse(i))throw Error(`Invalid ${t} environment variable: "${r}" is not a valid URL.`);return i}function getOAuthIssuerUrl(){return readUrlEnv(`APIFY_CLI_OAUTH_ISSUER_URL`,`https://console-backend.apify.com`)}function getOAuthClientId(){let t=e.env.APIFY_CLI_OAUTH_CLIENT_ID;if(!t)return`https://apify.com/.well-known/oauth-clients/apify-cli.json`;if(!URL.canParse(t))throw Error(`Invalid APIFY_CLI_OAUTH_CLIENT_ID environment variable: "${t}" is not a valid URL.`);return t}var OAuthError=class extends Error{code;status;description;name=`OAuthError`;constructor(e,t,n){super(n?`${e}: ${n}`:e),this.code=e,this.status=t,this.description=n}};async function postTokenRequest(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`,...sn},body:new URLSearchParams(t),signal:AbortSignal.timeout(bn)}),r=await n.text(),i={};try{i=r?JSON.parse(r):{}}catch{}if(n.ok&&typeof i.access_token==`string`)return{ok:!0,tokens:i};let a=typeof i.error==`string`?i.error:`http_${n.status}`,s=typeof i.error_description==`string`?i.error_description:void 0;return{ok:!1,error:new OAuthError(a,n.status,s)}}async function refreshAccessToken(e){let t=await postTokenRequest(e.tokenEndpoint,{grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:e.clientId});if(!t.ok)throw t.error;return t.tokens}var OAuthSessionError=class extends Error{name=`OAuthSessionError`},OAuthSessionExpiredError=class extends OAuthSessionError{name=`OAuthSessionExpiredError`;constructor(){super(`Your Apify login session has expired. Run "apify login" to sign in again.`)}};const xn=/* @__PURE__ */ new Map;function sessionOf(e){let t=xn.get(e);return t||(t={refreshAttempted:!1},xn.set(e,t)),t}function readMetadata(e){let{profile:t}=lookUpProfile(e);if(t?.authMethod!==`oauth2`||!t.oauth||!t.expiresAt)return;let n=Date.parse(t.expiresAt);if(!Number.isFinite(n))return;let r=t.oauth.refreshTokenExpiresAt?Date.parse(t.oauth.refreshTokenExpiresAt):void 0;return{...t.oauth,expiresAt:n,...Number.isFinite(r)?{refreshTokenExpiresAtMs:r}:{}}}async function getAccessToken(e,{minRemainingMs:t=6e4}={}){let n=readMetadata(e);if(!n)return getSecret(e,`token`);let r=sessionOf(e),i=Date.now();if(!needsRefresh(n,i,t)){if(r.cached&&r.cached.expiresAt===n.expiresAt)return r.cached.token;let t=await getSecret(e,`token`);return t&&(r.cached={token:t,expiresAt:n.expiresAt}),t}if(n.refreshTokenExpiresAtMs!==void 0&&n.refreshTokenExpiresAtMs<=i)throw new OAuthSessionExpiredError;if(r.refreshAttempted){if(r.refreshFailure)throw r.refreshFailure;return r.cached?.token??getSecret(e,`token`)}return r.inflightRefresh??=refreshSession(e,r,n,t).catch(e=>{throw r.refreshFailure=e,e}).finally(()=>{r.inflightRefresh=void 0}),r.inflightRefresh}async function saveOAuthSession(e,t,n){await persistTokens(e,t,{...n,refreshTokenExpiresAt:null})}async function clearOAuthSession(e){xn.delete(e);let t=await deleteSecret(e,`refresh-token`);t&&cliDebugPrint(`oauth`,`the keyring kept the refresh token`,t.error),lookUpProfile(e).profile?.authMethod===`oauth2`&&updateProfileAuth(e,{authMethod:`token`,expiresAt:null,hasRefreshToken:!1})}function needsRefresh(e,t,n){return e.expiresAt-t<n||e.refreshTokenExpiresAtMs!==void 0&&e.refreshTokenExpiresAtMs-t<18e5}async function refreshSession(e,t,n,r){let i=await acquireRefreshLock(e);try{let i=readMetadata(e)??n;if(!needsRefresh(i,Date.now(),r)){let n=await getSecret(e,`token`);return n&&(t.cached={token:n,expiresAt:i.expiresAt}),n}let a=await getSecret(e,`refresh-token`);if(!a)throw new OAuthSessionExpiredError;t.refreshAttempted=!0;let s;try{s=await refreshAccessToken({tokenEndpoint:i.tokenEndpoint,clientId:i.clientId,refreshToken:a})}catch(n){return handleRefreshFailure(e,t,n,i,a)}return await persistTokens(e,s,i),s.access_token}finally{i()}}async function handleRefreshFailure(e,t,n,r,i){cliDebugPrint(`oauth`,`refresh failed`,n);let a=n instanceof OAuthError&&(n.code===`invalid_grant`||n.code===`expired_token`);if(a){let n=await getSecret(e,`refresh-token`);if(n&&n!==i){let n=await getSecret(e,`token`),r=readMetadata(e);return n&&r&&(t.cached={token:n,expiresAt:r.expiresAt}),n}}if(Date.now()<r.expiresAt)return getSecret(e,`token`);throw a?(await clearOAuthSession(e),new OAuthSessionExpiredError):new OAuthSessionError(`Could not refresh your Apify session. Check your connection or run "apify login".`)}async function persistTokens(e,t,n){let r=Date.now(),i=r+(t.expires_in??3600)*1e3,a=t.refresh_token_expires_in===void 0?n.refreshTokenExpiresAt:new Date(r+t.refresh_token_expires_in*1e3).toISOString();t.refresh_token&&await setSecret(e,`refresh-token`,t.refresh_token,{skipIfUnchanged:!0}),await setSecret(e,`token`,t.access_token,{skipIfUnchanged:!0}),updateProfileAuth(e,{authMethod:`oauth2`,expiresAt:new Date(i).toISOString(),hasRefreshToken:!!t.refresh_token||await getSecret(e,`refresh-token`)!==void 0,oauth:{issuer:n.issuer,clientId:n.clientId,tokenEndpoint:n.tokenEndpoint,refreshTokenExpiresAt:a}}),sessionOf(e).cached={token:t.access_token,expiresAt:i}}async function acquireRefreshLock(t){let n=B(GLOBAL_CONFIGS_FOLDER(),`oauth-refresh-${t}.lock`),release=()=>{try{T(n)}catch{}},noop=()=>{};try{ensureApifyDirectory(AUTH_FILE_PATH())}catch{return noop}for(let t=0;t<50;t++){try{let t=_(n,`wx`);return D(t,`${e.pid}`),c(t),release}catch(e){if(e.code!==`EEXIST`)return noop}try{if(Date.now()-w(n).mtimeMs>3e4){T(n);continue}}catch{continue}await Oe(100)}return cliDebugPrint(`oauth`,`refresh lock wait timed out; continuing without it`),noop}const Sn=`apify-actor-runtime`,Cn=`https://podman.io/docs/installation`,wn=`NOTE: This command is experimental and might change in future releases.`,Tn=3333,En=3e3,Dn={api:Tn,console:En},runtimeApiUrl=e=>`http://localhost:${e}`,runtimeConsoleUrl=e=>`http://localhost:${e}`,On=runtimeApiUrl(Tn),kn=runtimeConsoleUrl(En),An=[`docker`,`podman`],jn=`APIFY_CONTAINER_ENGINE`,Mn=`/var/run/docker.sock`,Nn=`/data`;function runtimeEnvExportLines(e=Dn){return[`export APIFY_CLIENT_BASE_URL=${runtimeApiUrl(e.api)}`,`export APIFY_CONSOLE_URL=${runtimeConsoleUrl(e.console)}`]}function requestedContainerEngine(t=e.env){let n=t[jn]?.trim().toLowerCase();return An.find(e=>e===n)}async function installedContainerEngines(t=e.env){let n=requestedContainerEngine(t),r=n?[n]:An,i=[];for(let e of r)await ke(e,{nothrow:!0})&&i.push(e);return i}async function findContainerEngine(t=e.env){let n=await installedContainerEngines(t);for(let e of n)if(await isEngineReady(e))return{engine:e,ready:!0};return n[0]?{engine:n[0],ready:!1}:null}async function findRunningRuntimeEngine(t=e.env){for(let e of await installedContainerEngines(t))if(await isRuntimeContainerRunning(e))return e;return null}function engineInstallHint(t,n=e.platform){if(t===`podman`)return`Install Podman: ${Cn}`;switch(n){case`darwin`:return`Install Docker Desktop for Mac: https://docs.docker.com/desktop/setup/install/mac-install/`;case`win32`:return`Install Docker Desktop for Windows (WSL 2 backend): https://docs.docker.com/desktop/setup/install/windows-install/`;default:return`Install Docker Engine: https://docs.docker.com/engine/install/`}}function engineDaemonHint(t,n=e.platform){if(t===`podman`)switch(n){case`darwin`:case`win32`:return`Start the Podman machine: 'podman machine start'.`;default:return`Serve Podman's API socket: 'systemctl --user enable --now podman.socket' (rootless) or 'sudo systemctl enable --now podman.socket' (rootful); without systemd, 'podman system service --time=0 &'.`}switch(n){case`darwin`:case`win32`:return`Start Docker Desktop and wait until it reports "Docker Desktop is running".`;default:return`Start the Docker daemon, e.g. 'sudo systemctl start docker'.`}}async function isEngineReady(e){try{if(e===`podman`){let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Exists}}`]);return e.trim()===`true`}return await K(`docker`,[`info`,`--format`,`{{.ServerVersion}}`]),!0}catch{return!1}}function isDigestPinned(e){return e.includes(`@`)}async function imageExistsLocally(e,t){try{return await K(e,[`image`,`inspect`,t]),!0}catch{return!1}}async function isRuntimeContainerRunning(e){try{let{stdout:t}=await K(e,[`ps`,`--filter`,`name=^${Sn}$`,`--format`,`{{.Names}}`]);return t.trim().length>0}catch{return!1}}async function waitForRuntimeContainer(e,t,n=3e4){let r=Date.now()+n;for(;!t.aborted&&Date.now()<r;){if(await isRuntimeContainerRunning(e)&&!t.aborted)return!0;await Oe(250,void 0,{signal:t}).catch(()=>{})}return!1}function parsePublishedPorts(e){let t=e.NetworkSettings?.Ports??e.HostConfig?.PortBindings??{},n=[];for(let[e,r]of Object.entries(t)){let[t,i=`tcp`]=e.split(`/`),a=Number(t);if(Number.isInteger(a))for(let e of r??[])e?.HostPort&&n.push({containerPort:a,protocol:i,hostAddress:`${e.HostIp||`0.0.0.0`}:${e.HostPort}`})}return n.sort((e,t)=>e.containerPort-t.containerPort)}function parseRuntimeContainerInfo(e,t){let n;try{n=JSON.parse(t)}catch{return null}return!n||typeof n!=`object`?null:{engine:e,image:n.Config?.Image??n.ImageName,status:n.State?.Status,startedAt:n.State?.StartedAt,dataDir:n.Mounts?.find(e=>e.Destination===Nn)?.Source,ports:parsePublishedPorts(n)}}async function inspectRuntimeContainer(e){try{let{stdout:t}=await K(e,[`inspect`,Sn,`--format`,`{{json .}}`]);return parseRuntimeContainerInfo(e,t)}catch{return null}}function unixSocketPath(e){return e?.startsWith(`unix://`)?e.slice(7):void 0}async function resolveEngineSocketPath(t,n=e.env,r=e.platform){if(t===`docker`)return r===`linux`?unixSocketPath(n.DOCKER_HOST)??Mn:Mn;try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Path}}`]),t=e.trim();return unixSocketPath(t)??t}catch{return`/run/podman/podman.sock`}}function parsePodmanInfo(e){let[t,n,r]=e.trim().split(/\s+/),i=Number(r?.match(/^(\d+)\./)?.[1]);return{rootless:t===`true`,selinux:n===`true`,...Number.isInteger(i)?{majorVersion:i}:{}}}async function podmanInfo(){try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.Security.Rootless}} {{.Host.Security.SELinuxEnabled}} {{.Version.Version}}`]);return parsePodmanInfo(e)}catch{return}}function runtimeNetworkMode(e,t){if(e===`podman`&&t?.rootless&&t.majorVersion===3)return`slirp4netns:allow_host_loopback=true`}function runtimeSecurityOptions(e,t){return e!==`podman`||!t?.selinux?[]:[`label=disable`]}function socketMountArg(t,n=e.platform){return`${n===`win32`&&t.startsWith(`/`)?`/${t}`:t}:${Mn}`}function buildRuntimeRunArgs({image:t,dataDir:n,detach:r,hostSocketPath:i,ports:a=Dn,platform:s=e.platform,networkMode:c,securityOptions:l=[]}){let u=[`run`,`--rm`,`--init`,`--name`,Sn];r&&u.push(`--detach`),a.api!==3333&&u.push(`-e`,`ACTOR_RUNTIME_API_PORT=${a.api}`),a.console!==3e3&&u.push(`-e`,`ACTOR_RUNTIME_CONSOLE_PORT=${a.console}`),c&&u.push(`--network`,c);for(let e of l)u.push(`--security-opt`,e);return u.push(`-p`,`${a.api}:${a.api}`,`-p`,`${a.console}:${a.console}`,`-v`,socketMountArg(i,s),`-v`,`${n}:${Nn}`,t),u}function runtimeSkillHintLines(){return[`Agents: run 'apify runtime skill --install' to install this runtime's Agent Skill,`,` or 'apify runtime skill' to read it now.`]}function readActorRuntimeConfig(){try{let e=JSON.parse(v(ACTOR_RUNTIME_CONFIG_FILE_PATH(),`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function updateActorRuntimeConfig(e){ensureApifyDirectory(ACTOR_RUNTIME_CONFIG_FILE_PATH()),E(ACTOR_RUNTIME_CONFIG_FILE_PATH(),JSON.stringify({...readActorRuntimeConfig(),...e},null,` `))}const Pn=[`APIFY_CLIENT_BASE_URL`,`APIFY_CONSOLE_URL`];function isConnectedToActorRuntime(){return readActorRuntimeConfig().connected===!0}function setConnectedToActorRuntime(e){updateActorRuntimeConfig({connected:e})}function configuredRuntimePorts(){let{apiPort:e,consolePort:t}=readActorRuntimeConfig();return{api:e??Dn.api,console:t??Dn.console}}function overridingRuntimeEnvVars(t=e.env){return Pn.filter(e=>t[e]).map(e=>[e,t[e]])}function resolveApiBaseUrl(t=e.env){return t.APIFY_CLIENT_BASE_URL||(isConnectedToActorRuntime()?runtimeApiUrl(configuredRuntimePorts().api):void 0)}function resolveConsoleUrl(t=e.env){return t.APIFY_CONSOLE_URL||(isConnectedToActorRuntime()?runtimeConsoleUrl(configuredRuntimePorts().console):void 0)}var ActorRuntimeNotRunningError=class extends Error{constructor(e){super(`The Apify CLI is connected to the local Actor runtime at ${runtimeApiUrl(e)}, but the runtime isn't running. Start it with 'apify runtime start --detach', or run 'apify runtime disconnect' to target the Apify platform.`),this.name=`ActorRuntimeNotRunningError`}};function targetsConnectedRuntime(t,n=e.env){return!n.APIFY_CLIENT_BASE_URL&&isConnectedToActorRuntime()&&t===runtimeApiUrl(configuredRuntimePorts().api)}const runtimeDownInterceptor=e=>{let t=j.getAdapter(e.adapter??j.defaults.adapter);return e.adapter=async e=>{try{return await t(e)}catch(e){throw e.code===`ECONNREFUSED`&&!await findRunningRuntimeEngine()?new ActorRuntimeNotRunningError(configuredRuntimePorts().api):e}},e},Fn=/* @__PURE__ */ new Set([`undefined`,`null`,`nil`,`none`,`nan`,`false`,`0`,`-`]);function readEnvToken(){let t=e.env[I.TOKEN]?.trim();return t?Fn.has(t.toLowerCase())?{kind:`invalid`,raw:t}:{kind:`token`,token:t}:{kind:`unset`}}function invalidEnvTokenMessage(e){return`${I.TOKEN} is set to "${e}", which is not an API token. Unset ${I.TOKEN} and try again.`}const In={env:`${I.TOKEN} environment variable`,stored:`apify login`,profile:`--profile flag`};let Ln,Rn;const zn=`No accounts are stored. Run "apify login" to add one.`;function envTokenOverridesProfileMessage(e){return`${I.TOKEN} is set, so commands ignore ${e}. Unset ${I.TOKEN} and try again.`}async function requireProfile(t){await ensureCredentialsCurrent();let n=matchProfiles(t);if(n.length===1)return n[0];if(e.exitCode=5,n.length>1)throw Error(`More than one stored account is called "${t}": ${n.map(({id:e})=>e).join(`, `)}. Use the user ID instead.`);let r=listProfiles().map(profileLabel);throw Error(r.length?`No stored account is called "${t}". Stored accounts: ${r.join(`, `)}.`:`No stored account is called "${t}". Run "apify login" to add one.`)}function getCurrentProfile(){return Rn??getActiveProfile()}async function selectProfile(t){if(readEnvToken().kind!==`unset`)throw e.exitCode=5,Error(envTokenOverridesProfileMessage(`--profile`));Rn=await requireProfile(t),Ln=void 0}const resolveAuth=async()=>{Ln??=(async()=>{await ensureMigrated();let t=readEnvToken();if(t.kind===`invalid`)throw e.exitCode=5,Error(invalidEnvTokenMessage(t.raw));if(t.kind===`token`)return p(AUTH_FILE_PATH())&&warning({message:`Using the API token from ${I.TOKEN}.`}),{token:t.token,source:`env`};if(await ensureCredentialsCurrent(),Rn){let t=await getAccessToken(Rn.id);if(!t)throw e.exitCode=1,Error(missingProfileTokenMessage(Rn));return{token:t,source:`profile`,profile:profileRef(Rn)}}let n=getActiveProfileId(),r=n?await getAccessToken(n):void 0;if(!r)return;let i=getActiveProfile();return{token:r,source:`stored`,...i?{profile:profileRef(i)}:{}}})();try{return await Ln}catch(e){throw Ln=void 0,e}};function profileRef(e){return{id:e.id,label:profileLabel(e)}}function missingProfileTokenMessage(e){return`No API token is stored for ${profileLabel(e)}. Run "apify login" to log in to ${profileLabel(e)} again.`}function describeAuthFailure(e,t){if(!e)return`You are not logged in with your Apify account. Call "apify login" to fix that.`;if(t instanceof ActorRuntimeNotRunningError)return t.message;let n=t instanceof O?t.statusCode:void 0;if(t&&n!==401&&n!==403)return`Could not verify your API token. The Apify API request failed: ${t instanceof Error?t.message:String(t)}`;switch(e.source){case`env`:return`The API token in ${I.TOKEN} was rejected. Unset it to use your stored login instead.`;default:return e.profile?`The stored API token for ${e.profile.label} was rejected. Run "apify login" to log in to ${e.profile.label} again.`:`Your stored API token was rejected. Call "apify login" to log in again.`}}const getAnonymousApifyClientOptions=e=>{let t=e||resolveApiBaseUrl();return{baseUrl:t,requestInterceptors:[e=>{e.headers??=new M;for(let[t,n]of Object.entries(sn))e.headers[t]=n;return e},...targetsConnectedRuntime(t)?[runtimeDownInterceptor]:[]]}},getApifyClientOptionsForToken=(e,t)=>({...getAnonymousApifyClientOptions(t),token:e});async function loginWithToken(e,t){let n=new k(getApifyClientOptionsForToken(e,t)),r;try{r=await n.user(`me`).get()}catch(e){return cliDebugPrint(`[loginWithToken] error getting user info`,{error:e,apiBaseUrl:t}),null}if(!r.id)throw Error(`The Apify API returned no user ID for this token, so the login cannot be stored.`);let i=r.proxy?.password;await ensureCredentialsCurrent();let{organizationOwnerUserId:a}=r;upsertProfile(r.id,{username:r.username,name:r.username||r.id,...a?{organizationOwnerUserId:a}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:(/* @__PURE__ */ new Date()).toISOString()});let s=await clearKeyringSecrets();if(await clearOAuthSession(r.id),await setSecret(r.id,`token`,e,{skipIfUnchanged:!0}),i)await setSecret(r.id,`proxy-password`,i,{skipIfUnchanged:!0});else{let e=await deleteSecret(r.id,`proxy-password`);e&&s.push(e)}return s.length&&warning({message:`Secrets this login could not remove are still in the OS keyring at ${describeLeftovers(s)}; delete them with your OS keyring app.`}),{client:n,userInfo:r}}const Bn=Ne(m);let Vn;async function useStdin(){if(Vn)return Vn;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Bn(0).then(t=>{if(cliDebugPrint(`useStdin`,{stat:t,isRegularFile:t.isFile(),isDirectory:t.isDirectory(),isBlockDevice:t.isBlockDevice(),isCharDevice:t.isCharacterDevice(),isSymbolicLink:t.isSymbolicLink(),isFIFO:t.isFIFO(),isSocket:t.isSocket()}),e.platform===`win32`){if((t.mode&l.S_IFIFO)===l.S_IFIFO)return 100;if(t.isFile())return 50}return t.isFIFO()||t.isFile()||(t.isSocket()?50:!1)}).catch(()=>!1);return cliDebugPrint(`useStdin`,{hasData:n.hasData,waitDelay:n.waitDelay,isTTY:n.isTTY,pipedIn:r,readableEnded:t.readableEnded}),t.isTTY&&(r===!1||t.isTTY===void 0&&t.readableEnded)||(n.hasData=!0),typeof r==`number`&&(n.waitDelay=r),Vn=n,n}const Hn=5e3;let Un,Wn,Gn=!1,Kn=!1;async function readStdin(e={}){return Un??=_readStdin(e).then(e=>(Wn=e,Gn=!0,e)),Un}function stdinWasCutShort(){return Kn}function describeStdinRead(){return Gn?Wn?`Yes`:`No`:`Not read`}async function _readStdin({implicit:e}){let{hasData:t,waitDelay:n,stream:r}=await useStdin();if(!t)return;let i=e?n||Hn:n,a=[],s=new AbortController,c=null,armTimeout=e=>{e&&(c=setTimeout(()=>s.abort(),e).unref())},disarmTimeout=()=>{c&&=(clearTimeout(c),null)};armTimeout(i);let onData=t=>{a.push(t),disarmTimeout(),e&&armTimeout(1e3)};r.on(`data`,onData);try{await Ae(r,`end`,{signal:s.signal})}catch(t){if(t.name===`AbortError`){if(!e)return;Kn=a.length>0||i===Hn}}finally{r.off(`data`,onData),r.pause()}disarmTimeout();let l=Buffer.concat(a);if(l.length)return l}let qn=`inherit`;function keepStdoutClean(){qn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{cliDebugPrint(`spawnPromised`,{cmd:t,args:n,opts:r,forwardSignals:i});let a=K(t,n,{windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,qn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),s=[];if(i?.length)for(let t of i){let handler=()=>{a.kill(t)};e.on(t,handler),s.push(()=>e.off(t,handler))}try{return await Pe.fromAsync(a.catch(e=>{let n;throw n=e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage:`${t} exited with code ${e.exitCode}`,Error(n,{cause:e})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const Jn=[[`CLAUDECODE`,`claude_code`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CURSOR_AGENT`,`cursor`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`]];function detectAiAgent(){for(let[e,t]of Jn)if(process.env[e])return t}function detectCi(){return _e.isCI?{isCi:!0,ciProvider:_e.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const Yn=[`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{appendFileSync as a,chmodSync as s,closeSync as c,constants as l,copyFileSync as u,createWriteStream as f,existsSync as p,fstat as m,lstatSync as h,mkdirSync as g,openSync as _,readFileSync as v,readdirSync as y,readlinkSync as b,realpathSync as x,renameSync as S,rmSync as C,statSync as w,unlinkSync as T,writeFileSync as E,writeSync as D}from"node:fs";import{ApifyApiError as O,ApifyClient as k,DownloadItemsFormat as A}from"apify-client";import j,{AxiosHeaders as M}from"axios";import{ACTOR_ENV_VARS as N,ACTOR_JOB_STATUSES as P,ACTOR_JOB_TERMINAL_STATUSES as ee,ACTOR_JOB_TYPES as F,ACTOR_NAME as te,ACTOR_SOURCE_TYPES as ne,APIFY_ENV_VARS as I,KEY_VALUE_STORE_KEYS as re,LOCAL_ACTOR_ENV_VARS as ie,LOCAL_STORAGE_SUBDIRS as ae,MAX_MULTIFILE_BYTES as oe,META_ORIGINS as se,SOURCE_FILE_FORMATS as ce}from"@apify/consts";import{createHmacSignature as le,cryptoRandomObjectId as L}from"@apify/utilities";import{homedir as ue,platform as de,tmpdir as fe}from"node:os";import R,{basename as pe,dirname as z,isAbsolute as me,join as B,posix as he,relative as V,resolve as H,sep as ge}from"node:path";import _e,{isCI as ve}from"ci-info";import{access as ye,appendFile as be,mkdir as U,mkdtemp as xe,readFile as Se,readdir as Ce,rename as we,rm as Te,stat as W,symlink as Ee,unlink as De,writeFile as G}from"node:fs/promises";import{setTimeout as Oe}from"node:timers/promises";import{execa as K}from"execa";import ke from"which";import{once as Ae}from"node:events";import{inspect as je,parseArgs as Me,promisify as Ne}from"node:util";import{Result as Pe,err as Fe,none as Ie,ok as Le,some as Re}from"@sapphire/result";import{gt as ze,gte as Be,minVersion as Ve,satisfies as He}from"semver";import Ue from"string-width";import We from"strip-ansi";import{jaroWinkler as Ge}from"@skyra/jaro-winkler";import Ke from"js-levenshtein";import{execFileSync as qe,execSync as Je,spawn as Ye}from"node:child_process";import{finished as Xe,pipeline as Ze}from"node:stream/promises";import{DurationFormatter as Qe,Time as $e,TimeTypes as et}from"@sapphire/duration";import{Timestamp as tt}from"@sapphire/timestamp";import nt from"adm-zip";import rt from"ajv/dist/2019.js";import{TarArchive as it,ZipArchive as at}from"archiver";import ot from"escape-string-regexp";import st from"ignore";import{getEncoding as ct}from"istextorbinary";import lt,{Mime as ut}from"mime";import dt from"mime/types/other.js";import ft from"mime/types/standard.js";import{glob as pt}from"tinyglobby";import mt from"configparser";import ht from"@inquirer/input";import{Separator as gt,createPrompt as _t,isEnterKey as vt,makeTheme as yt,useKeypress as bt,usePrefix as xt,useState as St}from"@inquirer/core";import{compile as Ct}from"json-schema-to-typescript";import{validateInputSchema as wt,validateInputUsingValidator as Tt}from"@apify/input_schema";import{getDatasetSchemaValidator as Et,getKeyValueStoreSchemaValidator as Dt,getOutputSchemaValidator as Ot}from"@apify/json_schemas";import{MemoryStorage as kt}from"@crawlee/memory-storage";import At from"cli-table3";import{downloadTemplate as jt}from"giget";import Mt from"jju";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"open";import{fetchManifest as Lt,manifestUrl as Rt,wrapperManifestUrl as zt}from"@apify/actor-templates";import Bt from"@inquirer/checkbox";import Vt from"computer-name";import Ht from"@inquirer/password";import{createServer as Ut}from"node:http";import Wt from"@inquirer/select";import Gt from"node:assert";import{ReadStream as Kt}from"node:tty";import qt from"detect-indent";import{fileURLToPath as Jt}from"node:url";import Yt from"@root/walk";import Xt from"handlebars";var Zt={node:`>=22`};const Qt=`storage`,$t={$schema:`https://apify.com/schemas/v1/actor.ide.json`,actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},en=Date.UTC(2026,9,1),tn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=B(ue(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?B(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),ACTOR_RUNTIME_CONFIG_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`actor-runtime`,`config.json`),nn=`apify.json`,rn=`.actor`,q=B(rn,`actor.json`),an=Zt.node,on=_e.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,sn={"X-Apify-Request-Origin":_e.isCI?se.CI:se.CLI,...on&&{"X-Apify-Github-Actions-Run-Url":on}},cn=`3.11.0`,updateLocalJson=async(e,t={},n=null)=>{let r=await Se(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await G(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(ge).reduce((e,t)=>(e=B(e,t),p(e)||g(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Te(e,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})))},deleteFile=async e=>{(await W(e)).isFile()&&await De(e)};function ensureApifyDirectory(e){let t=z(e);g(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>W(B(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0);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 cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}let ln;function parseAuthFile(){if(!p(AUTH_FILE_PATH()))return{};try{let e=JSON.parse(v(AUTH_FILE_PATH(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?null:e}catch{return null}}function readAuthFile(){return parseAuthFile()??{}}function writeAuthFile(e){atomicWriteJson(AUTH_FILE_PATH(),e)}function atomicWriteJson(e,t){ensureApifyDirectory(e);let n=`${e}.tmp-${L(8)}`;try{E(n,JSON.stringify(t,null,` `),{mode:384}),S(n,e)}catch(e){throw C(n,{force:!0}),e}}function v1Profile(e){return{...typeof e.username==`string`?{username:e.username}:{},name:null,...typeof e.organizationOwnerUserId==`string`?{organizationOwnerUserId:e.organizationOwnerUserId}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:null}}function toV2(e){let t={version:2,profiles:{}};return typeof e.id==`string`&&(t.activeProfile=e.id,t.profiles[e.id]=v1Profile(e)),typeof e.token==`string`&&(t.token=e.token),typeof e.proxy?.password==`string`&&(t.proxy={password:e.proxy.password}),t}const un={1:toV2};async function migrateAuthFile(){return ln??=(async()=>{try{let e=parseAuthFile();if(!e||Object.keys(e).length===0)return;let t=typeof e.version==`number`?e.version:1;if(t>=2)return;let n=e;for(let e=t;e<2;e++){let t=un[e];if(!t)throw Error(`No migration step from auth file version ${e}.`);n=t(n)}writeAuthFile(n)}catch(e){cliDebugPrint(`auth-file`,`auth file migration failed`,e),warning({message:`Your stored login cannot be read until ${AUTH_FILE_PATH()} is updated to the current format, and the update failed. Make the directory it is in writable, then run the command again. Set APIFY_CLI_DEBUG=1 to see why.`})}})(),ln}function assertSupportedAuthFileVersion(){let{version:e}=readAuthFile();if(typeof e==`number`&&e>2)throw Error(`Your credentials in ${AUTH_FILE_PATH()} were written by a newer Apify CLI. It uses auth file version ${e} and this one reads 2. Upgrade the CLI, or run "apify logout" to discard them.`)}async function ensureAuthFileCurrent(){await migrateAuthFile(),assertSupportedAuthFileVersion()}function lookUpActiveProfile(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?{profile:{id:t.id,...v1Profile(t)}}:{}}if(!e.activeProfile)return{};let t=e.profiles?.[e.activeProfile];return t?{profile:{id:e.activeProfile,...t}}:{missingProfile:e.activeProfile}}function profileLabel(e){return e.name??e.username??e.id}function listProfiles(){let e=readAuthFile();if(e.version!==2){let{profile:e}=lookUpActiveProfile();return e?[e]:[]}return Object.entries(e.profiles??{}).map(([e,t])=>({id:e,...t}))}function matchProfiles(e){let t=listProfiles(),n=t.find(({id:t})=>t===e);return n?[n]:t.filter(t=>profileLabel(t)===e)}function lookUpProfile(e){let t=listProfiles().find(({id:t})=>t===e);return t?{profile:t}:{missingProfile:e}}function setActiveProfile(e){let t=readAuthFile();t.profiles?.[e]&&(t.activeProfile=e,writeAuthFile(t))}function getActiveProfile(){return lookUpActiveProfile().profile}function getActiveProfileId(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?t.id:void 0}return e.activeProfile}function readProfileSecret(e,t){let n=readAuthFile().profiles?.[e];if(n)switch(t){case`token`:return n.token;case`refresh-token`:return n.refreshToken;default:return n.proxy?.password}}function writeProfileSecret(e,t,n){updateProfile(e,e=>setProfileSecret(e,t,n))}function clearProfileFileSecrets(e){let t=readAuthFile().profiles?.[e];(t?.token!==void 0||t?.proxy!==void 0||t?.refreshToken!==void 0)&&updateProfile(e,e=>{delete e.token,delete e.proxy,delete e.refreshToken})}function setProfileSecret(e,t,n){t===`token`?e.token=n:t===`refresh-token`?e.refreshToken=n:e.proxy={...e.proxy,password:n}}function deleteProfileSecret(e,t){readProfileSecret(e,t)!==void 0&&updateProfile(e,e=>{t===`token`?delete e.token:t===`refresh-token`?delete e.refreshToken:delete e.proxy})}function updateProfile(e,t){let n=readAuthFile(),r=n.profiles?.[e];r&&(t(r),writeAuthFile(n))}function updateProfileAuth(e,t){updateProfile(e,e=>{e.authMethod=t.authMethod,e.expiresAt=t.expiresAt,e.hasRefreshToken=t.hasRefreshToken,t.oauth?e.oauth=t.oauth:delete e.oauth})}function upsertProfile(e,t){assertSupportedAuthFileVersion();let n=readAuthFile(),r=n.version===2?n:{version:2};r.profiles??={},delete r.token,delete r.proxy;let i=r.profiles[e];r.profiles[e]={...t,...i?.token?{token:i.token}:{},...i?.proxy?{proxy:i.proxy}:{},...i?.refreshToken?{refreshToken:i.refreshToken}:{}},r.activeProfile=e,writeAuthFile(r)}function removeProfile(e){let t=readAuthFile();if(t.version!==2)return discardAuthFile(),{};let n=e??t.activeProfile,r=n?t.profiles?.[n]:void 0,i=n&&r?{id:n,...r}:void 0;if(n&&t.profiles&&delete t.profiles[n],n!==t.activeProfile){writeAuthFile(t);let e=t.activeProfile?t.profiles?.[t.activeProfile]:void 0;return{removed:i,active:e&&{id:t.activeProfile,...e}}}delete t.activeProfile,delete t.token,delete t.proxy;let[a]=Object.entries(t.profiles??{}).sort(([,e],[,t])=>(t.loggedInAt??``).localeCompare(e.loggedInAt??``)).map(([e])=>e);return a?(t.activeProfile=a,writeAuthFile(t),{removed:i,active:{id:a,...t.profiles[a]}}):(discardAuthFile(),{removed:i})}function removeAllProfiles(){discardAuthFile()}function discardAuthFile(){C(AUTH_FILE_PATH(),{force:!0,maxRetries:10,retryDelay:100})}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=x(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 dn=null;function useCLIMetadata(){if(dn)return dn;let e=detectInstallMethod(),t=getRuntimeInfo();return dn={version:`1.14.1-beta.2`,hash:`17a5b5b9aa810608461088b9934110f01bf16684`,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`&&(dn.installPath=z(process.execPath)),dn}const fn=`com.apify.cli`,pn=[`token`,`proxy-password`,`refresh-token`];function keyringKey(e,t){return{service:`${fn}.${t}`,account:e}}function legacyKeyringKey(e){return{service:fn,account:e}}let mn,hn,gn,_n;async function loadKeyringModule(){return mn===void 0&&(mn=await importKeyringModule()),mn}async function importKeyringModule(){if(useCLIMetadata().installMethod===`bundle`)try{let e=await import(`__APIFY_KEYRING_NATIVE_SUBPACKAGE__`),t=e.Entry??e.default?.Entry;return t?{Entry:t}:null}catch(e){return cliDebugPrint(`credentials`,`failed to load bundled keyring`,e),null}try{return await import(`@napi-rs/keyring`)}catch(e){return cliDebugPrint(`credentials`,`failed to load @napi-rs/keyring`,e),null}}async function getBackend(){return hn||(hn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`?`file`:await loadKeyringModule()?`keyring`:`file`)(),hn)}function stripProxyPassword(e){e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy)}async function getKeyringEntry({service:e,account:t}){let n=await loadKeyringModule();return n?new n.Entry(e,t):null}async function readKeyring(e){try{let t=await getKeyringEntry(e);return t?t.getPassword()??void 0:void 0}catch(t){cliDebugPrint(`credentials`,`failed to read ${e.service}/${e.account} from keyring`,t);return}}async function writeKeyring(e,t){let n=await getKeyringEntry(e);if(!n)throw Error(`OS keyring is not available.`);n.setPassword(t)}async function deleteKeyring(e){try{let t=await getKeyringEntry(e);return t&&t.deletePassword(),null}catch(t){return cliDebugPrint(`credentials`,`failed to delete ${e.service}/${e.account} from keyring`,t),await readKeyring(e)===void 0?null:{key:e,error:t}}}async function backendFor(e){return readProfileSecret(e,`token`)===void 0?getBackend():`file`}async function getSecret(e,t){return await backendFor(e)===`keyring`?await readKeyring(keyringKey(e,t))??readProfileSecret(e,t):readProfileSecret(e,t)}async function setSecret(e,t,n,r={}){let i=await backendFor(e),a=t===`token`?await getBackend():i;if(!(r.skipIfUnchanged&&i===a&&await getSecret(e,t)===n)){if(a===`keyring`)try{await writeKeyring(keyringKey(e,t),n),t===`token`&&clearProfileFileSecrets(e);return}catch(n){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,n),t===`token`&&await moveKeyringSecretsToFile(e)}writeProfileSecret(e,t,n)}}async function moveKeyringSecretsToFile(e){for(let t of pn){if(t===`token`)continue;let n=await readKeyring(keyringKey(e,t));n!==void 0&&(writeProfileSecret(e,t,n),readProfileSecret(e,t)===n&&await deleteKeyring(keyringKey(e,t)))}}async function deleteSecret(e,t){let n=await backendFor(e)===`keyring`?await deleteKeyring(keyringKey(e,t)):null;return deleteProfileSecret(e,t),n}async function clearKeyringSecrets(e,{keepLegacy:t=!1}={}){let n=[];for(let r of pn)e&&n.push(await deleteKeyring(keyringKey(e,r))),t||n.push(await deleteKeyring(legacyKeyringKey(r)));return n.filter(e=>e!==null)}function describeLeftovers(e){return e.map(({key:e})=>`${e.service}/${e.account}`).join(`, `)}function leftoverReasons(e){let t=e.map(({error:e})=>e instanceof Error?e.message:String(e));return[...new Set(t)].join(` `)}async function ensureMigrated(){return gn||(gn=(async()=>{try{let e=readAuthFile();if(typeof e.version==`number`&&e.version>2||!e.token&&!e.proxy?.password||await getBackend()===`file`)return;try{e.token&&await writeKeyring(legacyKeyringKey(`token`),e.token),e.proxy?.password&&await writeKeyring(legacyKeyringKey(`proxy-password`),e.proxy.password)}catch(e){cliDebugPrint(`credentials`,`keyring write failed during migration; keeping secrets in the file`,e);return}delete e.token,stripProxyPassword(e),writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),gn)}async function dropUnkeyedSecrets(e){for(let e of pn)await deleteKeyring(legacyKeyringKey(e));(e.token!==void 0||e.proxy!==void 0)&&(delete e.token,delete e.proxy,writeAuthFile(e))}async function keyKeyringSecrets(e){let t;for(let n of pn){let r=legacyKeyringKey(n),i=await readKeyring(r);if(i!==void 0){if(t??=await readKeyring(keyringKey(e,`token`))===void 0,!t||await getSecret(e,n)!==void 0)await deleteKeyring(r);else{if(await backendFor(e)===`keyring`){let t=keyringKey(e,n);try{await writeKeyring(t,i),await readKeyring(t)===i&&await deleteKeyring(r);continue}catch(e){cliDebugPrint(`credentials`,`keyring write failed while keying secrets by user`,e)}}writeProfileSecret(e,n,i),readProfileSecret(e,n)===i&&await deleteKeyring(r)}}}}function keyFileSecrets(e,t){let n=t.profiles?.[e];if(!n)return;let{token:r}=t,i=t.proxy?.password;(r!==void 0||i!==void 0)&&(r!==void 0&&(n.token=r),i!==void 0&&(n.proxy={password:i}),delete t.token,delete t.proxy,writeAuthFile(t))}async function ensureSecretsKeyed(){return _n??=(async()=>{try{let e=readAuthFile();if(e.version!==2)return;let t=e.activeProfile;if(!t){await dropUnkeyedSecrets(e);return}keyFileSecrets(t,e),await backendFor(t)===`keyring`&&await keyKeyringSecrets(t)}catch(e){cliDebugPrint(`credentials`,`keying secrets by user failed`,e)}})(),_n}async function ensureCredentialsCurrent(){await ensureMigrated(),await ensureAuthFileCurrent(),await ensureSecretsKeyed()}const vn=`full_api_access`,yn=3e5,bn=3e4;function readUrlEnv(t,n){let r=e.env[t];if(!r)return n;let i=r.replace(/\/+$/,``);if(!URL.canParse(i))throw Error(`Invalid ${t} environment variable: "${r}" is not a valid URL.`);return i}function getOAuthIssuerUrl(){return readUrlEnv(`APIFY_CLI_OAUTH_ISSUER_URL`,`https://console-backend.apify.com`)}function getOAuthClientId(){let t=e.env.APIFY_CLI_OAUTH_CLIENT_ID;if(!t)return`https://apify.com/.well-known/oauth-clients/apify-cli.json`;if(!URL.canParse(t))throw Error(`Invalid APIFY_CLI_OAUTH_CLIENT_ID environment variable: "${t}" is not a valid URL.`);return t}var OAuthError=class extends Error{code;status;description;name=`OAuthError`;constructor(e,t,n){super(n?`${e}: ${n}`:e),this.code=e,this.status=t,this.description=n}};async function postTokenRequest(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`,...sn},body:new URLSearchParams(t),signal:AbortSignal.timeout(bn)}),r=await n.text(),i={};try{i=r?JSON.parse(r):{}}catch{}if(n.ok&&typeof i.access_token==`string`)return{ok:!0,tokens:i};let a=typeof i.error==`string`?i.error:`http_${n.status}`,s=typeof i.error_description==`string`?i.error_description:void 0;return{ok:!1,error:new OAuthError(a,n.status,s)}}async function refreshAccessToken(e){let t=await postTokenRequest(e.tokenEndpoint,{grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:e.clientId});if(!t.ok)throw t.error;return t.tokens}var OAuthSessionError=class extends Error{name=`OAuthSessionError`},OAuthSessionExpiredError=class extends OAuthSessionError{name=`OAuthSessionExpiredError`;constructor(){super(`Your Apify login session has expired. Run "apify login" to sign in again.`)}};const xn=/* @__PURE__ */ new Map;function sessionOf(e){let t=xn.get(e);return t||(t={refreshAttempted:!1},xn.set(e,t)),t}function readMetadata(e){let{profile:t}=lookUpProfile(e);if(t?.authMethod!==`oauth2`||!t.oauth||!t.expiresAt)return;let n=Date.parse(t.expiresAt);if(!Number.isFinite(n))return;let r=t.oauth.refreshTokenExpiresAt?Date.parse(t.oauth.refreshTokenExpiresAt):void 0;return{...t.oauth,expiresAt:n,...Number.isFinite(r)?{refreshTokenExpiresAtMs:r}:{}}}async function getAccessToken(e,{minRemainingMs:t=6e4}={}){let n=readMetadata(e);if(!n)return getSecret(e,`token`);let r=sessionOf(e),i=Date.now();if(!needsRefresh(n,i,t)){if(r.cached&&r.cached.expiresAt===n.expiresAt)return r.cached.token;let t=await getSecret(e,`token`);return t&&(r.cached={token:t,expiresAt:n.expiresAt}),t}if(n.refreshTokenExpiresAtMs!==void 0&&n.refreshTokenExpiresAtMs<=i)throw new OAuthSessionExpiredError;if(r.refreshAttempted){if(r.refreshFailure)throw r.refreshFailure;return r.cached?.token??getSecret(e,`token`)}return r.inflightRefresh??=refreshSession(e,r,n,t).catch(e=>{throw r.refreshFailure=e,e}).finally(()=>{r.inflightRefresh=void 0}),r.inflightRefresh}async function saveOAuthSession(e,t,n){await persistTokens(e,t,{...n,refreshTokenExpiresAt:null})}async function clearOAuthSession(e){xn.delete(e);let t=await deleteSecret(e,`refresh-token`);t&&cliDebugPrint(`oauth`,`the keyring kept the refresh token`,t.error),lookUpProfile(e).profile?.authMethod===`oauth2`&&updateProfileAuth(e,{authMethod:`token`,expiresAt:null,hasRefreshToken:!1})}function needsRefresh(e,t,n){return e.expiresAt-t<n||e.refreshTokenExpiresAtMs!==void 0&&e.refreshTokenExpiresAtMs-t<18e5}async function refreshSession(e,t,n,r){let i=await acquireRefreshLock(e);try{let i=readMetadata(e)??n;if(!needsRefresh(i,Date.now(),r)){let n=await getSecret(e,`token`);return n&&(t.cached={token:n,expiresAt:i.expiresAt}),n}let a=await getSecret(e,`refresh-token`);if(!a)throw new OAuthSessionExpiredError;t.refreshAttempted=!0;let s;try{s=await refreshAccessToken({tokenEndpoint:i.tokenEndpoint,clientId:i.clientId,refreshToken:a})}catch(n){return handleRefreshFailure(e,t,n,i,a)}return await persistTokens(e,s,i),s.access_token}finally{i()}}async function handleRefreshFailure(e,t,n,r,i){cliDebugPrint(`oauth`,`refresh failed`,n);let a=n instanceof OAuthError&&(n.code===`invalid_grant`||n.code===`expired_token`);if(a){let n=await getSecret(e,`refresh-token`);if(n&&n!==i){let n=await getSecret(e,`token`),r=readMetadata(e);return n&&r&&(t.cached={token:n,expiresAt:r.expiresAt}),n}}if(Date.now()<r.expiresAt)return getSecret(e,`token`);throw a?(await clearOAuthSession(e),new OAuthSessionExpiredError):new OAuthSessionError(`Could not refresh your Apify session. Check your connection or run "apify login".`)}async function persistTokens(e,t,n){let r=Date.now(),i=r+(t.expires_in??3600)*1e3,a=t.refresh_token_expires_in===void 0?n.refreshTokenExpiresAt:new Date(r+t.refresh_token_expires_in*1e3).toISOString();t.refresh_token&&await setSecret(e,`refresh-token`,t.refresh_token,{skipIfUnchanged:!0}),await setSecret(e,`token`,t.access_token,{skipIfUnchanged:!0}),updateProfileAuth(e,{authMethod:`oauth2`,expiresAt:new Date(i).toISOString(),hasRefreshToken:!!t.refresh_token||await getSecret(e,`refresh-token`)!==void 0,oauth:{issuer:n.issuer,clientId:n.clientId,tokenEndpoint:n.tokenEndpoint,refreshTokenExpiresAt:a}}),sessionOf(e).cached={token:t.access_token,expiresAt:i}}async function acquireRefreshLock(t){let n=B(GLOBAL_CONFIGS_FOLDER(),`oauth-refresh-${t}.lock`),release=()=>{try{T(n)}catch{}},noop=()=>{};try{ensureApifyDirectory(AUTH_FILE_PATH())}catch{return noop}for(let t=0;t<50;t++){try{let t=_(n,`wx`);return D(t,`${e.pid}`),c(t),release}catch(e){if(e.code!==`EEXIST`)return noop}try{if(Date.now()-w(n).mtimeMs>3e4){T(n);continue}}catch{continue}await Oe(100)}return cliDebugPrint(`oauth`,`refresh lock wait timed out; continuing without it`),noop}const Sn=`apify-actor-runtime`,Cn=`https://podman.io/docs/installation`,wn=`NOTE: This command is experimental and might change in future releases.`,Tn=3333,En=3e3,Dn={api:Tn,console:En},runtimeApiUrl=e=>`http://localhost:${e}`,runtimeConsoleUrl=e=>`http://localhost:${e}`,On=runtimeApiUrl(Tn),kn=runtimeConsoleUrl(En),An=[`docker`,`podman`],jn=`APIFY_CONTAINER_ENGINE`,Mn=`/var/run/docker.sock`,Nn=`/data`;function runtimeEnvExportLines(e=Dn){return[`export APIFY_CLIENT_BASE_URL=${runtimeApiUrl(e.api)}`,`export APIFY_CONSOLE_URL=${runtimeConsoleUrl(e.console)}`]}function requestedContainerEngine(t=e.env){let n=t[jn]?.trim().toLowerCase();return An.find(e=>e===n)}async function installedContainerEngines(t=e.env){let n=requestedContainerEngine(t),r=n?[n]:An,i=[];for(let e of r)await ke(e,{nothrow:!0})&&i.push(e);return i}async function findContainerEngine(t=e.env){let n=await installedContainerEngines(t);for(let e of n)if(await isEngineReady(e))return{engine:e,ready:!0};return n[0]?{engine:n[0],ready:!1}:null}async function findRunningRuntimeEngine(t=e.env){for(let e of await installedContainerEngines(t))if(await isRuntimeContainerRunning(e))return e;return null}function engineInstallHint(t,n=e.platform){if(t===`podman`)return`Install Podman: ${Cn}`;switch(n){case`darwin`:return`Install Docker Desktop for Mac: https://docs.docker.com/desktop/setup/install/mac-install/`;case`win32`:return`Install Docker Desktop for Windows (WSL 2 backend): https://docs.docker.com/desktop/setup/install/windows-install/`;default:return`Install Docker Engine: https://docs.docker.com/engine/install/`}}function engineDaemonHint(t,n=e.platform){if(t===`podman`)switch(n){case`darwin`:case`win32`:return`Start the Podman machine: 'podman machine start'.`;default:return`Serve Podman's API socket: 'systemctl --user enable --now podman.socket' (rootless) or 'sudo systemctl enable --now podman.socket' (rootful); without systemd, 'podman system service --time=0 &'.`}switch(n){case`darwin`:case`win32`:return`Start Docker Desktop and wait until it reports "Docker Desktop is running".`;default:return`Start the Docker daemon, e.g. 'sudo systemctl start docker'.`}}async function isEngineReady(e){try{if(e===`podman`){let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Exists}}`]);return e.trim()===`true`}return await K(`docker`,[`info`,`--format`,`{{.ServerVersion}}`]),!0}catch{return!1}}function isDigestPinned(e){return e.includes(`@`)}async function imageExistsLocally(e,t){try{return await K(e,[`image`,`inspect`,t]),!0}catch{return!1}}async function isRuntimeContainerRunning(e){try{let{stdout:t}=await K(e,[`ps`,`--filter`,`name=^${Sn}$`,`--format`,`{{.Names}}`]);return t.trim().length>0}catch{return!1}}async function waitForRuntimeContainer(e,t,n=3e4){let r=Date.now()+n;for(;!t.aborted&&Date.now()<r;){if(await isRuntimeContainerRunning(e)&&!t.aborted)return!0;await Oe(250,void 0,{signal:t}).catch(()=>{})}return!1}function parsePublishedPorts(e){let t=e.NetworkSettings?.Ports??e.HostConfig?.PortBindings??{},n=[];for(let[e,r]of Object.entries(t)){let[t,i=`tcp`]=e.split(`/`),a=Number(t);if(Number.isInteger(a))for(let e of r??[])e?.HostPort&&n.push({containerPort:a,protocol:i,hostAddress:`${e.HostIp||`0.0.0.0`}:${e.HostPort}`})}return n.sort((e,t)=>e.containerPort-t.containerPort)}function parseRuntimeContainerInfo(e,t){let n;try{n=JSON.parse(t)}catch{return null}return!n||typeof n!=`object`?null:{engine:e,image:n.Config?.Image??n.ImageName,status:n.State?.Status,startedAt:n.State?.StartedAt,dataDir:n.Mounts?.find(e=>e.Destination===Nn)?.Source,ports:parsePublishedPorts(n)}}async function inspectRuntimeContainer(e){try{let{stdout:t}=await K(e,[`inspect`,Sn,`--format`,`{{json .}}`]);return parseRuntimeContainerInfo(e,t)}catch{return null}}function unixSocketPath(e){return e?.startsWith(`unix://`)?e.slice(7):void 0}async function resolveEngineSocketPath(t,n=e.env,r=e.platform){if(t===`docker`)return r===`linux`?unixSocketPath(n.DOCKER_HOST)??Mn:Mn;try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Path}}`]),t=e.trim();return unixSocketPath(t)??t}catch{return`/run/podman/podman.sock`}}function parsePodmanInfo(e){let[t,n,r]=e.trim().split(/\s+/),i=Number(r?.match(/^(\d+)\./)?.[1]);return{rootless:t===`true`,selinux:n===`true`,...Number.isInteger(i)?{majorVersion:i}:{}}}async function podmanInfo(){try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.Security.Rootless}} {{.Host.Security.SELinuxEnabled}} {{.Version.Version}}`]);return parsePodmanInfo(e)}catch{return}}function runtimeNetworkMode(e,t){if(e===`podman`&&t?.rootless&&t.majorVersion===3)return`slirp4netns:allow_host_loopback=true`}function runtimeSecurityOptions(e,t){return e!==`podman`||!t?.selinux?[]:[`label=disable`]}function socketMountArg(t,n=e.platform){return`${n===`win32`&&t.startsWith(`/`)?`/${t}`:t}:${Mn}`}function buildRuntimeRunArgs({image:t,dataDir:n,detach:r,hostSocketPath:i,ports:a=Dn,platform:s=e.platform,networkMode:c,securityOptions:l=[]}){let u=[`run`,`--rm`,`--init`,`--name`,Sn];r&&u.push(`--detach`),a.api!==3333&&u.push(`-e`,`ACTOR_RUNTIME_API_PORT=${a.api}`),a.console!==3e3&&u.push(`-e`,`ACTOR_RUNTIME_CONSOLE_PORT=${a.console}`),c&&u.push(`--network`,c);for(let e of l)u.push(`--security-opt`,e);return u.push(`-p`,`${a.api}:${a.api}`,`-p`,`${a.console}:${a.console}`,`-v`,socketMountArg(i,s),`-v`,`${n}:${Nn}`,t),u}function runtimeSkillHintLines(){return[`Agents: run 'apify runtime skill --install' to install this runtime's Agent Skill,`,` or 'apify runtime skill' to read it now.`]}function readActorRuntimeConfig(){try{let e=JSON.parse(v(ACTOR_RUNTIME_CONFIG_FILE_PATH(),`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function updateActorRuntimeConfig(e){ensureApifyDirectory(ACTOR_RUNTIME_CONFIG_FILE_PATH()),E(ACTOR_RUNTIME_CONFIG_FILE_PATH(),JSON.stringify({...readActorRuntimeConfig(),...e},null,` `))}const Pn=[`APIFY_CLIENT_BASE_URL`,`APIFY_CONSOLE_URL`];function isConnectedToActorRuntime(){return readActorRuntimeConfig().connected===!0}function setConnectedToActorRuntime(e){updateActorRuntimeConfig({connected:e})}function configuredRuntimePorts(){let{apiPort:e,consolePort:t}=readActorRuntimeConfig();return{api:e??Dn.api,console:t??Dn.console}}function overridingRuntimeEnvVars(t=e.env){return Pn.filter(e=>t[e]).map(e=>[e,t[e]])}function resolveApiBaseUrl(t=e.env){return t.APIFY_CLIENT_BASE_URL||(isConnectedToActorRuntime()?runtimeApiUrl(configuredRuntimePorts().api):void 0)}function resolveConsoleUrl(t=e.env){return t.APIFY_CONSOLE_URL||(isConnectedToActorRuntime()?runtimeConsoleUrl(configuredRuntimePorts().console):void 0)}var ActorRuntimeNotRunningError=class extends Error{constructor(e){super(`The Apify CLI is connected to the local Actor runtime at ${runtimeApiUrl(e)}, but the runtime isn't running. Start it with 'apify runtime start --detach', or run 'apify runtime disconnect' to target the Apify platform.`),this.name=`ActorRuntimeNotRunningError`}};function targetsConnectedRuntime(t,n=e.env){return!n.APIFY_CLIENT_BASE_URL&&isConnectedToActorRuntime()&&t===runtimeApiUrl(configuredRuntimePorts().api)}const runtimeDownInterceptor=e=>{let t=j.getAdapter(e.adapter??j.defaults.adapter);return e.adapter=async e=>{try{return await t(e)}catch(e){throw e.code===`ECONNREFUSED`&&!await findRunningRuntimeEngine()?new ActorRuntimeNotRunningError(configuredRuntimePorts().api):e}},e},Fn=/* @__PURE__ */ new Set([`undefined`,`null`,`nil`,`none`,`nan`,`false`,`0`,`-`]);function readEnvToken(){let t=e.env[I.TOKEN]?.trim();return t?Fn.has(t.toLowerCase())?{kind:`invalid`,raw:t}:{kind:`token`,token:t}:{kind:`unset`}}function invalidEnvTokenMessage(e){return`${I.TOKEN} is set to "${e}", which is not an API token. Unset ${I.TOKEN} and try again.`}const In={env:`${I.TOKEN} environment variable`,stored:`apify login`,profile:`--profile flag`};let Ln,Rn;const zn=`No accounts are stored. Run "apify login" to add one.`;function envTokenOverridesProfileMessage(e){return`${I.TOKEN} is set, so commands ignore ${e}. Unset ${I.TOKEN} and try again.`}async function requireProfile(t){await ensureCredentialsCurrent();let n=matchProfiles(t);if(n.length===1)return n[0];if(e.exitCode=5,n.length>1)throw Error(`More than one stored account is called "${t}": ${n.map(({id:e})=>e).join(`, `)}. Use the user ID instead.`);let r=listProfiles().map(profileLabel);throw Error(r.length?`No stored account is called "${t}". Stored accounts: ${r.join(`, `)}.`:`No stored account is called "${t}". Run "apify login" to add one.`)}function getCurrentProfile(){return Rn??getActiveProfile()}async function selectProfile(t){if(readEnvToken().kind!==`unset`)throw e.exitCode=5,Error(envTokenOverridesProfileMessage(`--profile`));Rn=await requireProfile(t),Ln=void 0}const resolveAuth=async()=>{Ln??=(async()=>{await ensureMigrated();let t=readEnvToken();if(t.kind===`invalid`)throw e.exitCode=5,Error(invalidEnvTokenMessage(t.raw));if(t.kind===`token`)return p(AUTH_FILE_PATH())&&warning({message:`Using the API token from ${I.TOKEN}.`}),{token:t.token,source:`env`};if(await ensureCredentialsCurrent(),Rn){let t=await getAccessToken(Rn.id);if(!t)throw e.exitCode=1,Error(missingProfileTokenMessage(Rn));return{token:t,source:`profile`,profile:profileRef(Rn)}}let n=getActiveProfileId(),r=n?await getAccessToken(n):void 0;if(!r)return;let i=getActiveProfile();return{token:r,source:`stored`,...i?{profile:profileRef(i)}:{}}})();try{return await Ln}catch(e){throw Ln=void 0,e}};function profileRef(e){return{id:e.id,label:profileLabel(e)}}function missingProfileTokenMessage(e){return`No API token is stored for ${profileLabel(e)}. Run "apify login" to log in to ${profileLabel(e)} again.`}function describeAuthFailure(e,t){if(!e)return`You are not logged in with your Apify account. Call "apify login" to fix that.`;if(t instanceof ActorRuntimeNotRunningError)return t.message;let n=t instanceof O?t.statusCode:void 0;return t&&n!==401&&n!==403?`Could not verify your API token. The Apify API request failed: ${t instanceof Error?t.message:String(t)}`:e.source===`env`?`The API token in ${I.TOKEN} was rejected. Unset it to use your stored login instead.`:e.profile?`The stored API token for ${e.profile.label} was rejected. Run "apify login" to log in to ${e.profile.label} again.`:`Your stored API token was rejected. Call "apify login" to log in again.`}const getAnonymousApifyClientOptions=e=>{let t=e||resolveApiBaseUrl();return{baseUrl:t,requestInterceptors:[e=>{e.headers??=new M;for(let[t,n]of Object.entries(sn))e.headers[t]=n;return e},...targetsConnectedRuntime(t)?[runtimeDownInterceptor]:[]]}},getApifyClientOptionsForToken=(e,t)=>({...getAnonymousApifyClientOptions(t),token:e});async function loginWithToken(e,t){let n=new k(getApifyClientOptionsForToken(e,t)),r;try{r=await n.user(`me`).get()}catch(e){return cliDebugPrint(`[loginWithToken] error getting user info`,{error:e,apiBaseUrl:t}),null}if(!r.id)throw Error(`The Apify API returned no user ID for this token, so the login cannot be stored.`);let i=r.proxy?.password;await ensureCredentialsCurrent();let{organizationOwnerUserId:a}=r;upsertProfile(r.id,{username:r.username,name:r.username||r.id,...a?{organizationOwnerUserId:a}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:(/* @__PURE__ */ new Date()).toISOString()});let s=await clearKeyringSecrets();if(await clearOAuthSession(r.id),await setSecret(r.id,`token`,e,{skipIfUnchanged:!0}),i)await setSecret(r.id,`proxy-password`,i,{skipIfUnchanged:!0});else{let e=await deleteSecret(r.id,`proxy-password`);e&&s.push(e)}return s.length&&warning({message:`Secrets this login could not remove are still in the OS keyring at ${describeLeftovers(s)}; delete them with your OS keyring app.`}),{client:n,userInfo:r}}const Bn=Ne(m);let Vn;async function useStdin(){if(Vn)return Vn;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Bn(0).then(t=>{if(cliDebugPrint(`useStdin`,{stat:t,isRegularFile:t.isFile(),isDirectory:t.isDirectory(),isBlockDevice:t.isBlockDevice(),isCharDevice:t.isCharacterDevice(),isSymbolicLink:t.isSymbolicLink(),isFIFO:t.isFIFO(),isSocket:t.isSocket()}),e.platform===`win32`){if((t.mode&l.S_IFIFO)===l.S_IFIFO)return 100;if(t.isFile())return 50}return t.isFIFO()||t.isFile()||(t.isSocket()?50:!1)}).catch(()=>!1);return cliDebugPrint(`useStdin`,{hasData:n.hasData,waitDelay:n.waitDelay,isTTY:n.isTTY,pipedIn:r,readableEnded:t.readableEnded}),t.isTTY&&(r===!1||t.isTTY===void 0&&t.readableEnded)||(n.hasData=!0),typeof r==`number`&&(n.waitDelay=r),Vn=n,n}const Hn=5e3;let Un,Wn,Gn=!1,Kn=!1;async function readStdin(e={}){return Un??=_readStdin(e).then(e=>(Wn=e,Gn=!0,e)),Un}function stdinWasCutShort(){return Kn}function describeStdinRead(){return Gn?Wn?`Yes`:`No`:`Not read`}async function _readStdin({implicit:e}){let{hasData:t,waitDelay:n,stream:r}=await useStdin();if(!t)return;let i=e?n||Hn:n,a=[],s=new AbortController,c=null,armTimeout=e=>{e&&(c=setTimeout(()=>s.abort(),e).unref())},disarmTimeout=()=>{c&&=(clearTimeout(c),null)};armTimeout(i);let onData=t=>{a.push(t),disarmTimeout(),e&&armTimeout(1e3)};r.on(`data`,onData);try{await Ae(r,`end`,{signal:s.signal})}catch(t){if(t.name===`AbortError`){if(!e)return;Kn=a.length>0||i===Hn}}finally{r.off(`data`,onData),r.pause()}disarmTimeout();let l=Buffer.concat(a);if(l.length)return l}let qn=`inherit`;function keepStdoutClean(){qn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{cliDebugPrint(`spawnPromised`,{cmd:t,args:n,opts:r,forwardSignals:i});let a=K(t,n,{windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,qn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),s=[];if(i?.length)for(let t of i){let handler=()=>{a.kill(t)};e.on(t,handler),s.push(()=>e.off(t,handler))}try{return await Pe.fromAsync(a.catch(e=>{let n;throw n=e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage:`${t} exited with code ${e.exitCode}`,Error(n,{cause:e})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const Jn=[[`CLAUDECODE`,`claude_code`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CURSOR_AGENT`,`cursor`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`]];function detectAiAgent(){for(let[e,t]of Jn)if(process.env[e])return t}function detectCi(){return _e.isCI?{isCi:!0,ciProvider:_e.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const Yn=[`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{E(i,n),r!==void 0&&s(i,r),S(i,t)}catch(e){try{C(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{u(t,i),r!==void 0&&s(i,r),S(i,n)}catch(e){try{C(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Yn)atomicWriteSync(B(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(B(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(B(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=z(e.execPath),i=pe(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Yn){let t=B(r,`${e}.exe.old`);if(p(t))try{C(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`||!Yn.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=B(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 Yn){let n=B(r,`${t}.exe`);if(p(n))try{H(n)===H(e.execPath)?(S(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):C(n,{force:!0})}catch(e){try{S(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Xn;function getMaxLineWidth(){if(Xn)return Xn;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Xn=e;else if(!process.stdout.isTTY)Xn=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Xn=e<1?80:e<40?40:e}return Xn}function experimentalLabel(e){return e.experimental?`${t.yellow(`[EXPERIMENTAL]`)} `:``}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=`${experimentalLabel(this.command)}${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(`
|
|
@@ -54,7 +54,7 @@ Common package structures:
|
|
|
54
54
|
main.py`);return null}async function checkScrapyProject(e){return ScrapyProjectAnalyzer.isApplicable(e)}function shouldSkipRentalSunsetNotice({now:e,isCi:t,skipEnvValue:n}){return!!(n&&![`0`,`false`].includes(n)||t||e>=en)}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(e){let t=useCLIMetadata(),n=new URL(`/v2/store`,resolveApiBaseUrl()||`https://api.apify.com`);try{let{data:r}=await j.get(n.href,{params:{username:e,pricingModel:`FLAT_PRICE_PER_MONTH`,limit:1},timeout:3e3,headers:{...sn,"User-Agent":`Apify CLI/${t.version} (https://github.com/apify/apify-cli)`}});return typeof r?.data?.total==`number`?r.data.total:(cliDebugPrint(`useRentalSunsetNotice`,`Store response has no data.total`,{body:r}),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:ve,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 Nr={type:`boolean`,multiple:!1,short:`h`},Pr={type:`boolean`,multiple:!1},Fr={type:`string`,multiple:!1},Ir={type:`string`,multiple:!1},Lr=`user-agent`,Rr=/* @__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 Y=/* @__PURE__ */ new Map,zr=[`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 experimental;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(),Rr.has(this.entrypoint)){let t=r[Lr],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]=await 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);else{await 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&&zr.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}async _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 rr({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(h===void 0&&s.required)throw new rr({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0]}});if(Array.isArray(h)){if(h.length>1)throw new rr({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 rr({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 rr({code:8,command:this.ctor,metadata:{firstUse:i,secondUse:l}});i=l,this.flags[f]=await 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 rr({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 rr({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 rr({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(`
|
|
56
56
|
`)),c=[];for(let[r,a]of e){let e=`${r.padEnd(s)} ${a.description}`,l=i(e,getMaxLineWidth()-s-2),u=n(l,s+2+2).trim();c.push(` ${t.red(`>`)} ${u}`)}let l=[`Missing ${e.size} required ${this.pluralString(e.size,`argument`,`arguments`)}:`,...c,t.gray(` See more help with --help`)];a&&l.push(``,a),error({message:l.join(`
|
|
57
|
-
`)})}async _handleStdin(e){let t=await readStdin();switch(e){case 2:return(t?.toString(`utf8`)??``).trim();default:return t}}_buildParseArgsOption(){let e={help:Nr};Rr.has(this.entrypoint)&&(e[Lr]=Ir);let t={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:e};if(this.ctor.flags)for(let[e,n]of Object.entries(this.ctor.flags)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json flag! It is a type level assertion!`);if(e.toLowerCase()===`json`)continue;let r=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();r.startsWith(`no-`)&&(r=r.slice(3));let i=n.builder(r);for(let{flagName:e,option:n}of i)t.options[e]=n}return this.ctor.enableJsonFlag&&(t.options.json=Pr),this.ctor.enableProfileFlag&&(t.options.profile=Fr),t}static registerCommand(e){if(registerCommandForHelpGeneration(e,this),Y.set(this.name,this),this.aliases?.length)for(let e of this.aliases)Y.set(e,this);if(this.hiddenAliases?.length)for(let e of this.hiddenAliases)Y.set(e,this);if(this.subcommands?.length)for(let e of this.subcommands){if(Y.set(`${this.name} ${e.name}`,e),this.aliases?.length)for(let t of this.aliases)Y.set(`${t} ${e.name}`,e);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)Y.set(`${t} ${e.name}`,e);if(e.aliases?.length)for(let t of e.aliases){if(Y.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)Y.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)Y.set(`${n} ${t}`,e)}if(e.hiddenAliases?.length)for(let t of e.hiddenAliases){if(Y.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)Y.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)Y.set(`${n} ${t}`,e)}}}};async function internalRunCommand(e,t,n){let r={positionals:[],values:{},tokens:[]},i=0;for(let[e,t]of Object.entries(n)){let[n,a]=e.split(`_`);if(n===`args`)r.positionals[i++]=t;else{let e=kebabCaseString(camelCaseToKebabCase(a)).toLowerCase();e.startsWith(`no-`)?r.values[e.slice(3)]=!t:r.values[e]=t}}let a=new t(e,t.name,t.name);return a.skipTelemetry=!0,a.skipNotices=!0,await a._run(r),a}const X={string:stringFlag,boolean:booleanFlag,integer:integerFlag};function YesFlag(e=`Answer "yes" to all prompts.`){return{yes:X.boolean({char:`y`,description:e,default:!1})}}function stringFlag(e){return{flagTag:`string`,builder:t=>{let n=/* @__PURE__ */ new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:e.choices,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??2,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function booleanFlag(e){return{flagTag:`boolean`,builder:t=>{let n=/* @__PURE__ */ new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`boolean`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`boolean`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function integerFlag(e){return{flagTag:`integer`,builder:t=>{let n=/* @__PURE__ */ new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function getBooleanValue(e,t){let n=t!==!1;return/^(y|yes)/i.test(e)?n=!0:/^(n|no)/i.test(e)&&(n=!1),n}function boolToString(e){return e?`Yes`:`No`}const Br=_t((e,t)=>{let n=boolToString,[r,i]=St(`idle`),[a,s]=St(``),c=yt(),l=xt({status:r,theme:c});bt((r,c)=>{if(vt(r)){let r=getBooleanValue(a,e.default);s(n(r)),i(`done`),t(r)}else if(r.name===`tab`){let t=boolToString(!getBooleanValue(a,e.default));c.clearLine(0),c.write(t),s(t)}else if(r.name===`y`||r.name===`n`){let a=getBooleanValue(r.name,e.default);s(n(a)),i(`done`),t(a)}else c.clearLine(0),c.write(a),s(c.line)});let u=a,f=``;return r===`done`?u=c.style.answer(a):f=` ${c.style.defaultAnswer(e.default===!1?`y/N`:`Y/n`)}`,`${l} ${c.style.message(e.message,r)}${f} ${u}`}),Z=stdinCheckWrapper(async({message:e,default:t})=>await Br({message:e,default:t},Tr)),getDeprecatedLocalConfigPath=e=>B(e,nn),Vr=/* @__PURE__ */ new Map;async function useActorConfig({cwd:t=e.cwd(),migrateConfig:n=!0,warnAboutOldConfig:r=!0}={cwd:e.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let i=Vr.get(t);if(i)return cliDebugPrint(`useActorConfig`,{cacheHit:!0,config:i}),Le(i);let a=getLocalConfigPath(t),s=getDeprecatedLocalConfigPath(t),c,l;try{c=getJsonFileContent(a)}catch(e){return Fe({message:`Failed to read local config at path: '${a}':`,cause:e,exists:!1,config:{}})}try{l=getJsonFileContent(s)}catch(e){return Fe({message:`Failed to read local config at path: '${s}':`,cause:e,exists:!1,config:{}})}if(c&&l&&r&&await handleBothConfigVersionsFound(s),!c&&!l)return Vr.set(t,{exists:!1,migrated:!1,config:{}}),Le({exists:!1,migrated:!1,config:{}});let u=!1;if(!c&&l&&n){let e=await handleMigrationFlow(l,s,a);if(e.isErr())return Fe(e.unwrapErr());c=e.unwrap(),u=!0}return Vr.set(t,{exists:!0,migrated:u,config:c||l||{}}),cliDebugPrint(`useActorConfig`,{cacheHit:!1,config:Vr.get(t)}),Le({exists:!0,migrated:u,config:c||l||{}})}async function handleBothConfigVersionsFound(e){if(!await Z({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?`}))warning({message:`The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.`});else try{await we(e,`${e}.deprecated`),info({message:`The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.`})}catch(e){e instanceof Error?error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${e.message||e}`}):error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${je(e,{showHidden:!1})}`})}}const Hr=[`name`,`version`,`buildTag`];async function handleMigrationFlow(e,t,n){let r={...e};if(typeof r.version==`object`&&(r=updateLocalConfigStructure(r)),r={actorSpecification:1,environmentVariables:e?.env||void 0,...Hr.reduce((t,n)=>(t[n]=e[n],t),{})},!await Z({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?`}))return Fe({message:`Command can not run with old "apify.json" structure. Either let the CLI auto-update it or follow the guide on https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md and update it manually.`,exists:!0,config:r});try{await U(z(n),{recursive:!0}),await G(n,JSON.stringify(r,null,` `))}catch(e){let t=e;return Fe({message:`Failed to write the new "actor.json" file to path: '${n}'.\n ${t.message||t}`,exists:!0,config:r})}try{await we(t,`${t}.deprecated`)}catch(e){let t=e;warning({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${t.message||t}`})}return info({message:`The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.`}),Le(r)}function updateLocalConfigStructure(e){let t={name:e.name,template:e.template,version:e.version.versionNumber,buildTag:e.version.buildTag,env:null};if(e.version.envVars?.length){let n={};e.version.envVars.forEach(e=>{e.name&&e.value&&(n[e.name]=e.value)}),t.env=n}return t}const Ur=B(getLocalKeyValueStorePath(`default`),`INPUT.json`);var ActorCalculateMemoryCommand=class extends ApifyCommand{static name=`calculate-memory`;static description=`Calculates the Actor’s dynamic memory usage based on a memory expression from actor.json, input data, and run options.`;static group=`Actor Runtime`;static examples=[{description:`Calculate memory using the expression and input defaults from actor.json.`,command:`actor calculate-memory`},{description:`Override the memory expression and input file.`,command:`actor calculate-memory --defaultMemoryMbytes "input.length * 128" --input ./my-input.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#actor-calculate-memory`;static flags={input:X.string({description:`Path to the input JSON file used for the calculation.`,required:!1,default:Ur}),defaultMemoryMbytes:X.string({description:`Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.`,required:!1}),build:X.string({description:`Actor build version or build tag to evaluate the expression with.`,required:!1}),timeoutSecs:X.integer({description:`Maximum run timeout, in seconds.`,required:!1}),maxItems:X.integer({description:`Maximum number of items Actor can output.`,required:!1}),maxTotalChargeUsd:X.integer({description:`Maximum total charge in USD.`,required:!1})};async run(){let{input:t,memoryExpression:n,minMemory:r,maxMemory:i,runOptions:a}=await this.prepareMemoryArguments();if(!n)throw Error(`No memory-calculation expression found. Provide it via the --default-memory-mbytes flag or define defaultMemoryMbytes in actor.json.`);let s=H(e.cwd(),t),c=getJsonFileContent(s)??{};info({message:`Evaluating memory expression: ${n}`});try{let{calculateRunDynamicMemory:e}=await import(`@apify/actor-memory-expression`),t=await e(n,{input:c,runOptions:a});success({message:`Calculated memory: ${Math.min(Math.max(t,r),i)} MB`,stdout:!0})}catch(e){error({message:`Memory calculation failed: ${e.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...n}=this.flags,r=t,i=0,a=1/0;return r||({defaultMemoryMbytes:r,minMemoryMbytes:i=i,maxMemoryMbytes:a=a}=await this.getExpressionFromConfig()),{memoryExpression:r,minMemory:i,maxMemory:a,input:e,runOptions:n}}async getExpressionFromConfig(){let t=await useActorConfig({cwd:e.cwd()});if(t.isErr()){let{message:n,cause:r}=t.unwrapErr();return error({message:`${n}${r?`\n ${r.message}`:``}`}),e.exitCode=5,{}}let{config:n}=t.unwrap();return{defaultMemoryMbytes:n?.defaultMemoryMbytes?.toString(),minMemoryMbytes:n?.minMemoryMbytes,maxMemoryMbytes:n?.maxMemoryMbytes}}};function stringArg(e){return{argTag:`string`,required:e.required??!1,stdin:e.stdin??1,description:e.description,aliases:e.aliases,catchAll:e.catchAll??!1}}const Q={string:stringArg};var ActorChargeCommand=class extends ApifyCommand{static name=`charge`;static description=`Charge for a specific event in a pay-per-event Actor run.`;static group=`Actor Runtime`;static examples=[{description:`Charge one event of the given type.`,command:`actor charge result-item`},{description:`Charge 5 events with an idempotency key.`,command:`actor charge result-item --count 5 --idempotency-key req-123`},{description:`Test locally without actually charging.`,command:`actor charge result-item --test-pay-per-event`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#actor-charge`;static args={eventName:Q.string({description:`Name of the event to charge for.`,required:!0})};static flags={count:X.integer({description:`Number of events to charge.`,required:!1,default:1}),"idempotency-key":X.string({description:`Idempotency key for the charge request.`,required:!1}),"test-pay-per-event":X.boolean({description:`Test pay-per-event charging without actually charging.`,required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:n,idempotencyKey:r}=this.flags;if(!process.env.APIFY_IS_AT_HOME){info({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}if(n){info({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}let i=await getLoggedClientOrThrow(),a=process.env[I.ACTOR_RUN_ID];if(!a)throw Error(`Charge command must be executed in a running Actor. Run ID not found.`);if((await i.run(a).get())?.pricingInfo?.pricingModel!==`PAY_PER_EVENT`)throw Error(`Charge command can only be used with pay-per-event pricing model.`);info({message:`Charging ${t} events of type "${e}" with idempotency key "${r??`not-provided`}" (runId: ${a}).`,stdout:!0}),await i.run(a).charge({eventName:e,count:t,idempotencyKey:r})}};const Wr=[`.actor/INPUT_SCHEMA.json`,`./INPUT_SCHEMA.json`,`.actor/input_schema.json`,`./input_schema.json`],readInputSchema=async({forcePath:e,cwd:t,throwOnMissing:n=!1})=>{if(e)return{inputSchema:getJsonFileContent(e),inputSchemaPath:e};let r=getLocalConfig(t);if(typeof r?.input==`object`&&r.input!==null)return{inputSchema:r.input,inputSchemaPath:null};if(typeof r?.input==`string`){let e=B(t,rn,r.input),i=getJsonFileContent(e);if(!i){if(n)throw Error(`Input schema file not found at ${e} (referenced in '${q}').`);return warning({message:`Input schema file not found at ${e} (referenced in '${q}').`}),{inputSchema:null,inputSchemaPath:e}}return{inputSchema:i,inputSchemaPath:e}}for(let e of Wr){let n=B(t,e);if(p(n))return{inputSchema:getJsonFileContent(n),inputSchemaPath:n}}return{inputSchema:null,inputSchemaPath:B(t,Wr[0])}},readAndValidateInputSchema=async({forcePath:e,cwd:t,getMessage:n})=>{let{inputSchema:r,inputSchemaPath:i}=await readInputSchema({forcePath:e,cwd:t});if(!r)throw Error(`Input schema has not been found at ${i}.`);info({message:n(i)});let a=new mr({strict:!1});return wt(a,r),{inputSchema:r,inputSchemaPath:i}},readStorageSchema=({cwd:e,key:t,label:n,getRef:r,throwOnMissing:i=!1})=>{let a=getLocalConfig(e),s=r?r(a):a?.storages?.[t];if(typeof s==`object`&&s)return{schema:s,schemaPath:null};if(typeof s==`string`){let t=B(e,rn,s),r=getJsonFileContent(t);if(!r){if(i)throw Error(`${n} schema file not found at ${t} (referenced in '${q}').`);return warning({message:`${n} schema file not found at ${t} (referenced in '${q}').`}),null}return{schema:r,schemaPath:t}}return null},readDatasetSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`dataset`,label:`Dataset`});return t?{datasetSchema:t.schema,datasetSchemaPath:t.schemaPath}:null},readOutputSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`output`,label:`Output`,getRef:e=>e?.output});return t?{outputSchema:t.schema,outputSchemaPath:t.schemaPath}:null},createPrefilledInputFileFromInputSchema=async e=>{let t={};try{let{inputSchema:n}=await readInputSchema({cwd:e});if(n){let e=new mr({strict:!1});wt(e,n),t=Object.entries(n.properties).reduce((e,[t,n])=>(e[t]=n.type===`boolean`||n.editor===`hidden`?n.default:n.prefill,e),{})}}catch(e){warning({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${e.message}`})}finally{await writeKvsRecord({storePath:B(e,getLocalKeyValueStorePath()),key:re.INPUT,fileName:`${re.INPUT}.json`,contentType:`application/json; charset=utf-8`,body:JSON.stringify(t,null,` `)})}},getDefaultsFromInputSchema=e=>{let t={};for(let[n,r]of Object.entries(e.properties))r.default!==void 0&&(t[n]=r.default);return t};function formatSchemaValidationErrors(e,t){return`${t} schema is not valid:\n${e.map(e=>{let t=e.instancePath?` at ${e.instancePath}`:``;return` - ${e.message}${t}`}).join(`
|
|
57
|
+
`)})}async _handleStdin(e){let t=await readStdin();return e===2?(t?.toString(`utf8`)??``).trim():t}_buildParseArgsOption(){let e={help:Nr};Rr.has(this.entrypoint)&&(e[Lr]=Ir);let t={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:e};if(this.ctor.flags)for(let[e,n]of Object.entries(this.ctor.flags)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json flag! It is a type level assertion!`);if(e.toLowerCase()===`json`)continue;let r=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();r.startsWith(`no-`)&&(r=r.slice(3));let i=n.builder(r);for(let{flagName:e,option:n}of i)t.options[e]=n}return this.ctor.enableJsonFlag&&(t.options.json=Pr),this.ctor.enableProfileFlag&&(t.options.profile=Fr),t}static registerCommand(e){if(registerCommandForHelpGeneration(e,this),Y.set(this.name,this),this.aliases?.length)for(let e of this.aliases)Y.set(e,this);if(this.hiddenAliases?.length)for(let e of this.hiddenAliases)Y.set(e,this);if(this.subcommands?.length)for(let e of this.subcommands){if(Y.set(`${this.name} ${e.name}`,e),this.aliases?.length)for(let t of this.aliases)Y.set(`${t} ${e.name}`,e);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)Y.set(`${t} ${e.name}`,e);if(e.aliases?.length)for(let t of e.aliases){if(Y.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)Y.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)Y.set(`${n} ${t}`,e)}if(e.hiddenAliases?.length)for(let t of e.hiddenAliases){if(Y.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)Y.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)Y.set(`${n} ${t}`,e)}}}};async function internalRunCommand(e,t,n){let r={positionals:[],values:{},tokens:[]},i=0;for(let[e,t]of Object.entries(n)){let[n,a]=e.split(`_`);if(n===`args`)r.positionals[i++]=t;else{let e=kebabCaseString(camelCaseToKebabCase(a)).toLowerCase();e.startsWith(`no-`)?r.values[e.slice(3)]=!t:r.values[e]=t}}let a=new t(e,t.name,t.name);return a.skipTelemetry=!0,a.skipNotices=!0,await a._run(r),a}const X={string:stringFlag,boolean:booleanFlag,integer:integerFlag};function YesFlag(e=`Answer "yes" to all prompts.`){return{yes:X.boolean({char:`y`,description:e,default:!1})}}function stringFlag(e){return{flagTag:`string`,builder:t=>{let n=/* @__PURE__ */ new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:e.choices,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??2,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function booleanFlag(e){return{flagTag:`boolean`,builder:t=>{let n=/* @__PURE__ */ new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`boolean`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`boolean`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function integerFlag(e){return{flagTag:`integer`,builder:t=>{let n=/* @__PURE__ */ new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function getBooleanValue(e,t){let n=t!==!1;return/^(y|yes)/i.test(e)?n=!0:/^(n|no)/i.test(e)&&(n=!1),n}function boolToString(e){return e?`Yes`:`No`}const Br=_t((e,t)=>{let n=boolToString,[r,i]=St(`idle`),[a,s]=St(``),c=yt(),l=xt({status:r,theme:c});bt((r,c)=>{if(vt(r)){let r=getBooleanValue(a,e.default);s(n(r)),i(`done`),t(r)}else if(r.name===`tab`){let t=boolToString(!getBooleanValue(a,e.default));c.clearLine(0),c.write(t),s(t)}else if(r.name===`y`||r.name===`n`){let a=getBooleanValue(r.name,e.default);s(n(a)),i(`done`),t(a)}else c.clearLine(0),c.write(a),s(c.line)});let u=a,f=``;return r===`done`?u=c.style.answer(a):f=` ${c.style.defaultAnswer(e.default===!1?`y/N`:`Y/n`)}`,`${l} ${c.style.message(e.message,r)}${f} ${u}`}),Z=stdinCheckWrapper(async({message:e,default:t})=>await Br({message:e,default:t},Tr)),getDeprecatedLocalConfigPath=e=>B(e,nn),Vr=/* @__PURE__ */ new Map;async function useActorConfig({cwd:t=e.cwd(),migrateConfig:n=!0,warnAboutOldConfig:r=!0}={cwd:e.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let i=Vr.get(t);if(i)return cliDebugPrint(`useActorConfig`,{cacheHit:!0,config:i}),Le(i);let a=getLocalConfigPath(t),s=getDeprecatedLocalConfigPath(t),c,l;try{c=getJsonFileContent(a)}catch(e){return Fe({message:`Failed to read local config at path: '${a}':`,cause:e,exists:!1,config:{}})}try{l=getJsonFileContent(s)}catch(e){return Fe({message:`Failed to read local config at path: '${s}':`,cause:e,exists:!1,config:{}})}if(c&&l&&r&&await handleBothConfigVersionsFound(s),!c&&!l)return Vr.set(t,{exists:!1,migrated:!1,config:{}}),Le({exists:!1,migrated:!1,config:{}});let u=!1;if(!c&&l&&n){let e=await handleMigrationFlow(l,s,a);if(e.isErr())return Fe(e.unwrapErr());c=e.unwrap(),u=!0}return Vr.set(t,{exists:!0,migrated:u,config:c||l||{}}),cliDebugPrint(`useActorConfig`,{cacheHit:!1,config:Vr.get(t)}),Le({exists:!0,migrated:u,config:c||l||{}})}async function handleBothConfigVersionsFound(e){if(!await Z({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?`}))warning({message:`The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.`});else try{await we(e,`${e}.deprecated`),info({message:`The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.`})}catch(e){e instanceof Error?error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${e.message||e}`}):error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${je(e,{showHidden:!1})}`})}}const Hr=[`name`,`version`,`buildTag`];async function handleMigrationFlow(e,t,n){let r={...e};if(typeof r.version==`object`&&(r=updateLocalConfigStructure(r)),r={actorSpecification:1,environmentVariables:e?.env||void 0,...Hr.reduce((t,n)=>(t[n]=e[n],t),{})},!await Z({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?`}))return Fe({message:`Command can not run with old "apify.json" structure. Either let the CLI auto-update it or follow the guide on https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md and update it manually.`,exists:!0,config:r});try{await U(z(n),{recursive:!0}),await G(n,JSON.stringify(r,null,` `))}catch(e){let t=e;return Fe({message:`Failed to write the new "actor.json" file to path: '${n}'.\n ${t.message||t}`,exists:!0,config:r})}try{await we(t,`${t}.deprecated`)}catch(e){let t=e;warning({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${t.message||t}`})}return info({message:`The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.`}),Le(r)}function updateLocalConfigStructure(e){let t={name:e.name,template:e.template,version:e.version.versionNumber,buildTag:e.version.buildTag,env:null};if(e.version.envVars?.length){let n={};e.version.envVars.forEach(e=>{e.name&&e.value&&(n[e.name]=e.value)}),t.env=n}return t}const Ur=B(getLocalKeyValueStorePath(`default`),`INPUT.json`);var ActorCalculateMemoryCommand=class extends ApifyCommand{static name=`calculate-memory`;static description=`Calculates the Actor’s dynamic memory usage based on a memory expression from actor.json, input data, and run options.`;static group=`Actor Runtime`;static examples=[{description:`Calculate memory using the expression and input defaults from actor.json.`,command:`actor calculate-memory`},{description:`Override the memory expression and input file.`,command:`actor calculate-memory --defaultMemoryMbytes "input.length * 128" --input ./my-input.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#actor-calculate-memory`;static flags={input:X.string({description:`Path to the input JSON file used for the calculation.`,required:!1,default:Ur}),defaultMemoryMbytes:X.string({description:`Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.`,required:!1}),build:X.string({description:`Actor build version or build tag to evaluate the expression with.`,required:!1}),timeoutSecs:X.integer({description:`Maximum run timeout, in seconds.`,required:!1}),maxItems:X.integer({description:`Maximum number of items Actor can output.`,required:!1}),maxTotalChargeUsd:X.integer({description:`Maximum total charge in USD.`,required:!1})};async run(){let{input:t,memoryExpression:n,minMemory:r,maxMemory:i,runOptions:a}=await this.prepareMemoryArguments();if(!n)throw Error(`No memory-calculation expression found. Provide it via the --default-memory-mbytes flag or define defaultMemoryMbytes in actor.json.`);let s=H(e.cwd(),t),c=getJsonFileContent(s)??{};info({message:`Evaluating memory expression: ${n}`});try{let{calculateRunDynamicMemory:e}=await import(`@apify/actor-memory-expression`),t=await e(n,{input:c,runOptions:a});success({message:`Calculated memory: ${Math.min(Math.max(t,r),i)} MB`,stdout:!0})}catch(e){error({message:`Memory calculation failed: ${e.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...n}=this.flags,r=t,i=0,a=1/0;return r||({defaultMemoryMbytes:r,minMemoryMbytes:i=i,maxMemoryMbytes:a=a}=await this.getExpressionFromConfig()),{memoryExpression:r,minMemory:i,maxMemory:a,input:e,runOptions:n}}async getExpressionFromConfig(){let t=await useActorConfig({cwd:e.cwd()});if(t.isErr()){let{message:n,cause:r}=t.unwrapErr();return error({message:`${n}${r?`\n ${r.message}`:``}`}),e.exitCode=5,{}}let{config:n}=t.unwrap();return{defaultMemoryMbytes:n?.defaultMemoryMbytes?.toString(),minMemoryMbytes:n?.minMemoryMbytes,maxMemoryMbytes:n?.maxMemoryMbytes}}};function stringArg(e){return{argTag:`string`,required:e.required??!1,stdin:e.stdin??1,description:e.description,aliases:e.aliases,catchAll:e.catchAll??!1}}const Q={string:stringArg};var ActorChargeCommand=class extends ApifyCommand{static name=`charge`;static description=`Charge for a specific event in a pay-per-event Actor run.`;static group=`Actor Runtime`;static examples=[{description:`Charge one event of the given type.`,command:`actor charge result-item`},{description:`Charge 5 events with an idempotency key.`,command:`actor charge result-item --count 5 --idempotency-key req-123`},{description:`Test locally without actually charging.`,command:`actor charge result-item --test-pay-per-event`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#actor-charge`;static args={eventName:Q.string({description:`Name of the event to charge for.`,required:!0})};static flags={count:X.integer({description:`Number of events to charge.`,required:!1,default:1}),"idempotency-key":X.string({description:`Idempotency key for the charge request.`,required:!1}),"test-pay-per-event":X.boolean({description:`Test pay-per-event charging without actually charging.`,required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:n,idempotencyKey:r}=this.flags;if(!process.env.APIFY_IS_AT_HOME){info({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}if(n){info({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}let i=await getLoggedClientOrThrow(),a=process.env[I.ACTOR_RUN_ID];if(!a)throw Error(`Charge command must be executed in a running Actor. Run ID not found.`);if((await i.run(a).get())?.pricingInfo?.pricingModel!==`PAY_PER_EVENT`)throw Error(`Charge command can only be used with pay-per-event pricing model.`);info({message:`Charging ${t} events of type "${e}" with idempotency key "${r??`not-provided`}" (runId: ${a}).`,stdout:!0}),await i.run(a).charge({eventName:e,count:t,idempotencyKey:r})}};const Wr=[`.actor/INPUT_SCHEMA.json`,`./INPUT_SCHEMA.json`,`.actor/input_schema.json`,`./input_schema.json`],readInputSchema=async({forcePath:e,cwd:t,throwOnMissing:n=!1})=>{if(e)return{inputSchema:getJsonFileContent(e),inputSchemaPath:e};let r=getLocalConfig(t);if(typeof r?.input==`object`&&r.input!==null)return{inputSchema:r.input,inputSchemaPath:null};if(typeof r?.input==`string`){let e=B(t,rn,r.input),i=getJsonFileContent(e);if(!i){if(n)throw Error(`Input schema file not found at ${e} (referenced in '${q}').`);return warning({message:`Input schema file not found at ${e} (referenced in '${q}').`}),{inputSchema:null,inputSchemaPath:e}}return{inputSchema:i,inputSchemaPath:e}}for(let e of Wr){let n=B(t,e);if(p(n))return{inputSchema:getJsonFileContent(n),inputSchemaPath:n}}return{inputSchema:null,inputSchemaPath:B(t,Wr[0])}},readAndValidateInputSchema=async({forcePath:e,cwd:t,getMessage:n})=>{let{inputSchema:r,inputSchemaPath:i}=await readInputSchema({forcePath:e,cwd:t});if(!r)throw Error(`Input schema has not been found at ${i}.`);info({message:n(i)});let a=new mr({strict:!1});return wt(a,r),{inputSchema:r,inputSchemaPath:i}},readStorageSchema=({cwd:e,key:t,label:n,getRef:r,throwOnMissing:i=!1})=>{let a=getLocalConfig(e),s=r?r(a):a?.storages?.[t];if(typeof s==`object`&&s)return{schema:s,schemaPath:null};if(typeof s==`string`){let t=B(e,rn,s),r=getJsonFileContent(t);if(!r){if(i)throw Error(`${n} schema file not found at ${t} (referenced in '${q}').`);return warning({message:`${n} schema file not found at ${t} (referenced in '${q}').`}),null}return{schema:r,schemaPath:t}}return null},readDatasetSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`dataset`,label:`Dataset`});return t?{datasetSchema:t.schema,datasetSchemaPath:t.schemaPath}:null},readOutputSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`output`,label:`Output`,getRef:e=>e?.output});return t?{outputSchema:t.schema,outputSchemaPath:t.schemaPath}:null},createPrefilledInputFileFromInputSchema=async e=>{let t={};try{let{inputSchema:n}=await readInputSchema({cwd:e});if(n){let e=new mr({strict:!1});wt(e,n),t=Object.entries(n.properties).reduce((e,[t,n])=>(e[t]=n.type===`boolean`||n.editor===`hidden`?n.default:n.prefill,e),{})}}catch(e){warning({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${e.message}`})}finally{await writeKvsRecord({storePath:B(e,getLocalKeyValueStorePath()),key:re.INPUT,fileName:`${re.INPUT}.json`,contentType:`application/json; charset=utf-8`,body:JSON.stringify(t,null,` `)})}},getDefaultsFromInputSchema=e=>{let t={};for(let[n,r]of Object.entries(e.properties))r.default!==void 0&&(t[n]=r.default);return t};function formatSchemaValidationErrors(e,t){return`${t} schema is not valid:\n${e.map(e=>{let t=e.instancePath?` at ${e.instancePath}`:``;return` - ${e.message}${t}`}).join(`
|
|
58
58
|
`)}`}function validateDatasetSchema(e){let t=Et();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Dataset`))}function validateOutputSchema(e){let t=Ot();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Output`))}function validateKvsSchema(e){let t=Dt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Key-Value Store`))}const getAjvValidator=(e,t)=>{let n=structuredClone(e);n.required=[];for(let[t,r]of Object.entries(e.properties)){let i=e.required?.includes(t),a=r.default!==void 0;i&&!a&&(n.required.push(t),r.type===`array`&&(r.minItems=Math.max(1,r.minItems||0)))}return delete n.$schema,t.compile(n)};function makePropertiesRequired(e){let t=structuredClone(e);if(!t.properties||typeof t.properties!=`object`)return t;let n=t.properties,r=new Set(Array.isArray(t.required)?t.required:[]);for(let[e,t]of Object.entries(n))t.default!==void 0&&r.add(e),t.type===`object`&&t.properties&&(n[e]=makePropertiesRequired(t));return t.required=Array.from(r),t}function clearAllRequired(e){let t=structuredClone(e);if(delete t.required,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n.type===`object`&&n.properties&&(e[t]=clearAllRequired(n))}return t}function stripTitles(e){let t=structuredClone(e);if(delete t.title,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}t.items&&typeof t.items==`object`&&(t.items=stripTitles(t.items));for(let e of[`allOf`,`anyOf`,`oneOf`])Array.isArray(t[e])&&(t[e]=t[e].map(e=>e&&typeof e==`object`?stripTitles(e):e));for(let e of[`definitions`,`$defs`])if(t[e]&&typeof t[e]==`object`&&!Array.isArray(t[e])){let n=t[e];for(let[e,t]of Object.entries(n))t&&typeof t==`object`&&(n[e]=stripTitles(t))}t.additionalProperties&&typeof t.additionalProperties==`object`&&(t.additionalProperties=stripTitles(t.additionalProperties));for(let e of[`if`,`then`,`else`,`not`])t[e]&&typeof t[e]==`object`&&(t[e]=stripTitles(t[e]));if(t.patternProperties&&typeof t.patternProperties==`object`&&!Array.isArray(t.patternProperties)){let e=t.patternProperties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}return t}function prepareFieldsSchemaForCompilation(e){let t=e.fields;if(!t||typeof t!=`object`||!t.properties||typeof t.properties!=`object`)return null;let n=structuredClone(t);return n.type||=`object`,n}function prepareOutputSchemaForCompilation(e){let t=e.properties;if(!t||typeof t!=`object`||Object.keys(t).length===0)return null;let n=structuredClone(t);for(let e of Object.values(n))e&&typeof e==`object`&&delete e.template;let r={type:e.type||`object`,properties:n};return Array.isArray(e.required)&&(r.required=[...e.required]),r}function prepareKvsCollectionsForCompilation(e){let t=e.collections;if(!t||typeof t!=`object`)return[];let n=[];for(let[e,r]of Object.entries(t)){if(!r||typeof r!=`object`)continue;let t=r.jsonSchema;if(!t||typeof t!=`object`||Object.keys(t).length===0)continue;let i=structuredClone(t);i.type||=`object`,n.push({name:e,schema:i})}return n}var ActorGenerateSchemaTypesCommand=class extends ApifyCommand{static name=`generate-schema-types`;static hiddenAliases=[`generate-types`];static description=`Generate TypeScript types from Actor schemas.
|
|
59
59
|
|
|
60
60
|
Generates types from the input schema and, when no custom path is provided,
|
|
@@ -88,7 +88,7 @@ just as if the command were run from that directory with no argument.`;static gr
|
|
|
88
88
|
For platform-level management (deploy, list, call Actors), see 'apify actors' (plural).`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actor`;static subcommands=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand];async run(){this.printHelp()}};function OverrideClassName(e){return e}function getConsoleUrl(){let e=resolveConsoleUrl();if(e){let t=stripTrailingSlash(e);if(!URL.canParse(t))throw Error(`Invalid APIFY_CONSOLE_URL environment variable: "${e}" is not a valid URL.`);return t}return`https://console.apify.com`}function getConsoleRoutePrefix(e){return e?.organizationOwnerUserId&&e.id?`/organization/${e.id}`:null}function getConsoleIntegrationsUrl(e){return`${getConsoleUrl()}${getConsoleRoutePrefix(e)??``}/settings/integrations`}function stripTrailingSlash(e){return e.replace(/\/+$/,``)}function isTerminalStatus(e){return!!e&&ee.includes(e)}function exitCodeForJobStatus(e,t){switch(e){case P.SUCCEEDED:return 0;case P.TIMED_OUT:case P.TIMING_OUT:return F.BUILD,2;case P.ABORTED:case P.ABORTING:return F.BUILD,3;default:return F.BUILD,1}}function exitCodeForWaitResult(e,t){return e.timedOutWaiting?6:exitCodeForJobStatus(e.job.status,t)}async function waitForTerminalStatus(e){let{apifyClient:t,jobId:n,kind:r,pollIntervalMillis:i=2e3,maxWaitMillis:a}=e,s=Date.now();for(;;){let e=r===F.BUILD?await t.build(n).get():await t.run(n).get();if(!e)throw Error(`${r===F.BUILD?`Build`:`Run`} with ID "${n}" was not found.`);if(isTerminalStatus(e.status))return{job:e,timedOutWaiting:!1};if(a&&Date.now()-s>=a)return{job:e,timedOutWaiting:!0};let c=a?Math.min(i,a-(Date.now()-s)):i;await new Promise(e=>setTimeout(e,Math.max(0,c)))}}async function fetchLogTail(e,t,n=20){try{let r=await e.log(t).get();return r?r.split(`
|
|
89
89
|
`).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-n):[]}catch{return[]}}function consoleActorUrl(e){return`${getConsoleUrl()}/actors/${e}`}function consoleRunUrl(e,t){return`${getConsoleUrl()}/actors/${e}/runs/${t}`}function consoleBuildUrl(e,t){return`${getConsoleUrl()}/actors/${e}/builds/${t}`}function consoleDatasetUrl(e){return`${getConsoleUrl()}/storage/datasets/${e}`}function consoleKeyValueStoreUrl(e){return`${getConsoleUrl()}/storage/key-value-stores/${e}`}function statusColor(e){return e===P.SUCCEEDED?t.green(e):e===P.RUNNING||e===P.READY?t.blue(e):t.red(e)}function formatResultSummary(e){let n=[];n.push(`${t.bold(e.resultLabel)}: ${statusColor(e.overallStatus)}`),n.push(``);for(let t of e.lines)n.push(`${t.label}: ${t.value}`);if(e.links?.length){n.push(``);for(let r of e.links)n.push(`${r.label}: ${t.blue(r.url)}`)}if(e.errorReason?.length){n.push(``),n.push(t.red(`Reason:`));for(let t of e.errorReason)n.push(t)}return n.join(`
|
|
90
90
|
`)}async function resolveActorContext({providedActorNameOrId:t,client:n}){let r=await getCurrentUserInfo(),i=r.username||r.id,a=getLocalConfig(e.cwd())||{};if(t?.includes(`/`)){let e=await n.actor(t).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with ID "${t}" was not found`}}if(t){let e=await n.actor(t).get();if(e)return{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id};let r=await n.actor(`${i}/${t.toLowerCase()}`).get();return r?{valid:!0,userFriendlyId:`${r.username}/${r.name}`,id:r.id}:{valid:!1,reason:`Actor with name or ID "${t}" was not found`}}if(a.name){let e=await n.actor(`${i}/${a.name}`).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with name "${a.name}" was not found`}}return{valid:!1,reason:`No Actor specified. Pass an Actor ID or "username/name", or run this command from an Actor project directory`}}function useSignalHandler({signals:e,handler:t,cleanTerminalLine:n=!0,once:r=!0}){let i=!1,wrapped=a=>{if(!i){if(r){i=!0;for(let t of e)process.off(t,wrapped)}n&&process.stderr.isTTY&&process.stderr.write(`\r\x1B[2K\x1B[0m`),cliDebugPrint(`useSignalHandler`,{event:`fired`,signal:a,once:r}),(async()=>{try{await t(a)}catch(e){cliDebugPrint(`useSignalHandler`,{event:`handler-threw`,signal:a,err:e})}})()}};for(let t of e)process.on(t,wrapped);return cliDebugPrint(`useSignalHandler`,{event:`registered`,signals:e,once:r}),{[Symbol.dispose](){if(!i){i=!0;for(let t of e)process.off(t,wrapped);cliDebugPrint(`useSignalHandler`,{event:`disposed`,signals:e})}}}}function reraiseSignal(e){process.kill(process.pid,e)}let Kr=0;function isAbortingJobOnSignal(){return Kr>0}function useAbortJobOnSignal(e){let{apifyClient:n,silent:r=!1}=e,i=0,a=useSignalHandler({signals:tn,once:!1,handler:async a=>{if(i+=1,e.kind===F.BUILD){if(i>1)return;r||info({message:t.gray(`Received ${t.yellow(a)}, aborting build "${t.yellow(e.jobId)}" on the Apify platform...`),stdout:!0});try{await n.build(e.jobId).abort()}catch(t){error({message:`Failed to abort build "${e.jobId}": ${t.message}`,stdout:!0})}return}if(i>2)return;let s=i===1,c=`${e.runType.toLowerCase()} run`;if(!r){let n=s?`Received ${t.yellow(a)}, gracefully aborting ${c} "${t.yellow(e.jobId)}" on the Apify platform... ${t.dim(`(press Ctrl+C again to abort immediately)`)}`:`Received ${t.yellow(a)} again, aborting ${c} "${t.yellow(e.jobId)}" immediately...`;info({message:t.gray(n),stdout:!0})}try{await n.run(e.jobId).abort({gracefully:s})}catch(t){error({message:`Failed to abort run "${e.jobId}": ${t.message}`,stdout:!0})}}});Kr+=1;let s=!1;return{[Symbol.dispose](){s||(s=!0,--Kr,a[Symbol.dispose]())}}}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}var BuildsCreateCommand=class extends ApifyCommand{static name=`create`;static enableProfileFlag=!0;static description=`Creates a new build of the Actor.`;static examples=[{description:`Build the Actor in the current directory with the default "latest" tag.`,command:`apify builds create`},{description:`Build a specific Actor with a custom tag and stream the build log.`,command:`apify builds create apify/hello-world --tag beta --log`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-create`;static flags={tag:X.string({description:`Build tag to be applied to the successful Actor build. By default, this is "latest".`}),version:X.string({description:`Optional Actor Version to build. By default, this will be inferred from the tag, but this flag is required when multiple versions have the same tag.`,required:!1}),log:X.boolean({description:`Whether to print out the build log after the build is triggered.`}),wait:X.boolean({description:`Wait for the build to reach a terminal status. Returns exit code 0 only when the build SUCCEEDED.`,default:!1})};static args={actorId:Q.string({description:`Optional Actor ID or Name to trigger a build for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{tag:n,version:r,json:i,log:a,wait:s}=this.flags,{actorId:c}=this.args;if(a&&s){error({message:`The --log and --wait flags cannot be used together. --log already waits for the build to finish while streaming its log.`}),e.exitCode=5;return}let l=await getLoggedClientOrThrow(),u=await resolveActorContext({providedActorNameOrId:c,client:l});if(!u.valid){error({message:`${u.reason}.`,stdout:!0});return}let f=await l.actor(u.id).get(),p=objectGroupBy(f.versions,e=>e.buildTag??`latest`)[n??`latest`],m=f.versions.find(e=>e.versionNumber===r),h;if(m){if(n&&(!p||!p.some(e=>e.versionNumber===r))){error({message:`The Actor Version "${r}" does not have the tag "${n}".`,stdout:!0});return}h=r}else if(p&&(h=p[0].versionNumber,p.length>1&&!r)){error({message:`Multiple Actor versions with the tag "${n}" found. Please specify the version number using the "--version" flag.\n Available versions for this tag: ${p.map(e=>t.yellow(e.versionNumber)).join(`, `)}`,stdout:!0});return}if(!h){error({message:`No Actor versions with the tag "${n}" found. You can push a new version with this tag by using "apify push --build-tag=${n}".`,stdout:!0});return}let g=await l.actor(u.id).build(h,{tag:n}),_=f?.name??`unknown-actor`,v=consoleBuildUrl(g.actId,g.buildNumber);if(a||s)try{var y=_usingCtx();if(y.u(useAbortJobOnSignal({apifyClient:l,kind:F.BUILD,jobId:g.id})),a)try{await outputJobLog({job:g,apifyClient:l})}catch(e){error({message:`Failed to print log for build with ID "${g.id}": ${e.message}`,stdout:!0})}let{job:e}=await waitForTerminalStatus({apifyClient:l,jobId:g.id,kind:F.BUILD});g=e}catch(e){y.e=e}finally{y.d()}if(a||s){let t=g.status===P.SUCCEEDED,n=exitCodeForJobStatus(g.status,F.BUILD),r=t?[]:await fetchLogTail(l,g.id);if(i){printJsonToStdout({ok:t,operation:`builds.create`,waited:!0,actor:{id:g.actId,name:_},build:{id:g.id,number:g.buildNumber,status:g.status,url:v},...t?{}:{error:{phase:`build`,message:`Actor build did not succeed`,logTail:r}},exitCode:n}),e.exitCode=n;return}simpleLog({message:formatResultSummary({resultLabel:`Apify build result`,overallStatus:g.status,lines:[{label:`Build`,value:g.status},{label:`Build ID`,value:g.id},{label:`Build number`,value:g.buildNumber},{label:`Actor ID`,value:g.actId}],links:[{label:`Build URL`,url:v}],errorReason:t?void 0:r}),stdout:!0}),e.exitCode=n}else i?printJsonToStdout({ok:!0,operation:`builds.create`,waited:!1,actor:{id:g.actId,name:_},build:{id:g.id,number:g.buildNumber,status:g.status,url:v},next:{wait:`apify builds wait ${g.id} --json`,log:`apify builds log ${g.id}`,info:`apify builds info ${g.id} --json`},exitCode:0}):simpleLog({message:[t.greenBright(`Build started.`),``,`${t.yellow(`Actor`)}: ${_} (${t.gray(g.actId)})`,`${t.yellow(`Build ID`)}: ${g.id}`,`${t.yellow(`Build number`)}: ${g.buildNumber}`,`${t.yellow(`Status`)}: ${g.status}`,``,t.gray(`This command does not wait for the build to finish.`),``,`To wait for the final status:`,` apify builds wait ${g.id} --json`,``,`To inspect logs:`,` apify builds log ${g.id}`,``,`To inspect build metadata:`,` apify builds info ${g.id} --json`].join(`
|
|
91
|
-
`),stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function withSchemaHint(e,t){return t?`${e}\n${t}`:e}function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(lt.getExtension(t.contentType)===`json`?(n=JSON.parse(t.body.toString(`utf8`)),r=`application/json`):(n=t.body,r=t.contentType))}return!n||!r?null:{inputToUse:n,contentType:r}}async function getInputOverride(t,n,r,i={}){let a,s,{schemaHint:c}=i;if(!n&&!r){let t=await readStdin({implicit:!0});if(!t&&stdinWasCutShort()&&warning({message:"Nothing arrived on standard input, so it was ignored. Use `--input-file=-` to wait for a slow writer."}),t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,c)}),e.exitCode=5,!1;a=n,s=`stdin`}catch(t){let n=stdinWasCutShort()?"\nStandard input was still open when the CLI stopped waiting for it. If the input is incomplete, use `--input-file=-` to wait for all of it.":``;return error({message:withSchemaHint(`Cannot parse JSON input from standard input.\n ${t.message}${n}`,c)}),e.exitCode=5,!1}}if(n)
|
|
91
|
+
`),stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function withSchemaHint(e,t){return t?`${e}\n${t}`:e}function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(lt.getExtension(t.contentType)===`json`?(n=JSON.parse(t.body.toString(`utf8`)),r=`application/json`):(n=t.body,r=t.contentType))}return!n||!r?null:{inputToUse:n,contentType:r}}async function getInputOverride(t,n,r,i={}){let a,s,{schemaHint:c}=i;if(!n&&!r){let t=await readStdin({implicit:!0});if(!t&&stdinWasCutShort()&&warning({message:"Nothing arrived on standard input, so it was ignored. Use `--input-file=-` to wait for a slow writer."}),t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,c)}),e.exitCode=5,!1;a=n,s=`stdin`}catch(t){let n=stdinWasCutShort()?"\nStandard input was still open when the CLI stopped waiting for it. If the input is incomplete, use `--input-file=-` to wait for all of it.":``;return error({message:withSchemaHint(`Cannot parse JSON input from standard input.\n ${t.message}${n}`,c)}),e.exitCode=5,!1}}if(n){if(n[0]===`-`)return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),e.exitCode=5,!1;{let r=await ye(H(t,n)).then(()=>!0).catch(()=>!1),i=n.endsWith(`.json`)||n.endsWith(`.json5`)||R.isAbsolute(n)||n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`~`)||n.startsWith(`.\\`)||n.startsWith(`..\\`);if(r||i)return error({message:`Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead`}),e.exitCode=5,!1;try{let t=JSON.parse(n);if(Array.isArray(t))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,c)}),e.exitCode=5,!1;a=t,s=`input`}catch(t){return error({message:withSchemaHint(`Cannot parse JSON input.\n ${t.message}`,c)}),e.exitCode=5,!1}}}else if(r){if(r[0]===`-`)return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),e.exitCode=5,!1;{let n=H(t,r),i;try{let t=await Se(n,`utf8`),i=JSON.parse(t);if(Array.isArray(i))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,c)}),e.exitCode=5,!1;a=i,s=r}catch(e){i=e}if(i)try{let t=JSON.parse(r);if(Array.isArray(t))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,c)}),e.exitCode=5,!1;a=t,s=r}catch{return error({message:withSchemaHint(`Cannot read input file at path "${n}".\n ${i.message}`,i instanceof SyntaxError?c:void 0)}),e.exitCode=5,!1}}}return a?{input:a,source:s}:void 0}const qr=[P.SUCCEEDED,P.ABORTED,P.FAILED,P.TIMED_OUT];async function startActorWithExtraParams(e,t,n,r,i){let{waitForFinish:a,timeout:s,memory:c,build:l}=r,u=await e.httpClient.call({url:`${e.actor(t).url}/runs`,method:`POST`,data:n?.inputToUse,headers:n?{"content-type":n.contentType}:void 0,params:{waitForFinish:a,timeout:s,memory:c,build:l,...i}});return await e.run(u.data.data.id).get()}async function*runActorOrTaskOnCloud(n,r){try{var i=_usingCtx();let a=e.cwd(),{actorOrTaskData:s,runOptions:c,type:l,waitForFinishMillis:u,inputOverride:f,silent:p,waitForRunToFinish:m,printRunLogs:h,suppressFinalStatus:g,extraStartParams:_}=r,v=l===`Actor`?`actor`:`task`,y=resolveInput(a,f);p||(l===`Actor`?run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}):s.title?run({message:`Calling ${l} ${s.title} (${s.userFriendlyId}, ${t.gray(s.id)})\n`}):run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}));let b;try{b=_&&l===`Actor`?await startActorWithExtraParams(n,s.id,y,c,_):y&&l===`Actor`?await n[v](s.id).start(y.inputToUse,{...c,contentType:y.contentType}):await n[v](s.id).start(void 0,c)}catch(e){if(e.type===`record-not-found`){let t=typeof e.message==`string`&&e.message?`: ${e.message}`:`!`;throw Error(`${l} ${s.userFriendlyId} (${s.id}) not found${t}`)}if(e.type===`full-permission-actor-not-approved`){let n=e.data?.approvalUrl,r=[`${l} ${s.userFriendlyId} requires full access to your Apify account and has not been approved yet.`];throw n&&r.push(``,`Approve here: ${t.blue(n)}`),Error(r.join(`
|
|
92
92
|
`))}throw e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:F.RUN,jobId:b.id,runType:l,silent:p})),yield b,!p&&h)try{await outputJobLog({job:b,timeoutMillis:u,apifyClient:n})===`timeouts`?console.error(`\n${t.gray(`Timeout for printing logs was hit, there may be future logs.`)}\n`):console.error()}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(b=await n.run(b.id).get(),m)for(;!qr.includes(b.status)&&(b=await n.run(b.id).get(),!qr.includes(b.status));)await new Promise(e=>{setTimeout(e,1e3)});g||(b.status===P.SUCCEEDED?p||success({message:`${l} finished.`}):b.status===P.RUNNING?p||warning({message:`${l} is still running!`}):b.status===P.ABORTED||b.status===P.ABORTING?(p||warning({message:`${l} was aborted!`}),e.exitCode=3):(p||error({message:`${l} failed!`}),e.exitCode=1)),yield b}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:X.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:X.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:X.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})}),Jr={call:`Apify call`,"task-run":`Apify task run`};function isSucceeded(e){return e.status===P.SUCCEEDED}function getRunExitCode(e){switch(e.status){case P.SUCCEEDED:return 0;case P.ABORTED:case P.ABORTING:return 3;case P.TIMED_OUT:case P.TIMING_OUT:return 2;default:return e.exitCode&&e.exitCode!==0?e.exitCode:1}}function genericReason(e){switch(e.status){case P.ABORTED:case P.ABORTING:return`Actor run was aborted`;case P.TIMED_OUT:case P.TIMING_OUT:return`Actor run timed out`;default:return`Actor run failed`}}async function fetchRunLogTail(e,t){return isSucceeded(t)?[]:fetchLogTail(e,t.id,10)}function buildRunResultJson({run:e,operation:t,logTail:n}){let r=isSucceeded(e),i={ok:r,operation:t,actor:{id:e.actId,url:consoleActorUrl(e.actId)},run:{id:e.id,status:e.status,url:consoleRunUrl(e.actId,e.id)},storage:{defaultDatasetId:e.defaultDatasetId,defaultKeyValueStoreId:e.defaultKeyValueStoreId,datasetUrl:consoleDatasetUrl(e.defaultDatasetId)},exitCode:getRunExitCode(e)};return r||(i.error={phase:`run`,message:e.statusMessage||genericReason(e),logTail:n}),i}function printRunResultSummary({run:e,operation:n,logTail:r}){let i=isSucceeded(e),a=i?t.green:t.red,s=[`${Jr[n]} result: ${a(e.status)}`,``,`${t.yellow(`Run`)}: ${a(e.status)}`,`${t.yellow(`Actor ID`)}: ${e.actId}`,`${t.yellow(`Run ID`)}: ${e.id}`,`${t.yellow(`Build number`)}: ${e.buildNumber}`];!i&&e.exitCode!=null&&s.push(`${t.yellow(`Exit code`)}: ${e.exitCode}`),s.push(`${t.yellow(`Dataset ID`)}: ${e.defaultDatasetId}`,`${t.yellow(`Key-value store ID`)}: ${e.defaultKeyValueStoreId}`,``,`${t.blue(`Run URL`)}: ${consoleRunUrl(e.actId,e.id)}`,`${t.blue(`Dataset URL`)}: ${consoleDatasetUrl(e.defaultDatasetId)}`),i||s.push(``,`${t.yellow(`Reason`)}:`,e.statusMessage||genericReason(e),...r),simpleLog({message:s.join(`
|
|
93
93
|
`),stdout:!0})}async function finalizeRun({apifyClient:t,run:n,operation:r,json:i,silent:a}){if(e.exitCode=getRunExitCode(n),a)return;let s=await fetchRunLogTail(t,n);i?printJsonToStdout(buildRunResultJson({run:n,operation:r,logTail:s})):printRunResultSummary({run:n,operation:r,logTail:s})}function mayTargetActorRuntime(e){if(!e.baseUrl)return!1;try{let{hostname:t}=new URL(e.baseUrl);return t!==`apify.com`&&!t.endsWith(`.apify.com`)}catch{return!1}}async function registerActorRuntimeDevFolder(e,t,n){try{let r=await fetch(`${e.baseUrl}/actor-runtime/dev-folder/${t}`,{method:`POST`,headers:{...sn,Authorization:`Bearer ${e.token}`,"Content-Type":`application/json`},body:JSON.stringify(n)});return r.ok?{ok:!0}:r.status===404?{ok:!1}:{ok:!1,error:(await r.json().catch(()=>null))?.error?.message??`${r.status} ${r.statusText}`}}catch(e){return{ok:!1,error:e.message}}}const Yr=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],Xr=/* @__PURE__ */ new Set([`GET`,`HEAD`]);function parseParams(e){if(!e)return``;let t;try{t=JSON.parse(e)}catch{throw Error(`Invalid JSON in --params flag. Please provide a valid JSON object, e.g. '{"limit": 1}'.`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`--params must be a JSON object (e.g. '{"limit": 1}').`);let n=new URLSearchParams;for(let[e,r]of Object.entries(t))if(r!=null){if(typeof r==`object`)throw Error(`--params value for "${e}" must be a scalar (string, number, or boolean), got ${Array.isArray(r)?`array`:`object`}. Query parameters cannot contain nested objects or arrays.`);n.append(e,String(r))}return n.toString()}function parseHeaders(e){if(!e)return{};let t=e.trim();if(t.startsWith(`{`)){let e;try{e=JSON.parse(t)}catch{throw Error(`Invalid JSON in --header flag. Provide a JSON object like '{"X-Foo": "bar"}'.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--header JSON must be an object mapping header names to string values.`);let n={};for(let[t,r]of Object.entries(e)){if(typeof r!=`string`)throw Error(`--header value for "${t}" must be a string, got ${typeof r}.`);n[t.trim()]=r.trim()}return n}let n=t.indexOf(`:`);if(n===-1)throw Error(`Header must be in "key:value" format, or a JSON object for multiple headers.`);return{[t.slice(0,n).trim()]:t.slice(n+1).trim()}}function mergeHeaders(e,t){let n={...e};for(let[e,r]of Object.entries(t)){for(let t of Object.keys(n))t.toLowerCase()===e.toLowerCase()&&delete n[t];n[e]=r}return n}const Zr=`x-apify-container-server-readiness-probe`,Qr=/^\d+\.\d+\.\d+$/,$r=/* @__PURE__ */ new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`]);function isMultiTenant(e){return e.tenancy===`MULTI_TENANT`}function getEffectivePricingModel(e,t=Date.now()){let n;for(let r of e??[]){let e=new Date(r.startedAt).getTime();Number.isNaN(e)||e>t||(!n||e>n.startedAt)&&(n={pricingModel:r.pricingModel,startedAt:e})}return n?.pricingModel}function describeTenancy(e,t){return isMultiTenant(e)?t===e.ownerUsername?`multi-tenant (runs in your account; your own requests pay the platform usage, never events)`:`multi-tenant (runs in "${e.ownerUsername}"'s account; ${describeCallerCost(e.pricingModel)})`:`single-tenant (runs in your account "${t}", which pays the platform usage)`}function describeCallerCost(e){switch(e){case`PAY_PER_EVENT`:return`you pay per event`;case`PRICE_PER_DATASET_ITEM`:return`you pay per dataset item`;case`FLAT_PRICE_PER_MONTH`:return`your monthly subscription covers it`;default:return`it's free for you`}}function getServerInterfaceHint(e,t){if(e.actorStandby?.isEnabled)return`${t} also has a server interface. To send it HTTP requests instead of starting a run, use "apify server request ${t} <path>".`}async function resolveServerActor(e,t){let n=await resolveActorContext({providedActorNameOrId:t,client:e});if(!n.valid)throw Error(t?`${n.reason}.`:`No Actor specified and the current directory is not an Actor project. Pass an Actor ID or "username/name".`);let r=await e.actor(n.id).get();if(!r)throw Error(`Actor "${n.userFriendlyId}" was not found.`);if(!r.actorStandby?.isEnabled||!r.standbyUrl)throw Error(`Actor "${n.userFriendlyId}" has no server interface. Run it with "apify call ${n.userFriendlyId}" instead.`);return{id:r.id,userFriendlyId:n.userFriendlyId,ownerUsername:r.username,standbyUrl:r.standbyUrl,tenancy:r.actorStandby.tenancy,pricingModel:getEffectivePricingModel(r.pricingInfos),buildRef:r.actorStandby.build,taggedBuilds:r.taggedBuilds,standby:r.actorStandby}}function shortenSummary(e,t=100){let n=e.split(`
|
|
94
94
|
`)[0].trim();if(n.length<=t)return n;let r=n.slice(0,t-1),i=r.lastIndexOf(` `);return`${(i>t/2?r.slice(0,i):r).trimEnd()}…`}async function resolveServerBuild(e,t){let n=t.buildRef;if(!n)throw Error(`Actor "${t.userFriendlyId}" has no build set for its server interface.`);let r;if(Qr.test(n)){let{items:i}=await e.actor(t.id).builds().list({desc:!0,limit:1e3});r=i.find(e=>e.buildNumber===n)?.id}else r=t.taggedBuilds?.[n]?.buildId;let i=r?await e.build(r).get():void 0;if(!i)throw Error(`The server interface of Actor "${t.userFriendlyId}" uses build "${n}", which was not found.`);return i}function getServerDefinition(e){let t=e.actorDefinition;return{webServerSchema:t?.webServerSchema,webServerMcpPath:t?.webServerMcpPath}}function listServerOperations(e){if(!e||typeof e!=`object`)return[];let{paths:t}=e;if(!t||typeof t!=`object`)return[];let n=[];for(let[e,r]of Object.entries(t))if(r&&typeof r==`object`)for(let[t,i]of Object.entries(r)){if(!$r.has(t.toLowerCase()))continue;let r=i?.summary;n.push({method:t.toUpperCase(),path:e,summary:typeof r==`string`?r:void 0})}return n}function resolveServerRequestUrl(e,t,n=``){if(!t.startsWith(`/`))throw Error(`The path must start with "/", got "${t}". Pass a path, not a full URL.`);let r=new URL(e),i=new URL(t,r);if(i.origin!==r.origin||i.username||i.password)throw Error(`The path "${t}" points outside ${r.origin}. Pass a path on the Actor's server.`);if(n)for(let[e,t]of new URLSearchParams(n))i.searchParams.append(e,t);if(i.searchParams.has(`token`))throw Error(`Do not put the API token in the URL. The CLI sends it in the Authorization header.`);return i}function parseServerRequestArgs(e){let t=e.filter(e=>e!==void 0&&e!==``),n;t.length>0&&Yr.includes(t[0].toUpperCase())&&(n=t.shift().toUpperCase());let r;t.length>0&&!t[0].startsWith(`/`)&&(r=t.shift());let i=t.shift()??`/`;if(t.length>0)throw Error(`Unexpected argument "${t[0]}". Usage: apify server request [METHOD] [target] [path]`);return{method:n,target:r,path:i}}function describeServerError(e,t){let n;try{let e=JSON.parse(t)?.error?.type;n=typeof e==`string`?e:void 0}catch{}let r=n!==void 0;switch(n){case`failed-to-choose-actor-run`:return`The platform could not start or find a run of this Actor within 2 minutes. Check the Actor runs for failures, then retry.`;case`too-many-concurrent-requests`:return`Too many requests to this Actor are waiting for a run. Send fewer requests at once.`;case`rate-limit-exceeded`:return`Your account sent too many requests to Server Actors. Wait, then retry.`}if(e===504&&(r||!t.trim()))return`The Actor did not respond within 5 minutes.`}async function watchLocalServerReadiness(e,t){let n=`http://127.0.0.1:${e}/`,r=Date.now(),i=!1;for(;!t.aborted;){try{await fetch(n,{headers:{[Zr]:`1`},signal:AbortSignal.any([t,AbortSignal.timeout(2e3)])}),success({message:`The Actor server is ready at http://localhost:${e}`});return}catch{}!i&&Date.now()-r>3e4&&(i=!0,warning({message:`No response from http://localhost:${e} after 30 seconds. On the platform, a run receives requests only after it answers GET / with the "${Zr}" header.`}));try{await Oe(500,void 0,{signal:t})}catch{return}}}var ei=class ActorsCallCommand extends ApifyCommand{static name=`call`;static enableProfileFlag=!0;static description=`Executes Actor remotely using your authenticated account.
|
|
@@ -99,7 +99,7 @@ To inspect the input schema before creating a JSON input, use "apify actors info
|
|
|
99
99
|
`));break}case`FREE`:l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);break;default:{let n=e.pricingModel;l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Unknown pricing model (${t.yellow(n)})`)}`)}}}else l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);(c.seoTitle||c.seoDescription)&&(l.push(``,t.yellow(`SEO information:`)),c.seoTitle&&l.push(` ${t.yellow(`Title:`)} ${c.seoTitle}`),c.seoDescription&&l.push(` ${t.yellow(`Description:`)} ${c.seoDescription}`));let{stats:f}=c;if(l.push(``,t.yellow(`Actor stats:`),` ${t.yellow(`Total users:`)} ${t.cyan(`${f.totalUsers}`)}`,` ${t.yellow(`Users (30d):`)} ${t.cyan(`${f.totalUsers30Days}`)}`,` ${t.yellow(`Total runs:`)} ${t.cyan(`${f.totalRuns}`)}`),c.taggedBuilds){l.push(``,t.yellow(`Builds:`));let e=c.taggedBuilds.latest;e&&l.push(` ${t.yellow(`-`)} ${t.cyan(e.buildNumber)} ${t.gray(`/`)} ${t.yellow(`latest`)}`);for(let[e,n]of Object.entries(c.taggedBuilds))e!==`latest`&&l.push(` ${t.yellow(`-`)} ${t.cyan(n.buildNumber)} ${t.gray(`/`)} ${t.yellow(e)}`)}simpleLog({message:l.join(`
|
|
100
100
|
`),stdout:!0})}};function prettyPrintStatus(e){switch(e){case`READY`:return t.green(`Ready`);case`RUNNING`:return t.blue(`Running`);case`SUCCEEDED`:return t.green(`Succeeded`);case`FAILED`:return t.red(`Failed`);case`ABORTING`:return t.yellow(`Aborting`);case`ABORTED`:return t.red(`Aborted`);case`TIMING-OUT`:return t.yellow(`Timing Out`);case`TIMED-OUT`:return t.red(`Timed Out`);default:return t.gray(e.split(`-`).map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(` `))}}const li={"TIMED-OUT":t.gray(`after`),"TIMING-OUT":t.gray(`after`),ABORTED:t.gray(`after`),ABORTING:t.gray(`after`),FAILED:t.gray(`after`),READY:t.gray(`for`),RUNNING:t.gray(`for`),SUCCEEDED:t.gray(`after`)},ui=new $({allColumns:[`Name`,`Runs`,`Last run started at`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run status`,`Last run duration`],columnAlignments:{Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},hiddenColumns:[`_Small_LastRunText`],breakpointOverrides:{small:{"Last run status":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}}),di=new $({allColumns:[`Name`,`Modified at`,`Builds`,`Default build`,`Runs`,`Last run`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run`,`Last run duration`],hiddenColumns:[`_Small_LastRunText`],columnAlignments:{Builds:`right`,Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},breakpointOverrides:{small:{"Last run":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}});var ActorsLsCommand=class extends ApifyCommand{static name=`ls`;static enableProfileFlag=!0;static description=`Prints a list of recently executed Actors or Actors you own.`;static examples=[{description:`List Actors you recently interacted with.`,command:`apify actors ls`},{description:`List Actors you own, newest first.`,command:`apify actors ls --my --desc`},{description:`List the next page of 50 Actors.`,command:`apify actors ls --limit 50 --offset 50`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-ls`;static flags={my:X.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:X.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:X.integer({description:`Number of Actors that will be listed.`,default:20}),desc:X.boolean({description:`Sort Actors in descending order.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,my:i,json:a}=this.flags,s=await getLoggedClientOrThrow(),c=await s.actors().list({limit:n,offset:r,desc:e,my:i});if(c.count===0){if(a){printJsonToStdout(c);return}info({message:i?`You don't have any Actors yet!`:`There are no recent Actors used by you.`,stdout:!0});return}let l={...c,items:await Promise.all(c.items.map(async e=>{let t=await s.actor(e.id).get(),n=await s.actor(e.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...e,actor:t??null,lastRun:n.items[0]??null}}))};if(l.items=i?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),a){printJsonToStdout(l);return}let u=i?di:ui,f=l.items.reduce((e,t)=>{let n=`${t.username}/${t.name}`;return n.length>e?n.length:e},0)+2+6;for(let e of l.items){let n=e.stats.lastRunStartedAt?yr.display(e.stats.lastRunStartedAt):``,r=e.lastRun?(()=>{if(e.lastRun.finishedAt)return Sr.format(e.lastRun.finishedAt.getTime()-e.lastRun.startedAt.getTime());let t=Date.now()-e.lastRun.startedAt.getTime();return`${Sr.format(t)}…`})():``,i=e.actor?(()=>{let n=Object.entries(e.actor.taggedBuilds??{}).find(([t,n])=>n.buildNumber===e.actor.defaultRunOptions.build||t===e.actor.defaultRunOptions.build);return n?`${t.yellow(n[0])} / ${t.cyan(n[1].buildNumber??e.actor.defaultRunOptions.build)}`:t.gray(`Unknown`)})():t.gray(`Unknown`),a=(()=>{if(e.lastRun){let n=[prettyPrintStatus(e.lastRun.status)];if(r&&n.push(li[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<$e.Week?n.push(`
|
|
101
101
|
`,t.gray(`${Sr.format(r)} ago`)):n.push(`
|
|
102
|
-
`,t.gray(`On`,br.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:$.isSmallTerminal()&&f>=56?oi:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":yr.display(e.modifiedAt),Builds:e.actor?.stats?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":$.isSmallTerminal()?oi:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const fi=String.raw`[\w.~][\w.~-]*`,pi=String.raw`[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?`,mi=String.raw`[\w.][\w.-]*`,hi=new RegExp(String.raw`^https://(?:${mi}(?::[\w.~-]+)?@)?${pi}(?::\d+)?(?:/${fi})+$`),gi=new RegExp(String.raw`^ssh://(?:${mi}@)?${pi}(?::\d+)?(?:/${fi})+$`),_i=new RegExp(String.raw`^${mi}@${pi}:/?${fi}(?:/${fi})*$`),vi=/[\s\u0000-\u001F\u007F#:]/,hasUnsafeSegment=e=>e.split(`/`).some(e=>e.startsWith(`-`)||e===`..`),isSafeRef=e=>!vi.test(e)&&!hasUnsafeSegment(e);function parseGitRepoUrl(e){let t=e.indexOf(`#`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t+1),i=r.indexOf(`:`),a=i===-1?r:r.slice(0,i),s=i===-1?``:r.slice(i+1);if(![hi,gi,_i].some(e=>e.test(n))||hasUnsafeSegment(n))throw Error(`Can't pull Actor from Git URL '${e}'. Only https and ssh repository URLs are supported.`);if(!isSafeRef(a)||!isSafeRef(s))throw Error(`Can't pull Actor from Git URL '${e}'. The branch or directory in the URL isn't valid.`);return{url:n,...a&&{branch:a},...s&&{subdir:s}}}async function withAllowedGitProtocols(t){let n=e.env.GIT_ALLOW_PROTOCOL;e.env.GIT_ALLOW_PROTOCOL=`https:ssh`;try{return await t()}finally{n===void 0?delete e.env.GIT_ALLOW_PROTOCOL:e.env.GIT_ALLOW_PROTOCOL=n}}const extractGitHubZip=async(e,t)=>{let n=await downloadZip(e);n.extractEntryTo(n.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{static name=`pull`;static enableProfileFlag=!0;static description=`Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.`;static group=`Local Actor Development`;static examples=[{description:`Pull the Actor linked to the current directory from the Apify platform.`,command:`apify pull`},{description:`Pull a specific Actor by its full name into a target directory.`,command:`apify pull apify/hello-world --dir ./hello-world`},{description:`Pull a specific version of an Actor.`,command:`apify pull apify/hello-world --version 1.2`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-pull`;static flags={version:X.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:X.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Q.string({required:!1,description:`Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.`})};async run(){let t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLoggedClientOrThrow(),a=await getCurrentUserInfo(),s=!this.args.actorId,c=a.username||a.id,l=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!l)throw Error(`Cannot find Actor in this directory.`);let u;try{u=await i.actor(l).get()}catch{throw Error(`Cannot find Actor with ID/name '${l}' in your account.`)}if(!u)throw Error(`Cannot find Actor with ID/name '${l}' in your account.`);let{name:f,versions:p}=u,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!u.versions.length)throw Error(`Actor ${l} has no versions.`);let m=null;if(this.flags.version&&(m=p.find(e=>e.versionNumber===this.flags.version),!m))throw Error(`Cannot find version ${this.flags.version} of Actor ${l}.`);m||=p.reduce((e,t)=>ze(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let h=s?t:B(t,this.flags.dir??f);if(g(h,{recursive:!0}),!s&&y(h).length!==0){error({message:`Directory ${h} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=m;switch(_){case`TARBALL`:m.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(m.tarballUrl,h);break;case`SOURCE_FILES`:{m.sourceFiles||throwMissingSourceCodeAccessError();let e=H(h),{sourceFiles:t}=m,n=t.map(t=>{let n=H(e,t.name),r=V(e,n);if(!r||r===`..`||r.startsWith(`..${ge}`)||me(r))throw Error(`Cannot pull Actor: source file "${t.name}" would be written outside the target directory.`);return{file:t,target:n}});for(let{file:t,target:r}of n)if(g(z(r),{recursive:!0}),!t.folder){let n=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(r===B(e,q)){let e=Mt.parse(n);e.name=u.name,E(r,Mt.update(n,e))}else E(r,n)}break}case`GIT_REPO`:{m.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=m;parseGitRepoUrl(e);try{await withAllowedGitProtocols(async()=>jt(`git:${e}`,{dir:h}))}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:m.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${m.gitHubGistUrl}/archive/master.zip`,h);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${f} updated at ${h}/`:`Pulled to ${h}/`})}};function resolveDockerContext(e,t){if(t==null||t===``)return{kind:`none`};if(typeof t!=`string`)return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json must be a string.`};if(me(t))return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json is absolute (${t}); the path is relative to .actor/.`};if(t.includes(`\\`))return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json uses a backslash (${t}); the platform resolves paths with forward slashes.`};let n;try{n=realPath(e)}catch{return{kind:`invalid`,message:`The Actor folder ${e} does not exist.`}}let r=H(n,rn,t),i=w(r,{throwIfNoEntry:!1});if(!i)return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${r}, which does not exist.`};if(!i.isDirectory())return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${r}, which is not a directory.`};let a=realPath(r),s=V(n,r);if(s===``||!isOutside(s))return{kind:`within`,contextRoot:r};let c=git(n,[`rev-parse`,`--show-toplevel`]),l=a;if(c&&(l=realPath(c),isOutside(V(l,a))))return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${a}, outside the Git repository ${l}. The Apify platform builds from a clone of the repository, so it could not build this Actor.`};let u=V(l,n);return isOutside(u)?{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${a}, which does not contain the Actor's folder.`}:u===``?{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json leaves the Actor folder, then leads back into it at ${a}, through a symlink or a folder name in another letter case. Write the path without leaving the Actor folder.`}:{kind:`outside`,contextRoot:r,sourceRoot:l,actorPath:toPosix(u)}}function realPath(e){try{return x.native(e)}catch{return x(e)}}function isOutside(e){return me(e)||e===`..`||e.startsWith(`..${ge}`)}function toPosix(e){return e.split(ge).join(`/`)}function git(e,t){try{return qe(`git`,t,{cwd:e,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],maxBuffer:1/0}).replace(/\r?\n$/,``)}catch{return}}function withoutCredentials(e){try{let t=new URL(e);return t.username=``,t.password=``,t.toString()}catch{return e}}function readGitState(e){let t=git(e,[`rev-parse`,`HEAD`]),n=git(e,[`status`,`--porcelain`,`--`,`.`]);if(!t)return n?{dirty:!0}:{};let r={commit:t},i=git(e,[`rev-parse`,`--abbrev-ref`,`HEAD`]);i&&i!==`HEAD`&&(r.branch=i);let a=git(e,[`remote`,`get-url`,`origin`]);return a&&(r.remoteUrl=withoutCredentials(a)),n!==void 0&&(r.dirty=n.length>0),r}const yi=/* @__PURE__ */ new Set([`storage`,`apify_storage`,`crawlee_storage`]),bi=/* @__PURE__ */ new Set([`datasets`,`key_value_stores`,`request_queues`]);function isDependencyOrRunState(e){let t=e.split(`/`);return t.some((e,n)=>e===`node_modules`||yi.has(e)&&bi.has(t[n+1])&&n+3<t.length)}function gitFileList(e,t){let n=git(e,[`ls-files`,`-z`,...t]);return n===void 0?void 0:[...new Set(n.split(`\0`).filter(Boolean))]}async function getContextFilePaths(e){let t=gitFileList(e,[`--cached`]),n=gitFileList(e,[`--others`,`--exclude-standard`]);if(!t||!n)return(await getActorLocalFilePaths(e)).filter(e=>!isDependencyOrRunState(e));let isPushable=t=>{try{let n=h(B(e,t));return n.isSymbolicLink()||n.isFile()}catch{return!1}};return[...t.filter(isPushable),...n.filter(e=>isPushable(e)&&!isDependencyOrRunState(e))]}const xi=[`dockerfile`,`readme`,`changelog`],Si=[{field:`input`,alias:`inputSchema`},{field:`output`,alias:`outputSchema`},{field:`webServerSchema`}],Ci=[`keyValueStore`,`dataset`],wi=/* @__PURE__ */ new Set([`readme`,`changelog`]),Ti=[`./Dockerfile`,`../Dockerfile`];function isRecord(e){return typeof e==`object`&&!!e}function collectPathFields(e){let t=[],add=(e,n,r=!1)=>{typeof n==`string`&&n!==``&&t.push({field:e,value:n,caseInsensitive:r})};for(let t of xi)add(t,e[t],!0);for(let{field:t,alias:n}of Si)n&&e[n]?add(n,e[n]):add(t,e[t]);if(isRecord(e.storages)){for(let t of Ci)add(`storages.${t}`,e.storages[t]);if(isRecord(e.storages.datasets))for(let[t,n]of Object.entries(e.storages.datasets))add(`storages.datasets.${t}`,n)}return t}function listDirectory(e){try{return y(e)}catch{return[]}}function findEntry(e){let t=pe(e),n=listDirectory(z(e));return{sameCase:n.find(e=>e===t),anyCase:n.find(e=>e.toLowerCase()===t.toLowerCase())}}function checkPathField({field:e,value:t,caseInsensitive:n},{actorDir:r,uploadRoot:i,uploadedFiles:a,dockerContextRoot:s}){let problem=(n,r,i=!1)=>({field:e,value:t,resolvedPath:n,reason:r,severity:i&&wi.has(e)?`warning`:`error`}),absolute=()=>problem(t,`is absolute; the path is relative to ${rn}/`),c=H(r,rn,t),outside=()=>problem(c,`lies outside the uploaded folder ${i}`);if(t.startsWith(`/`))return absolute();let l=he.join(toPosix(V(i,r)),rn,t);if(l===`..`||l.startsWith(`../`))return outside();if(t.includes(`\\`))return problem(t,`uses a backslash; the platform resolves paths with forward slashes`,!0);if(me(t))return absolute();if(isOutside(V(i,c)))return outside();let{sameCase:u,anyCase:f}=findEntry(c),p=u??(n?f:void 0);if(!p)return problem(c,f?`does not exist (the name must match ${f} exactly)`:`does not exist`,!0);let m=B(z(c),p),h;try{h=w(m)}catch{return problem(c,`does not exist`,!0)}if(h.isDirectory())return problem(c,`is a directory, not a file`);if(s&&e===`dockerfile`&&isOutside(V(s,m)))return problem(c,`lies outside the Docker context ${s}`);let g=toPosix(V(i,m));if(!a.has(g)){let e=[...a].find(e=>e.toLowerCase()===g.toLowerCase());return problem(c,e?`does not match the case of the uploaded file ${e}`:`is not among the files apify push uploads (excluded by .gitignore or .actorignore?)`,!0)}}function isUploaded(e,{uploadRoot:t,uploadedFiles:n}){let r=toPosix(V(t,e));return n.has(r)||[...n].some(e=>e.startsWith(`${r}/`))}function checkDefaultDockerfile(e){let{actorDir:t,dockerContextRoot:n}=e,r=Ti.find(n=>{let r=H(t,rn,n),{sameCase:i,anyCase:a}=findEntry(r),s=i??a;return s!==void 0&&isUploaded(B(z(r),s),e)});if(r){let t=checkPathField({field:`dockerfile`,value:r,caseInsensitive:!0},e);return t&&{...t,value:``,reason:`is not set, so the platform would use the default ${t.resolvedPath}, which ${t.reason}`}}if(V(t,n)!==``)return{field:`dockerfile`,value:``,resolvedPath:B(n,`Dockerfile`),reason:`is not set and push uploads no ${rn}/Dockerfile or Dockerfile in the Actor folder, so the platform would build the Docker context ${n} with its built-in Node.js Dockerfile; add a Dockerfile, or set "dockerfile" to one inside the Docker context`,severity:`error`}}function checkActorPaths(e){let t={actorDir:realPath(e.actorDir),uploadRoot:realPath(e.uploadRoot),uploadedFiles:new Set(e.uploadedFiles.map(toPosix)),dockerContextRoot:e.dockerContextRoot},n=collectPathFields(e.config),r=n.flatMap(e=>checkPathField(e,t)??[]),{dockerContextRoot:i}=t;if(i&&!n.some(({field:e})=>e===`dockerfile`)){let e=checkDefaultDockerfile({...t,dockerContextRoot:i});e&&r.push(e)}return r}const Ei={error:`.actor/actor.json refers to files the Apify platform could not use:`,warning:`.actor/actor.json refers to files the Apify platform will not find. The push continues, and the platform falls back to its default README or CHANGELOG:`};function formatActorPathProblems(e,t){let n=e.filter(e=>e.severity===t);return n.length===0?``:[Ei[t],...n.map(({field:e,value:t,resolvedPath:n,reason:r})=>t?` "${e}": "${t}" (${n}) ${r}.`:` "${e}" ${r}.`),`Paths are relative to ${rn}/ and must point to files inside the uploaded folder.`].join(`
|
|
102
|
+
`,t.gray(`On`,br.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:$.isSmallTerminal()&&f>=56?oi:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":yr.display(e.modifiedAt),Builds:e.actor?.stats?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":$.isSmallTerminal()?oi:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const isGitMetadataSegment=e=>{let t=e.replace(/\p{Default_Ignorable_Code_Point}/gu,``).toLowerCase().replace(/:.*$/,``).replace(/[. ]+$/,``);return t===`.git`||t===`git~1`},hasGitMetadataSegment=e=>e.split(/[\\/]/).some(isGitMetadataSegment),fi=String.raw`[\w.~][\w.~-]*`,pi=String.raw`[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?`,mi=String.raw`[\w.][\w.-]*`,hi=new RegExp(String.raw`^https://(?:${mi}(?::[\w.~-]+)?@)?${pi}(?::\d+)?(?:/${fi})+$`),gi=new RegExp(String.raw`^ssh://(?:${mi}@)?${pi}(?::\d+)?(?:/${fi})+$`),_i=new RegExp(String.raw`^${mi}@${pi}:/?${fi}(?:/${fi})*$`),vi=/[\s\u0000-\u001F\u007F#:]/,hasUnsafeSegment=e=>e.split(`/`).some(e=>e.startsWith(`-`)||e===`..`),isSafeRef=e=>!vi.test(e)&&!hasUnsafeSegment(e);function parseGitRepoUrl(e){let t=e.indexOf(`#`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t+1),i=r.indexOf(`:`),a=i===-1?r:r.slice(0,i),s=i===-1?``:r.slice(i+1);if(![hi,gi,_i].some(e=>e.test(n))||hasUnsafeSegment(n))throw Error(`Can't pull Actor from Git URL '${e}'. Only https and ssh repository URLs are supported.`);if(!isSafeRef(a)||!isSafeRef(s))throw Error(`Can't pull Actor from Git URL '${e}'. The branch or directory in the URL isn't valid.`);return{url:n,...a&&{branch:a},...s&&{subdir:s}}}async function withAllowedGitProtocols(t){let n=e.env.GIT_ALLOW_PROTOCOL;e.env.GIT_ALLOW_PROTOCOL=`https:ssh`;try{return await t()}finally{n===void 0?delete e.env.GIT_ALLOW_PROTOCOL:e.env.GIT_ALLOW_PROTOCOL=n}}const extractGitHubZip=async(e,t)=>{let n=await downloadZip(e),r=n.getEntries(),i=r.find(e=>hasGitMetadataSegment(e.entryName));if(i)throw Error(`Cannot pull Actor: archive entry "${i.entryName}" would be written to Git metadata in the target directory.`);n.extractEntryTo(r[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{static name=`pull`;static enableProfileFlag=!0;static description=`Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.`;static group=`Local Actor Development`;static examples=[{description:`Pull the Actor linked to the current directory from the Apify platform.`,command:`apify pull`},{description:`Pull a specific Actor by its full name into a target directory.`,command:`apify pull apify/hello-world --dir ./hello-world`},{description:`Pull a specific version of an Actor.`,command:`apify pull apify/hello-world --version 1.2`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-pull`;static flags={version:X.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:X.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Q.string({required:!1,description:`Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.`})};async run(){let t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLoggedClientOrThrow(),a=await getCurrentUserInfo(),s=!this.args.actorId,c=a.username||a.id,l=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!l)throw Error(`Cannot find Actor in this directory.`);let u;try{u=await i.actor(l).get()}catch{throw Error(`Cannot find Actor with ID/name '${l}' in your account.`)}if(!u)throw Error(`Cannot find Actor with ID/name '${l}' in your account.`);let{name:f,versions:p}=u,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!u.versions.length)throw Error(`Actor ${l} has no versions.`);let m=null;if(this.flags.version&&(m=p.find(e=>e.versionNumber===this.flags.version),!m))throw Error(`Cannot find version ${this.flags.version} of Actor ${l}.`);m||=p.reduce((e,t)=>ze(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let h=s?t:B(t,this.flags.dir??f);if(g(h,{recursive:!0}),!s&&y(h).length!==0){error({message:`Directory ${h} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=m;switch(_){case`TARBALL`:m.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(m.tarballUrl,h);break;case`SOURCE_FILES`:{m.sourceFiles||throwMissingSourceCodeAccessError();let e=H(h),{sourceFiles:t}=m,n=t.map(t=>{let n=H(e,t.name),r=V(e,n);if(!r||r===`..`||r.startsWith(`..${ge}`)||me(r))throw Error(`Cannot pull Actor: source file "${t.name}" would be written outside the target directory.`);if(hasGitMetadataSegment(r))throw Error(`Cannot pull Actor: source file "${t.name}" would be written to Git metadata in the target directory.`);return{file:t,target:n}});for(let{file:t,target:r}of n)if(g(z(r),{recursive:!0}),!t.folder){let n=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(r===B(e,q)){let e=Mt.parse(n);e.name=u.name,E(r,Mt.update(n,e))}else E(r,n)}break}case`GIT_REPO`:{m.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=m;parseGitRepoUrl(e);try{await withAllowedGitProtocols(async()=>jt(`git:${e}`,{dir:h}))}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:m.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${m.gitHubGistUrl}/archive/master.zip`,h);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${f} updated at ${h}/`:`Pulled to ${h}/`})}};function resolveDockerContext(e,t){if(t==null||t===``)return{kind:`none`};if(typeof t!=`string`)return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json must be a string.`};if(me(t))return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json is absolute (${t}); the path is relative to .actor/.`};if(t.includes(`\\`))return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json uses a backslash (${t}); the platform resolves paths with forward slashes.`};let n;try{n=realPath(e)}catch{return{kind:`invalid`,message:`The Actor folder ${e} does not exist.`}}let r=H(n,rn,t),i=w(r,{throwIfNoEntry:!1});if(!i)return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${r}, which does not exist.`};if(!i.isDirectory())return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${r}, which is not a directory.`};let a=realPath(r),s=V(n,r);if(s===``||!isOutside(s))return{kind:`within`,contextRoot:r};let c=git(n,[`rev-parse`,`--show-toplevel`]),l=a;if(c&&(l=realPath(c),isOutside(V(l,a))))return{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${a}, outside the Git repository ${l}. The Apify platform builds from a clone of the repository, so it could not build this Actor.`};let u=V(l,n);return isOutside(u)?{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json points to ${a}, which does not contain the Actor's folder.`}:u===``?{kind:`invalid`,message:`"dockerContextDir" in .actor/actor.json leaves the Actor folder, then leads back into it at ${a}, through a symlink or a folder name in another letter case. Write the path without leaving the Actor folder.`}:{kind:`outside`,contextRoot:r,sourceRoot:l,actorPath:toPosix(u)}}function realPath(e){try{return x.native(e)}catch{return x(e)}}function isOutside(e){return me(e)||e===`..`||e.startsWith(`..${ge}`)}function toPosix(e){return e.split(ge).join(`/`)}function git(e,t){try{return qe(`git`,t,{cwd:e,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],maxBuffer:1/0}).replace(/\r?\n$/,``)}catch{return}}function withoutCredentials(e){try{let t=new URL(e);return t.username=``,t.password=``,t.toString()}catch{return e}}function readGitState(e){let t=git(e,[`rev-parse`,`HEAD`]),n=git(e,[`status`,`--porcelain`,`--`,`.`]);if(!t)return n?{dirty:!0}:{};let r={commit:t},i=git(e,[`rev-parse`,`--abbrev-ref`,`HEAD`]);i&&i!==`HEAD`&&(r.branch=i);let a=git(e,[`remote`,`get-url`,`origin`]);return a&&(r.remoteUrl=withoutCredentials(a)),n!==void 0&&(r.dirty=n.length>0),r}const yi=/* @__PURE__ */ new Set([`storage`,`apify_storage`,`crawlee_storage`]),bi=/* @__PURE__ */ new Set([`datasets`,`key_value_stores`,`request_queues`]);function isDependencyOrRunState(e){let t=e.split(`/`);return t.some((e,n)=>e===`node_modules`||yi.has(e)&&bi.has(t[n+1])&&n+3<t.length)}function gitFileList(e,t){let n=git(e,[`ls-files`,`-z`,...t]);return n===void 0?void 0:[...new Set(n.split(`\0`).filter(Boolean))]}async function getContextFilePaths(e){let t=gitFileList(e,[`--cached`]),n=gitFileList(e,[`--others`,`--exclude-standard`]);if(!t||!n)return(await getActorLocalFilePaths(e)).filter(e=>!isDependencyOrRunState(e));let isPushable=t=>{try{let n=h(B(e,t));return n.isSymbolicLink()||n.isFile()}catch{return!1}};return[...t.filter(isPushable),...n.filter(e=>isPushable(e)&&!isDependencyOrRunState(e))]}const xi=[`dockerfile`,`readme`,`changelog`],Si=[{field:`input`,alias:`inputSchema`},{field:`output`,alias:`outputSchema`},{field:`webServerSchema`}],Ci=[`keyValueStore`,`dataset`],wi=/* @__PURE__ */ new Set([`readme`,`changelog`]),Ti=[`./Dockerfile`,`../Dockerfile`];function isRecord(e){return typeof e==`object`&&!!e}function collectPathFields(e){let t=[],add=(e,n,r=!1)=>{typeof n==`string`&&n!==``&&t.push({field:e,value:n,caseInsensitive:r})};for(let t of xi)add(t,e[t],!0);for(let{field:t,alias:n}of Si)n&&e[n]?add(n,e[n]):add(t,e[t]);if(isRecord(e.storages)){for(let t of Ci)add(`storages.${t}`,e.storages[t]);if(isRecord(e.storages.datasets))for(let[t,n]of Object.entries(e.storages.datasets))add(`storages.datasets.${t}`,n)}return t}function listDirectory(e){try{return y(e)}catch{return[]}}function findEntry(e){let t=pe(e),n=listDirectory(z(e));return{sameCase:n.find(e=>e===t),anyCase:n.find(e=>e.toLowerCase()===t.toLowerCase())}}function checkPathField({field:e,value:t,caseInsensitive:n},{actorDir:r,uploadRoot:i,uploadedFiles:a,dockerContextRoot:s}){let problem=(n,r,i=!1)=>({field:e,value:t,resolvedPath:n,reason:r,severity:i&&wi.has(e)?`warning`:`error`}),absolute=()=>problem(t,`is absolute; the path is relative to ${rn}/`),c=H(r,rn,t),outside=()=>problem(c,`lies outside the uploaded folder ${i}`);if(t.startsWith(`/`))return absolute();let l=he.join(toPosix(V(i,r)),rn,t);if(l===`..`||l.startsWith(`../`))return outside();if(t.includes(`\\`))return problem(t,`uses a backslash; the platform resolves paths with forward slashes`,!0);if(me(t))return absolute();if(isOutside(V(i,c)))return outside();let{sameCase:u,anyCase:f}=findEntry(c),p=u??(n?f:void 0);if(!p)return problem(c,f?`does not exist (the name must match ${f} exactly)`:`does not exist`,!0);let m=B(z(c),p),h;try{h=w(m)}catch{return problem(c,`does not exist`,!0)}if(h.isDirectory())return problem(c,`is a directory, not a file`);if(s&&e===`dockerfile`&&isOutside(V(s,m)))return problem(c,`lies outside the Docker context ${s}`);let g=toPosix(V(i,m));if(!a.has(g)){let e=[...a].find(e=>e.toLowerCase()===g.toLowerCase());return problem(c,e?`does not match the case of the uploaded file ${e}`:`is not among the files apify push uploads (excluded by .gitignore or .actorignore?)`,!0)}}function isUploaded(e,{uploadRoot:t,uploadedFiles:n}){let r=toPosix(V(t,e));return n.has(r)||[...n].some(e=>e.startsWith(`${r}/`))}function checkDefaultDockerfile(e){let{actorDir:t,dockerContextRoot:n}=e,r=Ti.find(n=>{let r=H(t,rn,n),{sameCase:i,anyCase:a}=findEntry(r),s=i??a;return s!==void 0&&isUploaded(B(z(r),s),e)});if(r){let t=checkPathField({field:`dockerfile`,value:r,caseInsensitive:!0},e);return t&&{...t,value:``,reason:`is not set, so the platform would use the default ${t.resolvedPath}, which ${t.reason}`}}if(V(t,n)!==``)return{field:`dockerfile`,value:``,resolvedPath:B(n,`Dockerfile`),reason:`is not set and push uploads no ${rn}/Dockerfile or Dockerfile in the Actor folder, so the platform would build the Docker context ${n} with its built-in Node.js Dockerfile; add a Dockerfile, or set "dockerfile" to one inside the Docker context`,severity:`error`}}function checkActorPaths(e){let t={actorDir:realPath(e.actorDir),uploadRoot:realPath(e.uploadRoot),uploadedFiles:new Set(e.uploadedFiles.map(toPosix)),dockerContextRoot:e.dockerContextRoot},n=collectPathFields(e.config),r=n.flatMap(e=>checkPathField(e,t)??[]),{dockerContextRoot:i}=t;if(i&&!n.some(({field:e})=>e===`dockerfile`)){let e=checkDefaultDockerfile({...t,dockerContextRoot:i});e&&r.push(e)}return r}const Ei={error:`.actor/actor.json refers to files the Apify platform could not use:`,warning:`.actor/actor.json refers to files the Apify platform will not find. The push continues, and the platform falls back to its default README or CHANGELOG:`};function formatActorPathProblems(e,t){let n=e.filter(e=>e.severity===t);return n.length===0?``:[Ei[t],...n.map(({field:e,value:t,resolvedPath:n,reason:r})=>t?` "${e}": "${t}" (${n}) ${r}.`:` "${e}" ${r}.`),`Paths are relative to ${rn}/ and must point to files inside the uploaded folder.`].join(`
|
|
103
103
|
`)}const Di=new Set(vr.map(e=>e.replace(/^\*\*\//,``)));function toPosixRelative(e,t){return V(e,t).split(ge).join(`/`)}function readActorName(e){try{let t=getJsonFileContent(B(e,q))?.name;return typeof t==`string`?t:void 0}catch{return}}async function findActorDirs(e){let t=[],walk=async n=>{let r;try{r=await Ce(n,{withFileTypes:!0})}catch(e){cliDebugPrint(`findActorDirs`,{event:`unreadable-directory`,dir:n,err:e});return}for(let i of r){if(!i.isDirectory()||Di.has(i.name))continue;let r=B(n,i.name);p(B(r,q))?t.push({dir:toPosixRelative(e,r),name:readActorName(r)}):await walk(r)}};if(await walk(e),!t.length)return[];let n=await getGitignoreMatcher(e,t.map(e=>`${e.dir}/`));return t.map(e=>({...e,ignored:n(`${e.dir}/`)})).sort((e,t)=>e.dir<t.dir?-1:+(e.dir>t.dir))}const Oi=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r})=>await Bt({message:e,choices:t,pageSize:n,loop:r},Tr),{errorMessageForStdin:`Please provide the selection using the command options.`});async function createContextTarball(e,t){let n=new it({gzip:!0,gzipOptions:{level:6}}),r=[];n.on(`data`,e=>r.push(e));let i=new Promise((e,t)=>{n.once(`end`,e),n.once(`error`,t)});for(let r of e){let e=r.split(ge).join(`/`),i=B(t,r);h(i).isSymbolicLink()?n.symlink(e,b(i)):n.file(i,{name:e})}return await n.finalize(),await i,Buffer.concat(r)}async function pushActorRuntimeSourceContext(e,t,n,r){let i=new URL(`${e.baseUrl}/actor-runtime/source-context/${encodeURIComponent(t)}/${encodeURIComponent(n)}`);i.searchParams.set(`actorPath`,r.actorPath);let{git:a}=r;a?.remoteUrl&&i.searchParams.set(`gitRemoteUrl`,a.remoteUrl),a?.branch&&i.searchParams.set(`gitBranch`,a.branch),a?.commit&&i.searchParams.set(`gitCommit`,a.commit),a?.dirty!==void 0&&i.searchParams.set(`gitDirty`,String(a.dirty));let s=await fetch(i,{method:`PUT`,headers:{...sn,Authorization:`Bearer ${e.token}`,"Content-Type":`application/gzip`},body:new Uint8Array(r.tarball.buffer,r.tarball.byteOffset,r.tarball.byteLength)});if(s.ok)return{ok:!0};let c=await s.json().catch(()=>null),l=c?.error?.message??`${s.status} ${s.statusText}`;return{ok:!1,unsupported:s.status===404&&c?.error?.type!==`record-not-found`,error:l}}function monorepoOutdatedRuntimeMessage(e){return`${e} does not accept monorepo Actors. If it is a local Actor runtime, update it with 'apify runtime install'.`}const ki=5e4,getSecretsFile=()=>{try{return JSON.parse(v(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),E(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>ki)throw Error(`Secret value has to be string with maximum length ${ki}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>(/* @__PURE__ */ RegExp(`^@.{1}`)).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(/* @__PURE__ */ RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
|
|
104
104
|
`);if(n)for(let e of i)warning({message:`Value for ${e} not found in local secrets. Set it by calling "apify secrets add ${e} [SECRET_VALUE]"`});else throw Error(`The following secrets are missing:\n${e}\n\nSet them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
|
|
105
105
|
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},transformEnvToEnvVars=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r=[],i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(/* @__PURE__ */ RegExp(`^@`),``);t[a]?r.push({name:n,value:t[a],isSecret:!0}):i.push(a)}else r.push({name:n,value:e[n]})}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
|
|
@@ -289,4 +289,4 @@ When no path is provided, validates all schemas found in '${q}':
|
|
|
289
289
|
- Dataset schema (from "storages.dataset")
|
|
290
290
|
- Output schema (from "output")
|
|
291
291
|
- 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:Q.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${q}'.`})};static hiddenAliases=[`vis`];async run(){this.args.path?await this.validateInputSchemaAtPath(this.args.path):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 '${q}'`}`});let t=new mr({strict:!1});wt(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 '${q}'`}`}),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 '${q}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Ra=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,RuntimeIndexCommand,SecretsIndexCommand,ServerIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],za=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Ra as n,processVersionCheck as r,za as t};
|
|
292
|
-
//# sourceMappingURL=_register-
|
|
292
|
+
//# sourceMappingURL=_register-xsMdWOpb.js.map
|