diff --git a/dist/index.js b/dist/index.js index fa41c4e..dcc5a05 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,2 +1,2 @@ #!/usr/bin/env node -(()=>{"use strict";var e={522:function(e,t,s){var r=this&&this.__awaiter||function(e,t,s,r){function adopt(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||(s=Promise))(function(s,o){function fulfilled(e){try{step(r.next(e))}catch(e){o(e)}}function rejected(e){try{step(r["throw"](e))}catch(e){o(e)}}function step(e){e.done?s(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:true});const o=s(317);const n=s(916);const u=s(690);const a=s(53);const l="@devicecloud.dev/dcd";const executeCommand=(e,t=true)=>new Promise((s,r)=>{let n="";const u=(0,o.spawn)(e,{shell:true});u.stdout.on("data",e=>{const s=e.toString();n+=s;if(t){process.stderr.write(s)}});u.stderr.on("data",e=>{const s=e.toString();n+=s;if(t){process.stderr.write(s)}});u.on("close",e=>{s({output:n,exitCode:e!==null&&e!==void 0?e:0})});u.on("error",e=>{r(e)})});const getLatestDcdVersion=e=>r(void 0,void 0,void 0,function*(){try{if(e){console.error("Using beta version of DCD CLI");return`${l}@beta`}const{output:t}=yield executeCommand(`npm view ${l} version`,false);const s=t.trim();console.error(`Latest DCD version from npm: ${s}`);return`${l}@${s}`}catch(e){console.error("Failed to fetch latest DCD version, falling back to >=5.0.0:",e);return`${l}@>=5.0.0`}});const getTestStatus=(e,t,s,o)=>r(void 0,void 0,void 0,function*(){try{let r=`npx --yes "${s}" status --json --upload-id ${e} --api-key ${(0,u.escapeShellValue)(t)}`;if(o){r+=` --api-url ${(0,u.escapeShellValue)(o)}`}const{output:n}=yield executeCommand(r,false);const a=n.split("\n");const l=a.findIndex(e=>{const t=e.trim();return t.startsWith("{")||t.startsWith("[")});if(l===-1){throw new Error("No JSON found in status output")}const i=a.slice(l).join("\n");return JSON.parse(i)}catch(e){console.error("Failed to get test status:",e);return null}});const run=()=>r(void 0,void 0,void 0,function*(){var e;try{const t=(0,n.getEnv)();const r=yield getLatestDcdVersion(t.useBeta);const o=[`--apiKey ${(0,u.escapeShellValue)(t.apiKey)}`,"--quiet"];if(t.apiUrl){o.push(`--api-url ${(0,u.escapeShellValue)(t.apiUrl)}`)}if(t.buildUrl){o.push(`--app-url ${(0,u.escapeShellValue)(t.buildUrl)}`)}for(const e of t.metadata){o.push(`--metadata ${(0,u.escapeShellValue)(e)}`)}const l=process.argv.slice(2).map(u.escapeShellValue).join(" ");const i=`npx --yes "${r}" cloud ${o.join(" ")} ${l}`.trim();process.env.DCD_CI_PROVIDER="eas";try{process.env.DCD_CI_WRAPPER_VERSION=s(330).rE}catch(e){}let c="";let p=null;let d=0;try{const{output:e,exitCode:t}=yield executeCommand(i);c=e;d=t;if(t===1){throw new Error("DeviceCloud CLI failed to run - check your parameters or contact support")}}finally{p=((e=c===null||c===void 0?void 0:c.match(/https:\/\/(?:dev\.)?console\.devicecloud\.dev\/results\?upload=([a-zA-Z0-9-]+)/))===null||e===void 0?void 0:e[1])||null}if(!p){throw new Error("Failed to get upload ID from console URL")}const _=yield getTestStatus(p,t.apiKey,r,t.apiUrl);if(_){const e=(0,a.evaluateRun)(_,d);(0,u.setOutput)("console_url",_.consoleUrl||"");(0,u.setOutput)("app_binary_id",_.appBinaryId||"");(0,u.setOutput)("upload_status",e.uploadStatus);const t=(_.tests||[]).map(e=>({name:e.name,status:e.status}));(0,u.setOutput)("flow_results",JSON.stringify(t));console.error(e.message);process.exit(e.exitCode)}else{(0,u.setOutput)("upload_status","ERROR");(0,u.setOutput)("flow_results","[]");throw new Error("Failed to get test status")}}catch(e){const t=typeof e==="string"?e:e.message;console.error(t);process.exit(1)}});run()},916:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.getEnv=getEnv;const s=[["DCD_EAS_BUILD_ID","eas_build_id"],["DCD_EAS_PLATFORM","eas_platform"],["DCD_EAS_PROFILE","eas_profile"],["DCD_EAS_APP_VERSION","eas_app_version"],["DCD_GH_SHA","gh_sha"],["DCD_GH_BRANCH","gh_branch"],["DCD_GH_PR_NUMBER","gh_pr_number"],["DCD_GH_PR_URL","gh_pr_url"],["DCD_GH_REPO","gh_repo"],["DCD_GH_RUN_ID","gh_run_id"],["DCD_CHECK_NAME","gh_check_name"]];function getEnv(){const e=process.env.DEVICE_CLOUD_API_KEY;if(!e){throw new Error("DEVICE_CLOUD_API_KEY is not set. Pass it via the step `env:` block: "+"DEVICE_CLOUD_API_KEY: ${{ secrets.DEVICE_CLOUD_API_KEY }}")}const t=[];for(const[e,r]of s){const s=process.env[e];if(s){t.push(`${r}=${s}`)}}return{apiKey:e,apiUrl:process.env.DEVICE_CLOUD_API_URL||undefined,buildUrl:process.env.DCD_EAS_BUILD_URL||undefined,useBeta:process.env.DCD_USE_BETA==="true",metadata:t}}},690:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.setOutput=setOutput;t.escapeShellValue=escapeShellValue;function setOutput(e,t){const s=t.replace(/\r?\n/g," ");process.stdout.write(`set-output ${e} ${s}\n`)}function escapeShellValue(e){return e.replace(/(["\\'$`!\s\[\]{}()&|;<>*?#^~])/g,"\\$1")}},53:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.supersedingConsoleUrl=supersedingConsoleUrl;t.evaluateRun=evaluateRun;function supersedingConsoleUrl(e,t){if(!e)return undefined;try{const s=new URL(e);s.searchParams.set("upload",t);s.searchParams.delete("result");return s.toString()}catch(e){return undefined}}function evaluateRun(e,t){const s=typeof e.supersededBy==="string"?e.supersededBy:"";if(s){const t=supersedingConsoleUrl(e.consoleUrl,s);return{exitCode:0,uploadStatus:"SUPERSEDED",message:`Superseded by ${s}: a newer run from the same CI context `+`replaced this one, so this job does not fail.`+(t?` Newer run: ${t}`:"")}}const r=e.status||"PENDING";if(t!==0){return{exitCode:1,uploadStatus:r,message:`Test run failed (dcd exited ${t}, status ${e.status}). `+`Check flow results: ${e.consoleUrl}`}}if(e.status==="PASSED"){return{exitCode:0,uploadStatus:r,message:"Successfully completed test run."}}if(e.status==="FAILED"||e.status==="CANCELLED"){return{exitCode:1,uploadStatus:r,message:`Test run ${e.status}. Check flow results: ${e.consoleUrl}`}}return{exitCode:0,uploadStatus:r,message:`dcd reported success but the upload status is ${e.status}. `+`Treating the run as passed: ${e.consoleUrl}`}}},317:e=>{e.exports=require("child_process")},330:e=>{e.exports={rE:"1.4.1"}}};var t={};function __nccwpck_require__(s){var r=t[s];if(r!==undefined){return r.exports}var o=t[s]={exports:{}};var n=true;try{e[s].call(o.exports,o,o.exports,__nccwpck_require__);n=false}finally{if(n)delete t[s]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(522);module.exports=s})(); \ No newline at end of file +(()=>{"use strict";var e={522:function(e,t,s){var r=this&&this.__awaiter||function(e,t,s,r){function adopt(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||(s=Promise))(function(s,o){function fulfilled(e){try{step(r.next(e))}catch(e){o(e)}}function rejected(e){try{step(r["throw"](e))}catch(e){o(e)}}function step(e){e.done?s(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:true});const o=s(317);const n=s(916);const u=s(690);const i=s(53);const a="@devicecloud.dev/dcd";const executeCommand=(e,t=true)=>new Promise((s,r)=>{let n="";const u=(0,o.spawn)(e,{shell:true});u.stdout.on("data",e=>{const s=e.toString();n+=s;if(t){process.stderr.write(s)}});u.stderr.on("data",e=>{const s=e.toString();n+=s;if(t){process.stderr.write(s)}});u.on("close",e=>{s({output:n,exitCode:e!==null&&e!==void 0?e:0})});u.on("error",e=>{r(e)})});const getLatestDcdVersion=e=>r(void 0,void 0,void 0,function*(){try{if(e){console.error("Using beta version of DCD CLI");return`${a}@beta`}const{output:t}=yield executeCommand(`npm view ${a} version`,false);const s=t.trim();console.error(`Latest DCD version from npm: ${s}`);return`${a}@${s}`}catch(e){console.error("Failed to fetch latest DCD version, falling back to >=5.0.0:",e);return`${a}@>=5.0.0`}});const getTestStatus=(e,t,s,o)=>r(void 0,void 0,void 0,function*(){try{let r=`npx --yes "${s}" status --json --upload-id ${e} --api-key ${(0,u.escapeShellValue)(t)}`;if(o){r+=` --api-url ${(0,u.escapeShellValue)(o)}`}const{output:n}=yield executeCommand(r,false);const i=n.split("\n");const a=i.findIndex(e=>{const t=e.trim();return t.startsWith("{")||t.startsWith("[")});if(a===-1){throw new Error("No JSON found in status output")}const l=i.slice(a).join("\n");return JSON.parse(l)}catch(e){console.error("Failed to get test status:",e);return null}});const run=()=>r(void 0,void 0,void 0,function*(){var e;try{const t=(0,n.getEnv)();const r=yield getLatestDcdVersion(t.useBeta);const o=[`--apiKey ${(0,u.escapeShellValue)(t.apiKey)}`,"--quiet"];if(t.apiUrl){o.push(`--api-url ${(0,u.escapeShellValue)(t.apiUrl)}`)}if(t.buildUrl){o.push(`--app-url ${(0,u.escapeShellValue)(t.buildUrl)}`)}for(const e of t.metadata){o.push(`--metadata ${(0,u.escapeShellValue)(e)}`)}const a=process.argv.slice(2).map(u.escapeShellValue).join(" ");const l=`npx --yes "${r}" cloud ${o.join(" ")} ${a}`.trim();process.env.DCD_CI_PROVIDER="eas";try{process.env.DCD_CI_WRAPPER_VERSION=s(330).rE}catch(e){}let c="";let p=null;let d=0;try{const{output:e,exitCode:t}=yield executeCommand(l);c=e;d=t;if(t===1){throw new Error("DeviceCloud CLI failed to run - check your parameters or contact support")}}finally{p=((e=c===null||c===void 0?void 0:c.match(/https:\/\/(?:dev\.)?console\.devicecloud\.dev\/results\?upload=([a-zA-Z0-9-]+)/))===null||e===void 0?void 0:e[1])||null}if(!p){throw new Error("Failed to get upload ID from console URL")}const _=yield getTestStatus(p,t.apiKey,r,t.apiUrl);if(_){const e=(0,i.evaluateRun)(_,d);(0,u.setOutput)("console_url",_.consoleUrl||"");(0,u.setOutput)("app_binary_id",_.appBinaryId||"");(0,u.setOutput)("upload_status",e.uploadStatus);const t=(_.tests||[]).map(e=>({name:e.name,status:e.status}));(0,u.setOutput)("flow_results",JSON.stringify(t));console.error(e.message);process.exit(e.exitCode)}else{(0,u.setOutput)("upload_status","ERROR");(0,u.setOutput)("flow_results","[]");throw new Error("Failed to get test status")}}catch(e){const t=typeof e==="string"?e:e.message;console.error(t);process.exit(1)}});run()},916:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.getEnv=getEnv;const s=[["DCD_EAS_BUILD_ID","eas_build_id"],["DCD_EAS_PLATFORM","eas_platform"],["DCD_EAS_PROFILE","eas_profile"],["DCD_EAS_APP_VERSION","eas_app_version"],["DCD_GH_SHA","gh_sha"],["DCD_GH_BRANCH","gh_branch"],["DCD_GH_PR_NUMBER","gh_pr_number"],["DCD_GH_PR_URL","gh_pr_url"],["DCD_GH_REPO","gh_repo"],["DCD_GH_RUN_ID","gh_run_id"],["DCD_CHECK_NAME","gh_check_name"]];function getEnv(){const e=process.env.DEVICE_CLOUD_API_KEY;if(!e){throw new Error("DEVICE_CLOUD_API_KEY is not set. Store your DeviceCloud API key as an "+"EAS environment variable with secret visibility, in the environment "+"the job runs in (its `environment:`, production by default), and "+"EAS sets it for every step. For example: eas env:create --scope "+"project --environment production --environment preview "+"--environment development --name DEVICE_CLOUD_API_KEY "+"--visibility secret --type string --value . "+"Don't use ${{ secrets.DEVICE_CLOUD_API_KEY }}: EAS Workflows "+"don't support it.")}const t=[];for(const[e,r]of s){const s=process.env[e];if(s){t.push(`${r}=${s}`)}}return{apiKey:e,apiUrl:process.env.DEVICE_CLOUD_API_URL||undefined,buildUrl:process.env.DCD_EAS_BUILD_URL||undefined,useBeta:process.env.DCD_USE_BETA==="true",metadata:t}}},690:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:true});t.setOutput=setOutput;t.escapeShellValue=escapeShellValue;const r=s(317);const o=s(896);const n=s(928);function setOutput(e,t){var s;if(t!==""){try{(0,r.execFileSync)("set-output",[e,t],{stdio:["ignore","pipe","pipe"]});return}catch(t){const{code:r,signal:o,status:n,stdout:u,stderr:i}=t;if(r!=="ENOENT"&&r!=="E2BIG"){const t=`${u!==null&&u!==void 0?u:""}${i!==null&&i!==void 0?i:""}`.trim();console.error(`Warning: set-output could not set ${e} `+`(${(s=r!==null&&r!==void 0?r:o)!==null&&s!==void 0?s:`exit code ${n}`})`+(t?`: ${t}`:""));return}}}const u=process.env.__EXPO_STEPS_OUTPUTS_DIR;if(u){try{(0,o.writeFileSync)((0,n.join)(u,e),Buffer.from(t).toString("base64"))}catch(t){console.error(`Warning: could not set ${e}: ${t.message}`)}return}const i=t.replace(/\r?\n/g," ");process.stdout.write(`set-output ${e} ${i}\n`)}function escapeShellValue(e){return e.replace(/(["\\'$`!\s\[\]{}()&|;<>*?#^~])/g,"\\$1")}},53:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.supersedingConsoleUrl=supersedingConsoleUrl;t.evaluateRun=evaluateRun;function supersedingConsoleUrl(e,t){if(!e)return undefined;try{const s=new URL(e);s.searchParams.set("upload",t);s.searchParams.delete("result");return s.toString()}catch(e){return undefined}}function evaluateRun(e,t){const s=typeof e.supersededBy==="string"?e.supersededBy:"";if(s){const t=supersedingConsoleUrl(e.consoleUrl,s);return{exitCode:0,uploadStatus:"SUPERSEDED",message:`Superseded by ${s}: a newer run from the same CI context `+`replaced this one, so this job does not fail.`+(t?` Newer run: ${t}`:"")}}const r=e.status||"PENDING";if(t!==0){return{exitCode:1,uploadStatus:r,message:`Test run failed (dcd exited ${t}, status ${e.status}). `+`Check flow results: ${e.consoleUrl}`}}if(e.status==="PASSED"){return{exitCode:0,uploadStatus:r,message:"Successfully completed test run."}}if(e.status==="FAILED"||e.status==="CANCELLED"){return{exitCode:1,uploadStatus:r,message:`Test run ${e.status}. Check flow results: ${e.consoleUrl}`}}return{exitCode:0,uploadStatus:r,message:`dcd reported success but the upload status is ${e.status}. `+`Treating the run as passed: ${e.consoleUrl}`}}},317:e=>{e.exports=require("child_process")},896:e=>{e.exports=require("fs")},928:e=>{e.exports=require("path")},330:e=>{e.exports={rE:"1.4.1"}}};var t={};function __nccwpck_require__(s){var r=t[s];if(r!==undefined){return r.exports}var o=t[s]={exports:{}};var n=true;try{e[s].call(o.exports,o,o.exports,__nccwpck_require__);n=false}finally{if(n)delete t[s]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(522);module.exports=s})(); \ No newline at end of file diff --git a/src/methods/env.test.ts b/src/methods/env.test.ts index 63bf858..5fc1bc9 100644 --- a/src/methods/env.test.ts +++ b/src/methods/env.test.ts @@ -12,6 +12,25 @@ describe('getEnv', () => { expect(() => getEnv()).toThrow(/DEVICE_CLOUD_API_KEY is not set/); }); + it('points to an EAS environment variable, not a GitHub Actions secret', () => { + // EAS Workflows have no secrets context, so a step env: block reading + // ${{ secrets.X }} can't supply the key. + vi.stubEnv('DEVICE_CLOUD_API_KEY', ''); + let message = ''; + try { + getEnv(); + } catch (error) { + message = (error as Error).message; + } + expect(message).toContain( + 'eas env:create --scope project --environment production' + ); + expect(message).toContain( + '--name DEVICE_CLOUD_API_KEY --visibility secret' + ); + expect(message).not.toMatch(/env:` block/); + }); + it('returns the api key and an empty metadata list when no DCD_* vars are set', () => { vi.stubEnv('DEVICE_CLOUD_API_KEY', 'secret-key'); const env = getEnv(); diff --git a/src/methods/env.ts b/src/methods/env.ts index c7d44ed..fca4dba 100644 --- a/src/methods/env.ts +++ b/src/methods/env.ts @@ -32,9 +32,18 @@ const metadataMappings: Array<[envVar: string, metadataKey: string]> = [ export function getEnv(): EasEnv { const apiKey = process.env.DEVICE_CLOUD_API_KEY; if (!apiKey) { + // EAS Workflows have no secrets context: a job gets the EAS environment + // variables of the environment it runs in (its `environment:`). throw new Error( - 'DEVICE_CLOUD_API_KEY is not set. Pass it via the step `env:` block: ' + - 'DEVICE_CLOUD_API_KEY: ${{ secrets.DEVICE_CLOUD_API_KEY }}' + 'DEVICE_CLOUD_API_KEY is not set. Store your DeviceCloud API key as an ' + + 'EAS environment variable with secret visibility, in the environment ' + + 'the job runs in (its `environment:`, production by default), and ' + + 'EAS sets it for every step. For example: eas env:create --scope ' + + 'project --environment production --environment preview ' + + '--environment development --name DEVICE_CLOUD_API_KEY ' + + '--visibility secret --type string --value . ' + + "Don't use ${{ secrets.DEVICE_CLOUD_API_KEY }}: EAS Workflows " + + "don't support it." ); } diff --git a/src/methods/output.test.ts b/src/methods/output.test.ts index ee9564e..7a6825c 100644 --- a/src/methods/output.test.ts +++ b/src/methods/output.test.ts @@ -1,7 +1,77 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { execFileSync } from 'child_process'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'fs'; +import { tmpdir } from 'os'; +import { delimiter, join } from 'path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { escapeShellValue, setOutput } from './output'; +// The real execFileSync, wrapped so tests can see how set-output was called. +vi.mock('child_process', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, execFileSync: vi.fn(actual.execFileSync) }; +}); + +// Expo's set-output, which EAS puts on every step's PATH. Copied verbatim from +// expo/eas-cli packages/steps/bin/set-output. +const EXPO_SET_OUTPUT = `#!/usr/bin/env bash + +set -eo pipefail + +NAME=$1 +VALUE=$2 + +if [[ -z "$__EXPO_STEPS_OUTPUTS_DIR" ]]; then + echo "Set __EXPO_STEPS_OUTPUTS_DIR" + exit 1 +fi + +if [[ -z "$NAME" || -z "$VALUE" ]]; then + echo "Usage: set-output NAME VALUE" + exit 2 +fi + +if [[ "$OSTYPE" == "linux"* ]]; then + echo -n "$VALUE" | base64 -w 0 > $__EXPO_STEPS_OUTPUTS_DIR/$NAME +else + echo -n "$VALUE" | base64 > $__EXPO_STEPS_OUTPUTS_DIR/$NAME +fi +`; + +const ORIGINAL_PATH = process.env.PATH; + +// How EAS reads an output back (BuildStep.collectAndValidateOutputsAsync in +// expo/eas-cli). +function readOutput(outputsDir: string, name: string): string { + const raw = readFileSync(join(outputsDir, name), 'utf-8'); + return Buffer.from(raw, 'base64').toString('utf-8'); +} + +const VALUES: Array<[label: string, value: string]> = [ + ['a plain value', 'PASSED'], + [ + 'a URL', + 'https://console.devicecloud.dev/results?upload=abc-123&result=456', + ], + ['spaces and quotes', 'my "quoted" value, it\'s $HOME and `ls` & more'], + [ + 'JSON', + JSON.stringify([ + { name: 'Login "happy" path', status: 'PASSED' }, + { name: "it's a flow", status: 'FAILED' }, + ]), + ], + ['several lines', 'line1\nline2\r\nline3'], + ['non-ASCII text', 'Tëst ✓ 日本語'], +]; + describe('escapeShellValue', () => { it('leaves plain alphanumeric values untouched', () => { expect(escapeShellValue('pixel-6')).toBe('pixel-6'); @@ -23,27 +93,146 @@ describe('escapeShellValue', () => { }); describe('setOutput', () => { + let tempDir: string; + let outputsDir: string; + let stdoutWrite: ReturnType; + let consoleError: ReturnType; + + beforeEach(() => { + vi.mocked(execFileSync).mockClear(); + tempDir = mkdtempSync(join(tmpdir(), 'eas-set-output-')); + outputsDir = join(tempDir, 'outputs'); + mkdirSync(outputsDir); + // By default nothing named set-output can be found and no outputs + // directory is set, as in a local run. Each describe sets up its own. + const emptyDir = join(tempDir, 'empty'); + mkdirSync(emptyDir); + vi.stubEnv('PATH', emptyDir); + vi.stubEnv('__EXPO_STEPS_OUTPUTS_DIR', undefined); + stdoutWrite = vi + .spyOn(process.stdout, 'write') + .mockImplementation(() => true); + consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + }); + afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); + rmSync(tempDir, { recursive: true, force: true }); }); - it('writes a set-output line for the given name and value', () => { - const spy = vi - .spyOn(process.stdout, 'write') - .mockImplementation(() => true); - setOutput('DEVICE_CLOUD_UPLOAD_STATUS', 'PASSED'); - expect(spy).toHaveBeenCalledWith( - 'set-output DEVICE_CLOUD_UPLOAD_STATUS PASSED\n' - ); + describe('in an EAS step, with set-output on PATH', () => { + beforeEach(() => { + const binDir = join(tempDir, 'bin'); + mkdirSync(binDir); + writeFileSync(join(binDir, 'set-output'), EXPO_SET_OUTPUT, { + mode: 0o755, + }); + vi.stubEnv('PATH', `${binDir}${delimiter}${ORIGINAL_PATH}`); + vi.stubEnv('__EXPO_STEPS_OUTPUTS_DIR', outputsDir); + }); + + it.each(VALUES)('stores %s through set-output', (_label, value) => { + setOutput('flow_results', value); + + expect(execFileSync).toHaveBeenCalledWith( + 'set-output', + ['flow_results', value], + expect.anything() + ); + expect(readOutput(outputsDir, 'flow_results')).toBe(value); + expect(stdoutWrite).not.toHaveBeenCalled(); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('writes an empty value itself, since set-output refuses one', () => { + setOutput('app_binary_id', ''); + + expect(execFileSync).not.toHaveBeenCalled(); + expect(existsSync(join(outputsDir, 'app_binary_id'))).toBe(true); + expect(readOutput(outputsDir, 'app_binary_id')).toBe(''); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('writes the file itself when the value is too long for an argument', () => { + // Over the per-argument (Linux) and total (macOS) limits, so spawning + // set-output fails with E2BIG. + const value = JSON.stringify([ + { name: 'x'.repeat(2 * 1024 * 1024), status: 'PASSED' }, + ]); + + setOutput('flow_results', value); + + expect(execFileSync).toHaveBeenCalledTimes(1); + expect(readOutput(outputsDir, 'flow_results')).toBe(value); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('warns, without throwing, when set-output fails', () => { + // Expo's script exits 1 without an outputs directory. + vi.stubEnv('__EXPO_STEPS_OUTPUTS_DIR', undefined); + + expect(() => setOutput('upload_status', 'PASSED')).not.toThrow(); + + expect(consoleError).toHaveBeenCalledWith( + expect.stringContaining( + 'set-output could not set upload_status (exit code 1): Set __EXPO_STEPS_OUTPUTS_DIR' + ) + ); + expect(stdoutWrite).not.toHaveBeenCalled(); + }); }); - it('collapses newlines in the value to single spaces so the line stays parseable', () => { - const spy = vi - .spyOn(process.stdout, 'write') - .mockImplementation(() => true); - setOutput('DEVICE_CLOUD_FLOW_RESULTS', 'line1\nline2\r\nline3'); - expect(spy).toHaveBeenCalledWith( - 'set-output DEVICE_CLOUD_FLOW_RESULTS line1 line2 line3\n' - ); + describe('in an EAS step, without set-output on PATH', () => { + beforeEach(() => { + vi.stubEnv('__EXPO_STEPS_OUTPUTS_DIR', outputsDir); + }); + + it('writes the output file the way set-output does', () => { + const value = JSON.stringify( + [{ name: 'Login "happy" path', status: 'PASSED' }], + null, + 2 + ); + + setOutput('flow_results', value); + + expect(execFileSync).toHaveBeenCalledTimes(1); + expect(readFileSync(join(outputsDir, 'flow_results'), 'utf-8')).toBe( + Buffer.from(value).toString('base64') + ); + expect(readOutput(outputsDir, 'flow_results')).toBe(value); + expect(stdoutWrite).not.toHaveBeenCalled(); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('warns, without throwing, when the file cannot be written', () => { + vi.stubEnv('__EXPO_STEPS_OUTPUTS_DIR', join(tempDir, 'missing')); + + expect(() => setOutput('upload_status', 'PASSED')).not.toThrow(); + + expect(consoleError).toHaveBeenCalledWith( + expect.stringContaining('could not set upload_status') + ); + }); + }); + + describe('outside EAS', () => { + it('prints a set-output line for the given name and value', () => { + setOutput('upload_status', 'PASSED'); + + expect(stdoutWrite).toHaveBeenCalledWith( + 'set-output upload_status PASSED\n' + ); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('collapses newlines in the value to single spaces so the line stays parseable', () => { + setOutput('flow_results', 'line1\nline2\r\nline3'); + + expect(stdoutWrite).toHaveBeenCalledWith( + 'set-output flow_results line1 line2 line3\n' + ); + }); }); }); diff --git a/src/methods/output.ts b/src/methods/output.ts index f7453d9..ceead40 100644 --- a/src/methods/output.ts +++ b/src/methods/output.ts @@ -1,4 +1,70 @@ +import { execFileSync } from 'child_process'; +import { writeFileSync } from 'fs'; +import { join } from 'path'; + +type ExecFileSyncError = NodeJS.ErrnoException & { + status?: number | null; + signal?: NodeJS.Signals | null; + stdout?: Buffer | string; + stderr?: Buffer | string; +}; + +/** + * Sets an EAS Workflows step output, which the workflow reads as + * `steps..outputs.`. + * + * EAS reads a step's outputs from the files in $__EXPO_STEPS_OUTPUTS_DIR, one + * per output, each holding the value in base64. It puts its own `set-output` + * command, which writes them, on the step's PATH. A `set-output` line printed + * to stdout sets nothing. + */ export function setOutput(name: string, value: string): void { + // Expo's set-output refuses an empty value (it exits 2), so an empty value + // skips it and gets written directly below. + if (value !== '') { + try { + // No shell runs, so the value needs no quoting. + execFileSync('set-output', [name, value], { + stdio: ['ignore', 'pipe', 'pipe'], + }); + return; + } catch (error) { + const { code, signal, status, stdout, stderr } = + error as ExecFileSyncError; + // set-output never started. ENOENT: it isn't on PATH. E2BIG: the value + // is too long for one argument (Linux caps one at 128 KiB), which + // flow_results can be for a large run. Write the file ourselves. + if (code !== 'ENOENT' && code !== 'E2BIG') { + // It ran and failed. The verdict doesn't depend on the outputs, so + // warn rather than fail the run. + const printed = `${stdout ?? ''}${stderr ?? ''}`.trim(); + console.error( + `Warning: set-output could not set ${name} ` + + `(${code ?? signal ?? `exit code ${status}`})` + + (printed ? `: ${printed}` : '') + ); + return; + } + } + } + + const outputsDir = process.env.__EXPO_STEPS_OUTPUTS_DIR; + if (outputsDir) { + try { + // The file set-output writes: the value in base64, nothing else. + writeFileSync( + join(outputsDir, name), + Buffer.from(value).toString('base64') + ); + } catch (error) { + console.error( + `Warning: could not set ${name}: ${(error as Error).message}` + ); + } + return; + } + + // Not in an EAS step (a local run): print the output on one line instead. const oneLine = value.replace(/\r?\n/g, ' '); process.stdout.write(`set-output ${name} ${oneLine}\n`); }