@runveric/cli 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runveric.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __runveric_createRequire } from "node:module";
3
3
  const require = __runveric_createRequire(import.meta.url);
4
- var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:true});var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_enums=__commonJS({"../contracts/dist/enums.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUN_TRIGGER_KINDS=exports.ROLE_KEYS=exports.SETTLED_EXECUTION_STATUSES=exports.DIRECTLY_CANCELLABLE_EXECUTION_STATUSES=exports.WORKER_HELD_EXECUTION_STATUSES=exports.EXECUTION_CANCEL_MECHANISM=exports.EXECUTION_STATUS_SETTLED=exports.EXECUTION_STATUSES=exports.ENVIRONMENTS=exports.VERSION_STATUSES=exports.RISK_LEVELS=exports.ACTION_CATEGORIES=exports.CONNECTION_SCOPE_KINDS=exports.CONNECTION_STATES=exports.IDENTITY_MECHANISMS=exports.PROVIDERS=void 0;exports.maxRiskLevel=maxRiskLevel;exports.isSettledExecutionStatus=isSettledExecutionStatus;exports.PROVIDERS=["azure","aws","gcp","terraform"];exports.IDENTITY_MECHANISMS=["service_principal","managed_identity","iam_role","hcp_dynamic","api_token"];exports.CONNECTION_STATES=["draft","active","degraded"];exports.CONNECTION_SCOPE_KINDS=["subscription","account","project","workspace"];exports.ACTION_CATEGORIES=["compute","storage","security","databases","containers"];exports.RISK_LEVELS=["low","medium","high"];function maxRiskLevel(left,right){return exports.RISK_LEVELS.indexOf(left)>=exports.RISK_LEVELS.indexOf(right)?left:right}__name(maxRiskLevel,"maxRiskLevel");exports.VERSION_STATUSES=["draft","published","deprecated"];exports.ENVIRONMENTS=["production","staging","non_prod"];exports.EXECUTION_STATUSES=["draft","validating","validated","validation_failed","pending_approval","approved","rejected","queued","pending_runner","running","succeeded","rolling_back","failed","cancelled","rolled_back","rollback_failed"];exports.EXECUTION_STATUS_SETTLED={draft:false,validating:false,validated:false,validation_failed:true,pending_approval:false,approved:false,rejected:true,queued:false,pending_runner:false,running:false,succeeded:true,rolling_back:false,failed:true,cancelled:true,rolled_back:true,rollback_failed:true};exports.EXECUTION_CANCEL_MECHANISM={draft:"direct",validating:"no",validated:"direct",validation_failed:"no",pending_approval:"direct",approved:"no",rejected:"no",queued:"direct",pending_runner:"cooperative",running:"cooperative",succeeded:"no",rolling_back:"no",failed:"no",cancelled:"no",rolled_back:"no",rollback_failed:"no"};exports.WORKER_HELD_EXECUTION_STATUSES=exports.EXECUTION_STATUSES.filter(status=>exports.EXECUTION_CANCEL_MECHANISM[status]==="cooperative");exports.DIRECTLY_CANCELLABLE_EXECUTION_STATUSES=exports.EXECUTION_STATUSES.filter(status=>exports.EXECUTION_CANCEL_MECHANISM[status]==="direct");exports.SETTLED_EXECUTION_STATUSES=exports.EXECUTION_STATUSES.filter(status=>exports.EXECUTION_STATUS_SETTLED[status]);function isSettledExecutionStatus(status){return exports.EXECUTION_STATUS_SETTLED[status]===true}__name(isSettledExecutionStatus,"isSettledExecutionStatus");exports.ROLE_KEYS=["viewer","operator","approver","auditor","admin"];exports.RUN_TRIGGER_KINDS=["manual","schedule","api","agent"]}});var require_brand=__commonJS({"../contracts/dist/brand.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PACKAGE_IMPORTER_USER_AGENT=exports.BRAND_SLUG=exports.BRAND_ARTICLE_CAPITALISED=exports.BRAND_ARTICLE=exports.BRAND_SHORT_NAME=exports.BRAND_NAME=void 0;exports.BRAND_NAME="Runveric";exports.BRAND_SHORT_NAME=exports.BRAND_NAME.split(" ")[0];exports.BRAND_ARTICLE=/^[aeiou]/i.test(exports.BRAND_SHORT_NAME)?"an":"a";exports.BRAND_ARTICLE_CAPITALISED=exports.BRAND_ARTICLE==="an"?"An":"A";exports.BRAND_SLUG=exports.BRAND_NAME.replace(/[^A-Za-z0-9]+/g,"-").replace(/^-|-$/g,"");exports.PACKAGE_IMPORTER_USER_AGENT=`${exports.BRAND_SLUG}-Action-Package-Importer`}});var require_wire_identity=__commonJS({"../contracts/dist/wire-identity.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PROBLEM_TYPE_BASE=exports.CATALOG_ARTIFACT_MEDIA_TYPE=exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V2=exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V1=exports.CATALOG_RELEASE_SCHEMA_V1=exports.EVIDENCE_PACK_SCHEMA_VERSION=exports.ACTION_PROTOCOL_V1=exports.RUNNER_PROTOCOL_VERSION=exports.PACKAGE_WORK_ITEM_VERSION=exports.ACTION_MANIFEST_API_VERSION=exports.PACKAGE_EXECUTION_PROTOCOL_VERSION=exports.PACKAGE_RESULT_PROTOCOL_VERSION=void 0;exports.problemType=problemType;exports.PACKAGE_RESULT_PROTOCOL_VERSION="runveric.dev/package-result/v1";exports.PACKAGE_EXECUTION_PROTOCOL_VERSION="runveric.dev/package-execution/v1";exports.ACTION_MANIFEST_API_VERSION="runveric.dev/action/v1";exports.PACKAGE_WORK_ITEM_VERSION="runveric.dev/package-work-item/v1";exports.RUNNER_PROTOCOL_VERSION="runveric.dev/runner-channel/v2";exports.ACTION_PROTOCOL_V1="runveric.dev/action-protocol/v1";exports.EVIDENCE_PACK_SCHEMA_VERSION="runveric.dev/evidence-pack/v1";exports.CATALOG_RELEASE_SCHEMA_V1="runveric.dev/catalog-release/v1";exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V1="runveric.dev/catalog-action/v1";exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V2="runveric.dev/catalog-action/v2";exports.CATALOG_ARTIFACT_MEDIA_TYPE="application/vnd.runveric.catalog-artifact+json";exports.PROBLEM_TYPE_BASE="https://runveric.dev/errors";function problemType(slug){return`${exports.PROBLEM_TYPE_BASE}/${slug}`}__name(problemType,"problemType")}});var require_problem=__commonJS({"../contracts/dist/problem.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parseProblemDocument=parseProblemDocument2;exports.problemFieldErrors=problemFieldErrors2;function isFieldError(entry){if(typeof entry!=="object"||entry===null)return false;const record=entry;return typeof record.field==="string"&&typeof record.message==="string"}__name(isFieldError,"isFieldError");function isManifestError(entry){if(typeof entry!=="object"||entry===null)return false;const record=entry;return typeof record.path==="string"&&typeof record.message==="string"}__name(isManifestError,"isManifestError");function optional(value,type){return value===void 0||typeof value===type}__name(optional,"optional");function parseProblemDocument2(body){if(typeof body!=="object"||body===null||Array.isArray(body))return null;const record=body;if(!optional(record.type,"string"))return null;if(!optional(record.title,"string"))return null;if(!optional(record.status,"number"))return null;if(!optional(record.detail,"string"))return null;if(!optional(record.code,"string"))return null;if(!optional(record.permission,"string"))return null;if(record.message!==void 0){const ok=typeof record.message==="string"||Array.isArray(record.message)&&record.message.every(one=>typeof one==="string");if(!ok)return null}if(record.errors!==void 0){if(!Array.isArray(record.errors))return null;const ok=record.errors.every(entry=>typeof entry==="string"||isFieldError(entry)||isManifestError(entry));if(!ok)return null}return record}__name(parseProblemDocument2,"parseProblemDocument");function problemFieldErrors2(problem){const entries=problem.errors??[];return entries.map(entry=>{if(typeof entry==="string")return{field:"",message:entry};if(isFieldError(entry))return{field:entry.field,message:entry.message};return{field:entry.path,message:entry.message}})}__name(problemFieldErrors2,"problemFieldErrors")}});var require_permissions=__commonJS({"../contracts/dist/permissions.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PLATFORM_PERMISSIONS=void 0;exports.PLATFORM_PERMISSIONS=["catalog:release"]}});var require_request_context=__commonJS({"../contracts/dist/request-context.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.hasPermission=hasPermission;function hasPermission(ctx,p){return ctx.permissions.includes(p)}__name(hasPermission,"hasPermission")}});var require_role_permissions=__commonJS({"../contracts/dist/role-permissions.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ROLE_PERMISSIONS=void 0;exports.permissionsForRoles=permissionsForRoles;var VIEWER=["catalog:read","subscription:read","operation:read","execution:read","execution:stream","evidence:read","connection:read"];exports.ROLE_PERMISSIONS={viewer:VIEWER,operator:[...VIEWER,"execution:create","execution:validate","execution:submit","execution:cancel","execution:rollback","operation:write"],approver:[...VIEWER,"approval:read","approval:decide"],auditor:[...VIEWER,"approval:read","audit:read"],admin:[...VIEWER,"execution:create","execution:validate","execution:submit","execution:cancel","execution:rollback","operation:write","approval:read","approval:decide","audit:read","connection:manage","package:manage","policy:manage","subscription:manage","rbac:manage"]};function permissionsForRoles(roles){const seen=new Set;for(const role of roles){for(const permission of exports.ROLE_PERMISSIONS[role]??[]){seen.add(permission)}}return[...seen]}__name(permissionsForRoles,"permissionsForRoles")}});var require_me=__commonJS({"../contracts/dist/me.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_tenant_users=__commonJS({"../contracts/dist/tenant-users.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_invitations=__commonJS({"../contracts/dist/invitations.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_groups=__commonJS({"../contracts/dist/groups.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_catalog_version=__commonJS({"../contracts/dist/catalog-version.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RETIRED_BETA_LIFECYCLE_REFUSAL=exports.RETIRED_BETA_LIFECYCLE=exports.FIRST_ACTION_VERSION=exports.CATALOG_CHANNEL_LABELS=exports.CATALOG_CHANNELS=void 0;exports.parseCatalogVersion=parseCatalogVersion;exports.catalogVersionString=catalogVersionString;exports.catalogVersionRefusal=catalogVersionRefusal;exports.channelOf=channelOf;exports.compareCatalogVersions=compareCatalogVersions;var CATALOG_CHANNEL_SET={ga:true,beta:true};exports.CATALOG_CHANNELS=Object.keys(CATALOG_CHANNEL_SET);exports.CATALOG_CHANNEL_LABELS={ga:"GA",beta:"Beta"};var NUMBER="(0|[1-9][0-9]*)";var CATALOG_VERSION_GRAMMAR=new RegExp(`^v${NUMBER}\\.${NUMBER}\\.${NUMBER}(?:-beta\\.([1-9][0-9]*))?$`);function parseCatalogVersion(value){const match=CATALOG_VERSION_GRAMMAR.exec(value);if(!match)return null;const[major,minor,patch]=[match[1],match[2],match[3]].map(Number);const beta=match[4]===void 0?null:Number(match[4]);if(![major,minor,patch,beta??0].every(Number.isSafeInteger))return null;return{major,minor,patch,beta}}__name(parseCatalogVersion,"parseCatalogVersion");function catalogVersionString(version5){const{major,minor,patch,beta}=version5;const text=`v${major}.${minor}.${patch}${beta===null?"":`-beta.${beta}`}`;if(parseCatalogVersion(text)===null)throw new Error(`${JSON.stringify(version5)} is not a catalog version.`);return text}__name(catalogVersionString,"catalogVersionString");exports.FIRST_ACTION_VERSION=catalogVersionString({major:0,minor:1,patch:0,beta:1});function catalogVersionRefusal(value){if(parseCatalogVersion(value)!==null)return null;return`version "${value}" is not a catalog version. Write vMAJOR.MINOR.PATCH for a GA release (e.g. "v1.4.0") or vMAJOR.MINOR.PATCH-beta.N for a beta (e.g. "v1.4.0-beta.1"): a "v", three numbers with no leading zeros, and for a beta a number from 1. Nothing else is accepted \u2014 no -rc or -alpha, and no +build metadata.`}__name(catalogVersionRefusal,"catalogVersionRefusal");exports.RETIRED_BETA_LIFECYCLE="beta";exports.RETIRED_BETA_LIFECYCLE_REFUSAL=`declares lifecycle "${exports.RETIRED_BETA_LIFECYCLE}", which is no longer a lifecycle. A beta is a VERSION: write version "vX.Y.Z-beta.N" (e.g. "v1.0.0-beta.1") and leave lifecycle out, or write "published". A beta version reaches only the workspaces that allowed beta actions; a lifecycle reached every workspace, which is why it was retired (docs/128 \xA721.2 D2).`;function channelOf(version5){const parsed=parseCatalogVersion(version5);if(parsed===null){throw new Error(`"${version5}" is not a catalog version, so it has no channel. ${catalogVersionRefusal(version5)}`)}return parsed.beta===null?"ga":"beta"}__name(channelOf,"channelOf");function compareCatalogVersions(left,right){const a=requireCatalogVersion(left);const b=requireCatalogVersion(right);return a.major-b.major||a.minor-b.minor||a.patch-b.patch||(a.beta===null?b.beta===null?0:1:b.beta===null?-1:a.beta-b.beta)}__name(compareCatalogVersions,"compareCatalogVersions");function requireCatalogVersion(value){const parsed=parseCatalogVersion(value);if(parsed===null)throw new Error(catalogVersionRefusal(value)??`"${value}" is not a catalog version.`);return parsed}__name(requireCatalogVersion,"requireCatalogVersion")}});var require_catalog_policy=__commonJS({"../contracts/dist/catalog-policy.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CATALOG_ALLOW_BETA_WHEN_UNSET=exports.CATALOG_RULE_EFFECTS=exports.CATALOG_DEFAULT_MODE_WHEN_UNSET=exports.CATALOG_DEFAULT_MODES=void 0;exports.effectiveCatalogAccess=effectiveCatalogAccess;var CATALOG_DEFAULT_MODE_SET={allow_all:true,deny_all:true};exports.CATALOG_DEFAULT_MODES=Object.keys(CATALOG_DEFAULT_MODE_SET);exports.CATALOG_DEFAULT_MODE_WHEN_UNSET="allow_all";var CATALOG_RULE_EFFECT_SET={allow:true,deny:true};exports.CATALOG_RULE_EFFECTS=Object.keys(CATALOG_RULE_EFFECT_SET);var RULE_ACCESS={allow:"allowed",deny:"blocked"};var UNRULED_ACCESS={allow_all:"allowed",deny_all:"blocked"};var CHANNEL_ACCESS={ga:{off:"allowed",on:"allowed"},beta:{off:"beta_not_allowed",on:"allowed"}};function effectiveCatalogAccess(defaultMode,rule,channel,allowBeta){const decided=rule!==null?RULE_ACCESS[rule]:UNRULED_ACCESS[defaultMode];if(decided==="blocked")return decided;return CHANNEL_ACCESS[channel][allowBeta?"on":"off"]}__name(effectiveCatalogAccess,"effectiveCatalogAccess");exports.CATALOG_ALLOW_BETA_WHEN_UNSET=false}});var require_catalog=__commonJS({"../contracts/dist/catalog.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NEW_ACTION_WINDOW_DAYS=exports.PARAMETER_ORDER_KEY=exports.PARAMETER_CONTROLS=exports.ACTION_LIFECYCLE_LABELS=exports.INACTIVE_ACTION_LIFECYCLES=exports.RUNNABLE_ACTION_LIFECYCLES=exports.LISTED_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLE_STANDING=exports.ACTION_LIFECYCLES=void 0;exports.orderedParameterEntries=orderedParameterEntries;exports.withParameterOrder=withParameterOrder;exports.isNewAction=isNewAction;exports.ACTION_LIFECYCLES=["draft","published","deprecated","retired"];exports.ACTION_LIFECYCLE_STANDING={draft:{listed:false,runnable:false},published:{listed:true,runnable:true},deprecated:{listed:true,runnable:true},retired:{listed:false,runnable:false}};exports.LISTED_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLES.filter(lifecycle=>exports.ACTION_LIFECYCLE_STANDING[lifecycle].listed);exports.RUNNABLE_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLES.filter(lifecycle=>exports.ACTION_LIFECYCLE_STANDING[lifecycle].runnable);exports.INACTIVE_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLES.filter(lifecycle=>!exports.ACTION_LIFECYCLE_STANDING[lifecycle].runnable);exports.ACTION_LIFECYCLE_LABELS={draft:"Draft",published:"Published",deprecated:"Deprecated",retired:"Retired"};exports.PARAMETER_CONTROLS=["select","text","switch","info"];exports.PARAMETER_ORDER_KEY="x-runveric-order";function orderedParameterEntries(schema){const properties=schema.properties??{};const declared=schema[exports.PARAMETER_ORDER_KEY]??[];const seen=new Set;const ordered=[];for(const id of declared){const property=properties[id];if(!property||seen.has(id))continue;seen.add(id);ordered.push([id,property])}for(const[id,property]of Object.entries(properties)){if(seen.has(id))continue;ordered.push([id,property])}return ordered}__name(orderedParameterEntries,"orderedParameterEntries");function withParameterOrder(schema){return{...schema,[exports.PARAMETER_ORDER_KEY]:Object.keys(schema.properties??{})}}__name(withParameterOrder,"withParameterOrder");exports.NEW_ACTION_WINDOW_DAYS=30;var MS_PER_DAY=24*60*60*1e3;function isNewAction(publishedAt,now){if(publishedAt===null)return false;const published=new Date(publishedAt).getTime();if(Number.isNaN(published))return false;const age=now.getTime()-published;return age>=0&&age<exports.NEW_ACTION_WINDOW_DAYS*MS_PER_DAY}__name(isNewAction,"isNewAction")}});var require_catalog_release=__commonJS({"../contracts/dist/catalog-release.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CatalogReleaseStateError=exports.CATALOG_SYNC_STALE_AFTER_MINUTES=exports.CATALOG_SYNC_INTERVAL_MINUTES=exports.CATALOG_SYNC_SOURCES=exports.CATALOG_SYNC_RUN_OUTCOMES=exports.ARTIFACT_DIGEST_PATTERN=exports.ARTIFACT_REPOSITORY_PATTERN=exports.CATALOG_ACTION_ARTIFACT_SCHEMA_VERSIONS=exports.CATALOG_RELEASE_SCHEMA_VERSIONS=void 0;exports.parseCatalogReleaseState=parseCatalogReleaseState;var wire_identity_1=require_wire_identity();exports.CATALOG_RELEASE_SCHEMA_VERSIONS=[wire_identity_1.CATALOG_RELEASE_SCHEMA_V1];exports.CATALOG_ACTION_ARTIFACT_SCHEMA_VERSIONS=[wire_identity_1.CATALOG_ACTION_ARTIFACT_SCHEMA_V1,wire_identity_1.CATALOG_ACTION_ARTIFACT_SCHEMA_V2];exports.ARTIFACT_REPOSITORY_PATTERN=/^[a-z0-9][a-z0-9.-]*(:[0-9]+)?(\/[a-z0-9][a-z0-9._-]*)+$/;exports.ARTIFACT_DIGEST_PATTERN=/^sha256:[0-9a-f]{64}$/;exports.CATALOG_SYNC_RUN_OUTCOMES=["applied","refused","superseded"];exports.CATALOG_SYNC_SOURCES=["directory","release"];exports.CATALOG_SYNC_INTERVAL_MINUTES=15;exports.CATALOG_SYNC_STALE_AFTER_MINUTES=exports.CATALOG_SYNC_INTERVAL_MINUTES*2;var CatalogReleaseStateError=class CatalogReleaseStateError extends Error{static{__name(this,"CatalogReleaseStateError")}constructor(message){super(message);this.name="CatalogReleaseStateError"}};exports.CatalogReleaseStateError=CatalogReleaseStateError;function stateObject(path,value){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new CatalogReleaseStateError(`${path} is not an object.`)}return value}__name(stateObject,"stateObject");function stateString(path,value,pattern,expected="a non-empty string"){if(typeof value!=="string"||value===""||pattern!==void 0&&!pattern.test(value)){throw new CatalogReleaseStateError(`${path} is ${JSON.stringify(value)}, not ${expected}.`)}return value}__name(stateString,"stateString");function stateInstant(path,value){const text=stateString(path,value);if(Number.isNaN(Date.parse(text))){throw new CatalogReleaseStateError(`${path} is "${text}", which is not a timestamp.`)}return text}__name(stateInstant,"stateInstant");var orNull=__name((value,read)=>value===null?null:read(value),"orNull");function stateMember(path,value,members){if(typeof value==="string"&&members.includes(value))return value;throw new CatalogReleaseStateError(`${path} is ${JSON.stringify(value)}; this build reads ${members.join(", ")}.`)}__name(stateMember,"stateMember");function parseSyncRun(value){const run3=stateObject("lastSync",value);const source=stateMember("lastSync.source",run3.source,exports.CATALOG_SYNC_SOURCES);const release=orNull(run3.release,raw=>{const fields=stateObject("lastSync.release",raw);return{artifactRef:stateString("lastSync.release.artifactRef",fields.artifactRef,exports.ARTIFACT_REPOSITORY_PATTERN,"a registry repository"),digest:stateString("lastSync.release.digest",fields.digest,exports.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),version:orNull(fields.version,label=>stateString("lastSync.release.version",label))}});if(source==="release"!==(release!==null)){throw new CatalogReleaseStateError(`lastSync.source is "${source}" and lastSync.release is ${release===null?"null":"set"}; a run names a release exactly when a release declared it.`)}return{startedAt:stateInstant("lastSync.startedAt",run3.startedAt),finishedAt:stateInstant("lastSync.finishedAt",run3.finishedAt),imageTag:orNull(run3.imageTag,tag=>stateString("lastSync.imageTag",tag)),source,release,outcome:stateMember("lastSync.outcome",run3.outcome,exports.CATALOG_SYNC_RUN_OUTCOMES),detail:stateString("lastSync.detail",run3.detail)}}__name(parseSyncRun,"parseSyncRun");function parsePinned(value){const pin=stateObject("release",value);return{artifactRef:stateString("release.artifactRef",pin.artifactRef,exports.ARTIFACT_REPOSITORY_PATTERN,"a registry repository"),digest:stateString("release.digest",pin.digest,exports.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),version:stateString("release.version",pin.version),provenance:orNull(pin.provenance,raw=>{const fields=stateObject("release.provenance",raw);return{repository:stateString("release.provenance.repository",fields.repository),commit:stateString("release.provenance.commit",fields.commit)}}),pinnedBy:stateString("release.pinnedBy",pin.pinnedBy),pinnedByName:orNull(pin.pinnedByName,name3=>stateString("release.pinnedByName",name3)),pinnedAt:stateInstant("release.pinnedAt",pin.pinnedAt)}}__name(parsePinned,"parsePinned");function parseCatalogReleaseState(value){const state=stateObject("the catalog release state",value);for(const field of["release","imageTag","lastSync","liveSince"]){if(!(field in state))throw new CatalogReleaseStateError(`${field} is missing.`)}const release=orNull(state.release,parsePinned);const liveSince=orNull(state.liveSince,instant=>stateInstant("liveSince",instant));if(release===null&&liveSince!==null){throw new CatalogReleaseStateError("liveSince is set with nothing pinned; only a pin goes live.")}return{release,imageTag:orNull(state.imageTag,tag=>stateString("imageTag",tag)),lastSync:orNull(state.lastSync,parseSyncRun),liveSince}}__name(parseCatalogReleaseState,"parseCatalogReleaseState")}});var require_action_repository=__commonJS({"../contracts/dist/action-repository.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ACTION_SOURCE_REPOSITORY_PREFIX=exports.ACTION_REPOSITORY_PREFIX=void 0;exports.actionKeyRefusal=actionKeyRefusal2;exports.isActionKey=isActionKey;exports.actionRepositoryName=actionRepositoryName4;exports.actionSourceRepository=actionSourceRepository2;exports.actionKeyOf=actionKeyOf;exports.actionPackageRefusal=actionPackageRefusal4;exports.ACTION_REPOSITORY_PREFIX="action-";var WORD=/^[a-z][a-z0-9]*$/;var VERB=/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*$/;function actionKeyRefusal2(key){const shape="an action key is <provider>.<resource>.<verb>: provider and resource are one lowercase word (a-z, then a-z or 0-9), the verb is camelCase with no two capitals in a row \u2014 so the key maps to exactly one repository name and back.";const segments=key.split(".");if(segments.length!==3){return`"${key}" is not an action key: it has ${segments.length} dot-separated segment(s), not 3; ${shape}`}const[provider,resource,verb]=segments;const not=__name(what=>`"${key}" is not an action key: ${what}; ${shape}`,"not");if(!WORD.test(provider))return not(`its provider "${provider}" is not one lowercase word`);if(!WORD.test(resource))return not(`its resource "${resource}" is not one lowercase word`);if(!VERB.test(verb))return not(`its verb "${verb}" is not camelCase without two capitals in a row`);return null}__name(actionKeyRefusal2,"actionKeyRefusal");function isActionKey(key){return actionKeyRefusal2(key)===null}__name(isActionKey,"isActionKey");var kebab=__name(verb=>verb.replace(/[A-Z]/g,capital=>`-${capital.toLowerCase()}`),"kebab");function actionRepositoryName4(key){const refusal=actionKeyRefusal2(key);if(refusal!==null)throw new Error(refusal);const[provider,resource,verb]=key.split(".");return`${exports.ACTION_REPOSITORY_PREFIX}${provider}-${resource}-${kebab(verb)}`}__name(actionRepositoryName4,"actionRepositoryName");exports.ACTION_SOURCE_REPOSITORY_PREFIX="https://github.com/runveric/";function actionSourceRepository2(key){return`${exports.ACTION_SOURCE_REPOSITORY_PREFIX}${actionRepositoryName4(key)}`}__name(actionSourceRepository2,"actionSourceRepository");function actionKeyOf(name3){if(!name3.startsWith(exports.ACTION_REPOSITORY_PREFIX))return null;const[provider,resource,first2,...rest]=name3.slice(exports.ACTION_REPOSITORY_PREFIX.length).split("-");if(provider===void 0||resource===void 0||first2===void 0)return null;const verb=first2+rest.map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join("");const key=`${provider}.${resource}.${verb}`;return isActionKey(key)&&actionRepositoryName4(key)===name3?key:null}__name(actionKeyOf,"actionKeyOf");function actionPackageRefusal4(key,artifactRef){const keyRefusal=actionKeyRefusal2(key);if(keyRefusal!==null)return`${keyRefusal} No package can carry it.`;const cut=artifactRef.lastIndexOf("/");const named=artifactRef.slice(cut+1);const expected=actionRepositoryName4(key);if(named===expected)return null;return`action "${key}" is published only from a package named "${expected}" (${artifactRef.slice(0,cut+1)}${expected}), not "${named}". An action's package carries its key's name, so an artifact cannot claim an identity its package does not carry.`}__name(actionPackageRefusal4,"actionPackageRefusal")}});var require_catalog_release_spec=__commonJS({"../contracts/dist/catalog-release-spec.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CatalogReleaseSpecError=void 0;exports.splitArtifactReference=splitArtifactReference;exports.parseCatalogReleaseSpec=parseCatalogReleaseSpec3;var CatalogReleaseSpecError=class CatalogReleaseSpecError extends Error{static{__name(this,"CatalogReleaseSpecError")}constructor(message){super(message);this.name="CatalogReleaseSpecError"}};exports.CatalogReleaseSpecError=CatalogReleaseSpecError;function splitArtifactReference(reference){const at=reference.indexOf("@");if(at<=0||at===reference.length-1)return null;return{artifactRef:reference.slice(0,at),digest:reference.slice(at+1)}}__name(splitArtifactReference,"splitArtifactReference");var isMapping3=__name(value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"isMapping");function parseCatalogReleaseSpec3(value){if(!isMapping3(value)){throw new CatalogReleaseSpecError("release.yaml is not a mapping of `version` and `actions`.")}const unknown=Object.keys(value).filter(key=>key!=="version"&&key!=="actions");if(unknown.length>0){throw new CatalogReleaseSpecError(`release.yaml carries ${unknown.map(key=>`"${key}"`).join(", ")}; it has exactly two fields, \`version\` and \`actions\`.`)}const{version:version5,actions}=value;if(typeof version5!=="string"||version5.trim().length===0){throw new CatalogReleaseSpecError(`release.yaml's version is ${JSON.stringify(version5??null)}, not a label. Write it as a quoted string \u2014 version: "2026.10.1" \u2014 because YAML reads an unquoted 2026.10 as a number.`)}if(actions===null||actions===void 0||isMapping3(actions)&&Object.keys(actions).length===0){throw new CatalogReleaseSpecError("release.yaml declares no action. An empty release is refused: pinned, it would declare a catalog with nothing in it.")}if(!isMapping3(actions)){throw new CatalogReleaseSpecError("release.yaml's actions is not a mapping of action key to <repository>@<digest>.")}return{version:version5,actions:Object.entries(actions).map(([key,reference])=>{const split=typeof reference==="string"?splitArtifactReference(reference):null;if(split===null){throw new CatalogReleaseSpecError(`release.yaml's ${key} is ${JSON.stringify(reference)}, not <repository>@<digest>.`)}return{key,...split}})}}__name(parseCatalogReleaseSpec3,"parseCatalogReleaseSpec")}});var require_catalog_lock=__commonJS({"../contracts/dist/catalog-lock.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MANIFEST_SHA256_PATTERN=exports.CatalogLockError=exports.CATALOG_LOCK_ENGINE_EXECUTION=exports.CATALOG_LOCK_FILE=exports.CATALOG_LOCK_SCHEMA_V1=void 0;exports.parseCatalogLock=parseCatalogLock;exports.catalogLockText=catalogLockText;exports.authoredElsewhere=authoredElsewhere;var action_repository_1=require_action_repository();var catalog_release_1=require_catalog_release();exports.CATALOG_LOCK_SCHEMA_V1="runveric.catalog-lock/v1";exports.CATALOG_LOCK_FILE="release.lock.json";exports.CATALOG_LOCK_ENGINE_EXECUTION="engine";var CatalogLockError=class CatalogLockError extends Error{static{__name(this,"CatalogLockError")}constructor(message){super(message);this.name="CatalogLockError"}};exports.CatalogLockError=CatalogLockError;exports.MANIFEST_SHA256_PATTERN=/^[0-9a-f]{64}$/;function objectAt(path,value,keys){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new CatalogLockError(`${path} is not an object.`)}const unknown=Object.keys(value).filter(key=>!keys.includes(key));if(unknown.length>0){throw new CatalogLockError(`${path} carries ${unknown.map(key=>`"${key}"`).join(", ")}, which a lock does not have. A lock is written by catalog:vendor and never edited; re-vendor instead.`)}return value}__name(objectAt,"objectAt");function stringAt(path,value,pattern,expected){if(typeof value!=="string"||value.length===0){throw new CatalogLockError(`${path} is not a non-empty string.`)}if(pattern!==void 0&&!pattern.test(value)){throw new CatalogLockError(`${path} is "${value}", which is not ${expected}.`)}return value}__name(stringAt,"stringAt");function parseCatalogLock(value){const root=objectAt("the lock",value,["schemaVersion","release","actions"]);if(root.schemaVersion!==exports.CATALOG_LOCK_SCHEMA_V1){throw new CatalogLockError(`the lock declares schemaVersion ${JSON.stringify(root.schemaVersion)}; this build reads ${exports.CATALOG_LOCK_SCHEMA_V1} only.`)}const release=objectAt("release",root.release,["artifactRef","digest","version"]);const lock={schemaVersion:exports.CATALOG_LOCK_SCHEMA_V1,release:{artifactRef:stringAt("release.artifactRef",release.artifactRef,catalog_release_1.ARTIFACT_REPOSITORY_PATTERN,"a registry repository"),digest:stringAt("release.digest",release.digest,catalog_release_1.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),version:stringAt("release.version",release.version)},actions:[]};if(!Array.isArray(root.actions)||root.actions.length===0){throw new CatalogLockError("actions is not a non-empty array. A release names at least one action.")}root.actions.forEach((entry,index)=>{const path=`actions[${index}]`;const action=objectAt(path,entry,["key","artifactRef","digest","manifestSha256","provenance","executes","imageDigest"]);const key=stringAt(`${path}.key`,action.key);const artifactRef=stringAt(`${path}.artifactRef`,action.artifactRef,catalog_release_1.ARTIFACT_REPOSITORY_PATTERN,"a registry repository");const misnamed=(0,action_repository_1.actionPackageRefusal)(key,artifactRef);if(misnamed!==null)throw new CatalogLockError(`${path}: ${misnamed}`);const previous=lock.actions[lock.actions.length-1];if(previous!==void 0&&!(previous.key<key)){throw new CatalogLockError(`${path}.key "${key}" follows "${previous.key}": a lock names each action once, sorted by key.`)}const provenance2=objectAt(`${path}.provenance`,action.provenance,["repository","commit"]);if(action.executes===void 0!==(action.imageDigest===void 0)){throw new CatalogLockError(`${path} carries ${action.executes===void 0?"imageDigest without executes":"executes without imageDigest"}; an engine action records both, a built-in neither.`)}if(action.executes!==void 0&&action.executes!==exports.CATALOG_LOCK_ENGINE_EXECUTION){throw new CatalogLockError(`${path}.executes is ${JSON.stringify(action.executes)}; the one value it takes is "${exports.CATALOG_LOCK_ENGINE_EXECUTION}".`)}lock.actions.push({key,artifactRef,digest:stringAt(`${path}.digest`,action.digest,catalog_release_1.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),manifestSha256:stringAt(`${path}.manifestSha256`,action.manifestSha256,exports.MANIFEST_SHA256_PATTERN,"64 lowercase hex characters"),provenance:{repository:stringAt(`${path}.provenance.repository`,provenance2.repository),commit:stringAt(`${path}.provenance.commit`,provenance2.commit)},...action.executes===void 0?{}:{executes:exports.CATALOG_LOCK_ENGINE_EXECUTION,imageDigest:stringAt(`${path}.imageDigest`,action.imageDigest,catalog_release_1.ARTIFACT_DIGEST_PATTERN,"a sha256 digest")}})});return lock}__name(parseCatalogLock,"parseCatalogLock");function catalogLockText(lock){const ordered={schemaVersion:lock.schemaVersion,release:{artifactRef:lock.release.artifactRef,digest:lock.release.digest,version:lock.release.version},actions:[...lock.actions].sort((a,b)=>a.key<b.key?-1:a.key>b.key?1:0).map(action=>({key:action.key,artifactRef:action.artifactRef,digest:action.digest,manifestSha256:action.manifestSha256,provenance:{repository:action.provenance.repository,commit:action.provenance.commit},...action.executes===void 0||action.imageDigest===void 0?{}:{executes:action.executes,imageDigest:action.imageDigest}}))};return`${JSON.stringify(ordered,null,2)}
5
- `}__name(catalogLockText,"catalogLockText");function authoredElsewhere(lock,key){const namespace=lock.release.artifactRef.slice(0,lock.release.artifactRef.lastIndexOf("/"));const organisation=namespace.slice(namespace.lastIndexOf("/")+1);return`${key} is authored in ${organisation}/${(0,action_repository_1.actionRepositoryName)(key)} \u2014 change it there, publish, assemble, vendor`}__name(authoredElsewhere,"authoredElsewhere")}});var require_catalog_manifest_placeholders=__commonJS({"../contracts/dist/catalog-manifest-placeholders.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MANIFEST_PLACEHOLDER_PATTERN=exports.MANIFEST_PLACEHOLDERS=void 0;var brand_1=require_brand();exports.MANIFEST_PLACEHOLDERS={BRAND_SHORT_NAME:brand_1.BRAND_SHORT_NAME,BRAND_NAME:brand_1.BRAND_NAME};exports.MANIFEST_PLACEHOLDER_PATTERN=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g}});var require_change_control=__commonJS({"../contracts/dist/change-control.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CHANGE_CONTROL_REFUSAL_OWNER=exports.CHANGE_CONTROL_REFUSAL_KINDS=exports.CHANGE_RECORD_REQUIREMENT_UNMET=exports.CHANGE_RECORD_REQUIREMENTS=exports.CHANGE_RECORD_ASSURANCE_ESTABLISHED=exports.CHANGE_RECORD_ASSURANCE_REQUIRES=exports.CHANGE_RECORD_ASSURANCE_LABEL=exports.DEFAULT_CHANGE_RECORD_ASSURANCE=exports.CHANGE_RECORD_ASSURANCE=exports.CHANGE_RECORD_AUTHORIZATION=exports.CHANGE_RECORD_TYPE_LABEL=exports.CHANGE_RECORD_TYPES=exports.POLICY_KIND_LABEL=exports.DEFAULT_POLICY_KIND=exports.POLICY_KINDS=void 0;exports.changeRecordEstablishedSentence=changeRecordEstablishedSentence;exports.changeRecordAuthorization=changeRecordAuthorization;exports.changeControlRefusalSentence=changeControlRefusalSentence;exports.changeRecordTypeWord=changeRecordTypeWord;exports.changeRecordTypesPhrase=changeRecordTypesPhrase;exports.changeRecordTypeNoun=changeRecordTypeNoun;var brand_1=require_brand();exports.POLICY_KINDS=["approval","change_control"];exports.DEFAULT_POLICY_KIND="approval";exports.POLICY_KIND_LABEL={approval:"Approval",change_control:"Change control"};exports.CHANGE_RECORD_TYPES=["change_request","incident"];exports.CHANGE_RECORD_TYPE_LABEL={change_request:"Change request",incident:"Incident"};exports.CHANGE_RECORD_AUTHORIZATION={change_request:["approved","permits_work","within_window"],incident:["open"]};exports.CHANGE_RECORD_ASSURANCE=["recorded","verified"];exports.DEFAULT_CHANGE_RECORD_ASSURANCE="verified";exports.CHANGE_RECORD_ASSURANCE_LABEL={recorded:"Recorded",verified:"Verified"};exports.CHANGE_RECORD_ASSURANCE_REQUIRES={recorded:`The run must name a record of an accepted type. ${brand_1.BRAND_SHORT_NAME} records it on the run permanently and does not check it \u2014 nothing is looked up in your system of record.`,verified:`${brand_1.BRAND_SHORT_NAME} looks the record up in your system of record and refuses the run unless it authorizes the work \u2014 re-checked the moment the run starts.`};exports.CHANGE_RECORD_ASSURANCE_ESTABLISHED={recorded:`Recorded on this run. ${brand_1.BRAND_SHORT_NAME} did not check it.`,verified:"Checked with your system of record, which authorized this run."};function changeRecordEstablishedSentence(citation){const declarer=citation.declaredBy??{kind:"run"};const assurance=citation.assurance;if(declarer.kind==="run")return exports.CHANGE_RECORD_ASSURANCE_ESTABLISHED[assurance];const named=declarer.scheduleName?`the schedule \u201C${declarer.scheduleName}\u201D`:"the schedule that fired this run";return assurance==="recorded"?`Declared on ${named}, not named for this run. ${brand_1.BRAND_SHORT_NAME} did not check it.`:`Declared on ${named}, and checked with your system of record when this run started.`}__name(changeRecordEstablishedSentence,"changeRecordEstablishedSentence");exports.CHANGE_RECORD_REQUIREMENTS=["approved","permits_work","within_window","open"];exports.CHANGE_RECORD_REQUIREMENT_UNMET={approved:"it has not been approved",permits_work:"its state does not permit work yet",within_window:"now is outside its planned window",open:"it is no longer open"};function changeRecordAuthorization(facts,now){const unmet=exports.CHANGE_RECORD_AUTHORIZATION[facts.type].filter(requirement=>!requirementMet(requirement,facts,now));return unmet.length===0?{authorized:true}:{authorized:false,unmet}}__name(changeRecordAuthorization,"changeRecordAuthorization");function requirementMet(requirement,facts,now){switch(requirement){case"approved":return facts.approved;case"permits_work":return facts.permitsWork;case"open":return facts.open;case"within_window":return withinWindow(facts.window,now)}}__name(requirementMet,"requirementMet");function withinWindow(window,now){if(!window)return false;const start=Date.parse(window.startsAt);const end=Date.parse(window.endsAt);if(Number.isNaN(start)||Number.isNaN(end))return false;const at=now.getTime();return at>=start&&at<end}__name(withinWindow,"withinWindow");var CHANGE_CONTROL_REFUSAL_KIND_SET={no_reference:true,wrong_type:true,not_found:true,unavailable:true,not_authorizing:true,standing_declaration:true};exports.CHANGE_CONTROL_REFUSAL_KINDS=Object.keys(CHANGE_CONTROL_REFUSAL_KIND_SET);exports.CHANGE_CONTROL_REFUSAL_OWNER={no_reference:"operator",wrong_type:"operator",not_found:"operator",unavailable:"opera",not_authorizing:"record",standing_declaration:"operator"};function changeControlRefusalSentence(refusal,subject={kind:"run"}){const rule=`your governance rule \u201C${refusal.rule.name}\u201D`;switch(refusal.kind){case"no_reference":return subject.kind==="schedule"?`Schedule \u201C${subject.name}\u201D did not fire: it needs ${orList(refusal.recordTypes.map(typeWord))}, because ${rule} matches the runs it starts. Name the record this schedule implements and it fires again at its next occurrence.`:`This run needs ${orList(refusal.recordTypes.map(typeWord))} before it can go ahead: ${rule} requires one. Name the record this run implements and submit again.`;case"wrong_type":return`This run names ${typeWord(refusal.supplied.type)} ${refusal.supplied.reference}, and ${rule} requires ${orList(refusal.recordTypes.map(typeWord))}.`;case"not_found":return`Your system of record has no ${typeNoun(refusal.supplied.type)} ${refusal.supplied.reference}. ${capitalize(rule)} requires one that exists, so nothing was started \u2014 check the reference.`;case"unavailable":return`${brand_1.BRAND_SHORT_NAME} could not reach your system of record to check ${typeWord(refusal.supplied.type)} ${refusal.supplied.reference}, so this run was refused rather than started unchecked (${rule} requires it). There is nothing to fix on the record itself \u2014 the connection reported: ${refusal.detail}`;case"not_authorizing":return`${capitalize(typeWord(refusal.facts.type))} ${refusal.facts.reference} does not authorize this run: ${orList(refusal.unmet.map(requirement=>exports.CHANGE_RECORD_REQUIREMENT_UNMET[requirement]),"and")}. It is ${refusal.facts.stateLabel}${windowClause(refusal)}. ${capitalize(rule)} requires a record that authorizes the work.`;case"standing_declaration":return`${capitalize(scheduleNameClause(refusal.scheduleName))} names ${typeWord(refusal.supplied.type)} ${refusal.supplied.reference} for every occurrence, and ${rule} now requires a record ${brand_1.BRAND_SHORT_NAME} checks when each run starts. A reference named once cannot be that \u2014 a change request authorizes one planned window and this job recurs \u2014 so nothing was started. Either set that rule to Recorded, or run this work attended and name a record each time.`}}__name(changeControlRefusalSentence,"changeControlRefusalSentence");function scheduleNameClause(scheduleName){return scheduleName?`the schedule \u201C${scheduleName}\u201D`:"the schedule that fired this run"}__name(scheduleNameClause,"scheduleNameClause");function windowClause(refusal){if(!refusal.unmet.includes("within_window"))return"";const window=refusal.facts.window;return window?`, and its planned window is ${window.startsAt} to ${window.endsAt}`:", and it names no planned window at all"}__name(windowClause,"windowClause");function changeRecordTypeWord(type){return type==="incident"?"an incident":"a change request"}__name(changeRecordTypeWord,"changeRecordTypeWord");function changeRecordTypesPhrase(types){return orList(types.map(changeRecordTypeWord))}__name(changeRecordTypesPhrase,"changeRecordTypesPhrase");function changeRecordTypeNoun(type){return type==="incident"?"incident":"change request"}__name(changeRecordTypeNoun,"changeRecordTypeNoun");var typeWord=changeRecordTypeWord;var typeNoun=changeRecordTypeNoun;function orList(values,conjunction="or"){if(values.length<=1)return values[0]??"";return`${values.slice(0,-1).join(", ")} ${conjunction} ${values[values.length-1]}`}__name(orList,"orList");function capitalize(value){return value.charAt(0).toUpperCase()+value.slice(1)}__name(capitalize,"capitalize")}});var require_run_placement=__commonJS({"../contracts/dist/run-placement.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HOSTED_EXECUTION_LABEL=exports.RUN_PLACEMENTS=exports.EXECUTION_SITES=void 0;exports.isExecutionSite=isExecutionSite;exports.EXECUTION_SITES=["hosted","runner","unknown"];function isExecutionSite(value){return exports.EXECUTION_SITES.includes(value)}__name(isExecutionSite,"isExecutionSite");exports.RUN_PLACEMENTS=["hosted","runner"];exports.HOSTED_EXECUTION_LABEL="our hosted cloud"}});var require_package_provenance=__commonJS({"../contracts/dist/package-provenance.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POOL_PROVENANCE_AUDIT_ACTION_NAMES=exports.POOL_PROVENANCE_AUDIT_ACTIONS=exports.PACKAGE_PROVENANCE_DISCLOSURES=exports.PACKAGE_PROVENANCE_CLAUSES=exports.PACKAGE_PROVENANCE_LABELS=exports.PACKAGE_PROVENANCE_IS_REVOCABLE=exports.PACKAGE_PROVENANCE_KINDS=void 0;exports.poolProvenanceAuditAction=poolProvenanceAuditAction;var brand_1=require_brand();exports.PACKAGE_PROVENANCE_KINDS=["git_source","public_git","authored"];exports.PACKAGE_PROVENANCE_IS_REVOCABLE={git_source:true,public_git:false,authored:false};exports.PACKAGE_PROVENANCE_LABELS={git_source:"Imported from Git",public_git:"Imported from a public repository",authored:`Authored in ${brand_1.BRAND_SHORT_NAME}`};exports.PACKAGE_PROVENANCE_CLAUSES={git_source:"imported from Git",public_git:"imported from a public repository",authored:`authored in ${brand_1.BRAND_SHORT_NAME}`};exports.PACKAGE_PROVENANCE_DISCLOSURES={git_source:"imported from a Git repository your organisation connected. Connecting a repository says who it belongs to; it does not say anybody reviewed what is in it.",public_git:`imported from a public repository. Neither ${brand_1.BRAND_SHORT_NAME} nor your organisation wrote it, and nobody vouched for it when it was imported.`,authored:`written in ${brand_1.BRAND_SHORT_NAME} by a named member of your organisation, and pinned to the exact bytes they published.`};exports.POOL_PROVENANCE_AUDIT_ACTIONS={git_source:{accepted:"runner.pool.accepted_git_source",revoked:"runner.pool.revoked_git_source"},public_git:{accepted:"runner.pool.accepted_public_git",revoked:"runner.pool.revoked_public_git"},authored:{accepted:"runner.pool.accepted_authored",revoked:"runner.pool.revoked_authored"}};exports.POOL_PROVENANCE_AUDIT_ACTION_NAMES=Object.values(exports.POOL_PROVENANCE_AUDIT_ACTIONS).flatMap(pair=>[pair.accepted,pair.revoked]);function poolProvenanceAuditAction(provenance2,accepted){const pair=exports.POOL_PROVENANCE_AUDIT_ACTIONS[provenance2];return accepted?pair.accepted:pair.revoked}__name(poolProvenanceAuditAction,"poolProvenanceAuditAction")}});var require_package_tier=__commonJS({"../contracts/dist/package-tier.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PACKAGE_TIER_LABELS=exports.PACKAGE_TIER_CLAIMS=void 0;var brand_1=require_brand();exports.PACKAGE_TIER_CLAIMS={official:`${brand_1.BRAND_SHORT_NAME} wrote and maintains this action.`,partner:"Published by a named partner under agreement, with a security contact.",verified:"Automated checks passed. Nobody reviewed the code.",community:"Published by anyone. Nobody vouches for it.",organization:"Authored inside this workspace by one of its own admins."};exports.PACKAGE_TIER_LABELS={official:"Official",partner:"Partner",verified:"Verified",community:"Community",organization:"Workspace"}}});var require_packages=__commonJS({"../contracts/dist/packages.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:__name(function(){return m[k]},"get")}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]});var __exportStar=exports&&exports.__exportStar||function(m,exports1){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports1,p))__createBinding(exports1,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.PACKAGE_IMPORT_WARNING_REASONS=exports.PACKAGE_IMPORT_SKIP_REASON_LABELS=exports.PACKAGE_IMPORT_SKIP_REASONS=exports.PACKAGE_IMPORT_LIMITS=exports.PACKAGE_DRAFT_FILTER_LABELS=exports.PACKAGE_DRAFT_FILTERS=exports.PACKAGE_INTERPRETER_LABEL=exports.PARAMETER_DETECTION_UNAVAILABLE=exports.PARAMETER_DETECTION_SOURCES=exports.PACKAGE_PARAMETERS_UNRESOLVED_COPY=exports.PACKAGE_PARAMETERS_UNRESOLVED_REASONS=exports.PACKAGE_DRAFT_STATES=exports.PACKAGE_VERSION_MODES=exports.ACTION_UNRUNNABLE_REASONS=exports.PACKAGE_SOURCE_RECONNECT_OUTCOMES=exports.ADOPTION_REVIEW_DIRECTIONS=exports.ADOPTION_CHANGE_SEVERITY=exports.ADOPTION_CHANGE_KINDS=exports.ADOPTION_CHANGE_SEVERITIES=exports.ADOPTION_STATUSES=exports.PACKAGE_INTERPRETERS=exports.PACKAGE_RUNTIME_KINDS=exports.LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY=exports.PACKAGE_RUNNER_CONNECTOR_KEY=void 0;exports.isPackageRunnerConnectorKey=isPackageRunnerConnectorKey;exports.canonicalConnectorKey=canonicalConnectorKey;exports.packageSourceConnectedRemovalMessage=packageSourceConnectedRemovalMessage;exports.packageVersionAdoptedRemovalMessage=packageVersionAdoptedRemovalMessage;exports.actionUnrunnableCopy=actionUnrunnableCopy;exports.actionUnrunnableHeadline=actionUnrunnableHeadline;exports.actionUnrunnableRefusal=actionUnrunnableRefusal;exports.trialSemanticVersion=trialSemanticVersion;exports.parameterDetectionConsequence=parameterDetectionConsequence;__exportStar(require_package_provenance(),exports);__exportStar(require_package_tier(),exports);var brand_1=require_brand();exports.PACKAGE_RUNNER_CONNECTOR_KEY="runveric.package-runner";exports.LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY="opera.package-runner";function isPackageRunnerConnectorKey(connectorKey){return connectorKey===exports.PACKAGE_RUNNER_CONNECTOR_KEY||connectorKey===exports.LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY}__name(isPackageRunnerConnectorKey,"isPackageRunnerConnectorKey");function canonicalConnectorKey(connectorKey){return isPackageRunnerConnectorKey(connectorKey)?exports.PACKAGE_RUNNER_CONNECTOR_KEY:connectorKey}__name(canonicalConnectorKey,"canonicalConnectorKey");exports.PACKAGE_RUNTIME_KINDS=["interpreter","oci"];exports.PACKAGE_INTERPRETERS=["powershell","bash","python"];exports.ADOPTION_STATUSES=["draft","published","decommissioned"];exports.ADOPTION_CHANGE_SEVERITIES=["privilege_increase","safety_reduction","code_changed","privilege_decrease","metadata"];exports.ADOPTION_CHANGE_KINDS=["permission_added","permission_scope_widened","egress_host_added","network_enabled","secret_added","credential_scope_added","version_contract_violation","rollback_removed","dry_run_removed","idempotency_removed","validate_entrypoint_removed","timeout_increased","content_digest_changed","runtime_kind_changed","runtime_image_changed","runtime_interpreter_changed","entrypoint_changed","rollback_entrypoint_changed","validate_entrypoint_changed","permission_removed","permission_scope_narrowed","egress_host_removed","network_disabled","secret_removed","credential_scope_removed","timeout_decreased","capability_added","source_repo_changed","git_commit_changed","tier_changed"];exports.ADOPTION_CHANGE_SEVERITY={permission_added:"privilege_increase",permission_scope_widened:"privilege_increase",egress_host_added:"privilege_increase",network_enabled:"privilege_increase",secret_added:"privilege_increase",credential_scope_added:"privilege_increase",version_contract_violation:"privilege_increase",rollback_removed:"safety_reduction",dry_run_removed:"safety_reduction",idempotency_removed:"safety_reduction",validate_entrypoint_removed:"safety_reduction",timeout_increased:"safety_reduction",content_digest_changed:"code_changed",runtime_kind_changed:"code_changed",runtime_image_changed:"code_changed",runtime_interpreter_changed:"code_changed",entrypoint_changed:"code_changed",rollback_entrypoint_changed:"code_changed",validate_entrypoint_changed:"code_changed",permission_removed:"privilege_decrease",permission_scope_narrowed:"privilege_decrease",egress_host_removed:"privilege_decrease",network_disabled:"privilege_decrease",secret_removed:"privilege_decrease",credential_scope_removed:"privilege_decrease",timeout_decreased:"privilege_decrease",capability_added:"metadata",source_repo_changed:"code_changed",git_commit_changed:"metadata",tier_changed:"metadata"};exports.ADOPTION_REVIEW_DIRECTIONS=["upgrade","downgrade","same"];function packageSourceConnectedRemovalMessage(){return"This source is still connected, so removing it would silently drop a live GitHub App installation. Disconnect it first, then remove it."}__name(packageSourceConnectedRemovalMessage,"packageSourceConnectedRemovalMessage");exports.PACKAGE_SOURCE_RECONNECT_OUTCOMES=["reconnected","reinstall_required"];function packageVersionAdoptedRemovalMessage(adoption){return`This version cannot be removed while an action still adopts it: adoption ${adoption.id} is ${adoption.status}. Decommission that adoption first \u2014 then this version can be removed.`}__name(packageVersionAdoptedRemovalMessage,"packageVersionAdoptedRemovalMessage");exports.ACTION_UNRUNNABLE_REASONS=["runtime_kind","interpreter_unavailable","runtime_unavailable","egress_unconfigurable","source_disconnected","source_removed","not_trusted"];var RUNTIME_KIND_NAMES={interpreter:"interpreter",oci:"OCI image"};function anArticle(noun){return`${/^[aeiou]/i.test(noun)?"an":"a"} ${noun}`}__name(anArticle,"anArticle");function supportedInterpreterRemedy(available){const deploy="an administrator has to deploy a runner that provides the one this package needs.";if(available.length===0){return`This deployment runs no package interpreter at all, so ${deploy}`}const list=available.length===1?available[0]:`${available.slice(0,-1).join(", ")} and ${available[available.length-1]}`;return`This deployment runs ${list}. A package has to be published for one of those, or ${deploy}`}__name(supportedInterpreterRemedy,"supportedInterpreterRemedy");function unrunnableClauses(detail){switch(detail.reason){case"runtime_kind":return{cause:`runs as ${anArticle(RUNTIME_KIND_NAMES[detail.runtimeKind])}, which ${brand_1.BRAND_SHORT_NAME} cannot execute yet.`,remedy:"Nothing is wrong with your setup \u2014 the package has to be published for a runtime this deployment supports."};case"interpreter_unavailable":return{cause:`is written for ${detail.interpreter}, which no runner on this deployment executes.`,remedy:supportedInterpreterRemedy(detail.available)};case"runtime_unavailable":return{cause:`has to run under the "${detail.isolation}" isolation, and this deployment provides no runner for it.`,remedy:"Nothing about the package or its Git source needs to change \u2014 an administrator has to configure that runner before any package routed to it can run."};case"egress_unconfigurable":return{cause:`declares outbound network access, and this deployment has no way to broker it under the "${detail.isolation}" isolation.`,remedy:"A package that declares network is never run without its allowlist in force, so an administrator has to configure the egress proxy for that runner first."};case"source_disconnected":return{cause:`came from the Git source ${detail.sourceAccount}, which is disconnected, so ${brand_1.BRAND_SHORT_NAME} can no longer vouch for where its code came from.`,remedy:"Reconnecting that source is all it takes \u2014 nothing has to be re-imported."};case"source_removed":return{cause:`came from the Git source ${detail.sourceAccount}, and that connection has been removed, so ${brand_1.BRAND_SHORT_NAME} can no longer vouch for where its code came from.`,remedy:"Re-import the package through a live Git source to run it again."};case"not_trusted":return{cause:"is not allowlisted for trusted execution, and this deployment does not run untrusted packages.",remedy:"Ask an administrator to allowlist this package for trusted execution."}}}__name(unrunnableClauses,"unrunnableClauses");function actionUnrunnableCopy(detail){const{cause,remedy}=unrunnableClauses(detail);return`This action's package ${cause} ${remedy}`}__name(actionUnrunnableCopy,"actionUnrunnableCopy");function actionUnrunnableHeadline(detail){switch(detail.reason){case"runtime_kind":return`its package runs as ${anArticle(RUNTIME_KIND_NAMES[detail.runtimeKind])}, which ${brand_1.BRAND_SHORT_NAME} cannot execute`;case"interpreter_unavailable":return`its package is written for ${detail.interpreter}, which no runner here executes`;case"runtime_unavailable":return`this deployment provides no "${detail.isolation}" runner for its package`;case"egress_unconfigurable":return`its package needs outbound network and the "${detail.isolation}" runner here has no egress proxy`;case"source_disconnected":return`its package's Git source ${detail.sourceAccount} is disconnected`;case"source_removed":return`its package's Git source ${detail.sourceAccount} has been removed`;case"not_trusted":return"its package is not allowlisted for trusted execution"}}__name(actionUnrunnableHeadline,"actionUnrunnableHeadline");function actionUnrunnableRefusal(detail,pkg){const{cause,remedy}=unrunnableClauses(detail);return`Package ${pkg.packageId} from ${pkg.sourceRepo} ${cause} ${remedy} Nothing was started.`}__name(actionUnrunnableRefusal,"actionUnrunnableRefusal");exports.PACKAGE_VERSION_MODES=["trial","release"];var TRIAL_DIGEST_LENGTH=12;function trialSemanticVersion(manifestVersion,contentDigest){return`${manifestVersion}+trial.${contentDigest.slice(0,TRIAL_DIGEST_LENGTH)}`}__name(trialSemanticVersion,"trialSemanticVersion");exports.PACKAGE_DRAFT_STATES=["draft","published","superseded"];exports.PACKAGE_PARAMETERS_UNRESOLVED_REASONS=["manifest_missing","manifest_unparseable","parameters_ref_missing","parameters_ref_unsafe"];exports.PACKAGE_PARAMETERS_UNRESOLVED_COPY={manifest_missing:{headline:"This package has no action.yaml.",fix:"Every package needs one \u2014 it is the file that declares which file holds the parameters. Add it in the Files tab."},manifest_unparseable:{headline:"action.yaml cannot be read.",fix:"It is not valid YAML, so nothing can tell which file holds the parameters. Fix it in the Files tab and this returns."},parameters_ref_missing:{headline:"action.yaml does not declare parametersRef.",fix:"Add `parametersRef: parameters.json` \u2014 the path, relative to the package root, of the file that holds the parameters."},parameters_ref_unsafe:{headline:"action.yaml's parametersRef is not a safe package path.",fix:"It must be relative to the package root, use forward slashes, and contain no `.` or `..` segments."}};exports.PARAMETER_DETECTION_SOURCES=["powershell_param","none"];exports.PARAMETER_DETECTION_UNAVAILABLE={powershell:null,bash:"Bash has no parameter declaration to read, so you will define these yourself.",python:`${brand_1.BRAND_SHORT_NAME} cannot read Python parameters yet \u2014 argparse detection is not built. Define these yourself for now.`};function parameterDetectionConsequence(interpreter){return exports.PARAMETER_DETECTION_UNAVAILABLE[interpreter]===null?`${brand_1.BRAND_SHORT_NAME} reads your parameters from your script.`:"You define your parameters yourself."}__name(parameterDetectionConsequence,"parameterDetectionConsequence");exports.PACKAGE_INTERPRETER_LABEL={powershell:"PowerShell",bash:"Bash",python:"Python"};exports.PACKAGE_DRAFT_FILTERS=["never_published","published","unpublished_changes","superseded"];exports.PACKAGE_DRAFT_FILTER_LABELS={never_published:"Never published",published:"Published",unpublished_changes:"Unpublished changes",superseded:"Superseded"};exports.PACKAGE_IMPORT_LIMITS={maxFileBytes:1024*1024,maxTotalBytes:5*1024*1024,maxFiles:200,maxInspectFiles:2e3,maxInspectBytes:20*1024*1024};exports.PACKAGE_IMPORT_SKIP_REASONS=["version_control","dependencies","build_output","editor_metadata","os_metadata","lockfile","runveric_scratch","not_text"];exports.PACKAGE_IMPORT_SKIP_REASON_LABELS={version_control:"version-control metadata",dependencies:"dependencies are not part of a package",build_output:"build output",editor_metadata:"editor settings",os_metadata:"operating-system metadata",lockfile:"a dependency lockfile",runveric_scratch:"scratch written by `runveric test`",not_text:"not UTF-8 text"};exports.PACKAGE_IMPORT_WARNING_REASONS=["mixed_interpreter"]}});var require_validation=__commonJS({"../contracts/dist/validation.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TARGET_COMPARISON_KINDS=exports.DECISION_CODES=exports.REFUSAL_CODES=exports.CHECK_LEVELS=exports.TARGETS_NO_SCOPE=exports.TARGETS_NOT_COUNTED=exports.TARGET_COUNT_ABSENCES=void 0;exports.isTargetCountAbsence=isTargetCountAbsence;exports.singleTarget=singleTarget;exports.noTargetsResolved=noTargetsResolved;exports.targetsUnavailable=targetsUnavailable;exports.targetSummarySentence=targetSummarySentence;exports.targetSummaryLabel=targetSummaryLabel;exports.eligibleTargetCount=eligibleTargetCount;exports.targetsValidationCheck=targetsValidationCheck;exports.targetSummaryOf=targetSummaryOf;exports.isCheckLevel=isCheckLevel;exports.isRefusalCode=isRefusalCode;exports.isDecisionCode=isDecisionCode;exports.validationCheckOf=validationCheckOf;exports.scopeFailureDetail=scopeFailureDetail;exports.targetsUnavailableFrom=targetsUnavailableFrom;exports.compareTargets=compareTargets;exports.targetComparisonSentence=targetComparisonSentence;exports.targetComparisonLabel=targetComparisonLabel;exports.targetComparisonLevel=targetComparisonLevel;var brand_1=require_brand();exports.TARGET_COUNT_ABSENCES=["no_scope","unavailable","not_attempted"];function isTargetCountAbsence(value){return typeof value==="string"&&exports.TARGET_COUNT_ABSENCES.includes(value)}__name(isTargetCountAbsence,"isTargetCountAbsence");function singleTarget(){return{eligible:1,excluded:0,blocked:0}}__name(singleTarget,"singleTarget");function noTargetsResolved(){return{eligible:0,excluded:0,blocked:0}}__name(noTargetsResolved,"noTargetsResolved");exports.TARGETS_NOT_COUNTED={uncounted:"not_attempted"};exports.TARGETS_NO_SCOPE={uncounted:"no_scope"};function targetsUnavailable(detail){return{uncounted:"unavailable",detail}}__name(targetsUnavailable,"targetsUnavailable");function targetSummarySentence(summary){if(!summary.uncounted){return`${summary.eligible} eligible ${summary.eligible===1?"target":"targets"}`}switch(summary.uncounted){case"no_scope":return`No scope for ${brand_1.BRAND_SHORT_NAME} to count`;case"unavailable":return summary.detail?`Targets could not be counted \u2014 ${summary.detail}`:"Targets could not be counted";case"not_attempted":return"Targets not counted"}}__name(targetSummarySentence,"targetSummarySentence");function targetSummaryLabel(summary){if(!summary.uncounted)return`${summary.eligible} eligible`;switch(summary.uncounted){case"no_scope":return"None to count";case"unavailable":return"Could not count";case"not_attempted":return"Not counted"}}__name(targetSummaryLabel,"targetSummaryLabel");function eligibleTargetCount(summary){return summary.uncounted?null:summary.eligible}__name(eligibleTargetCount,"eligibleTargetCount");function targetsValidationCheck(summary){if(!summary.uncounted){return{level:"info",title:`Scope resolved \u2014 ${targetSummarySentence(summary)}.`}}if(summary.uncounted==="no_scope"){return{level:"info",title:`This action has no scope for ${brand_1.BRAND_SHORT_NAME} to count \u2014 it acts on what it declares.`}}return{level:"warn",title:`${targetSummarySentence(summary)}. The run can still be submitted.`}}__name(targetsValidationCheck,"targetsValidationCheck");function targetSummaryOf(stored){if(typeof stored!=="object"||stored===null)return exports.TARGETS_NOT_COUNTED;const value=stored;if(value.uncounted!==void 0){return isTargetCountAbsence(value.uncounted)?{uncounted:value.uncounted,...typeof value.detail==="string"?{detail:value.detail}:{}}:exports.TARGETS_NOT_COUNTED}const{eligible,excluded,blocked}=value;if(typeof eligible==="number"&&typeof excluded==="number"&&typeof blocked==="number"){return{eligible,excluded,blocked}}return exports.TARGETS_NOT_COUNTED}__name(targetSummaryOf,"targetSummaryOf");exports.CHECK_LEVELS=["info","warn","error"];function isCheckLevel(value){return typeof value==="string"&&exports.CHECK_LEVELS.includes(value)}__name(isCheckLevel,"isCheckLevel");exports.REFUSAL_CODES=["disk.notUnattached","disk.locked","disk.shared","disk.inRecoveryPlan","disk.keyUnusable","disk.unverifiable"];function isRefusalCode(value){return typeof value==="string"&&exports.REFUSAL_CODES.includes(value)}__name(isRefusalCode,"isRefusalCode");exports.DECISION_CODES=["disk.recentlyDetached","disk.customerKey","disk.customerKeyUnverified","disk.guestEncrypted","disk.noSnapshot","disk.confidential"];function isDecisionCode(value){return typeof value==="string"&&exports.DECISION_CODES.includes(value)}__name(isDecisionCode,"isDecisionCode");function validationCheckOf(value){const raw=typeof value==="object"&&value!==null?value:{};const level=raw.level;if(!isCheckLevel(level)){return{refusal:`A check level of "${String(level)}" is not in the vocabulary.`}}if(typeof raw.title!=="string"||raw.title.length===0){return{refusal:"Every check must carry a title."}}if(raw.decision!==void 0&&raw.refusal!==void 0){return{refusal:`A check carrying both a decision ("${String(raw.decision)}") and a refusal ("${String(raw.refusal)}") is not a check any producer of ours can build.`}}if(raw.decision!==void 0){if(!isDecisionCode(raw.decision)||level==="info"){return{refusal:`A check's decision of "${String(raw.decision)}" at level "${level}" is not one this channel accepts.`}}return{check:{level,title:raw.title,decision:raw.decision}}}if(raw.refusal!==void 0){if(!isRefusalCode(raw.refusal)||level!=="error"){return{refusal:`A check's refusal of "${String(raw.refusal)}" at level "${level}" is not one this channel accepts.`}}return{check:{level,title:raw.title,refusal:raw.refusal}}}return{check:{level,title:raw.title}}}__name(validationCheckOf,"validationCheckOf");function scopeFailureDetail(error){const raw=error instanceof Error?error.message:String(error);const oneLine=raw.replace(/\s+/g," ").trim().replace(/[.!]+$/,"");if(oneLine.length===0)return"the connector refused without saying why";return oneLine.length>180?`${oneLine.slice(0,179)}\u2026`:oneLine}__name(scopeFailureDetail,"scopeFailureDetail");function targetsUnavailableFrom(error){return targetsUnavailable(scopeFailureDetail(error))}__name(targetsUnavailableFrom,"targetsUnavailableFrom");exports.TARGET_COMPARISON_KINDS=["matched","drifted","unconfirmed","unpromised"];function compareTargets(promised,touched){if(promised.uncounted)return{kind:"unpromised",promised,touched};if(touched.uncounted)return{kind:"unconfirmed",promised,touched};return{kind:promised.eligible===touched.eligible?"matched":"drifted",promised,touched}}__name(compareTargets,"compareTargets");function targetComparisonSentence(comparison){switch(comparison.kind){case"matched":return`The run acted on what was approved \u2014 ${targetSummarySentence(comparison.promised)}.`;case"drifted":return`Approved for ${targetSummarySentence(comparison.promised)}; the run acted on ${comparison.touched.eligible}.`;case"unconfirmed":{const because=comparison.touched.detail?` \u2014 ${comparison.touched.detail}`:"";return`Approved for ${targetSummarySentence(comparison.promised)}. The run did not record what it acted on${because}.`}case"unpromised":if(comparison.promised.uncounted==="no_scope")return null;if(comparison.touched.uncounted)return null;return`No target count was approved for this run; it acted on ${targetSummarySentence(comparison.touched)}.`}}__name(targetComparisonSentence,"targetComparisonSentence");function targetComparisonLabel(comparison){return comparison.kind==="drifted"?"Targets drifted":null}__name(targetComparisonLabel,"targetComparisonLabel");function targetComparisonLevel(comparison){return comparison.kind==="drifted"?"warn":"info"}__name(targetComparisonLevel,"targetComparisonLevel")}});var require_execution=__commonJS({"../contracts/dist/execution.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ACCEPTING_A_PROVENANCE_IS_NOT_A_CAPABILITY=exports.RUNNER_PACKAGE_RUNTIME_NOT_PINNED=exports.CONNECTOR_UNAVAILABLE_MESSAGE=exports.ACTION_RUNNABILITY_CAUSE_KINDS=exports.EXECUTION_LOG_ACTIVITY_PHRASE=exports.EXECUTION_LOG_CONNECTION_PHRASE=exports.EXECUTION_LOG_STREAM_PHASES=exports.EXECUTION_LOG_ACTIVITIES=exports.validationCheckOf=exports.targetsValidationCheck=exports.targetSummarySentence=exports.targetSummaryOf=exports.targetSummaryLabel=exports.targetsUnavailableFrom=exports.targetsUnavailable=exports.targetComparisonSentence=exports.targetComparisonLevel=exports.targetComparisonLabel=exports.TARGETS_NOT_COUNTED=exports.TARGETS_NO_SCOPE=exports.TARGET_COUNT_ABSENCES=exports.TARGET_COMPARISON_KINDS=exports.singleTarget=exports.scopeFailureDetail=exports.noTargetsResolved=exports.isTargetCountAbsence=exports.eligibleTargetCount=exports.compareTargets=exports.REFUSAL_CODES=exports.isRefusalCode=exports.isDecisionCode=exports.isCheckLevel=exports.DECISION_CODES=exports.CHECK_LEVELS=exports.SUBSCRIPTION_ID_FIELD_RENAMED=void 0;exports.executionLogStreamSentence=executionLogStreamSentence;exports.actionRunnabilityCopy=actionRunnabilityCopy;exports.actionRunnabilityHeadline=actionRunnabilityHeadline;exports.actionRunnabilityRefusal=actionRunnabilityRefusal;var run_placement_1=require_run_placement();var packages_1=require_packages();var packages_2=require_packages();var brand_1=require_brand();exports.SUBSCRIPTION_ID_FIELD_RENAMED="`subscriptionId` is not accepted on this route. It named an `azure_subscription.id` while this route has always resolved a `connection_scope.id`. The two were the same value while one shim gave a scope the registry row's id; a scope discovered since has an id of its own, and the registry id is either nobody's scope or another connector's. Send `connectionScopeId` \u2014 the value `ExecutionDto.connectionScopeId` reports for a run.";var validation_1=require_validation();Object.defineProperty(exports,"CHECK_LEVELS",{enumerable:true,get:__name(function(){return validation_1.CHECK_LEVELS},"get")});Object.defineProperty(exports,"DECISION_CODES",{enumerable:true,get:__name(function(){return validation_1.DECISION_CODES},"get")});Object.defineProperty(exports,"isCheckLevel",{enumerable:true,get:__name(function(){return validation_1.isCheckLevel},"get")});Object.defineProperty(exports,"isDecisionCode",{enumerable:true,get:__name(function(){return validation_1.isDecisionCode},"get")});Object.defineProperty(exports,"isRefusalCode",{enumerable:true,get:__name(function(){return validation_1.isRefusalCode},"get")});Object.defineProperty(exports,"REFUSAL_CODES",{enumerable:true,get:__name(function(){return validation_1.REFUSAL_CODES},"get")});Object.defineProperty(exports,"compareTargets",{enumerable:true,get:__name(function(){return validation_1.compareTargets},"get")});Object.defineProperty(exports,"eligibleTargetCount",{enumerable:true,get:__name(function(){return validation_1.eligibleTargetCount},"get")});Object.defineProperty(exports,"isTargetCountAbsence",{enumerable:true,get:__name(function(){return validation_1.isTargetCountAbsence},"get")});Object.defineProperty(exports,"noTargetsResolved",{enumerable:true,get:__name(function(){return validation_1.noTargetsResolved},"get")});Object.defineProperty(exports,"scopeFailureDetail",{enumerable:true,get:__name(function(){return validation_1.scopeFailureDetail},"get")});Object.defineProperty(exports,"singleTarget",{enumerable:true,get:__name(function(){return validation_1.singleTarget},"get")});Object.defineProperty(exports,"TARGET_COMPARISON_KINDS",{enumerable:true,get:__name(function(){return validation_1.TARGET_COMPARISON_KINDS},"get")});Object.defineProperty(exports,"TARGET_COUNT_ABSENCES",{enumerable:true,get:__name(function(){return validation_1.TARGET_COUNT_ABSENCES},"get")});Object.defineProperty(exports,"TARGETS_NO_SCOPE",{enumerable:true,get:__name(function(){return validation_1.TARGETS_NO_SCOPE},"get")});Object.defineProperty(exports,"TARGETS_NOT_COUNTED",{enumerable:true,get:__name(function(){return validation_1.TARGETS_NOT_COUNTED},"get")});Object.defineProperty(exports,"targetComparisonLabel",{enumerable:true,get:__name(function(){return validation_1.targetComparisonLabel},"get")});Object.defineProperty(exports,"targetComparisonLevel",{enumerable:true,get:__name(function(){return validation_1.targetComparisonLevel},"get")});Object.defineProperty(exports,"targetComparisonSentence",{enumerable:true,get:__name(function(){return validation_1.targetComparisonSentence},"get")});Object.defineProperty(exports,"targetsUnavailable",{enumerable:true,get:__name(function(){return validation_1.targetsUnavailable},"get")});Object.defineProperty(exports,"targetsUnavailableFrom",{enumerable:true,get:__name(function(){return validation_1.targetsUnavailableFrom},"get")});Object.defineProperty(exports,"targetSummaryLabel",{enumerable:true,get:__name(function(){return validation_1.targetSummaryLabel},"get")});Object.defineProperty(exports,"targetSummaryOf",{enumerable:true,get:__name(function(){return validation_1.targetSummaryOf},"get")});Object.defineProperty(exports,"targetSummarySentence",{enumerable:true,get:__name(function(){return validation_1.targetSummarySentence},"get")});Object.defineProperty(exports,"targetsValidationCheck",{enumerable:true,get:__name(function(){return validation_1.targetsValidationCheck},"get")});Object.defineProperty(exports,"validationCheckOf",{enumerable:true,get:__name(function(){return validation_1.validationCheckOf},"get")});exports.EXECUTION_LOG_ACTIVITIES=["executing","queued","awaiting_runner","awaiting_approval"];exports.EXECUTION_LOG_STREAM_PHASES=["reconnecting","stopped"];exports.EXECUTION_LOG_CONNECTION_PHRASE={reconnecting:"The live connection dropped, so this log has paused. It is reconnecting on its own.",stopped:"The live connection dropped and could not be restored, so this log has stopped updating."};exports.EXECUTION_LOG_ACTIVITY_PHRASE={executing:"The run itself is unaffected \u2014 it is still executing on the server.",queued:"The run has not started yet \u2014 it is waiting in the queue to be picked up.",awaiting_runner:"The run has not started yet \u2014 it is waiting for one of your runners to pick it up.",awaiting_approval:"The run has not started yet \u2014 it is waiting for a person to approve it."};function executionLogStreamSentence(phase,activity){return`${exports.EXECUTION_LOG_CONNECTION_PHRASE[phase]} ${exports.EXECUTION_LOG_ACTIVITY_PHRASE[activity]}`}__name(executionLogStreamSentence,"executionLogStreamSentence");var ACTION_RUNNABILITY_CAUSE_KIND_SET={catalog_blocked:true,beta_not_allowed:true,connector_unregistered:true,package:true,runner_pool:true,runner_image:true,runner_egress:true,runner_pool_ambiguous:true};exports.ACTION_RUNNABILITY_CAUSE_KINDS=Object.keys(ACTION_RUNNABILITY_CAUSE_KIND_SET);exports.CONNECTOR_UNAVAILABLE_MESSAGE="This action is not yet available to run.";var CATALOG_BLOCKED_CAUSE="This workspace does not permit this action.";var CATALOG_BLOCKED_REMEDY="An administrator of this workspace decides which catalog actions may run here, and can allow it.";var BETA_NOT_ALLOWED_CAUSE="This version is a beta, and this workspace has not allowed beta actions.";var BETA_NOT_ALLOWED_REMEDY="A workspace administrator can allow beta actions in Settings \u2192 Catalog.";function actionRunnabilityCopy(cause){switch(cause.kind){case"catalog_blocked":return`${CATALOG_BLOCKED_CAUSE} ${CATALOG_BLOCKED_REMEDY}`;case"beta_not_allowed":return`${BETA_NOT_ALLOWED_CAUSE} ${BETA_NOT_ALLOWED_REMEDY}`;case"package":return(0,packages_2.actionUnrunnableCopy)(cause.detail);case"runner_pool":{const{cause:why,remedy}=runnerPoolClauses(cause);return`This action's package ${why} ${remedy}`}case"runner_image":{const{cause:why,remedy}=runnerImageClauses(cause);return`${why} ${remedy}`}case"runner_egress":{const{cause:why,remedy}=runnerEgressClauses(cause);return`${why} ${remedy}`}case"runner_pool_ambiguous":return`This run's resources do not all execute in the same place: ${describeRoutingPlaces(cause.places)}. ${AMBIGUOUS_ROUTING_REMEDY}`;case"connector_unregistered":return exports.CONNECTOR_UNAVAILABLE_MESSAGE}}__name(actionRunnabilityCopy,"actionRunnabilityCopy");var AMBIGUOUS_ROUTING_REMEDY="Nothing was started \u2014 a run is recorded as having executed in ONE place, and splitting it would make that record untrue. Narrow the targets so they route together, and run each group separately.";function describeRoutingPlaces(places){return places.map(place=>{const where=place.poolName?`runner pool \u201C${place.poolName}\u201D`:run_placement_1.HOSTED_EXECUTION_LABEL;const why=place.ruleName?`the rule \u201C${place.ruleName}\u201D`:"this connection's default";return`${place.targetCount} via ${why} \u2192 ${where} (for example ${place.exampleResourceId})`}).join("; ")}__name(describeRoutingPlaces,"describeRoutingPlaces");function runnerPoolClauses(cause){const provenance2=cause.provenance?`is ${packages_1.PACKAGE_PROVENANCE_CLAUSES[cause.provenance]}`:"has no recorded provenance";return{cause:`${provenance2}, and would run on the private runner pool "${cause.poolName}", because that is where runs using this connection execute \u2014 on a machine you own, in a container that shares its host's kernel and acts with this connection's credential.`,remedy:`${acceptedClause(cause.accepts)} ${POOL_CONSENT_REMEDY}`}}__name(runnerPoolClauses,"runnerPoolClauses");function acceptedClause(accepts){if(accepts.length===0){return"This pool does not accept action packages of any provenance."}const labels=accepts.map(kind=>`\u201C${packages_1.PACKAGE_PROVENANCE_LABELS[kind]}\u201D`);return`This pool accepts ${joinWithAnd(labels)}, but not this package's provenance.`}__name(acceptedClause,"acceptedClause");function joinWithAnd(parts){if(parts.length<=1)return parts[0]??"";return`${parts.slice(0,-1).join(", ")} and ${parts[parts.length-1]}`}__name(joinWithAnd,"joinWithAnd");exports.RUNNER_PACKAGE_RUNTIME_NOT_PINNED="This deployment has not pinned a package runtime image, so its runners are installed without one and no action package can execute on a runner here.";exports.ACCEPTING_A_PROVENANCE_IS_NOT_A_CAPABILITY="Accepting a provenance decides WHOSE code may run on your machines; it does not decide whether a runner is able to run it.";function runnerImageClauses(cause){const where=`would run on the private runner pool \u201C${cause.poolName}\u201D, because that is where runs using this connection execute`;return{cause:`This action's connector ${where} \u2014 and it is not one of the connectors built into the runner's step image.`,remedy:`Every runner in the pool would have to be running an image that carries it. Runs whose resources execute in ${run_placement_1.HOSTED_EXECUTION_LABEL} are unaffected.`}}__name(runnerImageClauses,"runnerImageClauses");function runnerEgressClauses(cause){const scope=cause.confinedRunners===0?`No runner in the private runner pool \u201C${cause.poolName}\u201D blocks`:`Only ${cause.confinedRunners} of ${cause.totalRunners} runners in the private runner pool \u201C${cause.poolName}\u201D block`;return{cause:`This action's package declares the hosts it may reach, and ${brand_1.BRAND_SHORT_NAME} would have to enforce that where the package runs. ${scope} outbound traffic a package was never configured to send \u2014 each one measured that on its own substrate \u2014 so the list could be stated but not enforced.`,remedy:`A run cannot choose which runner claims it, so this is a property of the pool. It changes when the hosts running these runners can confine outbound traffic \u2014 on Kubernetes that means a CNI that enforces NetworkPolicy, which several do not by default. Runs whose resources execute in ${run_placement_1.HOSTED_EXECUTION_LABEL}, or on a pool that confines, are unaffected.`}}__name(runnerEgressClauses,"runnerEgressClauses");var POOL_CONSENT_REMEDY=`${brand_1.BRAND_SHORT_NAME} does not vouch for what runs on your machines \u2014 the owner of this pool does. An administrator can accept this provenance under Settings \u2192 Runners, and until they do, nothing of this provenance will be sent there. Built-in actions still run in that pool.`;function actionRunnabilityHeadline(cause){switch(cause.kind){case"catalog_blocked":return"this workspace does not permit its action \u2014 an administrator of this workspace can allow it";case"beta_not_allowed":return"its action version is a beta and this workspace has not allowed beta actions \u2014 an administrator can allow them in Settings \u2192 Catalog";case"package":return(0,packages_2.actionUnrunnableHeadline)(cause.detail);case"runner_pool":return cause.provenance?`the pool "${cause.poolName}" does not accept packages ${packages_1.PACKAGE_PROVENANCE_CLAUSES[cause.provenance]}`:`its package has no recorded provenance, so the pool "${cause.poolName}" cannot accept it`;case"runner_image":return`the runners in "${cause.poolName}" run an image that does not carry this action's connector`;case"runner_egress":return cause.confinedRunners===0?`no runner in "${cause.poolName}" can confine this package's outbound traffic`:`only ${cause.confinedRunners} of ${cause.totalRunners} runners in "${cause.poolName}" can confine this package's outbound traffic`;case"runner_pool_ambiguous":return`its resources would execute in ${cause.places.length} different places`;case"connector_unregistered":return`this deployment has no connector for "${cause.connectorKey}"`}}__name(actionRunnabilityHeadline,"actionRunnabilityHeadline");function actionRunnabilityRefusal(cause){switch(cause.kind){case"catalog_blocked":return`${CATALOG_BLOCKED_CAUSE} ${CATALOG_BLOCKED_REMEDY} Nothing was started.`;case"beta_not_allowed":return`${BETA_NOT_ALLOWED_CAUSE} ${BETA_NOT_ALLOWED_REMEDY} Nothing was started.`;case"package":return(0,packages_2.actionUnrunnableRefusal)(cause.detail,cause);case"runner_pool":{const{cause:why,remedy}=runnerPoolClauses(cause);return`This action's package ${why} ${remedy} Nothing was started.`}case"runner_image":{const{cause:why,remedy}=runnerImageClauses(cause);return`${why} ${remedy} Nothing was started.`}case"runner_egress":{const{cause:why,remedy}=runnerEgressClauses(cause);return`${why} ${remedy} Nothing was started.`}case"runner_pool_ambiguous":return`This run's resources do not all execute in the same place: ${describeRoutingPlaces(cause.places)}. ${AMBIGUOUS_ROUTING_REMEDY}`;case"connector_unregistered":return exports.CONNECTOR_UNAVAILABLE_MESSAGE}}__name(actionRunnabilityRefusal,"actionRunnabilityRefusal")}});var require_decisions=__commonJS({"../contracts/dist/decisions.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DECISION_ACKNOWLEDGEMENT=exports.TARGET_DISPOSITIONS=exports.UNDECIDED_AT_RUN=void 0;exports.recordedDecisionsOf=recordedDecisionsOf;exports.settleDecisionChecks=settleDecisionChecks3;exports.raisedDecisionCodes=raisedDecisionCodes;exports.decisionMismatch=decisionMismatch;exports.decisionMismatchSentence=decisionMismatchSentence;exports.targetDecisionsMismatchSentence=targetDecisionsMismatchSentence;exports.decisionsMadeAtSubmit=decisionsMadeAtSubmit;exports.isTargetDisposition=isTargetDisposition;var validation_1=require_validation();function recordedDecisionsOf(stored){if(!Array.isArray(stored))return[];const read=[];for(const entry of stored){if(typeof entry!=="object"||entry===null)continue;const{code,acknowledgedBy,acknowledgedAt}=entry;if(!(0,validation_1.isDecisionCode)(code))continue;if(typeof acknowledgedBy!=="string"||acknowledgedBy.length===0)continue;if(typeof acknowledgedAt!=="string"||Number.isNaN(Date.parse(acknowledgedAt)))continue;if(read.some(decision=>decision.code===code))continue;read.push({code,acknowledgedBy,acknowledgedAt})}return read}__name(recordedDecisionsOf,"recordedDecisionsOf");exports.UNDECIDED_AT_RUN="Nobody acknowledged this before the run, so it was not acted on.";function settleDecisionChecks3(checks,inHand){if(inHand.phase==="plan")return[...checks];return checks.map(check=>{if(!check.decision||check.level==="error")return check;if(inHand.recorded.some(decision=>decision.code===check.decision))return check;return{...check,level:"error",title:`${check.title} ${exports.UNDECIDED_AT_RUN}`}})}__name(settleDecisionChecks3,"settleDecisionChecks");function raisedDecisionCodes(checks){const raised=[];for(const check of checks){if(check.decision&&!raised.includes(check.decision))raised.push(check.decision)}return raised}__name(raisedDecisionCodes,"raisedDecisionCodes");function decisionMismatch(raised,acknowledged){const unacknowledged=raised.filter(code=>!acknowledged.includes(code));const notRaised=acknowledged.filter(code=>!raised.includes(code));return unacknowledged.length===0&&notRaised.length===0?null:{unacknowledged,notRaised}}__name(decisionMismatch,"decisionMismatch");function decisionMismatchSentence(mismatch,checks=[]){return`This run was not submitted: the checks were run again at submit, and they no longer match what was acknowledged. ${mismatchParts(mismatch,checks).join(" ")} Review the plan and submit again.`}__name(decisionMismatchSentence,"decisionMismatchSentence");function targetDecisionsMismatchSentence(mismatches){const parts=mismatches.map(target=>target.unknown?`${target.label}: no longer one of this step's targets.`:`${target.label}: ${mismatchParts(target,target.checks).join(" ")}`);const count=mismatches.length;return`This run was not started: the checks were run again, and for ${count} ${count===1?"target":"targets"} they no longer match what was decided. ${parts.join(" ")} Review the plan and start the run again.`}__name(targetDecisionsMismatchSentence,"targetDecisionsMismatchSentence");function mismatchParts(mismatch,checks){const parts=[];for(const code of mismatch.unacknowledged){const sentence=checks.find(check=>check.decision===code)?.title??exports.DECISION_ACKNOWLEDGEMENT[code];parts.push(`Not acknowledged: ${withStop(sentence)}`)}for(const code of mismatch.notRaised){parts.push(`Acknowledged, but no longer raised: \u201C${exports.DECISION_ACKNOWLEDGEMENT[code]}\u201D.`)}return parts}__name(mismatchParts,"mismatchParts");function decisionsMadeAtSubmit(codes,by,at){return codes.map(code=>({code,acknowledgedBy:by,acknowledgedAt:at.toISOString()}))}__name(decisionsMadeAtSubmit,"decisionsMadeAtSubmit");exports.TARGET_DISPOSITIONS=["ready","left_out","refused"];function isTargetDisposition(value){return typeof value==="string"&&exports.TARGET_DISPOSITIONS.includes(value)}__name(isTargetDisposition,"isTargetDisposition");function withStop(sentence){const trimmed=sentence.trim();return/[.!?]$/.test(trimmed)?trimmed:`${trimmed}.`}__name(withStop,"withStop");exports.DECISION_ACKNOWLEDGEMENT={"disk.recentlyDetached":"Delete it even though it was detached recently","disk.customerKey":"Delete it \u2014 restoring later depends on this key staying enabled","disk.customerKeyUnverified":"Delete it without confirmation that the key is enabled","disk.guestEncrypted":"Delete it \u2014 restoring later depends on the guest's encryption secrets","disk.noSnapshot":"Delete it with no snapshot \u2014 this cannot be undone","disk.confidential":"Delete it, accepting that restoring a confidential VM disk is not verified"}}});var require_execution_site=__commonJS({"../contracts/dist/execution-site.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EXECUTION_SITE_UNKNOWN=void 0;exports.runExecutionSiteSentence=runExecutionSiteSentence;exports.runExecutionSiteLabel=runExecutionSiteLabel;exports.plannedExecutionSiteSentence=plannedExecutionSiteSentence;exports.ambiguousPlaceLabel=ambiguousPlaceLabel;var run_placement_1=require_run_placement();function runExecutionSiteSentence(where){switch(where.site){case"hosted":return run_placement_1.HOSTED_EXECUTION_LABEL;case"runner":return where.runner?`Your runner \u201C${where.runner.name}\u201D in pool \u201C${where.pool.name}\u201D`:`Pool \u201C${where.pool.name}\u201D \u2014 no runner claimed it`;case"unknown":return"Not recorded"}}__name(runExecutionSiteSentence,"runExecutionSiteSentence");function runExecutionSiteLabel(where){switch(where.site){case"hosted":return run_placement_1.HOSTED_EXECUTION_LABEL;case"runner":return where.runner?where.runner.name:where.pool.name;case"unknown":return"Not recorded"}}__name(runExecutionSiteLabel,"runExecutionSiteLabel");exports.EXECUTION_SITE_UNKNOWN={site:"unknown"};function plannedExecutionSiteSentence(where){switch(where.site){case"hosted":return run_placement_1.HOSTED_EXECUTION_LABEL;case"runner":return`your own network \u2014 runner pool \u201C${where.pool.name}\u201D`;case"ambiguous":return`${where.places.length} different places`}}__name(plannedExecutionSiteSentence,"plannedExecutionSiteSentence");function ambiguousPlaceLabel(place){return place.poolName?`runner pool \u201C${place.poolName}\u201D`:run_placement_1.HOSTED_EXECUTION_LABEL}__name(ambiguousPlaceLabel,"ambiguousPlaceLabel")}});var require_connections=__commonJS({"../contracts/dist/connections.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PROVIDER_BADGE_COLOR=void 0;exports.PROVIDER_BADGE_COLOR={azure:"#0078d4"}}});var require_resources=__commonJS({"../contracts/dist/resources.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DISCOVERY_TYPE_PATTERN=exports.RESOURCE_TYPE_QUERY_KEY=exports.ARM_RESOURCE_TYPE_MAX_LENGTH=exports.LEGACY_DISCOVERY_PROVIDER=exports.DISCOVERY_VOCABULARY=void 0;exports.discoveryTypesOf=discoveryTypesOf;exports.declaredDiscoveryTypes=declaredDiscoveryTypes;exports.liveDiscoveryTypes=liveDiscoveryTypes;exports.canonicalDiscoveryId=canonicalDiscoveryId;exports.resolveDiscoveryType=resolveDiscoveryType;exports.isSecretReference=isSecretReference;exports.armResourceTypeRefusal=armResourceTypeRefusal;exports.admitArmResourceType=admitArmResourceType;exports.armIdentityResourceType=armIdentityResourceType;exports.resourceTypeDeclarationRefusal=resourceTypeDeclarationRefusal;exports.strictDiscoveryRefusal=strictDiscoveryRefusal;exports.parseDiscoveryType=parseDiscoveryType;exports.formatDiscoveryType=formatDiscoveryType;exports.discoveryTypeSpec=discoveryTypeSpec;exports.dependsOnLookup=dependsOnLookup;exports.discoveryScopeValues=discoveryScopeValues;exports.composeTargetIdentity=composeTargetIdentity;exports.fanOutSuppliedParameters=fanOutSuppliedParameters;var enums_1=require_enums();var AZURE_DISCOVERY_TYPES={resourceGroup:{requires:[],routable:false,identity:null,secretRef:false,takesResourceType:false},keyVault:{requires:[],routable:true,identity:null,secretRef:false,takesResourceType:false},keyVaultSecret:{requires:["vault"],routable:true,identity:"https://{vault}.vault.azure.net/secrets/{name}",secretRef:true,takesResourceType:false},location:{requires:[],routable:false,identity:null,secretRef:false,takesResourceType:false},managedDisk:{requires:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/disks/{name}",secretRef:false,takesResourceType:false},sqlServer:{requires:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{name}",secretRef:false,takesResourceType:false},sqlDatabase:{requires:["resourceGroup","server"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{server}/databases/{name}",secretRef:false,takesResourceType:false},virtualMachine:{requires:[],identifiedBy:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}",secretRef:false,takesResourceType:false},vmSize:{requires:["resourceGroup","vm"],routable:false,identity:null,secretRef:false,takesResourceType:false},arm:{requires:[],identifiedBy:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/{resourceType}/{name}",secretRef:false,takesResourceType:true}};var DECLARED_DISCOVERY={azure:AZURE_DISCOVERY_TYPES,aws:{},gcp:{},terraform:{}};exports.DISCOVERY_VOCABULARY=DECLARED_DISCOVERY;exports.LEGACY_DISCOVERY_PROVIDER="azure";function discoveryTypesOf(provider){return Object.keys(exports.DISCOVERY_VOCABULARY[provider]).map(type=>formatDiscoveryType(provider,type))}__name(discoveryTypesOf,"discoveryTypesOf");function declaredDiscoveryTypes(){return enums_1.PROVIDERS.flatMap(discoveryTypesOf)}__name(declaredDiscoveryTypes,"declaredDiscoveryTypes");function liveDiscoveryTypes(registered){const providers=new Set(registered);return enums_1.PROVIDERS.filter(provider=>providers.has(provider)).flatMap(discoveryTypesOf)}__name(liveDiscoveryTypes,"liveDiscoveryTypes");function canonicalDiscoveryId(value){const parsed=parseDiscoveryType(value.trim(),exports.LEGACY_DISCOVERY_PROVIDER);return parsed?formatDiscoveryType(parsed.provider,parsed.type):null}__name(canonicalDiscoveryId,"canonicalDiscoveryId");function resolveDiscoveryType(value){const parsed=parseDiscoveryType(value.trim(),exports.LEGACY_DISCOVERY_PROVIDER);if(!parsed)return null;const spec=discoveryTypeSpec(parsed.provider,parsed.type);if(!spec)return null;return{id:formatDiscoveryType(parsed.provider,parsed.type),provider:parsed.provider,type:parsed.type,spec}}__name(resolveDiscoveryType,"resolveDiscoveryType");function isSecretReference(discover){return discover?resolveDiscoveryType(discover)?.spec.secretRef===true:false}__name(isSecretReference,"isSecretReference");var NAMESPACE_SEGMENT="[A-Z][A-Za-z0-9]*";var TYPE_SEGMENT="[A-Za-z][A-Za-z0-9]*";var ARM_RESOURCE_TYPE_PATTERN=new RegExp(`^${NAMESPACE_SEGMENT}(?:\\.${NAMESPACE_SEGMENT})+(?:/${TYPE_SEGMENT})+$`);exports.ARM_RESOURCE_TYPE_MAX_LENGTH=256;var ARM_RESOURCE_TYPE_SHAPE='an ARM resource type is a provider namespace of dot-separated PascalCase segments, then one or more "/type" segments of letters and digits, e.g. "Microsoft.Network/publicIPAddresses" or "Microsoft.Sql/servers/databases"';function armResourceTypeRefusal(value){if(typeof value!=="string")return`resourceType must be a string: ${ARM_RESOURCE_TYPE_SHAPE}.`;if(value.length>exports.ARM_RESOURCE_TYPE_MAX_LENGTH){return`resourceType is ${value.length} characters, longer than ${exports.ARM_RESOURCE_TYPE_MAX_LENGTH}: ${ARM_RESOURCE_TYPE_SHAPE}.`}if(!ARM_RESOURCE_TYPE_PATTERN.test(value)){return`${JSON.stringify(value)} is not an ARM resource type: ${ARM_RESOURCE_TYPE_SHAPE}.`}return null}__name(armResourceTypeRefusal,"armResourceTypeRefusal");function admitArmResourceType(value){return armResourceTypeRefusal(value)===null?value:null}__name(admitArmResourceType,"admitArmResourceType");function armIdentityResourceType(value){const admitted=admitArmResourceType(value);return admitted!==null&&admitted.split("/").length===2?admitted:null}__name(armIdentityResourceType,"armIdentityResourceType");function resourceTypeDeclarationRefusal(discover,resourceType){const resolved=discover===void 0?null:resolveDiscoveryType(discover);if(resolved?.spec.takesResourceType){if(resourceType!==void 0)return armResourceTypeRefusal(resourceType);return`"${resolved.id}" lists whatever ARM resource type the parameter declares, so the parameter must declare one in resourceType, e.g. "Microsoft.Network/publicIPAddresses".`}if(resourceType===void 0)return null;const readers=declaredDiscoveryTypes().filter(id=>resolveDiscoveryType(id)?.spec.takesResourceType);const discovers=discover===void 0?"declares no discovery":`discovers "${resolved?.id??discover}"`;return`resourceType is read only by a discovery type that lists a declared resource type (${readers.join(", ")}), and this parameter ${discovers}.`}__name(resourceTypeDeclarationRefusal,"resourceTypeDeclarationRefusal");function strictDiscoveryRefusal(input){const parsed=parseDiscoveryType(input.discover.trim(),input.provider??exports.LEGACY_DISCOVERY_PROVIDER);if(!parsed||!discoveryTypeSpec(parsed.provider,parsed.type)?.takesResourceType)return null;const id=`"${formatDiscoveryType(parsed.provider,parsed.type)}"`;const subject=input.parameter===void 0?id:`Parameter "${input.parameter}" discovers ${id}, which`;return`${subject} lists whatever resource type the action declares. A picker offers it, but nothing can be fanned out over it or routed by rule on it yet: fan-out and routing over an arbitrary resource type come with docs/128 Slice D.`}__name(strictDiscoveryRefusal,"strictDiscoveryRefusal");exports.RESOURCE_TYPE_QUERY_KEY="resourceType";exports.DISCOVERY_TYPE_PATTERN=/^(?:([a-z][a-z0-9]*)\/)?([a-z][a-zA-Z0-9]{0,63})$/;function parseDiscoveryType(value,fallbackProvider){const match=exports.DISCOVERY_TYPE_PATTERN.exec(value);if(!match)return null;const[,prefix,type]=match;if(prefix!==void 0){const provider=enums_1.PROVIDERS.find(p=>p===prefix);return provider?{provider,type}:null}return fallbackProvider?{provider:fallbackProvider,type}:null}__name(parseDiscoveryType,"parseDiscoveryType");function formatDiscoveryType(provider,type){return`${provider}/${type}`}__name(formatDiscoveryType,"formatDiscoveryType");function discoveryTypeSpec(provider,type){if(!Object.prototype.hasOwnProperty.call(exports.DISCOVERY_VOCABULARY,provider))return void 0;const vocabulary=exports.DISCOVERY_VOCABULARY[provider];return Object.prototype.hasOwnProperty.call(vocabulary,type)?vocabulary[type]:void 0}__name(discoveryTypeSpec,"discoveryTypeSpec");function dependsOnLookup(keys,dependsOn){const lookup={};for(const key of keys)lookup[key]=key;if(Array.isArray(dependsOn)){for(const name3 of dependsOn)if(keys.includes(name3))lookup[name3]=name3}else if(dependsOn){for(const[key,name3]of Object.entries(dependsOn)){if(typeof name3==="string"&&name3.trim())lookup[key]=name3.trim()}}return lookup}__name(dependsOnLookup,"dependsOnLookup");function discoveryScopeValues(requires,dependsOn,parameters,skipKeys=[]){const parameterFor=dependsOnLookup(requires,dependsOn);const scope={};for(const key of requires){if(skipKeys.includes(key))continue;const parameter=parameterFor[key]??key;const value=parameters[parameter];if(typeof value!=="string"||value.trim().length===0){return{resolved:false,missingKey:key,parameter}}scope[key]=value.trim()}return{resolved:true,scope}}__name(discoveryScopeValues,"discoveryScopeValues");function composeTargetIdentity(template,values){let missing="";const resourceId=template.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g,(_whole,key)=>{const value=values[key]?.trim();if(!value){if(!missing)missing=key;return""}return value});return missing?{composed:false,missing}:{composed:true,resourceId}}__name(composeTargetIdentity,"composeTargetIdentity");function fanOutSuppliedParameters(input){const{spec,dependsOn,selectorParameter,variedByQuery=[]}=input;const identity=spec.identifiedBy??spec.requires;const lookup=dependsOnLookup(identity,dependsOn);const varied=new Set(variedByQuery);const supplied=[];const push=__name(name3=>{const trimmed=name3.trim();if(trimmed&&!supplied.includes(trimmed))supplied.push(trimmed)},"push");push(selectorParameter);for(const key of identity){if(spec.requires.includes(key)&&!varied.has(key))continue;push(lookup[key]??key)}return supplied}__name(fanOutSuppliedParameters,"fanOutSuppliedParameters")}});var require_governance=__commonJS({"../contracts/dist/governance.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ANY_POLICY_MATCH=void 0;exports.approvalAssessmentOf=approvalAssessmentOf;exports.planAssessmentOf=planAssessmentOf;exports.approvalOutcome=approvalOutcome;exports.policyScopeSentence=policyScopeSentence;var decisions_1=require_decisions();function approvalAssessmentOf(checks,decided){const assessment={facts:[],warnings:[],decisions:[]};for(const check of checks){if(check.decision){const answer=decided.find(decision=>decision.code===check.decision);if(answer)assessment.decisions.push({...answer,title:check.title})}else if(check.level==="warn"){assessment.warnings.push(check.title)}else if(check.level==="info"){assessment.facts.push(check.title)}}return assessment}__name(approvalAssessmentOf,"approvalAssessmentOf");function planAssessmentOf(value){if(typeof value!=="object"||value===null||Array.isArray(value))return null;const a=value;if(!Array.isArray(a.facts)||!Array.isArray(a.warnings)||!Array.isArray(a.decisions)){return null}const decisions=[];for(const entry of a.decisions){const[decision]=(0,decisions_1.recordedDecisionsOf)([entry]);const title=typeof entry==="object"&&entry!==null?entry.title:null;if(!decision||typeof title!=="string")return null;decisions.push({...decision,title})}const strings=__name(list=>list.filter(item=>typeof item==="string"),"strings");return{facts:strings(a.facts),warnings:strings(a.warnings),decisions}}__name(planAssessmentOf,"planAssessmentOf");exports.ANY_POLICY_MATCH={environments:[],riskLevels:[],actionKeys:[],connectionIds:[]};function approvalOutcome(decision,adoptionRequiresApproval){if(!decision.requireApproval){return{requiresApproval:false,approverGroup:null,reason:"No approval required \u2014 this run is submitted straight to execution.",matchedPolicy:null}}const who=decision.approverGroup?` A member of ${decision.approverGroup.name} must approve it first.`:" Anyone who can approve may sign it off.";const rule=decision.matchedPolicy;const why=adoptionRequiresApproval?"Approval required \u2014 this action's adoption is configured to require sign-off.":rule?`Approval required by your governance rule \u201C${rule.name}\u201D (${policyScopeSentence(rule)}).`:"Approval required by your organization's governance policy.";return{requiresApproval:true,approverGroup:decision.approverGroup,reason:`${why}${who}`,matchedPolicy:adoptionRequiresApproval?null:rule??null}}__name(approvalOutcome,"approvalOutcome");function policyScopeSentence(rule){const parts=[];if(rule.riskLevels.length>0){parts.push(`${joinWithOr(rule.riskLevels)}-risk`)}parts.push(rule.actionKeys.length>0?`runs of ${joinWithOr(rule.actionKeys)}`:"runs");if(rule.environments.length>0){parts.push(`in ${joinWithOr(rule.environments.map(e=>ENVIRONMENT_PHRASE[e]))}`)}if(rule.connections.length>0){const named=rule.connections.map(c=>c.name??"a connector that no longer exists");parts.push(`using ${joinWithOr(named)}`)}const sentence=parts.join(" ");return sentence==="runs"?"every run":sentence}__name(policyScopeSentence,"policyScopeSentence");var ENVIRONMENT_PHRASE={production:"production",staging:"staging",non_prod:"non-prod"};function joinWithOr(values){if(values.length<=1)return values[0]??"";return`${values.slice(0,-1).join(", ")} or ${values[values.length-1]}`}__name(joinWithOr,"joinWithOr")}});var require_audit=__commonJS({"../contracts/dist/audit.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_notifications=__commonJS({"../contracts/dist/notifications.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NOTIFICATION_LEVELS=exports.NOTIFICATION_TYPES=void 0;exports.NOTIFICATION_TYPES=["run_completed","approval_requested","approval_resolved","schedule_failed","verification_failed"];exports.NOTIFICATION_LEVELS=["success","error","warning","info"]}});var require_scheduling=__commonJS({"../contracts/dist/scheduling.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_operations=__commonJS({"../contracts/dist/operations.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PREVIEW_UNCHECKED_SENTENCE=exports.PREVIEW_UNCHECKED_REASONS=exports.OPERATION_RUN_TARGET_STATUSES=exports.OPERATION_RUN_STEP_STATUSES=exports.OPERATION_RUN_STATUSES=exports.STEP_FAILURE_POLICIES=exports.OPERATION_STEP_KINDS=exports.DRY_RUN_OUTCOMES=exports.OPERATION_VERIFICATION_LIFECYCLES=exports.OPERATION_HEALTH_STATES=exports.OPERATION_LIFECYCLES=void 0;exports.targetPlanOf=targetPlanOf;var governance_1=require_governance();var decisions_1=require_decisions();exports.OPERATION_LIFECYCLES=["draft","published","deprecated","retired"];exports.OPERATION_HEALTH_STATES=["unverified","healthy","degraded","broken"];exports.OPERATION_VERIFICATION_LIFECYCLES=["queued","running","finished","abandoned"];exports.DRY_RUN_OUTCOMES=["passed","failed","unsupported","quota_exhausted","change_record_required"];exports.OPERATION_STEP_KINDS=["action","wait","approval"];exports.STEP_FAILURE_POLICIES=["stop","continue","rollback_completed"];exports.OPERATION_RUN_STATUSES=["pending","running","pending_approval","cancelling","succeeded","partially_succeeded","failed","rolled_back","partially_rolled_back","cancelled"];exports.OPERATION_RUN_STEP_STATUSES=["pending","running","awaiting_approval","succeeded","failed","skipped","not_reversible"];exports.OPERATION_RUN_TARGET_STATUSES=["pending","running","awaiting_approval","succeeded","failed","cancelled","rolled_back","rollback_failed"];function targetPlanOf(stored){if(!Array.isArray(stored))return null;const plan=[];for(const entry of stored){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;const{ref,label,disposition,decisions,assessment,refusal}=entry;if(typeof ref!=="string"||ref.length===0)continue;if(typeof label!=="string"||!(0,decisions_1.isTargetDisposition)(disposition))continue;if(refusal!==null&&typeof refusal!=="string")continue;plan.push({ref,label,disposition,decisions:(0,decisions_1.recordedDecisionsOf)(decisions),assessment:(0,governance_1.planAssessmentOf)(assessment),refusal:refusal??null})}return plan}__name(targetPlanOf,"targetPlanOf");exports.PREVIEW_UNCHECKED_REASONS=["depends_on_earlier_output","connector_plans_no_checks"];exports.PREVIEW_UNCHECKED_SENTENCE={depends_on_earlier_output:"Not checked before the run: this step's parameters come from an earlier step's outputs, which exist only once that step has run. Each target is checked when its execution is submitted, and a target that would need a decision is not acted on.",connector_plans_no_checks:"This action runs no checks of its own before the run."}}});var require_runs=__commonJS({"../contracts/dist/runs.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUN_STEP_TARGET_PAGE=exports.DEFAULT_RUN_SCOPE=exports.RUN_SCOPES=exports.RUN_FEED_STATUSES=exports.RUN_ORIGINS=void 0;exports.isRunFeedStatus=isRunFeedStatus;var enums_1=require_enums();var operations_1=require_operations();exports.RUN_ORIGINS=["operation","standalone","trial"];exports.RUN_FEED_STATUSES=[...enums_1.EXECUTION_STATUSES,...operations_1.OPERATION_RUN_STATUSES.filter(status=>!enums_1.EXECUTION_STATUSES.includes(status))];function isRunFeedStatus(value){return exports.RUN_FEED_STATUSES.includes(value)}__name(isRunFeedStatus,"isRunFeedStatus");exports.RUN_SCOPES=["all","mine"];exports.DEFAULT_RUN_SCOPE="all";exports.RUN_STEP_TARGET_PAGE=5}});var require_evidence_pack=__commonJS({"../contracts/dist/evidence-pack.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EVIDENCE_EXPORTED_AUDIT_ACTION=exports.EVIDENCE_DIGEST_HEADER=void 0;exports.evidencePackFilename=evidencePackFilename;exports.EVIDENCE_DIGEST_HEADER="X-Evidence-Digest";exports.EVIDENCE_EXPORTED_AUDIT_ACTION="operation.evidence_exported";function evidencePackFilename(operationKey,from,to){return`${operationKey}-evidence-${compactInstant(from)}-${compactInstant(to)}.json`}__name(evidencePackFilename,"evidencePackFilename");function compactInstant(iso){return iso.replace(/\.\d+(?=Z|[+-]\d{2}:?\d{2}$)/,"").replace(/[-:]/g,"")}__name(compactInstant,"compactInstant")}});var require_package_egress=__commonJS({"../contracts/dist/package-egress.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EGRESS_MODE_STOPS_BYPASS=exports.EGRESS_MODE_LABEL=exports.EGRESS_MODES=void 0;exports.egressWasABoundary=egressWasABoundary;exports.egressDisclosureHeadline=egressDisclosureHeadline;exports.egressDisclosureSentence=egressDisclosureSentence;var brand_1=require_brand();exports.EGRESS_MODES=["denied","enforced","cooperative"];exports.EGRESS_MODE_LABEL={denied:"No network",enforced:"Enforced",cooperative:"Configured, not enforced"};exports.EGRESS_MODE_STOPS_BYPASS={denied:false,enforced:true,cooperative:false};function egressWasABoundary(disclosure){return exports.EGRESS_MODE_STOPS_BYPASS[disclosure.mode]||disclosure.mode==="denied"&&disclosure.substrateBlocksUndeclared}__name(egressWasABoundary,"egressWasABoundary");function egressDisclosureHeadline(disclosure){switch(disclosure.mode){case"denied":return disclosure.substrateBlocksUndeclared?"No network \u2014 nothing outside was reachable.":"No network was configured, and this substrate does not block outbound traffic.";case"enforced":return"Only these hosts were reachable \u2014 nothing else could be.";case"cooperative":return"Configured to reach only these hosts \u2014 not prevented from reaching elsewhere."}}__name(egressDisclosureHeadline,"egressDisclosureHeadline");function egressDisclosureSentence(disclosure){const hosts=disclosure.allowlist.join(", ");switch(disclosure.mode){case"denied":return disclosure.substrateBlocksUndeclared?"This package declares no outbound network. It runs with no route out at all, so nothing outside is reachable.":`This package declares no outbound network, so ${brand_1.BRAND_SHORT_NAME} configures no proxy for it. The substrate it runs on does not itself block outbound traffic, so a package that reached out anyway would not be stopped.`;case"enforced":return`The package can reach only ${hosts}. The proxy enforcing that is the run's only route out, so a package that ignored it could not reach anywhere else either.`;case"cooperative":return`The package process is configured to reach only ${hosts}. This guards against the package reaching somewhere by mistake \u2014 a wrong endpoint, a dependency phoning home \u2014 and not against a package that sets out to go elsewhere: this substrate cannot stop one that ignores the configuration.`}}__name(egressDisclosureSentence,"egressDisclosureSentence")}});var require_package_execution=__commonJS({"../contracts/dist/package-execution.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUN_TOKEN_REJECTED=exports.RUN_TOKEN_HEADER=exports.PACKAGE_RUNNER_ENTRYPOINT=exports.PACKAGE_CONTAINER_ENV=exports.PACKAGE_PHASES=void 0;exports.PACKAGE_PHASES=["validate","run","rollback"];exports.PACKAGE_CONTAINER_ENV={callbackBaseUrl:"OPERA_CALLBACK_BASE_URL",executionId:"RUNVERIC_EXECUTION_ID",runToken:"OPERA_RUN_TOKEN",contentDigest:"RUNVERIC_CONTENT_DIGEST",runnerImageDigest:"OPERA_RUNNER_IMAGE_DIGEST",egressProxyUrl:"RUNVERIC_EGRESS_PROXY_URL",egressControlUrl:"RUNVERIC_EGRESS_CONTROL_URL",egressControlToken:"RUNVERIC_EGRESS_CONTROL_TOKEN"};exports.PACKAGE_RUNNER_ENTRYPOINT=["/opt/runveric/runner/launch.sh"];exports.RUN_TOKEN_HEADER="x-runveric-run-token";exports.RUN_TOKEN_REJECTED="This run token is not valid for this execution."}});var require_runner_confinement=__commonJS({"../contracts/dist/runner-confinement.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CONFINEMENT_FINDING_LABEL=exports.CONFINEMENT_FINDING_SENTENCE=exports.RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS=exports.CONFINEMENT_FINDING_BLOCKS_EGRESS=exports.CONFINEMENT_FINDINGS=exports.RUNNER_SUBSTRATE_LABEL=exports.RUNNER_SUBSTRATES=exports.EGRESS_GATE_SHUT=exports.EGRESS_GATE_OPEN=exports.EGRESS_GATE_PREFIX=exports.EGRESS_PROBE_TIMEOUT_MS=exports.EGRESS_PROBE_BLOCKED=exports.EGRESS_PROBE_REACHED=exports.EGRESS_PROBE_PREFIX=void 0;exports.effectiveBlocksUndeclaredEgress=effectiveBlocksUndeclaredEgress;exports.confinementOverclaims=confinementOverclaims;exports.runnerBlocksUndeclaredEgress=runnerBlocksUndeclaredEgress;exports.poolConfinementSentence=poolConfinementSentence;var brand_1=require_brand();exports.EGRESS_PROBE_PREFIX="runveric.egress-probe";exports.EGRESS_PROBE_REACHED="REACHED";exports.EGRESS_PROBE_BLOCKED="BLOCKED";exports.EGRESS_PROBE_TIMEOUT_MS=5e3;exports.EGRESS_GATE_PREFIX="runveric.egress-gate";exports.EGRESS_GATE_OPEN="OPEN";exports.EGRESS_GATE_SHUT="SHUT";exports.RUNNER_SUBSTRATES=["docker","kubernetes"];exports.RUNNER_SUBSTRATE_LABEL={docker:"Docker",kubernetes:"Kubernetes"};exports.CONFINEMENT_FINDINGS=["confined","unconfined","unproven"];exports.CONFINEMENT_FINDING_BLOCKS_EGRESS={confined:true,unconfined:false,unproven:false};exports.RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS=true;function effectiveBlocksUndeclaredEgress(isolationCeiling,finding){return isolationCeiling&&exports.CONFINEMENT_FINDING_BLOCKS_EGRESS[finding]}__name(effectiveBlocksUndeclaredEgress,"effectiveBlocksUndeclaredEgress");function confinementOverclaims(isolationCeiling,finding){return!isolationCeiling&&exports.CONFINEMENT_FINDING_BLOCKS_EGRESS[finding]}__name(confinementOverclaims,"confinementOverclaims");function runnerBlocksUndeclaredEgress(finding){return effectiveBlocksUndeclaredEgress(exports.RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS,finding)}__name(runnerBlocksUndeclaredEgress,"runnerBlocksUndeclaredEgress");exports.CONFINEMENT_FINDING_SENTENCE={confined:__name(()=>"Undeclared outbound traffic is blocked here. This runner proved it: a probe that reaches the network when nothing stops it could not reach anything once the confinement applied.","confined"),unconfined:__name(()=>"Undeclared outbound traffic is NOT blocked here. This runner probed its own substrate and the probe got out, so a package that ignored its egress settings would reach the network. Packages that need their allowlist enforced will not be sent to this pool.","unconfined"),unproven:__name(()=>`This runner could not establish whether undeclared outbound traffic is blocked, so ${brand_1.BRAND_SHORT_NAME} does not claim that it is. The check needs one throwaway pod that can reach the network when nothing stops it; until that succeeds there is no measurement to report.`,"unproven")};exports.CONFINEMENT_FINDING_LABEL={confined:"Egress confined",unconfined:"Egress not confined",unproven:"Confinement unproven"};function poolConfinementSentence(findings){if(findings.length===0)return null;const confined=findings.filter(runnerBlocksUndeclaredEgress).length;if(confined===findings.length)return exports.CONFINEMENT_FINDING_SENTENCE.confined();if(confined===0){const[first2]=findings;return findings.every(f=>f===first2)?exports.CONFINEMENT_FINDING_SENTENCE[first2]():`${exports.CONFINEMENT_FINDING_SENTENCE.unconfined()} Not every runner here reached that conclusion the same way \u2014 open a runner to see what each one measured.`}return`Only ${confined} of ${findings.length} runners in this pool block undeclared outbound traffic. A run cannot choose which runner claims it, so this pool is not relied on to confine egress and packages that need their allowlist enforced are not sent here.`}__name(poolConfinementSentence,"poolConfinementSentence")}});var require_runner_install=__commonJS({"../contracts/dist/runner-install.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POD_ROLE_BROKER=exports.POD_EGRESS_CONFINED=exports.POD_EGRESS_LABEL=exports.POD_RUNNER=exports.POD_ROLE=exports.POD_MANAGED_BY_VALUE=exports.POD_MANAGED_BY=exports.RUNNER_NETWORK_POLICY_NAME=exports.RUNNER_REPORT_DIRECTORY=exports.RUNNER_STATE_DIRECTORY=exports.RUNNER_CONTAINER_PREFIX=exports.RUNNER_NAMESPACE=exports.RUNNER_HOST_ENV=void 0;exports.RUNNER_HOST_ENV={substrate:"RUNVERIC_RUNNER_SUBSTRATE",controlPlaneUrl:"RUNVERIC_CONTROL_PLANE_URL",runnerName:"RUNVERIC_RUNNER_NAME",registrationToken:"RUNVERIC_RUNNER_REGISTRATION_TOKEN",stepImage:"RUNVERIC_RUNNER_STEP_IMAGE",packageImage:"RUNVERIC_RUNNER_PACKAGE_IMAGE",reportDirectory:"RUNVERIC_RUNNER_REPORT_DIR"};exports.RUNNER_NAMESPACE="runveric-runner";exports.RUNNER_CONTAINER_PREFIX="runveric-";exports.RUNNER_STATE_DIRECTORY="/var/lib/runveric-runner";exports.RUNNER_REPORT_DIRECTORY=`${exports.RUNNER_STATE_DIRECTORY}/reports`;exports.RUNNER_NETWORK_POLICY_NAME="runveric-confined-egress";exports.POD_MANAGED_BY="runveric.dev/managed-by";exports.POD_MANAGED_BY_VALUE="runveric-dispatcher";exports.POD_ROLE="runveric.dev/role";exports.POD_RUNNER="runveric.dev/runner";exports.POD_EGRESS_LABEL="runveric.dev/egress";exports.POD_EGRESS_CONFINED="confined";exports.POD_ROLE_BROKER="egress-broker"}});var require_authoring_cli=__commonJS({"../contracts/dist/authoring-cli.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ENGINE_AUTHORING_SINCE_CLI_VERSION=exports.RETIRED_AUTHORING_CLI_ENV=exports.AUTHORING_CLI_ENV=void 0;exports.pinnedCliVersion=pinnedCliVersion;exports.advertisesEngineAuthoring=advertisesEngineAuthoring;exports.AUTHORING_CLI_ENV={token:"RUNVERIC_TOKEN",url:"RUNVERIC_URL",runnerImage:"RUNVERIC_RUNNER_IMAGE"};exports.RETIRED_AUTHORING_CLI_ENV={token:"OPERA_TOKEN",url:"OPERA_URL",runnerImage:"OPERA_RUNNER_IMAGE"};exports.ENGINE_AUTHORING_SINCE_CLI_VERSION="0.5.0";function pinnedCliVersion(installCommand){return/^npx \S+@(\d+\.\d+\.\d+)$/.exec(installCommand)?.[1]??null}__name(pinnedCliVersion,"pinnedCliVersion");function advertisesEngineAuthoring(installCommand){const pinned=pinnedCliVersion(installCommand);if(pinned===null)return false;const[major,minor,patch]=pinned.split(".").map(Number);const[sinceMajor,sinceMinor,sincePatch]=exports.ENGINE_AUTHORING_SINCE_CLI_VERSION.split(".").map(Number);return(major-sinceMajor||minor-sinceMinor||patch-sincePatch)>=0}__name(advertisesEngineAuthoring,"advertisesEngineAuthoring")}});var require_runners=__commonJS({"../contracts/dist/runners.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUNNER_AUTHORIZATION_REFUSALS=exports.RUNNER_REFUSAL_SUBJECTS=exports.RUNNER_WORK_KINDS=exports.RUNNER_PROTOCOL_VERSION=exports.RUNNER_PRESENCES=exports.RUNNER_QUIET_AFTER_MS=exports.RUNNER_LIFECYCLES=exports.RUNNER_POOL_DEFAULT_ACCEPTS_PROVENANCE=exports.RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT=exports.RUNNER_AUTHORIZATION_TOKEN_HEADER=exports.RUNNER_CREDENTIAL_HEADER=exports.RUNNER_REGISTRATION_TOKEN_HEADER=void 0;exports.poolAcceptsProvenance=poolAcceptsProvenance;exports.containerNameFor=containerNameFor;exports.runnerPresence=runnerPresence;exports.runnerVersionStanding=runnerVersionStanding;var wire_identity_1=require_wire_identity();Object.defineProperty(exports,"RUNNER_PROTOCOL_VERSION",{enumerable:true,get:__name(function(){return wire_identity_1.RUNNER_PROTOCOL_VERSION},"get")});var package_provenance_1=require_package_provenance();var runner_install_1=require_runner_install();exports.RUNNER_REGISTRATION_TOKEN_HEADER="x-runveric-runner-registration-token";exports.RUNNER_CREDENTIAL_HEADER="x-runveric-runner-credential";exports.RUNNER_AUTHORIZATION_TOKEN_HEADER="x-runveric-runner-authorization";exports.RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT={git_source:false,public_git:false,authored:false};exports.RUNNER_POOL_DEFAULT_ACCEPTS_PROVENANCE=package_provenance_1.PACKAGE_PROVENANCE_KINDS.filter(kind=>exports.RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT[kind]);function poolAcceptsProvenance(accepts,provenance2){if(provenance2===null)return false;return accepts.includes(provenance2)}__name(poolAcceptsProvenance,"poolAcceptsProvenance");function containerNameFor(runnerName){return`${runner_install_1.RUNNER_CONTAINER_PREFIX}${runnerName.trim()}`}__name(containerNameFor,"containerNameFor");exports.RUNNER_LIFECYCLES=["active","draining","revoked"];exports.RUNNER_QUIET_AFTER_MS=9e4;exports.RUNNER_PRESENCES=["online","quiet","offline"];function runnerPresence(runner,now){if(new Date(runner.credentialExpiresAt).getTime()<=now)return"offline";return now-new Date(runner.lastSeenAt).getTime()<exports.RUNNER_QUIET_AFTER_MS?"online":"quiet"}__name(runnerPresence,"runnerPresence");function runnerVersionStanding(runnerVersion,policy){const runner=parseRunnerVersion(runnerVersion);if(runner===null)return"unsupported";if(compareRunnerVersions(runner,parseRunnerVersion(policy.minimumVersion)??[0,0,0])<0){return"unsupported"}const installed=parseRunnerVersion(policy.version);if(installed!==null&&compareRunnerVersions(runner,installed)<0)return"behind";return"current"}__name(runnerVersionStanding,"runnerVersionStanding");function parseRunnerVersion(value){const match=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(value.trim());if(!match)return null;return[Number(match[1]),Number(match[2]),Number(match[3])]}__name(parseRunnerVersion,"parseRunnerVersion");function compareRunnerVersions(a,b){for(let i=0;i<3;i+=1){if(a[i]!==b[i])return a[i]-b[i]}return 0}__name(compareRunnerVersions,"compareRunnerVersions");exports.RUNNER_WORK_KINDS=["step","package"];exports.RUNNER_REFUSAL_SUBJECTS=["runner","authorization"];exports.RUNNER_AUTHORIZATION_REFUSALS=["expired","unknown"]}});var require_scoped_credential=__commonJS({"../contracts/dist/scoped-credential.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RunnerStepCredentialExpiredError=exports.RunnerStepCredentialError=exports.STEP_CREDENTIAL_FAILURE=exports.ENGINE_ACTION_TOKEN_HOLDER=exports.RUNNER_STEP_TOKEN_HOLDER=exports.StaticScopedCredential=void 0;var StaticScopedCredential=class StaticScopedCredential{static{__name(this,"StaticScopedCredential")}now;holder;byScope;constructor(tokens2,now=Date.now,holder=exports.RUNNER_STEP_TOKEN_HOLDER){this.now=now;this.holder=holder;this.byScope=new Map(tokens2.map(token2=>[token2.scope,token2]))}async getToken(scopes){const requested=typeof scopes==="string"?[scopes]:scopes;for(const scope of requested){const token2=this.byScope.get(scope);if(token2){if(token2.expiresOnTimestamp<=this.now()){throw new RunnerStepCredentialExpiredError(scope,token2.expiresOnTimestamp,this.now(),this.holder)}return{token:token2.token,expiresOnTimestamp:token2.expiresOnTimestamp}}}throw new RunnerStepCredentialError(requested,[...this.byScope.keys()],this.holder)}};exports.StaticScopedCredential=StaticScopedCredential;exports.RUNNER_STEP_TOKEN_HOLDER={noun:"step",whereDeclared:"The channel mints exactly what a connector's azureAudiences declares, so this connector reaches an Azure resource it does not say it reaches.",whyNoMore:"A step container is handed minted bytes and nothing it can use to get another, so the step ran longer than its own credential and cannot continue."};exports.ENGINE_ACTION_TOKEN_HOLDER={noun:"action",whereDeclared:"The engine mints exactly the audiences an action's manifest declares in execution.audiences, so this action reaches an Azure resource it does not say it reaches.",whyNoMore:"An action is handed minted bytes and nothing it can use to get another, so it ran longer than its own credential and cannot continue."};exports.STEP_CREDENTIAL_FAILURE="runvericStepCredentialFailure";var RunnerStepCredentialError=class RunnerStepCredentialError extends Error{static{__name(this,"RunnerStepCredentialError")}constructor(requested,available,holder=exports.RUNNER_STEP_TOKEN_HOLDER){super(`This ${holder.noun} was authorized for ${available.length>0?available.map(quote).join(", "):"no scopes"} and asked for ${requested.map(quote).join(", ")}. ${holder.whereDeclared}`);this.name="RunnerStepCredentialError"}[exports.STEP_CREDENTIAL_FAILURE]=true};exports.RunnerStepCredentialError=RunnerStepCredentialError;var RunnerStepCredentialExpiredError=class RunnerStepCredentialExpiredError extends Error{static{__name(this,"RunnerStepCredentialExpiredError")}constructor(scope,expiresOnTimestamp,now,holder=exports.RUNNER_STEP_TOKEN_HOLDER){super(`This ${holder.noun}'s token for ${quote(scope)} expired ${Math.round((now-expiresOnTimestamp)/1e3)}s ago, at ${new Date(expiresOnTimestamp).toISOString()}. ${holder.whyNoMore}`);this.name="RunnerStepCredentialExpiredError"}[exports.STEP_CREDENTIAL_FAILURE]=true};exports.RunnerStepCredentialExpiredError=RunnerStepCredentialExpiredError;function quote(scope){return`"${scope}"`}__name(quote,"quote")}});var require_action_protocol=__commonJS({"../contracts/dist/action-protocol.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ActionProtocolError=exports.JWT_SHAPE=exports.REDACTED_SECRET=exports.ENGINE_RUN_ROUTES=exports.ACTION_PROBE_ENV=exports.ACTION_RUNTIME_PROBE_FLAG=exports.ACTION_CONTAINER_ENV=exports.MAX_PLAN_VALIDATE_TARGETS=exports.ACTION_PROTOCOL_LIMITS=exports.ACTION_EXECUTION_KINDS=exports.ENGINE_CONNECTOR_KEY=exports.ACTION_CONTRACTS=void 0;exports.isActionContract=isActionContract;exports.engineRunUrl=engineRunUrl;exports.actionAudienceRefusal=actionAudienceRefusal;exports.actionTokenScope=actionTokenScope;exports.redactSecrets=redactSecrets2;exports.redactJwtShaped=redactJwtShaped2;exports.carriesJwtShaped=carriesJwtShaped;exports.jsonByteLength=jsonByteLength;exports.parseActionInvocation=parseActionInvocation2;exports.parseActionEvent=parseActionEvent2;exports.tooManyEvents=tooManyEvents;exports.parseActionCheckpoint=parseActionCheckpoint2;exports.parseCheckpointAck=parseCheckpointAck;exports.parseActionReport=parseActionReport2;var wire_identity_1=require_wire_identity();var package_execution_1=require_package_execution();var validation_1=require_validation();exports.ACTION_CONTRACTS=[wire_identity_1.ACTION_PROTOCOL_V1];function isActionContract(value){return typeof value==="string"&&exports.ACTION_CONTRACTS.includes(value)}__name(isActionContract,"isActionContract");exports.ENGINE_CONNECTOR_KEY="runveric.engine";exports.ACTION_EXECUTION_KINDS=["engine"];exports.ACTION_PROTOCOL_LIMITS={maxEvents:500,maxEventBytes:2048,maxReportBytes:262144,maxRestorePointBytes:65536};exports.MAX_PLAN_VALIDATE_TARGETS=200;exports.ACTION_CONTAINER_ENV={runToken:"RUNVERIC_ACTION_RUN_TOKEN",callbackBaseUrl:"RUNVERIC_ACTION_CALLBACK_BASE_URL",runId:"RUNVERIC_ACTION_RUN_ID",imageDigest:"RUNVERIC_ACTION_IMAGE_DIGEST"};exports.ACTION_RUNTIME_PROBE_FLAG="--probe";exports.ACTION_PROBE_ENV={identities:"RUNVERIC_PROBE_IDENTITIES"};exports.ENGINE_RUN_ROUTES={base:"internal/engine-runs",invocation:"invocation",events:"events",checkpoint:"checkpoint",report:"report"};function engineRunUrl(callbackBaseUrl,runId,message){const origin2=callbackBaseUrl.replace(/\/+$/,"");return`${origin2}/${exports.ENGINE_RUN_ROUTES.base}/${encodeURIComponent(runId)}/${exports.ENGINE_RUN_ROUTES[message]}`}__name(engineRunUrl,"engineRunUrl");function actionAudienceRefusal(value){if(typeof value==="string"&&AUDIENCE_ORIGIN.test(value))return null;return`"${String(value)}" is not an audience. An audience is the https origin of the resource a token is for \u2014 lowercase, with no port, path or trailing slash, e.g. "https://management.azure.com".`}__name(actionAudienceRefusal,"actionAudienceRefusal");var AUDIENCE_ORIGIN=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;function actionTokenScope(audience){return`${audience}/.default`}__name(actionTokenScope,"actionTokenScope");exports.REDACTED_SECRET="[redacted]";function redactSecrets2(value,secrets){const present=secrets.filter(secret=>secret.length>0);if(present.length===0)return value;return mapStrings(value,text=>present.reduce((out,secret)=>out.split(secret).join(exports.REDACTED_SECRET),text))}__name(redactSecrets2,"redactSecrets");exports.JWT_SHAPE=/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/;function redactJwtShaped2(value){const everyMatch=new RegExp(exports.JWT_SHAPE.source,"g");return mapStrings(value,text=>text.replace(everyMatch,exports.REDACTED_SECRET))}__name(redactJwtShaped2,"redactJwtShaped");function carriesJwtShaped(value){let found=false;mapStrings(value,text=>{found||=exports.JWT_SHAPE.test(text);return text});return found}__name(carriesJwtShaped,"carriesJwtShaped");function mapStrings(value,scrub){const walk=__name(node=>{if(typeof node==="string")return scrub(node);if(Array.isArray(node))return node.map(walk);if(node!==null&&typeof node==="object"){return Object.fromEntries(Object.entries(node).map(([key,item])=>[scrub(key),walk(item)]))}return node},"walk");return walk(value)}__name(mapStrings,"mapStrings");function jsonByteLength(value){const text=JSON.stringify(value)??"";let bytes=0;for(const char of text){const point=char.codePointAt(0)??0;bytes+=point<128?1:point<2048?2:point<65536?3:4}return bytes}__name(jsonByteLength,"jsonByteLength");var ActionProtocolError=class ActionProtocolError extends Error{static{__name(this,"ActionProtocolError")}constructor(message){super(message);this.name="ActionProtocolError"}};exports.ActionProtocolError=ActionProtocolError;function parseActionInvocation2(body){const raw=objectOf2(body,"The invocation");onlyKeys(raw,INVOCATION_KEYS,"The invocation");if(!isActionContract(raw.protocol)){throw new ActionProtocolError(`The invocation speaks ${String(raw.protocol)}, and this runtime speaks ${exports.ACTION_CONTRACTS.join(", ")}.`)}const phase=raw.phase;if(typeof phase!=="string"||!package_execution_1.PACKAGE_PHASES.includes(phase)){throw new ActionProtocolError(`An invocation phase of "${String(phase)}" is not in the vocabulary.`)}const actionRaw=objectOf2(raw.action,"The invocation's action");onlyKeys(actionRaw,["key","version","image"],"The invocation's action");const action={key:nonEmpty(actionRaw.key,"The action's key"),version:nonEmpty(actionRaw.version,"The action's version"),image:digestPinned(actionRaw.image)};const executionRaw=objectOf2(raw.execution,"The invocation's execution");onlyKeys(executionRaw,["id","tenantId","correlationId","dryRun"],"The invocation's execution");if(typeof executionRaw.dryRun!=="boolean"){throw new ActionProtocolError("The invocation's execution must say whether it is a dry run.")}const execution={id:nonEmpty(executionRaw.id,"The execution's id"),tenantId:nonEmpty(executionRaw.tenantId,"The execution's tenant"),correlationId:nonEmpty(executionRaw.correlationId,"The execution's correlation id"),dryRun:executionRaw.dryRun};const limits=parseLimits(raw.limits);const decisions=parseDecisions(raw.decisions);const targets=parseTargets(raw.targets);const credentials={tokens:parseTokens(objectOf2(raw.credentials,"The invocation's credentials"))};const restorePoint=nullableObject(raw.restorePoint,"The invocation's restore point");const priorResult=nullableObject(raw.priorResult,"The invocation's prior result");if(restorePoint!==null&&jsonByteLength(restorePoint)>limits.maxRestorePointBytes){throw new ActionProtocolError(`The invocation's restore point is larger than ${limits.maxRestorePointBytes} bytes.`)}const base={protocol:raw.protocol,action,execution,targets,credentials,limits};if(phase==="validate"){if(raw.mode!=="plan"&&raw.mode!=="run"){throw new ActionProtocolError(`A validate invocation's mode of "${String(raw.mode)}" is not "plan" or "run".`)}if(raw.mode!==decisions.phase){throw new ActionProtocolError(`A validate invocation in ${raw.mode} mode carries ${decisions.phase}-phase decisions; the two are the same fact.`)}assertTargetCount(targets.length,raw.mode==="plan"?exports.MAX_PLAN_VALIDATE_TARGETS:1,`A ${raw.mode}-mode validate`);if(restorePoint!==null||priorResult!==null){throw new ActionProtocolError("A validate invocation carries no restore point and no prior result.")}return{...base,phase,mode:raw.mode,decisions,restorePoint:null,priorResult:null}}if(raw.mode!==void 0){throw new ActionProtocolError(`A ${phase} invocation has no mode \u2014 only a validate is asked in a mode.`)}if(decisions.phase!=="run"){throw new ActionProtocolError(`A ${phase} invocation carries a run's decisions, never a plan's.`)}assertTargetCount(targets.length,1,`A ${phase}`);if(phase==="run"){if(priorResult!==null){throw new ActionProtocolError("A run invocation carries no prior result \u2014 only a rollback reads one.")}return{...base,phase,decisions,restorePoint,priorResult:null}}return{...base,phase:"rollback",decisions,restorePoint,priorResult}}__name(parseActionInvocation2,"parseActionInvocation");function parseActionEvent2(body,limits,alreadyReceived){if(alreadyReceived>=limits.maxEvents)throw tooManyEvents(limits);const raw=objectOf2(body,"An event");onlyKeys(raw,["level","message","data"],"An event");if(jsonByteLength(raw)>limits.maxEventBytes){throw new ActionProtocolError(`An event is larger than ${limits.maxEventBytes} bytes.`)}if(typeof raw.level!=="string"||!Object.hasOwn(EVENT_LEVELS,raw.level)){throw new ActionProtocolError(`An event level of "${String(raw.level)}" is not in the vocabulary.`)}const message=nonEmpty(raw.message,"An event's message");if(raw.data===void 0)return{level:raw.level,message};return{level:raw.level,message,data:jsonObject(raw.data,"An event's data")}}__name(parseActionEvent2,"parseActionEvent");function tooManyEvents(limits){return new ActionProtocolError(`The action sent more than ${limits.maxEvents} events.`)}__name(tooManyEvents,"tooManyEvents");function parseActionCheckpoint2(body,limits){const raw=objectOf2(body,"A checkpoint");onlyKeys(raw,["kind","record"],"A checkpoint");if(raw.kind!=="restore_point"){throw new ActionProtocolError(`A checkpoint of kind "${String(raw.kind)}" is not one this contract knows.`)}const record=jsonObject(raw.record,"A checkpoint's record");if(jsonByteLength(record)>limits.maxRestorePointBytes){throw new ActionProtocolError(`A restore point is larger than ${limits.maxRestorePointBytes} bytes.`)}return{kind:"restore_point",record}}__name(parseActionCheckpoint2,"parseActionCheckpoint");function parseCheckpointAck(body){const raw=objectOf2(body,"A checkpoint acknowledgement");onlyKeys(raw,["acknowledged"],"A checkpoint acknowledgement");if(raw.acknowledged!==true){throw new ActionProtocolError("The checkpoint was not acknowledged.")}return{acknowledged:true}}__name(parseCheckpointAck,"parseCheckpointAck");function parseActionReport2(body,sent){const raw=objectOf2(body,"The report");onlyKeys(raw,["phase","checks","outcome"],"The report");if(jsonByteLength(raw)>sent.limits.maxReportBytes){throw new ActionProtocolError(`The report is larger than ${sent.limits.maxReportBytes} bytes.`)}if(raw.phase!==sent.phase){throw new ActionProtocolError(`The report is for phase "${String(raw.phase)}", but this invocation is for "${sent.phase}".`)}if(sent.phase==="validate"){if(raw.checks===void 0===(raw.outcome===void 0)){throw new ActionProtocolError("A validate report carries checks, or \u2014 when they could not run \u2014 a failed outcome; exactly one of the two.")}if(raw.outcome!==void 0){const outcome=parseOutcome(raw.outcome);if(outcome.status!=="failed"){throw new ActionProtocolError(`A validate report's outcome can only say the checks failed to run, never "${outcome.status}" \u2014 the engine decides what checks mean.`)}return{phase:"validate",outcome}}const byRef=objectOf2(raw.checks,"A validate report's checks");const expected=new Set(sent.targets.map(target=>target.ref));for(const ref of Object.keys(byRef)){if(!expected.has(ref)){throw new ActionProtocolError(`The report answers for "${ref}", which is not one of the targets it was given.`)}}const checks=sent.targets.map(({ref})=>{if(!Object.hasOwn(byRef,ref)){throw new ActionProtocolError(`The report says nothing about "${ref}", one of the targets it was given.`)}const list=byRef[ref];if(!Array.isArray(list)){throw new ActionProtocolError(`The checks for "${ref}" must be an array.`)}return{ref,checks:list.map(entry=>{const parsed=(0,validation_1.validationCheckOf)(entry);if("refusal"in parsed)throw new ActionProtocolError(`The checks for "${ref}": ${parsed.refusal}`);return parsed.check})}});return{phase:"validate",checks}}if(raw.checks!==void 0){throw new ActionProtocolError(`A ${sent.phase} report carries an outcome, never checks \u2014 those are the validate phase's answer.`)}return{phase:sent.phase,outcome:parseOutcome(raw.outcome)}}__name(parseActionReport2,"parseActionReport");var INVOCATION_KEYS=["protocol","action","phase","mode","execution","targets","decisions","restorePoint","priorResult","credentials","limits"];var EVENT_LEVELS={info:true,warn:true,error:true,success:true};var OUTCOME_STATUSES={succeeded:true,failed:true,cancelled:true};function parseOutcome(value){if(value===void 0){throw new ActionProtocolError("A run or rollback report must carry an outcome.")}const raw=objectOf2(value,"An outcome");onlyKeys(raw,["status","message","data"],"An outcome");if(typeof raw.status!=="string"||!Object.hasOwn(OUTCOME_STATUSES,raw.status)){throw new ActionProtocolError(`An outcome status of "${String(raw.status)}" is not in the vocabulary.`)}const status=raw.status;const message=nonEmpty(raw.message,"An outcome's message");if(raw.data===void 0)return{status,message};return{status,message,data:jsonObject(raw.data,"An outcome's data")}}__name(parseOutcome,"parseOutcome");function parseLimits(value){const raw=objectOf2(value,"The invocation's limits");onlyKeys(raw,["deadline","maxEvents","maxEventBytes","maxReportBytes","maxRestorePointBytes"],"The invocation's limits");return{deadline:isoInstant(raw.deadline,"The deadline"),maxEvents:positiveInteger(raw.maxEvents,"maxEvents"),maxEventBytes:positiveInteger(raw.maxEventBytes,"maxEventBytes"),maxReportBytes:positiveInteger(raw.maxReportBytes,"maxReportBytes"),maxRestorePointBytes:positiveInteger(raw.maxRestorePointBytes,"maxRestorePointBytes")}}__name(parseLimits,"parseLimits");function parseDecisions(value){const raw=objectOf2(value,"The invocation's decisions");if(raw.phase==="plan"){onlyKeys(raw,["phase"],"A plan's decisions");return{phase:"plan"}}if(raw.phase!=="run"){throw new ActionProtocolError(`A decisions phase of "${String(raw.phase)}" is not "plan" or "run".`)}onlyKeys(raw,["phase","recorded"],"A run's decisions");if(!Array.isArray(raw.recorded)){throw new ActionProtocolError("A run's decisions must carry the recorded list, even when it is empty.")}const recorded=raw.recorded.map(entry=>{const decision=objectOf2(entry,"A recorded decision");onlyKeys(decision,["code","acknowledgedBy","acknowledgedAt"],"A recorded decision");if(!(0,validation_1.isDecisionCode)(decision.code)){throw new ActionProtocolError(`A recorded decision of "${String(decision.code)}" is not in the vocabulary.`)}return{code:decision.code,acknowledgedBy:nonEmpty(decision.acknowledgedBy,"Who acknowledged a decision"),acknowledgedAt:isoInstant(decision.acknowledgedAt,"When a decision was acknowledged")}});if(new Set(recorded.map(decision=>decision.code)).size!==recorded.length){throw new ActionProtocolError("A run's decisions record one code twice.")}return{phase:"run",recorded}}__name(parseDecisions,"parseDecisions");function parseTargets(value){if(!Array.isArray(value)){throw new ActionProtocolError("The invocation's targets must be an array.")}const targets=value.map(entry=>{const raw=objectOf2(entry,"A target");onlyKeys(raw,["ref","parameters"],"A target");return{ref:nonEmpty(raw.ref,"A target's ref"),parameters:jsonObject(raw.parameters,"A target's parameters")}});if(new Set(targets.map(target=>target.ref)).size!==targets.length){throw new ActionProtocolError("The invocation names one target twice.")}return targets}__name(parseTargets,"parseTargets");function assertTargetCount(count,max,what){if(count<1||count>max){throw new ActionProtocolError(max===1?`${what} acts on exactly one target; this invocation names ${count}.`:`${what} checks between 1 and ${max} targets; this invocation names ${count}.`)}}__name(assertTargetCount,"assertTargetCount");function parseTokens(credentials){onlyKeys(credentials,["tokens"],"The invocation's credentials");if(!Array.isArray(credentials.tokens)){throw new ActionProtocolError("The invocation's credentials must carry a tokens array, even when it is empty.")}const tokens2=credentials.tokens.map(entry=>{const raw=objectOf2(entry,"A token");onlyKeys(raw,["audience","token","expiresOn"],"A token");const refusal=actionAudienceRefusal(raw.audience);if(refusal!==null)throw new ActionProtocolError(refusal);return{audience:raw.audience,token:nonEmpty(raw.token,"A token's value"),expiresOn:isoInstant(raw.expiresOn,"A token's expiry")}});if(new Set(tokens2.map(token2=>token2.audience)).size!==tokens2.length){throw new ActionProtocolError("The invocation carries two tokens for one audience.")}return tokens2}__name(parseTokens,"parseTokens");var DIGEST_PINNED_IMAGE=/^[a-z0-9][a-z0-9._\-/:]*@sha256:[0-9a-f]{64}$/;function digestPinned(value){if(typeof value!=="string"||!DIGEST_PINNED_IMAGE.test(value)){throw new ActionProtocolError(`The action's image "${String(value)}" is not addressed by digest. Nothing on the execution path resolves a tag (docs/128 \xA713.2).`)}return value}__name(digestPinned,"digestPinned");function objectOf2(value,what){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new ActionProtocolError(`${what} must be an object.`)}return value}__name(objectOf2,"objectOf");function onlyKeys(raw,allowed,what){for(const key of Object.keys(raw)){if(!allowed.includes(key)){throw new ActionProtocolError(`${what} carries "${key}", which this contract does not have.`)}}}__name(onlyKeys,"onlyKeys");function nonEmpty(value,what){if(typeof value!=="string"||value.length===0){throw new ActionProtocolError(`${what} must be a non-empty string.`)}return value}__name(nonEmpty,"nonEmpty");function positiveInteger(value,what){if(typeof value!=="number"||!Number.isInteger(value)||value<1){throw new ActionProtocolError(`The limit "${what}" must be a positive integer.`)}return value}__name(positiveInteger,"positiveInteger");function isoInstant(value,what){if(typeof value!=="string"||Number.isNaN(Date.parse(value))){throw new ActionProtocolError(`${what} must be an ISO-8601 instant.`)}return value}__name(isoInstant,"isoInstant");function nullableObject(value,what){return value===null?null:jsonObject(value,what)}__name(nullableObject,"nullableObject");function jsonObject(value,what){if(!isJsonObject(value)){throw new ActionProtocolError(`${what} must be a JSON object.`)}return value}__name(jsonObject,"jsonObject");function isJsonObject(value){if(typeof value!=="object"||value===null||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)return false;return Object.values(value).every(isJsonValue)}__name(isJsonObject,"isJsonObject");function isJsonValue(value){if(value===null||typeof value==="string"||typeof value==="boolean")return true;if(typeof value==="number")return Number.isFinite(value);if(Array.isArray(value))return value.every(isJsonValue);return isJsonObject(value)}__name(isJsonValue,"isJsonValue")}});var require_action_signing=__commonJS({"../contracts/dist/action-signing.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ACTION_SIGNATURE_REPOSITORY=exports.IMAGE_REVISION_LABEL=exports.IMAGE_SOURCE_LABEL=exports.COSIGN_SIGN_PREDICATE_TYPE=exports.IN_TOTO_STATEMENT_TYPE=exports.DSSE_IN_TOTO_PAYLOAD_TYPE=exports.SIGSTORE_BUNDLE_MEDIA_TYPE=void 0;exports.SIGSTORE_BUNDLE_MEDIA_TYPE="application/vnd.dev.sigstore.bundle.v0.3+json";exports.DSSE_IN_TOTO_PAYLOAD_TYPE="application/vnd.in-toto+json";exports.IN_TOTO_STATEMENT_TYPE="https://in-toto.io/Statement/v1";exports.COSIGN_SIGN_PREDICATE_TYPE="https://sigstore.dev/cosign/sign/v1";exports.IMAGE_SOURCE_LABEL="org.opencontainers.image.source";exports.IMAGE_REVISION_LABEL="org.opencontainers.image.revision";exports.ACTION_SIGNATURE_REPOSITORY="ghcr.io/runveric/action-signatures"}});var require_oci_media_types=__commonJS({"../contracts/dist/oci-media-types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IMAGE_MANIFEST_MEDIA_TYPES=exports.MANIFEST_MEDIA_TYPES=exports.DOCKER_MANIFEST_LIST=exports.OCI_IMAGE_INDEX=exports.DOCKER_IMAGE_MANIFEST=exports.OCI_IMAGE_MANIFEST=void 0;exports.OCI_IMAGE_MANIFEST="application/vnd.oci.image.manifest.v1+json";exports.DOCKER_IMAGE_MANIFEST="application/vnd.docker.distribution.manifest.v2+json";exports.OCI_IMAGE_INDEX="application/vnd.oci.image.index.v1+json";exports.DOCKER_MANIFEST_LIST="application/vnd.docker.distribution.manifest.list.v2+json";exports.MANIFEST_MEDIA_TYPES=[exports.OCI_IMAGE_MANIFEST,exports.DOCKER_IMAGE_MANIFEST,exports.OCI_IMAGE_INDEX,exports.DOCKER_MANIFEST_LIST];exports.IMAGE_MANIFEST_MEDIA_TYPES=[exports.OCI_IMAGE_MANIFEST,exports.DOCKER_IMAGE_MANIFEST]}});var require_action_image=__commonJS({"../contracts/dist/action-image.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_IMAGE_MANIFEST_BYTES=exports.ACTION_RUNTIME_IMAGE=exports.ACTION_RUNTIME_REPOSITORY=void 0;exports.imageConfigDescriptor=imageConfigDescriptor2;exports.actionImageRefusal=actionImageRefusal2;var action_repository_1=require_action_repository();var action_signing_1=require_action_signing();var oci_media_types_1=require_oci_media_types();exports.ACTION_RUNTIME_REPOSITORY="ghcr.io/runveric/action-runtime";exports.ACTION_RUNTIME_IMAGE=`${exports.ACTION_RUNTIME_REPOSITORY}@sha256:55126390dc54a79668e8475757f6de6dabc8c052242079d48d888eca4fdd5963`;exports.MAX_IMAGE_MANIFEST_BYTES=64*1024;var isRecord=__name(value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"isRecord");function imageConfigDescriptor2(manifest){if(!isRecord(manifest)||typeof manifest.mediaType!=="string")return null;if(!oci_media_types_1.IMAGE_MANIFEST_MEDIA_TYPES.includes(manifest.mediaType)||manifest.schemaVersion!==2)return null;const config=manifest.config;if(!isRecord(config)||typeof config.digest!=="string")return null;if(typeof config.size!=="number"||!Number.isInteger(config.size)||config.size<0)return null;return{digest:config.digest,size:config.size}}__name(imageConfigDescriptor2,"imageConfigDescriptor");function actionImageRefusal2(input){const{key,image,manifest,config,provenance:provenance2}=input;const mediaType=isRecord(manifest)?manifest.mediaType:void 0;if(typeof mediaType!=="string"||!oci_media_types_1.IMAGE_MANIFEST_MEDIA_TYPES.includes(mediaType)){return`${image} is ${typeof mediaType==="string"?`a ${mediaType}`:"a manifest of no declared type"}, not one image. An engine action's digest names exactly one linux/amd64 image manifest \u2014 never an index of several.`}if(imageConfigDescriptor2(manifest)===null){return`${image} is not an image manifest \u2014 it names no config descriptor (schemaVersion 2, a digest and a size).`}if(!isRecord(config)){return`${image}'s config is not a JSON object, so it cannot say what it was built for.`}const platform=`${String(config.os)}/${String(config.architecture)}`;if(platform!=="linux/amd64"){return`${image} is built for ${platform}; an engine action runs on linux/amd64, which is what Container Apps Jobs run.`}const labels=isRecord(config.config)&&isRecord(config.config.Labels)?config.config.Labels:{};const expected=(0,action_repository_1.actionSourceRepository)(key);const source=labels[action_signing_1.IMAGE_SOURCE_LABEL];if(source!==expected){return`the image of action "${key}" says it was built in ${source===void 0?"no repository (it carries no "+action_signing_1.IMAGE_SOURCE_LABEL+" label)":JSON.stringify(source)}, not ${expected}. A signature binds a digest and never a name, so an image built for another action cannot run under this one's manifest.`}if(provenance2.repository!==expected){return`the artifact of action "${key}" says it was authored in ${JSON.stringify(provenance2.repository)}, not ${expected}, which its image names.`}const revision=labels[action_signing_1.IMAGE_REVISION_LABEL];if(revision!==provenance2.commit){return`the image of action "${key}" says it was built at ${revision===void 0?"no commit (it carries no "+action_signing_1.IMAGE_REVISION_LABEL+" label)":JSON.stringify(revision)}, not ${provenance2.commit}, the commit its artifact was published from. An image and the manifest it runs under come from one commit, so neither can be swapped for another's.`}return null}__name(actionImageRefusal2,"actionImageRefusal")}});var require_catalog_templates=__commonJS({"../contracts/dist/catalog-templates.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.renderTemplate=renderTemplate2;exports.workflowValues=workflowValues2;var action_image_1=require_action_image();var action_signing_1=require_action_signing();var TEMPLATE_PLACEHOLDER=/\{\{([A-Z_]+)\}\}/g;function renderTemplate2(name3,text,values){return text.replace(TEMPLATE_PLACEHOLDER,(whole,key)=>{if(!Object.prototype.hasOwnProperty.call(values,key)){throw new Error(`${name3} uses ${whole}, which this script does not fill.`)}return values[key]})}__name(renderTemplate2,"renderTemplate");function workflowValues2(cli){return{CLI_PACKAGE:cli.name,CLI_VERSION:cli.version,ACTION_RUNTIME_IMAGE:action_image_1.ACTION_RUNTIME_IMAGE,ACTION_SIGNATURE_REPOSITORY:action_signing_1.ACTION_SIGNATURE_REPOSITORY}}__name(workflowValues2,"workflowValues")}});var require_runner_pool_presence=__commonJS({"../contracts/dist/runner-pool-presence.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUNNER_WAIT_MOMENTS=exports.LIFECYCLE_EXPLAINS=exports.RUNNER_KEPT_SENTENCE=exports.LIFECYCLE_ENDING=exports.RUNNER_ABANDONED_AFTER_MS=exports.VERSION_STANDING_CAN_RECOVER=exports.LIFECYCLE_CAN_RECOVER=exports.PRESENCE_CAN_RECOVER=void 0;exports.runnerRemovability=runnerRemovability;exports.countsAsBusy=countsAsBusy;exports.summarisePool=summarisePool;exports.poolNotice=poolNotice;exports.poolCanRecover=poolCanRecover;exports.formatWaitDuration=formatWaitDuration;exports.runnerWaitSentence=runnerWaitSentence;exports.runnerWaitRecordOf=runnerWaitRecordOf;exports.waitRecordReader=waitRecordReader;exports.isRunnerWaitRecord=isRunnerWaitRecord;exports.runnerClaimedSentence=runnerClaimedSentence;exports.poolWaitWarningSentence=poolWaitWarningSentence;var runners_1=require_runners();var brand_1=require_brand();exports.PRESENCE_CAN_RECOVER={online:true,quiet:true,offline:false};exports.LIFECYCLE_CAN_RECOVER={active:true,draining:false,revoked:false};exports.VERSION_STANDING_CAN_RECOVER={current:true,behind:true,unsupported:false};exports.RUNNER_ABANDONED_AFTER_MS=30*24*60*60*1e3;exports.LIFECYCLE_ENDING={active:{kind:"abandonment",afterMs:exports.RUNNER_ABANDONED_AFTER_MS},draining:{kind:"abandonment",afterMs:exports.RUNNER_ABANDONED_AFTER_MS},revoked:{kind:"ended"}};function runnerRemovability(runner,now){if(exports.PRESENCE_CAN_RECOVER[(0,runners_1.runnerPresence)(runner,now)]){return{removable:false,kept:"connected"}}if(runner.busy)return{removable:false,kept:"holding-a-step"};const ending=exports.LIFECYCLE_ENDING[runner.lifecycle];if(ending.kind==="ended")return{removable:true,because:"ended"};const silentForMs=now-new Date(runner.lastSeenAt).getTime();if(silentForMs<ending.afterMs)return{removable:false,kept:"within-retention"};return{removable:true,because:"abandoned"}}__name(runnerRemovability,"runnerRemovability");exports.RUNNER_KEPT_SENTENCE={connected:__name(name3=>`\u201C${name3}\u201D still has a working credential, so it can still be told to stand down or brought back. Revoke it first \u2014 that is what ends a runner you want gone now.`,"connected"),"holding-a-step":__name(name3=>`\u201C${name3}\u201D is still holding a step. Removing it now would leave the run that is waiting on it unable to say who claimed the work. It clears by itself when the step expires.`,"holding-a-step"),"within-retention":__name(name3=>`\u201C${name3}\u201D has not been heard from for less than ${Math.round(exports.RUNNER_ABANDONED_AFTER_MS/(24*60*60*1e3))} days. Revoke it if you want it gone now, or leave it \u2014 a host that comes back keeps its place until then.`,"within-retention")};function countsAsBusy(runner,now){return(0,runners_1.runnerPresence)(runner,now)==="online"&&runner.busy}__name(countsAsBusy,"countsAsBusy");function summarisePool(runners,now,policy){const summary={online:0,quiet:0,offline:0,total:runners.length,busy:0,behind:0,unsupported:0,draining:0,revoked:0,available:0,recoverable:0,removable:0};for(const runner of runners){const presence=(0,runners_1.runnerPresence)(runner,now);summary[presence]+=1;if(countsAsBusy(runner,now))summary.busy+=1;if(runner.lifecycle==="draining")summary.draining+=1;if(runner.lifecycle==="revoked")summary.revoked+=1;const standing=policy===null?"current":(0,runners_1.runnerVersionStanding)(runner.version,policy);if(standing==="behind")summary.behind+=1;if(standing==="unsupported")summary.unsupported+=1;if(presence==="online"&&runner.lifecycle==="active"&&standing!=="unsupported"){summary.available+=1}if(exports.PRESENCE_CAN_RECOVER[presence]&&exports.LIFECYCLE_CAN_RECOVER[runner.lifecycle]&&exports.VERSION_STANDING_CAN_RECOVER[standing]){summary.recoverable+=1}if(runnerRemovability(runner,now).removable)summary.removable+=1}return summary}__name(summarisePool,"summarisePool");exports.LIFECYCLE_EXPLAINS={active:[],draining:[],revoked:["connection"]};function connectionFinding(c){if(c.offline===c.total){return{axis:"connection",tone:"danger",finding:"Every runner in this pool is offline: their credentials have expired, so none can come back on its own.",continuation:"They are also offline, so none can come back on its own.",remedy:"Runs bound to this pool will wait until one is installed again."}}if(c.quiet===c.total){return{axis:"connection",tone:"warning",finding:"No runner in this pool has polled recently, so runs bound to it will wait.",continuation:"None of them has polled recently either.",remedy:"If they are restarting this clears on its own; if not, check they can still reach this control plane on 443 outbound."}}return null}__name(connectionFinding,"connectionFinding");function lifecycleFinding(l){if(l.revoked===l.total){return{axis:"lifecycle",tone:"danger",finding:"Every runner in this pool has been revoked, so none can claim work and none can come back.",continuation:"Every one of them has also been revoked, so none can come back.",remedy:"Revoking is one-way: issue a new registration token and install a runner again on each host that should run work here.",explains:exports.LIFECYCLE_EXPLAINS.revoked}}if(l.draining===l.total){return{axis:"lifecycle",tone:"warning",finding:"Every runner in this pool is draining, so runs bound to it will wait.",continuation:"Every one of them is also draining.",remedy:"That is a state somebody chose here \u2014 resume a runner below to put it back to work, or install a replacement before removing the last one.",explains:exports.LIFECYCLE_EXPLAINS.draining}}return null}__name(lifecycleFinding,"lifecycleFinding");function versionFinding(v){if(v.unsupported!==v.total)return null;return{axis:"version",tone:"danger",finding:`Every runner in this pool is running a build this ${brand_1.BRAND_SHORT_NAME} will not hand work to, so runs bound to it will wait indefinitely.`,continuation:`They are also on a build this ${brand_1.BRAND_SHORT_NAME} will not hand work to, so they will still be refused when they reconnect.`,remedy:"Pull the current runner images and start each host again with a new registration token."}}__name(versionFinding,"versionFinding");function crossAxisClause(findings,connection){const onlyVersion=findings.length===1&&findings[0].axis==="version";if(!onlyVersion)return null;return connection.online===connection.total?"They are still connected \u2014 this is a version problem, not a network one.":null}__name(crossAxisClause,"crossAxisClause");function poolNotice(summary,reader){if(summary.total===0)return null;if(summary.available>0){const busyElsewhere=summary.busy-(reader?.busyWithThisRun??0);if(busyElsewhere<summary.available)return null;return{tone:"neutral",message:"Every runner here that can take work is busy. New runs wait for one to finish \u2014 install another runner in the same pool to widen it."}}const found=[connectionFinding(summary),lifecycleFinding(summary),versionFinding(summary)].filter(finding=>finding!==null);const explained=new Set(found.flatMap(finding=>finding.explains??[]));const findings=found.filter(finding=>!explained.has(finding.axis));if(findings.length===0){return{tone:poolCanRecover(summary)?"warning":"danger",message:"No runner in this pool can take work right now \u2014 they are variously not connected, draining, revoked, or on too old a build. Runs bound to this pool will wait until one is available. Each runner's own row says which it is."}}const cross=crossAxisClause(findings,summary);const[first2,...rest]=findings;const message=[first2.finding,...rest.map(finding=>finding.continuation),cross,...findings.map(finding=>finding.remedy)].filter(part=>Boolean(part)).join(" ");return{tone:findings.some(finding=>finding.tone==="danger")?"danger":"warning",message}}__name(poolNotice,"poolNotice");function poolCanRecover(summary){if(summary.total===0)return true;return summary.recoverable>0}__name(poolCanRecover,"poolCanRecover");function formatWaitDuration(ms){const seconds=Math.max(0,Math.round(ms/1e3));if(seconds<60)return`${seconds}s`;const minutes=Math.floor(seconds/60);const rest=seconds%60;return rest===0?`${minutes}m`:`${minutes}m ${String(rest).padStart(2,"0")}s`}__name(formatWaitDuration,"formatWaitDuration");exports.RUNNER_WAIT_MOMENTS=["handoff","waiting","changed"];function runnerWaitSentence(wait,moment){switch(moment){case"handoff":return handoffSentence(wait);case"waiting":return stillWaitingSentence(wait,false);case"changed":return stillWaitingSentence(wait,true)}}__name(runnerWaitSentence,"runnerWaitSentence");function handoffSentence(wait){const deadline=`It waits up to ${formatWaitDuration(wait.remainingMs)} for one to claim it.`;const notice=poolNotice(wait.presence,{busyWithThisRun:wait.busyWithThisRun});if(wait.presence.available>0&&!notice){const n=wait.presence.available;return`Handed to runner pool \u201C${wait.poolName}\u201D \u2014 ${n} runner${n===1?"":"s"} able to take it. ${deadline}`}return`Handed to runner pool \u201C${wait.poolName}\u201D, and nothing there can take work right now. `+`${notice?.message??""} ${deadline}`.replace(/\s+/gu," ").trim()}__name(handoffSentence,"handoffSentence");function stillWaitingSentence(wait,conditionChanged){const head=`Still waiting for a runner in pool \u201C${wait.poolName}\u201D \u2014 ${formatWaitDuration(wait.waitedMs)} so far, ${formatWaitDuration(wait.remainingMs)} before this run gives up.`;if(!conditionChanged)return head;const notice=poolNotice(wait.presence,{busyWithThisRun:wait.busyWithThisRun});return notice?`${head} ${notice.message}`:`${head} Something here can take work now.`}__name(stillWaitingSentence,"stillWaitingSentence");function runnerWaitRecordOf(value){if(!isRunnerWaitRecord(value))return null;return{poolId:value.poolId,poolName:value.poolName,presence:value.presence,observedAt:value.observedAt,busyWithThisRun:typeof value.busyWithThisRun==="number"?value.busyWithThisRun:null}}__name(runnerWaitRecordOf,"runnerWaitRecordOf");function waitRecordReader(record){return typeof record.busyWithThisRun==="number"?{busyWithThisRun:record.busyWithThisRun}:null}__name(waitRecordReader,"waitRecordReader");function isRunnerWaitRecord(value){if(typeof value!=="object"||value===null)return false;const record=value;if(typeof record.poolId!=="string"||typeof record.poolName!=="string")return false;if(typeof record.observedAt!=="string")return false;if(record.busyWithThisRun!==void 0&&record.busyWithThisRun!==null&&typeof record.busyWithThisRun!=="number"){return false}const presence=record.presence;if(typeof presence!=="object"||presence===null)return false;return typeof presence.online==="number"&&typeof presence.quiet==="number"&&typeof presence.offline==="number"&&typeof presence.total==="number"&&typeof presence.busy==="number"&&typeof presence.behind==="number"&&typeof presence.unsupported==="number"&&typeof presence.draining==="number"&&typeof presence.revoked==="number"&&typeof presence.available==="number"&&typeof presence.recoverable==="number"}__name(isRunnerWaitRecord,"isRunnerWaitRecord");function runnerClaimedSentence(runnerName,waitedMs){return`Claimed by runner \u201C${runnerName}\u201D after ${formatWaitDuration(waitedMs)}.`}__name(runnerClaimedSentence,"runnerClaimedSentence");function poolWaitWarningSentence(warning){const notice=poolNotice(warning.presence,null);const consequence=`This run will be accepted and will wait up to ${formatWaitDuration(warning.waitsUpToMs)} for a runner to take it.`;return notice?`${notice.message} ${consequence}`:consequence}__name(poolWaitWarningSentence,"poolWaitWarningSentence")}});var require_routable_target=__commonJS({"../contracts/dist/routable-target.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_runner_pool_routing=__commonJS({"../contracts/dist/runner-pool-routing.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUNNER_POOL_RULES_PER_SCOPE_MAX=void 0;exports.routeRunnerPool=routeRunnerPool;exports.matchesRunnerPoolRule=matchesRunnerPoolRule;exports.runnerPoolRulesOverlap=runnerPoolRulesOverlap;exports.runnerPoolMatchIsEmpty=runnerPoolMatchIsEmpty;exports.describeRunnerPoolMatch=describeRunnerPoolMatch;exports.poolRoutingSentence=poolRoutingSentence;var run_placement_1=require_run_placement();exports.RUNNER_POOL_RULES_PER_SCOPE_MAX=100;function routeRunnerPool(bindings,targets){const byPool=new Map;for(const target of targets){const rule=bindings.rules.find(candidate=>matchesRunnerPoolRule(target,candidate.match));const pool=rule?rule.pool:bindings.default;const via=rule?{source:"rule",rule:{id:rule.id,name:rule.name,match:rule.match}}:{source:"default"};const key=pool?`pool:${pool.id}`:"hosted";const seen=byPool.get(key);if(seen){seen.match.targetCount+=1;continue}byPool.set(key,{match:{pool:pool??HOSTED_ROUTING_DESTINATION,via,exampleResourceId:target.resourceId,targetCount:1},pool})}if(byPool.size>1){return{kind:"ambiguous",matches:[...byPool.values()].map(entry=>entry.match)}}const only=[...byPool.values()][0];if(!only){return bindings.default?{kind:"pool",pool:bindings.default,via:{source:"default"}}:{kind:"hosted"}}if(!only.pool)return{kind:"hosted"};return{kind:"pool",pool:only.pool,via:only.match.via}}__name(routeRunnerPool,"routeRunnerPool");var HOSTED_ROUTING_DESTINATION={id:"",name:run_placement_1.HOSTED_EXECUTION_LABEL};function matchesRunnerPoolRule(target,match){const groups=lowerSet(match.resourceGroups);if(groups&&!groups.has((target.resourceGroup??"").trim().toLowerCase()))return false;const excluded=lowerSet(match.excludeResourceIds);if(excluded?.has(target.resourceId.trim().toLowerCase()))return false;const prefix=match.namePrefix?.trim().toLowerCase();if(prefix&&!target.name.trim().toLowerCase().startsWith(prefix))return false;for(const[key,value]of Object.entries(match.tags??{})){if(findTagValue(target.tags,key)!==value)return false}return true}__name(matchesRunnerPoolRule,"matchesRunnerPoolRule");function runnerPoolRulesOverlap(a,b){const groupsA=lowerSet(a.resourceGroups);const groupsB=lowerSet(b.resourceGroups);if(groupsA&&groupsB&&![...groupsA].some(group=>groupsB.has(group)))return false;const tagsA=lowerKeyed(a.tags);const tagsB=lowerKeyed(b.tags);for(const[key,value]of tagsA){if(tagsB.has(key)&&tagsB.get(key)!==value)return false}const prefixA=a.namePrefix?.trim().toLowerCase()??"";const prefixB=b.namePrefix?.trim().toLowerCase()??"";if(!prefixA.startsWith(prefixB)&&!prefixB.startsWith(prefixA))return false;return true}__name(runnerPoolRulesOverlap,"runnerPoolRulesOverlap");function runnerPoolMatchIsEmpty(match){return(match.resourceGroups?.filter(group=>group.trim()).length??0)===0&&Object.keys(match.tags??{}).length===0&&!match.namePrefix?.trim()}__name(runnerPoolMatchIsEmpty,"runnerPoolMatchIsEmpty");function describeRunnerPoolMatch(match){const parts=[];const groups=match.resourceGroups?.filter(group=>group.trim());if(groups?.length)parts.push(`resource groups: ${groups.join(", ")}`);const tags=Object.entries(match.tags??{});if(tags.length){parts.push(`tags (all of): ${tags.map(([key,value])=>`${key}=${value}`).join(", ")}`)}if(match.namePrefix?.trim())parts.push(`name prefix: "${match.namePrefix.trim()}"`);const excluded=match.excludeResourceIds?.filter(id=>id.trim());if(excluded?.length){parts.push(`${excluded.length} excluded resource ${excluded.length===1?"id":"ids"}`)}return parts.length>0?parts.join("; "):"every resource in this connection"}__name(describeRunnerPoolMatch,"describeRunnerPoolMatch");function poolRoutingSentence(via){return via.source==="default"?"this connection's default pool":`the rule \u201C${via.rule.name}\u201D (${describeRunnerPoolMatch(via.rule.match)})`}__name(poolRoutingSentence,"poolRoutingSentence");function lowerSet(values){if(!values||values.length===0)return null;const set=new Set;for(const value of values){const key=value.trim().toLowerCase();if(key)set.add(key)}return set.size>0?set:null}__name(lowerSet,"lowerSet");function lowerKeyed(tags){const map=new Map;for(const[key,value]of Object.entries(tags??{})){const normalized=key.trim().toLowerCase();if(normalized)map.set(normalized,value)}return map}__name(lowerKeyed,"lowerKeyed");function findTagValue(tags,key){if(!tags)return void 0;const wanted=key.trim().toLowerCase();for(const[tagKey,value]of Object.entries(tags)){if(tagKey.trim().toLowerCase()===wanted)return value}return void 0}__name(findTagValue,"findTagValue")}});var require_target_identity=__commonJS({"../contracts/dist/target-identity.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TARGET_LIST_SHOWN=exports.TARGET_NAMES_IN_A_SENTENCE=exports.TARGETS_HAVE_NO_NAME=exports.TARGETS_NOT_NAMED=void 0;exports.namedTargets=namedTargets;exports.targetsUnnamed=targetsUnnamed;exports.targetLabel=targetLabel;exports.unnamedTargetsSentence=unnamedTargetsSentence;exports.unnamedTargetsLabel=unnamedTargetsLabel;exports.resolvedTargetsOf=resolvedTargetsOf;exports.compareTargetIdentities=compareTargetIdentities;exports.targetIdentitiesAgree=targetIdentitiesAgree;exports.targetIdentityDriftSentence=targetIdentityDriftSentence;var brand_1=require_brand();function namedTargets(targets){return{targets}}__name(namedTargets,"namedTargets");function targetsUnnamed(reason,detail){return detail?{unnamed:reason,detail}:{unnamed:reason}}__name(targetsUnnamed,"targetsUnnamed");exports.TARGETS_NOT_NAMED={unnamed:"not_attempted"};exports.TARGETS_HAVE_NO_NAME={unnamed:"no_scope"};function targetLabel(target){const name3=target.name.trim();const group=target.resourceGroup?.trim();return group?`${name3} (${group})`:name3}__name(targetLabel,"targetLabel");function unnamedTargetsSentence(unnamed){switch(unnamed.unnamed){case"no_scope":return`This action does not declare a resource ${brand_1.BRAND_SHORT_NAME} can name \u2014 the run's parameters say what it acts on.`;case"unavailable":return unnamed.detail?`${brand_1.BRAND_SHORT_NAME} could not name this run's resource \u2014 ${unnamed.detail}.`:`${brand_1.BRAND_SHORT_NAME} could not name this run's resource.`;case"not_attempted":return`${brand_1.BRAND_SHORT_NAME} has not resolved this run's resources yet.`}}__name(unnamedTargetsSentence,"unnamedTargetsSentence");function unnamedTargetsLabel(unnamed){switch(unnamed.unnamed){case"no_scope":return"None declared";case"unavailable":return"Could not name";case"not_attempted":return"Not resolved"}}__name(unnamedTargetsLabel,"unnamedTargetsLabel");function resolvedTargetsOf(stored){if(typeof stored.unnamed==="string"){return isTargetIdentityAbsence(stored.unnamed)?targetsUnnamed(stored.unnamed,typeof stored.detail==="string"&&stored.detail.trim()?stored.detail:void 0):exports.TARGETS_NOT_NAMED}if(!Array.isArray(stored.targets))return exports.TARGETS_NOT_NAMED;const targets=stored.targets.flatMap(entry=>{const target=routableTargetOf(entry);return target?[target]:[]});if(stored.targets.length>0&&targets.length===0)return exports.TARGETS_NOT_NAMED;return namedTargets(targets)}__name(resolvedTargetsOf,"resolvedTargetsOf");function routableTargetOf(value){if(typeof value!=="object"||value===null||Array.isArray(value))return void 0;const entry=value;const resourceId=typeof entry.resourceId==="string"?entry.resourceId.trim():"";const name3=typeof entry.name==="string"?entry.name.trim():"";if(!resourceId||!name3)return void 0;const resourceGroup=typeof entry.resourceGroup==="string"&&entry.resourceGroup.trim()?entry.resourceGroup.trim():void 0;return{resourceId,name:name3,...resourceGroup?{resourceGroup}:{}}}__name(routableTargetOf,"routableTargetOf");function isTargetIdentityAbsence(value){return value==="no_scope"||value==="unavailable"||value==="not_attempted"}__name(isTargetIdentityAbsence,"isTargetIdentityAbsence");function compareTargetIdentities(planned,executed){if(planned.unnamed||executed.unnamed)return null;const key=__name(target=>target.resourceId.trim().toLowerCase(),"key");const executedIds=new Set(executed.targets.map(key));const plannedIds=new Set(planned.targets.map(key));return{dropped:planned.targets.filter(target=>!executedIds.has(key(target))),added:executed.targets.filter(target=>!plannedIds.has(key(target))),kept:planned.targets.filter(target=>executedIds.has(key(target)))}}__name(compareTargetIdentities,"compareTargetIdentities");function targetIdentitiesAgree(drift){return drift.dropped.length===0&&drift.added.length===0}__name(targetIdentitiesAgree,"targetIdentitiesAgree");exports.TARGET_NAMES_IN_A_SENTENCE=3;function targetIdentityDriftSentence(drift){if(drift.dropped.length===0&&drift.added.length===0)return null;const separable=labelsSeparate(drift);const clauses=[];if(drift.dropped.length>0){clauses.push(`did not act on ${countedResources(drift.dropped.length)} the plan named`+(separable?` \u2014 ${nameList(drift.dropped)}`:""))}if(drift.added.length>0){clauses.push(`acted on ${countedResources(drift.added.length)} the plan did not name`+(separable?` \u2014 ${nameList(drift.added)}`:""))}return`This run ${clauses.join("; and it ")}.`+(separable?"":" Their names do not tell them apart \u2014 the ids below do.")}__name(targetIdentityDriftSentence,"targetIdentityDriftSentence");function labelsSeparate(drift){const dropped=new Set(drift.dropped.map(targetLabel));return drift.added.every(target=>!dropped.has(targetLabel(target)))}__name(labelsSeparate,"labelsSeparate");function countedResources(total){return`${total} ${total===1?"resource":"resources"}`}__name(countedResources,"countedResources");function nameList(targets){const shown=targets.slice(0,exports.TARGET_NAMES_IN_A_SENTENCE).map(targetLabel);const rest=targets.length-shown.length;if(rest>0)shown.push(`${rest} more`);if(shown.length===1)return shown[0];return`${shown.slice(0,-1).join(", ")} and ${shown[shown.length-1]}`}__name(nameList,"nameList");exports.TARGET_LIST_SHOWN=20}});var require_declared_targets=__commonJS({"../contracts/dist/declared-targets.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.nameDeclaredTargets=nameDeclaredTargets;var resources_1=require_resources();var target_identity_1=require_target_identity();function nameDeclaredTargets(input){const{parameterSchema,provider,parameters,providerScopeId}=input;const declared=routableDeclarations(parameterSchema,provider);const targets=[];for(const candidate of declared){if(declared.some(other=>other.parents.includes(candidate.parameterName)))continue;const named=parameters[candidate.parameterName];if(typeof named!=="string"||!named.trim())continue;if(!candidate.spec.identity)continue;let declaredType;if(candidate.spec.takesResourceType){const composable=(0,resources_1.armIdentityResourceType)(candidate.resourceType);if(composable===null)continue;declaredType=composable}const values=(0,resources_1.discoveryScopeValues)(candidate.spec.identifiedBy??candidate.spec.requires,candidate.dependsOn,parameters);if(!values.resolved){return(0,target_identity_1.targetsUnnamed)("unavailable",`identifying the "${candidate.parameterName}" parameter needs a "${values.parameter}" value, which this run does not carry`)}const identity=(0,resources_1.composeTargetIdentity)(candidate.spec.identity,{...values.scope,subscription:providerScopeId,name:named.trim(),...declaredType?{resourceType:declaredType}:{}});if(!identity.composed){return(0,target_identity_1.targetsUnnamed)("unavailable",`identifying "${named.trim()}" needs a "${identity.missing}" value, which this run does not carry`)}targets.push({resourceId:identity.resourceId,name:named.trim(),...values.scope.resourceGroup?{resourceGroup:values.scope.resourceGroup}:{}})}return targets.length>0?(0,target_identity_1.namedTargets)(targets):target_identity_1.TARGETS_HAVE_NO_NAME}__name(nameDeclaredTargets,"nameDeclaredTargets");function routableDeclarations(parameterSchema,provider){const declarations=[];for(const[parameterName,property]of Object.entries(parameterSchema?.properties??{})){const declared=typeof property.discover==="string"?property.discover.trim():"";if(!declared)continue;const parsed=(0,resources_1.parseDiscoveryType)(declared,provider);const spec=parsed?(0,resources_1.discoveryTypeSpec)(parsed.provider,parsed.type):void 0;if(!spec?.routable)continue;const lookup=(0,resources_1.dependsOnLookup)(spec.requires,property.dependsOn);declarations.push({parameterName,spec,dependsOn:property.dependsOn,resourceType:property.resourceType,parents:spec.requires.map(key=>lookup[key]??key)})}return declarations}__name(routableDeclarations,"routableDeclarations")}});var require_catalog_parameters=__commonJS({"../contracts/dist/catalog-parameters.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.catalogParameterSchema=catalogParameterSchema2;var catalog_1=require_catalog();var resources_1=require_resources();function catalogParameterSchema2(params){const properties={};const required=[];for(const p of params){const prop={type:p.control==="switch"?"boolean":"string",title:p.label,description:p.hint,control:p.control};if(p.options)prop.enum=p.options;if(p.source){const discover=(0,resources_1.canonicalDiscoveryId)(p.source.discover);if(discover===null){throw new Error(`Parameter "${p.id}" discovers "${p.source.discover}", which is not a discovery id.`)}prop.discover=discover;if(p.source.dependsOn?.length)prop.dependsOn=p.source.dependsOn;const typeRefusal=(0,resources_1.resourceTypeDeclarationRefusal)(discover,p.source.resourceType);if(typeRefusal!==null)throw new Error(`Parameter "${p.id}": ${typeRefusal}`);if(p.source.resourceType!==void 0)prop.resourceType=p.source.resourceType}if(p.default!==void 0&&!p.source)prop.default=p.default;properties[p.id]=prop;if(p.required)required.push(p.id)}return(0,catalog_1.withParameterOrder)({$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties,required,additionalProperties:false})}__name(catalogParameterSchema2,"catalogParameterSchema")}});var require_engine_run=__commonJS({"../contracts/dist/engine-run.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.engineRunTarget=engineRunTarget2;exports.destructiveSuccessRefusal=destructiveSuccessRefusal2;var declared_targets_1=require_declared_targets();function engineRunTarget2(input){const named=(0,declared_targets_1.nameDeclaredTargets)({parameterSchema:input.parameterSchema,provider:input.provider,parameters:input.parameters,providerScopeId:input.providerScopeId});const only=named.unnamed?void 0:named.targets.length===1?named.targets[0]:void 0;if(!only){throw new Error(`An engine action acts on exactly one target per run, named by a discovered parameter; this run of "${input.key}" names ${named.unnamed?`none (${named.detail??named.unnamed})`:named.targets.length}.`)}return{ref:only.resourceId,parameters:input.parameters}}__name(engineRunTarget2,"engineRunTarget");function destructiveSuccessRefusal2(input){if(input.outcome.status==="succeeded"&&input.destructive&&!input.dryRun&&!input.acknowledgedCheckpoint&&input.restorePoint===null){return{status:"failed",message:`"${input.key}" reported success, but it is destructive and no restore point was acknowledged before it acted, so the engine does not accept that success. Check the target's state before running it again.`,data:{refused:"destructive-success-without-checkpoint",reported:input.outcome.message}}}return null}__name(destructiveSuccessRefusal2,"destructiveSuccessRefusal")}});var require_which_entra=__commonJS({"../contracts/dist/which-entra.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AZURE_CONNECTION_PRINCIPAL_SENTENCE=exports.AZURE_CONNECTION_ENTRA_SENTENCE=exports.SIGN_IN_ENTRA_SENTENCE=void 0;var brand_1=require_brand();exports.SIGN_IN_ENTRA_SENTENCE=`Signing in installs nothing in your identity directory. Letting ${brand_1.BRAND_SHORT_NAME} act on your cloud resources is a separate step, set up later, and that one does need an identity in the directory that owns them.`;exports.AZURE_CONNECTION_ENTRA_SENTENCE=`This is the other Entra. Connecting Azure is a different question from signing in: this step is about the Microsoft Entra tenant that owns the subscription you want ${brand_1.BRAND_SHORT_NAME} to act on.`;exports.AZURE_CONNECTION_PRINCIPAL_SENTENCE=`${brand_1.BRAND_SHORT_NAME} needs a service principal in that tenant \u2014 an app registration or a managed identity \u2014 and it is required: there is no way to act on your resources without one. No secret leaves your tenant; the trust is a federated credential you create below. It can do only what your Azure role assignments allow, on the subscriptions or resource groups you pick, and ${brand_1.BRAND_SHORT_NAME} never asks for Microsoft Graph or any directory permission. You can revoke it at any time in your own portal by removing the federated credential or the role assignment.`}});var require_onboarding=__commonJS({"../contracts/dist/onboarding.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NO_WORKSPACE_CODE=void 0;exports.NO_WORKSPACE_CODE="NO_WORKSPACE"}});var require_workspace_domain=__commonJS({"../contracts/dist/workspace-domain.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WORKSPACE_DOMAIN_RELEASE_CONSEQUENCE=exports.WORKSPACE_DOMAIN_STATE_SENTENCE=exports.DOMAIN_CHECK_OUTCOME_SENTENCE=exports.DOMAIN_VERIFICATION_RECORD_PREFIX=exports.DOMAIN_CHECK_OUTCOMES=exports.DOMAIN_PROOF_MAX_AGE_MS=exports.DOMAIN_PROOF_MAX_AGE_DAYS=exports.WORKSPACE_DOMAIN_STATES=void 0;exports.workspaceDomainState=workspaceDomainState;exports.domainVerificationRecord=domainVerificationRecord;exports.WORKSPACE_DOMAIN_STATES=["pending","verified","unconfirmed"];exports.DOMAIN_PROOF_MAX_AGE_DAYS=30;exports.DOMAIN_PROOF_MAX_AGE_MS=exports.DOMAIN_PROOF_MAX_AGE_DAYS*24*60*60*1e3;function workspaceDomainState(proof,now){const current=proof.verifiedAt!==null&&proof.lastVerifiedAt!==null&&now.getTime()-proof.lastVerifiedAt.getTime()<=exports.DOMAIN_PROOF_MAX_AGE_MS;if(current)return"verified";return proof.verifiedAt===null?"pending":"unconfirmed"}__name(workspaceDomainState,"workspaceDomainState");exports.DOMAIN_CHECK_OUTCOMES=["verified","record_missing","domain_unknown","dns_unreachable","challenge_expired","held_elsewhere"];exports.DOMAIN_VERIFICATION_RECORD_PREFIX="runveric-domain-verification=";function domainVerificationRecord(domain,token2){return{name:domain,type:"TXT",value:`${exports.DOMAIN_VERIFICATION_RECORD_PREFIX}${token2}`}}__name(domainVerificationRecord,"domainVerificationRecord");exports.DOMAIN_CHECK_OUTCOME_SENTENCE={verified:"The record was found and this domain is verified for this workspace.",record_missing:"The zone answered, but the record this workspace must publish was not among its TXT values.",domain_unknown:"This domain does not resolve at all, so no record could be looked for on it yet.",dns_unreachable:"The DNS check could not complete, which says nothing about the record itself yet.",challenge_expired:"The challenge has expired and a record carrying it would not be accepted any more.",held_elsewhere:"Another workspace holds this domain verified and its own record is still published there."};exports.WORKSPACE_DOMAIN_STATE_SENTENCE={pending:"Nobody can join by this domain until the record below is found in its zone.",verified:`Colleagues with an address at this domain can join without an invitation. The record must stay published: it is read again by later checks, and a proof that no check can confirm for ${exports.DOMAIN_PROOF_MAX_AGE_DAYS} days lapses until one does.`,unconfirmed:"This workspace still holds the domain, but its record could not be confirmed recently, so nobody can join by it until a check finds the record again. The record itself has not changed; make the value below visible in the zone, then check again."};exports.WORKSPACE_DOMAIN_RELEASE_CONSEQUENCE={pending:"The claim and its record are discarded. You can claim the domain again later, with a new record.",verified:"Colleagues will no longer be able to join by this domain. Members already in the workspace keep their access.",unconfirmed:"The workspace gives up the domain it still holds. Claiming it again later means publishing a new record, and another workspace may take it meanwhile."}}});var require_workspace_features=__commonJS({"../contracts/dist/workspace-features.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WORKSPACE_FEATURE_COPY=exports.WORKSPACE_FEATURES=void 0;exports.isWorkspaceFeature=isWorkspaceFeature;var brand_1=require_brand();exports.WORKSPACE_FEATURES=["directory_sync"];exports.WORKSPACE_FEATURE_COPY={directory_sync:{name:"Directory sync",notEntitled:`Group membership is managed here in ${brand_1.BRAND_SHORT_NAME}. Mirroring groups from your identity provider is a paid add-on \u2014 contact ${brand_1.BRAND_SHORT_NAME} to turn it on for this workspace.`}};function isWorkspaceFeature(value){return exports.WORKSPACE_FEATURES.includes(value)}__name(isWorkspaceFeature,"isWorkspaceFeature")}});var require_directory_sync=__commonJS({"../contracts/dist/directory-sync.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DIRECTORY_SYNC_UNAVAILABLE_CODE=exports.DIRECTORY_GROUP_UNMAINTAINED=exports.DIRECTORY_SYNC_AVAILABILITY_SENTENCE=exports.DIRECTORY_SYNC_AVAILABILITY_STATES=void 0;var brand_1=require_brand();var DIRECTORY_SYNC_AVAILABILITY_STATE_SET={not_entitled:true,not_connected:true,available:true};exports.DIRECTORY_SYNC_AVAILABILITY_STATES=Object.keys(DIRECTORY_SYNC_AVAILABILITY_STATE_SET);exports.DIRECTORY_SYNC_AVAILABILITY_SENTENCE={not_entitled:{headline:"Directory sync is not enabled for this workspace",detail:`Group membership is managed here in ${brand_1.BRAND_SHORT_NAME}. Mirroring groups from your identity provider is a paid add-on \u2014 contact ${brand_1.BRAND_SHORT_NAME} to turn it on for this workspace.`},not_connected:{headline:"No directory is connected",detail:"Directory sync is enabled for this workspace, but no identity directory is connected to it yet. Once one is connected, its groups can be linked here and their membership is mirrored at sign-in."},available:{headline:"Directory sync is on",detail:`A group linked to your directory mirrors its membership every time one of its members signs in. Roles stay attached here in ${brand_1.BRAND_SHORT_NAME}.`}};exports.DIRECTORY_GROUP_UNMAINTAINED={short:"Membership is not being maintained \u2014 no directory is connected.",detail:"This group is linked to a directory that is not connected, so nobody is added to it or removed from it automatically, and nothing is synced. Its roles still apply to whoever is already a member."};exports.DIRECTORY_SYNC_UNAVAILABLE_CODE="DIRECTORY_SYNC_UNAVAILABLE"}});var require_workos_binding=__commonJS({"../contracts/dist/workos-binding.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WORKOS_DEFAULT_API_HOSTNAME=exports.WORKOS_CLIENT_ID_PATTERN=exports.WORKOS_ENVIRONMENT_KEY_PREFIXES=exports.WORKOS_ENVIRONMENTS=void 0;exports.workosEnvironmentOfApiKey=workosEnvironmentOfApiKey;exports.workosIssuer=workosIssuer;exports.workosJwksUri=workosJwksUri;exports.workosBindingSentence=workosBindingSentence;exports.WORKOS_ENVIRONMENTS=["staging","production"];exports.WORKOS_ENVIRONMENT_KEY_PREFIXES={staging:"sk_test_",production:"sk_live_"};function workosEnvironmentOfApiKey(apiKey){for(const environment of exports.WORKOS_ENVIRONMENTS){if(apiKey.startsWith(exports.WORKOS_ENVIRONMENT_KEY_PREFIXES[environment])){return environment}}return null}__name(workosEnvironmentOfApiKey,"workosEnvironmentOfApiKey");exports.WORKOS_CLIENT_ID_PATTERN=/client_[0-9A-HJKMNP-TV-Z]{26}/;exports.WORKOS_DEFAULT_API_HOSTNAME="api.workos.com";function workosIssuer(apiHostname,clientId){return`https://${apiHostname}/user_management/${clientId}`}__name(workosIssuer,"workosIssuer");function workosJwksUri(apiHostname,clientId){return`https://${apiHostname}/sso/jwks/${clientId}`}__name(workosJwksUri,"workosJwksUri");function workosBindingSentence(binding){if(!binding.workosEnabled){return"WorkOS is disabled: this process authenticates nobody through it."}return`WorkOS binding: client ${binding.clientId??"(none)"}, environment ${binding.environment??"(not declared)"}.`}__name(workosBindingSentence,"workosBindingSentence")}});var require_dist=__commonJS({"../contracts/dist/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:__name(function(){return m[k]},"get")}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]});var __exportStar=exports&&exports.__exportStar||function(m,exports1){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports1,p))__createBinding(exports1,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require_enums(),exports);__exportStar(require_brand(),exports);__exportStar(require_wire_identity(),exports);__exportStar(require_problem(),exports);__exportStar(require_permissions(),exports);__exportStar(require_request_context(),exports);__exportStar(require_role_permissions(),exports);__exportStar(require_me(),exports);__exportStar(require_tenant_users(),exports);__exportStar(require_invitations(),exports);__exportStar(require_groups(),exports);__exportStar(require_catalog_version(),exports);__exportStar(require_catalog_policy(),exports);__exportStar(require_catalog(),exports);__exportStar(require_catalog_release(),exports);__exportStar(require_action_repository(),exports);__exportStar(require_catalog_release_spec(),exports);__exportStar(require_catalog_lock(),exports);__exportStar(require_catalog_manifest_placeholders(),exports);__exportStar(require_change_control(),exports);__exportStar(require_execution(),exports);__exportStar(require_decisions(),exports);__exportStar(require_execution_site(),exports);__exportStar(require_run_placement(),exports);__exportStar(require_connections(),exports);__exportStar(require_resources(),exports);__exportStar(require_governance(),exports);__exportStar(require_audit(),exports);__exportStar(require_notifications(),exports);__exportStar(require_scheduling(),exports);__exportStar(require_operations(),exports);__exportStar(require_runs(),exports);__exportStar(require_evidence_pack(),exports);__exportStar(require_package_tier(),exports);__exportStar(require_package_provenance(),exports);__exportStar(require_packages(),exports);__exportStar(require_package_egress(),exports);__exportStar(require_package_execution(),exports);__exportStar(require_runner_confinement(),exports);__exportStar(require_runner_install(),exports);__exportStar(require_authoring_cli(),exports);__exportStar(require_runners(),exports);__exportStar(require_scoped_credential(),exports);__exportStar(require_action_protocol(),exports);__exportStar(require_action_signing(),exports);__exportStar(require_oci_media_types(),exports);__exportStar(require_action_image(),exports);__exportStar(require_catalog_templates(),exports);__exportStar(require_runner_pool_presence(),exports);__exportStar(require_routable_target(),exports);__exportStar(require_runner_pool_routing(),exports);__exportStar(require_target_identity(),exports);__exportStar(require_declared_targets(),exports);__exportStar(require_catalog_parameters(),exports);__exportStar(require_engine_run(),exports);__exportStar(require_which_entra(),exports);__exportStar(require_onboarding(),exports);__exportStar(require_workspace_domain(),exports);__exportStar(require_workspace_features(),exports);__exportStar(require_directory_sync(),exports);__exportStar(require_workos_binding(),exports)}});var require_action_sdk_public=__commonJS({"../contracts/dist/action-sdk.public.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StaticScopedCredential=exports.ENGINE_ACTION_TOKEN_HOLDER=exports.settleDecisionChecks=exports.UNDECIDED_AT_RUN=exports.parseCheckpointAck=exports.actionTokenScope=void 0;var action_protocol_1=require_action_protocol();Object.defineProperty(exports,"actionTokenScope",{enumerable:true,get:__name(function(){return action_protocol_1.actionTokenScope},"get")});Object.defineProperty(exports,"parseCheckpointAck",{enumerable:true,get:__name(function(){return action_protocol_1.parseCheckpointAck},"get")});var decisions_1=require_decisions();Object.defineProperty(exports,"UNDECIDED_AT_RUN",{enumerable:true,get:__name(function(){return decisions_1.UNDECIDED_AT_RUN},"get")});Object.defineProperty(exports,"settleDecisionChecks",{enumerable:true,get:__name(function(){return decisions_1.settleDecisionChecks},"get")});var scoped_credential_1=require_scoped_credential();Object.defineProperty(exports,"ENGINE_ACTION_TOKEN_HOLDER",{enumerable:true,get:__name(function(){return scoped_credential_1.ENGINE_ACTION_TOKEN_HOLDER},"get")});Object.defineProperty(exports,"StaticScopedCredential",{enumerable:true,get:__name(function(){return scoped_credential_1.StaticScopedCredential},"get")})}});var require_dist2=__commonJS({"../action-sdk/dist/index.js"(exports,module){"use strict";var __defProp2=Object.defineProperty;var __getOwnPropDesc2=Object.getOwnPropertyDescriptor;var __getOwnPropNames2=Object.getOwnPropertyNames;var __hasOwnProp2=Object.prototype.hasOwnProperty;var __name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:true}),"__name");var __export=__name((target,all)=>{for(var name3 in all)__defProp2(target,name3,{get:all[name3],enumerable:true})},"__export");var __copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames2(from))if(!__hasOwnProp2.call(to,key)&&key!==except)__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable})}return to},"__copyProps");var __toCommonJS=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:true}),mod),"__toCommonJS");var src_exports={};__export(src_exports,{RestorePointNotAcknowledgedError:__name(()=>RestorePointNotAcknowledgedError,"RestorePointNotAcknowledgedError"),UNDECIDED_AT_RUN:__name(()=>import_action_sdk3.UNDECIDED_AT_RUN,"UNDECIDED_AT_RUN"),actionCredential:__name(()=>actionCredential,"actionCredential"),defineAction:__name(()=>defineAction,"defineAction"),executeContext:__name(()=>executeContext,"executeContext"),rollbackContext:__name(()=>rollbackContext,"rollbackContext"),settleDecisionChecks:__name(()=>import_action_sdk3.settleDecisionChecks,"settleDecisionChecks"),validateContext:__name(()=>validateContext,"validateContext")});module.exports=__toCommonJS(src_exports);function defineAction(definition){for(const handler of["validate","execute"]){if(typeof definition[handler]!=="function"){throw new TypeError(`An action must define a "${handler}" handler.`)}}if(definition.rollback!==void 0&&typeof definition.rollback!=="function"){throw new TypeError(`An action's "rollback", when present, must be a handler.`)}return definition}__name(defineAction,"defineAction");__name2(defineAction,"defineAction");var import_action_sdk2=require_action_sdk_public();var import_action_sdk=require_action_sdk_public();function actionCredential(tokens2,now=Date.now,holder=import_action_sdk.ENGINE_ACTION_TOKEN_HOLDER){return new import_action_sdk.StaticScopedCredential(tokens2.map(token2=>({scope:(0,import_action_sdk.actionTokenScope)(token2.audience),token:token2.token,expiresOnTimestamp:Date.parse(token2.expiresOn)})),now,holder)}__name(actionCredential,"actionCredential");__name2(actionCredential,"actionCredential");var RestorePointNotAcknowledgedError=class extends Error{static{__name(this,"RestorePointNotAcknowledgedError")}static{__name2(this,"RestorePointNotAcknowledgedError")}constructor(reason){super(`The restore point was not acknowledged by the engine, so nothing may be acted on: ${reason}`);this.name="RestorePointNotAcknowledgedError"}};function validateContext(invocation,channel,signal,now=Date.now,holder){return{...commonContext(invocation,channel,signal,now,holder),mode:invocation.mode,targets:invocation.targets,decisions:invocation.decisions}}__name(validateContext,"validateContext");__name2(validateContext,"validateContext");function executeContext(invocation,channel,signal,now=Date.now,holder){return{...commonContext(invocation,channel,signal,now,holder),target:onlyTarget(invocation.targets),decisions:invocation.decisions,restorePoint:invocation.restorePoint,saveRestorePoint:__name2(async record=>{let answer;try{answer=await channel.checkpoint({kind:"restore_point",record})}catch(cause){throw new RestorePointNotAcknowledgedError(messageOf2(cause))}try{(0,import_action_sdk2.parseCheckpointAck)(answer)}catch(cause){throw new RestorePointNotAcknowledgedError(messageOf2(cause))}},"saveRestorePoint")}}__name(executeContext,"executeContext");__name2(executeContext,"executeContext");function rollbackContext(invocation,channel,signal,now=Date.now,holder){return{...commonContext(invocation,channel,signal,now,holder),target:onlyTarget(invocation.targets),decisions:invocation.decisions,restorePoint:invocation.restorePoint,priorResult:invocation.priorResult}}__name(rollbackContext,"rollbackContext");__name2(rollbackContext,"rollbackContext");function commonContext(invocation,channel,signal,now,holder){return{azure:actionCredential(invocation.credentials.tokens,now,holder),emit:__name2(event=>channel.emit(event),"emit"),signal,dryRun:invocation.execution.dryRun,action:{key:invocation.action.key,version:invocation.action.version},execution:{id:invocation.execution.id,tenantId:invocation.execution.tenantId,correlationId:invocation.execution.correlationId}}}__name(commonContext,"commonContext");__name2(commonContext,"commonContext");function onlyTarget(targets){const[target]=targets;if(!target||targets.length!==1){throw new Error(`An act names exactly one target; this invocation names ${targets.length}.`)}return target}__name(onlyTarget,"onlyTarget");__name2(onlyTarget,"onlyTarget");function messageOf2(cause){return cause instanceof Error?cause.message:String(cause)}__name(messageOf2,"messageOf");__name2(messageOf2,"messageOf");var import_action_sdk3=require_action_sdk_public()}});var require_dist3=__commonJS({"../action-runtime/dist/index.js"(exports,module){"use strict";var __defProp2=Object.defineProperty;var __getOwnPropDesc2=Object.getOwnPropertyDescriptor;var __getOwnPropNames2=Object.getOwnPropertyNames;var __hasOwnProp2=Object.prototype.hasOwnProperty;var __name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:true}),"__name");var __export=__name((target,all)=>{for(var name3 in all)__defProp2(target,name3,{get:all[name3],enumerable:true})},"__export");var __copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames2(from))if(!__hasOwnProp2.call(to,key)&&key!==except)__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable})}return to},"__copyProps");var __toCommonJS=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:true}),mod),"__toCommonJS");var src_exports={};__export(src_exports,{ACTION_ENTRY:__name(()=>ACTION_ENTRY,"ACTION_ENTRY"),ActionDeadlineError:__name(()=>ActionDeadlineError,"ActionDeadlineError"),EGRESS_WAIT:__name(()=>EGRESS_WAIT,"EGRESS_WAIT"),EgressProxyNotListeningError:__name(()=>EgressProxyNotListeningError,"EgressProxyNotListeningError"),EgressProxyUrlError:__name(()=>EgressProxyUrlError,"EgressProxyUrlError"),EngineRefusedError:__name(()=>EngineRefusedError,"EngineRefusedError"),HttpTransport:__name(()=>HttpTransport,"HttpTransport"),LoopbackTransport:__name(()=>LoopbackTransport2,"LoopbackTransport"),PROBE_CONNECT_TARGETS:__name(()=>PROBE_CONNECT_TARGETS,"PROBE_CONNECT_TARGETS"),PROBE_EXIT:__name(()=>PROBE_EXIT,"PROBE_EXIT"),RUNTIME_EXIT:__name(()=>RUNTIME_EXIT,"RUNTIME_EXIT"),actionOf:__name(()=>actionOf2,"actionOf"),main:__name(()=>main2,"main"),probe:__name(()=>probe,"probe"),runAction:__name(()=>runAction2,"runAction"),waitForEgressProxy:__name(()=>waitForEgressProxy,"waitForEgressProxy")});module.exports=__toCommonJS(src_exports);var import_contracts16=require_dist();var import_action_sdk=require_dist2();async function runAction2(definition,transport,options={}){const now=options.now??Date.now;const invocation=(0,import_contracts16.parseActionInvocation)(await transport.fetchInvocation());const secrets=invocation.credentials.tokens.map(token2=>token2.token);const handlerSignal=new AbortController;let deadlineTimer;const deadlineReached=new Promise(resolve8=>{deadlineTimer=setTimeout(()=>{handlerSignal.abort(new ActionDeadlineError(invocation.limits.deadline));resolve8(DEADLINE)},Math.max(0,Date.parse(invocation.limits.deadline)-now()))});const onCancel=__name2(()=>handlerSignal.abort(options.cancel?.reason),"onCancel");if(options.cancel?.aborted)onCancel();options.cancel?.addEventListener("abort",onCancel,{once:true});const channel={emit:__name2(event=>transport.postEvent((0,import_contracts16.redactSecrets)(event,secrets)),"emit"),checkpoint:__name2(checkpoint=>transport.postCheckpoint(checkpoint),"checkpoint")};try{const answered=await Promise.race([answer(definition,invocation,channel,handlerSignal.signal,now,options.tokenHolder).catch(error=>failedReport(invocation,isCancel(error,options.cancel)?"cancelled":"failed",error)),deadlineReached]);const report=(0,import_contracts16.redactSecrets)(answered===DEADLINE?failedReport(invocation,"failed",new ActionDeadlineError(invocation.limits.deadline)):answered,secrets);await transport.postReport(report);return report}finally{clearTimeout(deadlineTimer);options.cancel?.removeEventListener("abort",onCancel)}}__name(runAction2,"runAction");__name2(runAction2,"runAction");var ActionDeadlineError=class extends Error{static{__name(this,"ActionDeadlineError")}static{__name2(this,"ActionDeadlineError")}constructor(deadline){super(`The action did not finish before its deadline (${deadline}), so it was stopped.`);this.name="ActionDeadlineError"}};var DEADLINE=Symbol("deadline");async function answer(definition,invocation,channel,signal,now,holder){switch(invocation.phase){case"validate":return{phase:"validate",checks:await definition.validate((0,import_action_sdk.validateContext)(invocation,channel,signal,now,holder))};case"run":return{phase:"run",outcome:await definition.execute((0,import_action_sdk.executeContext)(invocation,channel,signal,now,holder))};case"rollback":if(!definition.rollback){return{phase:"rollback",outcome:{status:"failed",message:`"${invocation.action.key}" has no rollback.`}}}return{phase:"rollback",outcome:await definition.rollback((0,import_action_sdk.rollbackContext)(invocation,channel,signal,now,holder))}}}__name(answer,"answer");__name2(answer,"answer");function failedReport(invocation,status,error){const message=messageOf2(error);if(invocation.phase==="validate"){return{phase:"validate",outcome:{status:"failed",message}}}return{phase:invocation.phase,outcome:{status,message}}}__name(failedReport,"failedReport");__name2(failedReport,"failedReport");function isCancel(error,cancel){return cancel?.aborted===true&&error instanceof Error&&error.name==="AbortError"}__name(isCancel,"isCancel");__name2(isCancel,"isCancel");function messageOf2(error){const message=error instanceof Error?error.message:String(error);return message.length>0?message:"The action failed without saying why."}__name(messageOf2,"messageOf");__name2(messageOf2,"messageOf");var LoopbackTransport2=class{static{__name(this,"LoopbackTransport")}static{__name2(this,"LoopbackTransport")}engine;constructor(engine){this.engine=engine}async fetchInvocation(){return overTheWire(await this.engine.invocation())}async postEvent(event){await this.engine.event(overTheWire(event))}async postCheckpoint(checkpoint){return overTheWire(await this.engine.checkpoint(overTheWire(checkpoint)))}async postReport(report){await this.engine.report(overTheWire(report))}};function overTheWire(value){const text=JSON.stringify(value);return text===void 0?void 0:JSON.parse(text)}__name(overTheWire,"overTheWire");__name2(overTheWire,"overTheWire");var import_contracts22=require_dist();var EngineRefusedError=class extends Error{static{__name(this,"EngineRefusedError")}static{__name2(this,"EngineRefusedError")}status;constructor(status,message){super(message),this.status=status;this.name="EngineRefusedError"}};var HttpTransport=class{static{__name(this,"HttpTransport")}static{__name2(this,"HttpTransport")}options;fetch;constructor(options){this.options=options;assertSafeOrigin(options.callbackBaseUrl);this.fetch=options.fetch??globalThis.fetch}async fetchInvocation(){const response=await this.send("invocation","GET");if(response.status!==200)throw await refusalOf(response);return response.json()}async postEvent(event){const response=await this.send("events","POST",event);if(response.status!==204)throw await refusalOf(response)}async postCheckpoint(checkpoint){const response=await this.send("checkpoint","POST",checkpoint);if(response.status!==200)throw await refusalOf(response);return response.json()}async postReport(report){const response=await this.send("report","POST",report);if(response.status===204||response.status===409)return;throw await refusalOf(response)}send(message,method,body){return this.fetch((0,import_contracts22.engineRunUrl)(this.options.callbackBaseUrl,this.options.runId,message),{method,redirect:"error",headers:{[import_contracts22.RUN_TOKEN_HEADER]:this.options.runToken,accept:"application/json",...body===void 0?{}:{"content-type":"application/json"}},...body===void 0?{}:{body:JSON.stringify(body)}})}};var LOOPBACK_HOSTS=new Set(["127.0.0.1","localhost"]);function assertSafeOrigin(callbackBaseUrl){let url;try{url=new URL(callbackBaseUrl)}catch{throw new Error(`The engine's callback origin "${callbackBaseUrl}" is not a URL.`)}if(url.protocol==="https:")return;if(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname))return;throw new Error(`The engine's callback origin "${url.origin}" is not HTTPS. A run token is a bearer secret, so it travels only over HTTPS \u2014 or to 127.0.0.1 or localhost, inside the job's own network.`)}__name(assertSafeOrigin,"assertSafeOrigin");__name2(assertSafeOrigin,"assertSafeOrigin");async function refusalOf(response){let sentence=`The engine answered ${response.status}.`;try{const body=await response.json();if(typeof body.message==="string"&&body.message.length>0)sentence=body.message}catch{}return new EngineRefusedError(response.status,sentence)}__name(refusalOf,"refusalOf");__name2(refusalOf,"refusalOf");var import_action_sdk2=require_dist2();var import_contracts32=require_dist();var import_node_net=__require("net");var EGRESS_WAIT={timeoutMs:6e4,intervalMs:250};var EgressProxyNotListeningError=class extends Error{static{__name(this,"EgressProxyNotListeningError")}static{__name2(this,"EgressProxyNotListeningError")}constructor(message){super(message);this.name="EgressProxyNotListeningError"}};var EgressProxyUrlError=class extends Error{static{__name(this,"EgressProxyUrlError")}static{__name2(this,"EgressProxyUrlError")}constructor(){super("HTTPS_PROXY is not a URL with a host.");this.name="EgressProxyUrlError"}};var REAL_CLOCK={now:__name2(()=>Date.now(),"now"),sleep:__name2(ms=>new Promise(resolve8=>setTimeout(resolve8,ms)),"sleep")};function egressProxyUrl(env){return env.HTTPS_PROXY||env.https_proxy||void 0}__name(egressProxyUrl,"egressProxyUrl");__name2(egressProxyUrl,"egressProxyUrl");function egressProxyAddress(proxyUrl){let url;try{url=new URL(proxyUrl)}catch{return void 0}const host=url.hostname.replace(/^\[(.*)\]$/,"$1");if(!host)return void 0;return{host,port:Number(url.port||(url.protocol==="https:"?443:80)),origin:`${url.protocol}//${url.host}`}}__name(egressProxyAddress,"egressProxyAddress");__name2(egressProxyAddress,"egressProxyAddress");async function waitForEgressProxy(proxyUrl,options={}){const address=egressProxyAddress(proxyUrl);if(!address)throw new EgressProxyUrlError;const connect=options.connect??import_node_net.connect;const clock=options.clock??REAL_CLOCK;const deadline=clock.now()+EGRESS_WAIT.timeoutMs;while(clock.now()<deadline){if(await accepts(connect,address))return;await clock.sleep(EGRESS_WAIT.intervalMs)}throw new EgressProxyNotListeningError(`The egress proxy at ${address.origin} did not accept a connection within ${EGRESS_WAIT.timeoutMs/1e3} s, so the action was not run: it declares an outbound allowlist, and running it without the proxy would give it unrestricted network.`)}__name(waitForEgressProxy,"waitForEgressProxy");__name2(waitForEgressProxy,"waitForEgressProxy");function accepts(connect,address){return new Promise(resolve8=>{let settled=false;const socket=connect(address.port,address.host);const finish=__name2(accepted=>{if(settled)return;settled=true;socket.destroy();resolve8(accepted)},"finish");socket.setTimeout(EGRESS_WAIT.intervalMs,()=>finish(false));socket.on("error",()=>finish(false));socket.once("connect",()=>finish(true))})}__name(accepts,"accepts");__name2(accepts,"accepts");var ACTION_ENTRY="/action/index.js";var RUNTIME_EXIT={reported:0,failed:1,misconfigured:2,refused:3};async function main2(job){const missing=Object.values(import_contracts32.ACTION_CONTAINER_ENV).filter(name3=>!job.env[name3]);if(missing.length>0){job.say(`action-runtime: refused to start \u2014 ${missing.join(", ")} not set.`);return RUNTIME_EXIT.misconfigured}const runToken=job.env[import_contracts32.ACTION_CONTAINER_ENV.runToken];const say=__name2(line=>job.say((0,import_contracts32.redactJwtShaped)((0,import_contracts32.redactSecrets)(line,[runToken]))),"say");const imageDigest=job.env[import_contracts32.ACTION_CONTAINER_ENV.imageDigest];if(!import_contracts32.ARTIFACT_DIGEST_PATTERN.test(imageDigest)){say(`action-runtime: refused to start \u2014 ${import_contracts32.ACTION_CONTAINER_ENV.imageDigest} is not a sha256 digest.`);return RUNTIME_EXIT.misconfigured}const openTransport=__name2(()=>(job.transport??(options=>new HttpTransport(options)))({callbackBaseUrl:job.env[import_contracts32.ACTION_CONTAINER_ENV.callbackBaseUrl],runId:job.env[import_contracts32.ACTION_CONTAINER_ENV.runId],runToken}),"openTransport");const proxy=egressProxyUrl(job.env);if(proxy){try{await waitForEgressProxy(proxy,{connect:job.connect,clock:job.clock})}catch(error){if(!(error instanceof EgressProxyNotListeningError)){say(`action-runtime: refused to start \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.misconfigured}return notRun(error.message,openTransport,say)}}let definition;let transport;try{definition=actionOf2(job.load(ACTION_ENTRY),ACTION_ENTRY);transport=openTransport()}catch(error){say(`action-runtime: refused to start \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.misconfigured}let fetched;let invocation;try{fetched=await transport.fetchInvocation();invocation=(0,import_contracts32.parseActionInvocation)(fetched)}catch(error){say(`action-runtime: no invocation \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.failed}const phase=`${invocation.phase} of ${invocation.action.key}`;if(!invocation.action.image.endsWith(`@${imageDigest}`)){const refusal=`This runtime was started as ${imageDigest}, and the invocation names ${invocation.action.image}: it does not run another image's invocation.`;try{await transport.postReport(failedReport2(invocation,refusal))}catch{}say(`action-runtime: ${phase} refused \u2014 ${refusal}`);return RUNTIME_EXIT.refused}try{const report=await runAction2(definition,{fetchInvocation:__name2(async()=>fetched,"fetchInvocation"),postEvent:__name2(event=>transport.postEvent(event),"postEvent"),postCheckpoint:__name2(checkpoint=>transport.postCheckpoint(checkpoint),"postCheckpoint"),postReport:__name2(sent=>transport.postReport(sent),"postReport")});say(`action-runtime: ${phase} reported ${endingOf(report)}.`);return RUNTIME_EXIT.reported}catch(error){say(`action-runtime: ${phase} ended without an accepted report \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.failed}}__name(main2,"main");__name2(main2,"main");async function notRun(sentence,openTransport,say){let transport;try{transport=openTransport()}catch(error){say(`action-runtime: refused to start \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.misconfigured}let phase="the phase";try{const invocation=(0,import_contracts32.parseActionInvocation)(await transport.fetchInvocation());phase=`${invocation.phase} of ${invocation.action.key}`;await transport.postReport(failedReport2(invocation,sentence))}catch{}say(`action-runtime: ${phase} failed \u2014 ${sentence}`);return RUNTIME_EXIT.failed}__name(notRun,"notRun");__name2(notRun,"notRun");function actionOf2(loaded,from){const candidate=loaded!==null&&typeof loaded==="object"&&"default"in loaded?loaded.default:loaded;if(candidate===null||typeof candidate!=="object"){throw new Error(`${from} does not export an action: its default export must be defineAction({ \u2026 }).`)}return(0,import_action_sdk2.defineAction)(candidate)}__name(actionOf2,"actionOf");__name2(actionOf2,"actionOf");function failedReport2(invocation,message){return invocation.phase==="validate"?{phase:"validate",outcome:{status:"failed",message}}:{phase:invocation.phase,outcome:{status:"failed",message}}}__name(failedReport2,"failedReport2");__name2(failedReport2,"failedReport");function endingOf(report){return"checks"in report?"its checks":report.outcome.status}__name(endingOf,"endingOf");__name2(endingOf,"endingOf");function messageOf22(error){return error instanceof Error?error.message:String(error)}__name(messageOf22,"messageOf2");__name2(messageOf22,"messageOf");var import_node_net2=__require("net");var import_contracts42=require_dist();var AZURE_IDENTITY_ENV={endpoint:"IDENTITY_ENDPOINT",header:"IDENTITY_HEADER"};var AZURE_IDENTITY_API_VERSION="2019-08-01";var MANAGEMENT_RESOURCE2="https://management.azure.com/";var PROBE_CONNECT_TARGETS=["management.azure.com:443","example.com:443"];var ANSWER_TIMEOUT_MS=1e4;var PROBE_EXIT={probed:0,misconfigured:2};async function probe(job){const header=job.env[AZURE_IDENTITY_ENV.header];const say=__name2(line=>job.say((0,import_contracts42.redactJwtShaped)((0,import_contracts42.redactSecrets)(`action-runtime probe: ${line}`,header?[header]:[]))),"say");const callback=job.env[import_contracts42.ACTION_CONTAINER_ENV.callbackBaseUrl];if(!callback){say(`refused to start \u2014 ${import_contracts42.ACTION_CONTAINER_ENV.callbackBaseUrl} not set.`);return PROBE_EXIT.misconfigured}const fetchOf=job.fetch??globalThis.fetch;const endpoint=job.env[AZURE_IDENTITY_ENV.endpoint];say(`identity endpoint ${endpoint?"present":"absent"}`);const identities=(job.env[import_contracts42.ACTION_PROBE_ENV.identities]??"").split(",").map(id=>id.trim()).filter(id=>id.length>0);for(const id of identities){const label=identityLabel(id);if(!endpoint){say(`identity ${label}: not asked \u2014 no endpoint`);continue}const answer2=await statusOf(()=>{const url=new URL(endpoint);url.searchParams.set("api-version",AZURE_IDENTITY_API_VERSION);url.searchParams.set("resource",MANAGEMENT_RESOURCE2);url.searchParams.set(id.startsWith("/")?"mi_res_id":"client_id",id);return fetchOf(url,{redirect:"error",headers:header?{"x-identity-header":header}:{}})});say(`identity ${label}: token request answered ${answer2}`)}const proxy=egressProxyUrl(job.env);if(!proxy){say("egress: no proxy in the environment")}else if(await neverListened(proxy,job)){say(`egress: the proxy did not listen within ${EGRESS_WAIT.timeoutMs/1e3} s`)}else{for(const target of PROBE_CONNECT_TARGETS){say(`egress CONNECT ${target}: ${await connectStatus(proxy,target,job.connect??import_node_net2.connect)}`)}}const health=await statusOf(()=>fetchOf(`${callback.replace(/\/+$/,"")}/healthz`,{redirect:"error"}));say(`callback GET /healthz: ${health}`);say("done");return PROBE_EXIT.probed}__name(probe,"probe");__name2(probe,"probe");function identityLabel(id){return id.split("/").filter(Boolean).pop()??id}__name(identityLabel,"identityLabel");__name2(identityLabel,"identityLabel");async function statusOf(request){try{const response=await withTimeout(request());await response.body?.cancel().catch(()=>void 0);return String(response.status)}catch{return"unreachable"}}__name(statusOf,"statusOf");__name2(statusOf,"statusOf");async function neverListened(proxy,job){try{await waitForEgressProxy(proxy,{connect:job.connect,clock:job.clock});return false}catch(error){return error instanceof EgressProxyNotListeningError}}__name(neverListened,"neverListened");__name2(neverListened,"neverListened");function connectStatus(proxy,target,connect){const address=egressProxyAddress(proxy);if(!address)return Promise.resolve("proxy is not a URL");return new Promise(resolve8=>{let settled=false;let received="";const socket=connect(address.port,address.host);const finish=__name2(answer2=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();resolve8(answer2)},"finish");const timer=setTimeout(()=>finish("no answer"),ANSWER_TIMEOUT_MS);socket.once("error",()=>finish("unreachable"));socket.once("connect",()=>socket.write(`CONNECT ${target} HTTP/1.1\r
4
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:true});var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_enums=__commonJS({"../contracts/dist/enums.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUN_TRIGGER_KINDS=exports.ROLE_KEYS=exports.SETTLED_EXECUTION_STATUSES=exports.DIRECTLY_CANCELLABLE_EXECUTION_STATUSES=exports.WORKER_HELD_EXECUTION_STATUSES=exports.EXECUTION_CANCEL_MECHANISM=exports.EXECUTION_STATUS_SETTLED=exports.EXECUTION_STATUSES=exports.ENVIRONMENTS=exports.VERSION_STATUSES=exports.RISK_LEVELS=exports.ACTION_CATEGORIES=exports.CONNECTION_SCOPE_KINDS=exports.CONNECTION_STATES=exports.IDENTITY_MECHANISMS=exports.PROVIDERS=void 0;exports.maxRiskLevel=maxRiskLevel;exports.isSettledExecutionStatus=isSettledExecutionStatus;exports.PROVIDERS=["azure","aws","gcp","terraform"];exports.IDENTITY_MECHANISMS=["service_principal","managed_identity","iam_role","hcp_dynamic","api_token"];exports.CONNECTION_STATES=["draft","active","degraded"];exports.CONNECTION_SCOPE_KINDS=["subscription","account","project","workspace"];exports.ACTION_CATEGORIES=["compute","storage","security","databases","containers"];exports.RISK_LEVELS=["low","medium","high"];function maxRiskLevel(left,right){return exports.RISK_LEVELS.indexOf(left)>=exports.RISK_LEVELS.indexOf(right)?left:right}__name(maxRiskLevel,"maxRiskLevel");exports.VERSION_STATUSES=["draft","published","deprecated"];exports.ENVIRONMENTS=["production","staging","non_prod"];exports.EXECUTION_STATUSES=["draft","validating","validated","validation_failed","pending_approval","approved","rejected","queued","pending_runner","running","succeeded","rolling_back","failed","cancelled","rolled_back","rollback_failed"];exports.EXECUTION_STATUS_SETTLED={draft:false,validating:false,validated:false,validation_failed:true,pending_approval:false,approved:false,rejected:true,queued:false,pending_runner:false,running:false,succeeded:true,rolling_back:false,failed:true,cancelled:true,rolled_back:true,rollback_failed:true};exports.EXECUTION_CANCEL_MECHANISM={draft:"direct",validating:"no",validated:"direct",validation_failed:"no",pending_approval:"direct",approved:"no",rejected:"no",queued:"direct",pending_runner:"cooperative",running:"cooperative",succeeded:"no",rolling_back:"no",failed:"no",cancelled:"no",rolled_back:"no",rollback_failed:"no"};exports.WORKER_HELD_EXECUTION_STATUSES=exports.EXECUTION_STATUSES.filter(status=>exports.EXECUTION_CANCEL_MECHANISM[status]==="cooperative");exports.DIRECTLY_CANCELLABLE_EXECUTION_STATUSES=exports.EXECUTION_STATUSES.filter(status=>exports.EXECUTION_CANCEL_MECHANISM[status]==="direct");exports.SETTLED_EXECUTION_STATUSES=exports.EXECUTION_STATUSES.filter(status=>exports.EXECUTION_STATUS_SETTLED[status]);function isSettledExecutionStatus(status){return exports.EXECUTION_STATUS_SETTLED[status]===true}__name(isSettledExecutionStatus,"isSettledExecutionStatus");exports.ROLE_KEYS=["viewer","operator","approver","auditor","admin"];exports.RUN_TRIGGER_KINDS=["manual","schedule","api","agent"]}});var require_brand=__commonJS({"../contracts/dist/brand.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PACKAGE_IMPORTER_USER_AGENT=exports.BRAND_SLUG=exports.BRAND_ARTICLE_CAPITALISED=exports.BRAND_ARTICLE=exports.BRAND_SHORT_NAME=exports.BRAND_NAME=void 0;exports.BRAND_NAME="Runveric";exports.BRAND_SHORT_NAME=exports.BRAND_NAME.split(" ")[0];exports.BRAND_ARTICLE=/^[aeiou]/i.test(exports.BRAND_SHORT_NAME)?"an":"a";exports.BRAND_ARTICLE_CAPITALISED=exports.BRAND_ARTICLE==="an"?"An":"A";exports.BRAND_SLUG=exports.BRAND_NAME.replace(/[^A-Za-z0-9]+/g,"-").replace(/^-|-$/g,"");exports.PACKAGE_IMPORTER_USER_AGENT=`${exports.BRAND_SLUG}-Action-Package-Importer`}});var require_wire_identity=__commonJS({"../contracts/dist/wire-identity.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PROBLEM_TYPE_BASE=exports.CATALOG_ARTIFACT_MEDIA_TYPE=exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V2=exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V1=exports.CATALOG_RELEASE_SCHEMA_V1=exports.EVIDENCE_PACK_SCHEMA_VERSION=exports.ACTION_PROTOCOL_V1=exports.RUNNER_PROTOCOL_VERSION=exports.PACKAGE_WORK_ITEM_VERSION=exports.ACTION_MANIFEST_API_VERSION=exports.PACKAGE_EXECUTION_PROTOCOL_VERSION=exports.PACKAGE_RESULT_PROTOCOL_VERSION=void 0;exports.problemType=problemType;exports.PACKAGE_RESULT_PROTOCOL_VERSION="runveric.dev/package-result/v1";exports.PACKAGE_EXECUTION_PROTOCOL_VERSION="runveric.dev/package-execution/v1";exports.ACTION_MANIFEST_API_VERSION="runveric.dev/action/v1";exports.PACKAGE_WORK_ITEM_VERSION="runveric.dev/package-work-item/v1";exports.RUNNER_PROTOCOL_VERSION="runveric.dev/runner-channel/v2";exports.ACTION_PROTOCOL_V1="runveric.dev/action-protocol/v1";exports.EVIDENCE_PACK_SCHEMA_VERSION="runveric.dev/evidence-pack/v1";exports.CATALOG_RELEASE_SCHEMA_V1="runveric.dev/catalog-release/v1";exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V1="runveric.dev/catalog-action/v1";exports.CATALOG_ACTION_ARTIFACT_SCHEMA_V2="runveric.dev/catalog-action/v2";exports.CATALOG_ARTIFACT_MEDIA_TYPE="application/vnd.runveric.catalog-artifact+json";exports.PROBLEM_TYPE_BASE="https://runveric.dev/errors";function problemType(slug){return`${exports.PROBLEM_TYPE_BASE}/${slug}`}__name(problemType,"problemType")}});var require_problem=__commonJS({"../contracts/dist/problem.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parseProblemDocument=parseProblemDocument2;exports.problemFieldErrors=problemFieldErrors2;function isFieldError(entry){if(typeof entry!=="object"||entry===null)return false;const record=entry;return typeof record.field==="string"&&typeof record.message==="string"}__name(isFieldError,"isFieldError");function isManifestError(entry){if(typeof entry!=="object"||entry===null)return false;const record=entry;return typeof record.path==="string"&&typeof record.message==="string"}__name(isManifestError,"isManifestError");function optional(value,type){return value===void 0||typeof value===type}__name(optional,"optional");function parseProblemDocument2(body){if(typeof body!=="object"||body===null||Array.isArray(body))return null;const record=body;if(!optional(record.type,"string"))return null;if(!optional(record.title,"string"))return null;if(!optional(record.status,"number"))return null;if(!optional(record.detail,"string"))return null;if(!optional(record.code,"string"))return null;if(!optional(record.permission,"string"))return null;if(record.message!==void 0){const ok=typeof record.message==="string"||Array.isArray(record.message)&&record.message.every(one=>typeof one==="string");if(!ok)return null}if(record.errors!==void 0){if(!Array.isArray(record.errors))return null;const ok=record.errors.every(entry=>typeof entry==="string"||isFieldError(entry)||isManifestError(entry));if(!ok)return null}return record}__name(parseProblemDocument2,"parseProblemDocument");function problemFieldErrors2(problem){const entries=problem.errors??[];return entries.map(entry=>{if(typeof entry==="string")return{field:"",message:entry};if(isFieldError(entry))return{field:entry.field,message:entry.message};return{field:entry.path,message:entry.message}})}__name(problemFieldErrors2,"problemFieldErrors")}});var require_permissions=__commonJS({"../contracts/dist/permissions.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PLATFORM_PERMISSIONS=void 0;exports.PLATFORM_PERMISSIONS=["catalog:release"]}});var require_request_context=__commonJS({"../contracts/dist/request-context.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.hasPermission=hasPermission;function hasPermission(ctx,p){return ctx.permissions.includes(p)}__name(hasPermission,"hasPermission")}});var require_role_permissions=__commonJS({"../contracts/dist/role-permissions.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ROLE_PERMISSIONS=void 0;exports.permissionsForRoles=permissionsForRoles;var VIEWER=["catalog:read","subscription:read","operation:read","execution:read","execution:stream","evidence:read","connection:read"];exports.ROLE_PERMISSIONS={viewer:VIEWER,operator:[...VIEWER,"execution:create","execution:validate","execution:submit","execution:cancel","execution:rollback","operation:write"],approver:[...VIEWER,"approval:read","approval:decide"],auditor:[...VIEWER,"approval:read","audit:read"],admin:[...VIEWER,"execution:create","execution:validate","execution:submit","execution:cancel","execution:rollback","operation:write","approval:read","approval:decide","audit:read","connection:manage","package:manage","policy:manage","subscription:manage","rbac:manage"]};function permissionsForRoles(roles){const seen=new Set;for(const role of roles){for(const permission of exports.ROLE_PERMISSIONS[role]??[]){seen.add(permission)}}return[...seen]}__name(permissionsForRoles,"permissionsForRoles")}});var require_me=__commonJS({"../contracts/dist/me.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_tenant_users=__commonJS({"../contracts/dist/tenant-users.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_invitations=__commonJS({"../contracts/dist/invitations.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_groups=__commonJS({"../contracts/dist/groups.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_catalog_version=__commonJS({"../contracts/dist/catalog-version.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RETIRED_BETA_LIFECYCLE_REFUSAL=exports.RETIRED_BETA_LIFECYCLE=exports.FIRST_ACTION_VERSION=exports.CATALOG_CHANNEL_LABELS=exports.CATALOG_CHANNELS=void 0;exports.parseCatalogVersion=parseCatalogVersion;exports.catalogVersionString=catalogVersionString;exports.catalogVersionRefusal=catalogVersionRefusal;exports.channelOf=channelOf;exports.compareCatalogVersions=compareCatalogVersions;var CATALOG_CHANNEL_SET={ga:true,beta:true};exports.CATALOG_CHANNELS=Object.keys(CATALOG_CHANNEL_SET);exports.CATALOG_CHANNEL_LABELS={ga:"GA",beta:"Beta"};var NUMBER="(0|[1-9][0-9]*)";var CATALOG_VERSION_GRAMMAR=new RegExp(`^v${NUMBER}\\.${NUMBER}\\.${NUMBER}(?:-beta\\.([1-9][0-9]*))?$`);function parseCatalogVersion(value){const match=CATALOG_VERSION_GRAMMAR.exec(value);if(!match)return null;const[major,minor,patch]=[match[1],match[2],match[3]].map(Number);const beta=match[4]===void 0?null:Number(match[4]);if(![major,minor,patch,beta??0].every(Number.isSafeInteger))return null;return{major,minor,patch,beta}}__name(parseCatalogVersion,"parseCatalogVersion");function catalogVersionString(version6){const{major,minor,patch,beta}=version6;const text=`v${major}.${minor}.${patch}${beta===null?"":`-beta.${beta}`}`;if(parseCatalogVersion(text)===null)throw new Error(`${JSON.stringify(version6)} is not a catalog version.`);return text}__name(catalogVersionString,"catalogVersionString");exports.FIRST_ACTION_VERSION=catalogVersionString({major:0,minor:1,patch:0,beta:1});function catalogVersionRefusal(value){if(parseCatalogVersion(value)!==null)return null;return`version "${value}" is not a catalog version. Write vMAJOR.MINOR.PATCH for a GA release (e.g. "v1.4.0") or vMAJOR.MINOR.PATCH-beta.N for a beta (e.g. "v1.4.0-beta.1"): a "v", three numbers with no leading zeros, and for a beta a number from 1. Nothing else is accepted \u2014 no -rc or -alpha, and no +build metadata.`}__name(catalogVersionRefusal,"catalogVersionRefusal");exports.RETIRED_BETA_LIFECYCLE="beta";exports.RETIRED_BETA_LIFECYCLE_REFUSAL=`declares lifecycle "${exports.RETIRED_BETA_LIFECYCLE}", which is no longer a lifecycle. A beta is a VERSION: write version "vX.Y.Z-beta.N" (e.g. "v1.0.0-beta.1") and leave lifecycle out, or write "published". A beta version reaches only the workspaces that allowed beta actions; a lifecycle reached every workspace, which is why it was retired (docs/128 \xA721.2 D2).`;function channelOf(version6){const parsed=parseCatalogVersion(version6);if(parsed===null){throw new Error(`"${version6}" is not a catalog version, so it has no channel. ${catalogVersionRefusal(version6)}`)}return parsed.beta===null?"ga":"beta"}__name(channelOf,"channelOf");function compareCatalogVersions(left,right){const a=requireCatalogVersion(left);const b=requireCatalogVersion(right);return a.major-b.major||a.minor-b.minor||a.patch-b.patch||(a.beta===null?b.beta===null?0:1:b.beta===null?-1:a.beta-b.beta)}__name(compareCatalogVersions,"compareCatalogVersions");function requireCatalogVersion(value){const parsed=parseCatalogVersion(value);if(parsed===null)throw new Error(catalogVersionRefusal(value)??`"${value}" is not a catalog version.`);return parsed}__name(requireCatalogVersion,"requireCatalogVersion")}});var require_catalog_policy=__commonJS({"../contracts/dist/catalog-policy.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CATALOG_ALLOW_BETA_WHEN_UNSET=exports.CATALOG_RULE_EFFECTS=exports.CATALOG_DEFAULT_MODE_WHEN_UNSET=exports.CATALOG_DEFAULT_MODES=void 0;exports.effectiveCatalogAccess=effectiveCatalogAccess;var CATALOG_DEFAULT_MODE_SET={allow_all:true,deny_all:true};exports.CATALOG_DEFAULT_MODES=Object.keys(CATALOG_DEFAULT_MODE_SET);exports.CATALOG_DEFAULT_MODE_WHEN_UNSET="allow_all";var CATALOG_RULE_EFFECT_SET={allow:true,deny:true};exports.CATALOG_RULE_EFFECTS=Object.keys(CATALOG_RULE_EFFECT_SET);var RULE_ACCESS={allow:"allowed",deny:"blocked"};var UNRULED_ACCESS={allow_all:"allowed",deny_all:"blocked"};var CHANNEL_ACCESS={ga:{off:"allowed",on:"allowed"},beta:{off:"beta_not_allowed",on:"allowed"}};function effectiveCatalogAccess(defaultMode,rule,channel,allowBeta){const decided=rule!==null?RULE_ACCESS[rule]:UNRULED_ACCESS[defaultMode];if(decided==="blocked")return decided;return CHANNEL_ACCESS[channel][allowBeta?"on":"off"]}__name(effectiveCatalogAccess,"effectiveCatalogAccess");exports.CATALOG_ALLOW_BETA_WHEN_UNSET=false}});var require_catalog=__commonJS({"../contracts/dist/catalog.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NEW_ACTION_WINDOW_DAYS=exports.PARAMETER_ORDER_KEY=exports.PARAMETER_CONTROLS=exports.ACTION_LIFECYCLE_LABELS=exports.INACTIVE_ACTION_LIFECYCLES=exports.RUNNABLE_ACTION_LIFECYCLES=exports.LISTED_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLE_STANDING=exports.ACTION_LIFECYCLES=void 0;exports.orderedParameterEntries=orderedParameterEntries;exports.withParameterOrder=withParameterOrder;exports.isNewAction=isNewAction;exports.ACTION_LIFECYCLES=["draft","published","deprecated","retired"];exports.ACTION_LIFECYCLE_STANDING={draft:{listed:false,runnable:false},published:{listed:true,runnable:true},deprecated:{listed:true,runnable:true},retired:{listed:false,runnable:false}};exports.LISTED_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLES.filter(lifecycle=>exports.ACTION_LIFECYCLE_STANDING[lifecycle].listed);exports.RUNNABLE_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLES.filter(lifecycle=>exports.ACTION_LIFECYCLE_STANDING[lifecycle].runnable);exports.INACTIVE_ACTION_LIFECYCLES=exports.ACTION_LIFECYCLES.filter(lifecycle=>!exports.ACTION_LIFECYCLE_STANDING[lifecycle].runnable);exports.ACTION_LIFECYCLE_LABELS={draft:"Draft",published:"Published",deprecated:"Deprecated",retired:"Retired"};exports.PARAMETER_CONTROLS=["select","text","switch","info"];exports.PARAMETER_ORDER_KEY="x-runveric-order";function orderedParameterEntries(schema){const properties=schema.properties??{};const declared=schema[exports.PARAMETER_ORDER_KEY]??[];const seen=new Set;const ordered=[];for(const id of declared){const property=properties[id];if(!property||seen.has(id))continue;seen.add(id);ordered.push([id,property])}for(const[id,property]of Object.entries(properties)){if(seen.has(id))continue;ordered.push([id,property])}return ordered}__name(orderedParameterEntries,"orderedParameterEntries");function withParameterOrder(schema){return{...schema,[exports.PARAMETER_ORDER_KEY]:Object.keys(schema.properties??{})}}__name(withParameterOrder,"withParameterOrder");exports.NEW_ACTION_WINDOW_DAYS=30;var MS_PER_DAY=24*60*60*1e3;function isNewAction(publishedAt,now){if(publishedAt===null)return false;const published=new Date(publishedAt).getTime();if(Number.isNaN(published))return false;const age=now.getTime()-published;return age>=0&&age<exports.NEW_ACTION_WINDOW_DAYS*MS_PER_DAY}__name(isNewAction,"isNewAction")}});var require_catalog_release=__commonJS({"../contracts/dist/catalog-release.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CatalogReleaseStateError=exports.CATALOG_SYNC_STALE_AFTER_MINUTES=exports.CATALOG_SYNC_INTERVAL_MINUTES=exports.CATALOG_SYNC_SOURCES=exports.CATALOG_SYNC_RUN_OUTCOMES=exports.ARTIFACT_DIGEST_PATTERN=exports.ARTIFACT_REPOSITORY_PATTERN=exports.CATALOG_ACTION_ARTIFACT_SCHEMA_VERSIONS=exports.CATALOG_RELEASE_SCHEMA_VERSIONS=void 0;exports.parseCatalogReleaseState=parseCatalogReleaseState;var wire_identity_1=require_wire_identity();exports.CATALOG_RELEASE_SCHEMA_VERSIONS=[wire_identity_1.CATALOG_RELEASE_SCHEMA_V1];exports.CATALOG_ACTION_ARTIFACT_SCHEMA_VERSIONS=[wire_identity_1.CATALOG_ACTION_ARTIFACT_SCHEMA_V1,wire_identity_1.CATALOG_ACTION_ARTIFACT_SCHEMA_V2];exports.ARTIFACT_REPOSITORY_PATTERN=/^[a-z0-9][a-z0-9.-]*(:[0-9]+)?(\/[a-z0-9][a-z0-9._-]*)+$/;exports.ARTIFACT_DIGEST_PATTERN=/^sha256:[0-9a-f]{64}$/;exports.CATALOG_SYNC_RUN_OUTCOMES=["applied","refused","superseded"];exports.CATALOG_SYNC_SOURCES=["directory","release"];exports.CATALOG_SYNC_INTERVAL_MINUTES=15;exports.CATALOG_SYNC_STALE_AFTER_MINUTES=exports.CATALOG_SYNC_INTERVAL_MINUTES*2;var CatalogReleaseStateError=class CatalogReleaseStateError extends Error{static{__name(this,"CatalogReleaseStateError")}constructor(message){super(message);this.name="CatalogReleaseStateError"}};exports.CatalogReleaseStateError=CatalogReleaseStateError;function stateObject(path,value){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new CatalogReleaseStateError(`${path} is not an object.`)}return value}__name(stateObject,"stateObject");function stateString(path,value,pattern,expected="a non-empty string"){if(typeof value!=="string"||value===""||pattern!==void 0&&!pattern.test(value)){throw new CatalogReleaseStateError(`${path} is ${JSON.stringify(value)}, not ${expected}.`)}return value}__name(stateString,"stateString");function stateInstant(path,value){const text=stateString(path,value);if(Number.isNaN(Date.parse(text))){throw new CatalogReleaseStateError(`${path} is "${text}", which is not a timestamp.`)}return text}__name(stateInstant,"stateInstant");var orNull=__name((value,read)=>value===null?null:read(value),"orNull");function stateMember(path,value,members){if(typeof value==="string"&&members.includes(value))return value;throw new CatalogReleaseStateError(`${path} is ${JSON.stringify(value)}; this build reads ${members.join(", ")}.`)}__name(stateMember,"stateMember");function parseSyncRun(value){const run3=stateObject("lastSync",value);const source=stateMember("lastSync.source",run3.source,exports.CATALOG_SYNC_SOURCES);const release=orNull(run3.release,raw=>{const fields=stateObject("lastSync.release",raw);return{artifactRef:stateString("lastSync.release.artifactRef",fields.artifactRef,exports.ARTIFACT_REPOSITORY_PATTERN,"a registry repository"),digest:stateString("lastSync.release.digest",fields.digest,exports.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),version:orNull(fields.version,label=>stateString("lastSync.release.version",label))}});if(source==="release"!==(release!==null)){throw new CatalogReleaseStateError(`lastSync.source is "${source}" and lastSync.release is ${release===null?"null":"set"}; a run names a release exactly when a release declared it.`)}return{startedAt:stateInstant("lastSync.startedAt",run3.startedAt),finishedAt:stateInstant("lastSync.finishedAt",run3.finishedAt),imageTag:orNull(run3.imageTag,tag=>stateString("lastSync.imageTag",tag)),source,release,outcome:stateMember("lastSync.outcome",run3.outcome,exports.CATALOG_SYNC_RUN_OUTCOMES),detail:stateString("lastSync.detail",run3.detail)}}__name(parseSyncRun,"parseSyncRun");function parsePinned(value){const pin=stateObject("release",value);return{artifactRef:stateString("release.artifactRef",pin.artifactRef,exports.ARTIFACT_REPOSITORY_PATTERN,"a registry repository"),digest:stateString("release.digest",pin.digest,exports.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),version:stateString("release.version",pin.version),provenance:orNull(pin.provenance,raw=>{const fields=stateObject("release.provenance",raw);return{repository:stateString("release.provenance.repository",fields.repository),commit:stateString("release.provenance.commit",fields.commit)}}),pinnedBy:stateString("release.pinnedBy",pin.pinnedBy),pinnedByName:orNull(pin.pinnedByName,name3=>stateString("release.pinnedByName",name3)),pinnedAt:stateInstant("release.pinnedAt",pin.pinnedAt)}}__name(parsePinned,"parsePinned");function parseCatalogReleaseState(value){const state=stateObject("the catalog release state",value);for(const field of["release","imageTag","lastSync","liveSince"]){if(!(field in state))throw new CatalogReleaseStateError(`${field} is missing.`)}const release=orNull(state.release,parsePinned);const liveSince=orNull(state.liveSince,instant=>stateInstant("liveSince",instant));if(release===null&&liveSince!==null){throw new CatalogReleaseStateError("liveSince is set with nothing pinned; only a pin goes live.")}return{release,imageTag:orNull(state.imageTag,tag=>stateString("imageTag",tag)),lastSync:orNull(state.lastSync,parseSyncRun),liveSince}}__name(parseCatalogReleaseState,"parseCatalogReleaseState")}});var require_action_repository=__commonJS({"../contracts/dist/action-repository.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ACTION_SOURCE_REPOSITORY_PREFIX=exports.ACTION_REPOSITORY_PREFIX=void 0;exports.actionKeyRefusal=actionKeyRefusal2;exports.isActionKey=isActionKey;exports.actionRepositoryName=actionRepositoryName4;exports.actionSourceRepository=actionSourceRepository2;exports.actionKeyOf=actionKeyOf;exports.actionPackageRefusal=actionPackageRefusal4;exports.ACTION_REPOSITORY_PREFIX="action-";var WORD=/^[a-z][a-z0-9]*$/;var VERB=/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*$/;function actionKeyRefusal2(key){const shape="an action key is <provider>.<resource>.<verb>: provider and resource are one lowercase word (a-z, then a-z or 0-9), the verb is camelCase with no two capitals in a row \u2014 so the key maps to exactly one repository name and back.";const segments=key.split(".");if(segments.length!==3){return`"${key}" is not an action key: it has ${segments.length} dot-separated segment(s), not 3; ${shape}`}const[provider,resource,verb]=segments;const not=__name(what=>`"${key}" is not an action key: ${what}; ${shape}`,"not");if(!WORD.test(provider))return not(`its provider "${provider}" is not one lowercase word`);if(!WORD.test(resource))return not(`its resource "${resource}" is not one lowercase word`);if(!VERB.test(verb))return not(`its verb "${verb}" is not camelCase without two capitals in a row`);return null}__name(actionKeyRefusal2,"actionKeyRefusal");function isActionKey(key){return actionKeyRefusal2(key)===null}__name(isActionKey,"isActionKey");var kebab=__name(verb=>verb.replace(/[A-Z]/g,capital=>`-${capital.toLowerCase()}`),"kebab");function actionRepositoryName4(key){const refusal=actionKeyRefusal2(key);if(refusal!==null)throw new Error(refusal);const[provider,resource,verb]=key.split(".");return`${exports.ACTION_REPOSITORY_PREFIX}${provider}-${resource}-${kebab(verb)}`}__name(actionRepositoryName4,"actionRepositoryName");exports.ACTION_SOURCE_REPOSITORY_PREFIX="https://github.com/runveric/";function actionSourceRepository2(key){return`${exports.ACTION_SOURCE_REPOSITORY_PREFIX}${actionRepositoryName4(key)}`}__name(actionSourceRepository2,"actionSourceRepository");function actionKeyOf(name3){if(!name3.startsWith(exports.ACTION_REPOSITORY_PREFIX))return null;const[provider,resource,first2,...rest]=name3.slice(exports.ACTION_REPOSITORY_PREFIX.length).split("-");if(provider===void 0||resource===void 0||first2===void 0)return null;const verb=first2+rest.map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join("");const key=`${provider}.${resource}.${verb}`;return isActionKey(key)&&actionRepositoryName4(key)===name3?key:null}__name(actionKeyOf,"actionKeyOf");function actionPackageRefusal4(key,artifactRef){const keyRefusal=actionKeyRefusal2(key);if(keyRefusal!==null)return`${keyRefusal} No package can carry it.`;const cut=artifactRef.lastIndexOf("/");const named=artifactRef.slice(cut+1);const expected=actionRepositoryName4(key);if(named===expected)return null;return`action "${key}" is published only from a package named "${expected}" (${artifactRef.slice(0,cut+1)}${expected}), not "${named}". An action's package carries its key's name, so an artifact cannot claim an identity its package does not carry.`}__name(actionPackageRefusal4,"actionPackageRefusal")}});var require_catalog_release_spec=__commonJS({"../contracts/dist/catalog-release-spec.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CatalogReleaseSpecError=void 0;exports.splitArtifactReference=splitArtifactReference;exports.parseCatalogReleaseSpec=parseCatalogReleaseSpec3;var CatalogReleaseSpecError=class CatalogReleaseSpecError extends Error{static{__name(this,"CatalogReleaseSpecError")}constructor(message){super(message);this.name="CatalogReleaseSpecError"}};exports.CatalogReleaseSpecError=CatalogReleaseSpecError;function splitArtifactReference(reference){const at=reference.indexOf("@");if(at<=0||at===reference.length-1)return null;return{artifactRef:reference.slice(0,at),digest:reference.slice(at+1)}}__name(splitArtifactReference,"splitArtifactReference");var isMapping3=__name(value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"isMapping");function parseCatalogReleaseSpec3(value){if(!isMapping3(value)){throw new CatalogReleaseSpecError("release.yaml is not a mapping of `version` and `actions`.")}const unknown=Object.keys(value).filter(key=>key!=="version"&&key!=="actions");if(unknown.length>0){throw new CatalogReleaseSpecError(`release.yaml carries ${unknown.map(key=>`"${key}"`).join(", ")}; it has exactly two fields, \`version\` and \`actions\`.`)}const{version:version6,actions}=value;if(typeof version6!=="string"||version6.trim().length===0){throw new CatalogReleaseSpecError(`release.yaml's version is ${JSON.stringify(version6??null)}, not a label. Write it as a quoted string \u2014 version: "2026.10.1" \u2014 because YAML reads an unquoted 2026.10 as a number.`)}if(actions===null||actions===void 0||isMapping3(actions)&&Object.keys(actions).length===0){throw new CatalogReleaseSpecError("release.yaml declares no action. An empty release is refused: pinned, it would declare a catalog with nothing in it.")}if(!isMapping3(actions)){throw new CatalogReleaseSpecError("release.yaml's actions is not a mapping of action key to <repository>@<digest>.")}return{version:version6,actions:Object.entries(actions).map(([key,reference])=>{const split=typeof reference==="string"?splitArtifactReference(reference):null;if(split===null){throw new CatalogReleaseSpecError(`release.yaml's ${key} is ${JSON.stringify(reference)}, not <repository>@<digest>.`)}return{key,...split}})}}__name(parseCatalogReleaseSpec3,"parseCatalogReleaseSpec")}});var require_catalog_lock=__commonJS({"../contracts/dist/catalog-lock.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MANIFEST_SHA256_PATTERN=exports.CatalogLockError=exports.CATALOG_LOCK_ENGINE_EXECUTION=exports.CATALOG_LOCK_FILE=exports.CATALOG_LOCK_SCHEMA_V1=void 0;exports.parseCatalogLock=parseCatalogLock;exports.catalogLockText=catalogLockText;exports.authoredElsewhere=authoredElsewhere;var action_repository_1=require_action_repository();var catalog_release_1=require_catalog_release();exports.CATALOG_LOCK_SCHEMA_V1="runveric.catalog-lock/v1";exports.CATALOG_LOCK_FILE="release.lock.json";exports.CATALOG_LOCK_ENGINE_EXECUTION="engine";var CatalogLockError=class CatalogLockError extends Error{static{__name(this,"CatalogLockError")}constructor(message){super(message);this.name="CatalogLockError"}};exports.CatalogLockError=CatalogLockError;exports.MANIFEST_SHA256_PATTERN=/^[0-9a-f]{64}$/;function objectAt(path,value,keys){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new CatalogLockError(`${path} is not an object.`)}const unknown=Object.keys(value).filter(key=>!keys.includes(key));if(unknown.length>0){throw new CatalogLockError(`${path} carries ${unknown.map(key=>`"${key}"`).join(", ")}, which a lock does not have. A lock is written by catalog:vendor and never edited; re-vendor instead.`)}return value}__name(objectAt,"objectAt");function stringAt(path,value,pattern,expected){if(typeof value!=="string"||value.length===0){throw new CatalogLockError(`${path} is not a non-empty string.`)}if(pattern!==void 0&&!pattern.test(value)){throw new CatalogLockError(`${path} is "${value}", which is not ${expected}.`)}return value}__name(stringAt,"stringAt");function parseCatalogLock(value){const root=objectAt("the lock",value,["schemaVersion","release","actions"]);if(root.schemaVersion!==exports.CATALOG_LOCK_SCHEMA_V1){throw new CatalogLockError(`the lock declares schemaVersion ${JSON.stringify(root.schemaVersion)}; this build reads ${exports.CATALOG_LOCK_SCHEMA_V1} only.`)}const release=objectAt("release",root.release,["artifactRef","digest","version"]);const lock={schemaVersion:exports.CATALOG_LOCK_SCHEMA_V1,release:{artifactRef:stringAt("release.artifactRef",release.artifactRef,catalog_release_1.ARTIFACT_REPOSITORY_PATTERN,"a registry repository"),digest:stringAt("release.digest",release.digest,catalog_release_1.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),version:stringAt("release.version",release.version)},actions:[]};if(!Array.isArray(root.actions)||root.actions.length===0){throw new CatalogLockError("actions is not a non-empty array. A release names at least one action.")}root.actions.forEach((entry,index)=>{const path=`actions[${index}]`;const action=objectAt(path,entry,["key","artifactRef","digest","manifestSha256","provenance","executes","imageDigest"]);const key=stringAt(`${path}.key`,action.key);const artifactRef=stringAt(`${path}.artifactRef`,action.artifactRef,catalog_release_1.ARTIFACT_REPOSITORY_PATTERN,"a registry repository");const misnamed=(0,action_repository_1.actionPackageRefusal)(key,artifactRef);if(misnamed!==null)throw new CatalogLockError(`${path}: ${misnamed}`);const previous=lock.actions[lock.actions.length-1];if(previous!==void 0&&!(previous.key<key)){throw new CatalogLockError(`${path}.key "${key}" follows "${previous.key}": a lock names each action once, sorted by key.`)}const provenance2=objectAt(`${path}.provenance`,action.provenance,["repository","commit"]);if(action.executes===void 0!==(action.imageDigest===void 0)){throw new CatalogLockError(`${path} carries ${action.executes===void 0?"imageDigest without executes":"executes without imageDigest"}; an engine action records both, a built-in neither.`)}if(action.executes!==void 0&&action.executes!==exports.CATALOG_LOCK_ENGINE_EXECUTION){throw new CatalogLockError(`${path}.executes is ${JSON.stringify(action.executes)}; the one value it takes is "${exports.CATALOG_LOCK_ENGINE_EXECUTION}".`)}lock.actions.push({key,artifactRef,digest:stringAt(`${path}.digest`,action.digest,catalog_release_1.ARTIFACT_DIGEST_PATTERN,"a sha256 digest"),manifestSha256:stringAt(`${path}.manifestSha256`,action.manifestSha256,exports.MANIFEST_SHA256_PATTERN,"64 lowercase hex characters"),provenance:{repository:stringAt(`${path}.provenance.repository`,provenance2.repository),commit:stringAt(`${path}.provenance.commit`,provenance2.commit)},...action.executes===void 0?{}:{executes:exports.CATALOG_LOCK_ENGINE_EXECUTION,imageDigest:stringAt(`${path}.imageDigest`,action.imageDigest,catalog_release_1.ARTIFACT_DIGEST_PATTERN,"a sha256 digest")}})});return lock}__name(parseCatalogLock,"parseCatalogLock");function catalogLockText(lock){const ordered={schemaVersion:lock.schemaVersion,release:{artifactRef:lock.release.artifactRef,digest:lock.release.digest,version:lock.release.version},actions:[...lock.actions].sort((a,b)=>a.key<b.key?-1:a.key>b.key?1:0).map(action=>({key:action.key,artifactRef:action.artifactRef,digest:action.digest,manifestSha256:action.manifestSha256,provenance:{repository:action.provenance.repository,commit:action.provenance.commit},...action.executes===void 0||action.imageDigest===void 0?{}:{executes:action.executes,imageDigest:action.imageDigest}}))};return`${JSON.stringify(ordered,null,2)}
5
+ `}__name(catalogLockText,"catalogLockText");function authoredElsewhere(lock,key){const namespace=lock.release.artifactRef.slice(0,lock.release.artifactRef.lastIndexOf("/"));const organisation=namespace.slice(namespace.lastIndexOf("/")+1);return`${key} is authored in ${organisation}/${(0,action_repository_1.actionRepositoryName)(key)} \u2014 change it there, publish, assemble, vendor`}__name(authoredElsewhere,"authoredElsewhere")}});var require_catalog_manifest_placeholders=__commonJS({"../contracts/dist/catalog-manifest-placeholders.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MANIFEST_PLACEHOLDER_PATTERN=exports.MANIFEST_PLACEHOLDERS=void 0;var brand_1=require_brand();exports.MANIFEST_PLACEHOLDERS={BRAND_SHORT_NAME:brand_1.BRAND_SHORT_NAME,BRAND_NAME:brand_1.BRAND_NAME};exports.MANIFEST_PLACEHOLDER_PATTERN=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g}});var require_change_control=__commonJS({"../contracts/dist/change-control.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CHANGE_CONTROL_REFUSAL_OWNER=exports.CHANGE_CONTROL_REFUSAL_KINDS=exports.CHANGE_RECORD_REQUIREMENT_UNMET=exports.CHANGE_RECORD_REQUIREMENTS=exports.CHANGE_RECORD_ASSURANCE_ESTABLISHED=exports.CHANGE_RECORD_ASSURANCE_REQUIRES=exports.CHANGE_RECORD_ASSURANCE_LABEL=exports.DEFAULT_CHANGE_RECORD_ASSURANCE=exports.CHANGE_RECORD_ASSURANCE=exports.CHANGE_RECORD_AUTHORIZATION=exports.CHANGE_RECORD_TYPE_LABEL=exports.CHANGE_RECORD_TYPES=exports.POLICY_KIND_LABEL=exports.DEFAULT_POLICY_KIND=exports.POLICY_KINDS=void 0;exports.changeRecordEstablishedSentence=changeRecordEstablishedSentence;exports.changeRecordAuthorization=changeRecordAuthorization;exports.changeControlRefusalSentence=changeControlRefusalSentence;exports.changeRecordTypeWord=changeRecordTypeWord;exports.changeRecordTypesPhrase=changeRecordTypesPhrase;exports.changeRecordTypeNoun=changeRecordTypeNoun;var brand_1=require_brand();exports.POLICY_KINDS=["approval","change_control"];exports.DEFAULT_POLICY_KIND="approval";exports.POLICY_KIND_LABEL={approval:"Approval",change_control:"Change control"};exports.CHANGE_RECORD_TYPES=["change_request","incident"];exports.CHANGE_RECORD_TYPE_LABEL={change_request:"Change request",incident:"Incident"};exports.CHANGE_RECORD_AUTHORIZATION={change_request:["approved","permits_work","within_window"],incident:["open"]};exports.CHANGE_RECORD_ASSURANCE=["recorded","verified"];exports.DEFAULT_CHANGE_RECORD_ASSURANCE="verified";exports.CHANGE_RECORD_ASSURANCE_LABEL={recorded:"Recorded",verified:"Verified"};exports.CHANGE_RECORD_ASSURANCE_REQUIRES={recorded:`The run must name a record of an accepted type. ${brand_1.BRAND_SHORT_NAME} records it on the run permanently and does not check it \u2014 nothing is looked up in your system of record.`,verified:`${brand_1.BRAND_SHORT_NAME} looks the record up in your system of record and refuses the run unless it authorizes the work \u2014 re-checked the moment the run starts.`};exports.CHANGE_RECORD_ASSURANCE_ESTABLISHED={recorded:`Recorded on this run. ${brand_1.BRAND_SHORT_NAME} did not check it.`,verified:"Checked with your system of record, which authorized this run."};function changeRecordEstablishedSentence(citation){const declarer=citation.declaredBy??{kind:"run"};const assurance=citation.assurance;if(declarer.kind==="run")return exports.CHANGE_RECORD_ASSURANCE_ESTABLISHED[assurance];const named=declarer.scheduleName?`the schedule \u201C${declarer.scheduleName}\u201D`:"the schedule that fired this run";return assurance==="recorded"?`Declared on ${named}, not named for this run. ${brand_1.BRAND_SHORT_NAME} did not check it.`:`Declared on ${named}, and checked with your system of record when this run started.`}__name(changeRecordEstablishedSentence,"changeRecordEstablishedSentence");exports.CHANGE_RECORD_REQUIREMENTS=["approved","permits_work","within_window","open"];exports.CHANGE_RECORD_REQUIREMENT_UNMET={approved:"it has not been approved",permits_work:"its state does not permit work yet",within_window:"now is outside its planned window",open:"it is no longer open"};function changeRecordAuthorization(facts,now){const unmet=exports.CHANGE_RECORD_AUTHORIZATION[facts.type].filter(requirement=>!requirementMet(requirement,facts,now));return unmet.length===0?{authorized:true}:{authorized:false,unmet}}__name(changeRecordAuthorization,"changeRecordAuthorization");function requirementMet(requirement,facts,now){switch(requirement){case"approved":return facts.approved;case"permits_work":return facts.permitsWork;case"open":return facts.open;case"within_window":return withinWindow(facts.window,now)}}__name(requirementMet,"requirementMet");function withinWindow(window,now){if(!window)return false;const start=Date.parse(window.startsAt);const end=Date.parse(window.endsAt);if(Number.isNaN(start)||Number.isNaN(end))return false;const at=now.getTime();return at>=start&&at<end}__name(withinWindow,"withinWindow");var CHANGE_CONTROL_REFUSAL_KIND_SET={no_reference:true,wrong_type:true,not_found:true,unavailable:true,not_authorizing:true,standing_declaration:true};exports.CHANGE_CONTROL_REFUSAL_KINDS=Object.keys(CHANGE_CONTROL_REFUSAL_KIND_SET);exports.CHANGE_CONTROL_REFUSAL_OWNER={no_reference:"operator",wrong_type:"operator",not_found:"operator",unavailable:"opera",not_authorizing:"record",standing_declaration:"operator"};function changeControlRefusalSentence(refusal,subject={kind:"run"}){const rule=`your governance rule \u201C${refusal.rule.name}\u201D`;switch(refusal.kind){case"no_reference":return subject.kind==="schedule"?`Schedule \u201C${subject.name}\u201D did not fire: it needs ${orList(refusal.recordTypes.map(typeWord))}, because ${rule} matches the runs it starts. Name the record this schedule implements and it fires again at its next occurrence.`:`This run needs ${orList(refusal.recordTypes.map(typeWord))} before it can go ahead: ${rule} requires one. Name the record this run implements and submit again.`;case"wrong_type":return`This run names ${typeWord(refusal.supplied.type)} ${refusal.supplied.reference}, and ${rule} requires ${orList(refusal.recordTypes.map(typeWord))}.`;case"not_found":return`Your system of record has no ${typeNoun(refusal.supplied.type)} ${refusal.supplied.reference}. ${capitalize(rule)} requires one that exists, so nothing was started \u2014 check the reference.`;case"unavailable":return`${brand_1.BRAND_SHORT_NAME} could not reach your system of record to check ${typeWord(refusal.supplied.type)} ${refusal.supplied.reference}, so this run was refused rather than started unchecked (${rule} requires it). There is nothing to fix on the record itself \u2014 the connection reported: ${refusal.detail}`;case"not_authorizing":return`${capitalize(typeWord(refusal.facts.type))} ${refusal.facts.reference} does not authorize this run: ${orList(refusal.unmet.map(requirement=>exports.CHANGE_RECORD_REQUIREMENT_UNMET[requirement]),"and")}. It is ${refusal.facts.stateLabel}${windowClause(refusal)}. ${capitalize(rule)} requires a record that authorizes the work.`;case"standing_declaration":return`${capitalize(scheduleNameClause(refusal.scheduleName))} names ${typeWord(refusal.supplied.type)} ${refusal.supplied.reference} for every occurrence, and ${rule} now requires a record ${brand_1.BRAND_SHORT_NAME} checks when each run starts. A reference named once cannot be that \u2014 a change request authorizes one planned window and this job recurs \u2014 so nothing was started. Either set that rule to Recorded, or run this work attended and name a record each time.`}}__name(changeControlRefusalSentence,"changeControlRefusalSentence");function scheduleNameClause(scheduleName){return scheduleName?`the schedule \u201C${scheduleName}\u201D`:"the schedule that fired this run"}__name(scheduleNameClause,"scheduleNameClause");function windowClause(refusal){if(!refusal.unmet.includes("within_window"))return"";const window=refusal.facts.window;return window?`, and its planned window is ${window.startsAt} to ${window.endsAt}`:", and it names no planned window at all"}__name(windowClause,"windowClause");function changeRecordTypeWord(type){return type==="incident"?"an incident":"a change request"}__name(changeRecordTypeWord,"changeRecordTypeWord");function changeRecordTypesPhrase(types){return orList(types.map(changeRecordTypeWord))}__name(changeRecordTypesPhrase,"changeRecordTypesPhrase");function changeRecordTypeNoun(type){return type==="incident"?"incident":"change request"}__name(changeRecordTypeNoun,"changeRecordTypeNoun");var typeWord=changeRecordTypeWord;var typeNoun=changeRecordTypeNoun;function orList(values,conjunction="or"){if(values.length<=1)return values[0]??"";return`${values.slice(0,-1).join(", ")} ${conjunction} ${values[values.length-1]}`}__name(orList,"orList");function capitalize(value){return value.charAt(0).toUpperCase()+value.slice(1)}__name(capitalize,"capitalize")}});var require_run_placement=__commonJS({"../contracts/dist/run-placement.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HOSTED_EXECUTION_LABEL=exports.RUN_PLACEMENTS=exports.EXECUTION_SITES=void 0;exports.isExecutionSite=isExecutionSite;exports.EXECUTION_SITES=["hosted","runner","unknown"];function isExecutionSite(value){return exports.EXECUTION_SITES.includes(value)}__name(isExecutionSite,"isExecutionSite");exports.RUN_PLACEMENTS=["hosted","runner"];exports.HOSTED_EXECUTION_LABEL="our hosted cloud"}});var require_package_provenance=__commonJS({"../contracts/dist/package-provenance.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POOL_PROVENANCE_AUDIT_ACTION_NAMES=exports.POOL_PROVENANCE_AUDIT_ACTIONS=exports.PACKAGE_PROVENANCE_DISCLOSURES=exports.PACKAGE_PROVENANCE_CLAUSES=exports.PACKAGE_PROVENANCE_LABELS=exports.PACKAGE_PROVENANCE_IS_REVOCABLE=exports.PACKAGE_PROVENANCE_KINDS=void 0;exports.poolProvenanceAuditAction=poolProvenanceAuditAction;var brand_1=require_brand();exports.PACKAGE_PROVENANCE_KINDS=["git_source","public_git","authored"];exports.PACKAGE_PROVENANCE_IS_REVOCABLE={git_source:true,public_git:false,authored:false};exports.PACKAGE_PROVENANCE_LABELS={git_source:"Imported from Git",public_git:"Imported from a public repository",authored:`Authored in ${brand_1.BRAND_SHORT_NAME}`};exports.PACKAGE_PROVENANCE_CLAUSES={git_source:"imported from Git",public_git:"imported from a public repository",authored:`authored in ${brand_1.BRAND_SHORT_NAME}`};exports.PACKAGE_PROVENANCE_DISCLOSURES={git_source:"imported from a Git repository your organisation connected. Connecting a repository says who it belongs to; it does not say anybody reviewed what is in it.",public_git:`imported from a public repository. Neither ${brand_1.BRAND_SHORT_NAME} nor your organisation wrote it, and nobody vouched for it when it was imported.`,authored:`written in ${brand_1.BRAND_SHORT_NAME} by a named member of your organisation, and pinned to the exact bytes they published.`};exports.POOL_PROVENANCE_AUDIT_ACTIONS={git_source:{accepted:"runner.pool.accepted_git_source",revoked:"runner.pool.revoked_git_source"},public_git:{accepted:"runner.pool.accepted_public_git",revoked:"runner.pool.revoked_public_git"},authored:{accepted:"runner.pool.accepted_authored",revoked:"runner.pool.revoked_authored"}};exports.POOL_PROVENANCE_AUDIT_ACTION_NAMES=Object.values(exports.POOL_PROVENANCE_AUDIT_ACTIONS).flatMap(pair=>[pair.accepted,pair.revoked]);function poolProvenanceAuditAction(provenance2,accepted){const pair=exports.POOL_PROVENANCE_AUDIT_ACTIONS[provenance2];return accepted?pair.accepted:pair.revoked}__name(poolProvenanceAuditAction,"poolProvenanceAuditAction")}});var require_package_tier=__commonJS({"../contracts/dist/package-tier.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PACKAGE_TIER_LABELS=exports.PACKAGE_TIER_CLAIMS=void 0;var brand_1=require_brand();exports.PACKAGE_TIER_CLAIMS={official:`${brand_1.BRAND_SHORT_NAME} wrote and maintains this action.`,partner:"Published by a named partner under agreement, with a security contact.",verified:"Automated checks passed. Nobody reviewed the code.",community:"Published by anyone. Nobody vouches for it.",organization:"Authored inside this workspace by one of its own admins."};exports.PACKAGE_TIER_LABELS={official:"Official",partner:"Partner",verified:"Verified",community:"Community",organization:"Workspace"}}});var require_packages=__commonJS({"../contracts/dist/packages.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:__name(function(){return m[k]},"get")}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]});var __exportStar=exports&&exports.__exportStar||function(m,exports1){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports1,p))__createBinding(exports1,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.PACKAGE_IMPORT_WARNING_REASONS=exports.PACKAGE_IMPORT_SKIP_REASON_LABELS=exports.PACKAGE_IMPORT_SKIP_REASONS=exports.PACKAGE_IMPORT_LIMITS=exports.PACKAGE_DRAFT_FILTER_LABELS=exports.PACKAGE_DRAFT_FILTERS=exports.PACKAGE_INTERPRETER_LABEL=exports.PARAMETER_DETECTION_UNAVAILABLE=exports.PARAMETER_DETECTION_SOURCES=exports.PACKAGE_PARAMETERS_UNRESOLVED_COPY=exports.PACKAGE_PARAMETERS_UNRESOLVED_REASONS=exports.PACKAGE_DRAFT_STATES=exports.PACKAGE_VERSION_MODES=exports.ACTION_UNRUNNABLE_REASONS=exports.PACKAGE_SOURCE_RECONNECT_OUTCOMES=exports.ADOPTION_REVIEW_DIRECTIONS=exports.ADOPTION_CHANGE_SEVERITY=exports.ADOPTION_CHANGE_KINDS=exports.ADOPTION_CHANGE_SEVERITIES=exports.ADOPTION_STATUSES=exports.PACKAGE_INTERPRETERS=exports.PACKAGE_RUNTIME_KINDS=exports.LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY=exports.PACKAGE_RUNNER_CONNECTOR_KEY=void 0;exports.isPackageRunnerConnectorKey=isPackageRunnerConnectorKey;exports.canonicalConnectorKey=canonicalConnectorKey;exports.packageSourceConnectedRemovalMessage=packageSourceConnectedRemovalMessage;exports.packageVersionAdoptedRemovalMessage=packageVersionAdoptedRemovalMessage;exports.actionUnrunnableCopy=actionUnrunnableCopy;exports.actionUnrunnableHeadline=actionUnrunnableHeadline;exports.actionUnrunnableRefusal=actionUnrunnableRefusal;exports.trialSemanticVersion=trialSemanticVersion;exports.parameterDetectionConsequence=parameterDetectionConsequence;__exportStar(require_package_provenance(),exports);__exportStar(require_package_tier(),exports);var brand_1=require_brand();exports.PACKAGE_RUNNER_CONNECTOR_KEY="runveric.package-runner";exports.LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY="opera.package-runner";function isPackageRunnerConnectorKey(connectorKey){return connectorKey===exports.PACKAGE_RUNNER_CONNECTOR_KEY||connectorKey===exports.LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY}__name(isPackageRunnerConnectorKey,"isPackageRunnerConnectorKey");function canonicalConnectorKey(connectorKey){return isPackageRunnerConnectorKey(connectorKey)?exports.PACKAGE_RUNNER_CONNECTOR_KEY:connectorKey}__name(canonicalConnectorKey,"canonicalConnectorKey");exports.PACKAGE_RUNTIME_KINDS=["interpreter","oci"];exports.PACKAGE_INTERPRETERS=["powershell","bash","python"];exports.ADOPTION_STATUSES=["draft","published","decommissioned"];exports.ADOPTION_CHANGE_SEVERITIES=["privilege_increase","safety_reduction","code_changed","privilege_decrease","metadata"];exports.ADOPTION_CHANGE_KINDS=["permission_added","permission_scope_widened","egress_host_added","network_enabled","secret_added","credential_scope_added","version_contract_violation","rollback_removed","dry_run_removed","idempotency_removed","validate_entrypoint_removed","timeout_increased","content_digest_changed","runtime_kind_changed","runtime_image_changed","runtime_interpreter_changed","entrypoint_changed","rollback_entrypoint_changed","validate_entrypoint_changed","permission_removed","permission_scope_narrowed","egress_host_removed","network_disabled","secret_removed","credential_scope_removed","timeout_decreased","capability_added","source_repo_changed","git_commit_changed","tier_changed"];exports.ADOPTION_CHANGE_SEVERITY={permission_added:"privilege_increase",permission_scope_widened:"privilege_increase",egress_host_added:"privilege_increase",network_enabled:"privilege_increase",secret_added:"privilege_increase",credential_scope_added:"privilege_increase",version_contract_violation:"privilege_increase",rollback_removed:"safety_reduction",dry_run_removed:"safety_reduction",idempotency_removed:"safety_reduction",validate_entrypoint_removed:"safety_reduction",timeout_increased:"safety_reduction",content_digest_changed:"code_changed",runtime_kind_changed:"code_changed",runtime_image_changed:"code_changed",runtime_interpreter_changed:"code_changed",entrypoint_changed:"code_changed",rollback_entrypoint_changed:"code_changed",validate_entrypoint_changed:"code_changed",permission_removed:"privilege_decrease",permission_scope_narrowed:"privilege_decrease",egress_host_removed:"privilege_decrease",network_disabled:"privilege_decrease",secret_removed:"privilege_decrease",credential_scope_removed:"privilege_decrease",timeout_decreased:"privilege_decrease",capability_added:"metadata",source_repo_changed:"code_changed",git_commit_changed:"metadata",tier_changed:"metadata"};exports.ADOPTION_REVIEW_DIRECTIONS=["upgrade","downgrade","same"];function packageSourceConnectedRemovalMessage(){return"This source is still connected, so removing it would silently drop a live GitHub App installation. Disconnect it first, then remove it."}__name(packageSourceConnectedRemovalMessage,"packageSourceConnectedRemovalMessage");exports.PACKAGE_SOURCE_RECONNECT_OUTCOMES=["reconnected","reinstall_required"];function packageVersionAdoptedRemovalMessage(adoption){return`This version cannot be removed while an action still adopts it: adoption ${adoption.id} is ${adoption.status}. Decommission that adoption first \u2014 then this version can be removed.`}__name(packageVersionAdoptedRemovalMessage,"packageVersionAdoptedRemovalMessage");exports.ACTION_UNRUNNABLE_REASONS=["runtime_kind","interpreter_unavailable","runtime_unavailable","egress_unconfigurable","source_disconnected","source_removed","not_trusted"];var RUNTIME_KIND_NAMES={interpreter:"interpreter",oci:"OCI image"};function anArticle(noun){return`${/^[aeiou]/i.test(noun)?"an":"a"} ${noun}`}__name(anArticle,"anArticle");function supportedInterpreterRemedy(available){const deploy="an administrator has to deploy a runner that provides the one this package needs.";if(available.length===0){return`This deployment runs no package interpreter at all, so ${deploy}`}const list=available.length===1?available[0]:`${available.slice(0,-1).join(", ")} and ${available[available.length-1]}`;return`This deployment runs ${list}. A package has to be published for one of those, or ${deploy}`}__name(supportedInterpreterRemedy,"supportedInterpreterRemedy");function unrunnableClauses(detail){switch(detail.reason){case"runtime_kind":return{cause:`runs as ${anArticle(RUNTIME_KIND_NAMES[detail.runtimeKind])}, which ${brand_1.BRAND_SHORT_NAME} cannot execute yet.`,remedy:"Nothing is wrong with your setup \u2014 the package has to be published for a runtime this deployment supports."};case"interpreter_unavailable":return{cause:`is written for ${detail.interpreter}, which no runner on this deployment executes.`,remedy:supportedInterpreterRemedy(detail.available)};case"runtime_unavailable":return{cause:`has to run under the "${detail.isolation}" isolation, and this deployment provides no runner for it.`,remedy:"Nothing about the package or its Git source needs to change \u2014 an administrator has to configure that runner before any package routed to it can run."};case"egress_unconfigurable":return{cause:`declares outbound network access, and this deployment has no way to broker it under the "${detail.isolation}" isolation.`,remedy:"A package that declares network is never run without its allowlist in force, so an administrator has to configure the egress proxy for that runner first."};case"source_disconnected":return{cause:`came from the Git source ${detail.sourceAccount}, which is disconnected, so ${brand_1.BRAND_SHORT_NAME} can no longer vouch for where its code came from.`,remedy:"Reconnecting that source is all it takes \u2014 nothing has to be re-imported."};case"source_removed":return{cause:`came from the Git source ${detail.sourceAccount}, and that connection has been removed, so ${brand_1.BRAND_SHORT_NAME} can no longer vouch for where its code came from.`,remedy:"Re-import the package through a live Git source to run it again."};case"not_trusted":return{cause:"is not allowlisted for trusted execution, and this deployment does not run untrusted packages.",remedy:"Ask an administrator to allowlist this package for trusted execution."}}}__name(unrunnableClauses,"unrunnableClauses");function actionUnrunnableCopy(detail){const{cause,remedy}=unrunnableClauses(detail);return`This action's package ${cause} ${remedy}`}__name(actionUnrunnableCopy,"actionUnrunnableCopy");function actionUnrunnableHeadline(detail){switch(detail.reason){case"runtime_kind":return`its package runs as ${anArticle(RUNTIME_KIND_NAMES[detail.runtimeKind])}, which ${brand_1.BRAND_SHORT_NAME} cannot execute`;case"interpreter_unavailable":return`its package is written for ${detail.interpreter}, which no runner here executes`;case"runtime_unavailable":return`this deployment provides no "${detail.isolation}" runner for its package`;case"egress_unconfigurable":return`its package needs outbound network and the "${detail.isolation}" runner here has no egress proxy`;case"source_disconnected":return`its package's Git source ${detail.sourceAccount} is disconnected`;case"source_removed":return`its package's Git source ${detail.sourceAccount} has been removed`;case"not_trusted":return"its package is not allowlisted for trusted execution"}}__name(actionUnrunnableHeadline,"actionUnrunnableHeadline");function actionUnrunnableRefusal(detail,pkg){const{cause,remedy}=unrunnableClauses(detail);return`Package ${pkg.packageId} from ${pkg.sourceRepo} ${cause} ${remedy} Nothing was started.`}__name(actionUnrunnableRefusal,"actionUnrunnableRefusal");exports.PACKAGE_VERSION_MODES=["trial","release"];var TRIAL_DIGEST_LENGTH=12;function trialSemanticVersion(manifestVersion,contentDigest){return`${manifestVersion}+trial.${contentDigest.slice(0,TRIAL_DIGEST_LENGTH)}`}__name(trialSemanticVersion,"trialSemanticVersion");exports.PACKAGE_DRAFT_STATES=["draft","published","superseded"];exports.PACKAGE_PARAMETERS_UNRESOLVED_REASONS=["manifest_missing","manifest_unparseable","parameters_ref_missing","parameters_ref_unsafe"];exports.PACKAGE_PARAMETERS_UNRESOLVED_COPY={manifest_missing:{headline:"This package has no action.yaml.",fix:"Every package needs one \u2014 it is the file that declares which file holds the parameters. Add it in the Files tab."},manifest_unparseable:{headline:"action.yaml cannot be read.",fix:"It is not valid YAML, so nothing can tell which file holds the parameters. Fix it in the Files tab and this returns."},parameters_ref_missing:{headline:"action.yaml does not declare parametersRef.",fix:"Add `parametersRef: parameters.json` \u2014 the path, relative to the package root, of the file that holds the parameters."},parameters_ref_unsafe:{headline:"action.yaml's parametersRef is not a safe package path.",fix:"It must be relative to the package root, use forward slashes, and contain no `.` or `..` segments."}};exports.PARAMETER_DETECTION_SOURCES=["powershell_param","none"];exports.PARAMETER_DETECTION_UNAVAILABLE={powershell:null,bash:"Bash has no parameter declaration to read, so you will define these yourself.",python:`${brand_1.BRAND_SHORT_NAME} cannot read Python parameters yet \u2014 argparse detection is not built. Define these yourself for now.`};function parameterDetectionConsequence(interpreter){return exports.PARAMETER_DETECTION_UNAVAILABLE[interpreter]===null?`${brand_1.BRAND_SHORT_NAME} reads your parameters from your script.`:"You define your parameters yourself."}__name(parameterDetectionConsequence,"parameterDetectionConsequence");exports.PACKAGE_INTERPRETER_LABEL={powershell:"PowerShell",bash:"Bash",python:"Python"};exports.PACKAGE_DRAFT_FILTERS=["never_published","published","unpublished_changes","superseded"];exports.PACKAGE_DRAFT_FILTER_LABELS={never_published:"Never published",published:"Published",unpublished_changes:"Unpublished changes",superseded:"Superseded"};exports.PACKAGE_IMPORT_LIMITS={maxFileBytes:1024*1024,maxTotalBytes:5*1024*1024,maxFiles:200,maxInspectFiles:2e3,maxInspectBytes:20*1024*1024};exports.PACKAGE_IMPORT_SKIP_REASONS=["version_control","dependencies","build_output","editor_metadata","os_metadata","lockfile","runveric_scratch","not_text"];exports.PACKAGE_IMPORT_SKIP_REASON_LABELS={version_control:"version-control metadata",dependencies:"dependencies are not part of a package",build_output:"build output",editor_metadata:"editor settings",os_metadata:"operating-system metadata",lockfile:"a dependency lockfile",runveric_scratch:"scratch written by `runveric test`",not_text:"not UTF-8 text"};exports.PACKAGE_IMPORT_WARNING_REASONS=["mixed_interpreter"]}});var require_validation=__commonJS({"../contracts/dist/validation.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TARGET_COMPARISON_KINDS=exports.DECISION_CODES=exports.REFUSAL_CODES=exports.CHECK_CODE_MAX_LENGTH=exports.CHECK_LEVELS=exports.TARGETS_NO_SCOPE=exports.TARGETS_NOT_COUNTED=exports.TARGET_COUNT_ABSENCES=void 0;exports.isTargetCountAbsence=isTargetCountAbsence;exports.singleTarget=singleTarget;exports.noTargetsResolved=noTargetsResolved;exports.targetsUnavailable=targetsUnavailable;exports.targetSummarySentence=targetSummarySentence;exports.targetSummaryLabel=targetSummaryLabel;exports.eligibleTargetCount=eligibleTargetCount;exports.targetsValidationCheck=targetsValidationCheck;exports.targetSummaryOf=targetSummaryOf;exports.isCheckLevel=isCheckLevel;exports.isCheckCode=isCheckCode;exports.checkCodeRefusal=checkCodeRefusal;exports.isBuiltInRefusalCode=isBuiltInRefusalCode;exports.isBuiltInDecisionCode=isBuiltInDecisionCode;exports.validationCheckOf=validationCheckOf;exports.scopeFailureDetail=scopeFailureDetail;exports.targetsUnavailableFrom=targetsUnavailableFrom;exports.compareTargets=compareTargets;exports.targetComparisonSentence=targetComparisonSentence;exports.targetComparisonLabel=targetComparisonLabel;exports.targetComparisonLevel=targetComparisonLevel;var brand_1=require_brand();exports.TARGET_COUNT_ABSENCES=["no_scope","unavailable","not_attempted"];function isTargetCountAbsence(value){return typeof value==="string"&&exports.TARGET_COUNT_ABSENCES.includes(value)}__name(isTargetCountAbsence,"isTargetCountAbsence");function singleTarget(){return{eligible:1,excluded:0,blocked:0}}__name(singleTarget,"singleTarget");function noTargetsResolved(){return{eligible:0,excluded:0,blocked:0}}__name(noTargetsResolved,"noTargetsResolved");exports.TARGETS_NOT_COUNTED={uncounted:"not_attempted"};exports.TARGETS_NO_SCOPE={uncounted:"no_scope"};function targetsUnavailable(detail){return{uncounted:"unavailable",detail}}__name(targetsUnavailable,"targetsUnavailable");function targetSummarySentence(summary){if(!summary.uncounted){return`${summary.eligible} eligible ${summary.eligible===1?"target":"targets"}`}switch(summary.uncounted){case"no_scope":return`No scope for ${brand_1.BRAND_SHORT_NAME} to count`;case"unavailable":return summary.detail?`Targets could not be counted \u2014 ${summary.detail}`:"Targets could not be counted";case"not_attempted":return"Targets not counted"}}__name(targetSummarySentence,"targetSummarySentence");function targetSummaryLabel(summary){if(!summary.uncounted)return`${summary.eligible} eligible`;switch(summary.uncounted){case"no_scope":return"None to count";case"unavailable":return"Could not count";case"not_attempted":return"Not counted"}}__name(targetSummaryLabel,"targetSummaryLabel");function eligibleTargetCount(summary){return summary.uncounted?null:summary.eligible}__name(eligibleTargetCount,"eligibleTargetCount");function targetsValidationCheck(summary){if(!summary.uncounted){return{level:"info",title:`Scope resolved \u2014 ${targetSummarySentence(summary)}.`}}if(summary.uncounted==="no_scope"){return{level:"info",title:`This action has no scope for ${brand_1.BRAND_SHORT_NAME} to count \u2014 it acts on what it declares.`}}return{level:"warn",title:`${targetSummarySentence(summary)}. The run can still be submitted.`}}__name(targetsValidationCheck,"targetsValidationCheck");function targetSummaryOf(stored){if(typeof stored!=="object"||stored===null)return exports.TARGETS_NOT_COUNTED;const value=stored;if(value.uncounted!==void 0){return isTargetCountAbsence(value.uncounted)?{uncounted:value.uncounted,...typeof value.detail==="string"?{detail:value.detail}:{}}:exports.TARGETS_NOT_COUNTED}const{eligible,excluded,blocked}=value;if(typeof eligible==="number"&&typeof excluded==="number"&&typeof blocked==="number"){return{eligible,excluded,blocked}}return exports.TARGETS_NOT_COUNTED}__name(targetSummaryOf,"targetSummaryOf");exports.CHECK_LEVELS=["info","warn","error"];function isCheckLevel(value){return typeof value==="string"&&exports.CHECK_LEVELS.includes(value)}__name(isCheckLevel,"isCheckLevel");exports.CHECK_CODE_MAX_LENGTH=64;var CHECK_CODE_PATTERN=/^[a-z][a-z0-9]*\.[a-z][A-Za-z0-9]*$/;function isCheckCode(value){return typeof value==="string"&&value.length<=exports.CHECK_CODE_MAX_LENGTH&&CHECK_CODE_PATTERN.test(value)}__name(isCheckCode,"isCheckCode");function checkCodeRefusal(value,what){if(isCheckCode(value))return null;const shown=typeof value==="string"&&value.length>exports.CHECK_CODE_MAX_LENGTH*2?`a ${value.length}-character string`:JSON.stringify(value)??String(value);return`${what} ${shown} is not a check code: one lowercase segment, a dot and one camelCase word (e.g. "ip.staticAddress"), at most ${exports.CHECK_CODE_MAX_LENGTH} characters.`}__name(checkCodeRefusal,"checkCodeRefusal");exports.REFUSAL_CODES=["disk.notUnattached","disk.locked","disk.shared","disk.inRecoveryPlan","disk.keyUnusable","disk.unverifiable"];function isBuiltInRefusalCode(value){return typeof value==="string"&&exports.REFUSAL_CODES.includes(value)}__name(isBuiltInRefusalCode,"isBuiltInRefusalCode");exports.DECISION_CODES=["disk.recentlyDetached","disk.customerKey","disk.customerKeyUnverified","disk.guestEncrypted","disk.noSnapshot","disk.confidential"];function isBuiltInDecisionCode(value){return typeof value==="string"&&exports.DECISION_CODES.includes(value)}__name(isBuiltInDecisionCode,"isBuiltInDecisionCode");function validationCheckOf(value){const raw=typeof value==="object"&&value!==null?value:{};const level=raw.level;if(!isCheckLevel(level)){return{refusal:`A check level of "${String(level)}" is not in the vocabulary.`}}if(typeof raw.title!=="string"||raw.title.length===0){return{refusal:"Every check must carry a title."}}if(raw.acknowledgement!==void 0){return{refusal:"A check may not carry an acknowledgement: the words on a decision's control are attached by the platform, from the version's declaration, never by whoever sent the check."}}if(raw.decision!==void 0&&raw.refusal!==void 0){return{refusal:`A check carrying both a decision ("${String(raw.decision)}") and a refusal ("${String(raw.refusal)}") is not a check any producer of ours can build.`}}if(raw.decision!==void 0){if(!isCheckCode(raw.decision))return{refusal:checkCodeRefusal(raw.decision,"A check's decision")};if(level==="info"){return{refusal:`A check's decision of "${String(raw.decision)}" at level "info" is not one this channel accepts: an info check asks nobody anything.`}}return{check:{level,title:raw.title,decision:raw.decision}}}if(raw.refusal!==void 0){if(!isCheckCode(raw.refusal))return{refusal:checkCodeRefusal(raw.refusal,"A check's refusal")};if(level!=="error"){return{refusal:`A check's refusal of "${String(raw.refusal)}" at level "${level}" is not one this channel accepts: a refusal is always an error.`}}return{check:{level,title:raw.title,refusal:raw.refusal}}}return{check:{level,title:raw.title}}}__name(validationCheckOf,"validationCheckOf");function scopeFailureDetail(error){const raw=error instanceof Error?error.message:String(error);const oneLine=raw.replace(/\s+/g," ").trim().replace(/[.!]+$/,"");if(oneLine.length===0)return"the connector refused without saying why";return oneLine.length>180?`${oneLine.slice(0,179)}\u2026`:oneLine}__name(scopeFailureDetail,"scopeFailureDetail");function targetsUnavailableFrom(error){return targetsUnavailable(scopeFailureDetail(error))}__name(targetsUnavailableFrom,"targetsUnavailableFrom");exports.TARGET_COMPARISON_KINDS=["matched","drifted","unconfirmed","unpromised"];function compareTargets(promised,touched){if(promised.uncounted)return{kind:"unpromised",promised,touched};if(touched.uncounted)return{kind:"unconfirmed",promised,touched};return{kind:promised.eligible===touched.eligible?"matched":"drifted",promised,touched}}__name(compareTargets,"compareTargets");function targetComparisonSentence(comparison){switch(comparison.kind){case"matched":return`The run acted on what was approved \u2014 ${targetSummarySentence(comparison.promised)}.`;case"drifted":return`Approved for ${targetSummarySentence(comparison.promised)}; the run acted on ${comparison.touched.eligible}.`;case"unconfirmed":{const because=comparison.touched.detail?` \u2014 ${comparison.touched.detail}`:"";return`Approved for ${targetSummarySentence(comparison.promised)}. The run did not record what it acted on${because}.`}case"unpromised":if(comparison.promised.uncounted==="no_scope")return null;if(comparison.touched.uncounted)return null;return`No target count was approved for this run; it acted on ${targetSummarySentence(comparison.touched)}.`}}__name(targetComparisonSentence,"targetComparisonSentence");function targetComparisonLabel(comparison){return comparison.kind==="drifted"?"Targets drifted":null}__name(targetComparisonLabel,"targetComparisonLabel");function targetComparisonLevel(comparison){return comparison.kind==="drifted"?"warn":"info"}__name(targetComparisonLevel,"targetComparisonLevel")}});var require_execution=__commonJS({"../contracts/dist/execution.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ACCEPTING_A_PROVENANCE_IS_NOT_A_CAPABILITY=exports.RUNNER_PACKAGE_RUNTIME_NOT_PINNED=exports.CONNECTOR_UNAVAILABLE_MESSAGE=exports.ACTION_RUNNABILITY_CAUSE_KINDS=exports.EXECUTION_LOG_ACTIVITY_PHRASE=exports.EXECUTION_LOG_CONNECTION_PHRASE=exports.EXECUTION_LOG_STREAM_PHASES=exports.EXECUTION_LOG_ACTIVITIES=exports.validationCheckOf=exports.targetsValidationCheck=exports.targetSummarySentence=exports.targetSummaryOf=exports.targetSummaryLabel=exports.targetsUnavailableFrom=exports.targetsUnavailable=exports.targetComparisonSentence=exports.targetComparisonLevel=exports.targetComparisonLabel=exports.TARGETS_NOT_COUNTED=exports.TARGETS_NO_SCOPE=exports.TARGET_COUNT_ABSENCES=exports.TARGET_COMPARISON_KINDS=exports.singleTarget=exports.scopeFailureDetail=exports.noTargetsResolved=exports.isTargetCountAbsence=exports.eligibleTargetCount=exports.compareTargets=exports.REFUSAL_CODES=exports.isCheckLevel=exports.isCheckCode=exports.isBuiltInRefusalCode=exports.isBuiltInDecisionCode=exports.DECISION_CODES=exports.checkCodeRefusal=exports.CHECK_LEVELS=exports.CHECK_CODE_MAX_LENGTH=exports.SUBSCRIPTION_ID_FIELD_RENAMED=void 0;exports.executionLogStreamSentence=executionLogStreamSentence;exports.actionRunnabilityCopy=actionRunnabilityCopy;exports.actionRunnabilityHeadline=actionRunnabilityHeadline;exports.actionRunnabilityRefusal=actionRunnabilityRefusal;var run_placement_1=require_run_placement();var packages_1=require_packages();var packages_2=require_packages();var brand_1=require_brand();exports.SUBSCRIPTION_ID_FIELD_RENAMED="`subscriptionId` is not accepted on this route. It named an `azure_subscription.id` while this route has always resolved a `connection_scope.id`. The two were the same value while one shim gave a scope the registry row's id; a scope discovered since has an id of its own, and the registry id is either nobody's scope or another connector's. Send `connectionScopeId` \u2014 the value `ExecutionDto.connectionScopeId` reports for a run.";var validation_1=require_validation();Object.defineProperty(exports,"CHECK_CODE_MAX_LENGTH",{enumerable:true,get:__name(function(){return validation_1.CHECK_CODE_MAX_LENGTH},"get")});Object.defineProperty(exports,"CHECK_LEVELS",{enumerable:true,get:__name(function(){return validation_1.CHECK_LEVELS},"get")});Object.defineProperty(exports,"checkCodeRefusal",{enumerable:true,get:__name(function(){return validation_1.checkCodeRefusal},"get")});Object.defineProperty(exports,"DECISION_CODES",{enumerable:true,get:__name(function(){return validation_1.DECISION_CODES},"get")});Object.defineProperty(exports,"isBuiltInDecisionCode",{enumerable:true,get:__name(function(){return validation_1.isBuiltInDecisionCode},"get")});Object.defineProperty(exports,"isBuiltInRefusalCode",{enumerable:true,get:__name(function(){return validation_1.isBuiltInRefusalCode},"get")});Object.defineProperty(exports,"isCheckCode",{enumerable:true,get:__name(function(){return validation_1.isCheckCode},"get")});Object.defineProperty(exports,"isCheckLevel",{enumerable:true,get:__name(function(){return validation_1.isCheckLevel},"get")});Object.defineProperty(exports,"REFUSAL_CODES",{enumerable:true,get:__name(function(){return validation_1.REFUSAL_CODES},"get")});Object.defineProperty(exports,"compareTargets",{enumerable:true,get:__name(function(){return validation_1.compareTargets},"get")});Object.defineProperty(exports,"eligibleTargetCount",{enumerable:true,get:__name(function(){return validation_1.eligibleTargetCount},"get")});Object.defineProperty(exports,"isTargetCountAbsence",{enumerable:true,get:__name(function(){return validation_1.isTargetCountAbsence},"get")});Object.defineProperty(exports,"noTargetsResolved",{enumerable:true,get:__name(function(){return validation_1.noTargetsResolved},"get")});Object.defineProperty(exports,"scopeFailureDetail",{enumerable:true,get:__name(function(){return validation_1.scopeFailureDetail},"get")});Object.defineProperty(exports,"singleTarget",{enumerable:true,get:__name(function(){return validation_1.singleTarget},"get")});Object.defineProperty(exports,"TARGET_COMPARISON_KINDS",{enumerable:true,get:__name(function(){return validation_1.TARGET_COMPARISON_KINDS},"get")});Object.defineProperty(exports,"TARGET_COUNT_ABSENCES",{enumerable:true,get:__name(function(){return validation_1.TARGET_COUNT_ABSENCES},"get")});Object.defineProperty(exports,"TARGETS_NO_SCOPE",{enumerable:true,get:__name(function(){return validation_1.TARGETS_NO_SCOPE},"get")});Object.defineProperty(exports,"TARGETS_NOT_COUNTED",{enumerable:true,get:__name(function(){return validation_1.TARGETS_NOT_COUNTED},"get")});Object.defineProperty(exports,"targetComparisonLabel",{enumerable:true,get:__name(function(){return validation_1.targetComparisonLabel},"get")});Object.defineProperty(exports,"targetComparisonLevel",{enumerable:true,get:__name(function(){return validation_1.targetComparisonLevel},"get")});Object.defineProperty(exports,"targetComparisonSentence",{enumerable:true,get:__name(function(){return validation_1.targetComparisonSentence},"get")});Object.defineProperty(exports,"targetsUnavailable",{enumerable:true,get:__name(function(){return validation_1.targetsUnavailable},"get")});Object.defineProperty(exports,"targetsUnavailableFrom",{enumerable:true,get:__name(function(){return validation_1.targetsUnavailableFrom},"get")});Object.defineProperty(exports,"targetSummaryLabel",{enumerable:true,get:__name(function(){return validation_1.targetSummaryLabel},"get")});Object.defineProperty(exports,"targetSummaryOf",{enumerable:true,get:__name(function(){return validation_1.targetSummaryOf},"get")});Object.defineProperty(exports,"targetSummarySentence",{enumerable:true,get:__name(function(){return validation_1.targetSummarySentence},"get")});Object.defineProperty(exports,"targetsValidationCheck",{enumerable:true,get:__name(function(){return validation_1.targetsValidationCheck},"get")});Object.defineProperty(exports,"validationCheckOf",{enumerable:true,get:__name(function(){return validation_1.validationCheckOf},"get")});exports.EXECUTION_LOG_ACTIVITIES=["executing","queued","awaiting_runner","awaiting_approval"];exports.EXECUTION_LOG_STREAM_PHASES=["reconnecting","stopped"];exports.EXECUTION_LOG_CONNECTION_PHRASE={reconnecting:"The live connection dropped, so this log has paused. It is reconnecting on its own.",stopped:"The live connection dropped and could not be restored, so this log has stopped updating."};exports.EXECUTION_LOG_ACTIVITY_PHRASE={executing:"The run itself is unaffected \u2014 it is still executing on the server.",queued:"The run has not started yet \u2014 it is waiting in the queue to be picked up.",awaiting_runner:"The run has not started yet \u2014 it is waiting for one of your runners to pick it up.",awaiting_approval:"The run has not started yet \u2014 it is waiting for a person to approve it."};function executionLogStreamSentence(phase,activity){return`${exports.EXECUTION_LOG_CONNECTION_PHRASE[phase]} ${exports.EXECUTION_LOG_ACTIVITY_PHRASE[activity]}`}__name(executionLogStreamSentence,"executionLogStreamSentence");var ACTION_RUNNABILITY_CAUSE_KIND_SET={catalog_blocked:true,beta_not_allowed:true,connector_unregistered:true,package:true,runner_pool:true,runner_image:true,runner_egress:true,runner_pool_ambiguous:true};exports.ACTION_RUNNABILITY_CAUSE_KINDS=Object.keys(ACTION_RUNNABILITY_CAUSE_KIND_SET);exports.CONNECTOR_UNAVAILABLE_MESSAGE="This action is not yet available to run.";var CATALOG_BLOCKED_CAUSE="This workspace does not permit this action.";var CATALOG_BLOCKED_REMEDY="An administrator of this workspace decides which catalog actions may run here, and can allow it.";var BETA_NOT_ALLOWED_CAUSE="This version is a beta, and this workspace has not allowed beta actions.";var BETA_NOT_ALLOWED_REMEDY="A workspace administrator can allow beta actions in Settings \u2192 Catalog.";function actionRunnabilityCopy(cause){switch(cause.kind){case"catalog_blocked":return`${CATALOG_BLOCKED_CAUSE} ${CATALOG_BLOCKED_REMEDY}`;case"beta_not_allowed":return`${BETA_NOT_ALLOWED_CAUSE} ${BETA_NOT_ALLOWED_REMEDY}`;case"package":return(0,packages_2.actionUnrunnableCopy)(cause.detail);case"runner_pool":{const{cause:why,remedy}=runnerPoolClauses(cause);return`This action's package ${why} ${remedy}`}case"runner_image":{const{cause:why,remedy}=runnerImageClauses(cause);return`${why} ${remedy}`}case"runner_egress":{const{cause:why,remedy}=runnerEgressClauses(cause);return`${why} ${remedy}`}case"runner_pool_ambiguous":return`This run's resources do not all execute in the same place: ${describeRoutingPlaces(cause.places)}. ${AMBIGUOUS_ROUTING_REMEDY}`;case"connector_unregistered":return exports.CONNECTOR_UNAVAILABLE_MESSAGE}}__name(actionRunnabilityCopy,"actionRunnabilityCopy");var AMBIGUOUS_ROUTING_REMEDY="Nothing was started \u2014 a run is recorded as having executed in ONE place, and splitting it would make that record untrue. Narrow the targets so they route together, and run each group separately.";function describeRoutingPlaces(places){return places.map(place=>{const where=place.poolName?`runner pool \u201C${place.poolName}\u201D`:run_placement_1.HOSTED_EXECUTION_LABEL;const why=place.ruleName?`the rule \u201C${place.ruleName}\u201D`:"this connection's default";return`${place.targetCount} via ${why} \u2192 ${where} (for example ${place.exampleResourceId})`}).join("; ")}__name(describeRoutingPlaces,"describeRoutingPlaces");function runnerPoolClauses(cause){const provenance2=cause.provenance?`is ${packages_1.PACKAGE_PROVENANCE_CLAUSES[cause.provenance]}`:"has no recorded provenance";return{cause:`${provenance2}, and would run on the private runner pool "${cause.poolName}", because that is where runs using this connection execute \u2014 on a machine you own, in a container that shares its host's kernel and acts with this connection's credential.`,remedy:`${acceptedClause(cause.accepts)} ${POOL_CONSENT_REMEDY}`}}__name(runnerPoolClauses,"runnerPoolClauses");function acceptedClause(accepts){if(accepts.length===0){return"This pool does not accept action packages of any provenance."}const labels=accepts.map(kind=>`\u201C${packages_1.PACKAGE_PROVENANCE_LABELS[kind]}\u201D`);return`This pool accepts ${joinWithAnd(labels)}, but not this package's provenance.`}__name(acceptedClause,"acceptedClause");function joinWithAnd(parts){if(parts.length<=1)return parts[0]??"";return`${parts.slice(0,-1).join(", ")} and ${parts[parts.length-1]}`}__name(joinWithAnd,"joinWithAnd");exports.RUNNER_PACKAGE_RUNTIME_NOT_PINNED="This deployment has not pinned a package runtime image, so its runners are installed without one and no action package can execute on a runner here.";exports.ACCEPTING_A_PROVENANCE_IS_NOT_A_CAPABILITY="Accepting a provenance decides WHOSE code may run on your machines; it does not decide whether a runner is able to run it.";function runnerImageClauses(cause){const where=`would run on the private runner pool \u201C${cause.poolName}\u201D, because that is where runs using this connection execute`;return{cause:`This action's connector ${where} \u2014 and it is not one of the connectors built into the runner's step image.`,remedy:`Every runner in the pool would have to be running an image that carries it. Runs whose resources execute in ${run_placement_1.HOSTED_EXECUTION_LABEL} are unaffected.`}}__name(runnerImageClauses,"runnerImageClauses");function runnerEgressClauses(cause){const scope=cause.confinedRunners===0?`No runner in the private runner pool \u201C${cause.poolName}\u201D blocks`:`Only ${cause.confinedRunners} of ${cause.totalRunners} runners in the private runner pool \u201C${cause.poolName}\u201D block`;return{cause:`This action's package declares the hosts it may reach, and ${brand_1.BRAND_SHORT_NAME} would have to enforce that where the package runs. ${scope} outbound traffic a package was never configured to send \u2014 each one measured that on its own substrate \u2014 so the list could be stated but not enforced.`,remedy:`A run cannot choose which runner claims it, so this is a property of the pool. It changes when the hosts running these runners can confine outbound traffic \u2014 on Kubernetes that means a CNI that enforces NetworkPolicy, which several do not by default. Runs whose resources execute in ${run_placement_1.HOSTED_EXECUTION_LABEL}, or on a pool that confines, are unaffected.`}}__name(runnerEgressClauses,"runnerEgressClauses");var POOL_CONSENT_REMEDY=`${brand_1.BRAND_SHORT_NAME} does not vouch for what runs on your machines \u2014 the owner of this pool does. An administrator can accept this provenance under Settings \u2192 Runners, and until they do, nothing of this provenance will be sent there. Built-in actions still run in that pool.`;function actionRunnabilityHeadline(cause){switch(cause.kind){case"catalog_blocked":return"this workspace does not permit its action \u2014 an administrator of this workspace can allow it";case"beta_not_allowed":return"its action version is a beta and this workspace has not allowed beta actions \u2014 an administrator can allow them in Settings \u2192 Catalog";case"package":return(0,packages_2.actionUnrunnableHeadline)(cause.detail);case"runner_pool":return cause.provenance?`the pool "${cause.poolName}" does not accept packages ${packages_1.PACKAGE_PROVENANCE_CLAUSES[cause.provenance]}`:`its package has no recorded provenance, so the pool "${cause.poolName}" cannot accept it`;case"runner_image":return`the runners in "${cause.poolName}" run an image that does not carry this action's connector`;case"runner_egress":return cause.confinedRunners===0?`no runner in "${cause.poolName}" can confine this package's outbound traffic`:`only ${cause.confinedRunners} of ${cause.totalRunners} runners in "${cause.poolName}" can confine this package's outbound traffic`;case"runner_pool_ambiguous":return`its resources would execute in ${cause.places.length} different places`;case"connector_unregistered":return`this deployment has no connector for "${cause.connectorKey}"`}}__name(actionRunnabilityHeadline,"actionRunnabilityHeadline");function actionRunnabilityRefusal(cause){switch(cause.kind){case"catalog_blocked":return`${CATALOG_BLOCKED_CAUSE} ${CATALOG_BLOCKED_REMEDY} Nothing was started.`;case"beta_not_allowed":return`${BETA_NOT_ALLOWED_CAUSE} ${BETA_NOT_ALLOWED_REMEDY} Nothing was started.`;case"package":return(0,packages_2.actionUnrunnableRefusal)(cause.detail,cause);case"runner_pool":{const{cause:why,remedy}=runnerPoolClauses(cause);return`This action's package ${why} ${remedy} Nothing was started.`}case"runner_image":{const{cause:why,remedy}=runnerImageClauses(cause);return`${why} ${remedy} Nothing was started.`}case"runner_egress":{const{cause:why,remedy}=runnerEgressClauses(cause);return`${why} ${remedy} Nothing was started.`}case"runner_pool_ambiguous":return`This run's resources do not all execute in the same place: ${describeRoutingPlaces(cause.places)}. ${AMBIGUOUS_ROUTING_REMEDY}`;case"connector_unregistered":return exports.CONNECTOR_UNAVAILABLE_MESSAGE}}__name(actionRunnabilityRefusal,"actionRunnabilityRefusal")}});var require_decisions=__commonJS({"../contracts/dist/decisions.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DECISION_ACKNOWLEDGEMENT=exports.TARGET_DISPOSITIONS=exports.UNDECIDED_AT_RUN=void 0;exports.recordedDecisionsOf=recordedDecisionsOf;exports.settleDecisionChecks=settleDecisionChecks3;exports.raisedDecisionCodes=raisedDecisionCodes;exports.decisionMismatch=decisionMismatch;exports.decisionMismatchSentence=decisionMismatchSentence;exports.targetDecisionsMismatchSentence=targetDecisionsMismatchSentence;exports.notRaisedPart=notRaisedPart;exports.decisionsMadeAtSubmit=decisionsMadeAtSubmit;exports.isTargetDisposition=isTargetDisposition;var validation_1=require_validation();function recordedDecisionsOf(stored){if(!Array.isArray(stored))return[];const read=[];for(const entry of stored){if(typeof entry!=="object"||entry===null)continue;const{code,acknowledgedBy,acknowledgedAt}=entry;if(!(0,validation_1.isCheckCode)(code))continue;if(typeof acknowledgedBy!=="string"||acknowledgedBy.length===0)continue;if(typeof acknowledgedAt!=="string"||Number.isNaN(Date.parse(acknowledgedAt)))continue;if(read.some(decision=>decision.code===code))continue;read.push({code,acknowledgedBy,acknowledgedAt})}return read}__name(recordedDecisionsOf,"recordedDecisionsOf");exports.UNDECIDED_AT_RUN="Nobody acknowledged this before the run, so it was not acted on.";function settleDecisionChecks3(checks,inHand){if(inHand.phase==="plan")return[...checks];return checks.map(check=>{if(!check.decision||check.level==="error")return check;if(inHand.recorded.some(decision=>decision.code===check.decision))return check;return{...check,level:"error",title:`${check.title} ${exports.UNDECIDED_AT_RUN}`}})}__name(settleDecisionChecks3,"settleDecisionChecks");function raisedDecisionCodes(checks){const raised=[];for(const check of checks){if(check.decision&&!raised.includes(check.decision))raised.push(check.decision)}return raised}__name(raisedDecisionCodes,"raisedDecisionCodes");function decisionMismatch(raised,acknowledged){const unacknowledged=raised.filter(code=>!acknowledged.includes(code));const notRaised=acknowledged.filter(code=>!raised.includes(code));return unacknowledged.length===0&&notRaised.length===0?null:{unacknowledged,notRaised}}__name(decisionMismatch,"decisionMismatch");function decisionMismatchSentence(mismatch,checks,acknowledgementOf){return`This run was not submitted: the checks were run again at submit, and they no longer match what was acknowledged. ${mismatchParts(mismatch,checks,acknowledgementOf).join(" ")} Review the plan and submit again.`}__name(decisionMismatchSentence,"decisionMismatchSentence");function targetDecisionsMismatchSentence(mismatches){const parts=mismatches.map(target=>target.unknown?`${target.label}: no longer one of this step's targets.`:`${target.label}: ${mismatchParts(target,target.checks,target.acknowledgementOf).join(" ")}`);const count=mismatches.length;return`This run was not started: the checks were run again, and for ${count} ${count===1?"target":"targets"} they no longer match what was decided. ${parts.join(" ")} Review the plan and start the run again.`}__name(targetDecisionsMismatchSentence,"targetDecisionsMismatchSentence");function mismatchParts(mismatch,checks,acknowledgementOf){const parts=[];for(const code of mismatch.unacknowledged){const sentence=checks.find(check=>check.decision===code)?.title??acknowledgementOf(code)??code;parts.push(`Not acknowledged: ${withStop(sentence)}`)}for(const code of mismatch.notRaised)parts.push(notRaisedPart(code,acknowledgementOf));return parts}__name(mismatchParts,"mismatchParts");function notRaisedPart(code,acknowledgementOf){const label=acknowledgementOf(code);return label===null?`Acknowledged, but this action declares no such decision: "${code}".`:`Acknowledged, but no longer raised: \u201C${label}\u201D.`}__name(notRaisedPart,"notRaisedPart");function decisionsMadeAtSubmit(codes,by,at){return codes.map(code=>({code,acknowledgedBy:by,acknowledgedAt:at.toISOString()}))}__name(decisionsMadeAtSubmit,"decisionsMadeAtSubmit");exports.TARGET_DISPOSITIONS=["ready","left_out","refused"];function isTargetDisposition(value){return typeof value==="string"&&exports.TARGET_DISPOSITIONS.includes(value)}__name(isTargetDisposition,"isTargetDisposition");function withStop(sentence){const trimmed=sentence.trim();return/[.!?]$/.test(trimmed)?trimmed:`${trimmed}.`}__name(withStop,"withStop");exports.DECISION_ACKNOWLEDGEMENT={"disk.recentlyDetached":"Delete it even though it was detached recently","disk.customerKey":"Delete it \u2014 restoring later depends on this key staying enabled","disk.customerKeyUnverified":"Delete it without confirmation that the key is enabled","disk.guestEncrypted":"Delete it \u2014 restoring later depends on the guest's encryption secrets","disk.noSnapshot":"Delete it with no snapshot \u2014 this cannot be undone","disk.confidential":"Delete it, accepting that restoring a confidential VM disk is not verified"}}});var require_execution_site=__commonJS({"../contracts/dist/execution-site.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EXECUTION_SITE_UNKNOWN=void 0;exports.runExecutionSiteSentence=runExecutionSiteSentence;exports.runExecutionSiteLabel=runExecutionSiteLabel;exports.plannedExecutionSiteSentence=plannedExecutionSiteSentence;exports.ambiguousPlaceLabel=ambiguousPlaceLabel;var run_placement_1=require_run_placement();function runExecutionSiteSentence(where){switch(where.site){case"hosted":return run_placement_1.HOSTED_EXECUTION_LABEL;case"runner":return where.runner?`Your runner \u201C${where.runner.name}\u201D in pool \u201C${where.pool.name}\u201D`:`Pool \u201C${where.pool.name}\u201D \u2014 no runner claimed it`;case"unknown":return"Not recorded"}}__name(runExecutionSiteSentence,"runExecutionSiteSentence");function runExecutionSiteLabel(where){switch(where.site){case"hosted":return run_placement_1.HOSTED_EXECUTION_LABEL;case"runner":return where.runner?where.runner.name:where.pool.name;case"unknown":return"Not recorded"}}__name(runExecutionSiteLabel,"runExecutionSiteLabel");exports.EXECUTION_SITE_UNKNOWN={site:"unknown"};function plannedExecutionSiteSentence(where){switch(where.site){case"hosted":return run_placement_1.HOSTED_EXECUTION_LABEL;case"runner":return`your own network \u2014 runner pool \u201C${where.pool.name}\u201D`;case"ambiguous":return`${where.places.length} different places`}}__name(plannedExecutionSiteSentence,"plannedExecutionSiteSentence");function ambiguousPlaceLabel(place){return place.poolName?`runner pool \u201C${place.poolName}\u201D`:run_placement_1.HOSTED_EXECUTION_LABEL}__name(ambiguousPlaceLabel,"ambiguousPlaceLabel")}});var require_connections=__commonJS({"../contracts/dist/connections.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PROVIDER_BADGE_COLOR=void 0;exports.PROVIDER_BADGE_COLOR={azure:"#0078d4"}}});var require_resources=__commonJS({"../contracts/dist/resources.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DISCOVERY_TYPE_PATTERN=exports.RESOURCE_TYPE_QUERY_KEY=exports.ARM_RESOURCE_TYPE_MAX_LENGTH=exports.LEGACY_DISCOVERY_PROVIDER=exports.DISCOVERY_VOCABULARY=void 0;exports.discoveryTypesOf=discoveryTypesOf;exports.declaredDiscoveryTypes=declaredDiscoveryTypes;exports.liveDiscoveryTypes=liveDiscoveryTypes;exports.canonicalDiscoveryId=canonicalDiscoveryId;exports.resolveDiscoveryType=resolveDiscoveryType;exports.isSecretReference=isSecretReference;exports.armResourceTypeRefusal=armResourceTypeRefusal;exports.admitArmResourceType=admitArmResourceType;exports.armIdentityResourceType=armIdentityResourceType;exports.resourceTypeDeclarationRefusal=resourceTypeDeclarationRefusal;exports.strictDiscoveryRefusal=strictDiscoveryRefusal;exports.parseDiscoveryType=parseDiscoveryType;exports.formatDiscoveryType=formatDiscoveryType;exports.discoveryTypeSpec=discoveryTypeSpec;exports.dependsOnLookup=dependsOnLookup;exports.discoveryScopeValues=discoveryScopeValues;exports.composeTargetIdentity=composeTargetIdentity;exports.fanOutSuppliedParameters=fanOutSuppliedParameters;var enums_1=require_enums();var AZURE_DISCOVERY_TYPES={resourceGroup:{requires:[],routable:false,identity:null,secretRef:false,takesResourceType:false},keyVault:{requires:[],routable:true,identity:null,secretRef:false,takesResourceType:false},keyVaultSecret:{requires:["vault"],routable:true,identity:"https://{vault}.vault.azure.net/secrets/{name}",secretRef:true,takesResourceType:false},location:{requires:[],routable:false,identity:null,secretRef:false,takesResourceType:false},managedDisk:{requires:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/disks/{name}",secretRef:false,takesResourceType:false},sqlServer:{requires:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{name}",secretRef:false,takesResourceType:false},sqlDatabase:{requires:["resourceGroup","server"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{server}/databases/{name}",secretRef:false,takesResourceType:false},virtualMachine:{requires:[],identifiedBy:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}",secretRef:false,takesResourceType:false},vmSize:{requires:["resourceGroup","vm"],routable:false,identity:null,secretRef:false,takesResourceType:false},arm:{requires:[],identifiedBy:["resourceGroup"],routable:true,identity:"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/{resourceType}/{name}",secretRef:false,takesResourceType:true}};var DECLARED_DISCOVERY={azure:AZURE_DISCOVERY_TYPES,aws:{},gcp:{},terraform:{}};exports.DISCOVERY_VOCABULARY=DECLARED_DISCOVERY;exports.LEGACY_DISCOVERY_PROVIDER="azure";function discoveryTypesOf(provider){return Object.keys(exports.DISCOVERY_VOCABULARY[provider]).map(type=>formatDiscoveryType(provider,type))}__name(discoveryTypesOf,"discoveryTypesOf");function declaredDiscoveryTypes(){return enums_1.PROVIDERS.flatMap(discoveryTypesOf)}__name(declaredDiscoveryTypes,"declaredDiscoveryTypes");function liveDiscoveryTypes(registered){const providers=new Set(registered);return enums_1.PROVIDERS.filter(provider=>providers.has(provider)).flatMap(discoveryTypesOf)}__name(liveDiscoveryTypes,"liveDiscoveryTypes");function canonicalDiscoveryId(value){const parsed=parseDiscoveryType(value.trim(),exports.LEGACY_DISCOVERY_PROVIDER);return parsed?formatDiscoveryType(parsed.provider,parsed.type):null}__name(canonicalDiscoveryId,"canonicalDiscoveryId");function resolveDiscoveryType(value){const parsed=parseDiscoveryType(value.trim(),exports.LEGACY_DISCOVERY_PROVIDER);if(!parsed)return null;const spec=discoveryTypeSpec(parsed.provider,parsed.type);if(!spec)return null;return{id:formatDiscoveryType(parsed.provider,parsed.type),provider:parsed.provider,type:parsed.type,spec}}__name(resolveDiscoveryType,"resolveDiscoveryType");function isSecretReference(discover){return discover?resolveDiscoveryType(discover)?.spec.secretRef===true:false}__name(isSecretReference,"isSecretReference");var NAMESPACE_SEGMENT="[A-Z][A-Za-z0-9]*";var TYPE_SEGMENT="[A-Za-z][A-Za-z0-9]*";var ARM_RESOURCE_TYPE_PATTERN=new RegExp(`^${NAMESPACE_SEGMENT}(?:\\.${NAMESPACE_SEGMENT})+(?:/${TYPE_SEGMENT})+$`);exports.ARM_RESOURCE_TYPE_MAX_LENGTH=256;var ARM_RESOURCE_TYPE_SHAPE='an ARM resource type is a provider namespace of dot-separated PascalCase segments, then one or more "/type" segments of letters and digits, e.g. "Microsoft.Network/publicIPAddresses" or "Microsoft.Sql/servers/databases"';function armResourceTypeRefusal(value){if(typeof value!=="string")return`resourceType must be a string: ${ARM_RESOURCE_TYPE_SHAPE}.`;if(value.length>exports.ARM_RESOURCE_TYPE_MAX_LENGTH){return`resourceType is ${value.length} characters, longer than ${exports.ARM_RESOURCE_TYPE_MAX_LENGTH}: ${ARM_RESOURCE_TYPE_SHAPE}.`}if(!ARM_RESOURCE_TYPE_PATTERN.test(value)){return`${JSON.stringify(value)} is not an ARM resource type: ${ARM_RESOURCE_TYPE_SHAPE}.`}return null}__name(armResourceTypeRefusal,"armResourceTypeRefusal");function admitArmResourceType(value){return armResourceTypeRefusal(value)===null?value:null}__name(admitArmResourceType,"admitArmResourceType");function armIdentityResourceType(value){const admitted=admitArmResourceType(value);return admitted!==null&&admitted.split("/").length===2?admitted:null}__name(armIdentityResourceType,"armIdentityResourceType");function resourceTypeDeclarationRefusal(discover,resourceType){const resolved=discover===void 0?null:resolveDiscoveryType(discover);if(resolved?.spec.takesResourceType){if(resourceType!==void 0)return armResourceTypeRefusal(resourceType);return`"${resolved.id}" lists whatever ARM resource type the parameter declares, so the parameter must declare one in resourceType, e.g. "Microsoft.Network/publicIPAddresses".`}if(resourceType===void 0)return null;const readers=declaredDiscoveryTypes().filter(id=>resolveDiscoveryType(id)?.spec.takesResourceType);const discovers=discover===void 0?"declares no discovery":`discovers "${resolved?.id??discover}"`;return`resourceType is read only by a discovery type that lists a declared resource type (${readers.join(", ")}), and this parameter ${discovers}.`}__name(resourceTypeDeclarationRefusal,"resourceTypeDeclarationRefusal");function strictDiscoveryRefusal(input){const parsed=parseDiscoveryType(input.discover.trim(),input.provider??exports.LEGACY_DISCOVERY_PROVIDER);if(!parsed||!discoveryTypeSpec(parsed.provider,parsed.type)?.takesResourceType)return null;const id=`"${formatDiscoveryType(parsed.provider,parsed.type)}"`;const subject=input.parameter===void 0?id:`Parameter "${input.parameter}" discovers ${id}, which`;return`${subject} lists whatever resource type the action declares. A picker offers it, but nothing can be fanned out over it or routed by rule on it yet: fan-out and routing over an arbitrary resource type come with docs/128 Slice D.`}__name(strictDiscoveryRefusal,"strictDiscoveryRefusal");exports.RESOURCE_TYPE_QUERY_KEY="resourceType";exports.DISCOVERY_TYPE_PATTERN=/^(?:([a-z][a-z0-9]*)\/)?([a-z][a-zA-Z0-9]{0,63})$/;function parseDiscoveryType(value,fallbackProvider){const match=exports.DISCOVERY_TYPE_PATTERN.exec(value);if(!match)return null;const[,prefix,type]=match;if(prefix!==void 0){const provider=enums_1.PROVIDERS.find(p=>p===prefix);return provider?{provider,type}:null}return fallbackProvider?{provider:fallbackProvider,type}:null}__name(parseDiscoveryType,"parseDiscoveryType");function formatDiscoveryType(provider,type){return`${provider}/${type}`}__name(formatDiscoveryType,"formatDiscoveryType");function discoveryTypeSpec(provider,type){if(!Object.prototype.hasOwnProperty.call(exports.DISCOVERY_VOCABULARY,provider))return void 0;const vocabulary=exports.DISCOVERY_VOCABULARY[provider];return Object.prototype.hasOwnProperty.call(vocabulary,type)?vocabulary[type]:void 0}__name(discoveryTypeSpec,"discoveryTypeSpec");function dependsOnLookup(keys,dependsOn){const lookup={};for(const key of keys)lookup[key]=key;if(Array.isArray(dependsOn)){for(const name3 of dependsOn)if(keys.includes(name3))lookup[name3]=name3}else if(dependsOn){for(const[key,name3]of Object.entries(dependsOn)){if(typeof name3==="string"&&name3.trim())lookup[key]=name3.trim()}}return lookup}__name(dependsOnLookup,"dependsOnLookup");function discoveryScopeValues(requires,dependsOn,parameters,skipKeys=[]){const parameterFor=dependsOnLookup(requires,dependsOn);const scope={};for(const key of requires){if(skipKeys.includes(key))continue;const parameter=parameterFor[key]??key;const value=parameters[parameter];if(typeof value!=="string"||value.trim().length===0){return{resolved:false,missingKey:key,parameter}}scope[key]=value.trim()}return{resolved:true,scope}}__name(discoveryScopeValues,"discoveryScopeValues");function composeTargetIdentity(template,values){let missing="";const resourceId=template.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g,(_whole,key)=>{const value=values[key]?.trim();if(!value){if(!missing)missing=key;return""}return value});return missing?{composed:false,missing}:{composed:true,resourceId}}__name(composeTargetIdentity,"composeTargetIdentity");function fanOutSuppliedParameters(input){const{spec,dependsOn,selectorParameter,variedByQuery=[]}=input;const identity=spec.identifiedBy??spec.requires;const lookup=dependsOnLookup(identity,dependsOn);const varied=new Set(variedByQuery);const supplied=[];const push=__name(name3=>{const trimmed=name3.trim();if(trimmed&&!supplied.includes(trimmed))supplied.push(trimmed)},"push");push(selectorParameter);for(const key of identity){if(spec.requires.includes(key)&&!varied.has(key))continue;push(lookup[key]??key)}return supplied}__name(fanOutSuppliedParameters,"fanOutSuppliedParameters")}});var require_governance=__commonJS({"../contracts/dist/governance.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ANY_POLICY_MATCH=void 0;exports.approvalAssessmentOf=approvalAssessmentOf;exports.planAssessmentOf=planAssessmentOf;exports.approvalOutcome=approvalOutcome;exports.policyScopeSentence=policyScopeSentence;var decisions_1=require_decisions();var validation_1=require_validation();function approvalAssessmentOf(checks,decided){const assessment={facts:[],warnings:[],decisions:[]};for(const check of checks){if(check.decision){const answer=decided.find(decision=>decision.code===check.decision);if(answer)assessment.decisions.push({...answer,title:check.title,acknowledgement:check.acknowledgement})}else if(check.level==="warn"){assessment.warnings.push(check.title)}else if(check.level==="info"){assessment.facts.push(check.title)}}return assessment}__name(approvalAssessmentOf,"approvalAssessmentOf");function planAssessmentOf(value){if(typeof value!=="object"||value===null||Array.isArray(value))return null;const a=value;if(!Array.isArray(a.facts)||!Array.isArray(a.warnings)||!Array.isArray(a.decisions)){return null}const decisions=[];for(const entry of a.decisions){const[decision]=(0,decisions_1.recordedDecisionsOf)([entry]);const raw=typeof entry==="object"&&entry!==null?entry:{};if(!decision||typeof raw.title!=="string")return null;const acknowledgement=typeof raw.acknowledgement==="string"&&raw.acknowledgement.length>0?raw.acknowledgement:raw.acknowledgement===void 0&&(0,validation_1.isBuiltInDecisionCode)(decision.code)?decisions_1.DECISION_ACKNOWLEDGEMENT[decision.code]:null;if(acknowledgement===null)return null;decisions.push({...decision,title:raw.title,acknowledgement})}const strings=__name(list=>list.filter(item=>typeof item==="string"),"strings");return{facts:strings(a.facts),warnings:strings(a.warnings),decisions}}__name(planAssessmentOf,"planAssessmentOf");exports.ANY_POLICY_MATCH={environments:[],riskLevels:[],actionKeys:[],connectionIds:[]};function approvalOutcome(decision,adoptionRequiresApproval){if(!decision.requireApproval){return{requiresApproval:false,approverGroup:null,reason:"No approval required \u2014 this run is submitted straight to execution.",matchedPolicy:null}}const who=decision.approverGroup?` A member of ${decision.approverGroup.name} must approve it first.`:" Anyone who can approve may sign it off.";const rule=decision.matchedPolicy;const why=adoptionRequiresApproval?"Approval required \u2014 this action's adoption is configured to require sign-off.":rule?`Approval required by your governance rule \u201C${rule.name}\u201D (${policyScopeSentence(rule)}).`:"Approval required by your organization's governance policy.";return{requiresApproval:true,approverGroup:decision.approverGroup,reason:`${why}${who}`,matchedPolicy:adoptionRequiresApproval?null:rule??null}}__name(approvalOutcome,"approvalOutcome");function policyScopeSentence(rule){const parts=[];if(rule.riskLevels.length>0){parts.push(`${joinWithOr(rule.riskLevels)}-risk`)}parts.push(rule.actionKeys.length>0?`runs of ${joinWithOr(rule.actionKeys)}`:"runs");if(rule.environments.length>0){parts.push(`in ${joinWithOr(rule.environments.map(e=>ENVIRONMENT_PHRASE[e]))}`)}if(rule.connections.length>0){const named=rule.connections.map(c=>c.name??"a connector that no longer exists");parts.push(`using ${joinWithOr(named)}`)}const sentence=parts.join(" ");return sentence==="runs"?"every run":sentence}__name(policyScopeSentence,"policyScopeSentence");var ENVIRONMENT_PHRASE={production:"production",staging:"staging",non_prod:"non-prod"};function joinWithOr(values){if(values.length<=1)return values[0]??"";return`${values.slice(0,-1).join(", ")} or ${values[values.length-1]}`}__name(joinWithOr,"joinWithOr")}});var require_audit=__commonJS({"../contracts/dist/audit.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_notifications=__commonJS({"../contracts/dist/notifications.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NOTIFICATION_LEVELS=exports.NOTIFICATION_TYPES=void 0;exports.NOTIFICATION_TYPES=["run_completed","approval_requested","approval_resolved","schedule_failed","verification_failed"];exports.NOTIFICATION_LEVELS=["success","error","warning","info"]}});var require_scheduling=__commonJS({"../contracts/dist/scheduling.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_operations=__commonJS({"../contracts/dist/operations.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PREVIEW_UNCHECKED_SENTENCE=exports.PREVIEW_UNCHECKED_REASONS=exports.OPERATION_RUN_TARGET_STATUSES=exports.OPERATION_RUN_STEP_STATUSES=exports.OPERATION_RUN_STATUSES=exports.STEP_FAILURE_POLICIES=exports.OPERATION_STEP_KINDS=exports.DRY_RUN_OUTCOMES=exports.OPERATION_VERIFICATION_LIFECYCLES=exports.OPERATION_HEALTH_STATES=exports.OPERATION_LIFECYCLES=void 0;exports.targetPlanOf=targetPlanOf;var governance_1=require_governance();var decisions_1=require_decisions();exports.OPERATION_LIFECYCLES=["draft","published","deprecated","retired"];exports.OPERATION_HEALTH_STATES=["unverified","healthy","degraded","broken"];exports.OPERATION_VERIFICATION_LIFECYCLES=["queued","running","finished","abandoned"];exports.DRY_RUN_OUTCOMES=["passed","failed","unsupported","quota_exhausted","change_record_required"];exports.OPERATION_STEP_KINDS=["action","wait","approval"];exports.STEP_FAILURE_POLICIES=["stop","continue","rollback_completed"];exports.OPERATION_RUN_STATUSES=["pending","running","pending_approval","cancelling","succeeded","partially_succeeded","failed","rolled_back","partially_rolled_back","cancelled"];exports.OPERATION_RUN_STEP_STATUSES=["pending","running","awaiting_approval","succeeded","failed","skipped","not_reversible"];exports.OPERATION_RUN_TARGET_STATUSES=["pending","running","awaiting_approval","succeeded","failed","cancelled","rolled_back","rollback_failed"];function targetPlanOf(stored){if(!Array.isArray(stored))return null;const plan=[];for(const entry of stored){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;const{ref,label,disposition,decisions,assessment,refusal}=entry;if(typeof ref!=="string"||ref.length===0)continue;if(typeof label!=="string"||!(0,decisions_1.isTargetDisposition)(disposition))continue;if(refusal!==null&&typeof refusal!=="string")continue;plan.push({ref,label,disposition,decisions:(0,decisions_1.recordedDecisionsOf)(decisions),assessment:(0,governance_1.planAssessmentOf)(assessment),refusal:refusal??null})}return plan}__name(targetPlanOf,"targetPlanOf");exports.PREVIEW_UNCHECKED_REASONS=["depends_on_earlier_output","connector_plans_no_checks"];exports.PREVIEW_UNCHECKED_SENTENCE={depends_on_earlier_output:"Not checked before the run: this step's parameters come from an earlier step's outputs, which exist only once that step has run. Each target is checked when its execution is submitted, and a target that would need a decision is not acted on.",connector_plans_no_checks:"This action runs no checks of its own before the run."}}});var require_runs=__commonJS({"../contracts/dist/runs.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUN_STEP_TARGET_PAGE=exports.DEFAULT_RUN_SCOPE=exports.RUN_SCOPES=exports.RUN_FEED_STATUSES=exports.RUN_ORIGINS=void 0;exports.isRunFeedStatus=isRunFeedStatus;var enums_1=require_enums();var operations_1=require_operations();exports.RUN_ORIGINS=["operation","standalone","trial"];exports.RUN_FEED_STATUSES=[...enums_1.EXECUTION_STATUSES,...operations_1.OPERATION_RUN_STATUSES.filter(status=>!enums_1.EXECUTION_STATUSES.includes(status))];function isRunFeedStatus(value){return exports.RUN_FEED_STATUSES.includes(value)}__name(isRunFeedStatus,"isRunFeedStatus");exports.RUN_SCOPES=["all","mine"];exports.DEFAULT_RUN_SCOPE="all";exports.RUN_STEP_TARGET_PAGE=5}});var require_evidence_pack=__commonJS({"../contracts/dist/evidence-pack.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EVIDENCE_EXPORTED_AUDIT_ACTION=exports.EVIDENCE_DIGEST_HEADER=void 0;exports.evidencePackFilename=evidencePackFilename;exports.EVIDENCE_DIGEST_HEADER="X-Evidence-Digest";exports.EVIDENCE_EXPORTED_AUDIT_ACTION="operation.evidence_exported";function evidencePackFilename(operationKey,from,to){return`${operationKey}-evidence-${compactInstant(from)}-${compactInstant(to)}.json`}__name(evidencePackFilename,"evidencePackFilename");function compactInstant(iso){return iso.replace(/\.\d+(?=Z|[+-]\d{2}:?\d{2}$)/,"").replace(/[-:]/g,"")}__name(compactInstant,"compactInstant")}});var require_package_egress=__commonJS({"../contracts/dist/package-egress.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EGRESS_MODE_STOPS_BYPASS=exports.EGRESS_MODE_LABEL=exports.EGRESS_MODES=void 0;exports.egressWasABoundary=egressWasABoundary;exports.egressDisclosureHeadline=egressDisclosureHeadline;exports.egressDisclosureSentence=egressDisclosureSentence;var brand_1=require_brand();exports.EGRESS_MODES=["denied","enforced","cooperative"];exports.EGRESS_MODE_LABEL={denied:"No network",enforced:"Enforced",cooperative:"Configured, not enforced"};exports.EGRESS_MODE_STOPS_BYPASS={denied:false,enforced:true,cooperative:false};function egressWasABoundary(disclosure){return exports.EGRESS_MODE_STOPS_BYPASS[disclosure.mode]||disclosure.mode==="denied"&&disclosure.substrateBlocksUndeclared}__name(egressWasABoundary,"egressWasABoundary");function egressDisclosureHeadline(disclosure){switch(disclosure.mode){case"denied":return disclosure.substrateBlocksUndeclared?"No network \u2014 nothing outside was reachable.":"No network was configured, and this substrate does not block outbound traffic.";case"enforced":return"Only these hosts were reachable \u2014 nothing else could be.";case"cooperative":return"Configured to reach only these hosts \u2014 not prevented from reaching elsewhere."}}__name(egressDisclosureHeadline,"egressDisclosureHeadline");function egressDisclosureSentence(disclosure){const hosts=disclosure.allowlist.join(", ");switch(disclosure.mode){case"denied":return disclosure.substrateBlocksUndeclared?"This package declares no outbound network. It runs with no route out at all, so nothing outside is reachable.":`This package declares no outbound network, so ${brand_1.BRAND_SHORT_NAME} configures no proxy for it. The substrate it runs on does not itself block outbound traffic, so a package that reached out anyway would not be stopped.`;case"enforced":return`The package can reach only ${hosts}. The proxy enforcing that is the run's only route out, so a package that ignored it could not reach anywhere else either.`;case"cooperative":return`The package process is configured to reach only ${hosts}. This guards against the package reaching somewhere by mistake \u2014 a wrong endpoint, a dependency phoning home \u2014 and not against a package that sets out to go elsewhere: this substrate cannot stop one that ignores the configuration.`}}__name(egressDisclosureSentence,"egressDisclosureSentence")}});var require_package_execution=__commonJS({"../contracts/dist/package-execution.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUN_TOKEN_REJECTED=exports.RUN_TOKEN_HEADER=exports.PACKAGE_RUNNER_ENTRYPOINT=exports.PACKAGE_CONTAINER_ENV=exports.PACKAGE_PHASES=void 0;exports.PACKAGE_PHASES=["validate","run","rollback"];exports.PACKAGE_CONTAINER_ENV={callbackBaseUrl:"OPERA_CALLBACK_BASE_URL",executionId:"RUNVERIC_EXECUTION_ID",runToken:"OPERA_RUN_TOKEN",contentDigest:"RUNVERIC_CONTENT_DIGEST",runnerImageDigest:"OPERA_RUNNER_IMAGE_DIGEST",egressProxyUrl:"RUNVERIC_EGRESS_PROXY_URL",egressControlUrl:"RUNVERIC_EGRESS_CONTROL_URL",egressControlToken:"RUNVERIC_EGRESS_CONTROL_TOKEN"};exports.PACKAGE_RUNNER_ENTRYPOINT=["/opt/runveric/runner/launch.sh"];exports.RUN_TOKEN_HEADER="x-runveric-run-token";exports.RUN_TOKEN_REJECTED="This run token is not valid for this execution."}});var require_runner_confinement=__commonJS({"../contracts/dist/runner-confinement.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CONFINEMENT_FINDING_LABEL=exports.CONFINEMENT_FINDING_SENTENCE=exports.RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS=exports.CONFINEMENT_FINDING_BLOCKS_EGRESS=exports.CONFINEMENT_FINDINGS=exports.RUNNER_SUBSTRATE_LABEL=exports.RUNNER_SUBSTRATES=exports.EGRESS_GATE_SHUT=exports.EGRESS_GATE_OPEN=exports.EGRESS_GATE_PREFIX=exports.EGRESS_PROBE_TIMEOUT_MS=exports.EGRESS_PROBE_BLOCKED=exports.EGRESS_PROBE_REACHED=exports.EGRESS_PROBE_PREFIX=void 0;exports.effectiveBlocksUndeclaredEgress=effectiveBlocksUndeclaredEgress;exports.confinementOverclaims=confinementOverclaims;exports.runnerBlocksUndeclaredEgress=runnerBlocksUndeclaredEgress;exports.poolConfinementSentence=poolConfinementSentence;var brand_1=require_brand();exports.EGRESS_PROBE_PREFIX="runveric.egress-probe";exports.EGRESS_PROBE_REACHED="REACHED";exports.EGRESS_PROBE_BLOCKED="BLOCKED";exports.EGRESS_PROBE_TIMEOUT_MS=5e3;exports.EGRESS_GATE_PREFIX="runveric.egress-gate";exports.EGRESS_GATE_OPEN="OPEN";exports.EGRESS_GATE_SHUT="SHUT";exports.RUNNER_SUBSTRATES=["docker","kubernetes"];exports.RUNNER_SUBSTRATE_LABEL={docker:"Docker",kubernetes:"Kubernetes"};exports.CONFINEMENT_FINDINGS=["confined","unconfined","unproven"];exports.CONFINEMENT_FINDING_BLOCKS_EGRESS={confined:true,unconfined:false,unproven:false};exports.RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS=true;function effectiveBlocksUndeclaredEgress(isolationCeiling,finding){return isolationCeiling&&exports.CONFINEMENT_FINDING_BLOCKS_EGRESS[finding]}__name(effectiveBlocksUndeclaredEgress,"effectiveBlocksUndeclaredEgress");function confinementOverclaims(isolationCeiling,finding){return!isolationCeiling&&exports.CONFINEMENT_FINDING_BLOCKS_EGRESS[finding]}__name(confinementOverclaims,"confinementOverclaims");function runnerBlocksUndeclaredEgress(finding){return effectiveBlocksUndeclaredEgress(exports.RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS,finding)}__name(runnerBlocksUndeclaredEgress,"runnerBlocksUndeclaredEgress");exports.CONFINEMENT_FINDING_SENTENCE={confined:__name(()=>"Undeclared outbound traffic is blocked here. This runner proved it: a probe that reaches the network when nothing stops it could not reach anything once the confinement applied.","confined"),unconfined:__name(()=>"Undeclared outbound traffic is NOT blocked here. This runner probed its own substrate and the probe got out, so a package that ignored its egress settings would reach the network. Packages that need their allowlist enforced will not be sent to this pool.","unconfined"),unproven:__name(()=>`This runner could not establish whether undeclared outbound traffic is blocked, so ${brand_1.BRAND_SHORT_NAME} does not claim that it is. The check needs one throwaway pod that can reach the network when nothing stops it; until that succeeds there is no measurement to report.`,"unproven")};exports.CONFINEMENT_FINDING_LABEL={confined:"Egress confined",unconfined:"Egress not confined",unproven:"Confinement unproven"};function poolConfinementSentence(findings){if(findings.length===0)return null;const confined=findings.filter(runnerBlocksUndeclaredEgress).length;if(confined===findings.length)return exports.CONFINEMENT_FINDING_SENTENCE.confined();if(confined===0){const[first2]=findings;return findings.every(f=>f===first2)?exports.CONFINEMENT_FINDING_SENTENCE[first2]():`${exports.CONFINEMENT_FINDING_SENTENCE.unconfined()} Not every runner here reached that conclusion the same way \u2014 open a runner to see what each one measured.`}return`Only ${confined} of ${findings.length} runners in this pool block undeclared outbound traffic. A run cannot choose which runner claims it, so this pool is not relied on to confine egress and packages that need their allowlist enforced are not sent here.`}__name(poolConfinementSentence,"poolConfinementSentence")}});var require_runner_install=__commonJS({"../contracts/dist/runner-install.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POD_ROLE_BROKER=exports.POD_EGRESS_CONFINED=exports.POD_EGRESS_LABEL=exports.POD_RUNNER=exports.POD_ROLE=exports.POD_MANAGED_BY_VALUE=exports.POD_MANAGED_BY=exports.RUNNER_NETWORK_POLICY_NAME=exports.RUNNER_REPORT_DIRECTORY=exports.RUNNER_STATE_DIRECTORY=exports.RUNNER_CONTAINER_PREFIX=exports.RUNNER_NAMESPACE=exports.RUNNER_HOST_ENV=void 0;exports.RUNNER_HOST_ENV={substrate:"RUNVERIC_RUNNER_SUBSTRATE",controlPlaneUrl:"RUNVERIC_CONTROL_PLANE_URL",runnerName:"RUNVERIC_RUNNER_NAME",registrationToken:"RUNVERIC_RUNNER_REGISTRATION_TOKEN",stepImage:"RUNVERIC_RUNNER_STEP_IMAGE",packageImage:"RUNVERIC_RUNNER_PACKAGE_IMAGE",reportDirectory:"RUNVERIC_RUNNER_REPORT_DIR"};exports.RUNNER_NAMESPACE="runveric-runner";exports.RUNNER_CONTAINER_PREFIX="runveric-";exports.RUNNER_STATE_DIRECTORY="/var/lib/runveric-runner";exports.RUNNER_REPORT_DIRECTORY=`${exports.RUNNER_STATE_DIRECTORY}/reports`;exports.RUNNER_NETWORK_POLICY_NAME="runveric-confined-egress";exports.POD_MANAGED_BY="runveric.dev/managed-by";exports.POD_MANAGED_BY_VALUE="runveric-dispatcher";exports.POD_ROLE="runveric.dev/role";exports.POD_RUNNER="runveric.dev/runner";exports.POD_EGRESS_LABEL="runveric.dev/egress";exports.POD_EGRESS_CONFINED="confined";exports.POD_ROLE_BROKER="egress-broker"}});var require_authoring_cli=__commonJS({"../contracts/dist/authoring-cli.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ENGINE_AUTHORING_SINCE_CLI_VERSION=exports.RETIRED_AUTHORING_CLI_ENV=exports.AUTHORING_CLI_ENV=void 0;exports.pinnedCliVersion=pinnedCliVersion;exports.advertisesEngineAuthoring=advertisesEngineAuthoring;exports.AUTHORING_CLI_ENV={token:"RUNVERIC_TOKEN",url:"RUNVERIC_URL",runnerImage:"RUNVERIC_RUNNER_IMAGE"};exports.RETIRED_AUTHORING_CLI_ENV={token:"OPERA_TOKEN",url:"OPERA_URL",runnerImage:"OPERA_RUNNER_IMAGE"};exports.ENGINE_AUTHORING_SINCE_CLI_VERSION="0.5.0";function pinnedCliVersion(installCommand){return/^npx \S+@(\d+\.\d+\.\d+)$/.exec(installCommand)?.[1]??null}__name(pinnedCliVersion,"pinnedCliVersion");function advertisesEngineAuthoring(installCommand){const pinned=pinnedCliVersion(installCommand);if(pinned===null)return false;const[major,minor,patch]=pinned.split(".").map(Number);const[sinceMajor,sinceMinor,sincePatch]=exports.ENGINE_AUTHORING_SINCE_CLI_VERSION.split(".").map(Number);return(major-sinceMajor||minor-sinceMinor||patch-sincePatch)>=0}__name(advertisesEngineAuthoring,"advertisesEngineAuthoring")}});var require_runners=__commonJS({"../contracts/dist/runners.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUNNER_AUTHORIZATION_REFUSALS=exports.RUNNER_REFUSAL_SUBJECTS=exports.RUNNER_WORK_KINDS=exports.RUNNER_PROTOCOL_VERSION=exports.RUNNER_PRESENCES=exports.RUNNER_QUIET_AFTER_MS=exports.RUNNER_LIFECYCLES=exports.RUNNER_POOL_DEFAULT_ACCEPTS_PROVENANCE=exports.RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT=exports.RUNNER_AUTHORIZATION_TOKEN_HEADER=exports.RUNNER_CREDENTIAL_HEADER=exports.RUNNER_REGISTRATION_TOKEN_HEADER=void 0;exports.poolAcceptsProvenance=poolAcceptsProvenance;exports.containerNameFor=containerNameFor;exports.runnerPresence=runnerPresence;exports.runnerVersionStanding=runnerVersionStanding;var wire_identity_1=require_wire_identity();Object.defineProperty(exports,"RUNNER_PROTOCOL_VERSION",{enumerable:true,get:__name(function(){return wire_identity_1.RUNNER_PROTOCOL_VERSION},"get")});var package_provenance_1=require_package_provenance();var runner_install_1=require_runner_install();exports.RUNNER_REGISTRATION_TOKEN_HEADER="x-runveric-runner-registration-token";exports.RUNNER_CREDENTIAL_HEADER="x-runveric-runner-credential";exports.RUNNER_AUTHORIZATION_TOKEN_HEADER="x-runveric-runner-authorization";exports.RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT={git_source:false,public_git:false,authored:false};exports.RUNNER_POOL_DEFAULT_ACCEPTS_PROVENANCE=package_provenance_1.PACKAGE_PROVENANCE_KINDS.filter(kind=>exports.RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT[kind]);function poolAcceptsProvenance(accepts,provenance2){if(provenance2===null)return false;return accepts.includes(provenance2)}__name(poolAcceptsProvenance,"poolAcceptsProvenance");function containerNameFor(runnerName){return`${runner_install_1.RUNNER_CONTAINER_PREFIX}${runnerName.trim()}`}__name(containerNameFor,"containerNameFor");exports.RUNNER_LIFECYCLES=["active","draining","revoked"];exports.RUNNER_QUIET_AFTER_MS=9e4;exports.RUNNER_PRESENCES=["online","quiet","offline"];function runnerPresence(runner,now){if(new Date(runner.credentialExpiresAt).getTime()<=now)return"offline";return now-new Date(runner.lastSeenAt).getTime()<exports.RUNNER_QUIET_AFTER_MS?"online":"quiet"}__name(runnerPresence,"runnerPresence");function runnerVersionStanding(runnerVersion,policy){const runner=parseRunnerVersion(runnerVersion);if(runner===null)return"unsupported";if(compareRunnerVersions(runner,parseRunnerVersion(policy.minimumVersion)??[0,0,0])<0){return"unsupported"}const installed=parseRunnerVersion(policy.version);if(installed!==null&&compareRunnerVersions(runner,installed)<0)return"behind";return"current"}__name(runnerVersionStanding,"runnerVersionStanding");function parseRunnerVersion(value){const match=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(value.trim());if(!match)return null;return[Number(match[1]),Number(match[2]),Number(match[3])]}__name(parseRunnerVersion,"parseRunnerVersion");function compareRunnerVersions(a,b){for(let i=0;i<3;i+=1){if(a[i]!==b[i])return a[i]-b[i]}return 0}__name(compareRunnerVersions,"compareRunnerVersions");exports.RUNNER_WORK_KINDS=["step","package"];exports.RUNNER_REFUSAL_SUBJECTS=["runner","authorization"];exports.RUNNER_AUTHORIZATION_REFUSALS=["expired","unknown"]}});var require_scoped_credential=__commonJS({"../contracts/dist/scoped-credential.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RunnerStepCredentialExpiredError=exports.RunnerStepCredentialError=exports.STEP_CREDENTIAL_FAILURE=exports.ENGINE_ACTION_TOKEN_HOLDER=exports.RUNNER_STEP_TOKEN_HOLDER=exports.StaticScopedCredential=void 0;var StaticScopedCredential=class StaticScopedCredential{static{__name(this,"StaticScopedCredential")}now;holder;byScope;constructor(tokens2,now=Date.now,holder=exports.RUNNER_STEP_TOKEN_HOLDER){this.now=now;this.holder=holder;this.byScope=new Map(tokens2.map(token2=>[token2.scope,token2]))}async getToken(scopes){const requested=typeof scopes==="string"?[scopes]:scopes;for(const scope of requested){const token2=this.byScope.get(scope);if(token2){if(token2.expiresOnTimestamp<=this.now()){throw new RunnerStepCredentialExpiredError(scope,token2.expiresOnTimestamp,this.now(),this.holder)}return{token:token2.token,expiresOnTimestamp:token2.expiresOnTimestamp}}}throw new RunnerStepCredentialError(requested,[...this.byScope.keys()],this.holder)}};exports.StaticScopedCredential=StaticScopedCredential;exports.RUNNER_STEP_TOKEN_HOLDER={noun:"step",whereDeclared:"The channel mints exactly what a connector's azureAudiences declares, so this connector reaches an Azure resource it does not say it reaches.",whyNoMore:"A step container is handed minted bytes and nothing it can use to get another, so the step ran longer than its own credential and cannot continue."};exports.ENGINE_ACTION_TOKEN_HOLDER={noun:"action",whereDeclared:"The engine mints exactly the audiences an action's manifest declares in execution.audiences, so this action reaches an Azure resource it does not say it reaches.",whyNoMore:"An action is handed minted bytes and nothing it can use to get another, so it ran longer than its own credential and cannot continue."};exports.STEP_CREDENTIAL_FAILURE="runvericStepCredentialFailure";var RunnerStepCredentialError=class RunnerStepCredentialError extends Error{static{__name(this,"RunnerStepCredentialError")}constructor(requested,available,holder=exports.RUNNER_STEP_TOKEN_HOLDER){super(`This ${holder.noun} was authorized for ${available.length>0?available.map(quote).join(", "):"no scopes"} and asked for ${requested.map(quote).join(", ")}. ${holder.whereDeclared}`);this.name="RunnerStepCredentialError"}[exports.STEP_CREDENTIAL_FAILURE]=true};exports.RunnerStepCredentialError=RunnerStepCredentialError;var RunnerStepCredentialExpiredError=class RunnerStepCredentialExpiredError extends Error{static{__name(this,"RunnerStepCredentialExpiredError")}constructor(scope,expiresOnTimestamp,now,holder=exports.RUNNER_STEP_TOKEN_HOLDER){super(`This ${holder.noun}'s token for ${quote(scope)} expired ${Math.round((now-expiresOnTimestamp)/1e3)}s ago, at ${new Date(expiresOnTimestamp).toISOString()}. ${holder.whyNoMore}`);this.name="RunnerStepCredentialExpiredError"}[exports.STEP_CREDENTIAL_FAILURE]=true};exports.RunnerStepCredentialExpiredError=RunnerStepCredentialExpiredError;function quote(scope){return`"${scope}"`}__name(quote,"quote")}});var require_action_protocol=__commonJS({"../contracts/dist/action-protocol.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ActionProtocolError=exports.JWT_SHAPE=exports.REDACTED_SECRET=exports.ENGINE_RUN_ROUTES=exports.ACTION_PROBE_ENV=exports.ACTION_RUNTIME_PROBE_FLAG=exports.ACTION_CONTAINER_ENV=exports.MAX_PLAN_VALIDATE_TARGETS=exports.ACTION_PROTOCOL_LIMITS=exports.ACTION_EXECUTION_KINDS=exports.ENGINE_CONNECTOR_KEY=exports.ACTION_CONTRACTS=void 0;exports.isActionContract=isActionContract;exports.engineRunUrl=engineRunUrl;exports.actionAudienceRefusal=actionAudienceRefusal;exports.actionTokenScope=actionTokenScope;exports.redactSecrets=redactSecrets2;exports.redactJwtShaped=redactJwtShaped2;exports.carriesJwtShaped=carriesJwtShaped;exports.jsonByteLength=jsonByteLength;exports.parseActionInvocation=parseActionInvocation2;exports.parseActionEvent=parseActionEvent2;exports.tooManyEvents=tooManyEvents;exports.parseActionCheckpoint=parseActionCheckpoint2;exports.parseCheckpointAck=parseCheckpointAck;exports.parseActionReport=parseActionReport2;var wire_identity_1=require_wire_identity();var package_execution_1=require_package_execution();var validation_1=require_validation();exports.ACTION_CONTRACTS=[wire_identity_1.ACTION_PROTOCOL_V1];function isActionContract(value){return typeof value==="string"&&exports.ACTION_CONTRACTS.includes(value)}__name(isActionContract,"isActionContract");exports.ENGINE_CONNECTOR_KEY="runveric.engine";exports.ACTION_EXECUTION_KINDS=["engine"];exports.ACTION_PROTOCOL_LIMITS={maxEvents:500,maxEventBytes:2048,maxReportBytes:262144,maxRestorePointBytes:65536};exports.MAX_PLAN_VALIDATE_TARGETS=200;exports.ACTION_CONTAINER_ENV={runToken:"RUNVERIC_ACTION_RUN_TOKEN",callbackBaseUrl:"RUNVERIC_ACTION_CALLBACK_BASE_URL",runId:"RUNVERIC_ACTION_RUN_ID",imageDigest:"RUNVERIC_ACTION_IMAGE_DIGEST"};exports.ACTION_RUNTIME_PROBE_FLAG="--probe";exports.ACTION_PROBE_ENV={identities:"RUNVERIC_PROBE_IDENTITIES"};exports.ENGINE_RUN_ROUTES={base:"internal/engine-runs",invocation:"invocation",events:"events",checkpoint:"checkpoint",report:"report"};function engineRunUrl(callbackBaseUrl,runId,message){const origin2=callbackBaseUrl.replace(/\/+$/,"");return`${origin2}/${exports.ENGINE_RUN_ROUTES.base}/${encodeURIComponent(runId)}/${exports.ENGINE_RUN_ROUTES[message]}`}__name(engineRunUrl,"engineRunUrl");function actionAudienceRefusal(value){if(typeof value==="string"&&AUDIENCE_ORIGIN.test(value))return null;return`"${String(value)}" is not an audience. An audience is the https origin of the resource a token is for \u2014 lowercase, with no port, path or trailing slash, e.g. "https://management.azure.com".`}__name(actionAudienceRefusal,"actionAudienceRefusal");var AUDIENCE_ORIGIN=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;function actionTokenScope(audience){return`${audience}/.default`}__name(actionTokenScope,"actionTokenScope");exports.REDACTED_SECRET="[redacted]";function redactSecrets2(value,secrets){const present=secrets.filter(secret=>secret.length>0);if(present.length===0)return value;return mapStrings(value,text=>present.reduce((out,secret)=>out.split(secret).join(exports.REDACTED_SECRET),text))}__name(redactSecrets2,"redactSecrets");exports.JWT_SHAPE=/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/;function redactJwtShaped2(value){const everyMatch=new RegExp(exports.JWT_SHAPE.source,"g");return mapStrings(value,text=>text.replace(everyMatch,exports.REDACTED_SECRET))}__name(redactJwtShaped2,"redactJwtShaped");function carriesJwtShaped(value){let found=false;mapStrings(value,text=>{found||=exports.JWT_SHAPE.test(text);return text});return found}__name(carriesJwtShaped,"carriesJwtShaped");function mapStrings(value,scrub){const walk=__name(node=>{if(typeof node==="string")return scrub(node);if(Array.isArray(node))return node.map(walk);if(node!==null&&typeof node==="object"){return Object.fromEntries(Object.entries(node).map(([key,item])=>[scrub(key),walk(item)]))}return node},"walk");return walk(value)}__name(mapStrings,"mapStrings");function jsonByteLength(value){const text=JSON.stringify(value)??"";let bytes=0;for(const char of text){const point=char.codePointAt(0)??0;bytes+=point<128?1:point<2048?2:point<65536?3:4}return bytes}__name(jsonByteLength,"jsonByteLength");var ActionProtocolError=class ActionProtocolError extends Error{static{__name(this,"ActionProtocolError")}constructor(message){super(message);this.name="ActionProtocolError"}};exports.ActionProtocolError=ActionProtocolError;function parseActionInvocation2(body){const raw=objectOf2(body,"The invocation");onlyKeys(raw,INVOCATION_KEYS,"The invocation");if(!isActionContract(raw.protocol)){throw new ActionProtocolError(`The invocation speaks ${String(raw.protocol)}, and this runtime speaks ${exports.ACTION_CONTRACTS.join(", ")}.`)}const phase=raw.phase;if(typeof phase!=="string"||!package_execution_1.PACKAGE_PHASES.includes(phase)){throw new ActionProtocolError(`An invocation phase of "${String(phase)}" is not in the vocabulary.`)}const actionRaw=objectOf2(raw.action,"The invocation's action");onlyKeys(actionRaw,["key","version","image"],"The invocation's action");const action={key:nonEmpty(actionRaw.key,"The action's key"),version:nonEmpty(actionRaw.version,"The action's version"),image:digestPinned(actionRaw.image)};const executionRaw=objectOf2(raw.execution,"The invocation's execution");onlyKeys(executionRaw,["id","tenantId","correlationId","dryRun"],"The invocation's execution");if(typeof executionRaw.dryRun!=="boolean"){throw new ActionProtocolError("The invocation's execution must say whether it is a dry run.")}const execution={id:nonEmpty(executionRaw.id,"The execution's id"),tenantId:nonEmpty(executionRaw.tenantId,"The execution's tenant"),correlationId:nonEmpty(executionRaw.correlationId,"The execution's correlation id"),dryRun:executionRaw.dryRun};const limits=parseLimits(raw.limits);const decisions=parseDecisions(raw.decisions);const targets=parseTargets(raw.targets);const credentials={tokens:parseTokens(objectOf2(raw.credentials,"The invocation's credentials"))};const restorePoint=nullableObject(raw.restorePoint,"The invocation's restore point");const priorResult=nullableObject(raw.priorResult,"The invocation's prior result");if(restorePoint!==null&&jsonByteLength(restorePoint)>limits.maxRestorePointBytes){throw new ActionProtocolError(`The invocation's restore point is larger than ${limits.maxRestorePointBytes} bytes.`)}const base={protocol:raw.protocol,action,execution,targets,credentials,limits};if(phase==="validate"){if(raw.mode!=="plan"&&raw.mode!=="run"){throw new ActionProtocolError(`A validate invocation's mode of "${String(raw.mode)}" is not "plan" or "run".`)}if(raw.mode!==decisions.phase){throw new ActionProtocolError(`A validate invocation in ${raw.mode} mode carries ${decisions.phase}-phase decisions; the two are the same fact.`)}assertTargetCount(targets.length,raw.mode==="plan"?exports.MAX_PLAN_VALIDATE_TARGETS:1,`A ${raw.mode}-mode validate`);if(restorePoint!==null||priorResult!==null){throw new ActionProtocolError("A validate invocation carries no restore point and no prior result.")}return{...base,phase,mode:raw.mode,decisions,restorePoint:null,priorResult:null}}if(raw.mode!==void 0){throw new ActionProtocolError(`A ${phase} invocation has no mode \u2014 only a validate is asked in a mode.`)}if(decisions.phase!=="run"){throw new ActionProtocolError(`A ${phase} invocation carries a run's decisions, never a plan's.`)}assertTargetCount(targets.length,1,`A ${phase}`);if(phase==="run"){if(priorResult!==null){throw new ActionProtocolError("A run invocation carries no prior result \u2014 only a rollback reads one.")}return{...base,phase,decisions,restorePoint,priorResult:null}}return{...base,phase:"rollback",decisions,restorePoint,priorResult}}__name(parseActionInvocation2,"parseActionInvocation");function parseActionEvent2(body,limits,alreadyReceived){if(alreadyReceived>=limits.maxEvents)throw tooManyEvents(limits);const raw=objectOf2(body,"An event");onlyKeys(raw,["level","message","data"],"An event");if(jsonByteLength(raw)>limits.maxEventBytes){throw new ActionProtocolError(`An event is larger than ${limits.maxEventBytes} bytes.`)}if(typeof raw.level!=="string"||!Object.hasOwn(EVENT_LEVELS,raw.level)){throw new ActionProtocolError(`An event level of "${String(raw.level)}" is not in the vocabulary.`)}const message=nonEmpty(raw.message,"An event's message");if(raw.data===void 0)return{level:raw.level,message};return{level:raw.level,message,data:jsonObject(raw.data,"An event's data")}}__name(parseActionEvent2,"parseActionEvent");function tooManyEvents(limits){return new ActionProtocolError(`The action sent more than ${limits.maxEvents} events.`)}__name(tooManyEvents,"tooManyEvents");function parseActionCheckpoint2(body,limits){const raw=objectOf2(body,"A checkpoint");onlyKeys(raw,["kind","record"],"A checkpoint");if(raw.kind!=="restore_point"){throw new ActionProtocolError(`A checkpoint of kind "${String(raw.kind)}" is not one this contract knows.`)}const record=jsonObject(raw.record,"A checkpoint's record");if(jsonByteLength(record)>limits.maxRestorePointBytes){throw new ActionProtocolError(`A restore point is larger than ${limits.maxRestorePointBytes} bytes.`)}return{kind:"restore_point",record}}__name(parseActionCheckpoint2,"parseActionCheckpoint");function parseCheckpointAck(body){const raw=objectOf2(body,"A checkpoint acknowledgement");onlyKeys(raw,["acknowledged"],"A checkpoint acknowledgement");if(raw.acknowledged!==true){throw new ActionProtocolError("The checkpoint was not acknowledged.")}return{acknowledged:true}}__name(parseCheckpointAck,"parseCheckpointAck");function parseActionReport2(body,sent){const raw=objectOf2(body,"The report");onlyKeys(raw,["phase","checks","outcome"],"The report");if(jsonByteLength(raw)>sent.limits.maxReportBytes){throw new ActionProtocolError(`The report is larger than ${sent.limits.maxReportBytes} bytes.`)}if(raw.phase!==sent.phase){throw new ActionProtocolError(`The report is for phase "${String(raw.phase)}", but this invocation is for "${sent.phase}".`)}if(sent.phase==="validate"){if(raw.checks===void 0===(raw.outcome===void 0)){throw new ActionProtocolError("A validate report carries checks, or \u2014 when they could not run \u2014 a failed outcome; exactly one of the two.")}if(raw.outcome!==void 0){const outcome=parseOutcome(raw.outcome);if(outcome.status!=="failed"){throw new ActionProtocolError(`A validate report's outcome can only say the checks failed to run, never "${outcome.status}" \u2014 the engine decides what checks mean.`)}return{phase:"validate",outcome}}const byRef=objectOf2(raw.checks,"A validate report's checks");const expected=new Set(sent.targets.map(target=>target.ref));for(const ref of Object.keys(byRef)){if(!expected.has(ref)){throw new ActionProtocolError(`The report answers for "${ref}", which is not one of the targets it was given.`)}}const checks=sent.targets.map(({ref})=>{if(!Object.hasOwn(byRef,ref)){throw new ActionProtocolError(`The report says nothing about "${ref}", one of the targets it was given.`)}const list=byRef[ref];if(!Array.isArray(list)){throw new ActionProtocolError(`The checks for "${ref}" must be an array.`)}return{ref,checks:list.map(entry=>{const parsed=(0,validation_1.validationCheckOf)(entry);if("refusal"in parsed)throw new ActionProtocolError(`The checks for "${ref}": ${parsed.refusal}`);return parsed.check})}});return{phase:"validate",checks}}if(raw.checks!==void 0){throw new ActionProtocolError(`A ${sent.phase} report carries an outcome, never checks \u2014 those are the validate phase's answer.`)}return{phase:sent.phase,outcome:parseOutcome(raw.outcome)}}__name(parseActionReport2,"parseActionReport");var INVOCATION_KEYS=["protocol","action","phase","mode","execution","targets","decisions","restorePoint","priorResult","credentials","limits"];var EVENT_LEVELS={info:true,warn:true,error:true,success:true};var OUTCOME_STATUSES={succeeded:true,failed:true,cancelled:true};function parseOutcome(value){if(value===void 0){throw new ActionProtocolError("A run or rollback report must carry an outcome.")}const raw=objectOf2(value,"An outcome");onlyKeys(raw,["status","message","data"],"An outcome");if(typeof raw.status!=="string"||!Object.hasOwn(OUTCOME_STATUSES,raw.status)){throw new ActionProtocolError(`An outcome status of "${String(raw.status)}" is not in the vocabulary.`)}const status=raw.status;const message=nonEmpty(raw.message,"An outcome's message");if(raw.data===void 0)return{status,message};return{status,message,data:jsonObject(raw.data,"An outcome's data")}}__name(parseOutcome,"parseOutcome");function parseLimits(value){const raw=objectOf2(value,"The invocation's limits");onlyKeys(raw,["deadline","maxEvents","maxEventBytes","maxReportBytes","maxRestorePointBytes"],"The invocation's limits");return{deadline:isoInstant(raw.deadline,"The deadline"),maxEvents:positiveInteger(raw.maxEvents,"maxEvents"),maxEventBytes:positiveInteger(raw.maxEventBytes,"maxEventBytes"),maxReportBytes:positiveInteger(raw.maxReportBytes,"maxReportBytes"),maxRestorePointBytes:positiveInteger(raw.maxRestorePointBytes,"maxRestorePointBytes")}}__name(parseLimits,"parseLimits");function parseDecisions(value){const raw=objectOf2(value,"The invocation's decisions");if(raw.phase==="plan"){onlyKeys(raw,["phase"],"A plan's decisions");return{phase:"plan"}}if(raw.phase!=="run"){throw new ActionProtocolError(`A decisions phase of "${String(raw.phase)}" is not "plan" or "run".`)}onlyKeys(raw,["phase","recorded"],"A run's decisions");if(!Array.isArray(raw.recorded)){throw new ActionProtocolError("A run's decisions must carry the recorded list, even when it is empty.")}const recorded=raw.recorded.map(entry=>{const decision=objectOf2(entry,"A recorded decision");onlyKeys(decision,["code","acknowledgedBy","acknowledgedAt"],"A recorded decision");if(!(0,validation_1.isCheckCode)(decision.code)){throw new ActionProtocolError((0,validation_1.checkCodeRefusal)(decision.code,"A recorded decision of"))}return{code:decision.code,acknowledgedBy:nonEmpty(decision.acknowledgedBy,"Who acknowledged a decision"),acknowledgedAt:isoInstant(decision.acknowledgedAt,"When a decision was acknowledged")}});if(new Set(recorded.map(decision=>decision.code)).size!==recorded.length){throw new ActionProtocolError("A run's decisions record one code twice.")}return{phase:"run",recorded}}__name(parseDecisions,"parseDecisions");function parseTargets(value){if(!Array.isArray(value)){throw new ActionProtocolError("The invocation's targets must be an array.")}const targets=value.map(entry=>{const raw=objectOf2(entry,"A target");onlyKeys(raw,["ref","parameters"],"A target");return{ref:nonEmpty(raw.ref,"A target's ref"),parameters:jsonObject(raw.parameters,"A target's parameters")}});if(new Set(targets.map(target=>target.ref)).size!==targets.length){throw new ActionProtocolError("The invocation names one target twice.")}return targets}__name(parseTargets,"parseTargets");function assertTargetCount(count,max,what){if(count<1||count>max){throw new ActionProtocolError(max===1?`${what} acts on exactly one target; this invocation names ${count}.`:`${what} checks between 1 and ${max} targets; this invocation names ${count}.`)}}__name(assertTargetCount,"assertTargetCount");function parseTokens(credentials){onlyKeys(credentials,["tokens"],"The invocation's credentials");if(!Array.isArray(credentials.tokens)){throw new ActionProtocolError("The invocation's credentials must carry a tokens array, even when it is empty.")}const tokens2=credentials.tokens.map(entry=>{const raw=objectOf2(entry,"A token");onlyKeys(raw,["audience","token","expiresOn"],"A token");const refusal=actionAudienceRefusal(raw.audience);if(refusal!==null)throw new ActionProtocolError(refusal);return{audience:raw.audience,token:nonEmpty(raw.token,"A token's value"),expiresOn:isoInstant(raw.expiresOn,"A token's expiry")}});if(new Set(tokens2.map(token2=>token2.audience)).size!==tokens2.length){throw new ActionProtocolError("The invocation carries two tokens for one audience.")}return tokens2}__name(parseTokens,"parseTokens");var DIGEST_PINNED_IMAGE=/^[a-z0-9][a-z0-9._\-/:]*@sha256:[0-9a-f]{64}$/;function digestPinned(value){if(typeof value!=="string"||!DIGEST_PINNED_IMAGE.test(value)){throw new ActionProtocolError(`The action's image "${String(value)}" is not addressed by digest. Nothing on the execution path resolves a tag (docs/128 \xA713.2).`)}return value}__name(digestPinned,"digestPinned");function objectOf2(value,what){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new ActionProtocolError(`${what} must be an object.`)}return value}__name(objectOf2,"objectOf");function onlyKeys(raw,allowed,what){for(const key of Object.keys(raw)){if(!allowed.includes(key)){throw new ActionProtocolError(`${what} carries "${key}", which this contract does not have.`)}}}__name(onlyKeys,"onlyKeys");function nonEmpty(value,what){if(typeof value!=="string"||value.length===0){throw new ActionProtocolError(`${what} must be a non-empty string.`)}return value}__name(nonEmpty,"nonEmpty");function positiveInteger(value,what){if(typeof value!=="number"||!Number.isInteger(value)||value<1){throw new ActionProtocolError(`The limit "${what}" must be a positive integer.`)}return value}__name(positiveInteger,"positiveInteger");function isoInstant(value,what){if(typeof value!=="string"||Number.isNaN(Date.parse(value))){throw new ActionProtocolError(`${what} must be an ISO-8601 instant.`)}return value}__name(isoInstant,"isoInstant");function nullableObject(value,what){return value===null?null:jsonObject(value,what)}__name(nullableObject,"nullableObject");function jsonObject(value,what){if(!isJsonObject(value)){throw new ActionProtocolError(`${what} must be a JSON object.`)}return value}__name(jsonObject,"jsonObject");function isJsonObject(value){if(typeof value!=="object"||value===null||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)return false;return Object.values(value).every(isJsonValue)}__name(isJsonObject,"isJsonObject");function isJsonValue(value){if(value===null||typeof value==="string"||typeof value==="boolean")return true;if(typeof value==="number")return Number.isFinite(value);if(Array.isArray(value))return value.every(isJsonValue);return isJsonObject(value)}__name(isJsonValue,"isJsonValue")}});var require_action_signing=__commonJS({"../contracts/dist/action-signing.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ACTION_SIGNATURE_REPOSITORY=exports.IMAGE_REVISION_LABEL=exports.IMAGE_SOURCE_LABEL=exports.COSIGN_SIGN_PREDICATE_TYPE=exports.IN_TOTO_STATEMENT_TYPE=exports.DSSE_IN_TOTO_PAYLOAD_TYPE=exports.SIGSTORE_BUNDLE_MEDIA_TYPE=void 0;exports.SIGSTORE_BUNDLE_MEDIA_TYPE="application/vnd.dev.sigstore.bundle.v0.3+json";exports.DSSE_IN_TOTO_PAYLOAD_TYPE="application/vnd.in-toto+json";exports.IN_TOTO_STATEMENT_TYPE="https://in-toto.io/Statement/v1";exports.COSIGN_SIGN_PREDICATE_TYPE="https://sigstore.dev/cosign/sign/v1";exports.IMAGE_SOURCE_LABEL="org.opencontainers.image.source";exports.IMAGE_REVISION_LABEL="org.opencontainers.image.revision";exports.ACTION_SIGNATURE_REPOSITORY="ghcr.io/runveric/action-signatures"}});var require_oci_media_types=__commonJS({"../contracts/dist/oci-media-types.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IMAGE_MANIFEST_MEDIA_TYPES=exports.MANIFEST_MEDIA_TYPES=exports.DOCKER_MANIFEST_LIST=exports.OCI_IMAGE_INDEX=exports.DOCKER_IMAGE_MANIFEST=exports.OCI_IMAGE_MANIFEST=void 0;exports.OCI_IMAGE_MANIFEST="application/vnd.oci.image.manifest.v1+json";exports.DOCKER_IMAGE_MANIFEST="application/vnd.docker.distribution.manifest.v2+json";exports.OCI_IMAGE_INDEX="application/vnd.oci.image.index.v1+json";exports.DOCKER_MANIFEST_LIST="application/vnd.docker.distribution.manifest.list.v2+json";exports.MANIFEST_MEDIA_TYPES=[exports.OCI_IMAGE_MANIFEST,exports.DOCKER_IMAGE_MANIFEST,exports.OCI_IMAGE_INDEX,exports.DOCKER_MANIFEST_LIST];exports.IMAGE_MANIFEST_MEDIA_TYPES=[exports.OCI_IMAGE_MANIFEST,exports.DOCKER_IMAGE_MANIFEST]}});var require_action_image=__commonJS({"../contracts/dist/action-image.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_IMAGE_MANIFEST_BYTES=exports.ACTION_RUNTIME_IMAGE=exports.ACTION_RUNTIME_REPOSITORY=void 0;exports.imageConfigDescriptor=imageConfigDescriptor2;exports.actionImageRefusal=actionImageRefusal2;var action_repository_1=require_action_repository();var action_signing_1=require_action_signing();var oci_media_types_1=require_oci_media_types();exports.ACTION_RUNTIME_REPOSITORY="ghcr.io/runveric/action-runtime";exports.ACTION_RUNTIME_IMAGE=`${exports.ACTION_RUNTIME_REPOSITORY}@sha256:da13930f35c260106b2051325e148671991aff810300f7303e474d9acec71cc1`;exports.MAX_IMAGE_MANIFEST_BYTES=64*1024;var isRecord=__name(value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"isRecord");function imageConfigDescriptor2(manifest){if(!isRecord(manifest)||typeof manifest.mediaType!=="string")return null;if(!oci_media_types_1.IMAGE_MANIFEST_MEDIA_TYPES.includes(manifest.mediaType)||manifest.schemaVersion!==2)return null;const config=manifest.config;if(!isRecord(config)||typeof config.digest!=="string")return null;if(typeof config.size!=="number"||!Number.isInteger(config.size)||config.size<0)return null;return{digest:config.digest,size:config.size}}__name(imageConfigDescriptor2,"imageConfigDescriptor");function actionImageRefusal2(input){const{key,image,manifest,config,provenance:provenance2}=input;const mediaType=isRecord(manifest)?manifest.mediaType:void 0;if(typeof mediaType!=="string"||!oci_media_types_1.IMAGE_MANIFEST_MEDIA_TYPES.includes(mediaType)){return`${image} is ${typeof mediaType==="string"?`a ${mediaType}`:"a manifest of no declared type"}, not one image. An engine action's digest names exactly one linux/amd64 image manifest \u2014 never an index of several.`}if(imageConfigDescriptor2(manifest)===null){return`${image} is not an image manifest \u2014 it names no config descriptor (schemaVersion 2, a digest and a size).`}if(!isRecord(config)){return`${image}'s config is not a JSON object, so it cannot say what it was built for.`}const platform=`${String(config.os)}/${String(config.architecture)}`;if(platform!=="linux/amd64"){return`${image} is built for ${platform}; an engine action runs on linux/amd64, which is what Container Apps Jobs run.`}const labels=isRecord(config.config)&&isRecord(config.config.Labels)?config.config.Labels:{};const expected=(0,action_repository_1.actionSourceRepository)(key);const source=labels[action_signing_1.IMAGE_SOURCE_LABEL];if(source!==expected){return`the image of action "${key}" says it was built in ${source===void 0?"no repository (it carries no "+action_signing_1.IMAGE_SOURCE_LABEL+" label)":JSON.stringify(source)}, not ${expected}. A signature binds a digest and never a name, so an image built for another action cannot run under this one's manifest.`}if(provenance2.repository!==expected){return`the artifact of action "${key}" says it was authored in ${JSON.stringify(provenance2.repository)}, not ${expected}, which its image names.`}const revision=labels[action_signing_1.IMAGE_REVISION_LABEL];if(revision!==provenance2.commit){return`the image of action "${key}" says it was built at ${revision===void 0?"no commit (it carries no "+action_signing_1.IMAGE_REVISION_LABEL+" label)":JSON.stringify(revision)}, not ${provenance2.commit}, the commit its artifact was published from. An image and the manifest it runs under come from one commit, so neither can be swapped for another's.`}return null}__name(actionImageRefusal2,"actionImageRefusal")}});var require_catalog_templates=__commonJS({"../contracts/dist/catalog-templates.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.renderTemplate=renderTemplate2;exports.workflowValues=workflowValues2;var action_image_1=require_action_image();var action_signing_1=require_action_signing();var TEMPLATE_PLACEHOLDER=/\{\{([A-Z_]+)\}\}/g;function renderTemplate2(name3,text,values){return text.replace(TEMPLATE_PLACEHOLDER,(whole,key)=>{if(!Object.prototype.hasOwnProperty.call(values,key)){throw new Error(`${name3} uses ${whole}, which this script does not fill.`)}return values[key]})}__name(renderTemplate2,"renderTemplate");function workflowValues2(cli){return{CLI_PACKAGE:cli.name,CLI_VERSION:cli.version,ACTION_RUNTIME_IMAGE:action_image_1.ACTION_RUNTIME_IMAGE,ACTION_SIGNATURE_REPOSITORY:action_signing_1.ACTION_SIGNATURE_REPOSITORY}}__name(workflowValues2,"workflowValues")}});var require_runner_pool_presence=__commonJS({"../contracts/dist/runner-pool-presence.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUNNER_WAIT_MOMENTS=exports.LIFECYCLE_EXPLAINS=exports.RUNNER_KEPT_SENTENCE=exports.LIFECYCLE_ENDING=exports.RUNNER_ABANDONED_AFTER_MS=exports.VERSION_STANDING_CAN_RECOVER=exports.LIFECYCLE_CAN_RECOVER=exports.PRESENCE_CAN_RECOVER=void 0;exports.runnerRemovability=runnerRemovability;exports.countsAsBusy=countsAsBusy;exports.summarisePool=summarisePool;exports.poolNotice=poolNotice;exports.poolCanRecover=poolCanRecover;exports.formatWaitDuration=formatWaitDuration;exports.runnerWaitSentence=runnerWaitSentence;exports.runnerWaitRecordOf=runnerWaitRecordOf;exports.waitRecordReader=waitRecordReader;exports.isRunnerWaitRecord=isRunnerWaitRecord;exports.runnerClaimedSentence=runnerClaimedSentence;exports.poolWaitWarningSentence=poolWaitWarningSentence;var runners_1=require_runners();var brand_1=require_brand();exports.PRESENCE_CAN_RECOVER={online:true,quiet:true,offline:false};exports.LIFECYCLE_CAN_RECOVER={active:true,draining:false,revoked:false};exports.VERSION_STANDING_CAN_RECOVER={current:true,behind:true,unsupported:false};exports.RUNNER_ABANDONED_AFTER_MS=30*24*60*60*1e3;exports.LIFECYCLE_ENDING={active:{kind:"abandonment",afterMs:exports.RUNNER_ABANDONED_AFTER_MS},draining:{kind:"abandonment",afterMs:exports.RUNNER_ABANDONED_AFTER_MS},revoked:{kind:"ended"}};function runnerRemovability(runner,now){if(exports.PRESENCE_CAN_RECOVER[(0,runners_1.runnerPresence)(runner,now)]){return{removable:false,kept:"connected"}}if(runner.busy)return{removable:false,kept:"holding-a-step"};const ending=exports.LIFECYCLE_ENDING[runner.lifecycle];if(ending.kind==="ended")return{removable:true,because:"ended"};const silentForMs=now-new Date(runner.lastSeenAt).getTime();if(silentForMs<ending.afterMs)return{removable:false,kept:"within-retention"};return{removable:true,because:"abandoned"}}__name(runnerRemovability,"runnerRemovability");exports.RUNNER_KEPT_SENTENCE={connected:__name(name3=>`\u201C${name3}\u201D still has a working credential, so it can still be told to stand down or brought back. Revoke it first \u2014 that is what ends a runner you want gone now.`,"connected"),"holding-a-step":__name(name3=>`\u201C${name3}\u201D is still holding a step. Removing it now would leave the run that is waiting on it unable to say who claimed the work. It clears by itself when the step expires.`,"holding-a-step"),"within-retention":__name(name3=>`\u201C${name3}\u201D has not been heard from for less than ${Math.round(exports.RUNNER_ABANDONED_AFTER_MS/(24*60*60*1e3))} days. Revoke it if you want it gone now, or leave it \u2014 a host that comes back keeps its place until then.`,"within-retention")};function countsAsBusy(runner,now){return(0,runners_1.runnerPresence)(runner,now)==="online"&&runner.busy}__name(countsAsBusy,"countsAsBusy");function summarisePool(runners,now,policy){const summary={online:0,quiet:0,offline:0,total:runners.length,busy:0,behind:0,unsupported:0,draining:0,revoked:0,available:0,recoverable:0,removable:0};for(const runner of runners){const presence=(0,runners_1.runnerPresence)(runner,now);summary[presence]+=1;if(countsAsBusy(runner,now))summary.busy+=1;if(runner.lifecycle==="draining")summary.draining+=1;if(runner.lifecycle==="revoked")summary.revoked+=1;const standing=policy===null?"current":(0,runners_1.runnerVersionStanding)(runner.version,policy);if(standing==="behind")summary.behind+=1;if(standing==="unsupported")summary.unsupported+=1;if(presence==="online"&&runner.lifecycle==="active"&&standing!=="unsupported"){summary.available+=1}if(exports.PRESENCE_CAN_RECOVER[presence]&&exports.LIFECYCLE_CAN_RECOVER[runner.lifecycle]&&exports.VERSION_STANDING_CAN_RECOVER[standing]){summary.recoverable+=1}if(runnerRemovability(runner,now).removable)summary.removable+=1}return summary}__name(summarisePool,"summarisePool");exports.LIFECYCLE_EXPLAINS={active:[],draining:[],revoked:["connection"]};function connectionFinding(c){if(c.offline===c.total){return{axis:"connection",tone:"danger",finding:"Every runner in this pool is offline: their credentials have expired, so none can come back on its own.",continuation:"They are also offline, so none can come back on its own.",remedy:"Runs bound to this pool will wait until one is installed again."}}if(c.quiet===c.total){return{axis:"connection",tone:"warning",finding:"No runner in this pool has polled recently, so runs bound to it will wait.",continuation:"None of them has polled recently either.",remedy:"If they are restarting this clears on its own; if not, check they can still reach this control plane on 443 outbound."}}return null}__name(connectionFinding,"connectionFinding");function lifecycleFinding(l){if(l.revoked===l.total){return{axis:"lifecycle",tone:"danger",finding:"Every runner in this pool has been revoked, so none can claim work and none can come back.",continuation:"Every one of them has also been revoked, so none can come back.",remedy:"Revoking is one-way: issue a new registration token and install a runner again on each host that should run work here.",explains:exports.LIFECYCLE_EXPLAINS.revoked}}if(l.draining===l.total){return{axis:"lifecycle",tone:"warning",finding:"Every runner in this pool is draining, so runs bound to it will wait.",continuation:"Every one of them is also draining.",remedy:"That is a state somebody chose here \u2014 resume a runner below to put it back to work, or install a replacement before removing the last one.",explains:exports.LIFECYCLE_EXPLAINS.draining}}return null}__name(lifecycleFinding,"lifecycleFinding");function versionFinding(v){if(v.unsupported!==v.total)return null;return{axis:"version",tone:"danger",finding:`Every runner in this pool is running a build this ${brand_1.BRAND_SHORT_NAME} will not hand work to, so runs bound to it will wait indefinitely.`,continuation:`They are also on a build this ${brand_1.BRAND_SHORT_NAME} will not hand work to, so they will still be refused when they reconnect.`,remedy:"Pull the current runner images and start each host again with a new registration token."}}__name(versionFinding,"versionFinding");function crossAxisClause(findings,connection){const onlyVersion=findings.length===1&&findings[0].axis==="version";if(!onlyVersion)return null;return connection.online===connection.total?"They are still connected \u2014 this is a version problem, not a network one.":null}__name(crossAxisClause,"crossAxisClause");function poolNotice(summary,reader){if(summary.total===0)return null;if(summary.available>0){const busyElsewhere=summary.busy-(reader?.busyWithThisRun??0);if(busyElsewhere<summary.available)return null;return{tone:"neutral",message:"Every runner here that can take work is busy. New runs wait for one to finish \u2014 install another runner in the same pool to widen it."}}const found=[connectionFinding(summary),lifecycleFinding(summary),versionFinding(summary)].filter(finding=>finding!==null);const explained=new Set(found.flatMap(finding=>finding.explains??[]));const findings=found.filter(finding=>!explained.has(finding.axis));if(findings.length===0){return{tone:poolCanRecover(summary)?"warning":"danger",message:"No runner in this pool can take work right now \u2014 they are variously not connected, draining, revoked, or on too old a build. Runs bound to this pool will wait until one is available. Each runner's own row says which it is."}}const cross=crossAxisClause(findings,summary);const[first2,...rest]=findings;const message=[first2.finding,...rest.map(finding=>finding.continuation),cross,...findings.map(finding=>finding.remedy)].filter(part=>Boolean(part)).join(" ");return{tone:findings.some(finding=>finding.tone==="danger")?"danger":"warning",message}}__name(poolNotice,"poolNotice");function poolCanRecover(summary){if(summary.total===0)return true;return summary.recoverable>0}__name(poolCanRecover,"poolCanRecover");function formatWaitDuration(ms){const seconds=Math.max(0,Math.round(ms/1e3));if(seconds<60)return`${seconds}s`;const minutes=Math.floor(seconds/60);const rest=seconds%60;return rest===0?`${minutes}m`:`${minutes}m ${String(rest).padStart(2,"0")}s`}__name(formatWaitDuration,"formatWaitDuration");exports.RUNNER_WAIT_MOMENTS=["handoff","waiting","changed"];function runnerWaitSentence(wait,moment){switch(moment){case"handoff":return handoffSentence(wait);case"waiting":return stillWaitingSentence(wait,false);case"changed":return stillWaitingSentence(wait,true)}}__name(runnerWaitSentence,"runnerWaitSentence");function handoffSentence(wait){const deadline=`It waits up to ${formatWaitDuration(wait.remainingMs)} for one to claim it.`;const notice=poolNotice(wait.presence,{busyWithThisRun:wait.busyWithThisRun});if(wait.presence.available>0&&!notice){const n=wait.presence.available;return`Handed to runner pool \u201C${wait.poolName}\u201D \u2014 ${n} runner${n===1?"":"s"} able to take it. ${deadline}`}return`Handed to runner pool \u201C${wait.poolName}\u201D, and nothing there can take work right now. `+`${notice?.message??""} ${deadline}`.replace(/\s+/gu," ").trim()}__name(handoffSentence,"handoffSentence");function stillWaitingSentence(wait,conditionChanged){const head=`Still waiting for a runner in pool \u201C${wait.poolName}\u201D \u2014 ${formatWaitDuration(wait.waitedMs)} so far, ${formatWaitDuration(wait.remainingMs)} before this run gives up.`;if(!conditionChanged)return head;const notice=poolNotice(wait.presence,{busyWithThisRun:wait.busyWithThisRun});return notice?`${head} ${notice.message}`:`${head} Something here can take work now.`}__name(stillWaitingSentence,"stillWaitingSentence");function runnerWaitRecordOf(value){if(!isRunnerWaitRecord(value))return null;return{poolId:value.poolId,poolName:value.poolName,presence:value.presence,observedAt:value.observedAt,busyWithThisRun:typeof value.busyWithThisRun==="number"?value.busyWithThisRun:null}}__name(runnerWaitRecordOf,"runnerWaitRecordOf");function waitRecordReader(record){return typeof record.busyWithThisRun==="number"?{busyWithThisRun:record.busyWithThisRun}:null}__name(waitRecordReader,"waitRecordReader");function isRunnerWaitRecord(value){if(typeof value!=="object"||value===null)return false;const record=value;if(typeof record.poolId!=="string"||typeof record.poolName!=="string")return false;if(typeof record.observedAt!=="string")return false;if(record.busyWithThisRun!==void 0&&record.busyWithThisRun!==null&&typeof record.busyWithThisRun!=="number"){return false}const presence=record.presence;if(typeof presence!=="object"||presence===null)return false;return typeof presence.online==="number"&&typeof presence.quiet==="number"&&typeof presence.offline==="number"&&typeof presence.total==="number"&&typeof presence.busy==="number"&&typeof presence.behind==="number"&&typeof presence.unsupported==="number"&&typeof presence.draining==="number"&&typeof presence.revoked==="number"&&typeof presence.available==="number"&&typeof presence.recoverable==="number"}__name(isRunnerWaitRecord,"isRunnerWaitRecord");function runnerClaimedSentence(runnerName,waitedMs){return`Claimed by runner \u201C${runnerName}\u201D after ${formatWaitDuration(waitedMs)}.`}__name(runnerClaimedSentence,"runnerClaimedSentence");function poolWaitWarningSentence(warning){const notice=poolNotice(warning.presence,null);const consequence=`This run will be accepted and will wait up to ${formatWaitDuration(warning.waitsUpToMs)} for a runner to take it.`;return notice?`${notice.message} ${consequence}`:consequence}__name(poolWaitWarningSentence,"poolWaitWarningSentence")}});var require_routable_target=__commonJS({"../contracts/dist/routable-target.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})}});var require_runner_pool_routing=__commonJS({"../contracts/dist/runner-pool-routing.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RUNNER_POOL_RULES_PER_SCOPE_MAX=void 0;exports.routeRunnerPool=routeRunnerPool;exports.matchesRunnerPoolRule=matchesRunnerPoolRule;exports.runnerPoolRulesOverlap=runnerPoolRulesOverlap;exports.runnerPoolMatchIsEmpty=runnerPoolMatchIsEmpty;exports.describeRunnerPoolMatch=describeRunnerPoolMatch;exports.poolRoutingSentence=poolRoutingSentence;var run_placement_1=require_run_placement();exports.RUNNER_POOL_RULES_PER_SCOPE_MAX=100;function routeRunnerPool(bindings,targets){const byPool=new Map;for(const target of targets){const rule=bindings.rules.find(candidate=>matchesRunnerPoolRule(target,candidate.match));const pool=rule?rule.pool:bindings.default;const via=rule?{source:"rule",rule:{id:rule.id,name:rule.name,match:rule.match}}:{source:"default"};const key=pool?`pool:${pool.id}`:"hosted";const seen=byPool.get(key);if(seen){seen.match.targetCount+=1;continue}byPool.set(key,{match:{pool:pool??HOSTED_ROUTING_DESTINATION,via,exampleResourceId:target.resourceId,targetCount:1},pool})}if(byPool.size>1){return{kind:"ambiguous",matches:[...byPool.values()].map(entry=>entry.match)}}const only=[...byPool.values()][0];if(!only){return bindings.default?{kind:"pool",pool:bindings.default,via:{source:"default"}}:{kind:"hosted"}}if(!only.pool)return{kind:"hosted"};return{kind:"pool",pool:only.pool,via:only.match.via}}__name(routeRunnerPool,"routeRunnerPool");var HOSTED_ROUTING_DESTINATION={id:"",name:run_placement_1.HOSTED_EXECUTION_LABEL};function matchesRunnerPoolRule(target,match){const groups=lowerSet(match.resourceGroups);if(groups&&!groups.has((target.resourceGroup??"").trim().toLowerCase()))return false;const excluded=lowerSet(match.excludeResourceIds);if(excluded?.has(target.resourceId.trim().toLowerCase()))return false;const prefix=match.namePrefix?.trim().toLowerCase();if(prefix&&!target.name.trim().toLowerCase().startsWith(prefix))return false;for(const[key,value]of Object.entries(match.tags??{})){if(findTagValue(target.tags,key)!==value)return false}return true}__name(matchesRunnerPoolRule,"matchesRunnerPoolRule");function runnerPoolRulesOverlap(a,b){const groupsA=lowerSet(a.resourceGroups);const groupsB=lowerSet(b.resourceGroups);if(groupsA&&groupsB&&![...groupsA].some(group=>groupsB.has(group)))return false;const tagsA=lowerKeyed(a.tags);const tagsB=lowerKeyed(b.tags);for(const[key,value]of tagsA){if(tagsB.has(key)&&tagsB.get(key)!==value)return false}const prefixA=a.namePrefix?.trim().toLowerCase()??"";const prefixB=b.namePrefix?.trim().toLowerCase()??"";if(!prefixA.startsWith(prefixB)&&!prefixB.startsWith(prefixA))return false;return true}__name(runnerPoolRulesOverlap,"runnerPoolRulesOverlap");function runnerPoolMatchIsEmpty(match){return(match.resourceGroups?.filter(group=>group.trim()).length??0)===0&&Object.keys(match.tags??{}).length===0&&!match.namePrefix?.trim()}__name(runnerPoolMatchIsEmpty,"runnerPoolMatchIsEmpty");function describeRunnerPoolMatch(match){const parts=[];const groups=match.resourceGroups?.filter(group=>group.trim());if(groups?.length)parts.push(`resource groups: ${groups.join(", ")}`);const tags=Object.entries(match.tags??{});if(tags.length){parts.push(`tags (all of): ${tags.map(([key,value])=>`${key}=${value}`).join(", ")}`)}if(match.namePrefix?.trim())parts.push(`name prefix: "${match.namePrefix.trim()}"`);const excluded=match.excludeResourceIds?.filter(id=>id.trim());if(excluded?.length){parts.push(`${excluded.length} excluded resource ${excluded.length===1?"id":"ids"}`)}return parts.length>0?parts.join("; "):"every resource in this connection"}__name(describeRunnerPoolMatch,"describeRunnerPoolMatch");function poolRoutingSentence(via){return via.source==="default"?"this connection's default pool":`the rule \u201C${via.rule.name}\u201D (${describeRunnerPoolMatch(via.rule.match)})`}__name(poolRoutingSentence,"poolRoutingSentence");function lowerSet(values){if(!values||values.length===0)return null;const set=new Set;for(const value of values){const key=value.trim().toLowerCase();if(key)set.add(key)}return set.size>0?set:null}__name(lowerSet,"lowerSet");function lowerKeyed(tags){const map=new Map;for(const[key,value]of Object.entries(tags??{})){const normalized=key.trim().toLowerCase();if(normalized)map.set(normalized,value)}return map}__name(lowerKeyed,"lowerKeyed");function findTagValue(tags,key){if(!tags)return void 0;const wanted=key.trim().toLowerCase();for(const[tagKey,value]of Object.entries(tags)){if(tagKey.trim().toLowerCase()===wanted)return value}return void 0}__name(findTagValue,"findTagValue")}});var require_target_identity=__commonJS({"../contracts/dist/target-identity.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TARGET_LIST_SHOWN=exports.TARGET_NAMES_IN_A_SENTENCE=exports.TARGETS_HAVE_NO_NAME=exports.TARGETS_NOT_NAMED=void 0;exports.namedTargets=namedTargets;exports.targetsUnnamed=targetsUnnamed;exports.targetLabel=targetLabel;exports.unnamedTargetsSentence=unnamedTargetsSentence;exports.unnamedTargetsLabel=unnamedTargetsLabel;exports.resolvedTargetsOf=resolvedTargetsOf;exports.compareTargetIdentities=compareTargetIdentities;exports.targetIdentitiesAgree=targetIdentitiesAgree;exports.targetIdentityDriftSentence=targetIdentityDriftSentence;var brand_1=require_brand();function namedTargets(targets){return{targets}}__name(namedTargets,"namedTargets");function targetsUnnamed(reason,detail){return detail?{unnamed:reason,detail}:{unnamed:reason}}__name(targetsUnnamed,"targetsUnnamed");exports.TARGETS_NOT_NAMED={unnamed:"not_attempted"};exports.TARGETS_HAVE_NO_NAME={unnamed:"no_scope"};function targetLabel(target){const name3=target.name.trim();const group=target.resourceGroup?.trim();return group?`${name3} (${group})`:name3}__name(targetLabel,"targetLabel");function unnamedTargetsSentence(unnamed){switch(unnamed.unnamed){case"no_scope":return`This action does not declare a resource ${brand_1.BRAND_SHORT_NAME} can name \u2014 the run's parameters say what it acts on.`;case"unavailable":return unnamed.detail?`${brand_1.BRAND_SHORT_NAME} could not name this run's resource \u2014 ${unnamed.detail}.`:`${brand_1.BRAND_SHORT_NAME} could not name this run's resource.`;case"not_attempted":return`${brand_1.BRAND_SHORT_NAME} has not resolved this run's resources yet.`}}__name(unnamedTargetsSentence,"unnamedTargetsSentence");function unnamedTargetsLabel(unnamed){switch(unnamed.unnamed){case"no_scope":return"None declared";case"unavailable":return"Could not name";case"not_attempted":return"Not resolved"}}__name(unnamedTargetsLabel,"unnamedTargetsLabel");function resolvedTargetsOf(stored){if(typeof stored.unnamed==="string"){return isTargetIdentityAbsence(stored.unnamed)?targetsUnnamed(stored.unnamed,typeof stored.detail==="string"&&stored.detail.trim()?stored.detail:void 0):exports.TARGETS_NOT_NAMED}if(!Array.isArray(stored.targets))return exports.TARGETS_NOT_NAMED;const targets=stored.targets.flatMap(entry=>{const target=routableTargetOf(entry);return target?[target]:[]});if(stored.targets.length>0&&targets.length===0)return exports.TARGETS_NOT_NAMED;return namedTargets(targets)}__name(resolvedTargetsOf,"resolvedTargetsOf");function routableTargetOf(value){if(typeof value!=="object"||value===null||Array.isArray(value))return void 0;const entry=value;const resourceId=typeof entry.resourceId==="string"?entry.resourceId.trim():"";const name3=typeof entry.name==="string"?entry.name.trim():"";if(!resourceId||!name3)return void 0;const resourceGroup=typeof entry.resourceGroup==="string"&&entry.resourceGroup.trim()?entry.resourceGroup.trim():void 0;return{resourceId,name:name3,...resourceGroup?{resourceGroup}:{}}}__name(routableTargetOf,"routableTargetOf");function isTargetIdentityAbsence(value){return value==="no_scope"||value==="unavailable"||value==="not_attempted"}__name(isTargetIdentityAbsence,"isTargetIdentityAbsence");function compareTargetIdentities(planned,executed){if(planned.unnamed||executed.unnamed)return null;const key=__name(target=>target.resourceId.trim().toLowerCase(),"key");const executedIds=new Set(executed.targets.map(key));const plannedIds=new Set(planned.targets.map(key));return{dropped:planned.targets.filter(target=>!executedIds.has(key(target))),added:executed.targets.filter(target=>!plannedIds.has(key(target))),kept:planned.targets.filter(target=>executedIds.has(key(target)))}}__name(compareTargetIdentities,"compareTargetIdentities");function targetIdentitiesAgree(drift){return drift.dropped.length===0&&drift.added.length===0}__name(targetIdentitiesAgree,"targetIdentitiesAgree");exports.TARGET_NAMES_IN_A_SENTENCE=3;function targetIdentityDriftSentence(drift){if(drift.dropped.length===0&&drift.added.length===0)return null;const separable=labelsSeparate(drift);const clauses=[];if(drift.dropped.length>0){clauses.push(`did not act on ${countedResources(drift.dropped.length)} the plan named`+(separable?` \u2014 ${nameList(drift.dropped)}`:""))}if(drift.added.length>0){clauses.push(`acted on ${countedResources(drift.added.length)} the plan did not name`+(separable?` \u2014 ${nameList(drift.added)}`:""))}return`This run ${clauses.join("; and it ")}.`+(separable?"":" Their names do not tell them apart \u2014 the ids below do.")}__name(targetIdentityDriftSentence,"targetIdentityDriftSentence");function labelsSeparate(drift){const dropped=new Set(drift.dropped.map(targetLabel));return drift.added.every(target=>!dropped.has(targetLabel(target)))}__name(labelsSeparate,"labelsSeparate");function countedResources(total){return`${total} ${total===1?"resource":"resources"}`}__name(countedResources,"countedResources");function nameList(targets){const shown=targets.slice(0,exports.TARGET_NAMES_IN_A_SENTENCE).map(targetLabel);const rest=targets.length-shown.length;if(rest>0)shown.push(`${rest} more`);if(shown.length===1)return shown[0];return`${shown.slice(0,-1).join(", ")} and ${shown[shown.length-1]}`}__name(nameList,"nameList");exports.TARGET_LIST_SHOWN=20}});var require_declared_targets=__commonJS({"../contracts/dist/declared-targets.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.nameDeclaredTargets=nameDeclaredTargets;var resources_1=require_resources();var target_identity_1=require_target_identity();function nameDeclaredTargets(input){const{parameterSchema,provider,parameters,providerScopeId}=input;const declared=routableDeclarations(parameterSchema,provider);const targets=[];for(const candidate of declared){if(declared.some(other=>other.parents.includes(candidate.parameterName)))continue;const named=parameters[candidate.parameterName];if(typeof named!=="string"||!named.trim())continue;if(!candidate.spec.identity)continue;let declaredType;if(candidate.spec.takesResourceType){const composable=(0,resources_1.armIdentityResourceType)(candidate.resourceType);if(composable===null)continue;declaredType=composable}const values=(0,resources_1.discoveryScopeValues)(candidate.spec.identifiedBy??candidate.spec.requires,candidate.dependsOn,parameters);if(!values.resolved){return(0,target_identity_1.targetsUnnamed)("unavailable",`identifying the "${candidate.parameterName}" parameter needs a "${values.parameter}" value, which this run does not carry`)}const identity=(0,resources_1.composeTargetIdentity)(candidate.spec.identity,{...values.scope,subscription:providerScopeId,name:named.trim(),...declaredType?{resourceType:declaredType}:{}});if(!identity.composed){return(0,target_identity_1.targetsUnnamed)("unavailable",`identifying "${named.trim()}" needs a "${identity.missing}" value, which this run does not carry`)}targets.push({resourceId:identity.resourceId,name:named.trim(),...values.scope.resourceGroup?{resourceGroup:values.scope.resourceGroup}:{}})}return targets.length>0?(0,target_identity_1.namedTargets)(targets):target_identity_1.TARGETS_HAVE_NO_NAME}__name(nameDeclaredTargets,"nameDeclaredTargets");function routableDeclarations(parameterSchema,provider){const declarations=[];for(const[parameterName,property]of Object.entries(parameterSchema?.properties??{})){const declared=typeof property.discover==="string"?property.discover.trim():"";if(!declared)continue;const parsed=(0,resources_1.parseDiscoveryType)(declared,provider);const spec=parsed?(0,resources_1.discoveryTypeSpec)(parsed.provider,parsed.type):void 0;if(!spec?.routable)continue;const lookup=(0,resources_1.dependsOnLookup)(spec.requires,property.dependsOn);declarations.push({parameterName,spec,dependsOn:property.dependsOn,resourceType:property.resourceType,parents:spec.requires.map(key=>lookup[key]??key)})}return declarations}__name(routableDeclarations,"routableDeclarations")}});var require_catalog_parameters=__commonJS({"../contracts/dist/catalog-parameters.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.catalogParameterSchema=catalogParameterSchema2;var catalog_1=require_catalog();var resources_1=require_resources();function catalogParameterSchema2(params){const properties={};const required=[];for(const p of params){const prop={type:p.control==="switch"?"boolean":"string",title:p.label,description:p.hint,control:p.control};if(p.options)prop.enum=p.options;if(p.source){const discover=(0,resources_1.canonicalDiscoveryId)(p.source.discover);if(discover===null){throw new Error(`Parameter "${p.id}" discovers "${p.source.discover}", which is not a discovery id.`)}prop.discover=discover;if(p.source.dependsOn?.length)prop.dependsOn=p.source.dependsOn;const typeRefusal=(0,resources_1.resourceTypeDeclarationRefusal)(discover,p.source.resourceType);if(typeRefusal!==null)throw new Error(`Parameter "${p.id}": ${typeRefusal}`);if(p.source.resourceType!==void 0)prop.resourceType=p.source.resourceType}if(p.default!==void 0&&!p.source)prop.default=p.default;properties[p.id]=prop;if(p.required)required.push(p.id)}return(0,catalog_1.withParameterOrder)({$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties,required,additionalProperties:false})}__name(catalogParameterSchema2,"catalogParameterSchema")}});var require_engine_run=__commonJS({"../contracts/dist/engine-run.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.engineRunTarget=engineRunTarget2;exports.destructiveSuccessRefusal=destructiveSuccessRefusal2;exports.engineTargetFindings=engineTargetFindings2;var declared_targets_1=require_declared_targets();var resources_1=require_resources();function engineRunTarget2(input){const named=(0,declared_targets_1.nameDeclaredTargets)({parameterSchema:input.parameterSchema,provider:input.provider,parameters:input.parameters,providerScopeId:input.providerScopeId});const only=named.unnamed?void 0:named.targets.length===1?named.targets[0]:void 0;if(!only){throw new Error(`An engine action acts on exactly one target per run, named by a discovered parameter; this run of "${input.key}" names ${named.unnamed?`none (${named.detail??named.unnamed})`:named.targets.length}.`)}return{ref:only.resourceId,parameters:input.parameters}}__name(engineRunTarget2,"engineRunTarget");function destructiveSuccessRefusal2(input){if(input.outcome.status==="succeeded"&&input.destructive&&!input.dryRun&&!input.acknowledgedCheckpoint&&input.restorePoint===null){return{status:"failed",message:`"${input.key}" reported success, but it is destructive and no restore point was acknowledged before it acted, so the engine does not accept that success. Check the target's state before running it again.`,data:{refused:"destructive-success-without-checkpoint",reported:input.outcome.message}}}return null}__name(destructiveSuccessRefusal2,"destructiveSuccessRefusal");function engineTargetFindings2(params){const declared=(Array.isArray(params)?params:[]).map((param,index)=>{const raw=isRecord(param)?param:{};const source=isRecord(raw.source)?raw.source:void 0;const discover=typeof source?.discover==="string"?(0,resources_1.resolveDiscoveryType)(source.discover)?.id??null:null;return{index,id:typeof raw.id==="string"?raw.id:`#${index}`,source,discover}});const targets=declared.filter(param=>param.discover===ENGINE_TARGET_DISCOVERY);if(targets.length!==1){return[`params: an engine action names the one resource it acts on with exactly one parameter that discovers "${ENGINE_TARGET_DISCOVERY}", and this manifest has ${targets.length===0?"none":`${targets.length} (${targets.map(param=>param.id).join(", ")})`}. Several targets wait until an action needs them.`]}const[target]=targets;const path=`params[${target.index}]`;const findings=[];const dependsOn=target.source?.dependsOn;if(!Array.isArray(dependsOn)||dependsOn.length!==1||dependsOn[0]!==ENGINE_TARGET_GROUP_PARAMETER){findings.push(`${path}.source.dependsOn: the target "${target.id}" must declare dependsOn: ["${ENGINE_TARGET_GROUP_PARAMETER}"] and nothing else \u2014 the engine composes its id from the resource group parameter of that name.`)}const group=declared.find(param=>param.id===ENGINE_TARGET_GROUP_PARAMETER);if(group?.discover!==ENGINE_TARGET_GROUP_DISCOVERY){findings.push(`params: the target "${target.id}" is named inside its resource group, so the manifest needs a parameter called "${ENGINE_TARGET_GROUP_PARAMETER}" that discovers "${ENGINE_TARGET_GROUP_DISCOVERY}"${group===void 0?"; it has none":`; "${ENGINE_TARGET_GROUP_PARAMETER}" discovers ${JSON.stringify(group.discover??group.source?.discover??null)}`}.`)}const resourceType=target.source?.resourceType;if((0,resources_1.armIdentityResourceType)(resourceType)===null){findings.push(`${path}.source.resourceType: ${JSON.stringify(resourceType??null)} is not a top-level ARM resource type. An engine action's target is one of two segments (e.g. "Microsoft.Network/publicIPAddresses"): a nested type's id interleaves its parents' names, which a run does not carry. Nested types wait until an action needs them.`)}if(findings.length>0)return findings;const properties={};const parameters={};for(const param of declared){const property={type:"string",title:param.id,control:"text"};if(param.discover!==null)property.discover=param.discover;if(Array.isArray(param.source?.dependsOn))property.dependsOn=param.source.dependsOn.filter(name3=>typeof name3==="string");if(typeof param.source?.resourceType==="string")property.resourceType=param.source.resourceType;properties[param.id]=property;parameters[param.id]=`probe-${param.index}`}const named=(0,declared_targets_1.nameDeclaredTargets)({parameterSchema:{$schema:"",type:"object",properties,required:[],additionalProperties:false},provider:resources_1.LEGACY_DISCOVERY_PROVIDER,parameters,providerScopeId:"probe"});const names=named.unnamed?[]:named.targets.map(resource=>resource.name);if(names.length!==1||names[0]!==parameters[target.id]){const routable=declared.filter(param=>names.includes(parameters[param.id])).map(param=>param.id);findings.push(`params: an engine run acts on exactly one target, and these parameters would name ${names.length===0?"none":`${names.length} (${routable.join(", ")})`}. Only "${target.id}" may name a resource the run reaches; several targets wait until an action needs them.`)}return findings}__name(engineTargetFindings2,"engineTargetFindings");var ENGINE_TARGET_TYPE="arm";var ENGINE_TARGET_DISCOVERY=(0,resources_1.formatDiscoveryType)(resources_1.LEGACY_DISCOVERY_PROVIDER,ENGINE_TARGET_TYPE);var ENGINE_TARGET_GROUP_PARAMETER="resourceGroup";var ENGINE_TARGET_GROUP_DISCOVERY=(0,resources_1.formatDiscoveryType)(resources_1.LEGACY_DISCOVERY_PROVIDER,ENGINE_TARGET_GROUP_PARAMETER);function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord")}});var require_check_declaration=__commonJS({"../contracts/dist/check-declaration.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BUILT_IN_CODES=exports.CHECK_ACKNOWLEDGEMENT_MAX_LENGTH=exports.CHECK_TITLE_MAX_LENGTH=void 0;exports.checkDeclarationFindings=checkDeclarationFindings2;exports.checkDeclarationOf=checkDeclarationOf2;exports.declaredCodesOf=declaredCodesOf2;exports.storedDeclaredCodesOf=storedDeclaredCodesOf;exports.undeclaredCodeRefusal=undeclaredCodeRefusal;exports.undeclaredReportCodeRefusal=undeclaredReportCodeRefusal2;var validation_1=require_validation();exports.CHECK_TITLE_MAX_LENGTH=120;exports.CHECK_ACKNOWLEDGEMENT_MAX_LENGTH=120;function checkDeclarationFindings2(manifest){const engine=manifest.execution!==void 0&&manifest.execution!==null;if(!engine){return manifest.checks===void 0?[]:["checks: is declared by an engine action (one with execution:). A built-in action's codes and their labels are the platform's own, so a built-in declares none."]}if(manifest.checks===void 0||manifest.checks===null){return[`checks: is required on an engine action \u2014 every refusal and decision code its validate may raise, and each decision's acknowledgement. The engine refuses a run that raises a code its version did not declare. An action that raises none declares "checks: { refusals: [], decisions: [] }".`]}return readDeclaration(manifest.checks).findings}__name(checkDeclarationFindings2,"checkDeclarationFindings");function checkDeclarationOf2(value){const read=readDeclaration(value);return read.findings.length===0?read.declaration:null}__name(checkDeclarationOf2,"checkDeclarationOf");var PLATFORM_CODES=[...validation_1.REFUSAL_CODES,...validation_1.DECISION_CODES];function readDeclaration(value){const declaration={refusals:[],decisions:[]};const findings=[];if(!isRecord(value)){return{declaration,findings:["checks: must be a mapping with refusals: and decisions:, each a list."]}}findings.push(...unknownKeys(value,["refusals","decisions"],"checks"));const seen=new Map;const entries=__name(key=>{const list=value[key];if(!Array.isArray(list)){findings.push(`checks.${key}: must be a list (an empty one, [], when the action raises none).`);return[]}return list.flatMap((entry,index)=>{if(isRecord(entry))return[[entry,index]];findings.push(`checks.${key}[${index}]: must be a mapping with code: and title:.`);return[]})},"entries");entries("refusals").forEach(([entry,index])=>{const path=`checks.refusals[${index}]`;findings.push(...unknownKeys(entry,["code","title"],path));const code=codeOf(entry.code,path,seen,findings);const title=textOf(entry.title,`${path}.title`,exports.CHECK_TITLE_MAX_LENGTH,findings);if(code!==null&&title!==null)declaration.refusals.push({code,title})});entries("decisions").forEach(([entry,index])=>{const path=`checks.decisions[${index}]`;findings.push(...unknownKeys(entry,["code","title","acknowledgement"],path));const code=codeOf(entry.code,path,seen,findings);const title=textOf(entry.title,`${path}.title`,exports.CHECK_TITLE_MAX_LENGTH,findings);let acknowledgement=null;if(entry.acknowledgement===void 0){findings.push(`${path}.acknowledgement: every decision carries one \u2014 the label on the control the requester ticks, saying what they agree to (at most ${exports.CHECK_ACKNOWLEDGEMENT_MAX_LENGTH} characters).`)}else{acknowledgement=textOf(entry.acknowledgement,`${path}.acknowledgement`,exports.CHECK_ACKNOWLEDGEMENT_MAX_LENGTH,findings)}if(code!==null&&title!==null&&acknowledgement!==null){declaration.decisions.push({code,title,acknowledgement})}});return{declaration,findings}}__name(readDeclaration,"readDeclaration");function codeOf(value,path,seen,findings){if(!(0,validation_1.isCheckCode)(value)){findings.push((0,validation_1.checkCodeRefusal)(value,`${path}.code:`));return null}if(PLATFORM_CODES.includes(value)){findings.push(`${path}.code: "${value}" is one of the platform's own codes, which the built-in actions raise. An engine action's codes are its own \u2014 a shared one would be read as the built-in's, its label and its records alike.`);return null}const earlier=seen.get(value);if(earlier!==void 0){findings.push(`${path}.code: "${value}" is already declared at ${earlier}. Each code is declared once.`);return null}seen.set(value,path);return value}__name(codeOf,"codeOf");function textOf(value,path,max,findings){if(typeof value!=="string"||value.trim().length===0){findings.push(`${path}: must be a non-empty string.`);return null}if(value.length>max){findings.push(`${path}: is ${value.length} characters, longer than ${max}.`);return null}return value}__name(textOf,"textOf");function unknownKeys(value,allowed,path){return Object.keys(value).filter(key=>!allowed.includes(key)).map(key=>`${path}.${key}: is not a field here. Allowed: ${allowed.join(", ")}.`)}__name(unknownKeys,"unknownKeys");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");exports.BUILT_IN_CODES={refusals:validation_1.REFUSAL_CODES,decisions:validation_1.DECISION_CODES};function declaredCodesOf2(declaration){return{refusals:declaration.refusals.map(refusal=>refusal.code),decisions:declaration.decisions.map(decision=>decision.code)}}__name(declaredCodesOf2,"declaredCodesOf");function storedDeclaredCodesOf(stored){if(!isRecord(stored))return{refusals:[],decisions:[]};const codes=__name(list=>Array.isArray(list)?list.filter(validation_1.isCheckCode):[],"codes");return{refusals:codes(stored.refusals),decisions:codes(stored.decisions)}}__name(storedDeclaredCodesOf,"storedDeclaredCodesOf");function undeclaredCodeRefusal(checks,declared){for(const check of checks){if(check.refusal!==void 0&&!declared.refusals.includes(check.refusal)){return undeclared("refusal",check.refusal,check.title)}if(check.decision!==void 0&&!declared.decisions.includes(check.decision)){return undeclared("decision",check.decision,check.title)}}return null}__name(undeclaredCodeRefusal,"undeclaredCodeRefusal");function undeclaredReportCodeRefusal2(report,declared){if(!("checks"in report))return null;for(const{ref,checks}of report.checks){const refused=undeclaredCodeRefusal(checks,declared);if(refused!==null)return`The checks for "${ref}": ${refused}`}return null}__name(undeclaredReportCodeRefusal2,"undeclaredReportCodeRefusal");function undeclared(kind,code,title){return`the check "${title}" raises the ${kind} "${code}", which this action version does not declare. An action raises only the codes its catalog.yaml declares in checks:, so that a reviewer saw each one before the version was signed.`}__name(undeclared,"undeclared")}});var require_which_entra=__commonJS({"../contracts/dist/which-entra.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AZURE_CONNECTION_PRINCIPAL_SENTENCE=exports.AZURE_CONNECTION_ENTRA_SENTENCE=exports.SIGN_IN_ENTRA_SENTENCE=void 0;var brand_1=require_brand();exports.SIGN_IN_ENTRA_SENTENCE=`Signing in installs nothing in your identity directory. Letting ${brand_1.BRAND_SHORT_NAME} act on your cloud resources is a separate step, set up later, and that one does need an identity in the directory that owns them.`;exports.AZURE_CONNECTION_ENTRA_SENTENCE=`This is the other Entra. Connecting Azure is a different question from signing in: this step is about the Microsoft Entra tenant that owns the subscription you want ${brand_1.BRAND_SHORT_NAME} to act on.`;exports.AZURE_CONNECTION_PRINCIPAL_SENTENCE=`${brand_1.BRAND_SHORT_NAME} needs a service principal in that tenant \u2014 an app registration or a managed identity \u2014 and it is required: there is no way to act on your resources without one. No secret leaves your tenant; the trust is a federated credential you create below. It can do only what your Azure role assignments allow, on the subscriptions or resource groups you pick, and ${brand_1.BRAND_SHORT_NAME} never asks for Microsoft Graph or any directory permission. You can revoke it at any time in your own portal by removing the federated credential or the role assignment.`}});var require_onboarding=__commonJS({"../contracts/dist/onboarding.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NO_WORKSPACE_CODE=void 0;exports.NO_WORKSPACE_CODE="NO_WORKSPACE"}});var require_workspace_domain=__commonJS({"../contracts/dist/workspace-domain.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WORKSPACE_DOMAIN_RELEASE_CONSEQUENCE=exports.WORKSPACE_DOMAIN_STATE_SENTENCE=exports.DOMAIN_CHECK_OUTCOME_SENTENCE=exports.DOMAIN_VERIFICATION_RECORD_PREFIX=exports.DOMAIN_CHECK_OUTCOMES=exports.DOMAIN_PROOF_MAX_AGE_MS=exports.DOMAIN_PROOF_MAX_AGE_DAYS=exports.WORKSPACE_DOMAIN_STATES=void 0;exports.workspaceDomainState=workspaceDomainState;exports.domainVerificationRecord=domainVerificationRecord;exports.WORKSPACE_DOMAIN_STATES=["pending","verified","unconfirmed"];exports.DOMAIN_PROOF_MAX_AGE_DAYS=30;exports.DOMAIN_PROOF_MAX_AGE_MS=exports.DOMAIN_PROOF_MAX_AGE_DAYS*24*60*60*1e3;function workspaceDomainState(proof,now){const current=proof.verifiedAt!==null&&proof.lastVerifiedAt!==null&&now.getTime()-proof.lastVerifiedAt.getTime()<=exports.DOMAIN_PROOF_MAX_AGE_MS;if(current)return"verified";return proof.verifiedAt===null?"pending":"unconfirmed"}__name(workspaceDomainState,"workspaceDomainState");exports.DOMAIN_CHECK_OUTCOMES=["verified","record_missing","domain_unknown","dns_unreachable","challenge_expired","held_elsewhere"];exports.DOMAIN_VERIFICATION_RECORD_PREFIX="runveric-domain-verification=";function domainVerificationRecord(domain,token2){return{name:domain,type:"TXT",value:`${exports.DOMAIN_VERIFICATION_RECORD_PREFIX}${token2}`}}__name(domainVerificationRecord,"domainVerificationRecord");exports.DOMAIN_CHECK_OUTCOME_SENTENCE={verified:"The record was found and this domain is verified for this workspace.",record_missing:"The zone answered, but the record this workspace must publish was not among its TXT values.",domain_unknown:"This domain does not resolve at all, so no record could be looked for on it yet.",dns_unreachable:"The DNS check could not complete, which says nothing about the record itself yet.",challenge_expired:"The challenge has expired and a record carrying it would not be accepted any more.",held_elsewhere:"Another workspace holds this domain verified and its own record is still published there."};exports.WORKSPACE_DOMAIN_STATE_SENTENCE={pending:"Nobody can join by this domain until the record below is found in its zone.",verified:`Colleagues with an address at this domain can join without an invitation. The record must stay published: it is read again by later checks, and a proof that no check can confirm for ${exports.DOMAIN_PROOF_MAX_AGE_DAYS} days lapses until one does.`,unconfirmed:"This workspace still holds the domain, but its record could not be confirmed recently, so nobody can join by it until a check finds the record again. The record itself has not changed; make the value below visible in the zone, then check again."};exports.WORKSPACE_DOMAIN_RELEASE_CONSEQUENCE={pending:"The claim and its record are discarded. You can claim the domain again later, with a new record.",verified:"Colleagues will no longer be able to join by this domain. Members already in the workspace keep their access.",unconfirmed:"The workspace gives up the domain it still holds. Claiming it again later means publishing a new record, and another workspace may take it meanwhile."}}});var require_workspace_features=__commonJS({"../contracts/dist/workspace-features.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WORKSPACE_FEATURE_COPY=exports.WORKSPACE_FEATURES=void 0;exports.isWorkspaceFeature=isWorkspaceFeature;var brand_1=require_brand();exports.WORKSPACE_FEATURES=["directory_sync"];exports.WORKSPACE_FEATURE_COPY={directory_sync:{name:"Directory sync",notEntitled:`Group membership is managed here in ${brand_1.BRAND_SHORT_NAME}. Mirroring groups from your identity provider is a paid add-on \u2014 contact ${brand_1.BRAND_SHORT_NAME} to turn it on for this workspace.`}};function isWorkspaceFeature(value){return exports.WORKSPACE_FEATURES.includes(value)}__name(isWorkspaceFeature,"isWorkspaceFeature")}});var require_directory_sync=__commonJS({"../contracts/dist/directory-sync.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DIRECTORY_SYNC_UNAVAILABLE_CODE=exports.DIRECTORY_GROUP_UNMAINTAINED=exports.DIRECTORY_SYNC_AVAILABILITY_SENTENCE=exports.DIRECTORY_SYNC_AVAILABILITY_STATES=void 0;var brand_1=require_brand();var DIRECTORY_SYNC_AVAILABILITY_STATE_SET={not_entitled:true,not_connected:true,available:true};exports.DIRECTORY_SYNC_AVAILABILITY_STATES=Object.keys(DIRECTORY_SYNC_AVAILABILITY_STATE_SET);exports.DIRECTORY_SYNC_AVAILABILITY_SENTENCE={not_entitled:{headline:"Directory sync is not enabled for this workspace",detail:`Group membership is managed here in ${brand_1.BRAND_SHORT_NAME}. Mirroring groups from your identity provider is a paid add-on \u2014 contact ${brand_1.BRAND_SHORT_NAME} to turn it on for this workspace.`},not_connected:{headline:"No directory is connected",detail:"Directory sync is enabled for this workspace, but no identity directory is connected to it yet. Once one is connected, its groups can be linked here and their membership is mirrored at sign-in."},available:{headline:"Directory sync is on",detail:`A group linked to your directory mirrors its membership every time one of its members signs in. Roles stay attached here in ${brand_1.BRAND_SHORT_NAME}.`}};exports.DIRECTORY_GROUP_UNMAINTAINED={short:"Membership is not being maintained \u2014 no directory is connected.",detail:"This group is linked to a directory that is not connected, so nobody is added to it or removed from it automatically, and nothing is synced. Its roles still apply to whoever is already a member."};exports.DIRECTORY_SYNC_UNAVAILABLE_CODE="DIRECTORY_SYNC_UNAVAILABLE"}});var require_workos_binding=__commonJS({"../contracts/dist/workos-binding.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WORKOS_DEFAULT_API_HOSTNAME=exports.WORKOS_CLIENT_ID_PATTERN=exports.WORKOS_ENVIRONMENT_KEY_PREFIXES=exports.WORKOS_ENVIRONMENTS=void 0;exports.workosEnvironmentOfApiKey=workosEnvironmentOfApiKey;exports.workosIssuer=workosIssuer;exports.workosJwksUri=workosJwksUri;exports.workosBindingSentence=workosBindingSentence;exports.WORKOS_ENVIRONMENTS=["staging","production"];exports.WORKOS_ENVIRONMENT_KEY_PREFIXES={staging:"sk_test_",production:"sk_live_"};function workosEnvironmentOfApiKey(apiKey){for(const environment of exports.WORKOS_ENVIRONMENTS){if(apiKey.startsWith(exports.WORKOS_ENVIRONMENT_KEY_PREFIXES[environment])){return environment}}return null}__name(workosEnvironmentOfApiKey,"workosEnvironmentOfApiKey");exports.WORKOS_CLIENT_ID_PATTERN=/client_[0-9A-HJKMNP-TV-Z]{26}/;exports.WORKOS_DEFAULT_API_HOSTNAME="api.workos.com";function workosIssuer(apiHostname,clientId){return`https://${apiHostname}/user_management/${clientId}`}__name(workosIssuer,"workosIssuer");function workosJwksUri(apiHostname,clientId){return`https://${apiHostname}/sso/jwks/${clientId}`}__name(workosJwksUri,"workosJwksUri");function workosBindingSentence(binding){if(!binding.workosEnabled){return"WorkOS is disabled: this process authenticates nobody through it."}return`WorkOS binding: client ${binding.clientId??"(none)"}, environment ${binding.environment??"(not declared)"}.`}__name(workosBindingSentence,"workosBindingSentence")}});var require_dist=__commonJS({"../contracts/dist/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:__name(function(){return m[k]},"get")}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]});var __exportStar=exports&&exports.__exportStar||function(m,exports1){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports1,p))__createBinding(exports1,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require_enums(),exports);__exportStar(require_brand(),exports);__exportStar(require_wire_identity(),exports);__exportStar(require_problem(),exports);__exportStar(require_permissions(),exports);__exportStar(require_request_context(),exports);__exportStar(require_role_permissions(),exports);__exportStar(require_me(),exports);__exportStar(require_tenant_users(),exports);__exportStar(require_invitations(),exports);__exportStar(require_groups(),exports);__exportStar(require_catalog_version(),exports);__exportStar(require_catalog_policy(),exports);__exportStar(require_catalog(),exports);__exportStar(require_catalog_release(),exports);__exportStar(require_action_repository(),exports);__exportStar(require_catalog_release_spec(),exports);__exportStar(require_catalog_lock(),exports);__exportStar(require_catalog_manifest_placeholders(),exports);__exportStar(require_change_control(),exports);__exportStar(require_execution(),exports);__exportStar(require_decisions(),exports);__exportStar(require_execution_site(),exports);__exportStar(require_run_placement(),exports);__exportStar(require_connections(),exports);__exportStar(require_resources(),exports);__exportStar(require_governance(),exports);__exportStar(require_audit(),exports);__exportStar(require_notifications(),exports);__exportStar(require_scheduling(),exports);__exportStar(require_operations(),exports);__exportStar(require_runs(),exports);__exportStar(require_evidence_pack(),exports);__exportStar(require_package_tier(),exports);__exportStar(require_package_provenance(),exports);__exportStar(require_packages(),exports);__exportStar(require_package_egress(),exports);__exportStar(require_package_execution(),exports);__exportStar(require_runner_confinement(),exports);__exportStar(require_runner_install(),exports);__exportStar(require_authoring_cli(),exports);__exportStar(require_runners(),exports);__exportStar(require_scoped_credential(),exports);__exportStar(require_action_protocol(),exports);__exportStar(require_action_signing(),exports);__exportStar(require_oci_media_types(),exports);__exportStar(require_action_image(),exports);__exportStar(require_catalog_templates(),exports);__exportStar(require_runner_pool_presence(),exports);__exportStar(require_routable_target(),exports);__exportStar(require_runner_pool_routing(),exports);__exportStar(require_target_identity(),exports);__exportStar(require_declared_targets(),exports);__exportStar(require_catalog_parameters(),exports);__exportStar(require_engine_run(),exports);__exportStar(require_check_declaration(),exports);__exportStar(require_which_entra(),exports);__exportStar(require_onboarding(),exports);__exportStar(require_workspace_domain(),exports);__exportStar(require_workspace_features(),exports);__exportStar(require_directory_sync(),exports);__exportStar(require_workos_binding(),exports)}});var require_action_sdk_public=__commonJS({"../contracts/dist/action-sdk.public.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StaticScopedCredential=exports.ENGINE_ACTION_TOKEN_HOLDER=exports.settleDecisionChecks=exports.UNDECIDED_AT_RUN=exports.parseCheckpointAck=exports.actionTokenScope=void 0;var action_protocol_1=require_action_protocol();Object.defineProperty(exports,"actionTokenScope",{enumerable:true,get:__name(function(){return action_protocol_1.actionTokenScope},"get")});Object.defineProperty(exports,"parseCheckpointAck",{enumerable:true,get:__name(function(){return action_protocol_1.parseCheckpointAck},"get")});var decisions_1=require_decisions();Object.defineProperty(exports,"UNDECIDED_AT_RUN",{enumerable:true,get:__name(function(){return decisions_1.UNDECIDED_AT_RUN},"get")});Object.defineProperty(exports,"settleDecisionChecks",{enumerable:true,get:__name(function(){return decisions_1.settleDecisionChecks},"get")});var scoped_credential_1=require_scoped_credential();Object.defineProperty(exports,"ENGINE_ACTION_TOKEN_HOLDER",{enumerable:true,get:__name(function(){return scoped_credential_1.ENGINE_ACTION_TOKEN_HOLDER},"get")});Object.defineProperty(exports,"StaticScopedCredential",{enumerable:true,get:__name(function(){return scoped_credential_1.StaticScopedCredential},"get")})}});var require_dist2=__commonJS({"../action-sdk/dist/index.js"(exports,module){"use strict";var __defProp2=Object.defineProperty;var __getOwnPropDesc2=Object.getOwnPropertyDescriptor;var __getOwnPropNames2=Object.getOwnPropertyNames;var __hasOwnProp2=Object.prototype.hasOwnProperty;var __name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:true}),"__name");var __export=__name((target,all)=>{for(var name3 in all)__defProp2(target,name3,{get:all[name3],enumerable:true})},"__export");var __copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames2(from))if(!__hasOwnProp2.call(to,key)&&key!==except)__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable})}return to},"__copyProps");var __toCommonJS=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:true}),mod),"__toCommonJS");var src_exports={};__export(src_exports,{RestorePointNotAcknowledgedError:__name(()=>RestorePointNotAcknowledgedError,"RestorePointNotAcknowledgedError"),UNDECIDED_AT_RUN:__name(()=>import_action_sdk3.UNDECIDED_AT_RUN,"UNDECIDED_AT_RUN"),actionCredential:__name(()=>actionCredential,"actionCredential"),defineAction:__name(()=>defineAction,"defineAction"),executeContext:__name(()=>executeContext,"executeContext"),rollbackContext:__name(()=>rollbackContext,"rollbackContext"),settleDecisionChecks:__name(()=>import_action_sdk3.settleDecisionChecks,"settleDecisionChecks"),validateContext:__name(()=>validateContext,"validateContext")});module.exports=__toCommonJS(src_exports);function defineAction(definition){for(const handler of["validate","execute"]){if(typeof definition[handler]!=="function"){throw new TypeError(`An action must define a "${handler}" handler.`)}}if(definition.rollback!==void 0&&typeof definition.rollback!=="function"){throw new TypeError(`An action's "rollback", when present, must be a handler.`)}return definition}__name(defineAction,"defineAction");__name2(defineAction,"defineAction");var import_action_sdk2=require_action_sdk_public();var import_action_sdk=require_action_sdk_public();function actionCredential(tokens2,now=Date.now,holder=import_action_sdk.ENGINE_ACTION_TOKEN_HOLDER){return new import_action_sdk.StaticScopedCredential(tokens2.map(token2=>({scope:(0,import_action_sdk.actionTokenScope)(token2.audience),token:token2.token,expiresOnTimestamp:Date.parse(token2.expiresOn)})),now,holder)}__name(actionCredential,"actionCredential");__name2(actionCredential,"actionCredential");var RestorePointNotAcknowledgedError=class extends Error{static{__name(this,"RestorePointNotAcknowledgedError")}static{__name2(this,"RestorePointNotAcknowledgedError")}constructor(reason){super(`The restore point was not acknowledged by the engine, so nothing may be acted on: ${reason}`);this.name="RestorePointNotAcknowledgedError"}};function validateContext(invocation,channel,signal,now=Date.now,holder){return{...commonContext(invocation,channel,signal,now,holder),mode:invocation.mode,targets:invocation.targets,decisions:invocation.decisions}}__name(validateContext,"validateContext");__name2(validateContext,"validateContext");function executeContext(invocation,channel,signal,now=Date.now,holder){return{...commonContext(invocation,channel,signal,now,holder),target:onlyTarget(invocation.targets),decisions:invocation.decisions,restorePoint:invocation.restorePoint,saveRestorePoint:__name2(async record=>{let answer;try{answer=await channel.checkpoint({kind:"restore_point",record})}catch(cause){throw new RestorePointNotAcknowledgedError(messageOf2(cause))}try{(0,import_action_sdk2.parseCheckpointAck)(answer)}catch(cause){throw new RestorePointNotAcknowledgedError(messageOf2(cause))}},"saveRestorePoint")}}__name(executeContext,"executeContext");__name2(executeContext,"executeContext");function rollbackContext(invocation,channel,signal,now=Date.now,holder){return{...commonContext(invocation,channel,signal,now,holder),target:onlyTarget(invocation.targets),decisions:invocation.decisions,restorePoint:invocation.restorePoint,priorResult:invocation.priorResult}}__name(rollbackContext,"rollbackContext");__name2(rollbackContext,"rollbackContext");function commonContext(invocation,channel,signal,now,holder){return{azure:actionCredential(invocation.credentials.tokens,now,holder),emit:__name2(event=>channel.emit(event),"emit"),signal,dryRun:invocation.execution.dryRun,action:{key:invocation.action.key,version:invocation.action.version},execution:{id:invocation.execution.id,tenantId:invocation.execution.tenantId,correlationId:invocation.execution.correlationId}}}__name(commonContext,"commonContext");__name2(commonContext,"commonContext");function onlyTarget(targets){const[target]=targets;if(!target||targets.length!==1){throw new Error(`An act names exactly one target; this invocation names ${targets.length}.`)}return target}__name(onlyTarget,"onlyTarget");__name2(onlyTarget,"onlyTarget");function messageOf2(cause){return cause instanceof Error?cause.message:String(cause)}__name(messageOf2,"messageOf");__name2(messageOf2,"messageOf");var import_action_sdk3=require_action_sdk_public()}});var require_dist3=__commonJS({"../action-runtime/dist/index.js"(exports,module){"use strict";var __defProp2=Object.defineProperty;var __getOwnPropDesc2=Object.getOwnPropertyDescriptor;var __getOwnPropNames2=Object.getOwnPropertyNames;var __hasOwnProp2=Object.prototype.hasOwnProperty;var __name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:true}),"__name");var __export=__name((target,all)=>{for(var name3 in all)__defProp2(target,name3,{get:all[name3],enumerable:true})},"__export");var __copyProps2=__name((to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames2(from))if(!__hasOwnProp2.call(to,key)&&key!==except)__defProp2(to,key,{get:__name(()=>from[key],"get"),enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable})}return to},"__copyProps");var __toCommonJS=__name(mod=>__copyProps2(__defProp2({},"__esModule",{value:true}),mod),"__toCommonJS");var src_exports={};__export(src_exports,{ACTION_ENTRY:__name(()=>ACTION_ENTRY,"ACTION_ENTRY"),ActionDeadlineError:__name(()=>ActionDeadlineError,"ActionDeadlineError"),EGRESS_WAIT:__name(()=>EGRESS_WAIT,"EGRESS_WAIT"),EgressProxyNotListeningError:__name(()=>EgressProxyNotListeningError,"EgressProxyNotListeningError"),EgressProxyUrlError:__name(()=>EgressProxyUrlError,"EgressProxyUrlError"),EngineRefusedError:__name(()=>EngineRefusedError,"EngineRefusedError"),HttpTransport:__name(()=>HttpTransport,"HttpTransport"),LoopbackTransport:__name(()=>LoopbackTransport2,"LoopbackTransport"),PROBE_CONNECT_TARGETS:__name(()=>PROBE_CONNECT_TARGETS,"PROBE_CONNECT_TARGETS"),PROBE_EXIT:__name(()=>PROBE_EXIT,"PROBE_EXIT"),RUNTIME_EXIT:__name(()=>RUNTIME_EXIT,"RUNTIME_EXIT"),actionOf:__name(()=>actionOf2,"actionOf"),main:__name(()=>main2,"main"),probe:__name(()=>probe,"probe"),runAction:__name(()=>runAction2,"runAction"),waitForEgressProxy:__name(()=>waitForEgressProxy,"waitForEgressProxy")});module.exports=__toCommonJS(src_exports);var import_contracts16=require_dist();var import_action_sdk=require_dist2();async function runAction2(definition,transport,options={}){const now=options.now??Date.now;const invocation=(0,import_contracts16.parseActionInvocation)(await transport.fetchInvocation());const secrets=invocation.credentials.tokens.map(token2=>token2.token);const handlerSignal=new AbortController;let deadlineTimer;const deadlineReached=new Promise(resolve8=>{deadlineTimer=setTimeout(()=>{handlerSignal.abort(new ActionDeadlineError(invocation.limits.deadline));resolve8(DEADLINE)},Math.max(0,Date.parse(invocation.limits.deadline)-now()))});const onCancel=__name2(()=>handlerSignal.abort(options.cancel?.reason),"onCancel");if(options.cancel?.aborted)onCancel();options.cancel?.addEventListener("abort",onCancel,{once:true});const channel={emit:__name2(event=>transport.postEvent((0,import_contracts16.redactSecrets)(event,secrets)),"emit"),checkpoint:__name2(checkpoint=>transport.postCheckpoint(checkpoint),"checkpoint")};try{const answered=await Promise.race([answer(definition,invocation,channel,handlerSignal.signal,now,options.tokenHolder).catch(error=>failedReport(invocation,isCancel(error,options.cancel)?"cancelled":"failed",error)),deadlineReached]);const report=(0,import_contracts16.redactSecrets)(answered===DEADLINE?failedReport(invocation,"failed",new ActionDeadlineError(invocation.limits.deadline)):answered,secrets);await transport.postReport(report);return report}finally{clearTimeout(deadlineTimer);options.cancel?.removeEventListener("abort",onCancel)}}__name(runAction2,"runAction");__name2(runAction2,"runAction");var ActionDeadlineError=class extends Error{static{__name(this,"ActionDeadlineError")}static{__name2(this,"ActionDeadlineError")}constructor(deadline){super(`The action did not finish before its deadline (${deadline}), so it was stopped.`);this.name="ActionDeadlineError"}};var DEADLINE=Symbol("deadline");async function answer(definition,invocation,channel,signal,now,holder){switch(invocation.phase){case"validate":return{phase:"validate",checks:await definition.validate((0,import_action_sdk.validateContext)(invocation,channel,signal,now,holder))};case"run":return{phase:"run",outcome:await definition.execute((0,import_action_sdk.executeContext)(invocation,channel,signal,now,holder))};case"rollback":if(!definition.rollback){return{phase:"rollback",outcome:{status:"failed",message:`"${invocation.action.key}" has no rollback.`}}}return{phase:"rollback",outcome:await definition.rollback((0,import_action_sdk.rollbackContext)(invocation,channel,signal,now,holder))}}}__name(answer,"answer");__name2(answer,"answer");function failedReport(invocation,status,error){const message=messageOf2(error);if(invocation.phase==="validate"){return{phase:"validate",outcome:{status:"failed",message}}}return{phase:invocation.phase,outcome:{status,message}}}__name(failedReport,"failedReport");__name2(failedReport,"failedReport");function isCancel(error,cancel){return cancel?.aborted===true&&error instanceof Error&&error.name==="AbortError"}__name(isCancel,"isCancel");__name2(isCancel,"isCancel");function messageOf2(error){const message=error instanceof Error?error.message:String(error);return message.length>0?message:"The action failed without saying why."}__name(messageOf2,"messageOf");__name2(messageOf2,"messageOf");var LoopbackTransport2=class{static{__name(this,"LoopbackTransport")}static{__name2(this,"LoopbackTransport")}engine;constructor(engine){this.engine=engine}async fetchInvocation(){return overTheWire(await this.engine.invocation())}async postEvent(event){await this.engine.event(overTheWire(event))}async postCheckpoint(checkpoint){return overTheWire(await this.engine.checkpoint(overTheWire(checkpoint)))}async postReport(report){await this.engine.report(overTheWire(report))}};function overTheWire(value){const text=JSON.stringify(value);return text===void 0?void 0:JSON.parse(text)}__name(overTheWire,"overTheWire");__name2(overTheWire,"overTheWire");var import_contracts22=require_dist();var EngineRefusedError=class extends Error{static{__name(this,"EngineRefusedError")}static{__name2(this,"EngineRefusedError")}status;constructor(status,message){super(message),this.status=status;this.name="EngineRefusedError"}};var HttpTransport=class{static{__name(this,"HttpTransport")}static{__name2(this,"HttpTransport")}options;fetch;constructor(options){this.options=options;assertSafeOrigin(options.callbackBaseUrl);this.fetch=options.fetch??globalThis.fetch}async fetchInvocation(){const response=await this.send("invocation","GET");if(response.status!==200)throw await refusalOf(response);return response.json()}async postEvent(event){const response=await this.send("events","POST",event);if(response.status!==204)throw await refusalOf(response)}async postCheckpoint(checkpoint){const response=await this.send("checkpoint","POST",checkpoint);if(response.status!==200)throw await refusalOf(response);return response.json()}async postReport(report){const response=await this.send("report","POST",report);if(response.status===204||response.status===409)return;throw await refusalOf(response)}send(message,method,body){return this.fetch((0,import_contracts22.engineRunUrl)(this.options.callbackBaseUrl,this.options.runId,message),{method,redirect:"error",headers:{[import_contracts22.RUN_TOKEN_HEADER]:this.options.runToken,accept:"application/json",...body===void 0?{}:{"content-type":"application/json"}},...body===void 0?{}:{body:JSON.stringify(body)}})}};var LOOPBACK_HOSTS=new Set(["127.0.0.1","localhost"]);function assertSafeOrigin(callbackBaseUrl){let url;try{url=new URL(callbackBaseUrl)}catch{throw new Error(`The engine's callback origin "${callbackBaseUrl}" is not a URL.`)}if(url.protocol==="https:")return;if(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname))return;throw new Error(`The engine's callback origin "${url.origin}" is not HTTPS. A run token is a bearer secret, so it travels only over HTTPS \u2014 or to 127.0.0.1 or localhost, inside the job's own network.`)}__name(assertSafeOrigin,"assertSafeOrigin");__name2(assertSafeOrigin,"assertSafeOrigin");async function refusalOf(response){let sentence=`The engine answered ${response.status}.`;try{const body=await response.json();if(typeof body.message==="string"&&body.message.length>0)sentence=body.message}catch{}return new EngineRefusedError(response.status,sentence)}__name(refusalOf,"refusalOf");__name2(refusalOf,"refusalOf");var import_action_sdk2=require_dist2();var import_contracts32=require_dist();var import_node_net=__require("net");var EGRESS_WAIT={timeoutMs:6e4,intervalMs:250};var EgressProxyNotListeningError=class extends Error{static{__name(this,"EgressProxyNotListeningError")}static{__name2(this,"EgressProxyNotListeningError")}constructor(message){super(message);this.name="EgressProxyNotListeningError"}};var EgressProxyUrlError=class extends Error{static{__name(this,"EgressProxyUrlError")}static{__name2(this,"EgressProxyUrlError")}constructor(){super("HTTPS_PROXY is not a URL with a host.");this.name="EgressProxyUrlError"}};var REAL_CLOCK={now:__name2(()=>Date.now(),"now"),sleep:__name2(ms=>new Promise(resolve8=>setTimeout(resolve8,ms)),"sleep")};function egressProxyUrl(env){return env.HTTPS_PROXY||env.https_proxy||void 0}__name(egressProxyUrl,"egressProxyUrl");__name2(egressProxyUrl,"egressProxyUrl");function egressProxyAddress(proxyUrl){let url;try{url=new URL(proxyUrl)}catch{return void 0}const host=url.hostname.replace(/^\[(.*)\]$/,"$1");if(!host)return void 0;return{host,port:Number(url.port||(url.protocol==="https:"?443:80)),origin:`${url.protocol}//${url.host}`}}__name(egressProxyAddress,"egressProxyAddress");__name2(egressProxyAddress,"egressProxyAddress");async function waitForEgressProxy(proxyUrl,options={}){const address=egressProxyAddress(proxyUrl);if(!address)throw new EgressProxyUrlError;const connect=options.connect??import_node_net.connect;const clock=options.clock??REAL_CLOCK;const deadline=clock.now()+EGRESS_WAIT.timeoutMs;while(clock.now()<deadline){if(await accepts(connect,address))return;await clock.sleep(EGRESS_WAIT.intervalMs)}throw new EgressProxyNotListeningError(`The egress proxy at ${address.origin} did not accept a connection within ${EGRESS_WAIT.timeoutMs/1e3} s, so the action was not run: it declares an outbound allowlist, and running it without the proxy would give it unrestricted network.`)}__name(waitForEgressProxy,"waitForEgressProxy");__name2(waitForEgressProxy,"waitForEgressProxy");function accepts(connect,address){return new Promise(resolve8=>{let settled=false;const socket=connect(address.port,address.host);const finish=__name2(accepted=>{if(settled)return;settled=true;socket.destroy();resolve8(accepted)},"finish");socket.setTimeout(EGRESS_WAIT.intervalMs,()=>finish(false));socket.on("error",()=>finish(false));socket.once("connect",()=>finish(true))})}__name(accepts,"accepts");__name2(accepts,"accepts");var ACTION_ENTRY="/action/index.js";var RUNTIME_EXIT={reported:0,failed:1,misconfigured:2,refused:3};async function main2(job){const missing=Object.values(import_contracts32.ACTION_CONTAINER_ENV).filter(name3=>!job.env[name3]);if(missing.length>0){job.say(`action-runtime: refused to start \u2014 ${missing.join(", ")} not set.`);return RUNTIME_EXIT.misconfigured}const runToken=job.env[import_contracts32.ACTION_CONTAINER_ENV.runToken];const say=__name2(line=>job.say((0,import_contracts32.redactJwtShaped)((0,import_contracts32.redactSecrets)(line,[runToken]))),"say");const imageDigest=job.env[import_contracts32.ACTION_CONTAINER_ENV.imageDigest];if(!import_contracts32.ARTIFACT_DIGEST_PATTERN.test(imageDigest)){say(`action-runtime: refused to start \u2014 ${import_contracts32.ACTION_CONTAINER_ENV.imageDigest} is not a sha256 digest.`);return RUNTIME_EXIT.misconfigured}const openTransport=__name2(()=>(job.transport??(options=>new HttpTransport(options)))({callbackBaseUrl:job.env[import_contracts32.ACTION_CONTAINER_ENV.callbackBaseUrl],runId:job.env[import_contracts32.ACTION_CONTAINER_ENV.runId],runToken}),"openTransport");const proxy=egressProxyUrl(job.env);if(proxy){try{await waitForEgressProxy(proxy,{connect:job.connect,clock:job.clock})}catch(error){if(!(error instanceof EgressProxyNotListeningError)){say(`action-runtime: refused to start \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.misconfigured}return notRun(error.message,openTransport,say)}}let definition;let transport;try{definition=actionOf2(job.load(ACTION_ENTRY),ACTION_ENTRY);transport=openTransport()}catch(error){say(`action-runtime: refused to start \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.misconfigured}let fetched;let invocation;try{fetched=await transport.fetchInvocation();invocation=(0,import_contracts32.parseActionInvocation)(fetched)}catch(error){say(`action-runtime: no invocation \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.failed}const phase=`${invocation.phase} of ${invocation.action.key}`;if(!invocation.action.image.endsWith(`@${imageDigest}`)){const refusal=`This runtime was started as ${imageDigest}, and the invocation names ${invocation.action.image}: it does not run another image's invocation.`;try{await transport.postReport(failedReport2(invocation,refusal))}catch{}say(`action-runtime: ${phase} refused \u2014 ${refusal}`);return RUNTIME_EXIT.refused}try{const report=await runAction2(definition,{fetchInvocation:__name2(async()=>fetched,"fetchInvocation"),postEvent:__name2(event=>transport.postEvent(event),"postEvent"),postCheckpoint:__name2(checkpoint=>transport.postCheckpoint(checkpoint),"postCheckpoint"),postReport:__name2(sent=>transport.postReport(sent),"postReport")});say(`action-runtime: ${phase} reported ${endingOf(report)}.`);return RUNTIME_EXIT.reported}catch(error){say(`action-runtime: ${phase} ended without an accepted report \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.failed}}__name(main2,"main");__name2(main2,"main");async function notRun(sentence,openTransport,say){let transport;try{transport=openTransport()}catch(error){say(`action-runtime: refused to start \u2014 ${messageOf22(error)}`);return RUNTIME_EXIT.misconfigured}let phase="the phase";try{const invocation=(0,import_contracts32.parseActionInvocation)(await transport.fetchInvocation());phase=`${invocation.phase} of ${invocation.action.key}`;await transport.postReport(failedReport2(invocation,sentence))}catch{}say(`action-runtime: ${phase} failed \u2014 ${sentence}`);return RUNTIME_EXIT.failed}__name(notRun,"notRun");__name2(notRun,"notRun");function actionOf2(loaded,from){const candidate=loaded!==null&&typeof loaded==="object"&&"default"in loaded?loaded.default:loaded;if(candidate===null||typeof candidate!=="object"){throw new Error(`${from} does not export an action: its default export must be defineAction({ \u2026 }).`)}return(0,import_action_sdk2.defineAction)(candidate)}__name(actionOf2,"actionOf");__name2(actionOf2,"actionOf");function failedReport2(invocation,message){return invocation.phase==="validate"?{phase:"validate",outcome:{status:"failed",message}}:{phase:invocation.phase,outcome:{status:"failed",message}}}__name(failedReport2,"failedReport2");__name2(failedReport2,"failedReport");function endingOf(report){return"checks"in report?"its checks":report.outcome.status}__name(endingOf,"endingOf");__name2(endingOf,"endingOf");function messageOf22(error){return error instanceof Error?error.message:String(error)}__name(messageOf22,"messageOf2");__name2(messageOf22,"messageOf");var import_node_net2=__require("net");var import_contracts42=require_dist();var AZURE_IDENTITY_ENV={endpoint:"IDENTITY_ENDPOINT",header:"IDENTITY_HEADER"};var AZURE_IDENTITY_API_VERSION="2019-08-01";var MANAGEMENT_RESOURCE2="https://management.azure.com/";var PROBE_CONNECT_TARGETS=["management.azure.com:443","example.com:443"];var ANSWER_TIMEOUT_MS=1e4;var PROBE_EXIT={probed:0,misconfigured:2};async function probe(job){const header=job.env[AZURE_IDENTITY_ENV.header];const say=__name2(line=>job.say((0,import_contracts42.redactJwtShaped)((0,import_contracts42.redactSecrets)(`action-runtime probe: ${line}`,header?[header]:[]))),"say");const callback=job.env[import_contracts42.ACTION_CONTAINER_ENV.callbackBaseUrl];if(!callback){say(`refused to start \u2014 ${import_contracts42.ACTION_CONTAINER_ENV.callbackBaseUrl} not set.`);return PROBE_EXIT.misconfigured}const fetchOf=job.fetch??globalThis.fetch;const endpoint=job.env[AZURE_IDENTITY_ENV.endpoint];say(`identity endpoint ${endpoint?"present":"absent"}`);const identities=(job.env[import_contracts42.ACTION_PROBE_ENV.identities]??"").split(",").map(id=>id.trim()).filter(id=>id.length>0);for(const id of identities){const label=identityLabel(id);if(!endpoint){say(`identity ${label}: not asked \u2014 no endpoint`);continue}const answer2=await statusOf(()=>{const url=new URL(endpoint);url.searchParams.set("api-version",AZURE_IDENTITY_API_VERSION);url.searchParams.set("resource",MANAGEMENT_RESOURCE2);url.searchParams.set(id.startsWith("/")?"mi_res_id":"client_id",id);return fetchOf(url,{redirect:"error",headers:header?{"x-identity-header":header}:{}})});say(`identity ${label}: token request answered ${answer2}`)}const proxy=egressProxyUrl(job.env);if(!proxy){say("egress: no proxy in the environment")}else if(await neverListened(proxy,job)){say(`egress: the proxy did not listen within ${EGRESS_WAIT.timeoutMs/1e3} s`)}else{for(const target of PROBE_CONNECT_TARGETS){say(`egress CONNECT ${target}: ${await connectStatus(proxy,target,job.connect??import_node_net2.connect)}`)}}const health=await statusOf(()=>fetchOf(`${callback.replace(/\/+$/,"")}/healthz`,{redirect:"error"}));say(`callback GET /healthz: ${health}`);say("done");return PROBE_EXIT.probed}__name(probe,"probe");__name2(probe,"probe");function identityLabel(id){return id.split("/").filter(Boolean).pop()??id}__name(identityLabel,"identityLabel");__name2(identityLabel,"identityLabel");async function statusOf(request){try{const response=await withTimeout(request());await response.body?.cancel().catch(()=>void 0);return String(response.status)}catch{return"unreachable"}}__name(statusOf,"statusOf");__name2(statusOf,"statusOf");async function neverListened(proxy,job){try{await waitForEgressProxy(proxy,{connect:job.connect,clock:job.clock});return false}catch(error){return error instanceof EgressProxyNotListeningError}}__name(neverListened,"neverListened");__name2(neverListened,"neverListened");function connectStatus(proxy,target,connect){const address=egressProxyAddress(proxy);if(!address)return Promise.resolve("proxy is not a URL");return new Promise(resolve8=>{let settled=false;let received="";const socket=connect(address.port,address.host);const finish=__name2(answer2=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();resolve8(answer2)},"finish");const timer=setTimeout(()=>finish("no answer"),ANSWER_TIMEOUT_MS);socket.once("error",()=>finish("unreachable"));socket.once("connect",()=>socket.write(`CONNECT ${target} HTTP/1.1\r
6
6
  Host: ${target}\r
7
7
  \r
8
8
  `));socket.on("data",chunk=>{received+=chunk.toString("latin1");const end=received.indexOf("\r\n");if(end===-1)return;const code=/^HTTP\/1\.[01] (\d{3})\b/.exec(received.slice(0,end))?.[1];finish(code??"not an HTTP answer")});socket.once("close",()=>finish("closed without an answer"))})}__name(connectStatus,"connectStatus");__name2(connectStatus,"connectStatus");function withTimeout(promise){return new Promise((resolve8,reject)=>{const timer=setTimeout(()=>reject(new Error("timeout")),ANSWER_TIMEOUT_MS);promise.then(value=>{clearTimeout(timer);resolve8(value)},error=>{clearTimeout(timer);reject(error)})})}__name(withTimeout,"withTimeout");__name2(withTimeout,"withTimeout")}});var require_package_runtime_declaration=__commonJS({"../action-manifest/dist/package-runtime-declaration.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PackageRuntimeDeclarationError=void 0;exports.checkOciImageReference=checkOciImageReference;exports.normalizePackageRuntime=normalizePackageRuntime;var contracts_1=require_dist();var PackageRuntimeDeclarationError=class PackageRuntimeDeclarationError extends Error{static{__name(this,"PackageRuntimeDeclarationError")}constructor(message){super(message);this.name="PackageRuntimeDeclarationError"}};exports.PackageRuntimeDeclarationError=PackageRuntimeDeclarationError;var REGISTRY_HOST=String.raw`[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\d{1,5})?`;var PATH_COMPONENT=String.raw`[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*`;var IMAGE_NAME=new RegExp(String.raw`^(?:${REGISTRY_HOST}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*$`);var SHA256_DIGEST=/^sha256:[0-9a-f]{64}$/;var DIGEST_PIN_GUIDANCE=`${contracts_1.BRAND_SHORT_NAME} runs OCI actions only from a digest-pinned reference (<registry>/<repository>@sha256:<64 hex characters>). A digest names the exact image bytes, so a published action cannot change under the workspaces that adopted it; a tag is a mutable pointer and can be moved to different bytes at any time. Get the digest for an image you have published with \`docker buildx imagetools inspect <registry>/<repository>:<tag>\`, or for a local build with \`docker inspect --format='{{index .RepoDigests 0}}' <image>\`, then pin the \`@sha256:\u2026\` value it prints.`;function checkOciImageReference(image){if(typeof image!=="string"||image.trim().length===0){return{ok:false,message:`An OCI runtime requires an "image" reference. ${DIGEST_PIN_GUIDANCE}`}}if(image!==image.trim()){return{ok:false,message:`Image reference "${image}" has leading or trailing whitespace.`}}const separator=image.indexOf("@");if(separator===-1){const lastColon=image.lastIndexOf(":");const tagged=lastColon>image.lastIndexOf("/");return{ok:false,message:tagged?`Image reference "${image}" is pinned by tag, not by digest. ${DIGEST_PIN_GUIDANCE}`:`Image reference "${image}" has no digest. ${DIGEST_PIN_GUIDANCE}`}}const reference=image.slice(0,separator);const tagStart=reference.lastIndexOf(":")>reference.lastIndexOf("/")?reference.lastIndexOf(":"):-1;const name3=tagStart===-1?reference:reference.slice(0,tagStart);const digest=image.slice(separator+1);if(!IMAGE_NAME.test(name3)){return{ok:false,message:`Image reference "${image}" does not name a valid registry/repository: expected lowercase name components (letters, digits, and \`.\`, \`_\`, \`-\` separators) with an optional registry host and port, such as registry.example.com:5000/team/rotate-secret.`}}if(!SHA256_DIGEST.test(digest)){const colon=digest.indexOf(":");const algorithm=colon===-1?void 0:digest.slice(0,colon);return{ok:false,message:algorithm&&algorithm!=="sha256"?`Image reference "${image}" is pinned with the "${algorithm}" digest algorithm; ${contracts_1.BRAND_SHORT_NAME} requires sha256. ${DIGEST_PIN_GUIDANCE}`:`Image reference "${image}" has a malformed digest; expected sha256 followed by exactly 64 lowercase hex characters. ${DIGEST_PIN_GUIDANCE}`}}return{ok:true}}__name(checkOciImageReference,"checkOciImageReference");function normalizePackageRuntime(value){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new PackageRuntimeDeclarationError(`Package runtime must be an object, got ${describe(value)}.`)}const runtime=value;const kind=runtime.kind===void 0?legacyKind(runtime):runtime.kind;if(kind==="interpreter"){if(typeof runtime.name!=="string"||typeof runtime.version!=="string"){throw new PackageRuntimeDeclarationError('An interpreter runtime requires string "name" and "version" fields.')}return{kind:"interpreter",name:runtime.name,version:runtime.version}}if(kind==="oci"){if(typeof runtime.image!=="string"||runtime.image.length===0){throw new PackageRuntimeDeclarationError('An OCI runtime requires a string "image" field.')}return{kind:"oci",image:runtime.image}}throw new PackageRuntimeDeclarationError(`Package runtime kind ${describe(runtime.kind)} is not one of: ${contracts_1.PACKAGE_RUNTIME_KINDS.join(", ")}.`)}__name(normalizePackageRuntime,"normalizePackageRuntime");function legacyKind(runtime){return typeof runtime.name==="string"&&typeof runtime.version==="string"?"interpreter":void 0}__name(legacyKind,"legacyKind");function describe(value){if(value===void 0)return"undefined";if(value===null)return"null";if(Array.isArray(value))return"an array";return typeof value==="string"?`"${value}"`:typeof value}__name(describe,"describe")}});var require_manifest_schema=__commonJS({"../action-manifest/dist/manifest.schema.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PARAMETER_CONTROLS=exports.PARAMETER_PROPERTY_FIELDS=exports.PARAMETER_SCHEMA_FIELDS=exports.CREDENTIAL_SCOPE_PATTERN=exports.SPDX_ID_PATTERN=exports.DURATION_PATTERN=exports.SEMVER_PATTERN=exports.PACKAGE_ID_PATTERN=exports.MANIFEST_FIELDS=exports.RISK_LEVELS=exports.PROVIDERS=exports.ACTION_CATEGORIES=void 0;var contracts_1=require_dist();Object.defineProperty(exports,"ACTION_CATEGORIES",{enumerable:true,get:__name(function(){return contracts_1.ACTION_CATEGORIES},"get")});Object.defineProperty(exports,"PROVIDERS",{enumerable:true,get:__name(function(){return contracts_1.PROVIDERS},"get")});Object.defineProperty(exports,"RISK_LEVELS",{enumerable:true,get:__name(function(){return contracts_1.RISK_LEVELS},"get")});var contracts_2=require_dist();exports.MANIFEST_FIELDS=["apiVersion","id","name","author","version","summary","category","providers","connectorKey","runtime","executionTimeout","parametersRef","entrypoint","rollback","rollbackEntrypoint","validateEntrypoint","riskLevel","requiredPermissions","capabilities","requiresNetwork","egressAllowlist","secrets","credentialScopes","license","minRunvericVersion"];exports.PACKAGE_ID_PATTERN=/^[a-z0-9-]+\/[a-z0-9-]+$/;exports.SEMVER_PATTERN=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;exports.DURATION_PATTERN=/^[1-9]\d*(?:ms|s|m|h)$/;exports.SPDX_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9.-]*$/;exports.CREDENTIAL_SCOPE_PATTERN=/^https:\/\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+\/\.default$/;exports.PARAMETER_SCHEMA_FIELDS=["$schema","type","properties","required","additionalProperties",contracts_2.PARAMETER_ORDER_KEY];exports.PARAMETER_PROPERTY_FIELDS=["type","title","description","enum","default","control","discover","dependsOn","resourceType"];exports.PARAMETER_CONTROLS=["select","text","switch","info"]}});var require_manifest_validator=__commonJS({"../action-manifest/dist/manifest-validator.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parseAndValidateManifest=parseAndValidateManifest;exports.validateManifest=validateManifest;exports.validateParameterSchema=validateParameterSchema;exports.canonicalJson=canonicalJson;exports.sha256Hex=sha256Hex;exports.isSafeRelativePath=isSafeRelativePath;exports.isEgressDestination=isEgressDestination;var node_crypto_1=__require("crypto");var node_net_1=__require("net");var contracts_1=require_dist();var package_runtime_declaration_1=require_package_runtime_declaration();var contracts_2=require_dist();var yaml_1=__require("yaml");var manifest_schema_1=require_manifest_schema();function parseAndValidateManifest(source){const document=(0,yaml_1.parseDocument)(source,{uniqueKeys:true});if(document.errors.length>0){return{ok:false,errors:document.errors.map(error=>({path:"action.yaml",message:error.message,keyword:"yaml"}))}}return validateManifest(document.toJS())}__name(parseAndValidateManifest,"parseAndValidateManifest");function validateManifest(value){const errors=[];if(!isRecord(value)){return invalid("action.yaml","Expected a YAML object.","type")}rejectUnknown(value,manifest_schema_1.MANIFEST_FIELDS,"",errors);requiredConst(value,"apiVersion",contracts_2.ACTION_MANIFEST_API_VERSION,errors);requiredString(value,"id",errors,manifest_schema_1.PACKAGE_ID_PATTERN,"publisher/name");requiredString(value,"name",errors);requiredString(value,"author",errors);requiredString(value,"version",errors,manifest_schema_1.SEMVER_PATTERN,"MAJOR.MINOR.PATCH");const summary=requiredString(value,"summary",errors);if(summary&&summary.length>200)add(errors,"summary","Must be at most 200 characters.","maxLength");requiredEnum(value,"category",manifest_schema_1.ACTION_CATEGORIES,errors);requiredStringArray(value,"providers",errors,{nonEmpty:true,unique:true,values:manifest_schema_1.PROVIDERS});requiredString(value,"connectorKey",errors);const runtime=validateRuntime(value.runtime,errors);requiredString(value,"executionTimeout",errors,manifest_schema_1.DURATION_PATTERN,"a duration such as 5m");requiredSafePath(value,"parametersRef",errors,false);requiredSafePath(value,"entrypoint",errors,true);const rollback=requiredBoolean(value,"rollback",errors);if(rollback===true)requiredSafePath(value,"rollbackEntrypoint",errors,true);if(rollback===false&&value.rollbackEntrypoint!==void 0){add(errors,"rollbackEntrypoint","Must be absent when rollback is false.","conditional")}if(value.validateEntrypoint!==void 0)optionalSafePath(value,"validateEntrypoint",errors,true);requiredEnum(value,"riskLevel",manifest_schema_1.RISK_LEVELS,errors);validatePermissions(value.requiredPermissions,errors);validateCapabilities(value.capabilities,errors);if(typeof rollback==="boolean"&&isRecord(value.capabilities)&&typeof value.capabilities.rollback==="boolean"&&value.capabilities.rollback!==rollback){add(errors,"capabilities.rollback","Must match the top-level rollback declaration.","consistency")}const requiresNetwork=requiredBoolean(value,"requiresNetwork",errors);validateEgressAllowlist(value.egressAllowlist,requiresNetwork,errors);requiredStringArray(value,"secrets",errors,{unique:true});validateCredentialScopes(value.credentialScopes,errors);requiredString(value,"license",errors,manifest_schema_1.SPDX_ID_PATTERN,"an SPDX identifier");requiredString(value,"minRunvericVersion",errors,manifest_schema_1.SEMVER_PATTERN,"MAJOR.MINOR.PATCH");return errors.length===0&&runtime!==void 0?{ok:true,value:{...value,runtime},manifestHash:sha256Hex(canonicalJson(value)),warnings:[]}:{ok:false,errors}}__name(validateManifest,"validateManifest");function validateParameterSchema(value,context){const errors=[];const warnings=[];if(!isRecord(value))return invalid("parameters","Expected a JSON object.","type");rejectUnknown(value,manifest_schema_1.PARAMETER_SCHEMA_FIELDS,"parameters",errors);requiredConst(value,"$schema","https://json-schema.org/draft/2020-12/schema",errors,"parameters.$schema");requiredConst(value,"type","object",errors,"parameters.type");if(value.additionalProperties!==false){add(errors,"parameters.additionalProperties","Must be false.","const")}const normalizedProperties={};if(!isRecord(value.properties)){add(errors,"parameters.properties","Expected an object.","type")}else{const declarationOrder=Object.keys(value.properties);for(const[name3,property]of Object.entries(value.properties)){const declaredType=validateParameterProperty(name3,property,errors);normalizedProperties[name3]=isRecord(property)?validateDiscoveryAnnotations(name3,property,declaredType,value.properties,declarationOrder,context?.providers,errors,warnings):property}validateParameterOrder(value[contracts_1.PARAMETER_ORDER_KEY],contracts_1.PARAMETER_ORDER_KEY,declarationOrder,errors)}if(!Array.isArray(value.required)||!value.required.every(isString)){add(errors,"parameters.required","Expected an array of property names.","type")}else{const seen=new Set;for(const name3 of value.required){if(seen.has(name3))add(errors,"parameters.required",`Duplicate property "${name3}".`,"unique");seen.add(name3);if(!isRecord(value.properties)||!(name3 in value.properties)){add(errors,"parameters.required",`Unknown property "${name3}".`,"reference")}}}return errors.length===0?{ok:true,value:{...value,properties:normalizedProperties},warnings}:{ok:false,errors}}__name(validateParameterSchema,"validateParameterSchema");function canonicalJson(value){return JSON.stringify(sortJson(value))}__name(canonicalJson,"canonicalJson");function sha256Hex(value){return(0,node_crypto_1.createHash)("sha256").update(value).digest("hex")}__name(sha256Hex,"sha256Hex");function isSafeRelativePath(value){if(!value||value.startsWith("/")||value.includes("\\")||value.includes("\0"))return false;const parts=value.split("/").filter(Boolean);return parts.length>0&&parts.every(part=>part!=="."&&part!=="..")}__name(isSafeRelativePath,"isSafeRelativePath");function validateEgressAllowlist(value,requiresNetwork,errors){if(value===void 0){if(requiresNetwork===true){add(errors,"egressAllowlist","A non-empty allowlist is required when network access is enabled.","conditional")}return}if(!Array.isArray(value)||!value.every(isString)){add(errors,"egressAllowlist","Expected an array of host or host:port strings.","type");return}if(value.length>64)add(errors,"egressAllowlist","Must contain at most 64 destinations.","maxItems");if(new Set(value).size!==value.length)add(errors,"egressAllowlist","Items must be unique.","uniqueItems");if(requiresNetwork===false&&value.length>0){add(errors,"egressAllowlist","Must be empty when network access is disabled.","conditional")}if(requiresNetwork===true&&value.length===0){add(errors,"egressAllowlist","A non-empty allowlist is required when network access is enabled.","conditional")}value.forEach((destination,index)=>{if(!isEgressDestination(destination)){add(errors,`egressAllowlist.${index}`,"Expected a lowercase public DNS name with an optional port; schemes, paths, IPs, and local names are forbidden.","pattern")}})}__name(validateEgressAllowlist,"validateEgressAllowlist");function validateCredentialScopes(value,errors){if(value===void 0)return;if(!Array.isArray(value)||!value.every(isString)){add(errors,"credentialScopes","Expected an array of AAD scope strings.","type");return}if(value.length===0)add(errors,"credentialScopes","Must be omitted rather than empty.","minItems");if(value.length>8)add(errors,"credentialScopes","Must contain at most 8 scopes.","maxItems");if(new Set(value).size!==value.length)add(errors,"credentialScopes","Items must be unique.","uniqueItems");value.forEach((scope,index)=>{if(!manifest_schema_1.CREDENTIAL_SCOPE_PATTERN.test(scope)){add(errors,`credentialScopes.${index}`,"Expected a least-privilege AAD scope such as https://vault.azure.net/.default.","pattern")}})}__name(validateCredentialScopes,"validateCredentialScopes");function isEgressDestination(destination){if(destination.length===0||destination.length>253||destination!==destination.toLowerCase()){return false}if(destination.includes("://")||destination.includes("/")||destination.includes("@"))return false;const withoutWildcard=destination.startsWith("*.")?destination.slice(2):destination;const host=withoutWildcard.replace(/:\d+$/,"");if((0,node_net_1.isIP)(host)!==0||host==="localhost"||host.endsWith(".localhost")||host.endsWith(".local")){return false}const match=/^(?:\*\.)?([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)(?::([1-9]\d{0,4}))?$/.exec(destination);if(!match)return false;const port=match[2]?Number(match[2]):void 0;return port===void 0||port<=65535}__name(isEgressDestination,"isEgressDestination");function validateRuntime(value,errors){if(!isRecord(value)){add(errors,"runtime","Expected an object.","type");return void 0}const before=errors.length;if(value.kind!==void 0&&!contracts_1.PACKAGE_RUNTIME_KINDS.includes(value.kind)){add(errors,"runtime.kind",`Must be one of: ${contracts_1.PACKAGE_RUNTIME_KINDS.join(", ")}.`,"enum");return void 0}if(value.kind==="oci"){rejectUnknown(value,["kind","image"],"runtime",errors);const image=requiredString(value,"image",errors,void 0,void 0,"runtime.image");if(image!==void 0){const check=(0,package_runtime_declaration_1.checkOciImageReference)(image);if(!check.ok)add(errors,"runtime.image",check.message,"digestPinned")}}else{rejectUnknown(value,["kind","name","version"],"runtime",errors);requiredEnum(value,"name",contracts_1.PACKAGE_INTERPRETERS,errors,"runtime.name");requiredString(value,"version",errors,void 0,void 0,"runtime.version")}return errors.length===before?(0,package_runtime_declaration_1.normalizePackageRuntime)(value):void 0}__name(validateRuntime,"validateRuntime");function validateCapabilities(value,errors){if(!isRecord(value)){add(errors,"capabilities","Expected an object.","type");return}rejectUnknown(value,["dryRun","idempotent","rollback"],"capabilities",errors);for(const key of["dryRun","idempotent","rollback"]){requiredBoolean(value,key,errors,`capabilities.${key}`)}}__name(validateCapabilities,"validateCapabilities");function validatePermissions(value,errors){if(!Array.isArray(value)){add(errors,"requiredPermissions","Expected an array.","type");return}value.forEach((permission,index)=>{const path=`requiredPermissions.${index}`;if(!isRecord(permission)){add(errors,path,"Expected an object.","type");return}rejectUnknown(permission,["provider","actions","scope"],path,errors);requiredEnum(permission,"provider",manifest_schema_1.PROVIDERS,errors,`${path}.provider`);requiredStringArray(permission,"actions",errors,{nonEmpty:true,unique:true,path:`${path}.actions`});requiredString(permission,"scope",errors,void 0,void 0,`${path}.scope`)})}__name(validatePermissions,"validatePermissions");function validateParameterProperty(name3,value,errors){const path=`parameters.properties.${name3}`;if(!isRecord(value)){add(errors,path,"Expected an object.","type");return void 0}rejectUnknown(value,manifest_schema_1.PARAMETER_PROPERTY_FIELDS,path,errors);const type=requiredEnum(value,"type",["string","boolean"],errors,`${path}.type`);requiredString(value,"title",errors,void 0,void 0,`${path}.title`);if(value.description!==void 0&&!isString(value.description))add(errors,`${path}.description`,"Expected a string.","type");requiredEnum(value,"control",manifest_schema_1.PARAMETER_CONTROLS,errors,`${path}.control`);if(value.enum!==void 0){if(!Array.isArray(value.enum)||!value.enum.every(isString))add(errors,`${path}.enum`,"Expected an array of strings.","type");else if(type==="boolean")add(errors,`${path}.enum`,"Boolean properties cannot declare string enum values.","type");else{if(value.enum.length===0)add(errors,`${path}.enum`,"Must contain at least one value.","minItems");if(new Set(value.enum).size!==value.enum.length)add(errors,`${path}.enum`,"Values must be unique.","uniqueItems");if(isString(value.default)&&!value.enum.includes(value.default)){add(errors,`${path}.default`,"Default must be one of the enum values.","enum")}}}if(value.default!==void 0&&type&&typeof value.default!==type){add(errors,`${path}.default`,`Expected a ${type}.`,"type")}return type}__name(validateParameterProperty,"validateParameterProperty");function validateDiscoveryAnnotations(name3,property,declaredType,properties,declarationOrder,providers,errors,warnings){const path=`parameters.properties.${name3}`;let normalized=property;let resolved=null;const errorsBeforeDiscover=errors.length;if(property.discover!==void 0){const match=isString(property.discover)?contracts_1.DISCOVERY_TYPE_PATTERN.exec(property.discover):null;if(!match){add(errors,`${path}.discover`,'Expected "provider/resourceType" (e.g. "azure/virtualMachine") or a bare resource type.',"pattern")}else if(declaredType==="boolean"){add(errors,`${path}.discover`,"Discovery applies only to string parameters.","type")}else{const[,prefix,type]=match;if(prefix!==void 0){const provider=manifest_schema_1.PROVIDERS.find(p=>p===prefix);if(!provider){add(errors,`${path}.discover`,`Unknown provider namespace "${prefix}".`,"enum")}else if(providers&&!providers.includes(provider)){add(errors,`${path}.discover`,`Discovery provider "${provider}" is not declared in the manifest's providers.`,"providerMismatch")}else{resolved={provider,type}}}else if(providers){if(providers.length===1){resolved={provider:providers[0],type};normalized={...property,discover:(0,contracts_1.formatDiscoveryType)(resolved.provider,resolved.type)}}else{add(errors,`${path}.discover`,'Bare discovery types are ambiguous in a multi-provider package; use "provider/type".',"ambiguous")}}if(resolved&&providers&&!(0,contracts_1.discoveryTypeSpec)(resolved.provider,resolved.type)){warnings.push({path:`${path}.discover`,message:`"${(0,contracts_1.formatDiscoveryType)(resolved.provider,resolved.type)}" is not implemented by this ${contracts_1.BRAND_SHORT_NAME} version; the field will render as free text.`,keyword:"unknownDiscoveryType"})}}}if(errors.length===errorsBeforeDiscover){const discover=resolved?(0,contracts_1.formatDiscoveryType)(resolved.provider,resolved.type):isString(property.discover)?property.discover:void 0;const refusal=(0,contracts_1.resourceTypeDeclarationRefusal)(discover,property.resourceType);if(refusal!==null)add(errors,`${path}.resourceType`,refusal,"resourceType")}let covers;if(property.dependsOn===void 0){covers=__name(()=>false,"covers")}else if(Array.isArray(property.dependsOn)&&property.dependsOn.every(isString)){const names=property.dependsOn;for(const dependency of names){validateDependency(name3,dependency,properties,declarationOrder,path,errors)}covers=__name(scopeKey=>names.includes(scopeKey),"covers")}else if(isRecord(property.dependsOn)&&Object.values(property.dependsOn).every(isString)){const mapping=property.dependsOn;for(const dependency of Object.values(mapping)){validateDependency(name3,dependency,properties,declarationOrder,path,errors)}covers=__name(scopeKey=>scopeKey in mapping,"covers")}else{add(errors,`${path}.dependsOn`,"Expected an array of property names or an object mapping scope keys to property names.","type")}if(resolved&&covers){const spec=(0,contracts_1.discoveryTypeSpec)(resolved.provider,resolved.type);const missing=spec?.requires.filter(scopeKey=>!covers(scopeKey))??[];if(missing.length>0){warnings.push({path:`${path}.dependsOn`,message:`Discovery of "${(0,contracts_1.formatDiscoveryType)(resolved.provider,resolved.type)}" needs scope key(s) ${missing.map(scopeKey=>`"${scopeKey}"`).join(", ")}; declare them in dependsOn or the picker will stay empty.`,keyword:"cascadeScopeMissing"})}}return normalized}__name(validateDiscoveryAnnotations,"validateDiscoveryAnnotations");function validateDependency(name3,dependency,properties,declarationOrder,path,errors){if(dependency===name3){add(errors,`${path}.dependsOn`,"A property cannot depend on itself.","reference");return}if(!(dependency in properties)){add(errors,`${path}.dependsOn`,`Unknown property "${dependency}".`,"reference");return}if(declarationOrder.indexOf(dependency)>declarationOrder.indexOf(name3)){add(errors,`${path}.dependsOn`,`"${name3}" depends on "${dependency}", which is declared after it. Parameters are shown in the order you declare them, so "${dependency}" must be declared before "${name3}" \u2014 otherwise the form asks for "${name3}" before the value that scopes it.`,"order")}}__name(validateDependency,"validateDependency");function validateParameterOrder(value,key,declarationOrder,errors){if(value===void 0)return;const path=`parameters.${key}`;if(!Array.isArray(value)||!value.every(isString)){add(errors,path,"Expected an array of property names.","type");return}if(value.length!==declarationOrder.length||value.some((name3,index)=>name3!==declarationOrder[index])){add(errors,path,`Must list every property exactly once, in the order the properties are declared (${declarationOrder.join(", ")}). ${contracts_1.BRAND_SHORT_NAME} writes this field at import to preserve your field order through storage; it is not a second place to choose an order.`,"consistency")}}__name(validateParameterOrder,"validateParameterOrder");function requiredSafePath(record,key,errors,directory){const value=requiredString(record,key,errors);if(value&&(!isSafeRelativePath(value)||directory&&!value.endsWith("/"))){add(errors,key,directory?"Expected a safe relative directory path ending in /.":"Expected a safe relative file path.","path")}return value}__name(requiredSafePath,"requiredSafePath");function optionalSafePath(record,key,errors,directory){if(!isString(record[key])||!record[key])add(errors,key,"Expected a non-empty string.","type");else if(!isSafeRelativePath(record[key])||directory&&!record[key].endsWith("/"))add(errors,key,"Expected a safe relative directory path ending in /.","path")}__name(optionalSafePath,"optionalSafePath");function requiredString(record,key,errors,pattern,expected,path=key){const value=record[key];if(!isString(value)||value.trim().length===0){add(errors,path,"Expected a non-empty string.","required");return void 0}if(pattern&&!pattern.test(value))add(errors,path,`Expected ${expected??"the required format"}.`,"pattern");return value}__name(requiredString,"requiredString");function requiredBoolean(record,key,errors,path=key){if(typeof record[key]!=="boolean"){add(errors,path,"Expected a boolean.","type");return void 0}return record[key]}__name(requiredBoolean,"requiredBoolean");function requiredConst(record,key,expected,errors,path=key){if(record[key]!==expected)add(errors,path,`Must equal "${expected}".`,"const")}__name(requiredConst,"requiredConst");function requiredEnum(record,key,values,errors,path=key){const value=record[key];if(!isString(value)||!values.includes(value)){add(errors,path,`Must be one of: ${values.join(", ")}.`,"enum");return void 0}return value}__name(requiredEnum,"requiredEnum");function requiredStringArray(record,key,errors,options={}){const path=options.path??key;const value=record[key];if(!Array.isArray(value)||!value.every(isString)){add(errors,path,"Expected an array of strings.","type");return void 0}if(options.nonEmpty&&value.length===0)add(errors,path,"Must contain at least one item.","minItems");value.forEach((item,index)=>{if(item.trim().length===0)add(errors,`${path}.${index}`,"Expected a non-empty string.","minLength")});if(options.unique&&new Set(value).size!==value.length)add(errors,path,"Items must be unique.","uniqueItems");const allowedValues=options.values;if(allowedValues)value.forEach((item,index)=>{if(!allowedValues.includes(item))add(errors,`${path}.${index}`,`Must be one of: ${allowedValues.join(", ")}.`,"enum")});return value}__name(requiredStringArray,"requiredStringArray");function rejectUnknown(record,fields,prefix,errors){for(const key of Object.keys(record))if(!fields.includes(key))add(errors,prefix?`${prefix}.${key}`:key,"Unknown field.","additionalProperties")}__name(rejectUnknown,"rejectUnknown");function add(errors,path,message,keyword){errors.push({path,message,...keyword?{keyword}:{}})}__name(add,"add");function invalid(path,message,keyword){return{ok:false,errors:[{path,message,keyword}]}}__name(invalid,"invalid");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function isString(value){return typeof value==="string"}__name(isString,"isString");function sortJson(value){if(Array.isArray(value))return value.map(sortJson);if(!isRecord(value))return value;return Object.fromEntries(Object.keys(value).sort().map(key=>[key,sortJson(value[key])]))}__name(sortJson,"sortJson")}});var require_package_result_validator=__commonJS({"../action-manifest/dist/package-result-validator.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PackageProtocolError=void 0;exports.validatePackageResult=validatePackageResult2;var contracts_1=require_dist();var RESULT_FIELDS=["protocolVersion","status","message","checks","outputs","rollbackCapture","error"];var CHECK_FIELDS=["status","message","data"];var ERROR_FIELDS=["code","message","retryable"];var MAX_MESSAGE_LENGTH=4096;var MAX_CHECKS=100;var MAX_JSON_DEPTH=16;var MAX_JSON_KEYS=1e3;var PackageProtocolError=class PackageProtocolError extends Error{static{__name(this,"PackageProtocolError")}constructor(message){super(message);this.name="PackageProtocolError"}};exports.PackageProtocolError=PackageProtocolError;function validatePackageResult2(value,phase){const result=record(value,"result");rejectUnknown(result,RESULT_FIELDS,"result");if(result.protocolVersion!==contracts_1.PACKAGE_RESULT_PROTOCOL_VERSION){fail(`result.protocolVersion must equal "${contracts_1.PACKAGE_RESULT_PROTOCOL_VERSION}".`)}if(!isOneOf(result.status,["succeeded","failed","cancelled"])){fail("result.status must be succeeded, failed, or cancelled.")}requiredBoundedString(result.message,"result.message");const checks=result.checks===void 0?void 0:validateChecks(result.checks);const outputs=result.outputs===void 0?void 0:jsonObject(result.outputs,"result.outputs");const rollbackCapture=result.rollbackCapture===void 0?void 0:jsonObject(result.rollbackCapture,"result.rollbackCapture");const error=result.error===void 0||result.error===null?result.error:validateError(result.error);if(phase==="validate"){if(outputs!==void 0||rollbackCapture!==void 0){fail("Validate results cannot contain outputs or rollbackCapture.")}}else if(checks!==void 0){fail(`${phase} results cannot contain validation checks.`)}if(phase!=="run"&&rollbackCapture!==void 0){fail("rollbackCapture is allowed only in run results.")}if(result.status==="failed"&&error===void 0){const reportedByChecks=phase==="validate"&&(checks??[]).some(check=>check.status==="failed");if(!reportedByChecks){fail(phase==="validate"?'A failed validate result must contain result.error, or at least one entry in result.checks with status "failed".':`A failed ${phase} result must contain result.error.`)}}if(result.status!=="failed"&&error!==void 0&&error!==null){fail("Only a failed result may contain result.error.")}return{protocolVersion:contracts_1.PACKAGE_RESULT_PROTOCOL_VERSION,status:result.status,message:result.message,...checks?{checks}:{},...outputs?{outputs}:{},...rollbackCapture?{rollbackCapture}:{},...error!==void 0?{error}:{}}}__name(validatePackageResult2,"validatePackageResult");function validateChecks(value){if(!Array.isArray(value)||value.length>MAX_CHECKS){fail(`result.checks must be an array of at most ${MAX_CHECKS} checks.`)}return value.map((item,index)=>{const check=record(item,`result.checks.${index}`);rejectUnknown(check,CHECK_FIELDS,`result.checks.${index}`);if(!isOneOf(check.status,["passed","warning","failed"])){fail(`result.checks.${index}.status is invalid.`)}requiredBoundedString(check.message,`result.checks.${index}.message`);const data=check.data===void 0?void 0:jsonObject(check.data,`result.checks.${index}.data`);return{status:check.status,message:check.message,...data?{data}:{}}})}__name(validateChecks,"validateChecks");function validateError(value){const error=record(value,"result.error");rejectUnknown(error,ERROR_FIELDS,"result.error");requiredBoundedString(error.code,"result.error.code");requiredBoundedString(error.message,"result.error.message");if(error.retryable!==void 0&&typeof error.retryable!=="boolean"){fail("result.error.retryable must be a boolean.")}return{code:error.code,message:error.message,...typeof error.retryable==="boolean"?{retryable:error.retryable}:{}}}__name(validateError,"validateError");function jsonObject(value,path){const object=record(value,path);let keys=0;validateJson(object,path,0,()=>{keys+=1;if(keys>MAX_JSON_KEYS)fail(`${path} contains too many keys.`)});return object}__name(jsonObject,"jsonObject");function validateJson(value,path,depth,keySeen){if(depth>MAX_JSON_DEPTH)fail(`${path} exceeds the maximum JSON depth.`);if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value)){return}if(Array.isArray(value)){value.forEach((item,index)=>validateJson(item,`${path}.${index}`,depth+1,keySeen));return}if(typeof value==="object"&&value!==null){for(const[key,nested]of Object.entries(value)){keySeen();validateJson(nested,`${path}.${key}`,depth+1,keySeen)}return}fail(`${path} must contain JSON values only.`)}__name(validateJson,"validateJson");function record(value,path){if(typeof value!=="object"||value===null||Array.isArray(value)){fail(`${path} must be an object.`)}return value}__name(record,"record");function rejectUnknown(value,fields,path){for(const key of Object.keys(value)){if(!fields.includes(key))fail(`${path}.${key} is not allowed.`)}}__name(rejectUnknown,"rejectUnknown");function requiredBoundedString(value,path){if(typeof value!=="string"||value.length===0||value.length>MAX_MESSAGE_LENGTH){fail(`${path} must be a non-empty string of at most ${MAX_MESSAGE_LENGTH} characters.`)}}__name(requiredBoundedString,"requiredBoundedString");function isOneOf(value,allowed){return typeof value==="string"&&allowed.includes(value)}__name(isOneOf,"isOneOf");function fail(message){throw new PackageProtocolError(message)}__name(fail,"fail")}});var require_package_validation=__commonJS({"../action-manifest/dist/package-validation.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.REQUIRED_PACKAGE_FILES=exports.MANIFEST_FILE=void 0;exports.validateActionPackage=validateActionPackage;var contracts_1=require_dist();var manifest_validator_1=require_manifest_validator();exports.MANIFEST_FILE="action.yaml";exports.REQUIRED_PACKAGE_FILES=["README.md","LICENSE"];function validateActionPackage(files){const errors=[];const warnings=[];const manifestSource=files.get(exports.MANIFEST_FILE);if(!manifestSource){return{ok:false,errors:[{path:exports.MANIFEST_FILE,message:"Required file is missing.",keyword:"required"}],warnings}}const parsed=(0,manifest_validator_1.parseAndValidateManifest)(manifestSource.toString("utf8"));const manifest=parsed.ok?parsed.value:void 0;if(parsed.ok)warnings.push(...parsed.warnings);else errors.push(...parsed.errors);errors.push(...layoutErrors(files,manifest));let parameterSchema;if(manifest){const schema=parameterSchemaOf(files,manifest.parametersRef,manifest.providers);if(schema.ok){parameterSchema=schema.value;warnings.push(...schema.warnings)}else{errors.push(...schema.errors)}}if(errors.length===0&&manifest&&parsed.ok&&parameterSchema){return{ok:true,errors:[],warnings,manifest,manifestHash:parsed.manifestHash,parameterSchema}}return{ok:false,errors:errors.length>0?errors:[{path:exports.MANIFEST_FILE,message:`The package could not be validated, and no specific problem was reported. This is ${contracts_1.BRAND_ARTICLE} ${contracts_1.BRAND_SHORT_NAME} defect, not a problem with the package.`,keyword:"internal"}],warnings,...manifest?{manifest}:{},...parsed.ok?{manifestHash:parsed.manifestHash}:{},...parameterSchema?{parameterSchema}:{}}}__name(validateActionPackage,"validateActionPackage");function layoutErrors(files,manifest){const errors=[];for(const required of exports.REQUIRED_PACKAGE_FILES){if(!files.has(required)){errors.push({path:required,message:"Required file is missing.",keyword:"required"})}}if(!manifest)return errors;const entrypoints=[manifest.entrypoint,manifest.rollbackEntrypoint,manifest.validateEntrypoint];for(const path of entrypoints){if(path&&![...files.keys()].some(file=>file.startsWith(path))){errors.push({path,message:"Entrypoint directory is missing or empty.",keyword:"reference"})}}return errors}__name(layoutErrors,"layoutErrors");function parameterSchemaOf(files,reference,providers){const file=files.get(reference);if(!file){return{ok:false,errors:[{path:"parametersRef",message:`Referenced file "${reference}" is missing.`,keyword:"reference"}]}}let value;try{value=JSON.parse(file.toString("utf8"))}catch{return{ok:false,errors:[{path:reference,message:"File is not valid JSON.",keyword:"json"}]}}const validated=(0,manifest_validator_1.validateParameterSchema)(value,{providers});if(!validated.ok)return validated;return{...validated,value:(0,contracts_1.withParameterOrder)(validated.value)}}__name(parameterSchemaOf,"parameterSchemaOf")}});var require_source_location=__commonJS({"../action-manifest/dist/source-location.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.pathSegments=pathSegments;exports.locate=locate;exports.offsetToLocation=offsetToLocation;var yaml_1=__require("yaml");function pathSegments(path){return path.split(".").filter(segment=>segment.length>0).map(segment=>/^\d+$/.test(segment)?Number(segment):segment)}__name(pathSegments,"pathSegments");function locate(source,path){const segments=pathSegments(path);let document;try{document=(0,yaml_1.parseDocument)(source)}catch{return null}if(document.errors.length>0)return null;let node=null;for(let depth=segments.length;depth>0;depth-=1){node=document.getIn(segments.slice(0,depth),true);if(isRangedNode(node))break;node=null}if(!isRangedNode(node)){return segments.length===0?{line:1,column:1}:null}return offsetToLocation(source,node.range[0])}__name(locate,"locate");function offsetToLocation(source,offset){const before=source.slice(0,Math.max(0,Math.min(offset,source.length)));const lines=before.split("\n");return{line:lines.length,column:(lines[lines.length-1]?.length??0)+1}}__name(offsetToLocation,"offsetToLocation");function isRangedNode(value){return typeof value==="object"&&value!==null&&"range"in value&&Array.isArray(value.range)&&typeof value.range[0]==="number"}__name(isRangedNode,"isRangedNode")}});var require_findings=__commonJS({"../action-manifest/dist/findings.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.findingFromValidation=findingFromValidation;exports.mergeFindings=mergeFindings;exports.sortFindings=sortFindings;var source_location_1=require_source_location();var contracts_1=require_dist();var FIX_BY_KEYWORD={yaml:"Fix the YAML syntax \u2014 the file could not be parsed at all, so nothing else was checked.",json:"Fix the JSON syntax \u2014 the file could not be parsed at all.",required:"Add this field. Every manifest field is required unless it is documented optional.",type:"Change the value to the type this field expects.",pattern:"Rewrite the value in the format named above.",const:"This field has exactly one legal value; use it verbatim.",enum:"Use one of the listed values \u2014 the vocabulary is closed, so anything else is refused at import.",minItems:"Add at least one item, or remove the field entirely if it is optional.",maxItems:"Remove items until the list is within the limit.",minLength:"Replace the empty entry with a real value, or remove it.",maxLength:"Shorten the value.",uniqueItems:"Remove the duplicate entries.",additionalProperties:"Remove this field. The manifest vocabulary is closed, so an unknown key is either a typo or a field that does not exist \u2014 both silently do nothing at run time.",conditional:"Make the two fields agree; one of them is describing a package the other is not.",consistency:"Make the two declarations agree.",reference:"Point this at something that exists in the package.",path:"Use a safe relative path inside the package (no leading /, no .., directories end in /).",order:"Move the declaration so the parameter it depends on comes first.",digestPinned:"Pin the image by digest (`registry/repo@sha256:\u2026`). A tag is a mutable pointer; a digest is the content, and only the second is reproducible.",providerMismatch:"Add the provider to `providers`, or discover from one already declared.",ambiguous:'Qualify the discovery type as "provider/type".',runnerCapability:"Either drop the capability from the manifest, or ask an administrator to enable the runtime feature named above on this deployment.",untrustedCapability:`Import through a tenant-owned Git source, or author the package in ${contracts_1.BRAND_SHORT_NAME} \u2014 both reach organization tier, which may declare these.`,organizationCapability:"Ask an administrator to enable organization-package sandboxing on this deployment.",unknownDiscoveryType:`Leave it if the type is coming; the field renders as free text until this ${contracts_1.BRAND_SHORT_NAME} version implements it.`,cascadeScopeMissing:"Add the named scope keys to `dependsOn`, or the picker will stay empty."};var GENERIC_FIX="Correct the value this field is reported on.";function findingFromValidation(problem,options){const prefix=options.pathPrefix?`${options.pathPrefix}.`:"";const documentPath=problem.path.startsWith(prefix)?problem.path.slice(prefix.length):problem.path;const at=(0,source_location_1.locate)(options.source,documentPath);return{severity:options.severity,rule:`manifest/${problem.keyword??"invalid"}`,file:options.file,...at?{line:at.line,column:at.column}:{},message:`${problem.path}: ${problem.message}`,fix:(problem.keyword&&FIX_BY_KEYWORD[problem.keyword])??GENERIC_FIX,subject:problem.path}}__name(findingFromValidation,"findingFromValidation");function mergeFindings(...groups){const bySubject=new Map;const unkeyed=[];for(const finding of groups.flat()){if(finding.subject===void 0){unkeyed.push(finding);continue}const existing=bySubject.get(finding.subject);if(!existing||existing.line===void 0&&finding.line!==void 0){bySubject.set(finding.subject,finding)}}return sortFindings([...bySubject.values(),...unkeyed])}__name(mergeFindings,"mergeFindings");function sortFindings(findings){const rank=__name(severity=>severity==="error"?0:1,"rank");return[...findings].sort((left,right)=>rank(left.severity)-rank(right.severity)||left.file.localeCompare(right.file)||(left.line??Number.MAX_SAFE_INTEGER)-(right.line??Number.MAX_SAFE_INTEGER)||left.rule.localeCompare(right.rule))}__name(sortFindings,"sortFindings")}});var require_interpreter_launch=__commonJS({"../action-manifest/dist/interpreter-launch.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PACKAGE_INTERPRETER_EXTENSIONS=exports.PACKAGE_INTERPRETER_LAUNCH=void 0;exports.interpreterEntryFileList=interpreterEntryFileList;exports.interpreterForPath=interpreterForPath;var contracts_1=require_dist();exports.PACKAGE_INTERPRETER_LAUNCH={powershell:{fileName:"/usr/local/bin/pwsh",arguments:["-NoLogo","-NoProfile","-NonInteractive","-File"],entryFile:"main.ps1",bodyFile:"body.ps1"},bash:{fileName:"/bin/bash",arguments:["-euo","pipefail"],entryFile:"main.sh",bodyFile:"body.sh"},python:{fileName:"/usr/bin/python3",arguments:["-u"],entryFile:"main.py",bodyFile:"body.py"}};function interpreterEntryFileList(){return contracts_1.PACKAGE_INTERPRETERS.map(name3=>`${name3} \u2192 ${exports.PACKAGE_INTERPRETER_LAUNCH[name3].entryFile}`).join(", ")}__name(interpreterEntryFileList,"interpreterEntryFileList");exports.PACKAGE_INTERPRETER_EXTENSIONS={powershell:extensionOf(exports.PACKAGE_INTERPRETER_LAUNCH.powershell.entryFile),bash:extensionOf(exports.PACKAGE_INTERPRETER_LAUNCH.bash.entryFile),python:extensionOf(exports.PACKAGE_INTERPRETER_LAUNCH.python.entryFile)};function extensionOf(entryFile){const dot=entryFile.lastIndexOf(".");if(dot<=0)throw new Error(`Entry file "${entryFile}" has no extension.`);return entryFile.slice(dot)}__name(extensionOf,"extensionOf");function interpreterForPath(path){const lower=path.toLowerCase();return contracts_1.PACKAGE_INTERPRETERS.find(name3=>lower.endsWith(exports.PACKAGE_INTERPRETER_EXTENSIONS[name3]))??null}__name(interpreterForPath,"interpreterForPath")}});var require_authoring_lint=__commonJS({"../action-manifest/dist/authoring-lint.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.lintActionPackage=lintActionPackage;var contracts_1=require_dist();var findings_1=require_findings();var interpreter_launch_1=require_interpreter_launch();var source_location_1=require_source_location();var MANIFEST_FILE="action.yaml";function lintActionPackage(input){return(0,findings_1.sortFindings)([...lintPowerShellOptionalVariable(input),...lintEntrypointFiles(input),...lintDependsOnOrder(input),...lintNetworkAllowlist(input),...lintPermissionProviders(input),...lintUnusedPermissions(input),...lintUnreferencedEgressHosts(input),...lintPhaseWritesNoResult(input)])}__name(lintActionPackage,"lintActionPackage");function lintPowerShellOptionalVariable(input){const findings=[];const pattern=/(?<!`)\$(?!\{)([A-Za-z_][A-Za-z0-9_]*)\?/g;for(const[file,source]of input.files){if(!file.endsWith(".ps1"))continue;source.split(/\r?\n/).forEach((text,index)=>{if(text.trimStart().startsWith("#"))return;for(const match of text.matchAll(pattern)){const name3=match[1];findings.push({severity:"error",rule:"powershell/optional-variable",file,line:index+1,column:(match.index??0)+1,message:`"$${name3}?" is read by PowerShell as a variable named "${name3}?", not as $${name3} followed by a question mark. "${name3}?" is undefined, so it expands to nothing and the value silently disappears from the output.`,fix:`Write \${${name3}}? \u2014 the braces end the variable name before the "?".`})}})}return findings}__name(lintPowerShellOptionalVariable,"lintPowerShellOptionalVariable");function lintEntrypointFiles(input){const manifest=input.manifest;if(!manifest)return[];const runtime=manifest.runtime;if(typeof runtime!=="object"||runtime===null||Array.isArray(runtime))return[];const declaration=runtime;if(declaration.kind==="oci")return[];const name3=declaration.name;if(typeof name3!=="string"||!isInterpreter2(name3))return[];const entryFile=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[name3].entryFile;const findings=[];for(const{field,phase}of ENTRYPOINT_PHASES){const directory=manifest[field];if(typeof directory!=="string"||directory.length===0)continue;const expected=`${directory}${entryFile}`;if(input.files.has(expected))continue;const present=[...input.files.keys()].filter(path=>path.startsWith(directory));const misnamed=present.find(path=>contracts_1.PACKAGE_INTERPRETERS.some(other=>path===`${directory}${interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[other].entryFile}`));findings.push({severity:"error",rule:"package/entrypoint-file-missing",file:MANIFEST_FILE,...input.manifestSource?locationOf(input.manifestSource,field):{},message:`This package declares runtime "${name3}", so its ${phase} phase runs "${expected}" \u2014 `+(misnamed?`and the package ships "${misnamed}" instead.`:present.length===0?`and "${directory}" contains no files at all.`:`and "${directory}" contains ${present.join(", ")}.`),fix:misnamed?`Rename "${misnamed}" to "${expected}", or change runtime.name to the interpreter that file is written for.`:`Add "${expected}".`})}return findings}__name(lintEntrypointFiles,"lintEntrypointFiles");function lintDependsOnOrder(input){const reference=input.manifest?.parametersRef;if(typeof reference!=="string")return[];const source=input.files.get(reference);if(source===void 0)return[];let schema;try{schema=JSON.parse(source)}catch{return[]}if(!isRecord(schema)||!isRecord(schema.properties))return[];const order=Object.keys(schema.properties);const findings=[];for(const[name3,property]of Object.entries(schema.properties)){if(!isRecord(property))continue;for(const dependency of dependencyNames(property.dependsOn)){if(!order.includes(dependency))continue;if(order.indexOf(dependency)<=order.indexOf(name3))continue;const path=`properties.${name3}.dependsOn`;findings.push({severity:"error",rule:"parameters/depends-on-declared-later",file:reference,...locationOf(source,path),message:`"${name3}" depends on "${dependency}", which is declared after it. Parameters are shown in the order you declare them, so the form would ask for "${name3}" before the value that scopes it.`,fix:`Move "${dependency}" above "${name3}" in the properties object.`,subject:`parameters.${path}`})}}return findings}__name(lintDependsOnOrder,"lintDependsOnOrder");function lintNetworkAllowlist(input){const manifest=input.manifest;if(!manifest||manifest.requiresNetwork!==true)return[];const allowlist=manifest.egressAllowlist;if(Array.isArray(allowlist)&&allowlist.length>0)return[];return[{severity:"error",rule:"package/network-without-allowlist",file:MANIFEST_FILE,...input.manifestSource?locationOf(input.manifestSource,"requiresNetwork"):{},message:`This package declares outbound network access but names no destinations. ${contracts_1.BRAND_SHORT_NAME} never runs a network package without its allowlist in force, so there is nothing it could be allowed to reach.`,fix:"List the hosts the script actually contacts in `egressAllowlist` (e.g. `api.example.com`), or set `requiresNetwork: false`.",subject:"egressAllowlist"}]}__name(lintNetworkAllowlist,"lintNetworkAllowlist");function lintPermissionProviders(input){const manifest=input.manifest;if(!manifest||!Array.isArray(manifest.requiredPermissions))return[];const declared=Array.isArray(manifest.providers)?manifest.providers.filter(value=>typeof value==="string"):[];if(declared.length===0)return[];const findings=[];manifest.requiredPermissions.forEach((permission,index)=>{if(!isRecord(permission))return;const provider=permission.provider;if(typeof provider!=="string"||declared.includes(provider))return;findings.push({severity:"error",rule:"package/permission-provider-undeclared",file:MANIFEST_FILE,...input.manifestSource?locationOf(input.manifestSource,`requiredPermissions.${index}.provider`):{},message:`This permission is for provider "${provider}", which is not in this package's providers (${declared.join(", ")}). ${contracts_1.BRAND_SHORT_NAME} would ask an approver to grant access the package has no connection to use.`,fix:`Add "${provider}" to providers, or remove this permission.`})});return findings}__name(lintPermissionProviders,"lintPermissionProviders");function lintUnusedPermissions(input){const manifest=input.manifest;if(!manifest||!Array.isArray(manifest.requiredPermissions))return[];const haystack=scriptText(input).toLowerCase();if(haystack.length===0)return[];const findings=[];manifest.requiredPermissions.forEach((permission,index)=>{if(!isRecord(permission)||!Array.isArray(permission.actions))return;permission.actions.forEach((action,actionIndex)=>{if(typeof action!=="string"||action.includes("*"))return;if(permissionTokens(action).some(token2=>haystack.includes(token2)))return;findings.push({severity:"warning",rule:"package/permission-possibly-unused",file:MANIFEST_FILE,...input.manifestSource?locationOf(input.manifestSource,`requiredPermissions.${index}.actions.${actionIndex}`):{},message:`Nothing in this package's scripts mentions "${action}" or any part of it. Every declared permission is privilege an approver is asked to grant, so a stale one makes the package look more dangerous than it is. (Text search \u2014 if the script builds the call dynamically, this is a false alarm.)`,fix:`Remove this permission if the package no longer needs it.`})})});return findings}__name(lintUnusedPermissions,"lintUnusedPermissions");function lintUnreferencedEgressHosts(input){const manifest=input.manifest;if(!manifest||!Array.isArray(manifest.egressAllowlist))return[];const haystack=scriptText(input).toLowerCase();if(haystack.length===0)return[];const findings=[];manifest.egressAllowlist.forEach((destination,index)=>{if(typeof destination!=="string")return;const host=destination.replace(/^\*\./,"").replace(/:\d+$/,"").toLowerCase();if(host.length===0||haystack.includes(host))return;findings.push({severity:"warning",rule:"package/egress-host-unreferenced",file:MANIFEST_FILE,...input.manifestSource?locationOf(input.manifestSource,`egressAllowlist.${index}`):{},message:`No script in this package mentions "${host}". Whoever adopts this action reads the allowlist as the list of things it talks to.`,fix:`Remove "${destination}" from egressAllowlist if nothing contacts it.`})});return findings}__name(lintUnreferencedEgressHosts,"lintUnreferencedEgressHosts");function lintPhaseWritesNoResult(input){const manifest=input.manifest;if(!manifest)return[];const runtime=manifest.runtime;if(typeof runtime!=="object"||runtime===null||Array.isArray(runtime))return[];const declaration=runtime;if(declaration.kind==="oci")return[];const name3=declaration.name;if(typeof name3!=="string"||!isInterpreter2(name3))return[];const entryFile=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[name3].entryFile;const findings=[];for(const{field,phase}of ENTRYPOINT_PHASES){const directory=manifest[field];if(typeof directory!=="string"||directory.length===0)continue;const scripts=[...input.files].filter(([path])=>path.startsWith(directory)&&SCRIPT_EXTENSIONS.some(ext=>path.endsWith(ext)));if(scripts.length===0)continue;if(scripts.some(([,source])=>codeOf(source).includes(RESULT_FILE_VARIABLE)))continue;findings.push({severity:"error",advisory:true,rule:"package/phase-writes-no-result",file:`${directory}${entryFile}`,message:`Nothing under "${directory}" writes ${RESULT_FILE_VARIABLE}, so this package's ${phase} phase has no way to report what it did. ${contracts_1.BRAND_SHORT_NAME} reads that file and nothing else: a package that exits 0 without writing one is a FAILED run, whatever it printed. (Text search \u2014 if the result is written somewhere this cannot see, publish anyway; this does not block you.)`,fix:`Write the result as the last thing "${directory}${entryFile}" does, on every path including the ones that fail \u2014 or let ${contracts_1.BRAND_SHORT_NAME}'s wrapper do it, which is what the scaffolded entrypoint is for: put your work in the phase's body file and it reports for you.`,subject:`${field}.result`})}return findings}__name(lintPhaseWritesNoResult,"lintPhaseWritesNoResult");var SCRIPT_EXTENSIONS=[".ps1",".sh",".py"];var RESULT_FILE_VARIABLE="RUNVERIC_RESULT_FILE";var ENTRYPOINT_PHASES=[{field:"entrypoint",phase:"run"},{field:"validateEntrypoint",phase:"validate"},{field:"rollbackEntrypoint",phase:"rollback"}];function scriptText(input){return[...input.files].filter(([path])=>SCRIPT_EXTENSIONS.some(extension=>path.endsWith(extension))).map(([,source])=>codeOf(source)).join("\n")}__name(scriptText,"scriptText");function codeOf(source){return source.split(/\r?\n/).filter(line=>!line.trimStart().startsWith("#")).join("\n")}__name(codeOf,"codeOf");function permissionTokens(action){const lower=action.toLowerCase();const segments=lower.split("/").slice(0,-1).filter(segment=>segment.length>=5);const singulars=segments.filter(segment=>segment.endsWith("s")).map(segment=>segment.slice(0,-1));return[lower,...segments,...singulars]}__name(permissionTokens,"permissionTokens");function dependencyNames(value){if(Array.isArray(value))return value.filter(item=>typeof item==="string");if(isRecord(value)){return Object.values(value).filter(item=>typeof item==="string")}return[]}__name(dependencyNames,"dependencyNames");function locationOf(source,path){const at=(0,source_location_1.locate)(source,path);return at?{line:at.line,column:at.column}:{}}__name(locationOf,"locationOf");function isInterpreter2(value){return contracts_1.PACKAGE_INTERPRETERS.includes(value)}__name(isInterpreter2,"isInterpreter");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord")}});var require_parameters_location=__commonJS({"../action-manifest/dist/parameters-location.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveParametersFile=resolveParametersFile;exports.resolveParametersFileOf=resolveParametersFileOf;exports.readManifest=readManifest2;var yaml_1=__require("yaml");var manifest_validator_1=require_manifest_validator();var package_validation_1=require_package_validation();function resolveParametersFile(manifestSource){if(manifestSource===void 0){return{resolved:false,reason:"manifest_missing"}}const manifest=readManifest2(manifestSource);if(!manifest)return{resolved:false,reason:"manifest_unparseable"};const reference=manifest.parametersRef;if(typeof reference!=="string"||reference.length===0){return{resolved:false,reason:"parameters_ref_missing"}}if(!(0,manifest_validator_1.isSafeRelativePath)(reference)){return{resolved:false,reason:"parameters_ref_unsafe"}}return{resolved:true,path:reference}}__name(resolveParametersFile,"resolveParametersFile");function resolveParametersFileOf(files){return resolveParametersFile(files.get(package_validation_1.MANIFEST_FILE))}__name(resolveParametersFileOf,"resolveParametersFileOf");function readManifest2(source){try{const document=(0,yaml_1.parseDocument)(source);if(document.errors.length>0)return void 0;const value=document.toJS();return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:void 0}catch{return void 0}}__name(readManifest2,"readManifest")}});var require_check=__commonJS({"../action-manifest/dist/check.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.checkActionPackage=checkActionPackage4;var authoring_lint_1=require_authoring_lint();var findings_1=require_findings();var parameters_location_1=require_parameters_location();var package_validation_1=require_package_validation();function checkActionPackage4(files){const validation=(0,package_validation_1.validateActionPackage)(files);const text=new Map([...files].map(([path,contents])=>[path,decode(contents)]));const manifestSource=text.get(package_validation_1.MANIFEST_FILE);const validatorFindings=[];const parametersRef=validation.manifest?.parametersRef;for(const[problems,severity]of[[validation.errors,"error"],[validation.warnings,"warning"]]){for(const problem of problems){const inParameters=problem.path==="parameters"||problem.path.startsWith("parameters.");const file=inParameters&&parametersRef?parametersRef:package_validation_1.MANIFEST_FILE;const source=text.get(file);validatorFindings.push((0,findings_1.findingFromValidation)(problem,{severity,file,source:source??"",...inParameters?{pathPrefix:"parameters"}:{}}))}}const lint=(0,authoring_lint_1.lintActionPackage)({files:text,manifest:manifestSource?(0,parameters_location_1.readManifest)(manifestSource):void 0,manifestSource});const findings=(0,findings_1.mergeFindings)(validatorFindings,lint);const errors=findings.filter(finding=>finding.severity==="error");return{findings,validation,errorCount:errors.length,warningCount:findings.filter(finding=>finding.severity==="warning").length,advisoryCount:errors.filter(finding=>finding.advisory===true).length,lintBlocked:validation.ok&&lint.some(finding=>finding.severity==="error"&&finding.advisory!==true)}}__name(checkActionPackage4,"checkActionPackage");function decode(contents){return contents.toString("utf8")}__name(decode,"decode")}});var require_powershell_param_detection=__commonJS({"../action-manifest/dist/powershell-param-detection.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POWERSHELL_PARAM_PROBE=void 0;exports.powerShellDetection=powerShellDetection;exports.parseProbeOutput=parseProbeOutput;exports.mapDeclaredParameters=mapDeclaredParameters;var contracts_1=require_dist();exports.POWERSHELL_PARAM_PROBE=`$ErrorActionPreference = 'Stop'
@@ -95,7 +95,7 @@ if ($null -ne $operaAst.ParamBlock) {
95
95
  }
96
96
 
97
97
  $operaResult | ConvertTo-Json -Depth 8 -Compress
98
- `;var MAPPED_TYPES={"System.String":{kind:"exact",type:"string"},"System.Boolean":{kind:"exact",type:"boolean"},"System.Management.Automation.SwitchParameter":{kind:"exact",type:"boolean"},"System.Object":{kind:"assumed"},"System.Int32":{kind:"widened"},"System.Int64":{kind:"widened"},"System.Decimal":{kind:"widened"},"System.Double":{kind:"widened"},"System.DateTime":{kind:"widened"}};var ASSUMED_NOTE=`Declared without a type, so ${contracts_1.BRAND_SHORT_NAME} proposes a text box. Nothing checks the answer on the way in \u2014 add [string] to say that is what you meant, or a stronger type if it is not.`;var WIDENED_NOTE=`${contracts_1.BRAND_SHORT_NAME} parameters are text or true/false, so this is proposed as a text box. Your own cast still validates what an operator types.`;var REFUSAL_REASON=`${contracts_1.BRAND_ARTICLE_CAPITALISED} ${contracts_1.BRAND_SHORT_NAME} parameter is text or true/false. A text box pretending to be this type would produce a run that fails on something the operator was never warned about, so it is not proposed \u2014 read this one inside your script instead.`;function powerShellDetection(block,fromFile){if(block.parseErrors.length>0){return{source:"none",fromFile,parameters:[],unrepresentable:[],failure:`\`${fromFile}\` is not valid PowerShell, so its parameters cannot be read: ${block.parseErrors[0]} Fix it and detect again \u2014 Check reports the same error.`}}return{source:"powershell_param",fromFile,...mapDeclaredParameters(block),failure:null}}__name(powerShellDetection,"powerShellDetection");function parseProbeOutput(stdout){let value;try{value=JSON.parse(stdout)}catch{return null}if(typeof value!=="object"||value===null||Array.isArray(value))return null;const record=value;if(typeof record.hasParamBlock!=="boolean")return null;if(!Array.isArray(record.parseErrors)||!Array.isArray(record.parameters))return null;const parameters=[];for(const entry of record.parameters){if(typeof entry!=="object"||entry===null)return null;const parameter=entry;if(typeof parameter.name!=="string"||typeof parameter.staticType!=="string")return null;if(typeof parameter.sourceLine!=="number")return null;parameters.push({name:parameter.name,staticType:parameter.staticType,declaredType:typeof parameter.declaredType==="string"?parameter.declaredType:"",mandatory:parameter.mandatory===true,helpMessage:typeof parameter.helpMessage==="string"?parameter.helpMessage:null,commentHelp:typeof parameter.commentHelp==="string"?parameter.commentHelp:null,validateSet:Array.isArray(parameter.validateSet)?parameter.validateSet.filter(item=>typeof item==="string"):null,defaultValue:constantOf(parameter.defaultValue),sourceLine:parameter.sourceLine,sourceText:typeof parameter.sourceText==="string"?parameter.sourceText:""})}return{parseErrors:record.parseErrors.filter(item=>typeof item==="string"),hasParamBlock:record.hasParamBlock,parameters}}__name(parseProbeOutput,"parseProbeOutput");function constantOf(value){if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}return null}__name(constantOf,"constantOf");function mapDeclaredParameters(block){const parameters=[];const unrepresentable=[];for(const declared of block.parameters){const mapping=MAPPED_TYPES[declared.staticType];if(!mapping){unrepresentable.push({name:declared.name,declaredType:declared.declaredType||declared.staticType,reason:REFUSAL_REASON,sourceLine:declared.sourceLine,sourceText:declared.sourceText});continue}const type=mapping.kind==="exact"?mapping.type:"string";const enumValues=type==="string"&&declared.validateSet?[...declared.validateSet]:[];parameters.push({name:declared.name,title:declared.name,declaredType:declared.declaredType||declared.staticType,type,control:type==="boolean"?"switch":enumValues.length>0?"select":"text",required:declared.mandatory,enumValues,defaultValue:defaultOf(declared,type),description:(declared.helpMessage??declared.commentHelp??"").trim(),note:mapping.kind==="widened"?WIDENED_NOTE:mapping.kind==="assumed"?ASSUMED_NOTE:null,sourceLine:declared.sourceLine,sourceText:declared.sourceText})}return{parameters,unrepresentable}}__name(mapDeclaredParameters,"mapDeclaredParameters");function defaultOf(declared,type){const value=declared.defaultValue;if(value===null)return null;if(type==="boolean")return typeof value==="boolean"?value:null;const text=String(value);if(declared.validateSet&&!declared.validateSet.includes(text))return null;return text}__name(defaultOf,"defaultOf")}});var require_scaffold=__commonJS({"../action-manifest/dist/scaffold.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.scaffoldActionPackage=scaffoldActionPackage2;exports.authoredBodyPath=authoredBodyPath;exports.authoredEntrypointOf=authoredEntrypointOf;exports.generateImportedPackage=generateImportedPackage;exports.reservedImportPaths=reservedImportPaths;var contracts_1=require_dist();var interpreter_launch_1=require_interpreter_launch();var package_validation_1=require_package_validation();function scaffoldActionPackage2(input){const{entryFile,bodyFile}=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[input.interpreter];const files=new Map;files.set(package_validation_1.MANIFEST_FILE,manifest(input,true));files.set(PARAMETERS_FILE,parameters());files.set(`run/${entryFile}`,wrapperScript(input.interpreter,authoredBodyPath(input.interpreter)));files.set(`run/${bodyFile}`,input.body??BODY_SCRIPT[input.interpreter]);files.set(`validate/${entryFile}`,commented(VALIDATE_SCRIPT[input.interpreter]));files.set(`rollback/${entryFile}`,commented(ROLLBACK_SCRIPT[input.interpreter]));files.set("README.md",readme2(input));files.set("LICENSE",license(input));files.set(".gitignore",GITIGNORE);return files}__name(scaffoldActionPackage2,"scaffoldActionPackage");function authoredBodyPath(interpreter){return`run/${interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[interpreter].bodyFile}`}__name(authoredBodyPath,"authoredBodyPath");function authoredEntrypointOf(files,interpreter){const wrapper=files.get(`run/${interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`);if(wrapper===void 0)return null;const marker=`# ${ENTRYPOINT_MARKER}`;for(const line of wrapper.split("\n")){const trimmed=line.trimEnd();if(!trimmed.endsWith(marker))continue;return LITERAL_READERS[interpreter](trimmed.slice(0,-marker.length))}return null}__name(authoredEntrypointOf,"authoredEntrypointOf");var ENTRYPOINT_MARKER="opera:entrypoint";function generateImportedPackage(input){const{entryFile}=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[input.interpreter];const uploaded=new Set(input.uploadedPaths);const scaffoldInput={id:input.id,name:input.name,interpreter:input.interpreter,author:input.author,year:input.year};const reserved=new Map([[package_validation_1.MANIFEST_FILE,manifest(scaffoldInput,false)],[PARAMETERS_FILE,parameters()],[`run/${entryFile}`,wrapperScript(input.interpreter,input.entrypoint)]]);const collisions=[...reserved.keys()].filter(path=>uploaded.has(path));if(collisions.length>0)return{files:new Map,collisions};const files=new Map(reserved);if(!uploaded.has("README.md"))files.set("README.md",importReadme(input));if(!uploaded.has("LICENSE"))files.set("LICENSE",license(scaffoldInput));return{files,collisions:[]}}__name(generateImportedPackage,"generateImportedPackage");function reservedImportPaths(interpreter){return[package_validation_1.MANIFEST_FILE,PARAMETERS_FILE,`run/${interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`]}__name(reservedImportPaths,"reservedImportPaths");var PARAMETERS_FILE="parameters.json";function manifest(input,phaseFilesPresent){const entryFile=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[input.interpreter].entryFile;const version5=INTERPRETER_VERSION[input.interpreter];const enable=phaseFilesPresent?"uncomment":"add";return`# The action's contract. Every field here is read by ${contracts_1.BRAND_SHORT_NAME}; nothing is decorative.
98
+ `;var MAPPED_TYPES={"System.String":{kind:"exact",type:"string"},"System.Boolean":{kind:"exact",type:"boolean"},"System.Management.Automation.SwitchParameter":{kind:"exact",type:"boolean"},"System.Object":{kind:"assumed"},"System.Int32":{kind:"widened"},"System.Int64":{kind:"widened"},"System.Decimal":{kind:"widened"},"System.Double":{kind:"widened"},"System.DateTime":{kind:"widened"}};var ASSUMED_NOTE=`Declared without a type, so ${contracts_1.BRAND_SHORT_NAME} proposes a text box. Nothing checks the answer on the way in \u2014 add [string] to say that is what you meant, or a stronger type if it is not.`;var WIDENED_NOTE=`${contracts_1.BRAND_SHORT_NAME} parameters are text or true/false, so this is proposed as a text box. Your own cast still validates what an operator types.`;var REFUSAL_REASON=`${contracts_1.BRAND_ARTICLE_CAPITALISED} ${contracts_1.BRAND_SHORT_NAME} parameter is text or true/false. A text box pretending to be this type would produce a run that fails on something the operator was never warned about, so it is not proposed \u2014 read this one inside your script instead.`;function powerShellDetection(block,fromFile){if(block.parseErrors.length>0){return{source:"none",fromFile,parameters:[],unrepresentable:[],failure:`\`${fromFile}\` is not valid PowerShell, so its parameters cannot be read: ${block.parseErrors[0]} Fix it and detect again \u2014 Check reports the same error.`}}return{source:"powershell_param",fromFile,...mapDeclaredParameters(block),failure:null}}__name(powerShellDetection,"powerShellDetection");function parseProbeOutput(stdout){let value;try{value=JSON.parse(stdout)}catch{return null}if(typeof value!=="object"||value===null||Array.isArray(value))return null;const record=value;if(typeof record.hasParamBlock!=="boolean")return null;if(!Array.isArray(record.parseErrors)||!Array.isArray(record.parameters))return null;const parameters=[];for(const entry of record.parameters){if(typeof entry!=="object"||entry===null)return null;const parameter=entry;if(typeof parameter.name!=="string"||typeof parameter.staticType!=="string")return null;if(typeof parameter.sourceLine!=="number")return null;parameters.push({name:parameter.name,staticType:parameter.staticType,declaredType:typeof parameter.declaredType==="string"?parameter.declaredType:"",mandatory:parameter.mandatory===true,helpMessage:typeof parameter.helpMessage==="string"?parameter.helpMessage:null,commentHelp:typeof parameter.commentHelp==="string"?parameter.commentHelp:null,validateSet:Array.isArray(parameter.validateSet)?parameter.validateSet.filter(item=>typeof item==="string"):null,defaultValue:constantOf(parameter.defaultValue),sourceLine:parameter.sourceLine,sourceText:typeof parameter.sourceText==="string"?parameter.sourceText:""})}return{parseErrors:record.parseErrors.filter(item=>typeof item==="string"),hasParamBlock:record.hasParamBlock,parameters}}__name(parseProbeOutput,"parseProbeOutput");function constantOf(value){if(typeof value==="string"||typeof value==="number"||typeof value==="boolean"){return value}return null}__name(constantOf,"constantOf");function mapDeclaredParameters(block){const parameters=[];const unrepresentable=[];for(const declared of block.parameters){const mapping=MAPPED_TYPES[declared.staticType];if(!mapping){unrepresentable.push({name:declared.name,declaredType:declared.declaredType||declared.staticType,reason:REFUSAL_REASON,sourceLine:declared.sourceLine,sourceText:declared.sourceText});continue}const type=mapping.kind==="exact"?mapping.type:"string";const enumValues=type==="string"&&declared.validateSet?[...declared.validateSet]:[];parameters.push({name:declared.name,title:declared.name,declaredType:declared.declaredType||declared.staticType,type,control:type==="boolean"?"switch":enumValues.length>0?"select":"text",required:declared.mandatory,enumValues,defaultValue:defaultOf(declared,type),description:(declared.helpMessage??declared.commentHelp??"").trim(),note:mapping.kind==="widened"?WIDENED_NOTE:mapping.kind==="assumed"?ASSUMED_NOTE:null,sourceLine:declared.sourceLine,sourceText:declared.sourceText})}return{parameters,unrepresentable}}__name(mapDeclaredParameters,"mapDeclaredParameters");function defaultOf(declared,type){const value=declared.defaultValue;if(value===null)return null;if(type==="boolean")return typeof value==="boolean"?value:null;const text=String(value);if(declared.validateSet&&!declared.validateSet.includes(text))return null;return text}__name(defaultOf,"defaultOf")}});var require_scaffold=__commonJS({"../action-manifest/dist/scaffold.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.scaffoldActionPackage=scaffoldActionPackage2;exports.authoredBodyPath=authoredBodyPath;exports.authoredEntrypointOf=authoredEntrypointOf;exports.generateImportedPackage=generateImportedPackage;exports.reservedImportPaths=reservedImportPaths;var contracts_1=require_dist();var interpreter_launch_1=require_interpreter_launch();var package_validation_1=require_package_validation();function scaffoldActionPackage2(input){const{entryFile,bodyFile}=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[input.interpreter];const files=new Map;files.set(package_validation_1.MANIFEST_FILE,manifest(input,true));files.set(PARAMETERS_FILE,parameters());files.set(`run/${entryFile}`,wrapperScript(input.interpreter,authoredBodyPath(input.interpreter)));files.set(`run/${bodyFile}`,input.body??BODY_SCRIPT[input.interpreter]);files.set(`validate/${entryFile}`,commented(VALIDATE_SCRIPT[input.interpreter]));files.set(`rollback/${entryFile}`,commented(ROLLBACK_SCRIPT[input.interpreter]));files.set("README.md",readme2(input));files.set("LICENSE",license(input));files.set(".gitignore",GITIGNORE);return files}__name(scaffoldActionPackage2,"scaffoldActionPackage");function authoredBodyPath(interpreter){return`run/${interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[interpreter].bodyFile}`}__name(authoredBodyPath,"authoredBodyPath");function authoredEntrypointOf(files,interpreter){const wrapper=files.get(`run/${interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`);if(wrapper===void 0)return null;const marker=`# ${ENTRYPOINT_MARKER}`;for(const line of wrapper.split("\n")){const trimmed=line.trimEnd();if(!trimmed.endsWith(marker))continue;return LITERAL_READERS[interpreter](trimmed.slice(0,-marker.length))}return null}__name(authoredEntrypointOf,"authoredEntrypointOf");var ENTRYPOINT_MARKER="opera:entrypoint";function generateImportedPackage(input){const{entryFile}=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[input.interpreter];const uploaded=new Set(input.uploadedPaths);const scaffoldInput={id:input.id,name:input.name,interpreter:input.interpreter,author:input.author,year:input.year};const reserved=new Map([[package_validation_1.MANIFEST_FILE,manifest(scaffoldInput,false)],[PARAMETERS_FILE,parameters()],[`run/${entryFile}`,wrapperScript(input.interpreter,input.entrypoint)]]);const collisions=[...reserved.keys()].filter(path=>uploaded.has(path));if(collisions.length>0)return{files:new Map,collisions};const files=new Map(reserved);if(!uploaded.has("README.md"))files.set("README.md",importReadme(input));if(!uploaded.has("LICENSE"))files.set("LICENSE",license(scaffoldInput));return{files,collisions:[]}}__name(generateImportedPackage,"generateImportedPackage");function reservedImportPaths(interpreter){return[package_validation_1.MANIFEST_FILE,PARAMETERS_FILE,`run/${interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`]}__name(reservedImportPaths,"reservedImportPaths");var PARAMETERS_FILE="parameters.json";function manifest(input,phaseFilesPresent){const entryFile=interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH[input.interpreter].entryFile;const version6=INTERPRETER_VERSION[input.interpreter];const enable=phaseFilesPresent?"uncomment":"add";return`# The action's contract. Every field here is read by ${contracts_1.BRAND_SHORT_NAME}; nothing is decorative.
99
99
  # \`runveric check\` validates this file with the SAME validator the server uses, so a
100
100
  # manifest that passes here is a manifest that imports.
101
101
  apiVersion: ${contracts_1.ACTION_MANIFEST_API_VERSION}
@@ -115,7 +115,7 @@ connectorKey: ${contracts_1.PACKAGE_RUNNER_CONNECTOR_KEY}
115
115
  runtime:
116
116
  kind: interpreter
117
117
  name: ${input.interpreter}
118
- version: "${version5}"
118
+ version: "${version6}"
119
119
  executionTimeout: 5m
120
120
  parametersRef: ${PARAMETERS_FILE}
121
121
  entrypoint: run/
@@ -848,9 +848,9 @@ SOFTWARE.
848
848
  `}__name(license,"license");var GITIGNORE=`# runveric test writes its scratch here.
849
849
  .runveric/
850
850
  *.log
851
- `;function yamlString(value){return`"${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}__name(yamlString,"yamlString");var LITERAL_READERS={powershell:__name(line=>singleQuoted(line,/''/g,"'"),"powershell"),bash:__name(line=>singleQuoted(line,/'\\''/g,"'"),"bash"),python:__name(line=>{const open=line.indexOf('"');const close=line.lastIndexOf('"');if(open<0||close<=open)return null;try{const value=JSON.parse(line.slice(open,close+1));return typeof value==="string"?value:null}catch{return null}},"python")};function singleQuoted(line,escaped,plain){const open=line.indexOf("'");const close=line.lastIndexOf("'");if(open<0||close<=open)return null;return line.slice(open+1,close).replace(escaped,plain)}__name(singleQuoted,"singleQuoted");function powershellLiteral(value){return`'${value.replace(/'/g,"''")}'`}__name(powershellLiteral,"powershellLiteral");function bashLiteral(value){return`'${value.replace(/'/g,`'\\''`)}'`}__name(bashLiteral,"bashLiteral");function pythonLiteral(value){return JSON.stringify(value)}__name(pythonLiteral,"pythonLiteral")}});var require_dist4=__commonJS({"../action-manifest/dist/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.reservedImportPaths=exports.generateImportedPackage=exports.authoredEntrypointOf=exports.authoredBodyPath=exports.powerShellDetection=exports.parseProbeOutput=exports.mapDeclaredParameters=exports.POWERSHELL_PARAM_PROBE=exports.pathSegments=exports.offsetToLocation=exports.locate=exports.interpreterForPath=exports.interpreterEntryFileList=exports.PACKAGE_INTERPRETER_EXTENSIONS=exports.PACKAGE_INTERPRETER_LAUNCH=exports.lintActionPackage=exports.sortFindings=exports.mergeFindings=exports.findingFromValidation=exports.resolveParametersFileOf=exports.resolveParametersFile=exports.readManifest=exports.checkActionPackage=exports.validateActionPackage=exports.REQUIRED_PACKAGE_FILES=exports.MANIFEST_FILE=exports.validatePackageResult=exports.PackageProtocolError=exports.normalizePackageRuntime=exports.checkOciImageReference=exports.PackageRuntimeDeclarationError=exports.PARAMETER_CONTROLS=exports.PARAMETER_PROPERTY_FIELDS=exports.PARAMETER_SCHEMA_FIELDS=exports.CREDENTIAL_SCOPE_PATTERN=exports.SPDX_ID_PATTERN=exports.DURATION_PATTERN=exports.SEMVER_PATTERN=exports.PACKAGE_ID_PATTERN=exports.MANIFEST_FIELDS=exports.RISK_LEVELS=exports.PROVIDERS=exports.ACTION_CATEGORIES=exports.isEgressDestination=exports.isSafeRelativePath=exports.sha256Hex=exports.canonicalJson=exports.validateParameterSchema=exports.validateManifest=exports.parseAndValidateManifest=void 0;exports.scaffoldActionPackage=void 0;var manifest_validator_1=require_manifest_validator();Object.defineProperty(exports,"parseAndValidateManifest",{enumerable:true,get:__name(function(){return manifest_validator_1.parseAndValidateManifest},"get")});Object.defineProperty(exports,"validateManifest",{enumerable:true,get:__name(function(){return manifest_validator_1.validateManifest},"get")});Object.defineProperty(exports,"validateParameterSchema",{enumerable:true,get:__name(function(){return manifest_validator_1.validateParameterSchema},"get")});Object.defineProperty(exports,"canonicalJson",{enumerable:true,get:__name(function(){return manifest_validator_1.canonicalJson},"get")});Object.defineProperty(exports,"sha256Hex",{enumerable:true,get:__name(function(){return manifest_validator_1.sha256Hex},"get")});Object.defineProperty(exports,"isSafeRelativePath",{enumerable:true,get:__name(function(){return manifest_validator_1.isSafeRelativePath},"get")});Object.defineProperty(exports,"isEgressDestination",{enumerable:true,get:__name(function(){return manifest_validator_1.isEgressDestination},"get")});var manifest_schema_1=require_manifest_schema();Object.defineProperty(exports,"ACTION_CATEGORIES",{enumerable:true,get:__name(function(){return manifest_schema_1.ACTION_CATEGORIES},"get")});Object.defineProperty(exports,"PROVIDERS",{enumerable:true,get:__name(function(){return manifest_schema_1.PROVIDERS},"get")});Object.defineProperty(exports,"RISK_LEVELS",{enumerable:true,get:__name(function(){return manifest_schema_1.RISK_LEVELS},"get")});Object.defineProperty(exports,"MANIFEST_FIELDS",{enumerable:true,get:__name(function(){return manifest_schema_1.MANIFEST_FIELDS},"get")});Object.defineProperty(exports,"PACKAGE_ID_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.PACKAGE_ID_PATTERN},"get")});Object.defineProperty(exports,"SEMVER_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.SEMVER_PATTERN},"get")});Object.defineProperty(exports,"DURATION_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.DURATION_PATTERN},"get")});Object.defineProperty(exports,"SPDX_ID_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.SPDX_ID_PATTERN},"get")});Object.defineProperty(exports,"CREDENTIAL_SCOPE_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.CREDENTIAL_SCOPE_PATTERN},"get")});Object.defineProperty(exports,"PARAMETER_SCHEMA_FIELDS",{enumerable:true,get:__name(function(){return manifest_schema_1.PARAMETER_SCHEMA_FIELDS},"get")});Object.defineProperty(exports,"PARAMETER_PROPERTY_FIELDS",{enumerable:true,get:__name(function(){return manifest_schema_1.PARAMETER_PROPERTY_FIELDS},"get")});Object.defineProperty(exports,"PARAMETER_CONTROLS",{enumerable:true,get:__name(function(){return manifest_schema_1.PARAMETER_CONTROLS},"get")});var package_runtime_declaration_1=require_package_runtime_declaration();Object.defineProperty(exports,"PackageRuntimeDeclarationError",{enumerable:true,get:__name(function(){return package_runtime_declaration_1.PackageRuntimeDeclarationError},"get")});Object.defineProperty(exports,"checkOciImageReference",{enumerable:true,get:__name(function(){return package_runtime_declaration_1.checkOciImageReference},"get")});Object.defineProperty(exports,"normalizePackageRuntime",{enumerable:true,get:__name(function(){return package_runtime_declaration_1.normalizePackageRuntime},"get")});var package_result_validator_1=require_package_result_validator();Object.defineProperty(exports,"PackageProtocolError",{enumerable:true,get:__name(function(){return package_result_validator_1.PackageProtocolError},"get")});Object.defineProperty(exports,"validatePackageResult",{enumerable:true,get:__name(function(){return package_result_validator_1.validatePackageResult},"get")});var package_validation_1=require_package_validation();Object.defineProperty(exports,"MANIFEST_FILE",{enumerable:true,get:__name(function(){return package_validation_1.MANIFEST_FILE},"get")});Object.defineProperty(exports,"REQUIRED_PACKAGE_FILES",{enumerable:true,get:__name(function(){return package_validation_1.REQUIRED_PACKAGE_FILES},"get")});Object.defineProperty(exports,"validateActionPackage",{enumerable:true,get:__name(function(){return package_validation_1.validateActionPackage},"get")});var check_1=require_check();Object.defineProperty(exports,"checkActionPackage",{enumerable:true,get:__name(function(){return check_1.checkActionPackage},"get")});var parameters_location_1=require_parameters_location();Object.defineProperty(exports,"readManifest",{enumerable:true,get:__name(function(){return parameters_location_1.readManifest},"get")});Object.defineProperty(exports,"resolveParametersFile",{enumerable:true,get:__name(function(){return parameters_location_1.resolveParametersFile},"get")});Object.defineProperty(exports,"resolveParametersFileOf",{enumerable:true,get:__name(function(){return parameters_location_1.resolveParametersFileOf},"get")});var findings_1=require_findings();Object.defineProperty(exports,"findingFromValidation",{enumerable:true,get:__name(function(){return findings_1.findingFromValidation},"get")});Object.defineProperty(exports,"mergeFindings",{enumerable:true,get:__name(function(){return findings_1.mergeFindings},"get")});Object.defineProperty(exports,"sortFindings",{enumerable:true,get:__name(function(){return findings_1.sortFindings},"get")});var authoring_lint_1=require_authoring_lint();Object.defineProperty(exports,"lintActionPackage",{enumerable:true,get:__name(function(){return authoring_lint_1.lintActionPackage},"get")});var interpreter_launch_1=require_interpreter_launch();Object.defineProperty(exports,"PACKAGE_INTERPRETER_LAUNCH",{enumerable:true,get:__name(function(){return interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH},"get")});Object.defineProperty(exports,"PACKAGE_INTERPRETER_EXTENSIONS",{enumerable:true,get:__name(function(){return interpreter_launch_1.PACKAGE_INTERPRETER_EXTENSIONS},"get")});Object.defineProperty(exports,"interpreterEntryFileList",{enumerable:true,get:__name(function(){return interpreter_launch_1.interpreterEntryFileList},"get")});Object.defineProperty(exports,"interpreterForPath",{enumerable:true,get:__name(function(){return interpreter_launch_1.interpreterForPath},"get")});var source_location_1=require_source_location();Object.defineProperty(exports,"locate",{enumerable:true,get:__name(function(){return source_location_1.locate},"get")});Object.defineProperty(exports,"offsetToLocation",{enumerable:true,get:__name(function(){return source_location_1.offsetToLocation},"get")});Object.defineProperty(exports,"pathSegments",{enumerable:true,get:__name(function(){return source_location_1.pathSegments},"get")});var powershell_param_detection_1=require_powershell_param_detection();Object.defineProperty(exports,"POWERSHELL_PARAM_PROBE",{enumerable:true,get:__name(function(){return powershell_param_detection_1.POWERSHELL_PARAM_PROBE},"get")});Object.defineProperty(exports,"mapDeclaredParameters",{enumerable:true,get:__name(function(){return powershell_param_detection_1.mapDeclaredParameters},"get")});Object.defineProperty(exports,"parseProbeOutput",{enumerable:true,get:__name(function(){return powershell_param_detection_1.parseProbeOutput},"get")});Object.defineProperty(exports,"powerShellDetection",{enumerable:true,get:__name(function(){return powershell_param_detection_1.powerShellDetection},"get")});var scaffold_1=require_scaffold();Object.defineProperty(exports,"authoredBodyPath",{enumerable:true,get:__name(function(){return scaffold_1.authoredBodyPath},"get")});Object.defineProperty(exports,"authoredEntrypointOf",{enumerable:true,get:__name(function(){return scaffold_1.authoredEntrypointOf},"get")});Object.defineProperty(exports,"generateImportedPackage",{enumerable:true,get:__name(function(){return scaffold_1.generateImportedPackage},"get")});Object.defineProperty(exports,"reservedImportPaths",{enumerable:true,get:__name(function(){return scaffold_1.reservedImportPaths},"get")});Object.defineProperty(exports,"scaffoldActionPackage",{enumerable:true,get:__name(function(){return scaffold_1.scaffoldActionPackage},"get")})}});var name="@runveric/cli";var version="0.5.1";var bin={runveric:"dist/runveric.mjs",rv:"dist/runveric.mjs"};var import_contracts4=__toESM(require_dist());var useColour=process.stdout.isTTY===true&&!process.env.NO_COLOR;var paint=__name(code=>text=>useColour?`\x1B[${code}m${text}\x1B[0m`:text,"paint");var style={bold:paint("1"),dim:paint("2"),red:paint("31"),green:paint("32"),yellow:paint("33"),blue:paint("34"),grey:paint("90")};function print(line=""){process.stdout.write(`${line}
851
+ `;function yamlString(value){return`"${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}__name(yamlString,"yamlString");var LITERAL_READERS={powershell:__name(line=>singleQuoted(line,/''/g,"'"),"powershell"),bash:__name(line=>singleQuoted(line,/'\\''/g,"'"),"bash"),python:__name(line=>{const open=line.indexOf('"');const close=line.lastIndexOf('"');if(open<0||close<=open)return null;try{const value=JSON.parse(line.slice(open,close+1));return typeof value==="string"?value:null}catch{return null}},"python")};function singleQuoted(line,escaped,plain){const open=line.indexOf("'");const close=line.lastIndexOf("'");if(open<0||close<=open)return null;return line.slice(open+1,close).replace(escaped,plain)}__name(singleQuoted,"singleQuoted");function powershellLiteral(value){return`'${value.replace(/'/g,"''")}'`}__name(powershellLiteral,"powershellLiteral");function bashLiteral(value){return`'${value.replace(/'/g,`'\\''`)}'`}__name(bashLiteral,"bashLiteral");function pythonLiteral(value){return JSON.stringify(value)}__name(pythonLiteral,"pythonLiteral")}});var require_dist4=__commonJS({"../action-manifest/dist/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.reservedImportPaths=exports.generateImportedPackage=exports.authoredEntrypointOf=exports.authoredBodyPath=exports.powerShellDetection=exports.parseProbeOutput=exports.mapDeclaredParameters=exports.POWERSHELL_PARAM_PROBE=exports.pathSegments=exports.offsetToLocation=exports.locate=exports.interpreterForPath=exports.interpreterEntryFileList=exports.PACKAGE_INTERPRETER_EXTENSIONS=exports.PACKAGE_INTERPRETER_LAUNCH=exports.lintActionPackage=exports.sortFindings=exports.mergeFindings=exports.findingFromValidation=exports.resolveParametersFileOf=exports.resolveParametersFile=exports.readManifest=exports.checkActionPackage=exports.validateActionPackage=exports.REQUIRED_PACKAGE_FILES=exports.MANIFEST_FILE=exports.validatePackageResult=exports.PackageProtocolError=exports.normalizePackageRuntime=exports.checkOciImageReference=exports.PackageRuntimeDeclarationError=exports.PARAMETER_CONTROLS=exports.PARAMETER_PROPERTY_FIELDS=exports.PARAMETER_SCHEMA_FIELDS=exports.CREDENTIAL_SCOPE_PATTERN=exports.SPDX_ID_PATTERN=exports.DURATION_PATTERN=exports.SEMVER_PATTERN=exports.PACKAGE_ID_PATTERN=exports.MANIFEST_FIELDS=exports.RISK_LEVELS=exports.PROVIDERS=exports.ACTION_CATEGORIES=exports.isEgressDestination=exports.isSafeRelativePath=exports.sha256Hex=exports.canonicalJson=exports.validateParameterSchema=exports.validateManifest=exports.parseAndValidateManifest=void 0;exports.scaffoldActionPackage=void 0;var manifest_validator_1=require_manifest_validator();Object.defineProperty(exports,"parseAndValidateManifest",{enumerable:true,get:__name(function(){return manifest_validator_1.parseAndValidateManifest},"get")});Object.defineProperty(exports,"validateManifest",{enumerable:true,get:__name(function(){return manifest_validator_1.validateManifest},"get")});Object.defineProperty(exports,"validateParameterSchema",{enumerable:true,get:__name(function(){return manifest_validator_1.validateParameterSchema},"get")});Object.defineProperty(exports,"canonicalJson",{enumerable:true,get:__name(function(){return manifest_validator_1.canonicalJson},"get")});Object.defineProperty(exports,"sha256Hex",{enumerable:true,get:__name(function(){return manifest_validator_1.sha256Hex},"get")});Object.defineProperty(exports,"isSafeRelativePath",{enumerable:true,get:__name(function(){return manifest_validator_1.isSafeRelativePath},"get")});Object.defineProperty(exports,"isEgressDestination",{enumerable:true,get:__name(function(){return manifest_validator_1.isEgressDestination},"get")});var manifest_schema_1=require_manifest_schema();Object.defineProperty(exports,"ACTION_CATEGORIES",{enumerable:true,get:__name(function(){return manifest_schema_1.ACTION_CATEGORIES},"get")});Object.defineProperty(exports,"PROVIDERS",{enumerable:true,get:__name(function(){return manifest_schema_1.PROVIDERS},"get")});Object.defineProperty(exports,"RISK_LEVELS",{enumerable:true,get:__name(function(){return manifest_schema_1.RISK_LEVELS},"get")});Object.defineProperty(exports,"MANIFEST_FIELDS",{enumerable:true,get:__name(function(){return manifest_schema_1.MANIFEST_FIELDS},"get")});Object.defineProperty(exports,"PACKAGE_ID_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.PACKAGE_ID_PATTERN},"get")});Object.defineProperty(exports,"SEMVER_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.SEMVER_PATTERN},"get")});Object.defineProperty(exports,"DURATION_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.DURATION_PATTERN},"get")});Object.defineProperty(exports,"SPDX_ID_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.SPDX_ID_PATTERN},"get")});Object.defineProperty(exports,"CREDENTIAL_SCOPE_PATTERN",{enumerable:true,get:__name(function(){return manifest_schema_1.CREDENTIAL_SCOPE_PATTERN},"get")});Object.defineProperty(exports,"PARAMETER_SCHEMA_FIELDS",{enumerable:true,get:__name(function(){return manifest_schema_1.PARAMETER_SCHEMA_FIELDS},"get")});Object.defineProperty(exports,"PARAMETER_PROPERTY_FIELDS",{enumerable:true,get:__name(function(){return manifest_schema_1.PARAMETER_PROPERTY_FIELDS},"get")});Object.defineProperty(exports,"PARAMETER_CONTROLS",{enumerable:true,get:__name(function(){return manifest_schema_1.PARAMETER_CONTROLS},"get")});var package_runtime_declaration_1=require_package_runtime_declaration();Object.defineProperty(exports,"PackageRuntimeDeclarationError",{enumerable:true,get:__name(function(){return package_runtime_declaration_1.PackageRuntimeDeclarationError},"get")});Object.defineProperty(exports,"checkOciImageReference",{enumerable:true,get:__name(function(){return package_runtime_declaration_1.checkOciImageReference},"get")});Object.defineProperty(exports,"normalizePackageRuntime",{enumerable:true,get:__name(function(){return package_runtime_declaration_1.normalizePackageRuntime},"get")});var package_result_validator_1=require_package_result_validator();Object.defineProperty(exports,"PackageProtocolError",{enumerable:true,get:__name(function(){return package_result_validator_1.PackageProtocolError},"get")});Object.defineProperty(exports,"validatePackageResult",{enumerable:true,get:__name(function(){return package_result_validator_1.validatePackageResult},"get")});var package_validation_1=require_package_validation();Object.defineProperty(exports,"MANIFEST_FILE",{enumerable:true,get:__name(function(){return package_validation_1.MANIFEST_FILE},"get")});Object.defineProperty(exports,"REQUIRED_PACKAGE_FILES",{enumerable:true,get:__name(function(){return package_validation_1.REQUIRED_PACKAGE_FILES},"get")});Object.defineProperty(exports,"validateActionPackage",{enumerable:true,get:__name(function(){return package_validation_1.validateActionPackage},"get")});var check_1=require_check();Object.defineProperty(exports,"checkActionPackage",{enumerable:true,get:__name(function(){return check_1.checkActionPackage},"get")});var parameters_location_1=require_parameters_location();Object.defineProperty(exports,"readManifest",{enumerable:true,get:__name(function(){return parameters_location_1.readManifest},"get")});Object.defineProperty(exports,"resolveParametersFile",{enumerable:true,get:__name(function(){return parameters_location_1.resolveParametersFile},"get")});Object.defineProperty(exports,"resolveParametersFileOf",{enumerable:true,get:__name(function(){return parameters_location_1.resolveParametersFileOf},"get")});var findings_1=require_findings();Object.defineProperty(exports,"findingFromValidation",{enumerable:true,get:__name(function(){return findings_1.findingFromValidation},"get")});Object.defineProperty(exports,"mergeFindings",{enumerable:true,get:__name(function(){return findings_1.mergeFindings},"get")});Object.defineProperty(exports,"sortFindings",{enumerable:true,get:__name(function(){return findings_1.sortFindings},"get")});var authoring_lint_1=require_authoring_lint();Object.defineProperty(exports,"lintActionPackage",{enumerable:true,get:__name(function(){return authoring_lint_1.lintActionPackage},"get")});var interpreter_launch_1=require_interpreter_launch();Object.defineProperty(exports,"PACKAGE_INTERPRETER_LAUNCH",{enumerable:true,get:__name(function(){return interpreter_launch_1.PACKAGE_INTERPRETER_LAUNCH},"get")});Object.defineProperty(exports,"PACKAGE_INTERPRETER_EXTENSIONS",{enumerable:true,get:__name(function(){return interpreter_launch_1.PACKAGE_INTERPRETER_EXTENSIONS},"get")});Object.defineProperty(exports,"interpreterEntryFileList",{enumerable:true,get:__name(function(){return interpreter_launch_1.interpreterEntryFileList},"get")});Object.defineProperty(exports,"interpreterForPath",{enumerable:true,get:__name(function(){return interpreter_launch_1.interpreterForPath},"get")});var source_location_1=require_source_location();Object.defineProperty(exports,"locate",{enumerable:true,get:__name(function(){return source_location_1.locate},"get")});Object.defineProperty(exports,"offsetToLocation",{enumerable:true,get:__name(function(){return source_location_1.offsetToLocation},"get")});Object.defineProperty(exports,"pathSegments",{enumerable:true,get:__name(function(){return source_location_1.pathSegments},"get")});var powershell_param_detection_1=require_powershell_param_detection();Object.defineProperty(exports,"POWERSHELL_PARAM_PROBE",{enumerable:true,get:__name(function(){return powershell_param_detection_1.POWERSHELL_PARAM_PROBE},"get")});Object.defineProperty(exports,"mapDeclaredParameters",{enumerable:true,get:__name(function(){return powershell_param_detection_1.mapDeclaredParameters},"get")});Object.defineProperty(exports,"parseProbeOutput",{enumerable:true,get:__name(function(){return powershell_param_detection_1.parseProbeOutput},"get")});Object.defineProperty(exports,"powerShellDetection",{enumerable:true,get:__name(function(){return powershell_param_detection_1.powerShellDetection},"get")});var scaffold_1=require_scaffold();Object.defineProperty(exports,"authoredBodyPath",{enumerable:true,get:__name(function(){return scaffold_1.authoredBodyPath},"get")});Object.defineProperty(exports,"authoredEntrypointOf",{enumerable:true,get:__name(function(){return scaffold_1.authoredEntrypointOf},"get")});Object.defineProperty(exports,"generateImportedPackage",{enumerable:true,get:__name(function(){return scaffold_1.generateImportedPackage},"get")});Object.defineProperty(exports,"reservedImportPaths",{enumerable:true,get:__name(function(){return scaffold_1.reservedImportPaths},"get")});Object.defineProperty(exports,"scaffoldActionPackage",{enumerable:true,get:__name(function(){return scaffold_1.scaffoldActionPackage},"get")})}});var name="@runveric/cli";var version="0.6.0";var bin={runveric:"dist/runveric.mjs",rv:"dist/runveric.mjs"};var import_contracts4=__toESM(require_dist());var useColour=process.stdout.isTTY===true&&!process.env.NO_COLOR;var paint=__name(code=>text=>useColour?`\x1B[${code}m${text}\x1B[0m`:text,"paint");var style={bold:paint("1"),dim:paint("2"),red:paint("31"),green:paint("32"),yellow:paint("33"),blue:paint("34"),grey:paint("90")};function print(line=""){process.stdout.write(`${line}
852
852
  `)}__name(print,"print");function printError(line){process.stderr.write(`${line}
853
- `)}__name(printError,"printError");function printFinding(finding){const badge=finding.severity==="error"?style.red(finding.advisory===true?"error (advisory)":"error"):style.yellow("warning");const at=finding.line===void 0?finding.file:`${finding.file}:${finding.line}:${finding.column??1}`;print(` ${badge} ${style.bold(at)}`);print(` ${finding.message}`);print(` ${style.green("fix:")} ${finding.fix}`);print(` ${style.grey(finding.rule)}`);print()}__name(printFinding,"printFinding");function printCheckSummary(counts){if(counts.errors===0&&counts.warnings===0){print(style.green("\u2713 No problems found."));return}const parts=[];if(counts.errors>0)parts.push(`${counts.errors} error${counts.errors===1?"":"s"}`);if(counts.warnings>0){parts.push(`${counts.warnings} warning${counts.warnings===1?"":"s"}`)}const summary=parts.join(", ");print(counts.errors>0?style.red(`\u2717 ${summary}.`):style.yellow(`${summary}.`))}__name(printCheckSummary,"printCheckSummary");function printEvent(event){const marker={info:style.grey("\xB7"),warn:style.yellow("!"),error:style.red("\u2717"),success:style.green("\u2713")}[event.level];print(` ${marker} ${event.message}`);if(event.data){print(` ${style.grey(JSON.stringify(event.data))}`)}}__name(printEvent,"printEvent");function printResult(result){const status={succeeded:style.green("succeeded"),failed:style.red("failed"),cancelled:style.yellow("cancelled")}[result.status];print();print(`${style.bold("Result")} ${status}`);print(` ${result.message}`);if(result.checks?.length){print();print(` ${style.bold("Checks")}`);for(const check of result.checks){const marker={passed:style.green("\u2713"),warning:style.yellow("!"),failed:style.red("\u2717")}[check.status];print(` ${marker} ${check.message}`);if(check.data)print(` ${style.grey(JSON.stringify(check.data))}`)}}if(result.outputs&&Object.keys(result.outputs).length>0){print();print(` ${style.bold("Outputs")}`);for(const[name3,value]of Object.entries(result.outputs)){print(` ${name3} = ${JSON.stringify(value)}`)}}if(result.rollbackCapture&&Object.keys(result.rollbackCapture).length>0){print();print(` ${style.bold("Rollback capture")} ${style.grey("(what a rollback would read)")}`);for(const[name3,value]of Object.entries(result.rollbackCapture)){print(` ${name3} = ${JSON.stringify(value)}`)}}if(result.error){print();print(` ${style.red("Error")} ${result.error.code}`);print(` ${result.error.message}`);if(result.error.retryable!==void 0){print(` ${style.grey(result.error.retryable?"retryable":"not retryable")}`)}}print()}__name(printResult,"printResult");var import_contracts2=__toESM(require_dist());import{access,mkdir,writeFile}from"fs/promises";import{dirname,join,relative,resolve}from"path";function parseActionFlags(argv,spec){const parsed={single:{},many:{},on:{},positional:[]};for(let index=0;index<argv.length;index+=1){const argument=argv[index];if(!argument.startsWith("--")){if(parsed.positional.length>=(spec.positional??0))throw new Error(`Unexpected argument: ${argument}`);parsed.positional.push(argument);continue}const separator=argument.indexOf("=");const name3=separator===-1?argument.slice(2):argument.slice(2,separator);if(spec.booleans?.includes(name3)){if(separator!==-1)throw new Error(`--${name3} takes no value.`);parsed.on[name3]=true;continue}if(!spec.values.includes(name3))throw new Error(`Unknown argument: ${argument}`);let value;if(separator!==-1){value=argument.slice(separator+1)}else{value=argv[index+1];index+=1}if(value===void 0||value===""||value.startsWith("--"))throw new Error(`--${name3} needs a value.`);if(spec.repeated?.includes(name3))(parsed.many[name3]??=[]).push(value);else if(parsed.single[name3]!==void 0)throw new Error(`--${name3} is given twice.`);else parsed.single[name3]=value}return parsed}__name(parseActionFlags,"parseActionFlags");var publish_default=`# Publishes this ENGINE action when a v* tag is pushed (docs/128 \xA78 step 4, \xA720 G4): its image, built
853
+ `)}__name(printError,"printError");function printFinding(finding){const badge=finding.severity==="error"?style.red(finding.advisory===true?"error (advisory)":"error"):style.yellow("warning");const at=finding.line===void 0?finding.file:`${finding.file}:${finding.line}:${finding.column??1}`;print(` ${badge} ${style.bold(at)}`);print(` ${finding.message}`);print(` ${style.green("fix:")} ${finding.fix}`);print(` ${style.grey(finding.rule)}`);print()}__name(printFinding,"printFinding");function printCheckSummary(counts){if(counts.errors===0&&counts.warnings===0){print(style.green("\u2713 No problems found."));return}const parts=[];if(counts.errors>0)parts.push(`${counts.errors} error${counts.errors===1?"":"s"}`);if(counts.warnings>0){parts.push(`${counts.warnings} warning${counts.warnings===1?"":"s"}`)}const summary=parts.join(", ");print(counts.errors>0?style.red(`\u2717 ${summary}.`):style.yellow(`${summary}.`))}__name(printCheckSummary,"printCheckSummary");function printEvent(event){const marker={info:style.grey("\xB7"),warn:style.yellow("!"),error:style.red("\u2717"),success:style.green("\u2713")}[event.level];print(` ${marker} ${event.message}`);if(event.data){print(` ${style.grey(JSON.stringify(event.data))}`)}}__name(printEvent,"printEvent");function printResult(result){const status={succeeded:style.green("succeeded"),failed:style.red("failed"),cancelled:style.yellow("cancelled")}[result.status];print();print(`${style.bold("Result")} ${status}`);print(` ${result.message}`);if(result.checks?.length){print();print(` ${style.bold("Checks")}`);for(const check of result.checks){const marker={passed:style.green("\u2713"),warning:style.yellow("!"),failed:style.red("\u2717")}[check.status];print(` ${marker} ${check.message}`);if(check.data)print(` ${style.grey(JSON.stringify(check.data))}`)}}if(result.outputs&&Object.keys(result.outputs).length>0){print();print(` ${style.bold("Outputs")}`);for(const[name3,value]of Object.entries(result.outputs)){print(` ${name3} = ${JSON.stringify(value)}`)}}if(result.rollbackCapture&&Object.keys(result.rollbackCapture).length>0){print();print(` ${style.bold("Rollback capture")} ${style.grey("(what a rollback would read)")}`);for(const[name3,value]of Object.entries(result.rollbackCapture)){print(` ${name3} = ${JSON.stringify(value)}`)}}if(result.error){print();print(` ${style.red("Error")} ${result.error.code}`);print(` ${result.error.message}`);if(result.error.retryable!==void 0){print(` ${style.grey(result.error.retryable?"retryable":"not retryable")}`)}}print()}__name(printResult,"printResult");var import_contracts2=__toESM(require_dist());import{access,mkdir,writeFile}from"fs/promises";import{dirname,join,relative,resolve}from"path";function parseActionFlags(argv,spec){const parsed={single:{},many:{},on:{},positional:[]};for(let index=0;index<argv.length;index+=1){const argument=argv[index];if(!argument.startsWith("--")){if(parsed.positional.length>=(spec.positional??0))throw new Error(`Unexpected argument: ${argument}`);parsed.positional.push(argument);continue}const separator=argument.indexOf("=");const name3=separator===-1?argument.slice(2):argument.slice(2,separator);if(spec.booleans?.includes(name3)){if(separator!==-1)throw new Error(`--${name3} takes no value.`);parsed.on[name3]=true;continue}if(!spec.values.includes(name3))throw new Error(`Unknown argument: ${argument}`);let value;if(separator!==-1){value=argument.slice(separator+1)}else{value=argv[index+1];index+=1}if(value===void 0||value===""||value.startsWith("--"))throw new Error(`--${name3} needs a value.`);if(spec.repeated?.includes(name3))(parsed.many[name3]??=[]).push(value);else if(parsed.single[name3]!==void 0)throw new Error(`--${name3} is given twice.`);else parsed.single[name3]=value}return parsed}__name(parseActionFlags,"parseActionFlags");var pull_request_template_default="## What this changes\n\n<!-- What the action does differently after this, and why. Name any check you added, removed or reworded. -->\n\n## Checks\n\n- [ ] Every refusal and decision code `validate` may raise is declared in `catalog.yaml` under `checks:`, each decision with the words a requester ticks\n- [ ] `npm test` passes: the typecheck, the build and every unit test \u2014 no Azure, no network\n- [ ] `npm run test:live` was run against a real resource, and each `--expect` drill raised exactly what it expected\n\n## Promotion checklist \u2014 before a beta version is followed by its GA version\n\nA beta (`vX.Y.Z-beta.N`) reaches only the workspaces that asked for betas. Its GA version is tagged only when\nevery box below is ticked, in the pull request that sets `capabilities.verified: true`.\n\n- [ ] Contract tests, including a sabotage proof per refusal: each refusal's test turns red when its check is broken\n- [ ] Every REFUSE and DECIDE path run against a real fixture estate, with the run recorded\n- [ ] The screens rendered: the plan, the approval and the run record, for a refusal and for a decision\n- [ ] Three clean runs in beta workspaces \u2014 each execute succeeded, no rollback failed, no protocol violation \u2014 counted from the platform's own database\n- [ ] README \"How it runs\" complete: what the action reads, what it refuses, what it changes, and what a rollback restores (or why there is none)\n";var publish_default=`# Publishes this ENGINE action when a v* tag is pushed (docs/128 \xA78 step 4, \xA720 G4): its image, built
854
854
  # FROM the action runtime by digest and pushed BY DIGEST to this repository's own package, then the
855
855
  # artifact (catalog-action/v2) naming that image by digest. Publishing makes it AVAILABLE; only a pin
856
856
  # in the console makes it live.
@@ -915,6 +915,12 @@ jobs:
915
915
  exit 1
916
916
  fi
917
917
 
918
+ # \u2605 THE ACTION'S OWN UNIT TESTS, AFTER THE BUILD AND BEFORE ANYTHING IS HANDED ON (docs/135 D4.5). They
919
+ # need no Azure and no network beyond the install above, so no token is given to them \u2014 this job holds
920
+ # none \u2014 and a tag whose tests fail uploads nothing, so no image is built from it.
921
+ - name: Run the unit tests
922
+ run: npm run test:unit
923
+
918
924
  # What the image is built from, for \`publish\`: dist/ and nothing else.
919
925
  - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
920
926
  with:
@@ -1050,31 +1056,36 @@ jobs:
1050
1056
  echo " \${line/=/: }"
1051
1057
  echo '\`\`\`'
1052
1058
  } >> "$GITHUB_STEP_SUMMARY"
1053
- `;var engine_action_repository_default={".github/workflows/publish.yml":publish_default};var name2="@runveric/action-sdk";var version2="0.1.0";var version3="0.27.7";var version4="5.9.3";var import_contracts=__toESM(require_dist());var ARM_AUDIENCE="https://management.azure.com";var SKELETON_RESOURCE_TYPE="Microsoft.Compute/disks";var CLI_BIN=Object.keys(bin)[0];var SKELETON_PARAMETERS={resourceGroup:"rg-example",resource:"example"};function scaffoldEngineAction(input){const repository=(0,import_contracts.actionRepositoryName)(input.key);const files=new Map;files.set("package.json",packageJson(repository,input.name));files.set("tsconfig.json",tsconfigJson());files.set("src/index.ts",actionSource(input.name));files.set("catalog.yaml",catalogYaml(input));files.set("test/params.json",`${JSON.stringify(SKELETON_PARAMETERS,null,2)}
1059
+ `;var engine_action_repository_default={".github/pull_request_template.md":pull_request_template_default,".github/workflows/publish.yml":publish_default};var name2="@runveric/action-sdk";var version2="0.2.0";var version3="0.27.7";var version4="5.9.3";var version5="2.1.9";var import_contracts=__toESM(require_dist());var ARM_AUDIENCE="https://management.azure.com";var EMPTY_EGRESS="starts no proxy; the sandbox does not yet block undeclared egress (docs/128 \xA715.5): declare every host you call";var SKELETON_RESOURCE_TYPE="Microsoft.Compute/disks";var CLI_BIN=Object.keys(bin)[0];var SKELETON_PARAMETERS={resourceGroup:"rg-example",resource:"example"};var SCAFFOLD_LOOP=[{command:"npm install",does:"the first time: writes package-lock.json \u2014 commit it (the publish workflow runs `npm ci --ignore-scripts`)",passesUntouched:true},{command:"npm test",does:"type-checks src/, builds dist/index.js, runs the unit tests \u2014 no Azure, no network",passesUntouched:true},{command:"npm run test:live",does:"validate, then a dry-run execute, against Azure with your own az login",passesUntouched:false}];function scaffoldEngineAction(input){const repository=(0,import_contracts.actionRepositoryName)(input.key);const files=new Map;files.set("package.json",packageJson(repository,input.name));files.set("tsconfig.json",tsconfigJson());files.set("src/index.ts",actionSource(input.name));files.set("src/assess.ts",assessSource(codesFor(input.key)));files.set("catalog.yaml",catalogYaml(input));files.set("test/assess.test.ts",assessTestSource(codesFor(input.key)));files.set("test/params.json",`${JSON.stringify(SKELETON_PARAMETERS,null,2)}
1054
1060
  `);files.set("test/prior-result.json",`${JSON.stringify(recordedExecute(),null,2)}
1055
- `);files.set("README.md",readme(input,repository));files.set(".gitignore","node_modules/\ndist/\n");const values=(0,import_contracts.workflowValues)({name,version});for(const[path,text]of Object.entries(engine_action_repository_default)){files.set(path,(0,import_contracts.renderTemplate)(`templates/engine-action-repository/${path}`,text,values))}return files}__name(scaffoldEngineAction,"scaffoldEngineAction");function packageJson(repository,name3){const phase=__name((phase2,extra="")=>`${CLI_BIN} action test --phase ${phase2} --params-file test/params.json${extra}`,"phase");return`${JSON.stringify({name:repository,private:true,description:`${name3} \u2014 ${import_contracts.BRAND_ARTICLE} ${import_contracts.BRAND_SHORT_NAME} engine action. Published from this repository by .github/workflows/publish.yml.`,scripts:{typecheck:"tsc -p tsconfig.json",build:"esbuild src/index.ts --bundle --platform=node --target=node22 --format=cjs --outfile=dist/index.js",test:["npm run typecheck","npm run build",phase("validate"),phase("execute"),phase("rollback"," --prior-result test/prior-result.json")].join(" && ")},dependencies:{[name2]:version2},devDependencies:{[name]:version,esbuild:version3,typescript:version4},engines:{node:">=22"}},null,2)}
1061
+ `);files.set("README.md",readme(input,repository));files.set(".gitignore","node_modules/\ndist/\n");const values=(0,import_contracts.workflowValues)({name,version});for(const[path,text]of Object.entries(engine_action_repository_default)){files.set(path,(0,import_contracts.renderTemplate)(`templates/engine-action-repository/${path}`,text,values))}return files}__name(scaffoldEngineAction,"scaffoldEngineAction");function packageJson(repository,name3){const phase=__name((phase2,extra="")=>`${CLI_BIN} action test --phase ${phase2} --params-file test/params.json${extra} --azure-token-from-az`,"phase");return`${JSON.stringify({name:repository,private:true,description:`${name3} \u2014 ${import_contracts.BRAND_ARTICLE} ${import_contracts.BRAND_SHORT_NAME} engine action. Published from this repository by .github/workflows/publish.yml.`,scripts:{typecheck:"tsc -p tsconfig.json",build:"esbuild src/index.ts --bundle --platform=node --target=node22 --format=cjs --outfile=dist/index.js","test:unit":"vitest run",test:["npm run typecheck","npm run build","npm run test:unit"].join(" && "),"test:live":["npm run build",phase("validate"),phase("execute"," --dry-run")].join(" && ")},dependencies:{[name2]:version2},devDependencies:{[name]:version,esbuild:version3,typescript:version4,vitest:version5},engines:{node:">=22"}},null,2)}
1056
1062
  `}__name(packageJson,"packageJson");function tsconfigJson(){return`${JSON.stringify({compilerOptions:{strict:true,noEmit:true,target:"es2022",module:"nodenext",moduleResolution:"nodenext",types:[],skipLibCheck:true},include:["src"]},null,2)}
1057
- `}__name(tsconfigJson,"tsconfigJson");function actionSource(name3){return[`import { defineAction, type ValidationCheck } from "${name2}";`,"","/**",` * ${name3} \u2014 ${import_contracts.BRAND_ARTICLE} ${import_contracts.BRAND_SHORT_NAME} engine action.`," *"," * validate reports facts about each target; the engine decides what they mean."," * execute acts on ONE target \u2014 after making a restore point durable."," * rollback restores from that restore point, and nothing else."," *"," * `ctx.azure` is a TokenCredential for exactly the audiences catalog.yaml declares, usable with the"," * official Azure SDK clients. Every TODO below is yours."," */","export default defineAction({"," async validate(ctx) {"," return Object.fromEntries("," ctx.targets.map((target): [string, ValidationCheck[]] => ["," target.ref,"," // TODO: read the resource and report what an approver needs to know \u2014 a REFUSE check stops"," // the run, a DECIDE check asks the requester.",' [{ level: "info", title: `${String(target.parameters.resource)} is ready to act on.` }],'," ]),"," );"," },",""," async execute(ctx) {"," const { ref, parameters } = ctx.target;",' if (ctx.dryRun) return { status: "succeeded", message: `Would act on ${ref}.` };',""," // \u2605 THE RESTORE POINT FIRST. It returns only once the engine has made it durable, and the engine"," // refuses a destructive success it never acknowledged one for. Record what rollback needs."," await ctx.saveRestorePoint({"," resourceGroup: String(parameters.resourceGroup),"," resource: String(parameters.resource),"," });",' await ctx.emit({ level: "info", message: `Acting on ${ref}.` });'," // TODO: act on the resource.",' return { status: "succeeded", message: `Acted on ${ref}.`, data: { ref } };'," },",""," async rollback(ctx) {"," const recorded = ctx.restorePoint;",' if (typeof recorded?.resource !== "string") {',' return { status: "failed", message: "No restore point was recorded, so there is nothing to restore from." };'," }"," // TODO: put the resource back as the restore point recorded it.",' return { status: "succeeded", message: `Restored ${recorded.resource} from its restore point.` };'," },","});",""].join("\n")}__name(actionSource,"actionSource");function recordedExecute(){return{restorePoint:{resourceGroup:SKELETON_PARAMETERS.resourceGroup,resource:SKELETON_PARAMETERS.resource},outcome:{status:"succeeded",message:`Acted on ${SKELETON_PARAMETERS.resource}.`}}}__name(recordedExecute,"recordedExecute");function catalogYaml(input){const quoted=__name(value=>JSON.stringify(value),"quoted");return["# The manifest the catalog reads. The catalog repository's release workflow publishes it with the","# image .github/workflows/publish.yml builds; every TODO is yours before the first tag.",'declares: "definition+version"',`key: ${quoted(input.key)}`,`name: ${quoted(input.name)}`,'summary: "TODO: one sentence an operator reads in the catalog."','description: "TODO: what the action does, what it refuses, and what a rollback restores."','category: "storage"',`connectorKey: ${quoted(import_contracts.ENGINE_CONNECTOR_KEY)}`,'riskLevel: "high"','maintainer: "TODO: the team that answers for this action"',"execution:",' kind: "engine"',` contract: ${quoted(import_contracts.ACTION_PROTOCOL_V1)}`," # host:port \u2014 the ONLY destinations the job may reach. Empty: it reaches nothing. When your code",' # calls Azure Resource Manager, add "management.azure.com:443".'," egress: []"," audiences:",` - ${quoted(ARM_AUDIENCE)}`,"capabilities:"," verified: false"," rollback: true"," approvalDefault: true"," dryRun: true"," destructive: true","# A beta: offered only to the workspaces that asked for betas. The tag that publishes it equals it.",`version: ${quoted(import_contracts.FIRST_ACTION_VERSION)}`,"params:",' - id: "resourceGroup"',' label: "Resource group"',' control: "text"',' hint: "The resource group that holds the resource"'," required: true"," source:",' discover: "azure/resourceGroup"'," # The target: listed from ARM by the type it declares, inside the group chosen above.",' - id: "resource"',' label: "Resource"',' control: "text"',' hint: "The resource to act on"'," required: true"," source:",' discover: "azure/arm"',` resourceType: ${quoted(SKELETON_RESOURCE_TYPE)}`," dependsOn:",' - "resourceGroup"',"requiredPermissions:",' - role: "Reader"',' scope: "Subscription"',' kind: "Built-in role"',"workflow:",' - n: "01"',' title: "Check"',' body: "TODO: what validate reads, and what it refuses."',' - n: "02"',' title: "Record"',' body: "Make a restore point durable before anything changes."',' - n: "03"',' title: "Act"',' body: "TODO: what execute changes; a rollback restores it from the restore point."',""].join("\n")}__name(catalogYaml,"catalogYaml");function readme(input,repository){return[`# ${input.name}`,"",`\`${input.key}\` \u2014 ${import_contracts.BRAND_ARTICLE} ${import_contracts.BRAND_SHORT_NAME} engine action. Its code is \`src/index.ts\`, its manifest`,"`catalog.yaml`. It runs as its own image, one isolated job per phase, built `FROM` the action runtime.","","## The loop","","```sh","npm install # the first time: writes package-lock.json \u2014 commit it (the publish workflow runs `npm ci --ignore-scripts`)","npm test # type-checks src/, builds dist/index.js, then validate, execute and rollback through a local engine","```","",`\`npm test\` runs each phase with \`${CLI_BIN} action test\`: your built \`dist/index.js\`, the real action runtime`,"and every message checked by the protocol's own parsers \u2014 with a local engine that acknowledges","checkpoints and names targets the way the platform does. One phase by hand:","","```sh",`npx ${CLI_BIN} action test --phase validate --param resourceGroup=rg-example --param resource=example`,`npx ${CLI_BIN} action test --phase execute --params-file test/params.json --dry-run`,`npx ${CLI_BIN} action test --phase execute --params-file test/params.json --azure-token-from-az`,"```","","`--azure-token-from-az` hands the action ONE token for Azure Resource Manager from your own `az login`,","held in memory for that run and never written or printed. Without it the action gets no credential.","",`**This is a development loop, not the gate.** When the action runs in ${import_contracts.BRAND_SHORT_NAME}, the engine judges every`,"message again, and the catalog's release workflow verifies and signs the image before anything can","run it.","","## Before the first tag","","- Replace every TODO in `catalog.yaml` and `src/index.ts`.","- `execution.egress` is empty, so the job reaches nothing. When the code calls Azure Resource Manager,",' add `"management.azure.com:443"`.',"- `resourceType` is the ARM type the picker lists for the `resource` parameter.","- `requiredPermissions` says what the connection's identity needs; Reader at the subscription reads only.","","## Publishing","",`Push a tag equal to \`catalog.yaml\`'s \`version\` (\`${import_contracts.FIRST_ACTION_VERSION}\` first). \`.github/workflows/publish.yml\``,"runs two jobs. `build`, which can write nothing, installs with `npm ci --ignore-scripts` (no dependency's install","script runs), type-checks `src/` and builds `dist/index.js`. `publish` installs nothing: it builds the image FROM the",`action runtime by digest, pushes it by digest to this repository's package (\`${repository}\`), and publishes the`,"catalog artifact; it prints the line for the catalog repository's `release.yaml`, whose release workflow verifies and","signs the image.","","Do not edit `.github/workflows/publish.yml`: it is planted from the product's templates, and the","template sync replaces it.",""].join("\n")}__name(readme,"readme");var ACTION_INIT_USAGE="action init [directory] --key <provider.resource.verb> --name <text>";async function runActionInit(argv){const flags=parseActionFlags(argv,{values:["key","name"],positional:1});const key=flags.single.key?.trim();if(!key)throw new Error('--key is required: the action key, <provider>.<resource>.<verb> \u2014 e.g. --key "azure.disk.snapshot".');const refusal=(0,import_contracts2.actionKeyRefusal)(key);if(refusal!==null)throw new Error(refusal);const name3=flags.single.name?.trim();if(!name3)throw new Error('--name is required: what an operator sees in the catalog \u2014 e.g. --name "Snapshot Disk".');const directory=resolve(flags.positional[0]??(0,import_contracts2.actionRepositoryName)(key));const files=scaffoldEngineAction({key,name:name3});const existing=[];for(const path of files.keys()){if(await access(join(directory,path)).then(()=>true,()=>false))existing.push(path)}if(existing.length>0){throw new Error(`${directory} already has ${existing.join(", ")}. action init never overwrites \u2014 remove ${existing.length===1?"it":"them"}, or run it somewhere else. Nothing was written.`)}for(const[path,contents]of files){const target=join(directory,path);await mkdir(dirname(target),{recursive:true});await writeFile(target,contents,{flag:"wx"}).catch(error=>{throw error.code==="EEXIST"?new Error(`${target} appeared while action init was writing. It never overwrites; it stopped there.`):error})}const below=relative(process.cwd(),directory);const shown=below===""?".":below.startsWith("..")?directory:below;print();print(`${style.green("\u2713")} Created ${style.bold(shown)} \u2014 the engine action ${style.bold(key)}`);print();for(const path of files.keys())print(` ${style.grey(path)}`);print();print("It builds and passes its own test before you change anything:");print();print(` ${style.bold("cd")} ${shown}`);print(` ${style.bold("npm install")} ${style.grey("# writes package-lock.json \u2014 commit it; the publish workflow runs npm ci --ignore-scripts")}`);print(` ${style.bold("npm test")} ${style.grey("# type-checks src/, builds, then validate, execute and rollback through a local engine")}`);print()}__name(runActionInit,"runActionInit");var import_action_runtime=__toESM(require_dist3());var import_contracts3=__toESM(require_dist());import{execFile}from"child_process";import{access as access2,readFile}from"fs/promises";import{createRequire}from"module";import{join as join2,resolve as resolve2}from"path";import{promisify}from"util";import{parse as parseYaml}from"yaml";var runProgram=promisify(execFile);var ACTION_TEST_USAGE="action test --phase validate|execute|rollback [--param <name=value>]\u2026 [--params-file <path>]\n [--prior-result <path>] [--dry-run] [--azure-token-from-az] [--dir <path>]";var PHASES={validate:"validate",execute:"run",rollback:"rollback"};var CATALOG_PROVIDER="azure";var LOCAL_SUBSCRIPTION_ID="00000000-0000-0000-0000-000000000000";var LOCAL_DEADLINE_MS=15*60*1e3;var LOCAL_RUN="local-test";var CLI_BIN2=Object.keys(bin)[0];var LOCAL_TOKEN_HOLDER={noun:"action",whereDeclared:`\`${CLI_BIN2} action test\` hands an action at most one token: Azure Resource Manager's, from your own az login, when run with --azure-token-from-az. In ${import_contracts3.BRAND_SHORT_NAME}, the engine mints one for each audience catalog.yaml declares in execution.audiences.`,whyNoMore:"The token from your az login expired during this test; run it again."};async function runActionTest(argv){const flags=parseActionFlags(argv,{values:["phase","param","params-file","prior-result","dir"],repeated:["param"],booleans:["dry-run","azure-token-from-az"]});const phase=flags.single.phase;if(phase===void 0||!Object.hasOwn(PHASES,phase)){throw new Error(`--phase is ${phase===void 0?"required":`"${phase}", which is not a phase`}: ${Object.keys(PHASES).join(", ")} \u2014 one at a time.`)}if(flags.single["prior-result"]!==void 0&&phase!=="rollback"){throw new Error("--prior-result is what a rollback reads; it means nothing to a "+phase+".")}const directory=resolve2(flags.single.dir??".");const manifest=await engineManifest(directory);const entry=join2(directory,"dist","index.js");if(!await access2(entry).then(()=>true,()=>false)){throw new Error("dist/index.js does not exist. Build first (npm run build): the runtime loads that one file and nothing else.")}const parameters=await parametersOf(manifest.params,flags.single["params-file"],flags.many.param??[]);const parameterSchema=(0,import_contracts3.catalogParameterSchema)(manifest.params);let tokens2=[];let subscription=LOCAL_SUBSCRIPTION_ID;if(flags.on["azure-token-from-az"]){if(!manifest.audiences.includes(ARM_AUDIENCE)){throw new Error(`--azure-token-from-az hands the action a token for ${ARM_AUDIENCE}, and catalog.yaml's execution.audiences does not declare it (${manifest.audiences.join(", ")||"none"}). The engine would mint none for it either.`)}const fromAz=await armTokenFromAz();tokens2=[fromAz.token];subscription=fromAz.subscription}const target=(0,import_contracts3.engineRunTarget)({key:manifest.key,parameterSchema,provider:CATALOG_PROVIDER,parameters,providerScopeId:subscription});const prior=phase==="rollback"?await priorOf(flags.single["prior-result"]):{restorePoint:null,priorResult:null};const invocation=invocationFor(PHASES[phase],manifest,target,flags.on["dry-run"]===true,tokens2,prior);let definition;try{definition=(0,import_action_runtime.actionOf)(createRequire(entry)(entry),"dist/index.js")}catch(error){throw new Error(`dist/index.js could not be loaded as an action: ${messageOf(error)}`)}const secrets=tokens2.map(token2=>token2.token);const shown=__name(value=>(0,import_contracts3.redactJwtShaped)((0,import_contracts3.redactSecrets)(value,secrets)),"shown");print();print(`${style.bold("action test")} ${manifest.key} ${manifest.version} ${style.grey(`phase ${phase}${flags.on["dry-run"]?", dry run":""}`)}`);print(` target ${target.ref}`);print(` credential ${tokens2.length>0?`ONE token for Azure Resource Manager from your az login ${style.grey(`(subscription ${subscription}) \u2014 YOUR access, not ${import_contracts3.BRAND_SHORT_NAME}'s, held in memory only`)}`:style.grey(`none \u2014 the subscription is a placeholder; --azure-token-from-az hands the action your az login's ARM token`)}`);print(` network ${manifest.egress.length>0?`${style.yellow("open")} ${style.grey(`\u2014 execution.egress (${manifest.egress.join(", ")}) is NOT enforced here; the sandbox enforces it`)}`:`${style.yellow("open")} ${style.grey("\u2014 execution.egress is empty, so the sandbox lets this action reach nothing; nothing here enforces that")}`}`);print(` engine ${style.grey("local: the protocol's parsers on every message, every checkpoint acknowledged")}`);print();print(style.bold("Events"));const engine=new LocalEngine(invocation,shown);let failure=null;try{await(0,import_action_runtime.runAction)(definition,new import_action_runtime.LoopbackTransport(engine),{tokenHolder:LOCAL_TOKEN_HOLDER})}catch(error){failure=messageOf(error)}if(engine.events===0)print(style.grey(" (the action emitted nothing)"));const code=verdict(phase,manifest,invocation,engine,shown,failure);print(style.grey(`A development loop, not the gate: when the action runs in ${import_contracts3.BRAND_SHORT_NAME}, the engine judges every message again, and the catalog's release workflow verifies and signs its image first.`));print();return code}__name(runActionTest,"runActionTest");var LocalEngine=class LocalEngine2{static{__name(this,"LocalEngine")}sent;shown;events=0;violation=null;acknowledged=null;parsed=null;constructor(sent,shown){this.sent=sent;this.shown=shown}async invocation(){return this.sent}async event(body){const event=this.judged(()=>(0,import_contracts3.parseActionEvent)(body,this.sent.limits,this.events));this.events+=1;printEvent((0,import_contracts3.redactJwtShaped)(event))}async checkpoint(body){const checkpoint=this.judged(()=>(0,import_contracts3.parseActionCheckpoint)(body,this.sent.limits));this.acknowledged=checkpoint.record;print(` ${style.green("\u2713")} restore point acknowledged ${style.grey(JSON.stringify(this.shown(checkpoint.record)))}`);return{acknowledged:true}}async report(body){this.parsed=this.judged(()=>(0,import_contracts3.parseActionReport)(body,this.sent))}judged(parse){try{return parse()}catch(error){this.violation??=messageOf(error);throw error}}};function verdict(phase,manifest,invocation,engine,shown,failure){if(engine.violation!==null){printError(style.red(`
1063
+ `}__name(tsconfigJson,"tsconfigJson");function actionSource(name3){return[`import { defineAction, type ValidationCheck } from "${name2}";`,'import { assess } from "./assess";',"","/**",` * ${name3} \u2014 ${import_contracts.BRAND_ARTICLE} ${import_contracts.BRAND_SHORT_NAME} engine action.`," *"," * validate reads each target and reports what `assess` makes of it; the engine decides what it means."," * execute acts on ONE target \u2014 after making a restore point durable."," * rollback restores from that restore point, and nothing else."," *"," * `ctx.azure` is a TokenCredential for exactly the audiences catalog.yaml declares, usable with the"," * official Azure SDK clients. Every TODO below is yours."," */","export default defineAction({"," async validate(ctx) {"," return Object.fromEntries("," ctx.targets.map((target): [string, ValidationCheck[]] => ["," target.ref,"," // TODO: READ the resource from Azure Resource Manager with ctx.azure \u2014 each source as"," // { ok: true, value } or, when it could not be read, { ok: false, reason }. Never guess one."," assess({ resource: { ok: true, value: { name: String(target.parameters.resource), changedAt: null } }, now: new Date() }),"," ]),"," );"," },",""," async execute(ctx) {"," const { ref, parameters } = ctx.target;",' if (ctx.dryRun) return { status: "succeeded", message: `Would act on ${ref}.` };',""," // \u2605 THE RESTORE POINT FIRST. It returns only once the engine has made it durable, and the engine"," // refuses a destructive success it never acknowledged one for. Record what rollback needs."," // An action that cannot be undone (rollback: false) saves its before-state here instead: the"," // record of what it is about to destroy, which restores nothing and is what an auditor reads."," // TODO: before you act, re-check the target with the same readers and `assess` \u2014 and stop on"," // anything at error (settleDecisionChecks, from the SDK, raises a decision nobody made to error)."," await ctx.saveRestorePoint({"," resourceGroup: String(parameters.resourceGroup),"," resource: String(parameters.resource),"," });",' await ctx.emit({ level: "info", message: `Acting on ${ref}.` });'," // TODO: act on the resource.",' return { status: "succeeded", message: `Acted on ${ref}.`, data: { ref } };'," },",""," async rollback(ctx) {"," const recorded = ctx.restorePoint;",' if (typeof recorded?.resource !== "string") {',' return { status: "failed", message: "No restore point was recorded, so there is nothing to restore from." };'," }"," // TODO: put the resource back as the restore point recorded it.",' return { status: "succeeded", message: `Restored ${recorded.resource} from its restore point.` };'," },","});",""].join("\n")}__name(actionSource,"actionSource");function codesFor(key){const segment=key.split(".")[1];return{unreadable:`${segment}.unreadable`,recentlyChanged:`${segment}.recentlyChanged`}}__name(codesFor,"codesFor");function assessSource(codes){return[`import type { ValidationCheck } from "${name2}";`,"","/** One source, as validate read it: its value, or why it could not be read. Never a guess. */","export type Read<T> = { ok: true; value: T } | { ok: false; reason: string };","","/** What validate read about ONE target. TODO: one field per source your action's checks need. */","export interface Evidence {"," resource: Read<{ name: string; changedAt: string | null }>;"," now: Date;","}","","const WEEK_MS = 7 * 86_400_000;","","/**"," * The checks for one target \u2014 PURE, so `npm run test:unit` covers every branch with no Azure. Every"," * code here is declared in catalog.yaml's checks:, and the engine refuses a code that is not."," */","export function assess({ resource, now }: Evidence): ValidationCheck[] {"," if (!resource.ok) {",` return [{ level: "error", refusal: ${JSON.stringify(codes.unreadable)}, title: \`It could not be read: \${resource.reason}.\` }];`," }"," const { name, changedAt } = resource.value;",' const checks: ValidationCheck[] = [{ level: "info", title: `${name} is ready to act on.` }];'," if (changedAt !== null && now.getTime() - Date.parse(changedAt) < WEEK_MS) {"," checks.push({",' level: "warn",',` decision: ${JSON.stringify(codes.recentlyChanged)},`," title: `${name} changed on ${changedAt.slice(0, 10)}, within the last week.`,"," });"," }"," return checks;","}",""].join("\n")}__name(assessSource,"assessSource");function assessTestSource(codes){return['import { describe, expect, it } from "vitest";','import { assess } from "../src/assess";',"",'const NOW = new Date("2026-10-17T12:00:00.000Z");','const read = (changedAt: string | null) => ({ ok: true as const, value: { name: "example", changedAt } });',"",'describe("assess \u2014 every branch, with no Azure", () => {',' it("refuses a resource it could not read, saying why \u2014 never a guess", () => {',' expect(assess({ resource: { ok: false, reason: "403 from ARM" }, now: NOW })).toEqual([',` { level: "error", refusal: ${JSON.stringify(codes.unreadable)}, title: "It could not be read: 403 from ARM." },`," ]);"," });","",' it("asks the requester about a resource changed within the last week", () => {',' expect(assess({ resource: read("2026-10-15T09:00:00.000Z"), now: NOW })).toContainEqual({',' level: "warn",',` decision: ${JSON.stringify(codes.recentlyChanged)},`,' title: "example changed on 2026-10-15, within the last week.",'," });"," });","",' it("says a resource nobody changed lately is ready, and asks nothing", () => {',' expect(assess({ resource: read(null), now: NOW })).toEqual([{ level: "info", title: "example is ready to act on." }]);',' expect(assess({ resource: read("2026-09-01T00:00:00.000Z"), now: NOW })).toHaveLength(1);'," });","});",""].join("\n")}__name(assessTestSource,"assessTestSource");function recordedExecute(){return{restorePoint:{resourceGroup:SKELETON_PARAMETERS.resourceGroup,resource:SKELETON_PARAMETERS.resource},outcome:{status:"succeeded",message:`Acted on ${SKELETON_PARAMETERS.resource}.`}}}__name(recordedExecute,"recordedExecute");function catalogYaml(input){const quoted=__name(value=>JSON.stringify(value),"quoted");return["# The manifest the catalog reads. The catalog repository's release workflow publishes it with the","# image .github/workflows/publish.yml builds; every TODO is yours before the first tag.",'declares: "definition+version"',`key: ${quoted(input.key)}`,`name: ${quoted(input.name)}`,'summary: "TODO: one sentence an operator reads in the catalog."','description: "TODO: what the action does, what it refuses, and what a rollback restores."','category: "storage"',`connectorKey: ${quoted(import_contracts.ENGINE_CONNECTOR_KEY)}`,'riskLevel: "high"','maintainer: "TODO: the team that answers for this action"',"execution:",' kind: "engine"',` contract: ${quoted(import_contracts.ACTION_PROTOCOL_V1)}`," # host:port \u2014 every destination the job calls. When your code calls Azure Resource Manager, add",' # "management.azure.com:443". Empty: it '+EMPTY_EGRESS+"."," egress: []"," audiences:",` - ${quoted(ARM_AUDIENCE)}`,"capabilities:"," verified: false"," rollback: true"," approvalDefault: true"," dryRun: true"," destructive: true","# Every refusal and decision code validate may raise (src/assess.ts) \u2014 the engine refuses a report","# raising any other. A code is <segment>.<camelCase>; never one of the built-in actions' own. Each","# decision's acknowledgement is the label on the box a requester ticks: what they agree to, the same","# for every target. Anything about one target goes in the title of the check that raises it.","checks:"," refusals:",` - code: ${quoted(codesFor(input.key).unreadable)}`,' title: "Could not be read"'," decisions:",` - code: ${quoted(codesFor(input.key).recentlyChanged)}`,' title: "Changed within the last week"',' acknowledgement: "Act on it even though it changed recently"',"# A beta: offered only to the workspaces that asked for betas. The tag that publishes it equals it.",`version: ${quoted(import_contracts.FIRST_ACTION_VERSION)}`,"params:",' - id: "resourceGroup"',' label: "Resource group"',' control: "text"',' hint: "The resource group that holds the resource"'," required: true"," source:",' discover: "azure/resourceGroup"'," # The target: listed from ARM by the type it declares, inside the group chosen above.",' - id: "resource"',' label: "Resource"',' control: "text"',' hint: "The resource to act on"'," required: true"," source:",' discover: "azure/arm"',` resourceType: ${quoted(SKELETON_RESOURCE_TYPE)}`," dependsOn:",' - "resourceGroup"',"requiredPermissions:",' - role: "Reader"',' scope: "Subscription"',' kind: "Built-in role"',"workflow:",' - n: "01"',' title: "Check"',' body: "TODO: what validate reads, and what it refuses."',' - n: "02"',' title: "Record"',' body: "Make a restore point durable before anything changes."',' - n: "03"',' title: "Act"',' body: "TODO: what execute changes; a rollback restores it from the restore point."',""].join("\n")}__name(catalogYaml,"catalogYaml");function readme(input,repository){return[`# ${input.name}`,"",`\`${input.key}\` \u2014 ${import_contracts.BRAND_ARTICLE} ${import_contracts.BRAND_SHORT_NAME} engine action. Its code is \`src/index.ts\`, its manifest`,"`catalog.yaml`. It runs as its own image, one isolated job per phase, built `FROM` the action runtime.","","## The loop","","```sh",...SCAFFOLD_LOOP.map(step=>`${step.command.padEnd(19)}# ${step.does}`),"```","","`npm run test:unit` is what the publish workflow runs before every image is built: keep `src/assess.ts`","pure and every branch covered. `test:live` runs each phase with",`\`${CLI_BIN} action test\`: your built \`dist/index.js\`, the real action runtime and every message checked`,"by the protocol's own parsers \u2014 with a local engine that acknowledges checkpoints, names targets the way","the platform does and refuses a code `catalog.yaml` does not declare. One phase by hand:","","```sh",`npx ${CLI_BIN} action test --phase validate --param resourceGroup=rg-example --param resource=example`,`npx ${CLI_BIN} action test --phase validate --params-file test/params.json --expect ${codesFor(input.key).unreadable}`,`npx ${CLI_BIN} action test --phase execute --params-file test/params.json --dry-run`,`npx ${CLI_BIN} action test --phase execute --params-file test/params.json --decide ${codesFor(input.key).recentlyChanged} --azure-token-from-az`,"```","","`--expect <code>` makes a validate exit 0 only when exactly those codes were raised \u2014 a drill against","a real resource, scripted. `--decide <code>` hands an execute what a requester decided.","`--azure-token-from-az` hands the action ONE token for Azure Resource Manager from your own `az login`,","held in memory for that run and never written or printed. Without it the action gets no credential.","",`**This is a development loop, not the gate.** When the action runs in ${import_contracts.BRAND_SHORT_NAME}, the engine judges every`,"message again, and the catalog's release workflow verifies and signs the image before anything can","run it.","","## Before the first tag","","- Replace every TODO in `catalog.yaml`, `src/index.ts` and `src/assess.ts`.","- `checks:` in `catalog.yaml` declares every refusal and decision code `validate` may raise, and the"," words on each decision's box; the engine refuses a code it does not declare.","- `execution.egress` is empty, which "+EMPTY_EGRESS+". When the code calls Azure Resource Manager,",' add `"management.azure.com:443"`.',"- `resourceType` is the ARM type the picker lists for the `resource` parameter \u2014 a top-level type.","- `requiredPermissions` says what the connection's identity needs; Reader at the subscription reads only.","- `.github/pull_request_template.md` holds the promotion checklist a beta answers before its GA version.","","## Publishing","",`Push a tag equal to \`catalog.yaml\`'s \`version\` (\`${import_contracts.FIRST_ACTION_VERSION}\` first). \`.github/workflows/publish.yml\``,"runs two jobs. `build`, which can write nothing, installs with `npm ci --ignore-scripts` (no dependency's install","script runs), type-checks `src/`, builds `dist/index.js` and runs `npm run test:unit`. `publish` installs nothing: it builds the image FROM the",`action runtime by digest, pushes it by digest to this repository's package (\`${repository}\`), and publishes the`,"catalog artifact; it prints the line for the catalog repository's `release.yaml`, whose release workflow verifies and","signs the image.","","Do not edit `.github/workflows/publish.yml`: it is planted from the product's templates, and the","template sync replaces it.",""].join("\n")}__name(readme,"readme");var ACTION_INIT_USAGE="action init [directory] --key <provider.resource.verb> --name <text>";async function runActionInit(argv){const flags=parseActionFlags(argv,{values:["key","name"],positional:1});const key=flags.single.key?.trim();if(!key)throw new Error('--key is required: the action key, <provider>.<resource>.<verb> \u2014 e.g. --key "azure.disk.snapshot".');const refusal=(0,import_contracts2.actionKeyRefusal)(key);if(refusal!==null)throw new Error(refusal);const name3=flags.single.name?.trim();if(!name3)throw new Error('--name is required: what an operator sees in the catalog \u2014 e.g. --name "Snapshot Disk".');const directory=resolve(flags.positional[0]??(0,import_contracts2.actionRepositoryName)(key));const files=scaffoldEngineAction({key,name:name3});const existing=[];for(const path of files.keys()){if(await access(join(directory,path)).then(()=>true,()=>false))existing.push(path)}if(existing.length>0){throw new Error(`${directory} already has ${existing.join(", ")}. action init never overwrites \u2014 remove ${existing.length===1?"it":"them"}, or run it somewhere else. Nothing was written.`)}for(const[path,contents]of files){const target=join(directory,path);await mkdir(dirname(target),{recursive:true});await writeFile(target,contents,{flag:"wx"}).catch(error=>{throw error.code==="EEXIST"?new Error(`${target} appeared while action init was writing. It never overwrites; it stopped there.`):error})}const below=relative(process.cwd(),directory);const shown=below===""?".":below.startsWith("..")?directory:below;print();print(`${style.green("\u2713")} Created ${style.bold(shown)} \u2014 the engine action ${style.bold(key)}`);print();for(const path of files.keys())print(` ${style.grey(path)}`);print();print("It builds and passes its own test before you change anything:");print();print(` ${style.bold("cd")} ${shown}`);for(const step of SCAFFOLD_LOOP.filter(each=>each.passesUntouched)){print(` ${style.bold(step.command.padEnd(14))}${style.grey(`# ${step.does.replaceAll("`","")}`)}`)}print()}__name(runActionInit,"runActionInit");var import_action_runtime=__toESM(require_dist3());var import_contracts3=__toESM(require_dist());import{execFile}from"child_process";import{access as access2,readFile}from"fs/promises";import{createRequire}from"module";import{join as join2,resolve as resolve2}from"path";import{promisify}from"util";import{parse as parseYaml}from"yaml";var runProgram=promisify(execFile);var ACTION_TEST_USAGE="action test --phase validate|execute|rollback [--param <name=value>]\u2026 [--params-file <path>]\n [--expect <code>]\u2026 [--decide <code>]\u2026 [--prior-result <path>] [--dry-run]\n [--azure-token-from-az] [--dir <path>]";var PHASES={validate:"validate",execute:"run",rollback:"rollback"};var CATALOG_PROVIDER="azure";var LOCAL_SUBSCRIPTION_ID="00000000-0000-0000-0000-000000000000";var LOCAL_DEADLINE_MS=15*60*1e3;var LOCAL_RUN="local-test";var CLI_BIN2=Object.keys(bin)[0];var LOCAL_TOKEN_HOLDER={noun:"action",whereDeclared:`\`${CLI_BIN2} action test\` hands an action at most one token: Azure Resource Manager's, from your own az login, when run with --azure-token-from-az. In ${import_contracts3.BRAND_SHORT_NAME}, the engine mints one for each audience catalog.yaml declares in execution.audiences.`,whyNoMore:"The token from your az login expired during this test; run it again."};async function runActionTest(argv){const flags=parseActionFlags(argv,{values:["phase","param","params-file","prior-result","dir","decide","expect"],repeated:["param","decide","expect"],booleans:["dry-run","azure-token-from-az"]});const phase=flags.single.phase;if(phase===void 0||!Object.hasOwn(PHASES,phase)){throw new Error(`--phase is ${phase===void 0?"required":`"${phase}", which is not a phase`}: ${Object.keys(PHASES).join(", ")} \u2014 one at a time.`)}if(flags.single["prior-result"]!==void 0&&phase!=="rollback"){throw new Error("--prior-result is what a rollback reads; it means nothing to a "+phase+".")}const decided=flags.many.decide??[];if(decided.length>0&&phase==="validate"){throw new Error("--decide is a decision a requester made, which an execute or a rollback receives; a validate is the plan, where the requester is still being asked.")}const expected=flags.many.expect??[];if(expected.length>0&&phase!=="validate"){throw new Error(`--expect compares the codes a validate raises; a ${phase} reports an outcome, not checks.`)}const directory=resolve2(flags.single.dir??".");const manifest=await engineManifest(directory);const recorded=decisionsDecided(decided,manifest.checks);const declaredCodes=(0,import_contracts3.declaredCodesOf)(manifest.checks);const raisable=[...declaredCodes.refusals,...declaredCodes.decisions];for(const code2 of expected){if(!raisable.includes(code2)){throw new Error(`--expect "${code2}" is not a code catalog.yaml declares, so no run of this action could raise it. It declares: ${declaredList(manifest.checks)||"none"}.`)}}const entry=join2(directory,"dist","index.js");if(!await access2(entry).then(()=>true,()=>false)){throw new Error("dist/index.js does not exist. Build first (npm run build): the runtime loads that one file and nothing else.")}const parameters=await parametersOf(manifest.params,flags.single["params-file"],flags.many.param??[]);const parameterSchema=(0,import_contracts3.catalogParameterSchema)(manifest.params);let tokens2=[];let subscription=LOCAL_SUBSCRIPTION_ID;if(flags.on["azure-token-from-az"]){if(!manifest.audiences.includes(ARM_AUDIENCE)){throw new Error(`--azure-token-from-az hands the action a token for ${ARM_AUDIENCE}, and catalog.yaml's execution.audiences does not declare it (${manifest.audiences.join(", ")||"none"}). The engine would mint none for it either.`)}const fromAz=await armTokenFromAz();tokens2=[fromAz.token];subscription=fromAz.subscription}const target=(0,import_contracts3.engineRunTarget)({key:manifest.key,parameterSchema,provider:CATALOG_PROVIDER,parameters,providerScopeId:subscription});const prior=phase==="rollback"?await priorOf(flags.single["prior-result"]):{restorePoint:null,priorResult:null};const invocation=invocationFor(PHASES[phase],manifest,target,flags.on["dry-run"]===true,tokens2,prior,recorded);let definition;try{definition=(0,import_action_runtime.actionOf)(createRequire(entry)(entry),"dist/index.js")}catch(error){throw new Error(`dist/index.js could not be loaded as an action: ${messageOf(error)}`)}const secrets=tokens2.map(token2=>token2.token);const shown=__name(value=>(0,import_contracts3.redactJwtShaped)((0,import_contracts3.redactSecrets)(value,secrets)),"shown");print();print(`${style.bold("action test")} ${manifest.key} ${manifest.version} ${style.grey(`phase ${phase}${flags.on["dry-run"]?", dry run":""}`)}`);print(` target ${target.ref}`);print(` credential ${tokens2.length>0?`ONE token for Azure Resource Manager from your az login ${style.grey(`(subscription ${subscription}) \u2014 YOUR access, not ${import_contracts3.BRAND_SHORT_NAME}'s, held in memory only`)}`:style.grey(`none \u2014 the subscription is a placeholder; --azure-token-from-az hands the action your az login's ARM token`)}`);print(` network ${manifest.egress.length>0?`${style.yellow("open")} ${style.grey(`\u2014 execution.egress (${manifest.egress.join(", ")}) is not applied here; in the sandbox it starts a proxy that allows only those hosts (docs/128 \xA715.5)`)}`:`${style.yellow("open")} ${style.grey(`\u2014 execution.egress is empty, which ${EMPTY_EGRESS}`)}`}`);if(recorded.length>0){print(` decided ${recorded.map(decision=>decision.code).join(", ")} ${style.grey("\u2014 as a requester's recorded decisions (--decide)")}`)}print(` engine ${style.grey("local: the protocol's parsers on every message, every checkpoint acknowledged")}`);print();print(style.bold("Events"));const engine=new LocalEngine(invocation,shown,declaredCodes);let failure=null;try{await(0,import_action_runtime.runAction)(definition,new import_action_runtime.LoopbackTransport(engine),{tokenHolder:LOCAL_TOKEN_HOLDER})}catch(error){failure=messageOf(error)}if(engine.events===0)print(style.grey(" (the action emitted nothing)"));const code=verdict(phase,manifest,invocation,engine,shown,failure,expected);print(style.grey(`A development loop, not the gate: when the action runs in ${import_contracts3.BRAND_SHORT_NAME}, the engine judges every message again, and the catalog's release workflow verifies and signs its image first.`));print();return code}__name(runActionTest,"runActionTest");var LocalEngine=class LocalEngine2{static{__name(this,"LocalEngine")}sent;shown;declared;events=0;violation=null;acknowledged=null;parsed=null;constructor(sent,shown,declared){this.sent=sent;this.shown=shown;this.declared=declared}async invocation(){return this.sent}async event(body){const event=this.judged(()=>(0,import_contracts3.parseActionEvent)(body,this.sent.limits,this.events));this.events+=1;printEvent((0,import_contracts3.redactJwtShaped)(event))}async checkpoint(body){const checkpoint=this.judged(()=>(0,import_contracts3.parseActionCheckpoint)(body,this.sent.limits));this.acknowledged=checkpoint.record;print(` ${style.green("\u2713")} restore point acknowledged ${style.grey(JSON.stringify(this.shown(checkpoint.record)))}`);return{acknowledged:true}}async report(body){this.parsed=this.judged(()=>{const parsed=(0,import_contracts3.parseActionReport)(body,this.sent);const undeclared=(0,import_contracts3.undeclaredReportCodeRefusal)(parsed,this.declared);if(undeclared!==null)throw new Error(undeclared);return parsed})}judged(parse){try{return parse()}catch(error){this.violation??=messageOf(error);throw error}}};function verdict(phase,manifest,invocation,engine,shown,failure,expected){if(engine.violation!==null){printError(style.red(`
1058
1064
  The engine would refuse this run: ${shown(engine.violation)}`));return 1}const report=engine.parsed;if(report===null){printError(style.red(`
1059
- The action ended without a report${failure?`: ${shown(failure)}`:""}.`));return 1}if("checks"in report){let refusals=0;let questions=0;for(const{ref,checks}of report.checks){print();print(`${style.bold("Checks")} ${ref}`);for(const check of(0,import_contracts3.settleDecisionChecks)(checks,invocation.decisions)){if(check.level==="error")refusals+=1;if(check.decision!==void 0&&check.level!=="error")questions+=1;printCheck(shown(check))}}print();print(refusals>0?style.red(`A plan would be REFUSED: ${refusals} check${refusals===1?"":"s"} at error.`):questions>0?style.yellow(`A plan would ask the requester ${questions} question${questions===1?"":"s"} before it runs.`):style.green("A plan would proceed."));print();return 0}let outcome=report.outcome;if(phase==="execute"){const refused=(0,import_contracts3.destructiveSuccessRefusal)({key:manifest.key,destructive:manifest.destructive,dryRun:invocation.execution.dryRun,outcome,acknowledgedCheckpoint:engine.acknowledged!==null,restorePoint:invocation.restorePoint});if(refused!==null){printOutcome(shown(outcome),"reported");printError(style.red(`The engine does not accept that success: ${refused.message}`));outcome=refused}}printOutcome(shown(outcome),"outcome");if(phase==="execute"&&outcome.status==="succeeded"&&!invocation.execution.dryRun){print(style.grey("Recorded \u2014 what a rollback reads; save it as the file --prior-result names:"));print(JSON.stringify(shown({restorePoint:engine.acknowledged,outcome}),null,2));print()}return outcome.status==="succeeded"?0:1}__name(verdict,"verdict");function printCheck(check){const marker={info:style.grey("\xB7"),warn:style.yellow("!"),error:style.red("\u2717")}[check.level];const what=check.refusal?style.red(` refusal ${check.refusal}`):check.decision?style.yellow(` decision ${check.decision}`):"";print(` ${marker} ${check.title}${what}`)}__name(printCheck,"printCheck");function printOutcome(outcome,label){const status={succeeded:style.green("succeeded"),failed:style.red("failed"),cancelled:style.yellow("cancelled")}[outcome.status];print();print(`${style.bold(label==="outcome"?"Outcome":"Reported")} ${status}`);print(` ${outcome.message}`);if(outcome.data)print(` ${style.grey(JSON.stringify(outcome.data))}`);print()}__name(printOutcome,"printOutcome");function invocationFor(phase,manifest,target,dryRun,tokens2,prior){const base={protocol:manifest.contract,action:{key:manifest.key,version:manifest.version,image:`local.invalid/${(0,import_contracts3.actionRepositoryName)(manifest.key)}@sha256:${"0".repeat(64)}`},execution:{id:LOCAL_RUN,tenantId:LOCAL_RUN,correlationId:LOCAL_RUN,dryRun},targets:[target],credentials:{tokens:tokens2},limits:{deadline:new Date(Date.now()+LOCAL_DEADLINE_MS).toISOString(),...import_contracts3.ACTION_PROTOCOL_LIMITS}};return(0,import_contracts3.parseActionInvocation)(phase==="validate"?{...base,phase,mode:"plan",decisions:{phase:"plan"},restorePoint:null,priorResult:null}:phase==="run"?{...base,phase,decisions:{phase:"run",recorded:[]},restorePoint:null,priorResult:null}:{...base,phase,decisions:{phase:"run",recorded:[]},restorePoint:prior.restorePoint,priorResult:prior.priorResult})}__name(invocationFor,"invocationFor");async function engineManifest(directory){const path=join2(directory,"catalog.yaml");const text=await readFile(path,"utf8").catch(()=>null);if(text===null){throw new Error(`There is no catalog.yaml in ${directory}. \`${CLI_BIN2} action test\` runs an engine action's repository; \`${CLI_BIN2} action init\` writes one.`)}const document=objectOf(parseYaml(text),"catalog.yaml");const execution=document.execution;if(typeof execution!=="object"||execution===null||execution.kind!=="engine"){throw new Error(`catalog.yaml declares no execution: { kind: engine }, so it is not an engine action. \`${CLI_BIN2} test\` runs an action package.`)}const declared=execution;const destructive=document.capabilities?.destructive;if(typeof destructive!=="boolean"){throw new Error("catalog.yaml must state capabilities.destructive (true or false): the engine's write-ahead rule reads it.")}return{key:stringOf(document.key,"catalog.yaml's key"),version:stringOf(document.version,"catalog.yaml's version"),contract:stringOf(declared.contract,"catalog.yaml's execution.contract"),audiences:stringsOf(declared.audiences,"catalog.yaml's execution.audiences"),egress:stringsOf(declared.egress,"catalog.yaml's execution.egress"),destructive,params:Array.isArray(document.params)?document.params:[]}}__name(engineManifest,"engineManifest");async function parametersOf(params,file,pairs){const declared=new Map(params.map(param=>[param.id,param]));const parameters={};const set=__name((name3,value)=>{if(!declared.has(name3)){throw new Error(`"${name3}" is not a parameter of this action. catalog.yaml declares: ${[...declared.keys()].join(", ")||"(none)"}.`)}parameters[name3]=value},"set");if(file!==void 0){for(const[name3,value]of Object.entries(await jsonObjectFile(file)))set(name3,value)}for(const pair of pairs){const separator=pair.indexOf("=");if(separator<=0)throw new Error(`--param expects name=value; got "${pair}".`);const name3=pair.slice(0,separator);const raw=pair.slice(separator+1);set(name3,declared.get(name3)?.control==="switch"?raw==="true":raw)}const missing=params.filter(param=>param.required&&(parameters[param.id]===void 0||parameters[param.id]===""));if(missing.length>0){throw new Error(`These parameters are required and have no value: ${missing.map(param=>param.id).join(", ")}. Give them with --param ${missing[0].id}=\u2026 (repeatable), or --params-file.`)}return parameters}__name(parametersOf,"parametersOf");async function priorOf(file){if(file===void 0)return{restorePoint:null,priorResult:null};const recorded=await jsonObjectFile(file);const restorePoint=recorded.restorePoint??null;const data=recorded.outcome?.data??null;return{restorePoint:restorePoint===null?null:objectOf(restorePoint,`${file}'s restorePoint`),priorResult:data===null?null:objectOf(data,`${file}'s outcome.data`)}}__name(priorOf,"priorOf");async function armTokenFromAz(){let stdout;try{({stdout}=await runProgram("az",["account","get-access-token","--resource",ARM_AUDIENCE,"--output","json"],{maxBuffer:1024*1024}))}catch(error){const failure=error;throw new Error(failure.code==="ENOENT"?"--azure-token-from-az needs the Azure CLI (az), and it is not installed. Install it and run `az login`.":`\`az account get-access-token\` failed \u2014 run \`az login\` and try again. ${String(failure.stderr??"").trim().split("\n")[0]??""}`)}let answer;try{answer=JSON.parse(stdout)}catch{throw new Error("`az account get-access-token` did not answer JSON.")}if(typeof answer.accessToken!=="string"||answer.accessToken.length===0||typeof answer.subscription!=="string"){throw new Error("`az account get-access-token` returned no token or no subscription. Run `az login` and try again.")}const expiresAt=answer.expires_on!==void 0&&Number.isFinite(Number(answer.expires_on))?new Date(Number(answer.expires_on)*1e3):new Date(String(answer.expiresOn).replace(" ","T"));if(Number.isNaN(expiresAt.getTime()))throw new Error("`az account get-access-token` returned no readable expiry.");return{token:{audience:ARM_AUDIENCE,token:answer.accessToken,expiresOn:expiresAt.toISOString()},subscription:answer.subscription}}__name(armTokenFromAz,"armTokenFromAz");async function jsonObjectFile(file){const text=await readFile(resolve2(file),"utf8").catch(()=>null);if(text===null)throw new Error(`Could not read ${file}.`);let parsed;try{parsed=JSON.parse(text)}catch{throw new Error(`${file} is not valid JSON.`)}return objectOf(parsed,file)}__name(jsonObjectFile,"jsonObjectFile");function objectOf(value,what){if(typeof value!=="object"||value===null||Array.isArray(value))throw new Error(`${what} must be an object.`);return value}__name(objectOf,"objectOf");function stringOf(value,what){if(typeof value!=="string"||value.length===0)throw new Error(`${what} must be a non-empty string.`);return value}__name(stringOf,"stringOf");function stringsOf(value,what){if(!Array.isArray(value)||!value.every(entry=>typeof entry==="string"))throw new Error(`${what} must be a list of strings.`);return value}__name(stringsOf,"stringsOf");function messageOf(error){return error instanceof Error?error.message:String(error)}__name(messageOf,"messageOf");var ACTION_USAGE=`runveric action \u2014 author an engine action: code that runs as its own image (docs/128 \xA723)
1065
+ The action ended without a report${failure?`: ${shown(failure)}`:""}.`));return 1}if("checks"in report){let refusals=0;let questions=0;const raised=[];for(const{ref,checks}of report.checks){print();print(`${style.bold("Checks")} ${ref}`);for(const check of(0,import_contracts3.settleDecisionChecks)(checks,invocation.decisions)){if(check.level==="error")refusals+=1;if(check.decision!==void 0&&check.level!=="error")questions+=1;const code2=check.refusal??check.decision;if(code2!==void 0&&!raised.includes(code2))raised.push(code2);printCheck(shown(check),manifest.checks)}}print();print(refusals>0?style.red(`A plan would be REFUSED: ${refusals} check${refusals===1?"":"s"} at error.`):questions>0?style.yellow(`A plan would ask the requester ${questions} question${questions===1?"":"s"} before it runs.`):style.green("A plan would proceed."));const code=expected.length>0?expectation(expected,raised):refusals>0?1:0;if(expected.length===0){print(style.grey(refusals>0?"Exit 1: a check is still at error after settling. To assert a refusal you meant to provoke, pass --expect <code> for each code it raises.":"Exit 0: no check is at error after settling."))}print();return code}let outcome=report.outcome;if(phase==="execute"){const refused=(0,import_contracts3.destructiveSuccessRefusal)({key:manifest.key,destructive:manifest.destructive,dryRun:invocation.execution.dryRun,outcome,acknowledgedCheckpoint:engine.acknowledged!==null,restorePoint:invocation.restorePoint});if(refused!==null){printOutcome(shown(outcome),"reported");printError(style.red(`The engine does not accept that success: ${refused.message}`));outcome=refused}}printOutcome(shown(outcome),"outcome");if(phase==="execute"&&outcome.status==="succeeded"&&!invocation.execution.dryRun){print(style.grey("Recorded \u2014 what a rollback reads; save it as the file --prior-result names:"));print(JSON.stringify(shown({restorePoint:engine.acknowledged,outcome}),null,2));print()}return outcome.status==="succeeded"?0:1}__name(verdict,"verdict");function expectation(expected,raised){const want=[...new Set(expected)];const missing=want.filter(code=>!raised.includes(code));const extra=raised.filter(code=>!want.includes(code));if(missing.length===0&&extra.length===0){print(style.green(`Exit 0: raised exactly the expected ${want.length===1?"code":"codes"} \u2014 ${want.join(", ")}.`));return 0}printError(style.red(`Exit 1: expected ${want.join(", ")}, and the plan raised ${raised.length>0?raised.join(", "):"no code"}.${missing.length>0?` Not raised: ${missing.join(", ")}.`:""}${extra.length>0?` Not expected: ${extra.join(", ")}.`:""}`));return 1}__name(expectation,"expectation");function printCheck(check,declared){const marker={info:style.grey("\xB7"),warn:style.yellow("!"),error:style.red("\u2717")}[check.level];const label=check.decision?declared.decisions.find(decision=>decision.code===check.decision)?.acknowledgement:void 0;const what=check.refusal?style.red(` refusal ${check.refusal}`):check.decision?`${style.yellow(` decision ${check.decision}`)}${label?style.grey(` \u2014 the requester ticks \u201C${label}\u201D`):""}`:"";print(` ${marker} ${check.title}${what}`)}__name(printCheck,"printCheck");function decisionsDecided(codes,declared){const at=new Date().toISOString();const recorded=[];for(const code of codes){const decision=declared.decisions.find(candidate=>candidate.code===code);if(!decision){throw new Error(`--decide "${code}" is not a decision catalog.yaml declares, so no requester could have decided it. It declares: ${declared.decisions.map(candidate=>candidate.code).join(", ")||"no decisions"}.`)}if(!recorded.some(entry=>entry.code===decision.code)){recorded.push({code:decision.code,acknowledgedBy:LOCAL_RUN,acknowledgedAt:at})}}return recorded}__name(decisionsDecided,"decisionsDecided");function declaredList(declared){return[...declared.refusals.map(refusal=>refusal.code),...declared.decisions.map(decision=>decision.code)].join(", ")}__name(declaredList,"declaredList");function printOutcome(outcome,label){const status={succeeded:style.green("succeeded"),failed:style.red("failed"),cancelled:style.yellow("cancelled")}[outcome.status];print();print(`${style.bold(label==="outcome"?"Outcome":"Reported")} ${status}`);print(` ${outcome.message}`);if(outcome.data)print(` ${style.grey(JSON.stringify(outcome.data))}`);print()}__name(printOutcome,"printOutcome");function invocationFor(phase,manifest,target,dryRun,tokens2,prior,recorded){const base={protocol:manifest.contract,action:{key:manifest.key,version:manifest.version,image:`local.invalid/${(0,import_contracts3.actionRepositoryName)(manifest.key)}@sha256:${"0".repeat(64)}`},execution:{id:LOCAL_RUN,tenantId:LOCAL_RUN,correlationId:LOCAL_RUN,dryRun},targets:[target],credentials:{tokens:tokens2},limits:{deadline:new Date(Date.now()+LOCAL_DEADLINE_MS).toISOString(),...import_contracts3.ACTION_PROTOCOL_LIMITS}};return(0,import_contracts3.parseActionInvocation)(phase==="validate"?{...base,phase,mode:"plan",decisions:{phase:"plan"},restorePoint:null,priorResult:null}:phase==="run"?{...base,phase,decisions:{phase:"run",recorded},restorePoint:null,priorResult:null}:{...base,phase,decisions:{phase:"run",recorded},restorePoint:prior.restorePoint,priorResult:prior.priorResult})}__name(invocationFor,"invocationFor");async function engineManifest(directory){const path=join2(directory,"catalog.yaml");const text=await readFile(path,"utf8").catch(()=>null);if(text===null){throw new Error(`There is no catalog.yaml in ${directory}. \`${CLI_BIN2} action test\` runs an engine action's repository; \`${CLI_BIN2} action init\` writes one.`)}const document=objectOf(parseYaml(text),"catalog.yaml");const execution=document.execution;if(typeof execution!=="object"||execution===null||execution.kind!=="engine"){throw new Error(`catalog.yaml declares no execution: { kind: engine }, so it is not an engine action. \`${CLI_BIN2} test\` runs an action package.`)}const findings=[...(0,import_contracts3.checkDeclarationFindings)(document),...(0,import_contracts3.engineTargetFindings)(Array.isArray(document.params)?document.params:void 0)];if(findings.length>0){throw new Error(`catalog.yaml breaks ${findings.length===1?"a rule":`${findings.length} rules`} ${import_contracts3.BRAND_SHORT_NAME}'s catalog refuses it for, so nothing was run:
1066
+ ${findings.join("\n ")}`)}const declared=execution;const destructive=document.capabilities?.destructive;if(typeof destructive!=="boolean"){throw new Error("catalog.yaml must state capabilities.destructive (true or false): the engine's write-ahead rule reads it.")}return{key:stringOf(document.key,"catalog.yaml's key"),version:stringOf(document.version,"catalog.yaml's version"),contract:stringOf(declared.contract,"catalog.yaml's execution.contract"),audiences:stringsOf(declared.audiences,"catalog.yaml's execution.audiences"),egress:stringsOf(declared.egress,"catalog.yaml's execution.egress"),destructive,params:Array.isArray(document.params)?document.params:[],checks:(0,import_contracts3.checkDeclarationOf)(document.checks)}}__name(engineManifest,"engineManifest");async function parametersOf(params,file,pairs){const declared=new Map(params.map(param=>[param.id,param]));const parameters={};const set=__name((name3,value)=>{if(!declared.has(name3)){throw new Error(`"${name3}" is not a parameter of this action. catalog.yaml declares: ${[...declared.keys()].join(", ")||"(none)"}.`)}parameters[name3]=value},"set");if(file!==void 0){for(const[name3,value]of Object.entries(await jsonObjectFile(file)))set(name3,value)}for(const pair of pairs){const separator=pair.indexOf("=");if(separator<=0)throw new Error(`--param expects name=value; got "${pair}".`);const name3=pair.slice(0,separator);const raw=pair.slice(separator+1);set(name3,declared.get(name3)?.control==="switch"?raw==="true":raw)}const missing=params.filter(param=>param.required&&(parameters[param.id]===void 0||parameters[param.id]===""));if(missing.length>0){throw new Error(`These parameters are required and have no value: ${missing.map(param=>param.id).join(", ")}. Give them with --param ${missing[0].id}=\u2026 (repeatable), or --params-file.`)}return parameters}__name(parametersOf,"parametersOf");async function priorOf(file){if(file===void 0)return{restorePoint:null,priorResult:null};const recorded=await jsonObjectFile(file);const restorePoint=recorded.restorePoint??null;const data=recorded.outcome?.data??null;return{restorePoint:restorePoint===null?null:objectOf(restorePoint,`${file}'s restorePoint`),priorResult:data===null?null:objectOf(data,`${file}'s outcome.data`)}}__name(priorOf,"priorOf");async function armTokenFromAz(){let stdout;try{({stdout}=await runProgram("az",["account","get-access-token","--resource",ARM_AUDIENCE,"--output","json"],{maxBuffer:1024*1024}))}catch(error){const failure=error;throw new Error(failure.code==="ENOENT"?"--azure-token-from-az needs the Azure CLI (az), and it is not installed. Install it and run `az login`.":`\`az account get-access-token\` failed \u2014 run \`az login\` and try again. ${String(failure.stderr??"").trim().split("\n")[0]??""}`)}let answer;try{answer=JSON.parse(stdout)}catch{throw new Error("`az account get-access-token` did not answer JSON.")}if(typeof answer.accessToken!=="string"||answer.accessToken.length===0||typeof answer.subscription!=="string"){throw new Error("`az account get-access-token` returned no token or no subscription. Run `az login` and try again.")}const expiresAt=answer.expires_on!==void 0&&Number.isFinite(Number(answer.expires_on))?new Date(Number(answer.expires_on)*1e3):new Date(String(answer.expiresOn).replace(" ","T"));if(Number.isNaN(expiresAt.getTime()))throw new Error("`az account get-access-token` returned no readable expiry.");return{token:{audience:ARM_AUDIENCE,token:answer.accessToken,expiresOn:expiresAt.toISOString()},subscription:answer.subscription}}__name(armTokenFromAz,"armTokenFromAz");async function jsonObjectFile(file){const text=await readFile(resolve2(file),"utf8").catch(()=>null);if(text===null)throw new Error(`Could not read ${file}.`);let parsed;try{parsed=JSON.parse(text)}catch{throw new Error(`${file} is not valid JSON.`)}return objectOf(parsed,file)}__name(jsonObjectFile,"jsonObjectFile");function objectOf(value,what){if(typeof value!=="object"||value===null||Array.isArray(value))throw new Error(`${what} must be an object.`);return value}__name(objectOf,"objectOf");function stringOf(value,what){if(typeof value!=="string"||value.length===0)throw new Error(`${what} must be a non-empty string.`);return value}__name(stringOf,"stringOf");function stringsOf(value,what){if(!Array.isArray(value)||!value.every(entry=>typeof entry==="string"))throw new Error(`${what} must be a list of strings.`);return value}__name(stringsOf,"stringsOf");function messageOf(error){return error instanceof Error?error.message:String(error)}__name(messageOf,"messageOf");var ACTION_USAGE=`runveric action \u2014 author an engine action: code that runs as its own image (docs/128 \xA723)
1060
1067
 
1061
1068
  ${ACTION_INIT_USAGE}
1062
- Write a repository that builds, tests and publishes: package.json (the SDK pinned), src/index.ts,
1063
- catalog.yaml, a test, README.md, .gitignore and the catalog's publish workflow. Never overwrites.
1069
+ Write a repository that builds, tests and publishes: package.json (the SDK pinned; test, test:unit,
1070
+ test:live), src/, catalog.yaml with its checks, unit tests, README.md, .gitignore, the catalog's
1071
+ publish workflow and a pull-request template with the promotion checklist. Never overwrites.
1064
1072
 
1065
1073
  ${ACTION_TEST_USAGE}
1066
- Run one phase of the built dist/index.js through the action runtime and a LOCAL engine: every
1067
- message parsed by the protocol's parsers, every checkpoint acknowledged. No credential unless
1074
+ Run one phase of the built dist/index.js through the action runtime and a LOCAL engine. catalog.yaml
1075
+ is held to the catalog's rules first; every message is parsed by the protocol's parsers, every
1076
+ checkpoint acknowledged, and every code a validate raises must be one catalog.yaml declares.
1077
+ --decide gives an execute or a rollback a requester's decision. No credential unless
1068
1078
  --azure-token-from-az, which takes ONE token from your az login, in memory only. Exit 1 on a
1069
- violation or a failed outcome. A development loop, not the gate.
1079
+ violation, a failed outcome, or a validate that leaves a check at error \u2014 or, with --expect, unless
1080
+ exactly those codes were raised. A development loop, not the gate.
1070
1081
 
1071
1082
  Then: npm install && npm test. Publishing is a tag that runs the repository's workflow; ${import_contracts4.BRAND_SHORT_NAME}'s
1072
1083
  engine and the catalog's release workflow judge and sign what it publishes.`;var SUBCOMMANDS={init:__name(async argv=>{await runActionInit(argv);return 0},"init"),test:runActionTest};async function runActionCommand(argv){const[subcommand,...rest]=argv;if(subcommand===void 0||subcommand==="--help"||rest.includes("--help")){process.stdout.write(`${ACTION_USAGE}
1073
1084
  `);return subcommand===void 0?1:0}const run3=SUBCOMMANDS[subcommand];if(run3===void 0){printError(`\u2717 "action ${subcommand}" is not a command. There are ${Object.keys(SUBCOMMANDS).length}: ${Object.keys(SUBCOMMANDS).join(", ")}.`);return 1}try{return await run3(rest)}catch(error){printError(`\u2717 ${error instanceof Error?error.message:String(error)}`);return 1}}__name(runActionCommand,"runActionCommand");var import_contracts7=__toESM(require_dist());import{readFileSync}from"fs";import{dirname as dirname2,resolve as resolve3}from"path";import{parse as parseYaml2}from"yaml";var import_contracts5=__toESM(require_dist());import{execFileSync}from"child_process";import{createHash}from"crypto";function parseRepository(ref,flag){if(!import_contracts5.ARTIFACT_REPOSITORY_PATTERN.test(ref)){throw new Error(`${flag} "${ref}" is not a bare registry repository (host[:port]/path, lowercase, no scheme, no tag, no digest). A catalog artifact is addressed by digest; tags are for humans.`)}const cut=ref.indexOf("/");return{ref,host:ref.slice(0,cut),path:ref.slice(cut+1),namespace:ref.slice(0,ref.lastIndexOf("/"))}}__name(parseRepository,"parseRepository");var isDigest=__name(value=>import_contracts5.ARTIFACT_DIGEST_PATTERN.test(value),"isDigest");var TAG_PATTERN=/^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$/;function requireTag(tag,origin2){if(!TAG_PATTERN.test(tag)){throw new Error(`${origin2} gives the tag "${tag}", which a registry cannot hold: letters, digits, "_", "." and "-", starting with a letter, digit or "_", at most 128 characters. Pass --tag.`)}}__name(requireTag,"requireTag");var LOOPBACK=/^(localhost|127\.0\.0\.1|\[::1\])(:[0-9]+)?$/;var origin=__name(host=>`${LOOPBACK.test(host)?"http":"https"}://${host}`,"origin");var sha256=__name(bytes=>`sha256:${createHash("sha256").update(bytes).digest("hex")}`,"sha256");var EMPTY_CONFIG=Buffer.from("{}");var EMPTY_CONFIG_DESCRIPTOR={mediaType:"application/vnd.oci.empty.v1+json",digest:sha256(EMPTY_CONFIG),size:EMPTY_CONFIG.length};var MANIFEST_ACCEPT=import_contracts5.MANIFEST_MEDIA_TYPES.join(", ");function provenance(flags,dir){const git=__name((...args)=>{try{return execFileSync("git",["-C",dir,...args],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}},"git");const actions=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:"";const repository=flags.repository??(actions||git("remote","get-url","origin"));const commit=flags.commit??(process.env.GITHUB_SHA||git("rev-parse","HEAD"));if(!repository||!commit){throw new Error("Provenance is required and could not be determined. Pass --repository <url> and --commit <sha> (in GitHub Actions, GITHUB_REPOSITORY and GITHUB_SHA supply them).")}return{repository,commit,publishedAt:new Date().toISOString()}}__name(provenance,"provenance");function buildArtifact(document){const documentBytes=Buffer.from(`${JSON.stringify(document,null,2)}
1074
- `);const manifest={schemaVersion:2,mediaType:import_contracts5.OCI_IMAGE_MANIFEST,artifactType:import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE,config:EMPTY_CONFIG_DESCRIPTOR,layers:[{mediaType:import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE,digest:sha256(documentBytes),size:documentBytes.length}],annotations:{"org.opencontainers.image.created":document.provenance.publishedAt,"org.opencontainers.image.source":document.provenance.repository,"org.opencontainers.image.revision":document.provenance.commit}};const manifestBytes=Buffer.from(JSON.stringify(manifest));return{documentBytes,manifestBytes,manifestDigest:sha256(manifestBytes)}}__name(buildArtifact,"buildArtifact");function basicCredential(){const pat=process.env.GHCR_TOKEN;if(pat)return Buffer.from(`x:${pat}`).toString("base64");const workflow=process.env.GITHUB_TOKEN;if(workflow)return Buffer.from(`${process.env.GITHUB_ACTOR||"x"}:${workflow}`).toString("base64");return void 0}__name(basicCredential,"basicCredential");var tokens=new Map;async function token(repository,challenge,access3){const field=__name(name3=>new RegExp(`${name3}="([^"]*)"`).exec(challenge??"")?.[1],"field");const realm=field("realm");if(!realm)throw new Error(`${repository.host} asked for credentials without a Bearer challenge.`);const url=new URL(realm);const service=field("service");if(service)url.searchParams.set("service",service);url.searchParams.set("scope",`repository:${repository.path}:${access3}`);const credential=basicCredential();const answer=await fetch(url,{headers:credential?{Authorization:`Basic ${credential}`}:{}});if(!answer.ok){throw new Error(`${repository.host} refused a ${access3==="pull"?"pull":"push"} token for ${repository.path}: HTTP ${answer.status}`+(credential||access3==="pull"?".":" \u2014 set GHCR_TOKEN to a token with write:packages, or in a workflow GITHUB_TOKEN with packages: write."))}const body=await answer.json();const value=body.token??body.access_token??"";tokens.set(`${repository.path} ${access3}`,value);return value}__name(token,"token");async function call(repository,method,path,{headers={},body,access:access3="pull,push"}={}){const url=path.startsWith("http")?path:`${origin(repository.host)}/v2/${repository.path}/${path}`;const send=__name(bearer=>fetch(url,{method,body,redirect:"follow",headers:{...headers,...bearer?{Authorization:`Bearer ${bearer}`}:{}}}),"send");let answer=await send(tokens.get(`${repository.path} ${access3}`));if(answer.status===401)answer=await send(await token(repository,answer.headers.get("www-authenticate"),access3));return answer}__name(call,"call");async function pushBlob(repository,bytes){const digest=sha256(bytes);if((await call(repository,"HEAD",`blobs/${digest}`)).ok)return digest;const started=await call(repository,"POST","blobs/uploads/");if(started.status!==202)throw new Error(`${repository.host} refused an upload: HTTP ${started.status}`);const location=new URL(started.headers.get("location")??"",`${origin(repository.host)}/`);location.searchParams.set("digest",digest);const put=await call(repository,"PUT",location.toString(),{headers:{"Content-Type":"application/octet-stream","Content-Length":String(bytes.length)},body:bytes});if(put.status!==201)throw new Error(`${repository.host} rejected blob ${digest}: HTTP ${put.status} ${await put.text()}`);return digest}__name(pushBlob,"pushBlob");async function manifestExists(repository,digest){const answer=await call(repository,"HEAD",`manifests/${digest}`,{headers:{Accept:import_contracts5.OCI_IMAGE_MANIFEST}});return answer.ok}__name(manifestExists,"manifestExists");async function readVerified(repository,kind,digest,size=null){if(!isDigest(digest))throw new Error(`"${digest}" is not a digest, so ${repository.ref} cannot be asked for it.`);const answer=await call(repository,"GET",`${kind}/${digest}`,{access:"pull",headers:kind==="manifests"?{Accept:MANIFEST_ACCEPT}:{}});if(!answer.ok){throw new Error(`${repository.ref}@${digest} could not be read: HTTP ${answer.status}${answer.status===404?" \u2014 it is not in the registry":""}.`)}const bytes=Buffer.from(await answer.arrayBuffer());const served=sha256(bytes);if(served!==digest||size!==null&&bytes.length!==size){throw new Error(`${repository.host} served ${bytes.length} bytes hashing to ${served} for ${repository.ref}@${digest}${size===null?"":` (${size} bytes named)`}. Refused: a digest this command did not compute is not a pin.`)}return bytes}__name(readVerified,"readVerified");var readManifest=__name((repository,digest)=>readVerified(repository,"manifests",digest),"readManifest");var readBlob=__name((repository,digest,size)=>readVerified(repository,"blobs",digest,size),"readBlob");function parseJsonBytes(bytes,what){try{return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch(cause){throw new Error(`${what} is not UTF-8 JSON. (${cause instanceof Error?cause.message:String(cause)})`)}}__name(parseJsonBytes,"parseJsonBytes");async function readArtifactDocument(repository,digest){const what=`${repository.ref}@${digest}`;const manifest=parseJsonBytes(await readManifest(repository,digest),`the manifest of ${what}`);const layers=Array.isArray(manifest?.layers)?manifest.layers:[];const layer=layers[0];if(manifest?.mediaType!==import_contracts5.OCI_IMAGE_MANIFEST||layers.length!==1||layer?.mediaType!==import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE||typeof layer.digest!=="string"||typeof layer.size!=="number"){throw new Error(`${what} is not a catalog artifact: expected one OCI manifest with exactly one ${import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE} layer.`)}return parseJsonBytes(await readBlob(repository,layer.digest,layer.size),`the document of ${what}`)}__name(readArtifactDocument,"readArtifactDocument");async function pushArtifact(repository,artifact,tag){await pushBlob(repository,EMPTY_CONFIG);await pushBlob(repository,artifact.documentBytes);for(const reference of[artifact.manifestDigest,tag]){const put=await call(repository,"PUT",`manifests/${reference}`,{headers:{"Content-Type":import_contracts5.OCI_IMAGE_MANIFEST},body:artifact.manifestBytes});if(put.status!==201){throw new Error(`${repository.host} rejected the manifest (${reference}): HTTP ${put.status} ${await put.text()}`)}}const asked=await call(repository,"HEAD",`manifests/${tag}`,{headers:{Accept:import_contracts5.OCI_IMAGE_MANIFEST}});const reported=asked.headers.get("docker-content-digest");if(!asked.ok||!reported){throw new Error(`${repository.host} could not say what :${tag} resolves to (HTTP ${asked.status}).`)}if(reported!==artifact.manifestDigest){throw new Error(`${repository.host} reports :${tag} as ${reported}, but the bytes sent hash to ${artifact.manifestDigest}. Something re-encoded the manifest; nothing printed here would name what is stored. Refusing to report a digest.`)}return reported}__name(pushArtifact,"pushArtifact");var defaultTag=__name(()=>new Date().toISOString().replace(/[-:]/g,"").replace(/\..*$/,"").toLowerCase(),"defaultTag");function parseCatalogFlags(argv,known,repeated=[]){const single2={};const many={};for(let index=0;index<argv.length;index+=1){const argument=argv[index];const separator=argument.indexOf("=");const name3=separator===-1?argument.slice(2):argument.slice(2,separator);if(!argument.startsWith("--")||!known.includes(name3))throw new Error(`Unknown argument: ${argument}`);let value;if(separator!==-1){value=argument.slice(separator+1)}else{value=argv[index+1];index+=1}if(value===void 0||value===""||value.startsWith("--"))throw new Error(`--${name3} needs a value.`);if(repeated.includes(name3))(many[name3]??=[]).push(value);else single2[name3]=value}return{single:single2,many}}__name(parseCatalogFlags,"parseCatalogFlags");var import_contracts6=__toESM(require_dist());function parseImageReference(value,origin2){const at=value.lastIndexOf("@");const digest=at===-1?"":value.slice(at+1);if(at===-1||!isDigest(digest)){throw new Error(`${origin2} "${value}" is not <repository>@<digest>. An engine action's image is named by its digest \u2014 sha256: and 64 lowercase hex \u2014 never by a tag, which a registry can repoint.`)}const repository=parseRepository(value.slice(0,at),origin2);return{repository,digest,ref:`${repository.ref}@${digest}`}}__name(parseImageReference,"parseImageReference");async function imageRefusal(image,key,provenance2){const manifestBytes=await readManifest(image.repository,image.digest);if(manifestBytes.length>import_contracts6.MAX_IMAGE_MANIFEST_BYTES){return`the image manifest of ${image.ref} is ${manifestBytes.length} bytes; the limit is ${import_contracts6.MAX_IMAGE_MANIFEST_BYTES}.`}const manifest=parseJsonBytes(manifestBytes,`the image manifest of ${image.ref}`);const descriptor=(0,import_contracts6.imageConfigDescriptor)(manifest);const config=descriptor===null?null:parseJsonBytes(await readBlob(image.repository,descriptor.digest,descriptor.size),`the image config of ${image.ref}`);return(0,import_contracts6.actionImageRefusal)({key,image:image.ref,manifest,config,provenance:provenance2})}__name(imageRefusal,"imageRefusal");var PUBLISH_ACTION_USAGE="runveric catalog publish-action --manifest <file.yaml> --to <registry>/<namespace>/<repository>\n [--image <repository>@<digest>] [--tag <tag>]\n [--repository <source url>] [--commit <sha>]";var isMapping=__name(value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"isMapping");async function runPublishAction(argv){const{single:flags}=parseCatalogFlags(argv,["manifest","to","image","tag","repository","commit"]);if(!flags.manifest||!flags.to)throw new Error("--manifest and --to are required.");const repository=parseRepository(flags.to,"--to");const image=flags.image===void 0?null:parseImageReference(flags.image,"--image");if(image!==null&&image.repository.ref!==repository.ref){throw new Error(`--image ${image.ref} is outside the artifact's repository ${repository.ref}. An engine action's image lives in its own package, so its artifact names it by digest alone (docs/128 \xA717.2 D2) \u2014 push the image to ${repository.ref}.`)}const path=resolve3(flags.manifest);const manifest=readFileSync(path,"utf8");let parsed;try{parsed=parseYaml2(manifest)}catch(cause){throw new Error(`${flags.manifest} is not valid YAML. (${cause instanceof Error?cause.message:String(cause)})`)}const fields=isMapping(parsed)?parsed:{};const key=typeof fields.key==="string"&&fields.key.length>0?fields.key:null;if(key===null)throw new Error(`${flags.manifest} declares no top-level \`key:\` \u2014 is it a catalog manifest?`);const misnamed=(0,import_contracts7.actionPackageRefusal)(key,repository.ref);if(misnamed!==null)throw new Error(`--to: ${misnamed}`);const executes=isMapping(fields.execution);if(executes&&image===null){throw new Error(`${flags.manifest} declares execution, so it is an engine action: publish it with --image <repository>@<digest>, the image its workflow built. Without one the server refuses it at plan.`)}if(!executes&&image!==null){throw new Error(`${flags.manifest} declares no execution, so nothing would ever run --image ${image.ref}. A built-in action is published without one.`)}let tag;if(fields.declares==="definition+version"){const version5=typeof fields.version==="string"?fields.version:null;if(version5===null)throw new Error(`${flags.manifest} declares "definition+version" and no version:.`);if(flags.tag!==void 0&&flags.tag!==version5){throw new Error(`${flags.manifest} declares version ${version5}, and the tag is ${flags.tag}. Tag the commit ${version5}, or change version: in ${flags.manifest} first.`)}tag=version5}else{tag=flags.tag??defaultTag()}requireTag(tag,flags.tag!==void 0?"--tag":`${flags.manifest}'s version`);const recorded=provenance(flags,dirname2(path));if(image!==null){const refusal=await imageRefusal(image,key,recorded);if(refusal!==null)throw new Error(`--image: ${refusal}`)}const artifact=buildArtifact(image===null?{schemaVersion:import_contracts7.CATALOG_ACTION_ARTIFACT_SCHEMA_V1,manifest,provenance:recorded}:{schemaVersion:import_contracts7.CATALOG_ACTION_ARTIFACT_SCHEMA_V2,manifest,provenance:recorded,image:{digest:image.digest}});const digest=await pushArtifact(repository,artifact,tag);process.stderr.write(`\u2713 ${key} published to ${repository.ref}:${tag}${image===null?"":`, naming the image ${image.digest}`}
1085
+ `);const manifest={schemaVersion:2,mediaType:import_contracts5.OCI_IMAGE_MANIFEST,artifactType:import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE,config:EMPTY_CONFIG_DESCRIPTOR,layers:[{mediaType:import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE,digest:sha256(documentBytes),size:documentBytes.length}],annotations:{"org.opencontainers.image.created":document.provenance.publishedAt,"org.opencontainers.image.source":document.provenance.repository,"org.opencontainers.image.revision":document.provenance.commit}};const manifestBytes=Buffer.from(JSON.stringify(manifest));return{documentBytes,manifestBytes,manifestDigest:sha256(manifestBytes)}}__name(buildArtifact,"buildArtifact");function basicCredential(){const pat=process.env.GHCR_TOKEN;if(pat)return Buffer.from(`x:${pat}`).toString("base64");const workflow=process.env.GITHUB_TOKEN;if(workflow)return Buffer.from(`${process.env.GITHUB_ACTOR||"x"}:${workflow}`).toString("base64");return void 0}__name(basicCredential,"basicCredential");var tokens=new Map;async function token(repository,challenge,access3){const field=__name(name3=>new RegExp(`${name3}="([^"]*)"`).exec(challenge??"")?.[1],"field");const realm=field("realm");if(!realm)throw new Error(`${repository.host} asked for credentials without a Bearer challenge.`);const url=new URL(realm);const service=field("service");if(service)url.searchParams.set("service",service);url.searchParams.set("scope",`repository:${repository.path}:${access3}`);const credential=basicCredential();const answer=await fetch(url,{headers:credential?{Authorization:`Basic ${credential}`}:{}});if(!answer.ok){throw new Error(`${repository.host} refused a ${access3==="pull"?"pull":"push"} token for ${repository.path}: HTTP ${answer.status}`+(credential||access3==="pull"?".":" \u2014 set GHCR_TOKEN to a token with write:packages, or in a workflow GITHUB_TOKEN with packages: write."))}const body=await answer.json();const value=body.token??body.access_token??"";tokens.set(`${repository.path} ${access3}`,value);return value}__name(token,"token");async function call(repository,method,path,{headers={},body,access:access3="pull,push"}={}){const url=path.startsWith("http")?path:`${origin(repository.host)}/v2/${repository.path}/${path}`;const send=__name(bearer=>fetch(url,{method,body,redirect:"follow",headers:{...headers,...bearer?{Authorization:`Bearer ${bearer}`}:{}}}),"send");let answer=await send(tokens.get(`${repository.path} ${access3}`));if(answer.status===401)answer=await send(await token(repository,answer.headers.get("www-authenticate"),access3));return answer}__name(call,"call");async function pushBlob(repository,bytes){const digest=sha256(bytes);if((await call(repository,"HEAD",`blobs/${digest}`)).ok)return digest;const started=await call(repository,"POST","blobs/uploads/");if(started.status!==202)throw new Error(`${repository.host} refused an upload: HTTP ${started.status}`);const location=new URL(started.headers.get("location")??"",`${origin(repository.host)}/`);location.searchParams.set("digest",digest);const put=await call(repository,"PUT",location.toString(),{headers:{"Content-Type":"application/octet-stream","Content-Length":String(bytes.length)},body:bytes});if(put.status!==201)throw new Error(`${repository.host} rejected blob ${digest}: HTTP ${put.status} ${await put.text()}`);return digest}__name(pushBlob,"pushBlob");async function manifestExists(repository,digest){const answer=await call(repository,"HEAD",`manifests/${digest}`,{headers:{Accept:import_contracts5.OCI_IMAGE_MANIFEST}});return answer.ok}__name(manifestExists,"manifestExists");async function readVerified(repository,kind,digest,size=null){if(!isDigest(digest))throw new Error(`"${digest}" is not a digest, so ${repository.ref} cannot be asked for it.`);const answer=await call(repository,"GET",`${kind}/${digest}`,{access:"pull",headers:kind==="manifests"?{Accept:MANIFEST_ACCEPT}:{}});if(!answer.ok){throw new Error(`${repository.ref}@${digest} could not be read: HTTP ${answer.status}${answer.status===404?" \u2014 it is not in the registry":""}.`)}const bytes=Buffer.from(await answer.arrayBuffer());const served=sha256(bytes);if(served!==digest||size!==null&&bytes.length!==size){throw new Error(`${repository.host} served ${bytes.length} bytes hashing to ${served} for ${repository.ref}@${digest}${size===null?"":` (${size} bytes named)`}. Refused: a digest this command did not compute is not a pin.`)}return bytes}__name(readVerified,"readVerified");var readManifest=__name((repository,digest)=>readVerified(repository,"manifests",digest),"readManifest");var readBlob=__name((repository,digest,size)=>readVerified(repository,"blobs",digest,size),"readBlob");function parseJsonBytes(bytes,what){try{return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes))}catch(cause){throw new Error(`${what} is not UTF-8 JSON. (${cause instanceof Error?cause.message:String(cause)})`)}}__name(parseJsonBytes,"parseJsonBytes");async function readArtifactDocument(repository,digest){const what=`${repository.ref}@${digest}`;const manifest=parseJsonBytes(await readManifest(repository,digest),`the manifest of ${what}`);const layers=Array.isArray(manifest?.layers)?manifest.layers:[];const layer=layers[0];if(manifest?.mediaType!==import_contracts5.OCI_IMAGE_MANIFEST||layers.length!==1||layer?.mediaType!==import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE||typeof layer.digest!=="string"||typeof layer.size!=="number"){throw new Error(`${what} is not a catalog artifact: expected one OCI manifest with exactly one ${import_contracts5.CATALOG_ARTIFACT_MEDIA_TYPE} layer.`)}return parseJsonBytes(await readBlob(repository,layer.digest,layer.size),`the document of ${what}`)}__name(readArtifactDocument,"readArtifactDocument");async function pushArtifact(repository,artifact,tag){await pushBlob(repository,EMPTY_CONFIG);await pushBlob(repository,artifact.documentBytes);for(const reference of[artifact.manifestDigest,tag]){const put=await call(repository,"PUT",`manifests/${reference}`,{headers:{"Content-Type":import_contracts5.OCI_IMAGE_MANIFEST},body:artifact.manifestBytes});if(put.status!==201){throw new Error(`${repository.host} rejected the manifest (${reference}): HTTP ${put.status} ${await put.text()}`)}}const asked=await call(repository,"HEAD",`manifests/${tag}`,{headers:{Accept:import_contracts5.OCI_IMAGE_MANIFEST}});const reported=asked.headers.get("docker-content-digest");if(!asked.ok||!reported){throw new Error(`${repository.host} could not say what :${tag} resolves to (HTTP ${asked.status}).`)}if(reported!==artifact.manifestDigest){throw new Error(`${repository.host} reports :${tag} as ${reported}, but the bytes sent hash to ${artifact.manifestDigest}. Something re-encoded the manifest; nothing printed here would name what is stored. Refusing to report a digest.`)}return reported}__name(pushArtifact,"pushArtifact");var defaultTag=__name(()=>new Date().toISOString().replace(/[-:]/g,"").replace(/\..*$/,"").toLowerCase(),"defaultTag");function parseCatalogFlags(argv,known,repeated=[]){const single2={};const many={};for(let index=0;index<argv.length;index+=1){const argument=argv[index];const separator=argument.indexOf("=");const name3=separator===-1?argument.slice(2):argument.slice(2,separator);if(!argument.startsWith("--")||!known.includes(name3))throw new Error(`Unknown argument: ${argument}`);let value;if(separator!==-1){value=argument.slice(separator+1)}else{value=argv[index+1];index+=1}if(value===void 0||value===""||value.startsWith("--"))throw new Error(`--${name3} needs a value.`);if(repeated.includes(name3))(many[name3]??=[]).push(value);else single2[name3]=value}return{single:single2,many}}__name(parseCatalogFlags,"parseCatalogFlags");var import_contracts6=__toESM(require_dist());function parseImageReference(value,origin2){const at=value.lastIndexOf("@");const digest=at===-1?"":value.slice(at+1);if(at===-1||!isDigest(digest)){throw new Error(`${origin2} "${value}" is not <repository>@<digest>. An engine action's image is named by its digest \u2014 sha256: and 64 lowercase hex \u2014 never by a tag, which a registry can repoint.`)}const repository=parseRepository(value.slice(0,at),origin2);return{repository,digest,ref:`${repository.ref}@${digest}`}}__name(parseImageReference,"parseImageReference");async function imageRefusal(image,key,provenance2){const manifestBytes=await readManifest(image.repository,image.digest);if(manifestBytes.length>import_contracts6.MAX_IMAGE_MANIFEST_BYTES){return`the image manifest of ${image.ref} is ${manifestBytes.length} bytes; the limit is ${import_contracts6.MAX_IMAGE_MANIFEST_BYTES}.`}const manifest=parseJsonBytes(manifestBytes,`the image manifest of ${image.ref}`);const descriptor=(0,import_contracts6.imageConfigDescriptor)(manifest);const config=descriptor===null?null:parseJsonBytes(await readBlob(image.repository,descriptor.digest,descriptor.size),`the image config of ${image.ref}`);return(0,import_contracts6.actionImageRefusal)({key,image:image.ref,manifest,config,provenance:provenance2})}__name(imageRefusal,"imageRefusal");var PUBLISH_ACTION_USAGE="runveric catalog publish-action --manifest <file.yaml> --to <registry>/<namespace>/<repository>\n [--image <repository>@<digest>] [--tag <tag>]\n [--repository <source url>] [--commit <sha>]";var isMapping=__name(value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"isMapping");async function runPublishAction(argv){const{single:flags}=parseCatalogFlags(argv,["manifest","to","image","tag","repository","commit"]);if(!flags.manifest||!flags.to)throw new Error("--manifest and --to are required.");const repository=parseRepository(flags.to,"--to");const image=flags.image===void 0?null:parseImageReference(flags.image,"--image");if(image!==null&&image.repository.ref!==repository.ref){throw new Error(`--image ${image.ref} is outside the artifact's repository ${repository.ref}. An engine action's image lives in its own package, so its artifact names it by digest alone (docs/128 \xA717.2 D2) \u2014 push the image to ${repository.ref}.`)}const path=resolve3(flags.manifest);const manifest=readFileSync(path,"utf8");let parsed;try{parsed=parseYaml2(manifest)}catch(cause){throw new Error(`${flags.manifest} is not valid YAML. (${cause instanceof Error?cause.message:String(cause)})`)}const fields=isMapping(parsed)?parsed:{};const key=typeof fields.key==="string"&&fields.key.length>0?fields.key:null;if(key===null)throw new Error(`${flags.manifest} declares no top-level \`key:\` \u2014 is it a catalog manifest?`);const misnamed=(0,import_contracts7.actionPackageRefusal)(key,repository.ref);if(misnamed!==null)throw new Error(`--to: ${misnamed}`);const executes=isMapping(fields.execution);if(executes&&image===null){throw new Error(`${flags.manifest} declares execution, so it is an engine action: publish it with --image <repository>@<digest>, the image its workflow built. Without one the server refuses it at plan.`)}if(!executes&&image!==null){throw new Error(`${flags.manifest} declares no execution, so nothing would ever run --image ${image.ref}. A built-in action is published without one.`)}let tag;if(fields.declares==="definition+version"){const version6=typeof fields.version==="string"?fields.version:null;if(version6===null)throw new Error(`${flags.manifest} declares "definition+version" and no version:.`);if(flags.tag!==void 0&&flags.tag!==version6){throw new Error(`${flags.manifest} declares version ${version6}, and the tag is ${flags.tag}. Tag the commit ${version6}, or change version: in ${flags.manifest} first.`)}tag=version6}else{tag=flags.tag??defaultTag()}requireTag(tag,flags.tag!==void 0?"--tag":`${flags.manifest}'s version`);const recorded=provenance(flags,dirname2(path));if(image!==null){const refusal=await imageRefusal(image,key,recorded);if(refusal!==null)throw new Error(`--image: ${refusal}`)}const artifact=buildArtifact(image===null?{schemaVersion:import_contracts7.CATALOG_ACTION_ARTIFACT_SCHEMA_V1,manifest,provenance:recorded}:{schemaVersion:import_contracts7.CATALOG_ACTION_ARTIFACT_SCHEMA_V2,manifest,provenance:recorded,image:{digest:image.digest}});const digest=await pushArtifact(repository,artifact,tag);process.stderr.write(`\u2713 ${key} published to ${repository.ref}:${tag}${image===null?"":`, naming the image ${image.digest}`}
1075
1086
  `);process.stderr.write(` the registry reports ${digest} \u2014 the digest a release must name.
1076
1087
  `);process.stdout.write(`${key}=${repository.ref}@${digest}
1077
- `)}__name(runPublishAction,"runPublishAction");var import_contracts8=__toESM(require_dist());import{readFileSync as readFileSync2}from"fs";import{parse as parseYaml3}from"yaml";var PUBLISH_RELEASE_USAGE="runveric catalog publish-release (--from <release.yaml> | --action <key>=<repository>@<digest> \u2026)\n --to <registry>/<namespace>/<repository> [--version <label>]\n [--tag <tag>] [--repository <source url>] [--commit <sha>]";function entriesFromFlags(values){return values.map(value=>{const match=/^([^=]+)=([^@]+)@(.+)$/.exec(value);if(!match)throw new Error(`--action "${value}" is not <key>=<repository>@<digest>.`);const[,key="",artifactRef="",digest=""]=match;return{key,artifactRef,digest,label:`--action ${key}`}})}__name(entriesFromFlags,"entriesFromFlags");function specFromFile(path){let value;try{value=parseYaml3(readFileSync2(path,"utf8"))}catch(cause){throw new Error(`--from ${path} could not be read as YAML. (${cause instanceof Error?cause.message:String(cause)})`)}const spec=(0,import_contracts8.parseCatalogReleaseSpec)(value);return{version:spec.version,entries:spec.actions.map(action=>({...action,label:`${path}'s ${action.key}`}))}}__name(specFromFile,"specFromFile");async function runPublishRelease(argv){const{single:flags,many}=parseCatalogFlags(argv,["to","version","action","from","tag","repository","commit"],["action"]);const actionFlags=many.action??[];if(flags.from!==void 0&&actionFlags.length>0){throw new Error("--from and --action are alternatives: name the release's actions in release.yaml or as flags, not both.")}if(flags.from!==void 0&&flags.version!==void 0){throw new Error("--version is read from release.yaml when --from is given; pass one or the other.")}if(!flags.to||flags.from===void 0&&(!flags.version||actionFlags.length===0)){throw new Error("--to and either --from, or --version and at least one --action, are required.")}const release=parseRepository(flags.to,"--to");const{version:version5,entries}=flags.from!==void 0?specFromFile(flags.from):{version:flags.version,entries:entriesFromFlags(actionFlags)};const tag=flags.tag??(flags.from!==void 0?version5:defaultTag());requireTag(tag,flags.tag!==void 0?"--tag":`${flags.from}'s version`);const seen=new Set;const actions=entries.map(entry=>{if(seen.has(entry.key))throw new Error(`${entry.label} names "${entry.key}" twice.`);seen.add(entry.key);const repository=parseRepository(entry.artifactRef,entry.label);if(repository.namespace!==release.namespace){throw new Error(`${entry.label} lives in "${repository.namespace}", outside the release's namespace "${release.namespace}". The server refuses a release that sends it to another host or org.`)}if(!isDigest(entry.digest)){throw new Error(`${entry.label}: "${entry.digest}" is not a digest. A release names artifacts by digest only.`)}const misnamed=(0,import_contracts8.actionPackageRefusal)(entry.key,entry.artifactRef);if(misnamed!==null)throw new Error(`${entry.label}: ${misnamed}`);return{...entry,repository}});for(const action of actions){if(!await manifestExists(action.repository,action.digest)){throw new Error(`${action.artifactRef}@${action.digest} (${action.key}) is not in the registry.`)}}const artifact=buildArtifact({schemaVersion:import_contracts8.CATALOG_RELEASE_SCHEMA_V1,version:version5,provenance:provenance(flags,process.cwd()),actions:actions.map(({key,artifactRef,digest:digest2})=>({key,artifactRef,digest:digest2}))});const digest=await pushArtifact(release,artifact,tag);process.stderr.write(`\u2713 catalog release ${version5} (${actions.length} action artifact(s)) published to ${release.ref}:${tag}
1088
+ `)}__name(runPublishAction,"runPublishAction");var import_contracts8=__toESM(require_dist());import{readFileSync as readFileSync2}from"fs";import{parse as parseYaml3}from"yaml";var PUBLISH_RELEASE_USAGE="runveric catalog publish-release (--from <release.yaml> | --action <key>=<repository>@<digest> \u2026)\n --to <registry>/<namespace>/<repository> [--version <label>]\n [--tag <tag>] [--repository <source url>] [--commit <sha>]";function entriesFromFlags(values){return values.map(value=>{const match=/^([^=]+)=([^@]+)@(.+)$/.exec(value);if(!match)throw new Error(`--action "${value}" is not <key>=<repository>@<digest>.`);const[,key="",artifactRef="",digest=""]=match;return{key,artifactRef,digest,label:`--action ${key}`}})}__name(entriesFromFlags,"entriesFromFlags");function specFromFile(path){let value;try{value=parseYaml3(readFileSync2(path,"utf8"))}catch(cause){throw new Error(`--from ${path} could not be read as YAML. (${cause instanceof Error?cause.message:String(cause)})`)}const spec=(0,import_contracts8.parseCatalogReleaseSpec)(value);return{version:spec.version,entries:spec.actions.map(action=>({...action,label:`${path}'s ${action.key}`}))}}__name(specFromFile,"specFromFile");async function runPublishRelease(argv){const{single:flags,many}=parseCatalogFlags(argv,["to","version","action","from","tag","repository","commit"],["action"]);const actionFlags=many.action??[];if(flags.from!==void 0&&actionFlags.length>0){throw new Error("--from and --action are alternatives: name the release's actions in release.yaml or as flags, not both.")}if(flags.from!==void 0&&flags.version!==void 0){throw new Error("--version is read from release.yaml when --from is given; pass one or the other.")}if(!flags.to||flags.from===void 0&&(!flags.version||actionFlags.length===0)){throw new Error("--to and either --from, or --version and at least one --action, are required.")}const release=parseRepository(flags.to,"--to");const{version:version6,entries}=flags.from!==void 0?specFromFile(flags.from):{version:flags.version,entries:entriesFromFlags(actionFlags)};const tag=flags.tag??(flags.from!==void 0?version6:defaultTag());requireTag(tag,flags.tag!==void 0?"--tag":`${flags.from}'s version`);const seen=new Set;const actions=entries.map(entry=>{if(seen.has(entry.key))throw new Error(`${entry.label} names "${entry.key}" twice.`);seen.add(entry.key);const repository=parseRepository(entry.artifactRef,entry.label);if(repository.namespace!==release.namespace){throw new Error(`${entry.label} lives in "${repository.namespace}", outside the release's namespace "${release.namespace}". The server refuses a release that sends it to another host or org.`)}if(!isDigest(entry.digest)){throw new Error(`${entry.label}: "${entry.digest}" is not a digest. A release names artifacts by digest only.`)}const misnamed=(0,import_contracts8.actionPackageRefusal)(entry.key,entry.artifactRef);if(misnamed!==null)throw new Error(`${entry.label}: ${misnamed}`);return{...entry,repository}});for(const action of actions){if(!await manifestExists(action.repository,action.digest)){throw new Error(`${action.artifactRef}@${action.digest} (${action.key}) is not in the registry.`)}}const artifact=buildArtifact({schemaVersion:import_contracts8.CATALOG_RELEASE_SCHEMA_V1,version:version6,provenance:provenance(flags,process.cwd()),actions:actions.map(({key,artifactRef,digest:digest2})=>({key,artifactRef,digest:digest2}))});const digest=await pushArtifact(release,artifact,tag);process.stderr.write(`\u2713 catalog release ${version6} (${actions.length} action artifact(s)) published to ${release.ref}:${tag}
1078
1089
  `);process.stderr.write(` the registry reports ${digest} \u2014 the digest to plan and pin.
1079
1090
  `);process.stdout.write(`${release.ref}@${digest}
1080
1091
  `)}__name(runPublishRelease,"runPublishRelease");var import_contracts9=__toESM(require_dist());import{readFileSync as readFileSync3}from"fs";import{parse as parseYaml4}from"yaml";var VERIFY_IMAGE_USAGE="runveric catalog verify-image (<repository>@<digest> --key <action key> --commit <sha> | --from <release.yaml>)";var COMMIT=/^[0-9a-f]{40}$/;var isMapping2=__name(value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"isMapping");function single(value,flags){if(!flags.key||!flags.commit)throw new Error(`verify-image ${value} needs --key <action key> and --commit <sha>.`);if(!COMMIT.test(flags.commit))throw new Error(`--commit "${flags.commit}" is not a 40-hex commit.`);const image=parseImageReference(value,"verify-image");const misnamed=(0,import_contracts9.actionPackageRefusal)(flags.key,image.repository.ref);if(misnamed!==null)throw new Error(misnamed);return{key:flags.key,image,provenance:{repository:(0,import_contracts9.actionSourceRepository)(flags.key),commit:flags.commit},label:`--key ${flags.key}`}}__name(single,"single");async function fromRelease(path){let value;try{value=parseYaml4(readFileSync3(path,"utf8"))}catch(cause){throw new Error(`--from ${path} could not be read as YAML. (${cause instanceof Error?cause.message:String(cause)})`)}const candidates=[];for(const action of(0,import_contracts9.parseCatalogReleaseSpec)(value).actions){const label=`${path}'s ${action.key}`;const misnamed=(0,import_contracts9.actionPackageRefusal)(action.key,action.artifactRef);if(misnamed!==null)throw new Error(`${label}: ${misnamed}`);if(!isDigest(action.digest))throw new Error(`${label}: "${action.digest}" is not a digest.`);const repository=parseRepository(action.artifactRef,label);const read=await readArtifactDocument(repository,action.digest);const document=isMapping2(read)?read:{};const schemaVersion=document.schemaVersion;if(schemaVersion===import_contracts9.CATALOG_ACTION_ARTIFACT_SCHEMA_V1)continue;if(schemaVersion!==import_contracts9.CATALOG_ACTION_ARTIFACT_SCHEMA_V2){throw new Error(`${label}: ${repository.ref}@${action.digest} declares schemaVersion ${JSON.stringify(schemaVersion)}; this CLI reads ${import_contracts9.CATALOG_ACTION_ARTIFACT_SCHEMA_V1} and ${import_contracts9.CATALOG_ACTION_ARTIFACT_SCHEMA_V2}.`)}const image=isMapping2(document.image)?document.image.digest:void 0;const recorded=isMapping2(document.provenance)?document.provenance:{};if(typeof image!=="string"||typeof recorded.repository!=="string"||typeof recorded.commit!=="string"){throw new Error(`${label}: its ${import_contracts9.CATALOG_ACTION_ARTIFACT_SCHEMA_V2} artifact carries no image digest or no provenance.`)}candidates.push({key:action.key,image:parseImageReference(`${repository.ref}@${image}`,label),provenance:{repository:recorded.repository,commit:recorded.commit},label})}return candidates}__name(fromRelease,"fromRelease");async function runVerifyImage(argv){const image=argv[0]!==void 0&&!argv[0].startsWith("--")?argv[0]:void 0;const{single:flags}=parseCatalogFlags(image===void 0?argv:argv.slice(1),["key","commit","from"]);if(image!==void 0&&flags.from!==void 0){throw new Error("An image and --from are alternatives: verify one image, or every engine action release.yaml names.")}if(image===void 0&&flags.from===void 0){throw new Error(`Name an image or a release. Usage: ${VERIFY_IMAGE_USAGE}`)}if(flags.from!==void 0&&(flags.key!==void 0||flags.commit!==void 0)){throw new Error("--key and --commit are read from each artifact when --from is given; pass one or the other.")}const candidates=image!==void 0?[single(image,flags)]:await fromRelease(flags.from);for(const candidate of candidates){const refusal=await imageRefusal(candidate.image,candidate.key,candidate.provenance);if(refusal!==null)throw new Error(`${candidate.label}: ${refusal} Nothing was signed.`)}for(const candidate of candidates){process.stderr.write(`\u2713 ${candidate.key}: ${candidate.image.ref} \u2014 built in ${candidate.provenance.repository} at ${candidate.provenance.commit}
@@ -1097,7 +1108,7 @@ The action ended without a report${failure?`: ${shown(failure)}`:""}.`));return
1097
1108
  Provenance: --repository/--commit, else GITHUB_SERVER_URL/GITHUB_REPOSITORY and GITHUB_SHA, else git.`;var SUBCOMMANDS2={"publish-action":runPublishAction,"publish-release":runPublishRelease,"verify-image":runVerifyImage};async function runCatalog(argv){const[subcommand,...rest]=argv;if(subcommand===void 0||subcommand==="--help"||rest.includes("--help")){process.stdout.write(`${CATALOG_USAGE}
1098
1109
  `);return subcommand===void 0?1:0}const run3=SUBCOMMANDS2[subcommand];if(run3===void 0){printError(`\u2717 "catalog ${subcommand}" is not a command. There are ${Object.keys(SUBCOMMANDS2).length}: ${Object.keys(SUBCOMMANDS2).join(", ")}.`);return 1}try{await run3(rest);return 0}catch(error){printError(`\u2717 ${error instanceof Error?error.message:String(error)}`);return 1}}__name(runCatalog,"runCatalog");var import_action_manifest=__toESM(require_dist4());import{resolve as resolve4}from"path";import{readdir,readFile as readFile2,stat}from"fs/promises";import{join as join3,relative as relative2,sep}from"path";var IGNORED_DIRECTORIES=new Set([".git",".runveric","node_modules",".venv","__pycache__",".DS_Store"]);var MAX_FILES=2e3;var MAX_TOTAL_BYTES=16*1024*1024;var PackageDirectoryError=class extends Error{static{__name(this,"PackageDirectoryError")}};async function readPackageDirectory(root){const properties=await stat(root).catch(()=>null);if(!properties?.isDirectory()){throw new PackageDirectoryError(`${root} is not a directory.`)}const files=new Map;let totalBytes=0;const walk=__name(async directory=>{for(const entry of await readdir(directory,{withFileTypes:true})){if(IGNORED_DIRECTORIES.has(entry.name))continue;const full=join3(directory,entry.name);if(entry.isDirectory()){await walk(full);continue}if(!entry.isFile())continue;if(files.size>=MAX_FILES){throw new PackageDirectoryError(`This directory holds more than ${MAX_FILES} files. That is almost certainly not a single action package \u2014 run this from the package directory itself.`)}const contents=await readFile2(full);totalBytes+=contents.byteLength;if(totalBytes>MAX_TOTAL_BYTES){throw new PackageDirectoryError(`This directory holds more than ${MAX_TOTAL_BYTES/(1024*1024)}MB. An action package is source, not artifacts \u2014 add build output to .gitignore.`)}files.set(toPackagePath(root,full),contents)}},"walk");await walk(root);return files}__name(readPackageDirectory,"readPackageDirectory");function toPackagePath(root,full){return relative2(root,full).split(sep).join("/")}__name(toPackagePath,"toPackagePath");var import_contracts10=__toESM(require_dist());async function runCheck(options){const directory=resolve4(options.directory??".");let files;try{files=await readPackageDirectory(directory)}catch(error){printError(style.red(error instanceof Error?error.message:String(error)));return 1}const report=(0,import_action_manifest.checkActionPackage)(files);print();print(`${style.bold("check")} ${style.grey(directory)}`);print();for(const finding of report.findings)printFinding(finding);printCheckSummary({errors:report.errorCount,warnings:report.warningCount});if(!report.validation.ok){print();print(style.red("This package would be REFUSED at import."))}else if(report.lintBlocked){print();print(style.red("This package would be ACCEPTED at import \u2014 and then misbehave.")+` The errors above are not things ${import_contracts10.BRAND_SHORT_NAME} checks; they are things that go wrong at run time, silently.`)}if(report.advisoryCount>0){print();print(style.red(`${report.advisoryCount} of the errors above ${report.advisoryCount===1?"is":"are"} ADVISORY.`)+" They are found by a text search that cannot be certain, so they do not refuse a publish \u2014 `check --strict` does, if you want the gate.")}if(report.validation.ok&&!report.lintBlocked){print();print(style.grey("Not checked here (they depend on the deployment, not the package): whether its runner ships your interpreter, whether it can broker outbound network, and whether organization packages are enabled. Those are answered at import."));print();print(`Next: ${style.bold("runveric test --phase run")}`)}print();const strictFailure=options.strict===true&&(report.warningCount>0||report.advisoryCount>0);const failed=!report.validation.ok||report.lintBlocked||strictFailure;return failed?1:0}__name(runCheck,"runCheck");var import_contracts11=__toESM(require_dist());var import_action_manifest2=__toESM(require_dist4());import{mkdir as mkdir2,writeFile as writeFile2}from"fs/promises";import{createInterface}from"readline/promises";import{dirname as dirname3,join as join4,resolve as resolve5}from"path";async function runInit(options){const interactive=process.stdin.isTTY===true&&options.yes!==true;const ask=interactive?prompter():null;try{const id=await resolveId(options.id,ask);if(!id)return 1;const suggestedName=titleCase(id.split("/")[1]??id);const name3=options.name?.trim()||await ask?.("Display name",suggestedName)||suggestedName;const interpreter=await resolveInterpreter(options.interpreter,ask);if(!interpreter)return 1;const author=options.author?.trim()||await ask?.("Author",id.split("/")[0])||id.split("/")[0];const directory=resolve5(options.directory??id.split("/")[1]??"action");const files=(0,import_action_manifest2.scaffoldActionPackage)({id,name:name3,interpreter,author,year:options.year??new Date().getFullYear()});for(const[path,contents]of files){const target=join4(directory,path);await mkdir2(dirname3(target),{recursive:true});await writeFile2(target,contents,{flag:"wx"}).catch(error=>{throw error.code==="EEXIST"?new Error(`${join4(directory,path)} already exists. init never overwrites \u2014 remove the directory, or run init somewhere else.`):error})}print();print(`${style.green("\u2713")} Created ${style.bold(directory)}`);print();for(const path of files.keys())print(` ${style.grey(path)}`);print();print("It already works. Prove it before you change anything:");print();print(` ${style.bold("cd")} ${directory}`);print(` ${style.bold("runveric check")}`);print(` ${style.bold("runveric test --phase run")}`);print();return 0}catch(error){printError(style.red(error instanceof Error?error.message:String(error)));return 1}finally{ask?.close()}}__name(runInit,"runInit");async function resolveId(supplied,ask){const value=supplied?.trim()||await ask?.("Action id (publisher/name)","");if(!value){printError(style.red("An id is required.")+' Use --id publisher/name, e.g. --id "contoso/restart-web-tier".');return null}if(!import_action_manifest2.PACKAGE_ID_PATTERN.test(value)){printError(style.red(`"${value}" is not a valid action id.`)+" It is `publisher/name`, lowercase letters, digits and hyphens \u2014 e.g. `contoso/restart-web-tier`. The publisher half is how an operator tells your actions from somebody else's in the catalog.");return null}return value}__name(resolveId,"resolveId");async function resolveInterpreter(supplied,ask){const value=supplied?.trim()||await ask?.(`Interpreter (${import_contracts11.PACKAGE_INTERPRETERS.join(" / ")})`,"bash")||"bash";if(!isInterpreter(value)){printError(style.red(`"${value}" is not an interpreter ${import_contracts11.BRAND_SHORT_NAME} runs.`)+` The runner image ships ${import_contracts11.PACKAGE_INTERPRETERS.join(", ")}.`);return null}return value}__name(resolveInterpreter,"resolveInterpreter");function prompter(){const rl=createInterface({input:process.stdin,output:process.stdout});const ask=__name(async(question,fallback)=>{const suffix=fallback?` ${style.grey(`(${fallback})`)}`:"";const answer=(await rl.question(`${question}${suffix}: `)).trim();return answer||fallback},"ask");ask.close=()=>rl.close();return ask}__name(prompter,"prompter");function isInterpreter(value){return import_contracts11.PACKAGE_INTERPRETERS.includes(value)}__name(isInterpreter,"isInterpreter");function titleCase(value){return value.split(/[-_]/).filter(Boolean).map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join(" ")}__name(titleCase,"titleCase");var import_action_manifest3=__toESM(require_dist4());var import_contracts12=__toESM(require_dist());import{resolve as resolve6}from"path";function renamedVariableRefusal(current,retired,env=process.env){if(env[current]?.trim())return null;if(!env[retired]?.trim())return null;return`${retired} is set, but this CLI reads ${current} \u2014 the variable was renamed in 0.1.2. Rename the export in your shell or CI; ${retired} is no longer read.`}__name(renamedVariableRefusal,"renamedVariableRefusal");var TOKEN_ENV=import_contracts12.AUTHORING_CLI_ENV.token;var URL_ENV=import_contracts12.AUTHORING_CLI_ENV.url;async function runPublish(options){const directory=resolve6(options.directory??".");const baseUrl=(options.to??process.env[URL_ENV]??"").trim().replace(/\/+$/,"");const token2=(options.token??process.env[TOKEN_ENV]??"").trim();const stale=[options.to===void 0?renamedVariableRefusal(URL_ENV,import_contracts12.RETIRED_AUTHORING_CLI_ENV.url):null,options.token===void 0?renamedVariableRefusal(TOKEN_ENV,import_contracts12.RETIRED_AUTHORING_CLI_ENV.token):null].filter(sentence=>sentence!==null);if(stale.length>0){for(const sentence of stale)printError(style.red(sentence));return 1}if(!baseUrl){printError(style.red("Where to?")+` Pass --to https://your-runveric.example.com, or set ${URL_ENV}.`);return 1}if(!token2){printError(style.red(`Publishing needs ${import_contracts12.BRAND_ARTICLE} ${import_contracts12.BRAND_SHORT_NAME} access token.`)+` Set ${TOKEN_ENV}, or pass --token. (init, check and test need no account at all.)`);return 1}let files;try{files=await readPackageDirectory(directory)}catch(error){printError(style.red(error instanceof Error?error.message:String(error)));return 1}const report=(0,import_action_manifest3.checkActionPackage)(files);if(!report.validation.ok||report.lintBlocked&&options.force!==true){print();for(const finding of report.findings.filter(f=>f.severity==="error")){printFinding(finding)}printCheckSummary({errors:report.errorCount,warnings:report.warningCount});printError(style.red("\nNot published.")+(report.validation.ok?` ${import_contracts12.BRAND_SHORT_NAME} would accept this, but the problems above make it misbehave at run time. Fix them, or pass --force if you disagree.`:" Fix the errors above and publish again."));return 1}if(report.advisoryCount>0){print();for(const finding of report.findings.filter(f=>f.advisory===true)){printFinding(finding)}print(style.yellow("Publishing anyway.")+" The above cannot be checked with certainty, so it does not refuse a publish.")}const manifest=report.validation.manifest;print();print(`${style.bold("publish")} ${manifest.id} ${manifest.version} \u2192 ${baseUrl}`);const body=JSON.stringify({files:[...files].map(([path,contents])=>({path,contentBase64:contents.toString("base64")}))});let response;try{response=await fetch(`${baseUrl}/packages/authored`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${token2}`},body})}catch(error){printError(style.red(`Could not reach ${baseUrl}.`)+`
1099
1110
  ${error instanceof Error?error.message:String(error)}`);return 1}const text=await response.text();if(!response.ok){printError(style.red(`
1100
- Publish refused (${response.status}).`));printError(formatProblem(text));return 1}let version5;try{version5=JSON.parse(text)}catch{printError(style.red(`${import_contracts12.BRAND_SHORT_NAME} accepted the package but returned a response we cannot read.`));return 1}print();print(`${style.green("\u2713")} Published ${style.bold(`${version5.packageId} ${version5.semanticVersion}`)}`);print(` version id ${version5.id}`);print(` content digest ${version5.contentDigest}`);print(` tier ${version5.tier} ${style.grey(`(${version5.provenance})`)}`);print();print(style.grey(`It is an immutable version now. Adopt it in ${import_contracts12.BRAND_SHORT_NAME} to put it in the catalog \u2014 publishing does not adopt, so nobody can run it until somebody chooses to.`));print();return 0}__name(runPublish,"runPublish");function formatProblem(text){let parsed;try{parsed=JSON.parse(text)}catch{return` ${text}`}const problem=(0,import_contracts12.parseProblemDocument)(parsed);if(!problem)return` ${text}`;const lines=[];if(problem.detail)lines.push(` ${problem.detail}`);for(const error of(0,import_contracts12.problemFieldErrors)(problem)){lines.push(error.field?` ${style.bold(error.field)}: ${error.message}`:` ${error.message}`)}return lines.length>0?lines.join("\n"):` ${text}`}__name(formatProblem,"formatProblem");var import_contracts13=__toESM(require_dist());import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";var run=promisify2(execFile2);var LOCAL_RUNNER_IMAGE="runveric-package-runner:local";var RUNNER_IMAGE_ENV=import_contracts13.AUTHORING_CLI_ENV.runnerImage;var RenamedVariableError=class extends Error{static{__name(this,"RenamedVariableError")}};function resolveRunnerImage(flag){const explicit=flag?.trim();if(explicit)return{reference:explicit,origin:"flag"};const configured=process.env[RUNNER_IMAGE_ENV]?.trim();if(configured)return{reference:configured,origin:"environment"};const stale=renamedVariableRefusal(RUNNER_IMAGE_ENV,import_contracts13.RETIRED_AUTHORING_CLI_ENV.runnerImage);if(stale)throw new RenamedVariableError(stale);return{reference:LOCAL_RUNNER_IMAGE,origin:"local-build"}}__name(resolveRunnerImage,"resolveRunnerImage");function runnerImageNote(image){switch(image.origin){case"flag":return"from --image";case"environment":return`from ${RUNNER_IMAGE_ENV}`;case"local-build":return`locally built \u2014 NOT the image your ${import_contracts13.BRAND_SHORT_NAME} runs; set ${RUNNER_IMAGE_ENV} to match it`}}__name(runnerImageNote,"runnerImageNote");var DockerMissingError=class extends Error{static{__name(this,"DockerMissingError")}};async function assertDockerAvailable(){try{await run("docker",["version","--format","{{.Server.Version}}"])}catch{throw new DockerMissingError(`Docker is not available. \`runveric test\` runs your package in the real ${import_contracts13.BRAND_SHORT_NAME} runner image, which needs a container runtime \u2014 install Docker Desktop (or start it), then try again. \`runveric check\` needs nothing and still works.`)}}__name(assertDockerAvailable,"assertDockerAvailable");async function imageIsPresent(reference){try{await run("docker",["image","inspect",reference]);return true}catch{return false}}__name(imageIsPresent,"imageIsPresent");var import_action_manifest4=__toESM(require_dist4());import{spawn}from"child_process";import{mkdir as mkdir3,mkdtemp,readFile as readFile3,rm,stat as stat2,writeFile as writeFile3}from"fs/promises";import{tmpdir}from"os";import{dirname as dirname4,join as join5,resolve as resolve7}from"path";import{StringDecoder}from"string_decoder";import{execFile as execFile3}from"child_process";import{promisify as promisify3}from"util";var run2=promisify3(execFile3);var AzureCredentialError=class extends Error{static{__name(this,"AzureCredentialError")}};var MANAGEMENT_RESOURCE="https://management.azure.com";async function acquireAzureCredential(){const account=await azJson(["account","show","--output","json"]);if(!account.id||!account.tenantId){throw new AzureCredentialError("`az account show` returned no subscription. Run `az login` and `az account set --subscription <id>` first.")}const token2=await azJson(["account","get-access-token","--resource",MANAGEMENT_RESOURCE,"--output","json"]);if(!token2.accessToken){throw new AzureCredentialError("`az account get-access-token` returned no access token.")}return{token:token2.accessToken,env:{AZURE_SUBSCRIPTION_ID:account.id,AZURE_TENANT_ID:account.tenantId},account:{name:account.name??account.id,subscriptionId:account.id,tenantId:account.tenantId}}}__name(acquireAzureCredential,"acquireAzureCredential");async function azJson(args){let stdout;try{({stdout}=await run2("az",args,{maxBuffer:8*1024*1024}))}catch(error){const message=error instanceof Error?error.message:String(error);throw new AzureCredentialError(message.includes("ENOENT")?"The Azure CLI (`az`) is not installed. Install it and run `az login`, or run with --no-credential to test a package that does not call Azure.":`\`az ${args.join(" ")}\` failed. Run \`az login\` and try again.
1111
+ Publish refused (${response.status}).`));printError(formatProblem(text));return 1}let version6;try{version6=JSON.parse(text)}catch{printError(style.red(`${import_contracts12.BRAND_SHORT_NAME} accepted the package but returned a response we cannot read.`));return 1}print();print(`${style.green("\u2713")} Published ${style.bold(`${version6.packageId} ${version6.semanticVersion}`)}`);print(` version id ${version6.id}`);print(` content digest ${version6.contentDigest}`);print(` tier ${version6.tier} ${style.grey(`(${version6.provenance})`)}`);print();print(style.grey(`It is an immutable version now. Adopt it in ${import_contracts12.BRAND_SHORT_NAME} to put it in the catalog \u2014 publishing does not adopt, so nobody can run it until somebody chooses to.`));print();return 0}__name(runPublish,"runPublish");function formatProblem(text){let parsed;try{parsed=JSON.parse(text)}catch{return` ${text}`}const problem=(0,import_contracts12.parseProblemDocument)(parsed);if(!problem)return` ${text}`;const lines=[];if(problem.detail)lines.push(` ${problem.detail}`);for(const error of(0,import_contracts12.problemFieldErrors)(problem)){lines.push(error.field?` ${style.bold(error.field)}: ${error.message}`:` ${error.message}`)}return lines.length>0?lines.join("\n"):` ${text}`}__name(formatProblem,"formatProblem");var import_contracts13=__toESM(require_dist());import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";var run=promisify2(execFile2);var LOCAL_RUNNER_IMAGE="runveric-package-runner:local";var RUNNER_IMAGE_ENV=import_contracts13.AUTHORING_CLI_ENV.runnerImage;var RenamedVariableError=class extends Error{static{__name(this,"RenamedVariableError")}};function resolveRunnerImage(flag){const explicit=flag?.trim();if(explicit)return{reference:explicit,origin:"flag"};const configured=process.env[RUNNER_IMAGE_ENV]?.trim();if(configured)return{reference:configured,origin:"environment"};const stale=renamedVariableRefusal(RUNNER_IMAGE_ENV,import_contracts13.RETIRED_AUTHORING_CLI_ENV.runnerImage);if(stale)throw new RenamedVariableError(stale);return{reference:LOCAL_RUNNER_IMAGE,origin:"local-build"}}__name(resolveRunnerImage,"resolveRunnerImage");function runnerImageNote(image){switch(image.origin){case"flag":return"from --image";case"environment":return`from ${RUNNER_IMAGE_ENV}`;case"local-build":return`locally built \u2014 NOT the image your ${import_contracts13.BRAND_SHORT_NAME} runs; set ${RUNNER_IMAGE_ENV} to match it`}}__name(runnerImageNote,"runnerImageNote");var DockerMissingError=class extends Error{static{__name(this,"DockerMissingError")}};async function assertDockerAvailable(){try{await run("docker",["version","--format","{{.Server.Version}}"])}catch{throw new DockerMissingError(`Docker is not available. \`runveric test\` runs your package in the real ${import_contracts13.BRAND_SHORT_NAME} runner image, which needs a container runtime \u2014 install Docker Desktop (or start it), then try again. \`runveric check\` needs nothing and still works.`)}}__name(assertDockerAvailable,"assertDockerAvailable");async function imageIsPresent(reference){try{await run("docker",["image","inspect",reference]);return true}catch{return false}}__name(imageIsPresent,"imageIsPresent");var import_action_manifest4=__toESM(require_dist4());import{spawn}from"child_process";import{mkdir as mkdir3,mkdtemp,readFile as readFile3,rm,stat as stat2,writeFile as writeFile3}from"fs/promises";import{tmpdir}from"os";import{dirname as dirname4,join as join5,resolve as resolve7}from"path";import{StringDecoder}from"string_decoder";import{execFile as execFile3}from"child_process";import{promisify as promisify3}from"util";var run2=promisify3(execFile3);var AzureCredentialError=class extends Error{static{__name(this,"AzureCredentialError")}};var MANAGEMENT_RESOURCE="https://management.azure.com";async function acquireAzureCredential(){const account=await azJson(["account","show","--output","json"]);if(!account.id||!account.tenantId){throw new AzureCredentialError("`az account show` returned no subscription. Run `az login` and `az account set --subscription <id>` first.")}const token2=await azJson(["account","get-access-token","--resource",MANAGEMENT_RESOURCE,"--output","json"]);if(!token2.accessToken){throw new AzureCredentialError("`az account get-access-token` returned no access token.")}return{token:token2.accessToken,env:{AZURE_SUBSCRIPTION_ID:account.id,AZURE_TENANT_ID:account.tenantId},account:{name:account.name??account.id,subscriptionId:account.id,tenantId:account.tenantId}}}__name(acquireAzureCredential,"acquireAzureCredential");async function azJson(args){let stdout;try{({stdout}=await run2("az",args,{maxBuffer:8*1024*1024}))}catch(error){const message=error instanceof Error?error.message:String(error);throw new AzureCredentialError(message.includes("ENOENT")?"The Azure CLI (`az`) is not installed. Install it and run `az login`, or run with --no-credential to test a package that does not call Azure.":`\`az ${args.join(" ")}\` failed. Run \`az login\` and try again.
1101
1112
  ${message.trim()}`)}try{return JSON.parse(stdout)}catch{throw new AzureCredentialError(`\`az ${args.join(" ")}\` did not return JSON.`)}}__name(azJson,"azJson");var import_contracts14=__toESM(require_dist());var PHASES2=["validate","run","rollback"];var CONTAINER={packageRoot:"/runveric/package",input:"/runveric/input",output:"/runveric/output",scratch:"/runveric/scratch",creds:"/runveric/creds"};async function runTest(options){const directory=resolve7(options.directory??".");const phase=options.phase??"run";if(!PHASES2.includes(phase)){printError(style.red(`"${options.phase}" is not a phase.`)+` ${import_contracts14.BRAND_SHORT_NAME} runs ${PHASES2.join(", ")} \u2014 one at a time, so you can read each one's result.`);return 1}let files;try{files=await readPackageDirectory(directory)}catch(error){printError(style.red(error instanceof Error?error.message:String(error)));return 1}const report=(0,import_action_manifest4.checkActionPackage)(files);if(!report.validation.ok){printError(style.red("This package would be refused at import, so there is nothing to test.")+" Run `runveric check` to see why.");return 1}const{manifest,parameterSchema}=report.validation;if(manifest.runtime.kind!=="interpreter"){printError(style.red("`test` runs interpreter packages.")+` This one declares an OCI image (${manifest.runtime.image}); run that image directly.`);return 1}const interpreter=manifest.runtime.name;const entrypoint=entrypointFor(manifest,phase);if(!entrypoint){printError(style.red(`This package declares no ${phase} phase.`)+(phase==="validate"?" Add `validateEntrypoint: validate/` to action.yaml to enable the pre-flight.":phase==="rollback"?" Set `rollback: true` and `rollbackEntrypoint: rollback/` in action.yaml.":""));return 1}let parameters;try{parameters=await resolveParameters(parameterSchema,options)}catch(error){printError(style.red(error instanceof Error?error.message:String(error)));return 1}let image;try{image=resolveRunnerImage(options.image)}catch(error){printError(style.red(error instanceof Error?error.message:String(error)));return 1}try{await assertDockerAvailable()}catch(error){printError(style.red(error instanceof Error?error.message:String(error)));return 1}let credential=null;if(options.noCredential!==true){try{credential=await acquireAzureCredential()}catch(error){if(!(error instanceof AzureCredentialError))throw error;printError(style.red(error.message));return 1}}const workspace=await mkdtemp(join5(tmpdir(),"runveric-"));try{const layout=await materialize(workspace,{files,parameters,phase,dryRun:options.dryRun===true,subscriptionId:credential?.account.subscriptionId??"local-test",priorResult:options.priorResult?await readJsonFile(options.priorResult):void 0,credentialToken:credential?.token});print();print(`${style.bold("test")} ${manifest.id} ${manifest.version} ${style.grey(`phase ${phase}`)}`);print(` runner image ${image.reference} ${style.grey(`(${runnerImageNote(image)})`)}`);print(` interpreter ${interpreter}@${manifest.runtime.version}`);print(` entrypoint ${entrypoint}${import_action_manifest4.PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`);print(` identity ${credential?`${credential.account.name} ${style.grey(`\u2014 YOUR access, not ${import_contracts14.BRAND_SHORT_NAME}'s brokered least-privilege identity`)}`:style.grey("none (--no-credential)")}`);if(manifest.requiresNetwork){print(` network ${style.yellow("open")} ${style.grey(`\u2014 your allowlist (${(manifest.egressAllowlist??[]).join(", ")}) is NOT enforced here; ${import_contracts14.BRAND_SHORT_NAME} enforces it`)}`)}else{print(` network ${style.grey("none \u2014 this package declares requiresNetwork: false")}`)}if(options.dryRun)print(` ${style.bold("dry run")} RUNVERIC_DRY_RUN=true`);if(!await imageIsPresent(image.reference)){print(` ${style.grey("pulling the image (first run only)\u2026")}`)}print();print(style.bold("Events"));const events=[];const exit=await runContainer({image:image.reference,interpreter,entrypoint,layout,phase,dryRun:options.dryRun===true,requiresNetwork:manifest.requiresNetwork,credentialEnv:credential?.env,timeoutMs:15*60*1e3,onEvent:__name(event=>{events.push(event);printEvent(event)},"onEvent")});if(events.length===0)print(style.grey(" (the package printed nothing)"));return await reportOutcome({exit,resultPath:join5(layout.output,"result.json"),phase,workspace,keep:options.keep===true})}finally{if(options.keep===true){print(style.grey(` kept ${workspace}`))}else{await rm(workspace,{recursive:true,force:true})}}}__name(runTest,"runTest");function entrypointFor(manifest,phase){if(phase==="run")return manifest.entrypoint;if(phase==="validate")return manifest.validateEntrypoint??null;return manifest.rollbackEntrypoint??null}__name(entrypointFor,"entrypointFor");async function resolveParameters(schema,options){const properties=schema.properties??{};const parameters={};for(const[name3,property]of Object.entries(properties)){if(property.default!==void 0)parameters[name3]=property.default}if(options.paramsFile){const supplied=await readJsonFile(options.paramsFile);for(const[name3,value]of Object.entries(supplied))parameters[name3]=value}for(const pair of options.param??[]){const separator=pair.indexOf("=");if(separator<=0){throw new Error(`--param expects name=value; got "${pair}".`)}const name3=pair.slice(0,separator);const raw=pair.slice(separator+1);if(!(name3 in properties)){throw new Error(`"${name3}" is not a parameter of this action. It declares: ${Object.keys(properties).join(", ")||"(none)"}.`)}parameters[name3]=properties[name3]?.type==="boolean"?raw==="true":raw}const missing=(schema.required??[]).filter(name3=>parameters[name3]===void 0);if(missing.length>0){throw new Error(`These parameters are required and have no value: ${missing.join(", ")}. Supply them with --param ${missing[0]}=\u2026 (repeatable), or --params-file params.json.`)}return parameters}__name(resolveParameters,"resolveParameters");async function materialize(workspace,input){const layout={packageRoot:join5(workspace,"package"),input:join5(workspace,"input"),output:join5(workspace,"output"),scratch:join5(workspace,"scratch"),creds:join5(workspace,"creds"),hasCredential:input.credentialToken!==void 0,hasPriorResult:input.priorResult!==void 0};await Promise.all([layout.packageRoot,layout.input,layout.output,layout.scratch,layout.creds].map(directory=>mkdir3(directory,{recursive:true})));for(const[path,contents]of input.files){const target=join5(layout.packageRoot,path);await mkdir3(dirname4(target),{recursive:true});await writeFile3(target,contents)}const context={protocolVersion:import_contracts14.PACKAGE_EXECUTION_PROTOCOL_VERSION,executionId:"local-test",phase:input.phase,provider:"azure",providerScopeId:input.subscriptionId,dryRun:input.dryRun};await writeFile3(join5(layout.input,"context.json"),JSON.stringify(context,null,2));await writeFile3(join5(layout.input,"parameters.json"),JSON.stringify(input.parameters,null,2));if(input.priorResult){await writeFile3(join5(layout.input,"prior-result.json"),JSON.stringify(input.priorResult,null,2))}if(input.credentialToken){await writeFile3(join5(layout.creds,"azure-token"),input.credentialToken,{mode:256})}return layout}__name(materialize,"materialize");async function runContainer(options){const launch=import_action_manifest4.PACKAGE_INTERPRETER_LAUNCH[options.interpreter];const script=`${CONTAINER.packageRoot}/${options.entrypoint}${launch.entryFile}`;const environment={RUNVERIC_PROTOCOL_VERSION:import_contracts14.PACKAGE_RESULT_PROTOCOL_VERSION,RUNVERIC_PHASE:options.phase,RUNVERIC_CONTEXT_FILE:`${CONTAINER.input}/context.json`,RUNVERIC_PARAMETERS_FILE:`${CONTAINER.input}/parameters.json`,RUNVERIC_RESULT_FILE:`${CONTAINER.output}/result.json`,RUNVERIC_WORK_DIR:CONTAINER.scratch,RUNVERIC_CANCEL_FILE:`${CONTAINER.input}/cancel.requested`,RUNVERIC_DRY_RUN:options.dryRun?"true":"false",RUNVERIC_NETWORK_ISOLATED:options.requiresNetwork?"false":"true",LANG:"C.UTF-8",LC_ALL:"C.UTF-8",POWERSHELL_TELEMETRY_OPTOUT:"1",DOTNET_CLI_TELEMETRY_OPTOUT:"1",...options.layout.hasPriorResult?{RUNVERIC_PRIOR_RESULT_FILE:`${CONTAINER.input}/prior-result.json`}:{},...options.layout.hasCredential?{RUNVERIC_AZURE_TOKEN_FILE:`${CONTAINER.creds}/azure-token`}:{},...options.credentialEnv??{}};const args=["run","--rm","--interactive=false","--workdir",CONTAINER.scratch,...options.requiresNetwork?[]:["--network","none"],"--mount",`type=bind,source=${options.layout.packageRoot},target=${CONTAINER.packageRoot},readonly`,"--mount",`type=bind,source=${options.layout.input},target=${CONTAINER.input},readonly`,"--mount",`type=bind,source=${options.layout.output},target=${CONTAINER.output}`,"--mount",`type=bind,source=${options.layout.scratch},target=${CONTAINER.scratch}`,...options.layout.hasCredential?["--mount",`type=bind,source=${options.layout.creds},target=${CONTAINER.creds},readonly`]:[],...Object.entries(environment).flatMap(([name3,value])=>["--env",`${name3}=${value}`]),"--entrypoint",launch.fileName,options.image,...launch.arguments,script];return await new Promise((resolvePromise,reject)=>{const child=spawn("docker",args,{stdio:["ignore","pipe","pipe"]});let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},options.timeoutMs);const consume=__name(stderr=>{const decoder=new StringDecoder("utf8");let pending="";return chunk=>{pending+=decoder.write(chunk);const lines=pending.split(/\r?\n/);pending=lines.pop()??"";for(const line of lines)emitLine(line,stderr,options.onEvent)}},"consume");child.stdout.on("data",consume(false));child.stderr.on("data",consume(true));child.once("error",error=>{clearTimeout(timer);reject(error)});child.once("close",code=>{clearTimeout(timer);resolvePromise({code,timedOut})})})}__name(runContainer,"runContainer");function emitLine(line,stderr,onEvent){if(line.length===0)return;const prefix="RUNVERIC_EVENT ";if(!stderr&&line.startsWith(prefix)){try{const parsed=JSON.parse(line.slice(prefix.length));if(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)){onEvent(parsed);return}}catch{}onEvent({level:"warn",message:"Package emitted malformed RUNVERIC_EVENT JSON."});return}onEvent({level:stderr?"warn":"info",message:line})}__name(emitLine,"emitLine");async function reportOutcome(options){if(options.exit.timedOut){printError(style.red("\nThe package did not finish within 15 minutes and was killed.")+` ${import_contracts14.BRAND_SHORT_NAME} enforces the \`executionTimeout\` in your manifest; this is the local ceiling.`);return 1}const exists=await stat2(options.resultPath).catch(()=>null);if(!exists?.isFile()||exists.size===0){printError(style.red("\nThe package wrote no result.")+`
1102
1113
  result.json is the only channel ${import_contracts14.BRAND_SHORT_NAME} reads. Exiting ${options.exit.code??"with a signal"} without writing $RUNVERIC_RESULT_FILE is a FAILED run, whatever the script printed.
1103
1114
  Write it as the last thing your script does, on every path \u2014 including the ones that fail.`);return 1}let parsed;try{parsed=JSON.parse(await readFile3(options.resultPath,"utf8"))}catch{printError(style.red("\nresult.json is not valid JSON.")+` ${import_contracts14.BRAND_SHORT_NAME} refuses the run rather than guessing what the package meant.`);return 1}let result;try{result=(0,import_action_manifest4.validatePackageResult)(parsed,options.phase)}catch(error){printError(style.red(`