@unbrained/pm-cli 2026.11.17 → 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 (124) 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-VLKCFZY6.js → chunk-4FNMPZ7Y.js} +2 -2
  5. package/dist/cli-bundle/chunks/chunk-723PMYNX.js +125 -0
  6. package/dist/cli-bundle/chunks/{chunk-77MGDTK4.js → chunk-AGPFANRX.js} +3 -3
  7. package/dist/cli-bundle/chunks/{chunk-RXNBNF6O.js → chunk-AMHD7WIV.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-7K2RUKMK.js → chunk-AOV5HG3Y.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-36R3JTAD.js → chunk-CNMGGAZO.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-XPBADEUK.js → chunk-CTOE26W4.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-FXSLODOK.js → chunk-GQCMICAL.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-ABFHWRLE.js → chunk-IQKCRLQP.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-QANUQMDL.js → chunk-IUTN67EB.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-M76BEWTT.js +31 -0
  15. package/dist/cli-bundle/chunks/{chunk-ADKDFCVT.js → chunk-N2CPCFSN.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-KIQNEOKJ.js → chunk-NMVPQTZI.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-XP35IEHT.js → chunk-O7IFAJ76.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-X5TFNFTS.js → chunk-OESI2ETD.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-ACLBUVQG.js → chunk-P4A5RFLX.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-QZNL5XDT.js → chunk-PRVT7ITI.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-O4ZSIMNC.js → chunk-Q32Q3LRH.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-DXSZL3T6.js → chunk-XPBPGDFW.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-4FIN2XWC.js → chunk-Z5LHCEXG.js} +2 -2
  24. package/dist/cli-bundle/chunks/{item-revision-7RVMVXTE.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-3PKQOAYK.js → mutation-admission-JLMQJ2M5.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-list-query-TPZLHFHQ.js → register-list-query-4AXLLXK7.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-mutation-JG5AEBRJ.js → register-mutation-FJIXGGF4.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-operations-3CNXP46P.js → register-operations-W4E2KEMA.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-setup-4N56VL2P.js → register-setup-RYRIBNSN.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-VBA4BIHN.js → chunk-2XULTI5B.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-2MQNIDKG.js → chunk-4S7I342K.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-GD2YWUAD.js → chunk-77CDWGBW.js} +55 -54
  34. package/dist/cli-bundle/focused-chunks/{chunk-BNLLST32.js → chunk-7A4VIRIU.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-SESMRMEE.js → chunk-D72EQN7Z.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-YWPLBFPC.js → chunk-GAOWBALE.js} +23 -23
  37. package/dist/cli-bundle/focused-chunks/chunk-N64BUB63.js +27 -0
  38. package/dist/cli-bundle/focused-chunks/{chunk-XJS4COL2.js → chunk-OF4UM5B6.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-6JQXDGHM.js → chunk-P4TG4VMJ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{item-revision-U7GDVAH7.js → item-revision-32HFGFYG.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{item-transaction-7C4BH47O.js → item-transaction-C4VW3SHX.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{mutation-admission-SKXVITP5.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 +58 -58
  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/fs/file-glob.js +2 -0
  53. package/dist/core/shared/process-tree.js +3 -0
  54. package/dist/core/shared/secret-rules.d.ts +94 -4
  55. package/dist/core/shared/secret-rules.js +5 -4
  56. package/dist/sdk/extension/managed-state.d.ts +3 -1
  57. package/dist/sdk/extension/managed-state.js +1 -1
  58. package/dist/sdk/extension/managed-update-status.js +1 -1
  59. package/dist/sdk/extension/update-check.d.ts +42 -6
  60. package/dist/sdk/extension/update-check.js +1 -1
  61. package/dist/sdk/extension.d.ts +3 -1
  62. package/dist/sdk/extension.js +1 -1
  63. package/dist/sdk/index.d.ts +1 -1
  64. package/dist/sdk/index.js +1 -1
  65. package/dist/sdk/linked-artifacts.js +2 -2
  66. package/dist/sdk/mutation-guard.d.ts +146 -5
  67. package/dist/sdk/mutation-guard.js +1 -1
  68. package/dist/sdk/public-surface.json +1 -1
  69. package/dist/sdk/test/execution.js +2 -2
  70. package/docs/COMMANDS.md +33 -0
  71. package/docs/CONFIGURATION.md +1 -0
  72. package/docs/DEFECT_RECURRENCE.md +3 -2
  73. package/docs/MUTATION_INTEGRITY.md +259 -7
  74. package/docs/PACKAGE_EVIDENCE.md +66 -0
  75. package/marketplace.json +1 -1
  76. package/package.json +1 -3
  77. package/packages/pm-beads/package.json +1 -1
  78. package/packages/pm-calendar/package.json +1 -1
  79. package/packages/pm-command-kit/package.json +1 -1
  80. package/packages/pm-digital-twin/package.json +1 -1
  81. package/packages/pm-governance-audit/package.json +1 -1
  82. package/packages/pm-guide-shell/package.json +1 -1
  83. package/packages/pm-kanban/package.json +1 -1
  84. package/packages/pm-lifecycle-hooks/package.json +1 -1
  85. package/packages/pm-linked-test-adapters/package.json +1 -1
  86. package/packages/pm-search-advanced/package.json +1 -1
  87. package/packages/pm-templates/package.json +1 -1
  88. package/packages/pm-todos/package.json +1 -1
  89. package/packages/pm-vcs/package.json +1 -1
  90. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  91. package/plugins/pm-claude/package.json +1 -1
  92. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  93. package/plugins/pm-codex/package.json +1 -1
  94. package/plugins/pm-codex/plugin.json +1 -1
  95. package/runtime-dependencies.json +1 -1
  96. package/dist/cli-bundle/chunks/chunk-2WHXFKMY.js +0 -31
  97. package/dist/cli-bundle/chunks/chunk-3IU2S5UQ.js +0 -70
  98. package/dist/cli-bundle/chunks/chunk-AM26RAG7.js +0 -124
  99. package/dist/cli-bundle/chunks/item-transaction-NVX6P3FK.js +0 -2
  100. package/dist/cli-bundle/focused-chunks/chunk-ZDY5L2C2.js +0 -26
  101. package/node_modules/fdir/LICENSE +0 -7
  102. package/node_modules/fdir/README.md +0 -91
  103. package/node_modules/fdir/dist/index.cjs +0 -588
  104. package/node_modules/fdir/dist/index.d.cts +0 -155
  105. package/node_modules/fdir/dist/index.d.mts +0 -155
  106. package/node_modules/fdir/dist/index.mjs +0 -570
  107. package/node_modules/fdir/package.json +0 -106
  108. package/node_modules/picomatch/LICENSE +0 -21
  109. package/node_modules/picomatch/README.md +0 -743
  110. package/node_modules/picomatch/index.js +0 -17
  111. package/node_modules/picomatch/lib/constants.js +0 -184
  112. package/node_modules/picomatch/lib/parse.js +0 -1425
  113. package/node_modules/picomatch/lib/picomatch.js +0 -361
  114. package/node_modules/picomatch/lib/scan.js +0 -403
  115. package/node_modules/picomatch/lib/utils.js +0 -72
  116. package/node_modules/picomatch/package.json +0 -83
  117. package/node_modules/picomatch/posix.js +0 -3
  118. package/node_modules/tinyglobby/LICENSE +0 -21
  119. package/node_modules/tinyglobby/README.md +0 -25
  120. package/node_modules/tinyglobby/dist/index.cjs +0 -335
  121. package/node_modules/tinyglobby/dist/index.d.cts +0 -148
  122. package/node_modules/tinyglobby/dist/index.d.mts +0 -148
  123. package/node_modules/tinyglobby/dist/index.mjs +0 -307
  124. package/node_modules/tinyglobby/package.json +0 -70
@@ -0,0 +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]="fa27dff5-0270-505f-bd5f-bc1eb0fe5ad8")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=path.isAbsolute(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(path.isAbsolute(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
2
+ //# sourceMappingURL=file-glob.js.map
@@ -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. */
@@ -54,10 +65,89 @@ rejectValue?:RegExp;
54
65
  /** Case-sensitive shape of an unquoted captured value that is a reference when a `;` ends its statement. */
55
66
  rejectStatementReference?:RegExp;
56
67
  /** Quoted-key, nested-container and element spellings judged by the same value grammar. */
57
- structured?:SecretStructuredSpelling;}
68
+ structured?:SecretStructuredSpelling;
69
+ /**
70
+ * Minimum length of the literal left in the captured value once every
71
+ * run-time reference expands to nothing (see {@link literalAfterReferences}).
72
+ * A reference is a placeholder only when it is the whole value. The literal,
73
+ * not the captured text, is then judged by the entropy and value predicates.
74
+ */
75
+ minimumLiteralLength?:number;
76
+ /**
77
+ * Sticky grammar that the literal a captured value spells must match whole,
78
+ * read as one double-quoted literal, when the captured text holds a
79
+ * reference opener or a quote (see {@link acceptsSecretMatch}). It lets a
80
+ * referenced value be judged by the same grammar as a reference-free one.
81
+ */
82
+ literalValue?:RegExp;
83
+ /**
84
+ * A narrower reading scanned as well: its own flat pattern and structured
85
+ * value grammar, with the same keys, judged on the captured text by the
86
+ * rule's value and entropy predicates but without the literal minimum or
87
+ * literal grammar, as the narrower rule always judged it. A value is a
88
+ * finding when either reading reports it, so widening `regex` and
89
+ * `structured.value` never drops a finding the narrower rule made, and
90
+ * every key the narrower scan visits is still visited (pm-hw00c2).
91
+ */
92
+ baseline?:SecretRuleReading;}
93
+ /** A flat pattern and the structured value grammar that go with it. */
94
+ export interface SecretRuleReading{
95
+ /** Global flat pattern, as {@link SecretRule.regex}. */
96
+ regex:RegExp;
97
+ /** Structured value grammar (regular-expression source), as {@link SecretStructuredSpelling.value}. */
98
+ value:string;}
58
99
  /** Canonical patterns; repository exemptions never exempt mutation payloads. */
59
- 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 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 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;}];
60
101
  /** Share matching and normalization, returning locations rather than matched values. */
61
102
  export declare function findSecretRuleMatches(rule:SecretRule,content:string):Generator<SecretRuleMatch>;
62
- /** Accept a pattern match, applying the declared entropy predicate when present. */
63
- export declare function acceptsSecretMatch(rule:SecretRule,match:RegExpMatchArray):boolean;
103
+ /**
104
+ * Where the references that lead a value end (`$($(cmd))`, `${A:-${B}}`,
105
+ * `$NAME`, `<x>`). An iterative scan, so no reference length can exhaust the
106
+ * regex backtrack stack and make the guard fail open; each character is read
107
+ * once.
108
+ */
109
+ declare function leadingReferencesEnd(text:string):number;
110
+ /**
111
+ * How a structured key spelling `"<name>":` reads for a key-named rule:
112
+ * `exact` when the key word is the whole name, `prefixed` when other key text
113
+ * precedes it, and undefined when the name does not end with one of the rule's
114
+ * keys. The same key pattern and shape check judge quoted keys in text, so a
115
+ * payload property and its JSON spelling read alike.
116
+ */
117
+ export declare function structuredKeyShape(rule:SecretRule,name:string):"exact"|"prefixed"|undefined;
118
+ /**
119
+ * Judge one string as a quoted structured value of a key-named rule, exactly
120
+ * as the structured pass judges a quoted value in text: `compact` for a
121
+ * prefixed key's value or an object member's value, lenient for an exact key's
122
+ * value or an array element.
123
+ */
124
+ export declare function acceptsStructuredValue(rule:SecretRule,value:string,compact:boolean):boolean;
125
+ /**
126
+ * Expand run-time references in data, such as a decoded literal or an element
127
+ * body, whose own quote characters are literal: `${NAME}`, `${NAME:?message}`,
128
+ * `$(command)`, a leading CONSTANT_CASE `$NAME` and `<placeholder>` contribute
129
+ * nothing (a value that is only one `$name` of any case spells nothing), and the default word of
130
+ * `${NAME:-word}` contributes its own expansion with the shell's quote removal
131
+ * (`${PW:-"x"}` contributes `x`; `${PW:-${FALLBACK}}` contributes nothing). A
132
+ * reference that never closes, and a `<` without a `>` before the next `<`,
133
+ * stay literal text. With `variables` false, `$NAME` text is always literal.
134
+ */
135
+ export declare function expandRuntimeReferences(text:string,variables?:boolean):string;
136
+ /**
137
+ * The literal a captured text value spells: references expand as in
138
+ * {@link expandRuntimeReferences}, and the quote characters that delimit each
139
+ * top-level quoted piece are removed, as a shell or configuration reader
140
+ * removes them; a quote of the other kind inside a piece is part of the
141
+ * literal. Both happen in the same pass, so a reference may hold quotes
142
+ * (`${PW:-""}`) and a default word's data quotes stay data.
143
+ */
144
+ export declare function literalAfterReferences(value:string,variables?:boolean):string;
145
+ /**
146
+ * Accept a pattern match, applying the declared literal-length, literal
147
+ * grammar, value and entropy predicates when present. A rule with a literal
148
+ * minimum judges the literal its value spells once references expand, so a
149
+ * reference never hides the literal around it and never counts as one.
150
+ */
151
+ export declare function acceptsSecretMatch(rule:SecretRule,match:RegExpMatchArray):boolean;
152
+ /** Internal scanners exposed for unit tests only; not part of any public surface. */
153
+ export declare const _testOnly:{leadingReferencesEnd:typeof leadingReferencesEnd;};export{};
@@ -1,5 +1,6 @@
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]="14a5d95f-9996-5e0a-a029-b53f3a2385e6")}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_VALUE=/(?:(?!<|\$\{|\$\(|config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))[A-Za-z0-9!@#$%^&*._+\-=]{8,}|"(?!<|\$\{|\$\()[^"]{8,}"|'(?!<|\$\{|\$\()[^']{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))",CREDENTIAL_VALUE=/(?:"(?=[^"\s]{8,}")|'(?=[^'\s]{8,}')|(?!["']))((?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.)+[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+)*|(?:[\w.-]+\/)+[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.)+[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+)*|(?:[\w.-]+\/)+[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+)*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.)+[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/)+[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8,}|(?<=')[^\s']{8,}|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,}))/,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}},{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:/\b[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,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}rule.regex.lastIndex=0;for(const match of content.matchAll(rule.regex))acceptsSecretMatch(rule,match)&&(yield{index:match.index});rule.structured&&(yield*findStructuredSpellingMatches(rule,rule.structured,content))}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,"iy"),...spelling.element?{element:new RegExp(String.raw`<(?:${spelling.keys})(?:\s[^<>]*)?>([^<]*)<\/(?:${spelling.keys})\s*>`,"gi")}:{}},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
- `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function decodeQuotedLiteral(literal,terminated){const quote=literal[0],neutral=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}).replaceAll(quote,quote==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," ");return`${quote}${neutral}${terminated?quote:""}`}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
- `||character==="\r"||character==='"'||character==="'")return"malformed"}return"malformed"}function createValueJudge(rule,value,content){const valueMatch=(text,at)=>{value.lastIndex=at;const match=value.exec(text);return match!==null&&!LINE_BREAK.test(match[0])&&acceptsSecretMatch(rule,match)?match:null},escapedMatches=at=>{if(content[at]!=='"'&&content[at]!=="'")return;const{end,terminated}=scanQuoted(content,at),literal=content.slice(at,end);return literal.includes("\\")?LINE_BREAK.test(literal)?[]:(content[at]==="'"?[decodeQuotedLiteral(literal,terminated),literal]:[decodeQuotedLiteral(literal,terminated)]).map(reading=>valueMatch(reading,0)).filter(match=>match!==null):void 0},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(match[0])))}}function*elementMatches(element,content,judge){element.lastIndex=0;for(const match of content.matchAll(element)){const value=match[1].trim();(judge?judge(value):value.length>=8&&!value.startsWith("${")&&!value.startsWith("$("))&&(yield{index:match.index})}}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)))}function elementValueJudge(rule,spelling,compiled){if(spelling.elementValue)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){const end=match.index+match[0].length,opener=match.input[end-match[1].length-1];return/^[ \t]*;/u.test(match.input.slice(end,end+64))&&opener!=='"'&&opener!=="'"&&shape.test(match[1])}function acceptsSecretMatch(rule,match){if(rule.rejectValue?.test(match[1])===!0||rule.rejectStatementReference&&isStatementReference(rule.rejectStatementReference,match))return!1;if(rule.minimumEntropy===void 0)return!0;const characters=[...match[1]],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}export{PRIVATE_HOME_PATH_PATTERN,SECRET_RULES,acceptsSecretMatch,findPrivateHomePathMatches,findSecretRuleMatches};
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
+ `,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
+ `||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
+ `?"":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};
5
6
  //# sourceMappingURL=secret-rules.js.map
@@ -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>;};