@unbrained/pm-cli 2026.11.27 → 2026.11.28

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 (176) 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-SIRZ4VMT.js → chunk-2YD2AERA.js} +2 -2
  4. package/dist/cli-bundle/chunks/{chunk-WY7467RY.js → chunk-54AQJTUH.js} +2 -2
  5. package/dist/cli-bundle/chunks/chunk-56DKWGHE.js +2 -0
  6. package/dist/cli-bundle/chunks/chunk-56GUDMXN.js +113 -0
  7. package/dist/cli-bundle/chunks/chunk-5ECCMDSU.js +2 -0
  8. package/dist/cli-bundle/chunks/chunk-6RBD2AKU.js +2 -0
  9. package/dist/cli-bundle/chunks/{chunk-O23KTJL6.js → chunk-C4O5TZY3.js} +46 -46
  10. package/dist/cli-bundle/chunks/chunk-CATRDGAB.js +125 -0
  11. package/dist/cli-bundle/chunks/{chunk-X6TE47CS.js → chunk-CDUV7DFD.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-CTM26LUE.js +4 -0
  13. package/dist/cli-bundle/chunks/chunk-D3I5AHNN.js +2 -0
  14. package/dist/cli-bundle/chunks/chunk-E2LQ6LCJ.js +2 -0
  15. package/dist/cli-bundle/chunks/{chunk-63AVXDZS.js → chunk-FG4TNQQM.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-JQYPSABI.js +2 -0
  17. package/dist/cli-bundle/chunks/chunk-LMDIKSDZ.js +9 -0
  18. package/dist/cli-bundle/chunks/chunk-LRGYV6QQ.js +2 -0
  19. package/dist/cli-bundle/chunks/chunk-MO6PPUI6.js +2 -0
  20. package/dist/cli-bundle/chunks/chunk-O2SWNEBW.js +8 -0
  21. package/dist/cli-bundle/chunks/{chunk-6NJ3BONB.js → chunk-O2WNNIKK.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-5CMR4R5V.js → chunk-OFIYA3PI.js} +3 -3
  23. package/dist/cli-bundle/chunks/{chunk-ZGV4ZXDS.js → chunk-Q6BGQRCB.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-RGE3XW3A.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-SP6CDM6B.js +31 -0
  26. package/dist/cli-bundle/chunks/{chunk-KS47NGMQ.js → chunk-T7RZPIOB.js} +14 -14
  27. package/dist/cli-bundle/chunks/{chunk-KP75JTTO.js → chunk-T7UTG56V.js} +4 -4
  28. package/dist/cli-bundle/chunks/chunk-TWRUA2NH.js +3 -0
  29. package/dist/cli-bundle/chunks/chunk-WKDKBS4P.js +4 -0
  30. package/dist/cli-bundle/chunks/chunk-YEMFOKFG.js +2 -0
  31. package/dist/cli-bundle/chunks/{chunk-Y5U7QCNX.js → chunk-YLS2N4SN.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-W7SPEGSP.js → chunk-ZXERHBMA.js} +2 -2
  33. package/dist/cli-bundle/chunks/field-definition-losses-JFMMMVTV.js +2 -0
  34. package/dist/cli-bundle/chunks/field-option-collisions-G4LQ2646.js +2 -0
  35. package/dist/cli-bundle/{focused-chunks/item-revision-NOHVIOQQ.js → chunks/item-revision-O7L3AA2W.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-transaction-4XC74ULD.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-A45DFDEO.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-SIUIMAEO.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-Q7UW2EPV.js → register-list-query-FCPGG2UT.js} +2 -2
  40. package/dist/cli-bundle/chunks/{register-mutation-YNW7E3T4.js → register-mutation-VD3JX23I.js} +2 -2
  41. package/dist/cli-bundle/chunks/register-operations-KHJD4GFZ.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-EWAZZWPL.js +2 -0
  43. package/dist/cli-bundle/chunks/runtime-schema-3RAXYNG5.js +2 -0
  44. package/dist/cli-bundle/chunks/{settlement-hook-ESAAEBRM.js → settlement-hook-KWBOSRDZ.js} +2 -2
  45. package/dist/cli-bundle/chunks/stage-UIDZMTE5.js +2 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-5MZXU6HB.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/chunk-64DSKZJN.js +100 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-N7ZAMULP.js → chunk-7EKKUYN5.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-7P6OGPEG.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-A5B43EWU.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-AHCOSTL7.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-CQLOYNJY.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-E4C6T3NL.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-GUAT4OAC.js → chunk-HCWDMFWA.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-AL47ODFZ.js → chunk-J4V3J5MC.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-JD45Y2BR.js +91 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-KMGI5GZP.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-MSLRDKWL.js +4 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-YPOATPTX.js → chunk-O33WUEAF.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-7FKGIJEB.js → chunk-OEMI52ZS.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-24W63UPP.js → chunk-Q6JCMFGU.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-RBOWKXFV.js +8 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-TF57RHS2.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-REORRDPH.js → chunk-VNU3IFBL.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/chunk-X5ZVPFK7.js +4 -0
  66. package/dist/cli-bundle/focused-chunks/{chunk-52PHSTGP.js → chunk-XVCMYFQU.js} +2 -2
  67. package/dist/cli-bundle/focused-chunks/{chunk-4HLZOOZI.js → chunk-Y7EC2L2G.js} +3 -3
  68. package/dist/cli-bundle/focused-chunks/{chunk-UGQ2EXTU.js → chunk-YC3PFFDE.js} +56 -56
  69. package/dist/cli-bundle/focused-chunks/{chunk-7GZMOLQY.js → chunk-YX75PQFO.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/{chunk-AN4NFFLL.js → chunk-Z4FWJGQG.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/chunk-ZHHFOQSL.js +44 -0
  72. package/dist/cli-bundle/focused-chunks/chunk-ZUAPUBJK.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/{chunk-HSWL6L2O.js → chunk-ZYHGQIQ7.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/field-definition-losses-NUZO3JCP.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/field-option-collisions-63YQ2J3N.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/item-revision-PV5O6F5Y.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/item-transaction-S5QXBGAT.js +2 -0
  78. package/dist/cli-bundle/{chunks/mutation-actor-SFYTD2ZB.js → focused-chunks/mutation-actor-2AAUJG2Z.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/mutation-admission-X7HHNERR.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/runtime-schema-5J2ONRNV.js +2 -0
  81. package/dist/cli-bundle/focused-chunks/stage-56RYPMBK.js +2 -0
  82. package/dist/cli-bundle/main.js +2 -2
  83. package/dist/cli-bundle/sdk-authoring.js +1 -1
  84. package/dist/cli-bundle/sdk-contracts.js +1 -1
  85. package/dist/cli-bundle/sdk-core.js +1 -1
  86. package/dist/cli-bundle/sdk-governance.js +1 -1
  87. package/dist/cli-bundle/sdk-graph.js +1 -1
  88. package/dist/cli-bundle/sdk-merge.js +63 -63
  89. package/dist/cli-bundle/sdk-query.js +1 -1
  90. package/dist/cli-bundle/sdk-runtime.js +1 -1
  91. package/dist/cli-bundle/sdk-testing.js +1 -1
  92. package/dist/cli-bundle/sdk.js +2 -2
  93. package/dist/core/extensions/item-fields.d.ts +15 -1
  94. package/dist/core/extensions/item-fields.js +1 -1
  95. package/dist/core/extensions/loader.js +1 -1
  96. package/dist/core/profile/profile-lint.js +1 -1
  97. package/dist/core/schema/runtime-schema.d.ts +20 -1
  98. package/dist/core/schema/runtime-schema.js +2 -2
  99. package/dist/sdk/agent/refusal-reachability.d.ts +1 -1
  100. package/dist/sdk/extension/command-options.d.ts +8 -0
  101. package/dist/sdk/extension/command-options.js +1 -1
  102. package/dist/sdk/extension-command-context.js +2 -2
  103. package/dist/sdk/governance/validate.js +1 -1
  104. package/dist/sdk/lifecycle/create.js +1 -1
  105. package/dist/sdk/lifecycle/update.js +2 -2
  106. package/dist/sdk/profile.js +1 -1
  107. package/dist/sdk/read-output-contracts.js +1 -1
  108. package/dist/sdk/schema/field-definition-losses.js +2 -0
  109. package/dist/sdk/schema/field-option-collisions.js +1 -1
  110. package/dist/sdk/schema.js +2 -2
  111. package/docs/COMMANDS.md +1 -1
  112. package/docs/CONFIGURATION.md +2 -0
  113. package/docs/EXTENSIONS.md +1 -1
  114. package/docs/SDK_AUDITED_MUTATIONS.md +12 -3
  115. package/marketplace.json +1 -1
  116. package/package.json +1 -1
  117. package/packages/pm-beads/package.json +1 -1
  118. package/packages/pm-calendar/package.json +1 -1
  119. package/packages/pm-command-kit/package.json +1 -1
  120. package/packages/pm-digital-twin/package.json +1 -1
  121. package/packages/pm-governance-audit/package.json +1 -1
  122. package/packages/pm-guide-shell/package.json +1 -1
  123. package/packages/pm-kanban/package.json +1 -1
  124. package/packages/pm-lifecycle-hooks/package.json +1 -1
  125. package/packages/pm-linked-test-adapters/package.json +1 -1
  126. package/packages/pm-search-advanced/package.json +1 -1
  127. package/packages/pm-templates/package.json +1 -1
  128. package/packages/pm-todos/package.json +1 -1
  129. package/packages/pm-vcs/package.json +1 -1
  130. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  131. package/plugins/pm-claude/package.json +1 -1
  132. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  133. package/plugins/pm-codex/package.json +1 -1
  134. package/plugins/pm-codex/plugin.json +1 -1
  135. package/runtime-dependencies.json +1 -1
  136. package/dist/cli-bundle/chunks/chunk-5M7UTO2G.js +0 -2
  137. package/dist/cli-bundle/chunks/chunk-66TNCHHG.js +0 -2
  138. package/dist/cli-bundle/chunks/chunk-AVHRMUXJ.js +0 -3
  139. package/dist/cli-bundle/chunks/chunk-HTT52JL3.js +0 -125
  140. package/dist/cli-bundle/chunks/chunk-J25DZRYJ.js +0 -31
  141. package/dist/cli-bundle/chunks/chunk-J6TFG34A.js +0 -4
  142. package/dist/cli-bundle/chunks/chunk-JX475QVU.js +0 -3
  143. package/dist/cli-bundle/chunks/chunk-OFX2VA5Z.js +0 -2
  144. package/dist/cli-bundle/chunks/chunk-QVDEZBSV.js +0 -8
  145. package/dist/cli-bundle/chunks/chunk-SX76UGEY.js +0 -3
  146. package/dist/cli-bundle/chunks/chunk-VC4BJIA7.js +0 -9
  147. package/dist/cli-bundle/chunks/chunk-XB6QEVUK.js +0 -2
  148. package/dist/cli-bundle/chunks/chunk-XYX4CXFR.js +0 -2
  149. package/dist/cli-bundle/chunks/chunk-YGK6SA7P.js +0 -2
  150. package/dist/cli-bundle/chunks/chunk-ZILIHDDY.js +0 -113
  151. package/dist/cli-bundle/chunks/field-option-collisions-UL6BIPAK.js +0 -2
  152. package/dist/cli-bundle/chunks/item-revision-WNUDY5DM.js +0 -2
  153. package/dist/cli-bundle/chunks/item-transaction-ER3OWOPV.js +0 -2
  154. package/dist/cli-bundle/chunks/mutation-admission-AVOOT3KH.js +0 -2
  155. package/dist/cli-bundle/chunks/register-operations-DAUTQCIO.js +0 -2
  156. package/dist/cli-bundle/chunks/register-setup-VSURGF7V.js +0 -2
  157. package/dist/cli-bundle/chunks/runtime-schema-Y4SHTEXL.js +0 -2
  158. package/dist/cli-bundle/chunks/stage-N5GDBS5A.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-2XGHBYDA.js +0 -44
  160. package/dist/cli-bundle/focused-chunks/chunk-3QRMY6KF.js +0 -2
  161. package/dist/cli-bundle/focused-chunks/chunk-B2HJI6KA.js +0 -2
  162. package/dist/cli-bundle/focused-chunks/chunk-C2HW7BSE.js +0 -2
  163. package/dist/cli-bundle/focused-chunks/chunk-GISZWMBS.js +0 -2
  164. package/dist/cli-bundle/focused-chunks/chunk-H4JBS477.js +0 -2
  165. package/dist/cli-bundle/focused-chunks/chunk-HGJ4MILN.js +0 -100
  166. package/dist/cli-bundle/focused-chunks/chunk-I4GY7HAP.js +0 -3
  167. package/dist/cli-bundle/focused-chunks/chunk-KMG4O2IU.js +0 -4
  168. package/dist/cli-bundle/focused-chunks/chunk-OCKKIECS.js +0 -3
  169. package/dist/cli-bundle/focused-chunks/chunk-SXWUKNTY.js +0 -8
  170. package/dist/cli-bundle/focused-chunks/chunk-ZZYJS74B.js +0 -91
  171. package/dist/cli-bundle/focused-chunks/field-option-collisions-BP7ILGQK.js +0 -2
  172. package/dist/cli-bundle/focused-chunks/item-transaction-O26COBOJ.js +0 -2
  173. package/dist/cli-bundle/focused-chunks/mutation-actor-HVJV5S76.js +0 -2
  174. package/dist/cli-bundle/focused-chunks/mutation-admission-JRICEVYN.js +0 -2
  175. package/dist/cli-bundle/focused-chunks/runtime-schema-YXPYDD2C.js +0 -2
  176. package/dist/cli-bundle/focused-chunks/stage-NSX6ASBZ.js +0 -2
@@ -1,2 +1,2 @@
1
- import{normalizeItemFieldType as _}from"./item-field-types.js";import{EXIT_CODE as f,ITEM_METADATA_KEY_ORDER as A}from"../shared/constants.js";import{PmCliError as l}from"../shared/errors.js";const c=new Set(A),u=Object.freeze({get size(){return c.size},has(e){return c.has(e)},entries(){return c.entries()},keys(){return c.keys()},values(){return c.values()},forEach(e,t){c.forEach(n=>e.call(t,n,n,u))},[Symbol.iterator](){return c.values()}});function h(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function y(e){return typeof e!="string"?null:_(e)}function w(e){try{return structuredClone(e)}catch{return e}}function E(e){const t=e.trim(),n=t.indexOf("=");if(n<=0)throw new l(`--field entries must use name=value syntax, received: ${e}`,f.USAGE);const i=t.slice(0,n).trim(),r=t.slice(n+1);return{key:i,value:r}}function b(e,t,n){try{const i=JSON.parse(e);if(n==="array"&&Array.isArray(i)||n==="object"&&typeof i=="object"&&i!==null&&!Array.isArray(i))return i}catch{}throw new l(`--field ${t}=... must be valid JSON ${n}`,f.USAGE)}function x(e,t,n){if(t==="string")return n;if(t==="number"){const i=n.trim();if(i.length===0)throw new l(`--field ${e}=... must be a number`,f.USAGE);const r=Number(i);if(!Number.isFinite(r))throw new l(`--field ${e}=... must be a number`,f.USAGE);return r}if(t==="boolean"){const i=n.trim().toLowerCase();if(i==="true"||i==="1"||i==="yes")return!0;if(i==="false"||i==="0"||i==="no")return!1;throw new l(`--field ${e}=... must be one of true|false|1|0|yes|no`,f.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(i=>i.trim()).filter(i=>i.length>0):b(n,e,t)}function p(e){const t=new Map;if(!e)return t;for(const n of e.item_fields)for(const i of n.fields){const r=h(i.name),o=y(i.type);if(!r||!o)continue;const s=t.get(r);if(s&&s.type!==o)throw new l(`Extension item field "${r}" is declared with conflicting types: ${s.type}, ${o}`,f.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(r,{name:r,type:o})}return t}function g(e){if(u.has(e))throw new l(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...u].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,f.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function U(e){return[...p(e).keys()].sort((t,n)=>t.localeCompare(n))}function j(e,t,n,i){if(!e||e.length===0)return{};const r=p(t),o={};for(const s of e){const{key:a,value:m}=E(s),d=r.get(a);if(!d)throw $(a,r,n,i);g(d.name),o[d.name]=x(d.name,d.type,m)}return o}function $(e,t,n,i){if(u.has(e)){const s=n?.(e)??{recovery:{provided_fields:[e]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new l(`--field ${e} is a core item field, not an extension field`,f.USAGE,{code:"core_item_field_requires_dedicated_flag",field:e,...s})}const r=i?.(e);if(r!==void 0){const s=r.recovery?.suggested_flags?.[0];return new l(s===void 0?`--field ${e} is a project-schema field, not an extension field`:`--field ${e} is a project-schema field; set it with its declared flag ${s}`,f.USAGE,{code:"project_schema_field_requires_declared_flag",field:e,changed:!1,...r})}const o=[...t.keys()].sort((s,a)=>s.localeCompare(a));return new l(`--field ${e} is not declared by an active extension item-field registration`,f.USAGE,{code:"extension_item_field_unknown",field:e,recovery:{provided_fields:[e]},nextSteps:o.length>0?[`Use one of the declared fields: ${o.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}function S(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(n=>typeof n=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function F(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function G(e,t,n={}){if(t){p(t);for(const i of t.item_fields)for(const r of i.fields){const o=h(r.name);if(!o)continue;g(o),!(o in e)&&!n.skipDefaultFields?.has(o)&&Object.prototype.hasOwnProperty.call(r,"default")&&(e[o]=w(r.default));const s=e[o];if(s===void 0)continue;const a=y(r.type);if(a&&!S(s,a))throw new TypeError(`Item field "${o}" must be of type ${a}`);const m=Array.isArray(r.values)?r.values:void 0;if(!F(s,m))throw new TypeError(`Item field "${o}" must match one of the configured allowed values`)}}}export{u as RESERVED_ITEM_FIELD_NAMES,G as applyRegisteredItemFieldDefaultsAndValidation,U as collectRegisteredItemFieldNames,j as parseRegisteredItemFieldAssignments};
1
+ import{normalizeItemFieldType as _}from"./item-field-types.js";import{EXIT_CODE as l,ITEM_METADATA_KEY_ORDER as A}from"../shared/constants.js";import{PmCliError as f}from"../shared/errors.js";const c=new Set(A),u=Object.freeze({get size(){return c.size},has(e){return c.has(e)},entries(){return c.entries()},keys(){return c.keys()},values(){return c.values()},forEach(e,t){c.forEach(n=>e.call(t,n,n,u))},[Symbol.iterator](){return c.values()}});function h(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function g(e){return typeof e!="string"?null:_(e)}function w(e){try{return structuredClone(e)}catch{return e}}function E(e){const t=e.trim(),n=t.indexOf("=");if(n<=0)throw new f(`--field entries must use name=value syntax, received: ${e}`,l.USAGE);const r=t.slice(0,n).trim(),i=t.slice(n+1);return{key:r,value:i}}function b(e,t,n){try{const r=JSON.parse(e);if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r}catch{}throw new f(`--field ${t}=... must be valid JSON ${n}`,l.USAGE)}function x(e,t,n){if(t==="string")return n;if(t==="number"){const r=n.trim();if(r.length===0)throw new f(`--field ${e}=... must be a number`,l.USAGE);const i=Number(r);if(!Number.isFinite(i))throw new f(`--field ${e}=... must be a number`,l.USAGE);return i}if(t==="boolean"){const r=n.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new f(`--field ${e}=... must be one of true|false|1|0|yes|no`,l.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):b(n,e,t)}function p(e){const t=new Map;if(!e)return t;for(const n of e.item_fields)for(const r of n.fields){const i=h(r.name),o=g(r.type);if(!i||!o)continue;const s=t.get(i);if(s&&s.type!==o)throw new f(`Extension item field "${i}" is declared with conflicting types: ${s.type}, ${o}`,l.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(i,{name:i,type:o})}return t}function y(e){if(u.has(e))throw new f(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...u].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,l.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function G(e,t,n){const r=t.replace(/^@[^/]+\//u,"").replaceAll(/[^A-Za-z0-9]+/gu,"_").toLowerCase();return`extension_item_field_reserved:${e}:${t}:${n}:rename=${r}_${n}`}function j(e){return[...p(e).keys()].sort((t,n)=>t.localeCompare(n))}function z(e,t,n,r){if(!e||e.length===0)return{};const i=p(t),o={};for(const s of e){const{key:a,value:m}=E(s),d=i.get(a);if(!d)throw $(a,i,n,r);y(d.name),o[d.name]=x(d.name,d.type,m)}return o}function $(e,t,n,r){if(u.has(e)){const s=n?.(e)??{recovery:{provided_fields:[e]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new f(`--field ${e} is a core item field, not an extension field`,l.USAGE,{code:"core_item_field_requires_dedicated_flag",field:e,...s})}const i=r?.(e);if(i!==void 0){const s=i.recovery?.suggested_flags?.[0];return new f(s===void 0?`--field ${e} is a project-schema field, not an extension field`:`--field ${e} is a project-schema field; set it with its declared flag ${s}`,l.USAGE,{code:"project_schema_field_requires_declared_flag",field:e,changed:!1,...i})}const o=[...t.keys()].sort((s,a)=>s.localeCompare(a));return new f(`--field ${e} is not declared by an active extension item-field registration`,l.USAGE,{code:"extension_item_field_unknown",field:e,recovery:{provided_fields:[e]},nextSteps:o.length>0?[`Use one of the declared fields: ${o.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}function F(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(n=>typeof n=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function S(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function I(e,t,n={}){if(t){p(t);for(const r of t.item_fields)for(const i of r.fields){const o=h(i.name);if(!o)continue;y(o),!(o in e)&&!n.skipDefaultFields?.has(o)&&Object.prototype.hasOwnProperty.call(i,"default")&&(e[o]=w(i.default));const s=e[o];if(s===void 0)continue;const a=g(i.type);if(a&&!F(s,a))throw new TypeError(`Item field "${o}" must be of type ${a}`);const m=Array.isArray(i.values)?i.values:void 0;if(!S(s,m))throw new TypeError(`Item field "${o}" must match one of the configured allowed values`)}}}function C(e,t,n={}){try{I(e,t,n)}catch(r){throw r instanceof f?r:new f(r.message,l.USAGE)}}export{u as RESERVED_ITEM_FIELD_NAMES,I as applyRegisteredItemFieldDefaultsAndValidation,C as applyRegisteredItemFieldDefaultsForWrite,j as collectRegisteredItemFieldNames,G as formatReservedItemFieldWarning,z as parseRegisteredItemFieldAssignments};
2
2
  //# sourceMappingURL=item-fields.js.map
@@ -1,2 +1,2 @@
1
- import w from"node:fs/promises";import x from"node:path";import{pathToFileURL as xe}from"node:url";import{createRelationshipKindRegistry as Ee}from"../../sdk/relationships.js";import{pathExists as H}from"../fs/fs-utils.js";import{isPathWithinDirectory as L}from"../fs/path-utils.js";import{isHostOutputSuppressed as be,suppressHostOutput as Ce}from"../output/output-control.js";import{resolvePmPackageRootFromModule as Re}from"../packages/root.js";import{asRecordLoose as B,resolveActivatablePropertyRecord as ke}from"../shared/primitives.js";import{resolveGlobalPmRoot as $e}from"../store/paths.js";import{captureExtensionActivationRollback as Pe}from"./activation-transaction.js";import{assertCommandDefinitionMetadataStrings as Se}from"./command-visibility-tier.js";import{normalizeExtensionReadOutput as Ie}from"./read-output-contract.js";import{normalizeExtensionContributionInventory as Me}from"./contribution-inventory.js";import{buildImportExportContext as U,resolveImportExportArtifactOutput as Ae}from"./exporter-output-contract.js";import{buildReadyExtensionCandidate as Te}from"./extension-candidate.js";import{collectUnknownExtensionCapabilities as De,formatLegacyExtensionCapabilityAliasWarning as Fe,formatUnknownExtensionCapabilityWarning as Oe,isKnownExtensionCapability as ze,normalizeNames as K}from"./extension-capability-aliases.js";import{evaluateExtensionPolicyForCapability as We,evaluateExtensionPolicyForExtension as je,evaluateExtensionPolicyForRegistration as Ne,hydrateExtensionPolicy as Ve,normalizeExtensionPolicy as qe,serializeExtensionPolicy as He}from"./extension-policy.js";import{createEmptyExtensionCommandRegistry as Le,createEmptyExtensionHookRegistry as Be,createEmptyExtensionParserRegistry as Ue,createEmptyExtensionPreflightRegistry as Ke,createEmptyExtensionRegistrationRegistry as Xe,createEmptyExtensionRendererRegistry as Ge,createEmptyExtensionServiceRegistry as Je}from"./extension-registries.js";import{normalizeCommandName as b}from"./extension-runtime-helpers.js";import{KNOWN_EXTENSION_CAPABILITIES as Ye,KNOWN_EXTENSION_SERVICE_NAMES as Qe,createDefaultExtensionGovernancePolicy as Ze}from"./extension-types.js";import{parseExtensionManifestDocument as X}from"./manifest-parser.js";import{formatExtensionManifestSchemaWarnings as er}from"./manifest-schema.js";import{snapshotExtensionModuleGraph as rr}from"./module-graph-snapshot.js";import{collectPreflightCollisionWarnings as tr,normalizePreflightOverride as nr}from"./preflight-ownership.js";import{applyProjectProfileDefaults as ir,assertFlagValueTypeAndDefault as sr,normalizeCommandDefinitionArguments as T,normalizeFlagDefinitions as D,resolveCommandDefinitionAction as F,validateFlagDefinitions as O,validateItemFieldDefinitions as G,validateItemTypeDefinitions as or,validateMigrationDefinition as ar,validateProjectProfileDefinition as mr}from"./registration-contracts.js";import{assertOptionalStringField as $,normalizeOptionalStringArrayField as C}from"./registration-validation.js";import{assertHookHandler as E,assertNonEmptyRegistrationString as P,assertRegistrationFunction as S,attachRuntimeDefinition as I,cloneRuntimeRegistrationValue as cr,createRegistrationValidationError as y,extractRegistrationValidationTrace as J,isExtensionServiceName as lr,isOutputRendererFormat as dr,normalizeRegistrationName as Y,normalizeRegistrationRecord as R,normalizeRegistrationRecordList as z,normalizeRuntimeRegistrationRecord as k,sanitizeRegistrationValue as Q,toRegistrationCommandPath as Z,validateAssuranceMeasurementProviderDefinition as ur}from"./registration-values.js";import{normalizeServiceOverrideOwnership as hr}from"./service-ownership.js";import{compareComparableVersions as pr,evaluatePmMaxVersionBound as fr,evaluatePmMinVersionBound as gr,parseComparableVersion as yr}from"./version-compat.js";import{parseLegacyExtensionCapabilityAliasWarning as wt,parseUnknownExtensionCapabilityWarning as xt}from"./extension-capability-aliases.js";import{createEmptyExtensionCommandRegistry as bt,createEmptyExtensionHookRegistry as Ct,createEmptyExtensionParserRegistry as Rt,createEmptyExtensionPreflightRegistry as kt,createEmptyExtensionRegistrationRegistry as $t,createEmptyExtensionRendererRegistry as Pt,createEmptyExtensionServiceRegistry as St}from"./extension-registries.js";import{runAfterCommandHooks as Mt,runBeforeCommandHooks as At,runBeforeMutationHooks as Tt,runCommandHandler as Dt,runCommandOverride as Ft,runOnIndexHooks as Ot,runOnReadHooks as zt,runOnWriteHooks as Wt,runParserOverride as jt,runPreflightOverride as Nt,runRendererOverride as Vt,runServiceOverride as qt,runServiceOverrideSync as Ht}from"./extension-hook-runtime.js";export*from"./extension-types.js";import{DEFAULT_EXTENSION_PRIORITY as Ut,parseExtensionManifestDocument as Kt}from"./manifest-parser.js";let W=null;const _r=Object.freeze(Ze());let ee=0;function vr(r=Date.now()){return ee+=1,`${ee}-${r}`}function wr(r,e,t){return t.has(r)?!1:e.size===0?!0:e.has(r)}async function xr(r,e){const[t,n]=await Promise.all([w.realpath(r),w.realpath(e)]);return L(t,n)}function Er(r,e=process.cwd()){return{global:x.join($e(e),"extensions"),project:x.join(r,"extensions")}}async function br(r){try{return(await w.readdir(r,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}catch{return[]}}function Cr(r){const e={layer:r.layer,directory:r.directory,manifest_path:r.manifest_path,name:r.manifest.name,version:r.manifest.version,entry:r.manifest.entry,priority:r.manifest.priority,entry_path:r.entry_path,manifest_version:r.manifest.manifest_version,pm_min_version:r.manifest.pm_min_version,pm_max_version:r.manifest.pm_max_version,engines:r.manifest.engines,trusted:r.manifest.trusted,provenance:r.manifest.provenance,sandbox_profile:r.manifest.sandbox_profile,permissions:r.manifest.permissions,capabilities:[...r.manifest.capabilities],activation:r.manifest.activation?{commands:[...r.manifest.activation.commands]}:void 0,contributions:r.manifest.contributions??r.contributions};return r.source_package&&(e.source_package=r.source_package),r.source_aliases&&(e.source_aliases=[...r.source_aliases]),e}function re(r){return typeof r=="string"&&r.trim().length>0?r.trim():void 0}async function te(r){const e=new Map;try{const t=JSON.parse(await w.readFile(x.join(r,".managed-extensions.json"),"utf8")),i=B(t)?.entries;if(!Array.isArray(i))return e;for(const o of i){if(typeof o!="object"||o===null)continue;const s=o,a=re(s.source?.package),m=[s.source?.input,s.source?.name,a].map(d=>re(d)).filter(d=>d!==void 0),c=Me(s.contributions),l={aliases:[...new Set(m)],...a?{package_name:a}:{},...c?{contributions:c}:{}};typeof s.directory=="string"&&s.directory.trim().length>0&&e.set(`directory:${s.directory.trim()}`,l),typeof s.name=="string"&&s.name.trim().length>0&&e.set(`name:${s.name.trim()}`,l)}}catch{return e}return e}function ne(r){return[...r].sort((e,t)=>{if(e.manifest.priority!==t.manifest.priority)return e.manifest.priority-t.manifest.priority;const n=e.manifest.name.localeCompare(t.manifest.name);return n!==0?n:e.directory.localeCompare(t.directory)})}function Rr(r,e){const t=[...ne(r),...ne(e)],n=[];for(const i of t){const o=n.findIndex(s=>s.manifest.name===i.manifest.name);o>=0&&n.splice(o,1),n.push(i)}return n}async function ie(r,e,t,n,i){const o=[],s=[],a=[],m=await br(e),c=await te(e);for(const l of m){const d=await Pr(r,e,l,t,n,c,i);o.push(d.diagnostic),s.push(...d.warnings),d.candidate&&a.push(d.candidate)}return{diagnostics:o,warnings:s,candidates:a}}function kr(){return{diagnostics:[],warnings:[],candidates:[]}}function se(r,e,t,n){return{diagnostic:{layer:r,directory:e,manifest_path:t,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[n],candidate:null}}function $r(r,e,t,n,i,o,s,a){const m=er(r,e,t);Array.isArray(e.legacy_capability_aliases)&&e.legacy_capability_aliases.length>0&&m.push(Fe(r,e.name,e.legacy_capability_aliases));for(const c of De(e.capabilities))m.push(Oe(r,e.name,c));return n?i||m.push(`extension_entry_missing:${r}:${e.name}`):m.push(`extension_entry_outside_extension:${r}:${e.name}`),o.warning&&m.push(a?o.warning:o.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&m.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),m}async function Pr(r,e,t,n,i,o,s){const a=x.join(e,t),m=x.join(a,"manifest.json");if(!await H(m))return se(r,t,m,`extension_manifest_missing:${r}:${t}`);let c,l;try{const q=JSON.parse(await w.readFile(m,"utf8"));l=B(q),c=X(q)}catch{l=null,c=null}if(!c||!l)return se(r,t,m,`extension_manifest_invalid:${r}:${t}`);const d=x.resolve(a,c.entry),h=L(a,d),u=h?await H(d):!1,f=h&&u?await xr(a,d):h,g=wr(c.name,n,i),v=await me(r,c),_=await ce(r,c,s),A=$r(r,c,l,f,u,v,_,g),V=f&&u&&v.allowed&&_.allowed,we=o.get(`directory:${t}`)??o.get(`name:${c.name}`);return{diagnostic:{layer:r,directory:t,manifest_path:m,name:c.name,version:c.version,entry:c.entry,priority:c.priority,entry_path:d,enabled:g,status:V?"ok":"warn"},warnings:A,candidate:Te({layer:r,directory:t,manifestPath:m,entryPath:d,manifest:c,sourceIdentity:we,extensionReady:V,enabledForLoad:g})}}async function Sr(r){const e=Er(r.pmRoot,r.cwd??process.cwd()),t=K(r.settings.extensions.enabled),n=K(r.settings.extensions.disabled),i=qe(r.settings),o=He(i);if(r.noExtensions)return{disabled_by_flag:!0,roots:e,configured_enabled:t,configured_disabled:n,discovered:[],effective:[],warnings:[...i.warnings],policy:o};const s=new Set(t),a=new Set(n),m=r.ignoreGlobalExtensions===!0?kr():await ie("global",e.global,s,a,i.pmMaxVersionExceededMode.global),c=await ie("project",e.project,s,a,i.pmMaxVersionExceededMode.project),l=[...i.warnings],d=Rr(m.candidates,c.candidates),h=[];for(const u of d){const f={layer:u.layer,name:u.manifest.name,trusted:u.manifest.trusted===!0,provenanceVerified:u.manifest.provenance?.verified===!0,sandboxProfile:u.manifest.sandbox_profile,permissions:u.manifest.permissions&&typeof u.manifest.permissions=="object"?{fs_read:u.manifest.permissions.fs_read,fs_write:u.manifest.permissions.fs_write,network:u.manifest.permissions.network,env_read:u.manifest.permissions.env_read,env_write:u.manifest.permissions.env_write,process_spawn:u.manifest.permissions.process_spawn}:void 0},g=je(i,f);if(g.warning&&l.push(g.warning),!!g.allowed){for(const v of u.manifest.capabilities){const _=We(i,f,v);_.warning&&l.push(_.warning)}h.push(Cr(u))}}return{disabled_by_flag:!1,roots:e,configured_enabled:t,configured_disabled:n,discovered:[...m.diagnostics,...c.diagnostics],effective:h,warnings:[...new Set([...m.warnings,...c.warnings,...l])],policy:o}}function M(r){return r instanceof Error&&r.message.trim().length>0?r.message:String(r)}async function oe(){try{const r=Re(import.meta.url,["../../.."]),e=await w.readFile(x.join(r,"package.json"),"utf8"),t=JSON.parse(e);return typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():null}catch{return null}}function j(){return W??=oe(),W}function ae(r,e,t){const n=t.current??"unknown";if(t.kind==="pm_min_version")switch(t.status){case"invalid":return`extension_pm_min_version_invalid:${r}:${e.name}:required=${t.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${r}:${e.name}:required=${t.required}:current=${n}`;case"unmet":return`extension_pm_min_version_unmet:${r}:${e.name}:required=${t.required}:current=${n}`;default:return}switch(t.status){case"invalid":return`extension_pm_max_version_invalid:${r}:${e.name}:allowed=${t.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${r}:${e.name}:allowed=${t.required}:current=${n}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${r}:${e.name}:allowed=${t.required}:current=${n}`;case"exceeded":return`extension_pm_max_version_exceeded:${r}:${e.name}:allowed=${t.required}:current=${n}`;default:return}}async function me(r,e){if(e.pm_min_version===void 0)return{allowed:!0};const t=gr(e.pm_min_version,await j()),n=ae(r,e,t);return n?{allowed:t.allowed,warning:n}:{allowed:t.allowed}}async function ce(r,e,t){if(e.pm_max_version===void 0)return{allowed:!0};const n=fr(e.pm_max_version,await j(),t),i=ae(r,e,n);return i?{allowed:n.allowed,warning:i}:{allowed:n.allowed}}async function N(r){try{const e=await w.stat(r);return`${Math.trunc(e.mtimeMs)}-${e.size}`}catch{return"missing"}}async function le(r,e){let t=r.entry_path;e.module_graph_snapshot_root&&(t=await rr(e.module_graph_snapshot_root,r));const n=new URL(xe(t).href);if(!(e.cache_bust===!0||typeof e.reload_token=="string"))return n.href;const[o,s]=await Promise.all([N(r.entry_path),N(r.manifest_path)]),a=e.reload_token??vr();return n.searchParams.set("pm_ext_reload",a),n.searchParams.set("pm_ext_entry",o),n.searchParams.set("pm_ext_manifest",s),n.href}async function pt(r){const e=await Sr(r),t=[],n=[],i=[...e.warnings];if(e.disabled_by_flag)return{...e,warnings:i,loaded:t,failed:n};const o=typeof r.extensionFilter=="function"?e.effective.filter(r.extensionFilter):e.effective;for(const s of o)try{const m=await import(await le(s,r));t.push({...s,module:m})}catch(a){i.push(`extension_load_failed:${s.layer}:${s.name}`),n.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:M(a)})}return{...e,warnings:i,loaded:t,failed:n}}const de=5e3,Ir=2147483647;function Mr(r){const t={activate:r.activate.bind(r)};if(typeof r.deactivate=="function"){const n=r.deactivate;t.deactivate=n.bind(r)}return t}function ue(r){const e=ke(r);return e?Mr(e):null}async function ft(r,e,t={}){const n=he(t?.deactivate_timeout_ms),i=new Set((e?.failed??[]).map(l=>`${l.layer}:${l.name}`)),o=[];for(const l of r.loaded){if(i.has(`${l.layer}:${l.name}`))continue;const d=ue(l.module);!d||typeof d.deactivate!="function"||o.push({extension:l,deactivate:d.deactivate})}const s=await Promise.all(o.map(async({extension:l,deactivate:d})=>{try{return await Ar(d,n),{ok:!0}}catch(h){return{ok:!1,layer:l.layer,name:l.name,error:M(h)}}})),a=[],m=[];let c=0;for(const l of s){if(l.ok){c+=1;continue}a.push(`extension_deactivate_failed:${l.layer}:${l.name}`),m.push({layer:l.layer,name:l.name,error:l.error})}return{deactivated:c,warnings:a,failed:m}}function he(r){return typeof r!="number"||r<0?de:r===0||r===1/0?0:Number.isFinite(r)?Math.min(Ir,Math.max(1,Math.floor(r))):de}async function Ar(r,e){if(e===0){await r();return}let t;try{const n=Promise.resolve().then(()=>r());n.catch(()=>{}),await Promise.race([n,new Promise((i,o)=>{t=setTimeout(()=>{o(new Error(`extension deactivate timed out after ${e}ms`))},e),t.unref?.()})])}finally{clearTimeout(t)}}function Tr(r){if(!Array.isArray(r.capabilities))return null;const e=new Set;for(const t of r.capabilities){const n=t.trim().toLowerCase();ze(n)&&e.add(n)}return e}function p(r,e,t){const n=Tr(r);if(n!==null&&!n.has(e))throw y(`${t} requires capability '${e}' in extension manifest capabilities`,{method:t,registration_index:-1,capability:e,missing_capability:e,expected_schema:`"capabilities": [..., "${e}"]`,received:r.capabilities,hint:`Add "${e}" to ${r.name} manifest capabilities, or remove the ${t} registration call.`})}function Dr(r){return Object.freeze({name:r.name,layer:r.layer,version:r.version,capabilities:Object.freeze((r.capabilities??[]).filter(e=>Ye.includes(e))),pm_min_version:r.pm_min_version,pm_max_version:r.pm_max_version,source_package:r.source_package})}function Fr(r){return{layer:r.layer,name:r.name,trusted:r.trusted===!0,provenanceVerified:r.provenance?.verified===!0,sandboxProfile:r.sandbox_profile,permissions:r.permissions&&typeof r.permissions=="object"?{fs_read:r.permissions.fs_read,fs_write:r.permissions.fs_write,network:r.permissions.network,env_read:r.permissions.env_read,env_write:r.permissions.env_write,process_spawn:r.permissions.process_spawn}:void 0}}class Or{extension;hooks;#e;#s;#t;#n;#o;#a;#m;#c;#r;#i;#l;#d;constructor(e,t,n,i,o,s,a,m,c,l,d){this.#e=e,this.extension=Dr(e),this.#s=Fr(e),this.#t=t,this.#n=n,this.#o=i,this.#a=o,this.#m=s,this.#c=a,this.#r=m,this.#i=c,this.#l=l,this.#d=d,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:h=>this.registerBeforeCommand(h),beforeMutation:h=>this.registerBeforeMutation(h),afterCommand:h=>this.registerAfterCommand(h),onWrite:h=>this.registerOnWrite(h),onRead:h=>this.registerOnRead(h),onIndex:h=>this.registerOnIndex(h)}}allowRegistration(e,t,n,i){const o=Ne(this.#d,this.#s,e,t,n,i);return o.warning&&this.#i.push(o.warning),o.allowed}registerCommandTrace(e,t,n,i,o){return{method:"registerCommand",registration_index:e==="override"?this.#n.overrides.length:this.#n.handlers.length,command:t,expected_schema:n,received:Q(i),hint:o}}registerCommandOverride(e,t){const n=b(e);if(n.length===0)throw y("registerCommand requires a non-empty command name",this.registerCommandTrace("override",e,'registerCommand("<command>", (context) => unknown)',e,"Provide a non-empty command path as the first argument."));if(typeof t!="function"){const i=this.registerCommandTrace("override",n,'registerCommand("<command>", (context) => unknown)',t,"Provide a function as the second registerCommand argument.");throw y(`registerCommand requires an override function when command name is provided (command="${n}", registration_index=${i.registration_index})`,i)}this.allowRegistration("commands.override","registerCommand","commands",{command:n})&&this.#n.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:t})}resolveCommandDefinitionRunHandler(e,t){const n=typeof e.run=="function"?e.run:void 0,i=typeof e.handler=="function"?e.handler:void 0;return!n&&i&&this.#i.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${t}`),n??i}registerCommandDefinition(e){if(typeof e!="object"||e===null)throw y("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",e,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof e.name!="string")throw y("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",e,"Set command definition.name to a non-empty string command path."));const t=b(e.name);if(t.length===0)throw y("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",e.name,"{ name: string; run: (context) => unknown; }",e,"Ensure command definition.name contains a non-empty command path."));const n=this.resolveCommandDefinitionRunHandler(e,t);if(typeof n!="function"){const i=this.registerCommandTrace("definition",t,"{ name: string; run: (context) => unknown; }",n,"Define command definition.run as a function.");throw y(`registerCommand requires a command definition run handler (command="${t}", registration_index=${i.registration_index})`,i)}try{Se(e);const i=F(t,e.action),o=Ie(e.read_output,t,i);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:t,action:i}))return;const s=e.description?.trim(),a=e.intent?.trim(),m=C("registerCommand definition.examples",e.examples),c=C("registerCommand definition.failure_hints",e.failure_hints),l=T(e.arguments);e.flags!==void 0&&(p(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(O(e.flags),this.#r.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:t,flags:D("registerCommand definition.flags",e.flags)})));const d={source_version:this.#e.version,read_output:o,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:t,action:i,examples:m,failure_hints:c,arguments:l,tier:e.tier??"standard",family:e.family??"extensions"};s&&(d.description=s),a&&(d.intent=a),this.#r.commands.push(d)}catch(i){const o=M(i),s=this.registerCommandTrace("definition",t,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",e,o),a=y(`registerCommand definition metadata invalid (command="${t}", registration_index=${s.registration_index}): ${o}`,s);this.#i.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${t}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:t,run:n})}registerCommand(e,t){if(p(this.#e,"commands","registerCommand"),typeof e=="string"){this.registerCommandOverride(e,t);return}this.registerCommandDefinition(e)}registerParser(e,t){if(p(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;const n=b(P("registerParser command",e));S("registerParser override",t),this.#o.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:t})}registerPreflight(e){if(p(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;const t=nr(e);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...t})}registerService(e,t,n={}){p(this.#e,"services","registerService");const i=String(e).trim().toLowerCase();if(!lr(i))throw new TypeError(`registerService service must be one of: ${Qe.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:i})&&(S("registerService override",t),this.#m.overrides.push({layer:this.#e.layer,name:this.#e.name,service:i,run:t,...hr(n)?{passThrough:!0}:{}}))}registerRenderer(e,t,n={}){if(p(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof t!="function")throw new TypeError("registerRenderer requires a renderer function");const i=String(e).trim().toLowerCase();if(!dr(i))throw new Error(`registerRenderer format must be toon|json, received: ${String(e)}`);if(n.resultDiscriminator!==void 0&&typeof n.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");const o=[...new Set((n.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return b(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:i,run:t,commands:o,...n.resultDiscriminator?{resultDiscriminator:n.resultDiscriminator}:{}})}registerFlags(e,t){if(p(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;const n=b(P("registerFlags targetCommand",e));O(t);const i=D("registerFlags flags",t);if(i.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#r.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:i})}registerItemFields(e){if(p(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;G(e);const t=z("registerItemFields fields",e);if(t.length===0)throw new TypeError("registerItemFields requires at least one field definition");this.#r.item_fields.push({layer:this.#e.layer,name:this.#e.name,fields:t})}registerItemTypes(e){if(p(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;or(e);const t=z("registerItemTypes types",e);if(t.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#r.item_types.push({layer:this.#e.layer,name:this.#e.name,types:t})}registerRelationshipKinds(e){if(p(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(e))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(e.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");const t=Ee();for(const i of this.#r.relationship_kinds)for(const o of i.definitions)t.register(o);const n=e.map(i=>(t.register(i),t.require(i.kind)));this.#r.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:n})}registerMigration(e){if(p(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;ar(e);const t=k("registerMigration definition",e);this.#r.migrations.push(I({layer:this.#e.layer,name:this.#e.name,definition:R("registerMigration definition",e)},t))}registerProfile(e){if(p(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;const t=cr(e);mr(t),this.#r.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:ir(t)})}registerImportExportCommandFlags(e,t,n){n.flags!==void 0&&(p(this.#e,"schema",`${e} options.flags`),this.allowRegistration("schema.flags",`${e} options.flags`,"schema")&&(O(n.flags),this.#r.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:t,flags:D(`${e} options.flags`,n.flags)})))}applyImportExportCommandMetadata(e,t,n){if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new TypeError(`${e} options must be an object when provided`);const i=`${e==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,o=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...n,description:n?.description??i,arguments:n?.arguments??o},a=Ae(e,s,n?.description!==void 0);$(`${e} options.action`,s.action),$(`${e} options.description`,s.description),$(`${e} options.intent`,s.intent);const m=F(t,s.action),c=C(`${e} options.examples`,s.examples),l=C(`${e} options.failure_hints`,s.failure_hints),d=T(s.arguments);this.registerImportExportCommandFlags(e,t,s);const h={source_version:this.#e.version,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:t,action:m,examples:c,failure_hints:l,arguments:d},u=s.description?.trim();u&&(h.description=u);const f=s.intent?.trim();return f&&(h.intent=f),this.#r.commands.push(h),a}registerImporter(e,t,n){if(p(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;const i=Y(P("registerImporter name",e));S("registerImporter importer",t);const o=Z(i,"import");this.applyImportExportCommandMetadata("registerImporter",o,n),this.#r.importers.push({layer:this.#e.layer,name:this.#e.name,importer:i}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:o,run:async s=>t(U(s,i,"import"))})}registerExporter(e,t,n){if(p(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;const i=Y(P("registerExporter name",e));S("registerExporter exporter",t);const o=Z(i,"export"),s=this.applyImportExportCommandMetadata("registerExporter",o,n);this.#r.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:i,...s===void 0?{}:{output:s}}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:o,run:async a=>{const m=await t(U(a,i,"export"));return s?.receipt==="suppress"&&!be(m)?Ce(m):m}})}registerSearchProvider(e){if(p(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;const t=k("registerSearchProvider provider",e);this.#r.search_providers.push(I({layer:this.#e.layer,name:this.#e.name,definition:R("registerSearchProvider provider",e)},t))}registerVectorStoreAdapter(e){if(p(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;const t=k("registerVectorStoreAdapter adapter",e);this.#r.vector_store_adapters.push(I({layer:this.#e.layer,name:this.#e.name,definition:R("registerVectorStoreAdapter adapter",e)},t))}registerAssuranceMeasurementProvider(e){if(p(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(ur(e),e.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");const t=k("registerAssuranceMeasurementProvider provider",e);this.#r.assurance_providers.push(I({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:R("registerAssuranceMeasurementProvider provider",e)},t))}registerBeforeCommand(e){p(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(E("beforeCommand",e),this.#t.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerBeforeMutation(e){p(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(E("beforeMutation",e),this.#t.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerAfterCommand(e){p(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(E("afterCommand",e),this.#t.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerOnWrite(e){p(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(E("onWrite",e),this.#t.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerOnRead(e){p(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(E("onRead",e),this.#t.onRead.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerOnIndex(e){p(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(E("onIndex",e),this.#t.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:e}))}}function pe(r,e,t,n,i,o,s,a,m,c,l){return new Or(r,e,t,n,i,o,s,a,m,c,l)}function fe(r){const e=r.commands.length,t=r.flags.reduce((s,a)=>s+a.flags.length,0),n=r.item_fields.reduce((s,a)=>s+a.fields.length,0),i=r.item_types.reduce((s,a)=>s+a.types.length,0),o=(r.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:e,flags:t,item_fields:n,item_types:i,...o>0?{relationship_kinds:o}:{},migrations:r.migrations.length,profiles:r.profiles.length,importers:r.importers.length,exporters:r.exporters.length,search_providers:r.search_providers.length,vector_store_adapters:r.vector_store_adapters.length,...(r.assurance_providers?.length??0)>0?{assurance_providers:r.assurance_providers.length}:{}}}function ge(r){const e=[],t=(o,s)=>{const a=new Map;for(const m of o){const c=a.get(m.command)??[];c.push(m),a.set(m.command,c)}for(const m of[...a.keys()].sort((c,l)=>c.localeCompare(l))){const c=a.get(m);if(c.length<=1)continue;const l=c[c.length-1];for(const d of c.slice(0,-1))e.push(`${s}:${m}:${l.layer}:${l.name}:${d.layer}:${d.name}`)}};t(r.handlers,"extension_command_handler_collision"),t(r.overrides,"extension_command_override_collision");const n=new Set(r.handlers.map(o=>o.command)),i=[...new Set(r.overrides.map(o=>o.command))].filter(o=>n.has(o));i.sort((o,s)=>o.localeCompare(s));for(const o of i){const s=r.handlers.filter(m=>m.command===o),a=r.overrides.filter(m=>m.command===o);for(const m of a)for(const c of s)e.push(`extension_command_override_handler_overlap:${o}:${m.layer}:${m.name}:${c.layer}:${c.name}`)}return e}function ye(r){const e=new Map;for(const n of r.overrides){const i=e.get(n.format)??[];i.push(n),e.set(n.format,i)}const t=[];for(const n of[...e.keys()].sort((i,o)=>i.localeCompare(o))){const i=e.get(n);if(i.length<=1)continue;const o=i[i.length-1];for(const s of i.slice(0,-1))o.commands?.length&&s.commands?.length&&!s.commands.some(a=>o.commands?.includes(a))||t.push(`extension_renderer_collision:${n}:${o.layer}:${o.name}:${s.layer}:${s.name}`)}return t}function _e(r){const e=[],t=new Map;for(const n of r.overrides){const i=t.get(n.command)??[];i.push(n),t.set(n.command,i)}for(const n of[...t.keys()].sort((i,o)=>i.localeCompare(o))){const i=t.get(n);if(i.length<=1)continue;const o=i[i.length-1];for(const s of i.slice(0,-1))e.push(`extension_parser_override_collision:${n}:${o.layer}:${o.name}:${s.layer}:${s.name}`)}return e}const zr=new Set(["output_format"]);function ve(r){const e=[],t=new Map;for(const n of r.overrides){const i=t.get(n.service)??[];i.push(n),t.set(n.service,i)}for(const n of[...t.keys()].sort((i,o)=>i.localeCompare(o))){const i=t.get(n);if(i.length<=1||zr.has(n))continue;const o=i[i.length-1];for(const s of i.slice(0,-1))e.push(`extension_service_override_collision:${n}:${o.layer}:${o.name}:${s.layer}:${s.name}`)}return e}async function gt(r){const e=Ve(r.policy??_r),t=Be(),n=Le(),i=Ue(),o=Ke(),s=Je(),a=Ge(),m=Xe(),c=[],l=[];for(const u of r.loaded){const f=ue(u.module);if(!f)continue;const g=c.length,v=Pe({hooks:t,commands:n,parsers:i,preflight:o,services:s,renderers:a,registrations:m});try{await f.activate(pe(u,t,n,i,o,s,a,m,l,c,e)),c.length>g&&(v(),l.push(`extension_activation_rolled_back:${u.layer}:${u.name}`))}catch(_){v(),l.push(`extension_activate_failed:${u.layer}:${u.name}`);const A=J(_);c.push({layer:u.layer,name:u.name,entry_path:u.entry_path,error:M(_),trace:A})}}const d=[...ge(n),..._e(i),...tr(o),...ve(s),...ye(a)],h=[...new Set([...l,...d])];return{hooks:t,commands:n,parsers:i,preflight:o,services:s,renderers:a,registrations:m,failed:c,warnings:h,hook_counts:{before_command:t.beforeCommand.length,before_mutation:t.beforeMutation.length,after_command:t.afterCommand.length,on_write:t.onWrite.length,on_read:t.onRead.length,on_index:t.onIndex.length},command_override_count:n.overrides.length,command_handler_count:n.handlers.length,parser_override_count:i.overrides.length,preflight_override_count:o.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:fe(m)}}const yt={assertFlagValueTypeAndDefault:sr,assertOptionalStringField:$,compareComparableVersions:pr,collectCommandCollisionWarnings:ge,collectParserCollisionWarnings:_e,collectRendererCollisionWarnings:ye,collectServiceCollisionWarnings:ve,createExtensionApi:pe,createRegistrationValidationError:y,evaluatePmMaxVersionCompatibility:ce,evaluatePmMinVersionCompatibility:me,extractRegistrationValidationTrace:J,fingerprintPath:N,getRegistrationCounts:fe,normalizeCommandDefinitionArguments:T,normalizeExtensionDeactivateTimeout:he,normalizeOptionalStringArrayField:C,normalizeRegistrationRecord:R,normalizeRegistrationRecordList:z,normalizeRuntimeRegistrationRecord:k,parseComparableVersion:yr,parseManifest:X,readCurrentPmCliVersion:oe,readManagedExtensionSourcePackages:async r=>new Map([...await te(r)].filter(e=>typeof e[1].package_name=="string").map(([e,t])=>[e,t.package_name])),resolveExtensionImportHref:le,resolveCurrentPmCliVersion:j,resolveCommandDefinitionAction:F,sanitizeRegistrationValue:Q,validateItemFieldDefinitions:G,resetCurrentPmCliVersionCacheForTest:()=>{W=null}};export{Ut as DEFAULT_EXTENSION_PRIORITY,yt as _testOnlyLoader,gt as activateExtensions,bt as createEmptyExtensionCommandRegistry,Ct as createEmptyExtensionHookRegistry,Rt as createEmptyExtensionParserRegistry,kt as createEmptyExtensionPreflightRegistry,$t as createEmptyExtensionRegistrationRegistry,Pt as createEmptyExtensionRendererRegistry,St as createEmptyExtensionServiceRegistry,ft as deactivateExtensions,Sr as discoverExtensions,xr as isCanonicalPathWithinDirectory,pt as loadExtensions,vr as nextExtensionReloadToken,Kt as parseExtensionManifestDocument,wt as parseLegacyExtensionCapabilityAliasWarning,xt as parseUnknownExtensionCapabilityWarning,Er as resolveExtensionRoots,Mt as runAfterCommandHooks,At as runBeforeCommandHooks,Tt as runBeforeMutationHooks,Dt as runCommandHandler,Ft as runCommandOverride,Ot as runOnIndexHooks,zt as runOnReadHooks,Wt as runOnWriteHooks,jt as runParserOverride,Nt as runPreflightOverride,Vt as runRendererOverride,qt as runServiceOverride,Ht as runServiceOverrideSync};
1
+ import w from"node:fs/promises";import x from"node:path";import{pathToFileURL as xe}from"node:url";import{createRelationshipKindRegistry as Ee}from"../../sdk/relationships.js";import{pathExists as H}from"../fs/fs-utils.js";import{isPathWithinDirectory as L}from"../fs/path-utils.js";import{isHostOutputSuppressed as be,suppressHostOutput as Ce}from"../output/output-control.js";import{resolvePmPackageRootFromModule as Re}from"../packages/root.js";import{asRecordLoose as B,resolveActivatablePropertyRecord as ke}from"../shared/primitives.js";import{resolveGlobalPmRoot as $e}from"../store/paths.js";import{captureExtensionActivationRollback as Pe}from"./activation-transaction.js";import{assertCommandDefinitionMetadataStrings as Se}from"./command-visibility-tier.js";import{normalizeExtensionReadOutput as Ie}from"./read-output-contract.js";import{normalizeExtensionContributionInventory as Me}from"./contribution-inventory.js";import{buildImportExportContext as U,resolveImportExportArtifactOutput as Ae}from"./exporter-output-contract.js";import{buildReadyExtensionCandidate as Te}from"./extension-candidate.js";import{collectUnknownExtensionCapabilities as De,formatLegacyExtensionCapabilityAliasWarning as Fe,formatUnknownExtensionCapabilityWarning as Oe,isKnownExtensionCapability as ze,normalizeNames as K}from"./extension-capability-aliases.js";import{evaluateExtensionPolicyForCapability as We,evaluateExtensionPolicyForExtension as Ne,evaluateExtensionPolicyForRegistration as je,hydrateExtensionPolicy as Ve,normalizeExtensionPolicy as qe,serializeExtensionPolicy as He}from"./extension-policy.js";import{createEmptyExtensionCommandRegistry as Le,createEmptyExtensionHookRegistry as Be,createEmptyExtensionParserRegistry as Ue,createEmptyExtensionPreflightRegistry as Ke,createEmptyExtensionRegistrationRegistry as Xe,createEmptyExtensionRendererRegistry as Ge,createEmptyExtensionServiceRegistry as Je}from"./extension-registries.js";import{normalizeCommandName as b}from"./extension-runtime-helpers.js";import{KNOWN_EXTENSION_CAPABILITIES as Ye,KNOWN_EXTENSION_SERVICE_NAMES as Qe,createDefaultExtensionGovernancePolicy as Ze}from"./extension-types.js";import{formatReservedItemFieldWarning as er,RESERVED_ITEM_FIELD_NAMES as rr}from"./item-fields.js";import{parseExtensionManifestDocument as X}from"./manifest-parser.js";import{formatExtensionManifestSchemaWarnings as tr}from"./manifest-schema.js";import{snapshotExtensionModuleGraph as nr}from"./module-graph-snapshot.js";import{collectPreflightCollisionWarnings as ir,normalizePreflightOverride as sr}from"./preflight-ownership.js";import{applyProjectProfileDefaults as or,assertFlagValueTypeAndDefault as ar,normalizeCommandDefinitionArguments as T,normalizeFlagDefinitions as D,resolveCommandDefinitionAction as F,validateFlagDefinitions as O,validateItemFieldDefinitions as G,validateItemTypeDefinitions as mr,validateMigrationDefinition as cr,validateProjectProfileDefinition as lr}from"./registration-contracts.js";import{assertOptionalStringField as $,normalizeOptionalStringArrayField as C}from"./registration-validation.js";import{assertHookHandler as E,assertNonEmptyRegistrationString as P,assertRegistrationFunction as S,attachRuntimeDefinition as I,cloneRuntimeRegistrationValue as dr,createRegistrationValidationError as y,extractRegistrationValidationTrace as J,isExtensionServiceName as ur,isOutputRendererFormat as hr,normalizeRegistrationName as Y,normalizeRegistrationRecord as R,normalizeRegistrationRecordList as z,normalizeRuntimeRegistrationRecord as k,sanitizeRegistrationValue as Q,toRegistrationCommandPath as Z,validateAssuranceMeasurementProviderDefinition as pr}from"./registration-values.js";import{normalizeServiceOverrideOwnership as fr}from"./service-ownership.js";import{compareComparableVersions as gr,evaluatePmMaxVersionBound as yr,evaluatePmMinVersionBound as _r,parseComparableVersion as vr}from"./version-compat.js";import{parseLegacyExtensionCapabilityAliasWarning as bt,parseUnknownExtensionCapabilityWarning as Ct}from"./extension-capability-aliases.js";import{createEmptyExtensionCommandRegistry as kt,createEmptyExtensionHookRegistry as $t,createEmptyExtensionParserRegistry as Pt,createEmptyExtensionPreflightRegistry as St,createEmptyExtensionRegistrationRegistry as It,createEmptyExtensionRendererRegistry as Mt,createEmptyExtensionServiceRegistry as At}from"./extension-registries.js";import{runAfterCommandHooks as Dt,runBeforeCommandHooks as Ft,runBeforeMutationHooks as Ot,runCommandHandler as zt,runCommandOverride as Wt,runOnIndexHooks as Nt,runOnReadHooks as jt,runOnWriteHooks as Vt,runParserOverride as qt,runPreflightOverride as Ht,runRendererOverride as Lt,runServiceOverride as Bt,runServiceOverrideSync as Ut}from"./extension-hook-runtime.js";export*from"./extension-types.js";import{DEFAULT_EXTENSION_PRIORITY as Gt,parseExtensionManifestDocument as Jt}from"./manifest-parser.js";let W=null;const wr=Object.freeze(Ze());let ee=0;function xr(r=Date.now()){return ee+=1,`${ee}-${r}`}function Er(r,e,t){return t.has(r)?!1:e.size===0?!0:e.has(r)}async function br(r,e){const[t,n]=await Promise.all([w.realpath(r),w.realpath(e)]);return L(t,n)}function Cr(r,e=process.cwd()){return{global:x.join($e(e),"extensions"),project:x.join(r,"extensions")}}async function Rr(r){try{return(await w.readdir(r,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}catch{return[]}}function kr(r){const e={layer:r.layer,directory:r.directory,manifest_path:r.manifest_path,name:r.manifest.name,version:r.manifest.version,entry:r.manifest.entry,priority:r.manifest.priority,entry_path:r.entry_path,manifest_version:r.manifest.manifest_version,pm_min_version:r.manifest.pm_min_version,pm_max_version:r.manifest.pm_max_version,engines:r.manifest.engines,trusted:r.manifest.trusted,provenance:r.manifest.provenance,sandbox_profile:r.manifest.sandbox_profile,permissions:r.manifest.permissions,capabilities:[...r.manifest.capabilities],activation:r.manifest.activation?{commands:[...r.manifest.activation.commands]}:void 0,contributions:r.manifest.contributions??r.contributions};return r.source_package&&(e.source_package=r.source_package),r.source_aliases&&(e.source_aliases=[...r.source_aliases]),e}function re(r){return typeof r=="string"&&r.trim().length>0?r.trim():void 0}async function te(r){const e=new Map;try{const t=JSON.parse(await w.readFile(x.join(r,".managed-extensions.json"),"utf8")),i=B(t)?.entries;if(!Array.isArray(i))return e;for(const o of i){if(typeof o!="object"||o===null)continue;const s=o,a=re(s.source?.package),m=[s.source?.input,s.source?.name,a].map(d=>re(d)).filter(d=>d!==void 0),c=Me(s.contributions),l={aliases:[...new Set(m)],...a?{package_name:a}:{},...c?{contributions:c}:{}};typeof s.directory=="string"&&s.directory.trim().length>0&&e.set(`directory:${s.directory.trim()}`,l),typeof s.name=="string"&&s.name.trim().length>0&&e.set(`name:${s.name.trim()}`,l)}}catch{return e}return e}function ne(r){return[...r].sort((e,t)=>{if(e.manifest.priority!==t.manifest.priority)return e.manifest.priority-t.manifest.priority;const n=e.manifest.name.localeCompare(t.manifest.name);return n!==0?n:e.directory.localeCompare(t.directory)})}function $r(r,e){const t=[...ne(r),...ne(e)],n=[];for(const i of t){const o=n.findIndex(s=>s.manifest.name===i.manifest.name);o>=0&&n.splice(o,1),n.push(i)}return n}async function ie(r,e,t,n,i){const o=[],s=[],a=[],m=await Rr(e),c=await te(e);for(const l of m){const d=await Ir(r,e,l,t,n,c,i);o.push(d.diagnostic),s.push(...d.warnings),d.candidate&&a.push(d.candidate)}return{diagnostics:o,warnings:s,candidates:a}}function Pr(){return{diagnostics:[],warnings:[],candidates:[]}}function se(r,e,t,n){return{diagnostic:{layer:r,directory:e,manifest_path:t,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[n],candidate:null}}function Sr(r,e,t,n,i,o,s,a){const m=tr(r,e,t);Array.isArray(e.legacy_capability_aliases)&&e.legacy_capability_aliases.length>0&&m.push(Fe(r,e.name,e.legacy_capability_aliases));for(const c of De(e.capabilities))m.push(Oe(r,e.name,c));return n?i||m.push(`extension_entry_missing:${r}:${e.name}`):m.push(`extension_entry_outside_extension:${r}:${e.name}`),o.warning&&m.push(a?o.warning:o.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&m.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),m}async function Ir(r,e,t,n,i,o,s){const a=x.join(e,t),m=x.join(a,"manifest.json");if(!await H(m))return se(r,t,m,`extension_manifest_missing:${r}:${t}`);let c,l;try{const q=JSON.parse(await w.readFile(m,"utf8"));l=B(q),c=X(q)}catch{l=null,c=null}if(!c||!l)return se(r,t,m,`extension_manifest_invalid:${r}:${t}`);const d=x.resolve(a,c.entry),h=L(a,d),u=h?await H(d):!1,f=h&&u?await br(a,d):h,g=Er(c.name,n,i),v=await me(r,c),_=await ce(r,c,s),A=Sr(r,c,l,f,u,v,_,g),V=f&&u&&v.allowed&&_.allowed,we=o.get(`directory:${t}`)??o.get(`name:${c.name}`);return{diagnostic:{layer:r,directory:t,manifest_path:m,name:c.name,version:c.version,entry:c.entry,priority:c.priority,entry_path:d,enabled:g,status:V?"ok":"warn"},warnings:A,candidate:Te({layer:r,directory:t,manifestPath:m,entryPath:d,manifest:c,sourceIdentity:we,extensionReady:V,enabledForLoad:g})}}async function Mr(r){const e=Cr(r.pmRoot,r.cwd??process.cwd()),t=K(r.settings.extensions.enabled),n=K(r.settings.extensions.disabled),i=qe(r.settings),o=He(i);if(r.noExtensions)return{disabled_by_flag:!0,roots:e,configured_enabled:t,configured_disabled:n,discovered:[],effective:[],warnings:[...i.warnings],policy:o};const s=new Set(t),a=new Set(n),m=r.ignoreGlobalExtensions===!0?Pr():await ie("global",e.global,s,a,i.pmMaxVersionExceededMode.global),c=await ie("project",e.project,s,a,i.pmMaxVersionExceededMode.project),l=[...i.warnings],d=$r(m.candidates,c.candidates),h=[];for(const u of d){const f={layer:u.layer,name:u.manifest.name,trusted:u.manifest.trusted===!0,provenanceVerified:u.manifest.provenance?.verified===!0,sandboxProfile:u.manifest.sandbox_profile,permissions:u.manifest.permissions&&typeof u.manifest.permissions=="object"?{fs_read:u.manifest.permissions.fs_read,fs_write:u.manifest.permissions.fs_write,network:u.manifest.permissions.network,env_read:u.manifest.permissions.env_read,env_write:u.manifest.permissions.env_write,process_spawn:u.manifest.permissions.process_spawn}:void 0},g=Ne(i,f);if(g.warning&&l.push(g.warning),!!g.allowed){for(const v of u.manifest.capabilities){const _=We(i,f,v);_.warning&&l.push(_.warning)}h.push(kr(u))}}return{disabled_by_flag:!1,roots:e,configured_enabled:t,configured_disabled:n,discovered:[...m.diagnostics,...c.diagnostics],effective:h,warnings:[...new Set([...m.warnings,...c.warnings,...l])],policy:o}}function M(r){return r instanceof Error&&r.message.trim().length>0?r.message:String(r)}async function oe(){try{const r=Re(import.meta.url,["../../.."]),e=await w.readFile(x.join(r,"package.json"),"utf8"),t=JSON.parse(e);return typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():null}catch{return null}}function N(){return W??=oe(),W}function ae(r,e,t){const n=t.current??"unknown";if(t.kind==="pm_min_version")switch(t.status){case"invalid":return`extension_pm_min_version_invalid:${r}:${e.name}:required=${t.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${r}:${e.name}:required=${t.required}:current=${n}`;case"unmet":return`extension_pm_min_version_unmet:${r}:${e.name}:required=${t.required}:current=${n}`;default:return}switch(t.status){case"invalid":return`extension_pm_max_version_invalid:${r}:${e.name}:allowed=${t.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${r}:${e.name}:allowed=${t.required}:current=${n}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${r}:${e.name}:allowed=${t.required}:current=${n}`;case"exceeded":return`extension_pm_max_version_exceeded:${r}:${e.name}:allowed=${t.required}:current=${n}`;default:return}}async function me(r,e){if(e.pm_min_version===void 0)return{allowed:!0};const t=_r(e.pm_min_version,await N()),n=ae(r,e,t);return n?{allowed:t.allowed,warning:n}:{allowed:t.allowed}}async function ce(r,e,t){if(e.pm_max_version===void 0)return{allowed:!0};const n=yr(e.pm_max_version,await N(),t),i=ae(r,e,n);return i?{allowed:n.allowed,warning:i}:{allowed:n.allowed}}async function j(r){try{const e=await w.stat(r);return`${Math.trunc(e.mtimeMs)}-${e.size}`}catch{return"missing"}}async function le(r,e){let t=r.entry_path;e.module_graph_snapshot_root&&(t=await nr(e.module_graph_snapshot_root,r));const n=new URL(xe(t).href);if(!(e.cache_bust===!0||typeof e.reload_token=="string"))return n.href;const[o,s]=await Promise.all([j(r.entry_path),j(r.manifest_path)]),a=e.reload_token??xr();return n.searchParams.set("pm_ext_reload",a),n.searchParams.set("pm_ext_entry",o),n.searchParams.set("pm_ext_manifest",s),n.href}async function yt(r){const e=await Mr(r),t=[],n=[],i=[...e.warnings];if(e.disabled_by_flag)return{...e,warnings:i,loaded:t,failed:n};const o=typeof r.extensionFilter=="function"?e.effective.filter(r.extensionFilter):e.effective;for(const s of o)try{const m=await import(await le(s,r));t.push({...s,module:m})}catch(a){i.push(`extension_load_failed:${s.layer}:${s.name}`),n.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:M(a)})}return{...e,warnings:i,loaded:t,failed:n}}const de=5e3,Ar=2147483647;function Tr(r){const t={activate:r.activate.bind(r)};if(typeof r.deactivate=="function"){const n=r.deactivate;t.deactivate=n.bind(r)}return t}function ue(r){const e=ke(r);return e?Tr(e):null}async function _t(r,e,t={}){const n=he(t?.deactivate_timeout_ms),i=new Set((e?.failed??[]).map(l=>`${l.layer}:${l.name}`)),o=[];for(const l of r.loaded){if(i.has(`${l.layer}:${l.name}`))continue;const d=ue(l.module);!d||typeof d.deactivate!="function"||o.push({extension:l,deactivate:d.deactivate})}const s=await Promise.all(o.map(async({extension:l,deactivate:d})=>{try{return await Dr(d,n),{ok:!0}}catch(h){return{ok:!1,layer:l.layer,name:l.name,error:M(h)}}})),a=[],m=[];let c=0;for(const l of s){if(l.ok){c+=1;continue}a.push(`extension_deactivate_failed:${l.layer}:${l.name}`),m.push({layer:l.layer,name:l.name,error:l.error})}return{deactivated:c,warnings:a,failed:m}}function he(r){return typeof r!="number"||r<0?de:r===0||r===1/0?0:Number.isFinite(r)?Math.min(Ar,Math.max(1,Math.floor(r))):de}async function Dr(r,e){if(e===0){await r();return}let t;try{const n=Promise.resolve().then(()=>r());n.catch(()=>{}),await Promise.race([n,new Promise((i,o)=>{t=setTimeout(()=>{o(new Error(`extension deactivate timed out after ${e}ms`))},e),t.unref?.()})])}finally{clearTimeout(t)}}function Fr(r){if(!Array.isArray(r.capabilities))return null;const e=new Set;for(const t of r.capabilities){const n=t.trim().toLowerCase();ze(n)&&e.add(n)}return e}function p(r,e,t){const n=Fr(r);if(n!==null&&!n.has(e))throw y(`${t} requires capability '${e}' in extension manifest capabilities`,{method:t,registration_index:-1,capability:e,missing_capability:e,expected_schema:`"capabilities": [..., "${e}"]`,received:r.capabilities,hint:`Add "${e}" to ${r.name} manifest capabilities, or remove the ${t} registration call.`})}function Or(r){return Object.freeze({name:r.name,layer:r.layer,version:r.version,capabilities:Object.freeze((r.capabilities??[]).filter(e=>Ye.includes(e))),pm_min_version:r.pm_min_version,pm_max_version:r.pm_max_version,source_package:r.source_package})}function zr(r){return{layer:r.layer,name:r.name,trusted:r.trusted===!0,provenanceVerified:r.provenance?.verified===!0,sandboxProfile:r.sandbox_profile,permissions:r.permissions&&typeof r.permissions=="object"?{fs_read:r.permissions.fs_read,fs_write:r.permissions.fs_write,network:r.permissions.network,env_read:r.permissions.env_read,env_write:r.permissions.env_write,process_spawn:r.permissions.process_spawn}:void 0}}class Wr{extension;hooks;#e;#s;#t;#n;#o;#a;#m;#c;#r;#i;#l;#d;constructor(e,t,n,i,o,s,a,m,c,l,d){this.#e=e,this.extension=Or(e),this.#s=zr(e),this.#t=t,this.#n=n,this.#o=i,this.#a=o,this.#m=s,this.#c=a,this.#r=m,this.#i=c,this.#l=l,this.#d=d,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:h=>this.registerBeforeCommand(h),beforeMutation:h=>this.registerBeforeMutation(h),afterCommand:h=>this.registerAfterCommand(h),onWrite:h=>this.registerOnWrite(h),onRead:h=>this.registerOnRead(h),onIndex:h=>this.registerOnIndex(h)}}allowRegistration(e,t,n,i){const o=je(this.#d,this.#s,e,t,n,i);return o.warning&&this.#i.push(o.warning),o.allowed}registerCommandTrace(e,t,n,i,o){return{method:"registerCommand",registration_index:e==="override"?this.#n.overrides.length:this.#n.handlers.length,command:t,expected_schema:n,received:Q(i),hint:o}}registerCommandOverride(e,t){const n=b(e);if(n.length===0)throw y("registerCommand requires a non-empty command name",this.registerCommandTrace("override",e,'registerCommand("<command>", (context) => unknown)',e,"Provide a non-empty command path as the first argument."));if(typeof t!="function"){const i=this.registerCommandTrace("override",n,'registerCommand("<command>", (context) => unknown)',t,"Provide a function as the second registerCommand argument.");throw y(`registerCommand requires an override function when command name is provided (command="${n}", registration_index=${i.registration_index})`,i)}this.allowRegistration("commands.override","registerCommand","commands",{command:n})&&this.#n.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:t})}resolveCommandDefinitionRunHandler(e,t){const n=typeof e.run=="function"?e.run:void 0,i=typeof e.handler=="function"?e.handler:void 0;return!n&&i&&this.#i.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${t}`),n??i}registerCommandDefinition(e){if(typeof e!="object"||e===null)throw y("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",e,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof e.name!="string")throw y("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",e,"Set command definition.name to a non-empty string command path."));const t=b(e.name);if(t.length===0)throw y("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",e.name,"{ name: string; run: (context) => unknown; }",e,"Ensure command definition.name contains a non-empty command path."));const n=this.resolveCommandDefinitionRunHandler(e,t);if(typeof n!="function"){const i=this.registerCommandTrace("definition",t,"{ name: string; run: (context) => unknown; }",n,"Define command definition.run as a function.");throw y(`registerCommand requires a command definition run handler (command="${t}", registration_index=${i.registration_index})`,i)}try{Se(e);const i=F(t,e.action),o=Ie(e.read_output,t,i);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:t,action:i}))return;const s=e.description?.trim(),a=e.intent?.trim(),m=C("registerCommand definition.examples",e.examples),c=C("registerCommand definition.failure_hints",e.failure_hints),l=T(e.arguments);e.flags!==void 0&&(p(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(O(e.flags),this.#r.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:t,flags:D("registerCommand definition.flags",e.flags)})));const d={source_version:this.#e.version,read_output:o,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:t,action:i,examples:m,failure_hints:c,arguments:l,tier:e.tier??"standard",family:e.family??"extensions"};s&&(d.description=s),a&&(d.intent=a),this.#r.commands.push(d)}catch(i){const o=M(i),s=this.registerCommandTrace("definition",t,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",e,o),a=y(`registerCommand definition metadata invalid (command="${t}", registration_index=${s.registration_index}): ${o}`,s);this.#i.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${t}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:t,run:n})}registerCommand(e,t){if(p(this.#e,"commands","registerCommand"),typeof e=="string"){this.registerCommandOverride(e,t);return}this.registerCommandDefinition(e)}registerParser(e,t){if(p(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;const n=b(P("registerParser command",e));S("registerParser override",t),this.#o.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:t})}registerPreflight(e){if(p(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;const t=sr(e);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...t})}registerService(e,t,n={}){p(this.#e,"services","registerService");const i=String(e).trim().toLowerCase();if(!ur(i))throw new TypeError(`registerService service must be one of: ${Qe.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:i})&&(S("registerService override",t),this.#m.overrides.push({layer:this.#e.layer,name:this.#e.name,service:i,run:t,...fr(n)?{passThrough:!0}:{}}))}registerRenderer(e,t,n={}){if(p(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof t!="function")throw new TypeError("registerRenderer requires a renderer function");const i=String(e).trim().toLowerCase();if(!hr(i))throw new Error(`registerRenderer format must be toon|json, received: ${String(e)}`);if(n.resultDiscriminator!==void 0&&typeof n.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");const o=[...new Set((n.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return b(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:i,run:t,commands:o,...n.resultDiscriminator?{resultDiscriminator:n.resultDiscriminator}:{}})}registerFlags(e,t){if(p(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;const n=b(P("registerFlags targetCommand",e));O(t);const i=D("registerFlags flags",t);if(i.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#r.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:i})}registerItemFields(e){if(p(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;G(e);const t=z("registerItemFields fields",e);if(t.length===0)throw new TypeError("registerItemFields requires at least one field definition");const{layer:n,name:i}=this.#e,o=t.filter(s=>{const a=typeof s.name=="string"?s.name.trim():"";return rr.has(a)?(this.#i.push(er(n,i,a)),!1):!0});this.#r.item_fields.push({layer:n,name:i,fields:o})}registerItemTypes(e){if(p(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;mr(e);const t=z("registerItemTypes types",e);if(t.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#r.item_types.push({layer:this.#e.layer,name:this.#e.name,types:t})}registerRelationshipKinds(e){if(p(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(e))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(e.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");const t=Ee();for(const i of this.#r.relationship_kinds)for(const o of i.definitions)t.register(o);const n=e.map(i=>(t.register(i),t.require(i.kind)));this.#r.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:n})}registerMigration(e){if(p(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;cr(e);const t=k("registerMigration definition",e);this.#r.migrations.push(I({layer:this.#e.layer,name:this.#e.name,definition:R("registerMigration definition",e)},t))}registerProfile(e){if(p(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;const t=dr(e);lr(t),this.#r.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:or(t)})}registerImportExportCommandFlags(e,t,n){n.flags!==void 0&&(p(this.#e,"schema",`${e} options.flags`),this.allowRegistration("schema.flags",`${e} options.flags`,"schema")&&(O(n.flags),this.#r.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:t,flags:D(`${e} options.flags`,n.flags)})))}applyImportExportCommandMetadata(e,t,n){if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new TypeError(`${e} options must be an object when provided`);const i=`${e==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,o=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...n,description:n?.description??i,arguments:n?.arguments??o},a=Ae(e,s,n?.description!==void 0);$(`${e} options.action`,s.action),$(`${e} options.description`,s.description),$(`${e} options.intent`,s.intent);const m=F(t,s.action),c=C(`${e} options.examples`,s.examples),l=C(`${e} options.failure_hints`,s.failure_hints),d=T(s.arguments);this.registerImportExportCommandFlags(e,t,s);const h={source_version:this.#e.version,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:t,action:m,examples:c,failure_hints:l,arguments:d},u=s.description?.trim();u&&(h.description=u);const f=s.intent?.trim();return f&&(h.intent=f),this.#r.commands.push(h),a}registerImporter(e,t,n){if(p(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;const i=Y(P("registerImporter name",e));S("registerImporter importer",t);const o=Z(i,"import");this.applyImportExportCommandMetadata("registerImporter",o,n),this.#r.importers.push({layer:this.#e.layer,name:this.#e.name,importer:i}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:o,run:async s=>t(U(s,i,"import"))})}registerExporter(e,t,n){if(p(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;const i=Y(P("registerExporter name",e));S("registerExporter exporter",t);const o=Z(i,"export"),s=this.applyImportExportCommandMetadata("registerExporter",o,n);this.#r.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:i,...s===void 0?{}:{output:s}}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:o,run:async a=>{const m=await t(U(a,i,"export"));return s?.receipt==="suppress"&&!be(m)?Ce(m):m}})}registerSearchProvider(e){if(p(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;const t=k("registerSearchProvider provider",e);this.#r.search_providers.push(I({layer:this.#e.layer,name:this.#e.name,definition:R("registerSearchProvider provider",e)},t))}registerVectorStoreAdapter(e){if(p(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;const t=k("registerVectorStoreAdapter adapter",e);this.#r.vector_store_adapters.push(I({layer:this.#e.layer,name:this.#e.name,definition:R("registerVectorStoreAdapter adapter",e)},t))}registerAssuranceMeasurementProvider(e){if(p(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(pr(e),e.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");const t=k("registerAssuranceMeasurementProvider provider",e);this.#r.assurance_providers.push(I({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:R("registerAssuranceMeasurementProvider provider",e)},t))}registerBeforeCommand(e){p(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(E("beforeCommand",e),this.#t.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerBeforeMutation(e){p(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(E("beforeMutation",e),this.#t.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerAfterCommand(e){p(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(E("afterCommand",e),this.#t.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerOnWrite(e){p(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(E("onWrite",e),this.#t.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerOnRead(e){p(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(E("onRead",e),this.#t.onRead.push({layer:this.#e.layer,name:this.#e.name,run:e}))}registerOnIndex(e){p(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(E("onIndex",e),this.#t.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:e}))}}function pe(r,e,t,n,i,o,s,a,m,c,l){return new Wr(r,e,t,n,i,o,s,a,m,c,l)}function fe(r){const e=r.commands.length,t=r.flags.reduce((s,a)=>s+a.flags.length,0),n=r.item_fields.reduce((s,a)=>s+a.fields.length,0),i=r.item_types.reduce((s,a)=>s+a.types.length,0),o=(r.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:e,flags:t,item_fields:n,item_types:i,...o>0?{relationship_kinds:o}:{},migrations:r.migrations.length,profiles:r.profiles.length,importers:r.importers.length,exporters:r.exporters.length,search_providers:r.search_providers.length,vector_store_adapters:r.vector_store_adapters.length,...(r.assurance_providers?.length??0)>0?{assurance_providers:r.assurance_providers.length}:{}}}function ge(r){const e=[],t=(o,s)=>{const a=new Map;for(const m of o){const c=a.get(m.command)??[];c.push(m),a.set(m.command,c)}for(const m of[...a.keys()].sort((c,l)=>c.localeCompare(l))){const c=a.get(m);if(c.length<=1)continue;const l=c[c.length-1];for(const d of c.slice(0,-1))e.push(`${s}:${m}:${l.layer}:${l.name}:${d.layer}:${d.name}`)}};t(r.handlers,"extension_command_handler_collision"),t(r.overrides,"extension_command_override_collision");const n=new Set(r.handlers.map(o=>o.command)),i=[...new Set(r.overrides.map(o=>o.command))].filter(o=>n.has(o));i.sort((o,s)=>o.localeCompare(s));for(const o of i){const s=r.handlers.filter(m=>m.command===o),a=r.overrides.filter(m=>m.command===o);for(const m of a)for(const c of s)e.push(`extension_command_override_handler_overlap:${o}:${m.layer}:${m.name}:${c.layer}:${c.name}`)}return e}function ye(r){const e=new Map;for(const n of r.overrides){const i=e.get(n.format)??[];i.push(n),e.set(n.format,i)}const t=[];for(const n of[...e.keys()].sort((i,o)=>i.localeCompare(o))){const i=e.get(n);if(i.length<=1)continue;const o=i[i.length-1];for(const s of i.slice(0,-1))o.commands?.length&&s.commands?.length&&!s.commands.some(a=>o.commands?.includes(a))||t.push(`extension_renderer_collision:${n}:${o.layer}:${o.name}:${s.layer}:${s.name}`)}return t}function _e(r){const e=[],t=new Map;for(const n of r.overrides){const i=t.get(n.command)??[];i.push(n),t.set(n.command,i)}for(const n of[...t.keys()].sort((i,o)=>i.localeCompare(o))){const i=t.get(n);if(i.length<=1)continue;const o=i[i.length-1];for(const s of i.slice(0,-1))e.push(`extension_parser_override_collision:${n}:${o.layer}:${o.name}:${s.layer}:${s.name}`)}return e}const Nr=new Set(["output_format"]);function ve(r){const e=[],t=new Map;for(const n of r.overrides){const i=t.get(n.service)??[];i.push(n),t.set(n.service,i)}for(const n of[...t.keys()].sort((i,o)=>i.localeCompare(o))){const i=t.get(n);if(i.length<=1||Nr.has(n))continue;const o=i[i.length-1];for(const s of i.slice(0,-1))e.push(`extension_service_override_collision:${n}:${o.layer}:${o.name}:${s.layer}:${s.name}`)}return e}async function vt(r){const e=Ve(r.policy??wr),t=Be(),n=Le(),i=Ue(),o=Ke(),s=Je(),a=Ge(),m=Xe(),c=[],l=[];for(const u of r.loaded){const f=ue(u.module);if(!f)continue;const g=c.length,v=Pe({hooks:t,commands:n,parsers:i,preflight:o,services:s,renderers:a,registrations:m});try{await f.activate(pe(u,t,n,i,o,s,a,m,l,c,e)),c.length>g&&(v(),l.push(`extension_activation_rolled_back:${u.layer}:${u.name}`))}catch(_){v(),l.push(`extension_activate_failed:${u.layer}:${u.name}`);const A=J(_);c.push({layer:u.layer,name:u.name,entry_path:u.entry_path,error:M(_),trace:A})}}const d=[...ge(n),..._e(i),...ir(o),...ve(s),...ye(a)],h=[...new Set([...l,...d])];return{hooks:t,commands:n,parsers:i,preflight:o,services:s,renderers:a,registrations:m,failed:c,warnings:h,hook_counts:{before_command:t.beforeCommand.length,before_mutation:t.beforeMutation.length,after_command:t.afterCommand.length,on_write:t.onWrite.length,on_read:t.onRead.length,on_index:t.onIndex.length},command_override_count:n.overrides.length,command_handler_count:n.handlers.length,parser_override_count:i.overrides.length,preflight_override_count:o.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:fe(m)}}const wt={assertFlagValueTypeAndDefault:ar,assertOptionalStringField:$,compareComparableVersions:gr,collectCommandCollisionWarnings:ge,collectParserCollisionWarnings:_e,collectRendererCollisionWarnings:ye,collectServiceCollisionWarnings:ve,createExtensionApi:pe,createRegistrationValidationError:y,evaluatePmMaxVersionCompatibility:ce,evaluatePmMinVersionCompatibility:me,extractRegistrationValidationTrace:J,fingerprintPath:j,getRegistrationCounts:fe,normalizeCommandDefinitionArguments:T,normalizeExtensionDeactivateTimeout:he,normalizeOptionalStringArrayField:C,normalizeRegistrationRecord:R,normalizeRegistrationRecordList:z,normalizeRuntimeRegistrationRecord:k,parseComparableVersion:vr,parseManifest:X,readCurrentPmCliVersion:oe,readManagedExtensionSourcePackages:async r=>new Map([...await te(r)].filter(e=>typeof e[1].package_name=="string").map(([e,t])=>[e,t.package_name])),resolveExtensionImportHref:le,resolveCurrentPmCliVersion:N,resolveCommandDefinitionAction:F,sanitizeRegistrationValue:Q,validateItemFieldDefinitions:G,resetCurrentPmCliVersionCacheForTest:()=>{W=null}};export{Gt as DEFAULT_EXTENSION_PRIORITY,wt as _testOnlyLoader,vt as activateExtensions,kt as createEmptyExtensionCommandRegistry,$t as createEmptyExtensionHookRegistry,Pt as createEmptyExtensionParserRegistry,St as createEmptyExtensionPreflightRegistry,It as createEmptyExtensionRegistrationRegistry,Mt as createEmptyExtensionRendererRegistry,At as createEmptyExtensionServiceRegistry,_t as deactivateExtensions,Mr as discoverExtensions,br as isCanonicalPathWithinDirectory,yt as loadExtensions,xr as nextExtensionReloadToken,Jt as parseExtensionManifestDocument,bt as parseLegacyExtensionCapabilityAliasWarning,Ct as parseUnknownExtensionCapabilityWarning,Cr as resolveExtensionRoots,Dt as runAfterCommandHooks,Ft as runBeforeCommandHooks,Ot as runBeforeMutationHooks,zt as runCommandHandler,Wt as runCommandOverride,Nt as runOnIndexHooks,jt as runOnReadHooks,Vt as runOnWriteHooks,qt as runParserOverride,Ht as runPreflightOverride,Lt as runRendererOverride,Bt as runServiceOverride,Ut as runServiceOverrideSync};
2
2
  //# sourceMappingURL=loader.js.map
@@ -1,2 +1,2 @@
1
- import{BUILTIN_ITEM_TYPE_VALUES as _}from"../../types/index.js";import{parseNestedSettingValue as g,resolveNestedSettingDescriptor as k}from"../config/nested-settings.js";import{normalizeAddFieldInput as v}from"../schema/fields-file.js";import{normalizeAddStatusInput as S}from"../schema/status-defs-file.js";import{normalizeAddTypeInput as $}from"../schema/item-types-file.js";import{normalizeStatusToken as p}from"../schema/type-workflows.js";import{DEFAULT_RUNTIME_STATUS_DEFINITIONS as T}from"../schema/runtime-schema.js";import{toErrorMessage as f}from"../shared/primitives.js";import{resolvePmToolCustomFieldCollision as I}from"../../sdk/cli-contracts/tool-schema.js";import{describeFieldFlagSpellingDefectLine as b,describeFieldOptionCollision as F,resolveAddFieldFlagSpellingDefects as P,resolveAddFieldOptionCollisions as C}from"../../sdk/schema/field-option-collisions.js";import{normalizeProfileLookupKey as h}from"./profile-presets.js";const J=["profile","types","statuses","fields","workflows","config","templates","packages"],Q=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","field_option_collision","field_flag_invalid","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],L=new Set(T.flatMap(t=>[p(t.id),...(t.aliases??[]).map(e=>p(e))]).filter(t=>t.length>0)),w=new Set(_.map(t=>t.toLowerCase()));function E(t,e){t.name.trim().length===0?e.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):t.name!==h(t.name)&&e.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:t.name,message:`Profile name "${t.name}" is not in canonical form; resolution folds it to "${h(t.name)}" (lowercase, hyphens as underscores).`}),t.title.trim().length===0&&e.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),t.summary.trim().length===0&&e.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function N(t,e){const r=new Set,i=new Set;for(const[s,o]of t.types.entries()){let n;try{n=$(o).name}catch(d){e.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof o.name=="string"?o.name:`#${s}`,message:f(d)});continue}const a=n.toLowerCase();if(i.has(a)){e.push({severity:"error",code:"type_duplicate",dimension:"types",target:n,message:`Item type "${n}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}i.add(a),r.add(a)}return r}function z(t,e){const r=new Set,i=new Set;for(const[s,o]of t.statuses.entries()){let n;try{n=S(o)}catch(a){e.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof o.id=="string"?o.id:`#${s}`,message:f(a)});continue}if(i.has(n.id)){e.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:n.id,message:`Status "${n.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}i.add(n.id),r.add(n.id);for(const a of n.aliases??[])r.add(p(a))}return r}function x(t,e){const r=new Set;for(const[i,s]of t.fields.entries()){let o,n;try{n=v(s),o=n.key}catch(m){e.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof s.key=="string"?s.key:`#${i}`,message:f(m)});continue}if(r.has(o)){e.push({severity:"error",code:"field_duplicate",dimension:"fields",target:o,message:`Field "${o}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}r.add(o);const a=P(n);a.length>0&&e.push({severity:"error",code:"field_flag_invalid",dimension:"fields",target:o,message:`Field "${o}" declares a flag that is not one option spelling: ${a.map(b).join("; ")}. Pass one spelling per alias.`});const d=C(n);d.length>0&&e.push({severity:"error",code:"field_option_collision",dimension:"fields",target:o,message:`Field "${o}" would disable a built-in option: ${d.map(F).join("; ")}. Rename the field or narrow its commands.`});const l=I(o);l&&e.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:o,message:`Field "${o}" collides with canonical MCP property "${l.property}" owned by ${l.owner}; callers must pass the custom value through ${l.nested_path}.`})}}function A(t,e,r,i){const s=new Set;for(const[o,n]of t.workflows.entries()){const a=n.type.trim().toLowerCase();if(a.length===0){i.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${o}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}const d=s.has(a);s.add(a),d?i.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:n.type,message:`Workflow type "${n.type}" is declared more than once; the later transition set wins.`}):!w.has(a)&&!e.has(a)&&i.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:n.type,message:`Workflow governs type "${n.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});const l=new Set;for(const m of n.allowed_transitions){const u=p(m[0]),y=p(m[1]);if(u.length===0||y.length===0){i.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:n.type,message:`Workflow "${n.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(const c of[u,y])L.has(c)||r.has(c)||l.has(c)||(l.add(c),i.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:c,message:`Workflow "${n.type}" references status "${c}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function O(t,e){const r=new Set;for(const i of t.config){const s=k(i.key);if(s===void 0){e.push({severity:"error",code:"config_key_unknown",dimension:"config",target:i.key,message:`Config knob "${i.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}r.has(s.key)?e.push({severity:"error",code:"config_duplicate",dimension:"config",target:s.key,message:`Config knob "${s.key}" is set more than once; the later value silently overwrites the earlier one.`}):r.add(s.key);const o=g(s,i.value);o.ok||e.push({severity:"error",code:"config_value_invalid",dimension:"config",target:i.key,message:o.error.message})}}function U(t,e,r){for(const i of t.templates){const s=i.options.type;if(typeof s!="string"||s.trim().length===0)continue;const o=s.trim().toLowerCase();!w.has(o)&&!e.has(o)&&r.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:i.name,message:`Template "${i.name}" creates type "${s}" which is neither a built-in type nor declared by this profile.`})}}function D(t,e){for(const[r,i]of t.packages.entries())i.spec.trim().length===0&&e.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${r}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function X(t){const e=[];E(t,e);const r=N(t,e),i=z(t,e);x(t,e),A(t,r,i,e),O(t,e),U(t,r,e),D(t,e);const s=e.filter(n=>n.severity==="error").length,o=e.length-s;return{profile:t.name,ok:s===0,findings:e,errorCount:s,warningCount:o}}export{Q as PROFILE_LINT_CODES,J as PROFILE_LINT_DIMENSIONS,X as lintProjectProfile};
1
+ import{BUILTIN_ITEM_TYPE_VALUES as _}from"../../types/index.js";import{parseNestedSettingValue as g,resolveNestedSettingDescriptor as k}from"../config/nested-settings.js";import{normalizeAddFieldInput as v}from"../schema/fields-file.js";import{normalizeAddStatusInput as S}from"../schema/status-defs-file.js";import{normalizeAddTypeInput as $}from"../schema/item-types-file.js";import{normalizeStatusToken as p}from"../schema/type-workflows.js";import{DEFAULT_RUNTIME_STATUS_DEFINITIONS as T}from"../schema/runtime-schema.js";import{toErrorMessage as f}from"../shared/primitives.js";import{resolvePmToolCustomFieldCollision as I}from"../../sdk/cli-contracts/tool-schema.js";import{describeFieldFlagSpellingDefectLine as b,describeFieldOptionCollision as F,resolveAddFieldFlagSpellingDefects as P,resolveAddFieldOptionCollisions as C}from"../../sdk/schema/field-option-collisions.js";import{normalizeProfileLookupKey as h}from"./profile-presets.js";const J=["profile","types","statuses","fields","workflows","config","templates","packages"],Q=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","field_option_collision","field_flag_invalid","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],L=new Set(T.flatMap(t=>[p(t.id),...(t.aliases??[]).map(e=>p(e))]).filter(t=>t.length>0)),w=new Set(_.map(t=>t.toLowerCase()));function E(t,e){t.name.trim().length===0?e.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):t.name!==h(t.name)&&e.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:t.name,message:`Profile name "${t.name}" is not in canonical form; resolution folds it to "${h(t.name)}" (lowercase, hyphens as underscores).`}),t.title.trim().length===0&&e.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),t.summary.trim().length===0&&e.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function N(t,e){const r=new Set,i=new Set;for(const[s,o]of t.types.entries()){let n;try{n=$(o).name}catch(d){e.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof o.name=="string"?o.name:`#${s}`,message:f(d)});continue}const a=n.toLowerCase();if(i.has(a)){e.push({severity:"error",code:"type_duplicate",dimension:"types",target:n,message:`Item type "${n}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}i.add(a),r.add(a)}return r}function z(t,e){const r=new Set,i=new Set;for(const[s,o]of t.statuses.entries()){let n;try{n=S(o)}catch(a){e.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof o.id=="string"?o.id:`#${s}`,message:f(a)});continue}if(i.has(n.id)){e.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:n.id,message:`Status "${n.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}i.add(n.id),r.add(n.id);for(const a of n.aliases??[])r.add(p(a))}return r}function x(t,e){const r=new Set;for(const[i,s]of t.fields.entries()){let o,n;try{n=v(s),o=n.key}catch(m){e.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof s.key=="string"?s.key:`#${i}`,message:f(m)});continue}if(r.has(o)){e.push({severity:"error",code:"field_duplicate",dimension:"fields",target:o,message:`Field "${o}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}r.add(o);const a=P(n,s);a.length>0&&e.push({severity:"error",code:"field_flag_invalid",dimension:"fields",target:o,message:`Field "${o}" declares a flag that is not one option spelling: ${a.map(b).join("; ")}. Pass one spelling per alias.`});const d=C(n);d.length>0&&e.push({severity:"error",code:"field_option_collision",dimension:"fields",target:o,message:`Field "${o}" would disable a built-in option: ${d.map(F).join("; ")}. Rename the field or narrow its commands.`});const l=I(o);l&&e.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:o,message:`Field "${o}" collides with canonical MCP property "${l.property}" owned by ${l.owner}; callers must pass the custom value through ${l.nested_path}.`})}}function A(t,e,r,i){const s=new Set;for(const[o,n]of t.workflows.entries()){const a=n.type.trim().toLowerCase();if(a.length===0){i.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${o}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}const d=s.has(a);s.add(a),d?i.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:n.type,message:`Workflow type "${n.type}" is declared more than once; the later transition set wins.`}):!w.has(a)&&!e.has(a)&&i.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:n.type,message:`Workflow governs type "${n.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});const l=new Set;for(const m of n.allowed_transitions){const u=p(m[0]),y=p(m[1]);if(u.length===0||y.length===0){i.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:n.type,message:`Workflow "${n.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(const c of[u,y])L.has(c)||r.has(c)||l.has(c)||(l.add(c),i.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:c,message:`Workflow "${n.type}" references status "${c}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function O(t,e){const r=new Set;for(const i of t.config){const s=k(i.key);if(s===void 0){e.push({severity:"error",code:"config_key_unknown",dimension:"config",target:i.key,message:`Config knob "${i.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}r.has(s.key)?e.push({severity:"error",code:"config_duplicate",dimension:"config",target:s.key,message:`Config knob "${s.key}" is set more than once; the later value silently overwrites the earlier one.`}):r.add(s.key);const o=g(s,i.value);o.ok||e.push({severity:"error",code:"config_value_invalid",dimension:"config",target:i.key,message:o.error.message})}}function U(t,e,r){for(const i of t.templates){const s=i.options.type;if(typeof s!="string"||s.trim().length===0)continue;const o=s.trim().toLowerCase();!w.has(o)&&!e.has(o)&&r.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:i.name,message:`Template "${i.name}" creates type "${s}" which is neither a built-in type nor declared by this profile.`})}}function D(t,e){for(const[r,i]of t.packages.entries())i.spec.trim().length===0&&e.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${r}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function X(t){const e=[];E(t,e);const r=N(t,e),i=z(t,e);x(t,e),A(t,r,i,e),O(t,e),U(t,r,e),D(t,e);const s=e.filter(n=>n.severity==="error").length,o=e.length-s;return{profile:t.name,ok:s===0,findings:e,errorCount:s,warningCount:o}}export{Q as PROFILE_LINT_CODES,J as PROFILE_LINT_DIMENSIONS,X as lintProjectProfile};
2
2
  //# sourceMappingURL=profile-lint.js.map
@@ -1,4 +1,4 @@
1
- import type{ItemTypeDefinition,RuntimeFieldCommand,RuntimeFieldValueSchema,RuntimeFieldType,RuntimeSchemaSettings,RuntimeStatusDefinition,RuntimeStatusRole,RuntimeWorkflowDefinition}from "../../types/index.js";export type{RuntimeFieldCommand}from "../../types/index.js";
1
+ import type{ItemTypeDefinition,RuntimeFieldCommand,RuntimeFieldDefinition,RuntimeFieldValueSchema,RuntimeFieldType,RuntimeSchemaSettings,RuntimeStatusDefinition,RuntimeStatusRole,RuntimeWorkflowDefinition}from "../../types/index.js";export type{RuntimeFieldCommand}from "../../types/index.js";
2
2
  /** Fallback runtime schema file paths used when callers do not provide an override. */
3
3
  export declare const DEFAULT_RUNTIME_SCHEMA_FILE_PATHS:Readonly<{types:"schema/types.json";statuses:"schema/statuses.json";fields:"schema/fields.json";workflows:"schema/workflows.json";}>;
4
4
  /** Fallback runtime workflow used when callers do not provide an override. */
@@ -101,8 +101,27 @@ warnings:string[];
101
101
  created_paths:string[];}
102
102
  /** Normalize a stored field flag token as the registry reads it: trimmed, lower-cased, separators as hyphens, leading dashes removed. */
103
103
  export declare function normalizeCliToken(value:unknown):string;
104
+ /** Why the field registry drops a whole stored definition (pm-x9r2h3). */
105
+ export type RuntimeFieldDefinitionDropReason="not_an_object"|"key_empty"|"metadata_key_empty"|"cli_flag_empty"|"value_schema_invalid";
106
+ /**
107
+ * What the field registry discards from one stored definition (pm-x9r2h3):
108
+ * the whole definition, or members it ignores or replaces while keeping it.
109
+ */
110
+ export interface RuntimeFieldDefinitionLoss{
111
+ /** Set when the registry drops the whole definition. */
112
+ dropped?:RuntimeFieldDefinitionDropReason;
113
+ /** One line per member the registry ignores or replaces, such as a blank alias. */
114
+ ignored:string[];}
115
+ /**
116
+ * Resolve one stored definition and record what the registry discards from
117
+ * it. The registry and `pm validate` both read this one function, so a
118
+ * diagnostic can never disagree with what the registry keeps.
119
+ */
120
+ export declare function inspectRuntimeFieldDefinition(definition:unknown):{resolved:RuntimeFieldDefinitionResolved|null;loss:RuntimeFieldDefinitionLoss;};
104
121
  /** Implements normalize runtime schema settings for the public runtime surface of this module. */
105
122
  export declare function normalizeRuntimeSchemaSettings(schema:Partial<RuntimeSchemaSettings>|undefined):RuntimeSchemaSettings;
123
+ /** The definitions list of a parsed fields file, in any of its accepted shapes; undefined for any other shape. */
124
+ export declare function readFieldsFromSchemaFile(parsed:unknown):RuntimeFieldDefinition[]|undefined;
106
125
  /** Implements file path for schema section for the public runtime surface of this module. */
107
126
  export declare function filePathForSchemaSection(pmRoot:string,configuredPath:string|undefined,fallbackPath:string):string;
108
127
  /** Resolves the active tracker's `schema/types.json` path so user-facing hints (e.g. the invalid-type error) point at the real `--pm-path` location instead of the hardcoded `.agents/pm` default. Mirrors how `pm schema add/remove-type` report their target path. */
@@ -1,3 +1,3 @@
1
- import U from"node:path";import{pathExists as W,readFileIfExists as v}from"../fs/fs-utils.js";import{createFileAtomic as K}from"../fs/atomic-create.js";import{DEFAULT_STATUS_DEFINITIONS as V,DEFAULT_WORKFLOW_DEFINITION as H}from"../shared/constants.js";import{RUNTIME_FIELD_COMMAND_VALUES as Y,RUNTIME_FIELD_TYPE_VALUES as $,RUNTIME_STATUS_ROLE_VALUES as J,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES as B,STATUS_VALUES as X}from"../../types/index.js";import{normalizeStatusToken as k}from"./status-token.js";const m=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),O=H,D=V,Z=["create","update"],G=new Set(J),Q=new Set($),ee=new Set(Y),te=new Set(B),ne=new Set(["string","number","boolean","array","object"]),re=16;function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const se=[e=>e.type===void 0||typeof e.type=="string"&&ne.has(e.type),e=>!Object.hasOwn(e,"const")||E(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>E(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||R(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function E(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);const n=Array.isArray(e)?e.every(r=>E(r,t)):Object.values(e).every(r=>E(r,t));return t.delete(e),n}function I(e,t=0,n=new Set){if(!R(e)||t>re||n.has(e))return;n.add(e);const r=e,s=r.type,o=r.enum,u=r.one_of,a=r.properties,i=r.items,d=r.required,c=r.min_length,l=r.min_items,p=r.format,w=r.additional_properties;if(!se.every(_=>_(r))){n.delete(e);return}const h=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([_,z])=>[_,I(z,t+1,n)])),A=i===void 0?void 0:I(i,t+1,n),g=u===void 0?void 0:u.map(_=>I(_,t+1,n));if([...Object.values(h??{}),...i===void 0?[]:[A],...g??[]].some(_=>_===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:s,const:Object.hasOwn(r,"const")?r.const:void 0,enum:o,min_length:c,min_items:l,format:p,properties:h,required:d===void 0?void 0:[...new Set(d)],additional_properties:w,items:A,one_of:g}).filter(([,_])=>_!==void 0))}function T(e){const t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function f(e){if(typeof e!="string"||e.length===0)return;const t=k(e);return t.length>0?t:void 0}function ie(e){return e.startsWith("--")?e.slice(2):e}function M(e){return typeof e=="string"?ie(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function j(e){return e.replaceAll("_","-")}function oe(e){const t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(s=>s.length>0).map(s=>s.toLowerCase());if(t.length===0)return e;const[n,...r]=t;return`${n}${r.map(s=>`${s.slice(0,1).toUpperCase()}${s.slice(1)}`).join("")}`}function L(e,t){const n=f(e.id);if(!n)return null;const r=[...new Set(T(e.aliases).map(k).filter(a=>a.length>0))].sort((a,i)=>a.localeCompare(i)),s=T(e.roles).filter(a=>G.has(a)),o=e.description?.trim(),u=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:s,description:o&&o.length>0?o:void 0,order:u}}function ae(e){return{draft_status:f(e?.draft_status),open_status:f(e?.open_status),in_progress_status:f(e?.in_progress_status),blocked_status:f(e?.blocked_status),close_status:f(e?.close_status),canceled_status:f(e?.canceled_status)}}function C(e,t){if(!Array.isArray(t)||t.length!==2)return;const n=k(t[0]),r=k(t[1]);n.length===0||r.length===0||e.pairs.some(s=>s[0]===n&&s[1]===r)||e.pairs.push([n,r])}function le(e){const t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;const n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(const r of e.allowed_transitions)C(n,r);return{typeKey:t.toLowerCase(),record:n}}function ue(e){if(!Array.isArray(e)||e.length===0)return;const t=new Map;for(const r of e){const s=le(r);if(s===null)continue;const o=t.get(s.typeKey)??s.record;o.denyAll||=s.record.denyAll;for(const u of s.record.pairs)C(o,u);t.set(s.typeKey,o)}const n=[];for(const r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,s)=>r.type.localeCompare(s.type)),n.length>0?n:void 0}function P(e){const t=k(e.key??"");if(!t)return null;const n=k(e.metadata_key??e.front_matter_key??t),r=M(e.cli_flag??j(t));if(!r)return null;const s=T(e.cli_aliases).map(l=>M(l)).filter(l=>l.length>0&&l!==r),o=typeof e.type=="string"?e.type.trim().toLowerCase():"string",u=Q.has(o)?o:"string",a=(()=>{const l=T(e.commands).filter(p=>ee.has(p));return l.length>0?l:[...Z]})(),i=e.description?.trim(),d=T(e.required_types),c=e.value_schema===void 0?void 0:I(e.value_schema);return e.value_schema!==void 0&&c===void 0?null:{key:t,metadata_key:n,cli_flag:r,cli_aliases:s,description:i&&i.length>0?i:void 0,type:u,commands:a,repeatable:[e.repeatable===!0,u==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:d,allow_unset:e.allow_unset!==!1,value_schema:c}}function de(e){const t=new Map;for(const[r,s]of e.entries()){const o=L(s,r);o&&t.set(o.id,o)}const n=q([...t.values()]);return n.length>0?n:q(D.map((r,s)=>L(r,s)).filter(r=>r!==null))}function q(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function ce(e){const t=new Map;for(const n of e??[]){const r=P(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function fe(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function _e(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==j(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function me(e){const t=typeof e=="string"?e.trim().toLowerCase():"allow";return te.has(t)?t:"allow"}function F(e){const t={...m,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:D,r=de(n),s=ce(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(fe),fields:s.map(_e),workflow:{...O,...ae(e?.workflow)},type_workflows:ue(e?.type_workflows),unknown_field_policy:me(e?.unknown_field_policy)}}function pe(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function ye(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;const t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){const n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function we(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;const t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Se(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;const t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function he(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function Ae(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function y(e,t,n){const r=t?.trim()||n;return U.isAbsolute(r)?r:U.join(e,r)}function Le(e,t){return y(e,t.files.types,m.types)}async function Ne(e,t){const n=F(t),r=[{path:y(e,n.files.types,m.types),seed:{definitions:[]}},{path:y(e,n.files.statuses,m.statuses),seed:{statuses:D}},{path:y(e,n.files.fields,m.fields),seed:{fields:[]}},{path:y(e,n.files.workflows,m.workflows),seed:{workflow:O}}],s=[];for(const o of r)await W(o.path)||await K(o.path,`${JSON.stringify(o.seed,null,2)}
2
- `)&&s.push(o.path);return{created_paths:s}}async function Ue(e,t){const n=F(t),r=[],s=y(e,n.files.types,m.types),o=y(e,n.files.statuses,m.statuses),u=y(e,n.files.fields,m.fields),a=y(e,n.files.workflows,m.workflows);let i,d,c,l,p;const w=async(z,x)=>{const N=await v(z);if(N!==null)return pe(N,x,r)},h=await w(s,"runtime_schema_types_invalid_json");h!==void 0&&(i=ye(h),i===void 0&&r.push("runtime_schema_types_invalid_shape"));const A=await w(o,"runtime_schema_statuses_invalid_json");A!==void 0&&(d=we(A),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));const g=await w(u,"runtime_schema_fields_invalid_json");g!==void 0&&(c=Se(g),c===void 0&&r.push("runtime_schema_fields_invalid_shape"));const S=await w(a,"runtime_schema_workflows_invalid_json");return S!==void 0&&(l=he(S),l===void 0&&r.push("runtime_schema_workflows_invalid_shape"),p=Ae(S)),{schema:F({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...c??[]],workflow:{...n.workflow,...l},type_workflows:[...n.type_workflows??[],...p??[]]}),type_definitions_from_file:i,warnings:r,created_paths:[]}}function b(e,t,n,r=!1){const o=n.map(a=>f(a)).filter(a=>typeof a=="string").find(a=>e.some(i=>i.id===a));if(r&&o!==void 0)return o;const u=e.find(a=>a.roles.includes(t));return u!==void 0?u.id:o??e[0]?.id}function ge(e){const t=new Map,n=new Map;for(const r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(const s of r.aliases)t.set(s,r.id),t.set(s.replaceAll("_","-"),r.id),t.set(s.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function ke(e){const t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(const n of e){const r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function Oe(e){const t=F(e),n=t.statuses.map((S,_)=>L(S,_)).filter(S=>S!==null),{aliasToId:r,byId:s}=ge(n),{activeStatuses:o,blockedStatuses:u,draftStatuses:a,terminalCanceledStatuses:i,terminalDoneStatuses:d,terminalStatuses:c}=ke(n),l=t.workflow,p=f(l.open_status)??b(n,"default_open",["open","in_progress",X[0]]),w=f(l.in_progress_status)??b(n,"active",["in_progress","in-progress",p],!0),h=f(l.blocked_status)??b(n,"blocked",["blocked"]),A=f(l.close_status)??b(n,"default_close",["closed","done","complete"]),g=f(l.canceled_status)??b(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:s,alias_to_id:r,terminal_statuses:c,terminal_done_statuses:d,terminal_canceled_statuses:i,active_statuses:o,blocked_statuses:u,draft_statuses:a,open_status:p,in_progress_status:w,blocked_status:h,close_status:A,canceled_status:g}}function Te(e,t){const n=k(e);if(n)return t.alias_to_id.get(n)}function Re(e){const t=F(e),n=new Map,r=t.fields.map(i=>P(i)).filter(i=>i!==null);for(const i of r)n.set(i.key,i);const s=[...n.values()].sort((i,d)=>i.key.localeCompare(d.key)),o=new Map,u=new Map,a=new Map;for(const i of s){o.set(i.key,i),u.set(i.cli_flag,i);for(const d of i.cli_aliases)u.set(d,i);for(const d of i.commands){const c=a.get(d)??[];c.push(i),a.set(d,c)}}for(const[i,d]of a.entries())d.sort((c,l)=>c.key.localeCompare(l.key)),a.set(i,d);return{definitions:s,by_key:o,by_cli_token:u,command_to_fields:a}}function Me(e){return oe(e.key)}function je(e,t){const n=Te(e,t);return n?t.terminal_statuses.has(n):!1}export{m as DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,D as DEFAULT_RUNTIME_STATUS_DEFINITIONS,O as DEFAULT_RUNTIME_WORKFLOW,Ne as ensureRuntimeSchemaFileScaffold,y as filePathForSchemaSection,Ue as loadRuntimeSchemaFromOptionalFiles,M as normalizeCliToken,F as normalizeRuntimeSchemaSettings,Te as normalizeStatusInputWithRegistry,Le as resolveItemTypesFilePath,Re as resolveRuntimeFieldRegistry,Oe as resolveRuntimeStatusRegistry,Me as runtimeFieldOptionTarget,je as statusIsTerminal};
1
+ import K from"node:path";import{pathExists as H,readFileIfExists as J}from"../fs/fs-utils.js";import{createFileAtomic as X}from"../fs/atomic-create.js";import{DEFAULT_STATUS_DEFINITIONS as Z,DEFAULT_WORKFLOW_DEFINITION as G,ITEM_METADATA_KEY_ORDER as Q}from"../shared/constants.js";import{RUNTIME_FIELD_COMMAND_VALUES as ee,RUNTIME_FIELD_TYPE_VALUES as te,RUNTIME_STATUS_ROLE_VALUES as ne,RUNTIME_UNKNOWN_FIELD_POLICY_VALUES as re,STATUS_VALUES as se}from"../../types/index.js";import{BUILTIN_FIELD_KEYS as ie}from"./fields-file.js";import{normalizeStatusToken as p}from"./status-token.js";const m=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),q=G,z=Z,oe=["create","update"],ae=new Set(ne),le=new Set(te),x=new Set(ee),ue=new Set(re),de=new Set(["string","number","boolean","array","object"]),ce=16;function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const fe=[e=>e.type===void 0||typeof e.type=="string"&&de.has(e.type),e=>!Object.hasOwn(e,"const")||I(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>I(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||T(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function I(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);const n=Array.isArray(e)?e.every(r=>I(r,t)):Object.values(e).every(r=>I(r,t));return t.delete(e),n}function L(e,t=0,n=new Set){if(!T(e)||t>ce||n.has(e))return;n.add(e);const r=e,s=r.type,o=r.enum,l=r.one_of,a=r.properties,i=r.items,u=r.required,f=r.min_length,d=r.min_items,h=r.format,S=r.additional_properties;if(!fe.every(_=>_(r))){n.delete(e);return}const g=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([_,O])=>[_,L(O,t+1,n)])),A=i===void 0?void 0:L(i,t+1,n),k=l===void 0?void 0:l.map(_=>L(_,t+1,n));if([...Object.values(g??{}),...i===void 0?[]:[A],...k??[]].some(_=>_===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:s,const:Object.hasOwn(r,"const")?r.const:void 0,enum:o,min_length:f,min_items:d,format:h,properties:g,required:u===void 0?void 0:[...new Set(u)],additional_properties:S,items:A,one_of:k}).filter(([,_])=>_!==void 0))}function E(e){const t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function c(e){if(typeof e!="string"||e.length===0)return;const t=p(e);return t.length>0?t:void 0}function _e(e){return e.replace(/^(?:--)+/u,"")}function N(e){return typeof e=="string"?_e(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function $(e){return e.replaceAll("_","-")}function me(e){const t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(s=>s.length>0).map(s=>s.toLowerCase());if(t.length===0)return e;const[n,...r]=t;return`${n}${r.map(s=>`${s.slice(0,1).toUpperCase()}${s.slice(1)}`).join("")}`}function U(e,t){const n=c(e.id);if(!n)return null;const r=[...new Set(E(e.aliases).map(p).filter(a=>a.length>0))].sort((a,i)=>a.localeCompare(i)),s=E(e.roles).filter(a=>ae.has(a)),o=e.description?.trim(),l=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:s,description:o&&o.length>0?o:void 0,order:l}}function pe(e){return{draft_status:c(e?.draft_status),open_status:c(e?.open_status),in_progress_status:c(e?.in_progress_status),blocked_status:c(e?.blocked_status),close_status:c(e?.close_status),canceled_status:c(e?.canceled_status)}}function W(e,t){if(!Array.isArray(t)||t.length!==2)return;const n=p(t[0]),r=p(t[1]);n.length===0||r.length===0||e.pairs.some(s=>s[0]===n&&s[1]===r)||e.pairs.push([n,r])}function ye(e){const t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;const n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(const r of e.allowed_transitions)W(n,r);return{typeKey:t.toLowerCase(),record:n}}function Se(e){if(!Array.isArray(e)||e.length===0)return;const t=new Map;for(const r of e){const s=ye(r);if(s===null)continue;const o=t.get(s.typeKey)??s.record;o.denyAll||=s.record.denyAll;for(const l of s.record.pairs)W(o,l);t.set(s.typeKey,o)}const n=[];for(const r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,s)=>r.type.localeCompare(s.type)),n.length>0?n:void 0}function M(e){try{return JSON.stringify(e)??String(e)}catch{try{return String(e)}catch{return"a value that cannot be shown"}}}function j(e,t,n,r){return t===void 0?[]:Array.isArray(t)?t.filter(s=>typeof s!="string"||!n(s.trim())).map(s=>`${e}: ${M(s)} is not ${r}`):[`${e}: is not a list`]}const we=["repeatable","required","required_on_create","allow_unset"];function he(e,t){return we.flatMap(n=>{const r=e[n];return r===void 0||typeof r=="boolean"?[]:[`${n}: ${M(r)} is not a boolean, so it reads as ${String(t[n])}`]})}const ge=new Set(["type","const","enum","min_length","min_items","format","properties","required","additional_properties","items","one_of"]);function D(e,t){if(!T(e))return[];const n=e;return[...Object.keys(n).filter(r=>!ge.has(r)).map(r=>`${t}.${r}: is not a value schema keyword, so it is not enforced`),...T(n.properties)?Object.entries(n.properties).flatMap(([r,s])=>D(s,`${t}.properties.${r}`)):[],...D(n.items,`${t}.items`),...Array.isArray(n.one_of)?n.one_of.flatMap((r,s)=>D(r,`${t}.one_of[${s}]`)):[]]}function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function C(e,t,n){if(e===void 0)return;const r=e.filter(s=>!t(s)).length;return r===0?e:(n.warnings.push(`${n.warningKey}:${r}`),n.keepPositions?e.map(s=>t(s)?s:{}):e.filter(s=>t(s)))}function Ae(e){return R(e)&&typeof e.name=="string"}function ke(e){const t=typeof e.type=="string"?e.type.trim().toLowerCase():"string";return le.has(t)?t:"string"}function Ee(e){const t=E(e.commands).filter(n=>x.has(n));return t.length>0?t:[...oe]}function v(e){return e.metadata_key!=null?{member:"metadata_key",value:e.metadata_key}:e.front_matter_key==null?void 0:{member:"front_matter_key",value:e.front_matter_key}}const be=new Set([...ie,...Q]);function Fe(e,t){const n=v(e);return n!==void 0&&p(n.value).length===0&&be.has(t)}function Te(e,t){const n=p(v(e)?.value);return n.length>0?n:t}function Ie(e,t){const n=typeof e.type=="string"&&e.type.trim().toLowerCase()===t.type,r=v(e);return[...r===void 0||p(r.value).length>0?[]:[`${r.member}: ${M(r.value)} names no item key, so values are stored under the field key`],...j("cli_aliases",e.cli_aliases,s=>N(s).length>0,"a flag spelling"),...e.type===void 0||n?[]:[`type: ${M(e.type)} is not a field type, so the field reads as string`],...j("commands",e.commands,s=>x.has(s),"a field command"),...j("required_types",e.required_types,s=>s.length>0,"a type name"),...e.description===void 0||typeof e.description=="string"?[]:["description: is not a string"],...he(e,t),...D(e.value_schema,"value_schema")]}function Le(e){const t=i=>({resolved:null,loss:{dropped:i,ignored:[]}});if(!R(e))return t("not_an_object");const n=p(e.key??"");if(!n)return t("key_empty");if(Fe(e,n))return t("metadata_key_empty");const r=N(e.cli_flag??$(n));if(!r)return t("cli_flag_empty");const s=e.value_schema===void 0?void 0:L(e.value_schema);if(e.value_schema!==void 0&&s===void 0)return t("value_schema_invalid");const o=ke(e),l=typeof e.description=="string"?e.description.trim():void 0,a={key:n,metadata_key:Te(e,n),cli_flag:r,cli_aliases:E(e.cli_aliases).map(i=>N(i)).filter(i=>i.length>0&&i!==r),description:l&&l.length>0?l:void 0,type:o,commands:Ee(e),repeatable:[e.repeatable===!0,o==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:E(e.required_types),allow_unset:e.allow_unset!==!1,value_schema:s};return{resolved:a,loss:{ignored:Ie(e,a)}}}function V(e){return Le(e).resolved}function Me(e){const t=new Map;for(const[r,s]of e.entries()){const o=U(s,r);o&&t.set(o.id,o)}const n=B([...t.values()]);return n.length>0?n:B(z.map((r,s)=>U(r,s)).filter(r=>r!==null))}function B(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function De(e){const t=new Map;for(const n of e??[]){const r=V(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function Re(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function Oe(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==$(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function ze(e){const t=typeof e=="string"?e.trim().toLowerCase():"allow";return ue.has(t)?t:"allow"}function b(e){const t={...m,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:z,r=Me(n),s=De(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(Re),fields:s.map(Oe),workflow:{...q,...pe(e?.workflow)},type_workflows:Se(e?.type_workflows),unknown_field_policy:ze(e?.unknown_field_policy)}}function Ne(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function Ue(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;const t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){const n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function je(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;const t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Ce(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;const t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function ve(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function Pe(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function y(e,t,n){const r=t?.trim()||n;return K.isAbsolute(r)?r:K.join(e,r)}function Xe(e,t){return y(e,t.files.types,m.types)}async function Ze(e,t){const n=b(t),r=[{path:y(e,n.files.types,m.types),seed:{definitions:[]}},{path:y(e,n.files.statuses,m.statuses),seed:{statuses:z}},{path:y(e,n.files.fields,m.fields),seed:{fields:[]}},{path:y(e,n.files.workflows,m.workflows),seed:{workflow:q}}],s=[];for(const o of r)await H(o.path)||await X(o.path,`${JSON.stringify(o.seed,null,2)}
2
+ `)&&s.push(o.path);return{created_paths:s}}async function Ge(e,t){const n=b(t),r=[],s=y(e,n.files.types,m.types),o=y(e,n.files.statuses,m.statuses),l=y(e,n.files.fields,m.fields),a=y(e,n.files.workflows,m.workflows);let i,u,f,d,h;const S=async(O,Y)=>{const P=await J(O);if(P!==null)return Ne(P,Y,r)},g=await S(s,"runtime_schema_types_invalid_json");g!==void 0&&(i=C(Ue(g),Ae,{warningKey:"runtime_schema_types_entry_invalid",warnings:r,keepPositions:!1}),i===void 0&&r.push("runtime_schema_types_invalid_shape"));const A=await S(o,"runtime_schema_statuses_invalid_json");A!==void 0&&(u=C(je(A),R,{warningKey:"runtime_schema_statuses_entry_invalid",warnings:r,keepPositions:!0}),u===void 0&&r.push("runtime_schema_statuses_invalid_shape"));const k=await S(l,"runtime_schema_fields_invalid_json");k!==void 0&&(f=C(Ce(k),R,{warningKey:"runtime_schema_fields_entry_invalid",warnings:r,keepPositions:!1}),f===void 0&&r.push("runtime_schema_fields_invalid_shape"));const w=await S(a,"runtime_schema_workflows_invalid_json");return w!==void 0&&(d=ve(w),d===void 0&&r.push("runtime_schema_workflows_invalid_shape"),h=Pe(w)),{schema:b({...n,statuses:[...n.statuses,...u??[]],fields:[...n.fields,...f??[]],workflow:{...n.workflow,...d},type_workflows:[...n.type_workflows??[],...h??[]]}),type_definitions_from_file:i,warnings:r,created_paths:[]}}function F(e,t,n,r=!1){const o=n.map(a=>c(a)).filter(a=>typeof a=="string").find(a=>e.some(i=>i.id===a));if(r&&o!==void 0)return o;const l=e.find(a=>a.roles.includes(t));return l!==void 0?l.id:o??e[0]?.id}function Ke(e){const t=new Map,n=new Map;for(const r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(const s of r.aliases)t.set(s,r.id),t.set(s.replaceAll("_","-"),r.id),t.set(s.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function qe(e){const t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(const n of e){const r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function Qe(e){const t=b(e),n=t.statuses.map((w,_)=>U(w,_)).filter(w=>w!==null),{aliasToId:r,byId:s}=Ke(n),{activeStatuses:o,blockedStatuses:l,draftStatuses:a,terminalCanceledStatuses:i,terminalDoneStatuses:u,terminalStatuses:f}=qe(n),d=t.workflow,h=c(d.open_status)??F(n,"default_open",["open","in_progress",se[0]]),S=c(d.in_progress_status)??F(n,"active",["in_progress","in-progress",h],!0),g=c(d.blocked_status)??F(n,"blocked",["blocked"]),A=c(d.close_status)??F(n,"default_close",["closed","done","complete"]),k=c(d.canceled_status)??F(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:s,alias_to_id:r,terminal_statuses:f,terminal_done_statuses:u,terminal_canceled_statuses:i,active_statuses:o,blocked_statuses:l,draft_statuses:a,open_status:h,in_progress_status:S,blocked_status:g,close_status:A,canceled_status:k}}function xe(e,t){const n=p(e);if(n)return t.alias_to_id.get(n)}function et(e){const t=b(e),n=new Map,r=t.fields.map(i=>V(i)).filter(i=>i!==null);for(const i of r)n.set(i.key,i);const s=[...n.values()].sort((i,u)=>i.key.localeCompare(u.key)),o=new Map,l=new Map,a=new Map;for(const i of s){o.set(i.key,i),l.set(i.cli_flag,i);for(const u of i.cli_aliases)l.set(u,i);for(const u of i.commands){const f=a.get(u)??[];f.push(i),a.set(u,f)}}for(const[i,u]of a.entries())u.sort((f,d)=>f.key.localeCompare(d.key)),a.set(i,u);return{definitions:s,by_key:o,by_cli_token:l,command_to_fields:a}}function tt(e){return me(e.key)}function nt(e,t){const n=xe(e,t);return n?t.terminal_statuses.has(n):!1}export{m as DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,z as DEFAULT_RUNTIME_STATUS_DEFINITIONS,q as DEFAULT_RUNTIME_WORKFLOW,Ze as ensureRuntimeSchemaFileScaffold,y as filePathForSchemaSection,Le as inspectRuntimeFieldDefinition,Ge as loadRuntimeSchemaFromOptionalFiles,N as normalizeCliToken,b as normalizeRuntimeSchemaSettings,xe as normalizeStatusInputWithRegistry,Ce as readFieldsFromSchemaFile,Xe as resolveItemTypesFilePath,et as resolveRuntimeFieldRegistry,Qe as resolveRuntimeStatusRegistry,tt as runtimeFieldOptionTarget,nt as statusIsTerminal};
3
3
  //# sourceMappingURL=runtime-schema.js.map
@@ -34,7 +34,7 @@ export type PmRecoveryReferenceKind=(typeof PM_RECOVERY_REFERENCE_KINDS)[number]
34
34
  /** Behavioral promise attached to a recovery reference. */
35
35
  export type PmRecoveryReferenceSemantics="recovery"|"replacement"|"behavior_preserving";
36
36
  /** Literal envelope fields recognized as recovery-reference producers. */
37
- export declare const PM_RECOVERY_REFERENCE_FIELDS:readonly("suggested_retry"|"restore_with"|"next_best_command"|"candidate_commands"|"next_steps"|"examples"|"migration_hint"|"migration_hints"|"fallback_candidates"|"suggested_next_steps"|"example"|"candidate_command"|"next_step"|"retry_command")[];
37
+ export declare const PM_RECOVERY_REFERENCE_FIELDS:readonly("examples"|"suggested_retry"|"restore_with"|"next_best_command"|"candidate_commands"|"next_steps"|"migration_hint"|"migration_hints"|"fallback_candidates"|"suggested_next_steps"|"example"|"candidate_command"|"next_step"|"retry_command")[];
38
38
  /** One source file supplied to the producer-census analyzer. */
39
39
  export interface PmRecoveryProducerSource{
40
40
  /** Repository-relative source path. */
@@ -88,6 +88,14 @@ export declare function normalizeDirectExtensionCommandOptions(options:Record<st
88
88
  export interface DirectExtensionOptionPolicy{
89
89
  /** `refuse` (default) for an extension-created command; `pass` for a native command path an extension extends. */
90
90
  undeclaredKeys?:"refuse"|"pass";}
91
+ /**
92
+ * The declared boolean a negated direct-caller spelling sets, under its handler key, with the value normalization
93
+ * gives it (pm-2nwcgg). It reads the normalizer's own spelling index and boolean tokens (`true`, `1`, `false`, `0`
94
+ * in any case, trimmed), so a negation through a declared short alias counts too, and the test harness's host
95
+ * admission judges an invocation exactly as normalization applies it. A spelling that is not such a negation, or a
96
+ * value normalization refuses (it refuses it again afterwards), yields undefined.
97
+ */
98
+ export declare function resolveNegatedDeclaredBooleanOption(definitions:ReadonlyArray<LooseCommandFlagDefinition>,spelling:string,value:unknown):{key:string;value:unknown;}|undefined;
91
99
  /** How an argv option token takes its value, as Commander parses it: `<value>`, `[value]`, or a switch. */
92
100
  export type ArgvOptionArity="required"|"optional"|"none";
93
101
  /** An option a command registered with Commander: how it takes its value and the attribute it sets. */
@@ -1,2 +1,2 @@
1
- import{isDeepStrictEqual as T}from"node:util";import{resolvePmCommandOperation as k}from"../cli-contracts/command-aliases.js";import{describeFlagScalarValueFailure as j,resolveExtensionFlagValueContract as F,resolveExtensionLongFlagName as L,EXIT_CODE as m,PmCliError as y,flattenFlagListValue as z,resolveFlagValueKind as fe}from"../runtime-primitives.js";import{RESERVED_EXTENSION_HOST_FLAG_NAMES as de}from"../../core/extensions/reserved-host-flags.js";const pe=new Set(["__proto__","prototype","constructor"]),x=Symbol("looseOptionOccurrences");function h(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,o)=>o.toUpperCase())}function ge(e,n,t){const o=e[n];if(o===void 0){e[n]=t;return}if(Array.isArray(o)){o.push(t),e[n]=o;return}e[n]=[o,t]}function N(e,n){const t=e[n];if(!t.startsWith("-")||t==="-"||t==="--")return null;if(!t.startsWith("--")){const i=t.indexOf("=");if(i>=0)return{consumed:1,key:t.slice(1,i).trim(),value:t.slice(i+1),attached:!0};const a=t.slice(1).trim(),l=e[n+1];return typeof l=="string"&&!l.startsWith("-")?{consumed:2,key:a,value:l}:{consumed:1,key:a,value:!0}}const o=t.indexOf("=");if(o>=0)return{consumed:1,key:t.slice(2,o).trim(),value:t.slice(o+1),attached:!0};if(t.startsWith("--no-"))return{consumed:1,key:t.slice(5).trim(),value:!1};const r=t.slice(2).trim(),s=e[n+1];return typeof s=="string"&&!s.startsWith("-")?{consumed:2,key:r,value:s}:{consumed:1,key:r,value:!0}}function E(e){return pe.has(e)}function C(e){const n=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return fe(n)}function v(e){const n=[],t=L(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(t.startsWith("--")){const r=h(t.slice(2));r.length>0&&!E(r)&&n.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){const r=h(o.slice(1));r.length>0&&!E(r)&&n.push(r)}return[...new Set(n)]}function He(e){const n=new Set;for(const t of e)for(const o of v(t))n.add(o);return n}function O(e){const n=L(e.long)??"";if(n.startsWith("--")){const t=h(n.slice(2));if(t.length>0&&!E(t))return t}return v(e)[0]??null}function $(e){const n=L(e.long)??"";if(n.startsWith("--")&&n.length>2)return n;const t=typeof e.short=="string"?e.short.trim():"";return t.startsWith("-")&&!t.startsWith("--")&&t.length>1?t:null}function U(e,n){return[...(n.definitions??e).map(o=>$(o)).filter(o=>o!==null),...n.inheritedFlags??[]]}function Je(e,n,t,o={}){if(n.length===0)return;const r=new Set,s=new Map,i=[],a=U(n,o);for(const l of n){const u=v(l),c=$(l);for(const g of u)r.add(g),l.enabled===!1&&s.set(g,c);l.required===!0&&l.enabled!==!1&&u.length>0&&i.push({keys:u,label:c,definition:l})}for(const l of Object.keys(e)){r.has(l)||B(`--${l}`,`--${l}`,t,a);const u=s.get(l);u&&I(u,t)}for(const l of i){const u=c=>Object.hasOwn(e,c)&&(l.definition.list!==!0||J(l.definition,e[c]));l.keys.some(u)||G(l.definition,l.keys[0],l.label,t)}}function B(e,n,t,o){const r=o.length>0?` Expected one of: ${[...new Set(o)].join(", ")}.`:"";throw new y(`Unknown option '${e}' for extension command '${t}'.${r}`,m.USAGE,{code:"unknown_option",flag:n,required:`Use a flag the command accepts; run pm contracts --command ${t} --flags-only --json to list them.`})}function I(e,n){throw new y(`Option '${e}' is disabled for extension command '${n}'.`,m.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${n} --help`],nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function G(e,n,t,o){const r=F(e),s=r.value_arity==="none"?t:r.value_arity==="optional"?`${t} [${r.value_name}]`:`${t} <${r.value_name}>`;throw new y(`Missing required option '${t}' for extension command '${o}'.`,m.USAGE,{code:"missing_required_option",flag:t,field:n,required:`Pass ${s}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${o} ${s}`],nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[t]}})}function he(e){return typeof e=="string"||e==null?e:String(e)}function me(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){const n=Number(e);return Number.isFinite(n)?n:e}return e}function H(e){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1}return e}const ye={string:he,number:me,boolean:H};function b(e,n){return Array.isArray(e)?e.map(t=>b(t,n)):ye[n](e)}function V(e,n,t){const o=t?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):z(e);return n?o.map(r=>b(r,n)):o}function J(e,n){return V(n,null,e.repeatable===!0).length>0}function Oe(e,n,t,o){return t?V(e,n,o):n?b(e,n):e}function be(e,n,t){const o=Y(e,n);return o.length===0?t:o.map(r=>r.value)}function X(e){return F(e).value_arity==="none"}function q(e,n,t,o,r){const s=$(e),i=r?` for extension command '${r}'`:"",a=t===!0?"no value":JSON.stringify(t);throw new y(`Option '${s}'${i} expects ${o}; received ${a}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:s,required:`Pass ${s} ${n==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${n} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${n} value for ${s}.`,`Run pm ${r??"<command>"} --help to review the declared flag contract.`]})}function D(e,n){return e.value_validation==="strict"&&n!=="string"}function Y(e,n){const t=e[x];if(!t)return[];const o=new Set(n);return t.filter(r=>o.has(r.key))}function we(e,n,t,o){if(X(e))for(const r of Y(t,n)){if(r.attached!==!0)continue;const s=e.list===!0&&e.repeatable!==!0?z(r.value):[r.value];for(const i of s){const a=j(b(i,"boolean"),"boolean");a!==null&&q(e,"boolean",i,a.expected,o)}}}function Se(e,n,t,o,r){const s=Array.isArray(t)?t.flat(1/0):[t],i=o?s:s.flatMap(a=>typeof a=="string"?a.split(","):[a]);for(const a of i)if(typeof a=="string"&&a.trim().length===0){const l=j(a,n);q(e,n,a,l.expected,r)}}function R(e,n,t,o){if(!D(e,t))return n;const r=t==="boolean"&&X(e),s=i=>{const a=j(i,t);return a===null?i:r&&typeof i=="string"?!0:q(e,t,i,a.expected,o)};return Array.isArray(n)?n.map(s):s(n)}function ve(e,n,t,o){for(const r of t)if(!(r===n||!Object.hasOwn(e,r))){if(Object.hasOwn(e,n)){if(o){const s=e[n],i=e[r];e[n]=[...Array.isArray(s)?s:[s],...Array.isArray(i)?i:[i]].filter(a=>a!=null)}delete e[r];continue}e[n]=e[r],delete e[r]}}function Z(e,n,t=e,o){if(n.length===0)return e;const r=Object.create(null);for(const[i,a]of Object.entries(e))r[i]=a;const s=new Set(n.map(i=>O(i)).filter(i=>i!==null));for(const i of n){const a=O(i);if(a){const l=v(i).filter(u=>u===a||!s.has(u));$e(r,i,a,l,t,o)}}return r}function $e(e,n,t,o,r,s){const i=n.list===!0,a=C(n);a&&!i&&xe(e,n,t,o,a,s),ve(e,t,o,i);const l=n.repeatable===!0;if(!Object.hasOwn(e,t)){n.default!==void 0&&(e[t]=Oe(n.default,a,i,l));return}if(a==="boolean"&&D(n,a)&&we(n,o,r,s),i){e[t]=Ae(n,o,r,e[t],a,l,s);return}a&&(e[t]=R(n,b(e[t],a),a,s))}function xe(e,n,t,o,r,s){for(const i of o)i!==t&&Object.hasOwn(e,i)&&R(n,b(e[i],r),r,s)}function Ae(e,n,t,o,r,s,i){const a=be(t,n,o);r&&D(e,r)&&Se(e,r,a,s,i);const l=V(a,r,s);return r?R(e,l,r,i):l}function Xe(e){const n=Object.create(null),t=[];Object.defineProperty(n,x,{value:t});let o=0;for(;o<e.length;){const r=N(e,o);if(!r){o+=1;continue}const s=h(r.key);if(s.length===0||E(s)){o+=r.consumed;continue}ge(n,s,r.value),t.push({...r,key:s}),o+=r.consumed}return n}function Ye(e){const n=[];let t=0;for(;t<e.length;){if(e[t]==="--"){n.push(...e.slice(t+1));break}const o=N(e,t);if(o){t+=Math.max(1,o.consumed);continue}n.push(e[t]),t+=1}return n}function Ze(e,n){if(n.length===0)return[...e];const t=new Set,o=new Set;for(const i of n){const a=C(i);for(const l of v(i))t.add(l),a==="boolean"&&o.add(l)}if(t.size===0)return[...e];const r=[];let s=0;for(;s<e.length;){if(e[s]==="--"){r.push(...e.slice(s+1));break}const i=N(e,s);if(i){const a=h(i.key);if(t.has(a)){const l=e[s],u=o.has(a)&&!l.includes("=")?1:i.consumed;s+=u;continue}}r.push(e[s]),s+=1}return r}function Qe(e){return O(e)}function Q(e){return e.trim().toLowerCase().split(/\s+/u).filter(n=>n.length>0).join(" ")}function Pe(e,n){const t=Q(n);if(t.length===0)return[];const o=k(t);return e.flags.filter(r=>k(Q(r.target_command))===o).flatMap(r=>[...r.flags])}function P(e,n,t,o){const r=$(e),[s,i]=t;throw new y(`Options '${s}' and '${i}' both set ${r} for extension command '${o}' with different values.`,m.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${r} once, under the handler key '${n}'.`,why:`'${s}' and '${i}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${s}' or '${i}' and pass one value as '${n}'.`,`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`]})}function en(e,n,t,o={}){if(n.length===0)return e;const r=n.map(c=>c.repeatable===!0&&c.list!==!0?{...c,list:!0}:c),s=Ce(r),i=Fe(e,s,t),a=new Set([...s.long.values()].map(({handlerKey:c})=>c)),l=Object.create(null),u=Object.create(null);for(const[c,g]of Object.entries(i))a.has(c)?l[c]=g:g===void 0||o.undeclaredKeys==="pass"||Le(c)?u[c]=g:B(c,Ee(c),t,U(r,{}));return ne(l,r,t),Object.assign(u,Z(l,r,ee(l,s),t))}function ee(e,n){const t=new Set([...n.long.values()].map(({handlerKey:s})=>s)),o=Object.entries(e).filter(([s])=>t.has(s)).flatMap(([s,i])=>(Array.isArray(i)?i.flat(1/0):[i]).map(a=>({consumed:1,key:s,value:a,attached:!0}))),r=Object.create(null);return Object.defineProperty(r,x,{value:o}),r}function ne(e,n,t){for(const o of n){const r=O(o);if(r===null)continue;const s=$(o),i=e[r],a=Object.hasOwn(e,r);o.enabled===!1&&a&&I(s,t);const l=a&&(o.list!==!0||J(o,i));o.required===!0&&o.enabled!==!1&&!l&&G(o,r,s,t),o.list!==!0&&Array.isArray(i)&&_e(s,t)}}function _e(e,n){throw new y(`Option '${e}' for extension command '${n}' takes one value; received an array.`,m.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${n} --flags-only --json to read each flag's value contract.`]})}const te=new Set([...[...de].flatMap(e=>{const n=e.replace(/^--/u,"");return[n,...n.startsWith("no-")?[n.slice(3)]:[]].flatMap(o=>[h(o),o.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function Le(e){return te.has(e)||te.has(h(e.replace(/^-{1,2}/u,"")))}function Ee(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function Ce(e){const n={long:new Map,short:new Map},t=(o,r,s)=>{r.length>0&&!o.has(r)&&o.set(r,s)};for(const o of e){const r=O(o);if(r===null)continue;const s={handlerKey:r,definition:o};t(n.long,r,s);const i=typeof o.short=="string"?o.short.trim():"";i.startsWith("-")&&!i.startsWith("--")&&t(n.short,i.slice(1),s)}return n}function W(e,n){return e.long.get(n)??e.short.get(n.replace(/^-(?!-)/u,""))??e.long.get(h(n.replace(/^-{1,2}/u,"")))}function Ke(e,n,t,o){const r=/^(?:--)?no-(.+)$/u.exec(n)?.[1];if(r===void 0||W(e,n)!==void 0)return{spelling:n,value:t};const s=W(e,r);return s===void 0||C(s.definition)!=="boolean"?{spelling:n,value:t}:(s.definition.list===!0||s.definition.repeatable===!0)&&Array.isArray(t)?{spelling:r,value:t.flat(1/0).map(i=>re(n,s.definition,i,o))}:s.definition.list===!0&&t!==void 0?{spelling:r,value:re(n,s.definition,t,o)}:{spelling:r,value:t===void 0?t:K(n,s.definition,t,o)}}function re(e,n,t,o){const r=s=>s.trim().length===0?s:String(K(e,n,s.trim(),o));return t==null?t:typeof t!="string"?K(e,n,t,o):t.trim().length===0?t:n.repeatable===!0||!t.includes(",")?K(e,n,t,o):t.split(",").map(r).join(",")}function K(e,n,t,o){const r=H(t);return typeof r=="boolean"?!r:je(e,n,t,o)}function je(e,n,t,o){const r=$(n);throw new y(`Option '${e}' for extension command '${o}' negates ${r} and expects true, false, 1, or 0; received ${JSON.stringify(t)}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:r,required:`Pass ${r} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${r}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's value contract.`]})}function Fe(e,n,t){const o=Object.create(null),r=new Map;for(const[s,i]of Object.entries(e)){const{spelling:a,value:l}=Ke(n,s,i,t),u=W(n,a);if(u===void 0)o[a]=l;else if(l!==void 0){const c=r.get(u.handlerKey);c===void 0?(r.set(u.handlerKey,a),o[u.handlerKey]=l):T(oe(u.definition,u.handlerKey,o[u.handlerKey],n,t),oe(u.definition,u.handlerKey,l,n,t))||P(u.definition,u.handlerKey,[c,a],t)}}return o}function oe(e,n,t,o,r){const s={[n]:t};return ne(s,[e],r),Z(s,[e],ee(s,o),r)[n]}function se(e){const n=new Map;for(const t of e){const o=O(t);if(o===null)continue;const r={definition:t,handlerKey:o,kind:C(t),arity:F(t).value_arity,scalar:t.list!==!0},s=[L(t.long),typeof t.short=="string"?t.short.trim():""];for(const i of s.filter(a=>a?.startsWith("-")===!0))n.has(i)||n.set(i,r)}return n}function ie(e,n,t,o=ke){const r=e.optionOf(t),s=n.get(t),i=s!==void 0&&o(s)?s:void 0;if(r!==void 0){const a={arity:r.arity,...r.variadic===!0?{variadic:!0}:{}};if(i?.handlerKey===r.key)return{...a,declared:i};if(s!==void 0)return a;const l=Te(n,t,r,o);return l===void 0?a:{...a,declared:l,negates:!0}}if(!(!e.includesLooseFlags||s===void 0))return i===void 0?{arity:s.arity,loose:!0}:{arity:s.arity,declared:i,loose:!0}}function M(e){return e.length>1&&e.startsWith("-")}const ae=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function le(e,n,t){const{tokens:o}=e;let r=0,s,i=!1,a=!1;for(;r<o.length||s!==void 0;){const l=s??o[r++];if(l==="--")return;if(a&&s===void 0&&Ne(e,l))continue;const u=M(l)?qe(e,l,o[r],n,t):{consumedByCommander:!1,consumed:0};if(r+=u.consumed,s=u.group,a=u.variadic===!0,!u.consumedByCommander){if(Ve(e.stop,l,i))return;i=!0}}}function Ne(e,n){return!M(n)||e.negativeNumbersAreValues&&ae.test(n)}function Ve(e,n,t){return e!==void 0&&(e.atFirstUnrecognized||!t&&e.atSubcommand(n))}function qe(e,n,t,o,r){const s=De(n,t,o);if(s!==void 0)return r(s.spelling,s.entry,s.value,"loose"),{consumedByCommander:!1,consumed:s.consumed};const i=o(n);if(i!==void 0){const a=i.arity==="required"||i.arity==="optional"&&t!==void 0&&(!M(t)||e.negativeNumbersAreValues&&ae.test(t));return r(n,i,i.negates===!0?!1:a?t:!0,"commander"),{consumedByCommander:!0,consumed:a?1:0,variadic:i.variadic===!0}}return n[1]!=="-"?{consumed:0,...Re(n,o,r)}:{consumedByCommander:We(n,o,r,e.includesLooseFlags?r:()=>{}),consumed:0}}function De(e,n,t){const o=e.indexOf("="),r=o>1?e.slice(0,o):e,s=t(r);if(s?.loose===!0)return o>1?{spelling:r,entry:s,value:e.slice(o+1),consumed:0}:n!==void 0&&!n.startsWith("-")?{spelling:r,entry:s,value:n,consumed:1}:{spelling:r,entry:s,value:!0,consumed:0};const i=o<0&&e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return i?.loose===!0&&i.declared?.kind==="boolean"?{spelling:e,entry:i,value:!1,consumed:0}:void 0}function Re(e,n,t){const o=e.slice(0,2),r=e.length>2?n(o):void 0;return r===void 0||r.loose===!0?{consumedByCommander:!1}:r.arity!=="none"?(t(o,r,e.slice(2),"commander"),{consumedByCommander:!0}):(t(o,r,!0,"commander"),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function We(e,n,t,o){const r=e.indexOf("=");if(r>2){const i=e.slice(0,r),a=n(i);return a!==void 0&&a.arity!=="none"?(t(i,a,e.slice(r+1),"commander"),!0):(a?.declared?.kind==="boolean"&&o(i,a,e.slice(r+1),"loose"),!1)}const s=e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return s?.declared?.kind==="boolean"&&o(e,s,!1,"loose"),!1}function nn(e,n,t){const o=se(n),r=new Map;for(const s of e)le(s,i=>ie(s,o,i),(i,a,l)=>{a.declared!==void 0&&Me(r,a.declared,i,l,t)})}function Me(e,n,t,o,r){const{definition:s,handlerKey:i,kind:a}=n,l=a?b(o,a):o,u=e.get(i)??new Map,c=[...u].find(([g,f])=>g!==t&&!T(f,l));c!==void 0&&P(s,i,[c[0],t],r),u.set(t,l),e.set(i,u)}function Te(e,n,t,o){const r=n.startsWith("--no-")?e.get(`--${n.slice(5)}`):void 0;return r!==void 0&&o(r)&&r.kind==="boolean"&&r.handlerKey===t.key?r:void 0}function ke(e){return e.scalar}function ue(e){return!e.scalar&&e.kind==="boolean"&&e.arity==="none"}function tn(e,n,t){const o=se(t),r=[...new Set(o.values())].filter(ue);if(r.length===0)return e;const s=new Set(t.map(f=>O(f)).filter(f=>f!==null)),i=f=>v(f.definition).filter(d=>d===f.handlerKey||!s.has(d)),a=new Map([...r].reverse().flatMap(f=>i(f).map(d=>[d,f]))),l=new Map;for(const f of n)le(f,d=>ie(f,o,d,ue)??ze(f,a,d),(d,w,S,A)=>{if(w.declared===void 0)return;const _=l.get(w.declared)??[];_.push(A==="commander"?{value:S}:null),l.set(w.declared,_)});const u=[...l].filter(([,f])=>f.some(d=>d!==null));if(u.length===0)return e;let c=e[x]??[];for(const[f,d]of u){const w=new Set(i(f)),S=c.filter(({key:p})=>w.has(p));if(S.length===0)continue;const A=p=>({consumed:0,key:f.handlerKey,value:p.value});let _=0;const ce=d.filter(p=>p===null).length===S.length?d.map(p=>p===null?S[_++]:A(p)):[...S,...d.filter(p=>p!==null).map(A)];c=[...c.filter(({key:p})=>!w.has(p)),...ce]}const g=Object.assign(Object.create(null),e);return Object.defineProperty(g,x,{value:c}),g}function ze(e,n,t){const o=!t.startsWith("--")&&e.optionOf(t.slice(0,2))!==void 0;if(!e.includesLooseFlags||o)return;const r=n.get(h(t.replace(/^-+/u,"")));return r===void 0?void 0:{arity:r.arity,declared:r,loose:!0}}export{Z as coerceLooseCommandOptionsWithFlagDefinitions,Pe as collectExtensionFlagDefinitionsForCommand,He as collectLooseCommandOptionKeysForDefinitions,Ye as collectLoosePositionalArgs,en as normalizeDirectExtensionCommandOptions,tn as orderArgvRepeatableSwitchOccurrences,Xe as parseLooseCommandOptions,nn as refuseConflictingArgvOptionSpellings,Qe as resolveExtensionFlagOptionKey,C as resolveLooseOptionCoercionKind,Ze as stripLooseCommandOptionTokens,Je as validateLooseCommandOptionsWithFlagDefinitions};
1
+ import{isDeepStrictEqual as k}from"node:util";import{resolvePmCommandOperation as z}from"../cli-contracts/command-aliases.js";import{describeFlagScalarValueFailure as N,resolveExtensionFlagValueContract as F,resolveExtensionLongFlagName as L,EXIT_CODE as m,PmCliError as y,flattenFlagListValue as B,resolveFlagValueKind as pe}from"../runtime-primitives.js";import{RESERVED_EXTENSION_HOST_FLAG_NAMES as ge}from"../../core/extensions/reserved-host-flags.js";const he=new Set(["__proto__","prototype","constructor"]),x=Symbol("looseOptionOccurrences");function h(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,o)=>o.toUpperCase())}function me(e,n,t){const o=e[n];if(o===void 0){e[n]=t;return}if(Array.isArray(o)){o.push(t),e[n]=o;return}e[n]=[o,t]}function V(e,n){const t=e[n];if(!t.startsWith("-")||t==="-"||t==="--")return null;if(!t.startsWith("--")){const i=t.indexOf("=");if(i>=0)return{consumed:1,key:t.slice(1,i).trim(),value:t.slice(i+1),attached:!0};const l=t.slice(1).trim(),a=e[n+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:l,value:a}:{consumed:1,key:l,value:!0}}const o=t.indexOf("=");if(o>=0)return{consumed:1,key:t.slice(2,o).trim(),value:t.slice(o+1),attached:!0};if(t.startsWith("--no-"))return{consumed:1,key:t.slice(5).trim(),value:!1};const r=t.slice(2).trim(),s=e[n+1];return typeof s=="string"&&!s.startsWith("-")?{consumed:2,key:r,value:s}:{consumed:1,key:r,value:!0}}function E(e){return he.has(e)}function K(e){const n=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return pe(n)}function S(e){const n=[],t=L(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(t.startsWith("--")){const r=h(t.slice(2));r.length>0&&!E(r)&&n.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){const r=h(o.slice(1));r.length>0&&!E(r)&&n.push(r)}return[...new Set(n)]}function He(e){const n=new Set;for(const t of e)for(const o of S(t))n.add(o);return n}function O(e){const n=L(e.long)??"";if(n.startsWith("--")){const t=h(n.slice(2));if(t.length>0&&!E(t))return t}return S(e)[0]??null}function $(e){const n=L(e.long)??"";if(n.startsWith("--")&&n.length>2)return n;const t=typeof e.short=="string"?e.short.trim():"";return t.startsWith("-")&&!t.startsWith("--")&&t.length>1?t:null}function U(e,n){return[...(n.definitions??e).map(o=>$(o)).filter(o=>o!==null),...n.inheritedFlags??[]]}function Je(e,n,t,o={}){if(n.length===0)return;const r=new Set,s=new Map,i=[],l=U(n,o);for(const a of n){const u=S(a),c=$(a);for(const g of u)r.add(g),a.enabled===!1&&s.set(g,c);a.required===!0&&a.enabled!==!1&&u.length>0&&i.push({keys:u,label:c,definition:a})}for(const a of Object.keys(e)){r.has(a)||I(`--${a}`,`--${a}`,t,l);const u=s.get(a);u&&G(u,t)}for(const a of i){const u=c=>Object.hasOwn(e,c)&&(a.definition.list!==!0||q(a.definition,e[c]));a.keys.some(u)||H(a.definition,a.keys[0],a.label,t)}}function I(e,n,t,o){const r=o.length>0?` Expected one of: ${[...new Set(o)].join(", ")}.`:"";throw new y(`Unknown option '${e}' for extension command '${t}'.${r}`,m.USAGE,{code:"unknown_option",flag:n,required:`Use a flag the command accepts; run pm contracts --command ${t} --flags-only --json to list them.`})}function G(e,n){throw new y(`Option '${e}' is disabled for extension command '${n}'.`,m.USAGE,{code:"extension_option_disabled",flag:e,required:`Remove ${e}; the command declares it with enabled: false.`,why:"A disabled declaration keeps the flag in the contract while refusing every value for it.",examples:[`pm ${n} --help`],nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function H(e,n,t,o){const r=F(e),s=r.value_arity==="none"?t:r.value_arity==="optional"?`${t} [${r.value_name}]`:`${t} <${r.value_name}>`;throw new y(`Missing required option '${t}' for extension command '${o}'.`,m.USAGE,{code:"missing_required_option",flag:t,field:n,required:`Pass ${s}.`,why:"The command declares this flag as required, so pm refuses the invocation before the extension handler runs.",examples:[`pm ${o} ${s}`],nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`],recovery:{missing:[t]}})}function ye(e){return typeof e=="string"||e==null?e:String(e)}function Oe(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){const n=Number(e);return Number.isFinite(n)?n:e}return e}function J(e){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1}return e}const be={string:ye,number:Oe,boolean:J};function b(e,n){return Array.isArray(e)?e.map(t=>b(t,n)):be[n](e)}function D(e,n,t){const o=t?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):B(e);return n?o.map(r=>b(r,n)):o}function q(e,n){return D(n,null,e.repeatable===!0).length>0}function ve(e,n,t,o){return t?D(e,n,o):n?b(e,n):e}function we(e,n,t){const o=Y(e,n);return o.length===0?t:o.map(r=>r.value)}function X(e){return F(e).value_arity==="none"}function R(e,n,t,o,r){const s=$(e),i=r?` for extension command '${r}'`:"",l=t===!0?"no value":JSON.stringify(t);throw new y(`Option '${s}'${i} expects ${o}; received ${l}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:s,required:`Pass ${s} ${n==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${n} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${n} value for ${s}.`,`Run pm ${r??"<command>"} --help to review the declared flag contract.`]})}function W(e,n){return e.value_validation==="strict"&&n!=="string"}function Y(e,n){const t=e[x];if(!t)return[];const o=new Set(n);return t.filter(r=>o.has(r.key))}function Se(e,n,t,o){if(X(e))for(const r of Y(t,n)){if(r.attached!==!0)continue;const s=e.list===!0&&e.repeatable!==!0?B(r.value):[r.value];for(const i of s){const l=N(b(i,"boolean"),"boolean");l!==null&&R(e,"boolean",i,l.expected,o)}}}function $e(e,n,t,o,r){const s=Array.isArray(t)?t.flat(1/0):[t],i=o?s:s.flatMap(l=>typeof l=="string"?l.split(","):[l]);for(const l of i)if(typeof l=="string"&&l.trim().length===0){const a=N(l,n);R(e,n,l,a.expected,r)}}function M(e,n,t,o){if(!W(e,t))return n;const r=t==="boolean"&&X(e),s=i=>{const l=N(i,t);return l===null?i:r&&typeof i=="string"?!0:R(e,t,i,l.expected,o)};return Array.isArray(n)?n.map(s):s(n)}function xe(e,n,t,o){for(const r of t)if(!(r===n||!Object.hasOwn(e,r))){if(Object.hasOwn(e,n)){if(o){const s=e[n],i=e[r];e[n]=[...Array.isArray(s)?s:[s],...Array.isArray(i)?i:[i]].filter(l=>l!=null)}delete e[r];continue}e[n]=e[r],delete e[r]}}function Z(e,n,t=e,o){if(n.length===0)return e;const r=Object.create(null);for(const[i,l]of Object.entries(e))r[i]=l;const s=new Set(n.map(i=>O(i)).filter(i=>i!==null));for(const i of n){const l=O(i);if(l){const a=S(i).filter(u=>u===l||!s.has(u));Ae(r,i,l,a,t,o)}}return r}function Ae(e,n,t,o,r,s){const i=n.list===!0,l=K(n);l&&!i&&_e(e,n,t,o,l,s),xe(e,t,o,i);const a=n.repeatable===!0;if(!Object.hasOwn(e,t)){n.default!==void 0&&(e[t]=ve(n.default,l,i,a));return}if(l==="boolean"&&W(n,l)&&Se(n,o,r,s),i){e[t]=Le(n,o,r,e[t],l,a,s);return}l&&(e[t]=M(n,b(e[t],l),l,s))}function _e(e,n,t,o,r,s){for(const i of o)i!==t&&Object.hasOwn(e,i)&&M(n,b(e[i],r),r,s)}function Le(e,n,t,o,r,s,i){const l=we(t,n,o);r&&W(e,r)&&$e(e,r,l,s,i);const a=D(l,r,s);return r?M(e,a,r,i):a}function Xe(e){const n=Object.create(null),t=[];Object.defineProperty(n,x,{value:t});let o=0;for(;o<e.length;){const r=V(e,o);if(!r){o+=1;continue}const s=h(r.key);if(s.length===0||E(s)){o+=r.consumed;continue}me(n,s,r.value),t.push({...r,key:s}),o+=r.consumed}return n}function Ye(e){const n=[];let t=0;for(;t<e.length;){if(e[t]==="--"){n.push(...e.slice(t+1));break}const o=V(e,t);if(o){t+=Math.max(1,o.consumed);continue}n.push(e[t]),t+=1}return n}function Ze(e,n){if(n.length===0)return[...e];const t=new Set,o=new Set;for(const i of n){const l=K(i);for(const a of S(i))t.add(a),l==="boolean"&&o.add(a)}if(t.size===0)return[...e];const r=[];let s=0;for(;s<e.length;){if(e[s]==="--"){r.push(...e.slice(s+1));break}const i=V(e,s);if(i){const l=h(i.key);if(t.has(l)){const a=e[s],u=o.has(l)&&!a.includes("=")?1:i.consumed;s+=u;continue}}r.push(e[s]),s+=1}return r}function Qe(e){return O(e)}function Q(e){return e.trim().toLowerCase().split(/\s+/u).filter(n=>n.length>0).join(" ")}function Pe(e,n){const t=Q(n);if(t.length===0)return[];const o=z(t);return e.flags.filter(r=>z(Q(r.target_command))===o).flatMap(r=>[...r.flags])}function P(e,n,t,o){const r=$(e),[s,i]=t;throw new y(`Options '${s}' and '${i}' both set ${r} for extension command '${o}' with different values.`,m.USAGE,{code:"extension_option_spelling_conflict",required:`Pass ${r} once, under the handler key '${n}'.`,why:`'${s}' and '${i}' are spellings of the same declared flag, and pm refuses to choose between two different values.`,nextSteps:[`Remove '${s}' or '${i}' and pass one value as '${n}'.`,`Run pm contracts --command ${o} --flags-only --json to read each flag's sdk_option key.`]})}function en(e,n,t,o={}){if(n.length===0)return e;const r=n.map(c=>c.repeatable===!0&&c.list!==!0?{...c,list:!0}:c),s=re(r),i=Ne(e,s,t),l=new Set([...s.long.values()].map(({handlerKey:c})=>c)),a=Object.create(null),u=Object.create(null);for(const[c,g]of Object.entries(i))l.has(c)?a[c]=g:g===void 0||o.undeclaredKeys==="pass"||Ke(c)?u[c]=g:I(c,Ce(c),t,U(r,{}));return ne(a,r,t),Object.assign(u,Z(a,r,ee(a,s),t))}function ee(e,n){const t=new Set([...n.long.values()].map(({handlerKey:s})=>s)),o=Object.entries(e).filter(([s])=>t.has(s)).flatMap(([s,i])=>(Array.isArray(i)?i.flat(1/0):[i]).map(l=>({consumed:1,key:s,value:l,attached:!0}))),r=Object.create(null);return Object.defineProperty(r,x,{value:o}),r}function ne(e,n,t){for(const o of n){const r=O(o);if(r===null)continue;const s=$(o),i=e[r],l=Object.hasOwn(e,r);o.enabled===!1&&l&&G(s,t);const a=l&&(o.list!==!0||q(o,i));o.required===!0&&o.enabled!==!1&&!a&&H(o,r,s,t),o.list!==!0&&Array.isArray(i)&&Ee(s,t)}}function Ee(e,n){throw new y(`Option '${e}' for extension command '${n}' takes one value; received an array.`,m.USAGE,{code:"extension_flag_value_invalid",flag:e,required:`Pass one value for ${e}, or ask the package to declare it with list: true or repeatable: true.`,why:"The flag is not declared list or repeatable, so pm refuses an array before the extension handler runs instead of handing it a value of the wrong shape.",nextSteps:[`Run pm contracts --command ${n} --flags-only --json to read each flag's value contract.`]})}const te=new Set([...[...ge].flatMap(e=>{const n=e.replace(/^--/u,"");return[n,...n.startsWith("no-")?[n.slice(3)]:[]].flatMap(o=>[h(o),o.replaceAll("-","_")])}),"force","subcommand","inputResponses","requestState"]);function Ke(e){return te.has(e)||te.has(h(e.replace(/^-{1,2}/u,"")))}function Ce(e){return`--${e.replace(/^-+/u,"").replace(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`}function re(e){const n={long:new Map,short:new Map},t=(o,r,s)=>{r.length>0&&!o.has(r)&&o.set(r,s)};for(const o of e){const r=O(o);if(r===null)continue;const s={handlerKey:r,definition:o};t(n.long,r,s);const i=typeof o.short=="string"?o.short.trim():"";i.startsWith("-")&&!i.startsWith("--")&&t(n.short,i.slice(1),s)}return n}function C(e,n){return e.long.get(n)??e.short.get(n.replace(/^-(?!-)/u,""))??e.long.get(h(n.replace(/^-{1,2}/u,"")))}function oe(e,n,t,o){const r=/^(?:--)?no-(.+)$/u.exec(n)?.[1];if(r===void 0||C(e,n)!==void 0)return{spelling:n,value:t};const s=C(e,r);return s===void 0||K(s.definition)!=="boolean"?{spelling:n,value:t}:(s.definition.list===!0||s.definition.repeatable===!0)&&Array.isArray(t)?{spelling:r,value:t.flat(1/0).map(i=>se(n,s.definition,i,o))}:s.definition.list===!0&&t!==void 0?{spelling:r,value:se(n,s.definition,t,o)}:{spelling:r,value:t===void 0?t:j(n,s.definition,t,o)}}function nn(e,n,t){const o=re(e);try{const r=oe(o,n,t,"");if(r.spelling===n)return;const s=C(o,r.spelling);return(s.definition.list===!0||s.definition.repeatable===!0)&&!q(s.definition,r.value)?void 0:{key:s.handlerKey,value:r.value}}catch{return}}function se(e,n,t,o){const r=s=>s.trim().length===0?s:String(j(e,n,s.trim(),o));return t==null?t:typeof t!="string"?j(e,n,t,o):t.trim().length===0?t:n.repeatable===!0||!t.includes(",")?j(e,n,t,o):t.split(",").map(r).join(",")}function j(e,n,t,o){const r=J(t);return typeof r=="boolean"?!r:je(e,n,t,o)}function je(e,n,t,o){const r=$(n);throw new y(`Option '${e}' for extension command '${o}' negates ${r} and expects true, false, 1, or 0; received ${JSON.stringify(t)}.`,m.USAGE,{code:"extension_flag_value_invalid",flag:r,required:`Pass ${r} as true or false, or '${e}' as true.`,why:`'${e}' is the negated spelling of the boolean ${r}, so only a boolean value can be inverted before the extension handler runs.`,nextSteps:[`Run pm contracts --command ${o} --flags-only --json to read each flag's value contract.`]})}function Ne(e,n,t){const o=Object.create(null),r=new Map;for(const[s,i]of Object.entries(e)){const{spelling:l,value:a}=oe(n,s,i,t),u=C(n,l);if(u===void 0)o[l]=a;else if(a!==void 0){const c=r.get(u.handlerKey);c===void 0?(r.set(u.handlerKey,l),o[u.handlerKey]=a):k(ie(u.definition,u.handlerKey,o[u.handlerKey],n,t),ie(u.definition,u.handlerKey,a,n,t))||P(u.definition,u.handlerKey,[c,l],t)}}return o}function ie(e,n,t,o,r){const s={[n]:t};return ne(s,[e],r),Z(s,[e],ee(s,o),r)[n]}function le(e){const n=new Map;for(const t of e){const o=O(t);if(o===null)continue;const r={definition:t,handlerKey:o,kind:K(t),arity:F(t).value_arity,scalar:t.list!==!0},s=[L(t.long),typeof t.short=="string"?t.short.trim():""];for(const i of s.filter(l=>l?.startsWith("-")===!0))n.has(i)||n.set(i,r)}return n}function ae(e,n,t,o=ke){const r=e.optionOf(t),s=n.get(t),i=s!==void 0&&o(s)?s:void 0;if(r!==void 0){const l={arity:r.arity,...r.variadic===!0?{variadic:!0}:{}};if(i?.handlerKey===r.key)return{...l,declared:i};if(s!==void 0)return l;const a=Te(n,t,r,o);return a===void 0?l:{...l,declared:a,negates:!0}}if(!(!e.includesLooseFlags||s===void 0))return i===void 0?{arity:s.arity,loose:!0}:{arity:s.arity,declared:i,loose:!0}}function T(e){return e.length>1&&e.startsWith("-")}const ue=/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/u;function ce(e,n,t){const{tokens:o}=e;let r=0,s,i=!1,l=!1;for(;r<o.length||s!==void 0;){const a=s??o[r++];if(a==="--")return;if(l&&s===void 0&&Fe(e,a))continue;const u=T(a)?De(e,a,o[r],n,t):{consumedByCommander:!1,consumed:0};if(r+=u.consumed,s=u.group,l=u.variadic===!0,!u.consumedByCommander){if(Ve(e.stop,a,i))return;i=!0}}}function Fe(e,n){return!T(n)||e.negativeNumbersAreValues&&ue.test(n)}function Ve(e,n,t){return e!==void 0&&(e.atFirstUnrecognized||!t&&e.atSubcommand(n))}function De(e,n,t,o,r){const s=qe(n,t,o);if(s!==void 0)return r(s.spelling,s.entry,s.value,"loose"),{consumedByCommander:!1,consumed:s.consumed};const i=o(n);if(i!==void 0){const l=i.arity==="required"||i.arity==="optional"&&t!==void 0&&(!T(t)||e.negativeNumbersAreValues&&ue.test(t));return r(n,i,i.negates===!0?!1:l?t:!0,"commander"),{consumedByCommander:!0,consumed:l?1:0,variadic:i.variadic===!0}}return n[1]!=="-"?{consumed:0,...Re(n,o,r)}:{consumedByCommander:We(n,o,r,e.includesLooseFlags?r:()=>{}),consumed:0}}function qe(e,n,t){const o=e.indexOf("="),r=o>1?e.slice(0,o):e,s=t(r);if(s?.loose===!0)return o>1?{spelling:r,entry:s,value:e.slice(o+1),consumed:0}:n!==void 0&&!n.startsWith("-")?{spelling:r,entry:s,value:n,consumed:1}:{spelling:r,entry:s,value:!0,consumed:0};const i=o<0&&e.startsWith("--no-")?t(`--${e.slice(5)}`):void 0;return i?.loose===!0&&i.declared?.kind==="boolean"?{spelling:e,entry:i,value:!1,consumed:0}:void 0}function Re(e,n,t){const o=e.slice(0,2),r=e.length>2?n(o):void 0;return r===void 0||r.loose===!0?{consumedByCommander:!1}:r.arity!=="none"?(t(o,r,e.slice(2),"commander"),{consumedByCommander:!0}):(t(o,r,!0,"commander"),{consumedByCommander:!0,group:`-${e.slice(2)}`})}function We(e,n,t,o){const r=e.indexOf("=");if(r>2){const i=e.slice(0,r),l=n(i);return l!==void 0&&l.arity!=="none"?(t(i,l,e.slice(r+1),"commander"),!0):(l?.declared?.kind==="boolean"&&o(i,l,e.slice(r+1),"loose"),!1)}const s=e.startsWith("--no-")?n(`--${e.slice(5)}`):void 0;return s?.declared?.kind==="boolean"&&o(e,s,!1,"loose"),!1}function tn(e,n,t){const o=le(n),r=new Map;for(const s of e)ce(s,i=>ae(s,o,i),(i,l,a)=>{l.declared!==void 0&&Me(r,l.declared,i,a,t)})}function Me(e,n,t,o,r){const{definition:s,handlerKey:i,kind:l}=n,a=l?b(o,l):o,u=e.get(i)??new Map,c=[...u].find(([g,f])=>g!==t&&!k(f,a));c!==void 0&&P(s,i,[c[0],t],r),u.set(t,a),e.set(i,u)}function Te(e,n,t,o){const r=n.startsWith("--no-")?e.get(`--${n.slice(5)}`):void 0;return r!==void 0&&o(r)&&r.kind==="boolean"&&r.handlerKey===t.key?r:void 0}function ke(e){return e.scalar}function fe(e){return!e.scalar&&e.kind==="boolean"&&e.arity==="none"}function rn(e,n,t){const o=le(t),r=[...new Set(o.values())].filter(fe);if(r.length===0)return e;const s=new Set(t.map(f=>O(f)).filter(f=>f!==null)),i=f=>S(f.definition).filter(d=>d===f.handlerKey||!s.has(d)),l=new Map([...r].reverse().flatMap(f=>i(f).map(d=>[d,f]))),a=new Map;for(const f of n)ce(f,d=>ae(f,o,d,fe)??ze(f,l,d),(d,v,w,A)=>{if(v.declared===void 0)return;const _=a.get(v.declared)??[];_.push(A==="commander"?{value:w}:null),a.set(v.declared,_)});const u=[...a].filter(([,f])=>f.some(d=>d!==null));if(u.length===0)return e;let c=e[x]??[];for(const[f,d]of u){const v=new Set(i(f)),w=c.filter(({key:p})=>v.has(p));if(w.length===0)continue;const A=p=>({consumed:0,key:f.handlerKey,value:p.value});let _=0;const de=d.filter(p=>p===null).length===w.length?d.map(p=>p===null?w[_++]:A(p)):[...w,...d.filter(p=>p!==null).map(A)];c=[...c.filter(({key:p})=>!v.has(p)),...de]}const g=Object.assign(Object.create(null),e);return Object.defineProperty(g,x,{value:c}),g}function ze(e,n,t){const o=!t.startsWith("--")&&e.optionOf(t.slice(0,2))!==void 0;if(!e.includesLooseFlags||o)return;const r=n.get(h(t.replace(/^-+/u,"")));return r===void 0?void 0:{arity:r.arity,declared:r,loose:!0}}export{Z as coerceLooseCommandOptionsWithFlagDefinitions,Pe as collectExtensionFlagDefinitionsForCommand,He as collectLooseCommandOptionKeysForDefinitions,Ye as collectLoosePositionalArgs,en as normalizeDirectExtensionCommandOptions,rn as orderArgvRepeatableSwitchOccurrences,Xe as parseLooseCommandOptions,tn as refuseConflictingArgvOptionSpellings,Qe as resolveExtensionFlagOptionKey,K as resolveLooseOptionCoercionKind,nn as resolveNegatedDeclaredBooleanOption,Ze as stripLooseCommandOptionTokens,Je as validateLooseCommandOptionsWithFlagDefinitions};
2
2
  //# sourceMappingURL=command-options.js.map
@@ -1,3 +1,3 @@
1
- import{createHash as k}from"node:crypto";import{runActiveOnWriteHooks as C}from"../core/extensions/index.js";import{mutateWorkspaceJsonWithHistory as I}from"../core/history/workspace-history.js";import{resolveAuthor as N}from"../core/shared/author.js";import{EXIT_CODE as p}from"../core/shared/constants.js";import{PmCliError as g}from"../core/shared/errors.js";import{asRecordOrNull as w}from"../core/shared/primitives.js";import{stableValueEquals as h}from"../core/shared/serialization.js";import{getSettingsPath as O}from"../core/store/paths.js";import{mergeSettings as E,readSettings as b,runWithConfigurationOnlySettings as P,serializeSettings as A}from"../core/store/settings.js";import{clearSettingsReadCache as W}from"../core/store/settings-read-cache.js";import{readSettingsSection as j,writeSettingsSection as x}from"../core/store/settings-sections.js";import{validateSettings as y}from"../core/store/settings-validator.js";import{isPmCliExpectedError as z}from"./errors.js";import{getItemAt as G}from"./history-read.js";import{fitOutputEnvelope as J}from"./output/fit-envelope.js";import{RelationshipEventLog as R,RelationshipEventStore as U}from"./relationship-history.js";import{analyzeGraphImpact as $}from"./relationship-analytics.js";import{RelationshipGraph as T,createRelationshipKindRegistry as F}from"./relationships.js";import{commitWorkspaceTransaction as D}from"./workspace-transaction.js";function v(t){const m=F();for(const c of t)m.register(c);return m}function H(t,m,c=[]){if(c.length===0)return t;const d=JSON.parse(t),e=JSON.parse(A(m));for(const n of c){const i=n.split(".");let l=e;for(const s of i){const a=w(l);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(s)||["constructor","prototype","__proto__"].includes(s)||a===null||!Object.hasOwn(a,s))throw new g(`Invalid owned settings subtree: ${n}. Select a declared inline object path.`,p.USAGE);l=a[s]}if(w(l)===null)throw new g(`Invalid owned settings subtree: ${n}. Select a declared inline object path.`,p.USAGE);let o=d,u=e;for(const s of i.slice(0,-1)){const a=o[s];u=u[s],a===void 0&&Object.defineProperty(o,s,{value:structuredClone(u),enumerable:!0,writable:!0,configurable:!0}),o=o[s]}Object.defineProperty(o,i.at(-1),{value:l,enumerable:!0,writable:!0,configurable:!0})}return h(d,JSON.parse(t))?t:`${JSON.stringify(d,null,2)}
2
- `}async function K(t,m,c){const d=m.schema?.fields??[];if(d.length===0)return;const{normalizeCliToken:e,resolveRuntimeFieldRegistry:n}=await import("../core/schema/runtime-schema.js"),i=r=>n({fields:[r]}).definitions[0],l=r=>JSON.parse(JSON.stringify(r)),o=[...t.schema.fields,...Array.isArray(c)?c:[]].map(r=>({resolved:i(r),persisted:l(r)})),u=r=>[r.cli_flag,...Array.isArray(r.cli_aliases)?r.cli_aliases:[]].some(f=>typeof f=="string"&&e(f).length===0),s=d.filter(r=>{const f=i(r),_=o.some(S=>h(S.persisted,l(r)));return f===void 0||u(r)?!_:!o.some(S=>h(S.resolved,f))});if(s.length===0)return;const{assertFieldDefinitionOptionsAvailable:a}=await import("./schema/field-option-collisions.js");for(const r of s)a(r)}function ue(t,m,c,d){return{fitOutputEnvelope:J,client:m,isItemNotFoundError:e=>z(e)&&e.exitCode===p.NOT_FOUND,getItemAt:(e,n)=>G(e,n,{pmRoot:t}),readSettingsSection:(e,n)=>j(t,e,n),writeSettingsSection:(e,n,i)=>x(t,e,n,{author:c,...i}),openRelationshipEventStore:e=>U.open({pmRoot:t,nodes:e.nodes,registry:v(e.definitions),...e.relativePath===void 0?{}:{relativePath:e.relativePath}}),createRelationshipGraph:e=>new T(e.nodes,e.edges,v(e.definitions)),analyzeRelationshipImpact:(e,n,i)=>$(e,n,i),validateRelationshipEvents:e=>{const n=new R(e.nodes,{registry:v(e.definitions)});return e.events.map(i=>n.append({...i,expectedVersion:n.version}))},commitWorkspaceTransaction:e=>D({...e,pmRoot:t}),mutateWorkspaceSettings:async e=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(e.operationId))throw new g("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",p.USAGE);const n=e.dryRun===!0?await P(t,()=>b(t)):await b(t);try{const i=await I({pmRoot:t,filePath:O(t),op:"extension:pm:settings",idempotencyKey:d===void 0?e.operationId:`${k("sha256").update(d).digest("hex").slice(0,16)}:${e.operationId}`,author:N(c,n.author_default),lockTtlSeconds:n.locks.ttl_seconds,lockWaitMs:n.locks.wait_ms,recordCreation:!1,dryRun:e.dryRun===!0,mutate:async l=>{const o=l===null?null:JSON.parse(l),u=y(o);if(!u.success)throw new g("Workspace settings mutation requires a valid initialized settings.json.",p.USAGE);const s=E(u.data),a=await e.mutate(structuredClone(s));if(!y(a).success)throw new g("Workspace settings mutation returned invalid settings.json.",p.USAGE);await K(s,a,o.schema?.fields);let r=h(s,a)?l:A(a,{source:{raw:o,validated:u.data}});r=H(r,a,e.replaceSubtrees);const f=y(JSON.parse(r));if(!f.success)throw new g("Workspace settings mutation serialized invalid settings.json.",p.USAGE);return{raw:r,result:e.includePreview===!0?E(f.data):void 0}}});return i.changed&&e.dryRun!==!0&&await C({path:O(t),scope:"project",op:"extension:pm:settings"}),{changed:i.changed,dry_run:e.dryRun===!0,replayed:i.replayed===!0,...i.result===void 0?{}:{preview:i.result}}}finally{W(t)}}}}export{ue as createExtensionCommandSdk};
1
+ import{createHash as N}from"node:crypto";import{runActiveOnWriteHooks as I}from"../core/extensions/index.js";import{mutateWorkspaceJsonWithHistory as P}from"../core/history/workspace-history.js";import{resolveAuthor as W}from"../core/shared/author.js";import{EXIT_CODE as p}from"../core/shared/constants.js";import{PmCliError as h}from"../core/shared/errors.js";import{asRecordOrNull as O}from"../core/shared/primitives.js";import{stableValueEquals as y}from"../core/shared/serialization.js";import{getSettingsPath as E}from"../core/store/paths.js";import{mergeSettings as A,readSettings as k,runWithConfigurationOnlySettings as j,serializeSettings as _}from"../core/store/settings.js";import{clearSettingsReadCache as x}from"../core/store/settings-read-cache.js";import{readSettingsSection as z,writeSettingsSection as G}from"../core/store/settings-sections.js";import{validateSettings as v}from"../core/store/settings-validator.js";import{isPmCliExpectedError as J}from"./errors.js";import{getItemAt as F}from"./history-read.js";import{fitOutputEnvelope as U}from"./output/fit-envelope.js";import{RelationshipEventLog as $,RelationshipEventStore as D}from"./relationship-history.js";import{analyzeGraphImpact as R}from"./relationship-analytics.js";import{RelationshipGraph as T,createRelationshipKindRegistry as K}from"./relationships.js";import{commitWorkspaceTransaction as H}from"./workspace-transaction.js";function b(t){const d=K();for(const s of t)d.register(s);return d}function Z(t,d,s=[]){if(s.length===0)return t;const o=JSON.parse(t),e=JSON.parse(_(d));for(const r of s){const n=r.split(".");let c=e;for(const a of n){const l=O(c);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(a)||["constructor","prototype","__proto__"].includes(a)||l===null||!Object.hasOwn(l,a))throw new h(`Invalid owned settings subtree: ${r}. Select a declared inline object path.`,p.USAGE);c=l[a]}if(O(c)===null)throw new h(`Invalid owned settings subtree: ${r}. Select a declared inline object path.`,p.USAGE);let u=o,f=e;for(const a of n.slice(0,-1)){const l=u[a];f=f[a],l===void 0&&Object.defineProperty(u,a,{value:structuredClone(f),enumerable:!0,writable:!0,configurable:!0}),u=u[a]}Object.defineProperty(u,n.at(-1),{value:c,enumerable:!0,writable:!0,configurable:!0})}return y(o,JSON.parse(t))?t:`${JSON.stringify(o,null,2)}
2
+ `}function C(t,d,s){const o=new Map;for(const e of[...d,...s]){const r=t(e);r!==void 0&&o.set(r.key,r)}return o}function q(t,d){return[...d].filter(([s,o])=>!y(t.get(s),o)).map(([,s])=>s)}async function M(t,d,s,o){const e=d.schema?.fields??[],{normalizeCliToken:r,resolveRuntimeFieldRegistry:n}=await import("../core/schema/runtime-schema.js"),c=i=>n({fields:[i]}).definitions[0],u=i=>JSON.parse(JSON.stringify(i)),f=[...t.schema.fields,...Array.isArray(s)?s:[]].map(i=>({resolved:c(i),persisted:u(i)})),a=i=>[i.cli_flag,...Array.isArray(i.cli_aliases)?i.cli_aliases:[]].some(m=>typeof m=="string"&&r(m).length===0),l=e.filter(i=>{const m=c(i),S=f.some(w=>y(w.persisted,u(i)));return m===void 0||a(i)?!S:!f.some(w=>y(w.resolved,m))});if(l.push(...q(C(c,t.schema.fields,o.before),C(c,o.inlineAfter,o.after))),l.length===0)return;const{assertFieldDefinitionOptionsAvailable:g}=await import("./schema/field-option-collisions.js");for(const i of l)g(i)}function pe(t,d,s,o){return{fitOutputEnvelope:U,client:d,isItemNotFoundError:e=>J(e)&&e.exitCode===p.NOT_FOUND,getItemAt:(e,r)=>F(e,r,{pmRoot:t}),readSettingsSection:(e,r)=>z(t,e,r),writeSettingsSection:(e,r,n)=>G(t,e,r,{author:s,...n}),openRelationshipEventStore:e=>D.open({pmRoot:t,nodes:e.nodes,registry:b(e.definitions),...e.relativePath===void 0?{}:{relativePath:e.relativePath}}),createRelationshipGraph:e=>new T(e.nodes,e.edges,b(e.definitions)),analyzeRelationshipImpact:(e,r,n)=>R(e,r,n),validateRelationshipEvents:e=>{const r=new $(e.nodes,{registry:b(e.definitions)});return e.events.map(n=>r.append({...n,expectedVersion:r.version}))},commitWorkspaceTransaction:e=>H({...e,pmRoot:t}),mutateWorkspaceSettings:async e=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(e.operationId))throw new h("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",p.USAGE);const r=e.dryRun===!0?await j(t,()=>k(t)):await k(t);try{const n=await P({pmRoot:t,filePath:E(t),op:"extension:pm:settings",idempotencyKey:o===void 0?e.operationId:`${N("sha256").update(o).digest("hex").slice(0,16)}:${e.operationId}`,author:W(s,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!1,dryRun:e.dryRun===!0,mutate:async c=>{const u=c===null?null:JSON.parse(c),f=v(u);if(!f.success)throw new h("Workspace settings mutation requires a valid initialized settings.json.",p.USAGE);const a=A(f.data),l=await e.mutate(structuredClone(a));if(!v(l).success)throw new h("Workspace settings mutation returned invalid settings.json.",p.USAGE);let g=y(a,l)?c:_(l,{source:{raw:u,validated:f.data}});g=Z(g,l,e.replaceSubtrees);const i=v(JSON.parse(g));if(!i.success)throw new h("Workspace settings mutation serialized invalid settings.json.",p.USAGE);const m=i.data.schema,{readFieldsFileDefinitions:S}=await import("./schema/field-definition-losses.js");return await M(a,l,u.schema?.fields,{before:await S(t,a.schema),after:await S(t,m),inlineAfter:m?.fields??[]}),{raw:g,result:e.includePreview===!0?A(i.data):void 0}}});return n.changed&&e.dryRun!==!0&&await I({path:E(t),scope:"project",op:"extension:pm:settings"}),{changed:n.changed,dry_run:e.dryRun===!0,replayed:n.replayed===!0,...n.result===void 0?{}:{preview:n.result}}}finally{x(t)}}}}export{pe as createExtensionCommandSdk};
3
3
  //# sourceMappingURL=extension-command-context.js.map