@unbrained/pm-cli 2026.11.18 → 2026.11.19

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.
Files changed (93) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli-bundle/bundle-manifest.json +1 -1
  3. package/dist/cli-bundle/chunks/chunk-2UTJ5QIE.js +71 -0
  4. package/dist/cli-bundle/chunks/{chunk-T3E3WNHO.js → chunk-4FNMPZ7Y.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-2VH6COJE.js → chunk-723PMYNX.js} +37 -37
  6. package/dist/cli-bundle/chunks/{chunk-S3RMFLEG.js → chunk-AGPFANRX.js} +3 -3
  7. package/dist/cli-bundle/chunks/{chunk-TS2CZE3O.js → chunk-AMHD7WIV.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-VETSGCF4.js → chunk-AOV5HG3Y.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-WKHS4QC6.js → chunk-CNMGGAZO.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-LGWP5D7V.js → chunk-CTOE26W4.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-7LCJA54R.js → chunk-GQCMICAL.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-JBPXNG6P.js → chunk-IQKCRLQP.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-SSZBVRIN.js → chunk-IUTN67EB.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-7ETRLLK3.js → chunk-M76BEWTT.js} +30 -30
  15. package/dist/cli-bundle/chunks/{chunk-TA5VN4ME.js → chunk-N2CPCFSN.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-MUGGRKK3.js → chunk-NMVPQTZI.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-YJI2Y5N6.js → chunk-O7IFAJ76.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-CGTVDSAR.js → chunk-OESI2ETD.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-FJQCORYR.js → chunk-P4A5RFLX.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-L2ZLH3LZ.js → chunk-PRVT7ITI.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-XDIJK6VW.js → chunk-Q32Q3LRH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-AGU7632B.js → chunk-XPBPGDFW.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-QK7RAN7R.js → chunk-Z5LHCEXG.js} +2 -2
  24. package/dist/cli-bundle/chunks/{item-revision-BV5BUBCR.js → item-revision-YJKGOYBR.js} +2 -2
  25. package/dist/cli-bundle/chunks/item-transaction-K4YZ7GWR.js +2 -0
  26. package/dist/cli-bundle/chunks/{mutation-admission-5AWMXMCB.js → mutation-admission-JLMQJ2M5.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-list-query-RJT7YBRF.js → register-list-query-4AXLLXK7.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-mutation-6KTMJGYF.js → register-mutation-FJIXGGF4.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-operations-W24TA3HZ.js → register-operations-W4E2KEMA.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-setup-QK67WUX6.js → register-setup-RYRIBNSN.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-LZR3JKYT.js → chunk-2XULTI5B.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-3H3SVHAT.js → chunk-4S7I342K.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-6OZ7BKWJ.js → chunk-77CDWGBW.js} +55 -54
  34. package/dist/cli-bundle/focused-chunks/{chunk-IGMFXB5W.js → chunk-7A4VIRIU.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-EO4XM3XJ.js → chunk-D72EQN7Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-PNCCTZKI.js → chunk-GAOWBALE.js} +23 -23
  37. package/dist/cli-bundle/focused-chunks/{chunk-T3NMYMW4.js → chunk-N64BUB63.js} +24 -24
  38. package/dist/cli-bundle/focused-chunks/{chunk-DWCFZVT2.js → chunk-OF4UM5B6.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-ONHUG7IL.js → chunk-P4TG4VMJ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{item-revision-NS2V4WON.js → item-revision-32HFGFYG.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{item-transaction-NENC4HYI.js → item-transaction-C4VW3SHX.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{mutation-admission-DZIBDJAE.js → mutation-admission-PNK6ORZR.js} +2 -2
  43. package/dist/cli-bundle/main.js +2 -2
  44. package/dist/cli-bundle/sdk-authoring.js +1 -1
  45. package/dist/cli-bundle/sdk-core.js +1 -1
  46. package/dist/cli-bundle/sdk-governance.js +1 -1
  47. package/dist/cli-bundle/sdk-merge.js +53 -53
  48. package/dist/cli-bundle/sdk-query.js +1 -1
  49. package/dist/cli-bundle/sdk-runtime.js +1 -1
  50. package/dist/cli-bundle/sdk-testing.js +1 -1
  51. package/dist/cli-bundle/sdk.js +11 -11
  52. package/dist/core/shared/process-tree.js +3 -0
  53. package/dist/core/shared/secret-rules.d.ts +12 -1
  54. package/dist/core/shared/secret-rules.js +2 -2
  55. package/dist/sdk/extension/managed-state.d.ts +3 -1
  56. package/dist/sdk/extension/managed-state.js +1 -1
  57. package/dist/sdk/extension/managed-update-status.js +1 -1
  58. package/dist/sdk/extension/update-check.d.ts +42 -6
  59. package/dist/sdk/extension/update-check.js +1 -1
  60. package/dist/sdk/extension.d.ts +3 -1
  61. package/dist/sdk/extension.js +1 -1
  62. package/dist/sdk/index.d.ts +1 -1
  63. package/dist/sdk/index.js +1 -1
  64. package/dist/sdk/mutation-guard.d.ts +121 -1
  65. package/dist/sdk/mutation-guard.js +1 -1
  66. package/dist/sdk/public-surface.json +1 -1
  67. package/dist/sdk/test/execution.js +2 -2
  68. package/docs/CONFIGURATION.md +1 -0
  69. package/docs/MUTATION_INTEGRITY.md +72 -0
  70. package/docs/PACKAGE_EVIDENCE.md +66 -0
  71. package/marketplace.json +1 -1
  72. package/package.json +1 -1
  73. package/packages/pm-beads/package.json +1 -1
  74. package/packages/pm-calendar/package.json +1 -1
  75. package/packages/pm-command-kit/package.json +1 -1
  76. package/packages/pm-digital-twin/package.json +1 -1
  77. package/packages/pm-governance-audit/package.json +1 -1
  78. package/packages/pm-guide-shell/package.json +1 -1
  79. package/packages/pm-kanban/package.json +1 -1
  80. package/packages/pm-lifecycle-hooks/package.json +1 -1
  81. package/packages/pm-linked-test-adapters/package.json +1 -1
  82. package/packages/pm-search-advanced/package.json +1 -1
  83. package/packages/pm-templates/package.json +1 -1
  84. package/packages/pm-todos/package.json +1 -1
  85. package/packages/pm-vcs/package.json +1 -1
  86. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  87. package/plugins/pm-claude/package.json +1 -1
  88. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  89. package/plugins/pm-codex/package.json +1 -1
  90. package/plugins/pm-codex/plugin.json +1 -1
  91. package/runtime-dependencies.json +1 -1
  92. package/dist/cli-bundle/chunks/chunk-OD2I3SFQ.js +0 -70
  93. package/dist/cli-bundle/chunks/item-transaction-E2ST3A3X.js +0 -2
@@ -0,0 +1,3 @@
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4b754f64-1bb8-54ef-a214-f1603b1711b8")}catch{}})();import{spawn}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import path from"node:path";const TEARDOWN_HELPER_TIMEOUT_MS=2e3;function descendantEntriesFromProcessTable(table,root){const children=new Map;for(const line of table.split(`
2
+ `)){const fields=line.trim().split(/\s+/u);if(fields.length!==2)continue;const[child,parent]=fields.map(Number);if(!Number.isSafeInteger(child)||!Number.isSafeInteger(parent)||child<=0)continue;const siblings=children.get(parent);siblings?siblings.push(child):children.set(parent,[child])}const seen=new Set([root]),descendants=[],pending=(children.get(root)??[]).map(pid=>({pid,parent:root}));for(let index=0;index<pending.length;index+=1){const next=pending[index];if(!seen.has(next.pid)){seen.add(next.pid),descendants.push(next);for(const grandchild of children.get(next.pid)??[])pending.push({pid:grandchild,parent:next.pid})}}return descendants.reverse()}function descendantsFromProcessTable(table,root){return descendantEntriesFromProcessTable(table,root).map(entry=>entry.pid)}function parentStillMatches(entry,readStat=readProcStat){const stat=readStat(`/proc/${entry.pid}/stat`);if(stat===void 0)return!existsSync("/proc/self/stat");const fields=stat.slice(stat.lastIndexOf(")")+1).trim().split(/\s+/u);return Number(fields[1])===entry.parent}function processTableSharesNamespace(readStatus=readProcStat,platform=process.platform){const status=readStatus("/proc/self/status");if(status===void 0)return platform!=="linux"&&!existsSync("/proc/self/status");const nspid=/^NSpid:\s*(.*)$/mu.exec(status)?.[1]?.trim().split(/\s+/u);return nspid?.length===1&&Number(nspid[0])===process.pid}function ancestryStillMatches(pid,root,parentOf,matches=parentStillMatches,verified=new Map){const chain=[];let outcome=!0;for(let current=pid;current!==root;){const known=verified.get(current);if(known!==void 0){outcome=known;break}chain.push(current);const parent=parentOf.get(current);if(parent===void 0||!matches({pid:current,parent})){outcome=!1;break}current=parent}for(const link of chain)verified.set(link,outcome);return outcome}function readProcStat(file){try{return readFileSync(file,"utf8")}catch{return}}const TRUSTED_PS_PATHS=["/bin/ps","/usr/bin/ps"],PS_ENV={PATH:"/usr/bin:/bin",LC_ALL:"C"};function resolveTrustedPs(exists=existsSync){return TRUSTED_PS_PATHS.find(file=>exists(file))}const DEFAULT_WINDOWS_ROOT="C:\\Windows";function resolveWindowsSystemRoot(env=process.env,exists=existsSync){const valueOf=name=>Object.entries(env).find(([key])=>key.toLowerCase()===name)?.[1];return[valueOf("systemroot"),valueOf("windir"),DEFAULT_WINDOWS_ROOT].find(candidate=>typeof candidate=="string"&&/^[A-Za-z]:[\\/]/u.test(candidate)&&exists(path.win32.join(candidate,"System32","taskkill.exe")))}function killProcess(pid){try{process.kill(pid,"SIGKILL")}catch{}}function runTeardownHelper(file,args,env,timeoutMs=TEARDOWN_HELPER_TIMEOUT_MS){return new Promise(resolve=>{let settled=!1,stdout="",helper;try{helper=spawn(file,args,{stdio:["ignore","pipe","ignore"],windowsHide:!0,...env===void 0?{}:{env}})}catch{resolve(void 0);return}const deadline=timeoutMs===null?void 0:setTimeout(()=>{settle(void 0),helper.stdout?.destroy(),helper.kill("SIGKILL"),helper.unref()},timeoutMs);function settle(result){settled||(settled=!0,clearTimeout(deadline),resolve(result))}if(helper.on("error",()=>settle(void 0)),!helper.stdout){settle(void 0);return}helper.stdout.setEncoding("utf8"),helper.stdout.on("data",chunk=>{stdout+=chunk}),helper.on("close",code=>settle({code,stdout}))})}async function killProcessTree(pid,root={kill:()=>killProcess(pid),alive:()=>!0},options={}){if(!(!Number.isInteger(pid)||pid<=0)){if(process.platform==="win32"){await killWindowsTree(pid,root,options.taskkillTimeoutMs===void 0?TEARDOWN_HELPER_TIMEOUT_MS:options.taskkillTimeoutMs);return}try{process.kill(-pid,"SIGKILL");return}catch{}await killPosixDescendants(pid,root),root.kill()}}async function killWindowsTree(pid,root,taskkillTimeoutMs){const systemRoot=resolveWindowsSystemRoot();if(systemRoot===void 0){root.alive()&&root.kill();return}const taskkill=path.win32.join(systemRoot,"System32","taskkill.exe");(await runTeardownHelper(taskkill,["/pid",String(pid),"/T","/F"],void 0,taskkillTimeoutMs))?.code!==0&&root.alive()&&root.kill()}async function killPosixDescendants(pid,root){const ps=resolveTrustedPs();if(ps===void 0||!processTableSharesNamespace())return;const table=await runTeardownHelper(ps,["-A","-o","pid=","-o","ppid="],PS_ENV);if(table?.code!==0||!root.alive())return;const descendants=descendantEntriesFromProcessTable(table.stdout,pid),parentOf=new Map(descendants.map(entry=>[entry.pid,entry.parent])),verified=new Map;for(const descendant of descendants)parentStillMatches(descendant)&&ancestryStillMatches(descendant.parent,pid,parentOf,parentStillMatches,verified)&&killProcess(descendant.pid)}export{ancestryStillMatches,descendantEntriesFromProcessTable,descendantsFromProcessTable,killProcessTree,parentStillMatches,processTableSharesNamespace,resolveTrustedPs,resolveWindowsSystemRoot,runTeardownHelper};
3
+ //# sourceMappingURL=process-tree.js.map
@@ -33,12 +33,23 @@ value:string;
33
33
  element?:true;
34
34
  /** Judge element content with the value grammar and entropy predicate instead of length alone. */
35
35
  elementValue?:true;}
36
+ /**
37
+ * What a detector protects: `credential` for secrets that grant access,
38
+ * `network` for private infrastructure addresses and `path` for local
39
+ * filesystem paths that reveal an account. A policy can decide a whole family
40
+ * at once, so a new rule inherits its category's decision (pm-gh1749). The set
41
+ * is part of the public SDK contract: a new rule joins an existing category,
42
+ * and a new category is a declared contract change.
43
+ */
44
+ export type SecretRuleCategory="credential"|"network"|"path";
36
45
  /** One detector and any explicit repository-only scope exception. */
37
46
  export interface SecretRule{
38
47
  /** Repository diagnostic identifier. */
39
48
  name:string;
40
49
  /** Compatible SDK diagnostic identifier. */
41
50
  mutationRule:string;
51
+ /** Stable family of the detector; see {@link SecretRuleCategory}. */
52
+ category:SecretRuleCategory;
42
53
  /** Global pattern; consumers reset lastIndex before each scan. */
43
54
  regex:RegExp;
44
55
  /** Repository paths with deliberate fixture exemptions. */
@@ -86,7 +97,7 @@ regex:RegExp;
86
97
  /** Structured value grammar (regular-expression source), as {@link SecretStructuredSpelling.value}. */
87
98
  value:string;}
88
99
  /** Canonical patterns; repository exemptions never exempt mutation payloads. */
89
- export declare const SECRET_RULES:readonly[{readonly name:"private-key";readonly mutationRule:"private_key";readonly regex:RegExp;},{readonly name:"github-token";readonly mutationRule:"github_token";readonly regex:RegExp;},{readonly name:"npm-token";readonly mutationRule:"npm_token";readonly regex:RegExp;},{readonly name:"aws-access-key";readonly mutationRule:"aws_access_key";readonly regex:RegExp;},{readonly name:"google-api-key";readonly mutationRule:"google_api_key";readonly regex:RegExp;},{readonly name:"slack-token";readonly mutationRule:"slack_token";readonly regex:RegExp;},{readonly name:"anthropic-api-key";readonly mutationRule:"anthropic_api_key";readonly regex:RegExp;},{readonly name:"openai-api-key";readonly mutationRule:"openai_api_key";readonly regex:RegExp;},{readonly name:"gitlab-token";readonly mutationRule:"gitlab_token";readonly regex:RegExp;},{readonly name:"jwt-like-token";readonly mutationRule:"jwt_like_token";readonly regex:RegExp;},{readonly name:"npm-auth-token-assignment";readonly mutationRule:"npm_auth_token_assignment";readonly regex:RegExp;},{readonly name:"sentry-user-token";readonly mutationRule:"sentry_user_token";readonly regex:RegExp;},{readonly name:"sentry-org-token";readonly mutationRule:"sentry_org_token";readonly regex:RegExp;},{readonly name:"private-ip";readonly mutationRule:"private_ip";readonly regex:RegExp;},{readonly name:"private-ssh-target";readonly mutationRule:"private_ssh_target";readonly regex:RegExp;},{readonly name:"sshpass-inline-password";readonly mutationRule:"sshpass_inline_password";readonly regex:RegExp;},{readonly name:"password-assignment";readonly mutationRule:"password_assignment";readonly regex:RegExp;readonly structured:{readonly keys:"password|passphrase";readonly value:string;readonly element:true;};readonly minimumLiteralLength:8;},{readonly name:"absolute-home-path";readonly mutationRule:"absolute_home_path";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"user-at-private-host";readonly mutationRule:"user_at_private_host";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"high-entropy-assignment";readonly mutationRule:"high_entropy_assignment";readonly regex:RegExp;readonly structured:{readonly keys:"token|secret|password|passwd|api[_-]?key";readonly value:string;};readonly mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.";readonly minimumEntropy:3.5;},{readonly name:"credential-key-assignment";readonly mutationRule:"credential_key_assignment";readonly regex:RegExp;readonly structured:{readonly keys:"(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))";readonly value:string;readonly element:true;readonly elementValue:true;};readonly mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.";readonly minimumEntropy:3;readonly minimumLiteralLength:8;readonly literalValue:RegExp;readonly baseline:{readonly regex:RegExp;readonly value:string;};readonly rejectValue:RegExp;readonly rejectStatementReference:RegExp;}];
100
+ export declare const SECRET_RULES:readonly[{readonly name:"private-key";readonly mutationRule:"private_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"github-token";readonly mutationRule:"github_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"npm-token";readonly mutationRule:"npm_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"aws-access-key";readonly mutationRule:"aws_access_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"google-api-key";readonly mutationRule:"google_api_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"slack-token";readonly mutationRule:"slack_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"anthropic-api-key";readonly mutationRule:"anthropic_api_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"openai-api-key";readonly mutationRule:"openai_api_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"gitlab-token";readonly mutationRule:"gitlab_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"jwt-like-token";readonly mutationRule:"jwt_like_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"npm-auth-token-assignment";readonly mutationRule:"npm_auth_token_assignment";readonly category:"credential";readonly regex:RegExp;},{readonly name:"sentry-user-token";readonly mutationRule:"sentry_user_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"sentry-org-token";readonly mutationRule:"sentry_org_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"private-ip";readonly mutationRule:"private_ip";readonly category:"network";readonly regex:RegExp;},{readonly name:"private-ssh-target";readonly mutationRule:"private_ssh_target";readonly category:"network";readonly regex:RegExp;},{readonly name:"sshpass-inline-password";readonly mutationRule:"sshpass_inline_password";readonly category:"credential";readonly regex:RegExp;},{readonly name:"password-assignment";readonly mutationRule:"password_assignment";readonly category:"credential";readonly regex:RegExp;readonly structured:{readonly keys:"password|passphrase";readonly value:string;readonly element:true;};readonly minimumLiteralLength:8;},{readonly name:"absolute-home-path";readonly mutationRule:"absolute_home_path";readonly category:"path";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"user-at-private-host";readonly mutationRule:"user_at_private_host";readonly category:"network";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"high-entropy-assignment";readonly mutationRule:"high_entropy_assignment";readonly category:"credential";readonly regex:RegExp;readonly structured:{readonly keys:"token|secret|password|passwd|api[_-]?key";readonly value:string;};readonly mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.";readonly minimumEntropy:3.5;},{readonly name:"credential-key-assignment";readonly mutationRule:"credential_key_assignment";readonly category:"credential";readonly regex:RegExp;readonly structured:{readonly keys:"(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))";readonly value:string;readonly element:true;readonly elementValue:true;};readonly mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.";readonly minimumEntropy:3;readonly minimumLiteralLength:8;readonly literalValue:RegExp;readonly baseline:{readonly regex:RegExp;readonly value:string;};readonly rejectValue:RegExp;readonly rejectStatementReference:RegExp;}];
90
101
  /** Share matching and normalization, returning locations rather than matched values. */
91
102
  export declare function findSecretRuleMatches(rule:SecretRule,content:string):Generator<SecretRuleMatch>;
92
103
  /**
@@ -1,5 +1,5 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b93aa43d-6c3e-5a34-9139-88000581c39f")}catch{}})();const COMPONENT=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,SEPARATOR="[/\\\\]+",ACCOUNT="[\\p{L}\\p{N}._@-]+",ACCOUNT_PATH=ACCOUNT+"(?:"+SEPARATOR+COMPONENT+")*",ROOT_HOME="(?:(?:home|users)"+SEPARATOR+ACCOUNT_PATH+"|root"+SEPARATOR+ACCOUNT_PATH+")",UNIX_HOME="[/\\\\]"+ROOT_HOME,MULTI_ROOT_HOME="[/\\\\]{2,}"+ROOT_HOME,WINDOWS_HOME="/?[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH,SHARE_COMPONENT=COMPONENT+"(?: +"+COMPONENT+")*",SHARED_PROFILE="(?:"+SHARE_COMPONENT+SEPARATOR+")?users"+SEPARATOR+ACCOUNT_PATH,UNC_HOME="[/\\\\]{2,}"+COMPONENT+SEPARATOR+SHARED_PROFILE,DEVICE_VOLUME="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+COMPONENT+")",DEVICE_HOME="[/\\\\]{2}[?.]"+SEPARATOR+"(?:unc"+SEPARATOR+COMPONENT+SEPARATOR+SHARED_PROFILE+"|"+DEVICE_VOLUME+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")",FILE_HOME="file:(?:"+DEVICE_HOME+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+SEPARATOR+")(?:"+ROOT_HOME+"|[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")|[/\\\\]{2}(?:[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+"|"+COMPONENT+SEPARATOR+"(?:"+ROOT_HOME+"|"+SHARED_PROFILE+")))",PRIVATE_HOME_PATH_PATTERN=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+UNIX_HOME+"|"+WINDOWS_HOME+"|"+FILE_HOME+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+MULTI_ROOT_HOME+"|"+UNC_HOME+"|"+DEVICE_HOME+")","giu"),MAX_NORMALIZATION_PASSES=4,REMAINING_ENCODING=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,utf8=new TextDecoder("utf-8");function percentView(value){return value.replace(/(?:%[a-f0-9]{2})+/giu,run=>utf8.decode(Uint8Array.from(run.matchAll(/%([a-f0-9]{2})/giu),match=>Number.parseInt(match[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function escapedView(value){return value.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(match,unicode,byte,slash)=>{const code=unicode??byte;return code===void 0?slash??match:String.fromCharCode(Number.parseInt(code,16))})}function unicodeView(value){return value.normalize("NFKC").replace(/[\p{Bidi_Control}\u200b-\u200f\u2060-\u206f\ufeff]/gu,"").replace(/[\u2215\u2044]/gu,"/").replace(/[\u043e\u041e]/gu,"o").replace(/[\u0455\u0405]/gu,"s")}function nextNormalizedView(view,steps){for(const[kind,transform]of[["percent_decode",percentView],["json_unescape",escapedView],["unicode_fold",unicodeView]]){const transformed=transform(view);transformed!==view&&!steps.includes(kind)&&steps.push(kind),view=transformed}return view}function*normalizedHomePathMatches(line,regex,detected){let view=line;const steps=[];for(let pass=0;pass<MAX_NORMALIZATION_PASSES;pass+=1){const previous=view;if(view=nextNormalizedView(view,steps),!detected){regex.lastIndex=0;for(const _match of view.matchAll(regex))detected=!0,yield{index:0,normalizations:[...steps]}}if(view===previous)break;pass===MAX_NORMALIZATION_PASSES-1&&REMAINING_ENCODING.test(view)&&(yield{index:0,normalizations:[...steps],normalization_incomplete:!0})}}function*findPrivateHomePathMatches(content,regex){let offset=0;for(const line of content.split(`
2
- `)){regex.lastIndex=0;let rawFound=!1;for(const match of line.matchAll(regex))rawFound=!0,yield{index:offset+match.index};for(const match of normalizedHomePathMatches(line,regex,rawFound))yield{...match,index:offset};offset+=line.length+1}}const PASSWORD_KEYS="password|passphrase",PASSWORD_QUOTED_PIECES=4,PASSWORD_REPEAT_BOUND=4096,maximalRun=characterClass=>`${characterClass}+(?!${characterClass})`,PASSWORD_QUOTED_SPAN=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${PASSWORD_REPEAT_BOUND}}"`,PASSWORD_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\()|\$\([^()\r\n]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`,PASSWORD_PIECE=String.raw`${PASSWORD_REFERENCE}|<[^<>\r\n]*>|${maximalRun(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,PASSWORD_QUOTED=String.raw`"[^"]*"|'[^']*'`,PASSWORD_QUOTED_PIECE=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${PASSWORD_PIECE}){0,${PASSWORD_REPEAT_BOUND}}`,PASSWORD_VALUE=new RegExp(String.raw`(?!config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))`+`((?:${PASSWORD_PIECE}){1,${PASSWORD_REPEAT_BOUND}}(?:${PASSWORD_QUOTED_PIECE}){0,${PASSWORD_QUOTED_PIECES}}|(?:${PASSWORD_QUOTED_PIECE}){1,${PASSWORD_QUOTED_PIECES}}|${PASSWORD_QUOTED})`),PASSWORD_MINIMUM_LITERAL_LENGTH=8,HIGH_ENTROPY_KEYS="token|secret|password|passwd|api[_-]?key",CREDENTIAL_KEYS="(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))",EXCLUSION_REPEAT_BOUND=4096,CREDENTIAL_OPEN=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,CREDENTIAL_PLAIN=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8}[^\s"]*|(?<=')[^\s']{8}[^\s']*|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,})`,CREDENTIAL_LITERAL_VALUE=new RegExp(`(?:${CREDENTIAL_OPEN})(${CREDENTIAL_PLAIN})`,"iy"),CREDENTIAL_MINIMUM_LITERAL_LENGTH=8,CREDENTIAL_RUN=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,CREDENTIAL_AMPERSAND=String.raw`&(?!&)`,CREDENTIAL_LEADING_LITERAL=64,CREDENTIAL_REFERENCE_SPAN=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${PASSWORD_REPEAT_BOUND}}"`,CREDENTIAL_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\{)|\$\{[^{}\s]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\()|\$\([^()\s]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,credentialPiece=run=>String.raw`${CREDENTIAL_REFERENCE}|${maximalRun(run)}|${CREDENTIAL_AMPERSAND}|\$(?![{(A-Za-z_])`,credentialQuotedPiece=run=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}`,credentialReferenced=run=>String.raw`(?:(?:${run}|${CREDENTIAL_AMPERSAND}){1,${CREDENTIAL_LEADING_LITERAL}}(?=[$<]))?(?:${CREDENTIAL_REFERENCE})`+String.raw`(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}(?:${credentialQuotedPiece(run)}){0,${PASSWORD_QUOTED_PIECES}}`,credentialConcatenated=run=>String.raw`(?:${credentialQuotedPiece(run)}){1,${PASSWORD_QUOTED_PIECES}}`,credentialUnquoted=build=>String.raw`(?<!["'])(?:${build(CREDENTIAL_RUN)})`,CREDENTIAL_CONCATENATION_CONTINUES=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,CREDENTIAL_CONCATENATION_OPEN=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${CREDENTIAL_CONCATENATION_CONTINUES}|'(?=[^'\s]*[$<])[^'\s]*'${CREDENTIAL_CONCATENATION_CONTINUES})`,CREDENTIAL_QUOTED_REFERENCED=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,CREDENTIAL_VALUE=new RegExp(`(?:${CREDENTIAL_CONCATENATION_OPEN}|${CREDENTIAL_OPEN})((?=["'])(?:${credentialUnquoted(credentialConcatenated)})|${CREDENTIAL_QUOTED_REFERENCED}|${credentialUnquoted(credentialReferenced)}|${CREDENTIAL_PLAIN})`),HIGH_ENTROPY_VALUE=/["']?([A-Za-z0-9+/=_-]{24,})/,SECRET_RULES=[{name:"private-key",mutationRule:"private_key",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",regex:/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g},{name:"npm-auth-token-assignment",mutationRule:"npm_auth_token_assignment",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",regex:/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"private-ssh-target",mutationRule:"private_ssh_target",regex:/\b(?:ssh|scp|rsync)\s+[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"sshpass-inline-password",mutationRule:"sshpass_inline_password",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",regex:new RegExp(String.raw`\b(?:${PASSWORD_KEYS})\s*[:=]\s*`+PASSWORD_VALUE.source,"gi"),structured:{keys:PASSWORD_KEYS,value:PASSWORD_VALUE.source,element:!0},minimumLiteralLength:PASSWORD_MINIMUM_LITERAL_LENGTH},{name:"absolute-home-path",mutationRule:"absolute_home_path",regex:PRIVATE_HOME_PATH_PATTERN,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",regex:/(?<![A-Za-z0-9._-])[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,excludeFiles:/^(?:tests\/|examples\/)/},{name:"high-entropy-assignment",mutationRule:"high_entropy_assignment",regex:new RegExp(String.raw`\b(?:${HIGH_ENTROPY_KEYS})\s*[:=]\s*`+HIGH_ENTROPY_VALUE.source,"gi"),structured:{keys:HIGH_ENTROPY_KEYS,value:HIGH_ENTROPY_VALUE.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5},{name:"credential-key-assignment",mutationRule:"credential_key_assignment",regex:new RegExp(String.raw`\b(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_VALUE.source,"gi"),structured:{keys:CREDENTIAL_KEYS,value:CREDENTIAL_VALUE.source,element:!0,elementValue:!0},mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.",minimumEntropy:3,minimumLiteralLength:CREDENTIAL_MINIMUM_LITERAL_LENGTH,literalValue:CREDENTIAL_LITERAL_VALUE,baseline:{regex:new RegExp(String.raw`\b(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_LITERAL_VALUE.source,"gi"),value:CREDENTIAL_LITERAL_VALUE.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*findSecretRuleMatches(rule,content){if(rule.mutationRule==="absolute_home_path"){yield*findPrivateHomePathMatches(content,rule.regex);return}for(const reading of ruleReadings(rule))yield*flatMatches(reading,content),reading.structured&&(yield*findStructuredSpellingMatches(reading,reading.structured,content))}const baselineRules=new WeakMap;function ruleReadings(rule){const baseline=rule.baseline;if(baseline===void 0)return[rule];let judged=baselineRules.get(rule);return judged===void 0&&(judged={...rule,regex:baseline.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},rule.structured&&(judged.structured={...rule.structured,value:baseline.value}),baselineRules.set(rule,judged)),[rule,judged]}function isParameterName(content,index){const name=content[index-1]==="#"||content[index-1]==="!"?index-1:index;return content[name-1]==="{"&&content[name-2]==="$"}const INNER_SHELL_MATCHES=new WeakSet,INNER_CLOSE_AT=new WeakMap,CUT_REFERENCE_BOUND=4096;function referenceSpans(content,offset,text){const spans=[],open=[],end=offset+text.length;return walkReferences(content,offset,end,open,spans),walkReferences(content,end,Math.min(content.length,end+CUT_REFERENCE_BOUND),open),spans}function walkReferences(content,start,end,open,spans){for(let index=start;index<end&&(spans!==void 0||open.length>0);index+=1){const frame=open.at(-1);if(content[index]==="$"&&(content[index+1]==="{"||content[index+1]==="(")&&frame?.quoted!=="'"){const span={open:index,close:end,command:content[index+1]==="(",quoted:[]};spans?.push(span),open.push({span,closer:content[index+1]==="{"?"}":")"}),index+=1}else frame!==void 0&&(index=referenceStep(content,index,open))}}function referenceStep(text,index,open){const frame=open.at(-1),character=text[index];return character==="\\"&&frame.quoted!=="'"?index+1:(frame.quoted!==void 0?character===frame.quoted&&(frame.span.quoted.push([frame.quoteStart,index]),frame.quoted=void 0):character==="'"||character==='"'?(frame.quoted=character,frame.quoteStart=index):character===frame.closer&&(open.pop().span.close=index),index)}function enclosingCloser(spans){const active=[];let next=0;return position=>{for(;next<spans.length&&spans[next].open<position;next+=1){for(;active.length>0&&active.at(-1).close<spans[next].open;)active.pop();active.push(spans[next])}for(;active.length>0&&active.at(-1).close<position;)active.pop();return active.at(-1)}}function insideQuotedRange(span,position){let low=0,high=span.quoted.length-1;for(;low<=high;){const middle=low+high>>1,[start,end]=span.quoted[middle];if(position<start)high=middle-1;else if(position>end)low=middle+1;else return!0}return!1}const VALUE_REFERENCE=/\$[({A-Za-z_]|</u;function*flatMatches(rule,content){const regex=rule.regex;regex.lastIndex=0;const rescan=rescanDepth(rule);let inner;for(const match of content.matchAll(regex))acceptsSecretMatch(rule,match)?yield{index:match.index}:rescan!==void 0&&VALUE_REFERENCE.test(match[1])&&(inner??=new RegExp(regex),yield*keysInsideRejectedValue(rule,inner,content,match,rescan==="deep"))}function rescanDepth(rule){return rule.minimumLiteralLength===void 0?void 0:rule.minimumEntropy===void 0&&rule.literalValue===void 0&&rule.rejectValue===void 0?"deep":"shallow"}function*keysInsideRejectedValue(rule,inner,content,match,deep){const end=match.index+match[0].length;inner.lastIndex=end-match[1].length;let closerAt;for(let found=inner.exec(content);found!==null&&found.index<end;found=inner.exec(content)){if(isParameterName(content,found.index)){inner.lastIndex=found.index+1;continue}closerAt??=enclosingCloser(referenceSpans(content,end-match[1].length,match[1]));const span=closerAt(found.index);span!==void 0&&(INNER_CLOSE_AT.set(found,span.close),span.command&&!insideQuotedRange(span,found.index)&&INNER_SHELL_MATCHES.add(found)),acceptsSecretMatch(rule,found)?yield{index:found.index}:deep&&VALUE_REFERENCE.test(found[1])&&(inner.lastIndex=found.index+found[0].length-found[1].length)}}const compiledSpellings=new Map,LINE_BREAK=/[\r\n\u2028\u2029]/u;function compileSpelling(spelling){const cacheKey=`${spelling.keys}\0${spelling.value}\0${spelling.element===!0}`;let compiled=compiledSpellings.get(cacheKey);return compiled||(compiled={key:new RegExp(String.raw`\b(?:${spelling.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(spelling.value,"iyd"),...spelling.element?{element:{open:new RegExp(String.raw`<(?:${spelling.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${spelling.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${spelling.keys})\b)[^<>]*>`,"iy")}}:{}},compiledSpellings.set(cacheKey,compiled)),compiled}function scanQuoted(content,start){const quote=content[start];for(let index=start+1;index<content.length;index+=1){const character=content[index];if(character==="\\")index+=1;else if(character===quote)return{end:index+1,terminated:!0}}return{end:content.length,terminated:!1}}function endOfQuoted(content,start){return scanQuoted(content,start).end}function judgeFor(closers,accepts,acceptsMember){return closers.at(-1)==="}"?acceptsMember:accepts}function walkContainer(content,start,accepts,acceptsMember=accepts){const closers=[];let expectKey=!1;for(let index=start;index<content.length;index+=1){const character=content[index];switch(character){case"[":case"{":closers.push(character==="["?"]":"}"),expectKey=character==="{";break;case"]":case"}":if(closers.pop()!==character||closers.length===0)return{found:!1,end:index+1};expectKey=!1;break;case",":expectKey=closers.at(-1)==="}";break;case":":expectKey=!1;break;case'"':case"'":if(!expectKey&&judgeFor(closers,accepts,acceptsMember)(index))return{found:!0,end:index};index=endOfQuoted(content,index)-1;break;default:break}}return{found:!1,end:content.length}}const ESCAPE_SEQUENCE=/\\(?:U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|[\s\S])/gu,SIMPLE_ESCAPES={n:`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a5619fc7-2547-59c9-bfff-4d4cebd14967")}catch{}})();const COMPONENT=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,SEPARATOR="[/\\\\]+",ACCOUNT="[\\p{L}\\p{N}._@-]+",ACCOUNT_PATH=ACCOUNT+"(?:"+SEPARATOR+COMPONENT+")*",ROOT_HOME="(?:(?:home|users)"+SEPARATOR+ACCOUNT_PATH+"|root"+SEPARATOR+ACCOUNT_PATH+")",UNIX_HOME="[/\\\\]"+ROOT_HOME,MULTI_ROOT_HOME="[/\\\\]{2,}"+ROOT_HOME,WINDOWS_HOME="/?[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH,SHARE_COMPONENT=COMPONENT+"(?: +"+COMPONENT+")*",SHARED_PROFILE="(?:"+SHARE_COMPONENT+SEPARATOR+")?users"+SEPARATOR+ACCOUNT_PATH,UNC_HOME="[/\\\\]{2,}"+COMPONENT+SEPARATOR+SHARED_PROFILE,DEVICE_VOLUME="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+COMPONENT+")",DEVICE_HOME="[/\\\\]{2}[?.]"+SEPARATOR+"(?:unc"+SEPARATOR+COMPONENT+SEPARATOR+SHARED_PROFILE+"|"+DEVICE_VOLUME+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")",FILE_HOME="file:(?:"+DEVICE_HOME+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+SEPARATOR+")(?:"+ROOT_HOME+"|[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")|[/\\\\]{2}(?:[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+"|"+COMPONENT+SEPARATOR+"(?:"+ROOT_HOME+"|"+SHARED_PROFILE+")))",PRIVATE_HOME_PATH_PATTERN=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+UNIX_HOME+"|"+WINDOWS_HOME+"|"+FILE_HOME+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+MULTI_ROOT_HOME+"|"+UNC_HOME+"|"+DEVICE_HOME+")","giu"),MAX_NORMALIZATION_PASSES=4,REMAINING_ENCODING=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,utf8=new TextDecoder("utf-8");function percentView(value){return value.replace(/(?:%[a-f0-9]{2})+/giu,run=>utf8.decode(Uint8Array.from(run.matchAll(/%([a-f0-9]{2})/giu),match=>Number.parseInt(match[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function escapedView(value){return value.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(match,unicode,byte,slash)=>{const code=unicode??byte;return code===void 0?slash??match:String.fromCharCode(Number.parseInt(code,16))})}function unicodeView(value){return value.normalize("NFKC").replace(/[\p{Bidi_Control}\u200b-\u200f\u2060-\u206f\ufeff]/gu,"").replace(/[\u2215\u2044]/gu,"/").replace(/[\u043e\u041e]/gu,"o").replace(/[\u0455\u0405]/gu,"s")}function nextNormalizedView(view,steps){for(const[kind,transform]of[["percent_decode",percentView],["json_unescape",escapedView],["unicode_fold",unicodeView]]){const transformed=transform(view);transformed!==view&&!steps.includes(kind)&&steps.push(kind),view=transformed}return view}function*normalizedHomePathMatches(line,regex,detected){let view=line;const steps=[];for(let pass=0;pass<MAX_NORMALIZATION_PASSES;pass+=1){const previous=view;if(view=nextNormalizedView(view,steps),!detected){regex.lastIndex=0;for(const _match of view.matchAll(regex))detected=!0,yield{index:0,normalizations:[...steps]}}if(view===previous)break;pass===MAX_NORMALIZATION_PASSES-1&&REMAINING_ENCODING.test(view)&&(yield{index:0,normalizations:[...steps],normalization_incomplete:!0})}}function*findPrivateHomePathMatches(content,regex){let offset=0;for(const line of content.split(`
2
+ `)){regex.lastIndex=0;let rawFound=!1;for(const match of line.matchAll(regex))rawFound=!0,yield{index:offset+match.index};for(const match of normalizedHomePathMatches(line,regex,rawFound))yield{...match,index:offset};offset+=line.length+1}}const PASSWORD_KEYS="password|passphrase",PASSWORD_QUOTED_PIECES=4,PASSWORD_REPEAT_BOUND=4096,maximalRun=characterClass=>`${characterClass}+(?!${characterClass})`,PASSWORD_QUOTED_SPAN=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${PASSWORD_REPEAT_BOUND}}"`,PASSWORD_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\()|\$\([^()\r\n]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`,PASSWORD_PIECE=String.raw`${PASSWORD_REFERENCE}|<[^<>\r\n]*>|${maximalRun(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,PASSWORD_QUOTED=String.raw`"[^"]*"|'[^']*'`,PASSWORD_QUOTED_PIECE=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${PASSWORD_PIECE}){0,${PASSWORD_REPEAT_BOUND}}`,PASSWORD_VALUE=new RegExp(String.raw`(?!config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))`+`((?:${PASSWORD_PIECE}){1,${PASSWORD_REPEAT_BOUND}}(?:${PASSWORD_QUOTED_PIECE}){0,${PASSWORD_QUOTED_PIECES}}|(?:${PASSWORD_QUOTED_PIECE}){1,${PASSWORD_QUOTED_PIECES}}|${PASSWORD_QUOTED})`),PASSWORD_MINIMUM_LITERAL_LENGTH=8,HIGH_ENTROPY_KEYS="token|secret|password|passwd|api[_-]?key",CREDENTIAL_KEYS="(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))",EXCLUSION_REPEAT_BOUND=4096,CREDENTIAL_OPEN=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,CREDENTIAL_PLAIN=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8}[^\s"]*|(?<=')[^\s']{8}[^\s']*|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,})`,CREDENTIAL_LITERAL_VALUE=new RegExp(`(?:${CREDENTIAL_OPEN})(${CREDENTIAL_PLAIN})`,"iy"),CREDENTIAL_MINIMUM_LITERAL_LENGTH=8,CREDENTIAL_RUN=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,CREDENTIAL_AMPERSAND=String.raw`&(?!&)`,CREDENTIAL_LEADING_LITERAL=64,CREDENTIAL_REFERENCE_SPAN=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${PASSWORD_REPEAT_BOUND}}"`,CREDENTIAL_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\{)|\$\{[^{}\s]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\()|\$\([^()\s]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,credentialPiece=run=>String.raw`${CREDENTIAL_REFERENCE}|${maximalRun(run)}|${CREDENTIAL_AMPERSAND}|\$(?![{(A-Za-z_])`,credentialQuotedPiece=run=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}`,credentialReferenced=run=>String.raw`(?:(?:${run}|${CREDENTIAL_AMPERSAND}){1,${CREDENTIAL_LEADING_LITERAL}}(?=[$<]))?(?:${CREDENTIAL_REFERENCE})`+String.raw`(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}(?:${credentialQuotedPiece(run)}){0,${PASSWORD_QUOTED_PIECES}}`,credentialConcatenated=run=>String.raw`(?:${credentialQuotedPiece(run)}){1,${PASSWORD_QUOTED_PIECES}}`,credentialUnquoted=build=>String.raw`(?<!["'])(?:${build(CREDENTIAL_RUN)})`,CREDENTIAL_CONCATENATION_CONTINUES=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,CREDENTIAL_CONCATENATION_OPEN=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${CREDENTIAL_CONCATENATION_CONTINUES}|'(?=[^'\s]*[$<])[^'\s]*'${CREDENTIAL_CONCATENATION_CONTINUES})`,CREDENTIAL_QUOTED_REFERENCED=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,CREDENTIAL_VALUE=new RegExp(`(?:${CREDENTIAL_CONCATENATION_OPEN}|${CREDENTIAL_OPEN})((?=["'])(?:${credentialUnquoted(credentialConcatenated)})|${CREDENTIAL_QUOTED_REFERENCED}|${credentialUnquoted(credentialReferenced)}|${CREDENTIAL_PLAIN})`),HIGH_ENTROPY_VALUE=/["']?([A-Za-z0-9+/=_-]{24,})/,SECRET_RULES=[{name:"private-key",mutationRule:"private_key",category:"credential",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",category:"credential",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",category:"credential",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",category:"credential",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",category:"credential",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",category:"credential",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",category:"credential",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",category:"credential",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",category:"credential",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",category:"credential",regex:/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g},{name:"npm-auth-token-assignment",mutationRule:"npm_auth_token_assignment",category:"credential",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",category:"credential",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",category:"credential",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",category:"network",regex:/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"private-ssh-target",mutationRule:"private_ssh_target",category:"network",regex:/\b(?:ssh|scp|rsync)\s+[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"sshpass-inline-password",mutationRule:"sshpass_inline_password",category:"credential",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${PASSWORD_KEYS})\s*[:=]\s*`+PASSWORD_VALUE.source,"gi"),structured:{keys:PASSWORD_KEYS,value:PASSWORD_VALUE.source,element:!0},minimumLiteralLength:PASSWORD_MINIMUM_LITERAL_LENGTH},{name:"absolute-home-path",mutationRule:"absolute_home_path",category:"path",regex:PRIVATE_HOME_PATH_PATTERN,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",category:"network",regex:/(?<![A-Za-z0-9._-])[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,excludeFiles:/^(?:tests\/|examples\/)/},{name:"high-entropy-assignment",mutationRule:"high_entropy_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${HIGH_ENTROPY_KEYS})\s*[:=]\s*`+HIGH_ENTROPY_VALUE.source,"gi"),structured:{keys:HIGH_ENTROPY_KEYS,value:HIGH_ENTROPY_VALUE.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5},{name:"credential-key-assignment",mutationRule:"credential_key_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_VALUE.source,"gi"),structured:{keys:CREDENTIAL_KEYS,value:CREDENTIAL_VALUE.source,element:!0,elementValue:!0},mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.",minimumEntropy:3,minimumLiteralLength:CREDENTIAL_MINIMUM_LITERAL_LENGTH,literalValue:CREDENTIAL_LITERAL_VALUE,baseline:{regex:new RegExp(String.raw`\b(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_LITERAL_VALUE.source,"gi"),value:CREDENTIAL_LITERAL_VALUE.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*findSecretRuleMatches(rule,content){if(rule.mutationRule==="absolute_home_path"){yield*findPrivateHomePathMatches(content,rule.regex);return}for(const reading of ruleReadings(rule))yield*flatMatches(reading,content),reading.structured&&(yield*findStructuredSpellingMatches(reading,reading.structured,content))}const baselineRules=new WeakMap;function ruleReadings(rule){const baseline=rule.baseline;if(baseline===void 0)return[rule];let judged=baselineRules.get(rule);return judged===void 0&&(judged={...rule,regex:baseline.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},rule.structured&&(judged.structured={...rule.structured,value:baseline.value}),baselineRules.set(rule,judged)),[rule,judged]}function isParameterName(content,index){const name=content[index-1]==="#"||content[index-1]==="!"?index-1:index;return content[name-1]==="{"&&content[name-2]==="$"}const INNER_SHELL_MATCHES=new WeakSet,INNER_CLOSE_AT=new WeakMap,CUT_REFERENCE_BOUND=4096;function referenceSpans(content,offset,text){const spans=[],open=[],end=offset+text.length;return walkReferences(content,offset,end,open,spans),walkReferences(content,end,Math.min(content.length,end+CUT_REFERENCE_BOUND),open),spans}function walkReferences(content,start,end,open,spans){for(let index=start;index<end&&(spans!==void 0||open.length>0);index+=1){const frame=open.at(-1);if(content[index]==="$"&&(content[index+1]==="{"||content[index+1]==="(")&&frame?.quoted!=="'"){const span={open:index,close:end,command:content[index+1]==="(",quoted:[]};spans?.push(span),open.push({span,closer:content[index+1]==="{"?"}":")"}),index+=1}else frame!==void 0&&(index=referenceStep(content,index,open))}}function referenceStep(text,index,open){const frame=open.at(-1),character=text[index];return character==="\\"&&frame.quoted!=="'"?index+1:(frame.quoted!==void 0?character===frame.quoted&&(frame.span.quoted.push([frame.quoteStart,index]),frame.quoted=void 0):character==="'"||character==='"'?(frame.quoted=character,frame.quoteStart=index):character===frame.closer&&(open.pop().span.close=index),index)}function enclosingCloser(spans){const active=[];let next=0;return position=>{for(;next<spans.length&&spans[next].open<position;next+=1){for(;active.length>0&&active.at(-1).close<spans[next].open;)active.pop();active.push(spans[next])}for(;active.length>0&&active.at(-1).close<position;)active.pop();return active.at(-1)}}function insideQuotedRange(span,position){let low=0,high=span.quoted.length-1;for(;low<=high;){const middle=low+high>>1,[start,end]=span.quoted[middle];if(position<start)high=middle-1;else if(position>end)low=middle+1;else return!0}return!1}const VALUE_REFERENCE=/\$[({A-Za-z_]|</u;function*flatMatches(rule,content){const regex=rule.regex;regex.lastIndex=0;const rescan=rescanDepth(rule);let inner;for(const match of content.matchAll(regex))acceptsSecretMatch(rule,match)?yield{index:match.index}:rescan!==void 0&&VALUE_REFERENCE.test(match[1])&&(inner??=new RegExp(regex),yield*keysInsideRejectedValue(rule,inner,content,match,rescan==="deep"))}function rescanDepth(rule){return rule.minimumLiteralLength===void 0?void 0:rule.minimumEntropy===void 0&&rule.literalValue===void 0&&rule.rejectValue===void 0?"deep":"shallow"}function*keysInsideRejectedValue(rule,inner,content,match,deep){const end=match.index+match[0].length;inner.lastIndex=end-match[1].length;let closerAt;for(let found=inner.exec(content);found!==null&&found.index<end;found=inner.exec(content)){if(isParameterName(content,found.index)){inner.lastIndex=found.index+1;continue}closerAt??=enclosingCloser(referenceSpans(content,end-match[1].length,match[1]));const span=closerAt(found.index);span!==void 0&&(INNER_CLOSE_AT.set(found,span.close),span.command&&!insideQuotedRange(span,found.index)&&INNER_SHELL_MATCHES.add(found)),acceptsSecretMatch(rule,found)?yield{index:found.index}:deep&&VALUE_REFERENCE.test(found[1])&&(inner.lastIndex=found.index+found[0].length-found[1].length)}}const compiledSpellings=new Map,LINE_BREAK=/[\r\n\u2028\u2029]/u;function compileSpelling(spelling){const cacheKey=`${spelling.keys}\0${spelling.value}\0${spelling.element===!0}`;let compiled=compiledSpellings.get(cacheKey);return compiled||(compiled={key:new RegExp(String.raw`\b(?:${spelling.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(spelling.value,"iyd"),...spelling.element?{element:{open:new RegExp(String.raw`<(?:${spelling.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${spelling.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${spelling.keys})\b)[^<>]*>`,"iy")}}:{}},compiledSpellings.set(cacheKey,compiled)),compiled}function scanQuoted(content,start){const quote=content[start];for(let index=start+1;index<content.length;index+=1){const character=content[index];if(character==="\\")index+=1;else if(character===quote)return{end:index+1,terminated:!0}}return{end:content.length,terminated:!1}}function endOfQuoted(content,start){return scanQuoted(content,start).end}function judgeFor(closers,accepts,acceptsMember){return closers.at(-1)==="}"?acceptsMember:accepts}function walkContainer(content,start,accepts,acceptsMember=accepts){const closers=[];let expectKey=!1;for(let index=start;index<content.length;index+=1){const character=content[index];switch(character){case"[":case"{":closers.push(character==="["?"]":"}"),expectKey=character==="{";break;case"]":case"}":if(closers.pop()!==character||closers.length===0)return{found:!1,end:index+1};expectKey=!1;break;case",":expectKey=closers.at(-1)==="}";break;case":":expectKey=!1;break;case'"':case"'":if(!expectKey&&judgeFor(closers,accepts,acceptsMember)(index))return{found:!0,end:index};index=endOfQuoted(content,index)-1;break;default:break}}return{found:!1,end:content.length}}const ESCAPE_SEQUENCE=/\\(?:U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|[\s\S])/gu,SIMPLE_ESCAPES={n:`
3
3
  `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function decodeQuotedLiteral(literal,terminated){const quote=literal[0],body=literal.slice(1,terminated?-1:void 0).replaceAll(ESCAPE_SEQUENCE,sequence=>{const kind=sequence[1];if((kind==="u"||kind==="x")&&sequence.length>2)return String.fromCharCode(Number.parseInt(sequence.slice(2),16));if(/^[0-7]$/u.test(kind))return String.fromCharCode(Number.parseInt(sequence.slice(1),8));if(kind==="U"&&sequence.length===10){const codePoint=Number.parseInt(sequence.slice(2),16);return codePoint<=1114111?String.fromCodePoint(codePoint):"\uFFFD"}return SIMPLE_ESCAPES[kind]??kind}),neutral=body.replaceAll(quote,quote==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," "),close=terminated?quote:"";return{reading:`${quote}${neutral}${close}`,...literalBody(`${quote}${body}${close}`,terminated)}}function literalBody(original,terminated){return{original,bodyStart:1,bodyEnd:original.length-(terminated?1:0)}}const MAX_KEY_PREFIX=64;function keyShape(content,index,quote){const previous=content[index-1];if(!quote)return previous!==void 0&&/[\p{L}\p{N}_.-]/u.test(previous)?"prefixed":"exact";if(previous===quote)return"exact";const floor=Math.max(0,index-MAX_KEY_PREFIX);for(let cursor=index-1;cursor>=floor;cursor-=1){const character=content[cursor];if(character===quote)return"prefixed";if(character===`
4
4
  `||character==="\r"||character==='"'||character==="'")return"malformed"}return"malformed"}function createValueJudge(rule,value,content,alwaysDecode=!1){const valueMatch=(text,at,decoded)=>{value.lastIndex=at;const match=value.exec(text);if(match===null||LINE_BREAK.test(match[0]))return null;const span=match.indices?.[1];return decoded!==void 0&&span!==void 0&&(match[1]=decoded.original.slice(Math.max(span[0],decoded.bodyStart),Math.min(span[1],decoded.bodyEnd)),DECODED_DATA_MATCHES.add(match)),acceptsSecretMatch(rule,match)?match:null},escapedMatches=at=>{if(content[at]!=='"'&&content[at]!=="'")return;const{end,terminated}=scanQuoted(content,at),literal=content.slice(at,end);if(!alwaysDecode&&!literal.includes("\\"))return;if(LINE_BREAK.test(literal))return[];const decoded=decodeQuotedLiteral(literal,terminated);return(content[at]==="'"?[decoded,{reading:literal,...literalBody(literal,terminated)}]:[decoded]).map(reading=>valueMatch(reading.reading,0,reading)).filter(match=>match!==null)},valuesAt=at=>{const escaped=escapedMatches(at);if(escaped!==void 0)return escaped;const match=valueMatch(content,at);return match===null?[]:[match]};return{direct:at=>valueMatch(content,at)!==null,escaped:at=>(escapedMatches(at)?.length??0)>0,accepts:compact=>at=>valuesAt(at).some(match=>!(compact&&/\s/u.test(compactReading(rule,match))))}}function compactReading(rule,match){return rule.minimumLiteralLength===void 0?match[0]:judgedLiteral(match)}const DECODED_DATA_MATCHES=new WeakSet;function judgedLiteral(match){const word=INNER_SHELL_MATCHES.has(match)&&!isQuote(captureOpener(match))?shellWordPrefix(match[1]):void 0,text=word??match[1],variables=word!==void 0||wordComplete(match);return DECODED_DATA_MATCHES.has(match)||isQuote(captureOpener(match))?expandRuntimeReferences(text,variables):literalAfterReferences(text,variables)}function shellWordPrefix(text){for(let index=0;index<text.length;index+=1){const character=text[index];if(character==="'"||character==='"')index=quotedSpanEnd(text,index);else if(character==="$"&&(text[index+1]==="{"||text[index+1]==="("))index=Math.max(index,referenceEnd(text,index)-1);else if(/[|&;<>]/u.test(character))return text.slice(0,index)}}const STRUCTURE_RUN=/^[;,)}\]]{0,64}/u;function wordComplete(match){const input=match.input,end=match.index+match[0].length,closed=isQuote(captureOpener(match))&&isQuote(input[end])?end+1:isQuote(match[0].at(-1))?end:-1,start=closed===-1?end:closed,structure=STRUCTURE_RUN.exec(input.slice(start,start+WORD_END_BOUND))[0].length,after=start+structure;if(after===input.length||/\s/u.test(input[after])||INNER_CLOSE_AT.get(match)===start||INNER_SHELL_MATCHES.has(match)&&/[|&;<>]/u.test(input[start]))return!0;if(closed===-1||structure===0)return!1;const context=structuredContext(match,closed===end+1),next=input.slice(after,after+40),closedContainer=/[}\]]/u.test(input.slice(start,after));return context!==void 0&&(NEXT_MEMBER.test(next)||(context==="element"||closedContainer)&&BARE_SCALAR_MEMBER.test(next))}function structuredContext(match,openerOutsideCapture){const input=match.input,valueStart=match.index+match[0].length-match[1].length-(openerOutsideCapture?1:0),before=input.slice(Math.max(0,valueStart-STRUCTURED_LOOK_BACK),valueStart);return ARRAY_ELEMENT_BEFORE.test(before)?"element":QUOTED_KEY_BEFORE.test(before)?"key":void 0}const STRUCTURED_LOOK_BACK=512,QUOTED_KEY_BEFORE=/[{,]\s*(["'])[^"'\r\n]{1,256}\1\s*[:=]\s*$/u,ARRAY_ELEMENT_BEFORE=/[[,]\s*$/u,NEXT_MEMBER=/^(?:["'`]|[{[](?:[\s"'`{[\]}]|$|(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]))/u,BARE_SCALAR_MEMBER=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]/u,WORD_END_BOUND=64,CALL_AFTER=/^\s{0,16}\(/u,ASSIGNED_BEFORE=/(?<![=!<>])=[ \t]{0,16}$/u;function captureOpener(match){return match.input[match.index+match[0].length-match[1].length-1]}function isQuote(character){return character==='"'||character==="'"}const SPELLING_SENSITIVE=/[$<"']/u;function isCodeAfterReference(match){if(DECODED_DATA_MATCHES.has(match)||isQuote(captureOpener(match))||!/^[$<]/u.test(match[1]))return!1;const end=match.index+match[0].length,valueStart=end-match[1].length,after=match.input.slice(end,end+18);if(match[1][0]==="<"&&(isTypeAssertion(match[1])||ASSIGNED_BEFORE.test(match.input.slice(Math.max(0,valueStart-18),valueStart))||EXPRESSION_AFTER.test(after)))return!0;const lead=leadingReferencesEnd(match[1]),operator=match[1][lead]==="!"?match[1][lead+1]:match[1][lead];return CODE_OPERATOR.test(operator??"")||CALL_AFTER.test(after)}function leadingReferencesEnd(text){let index=0;for(let next=referenceEnd(text,index);next!==-1;next=referenceEnd(text,index))index=next;return index}function referenceEnd(text,start){const opener=text[start];if(opener==="<")return angleSpanEnd(text,start);if(opener!=="$")return-1;const bracket=text[start+1];if(bracket==="{"||bracket==="(")return bracketedEnd(text,start+1,bracket);VARIABLE_REFERENCE.lastIndex=start;const variable=VARIABLE_REFERENCE.exec(text)?.[0];return variable===void 0?-1:start+variable.length}function angleSpanEnd(text,start){const close=text.indexOf(">",start+1),reopen=text.indexOf("<",start+1);return close!==-1&&(reopen===-1||close<reopen)?close+1:-1}function bracketedEnd(text,start,bracket){const closer=bracket==="{"?"}":")";let depth=0;for(let index=start;index<text.length;index+=1){const character=text[index];if(character==="\\")index+=1;else if(character==="'"||character==='"')index=quotedSpanEnd(text,index);else if(character===bracket)depth+=1;else if(character===closer&&--depth===0)return index+1}return-1}function quotedSpanEnd(text,start){const quote=text[start];for(let index=start+1;index<text.length;index+=1){if(text[index]===quote)return index;quote==='"'&&text[index]==="\\"&&(index+=1)}return text.length}const TYPE_TEXT=/^[\w$.[\]|&,{}:;?]+$/u,LITERAL_TYPE=/^(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?)(?:\|(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?|[A-Za-z_$][\w$.]*))*$/u,PRIMITIVE_TYPE=/\b(?:string|number|boolean|bigint|symbol|any|unknown|object|never|void|undefined|null)\b/u;function isTypeAssertion(value){const type=value.slice(1,value.indexOf(">"));return LITERAL_TYPE.test(type)?!0:TYPE_TEXT.test(type)?PRIMITIVE_TYPE.test(type)||/[.|&[{]/u.test(type)||/^[A-Z][\w$]*$/u.test(type)&&(type.length===1||/[a-z]/u.test(type)):!1}const CODE_OPERATOR=/[.+\-*/%=^&]/u,EXPRESSION_AFTER=/^\s{0,16}(?:\?\.|\?\?|\|\||&&|[([])/u;function literalMatches(grammar,literal,code){if(code)return!1;const body=literal.replaceAll('"',"'");return grammar.lastIndex=0,grammar.exec(`"${body}"`)?.[1]===body}function structuredKeyShape(rule,name){if(!rule.structured)return;const content=`${JSON.stringify(name)}:`,key=compileSpelling(rule.structured).key;key.lastIndex=0;for(let match=key.exec(content);match;match=key.exec(content)){if(match.index+match[0].length!==content.length)continue;const shape=keyShape(content,match.index,match[1]);if(shape!=="malformed")return shape}}function acceptsStructuredValue(rule,value,compact){if(!rule.structured)return!1;const content=JSON.stringify(value).replaceAll("\u2028","\\u2028").replaceAll("\u2029","\\u2029");return ruleReadings(rule).some(reading=>createValueJudge(reading,compileSpelling(reading.structured).value,content,!0).accepts(compact)(0))}function*elementMatches(element,content,judge){const open=new RegExp(element.open);for(let match=open.exec(content);match;match=open.exec(content)){const bodyStart=match.index+match[0].length,body=elementBodyEnd(element,content,bodyStart);if(body===void 0){open.lastIndex=match.index+1;continue}judge(content.slice(bodyStart,body.start).trim())&&(yield{index:match.index}),open.lastIndex=body.end}}function elementBodyEnd(element,content,start){for(let index=content.indexOf("<",start);index!==-1;){element.close.lastIndex=index;const close=element.close.exec(content);if(close!==null)return{start:index,end:index+close[0].length};element.span.lastIndex=index;const span=element.span.exec(content);if(span===null)return;index=content.indexOf("<",index+span[0].length)}}function alreadyWalked(walkedEnd,valueStart,compact){return valueStart<walkedEnd.exact||compact&&valueStart<walkedEnd.compact}function scalarFinds(judge,accepts,quote,valueStart){return(quote||judge.escaped(valueStart)&&!judge.direct(valueStart))&&accepts(valueStart)}function*findStructuredSpellingMatches(rule,spelling,content){const compiled=compileSpelling(spelling),judge=createValueJudge(rule,compiled.value,content),key=new RegExp(compiled.key),walkedEnd={exact:0,compact:0};for(let match=key.exec(content);match;match=key.exec(content)){const quote=match[1],shape=keyShape(content,match.index,quote);if(shape==="malformed")continue;const compact=shape==="prefixed",accepts=judge.accepts(compact),valueStart=match.index+match[0].length,opener=content[valueStart];if(opener==="["||opener==="{"){if(alreadyWalked(walkedEnd,valueStart,compact))continue;const walked=walkContainer(content,valueStart,accepts,judge.accepts(!0));walkedEnd[compact?"compact":"exact"]=walked.end,walked.found&&(yield{index:match.index})}else scalarFinds(judge,accepts,quote,valueStart)&&(yield{index:match.index})}compiled.element&&(yield*elementMatches(compiled.element,content,elementValueJudge(rule,spelling,compiled)))}const DEFAULT_ELEMENT_LITERAL_LENGTH=8;function elementValueJudge(rule,spelling,compiled){if(!spelling.elementValue){const minimum=rule.minimumLiteralLength??DEFAULT_ELEMENT_LITERAL_LENGTH;return value=>expandRuntimeReferences(value).length>=minimum}return value=>{const neutral=value.replaceAll('"',"'");compiled.value.lastIndex=0;const match=compiled.value.exec(`"${neutral}"`);return match===null||match[1]!==neutral?!1:(match[1]=value,acceptsSecretMatch(rule,match))}}function isStatementReference(shape,match,value){const end=match.index+match[0].length;return/^[ \t]*;/u.test(match.input.slice(end,end+64))&&!isQuote(captureOpener(match))&&shape.test(value)}function indexOfAngleClose(text,start){for(let index=start+1;index<text.length;index+=1){if(text[index]===">")return index;if(text[index]==="<")return-1}return-1}function appendText(frame,text){frame.raw+=text,frame.literal+=text}function openReference(text,index,frames){const next=text[index+1];if(text[index]!=="$"||next!=="{"&&next!=="(")return-1;const prefix=next==="{"?text.slice(index+2,index+2+defaultedPrefixLength(text,index+2)):"",root=frames[0],opensPiece=frames.length===1&&root.quote!==void 0&&root.literal.length===root.pieceStart;return frames.push({close:next==="{"?"}":")",keep:prefix!=="",raw:`$${next}${prefix}`,literal:"",opensPiece}),index+2+prefix.length}const NAME_START=/[A-Za-z_]/u,NAME_PART=/\w/u,REFERENCE_AFTER_DOLLAR=/[{(A-Za-z_]/u,VARIABLE_REFERENCE=/\$[A-Za-z_]\w*/y,CONSTANT_NAME=/^_*[A-Z][A-Z0-9_]*$/u,BARE_VARIABLE=/^\$[A-Za-z_]\w*$/u,QUOTED_BARE_VARIABLE=/^(["'])\$[A-Za-z_]\w*\1$/u;function variableStep(text,index,frame){VARIABLE_REFERENCE.lastIndex=index;const variable=VARIABLE_REFERENCE.exec(text)?.[0];return variable===void 0?-1:(frame.literal===""&&CONSTANT_NAME.test(variable.slice(1))?frame.raw+=variable:appendText(frame,variable),index+variable.length)}function defaultedPrefixLength(text,start){if(!NAME_START.test(text[start]??""))return 0;let index=start+1;for(;index<text.length&&NAME_PART.test(text[index]);)index+=1;text[index]===":"&&(index+=1);const operator=text[index];return operator==="-"||operator==="="||operator==="+"?index+1-start:0}function closeReference(frames,character){const frame=frames.pop(),parent=frames.at(-1);parent.raw+=`${frame.raw}${character}`,frame.keep&&(parent.literal+=frame.literal)}const PLAIN_RUN=/[^$<"'\\})]+/y,DOUBLE_QUOTE_ESCAPABLE='$`"\\\n';function escapedContribution(next,quote){return next===`
5
5
  `?"":quote==='"'&&!DOUBLE_QUOTE_ESCAPABLE.includes(next)?`\\${next}`:next}function quotedStep(text,index,frame){const character=text[index],quote=frame.quote;if(quote==='"'&&character==="$"&&REFERENCE_AFTER_DOLLAR.test(text[index+1]??""))return-1;let length=1,contributed=character;if(character==="\\"&&quote!=="'"&&index+1<text.length)length=2,contributed=escapedContribution(text[index+1],quote);else if(quote===void 0){if(character!=='"'&&character!=="'")return-1;frame.quote=character,contributed=""}else character===quote&&(frame.quote=void 0,contributed="");return frame.raw+=text.slice(index,index+length),frame.keep&&(frame.literal+=contributed),index+length}function expandStep(text,index,frames,rootQuotesAreSyntax,variables){const innermost=frames.at(-1);PLAIN_RUN.lastIndex=index;const run=PLAIN_RUN.exec(text)?.[0];if(run!==void 0)return appendText(innermost,run),index+run.length;if(frames.length>1){const quoted=quotedStep(text,index,innermost);if(quoted!==-1)return quoted}else if(rootQuotesAreSyntax&&rootQuoteStep(text[index],innermost))return index+1;const opened=openReference(text,index,frames);if(opened!==-1)return opened;const top=frames.at(-1),character=text[index],variable=variables&&character==="$"?variableStep(text,index,top):-1;if(variable!==-1)return variable;if(frames.length>1&&character===top.close)return closeReference(frames,character),index+1;const angleClose=character==="<"?indexOfAngleClose(text,index):-1;return angleClose!==-1?(top.raw+=text.slice(index,angleClose+1),angleClose+1):(appendText(top,character),index+1)}function rootQuoteStep(character,root){return character!=='"'&&character!=="'"?!1:root.quote===void 0?(root.quote=character,root.pieceStart=root.literal.length,!0):character!==root.quote?!1:(root.quote=void 0,!0)}function expandWords(text,rootQuotesAreSyntax,variables){if(variables&&(BARE_VARIABLE.test(text)||rootQuotesAreSyntax&&QUOTED_BARE_VARIABLE.test(text)))return"";const root={close:"}",keep:!0,raw:"",literal:""},frames=[root];for(let index=0;index<text.length;)index=expandStep(text,index,frames,rootQuotesAreSyntax,variables);for(let depth=frames.length-1;depth>0;depth-=1){const frame=frames[depth],parent=frames[depth-1];parent.raw+=frame.raw,rootQuotesAreSyntax&&depth===1&&frame.opensPiece===!0||(parent.literal+=frame.raw)}return root.literal}function expandRuntimeReferences(text,variables=!0){return expandWords(text,!1,variables)}function literalAfterReferences(value,variables=!0){return expandWords(value,!0,variables)}function acceptsSecretMatch(rule,match){const value=rule.minimumLiteralLength===void 0?match[1]:judgedLiteral(match);if(rule.minimumLiteralLength!==void 0&&value.length<rule.minimumLiteralLength||rule.literalValue&&SPELLING_SENSITIVE.test(match[1])&&!literalMatches(rule.literalValue,value,isCodeAfterReference(match))||rule.rejectValue?.test(value)===!0||rule.rejectStatementReference&&isStatementReference(rule.rejectStatementReference,match,value))return!1;if(rule.minimumEntropy===void 0)return!0;const characters=[...value],counts=new Map;for(const character of characters)counts.set(character,(counts.get(character)??0)+1);let entropy=0;for(const count of counts.values()){const probability=count/characters.length;entropy-=probability*Math.log2(probability)}return entropy>=rule.minimumEntropy}const _testOnly={leadingReferencesEnd};export{PRIVATE_HOME_PATH_PATTERN,SECRET_RULES,_testOnly,acceptsSecretMatch,acceptsStructuredValue,expandRuntimeReferences,findPrivateHomePathMatches,findSecretRuleMatches,literalAfterReferences,structuredKeyShape};
@@ -56,7 +56,9 @@ last_update_remote_version?:string;
56
56
  /** Value that configures or reports update available for this contract. */
57
57
  update_available?:boolean|null;
58
58
  /** Value that configures or reports update error for this contract. */
59
- update_error?:string;}
59
+ update_error?:string;
60
+ /** Budget in milliseconds that a diagnostic lookup ran out of; diagnostics never persist this field. */
61
+ update_check_timeout_ms?:number;}
60
62
  /** Documents the managed extension state payload exchanged by command, SDK, and package integrations. */
61
63
  export interface ManagedExtensionState{
62
64
  /** Value that configures or reports version for this contract. */
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{nowIso}from"../../core/shared/time.js";import{normalizeExtensionContributionInventory}from"../../core/extensions/contribution-inventory.js";import{normalizeExtensionNameForMatch,normalizeStringList}from"./shared.js";const MANAGED_EXTENSION_STATE_FILENAME=".managed-extensions.json",MANAGED_EXTENSION_STATE_VERSION=1;function resolveManagedExtensionStatePath(extensionsRoot){return path.join(extensionsRoot,MANAGED_EXTENSION_STATE_FILENAME)}function createEmptyManagedExtensionState(){return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:[]}}function sortManagedEntries(entries){return[...entries].sort((left,right)=>{const byScope=left.scope.localeCompare(right.scope);if(byScope!==0)return byScope;const byName=left.name.localeCompare(right.name);return byName!==0?byName:left.directory.localeCompare(right.directory)})}function managedExtensionSourcesEquivalent(left,right){return left.kind!==right.kind||left.input!==right.input||left.location!==right.location?!1:left.kind==="npm"&&right.kind==="npm"?left.package===right.package&&left.version===right.version:left.kind==="github"&&right.kind==="github"?left.repository===right.repository&&left.ref===right.ref&&left.subpath===right.subpath&&left.commit===right.commit:left.kind==="builtin"&&right.kind==="builtin"?left.name===right.name:!0}function optionalString(value){return typeof value=="string"?value:void 0}function hasRequiredManagedRecordFields(entry){return typeof entry.name=="string"&&entry.name.trim().length>0&&typeof entry.directory=="string"&&entry.directory.trim().length>0&&(entry.scope==="project"||entry.scope==="global")&&typeof entry.manifest_version=="string"&&typeof entry.manifest_entry=="string"&&Array.isArray(entry.capabilities)&&entry.capabilities.every(value=>typeof value=="string")&&typeof entry.installed_at=="string"&&typeof entry.updated_at=="string"}function normalizeManagedSource(raw){if(typeof raw!="object"||raw===null)return null;const source=raw;return source.kind!=="local"&&source.kind!=="github"&&source.kind!=="npm"&&source.kind!=="builtin"||typeof source.input!="string"||typeof source.location!="string"?null:{kind:source.kind,input:source.input,location:source.location,name:optionalString(source.name),package:optionalString(source.package),version:optionalString(source.version),repository:optionalString(source.repository),owner:optionalString(source.owner),repo:optionalString(source.repo),ref:optionalString(source.ref),subpath:optionalString(source.subpath),commit:optionalString(source.commit)}}function normalizeManagedRecord(raw){if(typeof raw!="object"||raw===null)return null;const entry=raw;if(!hasRequiredManagedRecordFields(entry))return null;const source=normalizeManagedSource(entry.source);if(!source)return null;const contributions=normalizeExtensionContributionInventory(entry.contributions);return contributions===null?null:{name:entry.name.trim(),directory:entry.directory.trim(),scope:entry.scope,manifest_version:entry.manifest_version,manifest_entry:entry.manifest_entry,capabilities:normalizeStringList(entry.capabilities),contributions,installed_at:entry.installed_at,updated_at:entry.updated_at,source,last_update_check_at:optionalString(entry.last_update_check_at),last_update_remote_commit:optionalString(entry.last_update_remote_commit),last_update_remote_version:optionalString(entry.last_update_remote_version),update_available:typeof entry.update_available=="boolean"||entry.update_available===null?entry.update_available:void 0,update_error:optionalString(entry.update_error)}}function normalizeManagedState(raw){if(typeof raw!="object"||raw===null)return null;const candidate=raw;if(candidate.version!==MANAGED_EXTENSION_STATE_VERSION||!Array.isArray(candidate.entries))return null;const entries=[];for(const rawEntry of candidate.entries){const record=normalizeManagedRecord(rawEntry);record&&entries.push(record)}return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:optionalString(candidate.updated_at)??nowIso(),entries:sortManagedEntries(entries)}}async function readManagedExtensionState(extensionsRoot){const statePath=resolveManagedExtensionStatePath(extensionsRoot),fallback=createEmptyManagedExtensionState();try{const raw=await fs.readFile(statePath,"utf8"),parsed=JSON.parse(raw),normalized=normalizeManagedState(parsed);if(!normalized)throw new PmCliError(`Managed extension state file "${statePath}" has an invalid schema. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE);return{path:statePath,state:normalized,warnings:[]}}catch(error){if(error instanceof PmCliError)throw error;if(typeof error=="object"&&error!==null&&"code"in error&&isFileMissingError(error))return{path:statePath,state:fallback,warnings:[]};throw new PmCliError(`Managed extension state file "${statePath}" could not be read. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE)}}async function writeManagedExtensionState(extensionsRoot,state){const statePath=resolveManagedExtensionStatePath(extensionsRoot),normalized={version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:sortManagedEntries(state.entries)};await fs.mkdir(extensionsRoot,{recursive:!0}),await fs.writeFile(statePath,`${JSON.stringify(normalized,null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="054bae8c-464f-5791-a78a-063588565393")}catch{}})();import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{nowIso}from"../../core/shared/time.js";import{normalizeExtensionContributionInventory}from"../../core/extensions/contribution-inventory.js";import{normalizeExtensionNameForMatch,normalizeStringList}from"./shared.js";const MANAGED_EXTENSION_STATE_FILENAME=".managed-extensions.json",MANAGED_EXTENSION_STATE_VERSION=1;function resolveManagedExtensionStatePath(extensionsRoot){return path.join(extensionsRoot,MANAGED_EXTENSION_STATE_FILENAME)}function createEmptyManagedExtensionState(){return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:[]}}function sortManagedEntries(entries){return[...entries].sort((left,right)=>{const byScope=left.scope.localeCompare(right.scope);if(byScope!==0)return byScope;const byName=left.name.localeCompare(right.name);return byName!==0?byName:left.directory.localeCompare(right.directory)})}function managedExtensionSourcesEquivalent(left,right){return left.kind!==right.kind||left.input!==right.input||left.location!==right.location?!1:left.kind==="npm"&&right.kind==="npm"?left.package===right.package&&left.version===right.version:left.kind==="github"&&right.kind==="github"?left.repository===right.repository&&left.ref===right.ref&&left.subpath===right.subpath&&left.commit===right.commit:left.kind==="builtin"&&right.kind==="builtin"?left.name===right.name:!0}function optionalString(value){return typeof value=="string"?value:void 0}const TIMED_OUT_UPDATE_ERROR=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function stableUpdateError(source,value){const error=optionalString(value);return error===void 0||source.kind!=="github"||error.trim().length===0||/^[a-z0-9_]+$/u.test(error.trim())?error:"github_remote_lookup_failed"}function isTimedOutUpdateError(error){return typeof error=="string"&&TIMED_OUT_UPDATE_ERROR.test(error.trim())}function optionalTimeoutBudget(error,value){return isTimedOutUpdateError(error)&&typeof value=="number"&&Number.isSafeInteger(value)&&value>0?{update_check_timeout_ms:value}:{}}function hasRequiredManagedRecordFields(entry){return typeof entry.name=="string"&&entry.name.trim().length>0&&typeof entry.directory=="string"&&entry.directory.trim().length>0&&(entry.scope==="project"||entry.scope==="global")&&typeof entry.manifest_version=="string"&&typeof entry.manifest_entry=="string"&&Array.isArray(entry.capabilities)&&entry.capabilities.every(value=>typeof value=="string")&&typeof entry.installed_at=="string"&&typeof entry.updated_at=="string"}function normalizeManagedSource(raw){if(typeof raw!="object"||raw===null)return null;const source=raw;return source.kind!=="local"&&source.kind!=="github"&&source.kind!=="npm"&&source.kind!=="builtin"||typeof source.input!="string"||typeof source.location!="string"?null:{kind:source.kind,input:source.input,location:source.location,name:optionalString(source.name),package:optionalString(source.package),version:optionalString(source.version),repository:optionalString(source.repository),owner:optionalString(source.owner),repo:optionalString(source.repo),ref:optionalString(source.ref),subpath:optionalString(source.subpath),commit:optionalString(source.commit)}}function normalizeManagedRecord(raw){if(typeof raw!="object"||raw===null)return null;const entry=raw;if(!hasRequiredManagedRecordFields(entry))return null;const source=normalizeManagedSource(entry.source);if(!source)return null;const contributions=normalizeExtensionContributionInventory(entry.contributions);return contributions===null?null:{name:entry.name.trim(),directory:entry.directory.trim(),scope:entry.scope,manifest_version:entry.manifest_version,manifest_entry:entry.manifest_entry,capabilities:normalizeStringList(entry.capabilities),contributions,installed_at:entry.installed_at,updated_at:entry.updated_at,source,last_update_check_at:optionalString(entry.last_update_check_at),last_update_remote_commit:optionalString(entry.last_update_remote_commit),last_update_remote_version:optionalString(entry.last_update_remote_version),update_available:isTimedOutUpdateError(entry.update_error)?null:typeof entry.update_available=="boolean"||entry.update_available===null?entry.update_available:void 0,update_error:stableUpdateError(source,entry.update_error),...optionalTimeoutBudget(entry.update_error,entry.update_check_timeout_ms)}}function normalizeManagedState(raw){if(typeof raw!="object"||raw===null)return null;const candidate=raw;if(candidate.version!==MANAGED_EXTENSION_STATE_VERSION||!Array.isArray(candidate.entries))return null;const entries=[];for(const rawEntry of candidate.entries){const record=normalizeManagedRecord(rawEntry);record&&entries.push(record)}return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:optionalString(candidate.updated_at)??nowIso(),entries:sortManagedEntries(entries)}}async function readManagedExtensionState(extensionsRoot){const statePath=resolveManagedExtensionStatePath(extensionsRoot),fallback=createEmptyManagedExtensionState();try{const raw=await fs.readFile(statePath,"utf8"),parsed=JSON.parse(raw),normalized=normalizeManagedState(parsed);if(!normalized)throw new PmCliError(`Managed extension state file "${statePath}" has an invalid schema. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE);return{path:statePath,state:normalized,warnings:[]}}catch(error){if(error instanceof PmCliError)throw error;if(typeof error=="object"&&error!==null&&"code"in error&&isFileMissingError(error))return{path:statePath,state:fallback,warnings:[]};throw new PmCliError(`Managed extension state file "${statePath}" could not be read. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE)}}async function writeManagedExtensionState(extensionsRoot,state){const statePath=resolveManagedExtensionStatePath(extensionsRoot),normalized={version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:sortManagedEntries(state.entries)};await fs.mkdir(extensionsRoot,{recursive:!0}),await fs.writeFile(statePath,`${JSON.stringify(normalized,null,2)}
2
2
  `,"utf8")}function upsertManagedEntry(state,entry){const updatedEntries=state.entries.filter(candidate=>normalizeExtensionNameForMatch(candidate.name)!==normalizeExtensionNameForMatch(entry.name)&&normalizeExtensionNameForMatch(candidate.directory)!==normalizeExtensionNameForMatch(entry.directory));return updatedEntries.push(entry),{...state,updated_at:nowIso(),entries:sortManagedEntries(updatedEntries)}}async function persistManagedContributionInventory(extensionsRoot,state,extensionName,contributions){const entry=state.entries.find(candidate=>normalizeExtensionNameForMatch(candidate.name)===normalizeExtensionNameForMatch(extensionName));if(!entry)return state;const updated=upsertManagedEntry(state,{...entry,contributions});return await writeManagedExtensionState(extensionsRoot,updated),updated}export{createEmptyManagedExtensionState,managedExtensionSourcesEquivalent,normalizeManagedState,persistManagedContributionInventory,readManagedExtensionState,resolveManagedExtensionStatePath,sortManagedEntries,upsertManagedEntry,writeManagedExtensionState};
3
3
  //# sourceMappingURL=managed-state.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();import{mapWithFixedConcurrency}from"./concurrency.js";import{sortManagedEntries}from"./managed-state.js";import{checkGithubUpdate,checkNpmUpdate}from"./update-check.js";const MANAGED_UPDATE_CHECK_CONCURRENCY=4;async function refreshManagedExtensionUpdates(state,offline=!1){const entries=await mapWithFixedConcurrency(state.entries,MANAGED_UPDATE_CHECK_CONCURRENCY,async entry=>{if(!["github","npm"].includes(entry.source.kind))return entry;if(offline)return{...entry,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};const updateStatus=entry.source.kind==="github"?await checkGithubUpdate(entry.source):await checkNpmUpdate(entry.source);return{...entry,last_update_check_at:updateStatus.checked_at,last_update_remote_commit:"remote_commit"in updateStatus?updateStatus.remote_commit:void 0,last_update_remote_version:"remote_version"in updateStatus?updateStatus.remote_version:void 0,update_available:updateStatus.available,update_error:updateStatus.error}});return{...state,entries:sortManagedEntries(entries)}}export{refreshManagedExtensionUpdates};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4f307be2-a113-558f-be2e-8b8f209285a5")}catch{}})();import{mapWithFixedConcurrency}from"./concurrency.js";import{sortManagedEntries}from"./managed-state.js";import{checkGithubUpdate,checkNpmUpdate,resolveExtensionUpdateCheckTimeoutMs,updateCheckTeardown}from"./update-check.js";const MANAGED_UPDATE_CHECK_CONCURRENCY=4;function createPermits(limit){let free=limit;const waiters=[];return{acquire:()=>free>0?(free-=1,Promise.resolve()):new Promise(resolve=>waiters.push(resolve)),release:()=>{const next=waiters.shift();next?next():free+=1}}}function withUpdateCheckTimeout(entry,timeoutMs){const{update_check_timeout_ms:_previous,...rest}=entry;return timeoutMs===void 0?rest:{...rest,update_check_timeout_ms:timeoutMs}}async function refreshManagedExtensionUpdates(state,offline=!1,timeoutMs=resolveExtensionUpdateCheckTimeoutMs(),holdPermitsThroughTeardown=!0){const providers=createPermits(MANAGED_UPDATE_CHECK_CONCURRENCY),entries=await mapWithFixedConcurrency(state.entries,MANAGED_UPDATE_CHECK_CONCURRENCY,async entry=>{if(!["github","npm"].includes(entry.source.kind))return entry;if(offline)return withUpdateCheckTimeout({...entry,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0},void 0);await providers.acquire();const updateStatus=entry.source.kind==="github"?await checkGithubUpdate(entry.source,void 0,timeoutMs):await checkNpmUpdate(entry.source,void 0,timeoutMs);return holdPermitsThroughTeardown?updateCheckTeardown(updateStatus).then(providers.release):providers.release(),withUpdateCheckTimeout({...entry,last_update_check_at:updateStatus.checked_at,last_update_remote_commit:"remote_commit"in updateStatus?updateStatus.remote_commit:void 0,last_update_remote_version:"remote_version"in updateStatus?updateStatus.remote_version:void 0,update_available:updateStatus.available,update_error:updateStatus.error},updateStatus.timeout_ms)});return{...state,entries:sortManagedEntries(entries)}}export{refreshManagedExtensionUpdates};
2
2
  //# sourceMappingURL=managed-update-status.js.map
@@ -1,4 +1,22 @@
1
- import type{ManagedExtensionSource}from "./managed-state.js";import{runGitCommand}from "./install-sources.js";
1
+ import type{ManagedExtensionSource}from "./managed-state.js";
2
+ /** Environment variable that overrides the per-lookup update-check budget. */
3
+ export declare const PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS_ENV="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS";
4
+ /** Default budget of one managed-extension update lookup. */
5
+ export declare const EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS=10000;
6
+ /** Stable reason for an npm lookup that failed for any reason other than its budget. */
7
+ export declare const NPM_REGISTRY_LOOKUP_FAILED="npm_registry_lookup_failed";
8
+ /** Stable reason for an npm lookup killed when its budget ran out (pm-5kfzjh). */
9
+ export declare const NPM_REGISTRY_LOOKUP_TIMED_OUT="npm_registry_lookup_timed_out";
10
+ /** Stable reason for a `git ls-remote` lookup that failed for any reason other than its budget. */
11
+ export declare const GITHUB_REMOTE_LOOKUP_FAILED="github_remote_lookup_failed";
12
+ /** Stable reason for a `git ls-remote` lookup killed when its budget ran out (pm-43p2c3). */
13
+ export declare const GITHUB_REMOTE_LOOKUP_TIMED_OUT="github_remote_lookup_timed_out";
14
+ /**
15
+ * Resolve the budget of one update lookup: `PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS`
16
+ * as integer milliseconds, clamped to 1000–25000, or the 10000 ms default when
17
+ * it is unset or not a finite number.
18
+ */
19
+ export declare function resolveExtensionUpdateCheckTimeoutMs(env?:NodeJS.ProcessEnv):number;
2
20
  /** Describes the remote revision health of one managed GitHub extension. */
3
21
  export interface GithubUpdateStatus{
4
22
  /** Time at which the remote comparison completed. */
@@ -8,14 +26,32 @@ available:boolean|null;
8
26
  /** Peeled remote commit when the selected reference resolves. */
9
27
  remote_commit?:string;
10
28
  /** Stable failure reason when the comparison is incomplete. */
11
- error?:string;}
29
+ error?:string;
30
+ /** Budget in milliseconds that ran out, present only with a `*_timed_out` reason. */
31
+ timeout_ms?:number;}
12
32
  /** Result of comparing the installed npm identity with its registry latest dist-tag. */
13
33
  export interface NpmUpdateStatus extends Omit<GithubUpdateStatus,"remote_commit">{
14
34
  /** Registry version selected by the latest dist-tag, when valid. */
15
35
  remote_version?:string;}
16
- /** Query npm's configured registry with bounded execution and no lifecycle scripts. */
17
- declare function runNpmUpdateQuery(args:string[],timeout:number):Promise<string>;
36
+ /** One bounded update lookup: run the provider command and return its trimmed stdout. */
37
+ type UpdateQueryRunner=(args:string[],timeoutMs:number)=> Promise<string>;
38
+ /**
39
+ * Resolve once the provider teardown behind a failed status has finished; at
40
+ * once for any other status. A caller that bounds how many providers run at a
41
+ * time holds its slot until then, without delaying the status itself.
42
+ */
43
+ export declare function updateCheckTeardown(status:object):Promise<void>;
44
+ /**
45
+ * Run one SDK action so that, inside a worker thread, every provider
46
+ * teardown it started has finished before it settles; on the main thread
47
+ * nothing is waited for. A worker has no shutdown hook that is sure to run
48
+ * (`terminate()` runs no exit listener), so its host may terminate it as soon
49
+ * as the result arrives; the main thread relies on the exit listener. Only
50
+ * this invocation's own teardowns are awaited, never another action's, and
51
+ * the wait runs after `run` settles, so a lock `run` holds is released first.
52
+ */
53
+ export declare function withUpdateCheckTeardownScope<T>(run:()=> Promise<T>):Promise<T>;
18
54
  /** Compare recorded npm provenance without persisting diagnostic results or guessing missing versions. */
19
- export declare function checkNpmUpdate(source:ManagedExtensionSource,npmRunner?:typeof runNpmUpdateQuery):Promise<NpmUpdateStatus>;
55
+ export declare function checkNpmUpdate(source:ManagedExtensionSource,npmRunner?:UpdateQueryRunner,timeoutMs?:number):Promise<NpmUpdateStatus>;
20
56
  /** Compare one managed GitHub extension against its remote revision. */
21
- export declare const checkGithubUpdate:(source:ManagedExtensionSource,gitCommandRunner?:typeof runGitCommand)=> Promise<GithubUpdateStatus>;export{};
57
+ export declare const checkGithubUpdate:(source:ManagedExtensionSource,gitCommandRunner?:UpdateQueryRunner,timeoutMs?:number)=> Promise<GithubUpdateStatus>;export{};
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b67e46f9-51ff-501b-98da-74353b4c66d9")}catch{}})();import{nowIso}from"../../core/shared/time.js";import{execFile}from"node:child_process";import{promisify}from"node:util";import npa from"npm-package-arg";import{resolveNpmCommandName,runGitCommand,shouldRunNpmCommandInShell}from"./install-sources.js";const execFileAsync=promisify(execFile),GITHUB_UPDATE_CHECK_TIMEOUT_MS=1e4;function resolveExactNpmVersion(packageName,version,errorCode){if(typeof version=="string")try{const parsed=npa.resolve(packageName,version);if(parsed.type==="version")return parsed.fetchSpec}catch{}throw new Error(errorCode)}async function runNpmUpdateQuery(args,timeout){try{return(await execFileAsync(resolveNpmCommandName(),args,{encoding:"utf8",timeout,maxBuffer:65536,shell:shouldRunNpmCommandInShell(),env:{...process.env,npm_config_ignore_scripts:"true"}})).stdout.trim()}catch{throw new Error("npm_registry_lookup_failed")}}async function checkNpmUpdate(source,npmRunner=runNpmUpdateQuery){const checkedAt=nowIso();try{if(source.kind!=="npm"||!source.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(source.package))throw new Error("missing_or_invalid_npm_package_identity");const installedVersion=resolveExactNpmVersion(source.package,source.version,"missing_or_invalid_installed_npm_version"),registryOutput=await npmRunner(["view",source.package,"dist-tags.latest","--json","--ignore-scripts"],GITHUB_UPDATE_CHECK_TIMEOUT_MS);let output;try{output=JSON.parse(registryOutput)}catch{throw new Error("invalid_npm_registry_metadata")}const version=Array.isArray(output)&&output.length===1?output[0]:output,latestVersion=resolveExactNpmVersion(source.package,version,"invalid_npm_registry_version");return{checked_at:checkedAt,available:latestVersion!==installedVersion,remote_version:latestVersion}}catch(error){return{checked_at:checkedAt,available:null,error:error instanceof Error?error.message:String(error)}}}const resolveGithubUpdateOutput=(output,installedCommitInput,checkedAt)=>{const references=output.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map(line=>{const[commit,ref=""]=line.split(/\s+/);return{commit,ref}}),remoteReference=references.find(reference=>reference.ref.endsWith("^{}"))??references[0];if(!remoteReference)return{checked_at:checkedAt,available:null,error:"no_remote_reference_found"};const installedCommit=installedCommitInput?.trim();return installedCommit?{checked_at:checkedAt,remote_commit:remoteReference.commit,available:remoteReference.commit!==installedCommit}:{checked_at:checkedAt,remote_commit:remoteReference.commit,available:null,error:"missing_installed_commit"}},checkGithubUpdate=async(source,gitCommandRunner=runGitCommand)=>{const checkedAt=nowIso();if(source.kind!=="github"||!source.repository)return{checked_at:checkedAt,available:null,error:"not_a_github_managed_source"};try{const ref=[source.ref?.trim(),"HEAD"].find(Boolean),output=await gitCommandRunner(["ls-remote",source.repository,ref,`${ref}^{}`],void 0,GITHUB_UPDATE_CHECK_TIMEOUT_MS);return resolveGithubUpdateOutput(output,source.commit,checkedAt)}catch(error){return{checked_at:checkedAt,available:null,error:error instanceof Error?error.message:String(error)}}};export{checkGithubUpdate,checkNpmUpdate};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8c4f3228-d035-53ae-b279-3f33bd5323c8")}catch{}})();import{nowIso}from"../../core/shared/time.js";import{spawn}from"node:child_process";import{AsyncLocalStorage}from"node:async_hooks";import{isMainThread}from"node:worker_threads";import npa from"npm-package-arg";import{killProcessTree}from"../../core/shared/process-tree.js";import{resolveNpmCommandName,shouldRunNpmCommandInShell}from"./install-sources.js";const PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS_ENV="PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS",EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS=1e4,EXTENSION_UPDATE_CHECK_TIMEOUT_MIN_MS=1e3,EXTENSION_UPDATE_CHECK_TIMEOUT_MAX_MS=25e3,PROVIDER_EXIT_WAIT_MS=2e3,NPM_REGISTRY_LOOKUP_FAILED="npm_registry_lookup_failed",NPM_REGISTRY_LOOKUP_TIMED_OUT="npm_registry_lookup_timed_out",GITHUB_REMOTE_LOOKUP_FAILED="github_remote_lookup_failed",GITHUB_REMOTE_LOOKUP_TIMED_OUT="github_remote_lookup_timed_out";function resolveExtensionUpdateCheckTimeoutMs(env=process.env){const raw=env[PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS_ENV]?.trim(),configured=raw?Number(raw):Number.NaN;return Number.isFinite(configured)?Math.min(EXTENSION_UPDATE_CHECK_TIMEOUT_MAX_MS,Math.max(EXTENSION_UPDATE_CHECK_TIMEOUT_MIN_MS,Math.trunc(configured))):EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS}class UpdateQueryError extends Error{timeout_ms;teardown;constructor(reason,timeoutMs,teardown){super(reason),this.name="UpdateQueryError",this.timeout_ms=timeoutMs,this.teardown=teardown}}const statusTeardowns=new WeakMap;function updateCheckTeardown(status){return statusTeardowns.get(status)??Promise.resolve()}function failedUpdateStatus(checkedAt,error){const status={checked_at:checkedAt,available:null,error:error instanceof Error?error.message:String(error)};return error instanceof UpdateQueryError&&error.timeout_ms!==void 0&&(status.timeout_ms=error.timeout_ms),error instanceof UpdateQueryError&&error.teardown!==void 0&&statusTeardowns.set(status,error.teardown),status}const pendingProviderKills=new Set;function killPendingProviders(){for(const kill of pendingProviderKills)kill()}const invocationTeardowns=new AsyncLocalStorage;async function withUpdateCheckTeardownScope(run){const started=new Set;try{return await invocationTeardowns.run(started,run)}finally{isMainThread||await Promise.all(started)}}function trackPendingProviderKill(kill){return pendingProviderKills.size===0&&process.on("exit",killPendingProviders),pendingProviderKills.add(kill),()=>{pendingProviderKills.delete(kill),pendingProviderKills.size===0&&process.off("exit",killPendingProviders)}}function createProviderTeardown(lookup){const exited=()=>lookup.exitCode!==null||lookup.signalCode!==null,killDirectChild=()=>{exited()||lookup.kill("SIGKILL")},awaitExit=()=>exited()||lookup.pid===void 0?Promise.resolve():new Promise(resolve=>{const bound=setTimeout(()=>{lookup.unref(),resolve()},PROVIDER_EXIT_WAIT_MS);lookup.once("exit",()=>{clearTimeout(bound),resolve()})}),finish=()=>(killDirectChild(),lookup.stdout?.destroy(),awaitExit());return{stop:()=>exited()||lookup.pid===void 0?Promise.resolve().then(finish):killProcessTree(lookup.pid,{kill:killDirectChild,alive:()=>!exited()}).then(finish,finish),killNow:killDirectChild}}function runBoundedUpdateQuery(file,args,timeout,spec){return new Promise((resolve,reject)=>{let child;try{child=spawn(file,args,{env:spec.env,shell:spec.shell,stdio:["ignore","pipe","ignore"]})}catch{reject(new UpdateQueryError(spec.failed));return}const lookup=child,deadlineAt=performance.now()+timeout;let settled=!1,stdout="",stdoutBytes=0;const provider=createProviderTeardown(lookup),scope=invocationTeardowns.getStore();let teardown;const deferTeardown=()=>{const untrack=trackPendingProviderKill(provider.killNow),running=new Promise(resolve2=>{setTimeout(()=>{provider.stop().then(resolve2,resolve2)},0)}).finally(untrack);return scope?.add(running),teardown=running,running},deadline=setTimeout(()=>{settle(new UpdateQueryError(spec.timedOut,timeout,deferTeardown()))},timeout);function settle(error){settled||(settled=!0,clearTimeout(deadline),performance.now()>=deadlineAt?reject(new UpdateQueryError(spec.timedOut,timeout,teardown)):error?reject(error):resolve(stdout.trim()))}if(lookup.on("error",()=>settle(new UpdateQueryError(spec.failed))),!lookup.stdout){settle(new UpdateQueryError(spec.failed,void 0,deferTeardown()));return}lookup.stdout.setEncoding("utf8"),lookup.stdout.on("data",chunk=>{if(!settled){if(stdoutBytes+=Buffer.byteLength(chunk),stdoutBytes>spec.maxBuffer){settle(new UpdateQueryError(spec.failed,void 0,deferTeardown()));return}stdout+=chunk}}),lookup.on("exit",(code,signal)=>{code===0&&signal===null||(settle(new UpdateQueryError(spec.failed)),lookup.stdout.destroy())}),lookup.on("close",(code,signal)=>settle(code===0&&signal===null?void 0:new UpdateQueryError(spec.failed)))})}function resolveExactNpmVersion(packageName,version,errorCode){if(typeof version=="string")try{const parsed=npa.resolve(packageName,version);if(parsed.type==="version")return parsed.fetchSpec}catch{}throw new Error(errorCode)}const runNpmUpdateQuery=(args,timeout)=>runBoundedUpdateQuery(resolveNpmCommandName(),args,timeout,{env:{...process.env,npm_config_ignore_scripts:"true"},shell:shouldRunNpmCommandInShell(),maxBuffer:64*1024,timedOut:NPM_REGISTRY_LOOKUP_TIMED_OUT,failed:NPM_REGISTRY_LOOKUP_FAILED}),runGitUpdateQuery=(args,timeout)=>runBoundedUpdateQuery("git",args,timeout,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"},maxBuffer:1024*1024,timedOut:GITHUB_REMOTE_LOOKUP_TIMED_OUT,failed:GITHUB_REMOTE_LOOKUP_FAILED});async function checkNpmUpdate(source,npmRunner=runNpmUpdateQuery,timeoutMs=resolveExtensionUpdateCheckTimeoutMs()){const checkedAt=nowIso();try{if(source.kind!=="npm"||!source.package||!/^(?:@[a-zA-Z0-9._-]+\/)?[a-zA-Z0-9._-]+$/u.test(source.package))throw new Error("missing_or_invalid_npm_package_identity");const installedVersion=resolveExactNpmVersion(source.package,source.version,"missing_or_invalid_installed_npm_version"),registryOutput=await npmRunner(["view",source.package,"dist-tags.latest","--json","--ignore-scripts"],timeoutMs);let output;try{output=JSON.parse(registryOutput)}catch{throw new Error("invalid_npm_registry_metadata")}const version=Array.isArray(output)&&output.length===1?output[0]:output,latestVersion=resolveExactNpmVersion(source.package,version,"invalid_npm_registry_version");return{checked_at:checkedAt,available:latestVersion!==installedVersion,remote_version:latestVersion}}catch(error){return failedUpdateStatus(checkedAt,error)}}const resolveGithubUpdateOutput=(output,installedCommitInput,checkedAt)=>{const references=output.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map(line=>{const[commit,ref=""]=line.split(/\s+/);return{commit,ref}}),remoteReference=references.find(reference=>reference.ref.endsWith("^{}"))??references[0];if(!remoteReference)return{checked_at:checkedAt,available:null,error:"no_remote_reference_found"};const installedCommit=installedCommitInput?.trim();return installedCommit?{checked_at:checkedAt,remote_commit:remoteReference.commit,available:remoteReference.commit!==installedCommit}:{checked_at:checkedAt,remote_commit:remoteReference.commit,available:null,error:"missing_installed_commit"}},checkGithubUpdate=async(source,gitCommandRunner=runGitUpdateQuery,timeoutMs=resolveExtensionUpdateCheckTimeoutMs())=>{const checkedAt=nowIso();if(source.kind!=="github"||!source.repository)return{checked_at:checkedAt,available:null,error:"not_a_github_managed_source"};try{const ref=[source.ref?.trim(),"HEAD"].find(Boolean),output=await gitCommandRunner(["ls-remote",source.repository,ref,`${ref}^{}`],timeoutMs);return resolveGithubUpdateOutput(output,source.commit,checkedAt)}catch(error){return failedUpdateStatus(checkedAt,error)}};export{EXTENSION_UPDATE_CHECK_TIMEOUT_DEFAULT_MS,GITHUB_REMOTE_LOOKUP_FAILED,GITHUB_REMOTE_LOOKUP_TIMED_OUT,NPM_REGISTRY_LOOKUP_FAILED,NPM_REGISTRY_LOOKUP_TIMED_OUT,PM_EXTENSION_UPDATE_CHECK_TIMEOUT_MS_ENV,checkGithubUpdate,checkNpmUpdate,resolveExtensionUpdateCheckTimeoutMs,updateCheckTeardown,withUpdateCheckTeardownScope};
2
2
  //# sourceMappingURL=update-check.js.map
@@ -130,6 +130,8 @@ last_update_remote_commit?:string;
130
130
  last_update_remote_version?:string;
131
131
  /** Value that configures or reports update error for this contract. */
132
132
  update_error?:string;
133
+ /** Budget in milliseconds that the update lookup ran out of, present only when it timed out. */
134
+ update_check_timeout_ms?:number;
133
135
  /** Outcome of the registry update check for this extension. */
134
136
  update_check_status:ExtensionUpdateCheckStatus;
135
137
  /** Value that configures or reports update check reason for this contract. */
@@ -236,4 +238,4 @@ interface AdoptUnmanagedExtensionsResult{state:ManagedExtensionState;adopted_ent
236
238
  */
237
239
  export declare const runExtension:(target:string|undefined,options:ExtensionCommandOptions,global:GlobalOptions)=> Promise<ExtensionCommandResult>;
238
240
  /** Public contract for test only, shared by SDK and presentation-layer consumers. */
239
- export declare const _testOnly:{adoptUnmanagedExtensions:(extensionsRoot:string,scope:ExtensionScope,installedExtensions:ManagedExtensionSummary[],state:ManagedExtensionState)=> Promise<AdoptUnmanagedExtensionsResult>;buildAdoptedExtensionSource:(githubOption:string|undefined,extensionTarget:string,extensionDirectory:string,ref:string|undefined)=> ManagedExtensionSource;buildExtensionPolicyDetails:(policy:PmSettings["extensions"]["policy"]|null|undefined)=> ExtensionPolicyDetails;buildInstallCommandDiscovery:(extensionName:string,source:ManagedExtensionSource,commandSummary:{command_paths:string[];action_paths:string[];},activationFailure?:ActivationFailureDiagnostic)=> Record<string,unknown>;checkGithubUpdate:(source:ManagedExtensionSource,gitCommandRunner?:typeof import("./extension/install-sources.js").runGitCommand)=> Promise<import("./extension/update-check.js").GithubUpdateStatus>;clearExtensionState:(settings:PmSettings,name:string)=> boolean;collectActivationFailureDiagnostics:(failures:ActivationFailureEntry[])=> ActivationFailureDiagnostic[];findActivationFailureByName:(extensionName:string,failures:ActivationFailureDiagnostic[],layer?:ExtensionScope)=> ActivationFailureDiagnostic|undefined;resolveInstallRuntimeActivationStatus:(extensionName:string,scope:ExtensionScope,runtimeInstalled:ManagedExtensionSummary[],installActivationFailure:ActivationFailureDiagnostic|undefined)=> ExtensionActivationStatus;collectGlobalOutputOverrideDoctorWarnings:typeof collectGlobalOutputOverrideDoctorWarnings;collectMcpCustomFieldCollisionDoctorWarnings:(activationResult:Awaited<ReturnType<typeof activateExtensions>>)=> string[];collectSchemaNarrowActivationDoctorWarnings:(loadResult:Awaited<ReturnType<typeof loadExtensions>>,activationResult:Awaited<ReturnType<typeof activateExtensions>>)=> string[];copyExtensionDirectoryWithoutSelfNesting:(sourceDirectory:string,destinationDirectory:string,copyDirectory:typeof fs.cp,temporaryDirectory?:string)=> Promise<void>;isErrnoCode:(error:unknown,code:string)=> boolean;isRetriableExtensionInstallCopyError:(error:unknown)=> boolean;listInstalledExtensions:(extensionsRoot:string,scope:ExtensionScope,settings:PmSettings,state:ManagedExtensionState)=> Promise<{extensions:ManagedExtensionSummary[];warnings:string[];}>;mapWithFixedConcurrency:<Input,Output>(inputs:Input[],concurrency:number,mapper:(input:Input)=> Promise<Output>)=> Promise<Output[]>;projectExtensionUpdateCheck:(entry:ManagedExtensionSummary|undefined)=>{update_check_status:string|null;update_check_reason:string|null;};readOptionalMetadataFile:(filePath:string)=> Promise<Buffer|null>;requireTarget:(target:string|undefined,action:ExtensionCommandAction,options?:ExtensionCommandOptions)=> string;resolveAction:(target:string|undefined,options:ExtensionCommandOptions)=> ExtensionCommandAction;resolveCommandDiscoveryPackageName:(extensionName:string,source:ManagedExtensionSource)=> string;resolveGithubOption:(options:ExtensionCommandOptions)=> string|undefined;resolveInstalledExtensionCandidate:(installed:ManagedExtensionSummary[],extensionTarget:string)=> Promise<ManagedExtensionSummary|undefined>;resolveManagedInstallTimestamps:(existing:ManagedExtensionRecord|undefined,manifestVersion:string,source:ManagedExtensionSource,now:string)=>{installed_at:string;updated_at:string;};resolveScope:(options:ExtensionCommandOptions)=> ExtensionScope;resolveUpdateCheckResolution:(managedEntry:ManagedExtensionRecord|undefined)=> ExtensionUpdateCheckResolution;withExtensionInstallLock:<T>(settingsRoot:string,destinationDirectoryName:string,run:()=> Promise<T>,options?:import("./extension/install-runtime.js").ExtensionInstallLockOptions)=> Promise<T>;};
241
+ export declare const _testOnly:{adoptUnmanagedExtensions:(extensionsRoot:string,scope:ExtensionScope,installedExtensions:ManagedExtensionSummary[],state:ManagedExtensionState)=> Promise<AdoptUnmanagedExtensionsResult>;buildAdoptedExtensionSource:(githubOption:string|undefined,extensionTarget:string,extensionDirectory:string,ref:string|undefined)=> ManagedExtensionSource;buildExtensionPolicyDetails:(policy:PmSettings["extensions"]["policy"]|null|undefined)=> ExtensionPolicyDetails;buildInstallCommandDiscovery:(extensionName:string,source:ManagedExtensionSource,commandSummary:{command_paths:string[];action_paths:string[];},activationFailure?:ActivationFailureDiagnostic)=> Record<string,unknown>;checkGithubUpdate:(source:ManagedExtensionSource,gitCommandRunner?:(args:string[],timeoutMs:number)=> Promise<string>,timeoutMs?:number)=> Promise<import("./extension/update-check.js").GithubUpdateStatus>;clearExtensionState:(settings:PmSettings,name:string)=> boolean;collectActivationFailureDiagnostics:(failures:ActivationFailureEntry[])=> ActivationFailureDiagnostic[];findActivationFailureByName:(extensionName:string,failures:ActivationFailureDiagnostic[],layer?:ExtensionScope)=> ActivationFailureDiagnostic|undefined;resolveInstallRuntimeActivationStatus:(extensionName:string,scope:ExtensionScope,runtimeInstalled:ManagedExtensionSummary[],installActivationFailure:ActivationFailureDiagnostic|undefined)=> ExtensionActivationStatus;collectGlobalOutputOverrideDoctorWarnings:typeof collectGlobalOutputOverrideDoctorWarnings;collectMcpCustomFieldCollisionDoctorWarnings:(activationResult:Awaited<ReturnType<typeof activateExtensions>>)=> string[];collectSchemaNarrowActivationDoctorWarnings:(loadResult:Awaited<ReturnType<typeof loadExtensions>>,activationResult:Awaited<ReturnType<typeof activateExtensions>>)=> string[];copyExtensionDirectoryWithoutSelfNesting:(sourceDirectory:string,destinationDirectory:string,copyDirectory:typeof fs.cp,temporaryDirectory?:string)=> Promise<void>;isErrnoCode:(error:unknown,code:string)=> boolean;isRetriableExtensionInstallCopyError:(error:unknown)=> boolean;listInstalledExtensions:(extensionsRoot:string,scope:ExtensionScope,settings:PmSettings,state:ManagedExtensionState)=> Promise<{extensions:ManagedExtensionSummary[];warnings:string[];}>;mapWithFixedConcurrency:<Input,Output>(inputs:Input[],concurrency:number,mapper:(input:Input)=> Promise<Output>)=> Promise<Output[]>;projectExtensionUpdateCheck:(entry:ManagedExtensionSummary|undefined)=>{update_check_status:string|null;update_check_reason:string|null;};readOptionalMetadataFile:(filePath:string)=> Promise<Buffer|null>;requireTarget:(target:string|undefined,action:ExtensionCommandAction,options?:ExtensionCommandOptions)=> string;resolveAction:(target:string|undefined,options:ExtensionCommandOptions)=> ExtensionCommandAction;resolveCommandDiscoveryPackageName:(extensionName:string,source:ManagedExtensionSource)=> string;resolveGithubOption:(options:ExtensionCommandOptions)=> string|undefined;resolveInstalledExtensionCandidate:(installed:ManagedExtensionSummary[],extensionTarget:string)=> Promise<ManagedExtensionSummary|undefined>;resolveManagedInstallTimestamps:(existing:ManagedExtensionRecord|undefined,manifestVersion:string,source:ManagedExtensionSource,now:string)=>{installed_at:string;updated_at:string;};resolveScope:(options:ExtensionCommandOptions)=> ExtensionScope;resolveUpdateCheckResolution:(managedEntry:ManagedExtensionRecord|undefined)=> ExtensionUpdateCheckResolution;withExtensionInstallLock:<T>(settingsRoot:string,destinationDirectoryName:string,run:()=> Promise<T>,options?:import("./extension/install-runtime.js").ExtensionInstallLockOptions)=> Promise<T>;};