@unbrained/pm-cli 2026.10.28 → 2026.10.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +50 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/commands/lifecycle/append.d.ts +4 -0
- package/dist/cli/commands/lifecycle/append.js +1 -1
- package/dist/cli/commands/lifecycle/create.d.ts +4 -0
- package/dist/cli/commands/lifecycle/create.js +1 -1
- package/dist/cli/commands/lifecycle/plan.d.ts +3 -0
- package/dist/cli/commands/lifecycle/plan.js +1 -1
- package/dist/cli/commands/lifecycle/update-many.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update-many.js +1 -1
- package/dist/cli/commands/lifecycle/update.d.ts +4 -0
- package/dist/cli/commands/lifecycle/update.js +1 -1
- package/dist/cli/error-guidance.d.ts +45 -5
- package/dist/cli/error-guidance.js +5 -3
- package/dist/cli/extension-command-help.d.ts +1 -0
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli/help-content.js +2 -2
- package/dist/cli/main.d.ts +1 -5
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.d.ts +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/preflight-warnings.d.ts +11 -0
- package/dist/cli/preflight-warnings.js +4 -0
- package/dist/cli/register-list-query.js +3 -3
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-24J6TNYE.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-YYD5MNAV.js → chunk-2AHSPMKJ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35Q2B2GJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-43R7UTWV.js +2 -0
- package/dist/cli-bundle/chunks/chunk-6PSDQ7T7.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-YUBUNECD.js → chunk-BS2KXT24.js} +84 -84
- package/dist/cli-bundle/chunks/{chunk-D3AIQZXF.js → chunk-GMBDZID5.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-HSBTITO4.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-LWW4F4G2.js → chunk-MRUA2Z43.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-P3LNMWL2.js +2 -0
- package/dist/cli-bundle/chunks/chunk-PT7TS6E7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D6P6IBPN.js → chunk-TL3O5GZA.js} +45 -45
- package/dist/cli-bundle/chunks/chunk-U7JXZMU5.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-DM3PICGU.js → chunk-V6EWBTNH.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VC7TA67O.js +20 -0
- package/dist/cli-bundle/chunks/chunk-WNF6FOL7.js +31 -0
- package/dist/cli-bundle/chunks/chunk-WRXQAW7Q.js +114 -0
- package/dist/cli-bundle/chunks/{chunk-RZQNFHXO.js → chunk-WX25MU4N.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-XDDPSWIW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YT5D5HNG.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZTJVOBDU.js +128 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-LHLE7PSG.js → indexed-receipt-blobs-KGMJVFH2.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-UWV6UNSV.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-GKDKHRTZ.js → mutation-admission-I4RHIT3Q.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-MHJJUM6M.js → register-list-query-MVDL5EXG.js} +6 -6
- package/dist/cli-bundle/chunks/register-mutation-GAF7LXRB.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-JLFRL36Q.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-WUZ2ZSMY.js → register-setup-MZN6ONB3.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-MN3Y7LVX.js → settlement-hook-YWSWFOZY.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-2FYJGGG3.js → stage-2ZORTOF6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4GN2ZPT5.js → chunk-2J7T2UCH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YLVHHWHN.js → chunk-4PW5XWVI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4QPGJO2G.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IQKLJFJE.js → chunk-57HPXGOQ.js} +18 -18
- package/dist/cli-bundle/focused-chunks/chunk-5MCGYBOQ.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-6F6APBCX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-AFVN2KCP.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ON5WFDCG.js → chunk-DFUTCKUF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EA65HVBO.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-GP2WU43K.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-C2GLO7HU.js → chunk-HPWT3RBG.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-HSAEEWSI.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7SZPZOIC.js → chunk-JLXGRDTG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-JNKRUCVZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JTCGDODH.js → chunk-KH5QJXY7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KKRIFBSL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TUN4M757.js → chunk-MW77Q3AQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NOKG4RFN.js +22 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DRN4W3YJ.js → chunk-NRBUMDLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ML5JIUM6.js → chunk-PC3R5CJV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PFBQOZPK.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-R3EA3SDW.js → chunk-QFMJGQGO.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-I4X6AKOO.js → chunk-SFQKCA5K.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WHIE2C6Q.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y6UYRMVG.js +6 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-5H6RMRTK.js → indexed-receipt-blobs-KHWT44EK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-LU75EG7D.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-admission-TM3SVU2O.js → mutation-admission-KDJ7SCPA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-LBVWWSCF.js → settlement-hook-SJV52ZTV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-7ZBRX2Q2.js → stage-R4KEBO37.js} +2 -2
- package/dist/cli-bundle/main.js +26 -22
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -43
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +61 -61
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +4 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/history/operation-contract.d.ts +2 -2
- package/dist/core/history/operation-contract.js +1 -1
- package/dist/core/item/literal-mutation-input.d.ts +12 -0
- package/dist/core/item/literal-mutation-input.js +2 -0
- package/dist/core/item/parse.d.ts +2 -0
- package/dist/core/item/parse.js +2 -2
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/output.js +3 -3
- package/dist/core/schema/fields-file.js +1 -1
- package/dist/core/sentry/helpers.d.ts +6 -0
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.d.ts +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.d.ts +6 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/output-unicode.d.ts +10 -0
- package/dist/core/shared/output-unicode.js +2 -0
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/core/telemetry/policy.d.ts +8 -0
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/runtime.js +3 -3
- package/dist/sdk/agent/command-recovery.d.ts +15 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +28 -0
- package/dist/sdk/cli-contracts/agent-output-contracts.js +2 -2
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion/fish.js +4 -4
- package/dist/sdk/completion/zsh.js +3 -3
- package/dist/sdk/config.d.ts +1 -0
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/core.d.ts +1 -0
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/error-runtime.d.ts +9 -0
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -2
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/append.js +1 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/cli-input.d.ts +4 -0
- package/dist/sdk/lifecycle/cli-input.js +2 -0
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
- package/dist/sdk/lifecycle/plan.d.ts +2 -3
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/reopen.js +1 -1
- package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +45 -0
- package/dist/sdk/lifecycle/repeated-terminal-state.js +2 -0
- package/dist/sdk/lifecycle/shared-unset-fields.d.ts +9 -0
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/update-many.d.ts +0 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +29 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/output/table-rows.d.ts +15 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.d.ts +18 -0
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/get.d.ts +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/history.d.ts +2 -0
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/query/next-ranking-policy.d.ts +35 -0
- package/dist/sdk/query/next-ranking-policy.js +2 -0
- package/dist/sdk/query/next.d.ts +12 -2
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/projection-contracts.d.ts +4 -0
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/surfaces.d.ts +27 -0
- package/dist/sdk/read-output/surfaces.js +2 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime/mutation-value-validation.d.ts +16 -0
- package/dist/sdk/runtime/mutation-value-validation.js +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +14 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/test/execution-receipts.d.ts +25 -0
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.d.ts +5 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/workspace-transaction-gc.js +1 -1
- package/dist/sdk/workspace-transaction.d.ts +54 -0
- package/dist/sdk/workspace-transaction.js +2 -2
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_OUTPUT_ENCODINGS.md +12 -0
- package/docs/AGENT_UX_CONTRACTS.md +2 -1
- package/docs/COMMANDS.md +73 -15
- package/docs/CONFIGURATION.md +48 -1
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +24 -2
- package/docs/PACKED_FIRST_RUN.md +2 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
- package/docs/SDK.md +207 -11
- package/docs/TESTING.md +46 -2
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2J7I54MQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7V37RC2L.js +0 -114
- package/dist/cli-bundle/chunks/chunk-AHVN4GHF.js +0 -31
- package/dist/cli-bundle/chunks/chunk-CS7QDSUX.js +0 -128
- package/dist/cli-bundle/chunks/chunk-CXUQEZDX.js +0 -8
- package/dist/cli-bundle/chunks/chunk-DKLEDWVW.js +0 -3
- package/dist/cli-bundle/chunks/chunk-E5QBZ4HI.js +0 -8
- package/dist/cli-bundle/chunks/chunk-JESLOJD7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-PQLRKFPZ.js +0 -20
- package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHONSCLJ.js +0 -6
- package/dist/cli-bundle/chunks/chunk-ZX3XMTZG.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-SN425O3R.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-EYUIUGPW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-46WLWK73.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6L4KKRK7.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-6VDRAJYX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-B4ZQJEMT.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-BZSACRVX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-F6UQJJYB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-L5GX2FGZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LPWZERVD.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-OASYSUOH.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-QUPGBO2L.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-Z26ZPQH6.js +0 -3
package/dist/core/item/parse.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b2ae2a38-678e-5f49-9f86-6e1ea4210b34")}catch{}})();import{PmCliError}from"../shared/errors.js";import{EXIT_CODE}from"../shared/constants.js";import{isCliMutationInput,preserveLiteralMutationInput,transferLiteralMutationInput}from"./literal-mutation-input.js";const STDIN_TOKEN="-",CONTINUABLE_VALUE_KEYS=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function looksLikeStructuredKeyValueEntry(raw,keys){if(raw.startsWith("```")||raw.includes(`
|
|
2
2
|
`))return!0;const keyPattern=keys.map(key=>key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${keyPattern})\\s*[:=]`,"i").test(raw)}function parseTags(raw){const trimmed=raw.trim();if(trimmed==="")return[];const tags=(coerceJsonTagArray(trimmed)??trimmed.split(",")).map(tag=>tag.trim()).filter(Boolean).map(tag=>tag.toLowerCase());return Array.from(new Set(tags)).sort((a,b)=>a.localeCompare(b))}function collectTagFlagValues(values){if(!Array.isArray(values)||values.length===0)return[];const collected=[];for(const raw of values)if(typeof raw=="string")for(const tag of parseTags(raw))collected.push(tag);return Array.from(new Set(collected)).sort((a,b)=>a.localeCompare(b))}function normalizeBaseTags(baseTags){return Array.isArray(baseTags)?baseTags.filter(tag=>typeof tag=="string").map(tag=>tag.trim().toLowerCase()).filter(Boolean):[]}function splitAcceptanceCriteria(value){return typeof value!="string"?[]:value.split(";").map(criterion=>criterion.trim()).filter(Boolean)}function applyAcceptanceCriteriaMutations(baseCriteria,add,remove){const criteria=baseCriteria.map(criterion=>criterion.trim()).filter(Boolean);for(const raw of add??[]){const criterion=raw.trim();if(criterion.includes(";"))throw new PmCliError('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',EXIT_CODE.USAGE,{code:"acceptance_criteria_semicolon_forbidden",required:"Pass one semicolon-free criterion per --add-ac value",why:"A semicolon inside one criterion would be re-read as multiple criteria",nextSteps:["Split the text into repeated --add-ac values, or replace the semicolon with punctuation that is not the storage delimiter"]});criterion.length>0&&!criteria.includes(criterion)&&criteria.push(criterion)}const unmatchedRemovals=[];let remaining=criteria;for(const raw of remove??[]){const criterion=raw.trim();if(criterion.length!==0){if(!remaining.includes(criterion)){unmatchedRemovals.push(criterion);continue}remaining=remaining.filter(entry=>entry!==criterion)}}return{criteria:remaining,unmatchedRemovals}}function mergeAdditiveTags(baseTags,add){const normalizedBase=normalizeBaseTags(baseTags);if(!add||add.length===0)return Array.from(new Set(normalizedBase)).sort((a,b)=>a.localeCompare(b));const merged=new Set(normalizedBase);for(const tag of collectTagFlagValues(add))merged.add(tag);return Array.from(merged).sort((a,b)=>a.localeCompare(b))}function applyTagRemovals(baseTags,remove){const normalizedBase=Array.from(new Set(normalizeBaseTags(baseTags))).sort((a,b)=>a.localeCompare(b));if(!remove||remove.length===0)return normalizedBase;const removeSet=new Set(collectTagFlagValues(remove));return removeSet.size===0?normalizedBase:normalizedBase.filter(tag=>!removeSet.has(tag))}function coerceJsonTagArray(trimmed){if(!trimmed.startsWith("["))return null;let parsed;try{parsed=JSON.parse(trimmed)}catch{return null}return parsed.map(entry=>typeof entry=="string"||typeof entry=="number"||typeof entry=="boolean"?String(entry):"").filter(entry=>entry.length>0)}function normalizeLineEndings(value){return value.replace(/\r\n/g,`
|
|
3
3
|
`)}function stripCodeFenceEnvelope(value){const normalized=normalizeLineEndings(value).trim();if(!normalized.startsWith("```"))return value;const lines=normalized.split(`
|
|
4
4
|
`);return lines.length<2||lines.at(-1)?.trim()!=="```"?value:lines.slice(1,-1).join(`
|
|
5
5
|
`)}function splitCsvSegments(raw){const segments=[];let current="",inQuotes=!1;for(let index=0;index<raw.length;index+=1){const char=raw[index];if(char==="\\"&&raw[index+1]===","){current+=",",index+=1;continue}if(char==="\\"&&raw[index+1]!==void 0){current+=`${char}${raw[index+1]}`,index+=1;continue}if(char==='"'){inQuotes=!inQuotes,current+=char;continue}if(char===","&&!inQuotes){segments.push(current),current="";continue}current+=char}return current.trim()&&segments.push(current),segments}function unquoteValue(value){const trimmed=value.trim();if(trimmed.startsWith('"')&&trimmed.endsWith('"')){try{const parsed=JSON.parse(trimmed);if(typeof parsed=="string")return parsed}catch{}return trimmed.slice(1,-1).replace(/\\"/g,'"')}return value}function findKeyValueDelimiter(segment){const equalsIndex=segment.indexOf("="),colonIndex=segment.indexOf(":"),hasEquals=equalsIndex>=0,hasColon=colonIndex>=0;return hasEquals&&hasColon?Math.min(equalsIndex,colonIndex):hasEquals?equalsIndex:hasColon?colonIndex:-1}function buildOptionSpecificKvGuidance(raw,optionName){if((optionName==="--add"||optionName==="--add-glob")&&(/[./\\]/.test(raw)||/\.[a-z]{1,6}$/i.test(raw.trim())))return"For file/doc paths use: path=<file-path>[,scope=project|global]. The scope field is optional and defaults to project (example: path=src/api.ts or path=README.md,scope=project). ";if(optionName!=="--event")return"";const lowered=raw.toLowerCase(),recurrenceHint=lowered.includes("recur_")||lowered.includes("recurrence")?' Recurrence list values must stay in one field and use "|" delimiters (for example recur_by_weekday=mon|wed or recur_by_month_day=1|15).':"",weekdayAliasHint=lowered.includes("recur_byweekday")?" Use recur_by_weekday (with underscores) for weekday recurrence filters.":"";return`${recurrenceHint}${weekdayAliasHint}`}function buildInvalidKvMessage(raw,optionName){const condensed=raw.replaceAll(/\s+/g," ").trim(),preview=condensed.length>160?`${condensed.slice(0,157)}...`:condensed,optionSpecificGuidance=buildOptionSpecificKvGuidance(raw,optionName);return`Invalid ${optionName} value "${preview}". Expected key=value entries separated by commas. `+optionSpecificGuidance+`Also accepts markdown-style key/value lines (for example "- path: README.md"). Use ${optionName} ${STDIN_TOKEN} to read piped stdin input.`}function parseMarkdownKeyValueLines(raw){const normalized=stripCodeFenceEnvelope(raw).trim();if(normalized.length===0||!normalized.includes(`
|
|
6
6
|
`)&&!normalized.startsWith("-")&&!normalized.startsWith("*")&&!normalized.startsWith("+"))return null;const result={};let activeKey;const lines=normalizeLineEndings(normalized).split(`
|
|
7
7
|
`).map(line=>line.trim()).filter(line=>line.length>0);for(const line of lines){const match=line.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(match){const key=match[1].trim();result[key]=unquoteValue(match[3].trim()),activeKey=key;continue}if(activeKey&&CONTINUABLE_VALUE_KEYS.has(activeKey.toLowerCase())){result[activeKey]=`${result[activeKey]}
|
|
8
|
-
${line}`;continue}return null}return result}function parseCsvKv(raw,optionName){const trimmed=stripCodeFenceEnvelope(raw).trim();if(!trimmed)throw new PmCliError(`${optionName} cannot be empty`,EXIT_CODE.USAGE);const markdownStyle=parseMarkdownKeyValueLines(trimmed);if(markdownStyle)return markdownStyle;const result={};let activeKey;const segments=splitCsvSegments(trimmed);for(const segment of segments){const delimiterIndex=findKeyValueDelimiter(segment);if(delimiterIndex>=0){const key=segment.slice(0,delimiterIndex).trim();if(!key)throw new PmCliError(buildInvalidKvMessage(raw,optionName),EXIT_CODE.USAGE);const value=unquoteValue(segment.slice(delimiterIndex+1).trim());result[key]=value,activeKey=key;continue}if(activeKey&&CONTINUABLE_VALUE_KEYS.has(activeKey.toLowerCase())){result[activeKey]=`${result[activeKey]},${segment}`;continue}throw new PmCliError(buildInvalidKvMessage(raw,optionName),EXIT_CODE.USAGE)}return result}const WINDOWS_ABSOLUTE_PATH_PATTERN=/^[A-Za-z]:[\\/]/,GENERIC_LEADING_KV_KEY_PATTERN=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function looksLikeGenericKeyValueEntry(raw){const trimmed=raw.trim();return WINDOWS_ABSOLUTE_PATH_PATTERN.test(trimmed)?!1:GENERIC_LEADING_KV_KEY_PATTERN.test(trimmed)}function assertNoAmbiguousBareCommaEntry(raw,optionName,noun,structured){if(!(structured||!raw.includes(",")))throw new PmCliError(`${optionName} received an ambiguous comma-bearing bare ${noun}. Repeat ${optionName} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,EXIT_CODE.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${optionName} per bare ${noun}, or quote or escape literal commas in a structured key=<value> entry.`})}function assertNoUnknownCsvKeys(kv,optionName,allowedKeys){const allowed=new Set(allowedKeys.map(key=>key.toLowerCase())),unknownKeys=Object.keys(kv).filter(key=>!allowed.has(key.toLowerCase()));if(unknownKeys.length>0)throw new PmCliError(`${optionName} does not recognize key${unknownKeys.length>1?"s":""} ${unknownKeys.map(key=>`"${key}"`).join(", ")}. Allowed keys: ${allowedKeys.join(", ")}.`,EXIT_CODE.USAGE);for(const key of Object.keys(kv)){const normalizedKey=key.toLowerCase();if(normalizedKey!==key){if(Object.hasOwn(kv,normalizedKey))throw new PmCliError(`${optionName} provides key "${key}" more than once after case normalization.`,EXIT_CODE.USAGE);kv[normalizedKey]=kv[key],delete kv[key]}}}async function readStdinText(optionName){if(process.stdin.isTTY===!0)throw new PmCliError(`${optionName} value "${STDIN_TOKEN}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,EXIT_CODE.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((resolve,reject)=>{let input="";process.stdin.on("data",chunk=>{input+=chunk}),process.stdin.on("end",()=>{resolve(normalizeLineEndings(input))}),process.stdin.on("error",error=>{reject(error)})})}const ALL_MUTATION_STDIN_FIELDS=Symbol("all-mutation-stdin-fields"),literalStdinTokenFields=new WeakMap;function preserveMutationStdinTokenLiterals(options){return literalStdinTokenFields.set(options,ALL_MUTATION_STDIN_FIELDS),options}function preserveMutationStdinTokenFields(options,fields){const current=literalStdinTokenFields.get(options);return current===ALL_MUTATION_STDIN_FIELDS||literalStdinTokenFields.set(options,new Set([...current??[],...fields])),options}function transferMutationStdinTokenPolicy(source,target){const policy=literalStdinTokenFields.get(source);return policy===void 0||literalStdinTokenFields.set(target,policy===ALL_MUTATION_STDIN_FIELDS?policy:new Set(policy)),target}function overlayMutationStdinTokenPolicy(source,target){const sourcePolicy=literalStdinTokenFields.get(source),targetPolicy=literalStdinTokenFields.get(target);return sourcePolicy===void 0||targetPolicy===ALL_MUTATION_STDIN_FIELDS?target:sourcePolicy===ALL_MUTATION_STDIN_FIELDS?(literalStdinTokenFields.set(target,sourcePolicy),target):(literalStdinTokenFields.set(target,new Set([...targetPolicy??[],...sourcePolicy])),target)}function shouldResolveMutationStdinTokens(options){return literalStdinTokenFields.get(options)!==ALL_MUTATION_STDIN_FIELDS}function shouldResolveMutationStdinTokenField(options,field){const literalFields=literalStdinTokenFields.get(options);return literalFields!==ALL_MUTATION_STDIN_FIELDS&&!literalFields?.has(field)}function assertSingleStdinTokenConsumer(candidates){let stdinConsumerOption;for(const candidate of candidates){if(candidate.resolveToken===!1||candidate.value===void 0)continue;const tokenCount=(Array.isArray(candidate.value)?candidate.value:[candidate.value]).filter(value=>value.trim()===STDIN_TOKEN).length;if(tokenCount>1)throw new PmCliError(`${candidate.optionName} accepts "${STDIN_TOKEN}" stdin token at most once per command invocation`,EXIT_CODE.USAGE);if(tokenCount!==0){if(stdinConsumerOption!==void 0&&stdinConsumerOption!==candidate.optionName)throw new PmCliError(`Only one option may use "${STDIN_TOKEN}" stdin token per command invocation. Already used by ${stdinConsumerOption}.`,EXIT_CODE.USAGE);stdinConsumerOption=candidate.optionName}}}async function resolveMutationStdinTokenFields(options,scalarFields,listFields){const source=options,definitions=[...scalarFields,...listFields];assertSingleStdinTokenConsumer(definitions.map(([field,optionName])=>({value:source[field],optionName,resolveToken:shouldResolveMutationStdinTokenField(options,field)})));const stdinResolver=createStdinTokenResolver(),resolved={...source};for(const[field,optionName]of scalarFields)resolved[field]=await stdinResolver.resolveValue(source[field],optionName,shouldResolveMutationStdinTokenField(options,field));for(const[field,optionName]of listFields)resolved[field]=await stdinResolver.resolveList(source[field],optionName,shouldResolveMutationStdinTokenField(options,field));return preserveMutationStdinTokenLiterals(resolved)}function createStdinTokenResolver(){let stdinValuePromise,stdinConsumerOption;const consumeStdin=async optionName=>{if(stdinConsumerOption&&stdinConsumerOption!==optionName)throw new PmCliError(`Only one option may use "${STDIN_TOKEN}" stdin token per command invocation. Already used by ${stdinConsumerOption}.`,EXIT_CODE.USAGE);return stdinConsumerOption=optionName,stdinValuePromise||(stdinValuePromise=readStdinText(optionName)),await stdinValuePromise};return{resolveValue:async(value,optionName,resolveToken=!0)=>{if(!resolveToken)return value;if(value!==void 0)return value.trim()!==STDIN_TOKEN?value:await consumeStdin(optionName)},resolveList:async(values,optionName,resolveToken=!0)=>{if(!resolveToken)return values;if(!values)return;const tokenIndexes=values.map((entry,index)=>entry.trim()===STDIN_TOKEN?index:-1).filter(index=>index>=0);if(tokenIndexes.length===0)return values;if(tokenIndexes.length>1)throw new PmCliError(`${optionName} accepts "${STDIN_TOKEN}" stdin token at most once per command invocation`,EXIT_CODE.USAGE);const stdinValue=await consumeStdin(optionName),next=[...values];return next[tokenIndexes[0]]=stdinValue,next}}}function parseOptionalNumber(raw,optionName){const value=Number(raw);if(!Number.isFinite(value))throw new PmCliError(`Invalid ${optionName} value "${raw}"`,EXIT_CODE.USAGE);return value}function parseOptionalNonNegativeInteger(raw,optionName){const trimmed=raw.trim(),value=Number(trimmed);if(trimmed===""||!Number.isInteger(value)||value<0)throw new PmCliError(`Invalid ${optionName} value "${raw}". Expected a non-negative integer.`,EXIT_CODE.USAGE);return value}const _testOnly={coerceJsonTagArray,stripCodeFenceEnvelope,parseMarkdownKeyValueLines};export{_testOnly,applyAcceptanceCriteriaMutations,applyTagRemovals,assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,assertSingleStdinTokenConsumer,collectTagFlagValues,createStdinTokenResolver,looksLikeGenericKeyValueEntry,looksLikeStructuredKeyValueEntry,mergeAdditiveTags,overlayMutationStdinTokenPolicy,parseCsvKv,parseOptionalNonNegativeInteger,parseOptionalNumber,parseTags,preserveMutationStdinTokenFields,preserveMutationStdinTokenLiterals,resolveMutationStdinTokenFields,shouldResolveMutationStdinTokenField,shouldResolveMutationStdinTokens,splitAcceptanceCriteria,transferMutationStdinTokenPolicy};
|
|
8
|
+
${line}`;continue}return null}return result}function parseCsvKv(raw,optionName){const trimmed=stripCodeFenceEnvelope(raw).trim();if(!trimmed)throw new PmCliError(`${optionName} cannot be empty`,EXIT_CODE.USAGE);const markdownStyle=parseMarkdownKeyValueLines(trimmed);if(markdownStyle)return markdownStyle;const result={};let activeKey;const segments=splitCsvSegments(trimmed);for(const segment of segments){const delimiterIndex=findKeyValueDelimiter(segment);if(delimiterIndex>=0){const key=segment.slice(0,delimiterIndex).trim();if(!key)throw new PmCliError(buildInvalidKvMessage(raw,optionName),EXIT_CODE.USAGE);const value=unquoteValue(segment.slice(delimiterIndex+1).trim());result[key]=value,activeKey=key;continue}if(activeKey&&CONTINUABLE_VALUE_KEYS.has(activeKey.toLowerCase())){result[activeKey]=`${result[activeKey]},${segment}`;continue}throw new PmCliError(buildInvalidKvMessage(raw,optionName),EXIT_CODE.USAGE)}return result}const WINDOWS_ABSOLUTE_PATH_PATTERN=/^[A-Za-z]:[\\/]/,GENERIC_LEADING_KV_KEY_PATTERN=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function looksLikeGenericKeyValueEntry(raw){const trimmed=raw.trim();return WINDOWS_ABSOLUTE_PATH_PATTERN.test(trimmed)?!1:GENERIC_LEADING_KV_KEY_PATTERN.test(trimmed)}function assertNoAmbiguousBareCommaEntry(raw,optionName,noun,structured){if(!(structured||!raw.includes(",")))throw new PmCliError(`${optionName} received an ambiguous comma-bearing bare ${noun}. Repeat ${optionName} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,EXIT_CODE.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${optionName} per bare ${noun}, or quote or escape literal commas in a structured key=<value> entry.`})}function assertNoUnknownCsvKeys(kv,optionName,allowedKeys){const allowed=new Set(allowedKeys.map(key=>key.toLowerCase())),unknownKeys=Object.keys(kv).filter(key=>!allowed.has(key.toLowerCase()));if(unknownKeys.length>0)throw new PmCliError(`${optionName} does not recognize key${unknownKeys.length>1?"s":""} ${unknownKeys.map(key=>`"${key}"`).join(", ")}. Allowed keys: ${allowedKeys.join(", ")}.`,EXIT_CODE.USAGE);for(const key of Object.keys(kv)){const normalizedKey=key.toLowerCase();if(normalizedKey!==key){if(Object.hasOwn(kv,normalizedKey))throw new PmCliError(`${optionName} provides key "${key}" more than once after case normalization.`,EXIT_CODE.USAGE);kv[normalizedKey]=kv[key],delete kv[key]}}}async function readStdinText(optionName){if(process.stdin.isTTY===!0)throw new PmCliError(`${optionName} value "${STDIN_TOKEN}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,EXIT_CODE.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((resolve,reject)=>{let input="";process.stdin.on("data",chunk=>{input+=chunk}),process.stdin.on("end",()=>{resolve(normalizeLineEndings(input))}),process.stdin.on("error",error=>{reject(error)})})}const ALL_MUTATION_STDIN_FIELDS=Symbol("all-mutation-stdin-fields"),literalStdinTokenFields=new WeakMap;function preserveSdkMutationInput(options){return isCliMutationInput(options)?options:preserveLiteralMutationInput(preserveMutationStdinTokenLiterals({...options}))}function preserveMutationStdinTokenLiterals(options){return literalStdinTokenFields.set(options,ALL_MUTATION_STDIN_FIELDS),options}function preserveMutationStdinTokenFields(options,fields){const current=literalStdinTokenFields.get(options);return current===ALL_MUTATION_STDIN_FIELDS||literalStdinTokenFields.set(options,new Set([...current??[],...fields])),options}function transferMutationStdinTokenPolicy(source,target){transferLiteralMutationInput(source,target);const policy=literalStdinTokenFields.get(source);return policy===void 0||literalStdinTokenFields.set(target,policy===ALL_MUTATION_STDIN_FIELDS?policy:new Set(policy)),target}function overlayMutationStdinTokenPolicy(source,target){const sourcePolicy=literalStdinTokenFields.get(source),targetPolicy=literalStdinTokenFields.get(target);return sourcePolicy===void 0||targetPolicy===ALL_MUTATION_STDIN_FIELDS?target:sourcePolicy===ALL_MUTATION_STDIN_FIELDS?(literalStdinTokenFields.set(target,sourcePolicy),target):(literalStdinTokenFields.set(target,new Set([...targetPolicy??[],...sourcePolicy])),target)}function shouldResolveMutationStdinTokens(options){return literalStdinTokenFields.get(options)!==ALL_MUTATION_STDIN_FIELDS}function shouldResolveMutationStdinTokenField(options,field){const literalFields=literalStdinTokenFields.get(options);return literalFields!==ALL_MUTATION_STDIN_FIELDS&&!literalFields?.has(field)}function assertSingleStdinTokenConsumer(candidates){let stdinConsumerOption;for(const candidate of candidates){if(candidate.resolveToken===!1||candidate.value===void 0)continue;const tokenCount=(Array.isArray(candidate.value)?candidate.value:[candidate.value]).filter(value=>value.trim()===STDIN_TOKEN).length;if(tokenCount>1)throw new PmCliError(`${candidate.optionName} accepts "${STDIN_TOKEN}" stdin token at most once per command invocation`,EXIT_CODE.USAGE);if(tokenCount!==0){if(stdinConsumerOption!==void 0&&stdinConsumerOption!==candidate.optionName)throw new PmCliError(`Only one option may use "${STDIN_TOKEN}" stdin token per command invocation. Already used by ${stdinConsumerOption}.`,EXIT_CODE.USAGE);stdinConsumerOption=candidate.optionName}}}async function resolveMutationStdinTokenFields(options,scalarFields,listFields){const source=options,definitions=[...scalarFields,...listFields];assertSingleStdinTokenConsumer(definitions.map(([field,optionName])=>({value:source[field],optionName,resolveToken:shouldResolveMutationStdinTokenField(options,field)})));const stdinResolver=createStdinTokenResolver(),resolved={...source};for(const[field,optionName]of scalarFields)resolved[field]=await stdinResolver.resolveValue(source[field],optionName,shouldResolveMutationStdinTokenField(options,field));for(const[field,optionName]of listFields)resolved[field]=await stdinResolver.resolveList(source[field],optionName,shouldResolveMutationStdinTokenField(options,field));return preserveMutationStdinTokenLiterals(transferMutationStdinTokenPolicy(options,resolved))}function createStdinTokenResolver(){let stdinValuePromise,stdinConsumerOption;const consumeStdin=async optionName=>{if(stdinConsumerOption&&stdinConsumerOption!==optionName)throw new PmCliError(`Only one option may use "${STDIN_TOKEN}" stdin token per command invocation. Already used by ${stdinConsumerOption}.`,EXIT_CODE.USAGE);return stdinConsumerOption=optionName,stdinValuePromise||(stdinValuePromise=readStdinText(optionName)),await stdinValuePromise};return{resolveValue:async(value,optionName,resolveToken=!0)=>{if(!resolveToken)return value;if(value!==void 0)return value.trim()!==STDIN_TOKEN?value:await consumeStdin(optionName)},resolveList:async(values,optionName,resolveToken=!0)=>{if(!resolveToken)return values;if(!values)return;const tokenIndexes=values.map((entry,index)=>entry.trim()===STDIN_TOKEN?index:-1).filter(index=>index>=0);if(tokenIndexes.length===0)return values;if(tokenIndexes.length>1)throw new PmCliError(`${optionName} accepts "${STDIN_TOKEN}" stdin token at most once per command invocation`,EXIT_CODE.USAGE);const stdinValue=await consumeStdin(optionName),next=[...values];return next[tokenIndexes[0]]=stdinValue,next}}}function parseOptionalNumber(raw,optionName){const value=Number(raw);if(!Number.isFinite(value))throw new PmCliError(`Invalid ${optionName} value "${raw}"`,EXIT_CODE.USAGE);return value}function parseOptionalNonNegativeInteger(raw,optionName){const trimmed=raw.trim(),value=Number(trimmed);if(trimmed===""||!Number.isInteger(value)||value<0)throw new PmCliError(`Invalid ${optionName} value "${raw}". Expected a non-negative integer.`,EXIT_CODE.USAGE);return value}const _testOnly={coerceJsonTagArray,stripCodeFenceEnvelope,parseMarkdownKeyValueLines};export{_testOnly,applyAcceptanceCriteriaMutations,applyTagRemovals,assertNoAmbiguousBareCommaEntry,assertNoUnknownCsvKeys,assertSingleStdinTokenConsumer,collectTagFlagValues,createStdinTokenResolver,looksLikeGenericKeyValueEntry,looksLikeStructuredKeyValueEntry,mergeAdditiveTags,overlayMutationStdinTokenPolicy,parseCsvKv,parseOptionalNonNegativeInteger,parseOptionalNumber,parseTags,preserveMutationStdinTokenFields,preserveMutationStdinTokenLiterals,preserveSdkMutationInput,resolveMutationStdinTokenFields,shouldResolveMutationStdinTokenField,shouldResolveMutationStdinTokens,splitAcceptanceCriteria,transferMutationStdinTokenPolicy};
|
|
9
9
|
//# sourceMappingURL=parse.js.map
|
package/dist/core/lock/lock.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
-
`,"utf8")}finally{await handle.close()}}catch(error){throw await unlinkLockWithHook(lockPath,"lock:release"),error}}finally{await releaseCleanupGate()}return await emitLockWriteHook(lockPath,"lock:create"),createdAt}async function unlinkLockWithHook(lockPath,op){try{return await fs.unlink(lockPath),await emitLockWriteHook(lockPath,op),!0}catch{return!1}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=
|
|
3
|
-
`,"utf8")}catch{return await removeStaleCleanupGateDirectory(gatePath),null}return owner}async function removeExpiredStaleCleanupGate(gatePath){let gateAgeMs;try{const stats=await fs.stat(gatePath);
|
|
4
|
-
`,{encoding:"utf8",flag:"wx",mode:384})}async function removeConfirmedStaleLock(params){const releaseCleanupGate=await acquireStaleCleanupGate(params.lockPath,params.id);if(releaseCleanupGate===null)return{lockInfo:params.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{const currentLockInfo=await readLockInfo(params.lockPath);if(currentLockInfo.info===null&¤tLockInfo.warnings.length===0)return{lockInfo:currentLockInfo,shouldRetryCreate:!0,staleRemovalCounted:!1};const ownerDead=await isConfirmedDeadLock(currentLockInfo.info);if(!isStaleLock(currentLockInfo.info,params.ttlSeconds)&&!ownerDead)return{lockInfo:currentLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};if(throwIfStaleLockNeedsForce(params.id,currentLockInfo,params.force||ownerDead,params.forceRequiredForStaleLock),params.staleRemovals>=MAX_STALE_LOCK_REMOVALS)throw await buildLockConflictError(params.id,currentLockInfo.info,
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="fa450dd8-119e-5a50-bdc7-e81c1dfdbd9b")}catch{}})();import{isFileMissingError}from"../fs/fs-utils.js";import{constants as fsConstants}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{runActiveOnReadHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{getLockPath}from"../store/paths.js";import{nowIso}from"../shared/time.js";import{captureProcessIdentity,captureLockOwnerIdentity,inspectLockOwner,isProcessIdentityAlive,parseLinuxProcessStartIdentity,readProcessStartIdentity}from"./lock-owner.js";import{captureProcessIdentity as captureProcessIdentity2,isProcessIdentityAlive as isProcessIdentityAlive2,readProcessStartIdentity as readProcessStartIdentity2}from"./lock-owner.js";function parseLockInfo(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{info:null,warnings:["lock_info_invalid_shape"]};const candidate=parsed,id=candidate.id,pid=candidate.pid,owner=candidate.owner,token=candidate.token,createdAt=candidate.created_at,ttlSeconds=candidate.ttl_seconds;return typeof id!="string"||typeof pid!="number"||!Number.isFinite(pid)||typeof owner!="string"||token!==void 0&&(typeof token!="string"||token.trim().length===0)||typeof createdAt!="string"||typeof ttlSeconds!="number"||!Number.isFinite(ttlSeconds)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id,pid,owner,...typeof token=="string"?{token}:{},created_at:createdAt,ttl_seconds:ttlSeconds,host_identity:candidate.host_identity,process_start_identity:candidate.process_start_identity},warnings:[]}}async function readLockInfo(lockPath,emitReadHook=!0){try{const raw=await fs.readFile(lockPath,"utf8");return emitReadHook&&await runActiveOnReadHooks({path:lockPath,scope:"project"}),parseLockInfo(raw)}catch(error){return isFileMissingError(error)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}async function isLockCreateContention(error,lockPath,platform=process.platform){if(isErrno(error,"EEXIST"))return!0;if(!isErrno(error,"EPERM")&&!isErrno(error,"EACCES")&&!isErrno(error,"EBUSY"))return!1;try{return await fs.lstat(lockPath),!0}catch(probeError){if(platform!=="win32"||!isFileMissingError(probeError)&&!isErrno(probeError,"EPERM")&&!isErrno(probeError,"EACCES")&&!isErrno(probeError,"EBUSY"))return!1}try{return await fs.access(path.dirname(lockPath),fsConstants.W_OK),!0}catch{return!1}}async function emitLockWriteHook(lockPath,op){await runActiveOnWriteHooks({path:lockPath,scope:"project",op})}async function buildLockPayload(id,owner,ttlSeconds,token=randomUUID()){return{...await captureLockOwnerIdentity(),id,pid:process.pid,owner,token,created_at:nowIso(),ttl_seconds:ttlSeconds}}async function createLockFile(lockPath,id,owner,ttlSeconds,token,createParentDirectories){createParentDirectories&&await fs.mkdir(path.dirname(lockPath),{recursive:!0});const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null)throw await fs.access(path.dirname(lockPath)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let createdAt;try{const handle=await fs.open(lockPath,"wx");try{try{const payload=await buildLockPayload(id,owner,ttlSeconds,token);createdAt=payload.created_at,await handle.writeFile(`${JSON.stringify(payload,null,2)}
|
|
2
|
+
`,"utf8")}finally{await handle.close()}}catch(error){throw await unlinkLockWithHook(lockPath,"lock:release"),error}}finally{await releaseCleanupGate()}return await emitLockWriteHook(lockPath,"lock:create"),createdAt}async function unlinkLockWithHook(lockPath,op){try{return await fs.unlink(lockPath),await emitLockWriteHook(lockPath,op),!0}catch{return!1}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,!1);isOwnedLock(current2.info,id,owner,token)&&await unlinkLockWithHook(lockPath,"lock:release")}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,owner,token))return;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;return(Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY)>ttlSeconds*1e3}async function isConfirmedDeadLock(info){return info!==null&&Number.isFinite(Date.parse(info.created_at))&&await inspectLockOwner(info)==="dead"}async function isReclaimableLock(info,ttlSeconds){return isStaleLock(info,ttlSeconds)||await isConfirmedDeadLock(info)}async function hasUnexpiredLockOwner(pmRoot,id,ownerPrefix){const{info}=await readLockInfo(getLockPath(pmRoot,id),!1);return info!==null&&info.owner.startsWith(ownerPrefix)&&!await isReclaimableLock(info,info.ttl_seconds)}function lockOwnerSuffix(info){return info?.owner?` (owner ${info.owner})`:""}const LOCK_WAIT_INITIAL_DELAY_MS=25,LOCK_WAIT_MAX_DELAY_MS=200,LOCK_CONFLICT_RETRY_HINT_MS=250,LOCK_PROGRESS_MAX_WAIT_MS=12e4,MAX_STALE_LOCK_REMOVALS=3,STALE_CLEANUP_GATE_SUFFIX=".stale-cleanup",STALE_CLEANUP_GATE_OWNER_FILE="owner.json",STALE_CLEANUP_GATE_STALE_MS=1e4,LOCK_RELEASE_GATE_WAIT_MS=STALE_CLEANUP_GATE_STALE_MS+LOCK_WAIT_MAX_DELAY_MS;function parseNonNegativeIntegerWaitMs(value){if(typeof value=="string"){const trimmed=value.trim();if(!/^\d+$/.test(trimmed))return;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)?parsed:void 0}if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return Math.trunc(value)}function resolveLockWaitMs(waitMs){const envRaw=process.env.PM_LOCK_WAIT_MS,envParsed=parseNonNegativeIntegerWaitMs(envRaw);if(envParsed!==void 0)return envParsed;const callerParsed=parseNonNegativeIntegerWaitMs(waitMs);return callerParsed!==void 0?callerParsed:0}function cappedLockWaitMs(waitMs,maxWaitMs){return Math.min(resolveLockWaitMs(waitMs),maxWaitMs??1/0)}function sleepWithJitter(baseDelayMs){const jitteredMs=Math.max(1,Math.round(baseDelayMs*(.5+Math.random())));return new Promise(resolve=>setTimeout(resolve,jitteredMs))}async function buildLockConflictError(id,info,waitedMs,ownerHandoffs=0){waitedMs=Math.floor(waitedMs);const ownerState=await inspectLockOwner(info),handoffSuffix=ownerHandoffs>0?` across ${ownerHandoffs} owner handoff(s)`:"",waitedSuffix=waitedMs>0?` after waiting ${waitedMs}ms${handoffSuffix}`:"";return new PmCliError(`Item ${id} is locked${lockOwnerSuffix(info)} (owner process ${ownerState})${waitedSuffix}`,EXIT_CODE.CONFLICT,{code:"lock_conflict",item_id:id,reason:`lock_owner_${ownerState}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS,...waitedMs>0?{waited_ms:waitedMs,owner_handoffs:ownerHandoffs}:{}}})}function createLockWaitTracker(waitBudgetMs,totalCeilingMs){const startedAtMs=performance.now();let stallStartedAtMs=startedAtMs,observedGeneration,ownerHandoffs=0;return{startedAtMs,observe(info){const nowMs=performance.now(),generation=lockGenerationKey(info);observedGeneration!==void 0&&generation!==observedGeneration&&(ownerHandoffs+=1,stallStartedAtMs=nowMs),observedGeneration=generation;const elapsedMs=nowMs-startedAtMs,stalledMs=nowMs-stallStartedAtMs;return{exhausted:waitBudgetMs===0||stalledMs>=waitBudgetMs||elapsedMs>=totalCeilingMs,elapsedMs,remainingMs:Math.min(waitBudgetMs-stalledMs,totalCeilingMs-elapsedMs),ownerHandoffs}}}}function resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,waitPolicy){return waitPolicy!=="progress"||maxWaitMs!==void 0?waitBudgetMs:Math.max(waitBudgetMs,LOCK_PROGRESS_MAX_WAIT_MS)}function lockGenerationKey(info){return info===null?"released":info.token??`${info.pid}:${info.owner}:${info.created_at}`}function describeLease(lease){const expiresAtMs=Date.parse(lease.acquiredAt)+lease.ttlSeconds*1e3;return{owner:lease.owner,acquired_at:lease.acquiredAt,ttl_seconds:lease.ttlSeconds,expires_at:new Date(expiresAtMs).toISOString()}}function describeLockLoss(id,lease,current,reason){const leaseLabel=`the lease acquired at ${lease.acquiredAt} (ttl ${lease.ttlSeconds}s)`;if(reason==="fence_gate_unavailable")return{summary:`Lock for ${id} could not be verified before commit: ${leaseLabel} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};const holder=current===null?"the lock no longer exists":`it is now held by ${current.owner} since ${current.created_at}`;return{summary:`Lock for ${id} was lost before commit: ${leaseLabel} is no longer owned by this writer, and ${holder}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function buildLockLostError(id,lease,current,reason){const{summary,required}=describeLockLoss(id,lease,current,reason);return new PmCliError(`${summary} Nothing was written.`,EXIT_CODE.CONFLICT,{code:"lock_lost",item_id:id,reason,lease:describeLease(lease),current_owner:current===null?null:{owner:current.owner,pid:current.pid,created_at:current.created_at,ttl_seconds:current.ttl_seconds},required,recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS}})}async function waitForStaleCleanupGate(lockPath,id){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null)return releaseCleanupGate;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return null;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}async function fenceOwnedLock(lockPath,id,lease,commit){const releaseCleanupGate=await waitForStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null){const current=await readLockInfo(lockPath,!1);throw buildLockLostError(id,lease,current.info,"fence_gate_unavailable")}try{const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,lease.owner,lease.token))throw buildLockLostError(id,lease,current.info,current.info===null?"lease_released":"lease_taken_over");return await commit()}finally{await releaseCleanupGate()}}function resolveLockOverrideRelease(result){if(typeof result=="function")return result;if(typeof result=="object"&&result!==null&&"release"in result){const release=result.release;return typeof release=="function"?release:null}return null}function throwIfStaleLockNeedsForce(id,lockInfo,force,forceRequired){if(!force&&forceRequired){const warningSuffix=lockInfo.warnings.length>0?` (${lockInfo.warnings.join(",")})`:"";throw new PmCliError(`Item ${id} lock is stale${warningSuffix}; rerun with --force when supported for this command`,EXIT_CODE.CONFLICT)}}function parseStaleCleanupGateOwner(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return null;const candidate=parsed,pid=candidate.pid,token=candidate.token,processStartIdentity=candidate.process_start_identity;return typeof pid!="number"||!Number.isInteger(pid)||pid<=0||typeof token!="string"||token.length===0||processStartIdentity!==void 0&&(typeof processStartIdentity!="string"||!/^\d+$/u.test(processStartIdentity))?null:{pid,token,host_identity:candidate.host_identity,...typeof processStartIdentity=="string"?{process_start_identity:processStartIdentity}:{}}}async function readStaleCleanupGateOwner(gatePath){try{return parseStaleCleanupGateOwner(await fs.readFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),"utf8"))}catch(error){return isFileMissingError(error)?null:void 0}}async function removeStaleCleanupGateDirectory(gatePath){try{return await fs.rm(gatePath,{recursive:!0,force:!0}),!0}catch{return!1}}async function releaseStaleCleanupGate(gatePath,token){let owner=await readStaleCleanupGateOwner(gatePath);for(let attempt=0;owner===void 0&&attempt<3;attempt+=1)await sleepWithJitter(LOCK_WAIT_INITIAL_DELAY_MS),owner=await readStaleCleanupGateOwner(gatePath);!owner||owner.token!==token||await removeStaleCleanupGateDirectory(gatePath)}async function tryCreateStaleCleanupGate(gatePath){try{await fs.mkdir(gatePath)}catch(error){return isErrno(error,"EEXIST"),null}const owner={...await captureProcessIdentity(),host_identity:(await captureLockOwnerIdentity()).host_identity,token:randomUUID()};try{await fs.writeFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),`${JSON.stringify(owner)}
|
|
3
|
+
`,"utf8")}catch{return await removeStaleCleanupGateDirectory(gatePath),null}return owner}async function retireCleanupGateGeneration(gatePath,token){const recoveries=path.join(path.dirname(gatePath),"recoveries"),generation=createHash("sha256").update(token).digest("hex");try{return await fs.mkdir(recoveries,{recursive:!0}),(await readStaleCleanupGateOwner(gatePath))?.token!==token?!1:(await fs.rename(gatePath,path.join(recoveries,`gate-${generation}`)),!0)}catch{return!1}}async function removeExpiredStaleCleanupGate(gatePath){let gateAgeMs;try{const stats=await fs.stat(gatePath);gateAgeMs=Date.now()-stats.mtimeMs}catch(error){return isFileMissingError(error)}const owner=await readStaleCleanupGateOwner(gatePath);if(owner===void 0)return!1;if(owner!==null){if(await inspectLockOwner(owner)==="dead")return retireCleanupGateGeneration(gatePath,owner.token);if(owner.host_identity!==void 0)return!1}return gateAgeMs<=STALE_CLEANUP_GATE_STALE_MS||owner!==null&&await isProcessIdentityAlive(owner,gateAgeMs,Number.POSITIVE_INFINITY)?!1:owner!==null?retireCleanupGateGeneration(gatePath,owner.token):removeStaleCleanupGateDirectory(gatePath)}async function acquireStaleCleanupGate(lockPath,_id){const gatePath=`${lockPath}${STALE_CLEANUP_GATE_SUFFIX}`,owner=await tryCreateStaleCleanupGate(gatePath);if(owner!==null)return async()=>releaseStaleCleanupGate(gatePath,owner.token);if(!await removeExpiredStaleCleanupGate(gatePath))return null;const recoveredOwner=await tryCreateStaleCleanupGate(gatePath);return recoveredOwner===null?null:async()=>releaseStaleCleanupGate(gatePath,recoveredOwner.token)}async function recordDeadLockRecovery(lockPath,raw){const directory=path.join(path.dirname(lockPath),"recoveries");await fs.mkdir(directory,{recursive:!0}),await fs.writeFile(path.join(directory,`${randomUUID()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:nowIso(),lock:JSON.parse(raw)})}
|
|
4
|
+
`,{encoding:"utf8",flag:"wx",mode:384})}async function removeConfirmedStaleLock(params){const releaseCleanupGate=await acquireStaleCleanupGate(params.lockPath,params.id);if(releaseCleanupGate===null)return{lockInfo:params.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{const currentLockInfo=await readLockInfo(params.lockPath);if(currentLockInfo.info===null&¤tLockInfo.warnings.length===0)return{lockInfo:currentLockInfo,shouldRetryCreate:!0,staleRemovalCounted:!1};const ownerDead=await isConfirmedDeadLock(currentLockInfo.info);if(!isStaleLock(currentLockInfo.info,params.ttlSeconds)&&!ownerDead)return{lockInfo:currentLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};if(throwIfStaleLockNeedsForce(params.id,currentLockInfo,params.force||ownerDead,params.forceRequiredForStaleLock),params.staleRemovals>=MAX_STALE_LOCK_REMOVALS)throw await buildLockConflictError(params.id,currentLockInfo.info,performance.now()-params.startedAtMs);return ownerDead&&await recordDeadLockRecovery(params.lockPath,JSON.stringify(currentLockInfo.info)),{lockInfo:currentLockInfo,shouldRetryCreate:await unlinkLockWithHook(params.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await releaseCleanupGate()}}const _testOnly={parseLockInfo,readLockInfo,isErrno,isLockCreateContention,buildLockPayload,isStaleLock,lockOwnerSuffix,resolveLockWaitMs,lockGenerationKey,parseLinuxProcessStartIdentity,readProcessStartIdentity,acquireStaleCleanupGate,removeConfirmedStaleLock};async function acquireLock(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){return(await acquireLockLease(pmRoot,id,ttlSeconds,owner,force,forceRequiredForStaleLock,waitMs,options)).release}async function acquireLockLease(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){const maxWaitMs=parseNonNegativeIntegerWaitMs(options.maxWaitMs),lockOverride=await runActiveServiceOverride("lock_acquire",{pm_root:pmRoot,id,ttl_seconds:ttlSeconds,owner,force,force_required_for_stale_lock:forceRequiredForStaleLock,...maxWaitMs===void 0?{}:{max_wait_ms:maxWaitMs}});if(lockOverride.handled){const release=resolveLockOverrideRelease(lockOverride.result);if(release)return{release:async()=>{await Promise.resolve(release()),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>commit()}}const lockPath=getLockPath(pmRoot,id),waitBudgetMs=cappedLockWaitMs(waitMs,maxWaitMs),totalCeilingMs=resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,options.waitPolicy),waitTracker=createLockWaitTracker(waitBudgetMs,totalCeilingMs),startedAtMs=waitTracker.startedAtMs;let staleRemovals=0,backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;const token=randomUUID();for(;;)try{const acquiredAt=await createLockFile(lockPath,id,owner,ttlSeconds,token,options.createParentDirectories!==!1),lease={owner,token,acquiredAt,ttlSeconds};return{release:async()=>{await releaseOwnedLock(lockPath,id,owner,token),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>fenceOwnedLock(lockPath,id,lease,commit)}}catch(error){if(!await isLockCreateContention(error,lockPath))throw new PmCliError(`Failed to acquire lock for ${id}: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE);let lockInfo=await readLockInfo(lockPath);if(await isReclaimableLock(lockInfo.info,ttlSeconds)){const staleRemoval=await removeConfirmedStaleLock({lockPath,id,ttlSeconds,force,forceRequiredForStaleLock,staleRemovals,waitBudgetMs,startedAtMs,fallbackLockInfo:lockInfo});if(lockInfo=staleRemoval.lockInfo,staleRemoval.staleRemovalCounted&&(staleRemovals+=1),staleRemoval.shouldRetryCreate)continue}const observation=waitTracker.observe(lockInfo.info);if(observation.exhausted)throw await buildLockConflictError(id,lockInfo.info,waitBudgetMs===0?0:observation.elapsedMs,observation.ownerHandoffs);await sleepWithJitter(Math.min(backoffMs,observation.remainingMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}export{_testOnly,acquireLock,acquireLockLease,acquireStaleCleanupGate,captureProcessIdentity2 as captureProcessIdentity,hasUnexpiredLockOwner,isProcessIdentityAlive2 as isProcessIdentityAlive,readProcessStartIdentity2 as readProcessStartIdentity,recordDeadLockRecovery,waitForStaleCleanupGate};
|
|
5
5
|
//# sourceMappingURL=lock.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2c705626-fd81-5b65-94cb-760600a88f7c")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadOutputBudgetExceeded,resolveReadOutputEncoding}from"../../sdk/read-output-contracts.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText}from"../shared/output-unicode.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
|
|
2
2
|
`).map(line=>`${indent}${line}`).join(`
|
|
3
|
-
`)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);
|
|
3
|
+
`)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:table.encoding}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
|
|
4
4
|
${renderToonValue(entry,depth+1)}`}function compactToonArray(values,policy,preserveEmpty){const compactedEntries=values.map(entry=>compactToonValue(entry,policy,preserveEmpty||policy.preserveRowFacts&&isPlainObject(entry))).filter(entry=>entry!==void 0);return compactedEntries.length>0||preserveEmpty?compactedEntries:void 0}function compactToonValue(value,policy={omitDuplicateCountAliases:!0,preserveRowFacts:!0},preserveEmpty=!1){if(value===null)return preserveEmpty?null:void 0;if(Array.isArray(value))return compactToonArray(value,policy,preserveEmpty);if(isPlainObject(value)){const compacted=[],entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!policy.omitDuplicateCountAliases||canonicalCount===void 0||!isPlainObject(value.collection_counts)||entry!==value.collection_counts[canonicalCount]});for(const[key,entry]of entries){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted.push([key,[]]);continue}const compactedEntry=compactToonValue(entry,policy,preserveEmpty);compactedEntry!==void 0&&compacted.push([key,compactedEntry])}return compacted.length>0||preserveEmpty?Object.fromEntries(compacted):void 0}return value}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":indentToon(encodeToon(value),depth);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth,!Object.hasOwn(value,`${key}_encoding`)&&!(key==="checks"&&isPlainObject(value.verdict)&&value.verdict.authority==="ok"))).join(`
|
|
5
5
|
`)}return`${indent}${renderScalar(value)}`}function renderDefaultMarkdownResult(value){if(!isPlainObject(value)||value.output_default!=="markdown"||typeof value.view!="string"||!Array.isArray(value.events)||!Array.isArray(value.days))return null;const lines=[`# pm calendar (${value.view})`,""],summary=isPlainObject(value.summary)?value.summary:{};if(lines.push(`- events: ${String(summary.events??0)}`),lines.push(""),value.events.length===0)return lines.push("No calendar events matched the selected filters."),`${lines.join(`
|
|
6
6
|
`)}
|
|
7
7
|
`;for(const event of value.events){if(!isPlainObject(event))continue;const kind=typeof event.kind=="string"?event.kind:"event",title=typeof event.item_title=="string"?event.item_title:"",itemId=typeof event.item_id=="string"?event.item_id:"",reminderText=typeof event.reminder_text=="string"&&event.reminder_text.length>0?` ${event.reminder_text}`:"";lines.push(`- [${kind}] ${itemId} ${title}${reminderText}`.trim())}return`${lines.join(`
|
|
8
8
|
`)}
|
|
9
|
-
`}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0)
|
|
9
|
+
`}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,sharedContext=resolveSharedExecutionContext(rows),runResults=rows.map(row=>{const{execution_context:_executionContext,stdout,stderr,...rest}=row;return sharedContext===void 0?row:!lean||row.status!=="passed"?{...rest,stdout,stderr}:rest});return lean&&isQuietLinkedTestSuccess(value,sharedContext,rows)?projectQuietLinkedTestSuccess(value,sharedContext,runResults):{...value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function resolveSharedExecutionContext(rows){const contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0);if(contexts.length!==rows.length||contexts.length===0)return;const first=JSON.stringify(contexts[0]);return contexts.every(context=>JSON.stringify(context)===first)?contexts[0]:void 0}function isQuietLinkedTestSuccess(value,sharedContext,rows){if(value.ok!==!0||!isPlainObject(sharedContext)||sharedContext.mismatch_detected!==!1||!rows.every(row=>row.status==="passed"))return!1;const categories=value.failure_categories;return!(isPlainObject(categories)&&Object.values(categories).some(count=>count!==0))}function projectQuietLinkedTestSuccess(value,context,runResults){const{failure_categories:_zeroCategories,...rest}=value,trust=isPlainObject(context.trust)?context.trust:{};return{...rest,execution_context:{pm_context_mode:context.pm_context_mode,workspace_context_mode:context.workspace_context_mode,mismatch_detected:!1,...typeof trust.trusted=="boolean"?{trusted:trust.trusted}:{},...trust.reason===void 0?{}:{trust_reason:trust.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:runResults}}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
|
|
10
10
|
`}const compactedToon=compactToonValue(projectEmptyCheckDetails(projectPmBriefListEnvelope(result)),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return compactedToon===void 0?`{}
|
|
11
11
|
`:`${renderToonValue(compactedToon,0)}
|
|
12
12
|
`}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1abceae0-299e-5fff-aa8c-46c015115571")}catch{}})();import{RUNTIME_FIELD_COMMAND_VALUES,RUNTIME_FIELD_TYPE_VALUES}from"../../types/index.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{normalizeStatusToken as normalizeFieldKey}from"./status-token.js";import{normalizeStatusToken}from"./status-token.js";const RUNTIME_FIELD_TYPE_SET=new Set(RUNTIME_FIELD_TYPE_VALUES),RUNTIME_FIELD_COMMAND_SET=new Set(RUNTIME_FIELD_COMMAND_VALUES),BUILTIN_FIELD_KEYS=new Set([...ITEM_METADATA_KEY_ORDER.filter(key=>key!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),DEFAULT_FIELD_COMMANDS=["create","update"];function normalizeCliToken(value){if(typeof value!="string")return"";const collapsed=value.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return collapsed.startsWith("--")?collapsed.slice(2):collapsed}function keyToDefaultCliFlag(key){return key.replaceAll("_","-")}function dedupeCliTokens(values,exclude){const seen=new Set;for(const value of values){const token=normalizeCliToken(value);token.length>0&&token!==exclude&&seen.add(token)}return[...seen].sort((left,right)=>left.localeCompare(right))}function dedupeStringList(values){const seen=new Set;for(const value of values??[]){const trimmed=value.trim();trimmed.length>0&&seen.add(trimmed)}return[...seen].sort((left,right)=>left.localeCompare(right))}function normalizeFieldCommands(rawCommands){const seen=new Set,normalized=[];for(const rawCommand of rawCommands??[]){const command=rawCommand.trim().toLowerCase();if(command.length!==0){if(!RUNTIME_FIELD_COMMAND_SET.has(command))throw new Error(`Invalid field command "${rawCommand}". Allowed: ${RUNTIME_FIELD_COMMAND_VALUES.join(", ")}.`);seen.has(command)||(seen.add(command),normalized.push(command))}}return rawCommands===void 0||normalized.length===0?[...DEFAULT_FIELD_COMMANDS]:normalized}function normalizeAddFieldInput(raw){const key=normalizeFieldKey(raw.key);if(key.length===0)throw new Error("Field key must not be empty.");if(key.includes(","))throw new Error(`Field key "${key}" must not contain commas: commas separate field names in list flags such as --unset and --fields.`);if(BUILTIN_FIELD_KEYS.has(key))throw new Error(`Cannot define custom field "${key}": custom schema field "${key}" collides with built-in item metadata "${key}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...BUILTIN_FIELD_KEYS].sort((left,right)=>left.localeCompare(right)).join(", ")}.`);const typeCandidate=typeof raw.type=="string"&&raw.type.trim().length>0?raw.type.trim().toLowerCase():"string";if(!RUNTIME_FIELD_TYPE_SET.has(typeCandidate))throw new Error(`Invalid field type "${raw.type}". Allowed: ${RUNTIME_FIELD_TYPE_VALUES.join(", ")}.`);const type=typeCandidate,commands=normalizeFieldCommands(raw.commands),cliFlagToken=normalizeCliToken(raw.cliFlag),cliFlag=cliFlagToken.length>0&&cliFlagToken!==keyToDefaultCliFlag(key)?cliFlagToken:void 0,effectiveFlag=cliFlag??keyToDefaultCliFlag(key),cliAliases=dedupeCliTokens(raw.aliases??[],effectiveFlag),commaFlag=[effectiveFlag,...cliAliases].find(flag=>flag.includes(","));if(commaFlag!==void 0)throw new Error(`Field flag "${commaFlag}" must not contain commas.`);const description=raw.description?.trim();return{key,type,commands,description:description&&description.length>0?description:void 0,cliFlag,cliAliases,required:raw.required===!0,requiredOnCreate:raw.requiredOnCreate===!0,allowUnset:raw.allowUnset!==!1,requiredTypes:dedupeStringList(raw.requiredTypes)}}function selectFieldsArray(parsed){if(Array.isArray(parsed))return parsed;if(typeof parsed!="object"||parsed===null)return;const record=parsed;if(Array.isArray(record.fields))return record.fields;if(Array.isArray(record.definitions))return record.definitions}function extractFieldDefinitions(parsed){const candidate=selectFieldsArray(parsed);if(!candidate)return[];const definitions=[];for(const entry of candidate){if(typeof entry!="object"||entry===null||Array.isArray(entry))continue;const record=entry;typeof record.key!="string"||record.key.trim().length===0||definitions.push(record)}return definitions}function parseFieldsFile(raw){if(raw==null||raw.trim().length===0)return{fields:[]};let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:extractFieldDefinitions(parsed)}}function serializeFieldsFile(file){return`${JSON.stringify({fields:file.fields},null,2)}
|
|
2
2
|
`}function upsertField(file,input){const existing=file.fields.find(definition=>normalizeFieldKey(definition.key)===input.key),replaced=existing!==void 0,fields=file.fields.filter(definition=>normalizeFieldKey(definition.key)!==input.key),next={...existing,key:input.key,type:input.type,commands:[...input.commands]};return applyOptionalString(next,"description",input.description),applyOptionalString(next,"cli_flag",input.cliFlag),input.cliAliases.length>0?next.cli_aliases=[...input.cliAliases]:delete next.cli_aliases,applyBooleanFlag(next,"required",input.required),applyBooleanFlag(next,"required_on_create",input.requiredOnCreate),input.allowUnset===!1?next.allow_unset=!1:delete next.allow_unset,input.requiredTypes.length>0?next.required_types=[...input.requiredTypes]:delete next.required_types,fields.push(next),fields.sort((left,right)=>normalizeFieldKey(left.key).localeCompare(normalizeFieldKey(right.key))),{file:{fields},definition:next,replaced}}function removeField(file,key){const normalizedKey=normalizeFieldKey(key);if(normalizedKey.length===0)throw new Error("Field key must not be empty.");const removed=[],fields=file.fields.filter(definition=>normalizeFieldKey(definition.key)===normalizedKey?(removed.push(definition),!1):!0);return removed.length===0?{file:{fields},removed:!1}:{file:{fields},removed:!0,definition:removed[0]}}function applyOptionalString(definition,key,value){const record=definition;value!==void 0&&value.length>0?record[key]=value:delete record[key]}function applyBooleanFlag(definition,key,value){const record=definition;value?record[key]=!0:delete record[key]}export{BUILTIN_FIELD_KEYS,normalizeAddFieldInput,normalizeStatusToken as normalizeFieldKey,parseFieldsFile,removeField,serializeFieldsFile,upsertField};
|
|
3
3
|
//# sourceMappingURL=fields-file.js.map
|
|
@@ -4,6 +4,12 @@ import { type TelemetryCommandResolution,type TelemetryResolutionStage } from ".
|
|
|
4
4
|
export declare function sentrySetCommandContext(command:string,args:string[],options:Record<string,unknown>,metadata?:{
|
|
5
5
|
source_context?:string;
|
|
6
6
|
source_context_source?:string;
|
|
7
|
+
pm_version?:string;
|
|
8
|
+
extension?:{
|
|
9
|
+
name:string;
|
|
10
|
+
version?:string;
|
|
11
|
+
layer:string;
|
|
12
|
+
};
|
|
7
13
|
}):void;
|
|
8
14
|
/** Implements sentry start command span for the public runtime surface of this module. */
|
|
9
15
|
export declare function sentryStartCommandSpan(command:string):void;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="fc213d81-bf8a-50a2-b1a8-1b2a69721855")}catch{}})();import{getSentry}from"./instrument.js";import{PmCliError}from"../shared/errors.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{ExtensionCommandError}from"../../sdk/error-runtime.js";import{EXIT_CODE}from"../shared/constants.js";import{deriveTelemetryCommandResolution,deriveTelemetryCommandTaxonomy}from"../telemetry/observability.js";let activeCommandSpan;function setSpanAttribute(span,key,value){if(value===void 0)return;const attributeTarget=span;typeof attributeTarget.setAttribute=="function"&&attributeTarget.setAttribute(key,value)}function setSentryTagIfPresent(Sentry,key,value){typeof value=="string"&&value.trim().length>0&&Sentry.setTag(key,value)}function setSentryCommandFinishTags(Sentry,normalizedOk,metadata){Sentry.setTag("pm.ok",normalizedOk),Sentry.setTag("pm.command_ok",normalizedOk),typeof metadata?.exit_code=="number"&&(Sentry.setTag("pm.exit_code",String(metadata.exit_code)),Sentry.setTag("pm.command_exit_code",String(metadata.exit_code))),setSentryTagIfPresent(Sentry,"pm.error_code",metadata?.error_code),setSentryTagIfPresent(Sentry,"pm.error_category",metadata?.error_category),setSentryTagIfPresent(Sentry,"pm.command_resolution",metadata?.command_resolution),setSentryTagIfPresent(Sentry,"pm.resolution_stage",metadata?.resolution_stage)}function setCommandSpanFinishAttributes(span,normalizedOk,normalizedExitCode,metadata){setSpanAttribute(span,"pm.ok",normalizedOk),setSpanAttribute(span,"pm.command_ok",normalizedOk),setSpanAttribute(span,"pm.exit_code",normalizedExitCode),setSpanAttribute(span,"pm.command_exit_code",normalizedExitCode),setSpanAttribute(span,"pm.error_code",metadata?.error_code),setSpanAttribute(span,"pm.error_category",metadata?.error_category),setSpanAttribute(span,"pm.command_resolution",metadata?.command_resolution),setSpanAttribute(span,"pm.resolution_stage",metadata?.resolution_stage)}function sentrySetCommandContext(command,args,options,metadata){const Sentry=getSentry();if(!Sentry)return;const taxonomy=deriveTelemetryCommandTaxonomy(command);Sentry.setTag("pm.command",command),Sentry.setTag("pm.command_root",taxonomy.command_root),Sentry.setTag("pm.command_family",taxonomy.command_family),setSentryTagIfPresent(Sentry,"pm.version",metadata?.pm_version),setSentryTagIfPresent(Sentry,"pm.source_context_source",metadata?.source_context_source),Sentry.setTag("pm.extension.name",metadata?.extension?.name),Sentry.setTag("pm.extension.version",metadata?.extension?.version),Sentry.setTag("pm.extension.layer",metadata?.extension?.layer),typeof metadata?.source_context=="string"&&metadata.source_context.trim().length>0&&(Sentry.setTag("pm.source_context",metadata.source_context),Sentry.setAttribute("pm.source_context",metadata.source_context));const safeArgs=args.map(()=>"[redacted]");Sentry.setContext("pm.command",{name:command,root:taxonomy.command_root,leaf:taxonomy.command_leaf,family:taxonomy.command_family,args:safeArgs,option_keys:Object.keys(options).sort(),source_context:metadata?.source_context,source_context_source:metadata?.source_context_source}),Sentry.addBreadcrumb({category:"pm.command",message:`pm ${command}`,level:"info",data:{args:safeArgs,command_root:taxonomy.command_root,command_family:taxonomy.command_family,source_context:metadata?.source_context}})}function sentryStartCommandSpan(command){const Sentry=getSentry();if(!Sentry)return;const taxonomy=deriveTelemetryCommandTaxonomy(command);activeCommandSpan=Sentry.startInactiveSpan({op:"pm.command",name:`pm ${command}`,forceTransaction:!0,attributes:{"pm.command":command,"pm.command_root":taxonomy.command_root,"pm.command_family":taxonomy.command_family}})}function sentryDiscardCommandSpan(){activeCommandSpan=void 0}function sentryFinishCommandSpan(ok,error,metadata){if(!activeCommandSpan)return;const normalizedOk=ok?"true":"false",normalizedExitCode=typeof metadata?.exit_code=="number"?String(metadata.exit_code):void 0,Sentry=getSentry();Sentry&&setSentryCommandFinishTags(Sentry,normalizedOk,metadata),setCommandSpanFinishAttributes(activeCommandSpan,normalizedOk,normalizedExitCode,metadata),activeCommandSpan.setStatus(ok?{code:1}:{code:2,message:error??"command_failed"}),activeCommandSpan.end(),activeCommandSpan=void 0}const UNCLASSIFIED_CAPTURED_ERROR_CODE="unclassified_runtime_error";function readCapturedErrorContract(error){const candidate=typeof error=="object"&&error!==null?error:void 0,hasDeclaredExitCode=typeof candidate?.exitCode=="number",exitCode=hasDeclaredExitCode?Math.trunc(candidate?.exitCode):EXIT_CODE.GENERIC_FAILURE;return{error_code:typeof candidate?.code=="string"&&candidate.code.length>0&&hasDeclaredExitCode?candidate?.code:UNCLASSIFIED_CAPTURED_ERROR_CODE,exit_code:exitCode}}function buildCapturedErrorTags(error){const contract=readCapturedErrorContract(error);return{"pm.error_code":contract.error_code,"pm.exit_code":String(contract.exit_code)}}function sentryCaptureCliError(error){if(!shouldCaptureCliError(error))return;const Sentry=getSentry();if(!Sentry)return;const tags=buildCapturedErrorTags(error);if(error instanceof Error){const extras={};"exitCode"in error&&typeof error.exitCode=="number"&&(extras.exit_code=error.exitCode),"context"in error&&typeof error.context=="object"&&(extras.error_context=error.context),Sentry.captureException(error,{extra:extras,tags})}else Sentry.captureException(new Error(String(error)),{tags})}function sentryLogCliUsageError(params){const Sentry=getSentry();if(!Sentry)return;const resolvedCommandResolution=params.command_resolution??deriveTelemetryCommandResolution({ok:!1,errorCode:params.error_code,errorCategory:params.error_category}),resolvedResolutionStage=params.resolution_stage??"unknown",payload={"pm.command":params.command,"pm.error_code":params.error_code,"pm.error_category":params.error_category,"pm.exit_code":params.exit_code,"pm.error_message":params.error_message,"pm.command_resolution":resolvedCommandResolution,"pm.resolution_stage":resolvedResolutionStage,"pm.source_context":params.source_context??""},loggerCandidate=Sentry.logger;if(loggerCandidate&&typeof loggerCandidate.warn=="function"){loggerCandidate.warn("pm_cli_usage_error",payload);return}Sentry.captureMessage(`pm_cli_usage_error:${params.error_code}`,{level:"warning",tags:{"pm.command":params.command,"pm.error_code":params.error_code,"pm.error_category":params.error_category,"pm.exit_code":String(params.exit_code),"pm.command_resolution":resolvedCommandResolution,"pm.resolution_stage":resolvedResolutionStage,"pm.source_context":params.source_context??"unknown"},extra:payload})}function shouldCaptureCliError(error){if(error instanceof ExtensionCommandError)return!0;if(error instanceof PmCliError||isPmCliExpectedError(error)||error instanceof Error&&error.name==="AbortError"&&/(?:ctrl\+[cd]|sigint|user[- ]initiated)/i.test(error.message))return!1;if(typeof error=="object"&&error!==null&&"exitCode"in error&&typeof error.exitCode=="number"){if(error instanceof Error&&error.name==="CommandError")return!1;const exitCode=Math.trunc(error.exitCode);return!new Set([EXIT_CODE.SUCCESS,EXIT_CODE.USAGE,EXIT_CODE.NOT_FOUND,EXIT_CODE.CONFLICT]).has(exitCode)}return!0}async function sentryFlush(timeoutMs=3e3){const Sentry=getSentry();if(Sentry)try{await Sentry.flush(timeoutMs)}catch{}}export{UNCLASSIFIED_CAPTURED_ERROR_CODE,sentryCaptureCliError,sentryDiscardCommandSpan,sentryFinishCommandSpan,sentryFlush,sentryLogCliUsageError,sentrySetCommandContext,sentryStartCommandSpan,shouldCaptureCliError};
|
|
2
2
|
//# sourceMappingURL=helpers.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="07b08f80-aa60-5ffa-b969-2859839f3f2d")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy}from"../telemetry/policy.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event){return!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();return explicit&&explicit.length>0?explicit:process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test"?"test":process.env.CI?"ci":"production"}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}const beforeSend=event=>{if(isExpectedCliErrorEvent(event)||isKnownNoisyConsoleEvent(event))return null;isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>(log.message=scrubString(log.message),log.attributes&&(log.attributes=scrubEventData(log.attributes)),log);function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes)for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(client)return client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="16379104-dc20-5034-95ab-ebeb63f54952")}catch{}})();import{createRequire}from"node:module";import{resolvePmCliVersion}from"../packages/root.js";import{resolveTelemetryEnvironmentPolicy,resolveTelemetrySourceAttribution}from"../telemetry/policy.js";import{isPmCliExpectedError}from"../../sdk/errors.js";import{scrubInlineSensitiveAssignments,SENSITIVE_KEY_PATTERN}from"./sensitive-assignments.js";const OPT_OUT_VALUES=new Set(["1","true","yes","on"]);function isSentryDisabled(){return!!(OPT_OUT_VALUES.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||resolveTelemetryEnvironmentPolicy().telemetry_disabled||typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string")}const ABSOLUTE_PATH_TOKEN_RE=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,FILE_URL_PATH_RE=/file:\/\/\/?[^\s"'`),;]+/giu,WINDOWS_PATH_TOKEN_RE=/\b[A-Za-z]:\\[^\s"'`),;]+/g,PRIVATE_IP_RE=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,PATH_FIELD_KEY_PATTERN=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=15,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function looksLikeFilesystemPath(value){const normalized=value.trim();return normalized.length===0?!1:normalized.startsWith("/")||normalized.startsWith("file://")||/^[A-Za-z]:\\/.test(normalized)||normalized.startsWith("\\\\")?!0:normalized.includes("/home/")}function scrubString(value,keyHint){if(keyHint&&PATH_FIELD_KEY_PATTERN.test(keyHint)&&looksLikeFilesystemPath(value))return"[scrubbed_path]";const scrubbed=scrubInlineSensitiveAssignments(value).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(PRIVATE_IP_RE,"[scrubbed_ip]").replaceAll(FILE_URL_PATH_RE,"[scrubbed_path]").replaceAll(WINDOWS_PATH_TOKEN_RE,"[scrubbed_path]").replaceAll(ABSOLUTE_PATH_TOKEN_RE,(_match,prefix)=>`${prefix}[scrubbed_path]`);return looksLikeFilesystemPath(scrubbed)?"[scrubbed_path]":scrubbed}function scrubEventData(obj){const result={};for(const[key,value]of Object.entries(obj))SENSITIVE_KEY_PATTERN.test(key)||key.startsWith("sentry.message.parameter.")?result[key]="[scrubbed]":typeof value=="string"?result[key]=scrubString(value,key):Array.isArray(value)?result[key]=value.map(entry=>typeof entry=="string"?scrubString(entry,key):entry&&typeof entry=="object"?scrubEventData(entry):entry):value&&typeof value=="object"?result[key]=scrubEventData(value):result[key]=value;return result}function scrubStackFrame(frame){for(const key of["filename","absPath","abs_path","module"]){const rawValue=frame[key];typeof rawValue=="string"&&(frame[key]=scrubString(rawValue,key))}const contextLine=frame.context_line;typeof contextLine=="string"&&(frame.context_line=scrubString(contextLine,"context_line"));for(const key of["pre_context","post_context"]){const context=frame[key];Array.isArray(context)&&(frame[key]=context.map(entry=>typeof entry=="string"?scrubString(entry,key):entry))}frame.vars&&typeof frame.vars=="object"&&(frame.vars=scrubEventData(frame.vars)),frame.data&&typeof frame.data=="object"&&(frame.data=scrubEventData(frame.data))}const requireFromInstrument=createRequire(import.meta.url),defaultSentryLoader=()=>requireFromInstrument("@sentry/node");let _sentry,_initDone=!1,_loadSentry=defaultSentryLoader;const PM_CLI_SENTRY_DSN="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function hasPmCliErrorPrefix(value){return/^\s*PmCliError:/.test(value)}function isKnownNoisyConsoleMessage(value){const normalized=value.trim().toLowerCase();return normalized.length===0?!1:KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS.some(pattern=>normalized.includes(pattern))}function isKnownNoisyConsoleEvent(event){return event.logger!=="console"?!1:typeof event.message=="string"&&isKnownNoisyConsoleMessage(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>typeof entry.value=="string"&&isKnownNoisyConsoleMessage(entry.value))}function isNodeRuntimeWarningEvent(event){if(event.logger!=="console")return!1;const isRuntimeWarning=value=>typeof value=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(value);return isRuntimeWarning(event.message)?!0:Array.isArray(event.exception?.values)&&event.exception.values.some(entry=>isRuntimeWarning(entry.value))}function isExpectedCliErrorEvent(event,originalException){return originalException instanceof Error?isPmCliExpectedError(originalException):!!(event.exception?.values?.some(ex=>ex.type==="PmCliError")||event.exception?.values?.some(ex=>typeof ex.value=="string"&&hasPmCliErrorPrefix(ex.value))||event.logger==="console"&&typeof event.message=="string"&&hasPmCliErrorPrefix(event.message))}function isPmCliErrorBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&hasPmCliErrorPrefix(breadcrumb.message)}function isKnownNoisyConsoleBreadcrumb(breadcrumb){return breadcrumb.category==="console"&&typeof breadcrumb.message=="string"&&isKnownNoisyConsoleMessage(breadcrumb.message)}function resolveCliVersion(){return resolvePmCliVersion(import.meta.url,["../../.."])??"0.0.0"}function resolveEnvironment(){const explicit=process.env.SENTRY_ENVIRONMENT?.trim();if(explicit&&explicit.length>0)return explicit;if(process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test")return"test";if(process.env.CI)return"ci";const source=resolveTelemetrySourceAttribution().source_context;return source==="user"?"production":source}const DEFAULT_TRACES_SAMPLE_RATE=.2;function resolveTracesSampleRate(){const raw=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!raw)return DEFAULT_TRACES_SAMPLE_RATE;const parsed=Number(raw);return!Number.isFinite(parsed)||parsed<0||parsed>1?DEFAULT_TRACES_SAMPLE_RATE:parsed}function scrubSentryExceptionValues(event){if(event.exception?.values){for(const exception of event.exception.values)if(exception.value&&(exception.value=scrubString(exception.value,"value")),exception.stacktrace?.frames)for(const frame of exception.stacktrace.frames)scrubStackFrame(frame)}}function scrubSentryBreadcrumbs(event){if(event.breadcrumbs)for(const breadcrumb of event.breadcrumbs)breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message)),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data))}function scrubSentryContexts(event){if(event.contexts)for(const[ctxKey,ctx]of Object.entries(event.contexts))ctx&&typeof ctx=="object"&&(event.contexts[ctxKey]=scrubEventData(ctx))}function scrubSentryRecordField(event,key){const target=event,value=target[key];value&&typeof value=="object"&&(target[key]=scrubEventData(value))}function sourceContextEnvironment(source){if(!process.env.SENTRY_ENVIRONMENT?.trim()&&(source==="automation"||source==="test"||source==="dogfood"||source==="user"))return source==="user"?"production":source}function applySourceContextEnvironment(event){const environment=sourceContextEnvironment(event.tags?.["pm.source_context"]);environment&&(event.environment=environment)}const beforeSend=(event,hint)=>{if(isExpectedCliErrorEvent(event,hint?.originalException)||isKnownNoisyConsoleEvent(event))return null;applySourceContextEnvironment(event),isNodeRuntimeWarningEvent(event)&&(event.level="warning",event.tags={...event.tags,"pm.diagnostic_class":"node_runtime_warning"}),event.message&&(event.message=scrubString(event.message,"message")),event.transaction&&(event.transaction=scrubString(event.transaction,"transaction")),scrubSentryExceptionValues(event),scrubSentryBreadcrumbs(event),scrubSentryRecordField(event,"extra"),scrubSentryContexts(event);for(const key of["request","user","tags"])scrubSentryRecordField(event,key);return event},beforeSendTransaction=event=>(applySourceContextEnvironment(event),event.breadcrumbs&&(event.breadcrumbs=event.breadcrumbs.filter(breadcrumb=>!isPmCliErrorBreadcrumb(breadcrumb)&&!isKnownNoisyConsoleBreadcrumb(breadcrumb)),scrubSentryBreadcrumbs(event)),scrubSentryContexts(event),event),beforeSendSpan=span=>scrubEventData(span),beforeSendLog=log=>{if(log.message=scrubString(log.message),log.attributes){const environment=sourceContextEnvironment(log.attributes["pm.source_context"]);environment&&(log.attributes["sentry.environment"]=environment),log.attributes=scrubEventData(log.attributes)}return log};function applySerializedLogEnvironment(attributes){const environment=sourceContextEnvironment(attributes["pm.source_context"]?.value);environment&&(attributes["sentry.environment"]={type:"string",value:environment})}function scrubSentryLogEnvelope(envelope){for(const item of envelope[1])if(item[0].type==="log")for(const log of item[1].items){log.body=scrubString(log.body);const attributes=log.attributes;if(attributes){applySerializedLogEnvironment(attributes);for(const[key,attribute]of Object.entries(attributes)){const value=scrubEventData({[key]:attribute.value})[key];typeof value=="string"&&(attributes[key]={type:"string",value})}}}}const beforeBreadcrumb=breadcrumb=>isPmCliErrorBreadcrumb(breadcrumb)||isKnownNoisyConsoleBreadcrumb(breadcrumb)?null:(breadcrumb.message&&(breadcrumb.message=scrubString(breadcrumb.message,"message")),breadcrumb.data&&typeof breadcrumb.data=="object"&&(breadcrumb.data=scrubEventData(breadcrumb.data)),breadcrumb);async function ensureSentryInit(){if(_initDone)return _sentry;if(_initDone=!0,isSentryDisabled())return;const SentryModule=_loadSentry(),dsn=process.env.SENTRY_DSN?.trim()||PM_CLI_SENTRY_DSN,release=resolveCliVersion();SentryModule.init({dsn,release:`pm-cli@${release}`,environment:resolveEnvironment(),tracesSampleRate:resolveTracesSampleRate(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,traceLifecycle:"stream",dataCollection:{userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,graphQL:{document:!1,variables:!1},stackFrameVariables:!1,frameContextLines:0},serverName:void 0,integrations:[SentryModule.extraErrorDataIntegration({depth:4,captureErrorCause:!1}),SentryModule.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":release,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend,beforeSendTransaction,beforeSendSpan:SentryModule.withStreamedSpan(beforeSendSpan),beforeSendLog,beforeBreadcrumb});const client=SentryModule.getClient();if(!client)return;const attribution=resolveTelemetrySourceAttribution();return SentryModule.setTags({"pm.version":release,"pm.source_context":attribution.source_context,"pm.source_context_source":attribution.source_context_source}),SentryModule.setAttribute("pm.source_context",attribution.source_context),client.on("beforeEnvelope",scrubSentryLogEnvelope),_sentry=SentryModule,SentryModule}async function ensureSentryCommandTracing(telemetryEnabled){if(telemetryEnabled!==!0||!OPT_OUT_VALUES.has((process.env.PM_SENTRY_TRACE_COMMANDS??"").trim().toLowerCase())||resolveTracesSampleRate()===0||isSentryDisabled())return!1;try{return await ensureSentryInit()!==void 0}catch{return _sentry=void 0,!1}}function getSentry(){return _sentry}const _testOnly={isExpectedCliErrorEvent,isKnownNoisyConsoleEvent,isNodeRuntimeWarningEvent,isPmCliErrorBreadcrumb,isKnownNoisyConsoleBreadcrumb,scrubString,scrubEventData,resolveTracesSampleRate,KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,MAX_KNOWN_NOISY_CONSOLE_MESSAGE_PATTERNS,defaultSentryLoader,setSentryLoaderForTests(loader){_loadSentry=loader??defaultSentryLoader},resetSentryStateForTests(){_sentry=void 0,_initDone=!1}};export{_testOnly,ensureSentryCommandTracing,ensureSentryInit,getSentry};
|
|
2
2
|
//# sourceMappingURL=instrument.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="426ae308-83c5-5c99-bb0d-c63e9c890570")}catch{}})();import{createDefaultExtensionGovernancePolicy}from"../extensions/extension-types.js";import{ITEM_METADATA_KEY_ORDER,ITEM_PROJECT_CONTEXT_KEYS}from"./item-metadata-contract.js";const DEFAULT_STATUS_DEFINITIONS=Object.freeze([{id:"draft",roles:["draft"]},{id:"open",roles:["active","default_open"]},{id:"in_progress",aliases:["in-progress"],roles:["active"]},{id:"blocked",roles:["blocked"]},{id:"closed",roles:["terminal","terminal_done","default_close"]},{id:"canceled",aliases:["cancelled"],roles:["terminal","terminal_canceled","default_cancel"]}]),DEFAULT_WORKFLOW_DEFINITION=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),PM_DIRNAME=".agents/pm",SETTINGS_FILENAME="settings.json",CREATE_DIRECT_CLOSE_REASON_DEFAULT="Closed at creation via pm create",PM_CORE_REQUIRED_SUBDIRS=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],PM_OPTIONAL_TYPE_SUBDIRS=["decisions","events","reminders","milestones","meetings","plans"],PM_REQUIRED_SUBDIRS=[...PM_CORE_REQUIRED_SUBDIRS,...PM_OPTIONAL_TYPE_SUBDIRS],TYPE_TO_FOLDER={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},GOVERNANCE_PRESET_DEFAULTS={minimal:{ownership_enforcement:"none",create_mode_default:"progressive",close_validation_default:"off",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!1,duplicate_detection_mode:"off",duplicate_detection_threshold:.8,duplicate_detection_limit:3},default:{ownership_enforcement:"warn",create_mode_default:"progressive",close_validation_default:"warn",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3},strict:{ownership_enforcement:"strict",create_mode_default:"strict",close_validation_default:"strict",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"strict",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3}},DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS={blocked_reason:["no active blocker because work is closed","work is closed"],resolution:["closed with implementation evidence","closed with verification evidence","work completed and recorded","work is closed"],actual_result:["closed and recorded","work completed","work completed and recorded"]};function cloneOptionalArray(values){return values?[...values]:void 0}const SETTINGS_DEFAULTS={version:1,id_prefix:"pm-",ids:{token_length:4},author_default:"",agent_identity:{probes_enabled:!0,identity_vocabulary:{version:1,aliases:{}},harness_signals:[]},mutation_guard:{require_attributed_author:!1,secret_guard:"advise",stale_in_progress_hours:72},item_format:"toon",locks:{ttl_seconds:1800,wait_ms:3e3},checkpoints:{retention_days:14},output:{default_format:"toon"},ux:{deprecation_hints:!0},history:{missing_stream:"auto_create",compact_policy:{enabled:!1,max_entries:500,trigger:"health_warn"}},validation:{sprint_release_format:"warn",parent_reference:"warn",metadata_profile:"core",metadata_required_fields:[],lifecycle_stale_blocker_reason_patterns:[...DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS],lifecycle_closure_like_blocked_reason_patterns:[...DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.blocked_reason],lifecycle_closure_like_resolution_patterns:[...DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.resolution],lifecycle_closure_like_actual_result_patterns:[...DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...GOVERNANCE_PRESET_DEFAULTS.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1,allow_untrusted_linked_tests:!1},telemetry:{enabled:!0,first_run_prompt_completed:!1,capture_level:"redacted",endpoint:"https://pm-cli.unbrained.dev/v1/events",installation_id:"",retention_days:365},agent_guidance:{prompt_completed:!1,declined:!1,declined_at:"",template_version:1,last_checked_files:[]},item_types:{definitions:[]},schema:{version:1,files:{types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"},statuses:DEFAULT_STATUS_DEFINITIONS.map(definition=>({...definition,aliases:cloneOptionalArray(definition.aliases),roles:cloneOptionalArray(definition.roles)})),fields:[],workflow:{...DEFAULT_WORKFLOW_DEFINITION},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:createDefaultExtensionGovernancePolicy()},search:{score_threshold:0,hybrid_semantic_weight:.7,max_results:50,embedding_model:"",embedding_batch_size:32,embedding_timeout_ms:3e4,scanner_max_batch_retries:3,provider:"",default_mode:"auto",mutation_refresh_policy:"semantic_configured",query_expansion:{enabled:!1,provider:""},rerank:{enabled:!1,model:"",top_k:20}},providers:{openai:{base_url:"",api_key:"",model:""},ollama:{base_url:"",model:""}},context:{default_depth:"brief",activity_limit:10,stale_threshold_days:7,next_ranking_policy:"priority_floor",sections:{hierarchy:!0,activity:!0,progress:!0,recently_created:!0,unparented:!0,blockers:!0,files:!0,workload:!0,staleness:!0,tests:!0}},vector_store:{adapter:"",collection_name:"pm_items",qdrant:{url:"",api_key:""},lancedb:{path:""}}},EMPTY_CANONICAL_DOCUMENT={metadata:{},body:""},EXIT_CODE={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},TELEMETRY_ERROR_CATEGORY_BY_CODE=Object.freeze({unknown_command:"usage",unknown_option:"usage",missing_required_option:"usage",missing_required_argument:"usage",invalid_command_usage:"usage",linked_test_value_not_quoted:"usage",invalid_argument_value:"validation",health_findings:"validation",validation_findings:"validation",close_through_update:"validation",no_update_fields:"validation",unsupported_update_option:"validation",tracker_not_initialized:"validation",item_not_found:"validation",ownership_conflict:"conflict",lock_conflict:"conflict",terminal_state_conflict:"conflict",dependency_failed:"runtime",init_gitignore_unwritable:"runtime",merge_git_config_unwritable:"runtime",command_failed:"runtime",unknown_error:"runtime"});function resolveTelemetryErrorCategory(errorCode){const normalized=(errorCode??"").trim().toLowerCase();if(normalized.length===0)return"unknown";const explicit=TELEMETRY_ERROR_CATEGORY_BY_CODE[normalized];return typeof explicit=="string"?explicit:normalized.includes("conflict")||normalized.includes("locked")?"conflict":normalized.startsWith("unknown_")||normalized.startsWith("missing_required_")?"usage":normalized.startsWith("invalid_")||normalized.endsWith("_not_found")||normalized.includes("validation")?"validation":normalized.endsWith("_error")||normalized.endsWith("_failed")?"runtime":"unknown"}export{CREATE_DIRECT_CLOSE_REASON_DEFAULT,DEFAULT_STATUS_DEFINITIONS,DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS,DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS,DEFAULT_WORKFLOW_DEFINITION,EMPTY_CANONICAL_DOCUMENT,EXIT_CODE,GOVERNANCE_PRESET_DEFAULTS,ITEM_METADATA_KEY_ORDER,ITEM_PROJECT_CONTEXT_KEYS,PM_CORE_REQUIRED_SUBDIRS,PM_DIRNAME,PM_OPTIONAL_TYPE_SUBDIRS,PM_REQUIRED_SUBDIRS,SETTINGS_DEFAULTS,SETTINGS_FILENAME,TELEMETRY_ERROR_CATEGORY_BY_CODE,TYPE_TO_FOLDER,resolveTelemetryErrorCategory};
|
|
2
2
|
//# sourceMappingURL=constants.js.map
|
|
@@ -271,6 +271,12 @@ first_timestamp:string | null;
|
|
|
271
271
|
/** Latest available history timestamp, or null for an empty stream. */
|
|
272
272
|
last_timestamp:string | null;
|
|
273
273
|
};
|
|
274
|
+
/** Principal that currently holds the item behind an `already_claimed_by` refusal. */
|
|
275
|
+
claimed_by?:string;
|
|
276
|
+
/** When that holder took the item, from the latest assignee change in history; null when history is unavailable. */
|
|
277
|
+
claimed_at?:string | null;
|
|
278
|
+
/** Whether the holder arrived through an explicit claim or a metadata assignment; `unknown` when history cannot say. */
|
|
279
|
+
claim_source?:"claim" | "assignment" | "unknown";
|
|
274
280
|
/** Lease a refused `lock_lost` commit held when it tried to commit. */
|
|
275
281
|
lease?:{
|
|
276
282
|
/** Principal recorded as the lease owner. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="277cefd2-1da3-55f6-aa07-9f0d34d02314")}catch{}})();class PmCliError extends Error{exitCode;code;context;constructor(message,exitCode,context={}){super(message),this.name="PmCliError",this.exitCode=exitCode,this.context=context,this.code=context.code}}export{PmCliError};
|
|
2
2
|
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Replace lone UTF-16 surrogates while preserving valid astral characters. */
|
|
2
|
+
export declare function toWellFormedText(value:string):string;
|
|
3
|
+
/** Build the validated snapshot used by both native formatters, without a second toJSON call. */
|
|
4
|
+
export declare function prepareWellFormedOutputText(value:unknown):unknown;
|
|
5
|
+
/**
|
|
6
|
+
* Refuse malformed strings or keys in JSON-compatible output with a typed field
|
|
7
|
+
* diagnostic. This never changes the caller's data. Use toWellFormedText at an
|
|
8
|
+
* external text boundary when replacement is the producer's intended policy.
|
|
9
|
+
*/
|
|
10
|
+
export declare function assertWellFormedOutputText(value:unknown):void;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1b399abd-460a-55a5-9df2-db23537aac0d")}catch{}})();import{isBoxedPrimitive}from"node:util/types";import{EXIT_CODE}from"./constants.js";import{PmCliError}from"./errors.js";const LONE_SURROGATE_PATTERN=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/gu;function toWellFormedText(value){return value.replaceAll(LONE_SURROGATE_PATTERN,"\uFFFD")}function outputFieldPath(field,key,array){return array&&/^\d+$/u.test(key)?`${field}[${key}]`:/^[A-Za-z_$][\w$]*$/u.test(key)?`${field}.${key}`:`${field}[${JSON.stringify(key)}]`}function findIllFormedOutputText(value,field,seen){if(typeof value=="string"){const index=value.search(LONE_SURROGATE_PATTERN);return index<0?void 0:{field,index}}if(!(value===null||typeof value!="object"||seen.has(value))){seen.add(value);for(const[key,entry]of Object.entries(value)){const child=outputFieldPath(field,key,Array.isArray(value)),malformed=findIllFormedOutputText(key,`${child} (key)`,seen)??findIllFormedOutputText(entry,child,seen);if(malformed)return malformed}}}function snapshotOutputText(value,key,seen){if(value===null||typeof value!="object")return value;if(isBoxedPrimitive(value)||typeof value.toJSON=="function")return JSON.parse(JSON.stringify({[key]:value}))[key];if(seen.has(value))return seen.get(value);const snapshot=Array.isArray(value)?new Array(value.length):{};seen.set(value,snapshot);for(const childKey of Object.keys(value))Object.defineProperty(snapshot,childKey,{value:snapshotOutputText(value[childKey],childKey,seen),enumerable:!0,configurable:!0,writable:!0});return snapshot}function prepareWellFormedOutputText(value){const snapshot=snapshotOutputText(value,"",new WeakMap),malformed=findIllFormedOutputText(snapshot,"$",new WeakSet);return malformed&&throwIllFormedOutputText(malformed),snapshot}function throwIllFormedOutputText(malformed){throw new PmCliError(`Output field ${malformed.field} contains an unpaired surrogate code unit at index ${malformed.index}; structured output requires well-formed Unicode.`,EXIT_CODE.USAGE,{code:"text_unpaired_surrogate",field:malformed.field,required:"Well-formed UTF-16 strings and object keys in both JSON and TOON output.",nextSteps:["Repair the producer's text before returning output; use toWellFormedText from @unbrained/pm-cli/sdk when replacement is intended."]})}function assertWellFormedOutputText(value){prepareWellFormedOutputText(value)}export{assertWellFormedOutputText,prepareWellFormedOutputText,toWellFormedText};
|
|
2
|
+
//# sourceMappingURL=output-unicode.js.map
|