import{__decorate}from"tslib";import{ChannelProvider}from"../core/ChannelProvider.js";import{activate}from"../../Hooks.js";import{validation}from"../../Validation.js";import{ActivityCancellationError}from"../../Errors.js";import{getAuthenticationToken,parsePortalItemUrl,getPortalItem,getPortalDataUrl}from"./shared.js";import{runJob,getServiceToken}from"./runUtils.js";import{oldDefaultServerVirtualPath,defaultServerVirtualPath}from"../constants.js";let RunWorkflow=class{async execute(r,t,e){var o=validation.string("url",r.url,validation.never),a=parsePortalItemUrl(o);if(a){var i=this.getAuthenticationToken(a.portalUrl),l=getPortalDataUrl(a,i);const n=t.cancellationToken;l=await getPortalItem(l,e,n);const s=e.create();if(n.finally(function(){s.cancel()}),this.isServerWorkflow(l))return this.runServerWorkflow(l,r.arguments,s,n,a.portalUrl,i)}return this.runClientWorkflow(o,r.arguments,t)}getAuthenticationToken(r){return getAuthenticationToken(r)}isServerWorkflow(r){if(null==r)return!1;var t=r.properties;if(null==t)return!1;r=t.isServerWorkflow,t=t.serverUrl;return!(!0!==r||!t)}async runServerWorkflow(r,t,e,o,a,i){let l=r.properties.serverUrl;l=l.replace(/\/+$/,"");let n;if(i&&"public"!==r.access)try{n=await getServiceToken(l,a,i,e)}catch(r){if(!oldDefaultServerVirtualPath.test(l))throw r;l=l.replace(oldDefaultServerVirtualPath,defaultServerVirtualPath),n=await getServiceToken(l,a,i,e)}t={workflow:{id:r.id},inputs:t};let s;try{s=await runJob(l,n,t,e)}catch(r){if(!oldDefaultServerVirtualPath.test(l))throw r;l=l.replace(oldDefaultServerVirtualPath,defaultServerVirtualPath),s=await runJob(l,n,t,e)}t=s.ticket;return{result:await this.checkResult(l,n,t,1e3,e,o)}}async delay(t){return new Promise(r=>setTimeout(r,t))}async checkResult(r,t,e,o,a,i){var l=await this.checkJobStatus(r,t,e,a,i);return l||(await this.delay(o),this.checkResult(r,t,e,1.1*o,a,i))}async checkJobStatus(r,t,e,o,a){if(o=o.new(),a.finally(function(){o.cancel()}),o.request.url=`${r}/job/artifacts?ticket=${e}`,t&&(o.request.headers.Authorization=`Bearer ${t}`),!await o.send())throw console.error("Unable to check workflow status.",o.response.message),new Error("Unable to check workflow status.");const i=JSON.parse(o.response.content);if(console.debug(i),i.results&&i.results.some(r=>"JobQuit"===r.$type)){t=i.results.filter(r=>"JobResult"===r.$type)[0];if(t)return t.outputs;throw console.error("Server workflow failed.",`${r}/job/logs?ticket=${e}&`),new Error("Server workflow failed.")}return null}async runClientWorkflow(r,t,e){const o=e.ambient.trivia;var a=e.ambient.activityContexts,a=a?a.$$form:void 0;try{var i=a?{$$form:a}:{};return{result:await o.runWorkflow(r,t,i,o.isDescendantOf)}}catch(r){if(!(r instanceof ActivityCancellationError))throw r;e.ambient.reject(r)}}};RunWorkflow.action="gcx:wf:core::RunWorkflow",RunWorkflow.suite="gcx:wf:builtin",RunWorkflow=__decorate([activate(ChannelProvider)],RunWorkflow);export{RunWorkflow};