@komatikai/trailhead 4.4.6 → 4.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","mappings":";;AAAA;AACA;AACA;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;;;;ACAA;AACA;;;;;;ACDA;;;ACAA;;ACAA;;;ACAA;AACA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAYA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAGA;AACA;AAEA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AAEA;AACA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AAGA;AACA;AACA;AAGA;AAEA;AACA;AACA;AAkCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AAAA;AACA;AACA;AACA;;;AChoBA;AACA;AACA;AACA;AAQA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AAAA;;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AAEA;AAKA;AAIA;AAEA;AAKA;AAKA;AAKA;AAKA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AAEA;AAMA;AACA;AACA;AACA;AAEA;AAMA;AAKA;AACA;AACA;AAKA;AAKA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AAEA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AAKA;AACA;AAKA;AACA;AACA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AAKA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAGA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAGA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AAGA;AAAA;AACA;AACA;AAEA;AACA;;AAEA;;AAEA;;;AAGA;;;AAGA;AACA;AAEA;AACA;;;AClaA;AAUA;;AAEA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AAAA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AAAA;AAEA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAKA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAKA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAGA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACRA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5mHA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/mBA;AAGA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;;;ACtHA;;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAGA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAGA;AAEA;AACA;AAGA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;;;ACnJA;AACA;AACA;AACA;AACA;AA8BA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAOA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAKA;AAAA;AAEA;AAIA;AACA;AACA;AAEA;AAIA;AAAA;AAEA;AAIA;AACA;AAEA;AAKA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAOA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAAA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;;;ACraA;AAEA;AACA;;;;;;;;;;;;;;;;;;AAkBA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;;;ACvFA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AACA;AAGA;AAEA;AAIA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AAAA;AACA;AACA;;;ACrJA;AACA;AAIA;AAEA;AACA;AACA;AAEA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/ZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/wHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AAYA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;;;;AAIA;AACA;AAIA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AAEA;AACA;AACA;AAMA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AAAA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAGA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACrLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AASA;AAGA;AACA;AAAA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AAAA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;;;AC/HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAQA;AAGA;AACA;AAAA;AAEA;AACA;AACA;AACA;AAAA;AAEA;AAGA;AAAA;AAEA;AAGA;AAAA;AAEA;AACA;AAEA;AAAA;AAEA;AAIA;AACA;AACA;AACA;AACA;AAGA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAQA;AAGA;AACA;AAAA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAEA;AAAA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;;;AC7GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AAAA;AACA;AAAA;AAEA;AAEA;AACA;AACA;AAGA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAIA;AAEA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;;;ACnFA;;ACAA;AACA;AAEA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;;;ACzCA;AACA;AA8DA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAIA;AAAA;AAEA;AACA;AAEA;AAAA;AACA;AAAA;AAEA;AAEA;AAIA;AACA;AAEA;AAEA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AAEA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAIA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAOA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAGA;AACA;AACA;AACA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAGA;AAAA;AAEA;AAGA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAAA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAAA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AAAA;AAEA;AAEA;AACA;AACA;AAGA;AAAA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAQA;AAMA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;;;AChlBA;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;;;ACrDA;AAQA;AACA;AAkBA;AAGA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AAGA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAKA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;;;ACtGA;AAIA;AAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AAEA;AAGA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAGA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AAAA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAKA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AAEA;AAEA;AAMA;AACA;AAEA;AACA;AAEA;AAAA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AACA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AAQA;AACA;AAEA;AACA;AAAA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAIA;AAAA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAEA;AAEA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AAEA;AACA;AAAA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AAAA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;;;AC9pBA;AACA;AAEA;AAEA;AACA;AAMA;AAKA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AAqBA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AAEA;AAIA;AAAA;AACA;AACA;;;AChHA;AACA;AACA;AACA;AAKA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAUA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;;AAEA;;;;;AAKA;;AAEA;;AAEA;AACA;AAEA;AACA;AACA;AACA","sources":["../webpack/bootstrap","../webpack/runtime/compat get default export","../webpack/runtime/define property getters","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/compat","../external node-commonjs \"node:fs\"","../external node-commonjs \"node:readline\"","../external node-commonjs \"node:path\"",".././cli/src/generators.ts",".././cli/src/init-wizard.ts",".././cli/src/shared/ci-core.ts",".././node_modules/zod/v3/helpers/util.js",".././node_modules/zod/v3/ZodError.js",".././node_modules/zod/v3/locales/en.js",".././node_modules/zod/v3/errors.js",".././node_modules/zod/v3/helpers/errorUtil.js",".././node_modules/zod/v3/helpers/parseUtil.js",".././node_modules/zod/v3/types.js",".././cli/src/shared/types.ts",".././cli/src/shared/config-core.ts",".././cli/src/shared/release-ready.ts",".././cli/src/shared/doctor.ts",".././cli/src/run-doctor.ts",".././cli/src/shared/submission-checks/helpers.ts",".././cli/src/shared/submission-checks/phase0-detectors.ts",".././node_modules/js-yaml/dist/js-yaml.mjs",".././cli/src/shared/submission-checks/contract-integrity.ts",".././cli/src/shared/submission-checks/safe-deprecation.ts",".././cli/src/shared/submission-checks/destructive-change.ts",".././cli/src/shared/submission-checks/claim-anchoring.ts",".././cli/src/shared/submission-checks/promotion-coherence.ts","../external node-commonjs \"@swc/core\"",".././cli/src/shared/submission-checks/syntax-validity.ts",".././cli/src/shared/risk-engine.ts",".././cli/src/shared/submission-checks/policy-defaults.ts",".././cli/src/shared/submission-checks/detector-policy.ts",".././cli/src/shared/submission-checks/detectors.ts",".././cli/src/shared/submission-engine.ts",".././cli/src/index.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","\nif (typeof __webpack_require__ !== 'undefined') __webpack_require__.ab = __dirname + \"/\";","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"node:fs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"node:readline\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"node:path\");","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport type GateModeOption = \"release-ready\" | \"risk-only\" | \"advisory\";\nexport type BranchModel = \"main-only\" | \"progressive\";\nexport type AudienceId = \"solo\" | \"team\" | \"agent\" | \"ops\" | \"custom\";\n\nexport function parseCheckList(input: string, fallback: string[]): string[] {\n const list = input\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n return list.length > 0 ? list : fallback;\n}\n\nconst AUDIENCE_COMMENTS: Record<AudienceId, string> = {\n solo: \"# Preset: solo — one repo, Release Ready beyond CI green\",\n team: \"# Preset: team — progressive dev → staging → main\",\n agent: \"# Preset: agent-guard — AI-authored PR safety (submission gate)\",\n ops: \"# Preset: ops — freeze windows, health probes, DORA\",\n custom: \"# Trailhead v4 configuration\",\n};\n\nexport function generateTrailheadYml(options: {\n highSensitivity: string[];\n mediumSensitivity: string[];\n riskThreshold: number;\n warnThreshold: number;\n freezeDays: string[];\n freezeAfterHour: number | null;\n environments: Array<{ name: string; risk: number; warn: number }>;\n services: Array<{ name: string; paths: string[]; env: string }>;\n securityGate: boolean;\n canaryType: string;\n}): string {\n const lines: string[] = [\n \"# Trailhead v3 configuration\",\n \"# https://github.com/KomatikAI/trailhead\",\n \"\",\n ];\n\n if (options.highSensitivity.length > 0 || options.mediumSensitivity.length > 0) {\n lines.push(\"sensitivity:\");\n if (options.highSensitivity.length > 0) {\n lines.push(\" high:\");\n for (const p of options.highSensitivity) lines.push(` - \"${p}\"`);\n }\n if (options.mediumSensitivity.length > 0) {\n lines.push(\" medium:\");\n for (const p of options.mediumSensitivity) lines.push(` - \"${p}\"`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"thresholds:\");\n lines.push(` risk: ${options.riskThreshold}`);\n lines.push(` warn: ${options.warnThreshold}`);\n lines.push(\"\");\n\n if (options.environments.length > 0) {\n lines.push(\"environments:\");\n for (const env of options.environments) {\n lines.push(` ${env.name}:`);\n lines.push(` risk: ${env.risk}`);\n lines.push(` warn: ${env.warn}`);\n }\n lines.push(\"\");\n }\n\n if (options.services.length > 0) {\n lines.push(\"services:\");\n for (const svc of options.services) {\n lines.push(` ${svc.name}:`);\n lines.push(\" paths:\");\n for (const p of svc.paths) lines.push(` - \"${p}\"`);\n if (svc.env) lines.push(` environment: ${svc.env}`);\n }\n lines.push(\"\");\n }\n\n if (options.securityGate) {\n lines.push(\"security:\");\n lines.push(\" severity_threshold: warning\");\n lines.push(\" block_on_critical: true\");\n lines.push(\"\");\n }\n\n if (options.canaryType) {\n lines.push(\"canary:\");\n lines.push(` webhook_type: ${options.canaryType}`);\n lines.push(\"\");\n }\n\n if (options.freezeDays.length > 0 && options.freezeAfterHour !== null) {\n lines.push(\"freeze:\");\n lines.push(\" - days:\");\n for (const d of options.freezeDays) lines.push(` - \"${d}\"`);\n lines.push(` afterHour: ${options.freezeAfterHour}`);\n lines.push(` message: \"No deploys during freeze window\"`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport interface TrailheadYmlV2Options {\n audience?: AudienceId;\n gateMode: GateModeOption;\n branchModel: BranchModel;\n riskThreshold: number;\n warnThreshold: number;\n featureRisk: number;\n featureWarn: number;\n stagingRisk: number;\n stagingWarn: number;\n productionRisk: number;\n productionWarn: number;\n featureChecks: string[];\n promotionChecks: string[];\n highSensitivity: string[];\n mediumSensitivity: string[];\n freezeDays: string[];\n freezeAfterHour: number | null;\n environments: Array<{ name: string; risk: number; warn: number }>;\n services: Array<{ name: string; paths: string[]; env: string }>;\n securityGate: boolean;\n canaryType: string;\n mainContextInheritsGlobalThresholds?: boolean;\n submissionEnabled?: boolean;\n remediationEnabled?: boolean;\n agentPolicies?: boolean;\n agentBrief?: boolean;\n}\n\nexport function generateTrailheadYmlV2(options: TrailheadYmlV2Options): string {\n const audience = options.audience ?? \"custom\";\n const lines: string[] = [\n AUDIENCE_COMMENTS[audience],\n \"# https://github.com/KomatikAI/trailhead\",\n \"\",\n \"schema_version: 2\",\n \"\",\n \"gate:\",\n ` mode: ${options.gateMode}`,\n ];\n if (options.agentBrief) {\n lines.push(\" agent_brief: collapsed\");\n }\n lines.push(\n \"\",\n \"thresholds:\",\n ` risk: ${options.riskThreshold}`,\n ` warn: ${options.warnThreshold}`,\n \"\",\n );\n\n if (options.gateMode !== \"risk-only\") {\n lines.push(\"contexts:\");\n if (options.branchModel === \"progressive\") {\n lines.push(\" - name: feature\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - dev\");\n lines.push(\" - develop\");\n lines.push(\" environment: dev\");\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.featureRisk}`);\n lines.push(` warn: ${options.featureWarn}`);\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.featureChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: skip\");\n lines.push(\"\");\n lines.push(\" - name: staging-promotion\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - staging\");\n lines.push(\" environment: staging\");\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.stagingRisk}`);\n lines.push(` warn: ${options.stagingWarn}`);\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.promotionChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: fail\");\n lines.push(\"\");\n lines.push(\" - name: production-promotion\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - main\");\n lines.push(\" - master\");\n lines.push(\" environment: production\");\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.productionRisk}`);\n lines.push(` warn: ${options.productionWarn}`);\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.promotionChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: fail\");\n lines.push(\"\");\n } else {\n lines.push(\" - name: main\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - main\");\n lines.push(\" - master\");\n lines.push(\" environment: production\");\n if (!options.mainContextInheritsGlobalThresholds) {\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.productionRisk}`);\n lines.push(` warn: ${options.productionWarn}`);\n }\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.promotionChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: fail\");\n lines.push(\"\");\n }\n }\n\n if (options.highSensitivity.length > 0 || options.mediumSensitivity.length > 0) {\n lines.push(\"sensitivity:\");\n if (options.highSensitivity.length > 0) {\n lines.push(\" high:\");\n for (const p of options.highSensitivity) lines.push(` - \"${p}\"`);\n }\n if (options.mediumSensitivity.length > 0) {\n lines.push(\" medium:\");\n for (const p of options.mediumSensitivity) lines.push(` - \"${p}\"`);\n }\n lines.push(\"\");\n }\n\n if (options.environments.length > 0) {\n lines.push(\"environments:\");\n for (const env of options.environments) {\n lines.push(` ${env.name}:`);\n lines.push(` risk: ${env.risk}`);\n lines.push(` warn: ${env.warn}`);\n }\n lines.push(\"\");\n }\n\n if (options.services.length > 0) {\n lines.push(\"services:\");\n for (const svc of options.services) {\n lines.push(` ${svc.name}:`);\n lines.push(\" paths:\");\n for (const p of svc.paths) lines.push(` - \"${p}\"`);\n if (svc.env) lines.push(` environment: ${svc.env}`);\n }\n lines.push(\"\");\n }\n\n if (options.agentPolicies) {\n lines.push(\"policies:\");\n lines.push(\" agent_prs:\");\n lines.push(\" enabled: true\");\n lines.push(` risk_threshold: ${Math.max(0, options.warnThreshold)}`);\n lines.push(\" strict_on_unknown_provenance: true\");\n lines.push(\" require_code_owner_approval: false\");\n lines.push(\" ci_integrity:\");\n lines.push(\" mode: block\");\n lines.push(\" workflow_security:\");\n lines.push(\" mode: block\");\n lines.push(\" prompt_injection:\");\n lines.push(\" mode: block\");\n lines.push(\" pr_scope:\");\n lines.push(\" mode: warn\");\n lines.push(\" max_files: 30\");\n lines.push(\" max_changes: 1500\");\n lines.push(\"\");\n }\n\n if (options.remediationEnabled) {\n lines.push(\"remediation:\");\n lines.push(\" enabled: true\");\n lines.push(\" max_loop_rounds: 5\");\n lines.push(\"\");\n }\n\n if (options.submissionEnabled) {\n lines.push(\"submission:\");\n lines.push(\" enabled: true\");\n lines.push(\" mode: block\");\n lines.push(\"\");\n }\n\n if (options.securityGate) {\n lines.push(\"security:\");\n lines.push(\" severity_threshold: warning\");\n lines.push(\" block_on_critical: true\");\n lines.push(\"\");\n }\n\n if (options.canaryType) {\n lines.push(\"canary:\");\n lines.push(` webhook_type: ${options.canaryType}`);\n lines.push(\"\");\n }\n\n if (options.freezeDays.length > 0 && options.freezeAfterHour !== null) {\n lines.push(\"freeze:\");\n lines.push(\" - days:\");\n for (const d of options.freezeDays) lines.push(` - \"${d}\"`);\n lines.push(` afterHour: ${options.freezeAfterHour}`);\n lines.push(` message: \"No deploys during freeze window\"`);\n lines.push(\"\");\n }\n\n if (options.agentPolicies) {\n lines.push(\"override:\");\n lines.push(\" enabled: true\");\n lines.push(\" max_per_week: 5\");\n lines.push(\"\");\n lines.push(\"tuning:\");\n lines.push(\" auto_downgrade: true\");\n lines.push(\" fp_threshold: 0.15\");\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport interface WorkflowYmlOptions {\n riskThreshold: number;\n healthCheckUrls: string[];\n doraMetrics: boolean;\n doraEnvironment: string;\n otelEndpoint: string;\n evaluationStoreUrl: string;\n storeSecretName: string;\n supabaseFallback: boolean;\n securityGate: boolean;\n environment: string;\n gateMode: GateModeOption;\n waitForChecks: boolean;\n submissionGate?: boolean;\n}\n\nexport function generateWorkflowYml(options: WorkflowYmlOptions): string {\n const lines: string[] = [\n \"name: Trailhead\",\n \"\",\n \"on:\",\n \" pull_request:\",\n \" types: [opened, synchronize, reopened]\",\n \"\",\n \"permissions:\",\n \" contents: read\",\n \" pull-requests: write\",\n \" checks: write\",\n \" security-events: read\",\n \"\",\n \"jobs:\",\n \" trailhead:\",\n \" runs-on: ubuntu-latest\",\n \" steps:\",\n \" - uses: actions/checkout@v4\",\n \"\",\n \" - uses: KomatikAI/trailhead@v4\",\n \" id: gate\",\n \" with:\",\n ];\n\n if (options.gateMode !== \"risk-only\") {\n lines.push(` gate-mode: \"${options.gateMode}\"`);\n if (options.waitForChecks) {\n lines.push(' wait-for-checks: \"true\"');\n lines.push(' wait-timeout-minutes: \"30\"');\n }\n }\n\n lines.push(` risk-threshold: \"${options.riskThreshold}\"`);\n\n if (options.submissionGate) {\n lines.push(' submission-gate: \"true\"');\n }\n\n if (options.healthCheckUrls.length > 0) {\n lines.push(` health-check-urls: \"${options.healthCheckUrls.join(\",\")}\"`);\n }\n\n if (options.doraMetrics) {\n lines.push(' dora-metrics: \"true\"');\n }\n\n if (options.doraEnvironment) {\n lines.push(` dora-environment: \"${options.doraEnvironment}\"`);\n }\n\n if (options.environment) {\n lines.push(` environment: \"${options.environment}\"`);\n }\n\n if (!options.securityGate) {\n lines.push(' security-gate: \"false\"');\n }\n\n if (options.otelEndpoint) {\n lines.push(` otel-endpoint: \"${options.otelEndpoint}\"`);\n }\n\n if (options.evaluationStoreUrl) {\n lines.push(` evaluation-store-url: \"${options.evaluationStoreUrl}\"`);\n if (options.storeSecretName) {\n lines.push(\n ` evaluation-store-secret: \\${{ secrets.${options.storeSecretName} }}`,\n );\n }\n }\n\n const envLines: string[] = [];\n if (options.evaluationStoreUrl && options.storeSecretName) {\n envLines.push(\n ` EVALUATION_STORE_SECRET: \\${{ secrets.${options.storeSecretName} }}`,\n );\n }\n if (options.supabaseFallback) {\n envLines.push(` SUPABASE_URL: \\${{ secrets.SUPABASE_URL }}`);\n envLines.push(\n ` SUPABASE_SERVICE_ROLE_KEY: \\${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}`,\n );\n }\n\n if (envLines.length > 0) {\n lines.push(\" env:\");\n for (const el of envLines) lines.push(el);\n }\n\n if (options.doraMetrics) {\n lines.push(\"\");\n lines.push(\" - name: DORA outputs\");\n lines.push(\" if: always()\");\n lines.push(\" run: |\");\n lines.push(' echo \"dora-rating: ${{ steps.gate.outputs.dora-rating }}\"');\n lines.push(\n ' echo \"dora-freq: ${{ steps.gate.outputs.dora-deployment-frequency }}\"',\n );\n lines.push(\n ' echo \"dora-cfr: ${{ steps.gate.outputs.dora-change-failure-rate }}\"',\n );\n lines.push(' echo \"dora-lead: ${{ steps.gate.outputs.dora-lead-time }}\"');\n lines.push(' echo \"dora-fdrt: ${{ steps.gate.outputs.dora-fdrt }}\"');\n lines.push(\n ' echo \"dora-rework: ${{ steps.gate.outputs.dora-rework-rate }}\"',\n );\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport interface InitProfile {\n audience: AudienceId;\n gateMode: GateModeOption;\n branchModel: BranchModel;\n riskThreshold: number;\n warnThreshold: number;\n featureChecks: string[];\n promotionChecks: string[];\n highSensitivity: string[];\n mediumSensitivity: string[];\n freezeDays: string[];\n freezeAfterHour: number | null;\n environments: Array<{ name: string; risk: number; warn: number }>;\n services: Array<{ name: string; paths: string[]; env: string }>;\n securityGate: boolean;\n canaryType: string;\n healthCheckUrls: string[];\n doraMetrics: boolean;\n doraEnvironment: string;\n otelEndpoint: string;\n evaluationStoreUrl: string;\n storeSecretName: string;\n supabaseFallback: boolean;\n environment: string;\n submissionGate: boolean;\n submissionEnabled: boolean;\n remediationEnabled: boolean;\n agentPolicies: boolean;\n agentBrief: boolean;\n mainContextInheritsGlobalThresholds: boolean;\n}\n\nexport function profileFromAudience(audience: AudienceId): InitProfile {\n const base: InitProfile = {\n audience,\n gateMode: \"release-ready\",\n branchModel: \"main-only\",\n riskThreshold: 70,\n warnThreshold: 55,\n featureChecks: [\"CI\", \"Build\"],\n promotionChecks: [\"CI\", \"Build\"],\n highSensitivity: [],\n mediumSensitivity: [],\n freezeDays: [],\n freezeAfterHour: null,\n environments: [],\n services: [],\n securityGate: true,\n canaryType: \"\",\n healthCheckUrls: [],\n doraMetrics: false,\n doraEnvironment: \"\",\n otelEndpoint: \"\",\n evaluationStoreUrl: \"\",\n storeSecretName: \"\",\n supabaseFallback: false,\n environment: \"\",\n submissionGate: false,\n submissionEnabled: false,\n remediationEnabled: false,\n agentPolicies: false,\n agentBrief: false,\n mainContextInheritsGlobalThresholds: true,\n };\n\n switch (audience) {\n case \"team\":\n return {\n ...base,\n branchModel: \"progressive\",\n promotionChecks: [\"CI\", \"Build\", \"Playwright\"],\n mainContextInheritsGlobalThresholds: false,\n };\n case \"agent\":\n return {\n ...base,\n riskThreshold: 60,\n warnThreshold: 40,\n submissionGate: true,\n submissionEnabled: true,\n remediationEnabled: true,\n agentPolicies: true,\n agentBrief: true,\n mainContextInheritsGlobalThresholds: true,\n };\n case \"ops\":\n return {\n ...base,\n riskThreshold: 70,\n warnThreshold: 55,\n freezeDays: [\"friday\", \"saturday\"],\n freezeAfterHour: 15,\n canaryType: \"generic\",\n doraMetrics: true,\n environments: [\n { name: \"production\", risk: 65, warn: 50 },\n { name: \"staging\", risk: 75, warn: 55 },\n ],\n environment: \"production\",\n mainContextInheritsGlobalThresholds: false,\n };\n case \"custom\":\n return { ...base, mainContextInheritsGlobalThresholds: false };\n default:\n return base;\n }\n}\n\nexport function writeInitArtifacts(profile: InitProfile, cwd = process.cwd()): void {\n const useV2 = profile.gateMode !== \"risk-only\";\n const configContent = useV2\n ? generateTrailheadYmlV2({\n audience: profile.audience,\n gateMode: profile.gateMode,\n branchModel: profile.branchModel,\n riskThreshold: profile.riskThreshold,\n warnThreshold: profile.warnThreshold,\n featureRisk: Math.min(100, profile.riskThreshold + 5),\n featureWarn: profile.warnThreshold,\n stagingRisk: Math.max(0, profile.riskThreshold - 5),\n stagingWarn: Math.max(0, profile.warnThreshold - 10),\n productionRisk: profile.mainContextInheritsGlobalThresholds\n ? profile.riskThreshold\n : Math.max(0, profile.riskThreshold - 10),\n productionWarn: profile.mainContextInheritsGlobalThresholds\n ? profile.warnThreshold\n : Math.max(0, profile.warnThreshold - 15),\n featureChecks: profile.featureChecks,\n promotionChecks: profile.promotionChecks,\n highSensitivity: profile.highSensitivity,\n mediumSensitivity: profile.mediumSensitivity,\n freezeDays: profile.freezeDays,\n freezeAfterHour: profile.freezeAfterHour,\n environments: profile.environments,\n services: profile.services,\n securityGate: profile.securityGate,\n canaryType: profile.canaryType,\n mainContextInheritsGlobalThresholds: profile.mainContextInheritsGlobalThresholds,\n submissionEnabled: profile.submissionEnabled,\n remediationEnabled: profile.remediationEnabled,\n agentPolicies: profile.agentPolicies,\n agentBrief: profile.agentBrief,\n })\n : generateTrailheadYml({\n highSensitivity: profile.highSensitivity,\n mediumSensitivity: profile.mediumSensitivity,\n riskThreshold: profile.riskThreshold,\n warnThreshold: profile.warnThreshold,\n freezeDays: profile.freezeDays,\n freezeAfterHour: profile.freezeAfterHour,\n environments: profile.environments,\n services: profile.services,\n securityGate: profile.securityGate,\n canaryType: profile.canaryType,\n });\n\n fs.writeFileSync(path.join(cwd, \".trailhead.yml\"), configContent, \"utf-8\");\n\n const workflowDir = path.join(cwd, \".github\", \"workflows\");\n fs.mkdirSync(workflowDir, { recursive: true });\n\n const workflowContent = generateWorkflowYml({\n riskThreshold: profile.riskThreshold,\n healthCheckUrls: profile.healthCheckUrls,\n doraMetrics: profile.doraMetrics,\n doraEnvironment: profile.doraEnvironment,\n otelEndpoint: profile.otelEndpoint,\n evaluationStoreUrl: profile.evaluationStoreUrl,\n storeSecretName: profile.storeSecretName,\n supabaseFallback: profile.supabaseFallback,\n securityGate: profile.securityGate,\n environment: profile.environment,\n gateMode: profile.gateMode,\n waitForChecks: profile.gateMode === \"release-ready\",\n submissionGate: profile.submissionGate,\n });\n\n const workflowPath = path.join(workflowDir, \"trailhead.yml\");\n if (fs.existsSync(workflowPath)) {\n fs.writeFileSync(\n path.join(workflowDir, \"trailhead-generated.yml\"),\n workflowContent,\n \"utf-8\",\n );\n } else {\n fs.writeFileSync(workflowPath, workflowContent, \"utf-8\");\n }\n}\n","import * as readline from \"node:readline\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n type AudienceId,\n type InitProfile,\n parseCheckList,\n profileFromAudience,\n writeInitArtifacts,\n} from \"./generators.js\";\n\nconst BOLD = \"\\x1b[1m\";\nconst GREEN = \"\\x1b[32m\";\nconst YELLOW = \"\\x1b[33m\";\nconst CYAN = \"\\x1b[36m\";\nconst RESET = \"\\x1b[0m\";\nconst DIM = \"\\x1b[2m\";\n\nfunction print(msg: string) {\n process.stdout.write(msg + \"\\n\");\n}\n\nfunction ask(\n rl: readline.Interface,\n question: string,\n defaultValue?: string,\n): Promise<string> {\n const suffix = defaultValue ? ` ${DIM}(${defaultValue})${RESET}` : \"\";\n return new Promise((resolve) => {\n rl.question(` ${question}${suffix}: `, (answer) => {\n resolve(answer.trim() || defaultValue || \"\");\n });\n });\n}\n\nfunction askYN(\n rl: readline.Interface,\n question: string,\n defaultYes: boolean,\n): Promise<boolean> {\n const hint = defaultYes ? \"Y/n\" : \"y/N\";\n return new Promise((resolve) => {\n rl.question(` ${question} ${DIM}(${hint})${RESET}: `, (answer) => {\n const a = answer.trim().toLowerCase();\n if (a === \"\") resolve(defaultYes);\n else resolve(a === \"y\" || a === \"yes\");\n });\n });\n}\n\nexport function parseInitPresetArg(args: string[]): AudienceId | undefined {\n const idx = args.indexOf(\"--preset\");\n if (idx >= 0 && args[idx + 1]) {\n const value = args[idx + 1] as AudienceId;\n if ([\"solo\", \"team\", \"agent\", \"ops\"].includes(value)) return value;\n process.stderr.write(`Unknown preset \"${value}\". Use: solo, team, agent, ops\\n`);\n process.exit(2);\n }\n return undefined;\n}\n\nasync function runCustomWizard(\n rl: readline.Interface,\n profile: InitProfile,\n): Promise<InitProfile> {\n print(`${BOLD}Gate mode${RESET}`);\n print(` ${DIM}1) release-ready — single required check (CI + risk)${RESET}`);\n print(` ${DIM}2) advisory — report only, never blocks${RESET}`);\n print(` ${DIM}3) risk-only — v3 behavior (risk score only)${RESET}`);\n const modeInput = await ask(rl, `${CYAN}Choose gate mode${RESET}`, \"1\");\n profile.gateMode =\n modeInput === \"2\" ? \"advisory\" : modeInput === \"3\" ? \"risk-only\" : \"release-ready\";\n\n if (profile.gateMode !== \"risk-only\") {\n print(`\\n${BOLD}Branch model${RESET}`);\n print(` ${DIM}1) main-only — PRs target main/master${RESET}`);\n print(` ${DIM}2) progressive — dev → staging → main promotion${RESET}`);\n const branchInput = await ask(rl, `${CYAN}Choose branch model${RESET}`, \"1\");\n profile.branchModel = branchInput === \"2\" ? \"progressive\" : \"main-only\";\n\n const featureChecksInput = await ask(\n rl,\n `${CYAN}Feature PR required checks${RESET} (comma-separated)`,\n \"CI, Build\",\n );\n profile.featureChecks = parseCheckList(featureChecksInput, profile.featureChecks);\n\n const promotionChecksInput = await ask(\n rl,\n `${CYAN}Promotion PR required checks${RESET} (comma-separated)`,\n \"CI, Build, Playwright\",\n );\n profile.promotionChecks = parseCheckList(\n promotionChecksInput,\n profile.promotionChecks,\n );\n }\n\n const riskStr = await ask(\n rl,\n `${CYAN}Risk threshold${RESET} (block above this score, 0-100)`,\n String(profile.riskThreshold),\n );\n profile.riskThreshold = Math.max(\n 0,\n Math.min(100, parseInt(riskStr, 10) || profile.riskThreshold),\n );\n\n const warnStr = await ask(\n rl,\n `${CYAN}Warn threshold${RESET} (warn above this score)`,\n String(profile.warnThreshold),\n );\n profile.warnThreshold = Math.max(\n 0,\n Math.min(100, parseInt(warnStr, 10) || profile.warnThreshold),\n );\n\n print(\n `\\n${BOLD}Sensitive file patterns${RESET} ${DIM}(files that carry extra risk weight)${RESET}`,\n );\n const highInput = await ask(rl, \"High-sensitivity globs (comma-separated)\", \"\");\n profile.highSensitivity = highInput\n ? highInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n\n const medInput = await ask(rl, \"Medium-sensitivity globs (comma-separated)\", \"\");\n profile.mediumSensitivity = medInput\n ? medInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n\n const wantEnvs = await askYN(rl, \"Configure environment-specific thresholds?\", false);\n if (wantEnvs) {\n const envsInput = await ask(\n rl,\n \"Environment names (comma-separated)\",\n \"production,staging\",\n );\n const envNames = envsInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n profile.environments = [];\n for (const name of envNames) {\n const r = await ask(rl, ` ${name} risk threshold`, String(profile.riskThreshold));\n const w = await ask(rl, ` ${name} warn threshold`, String(parseInt(r, 10) - 15));\n profile.environments.push({\n name,\n risk: parseInt(r, 10) || profile.riskThreshold,\n warn: parseInt(w, 10) || profile.warnThreshold - 15,\n });\n }\n profile.environment = envNames[0] ?? \"\";\n }\n\n const wantServices = await askYN(rl, \"Configure service boundaries (monorepo)?\", false);\n if (wantServices) {\n const svcInput = await ask(rl, \"Service names (comma-separated)\", \"api,web\");\n const svcNames = svcInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n profile.services = [];\n for (const name of svcNames) {\n const p = await ask(rl, ` ${name} path globs (comma-separated)`, `src/${name}/**`);\n const e = await ask(rl, ` ${name} environment`, \"\");\n profile.services.push({\n name,\n paths: p\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean),\n env: e,\n });\n }\n }\n\n const healthInput = await ask(\n rl,\n `${CYAN}Health check URLs${RESET} (comma-separated, or blank)`,\n \"\",\n );\n profile.healthCheckUrls = healthInput\n ? healthInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n\n profile.doraMetrics = await askYN(rl, `${CYAN}Enable DORA-5 metrics?${RESET}`, false);\n if (profile.doraMetrics) {\n profile.doraEnvironment = await ask(\n rl,\n `${CYAN}DORA environment filter${RESET} (blank for all)`,\n profile.environment || \"\",\n );\n }\n\n profile.securityGate = await askYN(\n rl,\n `${CYAN}Enable security alerts gate?${RESET} ${DIM}(requires Code Scanning)${RESET}`,\n true,\n );\n\n const wantCanary = await askYN(rl, \"Configure deployment outcome webhooks?\", false);\n profile.canaryType = wantCanary\n ? await ask(rl, \"Webhook type (vercel/generic)\", \"vercel\")\n : \"\";\n\n profile.otelEndpoint = await ask(\n rl,\n `${CYAN}OTLP endpoint${RESET} (blank to skip)`,\n \"\",\n );\n\n const wantStore = await askYN(\n rl,\n `${CYAN}POST evaluations to a trend-store URL?${RESET}`,\n false,\n );\n if (wantStore) {\n profile.evaluationStoreUrl = await ask(rl, \"Store URL\", \"\");\n profile.storeSecretName = await ask(\n rl,\n \"GitHub Actions secret name for Bearer token\",\n \"INTERNAL_API_SECRET\",\n );\n profile.supabaseFallback = await askYN(\n rl,\n \"Include Supabase direct-insert fallback env vars?\",\n false,\n );\n }\n\n const wantFreeze = await askYN(rl, \"Configure a release freeze window?\", false);\n if (wantFreeze) {\n const daysInput = await ask(rl, \"Freeze days (e.g. friday,saturday)\", \"friday\");\n profile.freezeDays = daysInput\n .split(\",\")\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean);\n const hourStr = await ask(rl, \"Freeze after hour (0-23, UTC)\", \"15\");\n profile.freezeAfterHour = Math.max(0, Math.min(23, parseInt(hourStr, 10) || 15));\n }\n\n profile.submissionEnabled = await askYN(\n rl,\n \"Enable submission gate (Gate 1) for agent PRs?\",\n false,\n );\n profile.submissionGate = profile.submissionEnabled;\n if (profile.submissionEnabled) {\n profile.remediationEnabled = await askYN(rl, \"Enable remediation payloads?\", true);\n profile.agentPolicies = await askYN(rl, \"Enable agent PR policies?\", true);\n profile.agentBrief = await askYN(rl, \"Collapsed agent brief in PR comments?\", true);\n }\n\n return profile;\n}\n\nasync function runAudienceWizard(\n rl: readline.Interface,\n audience: AudienceId,\n): Promise<InitProfile> {\n const profile = profileFromAudience(audience);\n\n switch (audience) {\n case \"solo\": {\n const checks = await ask(\n rl,\n `${CYAN}Required CI check names${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(checks, profile.promotionChecks);\n break;\n }\n case \"team\": {\n const feature = await ask(\n rl,\n `${CYAN}Feature PR required checks${RESET} (comma-separated)`,\n profile.featureChecks.join(\", \"),\n );\n profile.featureChecks = parseCheckList(feature, profile.featureChecks);\n const promo = await ask(\n rl,\n `${CYAN}Promotion PR required checks${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(promo, profile.promotionChecks);\n break;\n }\n case \"agent\": {\n const checks = await ask(\n rl,\n `${CYAN}Required CI check names${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(checks, profile.promotionChecks);\n break;\n }\n case \"ops\": {\n const checks = await ask(\n rl,\n `${CYAN}Required CI check names${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(checks, profile.promotionChecks);\n const healthInput = await ask(\n rl,\n `${CYAN}Production health check URLs${RESET} (comma-separated, recommended)`,\n \"\",\n );\n profile.healthCheckUrls = healthInput\n ? healthInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n const keepFreeze = await askYN(\n rl,\n \"Keep default freeze (Friday–Saturday after 15:00 UTC)?\",\n true,\n );\n if (!keepFreeze) {\n profile.freezeDays = [];\n profile.freezeAfterHour = null;\n }\n profile.doraMetrics = await askYN(rl, \"Enable DORA-5 metrics in workflow?\", true);\n break;\n }\n default:\n return runCustomWizard(rl, profile);\n }\n\n return profile;\n}\n\nexport async function runInitWizard(args: string[]): Promise<number> {\n const preset = parseInitPresetArg(args);\n const cwd = process.cwd();\n\n if (preset) {\n const profile = profileFromAudience(preset);\n writeInitArtifacts(profile, cwd);\n print(\n `\\n${GREEN}✓${RESET} Wrote .trailhead.yml and workflow from preset: ${BOLD}${preset}${RESET}\\n`,\n );\n return 0;\n }\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n print(`\\n${BOLD}${GREEN}Trailhead v4 Setup Wizard${RESET}\\n`);\n print(`${DIM}Creates .trailhead.yml and .github/workflows/trailhead.yml${RESET}\\n`);\n\n print(`${BOLD}What are you protecting?${RESET}`);\n print(` ${DIM}1) Solo / small team — one repo, Release Ready beyond CI green${RESET}`);\n print(\n ` ${DIM}2) Platform / eng lead — standard policy across repos (dev→staging→main)${RESET}`,\n );\n print(` ${DIM}3) AI-authored PRs — submission gate before merge${RESET}`);\n print(` ${DIM}4) Production ops — freeze windows, health probes, DORA${RESET}`);\n print(` ${DIM}5) Custom — full advanced wizard (all options)${RESET}`);\n\n const audienceInput = await ask(rl, `${CYAN}Choose setup path${RESET}`, \"1\");\n const audience: AudienceId =\n audienceInput === \"2\"\n ? \"team\"\n : audienceInput === \"3\"\n ? \"agent\"\n : audienceInput === \"4\"\n ? \"ops\"\n : audienceInput === \"5\"\n ? \"custom\"\n : \"solo\";\n\n const profile =\n audience === \"custom\"\n ? await runCustomWizard(rl, profileFromAudience(\"custom\"))\n : await runAudienceWizard(rl, audience);\n\n rl.close();\n\n print(`\\n${BOLD}Writing files...${RESET}\\n`);\n writeInitArtifacts(profile, cwd);\n\n print(` ${GREEN}✓${RESET} .trailhead.yml`);\n\n const workflowPath = path.join(cwd, \".github\", \"workflows\", \"trailhead.yml\");\n if (fs.existsSync(workflowPath)) {\n print(\n ` ${YELLOW}⚠${RESET} .github/workflows/trailhead.yml already exists — wrote trailhead-generated.yml`,\n );\n } else {\n print(` ${GREEN}✓${RESET} .github/workflows/trailhead.yml`);\n }\n\n print(`\n${BOLD}${GREEN}Setup complete!${RESET}\n\n${BOLD}Preset:${RESET} ${profile.audience} · See presets/${profile.audience === \"agent\" ? \"agent-guard\" : profile.audience}.yml\n\n${BOLD}Next steps:${RESET}\n 1. Review the generated files\n 2. Commit and push\n 3. Require ${BOLD}Trailhead — Release Ready${RESET} in branch protection\n 4. trailhead doctor --offline\n\n${DIM}Docs: docs/getting-started.md · https://github.com/KomatikAI/trailhead${RESET}\n`);\n\n return 0;\n}\n","import type { CiCheck, CiCheckStatusEnum, CiSummary, ContextCiConfig } from \"./types.js\";\nimport type { CiManifest, CiManifestJob } from \"./ci-manifest.js\";\n\nexport const DEFAULT_SELF_CHECK_NAMES = [\"Trailhead\", \"Trailhead — Release Ready\"];\n\nexport interface RawCheckRun {\n name: string;\n status: string;\n conclusion: string | null;\n html_url?: string | null;\n details_url?: string | null;\n}\n\n/**\n * Map GitHub check conclusion/status to Trailhead CI status (ADR-009).\n */\nexport function classifyCheck(\n status: string,\n conclusion: string | null,\n): CiCheckStatusEnum {\n if (status === \"completed\") {\n switch (conclusion) {\n case \"success\":\n return \"pass\";\n case \"skipped\":\n case \"neutral\":\n return \"skip\";\n case \"failure\":\n case \"timed_out\":\n case \"action_required\":\n case \"cancelled\":\n return \"fail\";\n default:\n return \"pending\";\n }\n }\n if (status === \"in_progress\" || status === \"queued\" || status === \"pending\") {\n return \"pending\";\n }\n return \"pending\";\n}\n\nfunction isSelfCheck(name: string, excludeNames: string[]): boolean {\n const lower = name.toLowerCase();\n return excludeNames.some((n) => n.toLowerCase() === lower);\n}\n\nexport function checkNameMatches(configured: string, actual: string): boolean {\n if (configured === actual) return true;\n if (configured.toLowerCase() === actual.toLowerCase()) return true;\n return actual.toLowerCase().startsWith(configured.toLowerCase());\n}\n\nfunction findManifestJob(\n manifest: CiManifest,\n configuredName: string,\n): CiManifestJob | undefined {\n return manifest.jobs.find((job) => checkNameMatches(configuredName, job.name));\n}\n\nfunction statusFromManifestJob(job: CiManifestJob): CiCheckStatusEnum | undefined {\n switch (job.outcome) {\n case \"passed\":\n return \"pass\";\n case \"skipped\":\n return \"skip\";\n case \"failed\":\n case \"cancelled\":\n return \"fail\";\n case \"pending\":\n return \"pending\";\n case \"ran\":\n return undefined;\n default: {\n const _exhaustive: never = job.outcome;\n return undefined;\n }\n }\n}\n\nfunction applyManifestToCheck(\n check: CiCheck,\n manifest: CiManifest | undefined,\n configuredName: string,\n): CiCheck {\n if (!manifest) return check;\n const manifestJob = findManifestJob(manifest, configuredName);\n if (!manifestJob) return check;\n\n const manifestStatus = statusFromManifestJob(manifestJob);\n if (manifestStatus === \"skip\") {\n return {\n ...check,\n status: \"skip\",\n conclusion: manifestJob.reason ?? check.conclusion,\n };\n }\n if (manifestStatus && (check.status === \"missing\" || check.status === \"pending\")) {\n return {\n ...check,\n status: manifestStatus,\n conclusion: manifestJob.reason ?? check.conclusion,\n };\n }\n return check;\n}\n\nfunction checkFromManifestOnly(\n configuredName: string,\n manifest: CiManifest,\n): CiCheck | undefined {\n const manifestJob = findManifestJob(manifest, configuredName);\n if (!manifestJob) return undefined;\n\n const status = statusFromManifestJob(manifestJob);\n if (!status) return undefined;\n\n return {\n name: configuredName,\n status,\n conclusion: manifestJob.reason,\n detailsUrl: manifestJob.details_url,\n required: false,\n };\n}\n\nexport function normalizeCheckRuns(\n runs: RawCheckRun[],\n excludeCheckNames: string[] = DEFAULT_SELF_CHECK_NAMES,\n): CiCheck[] {\n return runs\n .filter((r) => !isSelfCheck(r.name, excludeCheckNames))\n .map((r) => ({\n name: r.name,\n status: classifyCheck(r.status, r.conclusion),\n conclusion: r.conclusion ?? undefined,\n detailsUrl: r.details_url ?? r.html_url ?? undefined,\n required: false,\n }));\n}\n\nexport function evaluateRequiredChecks(\n allChecks: CiCheck[],\n ciConfig: ContextCiConfig,\n manifest?: CiManifest | null,\n): CiSummary {\n const requiredNames = ciConfig.required_checks;\n const optionalNames = ciConfig.optional_checks;\n const missingPolicy = ciConfig.missing_required;\n\n const evaluated: CiCheck[] = [];\n const seen = new Set<string>();\n\n for (const reqName of requiredNames) {\n const match = allChecks.find((c) => checkNameMatches(reqName, c.name));\n if (match) {\n const resolved = applyManifestToCheck(\n { ...match, name: reqName, required: true },\n manifest ?? undefined,\n reqName,\n );\n evaluated.push(resolved);\n seen.add(match.name);\n } else if (manifest) {\n const fromManifest = checkFromManifestOnly(reqName, manifest);\n if (fromManifest) {\n evaluated.push({ ...fromManifest, name: reqName, required: true });\n } else {\n evaluated.push({\n name: reqName,\n status: missingPolicy === \"skip\" ? \"skip\" : \"missing\",\n required: true,\n });\n }\n } else {\n evaluated.push({\n name: reqName,\n status: missingPolicy === \"skip\" ? \"skip\" : \"missing\",\n required: true,\n });\n }\n }\n\n for (const optName of optionalNames) {\n const match = allChecks.find((c) => checkNameMatches(optName, c.name));\n if (match) {\n const resolved = applyManifestToCheck(\n { ...match, name: optName, required: false },\n manifest ?? undefined,\n optName,\n );\n evaluated.push(resolved);\n seen.add(match.name);\n } else if (manifest) {\n const fromManifest = checkFromManifestOnly(optName, manifest);\n if (fromManifest) {\n evaluated.push({ ...fromManifest, name: optName, required: false });\n } else {\n evaluated.push({\n name: optName,\n status: \"missing\",\n required: false,\n });\n }\n } else {\n evaluated.push({\n name: optName,\n status: \"missing\",\n required: false,\n });\n }\n }\n\n for (const check of allChecks) {\n if (!seen.has(check.name)) {\n evaluated.push({ ...check, required: false });\n }\n }\n\n const requiredChecks = evaluated.filter((c) => c.required);\n const pendingCount = requiredChecks.filter((c) => c.status === \"pending\").length;\n const failedCount = requiredChecks.filter(\n (c) => c.status === \"fail\" || c.status === \"missing\" || c.status === \"stale\",\n ).length;\n const missingCount = requiredChecks.filter((c) => c.status === \"missing\").length;\n const allRequiredPassed =\n requiredNames.length === 0 ||\n requiredChecks.every((c) => c.status === \"pass\" || c.status === \"skip\");\n\n return {\n checks: evaluated,\n allRequiredPassed,\n pendingCount,\n failedCount,\n missingCount,\n };\n}\n\nexport function formatCiStatusIcon(status: CiCheckStatusEnum): string {\n switch (status) {\n case \"pass\":\n return \"✅\";\n case \"fail\":\n return \"❌\";\n case \"skip\":\n return \"⏭️\";\n case \"pending\":\n return \"⏳\";\n case \"stale\":\n return \"⚠️\";\n case \"missing\":\n return \"❓\";\n default: {\n const _exhaustive: never = status;\n return \"•\";\n }\n }\n}\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { z } from \"zod\";\nimport type { CiManifest } from \"./ci-manifest.js\";\n\nexport const GateDecision = z.enum([\"allow\", \"warn\", \"block\"]);\nexport type GateDecision = z.infer<typeof GateDecision>;\n\nexport const HealthCheckResult = z.object({\n target: z.string(),\n status: GateDecision,\n latencyMs: z.number(),\n detail: z.record(z.unknown()).optional(),\n});\nexport type HealthCheckResult = z.infer<typeof HealthCheckResult>;\n\nexport const RiskFactor = z.object({\n type: z.enum([\n \"code_churn\",\n \"test_coverage\",\n \"file_count\",\n \"sensitive_files\",\n \"author_history\",\n \"dependency_changes\",\n \"pr_age\",\n \"security_alerts\",\n \"deployment_history\",\n \"canary_status\",\n \"ci_integrity\",\n \"workflow_security\",\n \"prompt_injection_risk\",\n \"supply_chain\",\n \"pr_scope\",\n \"duplicate_logic\",\n \"cross_repo_impact\",\n ]),\n score: z.number().min(0).max(100),\n detail: z.record(z.unknown()).optional(),\n});\nexport type RiskFactor = z.infer<typeof RiskFactor>;\n\nexport const PrProvenance = z.object({\n type: z.enum([\n \"human\",\n \"dependabot\",\n \"copilot\",\n \"codex\",\n \"claude\",\n \"custom-bot\",\n \"unknown\",\n ]),\n confidence: z.number().min(0).max(1),\n source: z.string().optional(),\n});\nexport type PrProvenance = z.infer<typeof PrProvenance>;\n\nexport const GateMode = z.enum([\"release-ready\", \"advisory\", \"risk-only\"]);\nexport type GateMode = z.infer<typeof GateMode>;\n\nexport const AgentBriefMode = z.enum([\"off\", \"collapsed\", \"expanded\"]);\nexport type AgentBriefMode = z.infer<typeof AgentBriefMode>;\n\nexport const CiCheckStatusEnum = z.enum([\n \"pass\",\n \"fail\",\n \"skip\",\n \"pending\",\n \"stale\",\n \"missing\",\n]);\nexport type CiCheckStatusEnum = z.infer<typeof CiCheckStatusEnum>;\n\nexport const CiCheck = z.object({\n name: z.string(),\n status: CiCheckStatusEnum,\n conclusion: z.string().optional(),\n detailsUrl: z.string().url().optional(),\n required: z.boolean(),\n});\nexport type CiCheck = z.infer<typeof CiCheck>;\n\nexport const CiSummary = z.object({\n checks: z.array(CiCheck),\n allRequiredPassed: z.boolean(),\n pendingCount: z.number().int().min(0),\n failedCount: z.number().int().min(0),\n missingCount: z.number().int().min(0),\n});\nexport type CiSummary = z.infer<typeof CiSummary>;\n\nexport const MatchedContext = z.object({\n name: z.string(),\n environment: z.string().optional(),\n});\nexport type MatchedContext = z.infer<typeof MatchedContext>;\n\nexport const RemediationSeverity = z.enum([\"blocking\", \"warn\", \"advisory\"]);\nexport type RemediationSeverity = z.infer<typeof RemediationSeverity>;\n\nexport const SubmissionCheckCode = z.enum([\n \"artifact_integrity\",\n \"mock_placeholder\",\n \"context_freshness\",\n \"destructive_sql\",\n \"secrets\",\n \"path_format\",\n \"syntax_validity\",\n \"import_resolution\",\n \"rls_new_tables\",\n \"auth_route_auth\",\n \"hardcoded_env\",\n \"external_package_deps\",\n \"sql_syntax_basic\",\n \"large_file\",\n \"soul_integrity\",\n // ADR-010 — architecture & lifecycle gates\n \"contract_integrity\",\n \"safe_deprecation\",\n \"destructive_change\",\n \"claim_anchoring\",\n \"promotion_coherence\",\n // Phase 0 — agent suggestion quality (advisory / weight=0 in komatik-agents)\n \"output_size_min\",\n \"action_extraction_present\",\n \"delta_section_present\",\n \"preamble_absent\",\n \"graduation_signals_section_present\",\n \"fabricated_id_check\",\n \"session_narrative_detection\",\n \"incompleteness_self_flag\",\n \"referenced_files_exist\",\n \"prerequisite_secrets_check\",\n \"dependency_dag_validation\",\n \"uncommitted_fix_check\",\n \"verification_owner_assigned\",\n \"external_interface_validation\",\n]);\nexport type SubmissionCheckCode = z.infer<typeof SubmissionCheckCode>;\n\nexport const SubmissionCheckResult = z.object({\n code: SubmissionCheckCode,\n severity: RemediationSeverity,\n title: z.string(),\n detail: z.string(),\n files: z.array(z.string()).default([]),\n suggested_action: z.string().optional(),\n autofix_eligible: z.boolean().default(false),\n});\nexport type SubmissionCheckResult = z.infer<typeof SubmissionCheckResult>;\n\nexport const RemediationAutofixClass = z.enum([\n \"format\",\n \"lint\",\n \"import-fix\",\n \"type-narrow\",\n \"test-scaffold\",\n \"doc-update\",\n \"dependency-bump\",\n]);\nexport type RemediationAutofixClass = z.infer<typeof RemediationAutofixClass>;\n\nexport const RemediationFix = z.object({\n code: z.string(),\n severity: RemediationSeverity,\n title: z.string(),\n detail: z.string(),\n files: z.array(z.string()).default([]),\n suggested_action: z.string().optional(),\n suggested_command: z.string().optional(),\n autofix_eligible: z.boolean().default(false),\n autofix_class: RemediationAutofixClass.optional(),\n policy_link: z.string().url().optional(),\n});\nexport type RemediationFix = z.infer<typeof RemediationFix>;\n\nexport const RemediationNextAction = z.enum([\n \"ready_to_merge\",\n \"fix_and_retry\",\n \"human_review_required\",\n \"max_rounds_exceeded\",\n]);\nexport type RemediationNextAction = z.infer<typeof RemediationNextAction>;\n\nexport const Remediation = z.object({\n schema: z.literal(\"trailhead.remediation.v1\").default(\"trailhead.remediation.v1\"),\n release_ready: z.boolean(),\n fixes: z.array(RemediationFix),\n blocking_count: z.number().int().min(0),\n warn_count: z.number().int().min(0),\n advisory_count: z.number().int().min(0),\n autofix_eligible_count: z.number().int().min(0),\n loop_round: z.number().int().min(0).default(0),\n max_loop_rounds: z.number().int().min(0).default(3),\n previous_evaluation_id: z.string().optional(),\n fixes_resolved: z.array(z.string()).default([]),\n fixes_introduced: z.array(z.string()).default([]),\n next_action: RemediationNextAction,\n});\nexport type Remediation = z.infer<typeof Remediation>;\n\nexport const PolicyOverrideChanges = z.object({\n failMode: z.enum([\"open\", \"closed\"]).optional(),\n riskThreshold: z.number().min(0).max(100).optional(),\n warnThreshold: z.number().min(0).max(100).optional(),\n releaseReady: z.literal(true).optional(),\n});\nexport type PolicyOverrideChanges = z.infer<typeof PolicyOverrideChanges>;\n\nexport const PolicyOverrideAudit = z.object({\n source: z.enum([\"workflow\", \"label\"]).default(\"workflow\"),\n owner: z.string(),\n reason: z.string(),\n linkedTicket: z.string(),\n expiresAt: z.string(),\n appliedAt: z.string(),\n changes: PolicyOverrideChanges.default({}),\n preOverrideDecision: GateDecision.optional(),\n preOverrideReleaseReady: z.boolean().optional(),\n preOverrideReasons: z.array(z.string()).optional(),\n});\nexport type PolicyOverrideAudit = z.infer<typeof PolicyOverrideAudit>;\n\nexport const CreditMeterResult = z.object({\n metered: z.boolean(),\n skipped: z.boolean().optional(),\n reason: z.string().optional(),\n shadow: z.boolean().optional(),\n would_charge: z.number().optional(),\n charged: z.number().optional(),\n balance: z.number().optional(),\n allowed: z.boolean().optional(),\n ok: z.boolean().optional(),\n});\nexport type CreditMeterResult = z.infer<typeof CreditMeterResult>;\n\nexport const GateEvaluation = z.object({\n id: z.string(),\n repoId: z.string(),\n commitSha: z.string(),\n prNumber: z.number().optional(),\n healthScore: z.number().min(0).max(100),\n riskScore: z.number().min(0).max(100),\n gateDecision: GateDecision,\n healthChecks: z.array(HealthCheckResult),\n riskFactors: z.array(RiskFactor),\n files: z.array(z.string()).optional(),\n evaluationMs: z.number(),\n reportUrl: z.string().url().optional(),\n environment: z.string().optional(),\n service: z.string().optional(),\n policyFindings: z.array(z.string()).optional(),\n pr: z\n .object({\n provenance: PrProvenance.optional(),\n headRef: z.string().optional(),\n })\n .optional(),\n session_correlation: z\n .object({\n burst_count: z.number().int().min(0),\n window: z.string(),\n })\n .optional(),\n escalation_status: z\n .object({\n enabled: z.boolean(),\n target_count: z.number().int().min(0),\n acknowledge_sla_minutes: z.number().int().min(1).optional(),\n resolve_sla_minutes: z.number().int().min(1).optional(),\n })\n .optional(),\n trust_profile: z\n .object({\n strictness: z.enum([\"baseline\", \"elevated\", \"strict\"]),\n reason: z.string(),\n score: z.number().min(0).max(1).optional(),\n profile: z.enum([\"fast-track\", \"standard\", \"probation\"]).optional(),\n factors: z.record(z.number()).optional(),\n })\n .optional(),\n policyOverride: PolicyOverrideAudit.optional(),\n labelOverrideFeedback: z\n .object({\n status: z.enum([\"applied\", \"rejected\"]),\n message: z.string(),\n })\n .optional(),\n releaseReady: z.boolean().optional(),\n releaseReadyReasons: z.array(z.string()).optional(),\n ci: CiSummary.optional(),\n context: MatchedContext.optional(),\n gateMode: GateMode.optional(),\n storePersisted: z.boolean().optional(),\n credit_meter: CreditMeterResult.optional(),\n remediation: Remediation.optional(),\n agentBriefMode: AgentBriefMode.optional(),\n submissionChecks: z.array(SubmissionCheckResult).optional(),\n cross_repo_impact: z\n .object({\n services: z.array(\n z.object({\n serviceName: z.string(),\n touchedFiles: z.array(z.string()),\n consumers: z.array(\n z.object({\n id: z.string(),\n repo: z.string().optional(),\n branch: z.string().optional(),\n }),\n ),\n notify_webhook: z.string().url().optional(),\n }),\n ),\n })\n .optional(),\n});\nexport type GateEvaluation = z.infer<typeof GateEvaluation>;\n\nexport const GateApiResponse = z.object({\n id: z.string().optional(),\n reportUrl: z.string().url().optional(),\n healthScore: z.number().min(0).max(100).optional(),\n riskScore: z.number().min(0).max(100).optional(),\n gateDecision: GateDecision.optional(),\n healthChecks: z.array(HealthCheckResult).optional(),\n riskFactors: z.array(RiskFactor).optional(),\n});\nexport type GateApiResponse = z.infer<typeof GateApiResponse>;\n\nexport const FreezeWindow = z.object({\n days: z.array(z.string()).default([]),\n afterHour: z.number().min(0).max(23).optional(),\n beforeHour: z.number().min(0).max(23).optional(),\n timezone: z.string().default(\"UTC\"),\n message: z.string().optional(),\n});\nexport type FreezeWindow = z.infer<typeof FreezeWindow>;\n\nexport const EnvironmentConfig = z.object({\n risk: z.number().min(0).max(100).optional(),\n warn: z.number().min(0).max(100).optional(),\n require_security_clear: z.boolean().optional(),\n});\nexport type EnvironmentConfig = z.infer<typeof EnvironmentConfig>;\n\nexport const ServiceConsumerRef = z.object({\n repo: z.string().min(1),\n name: z.string().optional(),\n branch: z.string().optional(),\n notify_webhook: z.string().url().optional(),\n});\n\nexport const ServiceConsumer = z.union([z.string(), ServiceConsumerRef]);\nexport type ServiceConsumer = z.infer<typeof ServiceConsumer>;\n\nexport const ConsumerRegistry = z.record(z.string(), ServiceConsumerRef);\nexport type ConsumerRegistry = z.infer<typeof ConsumerRegistry>;\n\nexport const ServiceMapping = z.object({\n paths: z.array(z.string()),\n environment: z.string().optional(),\n consumers: z.array(ServiceConsumer).default([]),\n contracts: z.array(z.string()).default([]),\n notify_webhook: z.string().url().optional(),\n});\nexport type ServiceMapping = z.infer<typeof ServiceMapping>;\n\nexport const SecurityConfig = z.object({\n severity_threshold: z.enum([\"error\", \"warning\", \"note\", \"none\"]).default(\"warning\"),\n block_on_critical: z.boolean().default(true),\n ignore_rules: z.array(z.string()).default([]),\n});\nexport type SecurityConfig = z.infer<typeof SecurityConfig>;\n\nexport const CanaryConfig = z.object({\n webhook_type: z.enum([\"vercel\", \"generic\"]).default(\"vercel\"),\n field_map: z.record(z.string()).optional(),\n rollback_on_failure: z.boolean().default(false),\n});\nexport type CanaryConfig = z.infer<typeof CanaryConfig>;\n\nexport const RiskProfileMatch = z.object({\n files_include: z.array(z.string()).default([]),\n files_exclude: z.array(z.string()).default([]),\n min_files: z.number().int().min(1).optional(),\n max_files: z.number().int().min(1).optional(),\n});\nexport type RiskProfileMatch = z.infer<typeof RiskProfileMatch>;\n\nexport const RiskProfile = z.object({\n name: z.string().optional(),\n match: RiskProfileMatch,\n weights: z.record(z.number().min(0).max(10)).default({}),\n});\nexport type RiskProfile = z.infer<typeof RiskProfile>;\n\nexport const ContextMatch = z.object({\n base_branch: z.array(z.string()).default([]),\n head_branch: z.array(z.string()).default([]),\n labels: z.array(z.string()).default([]),\n});\nexport type ContextMatch = z.infer<typeof ContextMatch>;\n\nexport const ContextCiConfig = z.object({\n required_checks: z.array(z.string()).default([]),\n optional_checks: z.array(z.string()).default([]),\n missing_required: z.enum([\"fail\", \"skip\"]).default(\"fail\"),\n});\nexport type ContextCiConfig = z.infer<typeof ContextCiConfig>;\n\nexport const TrailheadContext = z.object({\n name: z.string(),\n match: ContextMatch,\n environment: z.string().optional(),\n thresholds: z\n .object({\n risk: z.number().min(0).max(100).optional(),\n warn: z.number().min(0).max(100).optional(),\n })\n .default({}),\n ci: ContextCiConfig.default({}),\n});\nexport type TrailheadContext = z.infer<typeof TrailheadContext>;\n\nexport const GateConfig = z.object({\n mode: GateMode.default(\"risk-only\"),\n check_name: z.string().default(\"Trailhead — Release Ready\"),\n agent_brief: AgentBriefMode.optional(),\n});\nexport type GateConfig = z.infer<typeof GateConfig>;\n\nexport const RemediationConfig = z.object({\n enabled: z.boolean().default(true),\n max_loop_rounds: z.number().int().min(0).default(3),\n});\nexport type RemediationConfig = z.infer<typeof RemediationConfig>;\n\nexport const OverrideConfig = z.object({\n enabled: z.boolean().default(true),\n max_per_week: z.number().int().min(1).default(5),\n});\nexport type OverrideConfig = z.infer<typeof OverrideConfig>;\n\nexport const TuningConfig = z.object({\n auto_downgrade: z.boolean().default(true),\n digest_webhook_url: z.string().url().optional(),\n fp_threshold: z.number().min(0).max(1).default(0.15),\n});\nexport type TuningConfig = z.infer<typeof TuningConfig>;\n\nexport const SubmissionDetectorPolicyEntry = z.object({\n enabled: z.boolean().optional(),\n severity: z.enum([\"block\", \"warn\", \"advisory\", \"blocking\"]).optional(),\n file_globs: z.array(z.string()).optional(),\n path_ignore: z.array(z.string()).optional(),\n weight: z.number().optional(),\n});\nexport type SubmissionDetectorPolicyEntry = z.infer<typeof SubmissionDetectorPolicyEntry>;\n\nexport const SubmissionRenamePattern = z.object({\n old: z.string().min(1),\n new: z.string().min(1),\n});\nexport type SubmissionRenamePattern = z.infer<typeof SubmissionRenamePattern>;\n\nexport const SubmissionConfig = z.object({\n enabled: z.boolean().default(false),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n stale_terms: z.array(z.string()).optional(),\n auth_route_allowlist: z.array(z.string()).optional(),\n max_file_lines: z.number().int().positive().optional(),\n /** Path substrings to skip for context_freshness (e.g. archived suggestion dirs). */\n path_ignore: z.array(z.string()).optional(),\n /** Legacy naming allowlist — skip stale-term hits on imports, slugs in strings, etc. */\n naming_allowlist: z\n .object({\n skip_extensions: z.array(z.string()).optional(),\n skip_path_patterns: z.array(z.string()).optional(),\n skip_comment_markers: z.array(z.string()).optional(),\n skip_in_imports: z.boolean().optional(),\n })\n .optional(),\n /** Project rename vocabulary — extends Komatik defaults when KOMATIK_INSTANCE=true. */\n rename_patterns: z.array(SubmissionRenamePattern).optional(),\n /** Extra slug-only regex sources (merged with product defaults). */\n slug_only_patterns: z.array(z.string()).optional(),\n /** Per-detector policy overrides (enable/severity/file scope). */\n detectors: z.record(SubmissionDetectorPolicyEntry).optional(),\n /** contract_integrity (ADR-010): cross-repo catalog resolution. */\n contract_integrity: z\n .object({\n /** Entity names published org-wide; lets cross-repo contract refs resolve. */\n known_entities: z.array(z.string()).optional(),\n /** Path to a JSON catalog index ({ entities: string[] }), merged with known_entities. */\n catalog_index_path: z.string().optional(),\n /** entity name → \"owner/repo\" that should publish it. Resolution registry\n * for the cross-repo PR opener: a dangling consumesApis/dependsOn ref whose\n * name is mapped here triggers a declaration PR in the owning repo. */\n api_owners: z.record(z.string()).optional(),\n /** Path to a catalog index JSON with an `owners` map; merged with api_owners\n * (inline api_owners wins). Usually the same file as catalog_index_path. */\n api_owners_path: z.string().optional(),\n /** Cross-repo PR opener (ADR-010). Off by default; opens declaration PRs in\n * the OWNING repo for dangling cross-repo contract refs. Needs a token with\n * write access to those repos (cross-repo-token input). */\n cross_repo_opener: z\n .object({\n enabled: z.boolean().default(false),\n /** Owners the opener may open PRs in. Defaults to the gated repo's owner. */\n owner_allowlist: z.array(z.string()).optional(),\n })\n .optional(),\n })\n .optional(),\n});\nexport type SubmissionConfig = z.infer<typeof SubmissionConfig>;\n\nexport const RepoConfig = z.object({\n schema_version: z.number().int().positive().default(1),\n gate: GateConfig.default({}),\n remediation: RemediationConfig.optional(),\n override: OverrideConfig.optional(),\n tuning: TuningConfig.optional(),\n submission: SubmissionConfig.optional(),\n contexts: z.array(TrailheadContext).default([]),\n sensitivity: z\n .object({\n high: z.array(z.string()).default([]),\n medium: z.array(z.string()).default([]),\n low: z.array(z.string()).default([]),\n })\n .default({}),\n weights: z.record(z.number().min(0).max(10)).default({}),\n profiles: z.array(RiskProfile).default([]),\n thresholds: z\n .object({\n risk: z.number().min(0).max(100).optional(),\n warn: z.number().min(0).max(100).optional(),\n })\n .default({}),\n ignore: z.array(z.string()).default([]),\n freeze: z.array(FreezeWindow).default([]),\n environments: z.record(EnvironmentConfig).default({}),\n services: z.record(ServiceMapping).default({}),\n consumer_registry: z.record(ServiceConsumerRef).default({}),\n security: SecurityConfig.default({}),\n canary: CanaryConfig.optional(),\n escalation: z\n .object({\n targets: z.array(z.string()).default([]),\n acknowledge_sla_minutes: z.number().int().min(1).default(30),\n resolve_sla_minutes: z.number().int().min(1).default(240),\n })\n .default({}),\n policies: z\n .object({\n agent_prs: z\n .object({\n enabled: z.boolean().default(false),\n risk_threshold: z.number().min(0).max(100).optional(),\n required_approvals: z.number().int().min(0).default(1),\n require_code_owner_approval: z.boolean().default(false),\n code_owner_reviewers: z.array(z.string()).default([]),\n sensitive_paths: z.array(z.string()).default([]),\n strict_on_unknown_provenance: z.boolean().default(true),\n })\n .default({}),\n session_correlation: z\n .object({\n enabled: z.boolean().default(false),\n threshold: z.number().int().min(2).default(3),\n window_minutes: z.number().int().min(5).default(60),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n })\n .default({}),\n ci_integrity: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n })\n .default({}),\n workflow_security: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n allow_unpinned_actions: z.array(z.string()).default([]),\n })\n .default({}),\n prompt_injection: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n })\n .default({}),\n supply_chain: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n force_score_on_critical: z.number().min(0).max(100).default(80),\n })\n .default({}),\n pr_scope: z\n .object({\n enabled: z.boolean().default(true),\n max_files: z.number().int().min(1).default(50),\n max_changes: z.number().int().min(1).default(2000),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n require_plan_for_agent_prs: z.boolean().default(false),\n })\n .default({}),\n duplicate_logic: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n })\n .default({}),\n cross_repo_impact: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n consumer_registry_path: z.string().optional(),\n })\n .default({}),\n })\n .default({}),\n});\nexport type RepoConfig = z.infer<typeof RepoConfig>;\n\nexport interface TrailheadConfig {\n apiKey: string;\n apiUrl: string;\n githubToken?: string;\n healthCheckUrls: string[];\n riskThreshold: number;\n warnThreshold?: number;\n failMode: \"open\" | \"closed\";\n selfHeal: boolean;\n addRiskLabels: boolean;\n reviewersOnRisk: string[];\n webhookUrl?: string;\n webhookEvents: string[];\n evaluationStoreUrl?: string;\n trailheadApiKey?: string;\n environment?: string;\n securityGate?: boolean;\n gateMode?: GateMode;\n waitForChecks?: boolean;\n waitTimeoutMinutes?: number;\n checkName?: string;\n ciManifest?: CiManifest | null;\n ciManifestPath?: string;\n agentBrief?: AgentBriefMode;\n submissionGate?: boolean;\n}\n\nexport interface TestRepairResult {\n testFile: string;\n failureType: string;\n strategy: string;\n success: boolean;\n diff?: string;\n}\n","import { RepoConfig } from \"./types.js\";\nimport type { RepoConfig as RepoConfigType } from \"./types.js\";\n\nexport const SUPPORTED_CONFIG_SCHEMA_VERSIONS = new Set([1, 2]);\nexport const CURRENT_CONFIG_SCHEMA_VERSION = 2;\n\nexport function parseYaml(input: string): unknown {\n const lines = input\n .split(\"\\n\")\n .map((line) => line.replace(/\\r$/, \"\"))\n .filter((line) => line.trim() !== \"\" && !line.trim().startsWith(\"#\"));\n const root: Record<string, unknown> = {};\n const stack: Array<{ indent: number; value: unknown }> = [{ indent: -1, value: root }];\n\n const parseScalar = (value: string): unknown => {\n const v = value.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"')) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\"))\n ) {\n return v.slice(1, -1);\n }\n if (v === \"true\") return true;\n if (v === \"false\") return false;\n if (v === \"null\") return null;\n const n = Number(v);\n if (!Number.isNaN(n) && v !== \"\") return n;\n return v;\n };\n\n const findNextSignificantLine = (fromIndex: number): string | null => {\n for (let i = fromIndex + 1; i < lines.length; i += 1) {\n const candidate = lines[i];\n if (candidate.trim() !== \"\" && !candidate.trim().startsWith(\"#\")) {\n return candidate;\n }\n }\n return null;\n };\n\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i];\n const indent = line.match(/^ */)?.[0].length ?? 0;\n const trimmed = line.trim();\n\n while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {\n stack.pop();\n }\n const container = stack[stack.length - 1].value;\n\n if (trimmed.startsWith(\"- \")) {\n if (!Array.isArray(container)) continue;\n const itemRaw = trimmed.slice(2).trim();\n if (itemRaw === \"\") {\n const child: Record<string, unknown> = {};\n container.push(child);\n stack.push({ indent, value: child });\n continue;\n }\n\n const itemKeyMatch = itemRaw.match(/^([A-Za-z0-9_-]+):\\s*(.*)$/);\n if (itemKeyMatch) {\n const child: Record<string, unknown> = {};\n const [, itemKey, itemVal] = itemKeyMatch;\n if (itemVal === \"\") {\n const nextLine = findNextSignificantLine(i);\n const nextIndent = nextLine?.match(/^ */)?.[0].length ?? -1;\n const nextTrimmed = nextLine?.trim() ?? \"\";\n const useArray =\n nextLine !== null && nextIndent > indent && nextTrimmed.startsWith(\"- \");\n child[itemKey] = useArray ? [] : {};\n if (\n !useArray &&\n typeof child[itemKey] === \"object\" &&\n child[itemKey] !== null\n ) {\n stack.push({ indent, value: child[itemKey] });\n }\n } else {\n const trimmedVal = itemVal.trim();\n if (trimmedVal.startsWith(\"[\") && trimmedVal.endsWith(\"]\")) {\n const inner = trimmedVal.slice(1, -1).trim();\n child[itemKey] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((item) => parseScalar(item.trim()));\n } else {\n child[itemKey] = parseScalar(itemVal);\n }\n }\n container.push(child);\n stack.push({ indent, value: child });\n continue;\n }\n\n container.push(parseScalar(itemRaw));\n continue;\n }\n\n const keyMatch = trimmed.match(/^([A-Za-z0-9_-]+):\\s*(.*)$/);\n if (\n !keyMatch ||\n typeof container !== \"object\" ||\n container === null ||\n Array.isArray(container)\n ) {\n continue;\n }\n\n const [, key, rawVal] = keyMatch;\n if (rawVal !== \"\") {\n const trimmedVal = rawVal.trim();\n if (trimmedVal.startsWith(\"[\") && trimmedVal.endsWith(\"]\")) {\n const inner = trimmedVal.slice(1, -1).trim();\n (container as Record<string, unknown>)[key] =\n inner === \"\" ? [] : inner.split(\",\").map((item) => parseScalar(item.trim()));\n continue;\n }\n (container as Record<string, unknown>)[key] = parseScalar(rawVal);\n continue;\n }\n\n const nextLine = findNextSignificantLine(i);\n const nextIndent = nextLine?.match(/^ */)?.[0].length ?? -1;\n const nextTrimmed = nextLine?.trim() ?? \"\";\n const useArray =\n nextLine !== null && nextIndent > indent && nextTrimmed.startsWith(\"- \");\n const child: unknown = useArray ? [] : {};\n (container as Record<string, unknown>)[key] = child;\n stack.push({ indent, value: child });\n }\n\n return root;\n}\n\nexport function parseRepoConfigContent(content: string): RepoConfigType | null {\n const raw = parseYaml(content);\n const parsed = RepoConfig.safeParse(raw);\n if (!parsed.success) return null;\n return parsed.data;\n}\n","import type { CiSummary, GateDecision, GateEvaluation, GateMode } from \"./types.js\";\n\nexport interface ReleaseReadyInput {\n gateMode: GateMode;\n gateDecision: GateDecision;\n riskScore: number;\n riskThreshold: number;\n healthScore: number;\n healthChecksConfigured: boolean;\n ciSummary?: CiSummary | null;\n freezeActive: boolean;\n freezeMessage?: string;\n policyFindings?: string[];\n requireSecurityClear?: boolean;\n securityBlocked?: boolean;\n}\n\nexport interface ReleaseReadyResult {\n releaseReady: boolean;\n reasons: string[];\n}\n\n/**\n * Composite release readiness decision (ADR-006).\n */\nexport function computeReleaseReady(input: ReleaseReadyInput): ReleaseReadyResult {\n const reasons: string[] = [];\n\n if (input.gateMode === \"risk-only\") {\n if (input.gateDecision === \"block\") {\n reasons.push(\"Risk/policy gate decision is BLOCK\");\n } else if (input.gateDecision === \"warn\") {\n reasons.push(\"Risk/policy gate decision is WARN (non-blocking in risk-only mode)\");\n }\n return {\n releaseReady: input.gateDecision !== \"block\",\n reasons,\n };\n }\n\n if (input.ciSummary) {\n if (!input.ciSummary.allRequiredPassed) {\n const failed = input.ciSummary.checks.filter(\n (c) =>\n c.required &&\n (c.status === \"fail\" || c.status === \"missing\" || c.status === \"stale\"),\n );\n for (const check of failed) {\n reasons.push(\n `Required CI check \"${check.name}\" is ${check.status.toUpperCase()}`,\n );\n }\n }\n if (input.ciSummary.pendingCount > 0) {\n reasons.push(`${input.ciSummary.pendingCount} required CI check(s) still pending`);\n }\n }\n\n if (input.gateDecision === \"block\") {\n reasons.push(\"Risk/policy gate decision is BLOCK\");\n }\n\n if (input.riskScore > input.riskThreshold) {\n reasons.push(\n `Risk score ${input.riskScore} exceeds threshold ${input.riskThreshold}`,\n );\n }\n\n if (input.freezeActive) {\n reasons.push(\n `Release freeze active${input.freezeMessage ? `: ${input.freezeMessage}` : \"\"}`,\n );\n }\n\n if (input.healthChecksConfigured && input.healthScore < 50) {\n reasons.push(`Health score ${input.healthScore} below minimum (50)`);\n }\n\n if (input.requireSecurityClear && input.securityBlocked) {\n reasons.push(\"Security gate requires clearance — blocking alerts present\");\n }\n\n const blockingFindings = (input.policyFindings ?? []).filter((f) =>\n /blocking|requires|exceeds|configured to block/i.test(f),\n );\n if (blockingFindings.length > 0 && input.gateDecision === \"block\") {\n for (const finding of blockingFindings.slice(0, 3)) {\n if (!reasons.includes(finding)) reasons.push(finding);\n }\n }\n\n const releaseReady = reasons.length === 0;\n\n return { releaseReady, reasons };\n}\n\nexport function applyReleaseReadyToEvaluation(\n evaluation: GateEvaluation,\n result: ReleaseReadyResult,\n gateMode: GateMode,\n): GateEvaluation {\n return {\n ...evaluation,\n releaseReady: result.releaseReady,\n releaseReadyReasons: result.reasons.length > 0 ? result.reasons : undefined,\n gateMode,\n };\n}\n\nexport function checkConclusionForEvaluation(\n evaluation: GateEvaluation,\n): \"success\" | \"neutral\" | \"failure\" {\n const mode = evaluation.gateMode ?? \"risk-only\";\n\n if (mode === \"advisory\") {\n return \"neutral\";\n }\n\n if (mode === \"release-ready\") {\n return evaluation.releaseReady ? \"success\" : \"failure\";\n }\n\n switch (evaluation.gateDecision) {\n case \"allow\":\n return \"success\";\n case \"warn\":\n return \"neutral\";\n case \"block\":\n return \"failure\";\n default: {\n const _exhaustive: never = evaluation.gateDecision;\n return \"failure\";\n }\n }\n}\n\nexport function shouldBlockMerge(evaluation: GateEvaluation): boolean {\n const mode = evaluation.gateMode ?? \"risk-only\";\n\n if (mode === \"advisory\") return false;\n if (mode === \"release-ready\") return evaluation.releaseReady === false;\n return evaluation.gateDecision === \"block\";\n}\n\nexport function resolveCheckName(gateMode: GateMode, configuredName?: string): string {\n if (gateMode === \"risk-only\") return \"Trailhead\";\n return configuredName ?? \"Trailhead — Release Ready\";\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { checkNameMatches } from \"./ci-core.js\";\nimport { parseRepoConfigContent } from \"./config-core.js\";\nimport { resolveCheckName } from \"./release-ready.js\";\nimport type { GateMode, RepoConfig } from \"./types.js\";\n\nexport type DoctorSeverity = \"error\" | \"warn\" | \"info\";\n\nexport interface DoctorFinding {\n severity: DoctorSeverity;\n code: string;\n message: string;\n}\n\nexport interface DoctorReport {\n configPath: string | null;\n configValid: boolean;\n gateMode: GateMode;\n expectedCheckName: string;\n configuredChecks: string[];\n observedChecks: string[];\n findings: DoctorFinding[];\n ok: boolean;\n}\n\nexport interface RunDoctorOptions {\n cwd?: string;\n offline?: boolean;\n githubToken?: string;\n repo?: string;\n ref?: string;\n}\n\nconst CONFIG_CANDIDATES = [\".trailhead.yml\", \".deployguard.yml\"];\n\nexport function findConfigPath(cwd: string): string | null {\n for (const name of CONFIG_CANDIDATES) {\n const candidate = path.join(cwd, name);\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n}\n\nexport function loadRepoConfig(cwd: string): {\n configPath: string | null;\n config: RepoConfig | null;\n error?: string;\n} {\n const configPath = findConfigPath(cwd);\n if (!configPath) {\n return {\n configPath: null,\n config: null,\n error: \"No .trailhead.yml or .deployguard.yml found\",\n };\n }\n\n const content = fs.readFileSync(configPath, \"utf8\");\n const config = parseRepoConfigContent(content);\n if (!config) {\n return {\n configPath,\n config: null,\n error: `Failed to parse ${path.basename(configPath)} — check YAML structure and schema fields`,\n };\n }\n\n return { configPath, config };\n}\n\nexport function collectConfiguredChecks(config: RepoConfig): string[] {\n const names = new Set<string>();\n for (const context of config.contexts) {\n for (const name of context.ci?.required_checks ?? []) {\n names.add(name);\n }\n for (const name of context.ci?.optional_checks ?? []) {\n names.add(name);\n }\n }\n return [...names];\n}\n\nexport function validateConfigStructure(\n config: RepoConfig,\n configPath: string,\n): DoctorFinding[] {\n const findings: DoctorFinding[] = [];\n const fileName = path.basename(configPath);\n const gateMode = config.gate.mode;\n\n if (gateMode !== \"risk-only\" && config.schema_version < 2) {\n findings.push({\n severity: \"warn\",\n code: \"schema_version\",\n message: `${fileName} uses schema_version ${config.schema_version} with gate.mode=${gateMode} — consider schema_version: 2 and contexts[]`,\n });\n }\n\n const risk = config.thresholds.risk;\n const warn = config.thresholds.warn;\n if (risk !== undefined && warn !== undefined && warn >= risk) {\n findings.push({\n severity: \"warn\",\n code: \"threshold_order\",\n message: `warn threshold (${warn}) should be lower than risk threshold (${risk})`,\n });\n }\n\n if (gateMode !== \"risk-only\") {\n if (config.contexts.length === 0) {\n findings.push({\n severity: \"error\",\n code: \"missing_contexts\",\n message:\n \"release-ready/advisory mode requires at least one contexts[] entry with ci.required_checks\",\n });\n }\n\n for (const context of config.contexts) {\n const required = context.ci?.required_checks ?? [];\n if (required.length === 0) {\n findings.push({\n severity: \"warn\",\n code: \"empty_required_checks\",\n message: `Context \"${context.name}\" has no ci.required_checks — release-ready may not wait for CI`,\n });\n }\n }\n }\n\n const gateCheck = resolveCheckName(gateMode, config.gate.check_name);\n if (gateMode !== \"risk-only\" && !gateCheck.includes(\"Release Ready\")) {\n findings.push({\n severity: \"info\",\n code: \"custom_check_name\",\n message: `Branch protection should require check name \"${gateCheck}\"`,\n });\n }\n\n return findings;\n}\n\nexport function compareConfiguredChecks(\n configuredChecks: string[],\n observedChecks: string[],\n): DoctorFinding[] {\n if (observedChecks.length === 0) {\n return [];\n }\n\n const findings: DoctorFinding[] = [];\n const observed = [...new Set(observedChecks)];\n\n for (const configured of configuredChecks) {\n const matched = observed.some((actual) => checkNameMatches(configured, actual));\n if (!matched) {\n findings.push({\n severity: \"warn\",\n code: \"unknown_check_name\",\n message: `Configured check \"${configured}\" did not match any recent GitHub check run`,\n });\n }\n }\n\n const selfChecks = new Set([\n \"Trailhead\",\n \"Trailhead — Release Ready\",\n resolveCheckName(\"release-ready\"),\n resolveCheckName(\"risk-only\"),\n ]);\n\n for (const actual of observed) {\n if (selfChecks.has(actual)) continue;\n const referenced = configuredChecks.some((configured) =>\n checkNameMatches(configured, actual),\n );\n if (!referenced) {\n findings.push({\n severity: \"info\",\n code: \"unconfigured_check\",\n message: `GitHub check \"${actual}\" is not referenced in contexts[].ci (optional unless required)`,\n });\n }\n }\n\n return findings;\n}\n\nexport interface GitHubRepoRef {\n owner: string;\n repo: string;\n}\n\nexport function parseRepoRef(input: string): GitHubRepoRef | null {\n const match = input.match(/^([^/]+)\\/([^/]+)$/);\n if (!match) return null;\n return { owner: match[1], repo: match[2] };\n}\n\nasync function githubRequest<T>(\n token: string,\n url: string,\n): Promise<{ ok: true; data: T } | { ok: false; status: number; message: string }> {\n const response = await fetch(url, {\n headers: {\n Accept: \"application/vnd.github+json\",\n Authorization: `Bearer ${token}`,\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n return {\n ok: false,\n status: response.status,\n message: body || response.statusText,\n };\n }\n\n return { ok: true, data: (await response.json()) as T };\n}\n\nasync function resolveCommitSha(\n token: string,\n repoRef: GitHubRepoRef,\n ref?: string,\n): Promise<string | null> {\n if (ref) return ref;\n\n const pulls = await githubRequest<Array<{ head: { sha: string } }>>(\n token,\n `https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/pulls?state=open&per_page=1`,\n );\n if (pulls.ok && pulls.data[0]?.head.sha) {\n return pulls.data[0].head.sha;\n }\n\n const repo = await githubRequest<{ default_branch: string }>(\n token,\n `https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}`,\n );\n if (!repo.ok) return null;\n\n const branch = await githubRequest<{ commit: { sha: string } }>(\n token,\n `https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/branches/${encodeURIComponent(repo.data.default_branch)}`,\n );\n return branch.ok ? branch.data.commit.sha : null;\n}\n\nexport async function fetchObservedCheckNames(options: {\n token: string;\n repo: GitHubRepoRef;\n ref?: string;\n}): Promise<{ checks: string[]; error?: string }> {\n const sha = await resolveCommitSha(options.token, options.repo, options.ref);\n if (!sha) {\n return { checks: [], error: \"Could not resolve a commit SHA for check lookup\" };\n }\n\n const names = new Set<string>();\n let page = 1;\n\n while (true) {\n const result = await githubRequest<{\n check_runs: Array<{ name: string }>;\n }>(\n options.token,\n `https://api.github.com/repos/${options.repo.owner}/${options.repo.repo}/commits/${sha}/check-runs?per_page=100&page=${page}`,\n );\n\n if (!result.ok) {\n return {\n checks: [],\n error: `GitHub Checks API failed (HTTP ${result.status})`,\n };\n }\n\n for (const run of result.data.check_runs) {\n names.add(run.name);\n }\n\n if (result.data.check_runs.length < 100) break;\n page += 1;\n }\n\n return { checks: [...names].sort() };\n}\n\nexport async function runDoctor(options: RunDoctorOptions = {}): Promise<DoctorReport> {\n const cwd = options.cwd ?? process.cwd();\n const loaded = loadRepoConfig(cwd);\n const findings: DoctorFinding[] = [];\n\n if (!loaded.configPath || !loaded.config) {\n findings.push({\n severity: \"error\",\n code: \"config_missing\",\n message: loaded.error ?? \"Configuration file not found\",\n });\n return {\n configPath: loaded.configPath,\n configValid: false,\n gateMode: \"risk-only\",\n expectedCheckName: \"Trailhead\",\n configuredChecks: [],\n observedChecks: [],\n findings,\n ok: false,\n };\n }\n\n const config = loaded.config;\n const gateMode = config.gate.mode;\n const expectedCheckName = resolveCheckName(gateMode, config.gate.check_name);\n const configuredChecks = collectConfiguredChecks(config);\n\n findings.push(...validateConfigStructure(config, loaded.configPath));\n\n let observedChecks: string[] = [];\n if (!options.offline) {\n const token = options.githubToken ?? process.env.GITHUB_TOKEN ?? \"\";\n const repoInput = options.repo ?? process.env.GITHUB_REPOSITORY ?? \"\";\n const repoRef = parseRepoRef(repoInput);\n\n if (!token) {\n findings.push({\n severity: \"info\",\n code: \"offline_checks\",\n message:\n \"Set GITHUB_TOKEN (or pass --token) to compare configured checks against GitHub\",\n });\n } else if (!repoRef) {\n findings.push({\n severity: \"info\",\n code: \"offline_checks\",\n message:\n \"Set GITHUB_REPOSITORY (or pass --repo owner/name) to compare checks against GitHub\",\n });\n } else {\n const observed = await fetchObservedCheckNames({\n token,\n repo: repoRef,\n ref: options.ref,\n });\n observedChecks = observed.checks;\n if (observed.error) {\n findings.push({\n severity: \"warn\",\n code: \"github_checks\",\n message: observed.error,\n });\n } else if (configuredChecks.length > 0) {\n findings.push(...compareConfiguredChecks(configuredChecks, observedChecks));\n }\n }\n }\n\n const ok = !findings.some((finding) => finding.severity === \"error\");\n return {\n configPath: loaded.configPath,\n configValid: true,\n gateMode,\n expectedCheckName,\n configuredChecks,\n observedChecks,\n findings,\n ok,\n };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n const lines: string[] = [];\n lines.push(\"Trailhead Doctor\");\n lines.push(\"================\");\n lines.push(\"\");\n\n if (report.configPath) {\n lines.push(`Config: ${report.configPath}`);\n } else {\n lines.push(\"Config: (not found)\");\n }\n\n lines.push(`Gate mode: ${report.gateMode}`);\n lines.push(`Expected branch protection check: ${report.expectedCheckName}`);\n\n if (report.configuredChecks.length > 0) {\n lines.push(`Configured CI checks: ${report.configuredChecks.join(\", \")}`);\n }\n\n if (report.observedChecks.length > 0) {\n lines.push(`Observed GitHub checks: ${report.observedChecks.join(\", \")}`);\n }\n\n if (report.findings.length === 0) {\n lines.push(\"\");\n lines.push(\"No issues found.\");\n return lines.join(\"\\n\");\n }\n\n lines.push(\"\");\n for (const finding of report.findings) {\n const label =\n finding.severity === \"error\"\n ? \"ERROR\"\n : finding.severity === \"warn\"\n ? \"WARN\"\n : \"INFO\";\n lines.push(`${label} [${finding.code}] ${finding.message}`);\n }\n\n lines.push(\"\");\n lines.push(\n report.ok\n ? \"Result: OK (review warnings before release-ready rollout)\"\n : \"Result: FAILED\",\n );\n return lines.join(\"\\n\");\n}\n","import { formatDoctorReport, runDoctor } from \"./shared/doctor.js\";\n\nfunction printUsage(): void {\n process.stdout.write(`\nTrailhead Doctor — validate .trailhead.yml and compare CI check names\n\nUsage:\n trailhead doctor [options]\n\nOptions:\n --path <dir> Directory to scan (default: cwd)\n --repo <owner/name> GitHub repository for check lookup\n --token <token> GitHub token (default: GITHUB_TOKEN)\n --ref <sha> Commit SHA for check runs (default: latest open PR or default branch)\n --offline Skip GitHub API check comparison\n --json Output report as JSON\n -h, --help Show this help\n\nEnvironment:\n GITHUB_TOKEN Personal access token with checks:read\n GITHUB_REPOSITORY owner/repo when running in GitHub Actions\n`);\n}\n\nexport async function runDoctorCommand(args: string[]): Promise<number> {\n if (args.includes(\"-h\") || args.includes(\"--help\")) {\n printUsage();\n return 0;\n }\n\n let cwd = process.cwd();\n let repo: string | undefined;\n let token: string | undefined;\n let ref: string | undefined;\n let offline = false;\n let json = false;\n\n for (let i = 0; i < args.length; i += 1) {\n const arg = args[i];\n if (arg === \"--offline\") {\n offline = true;\n continue;\n }\n if (arg === \"--json\") {\n json = true;\n continue;\n }\n if (arg === \"--path\" && args[i + 1]) {\n cwd = args[i + 1];\n i += 1;\n continue;\n }\n if (arg === \"--repo\" && args[i + 1]) {\n repo = args[i + 1];\n i += 1;\n continue;\n }\n if (arg === \"--token\" && args[i + 1]) {\n token = args[i + 1];\n i += 1;\n continue;\n }\n if (arg === \"--ref\" && args[i + 1]) {\n ref = args[i + 1];\n i += 1;\n continue;\n }\n process.stderr.write(`Unknown option: ${arg}\\n`);\n printUsage();\n return 2;\n }\n\n const report = await runDoctor({\n cwd,\n offline,\n githubToken: token,\n repo,\n ref,\n });\n\n if (json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n } else {\n process.stdout.write(`${formatDoctorReport(report)}\\n`);\n }\n\n return report.ok ? 0 : 1;\n}\n","// Shared helpers for Gate 1 submission checks (pure, no I/O).\n\nimport type { SubmissionFileInfo } from \"./types.js\";\n\nexport function normalizePath(filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n\nexport function extensionOf(filename: string): string {\n const base = normalizePath(filename);\n const idx = base.lastIndexOf(\".\");\n return idx >= 0 ? base.slice(idx).toLowerCase() : \"\";\n}\n\nexport function addedLines(patch: string | undefined): string[] {\n if (!patch) return [];\n return patch\n .split(\"\\n\")\n .filter((line) => line.startsWith(\"+\") && !line.startsWith(\"+++\"))\n .map((line) => line.slice(1));\n}\n\n/** Approximate post-change file body from a unified diff hunk (context + additions). */\nexport function effectiveContentFromPatch(patch: string | undefined): string {\n if (!patch) return \"\";\n return patch\n .split(\"\\n\")\n .filter(\n (line) =>\n !line.startsWith(\"@@\") && !line.startsWith(\"---\") && !line.startsWith(\"+++\"),\n )\n .filter((line) => !line.startsWith(\"-\"))\n .map((line) => (line.startsWith(\"+\") || line.startsWith(\" \") ? line.slice(1) : line))\n .join(\"\\n\");\n}\n\nexport function fileContent(file: SubmissionFileInfo): string {\n if (typeof file.content === \"string\") return file.content;\n return effectiveContentFromPatch(file.patch);\n}\n\nexport function lineCountFromPatch(patch: string | undefined): number {\n const content = effectiveContentFromPatch(patch);\n if (!content) return 0;\n return content.split(\"\\n\").length;\n}\n\nexport function scanAddedContent(\n files: SubmissionFileInfo[],\n predicate: (line: string, filename: string) => boolean,\n): string[] {\n const hits: string[] = [];\n for (const file of files) {\n for (const line of addedLines(file.patch)) {\n if (predicate(line, file.filename)) hits.push(file.filename);\n }\n }\n return [...new Set(hits)];\n}\n\nexport function scanFileContent(\n files: SubmissionFileInfo[],\n predicate: (line: string, filename: string, lineNo: number) => boolean,\n): Array<{ file: string; line: number }> {\n const hits: Array<{ file: string; line: number }> = [];\n for (const file of files) {\n const lines = fileContent(file).split(\"\\n\");\n lines.forEach((line, index) => {\n if (predicate(line, file.filename, index + 1)) {\n hits.push({ file: file.filename, line: index + 1 });\n }\n });\n }\n return hits;\n}\n\nexport function prPathSet(files: SubmissionFileInfo[]): Set<string> {\n return new Set(files.map((f) => normalizePath(f.filename)));\n}\n\nexport function isTestPath(filename: string): boolean {\n return /\\/__tests__\\/|\\/test\\/|\\/fixtures\\/|\\.test\\.|\\.spec\\./.test(filename);\n}\n\n/** Default archived/stale path segments skipped by context_freshness. */\nexport const DEFAULT_STALE_PATH_IGNORE = [\"/_stale/\", \"/_archive/\", \"/.archive/\"];\n\nexport function isStaleArchivedPath(\n filename: string,\n extraPatterns: string[] = [],\n): boolean {\n const path = normalizePath(filename);\n return [...DEFAULT_STALE_PATH_IGNORE, ...extraPatterns].some((segment) =>\n path.includes(segment),\n );\n}\n\nexport function packageJsonPathForFile(\n filename: string,\n prPaths: Set<string>,\n): string | null {\n const parts = normalizePath(filename).split(\"/\");\n for (let i = parts.length - 1; i >= 0; i--) {\n const candidate = [...parts.slice(0, i), \"package.json\"].filter(Boolean).join(\"/\");\n if (prPaths.has(candidate)) return candidate;\n }\n return prPaths.has(\"package.json\") ? \"package.json\" : null;\n}\n\nconst VALID_PACKAGE_SPECIFIER = /^(@[\\w.-]+\\/[\\w.-]+|[\\w@][\\w.-]*)(?:\\/[\\w./-]*)?$/;\n\nexport function isValidPackageSpecifier(specifier: string): boolean {\n if (!specifier || specifier.startsWith(\".\") || specifier.startsWith(\"@/\")) return false;\n if (/^https?:|^node:/.test(specifier)) return false;\n if (/[:()\\\\]/.test(specifier)) return false;\n return VALID_PACKAGE_SPECIFIER.test(specifier);\n}\n\n/** Extract module specifiers from full file content (legacy agent-gate parity). */\nexport function extractAllImports(\n content: string,\n): Array<{ specifier: string; line: number }> {\n const results: Array<{ specifier: string; line: number }> = [];\n const patterns = [\n /\\bimport\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)?['\"]([^'\"]+)['\"]/g,\n /\\bexport\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)['\"]([^'\"]+)['\"]/g,\n /\\brequire\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n /\\bimport\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n\n for (const pattern of patterns) {\n pattern.lastIndex = 0;\n for (const match of content.matchAll(pattern)) {\n const specifier = match[1];\n if (!specifier) continue;\n const line = content.slice(0, match.index ?? 0).split(\"\\n\").length;\n results.push({ specifier, line });\n }\n }\n return results;\n}\n\nexport function linesForFreshnessScan(file: {\n filename: string;\n patch?: string;\n content?: string;\n}): string[] {\n if (typeof file.content === \"string\") return file.content.split(\"\\n\");\n return addedLines(file.patch);\n}\n","// Phase 0 agent suggestion checks (weight=0 / advisory in Trailhead).\n// Ported from komatik-agents agent-gate-checks Phase 0 stubs with real heuristics.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst SEVERITY = \"advisory\" as const;\nconst OUTPUT_SIZE_MIN_CHARS = 400;\nconst NARRATIVE_MATCH_THRESHOLD = 3;\n\nconst PREAMBLE_OPENERS =\n /^(let me|here is the|here's the|i('| wi)ll|after reviewing|to start|based on my analysis)/i;\nconst SESSION_NARRATIVE =\n /\\bI (queried|reviewed|checked|will (build|create|fix|implement|add|update))/gi;\nconst PARTIAL_COMPLETION = /\\b\\d+\\s*(?:\\/|of)\\s*\\d+\\b/i;\nconst INCOMPLETE_MARKER = /\\b(INCOMPLETE|PARTIAL)\\b/i;\nconst FABRICATED_ID = /\\b(session|run|task|message)[-_]?[a-f0-9]{6,}\\b/gi;\nconst FILE_REF =\n /(?:^|[\\s('\"`])((?:src|scripts|supabase|app|agents)\\/[a-z0-9_/.-]+\\.(?:ts|tsx|js|mjs|sql|py|md))/gi;\nconst ACTION_SUFFIX = /(?:→\\s*@[\\w-]+|— No actions surfaced)\\s*$/i;\nconst UNVERIFIED_MARKER = /\\[UNVERIFIED\\]|verify after|needs verification/i;\nconst OWNER_DUE = /Owner:\\s*@[\\w-]+[\\s\\S]{0,120}Due:\\s*\\d{4}-\\d{2}-\\d{2}/i;\nconst FIX_CLAIM = /\\b(fix applied|now working|is live|deployed successfully)\\b/i;\nconst MULTI_PHASE = /\\bphase\\s+[ab12]\\b/gi;\nconst DEP_MATRIX = /\\b(depends on:|dependency matrix|blocks:|x blocks y)\\b/i;\nconst RUNBOOK_HINT = /runbook|deploy(?:ment)? guide/i;\nconst SECRETS_PREREQ =\n /\\b(secrets list|prerequisites:|required env|environment variables)\\b/i;\nconst PROPOSAL_ONLY = /\\bPROPOSAL_ONLY\\b/i;\nconst SCHEMA_LINK = /https?:\\/\\/[^\\s)]+\\/(schema|openapi|api-docs)/i;\n\nfunction advisory(\n partial: Omit<SubmissionCheckResult, \"severity\" | \"autofix_eligible\">,\n): SubmissionCheckResult {\n return { severity: SEVERITY, autofix_eligible: false, ...partial };\n}\n\nexport function suggestionMarkdownFiles(\n ctx: SubmissionCheckContext,\n): SubmissionFileInfo[] {\n return ctx.files.filter((file) => {\n const path = normalizePath(file.filename);\n if (!/\\.md$/i.test(path)) return false;\n return /agents\\/[^/]+\\/suggestions\\//.test(path) || /\\/suggestions\\//.test(path);\n });\n}\n\nfunction agentFromPath(filePath: string): string | null {\n const match = normalizePath(filePath).match(/^agents\\/([^/]+)\\//);\n return match?.[1] ?? null;\n}\n\nfunction paragraphs(text: string): string[] {\n return text\n .split(/\\n\\s*\\n/)\n .map((p) => p.trim())\n .filter((p) => p.length > 0 && !/^#+\\s/.test(p));\n}\n\nfunction extractFileRefs(text: string): string[] {\n const refs = new Set<string>();\n const re = new RegExp(FILE_REF.source, FILE_REF.flags);\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n if (m[1]) refs.add(normalizePath(m[1]));\n }\n const backtick = /`((?:src|scripts|supabase|app|agents)\\/[a-z0-9_/.-]+\\.[a-z]+)`/gi;\n while ((m = backtick.exec(text)) !== null) {\n refs.add(normalizePath(m[1]));\n }\n return [...refs];\n}\n\nfunction hasToBeCreatedMarker(text: string, ref: string): boolean {\n const idx = text.indexOf(ref);\n if (idx < 0) return false;\n const window = text.slice(Math.max(0, idx - 80), idx + ref.length + 80);\n return /to-be-created|to be created|TBD path/i.test(window);\n}\n\nexport function detectOutputSizeMin(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx);\n const short = files.filter((f) => fileContent(f).trim().length < OUTPUT_SIZE_MIN_CHARS);\n if (short.length === 0) return null;\n return advisory({\n code: \"output_size_min\",\n title: \"Agent output below minimum size\",\n detail: `Suggestion markdown under ${OUTPUT_SIZE_MIN_CHARS} chars (possible model bail-out): ${short.map((f) => f.filename).join(\", \")}.`,\n files: short.map((f) => f.filename),\n suggested_action: \"Expand the proposal with concrete actions and file-level detail.\",\n });\n}\n\nexport function detectActionExtractionPresent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx).filter(\n (f) => agentFromPath(f.filename) === \"coordinator\",\n );\n const missing: string[] = [];\n for (const file of files) {\n const paras = paragraphs(fileContent(file));\n const bad = paras.filter((p) => !ACTION_SUFFIX.test(p));\n if (bad.length > 0) missing.push(file.filename);\n }\n if (missing.length === 0) return null;\n return advisory({\n code: \"action_extraction_present\",\n title: \"Coordinator paragraph missing action extraction\",\n detail: `Paragraphs should end with \"→ @owner\" or \"— No actions surfaced\": ${missing.join(\", \")}.`,\n files: missing,\n suggested_action: \"Add explicit owner routing or a no-actions line per paragraph.\",\n });\n}\n\nexport function detectDeltaSectionPresent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx).filter((f) => {\n const agent = agentFromPath(f.filename);\n const path = normalizePath(f.filename);\n return agent === \"knowledge-scout\" || /DAILY-INTEL\\.md$/i.test(path);\n });\n const missing: string[] = [];\n for (const file of files) {\n const text = fileContent(file);\n if (!/## Δ Since Last Sweep/i.test(text) && !/No deltas — quiet sweep/i.test(text)) {\n missing.push(file.filename);\n }\n }\n if (missing.length === 0) return null;\n return advisory({\n code: \"delta_section_present\",\n title: \"Missing delta section (knowledge-scout)\",\n detail: `Require \"## Δ Since Last Sweep\" or \"No deltas — quiet sweep\": ${missing.join(\", \")}.`,\n files: missing,\n suggested_action: \"Add a delta header or explicit quiet-sweep line.\",\n });\n}\n\nexport function detectPreambleAbsent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const paras = paragraphs(fileContent(file)).slice(0, 2);\n if (paras.some((p) => PREAMBLE_OPENERS.test(p.split(\"\\n\")[0]?.trim() ?? \"\"))) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"preamble_absent\",\n title: \"Conversational preamble detected\",\n detail: `Opening paragraphs use session-style preambles: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Start with structured content, not meta narration.\",\n });\n}\n\nexport function detectGraduationSignalsSectionPresent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx).filter(\n (f) => agentFromPath(f.filename) === \"rd-satellite\",\n );\n const missing = files\n .filter((f) => !/## Graduation Signals/i.test(fileContent(f)))\n .map((f) => f.filename);\n if (missing.length === 0) return null;\n return advisory({\n code: \"graduation_signals_section_present\",\n title: \"Missing Graduation Signals section\",\n detail: `rd-satellite output requires \"## Graduation Signals\": ${missing.join(\", \")}.`,\n files: missing,\n suggested_action: \"Add a Graduation Signals section with promotion criteria.\",\n });\n}\n\nexport function detectFabricatedIdCheck(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n const ids: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n const re = new RegExp(FABRICATED_ID.source, FABRICATED_ID.flags);\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n ids.push(m[0]);\n hits.push(file.filename);\n }\n }\n if (ids.length === 0) return null;\n return advisory({\n code: \"fabricated_id_check\",\n title: \"Suspicious session/run identifiers\",\n detail: `Verify identifiers against agent_runs/tasks/messages: ${[...new Set(ids)].slice(0, 8).join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action: \"Replace fabricated IDs with verified references or remove them.\",\n });\n}\n\nexport function detectSessionNarrativeDetection(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n let total = 0;\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n const re = new RegExp(SESSION_NARRATIVE.source, SESSION_NARRATIVE.flags);\n const matches = text.match(re);\n // Per-file threshold: flag a single document dense with first-person\n // session narration, not a cumulative count that a large multi-file\n // submission would trip just by volume.\n if (matches && matches.length >= NARRATIVE_MATCH_THRESHOLD) {\n total += matches.length;\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"session_narrative_detection\",\n title: \"Session narrative instead of file content\",\n detail: `${total} first-person session phrases in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Replace narration with concrete diffs, paths, and commands.\",\n });\n}\n\nexport function detectIncompletenessSelfFlag(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n if (PARTIAL_COMPLETION.test(text) && !INCOMPLETE_MARKER.test(text)) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"incompleteness_self_flag\",\n title: \"Partial completion without INCOMPLETE marker\",\n detail: `Fractional completion hints require INCOMPLETE/PARTIAL flag: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: 'Add an explicit \"INCOMPLETE\" or \"PARTIAL\" marker for scoped work.',\n });\n}\n\nexport function detectReferencedFilesExist(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n // Needs a repo file listing to tell a fabricated path from a reference to an\n // existing, unchanged file. Without it, stay dormant — flagging every path\n // that merely isn't part of this PR is almost all false positives.\n if (!ctx.repoPaths) return null;\n const repoPaths = ctx.repoPaths;\n const missing: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n for (const ref of extractFileRefs(text)) {\n const known =\n ctx.prPaths.has(ref) ||\n repoPaths.has(ref) ||\n [...ctx.prPaths].some((p) => p.endsWith(`/${ref}`)) ||\n [...repoPaths].some((p) => p.endsWith(`/${ref}`));\n if (!known && !hasToBeCreatedMarker(text, ref)) {\n missing.push(`${file.filename}: ${ref}`);\n }\n }\n }\n if (missing.length === 0) return null;\n return advisory({\n code: \"referenced_files_exist\",\n title: \"Referenced path missing from PR and repo\",\n detail: missing.slice(0, 12).join(\"; \"),\n files: missing.map((m) => m.split(\": \")[0] ?? m),\n suggested_action: 'Include the file in the PR or mark adjacent \"to-be-created\".',\n });\n}\n\nexport function detectPrerequisiteSecretsCheck(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const path = normalizePath(file.filename);\n const text = fileContent(file);\n const titleLine = text.split(\"\\n\").find((l) => /^#\\s/.test(l)) ?? \"\";\n if (!RUNBOOK_HINT.test(`${path} ${titleLine}`)) continue;\n const head = text.split(\"\\n\").slice(0, 30).join(\"\\n\");\n if (!SECRETS_PREREQ.test(head)) hits.push(file.filename);\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"prerequisite_secrets_check\",\n title: \"Runbook missing secrets prerequisite step\",\n detail: `First 30 lines should include secrets/env prerequisites: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Open runbooks with Prerequisites or `secrets list` verification.\",\n });\n}\n\nexport function detectDependencyDagValidation(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n const phases = (text.match(MULTI_PHASE) ?? []).length;\n if (phases >= 2 && !DEP_MATRIX.test(text)) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"dependency_dag_validation\",\n title: \"Multi-phase plan missing dependency matrix\",\n detail: `Multi-phase proposals need Depends on / blocks lines: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Add explicit phase dependencies (X blocks Y).\",\n });\n}\n\nexport function detectUncommittedFixCheck(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n if (FIX_CLAIM.test(fileContent(file))) hits.push(file.filename);\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"uncommitted_fix_check\",\n title: \"Fix claim requires commit verification\",\n detail: `Claims like \"fix applied\" / \"now working\" need matching git history: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action:\n \"Reference the commit SHA or flag changes as on-disk pending commit.\",\n });\n}\n\nexport function detectVerificationOwnerAssigned(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const lines = fileContent(file).split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n if (!UNVERIFIED_MARKER.test(lines[i] ?? \"\")) continue;\n const window = lines.slice(i, i + 6).join(\"\\n\");\n if (!OWNER_DUE.test(window)) {\n hits.push(file.filename);\n break;\n }\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"verification_owner_assigned\",\n title: \"UNVERIFIED item missing owner and due date\",\n detail: `Add Owner: @user and Due: YYYY-MM-DD near unverified items: ${[...new Set(hits)].join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action: \"Assign verification owner and due date for each UNVERIFIED line.\",\n });\n}\n\nexport function detectExternalInterfaceValidation(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const path = normalizePath(file.filename);\n const crossRepo = /suggestions\\/(?!komatik-agents)[^/]+\\//.test(path);\n if (!crossRepo) continue;\n const text = fileContent(file);\n if (!PROPOSAL_ONLY.test(text) && !SCHEMA_LINK.test(text)) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"external_interface_validation\",\n title: \"Cross-repo proposal lacks schema verification\",\n detail: `Cross-repo suggestions need PROPOSAL_ONLY or verified schema link: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Link verified target schema or mark PROPOSAL_ONLY.\",\n });\n}\n\nexport function runPhase0Detectors(ctx: SubmissionCheckContext): SubmissionCheckResult[] {\n if (suggestionMarkdownFiles(ctx).length === 0) return [];\n const checks = [\n detectOutputSizeMin,\n detectActionExtractionPresent,\n detectDeltaSectionPresent,\n detectPreambleAbsent,\n detectGraduationSignalsSectionPresent,\n detectFabricatedIdCheck,\n detectSessionNarrativeDetection,\n detectIncompletenessSelfFlag,\n detectReferencedFilesExist,\n detectPrerequisiteSecretsCheck,\n detectDependencyDagValidation,\n detectUncommittedFixCheck,\n detectVerificationOwnerAssigned,\n detectExternalInterfaceValidation,\n ];\n return checks\n .map((fn) => fn(ctx))\n .filter((check): check is SubmissionCheckResult => check !== null);\n}\n","\n/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */\nfunction isNothing(subject) {\n return (typeof subject === 'undefined') || (subject === null);\n}\n\n\nfunction isObject(subject) {\n return (typeof subject === 'object') && (subject !== null);\n}\n\n\nfunction toArray(sequence) {\n if (Array.isArray(sequence)) return sequence;\n else if (isNothing(sequence)) return [];\n\n return [ sequence ];\n}\n\n\nfunction extend(target, source) {\n var index, length, key, sourceKeys;\n\n if (source) {\n sourceKeys = Object.keys(source);\n\n for (index = 0, length = sourceKeys.length; index < length; index += 1) {\n key = sourceKeys[index];\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\n\nfunction repeat(string, count) {\n var result = '', cycle;\n\n for (cycle = 0; cycle < count; cycle += 1) {\n result += string;\n }\n\n return result;\n}\n\n\nfunction isNegativeZero(number) {\n return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);\n}\n\n\nvar isNothing_1 = isNothing;\nvar isObject_1 = isObject;\nvar toArray_1 = toArray;\nvar repeat_1 = repeat;\nvar isNegativeZero_1 = isNegativeZero;\nvar extend_1 = extend;\n\nvar common = {\n\tisNothing: isNothing_1,\n\tisObject: isObject_1,\n\ttoArray: toArray_1,\n\trepeat: repeat_1,\n\tisNegativeZero: isNegativeZero_1,\n\textend: extend_1\n};\n\n// YAML error class. http://stackoverflow.com/questions/8458984\n\n\nfunction formatError(exception, compact) {\n var where = '', message = exception.reason || '(unknown reason)';\n\n if (!exception.mark) return message;\n\n if (exception.mark.name) {\n where += 'in \"' + exception.mark.name + '\" ';\n }\n\n where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';\n\n if (!compact && exception.mark.snippet) {\n where += '\\n\\n' + exception.mark.snippet;\n }\n\n return message + ' ' + where;\n}\n\n\nfunction YAMLException$1(reason, mark) {\n // Super constructor\n Error.call(this);\n\n this.name = 'YAMLException';\n this.reason = reason;\n this.mark = mark;\n this.message = formatError(this, false);\n\n // Include stack trace in error object\n if (Error.captureStackTrace) {\n // Chrome and NodeJS\n Error.captureStackTrace(this, this.constructor);\n } else {\n // FF, IE 10+ and Safari 6+. Fallback for others\n this.stack = (new Error()).stack || '';\n }\n}\n\n\n// Inherit from Error\nYAMLException$1.prototype = Object.create(Error.prototype);\nYAMLException$1.prototype.constructor = YAMLException$1;\n\n\nYAMLException$1.prototype.toString = function toString(compact) {\n return this.name + ': ' + formatError(this, compact);\n};\n\n\nvar exception = YAMLException$1;\n\n// get snippet for a single line, respecting maxLength\nfunction getLine(buffer, lineStart, lineEnd, position, maxLineLength) {\n var head = '';\n var tail = '';\n var maxHalfLength = Math.floor(maxLineLength / 2) - 1;\n\n if (position - lineStart > maxHalfLength) {\n head = ' ... ';\n lineStart = position - maxHalfLength + head.length;\n }\n\n if (lineEnd - position > maxHalfLength) {\n tail = ' ...';\n lineEnd = position + maxHalfLength - tail.length;\n }\n\n return {\n str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, '→') + tail,\n pos: position - lineStart + head.length // relative position\n };\n}\n\n\nfunction padStart(string, max) {\n return common.repeat(' ', max - string.length) + string;\n}\n\n\nfunction makeSnippet(mark, options) {\n options = Object.create(options || null);\n\n if (!mark.buffer) return null;\n\n if (!options.maxLength) options.maxLength = 79;\n if (typeof options.indent !== 'number') options.indent = 1;\n if (typeof options.linesBefore !== 'number') options.linesBefore = 3;\n if (typeof options.linesAfter !== 'number') options.linesAfter = 2;\n\n var re = /\\r?\\n|\\r|\\0/g;\n var lineStarts = [ 0 ];\n var lineEnds = [];\n var match;\n var foundLineNo = -1;\n\n while ((match = re.exec(mark.buffer))) {\n lineEnds.push(match.index);\n lineStarts.push(match.index + match[0].length);\n\n if (mark.position <= match.index && foundLineNo < 0) {\n foundLineNo = lineStarts.length - 2;\n }\n }\n\n if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;\n\n var result = '', i, line;\n var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;\n var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);\n\n for (i = 1; i <= options.linesBefore; i++) {\n if (foundLineNo - i < 0) break;\n line = getLine(\n mark.buffer,\n lineStarts[foundLineNo - i],\n lineEnds[foundLineNo - i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n maxLineLength\n );\n result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n' + result;\n }\n\n line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);\n result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n';\n result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\\n';\n\n for (i = 1; i <= options.linesAfter; i++) {\n if (foundLineNo + i >= lineEnds.length) break;\n line = getLine(\n mark.buffer,\n lineStarts[foundLineNo + i],\n lineEnds[foundLineNo + i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n maxLineLength\n );\n result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n';\n }\n\n return result.replace(/\\n$/, '');\n}\n\n\nvar snippet = makeSnippet;\n\nvar TYPE_CONSTRUCTOR_OPTIONS = [\n 'kind',\n 'multi',\n 'resolve',\n 'construct',\n 'instanceOf',\n 'predicate',\n 'represent',\n 'representName',\n 'defaultStyle',\n 'styleAliases'\n];\n\nvar YAML_NODE_KINDS = [\n 'scalar',\n 'sequence',\n 'mapping'\n];\n\nfunction compileStyleAliases(map) {\n var result = {};\n\n if (map !== null) {\n Object.keys(map).forEach(function (style) {\n map[style].forEach(function (alias) {\n result[String(alias)] = style;\n });\n });\n }\n\n return result;\n}\n\nfunction Type$1(tag, options) {\n options = options || {};\n\n Object.keys(options).forEach(function (name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new exception('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.');\n }\n });\n\n // TODO: Add tag format check.\n this.options = options; // keep original options in case user wants to extend this type later\n this.tag = tag;\n this.kind = options['kind'] || null;\n this.resolve = options['resolve'] || function () { return true; };\n this.construct = options['construct'] || function (data) { return data; };\n this.instanceOf = options['instanceOf'] || null;\n this.predicate = options['predicate'] || null;\n this.represent = options['represent'] || null;\n this.representName = options['representName'] || null;\n this.defaultStyle = options['defaultStyle'] || null;\n this.multi = options['multi'] || false;\n this.styleAliases = compileStyleAliases(options['styleAliases'] || null);\n\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new exception('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.');\n }\n}\n\nvar type = Type$1;\n\n/*eslint-disable max-len*/\n\n\n\n\n\nfunction compileList(schema, name) {\n var result = [];\n\n schema[name].forEach(function (currentType) {\n var newIndex = result.length;\n\n result.forEach(function (previousType, previousIndex) {\n if (previousType.tag === currentType.tag &&\n previousType.kind === currentType.kind &&\n previousType.multi === currentType.multi) {\n\n newIndex = previousIndex;\n }\n });\n\n result[newIndex] = currentType;\n });\n\n return result;\n}\n\n\nfunction compileMap(/* lists... */) {\n var result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {},\n multi: {\n scalar: [],\n sequence: [],\n mapping: [],\n fallback: []\n }\n }, index, length;\n\n function collectType(type) {\n if (type.multi) {\n result.multi[type.kind].push(type);\n result.multi['fallback'].push(type);\n } else {\n result[type.kind][type.tag] = result['fallback'][type.tag] = type;\n }\n }\n\n for (index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType);\n }\n return result;\n}\n\n\nfunction Schema$1(definition) {\n return this.extend(definition);\n}\n\n\nSchema$1.prototype.extend = function extend(definition) {\n var implicit = [];\n var explicit = [];\n\n if (definition instanceof type) {\n // Schema.extend(type)\n explicit.push(definition);\n\n } else if (Array.isArray(definition)) {\n // Schema.extend([ type1, type2, ... ])\n explicit = explicit.concat(definition);\n\n } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })\n if (definition.implicit) implicit = implicit.concat(definition.implicit);\n if (definition.explicit) explicit = explicit.concat(definition.explicit);\n\n } else {\n throw new exception('Schema.extend argument should be a Type, [ Type ], ' +\n 'or a schema definition ({ implicit: [...], explicit: [...] })');\n }\n\n implicit.forEach(function (type$1) {\n if (!(type$1 instanceof type)) {\n throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');\n }\n\n if (type$1.loadKind && type$1.loadKind !== 'scalar') {\n throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');\n }\n\n if (type$1.multi) {\n throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');\n }\n });\n\n explicit.forEach(function (type$1) {\n if (!(type$1 instanceof type)) {\n throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');\n }\n });\n\n var result = Object.create(Schema$1.prototype);\n\n result.implicit = (this.implicit || []).concat(implicit);\n result.explicit = (this.explicit || []).concat(explicit);\n\n result.compiledImplicit = compileList(result, 'implicit');\n result.compiledExplicit = compileList(result, 'explicit');\n result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);\n\n return result;\n};\n\n\nvar schema = Schema$1;\n\nvar str = new type('tag:yaml.org,2002:str', {\n kind: 'scalar',\n construct: function (data) { return data !== null ? data : ''; }\n});\n\nvar seq = new type('tag:yaml.org,2002:seq', {\n kind: 'sequence',\n construct: function (data) { return data !== null ? data : []; }\n});\n\nvar map = new type('tag:yaml.org,2002:map', {\n kind: 'mapping',\n construct: function (data) { return data !== null ? data : {}; }\n});\n\nvar failsafe = new schema({\n explicit: [\n str,\n seq,\n map\n ]\n});\n\nfunction resolveYamlNull(data) {\n if (data === null) return true;\n\n var max = data.length;\n\n return (max === 1 && data === '~') ||\n (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));\n}\n\nfunction constructYamlNull() {\n return null;\n}\n\nfunction isNull(object) {\n return object === null;\n}\n\nvar _null = new type('tag:yaml.org,2002:null', {\n kind: 'scalar',\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: function () { return '~'; },\n lowercase: function () { return 'null'; },\n uppercase: function () { return 'NULL'; },\n camelcase: function () { return 'Null'; },\n empty: function () { return ''; }\n },\n defaultStyle: 'lowercase'\n});\n\nfunction resolveYamlBoolean(data) {\n if (data === null) return false;\n\n var max = data.length;\n\n return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));\n}\n\nfunction constructYamlBoolean(data) {\n return data === 'true' ||\n data === 'True' ||\n data === 'TRUE';\n}\n\nfunction isBoolean(object) {\n return Object.prototype.toString.call(object) === '[object Boolean]';\n}\n\nvar bool = new type('tag:yaml.org,2002:bool', {\n kind: 'scalar',\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: function (object) { return object ? 'true' : 'false'; },\n uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },\n camelcase: function (object) { return object ? 'True' : 'False'; }\n },\n defaultStyle: 'lowercase'\n});\n\nfunction isHexCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||\n ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||\n ((0x61/* a */ <= c) && (c <= 0x66/* f */));\n}\n\nfunction isOctCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));\n}\n\nfunction isDecCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));\n}\n\nfunction resolveYamlInteger(data) {\n if (data === null) return false;\n\n var max = data.length,\n index = 0,\n hasDigits = false,\n ch;\n\n if (!max) return false;\n\n ch = data[index];\n\n // sign\n if (ch === '-' || ch === '+') {\n ch = data[++index];\n }\n\n if (ch === '0') {\n // 0\n if (index + 1 === max) return true;\n ch = data[++index];\n\n // base 2, base 8, base 16\n\n if (ch === 'b') {\n // base 2\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (ch !== '0' && ch !== '1') return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n\n if (ch === 'x') {\n // base 16\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isHexCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n\n if (ch === 'o') {\n // base 8\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isOctCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n }\n\n // base 10 (except 0)\n\n // value should not start with `_`;\n if (ch === '_') return false;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isDecCode(data.charCodeAt(index))) {\n return false;\n }\n hasDigits = true;\n }\n\n // Should have digits and should not end with `_`\n if (!hasDigits || ch === '_') return false;\n\n return true;\n}\n\nfunction constructYamlInteger(data) {\n var value = data, sign = 1, ch;\n\n if (value.indexOf('_') !== -1) {\n value = value.replace(/_/g, '');\n }\n\n ch = value[0];\n\n if (ch === '-' || ch === '+') {\n if (ch === '-') sign = -1;\n value = value.slice(1);\n ch = value[0];\n }\n\n if (value === '0') return 0;\n\n if (ch === '0') {\n if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);\n if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);\n if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);\n }\n\n return sign * parseInt(value, 10);\n}\n\nfunction isInteger(object) {\n return (Object.prototype.toString.call(object)) === '[object Number]' &&\n (object % 1 === 0 && !common.isNegativeZero(object));\n}\n\nvar int = new type('tag:yaml.org,2002:int', {\n kind: 'scalar',\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },\n octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); },\n decimal: function (obj) { return obj.toString(10); },\n /* eslint-disable max-len */\n hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }\n },\n defaultStyle: 'decimal',\n styleAliases: {\n binary: [ 2, 'bin' ],\n octal: [ 8, 'oct' ],\n decimal: [ 10, 'dec' ],\n hexadecimal: [ 16, 'hex' ]\n }\n});\n\nvar YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +\n // .2e4, .2\n // special case, seems not from spec\n '|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +\n // .inf\n '|[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$');\n\nfunction resolveYamlFloat(data) {\n if (data === null) return false;\n\n if (!YAML_FLOAT_PATTERN.test(data) ||\n // Quick hack to not allow integers end with `_`\n // Probably should update regexp & check speed\n data[data.length - 1] === '_') {\n return false;\n }\n\n return true;\n}\n\nfunction constructYamlFloat(data) {\n var value, sign;\n\n value = data.replace(/_/g, '').toLowerCase();\n sign = value[0] === '-' ? -1 : 1;\n\n if ('+-'.indexOf(value[0]) >= 0) {\n value = value.slice(1);\n }\n\n if (value === '.inf') {\n return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n\n } else if (value === '.nan') {\n return NaN;\n }\n return sign * parseFloat(value, 10);\n}\n\n\nvar SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\n\nfunction representYamlFloat(object, style) {\n var res;\n\n if (isNaN(object)) {\n switch (style) {\n case 'lowercase': return '.nan';\n case 'uppercase': return '.NAN';\n case 'camelcase': return '.NaN';\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '.inf';\n case 'uppercase': return '.INF';\n case 'camelcase': return '.Inf';\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '-.inf';\n case 'uppercase': return '-.INF';\n case 'camelcase': return '-.Inf';\n }\n } else if (common.isNegativeZero(object)) {\n return '-0.0';\n }\n\n res = object.toString(10);\n\n // JS stringifier can build scientific format without dots: 5e-100,\n // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;\n}\n\nfunction isFloat(object) {\n return (Object.prototype.toString.call(object) === '[object Number]') &&\n (object % 1 !== 0 || common.isNegativeZero(object));\n}\n\nvar float = new type('tag:yaml.org,2002:float', {\n kind: 'scalar',\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: 'lowercase'\n});\n\nvar json = failsafe.extend({\n implicit: [\n _null,\n bool,\n int,\n float\n ]\n});\n\nvar core = json;\n\nvar YAML_DATE_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9])' + // [2] month\n '-([0-9][0-9])$'); // [3] day\n\nvar YAML_TIMESTAMP_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9]?)' + // [2] month\n '-([0-9][0-9]?)' + // [3] day\n '(?:[Tt]|[ \\\\t]+)' + // ...\n '([0-9][0-9]?)' + // [4] hour\n ':([0-9][0-9])' + // [5] minute\n ':([0-9][0-9])' + // [6] second\n '(?:\\\\.([0-9]*))?' + // [7] fraction\n '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour\n '(?::([0-9][0-9]))?))?$'); // [11] tz_minute\n\nfunction resolveYamlTimestamp(data) {\n if (data === null) return false;\n if (YAML_DATE_REGEXP.exec(data) !== null) return true;\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n return false;\n}\n\nfunction constructYamlTimestamp(data) {\n var match, year, month, day, hour, minute, second, fraction = 0,\n delta = null, tz_hour, tz_minute, date;\n\n match = YAML_DATE_REGEXP.exec(data);\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n\n if (match === null) throw new Error('Date resolve error');\n\n // match: [1] year [2] month [3] day\n\n year = +(match[1]);\n month = +(match[2]) - 1; // JS month starts with 0\n day = +(match[3]);\n\n if (!match[4]) { // no hour\n return new Date(Date.UTC(year, month, day));\n }\n\n // match: [4] hour [5] minute [6] second [7] fraction\n\n hour = +(match[4]);\n minute = +(match[5]);\n second = +(match[6]);\n\n if (match[7]) {\n fraction = match[7].slice(0, 3);\n while (fraction.length < 3) { // milli-seconds\n fraction += '0';\n }\n fraction = +fraction;\n }\n\n // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute\n\n if (match[9]) {\n tz_hour = +(match[10]);\n tz_minute = +(match[11] || 0);\n delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds\n if (match[9] === '-') delta = -delta;\n }\n\n date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n\n if (delta) date.setTime(date.getTime() - delta);\n\n return date;\n}\n\nfunction representYamlTimestamp(object /*, style*/) {\n return object.toISOString();\n}\n\nvar timestamp = new type('tag:yaml.org,2002:timestamp', {\n kind: 'scalar',\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n});\n\nfunction resolveYamlMerge(data) {\n return data === '<<' || data === null;\n}\n\nvar merge = new type('tag:yaml.org,2002:merge', {\n kind: 'scalar',\n resolve: resolveYamlMerge\n});\n\n/*eslint-disable no-bitwise*/\n\n\n\n\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nvar BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r';\n\n\nfunction resolveYamlBinary(data) {\n if (data === null) return false;\n\n var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;\n\n // Convert one by one.\n for (idx = 0; idx < max; idx++) {\n code = map.indexOf(data.charAt(idx));\n\n // Skip CR/LF\n if (code > 64) continue;\n\n // Fail on illegal characters\n if (code < 0) return false;\n\n bitlen += 6;\n }\n\n // If there are any bits left, source was corrupted\n return (bitlen % 8) === 0;\n}\n\nfunction constructYamlBinary(data) {\n var idx, tailbits,\n input = data.replace(/[\\r\\n=]/g, ''), // remove CR/LF & padding to simplify scan\n max = input.length,\n map = BASE64_MAP,\n bits = 0,\n result = [];\n\n // Collect by 6*4 bits (3 bytes)\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 4 === 0) && idx) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n }\n\n bits = (bits << 6) | map.indexOf(input.charAt(idx));\n }\n\n // Dump tail\n\n tailbits = (max % 4) * 6;\n\n if (tailbits === 0) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n } else if (tailbits === 18) {\n result.push((bits >> 10) & 0xFF);\n result.push((bits >> 2) & 0xFF);\n } else if (tailbits === 12) {\n result.push((bits >> 4) & 0xFF);\n }\n\n return new Uint8Array(result);\n}\n\nfunction representYamlBinary(object /*, style*/) {\n var result = '', bits = 0, idx, tail,\n max = object.length,\n map = BASE64_MAP;\n\n // Convert every three bytes to 4 ASCII characters.\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 3 === 0) && idx) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n }\n\n bits = (bits << 8) + object[idx];\n }\n\n // Dump tail\n\n tail = max % 3;\n\n if (tail === 0) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n } else if (tail === 2) {\n result += map[(bits >> 10) & 0x3F];\n result += map[(bits >> 4) & 0x3F];\n result += map[(bits << 2) & 0x3F];\n result += map[64];\n } else if (tail === 1) {\n result += map[(bits >> 2) & 0x3F];\n result += map[(bits << 4) & 0x3F];\n result += map[64];\n result += map[64];\n }\n\n return result;\n}\n\nfunction isBinary(obj) {\n return Object.prototype.toString.call(obj) === '[object Uint8Array]';\n}\n\nvar binary = new type('tag:yaml.org,2002:binary', {\n kind: 'scalar',\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n});\n\nvar _hasOwnProperty$3 = Object.prototype.hasOwnProperty;\nvar _toString$2 = Object.prototype.toString;\n\nfunction resolveYamlOmap(data) {\n if (data === null) return true;\n\n var objectKeys = [], index, length, pair, pairKey, pairHasKey,\n object = data;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n pairHasKey = false;\n\n if (_toString$2.call(pair) !== '[object Object]') return false;\n\n for (pairKey in pair) {\n if (_hasOwnProperty$3.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true;\n else return false;\n }\n }\n\n if (!pairHasKey) return false;\n\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n else return false;\n }\n\n return true;\n}\n\nfunction constructYamlOmap(data) {\n return data !== null ? data : [];\n}\n\nvar omap = new type('tag:yaml.org,2002:omap', {\n kind: 'sequence',\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n});\n\nvar _toString$1 = Object.prototype.toString;\n\nfunction resolveYamlPairs(data) {\n if (data === null) return true;\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n if (_toString$1.call(pair) !== '[object Object]') return false;\n\n keys = Object.keys(pair);\n\n if (keys.length !== 1) return false;\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return true;\n}\n\nfunction constructYamlPairs(data) {\n if (data === null) return [];\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n keys = Object.keys(pair);\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return result;\n}\n\nvar pairs = new type('tag:yaml.org,2002:pairs', {\n kind: 'sequence',\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n});\n\nvar _hasOwnProperty$2 = Object.prototype.hasOwnProperty;\n\nfunction resolveYamlSet(data) {\n if (data === null) return true;\n\n var key, object = data;\n\n for (key in object) {\n if (_hasOwnProperty$2.call(object, key)) {\n if (object[key] !== null) return false;\n }\n }\n\n return true;\n}\n\nfunction constructYamlSet(data) {\n return data !== null ? data : {};\n}\n\nvar set = new type('tag:yaml.org,2002:set', {\n kind: 'mapping',\n resolve: resolveYamlSet,\n construct: constructYamlSet\n});\n\nvar _default = core.extend({\n implicit: [\n timestamp,\n merge\n ],\n explicit: [\n binary,\n omap,\n pairs,\n set\n ]\n});\n\n/*eslint-disable max-len,no-use-before-define*/\n\n\n\n\n\n\n\nvar _hasOwnProperty$1 = Object.prototype.hasOwnProperty;\n\n\nvar CONTEXT_FLOW_IN = 1;\nvar CONTEXT_FLOW_OUT = 2;\nvar CONTEXT_BLOCK_IN = 3;\nvar CONTEXT_BLOCK_OUT = 4;\n\n\nvar CHOMPING_CLIP = 1;\nvar CHOMPING_STRIP = 2;\nvar CHOMPING_KEEP = 3;\n\n\nvar PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\nvar PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\nvar PATTERN_FLOW_INDICATORS = /[,\\[\\]\\{\\}]/;\nvar PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\\-]+!)$/i;\nvar PATTERN_TAG_URI = /^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*'\\(\\)\\[\\]])*$/i;\n\n\nfunction _class(obj) { return Object.prototype.toString.call(obj); }\n\nfunction is_EOL(c) {\n return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);\n}\n\nfunction is_WHITE_SPACE(c) {\n return (c === 0x09/* Tab */) || (c === 0x20/* Space */);\n}\n\nfunction is_WS_OR_EOL(c) {\n return (c === 0x09/* Tab */) ||\n (c === 0x20/* Space */) ||\n (c === 0x0A/* LF */) ||\n (c === 0x0D/* CR */);\n}\n\nfunction is_FLOW_INDICATOR(c) {\n return c === 0x2C/* , */ ||\n c === 0x5B/* [ */ ||\n c === 0x5D/* ] */ ||\n c === 0x7B/* { */ ||\n c === 0x7D/* } */;\n}\n\nfunction fromHexCode(c) {\n var lc;\n\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n /*eslint-disable no-bitwise*/\n lc = c | 0x20;\n\n if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {\n return lc - 0x61 + 10;\n }\n\n return -1;\n}\n\nfunction escapedHexLen(c) {\n if (c === 0x78/* x */) { return 2; }\n if (c === 0x75/* u */) { return 4; }\n if (c === 0x55/* U */) { return 8; }\n return 0;\n}\n\nfunction fromDecimalCode(c) {\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n return -1;\n}\n\nfunction simpleEscapeSequence(c) {\n /* eslint-disable indent */\n return (c === 0x30/* 0 */) ? '\\x00' :\n (c === 0x61/* a */) ? '\\x07' :\n (c === 0x62/* b */) ? '\\x08' :\n (c === 0x74/* t */) ? '\\x09' :\n (c === 0x09/* Tab */) ? '\\x09' :\n (c === 0x6E/* n */) ? '\\x0A' :\n (c === 0x76/* v */) ? '\\x0B' :\n (c === 0x66/* f */) ? '\\x0C' :\n (c === 0x72/* r */) ? '\\x0D' :\n (c === 0x65/* e */) ? '\\x1B' :\n (c === 0x20/* Space */) ? ' ' :\n (c === 0x22/* \" */) ? '\\x22' :\n (c === 0x2F/* / */) ? '/' :\n (c === 0x5C/* \\ */) ? '\\x5C' :\n (c === 0x4E/* N */) ? '\\x85' :\n (c === 0x5F/* _ */) ? '\\xA0' :\n (c === 0x4C/* L */) ? '\\u2028' :\n (c === 0x50/* P */) ? '\\u2029' : '';\n}\n\nfunction charFromCodepoint(c) {\n if (c <= 0xFFFF) {\n return String.fromCharCode(c);\n }\n // Encode UTF-16 surrogate pair\n // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n return String.fromCharCode(\n ((c - 0x010000) >> 10) + 0xD800,\n ((c - 0x010000) & 0x03FF) + 0xDC00\n );\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty(object, key, value) {\n // used for this specific key only because Object.defineProperty is slow\n if (key === '__proto__') {\n Object.defineProperty(object, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: value\n });\n } else {\n object[key] = value;\n }\n}\n\nvar simpleEscapeCheck = new Array(256); // integer, for fast access\nvar simpleEscapeMap = new Array(256);\nfor (var i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n simpleEscapeMap[i] = simpleEscapeSequence(i);\n}\n\n\nfunction State$1(input, options) {\n this.input = input;\n\n this.filename = options['filename'] || null;\n this.schema = options['schema'] || _default;\n this.onWarning = options['onWarning'] || null;\n // (Hidden) Remove? makes the loader to expect YAML 1.1 documents\n // if such documents have no explicit %YAML directive\n this.legacy = options['legacy'] || false;\n\n this.json = options['json'] || false;\n this.listener = options['listener'] || null;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.typeMap = this.schema.compiledTypeMap;\n\n this.length = input.length;\n this.position = 0;\n this.line = 0;\n this.lineStart = 0;\n this.lineIndent = 0;\n\n // position of first leading tab in the current line,\n // used to make sure there are no tabs in the indentation\n this.firstTabInLine = -1;\n\n this.documents = [];\n\n /*\n this.version;\n this.checkLineBreaks;\n this.tagMap;\n this.anchorMap;\n this.tag;\n this.anchor;\n this.kind;\n this.result;*/\n\n}\n\n\nfunction generateError(state, message) {\n var mark = {\n name: state.filename,\n buffer: state.input.slice(0, -1), // omit trailing \\0\n position: state.position,\n line: state.line,\n column: state.position - state.lineStart\n };\n\n mark.snippet = snippet(mark);\n\n return new exception(message, mark);\n}\n\nfunction throwError(state, message) {\n throw generateError(state, message);\n}\n\nfunction throwWarning(state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message));\n }\n}\n\n\nvar directiveHandlers = {\n\n YAML: function handleYamlDirective(state, name, args) {\n\n var match, major, minor;\n\n if (state.version !== null) {\n throwError(state, 'duplication of %YAML directive');\n }\n\n if (args.length !== 1) {\n throwError(state, 'YAML directive accepts exactly one argument');\n }\n\n match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n\n if (match === null) {\n throwError(state, 'ill-formed argument of the YAML directive');\n }\n\n major = parseInt(match[1], 10);\n minor = parseInt(match[2], 10);\n\n if (major !== 1) {\n throwError(state, 'unacceptable YAML version of the document');\n }\n\n state.version = args[0];\n state.checkLineBreaks = (minor < 2);\n\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, 'unsupported YAML version of the document');\n }\n },\n\n TAG: function handleTagDirective(state, name, args) {\n\n var handle, prefix;\n\n if (args.length !== 2) {\n throwError(state, 'TAG directive accepts exactly two arguments');\n }\n\n handle = args[0];\n prefix = args[1];\n\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');\n }\n\n if (_hasOwnProperty$1.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle');\n }\n\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');\n }\n\n try {\n prefix = decodeURIComponent(prefix);\n } catch (err) {\n throwError(state, 'tag prefix is malformed: ' + prefix);\n }\n\n state.tagMap[handle] = prefix;\n }\n};\n\n\nfunction captureSegment(state, start, end, checkJson) {\n var _position, _length, _character, _result;\n\n if (start < end) {\n _result = state.input.slice(start, end);\n\n if (checkJson) {\n for (_position = 0, _length = _result.length; _position < _length; _position += 1) {\n _character = _result.charCodeAt(_position);\n if (!(_character === 0x09 ||\n (0x20 <= _character && _character <= 0x10FFFF))) {\n throwError(state, 'expected valid JSON character');\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, 'the stream contains non-printable characters');\n }\n\n state.result += _result;\n }\n}\n\nfunction mergeMappings(state, destination, source, overridableKeys) {\n var sourceKeys, key, index, quantity;\n\n if (!common.isObject(source)) {\n throwError(state, 'cannot merge mappings; the provided source object is unacceptable');\n }\n\n sourceKeys = Object.keys(source);\n\n for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n key = sourceKeys[index];\n\n if (!_hasOwnProperty$1.call(destination, key)) {\n setProperty(destination, key, source[key]);\n overridableKeys[key] = true;\n }\n }\n}\n\nfunction storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,\n startLine, startLineStart, startPos) {\n\n var index, quantity;\n\n // The output is a plain object here, so keys can only be strings.\n // We need to convert keyNode to a string, but doing so can hang the process\n // (deeply nested arrays that explode exponentially using aliases).\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode);\n\n for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, 'nested arrays are not supported inside keys');\n }\n\n if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n keyNode[index] = '[object Object]';\n }\n }\n }\n\n // Avoid code execution in load() via toString property\n // (still use its own toString for arrays, timestamps,\n // and whatever user schema extensions happen to have @@toStringTag)\n if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n keyNode = '[object Object]';\n }\n\n\n keyNode = String(keyNode);\n\n if (_result === null) {\n _result = {};\n }\n\n if (keyTag === 'tag:yaml.org,2002:merge') {\n if (Array.isArray(valueNode)) {\n for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n mergeMappings(state, _result, valueNode[index], overridableKeys);\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys);\n }\n } else {\n if (!state.json &&\n !_hasOwnProperty$1.call(overridableKeys, keyNode) &&\n _hasOwnProperty$1.call(_result, keyNode)) {\n state.line = startLine || state.line;\n state.lineStart = startLineStart || state.lineStart;\n state.position = startPos || state.position;\n throwError(state, 'duplicated mapping key');\n }\n\n setProperty(_result, keyNode, valueNode);\n delete overridableKeys[keyNode];\n }\n\n return _result;\n}\n\nfunction readLineBreak(state) {\n var ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x0A/* LF */) {\n state.position++;\n } else if (ch === 0x0D/* CR */) {\n state.position++;\n if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n state.position++;\n }\n } else {\n throwError(state, 'a line break is expected');\n }\n\n state.line += 1;\n state.lineStart = state.position;\n state.firstTabInLine = -1;\n}\n\nfunction skipSeparationSpace(state, allowComments, checkIndent) {\n var lineBreaks = 0,\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {\n state.firstTabInLine = state.position;\n }\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (allowComments && ch === 0x23/* # */) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);\n }\n\n if (is_EOL(ch)) {\n readLineBreak(state);\n\n ch = state.input.charCodeAt(state.position);\n lineBreaks++;\n state.lineIndent = 0;\n\n while (ch === 0x20/* Space */) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n } else {\n break;\n }\n }\n\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, 'deficient indentation');\n }\n\n return lineBreaks;\n}\n\nfunction testDocumentSeparator(state) {\n var _position = state.position,\n ch;\n\n ch = state.input.charCodeAt(_position);\n\n // Condition state.position === state.lineStart is tested\n // in parent on each call, for efficiency. No needs to test here again.\n if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n ch === state.input.charCodeAt(_position + 1) &&\n ch === state.input.charCodeAt(_position + 2)) {\n\n _position += 3;\n\n ch = state.input.charCodeAt(_position);\n\n if (ch === 0 || is_WS_OR_EOL(ch)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction writeFoldedLines(state, count) {\n if (count === 1) {\n state.result += ' ';\n } else if (count > 1) {\n state.result += common.repeat('\\n', count - 1);\n }\n}\n\n\nfunction readPlainScalar(state, nodeIndent, withinFlowCollection) {\n var preceding,\n following,\n captureStart,\n captureEnd,\n hasPendingContent,\n _line,\n _lineStart,\n _lineIndent,\n _kind = state.kind,\n _result = state.result,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (is_WS_OR_EOL(ch) ||\n is_FLOW_INDICATOR(ch) ||\n ch === 0x23/* # */ ||\n ch === 0x26/* & */ ||\n ch === 0x2A/* * */ ||\n ch === 0x21/* ! */ ||\n ch === 0x7C/* | */ ||\n ch === 0x3E/* > */ ||\n ch === 0x27/* ' */ ||\n ch === 0x22/* \" */ ||\n ch === 0x25/* % */ ||\n ch === 0x40/* @ */ ||\n ch === 0x60/* ` */) {\n return false;\n }\n\n if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n return false;\n }\n }\n\n state.kind = 'scalar';\n state.result = '';\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n\n while (ch !== 0) {\n if (ch === 0x3A/* : */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n break;\n }\n\n } else if (ch === 0x23/* # */) {\n preceding = state.input.charCodeAt(state.position - 1);\n\n if (is_WS_OR_EOL(preceding)) {\n break;\n }\n\n } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n withinFlowCollection && is_FLOW_INDICATOR(ch)) {\n break;\n\n } else if (is_EOL(ch)) {\n _line = state.line;\n _lineStart = state.lineStart;\n _lineIndent = state.lineIndent;\n skipSeparationSpace(state, false, -1);\n\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true;\n ch = state.input.charCodeAt(state.position);\n continue;\n } else {\n state.position = captureEnd;\n state.line = _line;\n state.lineStart = _lineStart;\n state.lineIndent = _lineIndent;\n break;\n }\n }\n\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false);\n writeFoldedLines(state, state.line - _line);\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n }\n\n if (!is_WHITE_SPACE(ch)) {\n captureEnd = state.position + 1;\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, captureEnd, false);\n\n if (state.result) {\n return true;\n }\n\n state.kind = _kind;\n state.result = _result;\n return false;\n}\n\nfunction readSingleQuotedScalar(state, nodeIndent) {\n var ch,\n captureStart, captureEnd;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x27/* ' */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x27/* ' */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x27/* ' */) {\n captureStart = state.position;\n state.position++;\n captureEnd = state.position;\n } else {\n return true;\n }\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a single quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a single quoted scalar');\n}\n\nfunction readDoubleQuotedScalar(state, nodeIndent) {\n var captureStart,\n captureEnd,\n hexLength,\n hexResult,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x22/* \" */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x22/* \" */) {\n captureSegment(state, captureStart, state.position, true);\n state.position++;\n return true;\n\n } else if (ch === 0x5C/* \\ */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (is_EOL(ch)) {\n skipSeparationSpace(state, false, nodeIndent);\n\n // TODO: rework to inline fn with no type cast?\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch];\n state.position++;\n\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n hexLength = tmp;\n hexResult = 0;\n\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position);\n\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp;\n\n } else {\n throwError(state, 'expected hexadecimal character');\n }\n }\n\n state.result += charFromCodepoint(hexResult);\n\n state.position++;\n\n } else {\n throwError(state, 'unknown escape sequence');\n }\n\n captureStart = captureEnd = state.position;\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a double quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a double quoted scalar');\n}\n\nfunction readFlowCollection(state, nodeIndent) {\n var readNext = true,\n _line,\n _lineStart,\n _pos,\n _tag = state.tag,\n _result,\n _anchor = state.anchor,\n following,\n terminator,\n isPair,\n isExplicitPair,\n isMapping,\n overridableKeys = Object.create(null),\n keyNode,\n keyTag,\n valueNode,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x5B/* [ */) {\n terminator = 0x5D;/* ] */\n isMapping = false;\n _result = [];\n } else if (ch === 0x7B/* { */) {\n terminator = 0x7D;/* } */\n isMapping = true;\n _result = {};\n } else {\n return false;\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === terminator) {\n state.position++;\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = isMapping ? 'mapping' : 'sequence';\n state.result = _result;\n return true;\n } else if (!readNext) {\n throwError(state, 'missed comma between flow collection entries');\n } else if (ch === 0x2C/* , */) {\n // \"flow collection entries can never be completely empty\", as per YAML 1.2, section 7.4\n throwError(state, \"expected the node content, but found ','\");\n }\n\n keyTag = keyNode = valueNode = null;\n isPair = isExplicitPair = false;\n\n if (ch === 0x3F/* ? */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following)) {\n isPair = isExplicitPair = true;\n state.position++;\n skipSeparationSpace(state, true, nodeIndent);\n }\n }\n\n _line = state.line; // Save the current line.\n _lineStart = state.lineStart;\n _pos = state.position;\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n keyTag = state.tag;\n keyNode = state.result;\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n isPair = true;\n ch = state.input.charCodeAt(++state.position);\n skipSeparationSpace(state, true, nodeIndent);\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n valueNode = state.result;\n }\n\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));\n } else {\n _result.push(keyNode);\n }\n\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x2C/* , */) {\n readNext = true;\n ch = state.input.charCodeAt(++state.position);\n } else {\n readNext = false;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a flow collection');\n}\n\nfunction readBlockScalar(state, nodeIndent) {\n var captureStart,\n folding,\n chomping = CHOMPING_CLIP,\n didReadContent = false,\n detectedIndent = false,\n textIndent = nodeIndent,\n emptyLines = 0,\n atMoreIndented = false,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x7C/* | */) {\n folding = false;\n } else if (ch === 0x3E/* > */) {\n folding = true;\n } else {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n if (CHOMPING_CLIP === chomping) {\n chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;\n } else {\n throwError(state, 'repeat of a chomping mode identifier');\n }\n\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1;\n detectedIndent = true;\n } else {\n throwError(state, 'repeat of an indentation width identifier');\n }\n\n } else {\n break;\n }\n }\n\n if (is_WHITE_SPACE(ch)) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (is_WHITE_SPACE(ch));\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (!is_EOL(ch) && (ch !== 0));\n }\n }\n\n while (ch !== 0) {\n readLineBreak(state);\n state.lineIndent = 0;\n\n ch = state.input.charCodeAt(state.position);\n\n while ((!detectedIndent || state.lineIndent < textIndent) &&\n (ch === 0x20/* Space */)) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent;\n }\n\n if (is_EOL(ch)) {\n emptyLines++;\n continue;\n }\n\n // End of the scalar.\n if (state.lineIndent < textIndent) {\n\n // Perform the chomping.\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) { // i.e. only if the scalar is not empty.\n state.result += '\\n';\n }\n }\n\n // Break this `while` cycle and go to the funciton's epilogue.\n break;\n }\n\n // Folded style: use fancy rules to handle line breaks.\n if (folding) {\n\n // Lines starting with white space characters (more-indented lines) are not folded.\n if (is_WHITE_SPACE(ch)) {\n atMoreIndented = true;\n // except for the first content line (cf. Example 8.1)\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n\n // End of more-indented block.\n } else if (atMoreIndented) {\n atMoreIndented = false;\n state.result += common.repeat('\\n', emptyLines + 1);\n\n // Just one line break - perceive as the same line.\n } else if (emptyLines === 0) {\n if (didReadContent) { // i.e. only if we have already read some scalar content.\n state.result += ' ';\n }\n\n // Several line breaks - perceive as different lines.\n } else {\n state.result += common.repeat('\\n', emptyLines);\n }\n\n // Literal style: just add exact number of line breaks between content lines.\n } else {\n // Keep all line breaks except the header line break.\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n }\n\n didReadContent = true;\n detectedIndent = true;\n emptyLines = 0;\n captureStart = state.position;\n\n while (!is_EOL(ch) && (ch !== 0)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, state.position, false);\n }\n\n return true;\n}\n\nfunction readBlockSequence(state, nodeIndent) {\n var _line,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = [],\n following,\n detected = false,\n ch;\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n if (state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine;\n throwError(state, 'tab characters must not be used in indentation');\n }\n\n if (ch !== 0x2D/* - */) {\n break;\n }\n\n following = state.input.charCodeAt(state.position + 1);\n\n if (!is_WS_OR_EOL(following)) {\n break;\n }\n\n detected = true;\n state.position++;\n\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null);\n ch = state.input.charCodeAt(state.position);\n continue;\n }\n }\n\n _line = state.line;\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n _result.push(state.result);\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a sequence entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'sequence';\n state.result = _result;\n return true;\n }\n return false;\n}\n\nfunction readBlockMapping(state, nodeIndent, flowIndent) {\n var following,\n allowCompact,\n _line,\n _keyLine,\n _keyLineStart,\n _keyPos,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = {},\n overridableKeys = Object.create(null),\n keyTag = null,\n keyNode = null,\n valueNode = null,\n atExplicitKey = false,\n detected = false,\n ch;\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n if (!atExplicitKey && state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine;\n throwError(state, 'tab characters must not be used in indentation');\n }\n\n following = state.input.charCodeAt(state.position + 1);\n _line = state.line; // Save the current line.\n\n //\n // Explicit notation case. There are two separate blocks:\n // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n //\n if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {\n\n if (ch === 0x3F/* ? */) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = true;\n allowCompact = true;\n\n } else if (atExplicitKey) {\n // i.e. 0x3A/* : */ === character after the explicit key.\n atExplicitKey = false;\n allowCompact = true;\n\n } else {\n throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');\n }\n\n state.position += 1;\n ch = following;\n\n //\n // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n //\n } else {\n _keyLine = state.line;\n _keyLineStart = state.lineStart;\n _keyPos = state.position;\n\n if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n // Neither implicit nor explicit notation.\n // Reading is done. Go to the epilogue.\n break;\n }\n\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position);\n\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x3A/* : */) {\n ch = state.input.charCodeAt(++state.position);\n\n if (!is_WS_OR_EOL(ch)) {\n throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');\n }\n\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = false;\n allowCompact = false;\n keyTag = state.tag;\n keyNode = state.result;\n\n } else if (detected) {\n throwError(state, 'can not read an implicit mapping pair; a colon is missed');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n\n } else if (detected) {\n throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n }\n\n //\n // Common reading code for both explicit and implicit notations.\n //\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (atExplicitKey) {\n _keyLine = state.line;\n _keyLineStart = state.lineStart;\n _keyPos = state.position;\n }\n\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result;\n } else {\n valueNode = state.result;\n }\n }\n\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n\n skipSeparationSpace(state, true, -1);\n ch = state.input.charCodeAt(state.position);\n }\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a mapping entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n //\n // Epilogue.\n //\n\n // Special case: last mapping's node contains only the key in explicit notation.\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n }\n\n // Expose the resulting mapping.\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'mapping';\n state.result = _result;\n }\n\n return detected;\n}\n\nfunction readTagProperty(state) {\n var _position,\n isVerbatim = false,\n isNamed = false,\n tagHandle,\n tagName,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x21/* ! */) return false;\n\n if (state.tag !== null) {\n throwError(state, 'duplication of a tag property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x3C/* < */) {\n isVerbatim = true;\n ch = state.input.charCodeAt(++state.position);\n\n } else if (ch === 0x21/* ! */) {\n isNamed = true;\n tagHandle = '!!';\n ch = state.input.charCodeAt(++state.position);\n\n } else {\n tagHandle = '!';\n }\n\n _position = state.position;\n\n if (isVerbatim) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && ch !== 0x3E/* > */);\n\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position);\n ch = state.input.charCodeAt(++state.position);\n } else {\n throwError(state, 'unexpected end of the stream within a verbatim tag');\n }\n } else {\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n\n if (ch === 0x21/* ! */) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1);\n\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, 'named tag handle cannot contain such characters');\n }\n\n isNamed = true;\n _position = state.position + 1;\n } else {\n throwError(state, 'tag suffix cannot contain exclamation marks');\n }\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n tagName = state.input.slice(_position, state.position);\n\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, 'tag suffix cannot contain flow indicator characters');\n }\n }\n\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, 'tag name cannot contain such characters: ' + tagName);\n }\n\n try {\n tagName = decodeURIComponent(tagName);\n } catch (err) {\n throwError(state, 'tag name is malformed: ' + tagName);\n }\n\n if (isVerbatim) {\n state.tag = tagName;\n\n } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName;\n\n } else if (tagHandle === '!') {\n state.tag = '!' + tagName;\n\n } else if (tagHandle === '!!') {\n state.tag = 'tag:yaml.org,2002:' + tagName;\n\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"');\n }\n\n return true;\n}\n\nfunction readAnchorProperty(state) {\n var _position,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x26/* & */) return false;\n\n if (state.anchor !== null) {\n throwError(state, 'duplication of an anchor property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an anchor node must contain at least one character');\n }\n\n state.anchor = state.input.slice(_position, state.position);\n return true;\n}\n\nfunction readAlias(state) {\n var _position, alias,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x2A/* * */) return false;\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an alias node must contain at least one character');\n }\n\n alias = state.input.slice(_position, state.position);\n\n if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"');\n }\n\n state.result = state.anchorMap[alias];\n skipSeparationSpace(state, true, -1);\n return true;\n}\n\nfunction composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n var allowBlockStyles,\n allowBlockScalars,\n allowBlockCollections,\n indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent\n atNewLine = false,\n hasContent = false,\n typeIndex,\n typeQuantity,\n typeList,\n type,\n flowIndent,\n blockIndent;\n\n if (state.listener !== null) {\n state.listener('open', state);\n }\n\n state.tag = null;\n state.anchor = null;\n state.kind = null;\n state.result = null;\n\n allowBlockStyles = allowBlockScalars = allowBlockCollections =\n CONTEXT_BLOCK_OUT === nodeContext ||\n CONTEXT_BLOCK_IN === nodeContext;\n\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n }\n }\n\n if (indentStatus === 1) {\n while (readTagProperty(state) || readAnchorProperty(state)) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n allowBlockCollections = allowBlockStyles;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n } else {\n allowBlockCollections = false;\n }\n }\n }\n\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact;\n }\n\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent;\n } else {\n flowIndent = parentIndent + 1;\n }\n\n blockIndent = state.position - state.lineStart;\n\n if (indentStatus === 1) {\n if (allowBlockCollections &&\n (readBlockSequence(state, blockIndent) ||\n readBlockMapping(state, blockIndent, flowIndent)) ||\n readFlowCollection(state, flowIndent)) {\n hasContent = true;\n } else {\n if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n readSingleQuotedScalar(state, flowIndent) ||\n readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true;\n\n } else if (readAlias(state)) {\n hasContent = true;\n\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, 'alias node should not have any properties');\n }\n\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true;\n\n if (state.tag === null) {\n state.tag = '?';\n }\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n } else if (indentStatus === 0) {\n // Special case: block sequences are allowed to have same indentation level as the parent.\n // http://www.yaml.org/spec/1.2/spec.html#id2799784\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n }\n }\n\n if (state.tag === null) {\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n\n } else if (state.tag === '?') {\n // Implicit resolving is not allowed for non-scalar types, and '?'\n // non-specific tag is only automatically assigned to plain scalars.\n //\n // We only need to check kind conformity in case user explicitly assigns '?'\n // tag, for example like this: \"!<?> [0]\"\n //\n if (state.result !== null && state.kind !== 'scalar') {\n throwError(state, 'unacceptable node kind for !<?> tag; it should be \"scalar\", not \"' + state.kind + '\"');\n }\n\n for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type = state.implicitTypes[typeIndex];\n\n if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n state.result = type.construct(state.result);\n state.tag = type.tag;\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n break;\n }\n }\n } else if (state.tag !== '!') {\n if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n type = state.typeMap[state.kind || 'fallback'][state.tag];\n } else {\n // looking for multi type\n type = null;\n typeList = state.typeMap.multi[state.kind || 'fallback'];\n\n for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {\n if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n type = typeList[typeIndex];\n break;\n }\n }\n }\n\n if (!type) {\n throwError(state, 'unknown tag !<' + state.tag + '>');\n }\n\n if (state.result !== null && type.kind !== state.kind) {\n throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"');\n }\n\n if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched\n throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');\n } else {\n state.result = type.construct(state.result, state.tag);\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n }\n\n if (state.listener !== null) {\n state.listener('close', state);\n }\n return state.tag !== null || state.anchor !== null || hasContent;\n}\n\nfunction readDocument(state) {\n var documentStart = state.position,\n _position,\n directiveName,\n directiveArgs,\n hasDirectives = false,\n ch;\n\n state.version = null;\n state.checkLineBreaks = state.legacy;\n state.tagMap = Object.create(null);\n state.anchorMap = Object.create(null);\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n break;\n }\n\n hasDirectives = true;\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveName = state.input.slice(_position, state.position);\n directiveArgs = [];\n\n if (directiveName.length < 1) {\n throwError(state, 'directive name must not be less than one character in length');\n }\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && !is_EOL(ch));\n break;\n }\n\n if (is_EOL(ch)) break;\n\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveArgs.push(state.input.slice(_position, state.position));\n }\n\n if (ch !== 0) readLineBreak(state);\n\n if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs);\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"');\n }\n }\n\n skipSeparationSpace(state, true, -1);\n\n if (state.lineIndent === 0 &&\n state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n\n } else if (hasDirectives) {\n throwError(state, 'directives end mark is expected');\n }\n\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n skipSeparationSpace(state, true, -1);\n\n if (state.checkLineBreaks &&\n PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, 'non-ASCII line breaks are interpreted as content');\n }\n\n state.documents.push(state.result);\n\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n\n if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n }\n return;\n }\n\n if (state.position < (state.length - 1)) {\n throwError(state, 'end of the stream or a document separator is expected');\n } else {\n return;\n }\n}\n\n\nfunction loadDocuments(input, options) {\n input = String(input);\n options = options || {};\n\n if (input.length !== 0) {\n\n // Add tailing `\\n` if not exists\n if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n input += '\\n';\n }\n\n // Strip BOM\n if (input.charCodeAt(0) === 0xFEFF) {\n input = input.slice(1);\n }\n }\n\n var state = new State$1(input, options);\n\n var nullpos = input.indexOf('\\0');\n\n if (nullpos !== -1) {\n state.position = nullpos;\n throwError(state, 'null byte is not allowed in input');\n }\n\n // Use 0 as string terminator. That significantly simplifies bounds check.\n state.input += '\\0';\n\n while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n state.lineIndent += 1;\n state.position += 1;\n }\n\n while (state.position < (state.length - 1)) {\n readDocument(state);\n }\n\n return state.documents;\n}\n\n\nfunction loadAll$1(input, iterator, options) {\n if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n options = iterator;\n iterator = null;\n }\n\n var documents = loadDocuments(input, options);\n\n if (typeof iterator !== 'function') {\n return documents;\n }\n\n for (var index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index]);\n }\n}\n\n\nfunction load$1(input, options) {\n var documents = loadDocuments(input, options);\n\n if (documents.length === 0) {\n /*eslint-disable no-undefined*/\n return undefined;\n } else if (documents.length === 1) {\n return documents[0];\n }\n throw new exception('expected a single document in the stream, but found more');\n}\n\n\nvar loadAll_1 = loadAll$1;\nvar load_1 = load$1;\n\nvar loader = {\n\tloadAll: loadAll_1,\n\tload: load_1\n};\n\n/*eslint-disable no-use-before-define*/\n\n\n\n\n\nvar _toString = Object.prototype.toString;\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar CHAR_BOM = 0xFEFF;\nvar CHAR_TAB = 0x09; /* Tab */\nvar CHAR_LINE_FEED = 0x0A; /* LF */\nvar CHAR_CARRIAGE_RETURN = 0x0D; /* CR */\nvar CHAR_SPACE = 0x20; /* Space */\nvar CHAR_EXCLAMATION = 0x21; /* ! */\nvar CHAR_DOUBLE_QUOTE = 0x22; /* \" */\nvar CHAR_SHARP = 0x23; /* # */\nvar CHAR_PERCENT = 0x25; /* % */\nvar CHAR_AMPERSAND = 0x26; /* & */\nvar CHAR_SINGLE_QUOTE = 0x27; /* ' */\nvar CHAR_ASTERISK = 0x2A; /* * */\nvar CHAR_COMMA = 0x2C; /* , */\nvar CHAR_MINUS = 0x2D; /* - */\nvar CHAR_COLON = 0x3A; /* : */\nvar CHAR_EQUALS = 0x3D; /* = */\nvar CHAR_GREATER_THAN = 0x3E; /* > */\nvar CHAR_QUESTION = 0x3F; /* ? */\nvar CHAR_COMMERCIAL_AT = 0x40; /* @ */\nvar CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */\nvar CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */\nvar CHAR_GRAVE_ACCENT = 0x60; /* ` */\nvar CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */\nvar CHAR_VERTICAL_LINE = 0x7C; /* | */\nvar CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */\n\nvar ESCAPE_SEQUENCES = {};\n\nESCAPE_SEQUENCES[0x00] = '\\\\0';\nESCAPE_SEQUENCES[0x07] = '\\\\a';\nESCAPE_SEQUENCES[0x08] = '\\\\b';\nESCAPE_SEQUENCES[0x09] = '\\\\t';\nESCAPE_SEQUENCES[0x0A] = '\\\\n';\nESCAPE_SEQUENCES[0x0B] = '\\\\v';\nESCAPE_SEQUENCES[0x0C] = '\\\\f';\nESCAPE_SEQUENCES[0x0D] = '\\\\r';\nESCAPE_SEQUENCES[0x1B] = '\\\\e';\nESCAPE_SEQUENCES[0x22] = '\\\\\"';\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\';\nESCAPE_SEQUENCES[0x85] = '\\\\N';\nESCAPE_SEQUENCES[0xA0] = '\\\\_';\nESCAPE_SEQUENCES[0x2028] = '\\\\L';\nESCAPE_SEQUENCES[0x2029] = '\\\\P';\n\nvar DEPRECATED_BOOLEANS_SYNTAX = [\n 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n];\n\nvar DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/;\n\nfunction compileStyleMap(schema, map) {\n var result, keys, index, length, tag, style, type;\n\n if (map === null) return {};\n\n result = {};\n keys = Object.keys(map);\n\n for (index = 0, length = keys.length; index < length; index += 1) {\n tag = keys[index];\n style = String(map[tag]);\n\n if (tag.slice(0, 2) === '!!') {\n tag = 'tag:yaml.org,2002:' + tag.slice(2);\n }\n type = schema.compiledTypeMap['fallback'][tag];\n\n if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n style = type.styleAliases[style];\n }\n\n result[tag] = style;\n }\n\n return result;\n}\n\nfunction encodeHex(character) {\n var string, handle, length;\n\n string = character.toString(16).toUpperCase();\n\n if (character <= 0xFF) {\n handle = 'x';\n length = 2;\n } else if (character <= 0xFFFF) {\n handle = 'u';\n length = 4;\n } else if (character <= 0xFFFFFFFF) {\n handle = 'U';\n length = 8;\n } else {\n throw new exception('code point within a string may not be greater than 0xFFFFFFFF');\n }\n\n return '\\\\' + handle + common.repeat('0', length - string.length) + string;\n}\n\n\nvar QUOTING_TYPE_SINGLE = 1,\n QUOTING_TYPE_DOUBLE = 2;\n\nfunction State(options) {\n this.schema = options['schema'] || _default;\n this.indent = Math.max(1, (options['indent'] || 2));\n this.noArrayIndent = options['noArrayIndent'] || false;\n this.skipInvalid = options['skipInvalid'] || false;\n this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);\n this.styleMap = compileStyleMap(this.schema, options['styles'] || null);\n this.sortKeys = options['sortKeys'] || false;\n this.lineWidth = options['lineWidth'] || 80;\n this.noRefs = options['noRefs'] || false;\n this.noCompatMode = options['noCompatMode'] || false;\n this.condenseFlow = options['condenseFlow'] || false;\n this.quotingType = options['quotingType'] === '\"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;\n this.forceQuotes = options['forceQuotes'] || false;\n this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.explicitTypes = this.schema.compiledExplicit;\n\n this.tag = null;\n this.result = '';\n\n this.duplicates = [];\n this.usedDuplicates = null;\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString(string, spaces) {\n var ind = common.repeat(' ', spaces),\n position = 0,\n next = -1,\n result = '',\n line,\n length = string.length;\n\n while (position < length) {\n next = string.indexOf('\\n', position);\n if (next === -1) {\n line = string.slice(position);\n position = length;\n } else {\n line = string.slice(position, next + 1);\n position = next + 1;\n }\n\n if (line.length && line !== '\\n') result += ind;\n\n result += line;\n }\n\n return result;\n}\n\nfunction generateNextLine(state, level) {\n return '\\n' + common.repeat(' ', state.indent * level);\n}\n\nfunction testImplicitResolving(state, str) {\n var index, length, type;\n\n for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n type = state.implicitTypes[index];\n\n if (type.resolve(str)) {\n return true;\n }\n }\n\n return false;\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace(c) {\n return c === CHAR_SPACE || c === CHAR_TAB;\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable(c) {\n return (0x00020 <= c && c <= 0x00007E)\n || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)\n || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)\n || (0x10000 <= c && c <= 0x10FFFF);\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char ::= b-line-feed | b-carriage-return\n// Including s-white (for some reason, examples doesn't match specs in this aspect)\n// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark\nfunction isNsCharOrWhitespace(c) {\n return isPrintable(c)\n && c !== CHAR_BOM\n // - b-char\n && c !== CHAR_CARRIAGE_RETURN\n && c !== CHAR_LINE_FEED;\n}\n\n// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out\n// c = flow-in ⇒ ns-plain-safe-in\n// c = block-key ⇒ ns-plain-safe-out\n// c = flow-key ⇒ ns-plain-safe-in\n// [128] ns-plain-safe-out ::= ns-char\n// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator\n// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )\n// | ( /* An ns-char preceding */ “#” )\n// | ( “:” /* Followed by an ns-plain-safe(c) */ )\nfunction isPlainSafe(c, prev, inblock) {\n var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);\n var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);\n return (\n // ns-plain-safe\n inblock ? // c = flow-in\n cIsNsCharOrWhitespace\n : cIsNsCharOrWhitespace\n // - c-flow-indicator\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n )\n // ns-plain-char\n && c !== CHAR_SHARP // false on '#'\n && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '\n || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'\n || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst(c) {\n // Uses a subset of ns-char - c-indicator\n // where ns-char = nb-char - s-white.\n // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part\n return isPrintable(c) && c !== CHAR_BOM\n && !isWhitespace(c) // - s-white\n // - (c-indicator ::=\n // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”\n && c !== CHAR_MINUS\n && c !== CHAR_QUESTION\n && c !== CHAR_COLON\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “\"”\n && c !== CHAR_SHARP\n && c !== CHAR_AMPERSAND\n && c !== CHAR_ASTERISK\n && c !== CHAR_EXCLAMATION\n && c !== CHAR_VERTICAL_LINE\n && c !== CHAR_EQUALS\n && c !== CHAR_GREATER_THAN\n && c !== CHAR_SINGLE_QUOTE\n && c !== CHAR_DOUBLE_QUOTE\n // | “%” | “@” | “`”)\n && c !== CHAR_PERCENT\n && c !== CHAR_COMMERCIAL_AT\n && c !== CHAR_GRAVE_ACCENT;\n}\n\n// Simplified test for values allowed as the last character in plain style.\nfunction isPlainSafeLast(c) {\n // just not whitespace or colon, it will be checked to be plain character later\n return !isWhitespace(c) && c !== CHAR_COLON;\n}\n\n// Same as 'string'.codePointAt(pos), but works in older browsers.\nfunction codePointAt(string, pos) {\n var first = string.charCodeAt(pos), second;\n if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {\n second = string.charCodeAt(pos + 1);\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n }\n }\n return first;\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator(string) {\n var leadingSpaceRe = /^\\n* /;\n return leadingSpaceRe.test(string);\n}\n\nvar STYLE_PLAIN = 1,\n STYLE_SINGLE = 2,\n STYLE_LITERAL = 3,\n STYLE_FOLDED = 4,\n STYLE_DOUBLE = 5;\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n// STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,\n testAmbiguousType, quotingType, forceQuotes, inblock) {\n\n var i;\n var char = 0;\n var prevChar = null;\n var hasLineBreak = false;\n var hasFoldableLine = false; // only checked if shouldTrackWidth\n var shouldTrackWidth = lineWidth !== -1;\n var previousLineBreak = -1; // count the first line correctly\n var plain = isPlainSafeFirst(codePointAt(string, 0))\n && isPlainSafeLast(codePointAt(string, string.length - 1));\n\n if (singleLineOnly || forceQuotes) {\n // Case: no block styles.\n // Check for disallowed characters to rule out plain and single.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i);\n if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n plain = plain && isPlainSafe(char, prevChar, inblock);\n prevChar = char;\n }\n } else {\n // Case: block styles permitted.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i);\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true;\n // Check if any line can be folded.\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine ||\n // Foldable line = too long, and not more-indented.\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' ');\n previousLineBreak = i;\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n plain = plain && isPlainSafe(char, prevChar, inblock);\n prevChar = char;\n }\n // in case the end is missing a \\n\n hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' '));\n }\n // Although every style can represent \\n without escaping, prefer block styles\n // for multiline, since they're more readable and they don't add empty lines.\n // Also prefer folding a super-long line.\n if (!hasLineBreak && !hasFoldableLine) {\n // Strings interpretable as another type have to be quoted;\n // e.g. the string 'true' vs. the boolean true.\n if (plain && !forceQuotes && !testAmbiguousType(string)) {\n return STYLE_PLAIN;\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n }\n // Edge case: block indentation indicator can only have one digit.\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE;\n }\n // At this point we know block styles are valid.\n // Prefer literal style unless we want to fold.\n if (!forceQuotes) {\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n// since the dumper adds its own newline. This always works:\n// • No ending newline => unaffected; already using strip \"-\" chomping.\n// • Ending newline => removed then restored.\n// Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar(state, string, level, iskey, inblock) {\n state.dump = (function () {\n if (string.length === 0) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? '\"\"' : \"''\";\n }\n if (!state.noCompatMode) {\n if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? ('\"' + string + '\"') : (\"'\" + string + \"'\");\n }\n }\n\n var indent = state.indent * Math.max(1, level); // no 0-indent scalars\n // As indentation gets deeper, let the width decrease monotonically\n // to the lower bound min(state.lineWidth, 40).\n // Note that this implies\n // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.\n // state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n // This behaves better than a constant minimum width which disallows narrower options,\n // or an indent threshold which causes the width to suddenly increase.\n var lineWidth = state.lineWidth === -1\n ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n\n // Without knowing if keys are implicit/explicit, assume implicit for safety.\n var singleLineOnly = iskey\n // No block styles in flow mode.\n || (state.flowLevel > -1 && level >= state.flowLevel);\n function testAmbiguity(string) {\n return testImplicitResolving(state, string);\n }\n\n switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,\n testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {\n\n case STYLE_PLAIN:\n return string;\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\";\n case STYLE_LITERAL:\n return '|' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(string, indent));\n case STYLE_FOLDED:\n return '>' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n case STYLE_DOUBLE:\n return '\"' + escapeString(string) + '\"';\n default:\n throw new exception('impossible error: invalid scalar style');\n }\n }());\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader(string, indentPerLevel) {\n var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';\n\n // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n var clip = string[string.length - 1] === '\\n';\n var keep = clip && (string[string.length - 2] === '\\n' || string === '\\n');\n var chomp = keep ? '+' : (clip ? '' : '-');\n\n return indentIndicator + chomp + '\\n';\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline(string) {\n return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string;\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString(string, width) {\n // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n // unless they're before or after a more-indented line, or at the very\n // beginning or end, in which case $k$ maps to $k$.\n // Therefore, parse each chunk as newline(s) followed by a content line.\n var lineRe = /(\\n+)([^\\n]*)/g;\n\n // first line (possibly an empty line)\n var result = (function () {\n var nextLF = string.indexOf('\\n');\n nextLF = nextLF !== -1 ? nextLF : string.length;\n lineRe.lastIndex = nextLF;\n return foldLine(string.slice(0, nextLF), width);\n }());\n // If we haven't reached the first content line yet, don't add an extra \\n.\n var prevMoreIndented = string[0] === '\\n' || string[0] === ' ';\n var moreIndented;\n\n // rest of the lines\n var match;\n while ((match = lineRe.exec(string))) {\n var prefix = match[1], line = match[2];\n moreIndented = (line[0] === ' ');\n result += prefix\n + (!prevMoreIndented && !moreIndented && line !== ''\n ? '\\n' : '')\n + foldLine(line, width);\n prevMoreIndented = moreIndented;\n }\n\n return result;\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine(line, width) {\n if (line === '' || line[0] === ' ') return line;\n\n // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.\n var match;\n // start is an inclusive index. end, curr, and next are exclusive.\n var start = 0, end, curr = 0, next = 0;\n var result = '';\n\n // Invariants: 0 <= start <= length-1.\n // 0 <= curr <= next <= max(0, length-2). curr - start <= width.\n // Inside the loop:\n // A match implies length >= 2, so curr and next are <= length-2.\n while ((match = breakRe.exec(line))) {\n next = match.index;\n // maintain invariant: curr - start <= width\n if (next - start > width) {\n end = (curr > start) ? curr : next; // derive end <= length-2\n result += '\\n' + line.slice(start, end);\n // skip the space that was output as \\n\n start = end + 1; // derive start <= length-1\n }\n curr = next;\n }\n\n // By the invariants, start <= length-1, so there is something left over.\n // It is either the whole string or a part starting from non-whitespace.\n result += '\\n';\n // Insert a break if the remainder is too long and there is a break available.\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + '\\n' + line.slice(curr + 1);\n } else {\n result += line.slice(start);\n }\n\n return result.slice(1); // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString(string) {\n var result = '';\n var char = 0;\n var escapeSeq;\n\n for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i);\n escapeSeq = ESCAPE_SEQUENCES[char];\n\n if (!escapeSeq && isPrintable(char)) {\n result += string[i];\n if (char >= 0x10000) result += string[i + 1];\n } else {\n result += escapeSeq || encodeHex(char);\n }\n }\n\n return result;\n}\n\nfunction writeFlowSequence(state, level, object) {\n var _result = '',\n _tag = state.tag,\n index,\n length,\n value;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n value = object[index];\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value);\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level, value, false, false) ||\n (typeof value === 'undefined' &&\n writeNode(state, level, null, false, false))) {\n\n if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = '[' + _result + ']';\n}\n\nfunction writeBlockSequence(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n index,\n length,\n value;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n value = object[index];\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value);\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level + 1, value, true, true, false, true) ||\n (typeof value === 'undefined' &&\n writeNode(state, level + 1, null, true, true, false, true))) {\n\n if (!compact || _result !== '') {\n _result += generateNextLine(state, level);\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += '-';\n } else {\n _result += '- ';\n }\n\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = _result || '[]'; // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping(state, level, object) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n pairBuffer;\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n\n pairBuffer = '';\n if (_result !== '') pairBuffer += ', ';\n\n if (state.condenseFlow) pairBuffer += '\"';\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue);\n }\n\n if (!writeNode(state, level, objectKey, false, false)) {\n continue; // Skip this pair because of invalid key;\n }\n\n if (state.dump.length > 1024) pairBuffer += '? ';\n\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ');\n\n if (!writeNode(state, level, objectValue, false, false)) {\n continue; // Skip this pair because of invalid value.\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = '{' + _result + '}';\n}\n\nfunction writeBlockMapping(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n explicitPair,\n pairBuffer;\n\n // Allow sorting keys so that the output file is deterministic\n if (state.sortKeys === true) {\n // Default sorting\n objectKeyList.sort();\n } else if (typeof state.sortKeys === 'function') {\n // Custom sort function\n objectKeyList.sort(state.sortKeys);\n } else if (state.sortKeys) {\n // Something is wrong\n throw new exception('sortKeys must be a boolean or a function');\n }\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n pairBuffer = '';\n\n if (!compact || _result !== '') {\n pairBuffer += generateNextLine(state, level);\n }\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue);\n }\n\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue; // Skip this pair because of invalid key.\n }\n\n explicitPair = (state.tag !== null && state.tag !== '?') ||\n (state.dump && state.dump.length > 1024);\n\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += '?';\n } else {\n pairBuffer += '? ';\n }\n }\n\n pairBuffer += state.dump;\n\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level);\n }\n\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue; // Skip this pair because of invalid value.\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += ':';\n } else {\n pairBuffer += ': ';\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = _result || '{}'; // Empty mapping if no valid pairs.\n}\n\nfunction detectType(state, object, explicit) {\n var _result, typeList, index, length, type, style;\n\n typeList = explicit ? state.explicitTypes : state.implicitTypes;\n\n for (index = 0, length = typeList.length; index < length; index += 1) {\n type = typeList[index];\n\n if ((type.instanceOf || type.predicate) &&\n (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n (!type.predicate || type.predicate(object))) {\n\n if (explicit) {\n if (type.multi && type.representName) {\n state.tag = type.representName(object);\n } else {\n state.tag = type.tag;\n }\n } else {\n state.tag = '?';\n }\n\n if (type.represent) {\n style = state.styleMap[type.tag] || type.defaultStyle;\n\n if (_toString.call(type.represent) === '[object Function]') {\n _result = type.represent(object, style);\n } else if (_hasOwnProperty.call(type.represent, style)) {\n _result = type.represent[style](object, style);\n } else {\n throw new exception('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style');\n }\n\n state.dump = _result;\n }\n\n return true;\n }\n }\n\n return false;\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode(state, level, object, block, compact, iskey, isblockseq) {\n state.tag = null;\n state.dump = object;\n\n if (!detectType(state, object, false)) {\n detectType(state, object, true);\n }\n\n var type = _toString.call(state.dump);\n var inblock = block;\n var tagStr;\n\n if (block) {\n block = (state.flowLevel < 0 || state.flowLevel > level);\n }\n\n var objectOrArray = type === '[object Object]' || type === '[object Array]',\n duplicateIndex,\n duplicate;\n\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object);\n duplicate = duplicateIndex !== -1;\n }\n\n if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n compact = false;\n }\n\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = '*ref_' + duplicateIndex;\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true;\n }\n if (type === '[object Object]') {\n if (block && (Object.keys(state.dump).length !== 0)) {\n writeBlockMapping(state, level, state.dump, compact);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowMapping(state, level, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object Array]') {\n if (block && (state.dump.length !== 0)) {\n if (state.noArrayIndent && !isblockseq && level > 0) {\n writeBlockSequence(state, level - 1, state.dump, compact);\n } else {\n writeBlockSequence(state, level, state.dump, compact);\n }\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowSequence(state, level, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object String]') {\n if (state.tag !== '?') {\n writeScalar(state, state.dump, level, iskey, inblock);\n }\n } else if (type === '[object Undefined]') {\n return false;\n } else {\n if (state.skipInvalid) return false;\n throw new exception('unacceptable kind of an object to dump ' + type);\n }\n\n if (state.tag !== null && state.tag !== '?') {\n // Need to encode all characters except those allowed by the spec:\n //\n // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */\n // [36] ns-hex-digit ::= ns-dec-digit\n // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */\n // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */\n // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”\n // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”\n // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”\n // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”\n //\n // Also need to encode '!' because it has special meaning (end of tag prefix).\n //\n tagStr = encodeURI(\n state.tag[0] === '!' ? state.tag.slice(1) : state.tag\n ).replace(/!/g, '%21');\n\n if (state.tag[0] === '!') {\n tagStr = '!' + tagStr;\n } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {\n tagStr = '!!' + tagStr.slice(18);\n } else {\n tagStr = '!<' + tagStr + '>';\n }\n\n state.dump = tagStr + ' ' + state.dump;\n }\n }\n\n return true;\n}\n\nfunction getDuplicateReferences(object, state) {\n var objects = [],\n duplicatesIndexes = [],\n index,\n length;\n\n inspectNode(object, objects, duplicatesIndexes);\n\n for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]]);\n }\n state.usedDuplicates = new Array(length);\n}\n\nfunction inspectNode(object, objects, duplicatesIndexes) {\n var objectKeyList,\n index,\n length;\n\n if (object !== null && typeof object === 'object') {\n index = objects.indexOf(object);\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index);\n }\n } else {\n objects.push(object);\n\n if (Array.isArray(object)) {\n for (index = 0, length = object.length; index < length; index += 1) {\n inspectNode(object[index], objects, duplicatesIndexes);\n }\n } else {\n objectKeyList = Object.keys(object);\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);\n }\n }\n }\n }\n}\n\nfunction dump$1(input, options) {\n options = options || {};\n\n var state = new State(options);\n\n if (!state.noRefs) getDuplicateReferences(input, state);\n\n var value = input;\n\n if (state.replacer) {\n value = state.replacer.call({ '': value }, '', value);\n }\n\n if (writeNode(state, 0, value, true, true)) return state.dump + '\\n';\n\n return '';\n}\n\nvar dump_1 = dump$1;\n\nvar dumper = {\n\tdump: dump_1\n};\n\nfunction renamed(from, to) {\n return function () {\n throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +\n 'Use yaml.' + to + ' instead, which is now safe by default.');\n };\n}\n\n\nvar Type = type;\nvar Schema = schema;\nvar FAILSAFE_SCHEMA = failsafe;\nvar JSON_SCHEMA = json;\nvar CORE_SCHEMA = core;\nvar DEFAULT_SCHEMA = _default;\nvar load = loader.load;\nvar loadAll = loader.loadAll;\nvar dump = dumper.dump;\nvar YAMLException = exception;\n\n// Re-export all types in case user wants to create custom schema\nvar types = {\n binary: binary,\n float: float,\n map: map,\n null: _null,\n pairs: pairs,\n set: set,\n timestamp: timestamp,\n bool: bool,\n int: int,\n merge: merge,\n omap: omap,\n seq: seq,\n str: str\n};\n\n// Removed functions from JS-YAML 3.0.x\nvar safeLoad = renamed('safeLoad', 'load');\nvar safeLoadAll = renamed('safeLoadAll', 'loadAll');\nvar safeDump = renamed('safeDump', 'dump');\n\nvar jsYaml = {\n\tType: Type,\n\tSchema: Schema,\n\tFAILSAFE_SCHEMA: FAILSAFE_SCHEMA,\n\tJSON_SCHEMA: JSON_SCHEMA,\n\tCORE_SCHEMA: CORE_SCHEMA,\n\tDEFAULT_SCHEMA: DEFAULT_SCHEMA,\n\tload: load,\n\tloadAll: loadAll,\n\tdump: dump,\n\tYAMLException: YAMLException,\n\ttypes: types,\n\tsafeLoad: safeLoad,\n\tsafeLoadAll: safeLoadAll,\n\tsafeDump: safeDump\n};\n\nexport { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, jsYaml as default, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types };\n","// Contract Integrity detector (ADR-010) — validates that Backstage\n// catalog-info.yaml references resolve to declared entities.\n//\n// Catches the \"dangling contract reference\" failure class: a repo declares it\n// CONSUMES an API (spec.consumesApis) that no repo PUBLISHES, or points at a\n// System / parent Component that doesn't exist. Each such PR is internally valid\n// and green; the break only exists across the system's contracts — which is\n// exactly what ordinary CI can't see.\n//\n// Resolution universe = entities declared across the catalog files in this PR,\n// unioned with an optional org catalog index (ctx.catalogKnownEntities). Local\n// structural refs (system / subcomponentOf) and owned refs (providesApis) must\n// resolve and warn when they don't; cross-repo contract refs (consumesApis /\n// dependsOn) warn only when an index is configured, otherwise advise.\n\nimport yaml from \"js-yaml\";\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst CATALOG_FILE = /(?:^|\\/)catalog-info\\.ya?ml$/i;\n\nexport type RefKind = \"local\" | \"owned\" | \"contract\";\n\nexport interface ContractRefFinding {\n file: string;\n field: string;\n ref: string;\n name: string;\n kind: RefKind;\n}\n\nexport function isCatalogFile(file: SubmissionFileInfo): boolean {\n return CATALOG_FILE.test(normalizePath(file.filename));\n}\n\n/** Backstage entity ref → bare name. \"component:default/foo\" → \"foo\". */\nfunction refName(ref: string): string {\n let s = String(ref).trim();\n const colon = s.indexOf(\":\");\n if (colon >= 0) s = s.slice(colon + 1); // strip \"kind:\"\n const slash = s.lastIndexOf(\"/\");\n if (slash >= 0) s = s.slice(slash + 1); // strip \"namespace/\"\n return s;\n}\n\nfunction asArray(value: unknown): string[] {\n if (Array.isArray(value))\n return value.filter((v): v is string => typeof v === \"string\");\n if (typeof value === \"string\") return [value];\n return [];\n}\n\n/** Parse every YAML doc in a catalog file; tolerate malformed docs (that's syntax_validity's job). */\nfunction parseDocs(content: string): Array<Record<string, unknown>> {\n const docs: Array<Record<string, unknown>> = [];\n try {\n yaml.loadAll(content, (doc) => {\n if (doc && typeof doc === \"object\") docs.push(doc as Record<string, unknown>);\n });\n } catch {\n // unparseable catalog — leave to syntax_validity; we simply can't analyze it\n }\n return docs;\n}\n\nfunction entityName(doc: Record<string, unknown>): string | null {\n const meta = doc.metadata as Record<string, unknown> | undefined;\n const name = meta?.name;\n return typeof name === \"string\" ? name : null;\n}\n\n/**\n * Core analysis shared by the detector and the self-heal lane: parse the PR's\n * catalog files, build the resolution universe, and return every reference that\n * doesn't resolve. Returns null when there are no catalog files to analyze.\n */\nexport function analyzeCatalogRefs(\n files: SubmissionFileInfo[],\n knownEntities?: Set<string>,\n): { findings: ContractRefFinding[]; hasOrgIndex: boolean } | null {\n const catalogFiles = files.filter(isCatalogFile);\n if (catalogFiles.length === 0) return null;\n\n // Parse once; remember which file each doc came from.\n const parsed = catalogFiles.map((file) => ({\n file,\n docs: parseDocs(fileContent(file)),\n }));\n\n // 1. Build the resolution universe: in-PR declarations ∪ configured org index.\n const declared = new Set<string>();\n for (const { docs } of parsed) {\n for (const doc of docs) {\n const name = entityName(doc);\n if (name) declared.add(name);\n }\n }\n const known = new Set<string>(declared);\n for (const name of knownEntities ?? []) known.add(name);\n const hasOrgIndex = (knownEntities?.size ?? 0) > 0;\n\n // 2. Walk references and collect anything that doesn't resolve.\n const findings: ContractRefFinding[] = [];\n const checkRef = (\n file: SubmissionFileInfo,\n field: string,\n ref: string,\n kind: RefKind,\n ) => {\n const name = refName(ref);\n if (!name || known.has(name)) return;\n findings.push({ file: normalizePath(file.filename), field, ref, name, kind });\n };\n\n for (const { file, docs } of parsed) {\n for (const doc of docs) {\n const spec = (doc.spec ?? {}) as Record<string, unknown>;\n if (typeof spec.system === \"string\") checkRef(file, \"system\", spec.system, \"local\");\n if (typeof spec.subcomponentOf === \"string\")\n checkRef(file, \"subcomponentOf\", spec.subcomponentOf, \"local\");\n for (const ref of asArray(spec.providesApis))\n checkRef(file, \"providesApis\", ref, \"owned\");\n for (const ref of asArray(spec.consumesApis))\n checkRef(file, \"consumesApis\", ref, \"contract\");\n for (const ref of asArray(spec.dependsOn))\n checkRef(file, \"dependsOn\", ref, \"contract\");\n }\n }\n\n return { findings, hasOrgIndex };\n}\n\nexport function detectContractIntegrity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const analysis = analyzeCatalogRefs(ctx.files, ctx.catalogKnownEntities);\n if (!analysis) return null;\n const { findings, hasOrgIndex } = analysis;\n\n if (findings.length === 0) return null;\n\n // 3. Severity: local/owned refs are structural (always warn). Cross-repo\n // contract refs warn only when an org index makes \"dangling\" decidable;\n // without one they're advisory (\"unverified\") to avoid single-repo FPs.\n const structural = findings.filter((f) => f.kind !== \"contract\");\n const contract = findings.filter((f) => f.kind === \"contract\");\n const severity: SubmissionCheckResult[\"severity\"] =\n structural.length > 0 || hasOrgIndex ? \"warn\" : \"advisory\";\n\n // Self-heal lane (ADR-010): a missing LOCAL entity (system / subcomponentOf\n // target) can be auto-declared in the same catalog file. See healers/catalog.ts.\n const localHealable = findings.some((f) => f.kind === \"local\");\n\n const lines = findings.map(\n (f) => `${f.file}: spec.${f.field} → \"${f.ref}\" (no declared entity \"${f.name}\")`,\n );\n const detailParts = [lines.join(\"; \")];\n if (contract.length > 0 && !hasOrgIndex) {\n detailParts.push(\n \"Cross-repo contract refs are UNVERIFIED — supply submission.contract_integrity.known_entities (an org catalog index) to enforce.\",\n );\n }\n\n return {\n code: \"contract_integrity\",\n severity,\n title:\n severity === \"warn\"\n ? \"Dangling catalog contract reference\"\n : \"Unverified catalog contract reference\",\n detail: detailParts.join(\" \"),\n files: [...new Set(findings.map((f) => f.file))],\n suggested_action:\n \"Declare the referenced entity in the owning repo's catalog-info.yaml (or fix the reference). \" +\n \"For cross-repo contracts, ensure the publishing repo declares the API and that it is in the org catalog index.\" +\n (localHealable\n ? \" A missing local entity (system / subcomponentOf target) can be auto-declared — Trailhead self-heal.\"\n : \"\"),\n autofix_eligible: localHealable,\n };\n}\n","// Safe Deprecation detector (ADR-010) — catalog coherence on retirement.\n//\n// When an entity is retired (a Backstage `catalog-info.yaml` doc with\n// `spec.lifecycle: deprecated`), nothing still ALIVE should keep depending on it.\n// A live component that still `consumesApis` / `dependsOn` / is `subcomponentOf`\n// / has `system` pointing at a deprecated entity is a zombie reference — the\n// retirement looks done but a live surface still wires to the corpse. This is the\n// catalog-level shape of the \"incomplete deprecation\" incident class.\n//\n// v1 is catalog-native (fully in-diff, high-confidence). Route/data-surface\n// coverage (redirect maps, route globs) needs full repo file contents and is a\n// tracked follow-up under ADR-010.\n\nimport yaml from \"js-yaml\";\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst CATALOG_FILE = /(?:^|\\/)catalog-info\\.ya?ml$/i;\n\nfunction isCatalogFile(file: SubmissionFileInfo): boolean {\n return CATALOG_FILE.test(normalizePath(file.filename));\n}\n\nfunction refName(ref: string): string {\n let s = String(ref).trim();\n const colon = s.indexOf(\":\");\n if (colon >= 0) s = s.slice(colon + 1);\n const slash = s.lastIndexOf(\"/\");\n if (slash >= 0) s = s.slice(slash + 1);\n return s;\n}\n\nfunction asArray(value: unknown): string[] {\n if (Array.isArray(value))\n return value.filter((v): v is string => typeof v === \"string\");\n if (typeof value === \"string\") return [value];\n return [];\n}\n\nfunction parseDocs(content: string): Array<Record<string, unknown>> {\n const docs: Array<Record<string, unknown>> = [];\n try {\n yaml.loadAll(content, (doc) => {\n if (doc && typeof doc === \"object\") docs.push(doc as Record<string, unknown>);\n });\n } catch {\n // malformed — leave to syntax_validity\n }\n return docs;\n}\n\nfunction entityName(doc: Record<string, unknown>): string | null {\n const meta = doc.metadata as Record<string, unknown> | undefined;\n return typeof meta?.name === \"string\" ? meta.name : null;\n}\n\nfunction isRetired(doc: Record<string, unknown>): boolean {\n const spec = (doc.spec ?? {}) as Record<string, unknown>;\n return spec.lifecycle === \"deprecated\";\n}\n\ninterface ZombieRef {\n file: string;\n from: string;\n field: string;\n to: string;\n}\n\nexport function detectSafeDeprecation(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const catalogFiles = ctx.files.filter(isCatalogFile);\n if (catalogFiles.length === 0) return null;\n\n const parsed = catalogFiles.map((file) => ({\n file,\n docs: parseDocs(fileContent(file)),\n }));\n\n // 1. Which entities are being retired?\n const retired = new Set<string>();\n for (const { docs } of parsed) {\n for (const doc of docs) {\n const name = entityName(doc);\n if (name && isRetired(doc)) retired.add(name);\n }\n }\n if (retired.size === 0) return null;\n\n // 2. A LIVE entity that still references a retired one is a zombie wire.\n const zombies: ZombieRef[] = [];\n for (const { file, docs } of parsed) {\n for (const doc of docs) {\n if (isRetired(doc)) continue; // a dying thing may reference another; ignore\n const from = entityName(doc) ?? \"(unnamed)\";\n const spec = (doc.spec ?? {}) as Record<string, unknown>;\n const check = (field: string, ref: string) => {\n const to = refName(ref);\n if (retired.has(to)) {\n zombies.push({ file: normalizePath(file.filename), from, field, to });\n }\n };\n if (typeof spec.system === \"string\") check(\"system\", spec.system);\n if (typeof spec.subcomponentOf === \"string\")\n check(\"subcomponentOf\", spec.subcomponentOf);\n for (const ref of asArray(spec.consumesApis)) check(\"consumesApis\", ref);\n for (const ref of asArray(spec.dependsOn)) check(\"dependsOn\", ref);\n }\n }\n\n if (zombies.length === 0) return null;\n\n const lines = zombies.map(\n (z) => `${z.file}: \"${z.from}\" still ${z.field} → \"${z.to}\" (deprecated)`,\n );\n return {\n code: \"safe_deprecation\",\n severity: \"warn\",\n title: \"Live entity depends on a retired one\",\n detail: `Deprecation left a live wire to a retired entity: ${lines.join(\"; \")}.`,\n files: [...new Set(zombies.map((z) => z.file))],\n suggested_action:\n \"Repoint the live reference to the surviving/canonical entity, or deprecate the dependent too. \" +\n \"Also confirm non-catalog surfaces (routes, redirects, listings) for the retired entity are covered.\",\n autofix_eligible: false,\n };\n}\n","// Destructive Change detector (ADR-010) — evidence-gated destructive migrations.\n//\n// `destructive_sql` already BLOCKS the always-bad shapes (DROP TABLE / TRUNCATE /\n// DELETE without WHERE). But it deliberately lets through *targeted* destructive\n// ops that are legitimate WITH due diligence: a `DELETE ... WHERE`, an\n// `ALTER ... DROP COLUMN`, a `DROP VIEW/TYPE/INDEX/...`, or a wide `UPDATE` with\n// no WHERE. Those are exactly the changes that should ship only with recorded\n// evidence — the FK / row-count / reversibility check a human does by hand today.\n//\n// This detector requires that evidence, inline in the migration, as a block:\n//\n// -- @destructive-change\n// -- fk-refs: 0 (or: names of referencing tables + how handled)\n// -- affected-rows: 1 (or an estimate)\n// -- reversible: re-seed; row carries no referenced data (or: no — <why ok>)\n// -- ack: dschirmer 2026-06-01\n//\n// Found a targeted destructive op but no complete evidence block → finding.\n// Ships `warn` (phase-0, per ADR-008); target state is `blocking` w/o evidence.\n// Self-heal follow-up: auto-run the FK/row probes and attach the evidence.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst SQL_FILE = /\\.sql$/i;\n\n/** Targeted destructive ops that `destructive_sql` allows but that warrant evidence. */\nconst DESTRUCTIVE_OPS: Array<{ label: string; pattern: RegExp }> = [\n // DELETE with a WHERE (destructive_sql only blocks DELETE *without* WHERE).\n { label: \"DELETE ... WHERE\", pattern: /\\bDELETE\\s+FROM\\s+[^\\n;]*?\\bWHERE\\b/i },\n // ALTER TABLE ... DROP COLUMN (data loss; not a bare DROP TABLE).\n {\n label: \"DROP COLUMN\",\n pattern: /\\bALTER\\s+TABLE\\b(?:(?!;)[\\s\\S])*?\\bDROP\\s+COLUMN\\b/i,\n },\n // DROP of other objects (view/type/index/function/sequence/schema/mat-view).\n {\n label: \"DROP <object>\",\n pattern:\n /\\bDROP\\s+(?:MATERIALIZED\\s+VIEW|VIEW|TYPE|INDEX|FUNCTION|SEQUENCE|SCHEMA)\\b/i,\n },\n // Wide UPDATE — a SET with no WHERE before the statement terminator.\n {\n label: \"UPDATE without WHERE\",\n pattern: /\\bUPDATE\\s+[^\\n;]+?\\bSET\\b(?:(?!\\bWHERE\\b)[^;])*;/i,\n },\n];\n\nconst EVIDENCE_FIELDS: Array<{ key: string; pattern: RegExp }> = [\n { key: \"fk-refs\", pattern: /\\bfk-refs\\s*:/i },\n { key: \"affected-rows\", pattern: /\\baffected-rows\\s*:/i },\n { key: \"reversible\", pattern: /\\breversible\\s*:/i },\n { key: \"ack\", pattern: /\\back\\s*:/i },\n];\n\nfunction isSqlFile(file: SubmissionFileInfo): boolean {\n return SQL_FILE.test(normalizePath(file.filename));\n}\n\ninterface FileFinding {\n file: string;\n ops: string[];\n missing: string[];\n}\n\nexport function detectDestructiveChange(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const sqlFiles = ctx.files.filter(isSqlFile);\n if (sqlFiles.length === 0) return null;\n\n const findings: FileFinding[] = [];\n for (const file of sqlFiles) {\n const content = fileContent(file);\n if (!content) continue;\n\n const ops = DESTRUCTIVE_OPS.filter((op) => op.pattern.test(content)).map(\n (op) => op.label,\n );\n if (ops.length === 0) continue;\n\n const missing = EVIDENCE_FIELDS.filter((f) => !f.pattern.test(content)).map(\n (f) => f.key,\n );\n if (missing.length === 0) continue; // op present, evidence complete → ok\n\n findings.push({ file: normalizePath(file.filename), ops, missing });\n }\n\n if (findings.length === 0) return null;\n\n const lines = findings.map(\n (f) => `${f.file}: ${f.ops.join(\", \")} — missing evidence: ${f.missing.join(\", \")}`,\n );\n\n return {\n code: \"destructive_change\",\n severity: \"warn\",\n title: \"Destructive migration without an evidence bundle\",\n detail: `Targeted destructive op(s) lack a complete evidence block: ${lines.join(\n \"; \",\n )}.`,\n files: findings.map((f) => f.file),\n suggested_action:\n \"Add an evidence block to the migration:\\n\" +\n \" -- @destructive-change\\n\" +\n \" -- fk-refs: <0 or referencing tables + how handled>\\n\" +\n \" -- affected-rows: <count or estimate>\\n\" +\n \" -- reversible: <how to undo, or 'no — <why acceptable>'>\\n\" +\n \" -- ack: <who/when>\",\n autofix_eligible: false,\n };\n}\n","// Claim Anchoring detector (ADR-010) — doc assertions should cite where they're true.\n//\n// Incident #3: a doc asserted \"redirects exist\" while the live canonical path had\n// none — the claim outlived the code. This detector flags assertive, *behavioral*\n// claims added to docs that carry no anchor (a file/path reference, a link, or a\n// `verified-by:` / `see:` pointer). It does NOT judge whether the claim is true —\n// it asks the author to point at where it's enforced/tested, so the claim and the\n// code can be cross-checked later. Advisory only (per ADR-008): informational, no\n// block. Self-heal follow-up: comment + open a test stub for the claim.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst DOC_FILE = /\\.mdx?$/i;\n\n// High-signal, behavioral, testable assertions. Kept tight to limit noise.\nconst CLAIM_PATTERNS: RegExp[] = [\n /\\bredirects?\\s+(?:exist|are\\s+in\\s+place|are\\s+configured|are\\s+handled)\\b/i,\n /\\bis\\s+(?:enforced|guaranteed|wired\\s+up|fully\\s+covered)\\b/i,\n /\\b(?:always|never)\\s+(?:redirects?|returns?|blocks?|allows?|runs?|fires?|resolves?)\\b/i,\n /\\bfully\\s+(?:covered|tested|implemented|wired)\\b/i,\n /\\b(?:every|all)\\s+\\w+\\s+(?:are\\s+)?(?:redirected|covered|validated|enforced)\\b/i,\n /\\bguaranteed\\s+to\\b/i,\n];\n\n// An anchor lets a reviewer cross-check the claim against reality.\nconst ANCHOR_PATTERNS: RegExp[] = [\n /`[^`]*[\\w.-]+\\.(?:ts|tsx|js|jsx|mjs|cjs|sql|ya?ml|json|py|go|rs)`/i, // code/path in backticks\n /`[^`]*\\/[^`]*`/, // any path-ish backtick span\n /\\]\\([^)]+\\)/, // markdown link\n /\\b(?:verified[ -]by|tested in|see|ref|test)\\s*[:=]/i, // explicit pointer\n /<!--\\s*claim-ok/i, // author override\n];\n\nfunction isDocFile(file: SubmissionFileInfo): boolean {\n return DOC_FILE.test(normalizePath(file.filename));\n}\n\nfunction hasAnchor(window: string): boolean {\n return ANCHOR_PATTERNS.some((re) => re.test(window));\n}\n\ninterface Unanchored {\n file: string;\n line: number;\n text: string;\n}\n\nexport function detectClaimAnchoring(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const docs = ctx.files.filter(isDocFile);\n if (docs.length === 0) return null;\n\n const unanchored: Unanchored[] = [];\n for (const file of docs) {\n const content = fileContent(file);\n if (!content) continue;\n const lines = content.split(\"\\n\");\n let inFence = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n if (/^\\s*```/.test(line)) {\n inFence = !inFence;\n continue;\n }\n if (inFence) continue; // claims inside code examples aren't doc assertions\n\n if (!CLAIM_PATTERNS.some((re) => re.test(line))) continue;\n\n // Anchor may sit on the claim line or an adjacent line.\n const windowText = [lines[i - 1] ?? \"\", line, lines[i + 1] ?? \"\"].join(\"\\n\");\n if (hasAnchor(windowText)) continue;\n\n unanchored.push({\n file: normalizePath(file.filename),\n line: i + 1,\n text: line.trim().slice(0, 120),\n });\n }\n }\n\n if (unanchored.length === 0) return null;\n\n const shown = unanchored.slice(0, 8);\n const lines = shown.map((u) => `${u.file}:${u.line} — \"${u.text}\"`);\n const more =\n unanchored.length > shown.length\n ? ` (+${unanchored.length - shown.length} more)`\n : \"\";\n\n return {\n code: \"claim_anchoring\",\n severity: \"advisory\",\n title: \"Behavioral claim in docs has no anchor\",\n detail:\n `Assertive claims with no reference to where they're enforced/tested: ${lines.join(\n \"; \",\n )}${more}. ` +\n \"Cite the code/test (a backtick path, a link, or `verified-by:`), or add `<!-- claim-ok -->` if intentional.\",\n files: [...new Set(unanchored.map((u) => u.file))],\n suggested_action:\n \"Anchor each claim to where it lives (e.g. `proxy.ts`, a test path, or a link), \" +\n \"so docs and reality can be cross-checked. This is the doc-vs-reality drift that let \" +\n '\"redirects exist\" outlive the missing /apps redirect.',\n autofix_eligible: false,\n };\n}\n","// Promotion Coherence detector (ADR-010) — guard env-branch promotions.\n//\n// Incident #5: work landed on `dev` behind an in-flight promotion, so the open\n// production release silently shipped without it — and a destructive migration\n// rode a staging→prod release to production. Ordinary detectors look at the diff;\n// this one looks at the *branch topology* of a promotion PR (base/head from\n// GITHUB_BASE_REF / GITHUB_HEAD_REF, threaded via ctx.promotion).\n//\n// v1 catches two in-reach signals on a promotion PR (env branch → env branch):\n// 1. Stage skip — a promotion straight into a production branch from `dev`\n// (bypassing staging). The ladder is dev → staging → master/main.\n// 2. Risky payload to prod — a promotion into production that carries SQL\n// migrations: confirm they belong in THIS release and carry destructive\n// evidence (see `destructive_change`).\n// Ships `warn` (phase-0). Follow-up: \"source has commits not in this PR\" (omitted\n// work) needs an octokit branch-compare, beyond the file-diff model — tracked.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext } from \"./types.js\";\nimport { normalizePath } from \"./helpers.js\";\n\nconst DEV_BRANCHES = new Set([\"dev\", \"develop\", \"development\"]);\nconst PREPROD_BRANCHES = new Set([\"staging\", \"stage\", \"preprod\", \"pre-prod\", \"release\"]);\nconst PROD_BRANCHES = new Set([\"master\", \"main\", \"production\", \"prod\"]);\nconst ENV_BRANCHES = new Set([...DEV_BRANCHES, ...PREPROD_BRANCHES, ...PROD_BRANCHES]);\n\n/** Strip refs/heads/ and any owner prefix; lower-case the bare branch name. */\nfunction bareBranch(ref: string | undefined): string {\n if (!ref) return \"\";\n let b = ref.trim();\n b = b.replace(/^refs\\/heads\\//, \"\");\n const slash = b.lastIndexOf(\":\");\n if (slash >= 0) b = b.slice(slash + 1);\n return b.toLowerCase();\n}\n\nfunction isMigration(path: string): boolean {\n return /\\.sql$/i.test(path);\n}\n\nexport function detectPromotionCoherence(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const base = bareBranch(ctx.promotion?.baseBranch);\n const head = bareBranch(ctx.promotion?.headBranch);\n // Dormant unless we actually have a promotion (env branch → env branch).\n if (!base || !head) return null;\n if (!ENV_BRANCHES.has(base) || !ENV_BRANCHES.has(head)) return null;\n\n const findings: string[] = [];\n\n // 1. Stage skip into production.\n if (PROD_BRANCHES.has(base) && DEV_BRANCHES.has(head)) {\n findings.push(\n `promotes ${head} → ${base}, skipping the pre-prod stage (ladder: dev → staging → ${base})`,\n );\n }\n\n // 2. Migrations entering production via a promotion.\n const migrations = ctx.files.map((f) => normalizePath(f.filename)).filter(isMigration);\n if (PROD_BRANCHES.has(base) && migrations.length > 0) {\n findings.push(\n `carries ${migrations.length} migration(s) into production (${migrations\n .slice(0, 5)\n .join(\n \", \",\n )}) — confirm they belong in this release and carry destructive_change evidence`,\n );\n }\n\n if (findings.length === 0) return null;\n\n return {\n code: \"promotion_coherence\",\n severity: \"warn\",\n title: \"Promotion coherence\",\n detail: `This promotion ${findings.join(\"; \")}.`,\n files: migrations,\n suggested_action:\n \"Promote through the full ladder (dev → staging → master/main), and double-check \" +\n \"the release contents (especially destructive migrations) match what you intend to ship.\",\n autofix_eligible: false,\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@swc/core\");","// Real parse-based syntax validation for Gate 1 (no bracket-count fallback).\n// Parses full file content only — never a partial diff hunk (see submission-gate.md).\n\nimport { parseSync, type ParseOptions } from \"@swc/core\";\nimport yaml from \"js-yaml\";\nimport { extensionOf } from \"./helpers.js\";\n\nconst PARSEABLE = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"] as const;\n\nfunction parserOptionsFor(ext: string): ParseOptions {\n const isTs = ext === \".ts\" || ext === \".tsx\";\n return {\n syntax: isTs ? \"typescript\" : \"ecmascript\",\n tsx: ext === \".tsx\",\n jsx: ext === \".jsx\",\n decorators: true,\n dynamicImport: true,\n };\n}\n\n/** Returns a one-line error message, or null when content parses cleanly. */\nexport function validateFileSyntax(filename: string, content: string): string | null {\n if (!content.trim()) return null;\n\n const ext = extensionOf(filename);\n try {\n if ((PARSEABLE as readonly string[]).includes(ext)) {\n parseSync(content, parserOptionsFor(ext));\n } else if (ext === \".json\") {\n JSON.parse(content);\n } else if (ext === \".yaml\" || ext === \".yml\") {\n yaml.load(content);\n } else if (ext === \".md\" && content.startsWith(\"---\")) {\n const end = content.indexOf(\"\\n---\", 3);\n if (end > 0) yaml.load(content.slice(3, end));\n }\n } catch (error) {\n const message = error instanceof Error ? error.message.split(\"\\n\")[0] : String(error);\n return message || \"Parse error\";\n }\n return null;\n}\n","// Pure risk scoring engine — no framework dependencies.\n// Shared across the GitHub Action, MCP server, and GitHub App.\n\n// ---------------------------------------------------------------------------\n// Interfaces (framework-agnostic mirrors of the Zod schemas in types.ts)\n// ---------------------------------------------------------------------------\n\nexport interface FileInfo {\n filename: string;\n additions?: number;\n deletions?: number;\n changes: number;\n patch?: string;\n}\n\nexport interface RiskFactorResult {\n type: string;\n score: number;\n detail?: Record<string, unknown>;\n}\n\nexport interface SensitivityConfig {\n high: string[];\n medium: string[];\n low: string[];\n}\n\nexport interface RiskProfileMatchDef {\n files_include: string[];\n files_exclude: string[];\n min_files?: number;\n max_files?: number;\n}\n\nexport interface RiskProfileDef {\n name?: string;\n match: RiskProfileMatchDef;\n weights: Record<string, number>;\n}\n\nexport interface RiskConfig {\n sensitivity?: SensitivityConfig;\n weights?: Record<string, number>;\n ignore?: string[];\n profiles?: RiskProfileDef[];\n}\n\nexport interface SecurityAlertCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n topRules?: string[];\n}\n\nexport interface DeploymentOutcomeSummary {\n recentFailures: number;\n recentTotal: number;\n lastDeployFailed: boolean;\n lastRollback: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Pattern constants\n// ---------------------------------------------------------------------------\n\nexport const TEST_FILE_PATTERN =\n /\\.(test|spec)\\.(ts|tsx|js|jsx)$|__tests__\\/|\\.cy\\.(ts|js)$/;\n\nexport const NON_SOURCE_PATTERN =\n /\\.(sql|ya?ml|json|md|css|svg|lock|txt|env|png|jpg|gif)$/i;\n\nexport const SENSITIVE_PATTERNS = [\n /(?:^|\\/)migrations\\//i,\n /(?:^|\\/)auth/i,\n /(?:^|\\/)security/i,\n /(?:^|\\/)payment/i,\n /(?:^|\\/)billing/i,\n /(?:^|\\/)webhook/i,\n /(?:^|\\/)infrastructure\\//i,\n /(?:^|\\/)\\.github\\/workflows\\//i,\n /(?:^|\\/)secrets/i,\n /(?:^|\\/)\\.env/i,\n];\n\nconst HIGH_SENSITIVITY_PATTERN = /(?:^|\\/)(?:auth|security|payment|billing|webhook)/i;\n\nconst INFRA_SENSITIVITY_PATTERN =\n /(?:^|\\/)(?:migrations|infrastructure|\\.github\\/workflows|secrets|\\.env)/i;\n\nexport const DEPENDENCY_FILES = [\n /^package\\.json$/,\n /^package-lock\\.json$/,\n /^yarn\\.lock$/,\n /^pnpm-lock\\.yaml$/,\n /^requirements\\.txt$/,\n /^Pipfile\\.lock$/,\n /^poetry\\.lock$/,\n /^go\\.mod$/,\n /^go\\.sum$/,\n /^Gemfile\\.lock$/,\n /^Cargo\\.lock$/,\n /^composer\\.lock$/,\n];\n\nconst PACKAGE_JSON_DEPENDENCY_FIELDS = new Set([\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n \"optionalDependencies\",\n \"bundledDependencies\",\n]);\n\n// ---------------------------------------------------------------------------\n// Factor weights (v3: includes security_alerts, deployment_history, canary_status)\n// ---------------------------------------------------------------------------\n\nexport const FACTOR_WEIGHTS: Record<string, number> = {\n code_churn: 3,\n test_coverage: 2,\n file_count: 2,\n sensitive_files: 3,\n author_history: 1,\n dependency_changes: 2,\n pr_age: 1,\n security_alerts: 4,\n deployment_history: 2,\n canary_status: 2,\n ci_integrity: 3,\n workflow_security: 4,\n prompt_injection_risk: 4,\n supply_chain: 3,\n pr_scope: 2,\n duplicate_logic: 1,\n cross_repo_impact: 2,\n};\n\n// ---------------------------------------------------------------------------\n// Glob matching\n// ---------------------------------------------------------------------------\n\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"<<GLOBSTAR>>\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/<<GLOBSTAR>>/g, \".*\")\n .replace(/\\?/g, \".\");\n return new RegExp(`^${escaped}$`, \"i\");\n}\n\nexport function matchesGlobs(filename: string, patterns: string[]): boolean {\n return patterns.some((p) => globToRegex(p).test(filename));\n}\n\n// ---------------------------------------------------------------------------\n// Risk profile matching\n// ---------------------------------------------------------------------------\n\nexport function matchRiskProfile(\n filenames: string[],\n profiles: RiskProfileDef[],\n): RiskProfileDef | null {\n if (profiles.length === 0) return null;\n\n for (const profile of profiles) {\n const m = profile.match;\n\n if (m.min_files !== undefined && filenames.length < m.min_files) continue;\n if (m.max_files !== undefined && filenames.length > m.max_files) continue;\n\n if (\n m.files_include.length > 0 &&\n !m.files_include.every((pattern) =>\n filenames.some((f) => matchesGlobs(f, [pattern])),\n )\n ) {\n continue;\n }\n\n if (\n m.files_exclude.length > 0 &&\n m.files_exclude.some((pattern) => filenames.some((f) => matchesGlobs(f, [pattern])))\n ) {\n continue;\n }\n\n return profile;\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// File classification helpers\n// ---------------------------------------------------------------------------\n\nexport function isTestFile(filename: string): boolean {\n return TEST_FILE_PATTERN.test(filename);\n}\n\nexport function isNonSourceFile(filename: string): boolean {\n return NON_SOURCE_PATTERN.test(filename);\n}\n\nexport function isSensitiveFile(filename: string): boolean {\n return SENSITIVE_PATTERNS.some((p) => p.test(filename));\n}\n\nexport function sensitivityWeight(filename: string, config?: RiskConfig | null): number {\n if (config) {\n if (config.ignore?.length && matchesGlobs(filename, config.ignore)) return 0;\n if (\n config.sensitivity?.high.length &&\n matchesGlobs(filename, config.sensitivity.high)\n )\n return 3;\n if (\n config.sensitivity?.medium.length &&\n matchesGlobs(filename, config.sensitivity.medium)\n )\n return 2;\n if (config.sensitivity?.low.length && matchesGlobs(filename, config.sensitivity.low))\n return 0.5;\n }\n\n if (isTestFile(filename)) return 0.3;\n if (HIGH_SENSITIVITY_PATTERN.test(filename)) return 3;\n if (INFRA_SENSITIVITY_PATTERN.test(filename)) return 2;\n if (isNonSourceFile(filename)) return 0.5;\n return 1;\n}\n\n// ---------------------------------------------------------------------------\n// Weighted average\n// ---------------------------------------------------------------------------\n\nexport function weightedAverageScores(\n factors: RiskFactorResult[],\n overrides?: Record<string, number>,\n): number {\n if (factors.length === 0) return 0;\n let totalWeight = 0;\n let weightedSum = 0;\n for (const f of factors) {\n const w = overrides?.[f.type] ?? FACTOR_WEIGHTS[f.type] ?? 1;\n weightedSum += f.score * w;\n totalWeight += w;\n }\n const avg = Math.round(weightedSum / totalWeight);\n return Math.min(100, Math.max(0, avg));\n}\n\n// ---------------------------------------------------------------------------\n// Risk scoring (pure — no API calls)\n// ---------------------------------------------------------------------------\n\nexport function computeRiskScore(\n files: FileInfo[],\n config?: RiskConfig | null,\n): {\n score: number;\n factors: RiskFactorResult[];\n} {\n if (files.length === 0) {\n return { score: 0, factors: [] };\n }\n\n const ignorePatterns = config?.ignore ?? [];\n const effectiveFiles =\n ignorePatterns.length > 0\n ? files.filter((f) => !matchesGlobs(f.filename, ignorePatterns))\n : files;\n\n if (effectiveFiles.length === 0) {\n return { score: 0, factors: [] };\n }\n\n const factors: RiskFactorResult[] = [];\n const customWeights = config?.weights ?? {};\n\n const fileCount = effectiveFiles.length;\n const fileCountScore = Math.min(100, Math.round(30 * Math.log2(1 + fileCount)));\n factors.push({\n type: \"file_count\",\n score: fileCountScore,\n detail: { fileCount, description: \"Number of files changed\" },\n });\n\n const totalChanges = effectiveFiles.reduce((sum, f) => sum + f.changes, 0);\n const weightedChanges = effectiveFiles.reduce(\n (sum, f) => sum + f.changes * sensitivityWeight(f.filename, config),\n 0,\n );\n const churnScore = Math.min(100, Math.round(25 * Math.log2(1 + weightedChanges / 50)));\n factors.push({\n type: \"code_churn\",\n score: churnScore,\n detail: {\n totalChanges,\n weightedChanges: Math.round(weightedChanges),\n description: \"Sensitivity-weighted lines changed\",\n },\n });\n\n const testFileCount = effectiveFiles.filter((f) => isTestFile(f.filename)).length;\n const nonSourceCount = effectiveFiles.filter(\n (f) => !isTestFile(f.filename) && isNonSourceFile(f.filename),\n ).length;\n const sourceFileCount = effectiveFiles.length - testFileCount - nonSourceCount;\n if (sourceFileCount > 0) {\n const testRatio = testFileCount / sourceFileCount;\n const testCoverageScore =\n testFileCount === 0\n ? 100\n : Math.round(\n Math.max(0, 100 - testRatio * 100 - Math.min(testFileCount, 5) * 10),\n );\n factors.push({\n type: \"test_coverage\",\n score: testCoverageScore,\n detail: {\n testFiles: testFileCount,\n sourceFiles: sourceFileCount,\n nonSourceFiles: nonSourceCount,\n testRatio: Math.round(testRatio * 100) / 100,\n },\n });\n }\n\n const highSensPatterns = config?.sensitivity?.high ?? [];\n const sensitiveByConfig =\n highSensPatterns.length > 0\n ? effectiveFiles.filter((f) => matchesGlobs(f.filename, highSensPatterns))\n : [];\n const sensitiveByDefault = effectiveFiles.filter((f) => isSensitiveFile(f.filename));\n const sensitiveFilenames = new Set([\n ...sensitiveByConfig.map((f) => f.filename),\n ...sensitiveByDefault.map((f) => f.filename),\n ]);\n const sensitiveFiles = effectiveFiles.filter((f) => sensitiveFilenames.has(f.filename));\n\n if (sensitiveFiles.length > 0) {\n const sensitiveScore = Math.min(100, sensitiveFiles.length * 25);\n factors.push({\n type: \"sensitive_files\",\n score: sensitiveScore,\n detail: {\n count: sensitiveFiles.length,\n files: sensitiveFiles.map((f) => f.filename),\n description: \"High-risk files (migrations, auth, payments, CI)\",\n },\n });\n }\n\n return { score: weightedAverageScores(factors, customWeights), factors };\n}\n\n// ---------------------------------------------------------------------------\n// Dependency change detection\n// ---------------------------------------------------------------------------\n\nexport function detectDependencyChanges(files: FileInfo[]): RiskFactorResult | null {\n const depFiles = files.filter((f) =>\n DEPENDENCY_FILES.some((p) => p.test(f.filename.replace(/.*\\//, \"\"))),\n );\n if (depFiles.length === 0) return null;\n\n const isLockfile = (filename: string): boolean =>\n /\\.(lock|sum)$|lock\\.(json|yaml)$/.test(filename);\n\n const packageJsonTouchesDependencies = (patch?: string): boolean => {\n if (!patch) return true;\n let activeSection: string | null = null;\n let sectionDepth = 0;\n\n for (const rawLine of patch.split(\"\\n\")) {\n if (rawLine.startsWith(\"@@\")) continue;\n const prefix = rawLine[0];\n if (prefix !== \" \" && prefix !== \"+\" && prefix !== \"-\") continue;\n\n const line = rawLine.slice(1);\n const sectionMatch = line.match(/^\\s*\"([^\"]+)\"\\s*:\\s*\\{\\s*$/);\n if (sectionMatch) {\n const key = sectionMatch[1];\n if (PACKAGE_JSON_DEPENDENCY_FIELDS.has(key)) {\n activeSection = key;\n sectionDepth = 1;\n if (prefix !== \" \") return true;\n continue;\n }\n }\n\n if (!activeSection) continue;\n\n const openCount = (line.match(/\\{/g) ?? []).length;\n const closeCount = (line.match(/\\}/g) ?? []).length;\n sectionDepth += openCount - closeCount;\n\n if (prefix !== \" \" && /^\\s*\"[^\"]+\"\\s*:\\s*\".*\"\\s*,?\\s*$/.test(line)) {\n return true;\n }\n\n if (sectionDepth <= 0) {\n activeSection = null;\n sectionDepth = 0;\n }\n }\n\n return false;\n };\n\n const relevantDepFiles = depFiles.filter((f) => {\n const base = f.filename.replace(/.*\\//, \"\");\n if (base === \"package.json\") {\n return packageJsonTouchesDependencies(f.patch);\n }\n return true;\n });\n\n if (relevantDepFiles.length === 0) return null;\n\n const hasLockfile = relevantDepFiles.some((f) => isLockfile(f.filename));\n const hasManifest = relevantDepFiles.some((f) => !isLockfile(f.filename));\n const totalChanges = relevantDepFiles.reduce((s, f) => s + f.changes, 0);\n\n const score = Math.min(\n 100,\n (hasManifest && hasLockfile ? 40 : hasManifest ? 60 : 20) +\n Math.min(30, Math.round(totalChanges / 100)),\n );\n\n return {\n type: \"dependency_changes\",\n score,\n detail: {\n files: relevantDepFiles.map((f) => f.filename),\n hasManifest,\n hasLockfile,\n totalChanges,\n description: \"Dependency manifests/lockfiles changed\",\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Security alerts risk factor (computed from pre-fetched alert counts)\n// ---------------------------------------------------------------------------\n\nexport function computeSecurityFactor(\n alerts: SecurityAlertCounts,\n): RiskFactorResult | null {\n if (alerts.total === 0) return null;\n\n const score = Math.min(\n 100,\n alerts.critical * 30 + alerts.high * 15 + alerts.medium * 5 + alerts.low * 1,\n );\n\n return {\n type: \"security_alerts\",\n score,\n detail: {\n critical: alerts.critical,\n high: alerts.high,\n medium: alerts.medium,\n low: alerts.low,\n total: alerts.total,\n topRules: alerts.topRules,\n description: `${alerts.total} open security alert(s)`,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Deployment history risk factor\n// ---------------------------------------------------------------------------\n\nexport function computeDeploymentHistoryFactor(\n outcomes: DeploymentOutcomeSummary,\n): RiskFactorResult | null {\n if (outcomes.recentTotal === 0) return null;\n\n let score = 0;\n const reasons: string[] = [];\n\n if (outcomes.recentFailures > 0) {\n score += Math.min(40, outcomes.recentFailures * 20);\n reasons.push(`${outcomes.recentFailures} recent failure(s)`);\n }\n if (outcomes.lastRollback) {\n score += 30;\n reasons.push(\"last deploy was rolled back\");\n }\n if (outcomes.lastDeployFailed) {\n score += 20;\n reasons.push(\"last deploy failed\");\n }\n\n score = Math.min(100, score);\n if (score === 0) return null;\n\n return {\n type: \"deployment_history\",\n score,\n detail: {\n recentFailures: outcomes.recentFailures,\n recentTotal: outcomes.recentTotal,\n lastDeployFailed: outcomes.lastDeployFailed,\n lastRollback: outcomes.lastRollback,\n description: reasons.join(\"; \"),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Release freeze window check\n// ---------------------------------------------------------------------------\n\nexport interface FreezeWindowDef {\n days: string[];\n afterHour?: number;\n beforeHour?: number;\n timezone?: string;\n message?: string;\n}\n\nconst DAY_NAMES = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n];\n\nexport function isInFreezeWindow(\n freezes: FreezeWindowDef[],\n now?: Date,\n): { frozen: boolean; message?: string } {\n if (freezes.length === 0) return { frozen: false };\n\n const d = now ?? new Date();\n\n for (const freeze of freezes) {\n const dayName = DAY_NAMES[d.getUTCDay()];\n const matchesDay =\n freeze.days.length === 0 || freeze.days.some((fd) => fd.toLowerCase() === dayName);\n\n if (!matchesDay) continue;\n\n const hour = d.getUTCHours();\n const afterOk = freeze.afterHour === undefined || hour >= freeze.afterHour;\n const beforeOk = freeze.beforeHour === undefined || hour < freeze.beforeHour;\n\n if (afterOk && beforeOk) {\n return {\n frozen: true,\n message: freeze.message ?? `Deployment frozen (${dayName} ${hour}:00 UTC)`,\n };\n }\n }\n\n return { frozen: false };\n}\n\n// ---------------------------------------------------------------------------\n// Gate decision\n// ---------------------------------------------------------------------------\n\nexport type GateDecisionValue = \"allow\" | \"warn\" | \"block\";\n\nexport function decideGate(\n riskScore: number,\n healthScore: number,\n blockThreshold: number,\n warnThreshold?: number,\n): GateDecisionValue {\n const effectiveWarn = warnThreshold ?? blockThreshold - 15;\n if (riskScore > blockThreshold) return \"block\";\n if (riskScore > effectiveWarn || healthScore < 50) return \"warn\";\n return \"allow\";\n}\n\n// ---------------------------------------------------------------------------\n// Rollback detection\n// ---------------------------------------------------------------------------\n\nexport function isRollback(prTitle: string): boolean {\n return /\\brevert\\b/i.test(prTitle) || /\\brollback\\b/i.test(prTitle);\n}\n","// Default submission detector policy data (Komatik fleet rename vocabulary).\n\nexport interface RenamePatternEntry {\n oldName: string;\n newName: string;\n pattern: RegExp;\n}\n\nexport const DEFAULT_RENAME_PATTERNS: RenamePatternEntry[] = [\n { oldName: \"DeployGuard\", newName: \"Trailhead\", pattern: /\\bDeployGuard\\b/g },\n { oldName: \"Daydream Studio\", newName: \"Sundog\", pattern: /\\bDaydream Studio\\b/g },\n {\n oldName: \"Storyboard Studio\",\n newName: \"Kindling\",\n pattern: /\\bStoryboard Studio\\b/g,\n },\n { oldName: \"Cognitive Debt\", newName: \"Drift\", pattern: /\\bCognitive Debt\\b/g },\n { oldName: \"cognitive-debt\", newName: \"Drift\", pattern: /\\bcognitive-debt\\b/g },\n { oldName: \"Undercurrent\", newName: \"Slipstream\", pattern: /\\bUndercurrent\\b/g },\n { oldName: \"Yggdrasil\", newName: \"Cairn\", pattern: /\\bYggdrasil\\b/g },\n { oldName: \"Bored\", newName: \"Lodge\", pattern: /\\bBored\\b/g },\n { oldName: \"Forge\", newName: \"Pack\", pattern: /\\bForge\\b/g },\n];\n\n/** @deprecated use DEFAULT_RENAME_PATTERNS */\nexport const OLD_NAME_PATTERNS = DEFAULT_RENAME_PATTERNS;\n\nexport const DEFAULT_SLUG_ONLY_PATTERN_SOURCES = [\n \"\\\\bcognitive-debt\\\\b\",\n \"\\\\bstoryboard-studio\\\\b\",\n \"\\\\bdaydream-studio\\\\b\",\n \"\\\\bshadow-ai-governance\\\\b\",\n];\n\nexport const DEFAULT_ARTIFACT_FILE_GLOBS = [\"**/*.{ts,tsx,js,jsx,mjs,cjs}\"];\n\nfunction escapeRegexLiteral(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport function compileRenamePattern(\n oldName: string,\n newName: string,\n): RenamePatternEntry {\n return {\n oldName,\n newName,\n pattern: new RegExp(`\\\\b${escapeRegexLiteral(oldName)}\\\\b`, \"g\"),\n };\n}\n\nexport function compileSlugOnlyPatterns(sources: string[]): RegExp[] {\n return sources.map((source) => new RegExp(source, \"i\"));\n}\n","// Resolve submission detector policy from `.trailhead.yml` (issue #256).\n\nimport type {\n RemediationSeverity,\n SubmissionCheckCode,\n SubmissionConfig,\n SubmissionDetectorPolicyEntry,\n} from \"../types.js\";\nimport { SubmissionCheckCode as SubmissionCheckCodeEnum } from \"../types.js\";\nimport {\n compileRenamePattern,\n compileSlugOnlyPatterns,\n DEFAULT_ARTIFACT_FILE_GLOBS,\n DEFAULT_RENAME_PATTERNS,\n DEFAULT_SLUG_ONLY_PATTERN_SOURCES,\n type RenamePatternEntry,\n} from \"./policy-defaults.js\";\n\nexport type DetectorPolicyEntry = {\n enabled?: boolean;\n severity?: RemediationSeverity;\n fileGlobs?: string[];\n pathIgnore?: string[];\n};\n\nexport type DetectorPolicyMap = Partial<Record<SubmissionCheckCode, DetectorPolicyEntry>>;\n\nfunction normalizeSeverity(\n severity: NonNullable<SubmissionDetectorPolicyEntry[\"severity\"]>,\n): RemediationSeverity {\n if (severity === \"block\") return \"blocking\";\n return severity as RemediationSeverity;\n}\n\nexport function resolveDetectorPolicy(submission?: Partial<SubmissionConfig>): {\n policy: DetectorPolicyMap;\n warnings: string[];\n} {\n const raw = submission?.detectors ?? {};\n const warnings: string[] = [];\n const policy: DetectorPolicyMap = {};\n\n for (const [key, value] of Object.entries(raw)) {\n const parsed = SubmissionCheckCodeEnum.safeParse(key);\n if (!parsed.success) {\n warnings.push(`Unknown submission.detectors key \"${key}\" will be ignored.`);\n continue;\n }\n if (!value || typeof value !== \"object\") continue;\n\n policy[parsed.data] = {\n enabled: value.enabled,\n severity: value.severity ? normalizeSeverity(value.severity) : undefined,\n fileGlobs: value.file_globs,\n pathIgnore: value.path_ignore,\n };\n }\n\n return { policy, warnings };\n}\n\nexport function buildRenamePatterns(\n submission?: Partial<SubmissionConfig>,\n options?: { includeKomatikDefaults?: boolean },\n): RenamePatternEntry[] {\n const custom = (submission?.rename_patterns ?? []).map(({ old, new: newName }) =>\n compileRenamePattern(old, newName),\n );\n const defaults = options?.includeKomatikDefaults ? DEFAULT_RENAME_PATTERNS : [];\n return [...defaults, ...custom];\n}\n\nexport function buildSlugOnlyPatterns(submission?: Partial<SubmissionConfig>): RegExp[] {\n const sources = [\n ...DEFAULT_SLUG_ONLY_PATTERN_SOURCES,\n ...(submission?.slug_only_patterns ?? []),\n ];\n return compileSlugOnlyPatterns(sources);\n}\n\nexport function artifactFileGlobs(policy: DetectorPolicyMap): string[] {\n return policy.artifact_integrity?.fileGlobs ?? DEFAULT_ARTIFACT_FILE_GLOBS;\n}\n\nexport function applyDetectorPolicy(\n code: SubmissionCheckCode,\n check: import(\"../types.js\").SubmissionCheckResult | null,\n policy: DetectorPolicyMap,\n): import(\"../types.js\").SubmissionCheckResult | null {\n const entry = policy[code];\n if (entry?.enabled === false) return null;\n if (!check) return null;\n if (entry?.severity) {\n return { ...check, severity: entry.severity };\n }\n return check;\n}\n\nexport function getSubmissionConfigWarnings(\n submission?: Partial<SubmissionConfig>,\n): string[] {\n return resolveDetectorPolicy(submission).warnings;\n}\n","// Gate 1 detectors — ported from komatik-agents agent-gate-checks (patch/content based).\n\nimport type { SubmissionCheckResult, SubmissionCheckCode } from \"../types.js\";\nimport type { SubmissionCheckContext } from \"./types.js\";\nimport {\n addedLines,\n extensionOf,\n extractAllImports,\n fileContent,\n isStaleArchivedPath,\n isTestPath,\n lineCountFromPatch,\n linesForFreshnessScan,\n normalizePath,\n scanAddedContent,\n} from \"./helpers.js\";\nimport type { NamingAllowlistConfig } from \"./types.js\";\nimport { runPhase0Detectors } from \"./phase0-detectors.js\";\nimport { detectContractIntegrity } from \"./contract-integrity.js\";\nimport { detectSafeDeprecation } from \"./safe-deprecation.js\";\nimport { detectDestructiveChange } from \"./destructive-change.js\";\nimport { detectClaimAnchoring } from \"./claim-anchoring.js\";\nimport { detectPromotionCoherence } from \"./promotion-coherence.js\";\nimport { validateFileSyntax } from \"./syntax-validity.js\";\nimport { matchesGlobs } from \"../risk-engine.js\";\nimport { applyDetectorPolicy, artifactFileGlobs } from \"./detector-policy.js\";\nexport { DEFAULT_RENAME_PATTERNS, OLD_NAME_PATTERNS } from \"./policy-defaults.js\";\n\nconst MOCK_PATTERNS = [\n /\\bTODO\\s*\\(\\s*mock\\s*\\)/i,\n /\\bFIXME\\s*\\(\\s*mock\\s*\\)/i,\n /\\bMOCK_[A-Z0-9_]+\\b/,\n /\\bfakeImplementation\\b/,\n /\\bstubResponse\\s*\\(/i,\n /\\b(?:generate|create|build|get)(?:Mock|Fake|Dummy|Sample)\\w*/g,\n /\\b(?:mockData|fakeData|sampleData|dummyData|testData)\\b/g,\n /\\bTODO:\\s*implement\\b/gi,\n /\\bFIXME\\b/g,\n /\\bIn production,\\s*use\\b/i,\n /\\bplaceholder\\b/gi,\n /\\blorem ipsum\\b/gi,\n];\n\nconst SECRET_PATTERNS: Array<{ name: string; pattern: RegExp }> = [\n { name: \"AWS access key\", pattern: /\\bAKIA[0-9A-Z]{16}\\b/g },\n { name: \"GitHub token\", pattern: /\\bgh[pousr]_[A-Za-z0-9_]{20,}\\b/g },\n { name: \"Stripe live key\", pattern: /\\bsk_live_[A-Za-z0-9]{10,}\\b/g },\n { name: \"Stripe test key\", pattern: /\\bsk_test_[A-Za-z0-9]{10,}\\b/g },\n { name: \"Private key block\", pattern: /-----BEGIN [A-Z ]+PRIVATE KEY-----/g },\n {\n name: \"Generic API key assignment\",\n pattern: /api[_-]?key\\s*[:=]\\s*['\"][A-Za-z0-9_-]{32,}['\"]/gi,\n },\n];\n\nconst HARDCODED_ENV_PATTERNS: Array<{ name: string; pattern: RegExp }> = [\n { name: \"localhost with port\", pattern: /(?:['\"`])localhost:\\d{2,5}(?:['\"`])/g },\n {\n name: \"hardcoded private IP\",\n pattern:\n /(?:['\"`])(?:10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|172\\.(?:1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}|192\\.168\\.\\d{1,3}\\.\\d{1,3})(?::\\d+)?(?:['\"`])/g,\n },\n];\n\nconst NODE_BUILTINS = new Set([\n \"assert\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"dns\",\n \"events\",\n \"fs\",\n \"http\",\n \"http2\",\n \"https\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"process\",\n \"stream\",\n \"url\",\n \"util\",\n \"zlib\",\n]);\n\nfunction result(\n partial: Omit<SubmissionCheckResult, \"autofix_eligible\"> & {\n autofix_eligible?: boolean;\n },\n): SubmissionCheckResult {\n return { autofix_eligible: false, ...partial };\n}\n\nexport function detectMockPlaceholder(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits = scanAddedContent(ctx.files, (line, filename) => {\n if (isTestPath(filename)) return false;\n if (/\\.(md|txt)$/i.test(filename)) return false;\n return MOCK_PATTERNS.some((re) => {\n re.lastIndex = 0;\n return re.test(line);\n });\n });\n if (hits.length === 0) return null;\n return result({\n code: \"mock_placeholder\",\n severity: \"blocking\",\n title: \"Mock placeholder in production path\",\n detail: `Found mock/TODO placeholder patterns in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Remove mock placeholders and implement real behavior.\",\n });\n}\n\nexport function detectSecrets(ctx: SubmissionCheckContext): SubmissionCheckResult | null {\n const hits = scanAddedContent(ctx.files, (line) =>\n SECRET_PATTERNS.some((entry) => {\n entry.pattern.lastIndex = 0;\n return entry.pattern.test(line);\n }),\n );\n if (hits.length === 0) return null;\n return result({\n code: \"secrets\",\n severity: \"blocking\",\n title: \"Potential secret in diff\",\n detail: `Added lines match secret patterns in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Remove secrets; use environment variables or a secret manager.\",\n });\n}\n\nexport function detectDestructiveSql(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const sqlFiles = ctx.files.filter((f) => extensionOf(f.filename) === \".sql\");\n const hits = scanAddedContent(sqlFiles, (line) =>\n /\\b(DROP\\s+TABLE|TRUNCATE|DELETE\\s+FROM(?![^\\n]*\\bWHERE\\b))/i.test(line),\n );\n if (hits.length === 0) return null;\n return result({\n code: \"destructive_sql\",\n severity: \"blocking\",\n title: \"Destructive SQL in migration\",\n detail: `Added SQL contains destructive statements in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action:\n \"Use additive migrations; avoid DROP/TRUNCATE without human approval.\",\n });\n}\n\n// Only code files can carry hard file references; prose (.md/.mdx/.txt) merely\n// *mentions* paths and was the dominant artifact_integrity false-positive source.\nconst ARTIFACT_BARE_IGNORE = new Set([\n \"package.json\",\n \"package-lock.json\",\n \"tsconfig.json\",\n \"readme.md\",\n]);\n\nexport function detectArtifactIntegrity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const referenced = new Set<string>();\n const fileGlobs = artifactFileGlobs(ctx.detectorPolicy);\n const pathIgnore = ctx.detectorPolicy.artifact_integrity?.pathIgnore ?? [];\n // Only treat a path *literal* inside an import/require/export-from statement\n // as a hard reference — natural-language \"see X\" / \"fix Y\" / \"update Z\" in\n // prose is not a code dependency (the old prose trigger over-flagged docs).\n const importRefPattern =\n /(?:\\bimport\\b|\\bfrom\\b|\\brequire\\s*\\(|\\bexport\\b[^'\"`]*\\bfrom\\b)\\s*['\"`]([\\w@./-]+\\.(?:ts|tsx|js|jsx|sql|yml|yaml|json))['\"`]/g;\n\n for (const file of ctx.files) {\n if (!matchesGlobs(file.filename, fileGlobs)) continue;\n if (pathIgnore.length > 0 && matchesGlobs(file.filename, pathIgnore)) continue;\n\n for (const line of addedLines(file.patch)) {\n importRefPattern.lastIndex = 0;\n for (const match of line.matchAll(importRefPattern)) {\n const candidate = match[1]?.replace(/^\\.\\//, \"\");\n if (!candidate || candidate.includes(\"*\")) continue;\n if (candidate.startsWith(\"node:\")) continue;\n // Skip bare, repo-ubiquitous manifest names (package.json, etc.).\n const base = candidate.split(\"/\").pop()?.toLowerCase() ?? \"\";\n if (!candidate.includes(\"/\") && ARTIFACT_BARE_IGNORE.has(base)) continue;\n if (!ctx.prPaths.has(candidate)) {\n referenced.add(candidate);\n }\n }\n }\n }\n\n if (referenced.size === 0) return null;\n const missing = [...referenced].slice(0, 8);\n return result({\n code: \"artifact_integrity\",\n severity: \"blocking\",\n title: \"Referenced files missing from PR\",\n detail: `Added lines reference paths not in this PR: ${missing.join(\", \")}${referenced.size > 8 ? \"…\" : \"\"}.`,\n files: missing,\n suggested_action: \"Include referenced files or fix hallucinated paths.\",\n });\n}\n\nfunction isNamingAllowlisted(\n filename: string,\n line: string,\n allowlist: NamingAllowlistConfig = {},\n slugOnlyPatterns: RegExp[] = [],\n): boolean {\n const trimmed = line.trim();\n const path = normalizePath(filename);\n const ext = extensionOf(filename);\n const skipExtensions = allowlist.skip_extensions ?? [\".sql\"];\n const skipPathPatterns = allowlist.skip_path_patterns ?? [\"migrations/\", \"schema/\"];\n const skipCommentMarkers = allowlist.skip_comment_markers ?? [\n \"historical:\",\n \"migration:\",\n \"deprecated:\",\n ];\n\n if (\n allowlist.skip_in_imports !== false &&\n /^import\\s|^from\\s|require\\(/.test(trimmed)\n ) {\n return true;\n }\n if (skipExtensions.includes(ext)) return true;\n if (skipPathPatterns.some((pattern) => path.includes(pattern))) return true;\n if (\n skipCommentMarkers.some((marker) =>\n trimmed.toLowerCase().includes(marker.toLowerCase()),\n )\n ) {\n return true;\n }\n if (/\\/memory\\//.test(path)) return true;\n if (/RESEARCH\\.md$|BRAND\\.md$|CHANGELOG\\.md$/.test(path)) return true;\n if (/^\\[.*\\]\\(.*\\)/.test(trimmed) || /\\]\\(http/.test(trimmed)) return true;\n\n if (\n slugOnlyPatterns.some((p) => p.test(trimmed)) &&\n !/[A-Z]/.test(\n trimmed.match(\n /(?:cognitive-debt|storyboard-studio|daydream-studio|shadow-ai-governance)/,\n )?.[0] ?? \"\",\n )\n ) {\n return true;\n }\n\n if (/[\"'`/]/.test(trimmed)) {\n const inStringOrPath =\n /[\"'`/][^\"'`]*(?:deployguard|storyboard-studio|daydream-studio|cognitive-debt|shadow-ai-governance|komatik-yggdrasil)[^\"'`]*[\"'`/]/i;\n if (inStringOrPath.test(trimmed)) return true;\n }\n\n return false;\n}\n\nexport function detectContextFreshness(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (ctx.staleTerms.length === 0 && ctx.renamePatterns.length === 0) {\n return null;\n }\n\n const hits: string[] = [];\n for (const file of ctx.files) {\n if (isStaleArchivedPath(file.filename, ctx.pathIgnorePatterns)) continue;\n\n for (const line of linesForFreshnessScan(file)) {\n if (\n isNamingAllowlisted(\n file.filename,\n line,\n ctx.namingAllowlist,\n ctx.slugOnlyPatterns,\n )\n ) {\n continue;\n }\n\n for (const term of ctx.staleTerms) {\n if (line.toLowerCase().includes(term.toLowerCase())) hits.push(file.filename);\n }\n\n for (const entry of ctx.renamePatterns) {\n entry.pattern.lastIndex = 0;\n if (entry.pattern.test(line)) hits.push(file.filename);\n }\n }\n }\n\n const unique = [...new Set(hits)];\n if (unique.length === 0) return null;\n return result({\n code: \"context_freshness\",\n severity: \"warn\",\n title: \"Stale naming or deprecated terms\",\n detail: `Added lines reference deprecated terms in ${unique.join(\", \")}.`,\n files: unique,\n suggested_action: \"Update naming to current product vocabulary (see BRAND.md).\",\n autofix_eligible: true,\n });\n}\n\nexport function detectPathFormat(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (!ctx.komatikInstance) return null;\n const hits = ctx.files\n .map((f) => normalizePath(f.filename))\n .filter(\n (name) =>\n /^komatik-agents\\/agents\\//.test(name) ||\n /\\/agents\\/agents\\//.test(name) ||\n (!/^agents\\/[a-z][a-z0-9-]*\\/suggestions\\//.test(name) &&\n /\\/suggestions\\//.test(name) &&\n !name.startsWith(\"agents/\")),\n );\n if (hits.length === 0) return null;\n return result({\n code: \"path_format\",\n severity: \"warn\",\n title: \"Suspicious agent suggestion path\",\n detail: `Paths should match agents/<id>/suggestions/<project>/… — found: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Use canonical agent suggestion paths without repo prefix.\",\n });\n}\n\nexport function detectHardcodedEnv(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits = scanAddedContent(ctx.files, (line, filename) => {\n if (/\\.(md|txt)$/i.test(filename)) return false;\n if (/^\\s*\\/\\/|^\\s*\\*|^\\s*#/.test(line)) return false;\n return HARDCODED_ENV_PATTERNS.some((entry) => {\n entry.pattern.lastIndex = 0;\n return entry.pattern.test(line);\n });\n });\n if (hits.length === 0) return null;\n return result({\n code: \"hardcoded_env\",\n severity: \"blocking\",\n title: \"Hardcoded environment value\",\n detail: `Added lines contain hardcoded localhost/IP patterns in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action:\n \"Use environment variables or configuration instead of hardcoded hosts.\",\n });\n}\n\nexport function detectLargeFile(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits = ctx.files\n .filter((file) => {\n const lines =\n typeof file.content === \"string\"\n ? file.content.split(\"\\n\").length\n : lineCountFromPatch(file.patch);\n return lines > ctx.maxFileLines;\n })\n .map((f) => f.filename);\n if (hits.length === 0) return null;\n return result({\n code: \"large_file\",\n severity: \"warn\",\n title: \"Large file in PR\",\n detail: `Files exceed ${ctx.maxFileLines} lines: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Split large changes into smaller PRs.\",\n });\n}\n\nfunction extractRelativeImports(content: string): string[] {\n const imports: string[] = [];\n const patterns = [\n /\\bimport\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)?['\"](\\.\\.?[^'\"]+)['\"]/g,\n /\\brequire\\(\\s*['\"](\\.\\.?[^'\"]+)['\"]\\s*\\)/g,\n ];\n for (const pattern of patterns) {\n for (const match of content.matchAll(pattern)) {\n if (match[1]) imports.push(match[1]);\n }\n }\n return imports;\n}\n\nfunction resolveRelativeImport(\n fromFile: string,\n specifier: string,\n prPaths: Set<string>,\n): boolean {\n const clean = specifier.split(\"?\")[0].split(\"#\")[0];\n const baseDir = normalizePath(fromFile).split(\"/\").slice(0, -1);\n const segments = clean.replace(/^\\.\\//, \"\").split(\"/\");\n for (const segment of segments) {\n if (segment === \"..\") baseDir.pop();\n else if (segment !== \".\") baseDir.push(segment);\n }\n const resolved = baseDir.join(\"/\");\n const candidates = [\n resolved,\n `${resolved}.ts`,\n `${resolved}.tsx`,\n `${resolved}.js`,\n `${resolved}.jsx`,\n `${resolved}/index.ts`,\n `${resolved}/index.js`,\n ];\n return candidates.some((c) => prPaths.has(c));\n}\n\nexport function detectImportResolution(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const codeExts = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n const hits: string[] = [];\n\n for (const file of ctx.files) {\n if (!codeExts.has(extensionOf(file.filename))) continue;\n const content = fileContent(file);\n for (const specifier of extractRelativeImports(content)) {\n if (!resolveRelativeImport(file.filename, specifier, ctx.prPaths)) {\n hits.push(file.filename);\n break;\n }\n }\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"import_resolution\",\n severity: \"blocking\",\n title: \"Unresolved relative import\",\n detail: `Relative imports could not be resolved within this PR: ${[...new Set(hits)].join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action: \"Add missing files to the PR or fix import paths.\",\n });\n}\n\nexport function detectRlsNewTables(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const sqlFiles = ctx.files.filter((f) => extensionOf(f.filename) === \".sql\");\n const corpus = sqlFiles.map((f) => fileContent(f)).join(\"\\n\");\n const hits: string[] = [];\n const createTable =\n /\\bCREATE\\s+(?!TEMP(?:ORARY)?\\s+)TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?((?:\"?[A-Za-z_][\\w$]*\"?\\.)?\"?[A-Za-z_][\\w$]*\"?)/gi;\n\n for (const file of sqlFiles) {\n const content = fileContent(file);\n for (const match of content.matchAll(createTable)) {\n const table = match[1]?.replace(/\"/g, \"\") ?? \"\";\n const pattern = new RegExp(\n `ALTER\\\\s+TABLE\\\\s+(?:ONLY\\\\s+)?[\"']?${table.split(\".\").pop()}[\"']?\\\\s+ENABLE\\\\s+ROW\\\\s+LEVEL\\\\s+SECURITY`,\n \"i\",\n );\n if (!pattern.test(corpus)) hits.push(file.filename);\n }\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"rls_new_tables\",\n severity: \"blocking\",\n title: \"New table missing RLS\",\n detail: `CREATE TABLE without ENABLE ROW LEVEL SECURITY in ${[...new Set(hits)].join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action:\n \"Add ALTER TABLE ... ENABLE ROW LEVEL SECURITY for every new table.\",\n });\n}\n\nfunction isRouteAllowlisted(path: string, allowlist: string[]): boolean {\n return allowlist.some((entry) => path.includes(entry.replace(/^\\//, \"\")));\n}\n\nexport function detectAuthRouteAuth(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const routePattern =\n /(?:^|\\/)(?:app\\/api\\/.+\\/route|pages\\/api\\/.+)\\.(?:ts|tsx|js|jsx)$/;\n const authPattern =\n /\\b(getUser|getSession|getServerSession|auth|requireAuth|withAuth)\\s*\\(/;\n const hits: string[] = [];\n\n for (const file of ctx.files) {\n const normalized = normalizePath(file.filename);\n if (!routePattern.test(normalized)) continue;\n if (isRouteAllowlisted(normalized, ctx.authRouteAllowlist)) continue;\n if (!authPattern.test(fileContent(file))) hits.push(normalized);\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"auth_route_auth\",\n severity: \"blocking\",\n title: \"API route missing auth check\",\n detail: `Routes appear to lack session/user verification: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Verify authenticated user before handling the request.\",\n });\n}\n\nfunction packageNameFromSpecifier(specifier: string): string {\n if (specifier.startsWith(\"@\")) return specifier.split(\"/\").slice(0, 2).join(\"/\");\n return specifier.split(\"/\")[0];\n}\n\nfunction isNodeBuiltin(specifier: string): boolean {\n const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n return NODE_BUILTINS.has(bare.split(\"/\")[0]);\n}\n\nexport function detectExternalPackageDeps(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (ctx.declaredPackages.size === 0) return null;\n const codeExts = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n const hits: string[] = [];\n\n for (const file of ctx.files) {\n if (!codeExts.has(extensionOf(file.filename))) continue;\n\n for (const imp of extractAllImports(fileContent(file))) {\n const specifier = imp.specifier;\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) continue;\n if (specifier.startsWith(\"@/\") || specifier.startsWith(\"~/\")) continue;\n if (specifier.startsWith(\"http:\") || specifier.startsWith(\"https:\")) continue;\n if (isNodeBuiltin(specifier)) continue;\n const pkg = packageNameFromSpecifier(specifier);\n if (!ctx.declaredPackages.has(pkg)) hits.push(`${file.filename} → ${pkg}`);\n }\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"external_package_deps\",\n severity: \"warn\",\n title: \"Undeclared package import\",\n detail: hits.slice(0, 6).join(\"; \"),\n files: [...new Set(hits.map((h) => h.split(\" → \")[0]))],\n suggested_action: \"Add the package to package.json or remove the import.\",\n });\n}\n\nfunction stripSqlComments(content: string): string {\n return content.replace(/--[^\\n]*/g, \"\").replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n}\n\nfunction countPlpgsqlBlockBegins(sql: string): number {\n const re = /\\bBEGIN\\b(?!\\s+(?:TRANSACTION|WORK)\\b)/gi;\n return (sql.match(re) || []).length;\n}\n\nfunction countPlpgsqlBlockEnds(sql: string): number {\n const re = /\\bEND\\s*(?!IF\\b|LOOP\\b|CASE\\b)\\s*(?:;|\\$\\$)/gi;\n return (sql.match(re) || []).length;\n}\n\nexport function detectSqlSyntaxBasic(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of ctx.files.filter((f) => extensionOf(f.filename) === \".sql\")) {\n const stripped = stripSqlComments(fileContent(file));\n const beginCount = countPlpgsqlBlockBegins(stripped);\n const endCount = countPlpgsqlBlockEnds(stripped);\n if (beginCount > 0 && beginCount > endCount) hits.push(file.filename);\n }\n if (hits.length === 0) return null;\n return result({\n code: \"sql_syntax_basic\",\n severity: \"warn\",\n title: \"SQL block balance issue\",\n detail: `Possible unclosed BEGIN block in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Verify PL/pgSQL block structure before merging.\",\n });\n}\n\nexport function detectSyntaxValidity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const errors: string[] = [];\n\n for (const file of ctx.files) {\n // Real parsers need the whole file — skip patch-only inputs (PR diff fragments).\n if (typeof file.content !== \"string\") continue;\n\n const message = validateFileSyntax(file.filename, file.content);\n if (message) errors.push(`${file.filename}: ${message}`);\n }\n\n if (errors.length === 0) return null;\n return result({\n code: \"syntax_validity\",\n severity: \"blocking\",\n title: \"Syntax error in submitted file\",\n detail: errors.slice(0, 12).join(\"; \"),\n files: errors.map((e) => e.split(\": \")[0] ?? e),\n suggested_action: \"Fix the parse error before submitting.\",\n });\n}\n\nexport function detectSoulIntegrity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (!ctx.komatikInstance) return null;\n const hits = ctx.files\n .map((f) => normalizePath(f.filename))\n .filter((name) => /^agents\\/[a-z][a-z0-9-]*\\/SOUL\\.md$/.test(name));\n if (hits.length === 0) return null;\n return result({\n code: \"soul_integrity\",\n severity: \"blocking\",\n title: \"Agent SOUL.md modified\",\n detail: `SOUL changes require human review: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Revert SOUL.md changes or request explicit human approval.\",\n });\n}\n\nexport function runAllDetectors(ctx: SubmissionCheckContext): SubmissionCheckResult[] {\n const policy = ctx.detectorPolicy;\n const finalize = (\n code: SubmissionCheckCode,\n check: SubmissionCheckResult | null,\n ): SubmissionCheckResult | null => applyDetectorPolicy(code, check, policy);\n\n const gate1 = [\n finalize(\"mock_placeholder\", detectMockPlaceholder(ctx)),\n finalize(\"secrets\", detectSecrets(ctx)),\n finalize(\"destructive_sql\", detectDestructiveSql(ctx)),\n finalize(\"syntax_validity\", detectSyntaxValidity(ctx)),\n finalize(\"import_resolution\", detectImportResolution(ctx)),\n finalize(\"rls_new_tables\", detectRlsNewTables(ctx)),\n finalize(\"auth_route_auth\", detectAuthRouteAuth(ctx)),\n finalize(\"hardcoded_env\", detectHardcodedEnv(ctx)),\n finalize(\"external_package_deps\", detectExternalPackageDeps(ctx)),\n finalize(\"sql_syntax_basic\", detectSqlSyntaxBasic(ctx)),\n finalize(\"large_file\", detectLargeFile(ctx)),\n finalize(\"artifact_integrity\", detectArtifactIntegrity(ctx)),\n finalize(\"context_freshness\", detectContextFreshness(ctx)),\n finalize(\"soul_integrity\", detectSoulIntegrity(ctx)),\n finalize(\"path_format\", detectPathFormat(ctx)),\n finalize(\"contract_integrity\", detectContractIntegrity(ctx)),\n finalize(\"safe_deprecation\", detectSafeDeprecation(ctx)),\n finalize(\"destructive_change\", detectDestructiveChange(ctx)),\n finalize(\"claim_anchoring\", detectClaimAnchoring(ctx)),\n finalize(\"promotion_coherence\", detectPromotionCoherence(ctx)),\n ].filter((check): check is SubmissionCheckResult => check !== null);\n\n const phase0 = runPhase0Detectors(ctx)\n .map((check) => finalize(check.code, check))\n .filter((check): check is SubmissionCheckResult => check !== null);\n\n return [...gate1, ...phase0];\n}\n","// Gate 1 — agent submission quality (Phase B1).\n// Pure module: no @actions/*, octokit, or Node I/O.\n\nimport { runAllDetectors } from \"./submission-checks/detectors.js\";\nimport type { SubmissionCheckContext } from \"./submission-checks/types.js\";\nimport { prPathSet } from \"./submission-checks/helpers.js\";\nimport {\n buildRenamePatterns,\n buildSlugOnlyPatterns,\n getSubmissionConfigWarnings,\n resolveDetectorPolicy,\n} from \"./submission-checks/detector-policy.js\";\nimport { SubmissionCheckCode } from \"./types.js\";\nimport type { RepoConfig, SubmissionCheckResult } from \"./types.js\";\n\nexport type { SubmissionFileInfo } from \"./submission-checks/types.js\";\nexport type { SubmissionCheckCode, SubmissionCheckResult } from \"./types.js\";\nexport { getSubmissionConfigWarnings };\n\n/** Gate 1 + Phase 0 submission check codes — keep in sync with A8 fixture manifest. */\nexport const SUBMISSION_CHECK_CODES = SubmissionCheckCode.options;\n\nconst DEFAULT_AUTH_ROUTE_ALLOWLIST = [\n \"/api/auth/\",\n \"/api/webhooks/\",\n \"/api/health/\",\n \"/api/metrics/\",\n];\n\n/** Package names declared in a package.json (legacy gate parity). */\nexport function declaredPackageNamesFromPackageJson(\n pkg: Record<string, unknown>,\n): string[] {\n const sections = [\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n \"optionalDependencies\",\n ] as const;\n return sections.flatMap((key) =>\n Object.keys((pkg[key] as Record<string, string> | undefined) ?? {}),\n );\n}\n\nexport interface SubmissionEngineOptions {\n files: import(\"./submission-checks/types.js\").SubmissionFileInfo[];\n repoConfig?: RepoConfig | null;\n komatikInstance?: boolean;\n mode?: \"warn\" | \"block\";\n /** Declared npm package names from root package.json (optional). */\n declaredPackages?: string[];\n /** Paths that exist in the target repo (e.g. `git ls-files`), optional. */\n repoPaths?: string[];\n /**\n * Org catalog entity names resolved by the caller (I/O layer) — e.g. loaded\n * from `submission.contract_integrity.catalog_index_path`. Merged with the\n * inline `known_entities` config for the `contract_integrity` detector.\n */\n catalogKnownEntities?: string[];\n /** Promotion branch topology (GITHUB_BASE_REF / GITHUB_HEAD_REF), set by the gate. */\n promotion?: { baseBranch?: string; headBranch?: string };\n}\n\nfunction buildContext(options: SubmissionEngineOptions): SubmissionCheckContext {\n const { files, repoConfig, komatikInstance = false } = options;\n const staleTerms = repoConfig?.submission?.stale_terms ?? [];\n\n const declared = new Set(options.declaredPackages ?? []);\n const { policy } = resolveDetectorPolicy(repoConfig?.submission);\n\n // contract_integrity (ADR-010): org catalog index = inline config ∪ caller-loaded.\n const inlineKnown = repoConfig?.submission?.contract_integrity?.known_entities ?? [];\n const catalogKnownEntities = new Set<string>([\n ...inlineKnown,\n ...(options.catalogKnownEntities ?? []),\n ]);\n\n return {\n files,\n prPaths: prPathSet(files),\n komatikInstance,\n staleTerms,\n namingAllowlist: repoConfig?.submission?.naming_allowlist ?? {},\n authRouteAllowlist:\n repoConfig?.submission?.auth_route_allowlist ?? DEFAULT_AUTH_ROUTE_ALLOWLIST,\n maxFileLines: repoConfig?.submission?.max_file_lines ?? 1000,\n declaredPackages: declared,\n pathIgnorePatterns: repoConfig?.submission?.path_ignore ?? [],\n renamePatterns: buildRenamePatterns(repoConfig?.submission, {\n includeKomatikDefaults: komatikInstance,\n }),\n slugOnlyPatterns: buildSlugOnlyPatterns(repoConfig?.submission),\n detectorPolicy: policy,\n repoPaths: options.repoPaths ? new Set(options.repoPaths) : undefined,\n catalogKnownEntities:\n catalogKnownEntities.size > 0 ? catalogKnownEntities : undefined,\n promotion: options.promotion,\n };\n}\n\nexport function runSubmissionGate(\n options: SubmissionEngineOptions,\n): SubmissionCheckResult[] {\n if (options.files.length === 0) return [];\n return runAllDetectors(buildContext(options));\n}\n\nexport function submissionGateShouldBlock(\n checks: SubmissionCheckResult[],\n mode: \"warn\" | \"block\" = \"block\",\n): boolean {\n if (mode !== \"block\") return false;\n return checks.some((check) => check.severity === \"blocking\");\n}\n","\nimport * as fs from \"node:fs\";\nimport { runInitWizard } from \"./init-wizard.js\";\nimport { runDoctorCommand } from \"./run-doctor.js\";\nimport {\n runSubmissionGate,\n submissionGateShouldBlock,\n} from \"./shared/submission-engine.js\";\n\nconst CLI_VERSION = \"4.4.5\";\n\nconst BOLD = \"\\x1b[1m\";\nconst GREEN = \"\\x1b[32m\";\nconst RESET = \"\\x1b[0m\";\n\nfunction print(msg: string) {\n process.stdout.write(msg + \"\\n\");\n}\n\nfunction asAddedPatch(content: string): string {\n const lines = content.split(\"\\n\");\n return `@@ -0,0 +1,${lines.length} @@\\n${lines.map((l) => `+${l}`).join(\"\\n\")}\\n`;\n}\n\nfunction runValidateSubmission(args: string[]): number {\n const inputIdx = args.indexOf(\"--input\");\n let raw: string;\n try {\n raw =\n inputIdx >= 0 && args[inputIdx + 1]\n ? fs.readFileSync(args[inputIdx + 1] as string, \"utf-8\")\n : fs.readFileSync(0, \"utf-8\");\n } catch {\n process.stderr.write(\"validate-submission: could not read input\\n\");\n return 2;\n }\n\n let payload: {\n files?: Array<{ filename: string; content?: string; patch?: string }>;\n komatikInstance?: boolean;\n komatik_instance?: boolean;\n repoPaths?: string[];\n repo_paths?: string[];\n declaredPackages?: string[];\n declared_packages?: string[];\n mode?: \"warn\" | \"block\";\n };\n try {\n payload = JSON.parse(raw);\n } catch {\n process.stderr.write(\"validate-submission: input is not valid JSON\\n\");\n return 2;\n }\n\n const mode = payload.mode ?? \"block\";\n const files = (payload.files ?? []).map((f) =>\n typeof f.content === \"string\" && !f.patch\n ? { ...f, patch: asAddedPatch(f.content) }\n : f,\n );\n const checks = runSubmissionGate({\n files,\n komatikInstance: payload.komatikInstance ?? payload.komatik_instance ?? false,\n repoPaths: payload.repoPaths ?? payload.repo_paths,\n declaredPackages: payload.declaredPackages ?? payload.declared_packages,\n mode,\n });\n\n const shouldBlock = submissionGateShouldBlock(checks, mode);\n const decision = shouldBlock\n ? \"block\"\n : checks.some((c) => c.severity === \"warn\")\n ? \"warn\"\n : \"allow\";\n\n process.stdout.write(\n JSON.stringify({ decision, shouldBlock, mode, checks }, null, 2) + \"\\n\",\n );\n return 0;\n}\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0];\n\n if (command === \"doctor\") {\n const code = await runDoctorCommand(args.slice(1));\n process.exit(code);\n }\n\n if (command === \"validate-submission\") {\n const code = runValidateSubmission(args.slice(1));\n process.exit(code);\n }\n\n if (command === \"init\") {\n const code = await runInitWizard(args.slice(1));\n process.exit(code);\n }\n\n print(`\n${BOLD}${GREEN}Trailhead CLI v${CLI_VERSION}${RESET}\n\n${BOLD}Usage:${RESET}\n npx @komatikai/trailhead init [--preset solo|team|agent|ops]\n npx @komatikai/trailhead doctor\n npx @komatikai/trailhead validate-submission\n\n${BOLD}Presets:${RESET} solo · team · agent · ops — see presets/ or docs/getting-started.md\n\n${BOLD}Learn more:${RESET}\n https://github.com/KomatikAI/trailhead\n`);\n}\n\nmain().catch((err) => {\n console.error(\"Error:\", err);\n process.exit(1);\n});\n"],"names":[],"sourceRoot":""}
1
+ {"version":3,"file":"index.js","mappings":";;AAAA;AACA;AACA;;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;;;;ACAA;AACA;;;;;;ACDA;;;ACAA;;ACAA;;;ACAA;AACA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAYA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAGA;AACA;AAEA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AAEA;AACA;AACA;AAAA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AAGA;AACA;AACA;AAGA;AAEA;AACA;AACA;AAkCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AAAA;AACA;AACA;AACA;;;AChoBA;AACA;AACA;AACA;AAQA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AAAA;;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AAEA;AAKA;AAIA;AAEA;AAKA;AAKA;AAKA;AAKA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AAEA;AAMA;AACA;AACA;AACA;AAEA;AAMA;AAKA;AACA;AACA;AAKA;AAKA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AAEA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AAKA;AACA;AAKA;AACA;AACA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AAKA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAGA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAGA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AAGA;AAAA;AACA;AACA;AAEA;AACA;;AAEA;;AAEA;;;AAGA;;;AAGA;AACA;AAEA;AACA;;;AClaA;AAUA;;AAEA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AAAA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AAAA;AAEA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAKA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAKA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAGA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACRA;AACA;AACA;AACA;AACA;AACA;;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC5mHA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACtnBA;AAGA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;;;ACtHA;;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAGA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAGA;AAEA;AACA;AAGA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAEA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;;;ACnJA;AACA;AACA;AACA;AACA;AA8BA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAOA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAKA;AAAA;AAEA;AAIA;AACA;AACA;AAEA;AAIA;AAAA;AAEA;AAIA;AACA;AAEA;AAKA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAOA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAAA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;;;ACraA;AAEA;AACA;;;;;;;;;;;;;;;;;;AAkBA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;;;ACvFA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AAIA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AACA;AAGA;AAEA;AAIA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAEA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AAAA;AACA;AACA;;;ACrJA;AACA;AAIA;AAEA;AACA;AACA;AAEA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/ZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/wHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AAYA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;;;;AAIA;AACA;AAIA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AAEA;AACA;AACA;AAMA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AAAA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AAEA;AAGA;AACA;AACA;AAGA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACrLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AASA;AAGA;AACA;AAAA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AAAA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;;;AC/HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAQA;AAGA;AACA;AAAA;AAEA;AACA;AACA;AACA;AAAA;AAEA;AAGA;AAAA;AAEA;AAGA;AAAA;AAEA;AACA;AAEA;AAAA;AAEA;AAIA;AACA;AACA;AACA;AACA;AAGA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAQA;AAGA;AACA;AAAA;AAEA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAEA;AAAA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;;;AC7GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAIA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AAAA;AACA;AAAA;AAEA;AAEA;AACA;AACA;AAGA;AAEA;AACA;AACA;AACA;AAEA;AACA;AAIA;AAEA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;;;ACnFA;;ACAA;AACA;AAEA;AACA;AACA;AAEA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;;;ACzCA;AACA;AAgEA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAIA;AAAA;AAEA;AACA;AAEA;AAAA;AACA;AAAA;AAEA;AAEA;AAIA;AACA;AAEA;AAEA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAIA;AAAA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAIA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AAEA;AASA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAAA;AACA;AAEA;AAEA;AACA;AAEA;AAEA;AACA;AACA;AACA;AAEA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAIA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAOA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAGA;AAGA;AACA;AACA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AACA;AAGA;AAAA;AAEA;AAGA;AACA;AAAA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AAEA;AACA;AACA;AAEA;AAGA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAAA;AAEA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAAA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAIA;AAAA;AAEA;AAEA;AACA;AACA;AAGA;AAAA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAQA;AAMA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;;;ACnoBA;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA;AAIA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;;;ACrDA;AAQA;AACA;AAkBA;AAGA;AAAA;AACA;AACA;AAEA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAIA;AAGA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAKA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;;;ACtGA;AAIA;AAaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AAEA;AAGA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAGA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AAAA;AACA;AAAA;AAEA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAKA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AAEA;AAEA;AAMA;AACA;AAEA;AACA;AAEA;AAAA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AACA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AAQA;AACA;AAEA;AACA;AAAA;AACA;AAEA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AAGA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AAEA;AAKA;AACA;AACA;AACA;AACA;AAAA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAEA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AAIA;AAAA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAEA;AAEA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAAA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AAEA;AACA;AAAA;AAEA;AACA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AAGA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAEA;AACA;AACA;AAAA;AAEA;AACA;AAAA;AACA;AAEA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;;;AC9pBA;AACA;AAEA;AAEA;AACA;AAMA;AAKA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AAqBA;AACA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AAEA;AAGA;AAAA;AACA;AACA;AAEA;AAIA;AAAA;AACA;AACA;;;AChHA;AACA;AACA;AACA;AAKA;AAEA;AACA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AAUA;AACA;AACA;AAAA;AACA;AACA;AACA;AAEA;AACA;AAEA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AAEA;AAGA;AACA;AAEA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AAEA;AACA;;AAEA;;;;;AAKA;;AAEA;;AAEA;AACA;AAEA;AACA;AACA;AACA","sources":["../webpack/bootstrap","../webpack/runtime/compat get default export","../webpack/runtime/define property getters","../webpack/runtime/hasOwnProperty shorthand","../webpack/runtime/compat","../external node-commonjs \"node:fs\"","../external node-commonjs \"node:readline\"","../external node-commonjs \"node:path\"",".././cli/src/generators.ts",".././cli/src/init-wizard.ts",".././cli/src/shared/ci-core.ts",".././node_modules/zod/v3/helpers/util.js",".././node_modules/zod/v3/ZodError.js",".././node_modules/zod/v3/locales/en.js",".././node_modules/zod/v3/errors.js",".././node_modules/zod/v3/helpers/errorUtil.js",".././node_modules/zod/v3/helpers/parseUtil.js",".././node_modules/zod/v3/types.js",".././cli/src/shared/types.ts",".././cli/src/shared/config-core.ts",".././cli/src/shared/release-ready.ts",".././cli/src/shared/doctor.ts",".././cli/src/run-doctor.ts",".././cli/src/shared/submission-checks/helpers.ts",".././cli/src/shared/submission-checks/phase0-detectors.ts",".././node_modules/js-yaml/dist/js-yaml.mjs",".././cli/src/shared/submission-checks/contract-integrity.ts",".././cli/src/shared/submission-checks/safe-deprecation.ts",".././cli/src/shared/submission-checks/destructive-change.ts",".././cli/src/shared/submission-checks/claim-anchoring.ts",".././cli/src/shared/submission-checks/promotion-coherence.ts","../external node-commonjs \"@swc/core\"",".././cli/src/shared/submission-checks/syntax-validity.ts",".././cli/src/shared/risk-engine.ts",".././cli/src/shared/submission-checks/policy-defaults.ts",".././cli/src/shared/submission-checks/detector-policy.ts",".././cli/src/shared/submission-checks/detectors.ts",".././cli/src/shared/submission-engine.ts",".././cli/src/index.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","\nif (typeof __webpack_require__ !== 'undefined') __webpack_require__.ab = __dirname + \"/\";","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"node:fs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"node:readline\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"node:path\");","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport type GateModeOption = \"release-ready\" | \"risk-only\" | \"advisory\";\nexport type BranchModel = \"main-only\" | \"progressive\";\nexport type AudienceId = \"solo\" | \"team\" | \"agent\" | \"ops\" | \"custom\";\n\nexport function parseCheckList(input: string, fallback: string[]): string[] {\n const list = input\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n return list.length > 0 ? list : fallback;\n}\n\nconst AUDIENCE_COMMENTS: Record<AudienceId, string> = {\n solo: \"# Preset: solo — one repo, Release Ready beyond CI green\",\n team: \"# Preset: team — progressive dev → staging → main\",\n agent: \"# Preset: agent-guard — AI-authored PR safety (submission gate)\",\n ops: \"# Preset: ops — freeze windows, health probes, DORA\",\n custom: \"# Trailhead v4 configuration\",\n};\n\nexport function generateTrailheadYml(options: {\n highSensitivity: string[];\n mediumSensitivity: string[];\n riskThreshold: number;\n warnThreshold: number;\n freezeDays: string[];\n freezeAfterHour: number | null;\n environments: Array<{ name: string; risk: number; warn: number }>;\n services: Array<{ name: string; paths: string[]; env: string }>;\n securityGate: boolean;\n canaryType: string;\n}): string {\n const lines: string[] = [\n \"# Trailhead v3 configuration\",\n \"# https://github.com/KomatikAI/trailhead\",\n \"\",\n ];\n\n if (options.highSensitivity.length > 0 || options.mediumSensitivity.length > 0) {\n lines.push(\"sensitivity:\");\n if (options.highSensitivity.length > 0) {\n lines.push(\" high:\");\n for (const p of options.highSensitivity) lines.push(` - \"${p}\"`);\n }\n if (options.mediumSensitivity.length > 0) {\n lines.push(\" medium:\");\n for (const p of options.mediumSensitivity) lines.push(` - \"${p}\"`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"thresholds:\");\n lines.push(` risk: ${options.riskThreshold}`);\n lines.push(` warn: ${options.warnThreshold}`);\n lines.push(\"\");\n\n if (options.environments.length > 0) {\n lines.push(\"environments:\");\n for (const env of options.environments) {\n lines.push(` ${env.name}:`);\n lines.push(` risk: ${env.risk}`);\n lines.push(` warn: ${env.warn}`);\n }\n lines.push(\"\");\n }\n\n if (options.services.length > 0) {\n lines.push(\"services:\");\n for (const svc of options.services) {\n lines.push(` ${svc.name}:`);\n lines.push(\" paths:\");\n for (const p of svc.paths) lines.push(` - \"${p}\"`);\n if (svc.env) lines.push(` environment: ${svc.env}`);\n }\n lines.push(\"\");\n }\n\n if (options.securityGate) {\n lines.push(\"security:\");\n lines.push(\" severity_threshold: warning\");\n lines.push(\" block_on_critical: true\");\n lines.push(\"\");\n }\n\n if (options.canaryType) {\n lines.push(\"canary:\");\n lines.push(` webhook_type: ${options.canaryType}`);\n lines.push(\"\");\n }\n\n if (options.freezeDays.length > 0 && options.freezeAfterHour !== null) {\n lines.push(\"freeze:\");\n lines.push(\" - days:\");\n for (const d of options.freezeDays) lines.push(` - \"${d}\"`);\n lines.push(` afterHour: ${options.freezeAfterHour}`);\n lines.push(` message: \"No deploys during freeze window\"`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport interface TrailheadYmlV2Options {\n audience?: AudienceId;\n gateMode: GateModeOption;\n branchModel: BranchModel;\n riskThreshold: number;\n warnThreshold: number;\n featureRisk: number;\n featureWarn: number;\n stagingRisk: number;\n stagingWarn: number;\n productionRisk: number;\n productionWarn: number;\n featureChecks: string[];\n promotionChecks: string[];\n highSensitivity: string[];\n mediumSensitivity: string[];\n freezeDays: string[];\n freezeAfterHour: number | null;\n environments: Array<{ name: string; risk: number; warn: number }>;\n services: Array<{ name: string; paths: string[]; env: string }>;\n securityGate: boolean;\n canaryType: string;\n mainContextInheritsGlobalThresholds?: boolean;\n submissionEnabled?: boolean;\n remediationEnabled?: boolean;\n agentPolicies?: boolean;\n agentBrief?: boolean;\n}\n\nexport function generateTrailheadYmlV2(options: TrailheadYmlV2Options): string {\n const audience = options.audience ?? \"custom\";\n const lines: string[] = [\n AUDIENCE_COMMENTS[audience],\n \"# https://github.com/KomatikAI/trailhead\",\n \"\",\n \"schema_version: 2\",\n \"\",\n \"gate:\",\n ` mode: ${options.gateMode}`,\n ];\n if (options.agentBrief) {\n lines.push(\" agent_brief: collapsed\");\n }\n lines.push(\n \"\",\n \"thresholds:\",\n ` risk: ${options.riskThreshold}`,\n ` warn: ${options.warnThreshold}`,\n \"\",\n );\n\n if (options.gateMode !== \"risk-only\") {\n lines.push(\"contexts:\");\n if (options.branchModel === \"progressive\") {\n lines.push(\" - name: feature\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - dev\");\n lines.push(\" - develop\");\n lines.push(\" environment: dev\");\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.featureRisk}`);\n lines.push(` warn: ${options.featureWarn}`);\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.featureChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: skip\");\n lines.push(\"\");\n lines.push(\" - name: staging-promotion\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - staging\");\n lines.push(\" environment: staging\");\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.stagingRisk}`);\n lines.push(` warn: ${options.stagingWarn}`);\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.promotionChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: fail\");\n lines.push(\"\");\n lines.push(\" - name: production-promotion\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - main\");\n lines.push(\" - master\");\n lines.push(\" environment: production\");\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.productionRisk}`);\n lines.push(` warn: ${options.productionWarn}`);\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.promotionChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: fail\");\n lines.push(\"\");\n } else {\n lines.push(\" - name: main\");\n lines.push(\" match:\");\n lines.push(\" base_branch:\");\n lines.push(\" - main\");\n lines.push(\" - master\");\n lines.push(\" environment: production\");\n if (!options.mainContextInheritsGlobalThresholds) {\n lines.push(\" thresholds:\");\n lines.push(` risk: ${options.productionRisk}`);\n lines.push(` warn: ${options.productionWarn}`);\n }\n lines.push(\" ci:\");\n lines.push(\" required_checks:\");\n for (const c of options.promotionChecks) lines.push(` - ${c}`);\n lines.push(\" missing_required: fail\");\n lines.push(\"\");\n }\n }\n\n if (options.highSensitivity.length > 0 || options.mediumSensitivity.length > 0) {\n lines.push(\"sensitivity:\");\n if (options.highSensitivity.length > 0) {\n lines.push(\" high:\");\n for (const p of options.highSensitivity) lines.push(` - \"${p}\"`);\n }\n if (options.mediumSensitivity.length > 0) {\n lines.push(\" medium:\");\n for (const p of options.mediumSensitivity) lines.push(` - \"${p}\"`);\n }\n lines.push(\"\");\n }\n\n if (options.environments.length > 0) {\n lines.push(\"environments:\");\n for (const env of options.environments) {\n lines.push(` ${env.name}:`);\n lines.push(` risk: ${env.risk}`);\n lines.push(` warn: ${env.warn}`);\n }\n lines.push(\"\");\n }\n\n if (options.services.length > 0) {\n lines.push(\"services:\");\n for (const svc of options.services) {\n lines.push(` ${svc.name}:`);\n lines.push(\" paths:\");\n for (const p of svc.paths) lines.push(` - \"${p}\"`);\n if (svc.env) lines.push(` environment: ${svc.env}`);\n }\n lines.push(\"\");\n }\n\n if (options.agentPolicies) {\n lines.push(\"policies:\");\n lines.push(\" agent_prs:\");\n lines.push(\" enabled: true\");\n lines.push(` risk_threshold: ${Math.max(0, options.warnThreshold)}`);\n lines.push(\" strict_on_unknown_provenance: true\");\n lines.push(\" require_code_owner_approval: false\");\n lines.push(\" ci_integrity:\");\n lines.push(\" mode: block\");\n lines.push(\" workflow_security:\");\n lines.push(\" mode: block\");\n lines.push(\" prompt_injection:\");\n lines.push(\" mode: block\");\n lines.push(\" pr_scope:\");\n lines.push(\" mode: warn\");\n lines.push(\" max_files: 30\");\n lines.push(\" max_changes: 1500\");\n lines.push(\"\");\n }\n\n if (options.remediationEnabled) {\n lines.push(\"remediation:\");\n lines.push(\" enabled: true\");\n lines.push(\" max_loop_rounds: 5\");\n lines.push(\"\");\n }\n\n if (options.submissionEnabled) {\n lines.push(\"submission:\");\n lines.push(\" enabled: true\");\n lines.push(\" mode: block\");\n lines.push(\"\");\n }\n\n if (options.securityGate) {\n lines.push(\"security:\");\n lines.push(\" severity_threshold: warning\");\n lines.push(\" block_on_critical: true\");\n lines.push(\"\");\n }\n\n if (options.canaryType) {\n lines.push(\"canary:\");\n lines.push(` webhook_type: ${options.canaryType}`);\n lines.push(\"\");\n }\n\n if (options.freezeDays.length > 0 && options.freezeAfterHour !== null) {\n lines.push(\"freeze:\");\n lines.push(\" - days:\");\n for (const d of options.freezeDays) lines.push(` - \"${d}\"`);\n lines.push(` afterHour: ${options.freezeAfterHour}`);\n lines.push(` message: \"No deploys during freeze window\"`);\n lines.push(\"\");\n }\n\n if (options.agentPolicies) {\n lines.push(\"override:\");\n lines.push(\" enabled: true\");\n lines.push(\" max_per_week: 5\");\n lines.push(\"\");\n lines.push(\"tuning:\");\n lines.push(\" auto_downgrade: true\");\n lines.push(\" fp_threshold: 0.15\");\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport interface WorkflowYmlOptions {\n riskThreshold: number;\n healthCheckUrls: string[];\n doraMetrics: boolean;\n doraEnvironment: string;\n otelEndpoint: string;\n evaluationStoreUrl: string;\n storeSecretName: string;\n supabaseFallback: boolean;\n securityGate: boolean;\n environment: string;\n gateMode: GateModeOption;\n waitForChecks: boolean;\n submissionGate?: boolean;\n}\n\nexport function generateWorkflowYml(options: WorkflowYmlOptions): string {\n const lines: string[] = [\n \"name: Trailhead\",\n \"\",\n \"on:\",\n \" pull_request:\",\n \" types: [opened, synchronize, reopened]\",\n \"\",\n \"permissions:\",\n \" contents: read\",\n \" pull-requests: write\",\n \" checks: write\",\n \" security-events: read\",\n \"\",\n \"jobs:\",\n \" trailhead:\",\n \" runs-on: ubuntu-latest\",\n \" steps:\",\n \" - uses: actions/checkout@v4\",\n \"\",\n \" - uses: KomatikAI/trailhead@v4\",\n \" id: gate\",\n \" with:\",\n ];\n\n if (options.gateMode !== \"risk-only\") {\n lines.push(` gate-mode: \"${options.gateMode}\"`);\n if (options.waitForChecks) {\n lines.push(' wait-for-checks: \"true\"');\n lines.push(' wait-timeout-minutes: \"30\"');\n }\n }\n\n lines.push(` risk-threshold: \"${options.riskThreshold}\"`);\n\n if (options.submissionGate) {\n lines.push(' submission-gate: \"true\"');\n }\n\n if (options.healthCheckUrls.length > 0) {\n lines.push(` health-check-urls: \"${options.healthCheckUrls.join(\",\")}\"`);\n }\n\n if (options.doraMetrics) {\n lines.push(' dora-metrics: \"true\"');\n }\n\n if (options.doraEnvironment) {\n lines.push(` dora-environment: \"${options.doraEnvironment}\"`);\n }\n\n if (options.environment) {\n lines.push(` environment: \"${options.environment}\"`);\n }\n\n if (!options.securityGate) {\n lines.push(' security-gate: \"false\"');\n }\n\n if (options.otelEndpoint) {\n lines.push(` otel-endpoint: \"${options.otelEndpoint}\"`);\n }\n\n if (options.evaluationStoreUrl) {\n lines.push(` evaluation-store-url: \"${options.evaluationStoreUrl}\"`);\n if (options.storeSecretName) {\n lines.push(\n ` evaluation-store-secret: \\${{ secrets.${options.storeSecretName} }}`,\n );\n }\n }\n\n const envLines: string[] = [];\n if (options.evaluationStoreUrl && options.storeSecretName) {\n envLines.push(\n ` EVALUATION_STORE_SECRET: \\${{ secrets.${options.storeSecretName} }}`,\n );\n }\n if (options.supabaseFallback) {\n envLines.push(` SUPABASE_URL: \\${{ secrets.SUPABASE_URL }}`);\n envLines.push(\n ` SUPABASE_SERVICE_ROLE_KEY: \\${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}`,\n );\n }\n\n if (envLines.length > 0) {\n lines.push(\" env:\");\n for (const el of envLines) lines.push(el);\n }\n\n if (options.doraMetrics) {\n lines.push(\"\");\n lines.push(\" - name: DORA outputs\");\n lines.push(\" if: always()\");\n lines.push(\" run: |\");\n lines.push(' echo \"dora-rating: ${{ steps.gate.outputs.dora-rating }}\"');\n lines.push(\n ' echo \"dora-freq: ${{ steps.gate.outputs.dora-deployment-frequency }}\"',\n );\n lines.push(\n ' echo \"dora-cfr: ${{ steps.gate.outputs.dora-change-failure-rate }}\"',\n );\n lines.push(' echo \"dora-lead: ${{ steps.gate.outputs.dora-lead-time }}\"');\n lines.push(' echo \"dora-fdrt: ${{ steps.gate.outputs.dora-fdrt }}\"');\n lines.push(\n ' echo \"dora-rework: ${{ steps.gate.outputs.dora-rework-rate }}\"',\n );\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport interface InitProfile {\n audience: AudienceId;\n gateMode: GateModeOption;\n branchModel: BranchModel;\n riskThreshold: number;\n warnThreshold: number;\n featureChecks: string[];\n promotionChecks: string[];\n highSensitivity: string[];\n mediumSensitivity: string[];\n freezeDays: string[];\n freezeAfterHour: number | null;\n environments: Array<{ name: string; risk: number; warn: number }>;\n services: Array<{ name: string; paths: string[]; env: string }>;\n securityGate: boolean;\n canaryType: string;\n healthCheckUrls: string[];\n doraMetrics: boolean;\n doraEnvironment: string;\n otelEndpoint: string;\n evaluationStoreUrl: string;\n storeSecretName: string;\n supabaseFallback: boolean;\n environment: string;\n submissionGate: boolean;\n submissionEnabled: boolean;\n remediationEnabled: boolean;\n agentPolicies: boolean;\n agentBrief: boolean;\n mainContextInheritsGlobalThresholds: boolean;\n}\n\nexport function profileFromAudience(audience: AudienceId): InitProfile {\n const base: InitProfile = {\n audience,\n gateMode: \"release-ready\",\n branchModel: \"main-only\",\n riskThreshold: 70,\n warnThreshold: 55,\n featureChecks: [\"CI\", \"Build\"],\n promotionChecks: [\"CI\", \"Build\"],\n highSensitivity: [],\n mediumSensitivity: [],\n freezeDays: [],\n freezeAfterHour: null,\n environments: [],\n services: [],\n securityGate: true,\n canaryType: \"\",\n healthCheckUrls: [],\n doraMetrics: false,\n doraEnvironment: \"\",\n otelEndpoint: \"\",\n evaluationStoreUrl: \"\",\n storeSecretName: \"\",\n supabaseFallback: false,\n environment: \"\",\n submissionGate: false,\n submissionEnabled: false,\n remediationEnabled: false,\n agentPolicies: false,\n agentBrief: false,\n mainContextInheritsGlobalThresholds: true,\n };\n\n switch (audience) {\n case \"team\":\n return {\n ...base,\n branchModel: \"progressive\",\n promotionChecks: [\"CI\", \"Build\", \"Playwright\"],\n mainContextInheritsGlobalThresholds: false,\n };\n case \"agent\":\n return {\n ...base,\n riskThreshold: 60,\n warnThreshold: 40,\n submissionGate: true,\n submissionEnabled: true,\n remediationEnabled: true,\n agentPolicies: true,\n agentBrief: true,\n mainContextInheritsGlobalThresholds: true,\n };\n case \"ops\":\n return {\n ...base,\n riskThreshold: 70,\n warnThreshold: 55,\n freezeDays: [\"friday\", \"saturday\"],\n freezeAfterHour: 15,\n canaryType: \"generic\",\n doraMetrics: true,\n environments: [\n { name: \"production\", risk: 65, warn: 50 },\n { name: \"staging\", risk: 75, warn: 55 },\n ],\n environment: \"production\",\n mainContextInheritsGlobalThresholds: false,\n };\n case \"custom\":\n return { ...base, mainContextInheritsGlobalThresholds: false };\n default:\n return base;\n }\n}\n\nexport function writeInitArtifacts(profile: InitProfile, cwd = process.cwd()): void {\n const useV2 = profile.gateMode !== \"risk-only\";\n const configContent = useV2\n ? generateTrailheadYmlV2({\n audience: profile.audience,\n gateMode: profile.gateMode,\n branchModel: profile.branchModel,\n riskThreshold: profile.riskThreshold,\n warnThreshold: profile.warnThreshold,\n featureRisk: Math.min(100, profile.riskThreshold + 5),\n featureWarn: profile.warnThreshold,\n stagingRisk: Math.max(0, profile.riskThreshold - 5),\n stagingWarn: Math.max(0, profile.warnThreshold - 10),\n productionRisk: profile.mainContextInheritsGlobalThresholds\n ? profile.riskThreshold\n : Math.max(0, profile.riskThreshold - 10),\n productionWarn: profile.mainContextInheritsGlobalThresholds\n ? profile.warnThreshold\n : Math.max(0, profile.warnThreshold - 15),\n featureChecks: profile.featureChecks,\n promotionChecks: profile.promotionChecks,\n highSensitivity: profile.highSensitivity,\n mediumSensitivity: profile.mediumSensitivity,\n freezeDays: profile.freezeDays,\n freezeAfterHour: profile.freezeAfterHour,\n environments: profile.environments,\n services: profile.services,\n securityGate: profile.securityGate,\n canaryType: profile.canaryType,\n mainContextInheritsGlobalThresholds: profile.mainContextInheritsGlobalThresholds,\n submissionEnabled: profile.submissionEnabled,\n remediationEnabled: profile.remediationEnabled,\n agentPolicies: profile.agentPolicies,\n agentBrief: profile.agentBrief,\n })\n : generateTrailheadYml({\n highSensitivity: profile.highSensitivity,\n mediumSensitivity: profile.mediumSensitivity,\n riskThreshold: profile.riskThreshold,\n warnThreshold: profile.warnThreshold,\n freezeDays: profile.freezeDays,\n freezeAfterHour: profile.freezeAfterHour,\n environments: profile.environments,\n services: profile.services,\n securityGate: profile.securityGate,\n canaryType: profile.canaryType,\n });\n\n fs.writeFileSync(path.join(cwd, \".trailhead.yml\"), configContent, \"utf-8\");\n\n const workflowDir = path.join(cwd, \".github\", \"workflows\");\n fs.mkdirSync(workflowDir, { recursive: true });\n\n const workflowContent = generateWorkflowYml({\n riskThreshold: profile.riskThreshold,\n healthCheckUrls: profile.healthCheckUrls,\n doraMetrics: profile.doraMetrics,\n doraEnvironment: profile.doraEnvironment,\n otelEndpoint: profile.otelEndpoint,\n evaluationStoreUrl: profile.evaluationStoreUrl,\n storeSecretName: profile.storeSecretName,\n supabaseFallback: profile.supabaseFallback,\n securityGate: profile.securityGate,\n environment: profile.environment,\n gateMode: profile.gateMode,\n waitForChecks: profile.gateMode === \"release-ready\",\n submissionGate: profile.submissionGate,\n });\n\n const workflowPath = path.join(workflowDir, \"trailhead.yml\");\n if (fs.existsSync(workflowPath)) {\n fs.writeFileSync(\n path.join(workflowDir, \"trailhead-generated.yml\"),\n workflowContent,\n \"utf-8\",\n );\n } else {\n fs.writeFileSync(workflowPath, workflowContent, \"utf-8\");\n }\n}\n","import * as readline from \"node:readline\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n type AudienceId,\n type InitProfile,\n parseCheckList,\n profileFromAudience,\n writeInitArtifacts,\n} from \"./generators.js\";\n\nconst BOLD = \"\\x1b[1m\";\nconst GREEN = \"\\x1b[32m\";\nconst YELLOW = \"\\x1b[33m\";\nconst CYAN = \"\\x1b[36m\";\nconst RESET = \"\\x1b[0m\";\nconst DIM = \"\\x1b[2m\";\n\nfunction print(msg: string) {\n process.stdout.write(msg + \"\\n\");\n}\n\nfunction ask(\n rl: readline.Interface,\n question: string,\n defaultValue?: string,\n): Promise<string> {\n const suffix = defaultValue ? ` ${DIM}(${defaultValue})${RESET}` : \"\";\n return new Promise((resolve) => {\n rl.question(` ${question}${suffix}: `, (answer) => {\n resolve(answer.trim() || defaultValue || \"\");\n });\n });\n}\n\nfunction askYN(\n rl: readline.Interface,\n question: string,\n defaultYes: boolean,\n): Promise<boolean> {\n const hint = defaultYes ? \"Y/n\" : \"y/N\";\n return new Promise((resolve) => {\n rl.question(` ${question} ${DIM}(${hint})${RESET}: `, (answer) => {\n const a = answer.trim().toLowerCase();\n if (a === \"\") resolve(defaultYes);\n else resolve(a === \"y\" || a === \"yes\");\n });\n });\n}\n\nexport function parseInitPresetArg(args: string[]): AudienceId | undefined {\n const idx = args.indexOf(\"--preset\");\n if (idx >= 0 && args[idx + 1]) {\n const value = args[idx + 1] as AudienceId;\n if ([\"solo\", \"team\", \"agent\", \"ops\"].includes(value)) return value;\n process.stderr.write(`Unknown preset \"${value}\". Use: solo, team, agent, ops\\n`);\n process.exit(2);\n }\n return undefined;\n}\n\nasync function runCustomWizard(\n rl: readline.Interface,\n profile: InitProfile,\n): Promise<InitProfile> {\n print(`${BOLD}Gate mode${RESET}`);\n print(` ${DIM}1) release-ready — single required check (CI + risk)${RESET}`);\n print(` ${DIM}2) advisory — report only, never blocks${RESET}`);\n print(` ${DIM}3) risk-only — v3 behavior (risk score only)${RESET}`);\n const modeInput = await ask(rl, `${CYAN}Choose gate mode${RESET}`, \"1\");\n profile.gateMode =\n modeInput === \"2\" ? \"advisory\" : modeInput === \"3\" ? \"risk-only\" : \"release-ready\";\n\n if (profile.gateMode !== \"risk-only\") {\n print(`\\n${BOLD}Branch model${RESET}`);\n print(` ${DIM}1) main-only — PRs target main/master${RESET}`);\n print(` ${DIM}2) progressive — dev → staging → main promotion${RESET}`);\n const branchInput = await ask(rl, `${CYAN}Choose branch model${RESET}`, \"1\");\n profile.branchModel = branchInput === \"2\" ? \"progressive\" : \"main-only\";\n\n const featureChecksInput = await ask(\n rl,\n `${CYAN}Feature PR required checks${RESET} (comma-separated)`,\n \"CI, Build\",\n );\n profile.featureChecks = parseCheckList(featureChecksInput, profile.featureChecks);\n\n const promotionChecksInput = await ask(\n rl,\n `${CYAN}Promotion PR required checks${RESET} (comma-separated)`,\n \"CI, Build, Playwright\",\n );\n profile.promotionChecks = parseCheckList(\n promotionChecksInput,\n profile.promotionChecks,\n );\n }\n\n const riskStr = await ask(\n rl,\n `${CYAN}Risk threshold${RESET} (block above this score, 0-100)`,\n String(profile.riskThreshold),\n );\n profile.riskThreshold = Math.max(\n 0,\n Math.min(100, parseInt(riskStr, 10) || profile.riskThreshold),\n );\n\n const warnStr = await ask(\n rl,\n `${CYAN}Warn threshold${RESET} (warn above this score)`,\n String(profile.warnThreshold),\n );\n profile.warnThreshold = Math.max(\n 0,\n Math.min(100, parseInt(warnStr, 10) || profile.warnThreshold),\n );\n\n print(\n `\\n${BOLD}Sensitive file patterns${RESET} ${DIM}(files that carry extra risk weight)${RESET}`,\n );\n const highInput = await ask(rl, \"High-sensitivity globs (comma-separated)\", \"\");\n profile.highSensitivity = highInput\n ? highInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n\n const medInput = await ask(rl, \"Medium-sensitivity globs (comma-separated)\", \"\");\n profile.mediumSensitivity = medInput\n ? medInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n\n const wantEnvs = await askYN(rl, \"Configure environment-specific thresholds?\", false);\n if (wantEnvs) {\n const envsInput = await ask(\n rl,\n \"Environment names (comma-separated)\",\n \"production,staging\",\n );\n const envNames = envsInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n profile.environments = [];\n for (const name of envNames) {\n const r = await ask(rl, ` ${name} risk threshold`, String(profile.riskThreshold));\n const w = await ask(rl, ` ${name} warn threshold`, String(parseInt(r, 10) - 15));\n profile.environments.push({\n name,\n risk: parseInt(r, 10) || profile.riskThreshold,\n warn: parseInt(w, 10) || profile.warnThreshold - 15,\n });\n }\n profile.environment = envNames[0] ?? \"\";\n }\n\n const wantServices = await askYN(rl, \"Configure service boundaries (monorepo)?\", false);\n if (wantServices) {\n const svcInput = await ask(rl, \"Service names (comma-separated)\", \"api,web\");\n const svcNames = svcInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n profile.services = [];\n for (const name of svcNames) {\n const p = await ask(rl, ` ${name} path globs (comma-separated)`, `src/${name}/**`);\n const e = await ask(rl, ` ${name} environment`, \"\");\n profile.services.push({\n name,\n paths: p\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean),\n env: e,\n });\n }\n }\n\n const healthInput = await ask(\n rl,\n `${CYAN}Health check URLs${RESET} (comma-separated, or blank)`,\n \"\",\n );\n profile.healthCheckUrls = healthInput\n ? healthInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n\n profile.doraMetrics = await askYN(rl, `${CYAN}Enable DORA-5 metrics?${RESET}`, false);\n if (profile.doraMetrics) {\n profile.doraEnvironment = await ask(\n rl,\n `${CYAN}DORA environment filter${RESET} (blank for all)`,\n profile.environment || \"\",\n );\n }\n\n profile.securityGate = await askYN(\n rl,\n `${CYAN}Enable security alerts gate?${RESET} ${DIM}(requires Code Scanning)${RESET}`,\n true,\n );\n\n const wantCanary = await askYN(rl, \"Configure deployment outcome webhooks?\", false);\n profile.canaryType = wantCanary\n ? await ask(rl, \"Webhook type (vercel/generic)\", \"vercel\")\n : \"\";\n\n profile.otelEndpoint = await ask(\n rl,\n `${CYAN}OTLP endpoint${RESET} (blank to skip)`,\n \"\",\n );\n\n const wantStore = await askYN(\n rl,\n `${CYAN}POST evaluations to a trend-store URL?${RESET}`,\n false,\n );\n if (wantStore) {\n profile.evaluationStoreUrl = await ask(rl, \"Store URL\", \"\");\n profile.storeSecretName = await ask(\n rl,\n \"GitHub Actions secret name for Bearer token\",\n \"INTERNAL_API_SECRET\",\n );\n profile.supabaseFallback = await askYN(\n rl,\n \"Include Supabase direct-insert fallback env vars?\",\n false,\n );\n }\n\n const wantFreeze = await askYN(rl, \"Configure a release freeze window?\", false);\n if (wantFreeze) {\n const daysInput = await ask(rl, \"Freeze days (e.g. friday,saturday)\", \"friday\");\n profile.freezeDays = daysInput\n .split(\",\")\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean);\n const hourStr = await ask(rl, \"Freeze after hour (0-23, UTC)\", \"15\");\n profile.freezeAfterHour = Math.max(0, Math.min(23, parseInt(hourStr, 10) || 15));\n }\n\n profile.submissionEnabled = await askYN(\n rl,\n \"Enable submission gate (Gate 1) for agent PRs?\",\n false,\n );\n profile.submissionGate = profile.submissionEnabled;\n if (profile.submissionEnabled) {\n profile.remediationEnabled = await askYN(rl, \"Enable remediation payloads?\", true);\n profile.agentPolicies = await askYN(rl, \"Enable agent PR policies?\", true);\n profile.agentBrief = await askYN(rl, \"Collapsed agent brief in PR comments?\", true);\n }\n\n return profile;\n}\n\nasync function runAudienceWizard(\n rl: readline.Interface,\n audience: AudienceId,\n): Promise<InitProfile> {\n const profile = profileFromAudience(audience);\n\n switch (audience) {\n case \"solo\": {\n const checks = await ask(\n rl,\n `${CYAN}Required CI check names${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(checks, profile.promotionChecks);\n break;\n }\n case \"team\": {\n const feature = await ask(\n rl,\n `${CYAN}Feature PR required checks${RESET} (comma-separated)`,\n profile.featureChecks.join(\", \"),\n );\n profile.featureChecks = parseCheckList(feature, profile.featureChecks);\n const promo = await ask(\n rl,\n `${CYAN}Promotion PR required checks${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(promo, profile.promotionChecks);\n break;\n }\n case \"agent\": {\n const checks = await ask(\n rl,\n `${CYAN}Required CI check names${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(checks, profile.promotionChecks);\n break;\n }\n case \"ops\": {\n const checks = await ask(\n rl,\n `${CYAN}Required CI check names${RESET} (comma-separated)`,\n profile.promotionChecks.join(\", \"),\n );\n profile.promotionChecks = parseCheckList(checks, profile.promotionChecks);\n const healthInput = await ask(\n rl,\n `${CYAN}Production health check URLs${RESET} (comma-separated, recommended)`,\n \"\",\n );\n profile.healthCheckUrls = healthInput\n ? healthInput\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n const keepFreeze = await askYN(\n rl,\n \"Keep default freeze (Friday–Saturday after 15:00 UTC)?\",\n true,\n );\n if (!keepFreeze) {\n profile.freezeDays = [];\n profile.freezeAfterHour = null;\n }\n profile.doraMetrics = await askYN(rl, \"Enable DORA-5 metrics in workflow?\", true);\n break;\n }\n default:\n return runCustomWizard(rl, profile);\n }\n\n return profile;\n}\n\nexport async function runInitWizard(args: string[]): Promise<number> {\n const preset = parseInitPresetArg(args);\n const cwd = process.cwd();\n\n if (preset) {\n const profile = profileFromAudience(preset);\n writeInitArtifacts(profile, cwd);\n print(\n `\\n${GREEN}✓${RESET} Wrote .trailhead.yml and workflow from preset: ${BOLD}${preset}${RESET}\\n`,\n );\n return 0;\n }\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n print(`\\n${BOLD}${GREEN}Trailhead v4 Setup Wizard${RESET}\\n`);\n print(`${DIM}Creates .trailhead.yml and .github/workflows/trailhead.yml${RESET}\\n`);\n\n print(`${BOLD}What are you protecting?${RESET}`);\n print(` ${DIM}1) Solo / small team — one repo, Release Ready beyond CI green${RESET}`);\n print(\n ` ${DIM}2) Platform / eng lead — standard policy across repos (dev→staging→main)${RESET}`,\n );\n print(` ${DIM}3) AI-authored PRs — submission gate before merge${RESET}`);\n print(` ${DIM}4) Production ops — freeze windows, health probes, DORA${RESET}`);\n print(` ${DIM}5) Custom — full advanced wizard (all options)${RESET}`);\n\n const audienceInput = await ask(rl, `${CYAN}Choose setup path${RESET}`, \"1\");\n const audience: AudienceId =\n audienceInput === \"2\"\n ? \"team\"\n : audienceInput === \"3\"\n ? \"agent\"\n : audienceInput === \"4\"\n ? \"ops\"\n : audienceInput === \"5\"\n ? \"custom\"\n : \"solo\";\n\n const profile =\n audience === \"custom\"\n ? await runCustomWizard(rl, profileFromAudience(\"custom\"))\n : await runAudienceWizard(rl, audience);\n\n rl.close();\n\n print(`\\n${BOLD}Writing files...${RESET}\\n`);\n writeInitArtifacts(profile, cwd);\n\n print(` ${GREEN}✓${RESET} .trailhead.yml`);\n\n const workflowPath = path.join(cwd, \".github\", \"workflows\", \"trailhead.yml\");\n if (fs.existsSync(workflowPath)) {\n print(\n ` ${YELLOW}⚠${RESET} .github/workflows/trailhead.yml already exists — wrote trailhead-generated.yml`,\n );\n } else {\n print(` ${GREEN}✓${RESET} .github/workflows/trailhead.yml`);\n }\n\n print(`\n${BOLD}${GREEN}Setup complete!${RESET}\n\n${BOLD}Preset:${RESET} ${profile.audience} · See presets/${profile.audience === \"agent\" ? \"agent-guard\" : profile.audience}.yml\n\n${BOLD}Next steps:${RESET}\n 1. Review the generated files\n 2. Commit and push\n 3. Require ${BOLD}Trailhead — Release Ready${RESET} in branch protection\n 4. trailhead doctor --offline\n\n${DIM}Docs: docs/getting-started.md · https://github.com/KomatikAI/trailhead${RESET}\n`);\n\n return 0;\n}\n","import type { CiCheck, CiCheckStatusEnum, CiSummary, ContextCiConfig } from \"./types.js\";\nimport type { CiManifest, CiManifestJob } from \"./ci-manifest.js\";\n\nexport const DEFAULT_SELF_CHECK_NAMES = [\"Trailhead\", \"Trailhead — Release Ready\"];\n\nexport interface RawCheckRun {\n name: string;\n status: string;\n conclusion: string | null;\n html_url?: string | null;\n details_url?: string | null;\n}\n\n/**\n * Map GitHub check conclusion/status to Trailhead CI status (ADR-009).\n */\nexport function classifyCheck(\n status: string,\n conclusion: string | null,\n): CiCheckStatusEnum {\n if (status === \"completed\") {\n switch (conclusion) {\n case \"success\":\n return \"pass\";\n case \"skipped\":\n case \"neutral\":\n return \"skip\";\n case \"failure\":\n case \"timed_out\":\n case \"action_required\":\n case \"cancelled\":\n return \"fail\";\n default:\n return \"pending\";\n }\n }\n if (status === \"in_progress\" || status === \"queued\" || status === \"pending\") {\n return \"pending\";\n }\n return \"pending\";\n}\n\nfunction isSelfCheck(name: string, excludeNames: string[]): boolean {\n const lower = name.toLowerCase();\n return excludeNames.some((n) => n.toLowerCase() === lower);\n}\n\nexport function checkNameMatches(configured: string, actual: string): boolean {\n if (configured === actual) return true;\n if (configured.toLowerCase() === actual.toLowerCase()) return true;\n return actual.toLowerCase().startsWith(configured.toLowerCase());\n}\n\nfunction findManifestJob(\n manifest: CiManifest,\n configuredName: string,\n): CiManifestJob | undefined {\n return manifest.jobs.find((job) => checkNameMatches(configuredName, job.name));\n}\n\nfunction statusFromManifestJob(job: CiManifestJob): CiCheckStatusEnum | undefined {\n switch (job.outcome) {\n case \"passed\":\n return \"pass\";\n case \"skipped\":\n return \"skip\";\n case \"failed\":\n case \"cancelled\":\n return \"fail\";\n case \"pending\":\n return \"pending\";\n case \"ran\":\n return undefined;\n default: {\n const _exhaustive: never = job.outcome;\n return undefined;\n }\n }\n}\n\nfunction applyManifestToCheck(\n check: CiCheck,\n manifest: CiManifest | undefined,\n configuredName: string,\n): CiCheck {\n if (!manifest) return check;\n const manifestJob = findManifestJob(manifest, configuredName);\n if (!manifestJob) return check;\n\n const manifestStatus = statusFromManifestJob(manifestJob);\n if (manifestStatus === \"skip\") {\n return {\n ...check,\n status: \"skip\",\n conclusion: manifestJob.reason ?? check.conclusion,\n };\n }\n if (manifestStatus && (check.status === \"missing\" || check.status === \"pending\")) {\n return {\n ...check,\n status: manifestStatus,\n conclusion: manifestJob.reason ?? check.conclusion,\n };\n }\n return check;\n}\n\nfunction checkFromManifestOnly(\n configuredName: string,\n manifest: CiManifest,\n): CiCheck | undefined {\n const manifestJob = findManifestJob(manifest, configuredName);\n if (!manifestJob) return undefined;\n\n const status = statusFromManifestJob(manifestJob);\n if (!status) return undefined;\n\n return {\n name: configuredName,\n status,\n conclusion: manifestJob.reason,\n detailsUrl: manifestJob.details_url,\n required: false,\n };\n}\n\nexport function normalizeCheckRuns(\n runs: RawCheckRun[],\n excludeCheckNames: string[] = DEFAULT_SELF_CHECK_NAMES,\n): CiCheck[] {\n return runs\n .filter((r) => !isSelfCheck(r.name, excludeCheckNames))\n .map((r) => ({\n name: r.name,\n status: classifyCheck(r.status, r.conclusion),\n conclusion: r.conclusion ?? undefined,\n detailsUrl: r.details_url ?? r.html_url ?? undefined,\n required: false,\n }));\n}\n\nexport function evaluateRequiredChecks(\n allChecks: CiCheck[],\n ciConfig: ContextCiConfig,\n manifest?: CiManifest | null,\n): CiSummary {\n const requiredNames = ciConfig.required_checks;\n const optionalNames = ciConfig.optional_checks;\n const missingPolicy = ciConfig.missing_required;\n\n const evaluated: CiCheck[] = [];\n const seen = new Set<string>();\n\n for (const reqName of requiredNames) {\n const match = allChecks.find((c) => checkNameMatches(reqName, c.name));\n if (match) {\n const resolved = applyManifestToCheck(\n { ...match, name: reqName, required: true },\n manifest ?? undefined,\n reqName,\n );\n evaluated.push(resolved);\n seen.add(match.name);\n } else if (manifest) {\n const fromManifest = checkFromManifestOnly(reqName, manifest);\n if (fromManifest) {\n evaluated.push({ ...fromManifest, name: reqName, required: true });\n } else {\n evaluated.push({\n name: reqName,\n status: missingPolicy === \"skip\" ? \"skip\" : \"missing\",\n required: true,\n });\n }\n } else {\n evaluated.push({\n name: reqName,\n status: missingPolicy === \"skip\" ? \"skip\" : \"missing\",\n required: true,\n });\n }\n }\n\n for (const optName of optionalNames) {\n const match = allChecks.find((c) => checkNameMatches(optName, c.name));\n if (match) {\n const resolved = applyManifestToCheck(\n { ...match, name: optName, required: false },\n manifest ?? undefined,\n optName,\n );\n evaluated.push(resolved);\n seen.add(match.name);\n } else if (manifest) {\n const fromManifest = checkFromManifestOnly(optName, manifest);\n if (fromManifest) {\n evaluated.push({ ...fromManifest, name: optName, required: false });\n } else {\n evaluated.push({\n name: optName,\n status: \"missing\",\n required: false,\n });\n }\n } else {\n evaluated.push({\n name: optName,\n status: \"missing\",\n required: false,\n });\n }\n }\n\n for (const check of allChecks) {\n if (!seen.has(check.name)) {\n evaluated.push({ ...check, required: false });\n }\n }\n\n const requiredChecks = evaluated.filter((c) => c.required);\n const pendingCount = requiredChecks.filter((c) => c.status === \"pending\").length;\n const failedCount = requiredChecks.filter(\n (c) => c.status === \"fail\" || c.status === \"missing\" || c.status === \"stale\",\n ).length;\n const missingCount = requiredChecks.filter((c) => c.status === \"missing\").length;\n const allRequiredPassed =\n requiredNames.length === 0 ||\n requiredChecks.every((c) => c.status === \"pass\" || c.status === \"skip\");\n\n return {\n checks: evaluated,\n allRequiredPassed,\n pendingCount,\n failedCount,\n missingCount,\n };\n}\n\nexport function formatCiStatusIcon(status: CiCheckStatusEnum): string {\n switch (status) {\n case \"pass\":\n return \"✅\";\n case \"fail\":\n return \"❌\";\n case \"skip\":\n return \"⏭️\";\n case \"pending\":\n return \"⏳\";\n case \"stale\":\n return \"⚠️\";\n case \"missing\":\n return \"❓\";\n default: {\n const _exhaustive: never = status;\n return \"•\";\n }\n }\n}\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { z } from \"zod\";\nimport type { CiManifest } from \"./ci-manifest.js\";\n\nexport const GateDecision = z.enum([\"allow\", \"warn\", \"block\"]);\nexport type GateDecision = z.infer<typeof GateDecision>;\n\nexport const HealthCheckResult = z.object({\n target: z.string(),\n status: GateDecision,\n latencyMs: z.number(),\n detail: z.record(z.unknown()).optional(),\n});\nexport type HealthCheckResult = z.infer<typeof HealthCheckResult>;\n\nexport const RiskFactor = z.object({\n type: z.enum([\n \"code_churn\",\n \"test_coverage\",\n \"file_count\",\n \"sensitive_files\",\n \"author_history\",\n \"dependency_changes\",\n \"pr_age\",\n \"security_alerts\",\n \"deployment_history\",\n \"canary_status\",\n \"ci_integrity\",\n \"workflow_security\",\n \"prompt_injection_risk\",\n \"supply_chain\",\n \"pr_scope\",\n \"duplicate_logic\",\n \"cross_repo_impact\",\n ]),\n score: z.number().min(0).max(100),\n detail: z.record(z.unknown()).optional(),\n});\nexport type RiskFactor = z.infer<typeof RiskFactor>;\n\nexport const PrProvenance = z.object({\n type: z.enum([\n \"human\",\n \"dependabot\",\n \"copilot\",\n \"codex\",\n \"claude\",\n \"custom-bot\",\n \"unknown\",\n ]),\n confidence: z.number().min(0).max(1),\n source: z.string().optional(),\n});\nexport type PrProvenance = z.infer<typeof PrProvenance>;\n\nexport const GateMode = z.enum([\"release-ready\", \"advisory\", \"risk-only\"]);\nexport type GateMode = z.infer<typeof GateMode>;\n\nexport const AgentBriefMode = z.enum([\"off\", \"collapsed\", \"expanded\"]);\nexport type AgentBriefMode = z.infer<typeof AgentBriefMode>;\n\nexport const CiCheckStatusEnum = z.enum([\n \"pass\",\n \"fail\",\n \"skip\",\n \"pending\",\n \"stale\",\n \"missing\",\n]);\nexport type CiCheckStatusEnum = z.infer<typeof CiCheckStatusEnum>;\n\nexport const CiCheck = z.object({\n name: z.string(),\n status: CiCheckStatusEnum,\n conclusion: z.string().optional(),\n detailsUrl: z.string().url().optional(),\n required: z.boolean(),\n});\nexport type CiCheck = z.infer<typeof CiCheck>;\n\nexport const CiSummary = z.object({\n checks: z.array(CiCheck),\n allRequiredPassed: z.boolean(),\n pendingCount: z.number().int().min(0),\n failedCount: z.number().int().min(0),\n missingCount: z.number().int().min(0),\n});\nexport type CiSummary = z.infer<typeof CiSummary>;\n\nexport const MatchedContext = z.object({\n name: z.string(),\n environment: z.string().optional(),\n});\nexport type MatchedContext = z.infer<typeof MatchedContext>;\n\nexport const RemediationSeverity = z.enum([\"blocking\", \"warn\", \"advisory\"]);\nexport type RemediationSeverity = z.infer<typeof RemediationSeverity>;\n\nexport const SubmissionCheckCode = z.enum([\n \"artifact_integrity\",\n \"mock_placeholder\",\n \"context_freshness\",\n \"destructive_sql\",\n \"secrets\",\n \"path_format\",\n \"syntax_validity\",\n \"import_resolution\",\n \"rls_new_tables\",\n \"auth_route_auth\",\n \"hardcoded_env\",\n \"external_package_deps\",\n \"sql_syntax_basic\",\n \"large_file\",\n \"soul_integrity\",\n // ADR-010 — architecture & lifecycle gates\n \"contract_integrity\",\n \"safe_deprecation\",\n \"destructive_change\",\n \"claim_anchoring\",\n \"promotion_coherence\",\n // Phase 0 — agent suggestion quality (advisory / weight=0 in komatik-agents)\n \"output_size_min\",\n \"action_extraction_present\",\n \"delta_section_present\",\n \"preamble_absent\",\n \"graduation_signals_section_present\",\n \"fabricated_id_check\",\n \"session_narrative_detection\",\n \"incompleteness_self_flag\",\n \"referenced_files_exist\",\n \"prerequisite_secrets_check\",\n \"dependency_dag_validation\",\n \"uncommitted_fix_check\",\n \"verification_owner_assigned\",\n \"external_interface_validation\",\n]);\nexport type SubmissionCheckCode = z.infer<typeof SubmissionCheckCode>;\n\nexport const SubmissionCheckResult = z.object({\n code: SubmissionCheckCode,\n severity: RemediationSeverity,\n title: z.string(),\n detail: z.string(),\n files: z.array(z.string()).default([]),\n suggested_action: z.string().optional(),\n autofix_eligible: z.boolean().default(false),\n});\nexport type SubmissionCheckResult = z.infer<typeof SubmissionCheckResult>;\n\nexport const RemediationAutofixClass = z.enum([\n \"format\",\n \"lint\",\n \"import-fix\",\n \"type-narrow\",\n \"test-scaffold\",\n \"doc-update\",\n \"dependency-bump\",\n]);\nexport type RemediationAutofixClass = z.infer<typeof RemediationAutofixClass>;\n\nexport const RemediationFix = z.object({\n code: z.string(),\n severity: RemediationSeverity,\n title: z.string(),\n detail: z.string(),\n files: z.array(z.string()).default([]),\n suggested_action: z.string().optional(),\n suggested_command: z.string().optional(),\n autofix_eligible: z.boolean().default(false),\n autofix_class: RemediationAutofixClass.optional(),\n policy_link: z.string().url().optional(),\n});\nexport type RemediationFix = z.infer<typeof RemediationFix>;\n\nexport const RemediationNextAction = z.enum([\n \"ready_to_merge\",\n \"fix_and_retry\",\n \"human_review_required\",\n \"max_rounds_exceeded\",\n]);\nexport type RemediationNextAction = z.infer<typeof RemediationNextAction>;\n\nexport const Remediation = z.object({\n schema: z.literal(\"trailhead.remediation.v1\").default(\"trailhead.remediation.v1\"),\n release_ready: z.boolean(),\n fixes: z.array(RemediationFix),\n blocking_count: z.number().int().min(0),\n warn_count: z.number().int().min(0),\n advisory_count: z.number().int().min(0),\n autofix_eligible_count: z.number().int().min(0),\n loop_round: z.number().int().min(0).default(0),\n max_loop_rounds: z.number().int().min(0).default(3),\n previous_evaluation_id: z.string().optional(),\n fixes_resolved: z.array(z.string()).default([]),\n fixes_introduced: z.array(z.string()).default([]),\n next_action: RemediationNextAction,\n});\nexport type Remediation = z.infer<typeof Remediation>;\n\nexport const PolicyOverrideChanges = z.object({\n failMode: z.enum([\"open\", \"closed\"]).optional(),\n riskThreshold: z.number().min(0).max(100).optional(),\n warnThreshold: z.number().min(0).max(100).optional(),\n releaseReady: z.literal(true).optional(),\n});\nexport type PolicyOverrideChanges = z.infer<typeof PolicyOverrideChanges>;\n\nexport const PolicyOverrideAudit = z.object({\n source: z.enum([\"workflow\", \"label\"]).default(\"workflow\"),\n owner: z.string(),\n reason: z.string(),\n linkedTicket: z.string(),\n expiresAt: z.string(),\n appliedAt: z.string(),\n changes: PolicyOverrideChanges.default({}),\n preOverrideDecision: GateDecision.optional(),\n preOverrideReleaseReady: z.boolean().optional(),\n preOverrideReasons: z.array(z.string()).optional(),\n});\nexport type PolicyOverrideAudit = z.infer<typeof PolicyOverrideAudit>;\n\nexport const CreditMeterResult = z.object({\n metered: z.boolean(),\n skipped: z.boolean().optional(),\n reason: z.string().optional(),\n shadow: z.boolean().optional(),\n would_charge: z.number().optional(),\n charged: z.number().optional(),\n balance: z.number().optional(),\n allowed: z.boolean().optional(),\n ok: z.boolean().optional(),\n});\nexport type CreditMeterResult = z.infer<typeof CreditMeterResult>;\n\nexport const GateEvaluation = z.object({\n id: z.string(),\n repoId: z.string(),\n commitSha: z.string(),\n prNumber: z.number().optional(),\n healthScore: z.number().min(0).max(100),\n riskScore: z.number().min(0).max(100),\n gateDecision: GateDecision,\n healthChecks: z.array(HealthCheckResult),\n riskFactors: z.array(RiskFactor),\n files: z.array(z.string()).optional(),\n evaluationMs: z.number(),\n reportUrl: z.string().url().optional(),\n environment: z.string().optional(),\n service: z.string().optional(),\n policyFindings: z.array(z.string()).optional(),\n pr: z\n .object({\n provenance: PrProvenance.optional(),\n headRef: z.string().optional(),\n })\n .optional(),\n session_correlation: z\n .object({\n burst_count: z.number().int().min(0),\n window: z.string(),\n })\n .optional(),\n escalation_status: z\n .object({\n enabled: z.boolean(),\n target_count: z.number().int().min(0),\n acknowledge_sla_minutes: z.number().int().min(1).optional(),\n resolve_sla_minutes: z.number().int().min(1).optional(),\n })\n .optional(),\n trust_profile: z\n .object({\n strictness: z.enum([\"baseline\", \"elevated\", \"strict\"]),\n reason: z.string(),\n score: z.number().min(0).max(1).optional(),\n profile: z.enum([\"fast-track\", \"standard\", \"probation\"]).optional(),\n factors: z.record(z.number()).optional(),\n })\n .optional(),\n policyOverride: PolicyOverrideAudit.optional(),\n labelOverrideFeedback: z\n .object({\n status: z.enum([\"applied\", \"rejected\"]),\n message: z.string(),\n })\n .optional(),\n releaseReady: z.boolean().optional(),\n releaseReadyReasons: z.array(z.string()).optional(),\n ci: CiSummary.optional(),\n context: MatchedContext.optional(),\n gateMode: GateMode.optional(),\n storePersisted: z.boolean().optional(),\n credit_meter: CreditMeterResult.optional(),\n remediation: Remediation.optional(),\n agentBriefMode: AgentBriefMode.optional(),\n submissionChecks: z.array(SubmissionCheckResult).optional(),\n cross_repo_impact: z\n .object({\n services: z.array(\n z.object({\n serviceName: z.string(),\n touchedFiles: z.array(z.string()),\n consumers: z.array(\n z.object({\n id: z.string(),\n repo: z.string().optional(),\n branch: z.string().optional(),\n }),\n ),\n notify_webhook: z.string().url().optional(),\n }),\n ),\n })\n .optional(),\n});\nexport type GateEvaluation = z.infer<typeof GateEvaluation>;\n\nexport const GateApiResponse = z.object({\n id: z.string().optional(),\n reportUrl: z.string().url().optional(),\n healthScore: z.number().min(0).max(100).optional(),\n riskScore: z.number().min(0).max(100).optional(),\n gateDecision: GateDecision.optional(),\n healthChecks: z.array(HealthCheckResult).optional(),\n riskFactors: z.array(RiskFactor).optional(),\n});\nexport type GateApiResponse = z.infer<typeof GateApiResponse>;\n\nexport const FreezeWindow = z.object({\n days: z.array(z.string()).default([]),\n afterHour: z.number().min(0).max(23).optional(),\n beforeHour: z.number().min(0).max(23).optional(),\n timezone: z.string().default(\"UTC\"),\n message: z.string().optional(),\n});\nexport type FreezeWindow = z.infer<typeof FreezeWindow>;\n\nexport const EnvironmentConfig = z.object({\n risk: z.number().min(0).max(100).optional(),\n warn: z.number().min(0).max(100).optional(),\n require_security_clear: z.boolean().optional(),\n});\nexport type EnvironmentConfig = z.infer<typeof EnvironmentConfig>;\n\nexport const ServiceConsumerRef = z.object({\n repo: z.string().min(1),\n name: z.string().optional(),\n branch: z.string().optional(),\n notify_webhook: z.string().url().optional(),\n});\n\nexport const ServiceConsumer = z.union([z.string(), ServiceConsumerRef]);\nexport type ServiceConsumer = z.infer<typeof ServiceConsumer>;\n\nexport const ConsumerRegistry = z.record(z.string(), ServiceConsumerRef);\nexport type ConsumerRegistry = z.infer<typeof ConsumerRegistry>;\n\nexport const ServiceMapping = z.object({\n paths: z.array(z.string()),\n environment: z.string().optional(),\n consumers: z.array(ServiceConsumer).default([]),\n contracts: z.array(z.string()).default([]),\n notify_webhook: z.string().url().optional(),\n});\nexport type ServiceMapping = z.infer<typeof ServiceMapping>;\n\nexport const SecurityConfig = z.object({\n severity_threshold: z.enum([\"error\", \"warning\", \"note\", \"none\"]).default(\"warning\"),\n block_on_critical: z.boolean().default(true),\n ignore_rules: z.array(z.string()).default([]),\n});\nexport type SecurityConfig = z.infer<typeof SecurityConfig>;\n\nexport const CanaryConfig = z.object({\n webhook_type: z.enum([\"vercel\", \"generic\"]).default(\"vercel\"),\n field_map: z.record(z.string()).optional(),\n rollback_on_failure: z.boolean().default(false),\n});\nexport type CanaryConfig = z.infer<typeof CanaryConfig>;\n\nexport const RiskProfileMatch = z.object({\n files_include: z.array(z.string()).default([]),\n files_exclude: z.array(z.string()).default([]),\n min_files: z.number().int().min(1).optional(),\n max_files: z.number().int().min(1).optional(),\n});\nexport type RiskProfileMatch = z.infer<typeof RiskProfileMatch>;\n\nexport const RiskProfile = z.object({\n name: z.string().optional(),\n match: RiskProfileMatch,\n weights: z.record(z.number().min(0).max(10)).default({}),\n});\nexport type RiskProfile = z.infer<typeof RiskProfile>;\n\nexport const ContextMatch = z.object({\n base_branch: z.array(z.string()).default([]),\n head_branch: z.array(z.string()).default([]),\n labels: z.array(z.string()).default([]),\n});\nexport type ContextMatch = z.infer<typeof ContextMatch>;\n\nexport const ContextCiConfig = z.object({\n required_checks: z.array(z.string()).default([]),\n optional_checks: z.array(z.string()).default([]),\n missing_required: z.enum([\"fail\", \"skip\"]).default(\"fail\"),\n});\nexport type ContextCiConfig = z.infer<typeof ContextCiConfig>;\n\nexport const TrailheadContext = z.object({\n name: z.string(),\n match: ContextMatch,\n environment: z.string().optional(),\n thresholds: z\n .object({\n risk: z.number().min(0).max(100).optional(),\n warn: z.number().min(0).max(100).optional(),\n })\n .default({}),\n ci: ContextCiConfig.default({}),\n});\nexport type TrailheadContext = z.infer<typeof TrailheadContext>;\n\nexport const GateConfig = z.object({\n mode: GateMode.default(\"risk-only\"),\n check_name: z.string().default(\"Trailhead — Release Ready\"),\n agent_brief: AgentBriefMode.optional(),\n});\nexport type GateConfig = z.infer<typeof GateConfig>;\n\nexport const RemediationConfig = z.object({\n enabled: z.boolean().default(true),\n max_loop_rounds: z.number().int().min(0).default(3),\n});\nexport type RemediationConfig = z.infer<typeof RemediationConfig>;\n\nexport const RiskPathProfileConfig = z.object({\n /** Extra globs excluded from sensitive_files + test_coverage (not file_count/churn). */\n non_source_globs: z.array(z.string()).default([]),\n});\nexport type RiskPathProfileConfig = z.infer<typeof RiskPathProfileConfig>;\n\nexport const OverrideConfig = z.object({\n enabled: z.boolean().default(true),\n max_per_week: z.number().int().min(1).default(5),\n});\nexport type OverrideConfig = z.infer<typeof OverrideConfig>;\n\nexport const TuningConfig = z.object({\n auto_downgrade: z.boolean().default(true),\n digest_webhook_url: z.string().url().optional(),\n fp_threshold: z.number().min(0).max(1).default(0.15),\n});\nexport type TuningConfig = z.infer<typeof TuningConfig>;\n\nexport const SubmissionDetectorPolicyEntry = z.object({\n enabled: z.boolean().optional(),\n severity: z.enum([\"block\", \"warn\", \"advisory\", \"blocking\"]).optional(),\n file_globs: z.array(z.string()).optional(),\n path_ignore: z.array(z.string()).optional(),\n weight: z.number().optional(),\n});\nexport type SubmissionDetectorPolicyEntry = z.infer<typeof SubmissionDetectorPolicyEntry>;\n\nexport const SubmissionRenamePattern = z.object({\n old: z.string().min(1),\n new: z.string().min(1),\n});\nexport type SubmissionRenamePattern = z.infer<typeof SubmissionRenamePattern>;\n\nexport const SubmissionConfig = z.object({\n enabled: z.boolean().default(false),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n stale_terms: z.array(z.string()).optional(),\n auth_route_allowlist: z.array(z.string()).optional(),\n max_file_lines: z.number().int().positive().optional(),\n /** Path substrings to skip for context_freshness (e.g. archived suggestion dirs). */\n path_ignore: z.array(z.string()).optional(),\n /** Legacy naming allowlist — skip stale-term hits on imports, slugs in strings, etc. */\n naming_allowlist: z\n .object({\n skip_extensions: z.array(z.string()).optional(),\n skip_path_patterns: z.array(z.string()).optional(),\n skip_comment_markers: z.array(z.string()).optional(),\n skip_in_imports: z.boolean().optional(),\n })\n .optional(),\n /** Project rename vocabulary — extends Komatik defaults when KOMATIK_INSTANCE=true. */\n rename_patterns: z.array(SubmissionRenamePattern).optional(),\n /** Extra slug-only regex sources (merged with product defaults). */\n slug_only_patterns: z.array(z.string()).optional(),\n /** Per-detector policy overrides (enable/severity/file scope). */\n detectors: z.record(SubmissionDetectorPolicyEntry).optional(),\n /** contract_integrity (ADR-010): cross-repo catalog resolution. */\n contract_integrity: z\n .object({\n /** Entity names published org-wide; lets cross-repo contract refs resolve. */\n known_entities: z.array(z.string()).optional(),\n /** Path to a JSON catalog index ({ entities: string[] }), merged with known_entities. */\n catalog_index_path: z.string().optional(),\n /** entity name → \"owner/repo\" that should publish it. Resolution registry\n * for the cross-repo PR opener: a dangling consumesApis/dependsOn ref whose\n * name is mapped here triggers a declaration PR in the owning repo. */\n api_owners: z.record(z.string()).optional(),\n /** Path to a catalog index JSON with an `owners` map; merged with api_owners\n * (inline api_owners wins). Usually the same file as catalog_index_path. */\n api_owners_path: z.string().optional(),\n /** Cross-repo PR opener (ADR-010). Off by default; opens declaration PRs in\n * the OWNING repo for dangling cross-repo contract refs. Needs a token with\n * write access to those repos (cross-repo-token input). */\n cross_repo_opener: z\n .object({\n enabled: z.boolean().default(false),\n /** Owners the opener may open PRs in. Defaults to the gated repo's owner. */\n owner_allowlist: z.array(z.string()).optional(),\n })\n .optional(),\n })\n .optional(),\n});\nexport type SubmissionConfig = z.infer<typeof SubmissionConfig>;\n\nexport const RepoConfig = z.object({\n schema_version: z.number().int().positive().default(1),\n gate: GateConfig.default({}),\n risk: RiskPathProfileConfig.optional(),\n remediation: RemediationConfig.optional(),\n override: OverrideConfig.optional(),\n tuning: TuningConfig.optional(),\n submission: SubmissionConfig.optional(),\n contexts: z.array(TrailheadContext).default([]),\n sensitivity: z\n .object({\n high: z.array(z.string()).default([]),\n medium: z.array(z.string()).default([]),\n low: z.array(z.string()).default([]),\n })\n .default({}),\n weights: z.record(z.number().min(0).max(10)).default({}),\n profiles: z.array(RiskProfile).default([]),\n thresholds: z\n .object({\n risk: z.number().min(0).max(100).optional(),\n warn: z.number().min(0).max(100).optional(),\n })\n .default({}),\n ignore: z.array(z.string()).default([]),\n freeze: z.array(FreezeWindow).default([]),\n environments: z.record(EnvironmentConfig).default({}),\n services: z.record(ServiceMapping).default({}),\n consumer_registry: z.record(ServiceConsumerRef).default({}),\n security: SecurityConfig.default({}),\n canary: CanaryConfig.optional(),\n escalation: z\n .object({\n targets: z.array(z.string()).default([]),\n acknowledge_sla_minutes: z.number().int().min(1).default(30),\n resolve_sla_minutes: z.number().int().min(1).default(240),\n })\n .default({}),\n policies: z\n .object({\n agent_prs: z\n .object({\n enabled: z.boolean().default(false),\n risk_threshold: z.number().min(0).max(100).optional(),\n required_approvals: z.number().int().min(0).default(1),\n require_code_owner_approval: z.boolean().default(false),\n code_owner_reviewers: z.array(z.string()).default([]),\n sensitive_paths: z.array(z.string()).default([]),\n strict_on_unknown_provenance: z.boolean().default(true),\n })\n .default({}),\n session_correlation: z\n .object({\n enabled: z.boolean().default(false),\n threshold: z.number().int().min(2).default(3),\n window_minutes: z.number().int().min(5).default(60),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n })\n .default({}),\n ci_integrity: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n })\n .default({}),\n workflow_security: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n allow_unpinned_actions: z.array(z.string()).default([]),\n })\n .default({}),\n prompt_injection: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"block\"),\n })\n .default({}),\n supply_chain: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n force_score_on_critical: z.number().min(0).max(100).default(80),\n })\n .default({}),\n pr_scope: z\n .object({\n enabled: z.boolean().default(true),\n max_files: z.number().int().min(1).default(50),\n max_changes: z.number().int().min(1).default(2000),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n require_plan_for_agent_prs: z.boolean().default(false),\n })\n .default({}),\n duplicate_logic: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n })\n .default({}),\n cross_repo_impact: z\n .object({\n enabled: z.boolean().default(true),\n mode: z.enum([\"warn\", \"block\"]).default(\"warn\"),\n consumer_registry_path: z.string().optional(),\n })\n .default({}),\n })\n .default({}),\n});\nexport type RepoConfig = z.infer<typeof RepoConfig>;\n\nexport interface TrailheadConfig {\n apiKey: string;\n apiUrl: string;\n githubToken?: string;\n healthCheckUrls: string[];\n riskThreshold: number;\n warnThreshold?: number;\n failMode: \"open\" | \"closed\";\n selfHeal: boolean;\n addRiskLabels: boolean;\n reviewersOnRisk: string[];\n webhookUrl?: string;\n webhookEvents: string[];\n evaluationStoreUrl?: string;\n trailheadApiKey?: string;\n environment?: string;\n securityGate?: boolean;\n gateMode?: GateMode;\n waitForChecks?: boolean;\n waitTimeoutMinutes?: number;\n checkName?: string;\n ciManifest?: CiManifest | null;\n ciManifestPath?: string;\n agentBrief?: AgentBriefMode;\n submissionGate?: boolean;\n}\n\nexport interface TestRepairResult {\n testFile: string;\n failureType: string;\n strategy: string;\n success: boolean;\n diff?: string;\n}\n","import { RepoConfig } from \"./types.js\";\nimport type { RepoConfig as RepoConfigType } from \"./types.js\";\n\nexport const SUPPORTED_CONFIG_SCHEMA_VERSIONS = new Set([1, 2]);\nexport const CURRENT_CONFIG_SCHEMA_VERSION = 2;\n\nexport function parseYaml(input: string): unknown {\n const lines = input\n .split(\"\\n\")\n .map((line) => line.replace(/\\r$/, \"\"))\n .filter((line) => line.trim() !== \"\" && !line.trim().startsWith(\"#\"));\n const root: Record<string, unknown> = {};\n const stack: Array<{ indent: number; value: unknown }> = [{ indent: -1, value: root }];\n\n const parseScalar = (value: string): unknown => {\n const v = value.trim();\n if (\n (v.startsWith('\"') && v.endsWith('\"')) ||\n (v.startsWith(\"'\") && v.endsWith(\"'\"))\n ) {\n return v.slice(1, -1);\n }\n if (v === \"true\") return true;\n if (v === \"false\") return false;\n if (v === \"null\") return null;\n const n = Number(v);\n if (!Number.isNaN(n) && v !== \"\") return n;\n return v;\n };\n\n const findNextSignificantLine = (fromIndex: number): string | null => {\n for (let i = fromIndex + 1; i < lines.length; i += 1) {\n const candidate = lines[i];\n if (candidate.trim() !== \"\" && !candidate.trim().startsWith(\"#\")) {\n return candidate;\n }\n }\n return null;\n };\n\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i];\n const indent = line.match(/^ */)?.[0].length ?? 0;\n const trimmed = line.trim();\n\n while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {\n stack.pop();\n }\n const container = stack[stack.length - 1].value;\n\n if (trimmed.startsWith(\"- \")) {\n if (!Array.isArray(container)) continue;\n const itemRaw = trimmed.slice(2).trim();\n if (itemRaw === \"\") {\n const child: Record<string, unknown> = {};\n container.push(child);\n stack.push({ indent, value: child });\n continue;\n }\n\n const itemKeyMatch = itemRaw.match(/^([A-Za-z0-9_-]+):\\s*(.*)$/);\n if (itemKeyMatch) {\n const child: Record<string, unknown> = {};\n const [, itemKey, itemVal] = itemKeyMatch;\n if (itemVal === \"\") {\n const nextLine = findNextSignificantLine(i);\n const nextIndent = nextLine?.match(/^ */)?.[0].length ?? -1;\n const nextTrimmed = nextLine?.trim() ?? \"\";\n const useArray =\n nextLine !== null && nextIndent > indent && nextTrimmed.startsWith(\"- \");\n child[itemKey] = useArray ? [] : {};\n if (\n !useArray &&\n typeof child[itemKey] === \"object\" &&\n child[itemKey] !== null\n ) {\n stack.push({ indent, value: child[itemKey] });\n }\n } else {\n const trimmedVal = itemVal.trim();\n if (trimmedVal.startsWith(\"[\") && trimmedVal.endsWith(\"]\")) {\n const inner = trimmedVal.slice(1, -1).trim();\n child[itemKey] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((item) => parseScalar(item.trim()));\n } else {\n child[itemKey] = parseScalar(itemVal);\n }\n }\n container.push(child);\n stack.push({ indent, value: child });\n continue;\n }\n\n container.push(parseScalar(itemRaw));\n continue;\n }\n\n const keyMatch = trimmed.match(/^([A-Za-z0-9_-]+):\\s*(.*)$/);\n if (\n !keyMatch ||\n typeof container !== \"object\" ||\n container === null ||\n Array.isArray(container)\n ) {\n continue;\n }\n\n const [, key, rawVal] = keyMatch;\n if (rawVal !== \"\") {\n const trimmedVal = rawVal.trim();\n if (trimmedVal.startsWith(\"[\") && trimmedVal.endsWith(\"]\")) {\n const inner = trimmedVal.slice(1, -1).trim();\n (container as Record<string, unknown>)[key] =\n inner === \"\" ? [] : inner.split(\",\").map((item) => parseScalar(item.trim()));\n continue;\n }\n (container as Record<string, unknown>)[key] = parseScalar(rawVal);\n continue;\n }\n\n const nextLine = findNextSignificantLine(i);\n const nextIndent = nextLine?.match(/^ */)?.[0].length ?? -1;\n const nextTrimmed = nextLine?.trim() ?? \"\";\n const useArray =\n nextLine !== null && nextIndent > indent && nextTrimmed.startsWith(\"- \");\n const child: unknown = useArray ? [] : {};\n (container as Record<string, unknown>)[key] = child;\n stack.push({ indent, value: child });\n }\n\n return root;\n}\n\nexport function parseRepoConfigContent(content: string): RepoConfigType | null {\n const raw = parseYaml(content);\n const parsed = RepoConfig.safeParse(raw);\n if (!parsed.success) return null;\n return parsed.data;\n}\n","import type { CiSummary, GateDecision, GateEvaluation, GateMode } from \"./types.js\";\n\nexport interface ReleaseReadyInput {\n gateMode: GateMode;\n gateDecision: GateDecision;\n riskScore: number;\n riskThreshold: number;\n healthScore: number;\n healthChecksConfigured: boolean;\n ciSummary?: CiSummary | null;\n freezeActive: boolean;\n freezeMessage?: string;\n policyFindings?: string[];\n requireSecurityClear?: boolean;\n securityBlocked?: boolean;\n}\n\nexport interface ReleaseReadyResult {\n releaseReady: boolean;\n reasons: string[];\n}\n\n/**\n * Composite release readiness decision (ADR-006).\n */\nexport function computeReleaseReady(input: ReleaseReadyInput): ReleaseReadyResult {\n const reasons: string[] = [];\n\n if (input.gateMode === \"risk-only\") {\n if (input.gateDecision === \"block\") {\n reasons.push(\"Risk/policy gate decision is BLOCK\");\n } else if (input.gateDecision === \"warn\") {\n reasons.push(\"Risk/policy gate decision is WARN (non-blocking in risk-only mode)\");\n }\n return {\n releaseReady: input.gateDecision !== \"block\",\n reasons,\n };\n }\n\n if (input.ciSummary) {\n if (!input.ciSummary.allRequiredPassed) {\n const failed = input.ciSummary.checks.filter(\n (c) =>\n c.required &&\n (c.status === \"fail\" || c.status === \"missing\" || c.status === \"stale\"),\n );\n for (const check of failed) {\n reasons.push(\n `Required CI check \"${check.name}\" is ${check.status.toUpperCase()}`,\n );\n }\n }\n if (input.ciSummary.pendingCount > 0) {\n reasons.push(`${input.ciSummary.pendingCount} required CI check(s) still pending`);\n }\n }\n\n if (input.gateDecision === \"block\") {\n reasons.push(\"Risk/policy gate decision is BLOCK\");\n }\n\n if (input.riskScore > input.riskThreshold) {\n reasons.push(\n `Risk score ${input.riskScore} exceeds threshold ${input.riskThreshold}`,\n );\n }\n\n if (input.freezeActive) {\n reasons.push(\n `Release freeze active${input.freezeMessage ? `: ${input.freezeMessage}` : \"\"}`,\n );\n }\n\n if (input.healthChecksConfigured && input.healthScore < 50) {\n reasons.push(`Health score ${input.healthScore} below minimum (50)`);\n }\n\n if (input.requireSecurityClear && input.securityBlocked) {\n reasons.push(\"Security gate requires clearance — blocking alerts present\");\n }\n\n const blockingFindings = (input.policyFindings ?? []).filter((f) =>\n /blocking|requires|exceeds|configured to block/i.test(f),\n );\n if (blockingFindings.length > 0 && input.gateDecision === \"block\") {\n for (const finding of blockingFindings.slice(0, 3)) {\n if (!reasons.includes(finding)) reasons.push(finding);\n }\n }\n\n const releaseReady = reasons.length === 0;\n\n return { releaseReady, reasons };\n}\n\nexport function applyReleaseReadyToEvaluation(\n evaluation: GateEvaluation,\n result: ReleaseReadyResult,\n gateMode: GateMode,\n): GateEvaluation {\n return {\n ...evaluation,\n releaseReady: result.releaseReady,\n releaseReadyReasons: result.reasons.length > 0 ? result.reasons : undefined,\n gateMode,\n };\n}\n\nexport function checkConclusionForEvaluation(\n evaluation: GateEvaluation,\n): \"success\" | \"neutral\" | \"failure\" {\n const mode = evaluation.gateMode ?? \"risk-only\";\n\n if (mode === \"advisory\") {\n return \"neutral\";\n }\n\n if (mode === \"release-ready\") {\n return evaluation.releaseReady ? \"success\" : \"failure\";\n }\n\n switch (evaluation.gateDecision) {\n case \"allow\":\n return \"success\";\n case \"warn\":\n return \"neutral\";\n case \"block\":\n return \"failure\";\n default: {\n const _exhaustive: never = evaluation.gateDecision;\n return \"failure\";\n }\n }\n}\n\nexport function shouldBlockMerge(evaluation: GateEvaluation): boolean {\n const mode = evaluation.gateMode ?? \"risk-only\";\n\n if (mode === \"advisory\") return false;\n if (mode === \"release-ready\") return evaluation.releaseReady === false;\n return evaluation.gateDecision === \"block\";\n}\n\nexport function resolveCheckName(gateMode: GateMode, configuredName?: string): string {\n if (gateMode === \"risk-only\") return \"Trailhead\";\n return configuredName ?? \"Trailhead — Release Ready\";\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { checkNameMatches } from \"./ci-core.js\";\nimport { parseRepoConfigContent } from \"./config-core.js\";\nimport { resolveCheckName } from \"./release-ready.js\";\nimport type { GateMode, RepoConfig } from \"./types.js\";\n\nexport type DoctorSeverity = \"error\" | \"warn\" | \"info\";\n\nexport interface DoctorFinding {\n severity: DoctorSeverity;\n code: string;\n message: string;\n}\n\nexport interface DoctorReport {\n configPath: string | null;\n configValid: boolean;\n gateMode: GateMode;\n expectedCheckName: string;\n configuredChecks: string[];\n observedChecks: string[];\n findings: DoctorFinding[];\n ok: boolean;\n}\n\nexport interface RunDoctorOptions {\n cwd?: string;\n offline?: boolean;\n githubToken?: string;\n repo?: string;\n ref?: string;\n}\n\nconst CONFIG_CANDIDATES = [\".trailhead.yml\", \".deployguard.yml\"];\n\nexport function findConfigPath(cwd: string): string | null {\n for (const name of CONFIG_CANDIDATES) {\n const candidate = path.join(cwd, name);\n if (fs.existsSync(candidate)) return candidate;\n }\n return null;\n}\n\nexport function loadRepoConfig(cwd: string): {\n configPath: string | null;\n config: RepoConfig | null;\n error?: string;\n} {\n const configPath = findConfigPath(cwd);\n if (!configPath) {\n return {\n configPath: null,\n config: null,\n error: \"No .trailhead.yml or .deployguard.yml found\",\n };\n }\n\n const content = fs.readFileSync(configPath, \"utf8\");\n const config = parseRepoConfigContent(content);\n if (!config) {\n return {\n configPath,\n config: null,\n error: `Failed to parse ${path.basename(configPath)} — check YAML structure and schema fields`,\n };\n }\n\n return { configPath, config };\n}\n\nexport function collectConfiguredChecks(config: RepoConfig): string[] {\n const names = new Set<string>();\n for (const context of config.contexts) {\n for (const name of context.ci?.required_checks ?? []) {\n names.add(name);\n }\n for (const name of context.ci?.optional_checks ?? []) {\n names.add(name);\n }\n }\n return [...names];\n}\n\nexport function validateConfigStructure(\n config: RepoConfig,\n configPath: string,\n): DoctorFinding[] {\n const findings: DoctorFinding[] = [];\n const fileName = path.basename(configPath);\n const gateMode = config.gate.mode;\n\n if (gateMode !== \"risk-only\" && config.schema_version < 2) {\n findings.push({\n severity: \"warn\",\n code: \"schema_version\",\n message: `${fileName} uses schema_version ${config.schema_version} with gate.mode=${gateMode} — consider schema_version: 2 and contexts[]`,\n });\n }\n\n const risk = config.thresholds.risk;\n const warn = config.thresholds.warn;\n if (risk !== undefined && warn !== undefined && warn >= risk) {\n findings.push({\n severity: \"warn\",\n code: \"threshold_order\",\n message: `warn threshold (${warn}) should be lower than risk threshold (${risk})`,\n });\n }\n\n if (gateMode !== \"risk-only\") {\n if (config.contexts.length === 0) {\n findings.push({\n severity: \"error\",\n code: \"missing_contexts\",\n message:\n \"release-ready/advisory mode requires at least one contexts[] entry with ci.required_checks\",\n });\n }\n\n for (const context of config.contexts) {\n const required = context.ci?.required_checks ?? [];\n if (required.length === 0) {\n findings.push({\n severity: \"warn\",\n code: \"empty_required_checks\",\n message: `Context \"${context.name}\" has no ci.required_checks — release-ready may not wait for CI`,\n });\n }\n }\n }\n\n const gateCheck = resolveCheckName(gateMode, config.gate.check_name);\n if (gateMode !== \"risk-only\" && !gateCheck.includes(\"Release Ready\")) {\n findings.push({\n severity: \"info\",\n code: \"custom_check_name\",\n message: `Branch protection should require check name \"${gateCheck}\"`,\n });\n }\n\n return findings;\n}\n\nexport function compareConfiguredChecks(\n configuredChecks: string[],\n observedChecks: string[],\n): DoctorFinding[] {\n if (observedChecks.length === 0) {\n return [];\n }\n\n const findings: DoctorFinding[] = [];\n const observed = [...new Set(observedChecks)];\n\n for (const configured of configuredChecks) {\n const matched = observed.some((actual) => checkNameMatches(configured, actual));\n if (!matched) {\n findings.push({\n severity: \"warn\",\n code: \"unknown_check_name\",\n message: `Configured check \"${configured}\" did not match any recent GitHub check run`,\n });\n }\n }\n\n const selfChecks = new Set([\n \"Trailhead\",\n \"Trailhead — Release Ready\",\n resolveCheckName(\"release-ready\"),\n resolveCheckName(\"risk-only\"),\n ]);\n\n for (const actual of observed) {\n if (selfChecks.has(actual)) continue;\n const referenced = configuredChecks.some((configured) =>\n checkNameMatches(configured, actual),\n );\n if (!referenced) {\n findings.push({\n severity: \"info\",\n code: \"unconfigured_check\",\n message: `GitHub check \"${actual}\" is not referenced in contexts[].ci (optional unless required)`,\n });\n }\n }\n\n return findings;\n}\n\nexport interface GitHubRepoRef {\n owner: string;\n repo: string;\n}\n\nexport function parseRepoRef(input: string): GitHubRepoRef | null {\n const match = input.match(/^([^/]+)\\/([^/]+)$/);\n if (!match) return null;\n return { owner: match[1], repo: match[2] };\n}\n\nasync function githubRequest<T>(\n token: string,\n url: string,\n): Promise<{ ok: true; data: T } | { ok: false; status: number; message: string }> {\n const response = await fetch(url, {\n headers: {\n Accept: \"application/vnd.github+json\",\n Authorization: `Bearer ${token}`,\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n return {\n ok: false,\n status: response.status,\n message: body || response.statusText,\n };\n }\n\n return { ok: true, data: (await response.json()) as T };\n}\n\nasync function resolveCommitSha(\n token: string,\n repoRef: GitHubRepoRef,\n ref?: string,\n): Promise<string | null> {\n if (ref) return ref;\n\n const pulls = await githubRequest<Array<{ head: { sha: string } }>>(\n token,\n `https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/pulls?state=open&per_page=1`,\n );\n if (pulls.ok && pulls.data[0]?.head.sha) {\n return pulls.data[0].head.sha;\n }\n\n const repo = await githubRequest<{ default_branch: string }>(\n token,\n `https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}`,\n );\n if (!repo.ok) return null;\n\n const branch = await githubRequest<{ commit: { sha: string } }>(\n token,\n `https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/branches/${encodeURIComponent(repo.data.default_branch)}`,\n );\n return branch.ok ? branch.data.commit.sha : null;\n}\n\nexport async function fetchObservedCheckNames(options: {\n token: string;\n repo: GitHubRepoRef;\n ref?: string;\n}): Promise<{ checks: string[]; error?: string }> {\n const sha = await resolveCommitSha(options.token, options.repo, options.ref);\n if (!sha) {\n return { checks: [], error: \"Could not resolve a commit SHA for check lookup\" };\n }\n\n const names = new Set<string>();\n let page = 1;\n\n while (true) {\n const result = await githubRequest<{\n check_runs: Array<{ name: string }>;\n }>(\n options.token,\n `https://api.github.com/repos/${options.repo.owner}/${options.repo.repo}/commits/${sha}/check-runs?per_page=100&page=${page}`,\n );\n\n if (!result.ok) {\n return {\n checks: [],\n error: `GitHub Checks API failed (HTTP ${result.status})`,\n };\n }\n\n for (const run of result.data.check_runs) {\n names.add(run.name);\n }\n\n if (result.data.check_runs.length < 100) break;\n page += 1;\n }\n\n return { checks: [...names].sort() };\n}\n\nexport async function runDoctor(options: RunDoctorOptions = {}): Promise<DoctorReport> {\n const cwd = options.cwd ?? process.cwd();\n const loaded = loadRepoConfig(cwd);\n const findings: DoctorFinding[] = [];\n\n if (!loaded.configPath || !loaded.config) {\n findings.push({\n severity: \"error\",\n code: \"config_missing\",\n message: loaded.error ?? \"Configuration file not found\",\n });\n return {\n configPath: loaded.configPath,\n configValid: false,\n gateMode: \"risk-only\",\n expectedCheckName: \"Trailhead\",\n configuredChecks: [],\n observedChecks: [],\n findings,\n ok: false,\n };\n }\n\n const config = loaded.config;\n const gateMode = config.gate.mode;\n const expectedCheckName = resolveCheckName(gateMode, config.gate.check_name);\n const configuredChecks = collectConfiguredChecks(config);\n\n findings.push(...validateConfigStructure(config, loaded.configPath));\n\n let observedChecks: string[] = [];\n if (!options.offline) {\n const token = options.githubToken ?? process.env.GITHUB_TOKEN ?? \"\";\n const repoInput = options.repo ?? process.env.GITHUB_REPOSITORY ?? \"\";\n const repoRef = parseRepoRef(repoInput);\n\n if (!token) {\n findings.push({\n severity: \"info\",\n code: \"offline_checks\",\n message:\n \"Set GITHUB_TOKEN (or pass --token) to compare configured checks against GitHub\",\n });\n } else if (!repoRef) {\n findings.push({\n severity: \"info\",\n code: \"offline_checks\",\n message:\n \"Set GITHUB_REPOSITORY (or pass --repo owner/name) to compare checks against GitHub\",\n });\n } else {\n const observed = await fetchObservedCheckNames({\n token,\n repo: repoRef,\n ref: options.ref,\n });\n observedChecks = observed.checks;\n if (observed.error) {\n findings.push({\n severity: \"warn\",\n code: \"github_checks\",\n message: observed.error,\n });\n } else if (configuredChecks.length > 0) {\n findings.push(...compareConfiguredChecks(configuredChecks, observedChecks));\n }\n }\n }\n\n const ok = !findings.some((finding) => finding.severity === \"error\");\n return {\n configPath: loaded.configPath,\n configValid: true,\n gateMode,\n expectedCheckName,\n configuredChecks,\n observedChecks,\n findings,\n ok,\n };\n}\n\nexport function formatDoctorReport(report: DoctorReport): string {\n const lines: string[] = [];\n lines.push(\"Trailhead Doctor\");\n lines.push(\"================\");\n lines.push(\"\");\n\n if (report.configPath) {\n lines.push(`Config: ${report.configPath}`);\n } else {\n lines.push(\"Config: (not found)\");\n }\n\n lines.push(`Gate mode: ${report.gateMode}`);\n lines.push(`Expected branch protection check: ${report.expectedCheckName}`);\n\n if (report.configuredChecks.length > 0) {\n lines.push(`Configured CI checks: ${report.configuredChecks.join(\", \")}`);\n }\n\n if (report.observedChecks.length > 0) {\n lines.push(`Observed GitHub checks: ${report.observedChecks.join(\", \")}`);\n }\n\n if (report.findings.length === 0) {\n lines.push(\"\");\n lines.push(\"No issues found.\");\n return lines.join(\"\\n\");\n }\n\n lines.push(\"\");\n for (const finding of report.findings) {\n const label =\n finding.severity === \"error\"\n ? \"ERROR\"\n : finding.severity === \"warn\"\n ? \"WARN\"\n : \"INFO\";\n lines.push(`${label} [${finding.code}] ${finding.message}`);\n }\n\n lines.push(\"\");\n lines.push(\n report.ok\n ? \"Result: OK (review warnings before release-ready rollout)\"\n : \"Result: FAILED\",\n );\n return lines.join(\"\\n\");\n}\n","import { formatDoctorReport, runDoctor } from \"./shared/doctor.js\";\n\nfunction printUsage(): void {\n process.stdout.write(`\nTrailhead Doctor — validate .trailhead.yml and compare CI check names\n\nUsage:\n trailhead doctor [options]\n\nOptions:\n --path <dir> Directory to scan (default: cwd)\n --repo <owner/name> GitHub repository for check lookup\n --token <token> GitHub token (default: GITHUB_TOKEN)\n --ref <sha> Commit SHA for check runs (default: latest open PR or default branch)\n --offline Skip GitHub API check comparison\n --json Output report as JSON\n -h, --help Show this help\n\nEnvironment:\n GITHUB_TOKEN Personal access token with checks:read\n GITHUB_REPOSITORY owner/repo when running in GitHub Actions\n`);\n}\n\nexport async function runDoctorCommand(args: string[]): Promise<number> {\n if (args.includes(\"-h\") || args.includes(\"--help\")) {\n printUsage();\n return 0;\n }\n\n let cwd = process.cwd();\n let repo: string | undefined;\n let token: string | undefined;\n let ref: string | undefined;\n let offline = false;\n let json = false;\n\n for (let i = 0; i < args.length; i += 1) {\n const arg = args[i];\n if (arg === \"--offline\") {\n offline = true;\n continue;\n }\n if (arg === \"--json\") {\n json = true;\n continue;\n }\n if (arg === \"--path\" && args[i + 1]) {\n cwd = args[i + 1];\n i += 1;\n continue;\n }\n if (arg === \"--repo\" && args[i + 1]) {\n repo = args[i + 1];\n i += 1;\n continue;\n }\n if (arg === \"--token\" && args[i + 1]) {\n token = args[i + 1];\n i += 1;\n continue;\n }\n if (arg === \"--ref\" && args[i + 1]) {\n ref = args[i + 1];\n i += 1;\n continue;\n }\n process.stderr.write(`Unknown option: ${arg}\\n`);\n printUsage();\n return 2;\n }\n\n const report = await runDoctor({\n cwd,\n offline,\n githubToken: token,\n repo,\n ref,\n });\n\n if (json) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`);\n } else {\n process.stdout.write(`${formatDoctorReport(report)}\\n`);\n }\n\n return report.ok ? 0 : 1;\n}\n","// Shared helpers for Gate 1 submission checks (pure, no I/O).\n\nimport type { SubmissionFileInfo } from \"./types.js\";\n\nexport function normalizePath(filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n\nexport function extensionOf(filename: string): string {\n const base = normalizePath(filename);\n const idx = base.lastIndexOf(\".\");\n return idx >= 0 ? base.slice(idx).toLowerCase() : \"\";\n}\n\nexport function addedLines(patch: string | undefined): string[] {\n if (!patch) return [];\n return patch\n .split(\"\\n\")\n .filter((line) => line.startsWith(\"+\") && !line.startsWith(\"+++\"))\n .map((line) => line.slice(1));\n}\n\n/** Approximate post-change file body from a unified diff hunk (context + additions). */\nexport function effectiveContentFromPatch(patch: string | undefined): string {\n if (!patch) return \"\";\n return patch\n .split(\"\\n\")\n .filter(\n (line) =>\n !line.startsWith(\"@@\") && !line.startsWith(\"---\") && !line.startsWith(\"+++\"),\n )\n .filter((line) => !line.startsWith(\"-\"))\n .map((line) => (line.startsWith(\"+\") || line.startsWith(\" \") ? line.slice(1) : line))\n .join(\"\\n\");\n}\n\nexport function fileContent(file: SubmissionFileInfo): string {\n if (typeof file.content === \"string\") return file.content;\n return effectiveContentFromPatch(file.patch);\n}\n\nexport function lineCountFromPatch(patch: string | undefined): number {\n const content = effectiveContentFromPatch(patch);\n if (!content) return 0;\n return content.split(\"\\n\").length;\n}\n\nexport function scanAddedContent(\n files: SubmissionFileInfo[],\n predicate: (line: string, filename: string) => boolean,\n): string[] {\n const hits: string[] = [];\n for (const file of files) {\n for (const line of addedLines(file.patch)) {\n if (predicate(line, file.filename)) hits.push(file.filename);\n }\n }\n return [...new Set(hits)];\n}\n\nexport function scanFileContent(\n files: SubmissionFileInfo[],\n predicate: (line: string, filename: string, lineNo: number) => boolean,\n): Array<{ file: string; line: number }> {\n const hits: Array<{ file: string; line: number }> = [];\n for (const file of files) {\n const lines = fileContent(file).split(\"\\n\");\n lines.forEach((line, index) => {\n if (predicate(line, file.filename, index + 1)) {\n hits.push({ file: file.filename, line: index + 1 });\n }\n });\n }\n return hits;\n}\n\nexport function prPathSet(files: SubmissionFileInfo[]): Set<string> {\n return new Set(files.map((f) => normalizePath(f.filename)));\n}\n\nexport function isTestPath(filename: string): boolean {\n return /\\/__tests__\\/|\\/test\\/|\\/fixtures\\/|\\.test\\.|\\.spec\\./.test(filename);\n}\n\n/** Default archived/stale path segments skipped by context_freshness. */\nexport const DEFAULT_STALE_PATH_IGNORE = [\"/_stale/\", \"/_archive/\", \"/.archive/\"];\n\nexport function isStaleArchivedPath(\n filename: string,\n extraPatterns: string[] = [],\n): boolean {\n const path = normalizePath(filename);\n return [...DEFAULT_STALE_PATH_IGNORE, ...extraPatterns].some((segment) =>\n path.includes(segment),\n );\n}\n\nexport function packageJsonPathForFile(\n filename: string,\n prPaths: Set<string>,\n): string | null {\n const parts = normalizePath(filename).split(\"/\");\n for (let i = parts.length - 1; i >= 0; i--) {\n const candidate = [...parts.slice(0, i), \"package.json\"].filter(Boolean).join(\"/\");\n if (prPaths.has(candidate)) return candidate;\n }\n return prPaths.has(\"package.json\") ? \"package.json\" : null;\n}\n\nconst VALID_PACKAGE_SPECIFIER = /^(@[\\w.-]+\\/[\\w.-]+|[\\w@][\\w.-]*)(?:\\/[\\w./-]*)?$/;\n\nexport function isValidPackageSpecifier(specifier: string): boolean {\n if (!specifier || specifier.startsWith(\".\") || specifier.startsWith(\"@/\")) return false;\n if (/^https?:|^node:/.test(specifier)) return false;\n if (/[:()\\\\]/.test(specifier)) return false;\n return VALID_PACKAGE_SPECIFIER.test(specifier);\n}\n\n/** Extract module specifiers from full file content (legacy agent-gate parity). */\nexport function extractAllImports(\n content: string,\n): Array<{ specifier: string; line: number }> {\n const results: Array<{ specifier: string; line: number }> = [];\n const patterns = [\n /\\bimport\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)?['\"]([^'\"]+)['\"]/g,\n /\\bexport\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)['\"]([^'\"]+)['\"]/g,\n /\\brequire\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n /\\bimport\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n\n for (const pattern of patterns) {\n pattern.lastIndex = 0;\n for (const match of content.matchAll(pattern)) {\n const specifier = match[1];\n if (!specifier) continue;\n const line = content.slice(0, match.index ?? 0).split(\"\\n\").length;\n results.push({ specifier, line });\n }\n }\n return results;\n}\n\nexport function linesForFreshnessScan(file: {\n filename: string;\n patch?: string;\n content?: string;\n}): string[] {\n if (typeof file.content === \"string\") return file.content.split(\"\\n\");\n return addedLines(file.patch);\n}\n","// Phase 0 agent suggestion checks (weight=0 / advisory in Trailhead).\n// Ported from komatik-agents agent-gate-checks Phase 0 stubs with real heuristics.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst SEVERITY = \"advisory\" as const;\nconst OUTPUT_SIZE_MIN_CHARS = 400;\nconst NARRATIVE_MATCH_THRESHOLD = 3;\n\nconst PREAMBLE_OPENERS =\n /^(let me|here is the|here's the|i('| wi)ll|after reviewing|to start|based on my analysis)/i;\nconst SESSION_NARRATIVE =\n /\\bI (queried|reviewed|checked|will (build|create|fix|implement|add|update))/gi;\nconst PARTIAL_COMPLETION = /\\b\\d+\\s*(?:\\/|of)\\s*\\d+\\b/i;\nconst INCOMPLETE_MARKER = /\\b(INCOMPLETE|PARTIAL)\\b/i;\nconst FABRICATED_ID = /\\b(session|run|task|message)[-_]?[a-f0-9]{6,}\\b/gi;\nconst FILE_REF =\n /(?:^|[\\s('\"`])((?:src|scripts|supabase|app|agents)\\/[a-z0-9_/.-]+\\.(?:ts|tsx|js|mjs|sql|py|md))/gi;\nconst ACTION_SUFFIX = /(?:→\\s*@[\\w-]+|— No actions surfaced)\\s*$/i;\nconst UNVERIFIED_MARKER = /\\[UNVERIFIED\\]|verify after|needs verification/i;\nconst OWNER_DUE = /Owner:\\s*@[\\w-]+[\\s\\S]{0,120}Due:\\s*\\d{4}-\\d{2}-\\d{2}/i;\nconst FIX_CLAIM = /\\b(fix applied|now working|is live|deployed successfully)\\b/i;\nconst MULTI_PHASE = /\\bphase\\s+[ab12]\\b/gi;\nconst DEP_MATRIX = /\\b(depends on:|dependency matrix|blocks:|x blocks y)\\b/i;\nconst RUNBOOK_HINT = /runbook|deploy(?:ment)? guide/i;\nconst SECRETS_PREREQ =\n /\\b(secrets list|prerequisites:|required env|environment variables)\\b/i;\nconst PROPOSAL_ONLY = /\\bPROPOSAL_ONLY\\b/i;\nconst SCHEMA_LINK = /https?:\\/\\/[^\\s)]+\\/(schema|openapi|api-docs)/i;\n\nfunction advisory(\n partial: Omit<SubmissionCheckResult, \"severity\" | \"autofix_eligible\">,\n): SubmissionCheckResult {\n return { severity: SEVERITY, autofix_eligible: false, ...partial };\n}\n\nexport function suggestionMarkdownFiles(\n ctx: SubmissionCheckContext,\n): SubmissionFileInfo[] {\n return ctx.files.filter((file) => {\n const path = normalizePath(file.filename);\n if (!/\\.md$/i.test(path)) return false;\n return /agents\\/[^/]+\\/suggestions\\//.test(path) || /\\/suggestions\\//.test(path);\n });\n}\n\nfunction agentFromPath(filePath: string): string | null {\n const match = normalizePath(filePath).match(/^agents\\/([^/]+)\\//);\n return match?.[1] ?? null;\n}\n\nfunction paragraphs(text: string): string[] {\n return text\n .split(/\\n\\s*\\n/)\n .map((p) => p.trim())\n .filter((p) => p.length > 0 && !/^#+\\s/.test(p));\n}\n\nfunction extractFileRefs(text: string): string[] {\n const refs = new Set<string>();\n const re = new RegExp(FILE_REF.source, FILE_REF.flags);\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n if (m[1]) refs.add(normalizePath(m[1]));\n }\n const backtick = /`((?:src|scripts|supabase|app|agents)\\/[a-z0-9_/.-]+\\.[a-z]+)`/gi;\n while ((m = backtick.exec(text)) !== null) {\n refs.add(normalizePath(m[1]));\n }\n return [...refs];\n}\n\nfunction hasToBeCreatedMarker(text: string, ref: string): boolean {\n const idx = text.indexOf(ref);\n if (idx < 0) return false;\n const window = text.slice(Math.max(0, idx - 80), idx + ref.length + 80);\n return /to-be-created|to be created|TBD path/i.test(window);\n}\n\nexport function detectOutputSizeMin(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx);\n const short = files.filter((f) => fileContent(f).trim().length < OUTPUT_SIZE_MIN_CHARS);\n if (short.length === 0) return null;\n return advisory({\n code: \"output_size_min\",\n title: \"Agent output below minimum size\",\n detail: `Suggestion markdown under ${OUTPUT_SIZE_MIN_CHARS} chars (possible model bail-out): ${short.map((f) => f.filename).join(\", \")}.`,\n files: short.map((f) => f.filename),\n suggested_action: \"Expand the proposal with concrete actions and file-level detail.\",\n });\n}\n\nexport function detectActionExtractionPresent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx).filter(\n (f) => agentFromPath(f.filename) === \"coordinator\",\n );\n const missing: string[] = [];\n for (const file of files) {\n const paras = paragraphs(fileContent(file));\n const bad = paras.filter((p) => !ACTION_SUFFIX.test(p));\n if (bad.length > 0) missing.push(file.filename);\n }\n if (missing.length === 0) return null;\n return advisory({\n code: \"action_extraction_present\",\n title: \"Coordinator paragraph missing action extraction\",\n detail: `Paragraphs should end with \"→ @owner\" or \"— No actions surfaced\": ${missing.join(\", \")}.`,\n files: missing,\n suggested_action: \"Add explicit owner routing or a no-actions line per paragraph.\",\n });\n}\n\nexport function detectDeltaSectionPresent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx).filter((f) => {\n const agent = agentFromPath(f.filename);\n const path = normalizePath(f.filename);\n return agent === \"knowledge-scout\" || /DAILY-INTEL\\.md$/i.test(path);\n });\n const missing: string[] = [];\n for (const file of files) {\n const text = fileContent(file);\n if (!/## Δ Since Last Sweep/i.test(text) && !/No deltas — quiet sweep/i.test(text)) {\n missing.push(file.filename);\n }\n }\n if (missing.length === 0) return null;\n return advisory({\n code: \"delta_section_present\",\n title: \"Missing delta section (knowledge-scout)\",\n detail: `Require \"## Δ Since Last Sweep\" or \"No deltas — quiet sweep\": ${missing.join(\", \")}.`,\n files: missing,\n suggested_action: \"Add a delta header or explicit quiet-sweep line.\",\n });\n}\n\nexport function detectPreambleAbsent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const paras = paragraphs(fileContent(file)).slice(0, 2);\n if (paras.some((p) => PREAMBLE_OPENERS.test(p.split(\"\\n\")[0]?.trim() ?? \"\"))) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"preamble_absent\",\n title: \"Conversational preamble detected\",\n detail: `Opening paragraphs use session-style preambles: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Start with structured content, not meta narration.\",\n });\n}\n\nexport function detectGraduationSignalsSectionPresent(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const files = suggestionMarkdownFiles(ctx).filter(\n (f) => agentFromPath(f.filename) === \"rd-satellite\",\n );\n const missing = files\n .filter((f) => !/## Graduation Signals/i.test(fileContent(f)))\n .map((f) => f.filename);\n if (missing.length === 0) return null;\n return advisory({\n code: \"graduation_signals_section_present\",\n title: \"Missing Graduation Signals section\",\n detail: `rd-satellite output requires \"## Graduation Signals\": ${missing.join(\", \")}.`,\n files: missing,\n suggested_action: \"Add a Graduation Signals section with promotion criteria.\",\n });\n}\n\nexport function detectFabricatedIdCheck(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n const ids: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n const re = new RegExp(FABRICATED_ID.source, FABRICATED_ID.flags);\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n ids.push(m[0]);\n hits.push(file.filename);\n }\n }\n if (ids.length === 0) return null;\n return advisory({\n code: \"fabricated_id_check\",\n title: \"Suspicious session/run identifiers\",\n detail: `Verify identifiers against agent_runs/tasks/messages: ${[...new Set(ids)].slice(0, 8).join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action: \"Replace fabricated IDs with verified references or remove them.\",\n });\n}\n\nexport function detectSessionNarrativeDetection(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n let total = 0;\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n const re = new RegExp(SESSION_NARRATIVE.source, SESSION_NARRATIVE.flags);\n const matches = text.match(re);\n // Per-file threshold: flag a single document dense with first-person\n // session narration, not a cumulative count that a large multi-file\n // submission would trip just by volume.\n if (matches && matches.length >= NARRATIVE_MATCH_THRESHOLD) {\n total += matches.length;\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"session_narrative_detection\",\n title: \"Session narrative instead of file content\",\n detail: `${total} first-person session phrases in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Replace narration with concrete diffs, paths, and commands.\",\n });\n}\n\nexport function detectIncompletenessSelfFlag(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n if (PARTIAL_COMPLETION.test(text) && !INCOMPLETE_MARKER.test(text)) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"incompleteness_self_flag\",\n title: \"Partial completion without INCOMPLETE marker\",\n detail: `Fractional completion hints require INCOMPLETE/PARTIAL flag: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: 'Add an explicit \"INCOMPLETE\" or \"PARTIAL\" marker for scoped work.',\n });\n}\n\nexport function detectReferencedFilesExist(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n // Needs a repo file listing to tell a fabricated path from a reference to an\n // existing, unchanged file. Without it, stay dormant — flagging every path\n // that merely isn't part of this PR is almost all false positives.\n if (!ctx.repoPaths) return null;\n const repoPaths = ctx.repoPaths;\n const missing: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n for (const ref of extractFileRefs(text)) {\n const known =\n ctx.prPaths.has(ref) ||\n repoPaths.has(ref) ||\n [...ctx.prPaths].some((p) => p.endsWith(`/${ref}`)) ||\n [...repoPaths].some((p) => p.endsWith(`/${ref}`));\n if (!known && !hasToBeCreatedMarker(text, ref)) {\n missing.push(`${file.filename}: ${ref}`);\n }\n }\n }\n if (missing.length === 0) return null;\n return advisory({\n code: \"referenced_files_exist\",\n title: \"Referenced path missing from PR and repo\",\n detail: missing.slice(0, 12).join(\"; \"),\n files: missing.map((m) => m.split(\": \")[0] ?? m),\n suggested_action: 'Include the file in the PR or mark adjacent \"to-be-created\".',\n });\n}\n\nexport function detectPrerequisiteSecretsCheck(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const path = normalizePath(file.filename);\n const text = fileContent(file);\n const titleLine = text.split(\"\\n\").find((l) => /^#\\s/.test(l)) ?? \"\";\n if (!RUNBOOK_HINT.test(`${path} ${titleLine}`)) continue;\n const head = text.split(\"\\n\").slice(0, 30).join(\"\\n\");\n if (!SECRETS_PREREQ.test(head)) hits.push(file.filename);\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"prerequisite_secrets_check\",\n title: \"Runbook missing secrets prerequisite step\",\n detail: `First 30 lines should include secrets/env prerequisites: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Open runbooks with Prerequisites or `secrets list` verification.\",\n });\n}\n\nexport function detectDependencyDagValidation(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const text = fileContent(file);\n const phases = (text.match(MULTI_PHASE) ?? []).length;\n if (phases >= 2 && !DEP_MATRIX.test(text)) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"dependency_dag_validation\",\n title: \"Multi-phase plan missing dependency matrix\",\n detail: `Multi-phase proposals need Depends on / blocks lines: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Add explicit phase dependencies (X blocks Y).\",\n });\n}\n\nexport function detectUncommittedFixCheck(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n if (FIX_CLAIM.test(fileContent(file))) hits.push(file.filename);\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"uncommitted_fix_check\",\n title: \"Fix claim requires commit verification\",\n detail: `Claims like \"fix applied\" / \"now working\" need matching git history: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action:\n \"Reference the commit SHA or flag changes as on-disk pending commit.\",\n });\n}\n\nexport function detectVerificationOwnerAssigned(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const lines = fileContent(file).split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n if (!UNVERIFIED_MARKER.test(lines[i] ?? \"\")) continue;\n const window = lines.slice(i, i + 6).join(\"\\n\");\n if (!OWNER_DUE.test(window)) {\n hits.push(file.filename);\n break;\n }\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"verification_owner_assigned\",\n title: \"UNVERIFIED item missing owner and due date\",\n detail: `Add Owner: @user and Due: YYYY-MM-DD near unverified items: ${[...new Set(hits)].join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action: \"Assign verification owner and due date for each UNVERIFIED line.\",\n });\n}\n\nexport function detectExternalInterfaceValidation(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of suggestionMarkdownFiles(ctx)) {\n const path = normalizePath(file.filename);\n const crossRepo = /suggestions\\/(?!komatik-agents)[^/]+\\//.test(path);\n if (!crossRepo) continue;\n const text = fileContent(file);\n if (!PROPOSAL_ONLY.test(text) && !SCHEMA_LINK.test(text)) {\n hits.push(file.filename);\n }\n }\n if (hits.length === 0) return null;\n return advisory({\n code: \"external_interface_validation\",\n title: \"Cross-repo proposal lacks schema verification\",\n detail: `Cross-repo suggestions need PROPOSAL_ONLY or verified schema link: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Link verified target schema or mark PROPOSAL_ONLY.\",\n });\n}\n\nexport function runPhase0Detectors(ctx: SubmissionCheckContext): SubmissionCheckResult[] {\n if (suggestionMarkdownFiles(ctx).length === 0) return [];\n const checks = [\n detectOutputSizeMin,\n detectActionExtractionPresent,\n detectDeltaSectionPresent,\n detectPreambleAbsent,\n detectGraduationSignalsSectionPresent,\n detectFabricatedIdCheck,\n detectSessionNarrativeDetection,\n detectIncompletenessSelfFlag,\n detectReferencedFilesExist,\n detectPrerequisiteSecretsCheck,\n detectDependencyDagValidation,\n detectUncommittedFixCheck,\n detectVerificationOwnerAssigned,\n detectExternalInterfaceValidation,\n ];\n return checks\n .map((fn) => fn(ctx))\n .filter((check): check is SubmissionCheckResult => check !== null);\n}\n","\n/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */\nfunction isNothing(subject) {\n return (typeof subject === 'undefined') || (subject === null);\n}\n\n\nfunction isObject(subject) {\n return (typeof subject === 'object') && (subject !== null);\n}\n\n\nfunction toArray(sequence) {\n if (Array.isArray(sequence)) return sequence;\n else if (isNothing(sequence)) return [];\n\n return [ sequence ];\n}\n\n\nfunction extend(target, source) {\n var index, length, key, sourceKeys;\n\n if (source) {\n sourceKeys = Object.keys(source);\n\n for (index = 0, length = sourceKeys.length; index < length; index += 1) {\n key = sourceKeys[index];\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\n\nfunction repeat(string, count) {\n var result = '', cycle;\n\n for (cycle = 0; cycle < count; cycle += 1) {\n result += string;\n }\n\n return result;\n}\n\n\nfunction isNegativeZero(number) {\n return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);\n}\n\n\nvar isNothing_1 = isNothing;\nvar isObject_1 = isObject;\nvar toArray_1 = toArray;\nvar repeat_1 = repeat;\nvar isNegativeZero_1 = isNegativeZero;\nvar extend_1 = extend;\n\nvar common = {\n\tisNothing: isNothing_1,\n\tisObject: isObject_1,\n\ttoArray: toArray_1,\n\trepeat: repeat_1,\n\tisNegativeZero: isNegativeZero_1,\n\textend: extend_1\n};\n\n// YAML error class. http://stackoverflow.com/questions/8458984\n\n\nfunction formatError(exception, compact) {\n var where = '', message = exception.reason || '(unknown reason)';\n\n if (!exception.mark) return message;\n\n if (exception.mark.name) {\n where += 'in \"' + exception.mark.name + '\" ';\n }\n\n where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';\n\n if (!compact && exception.mark.snippet) {\n where += '\\n\\n' + exception.mark.snippet;\n }\n\n return message + ' ' + where;\n}\n\n\nfunction YAMLException$1(reason, mark) {\n // Super constructor\n Error.call(this);\n\n this.name = 'YAMLException';\n this.reason = reason;\n this.mark = mark;\n this.message = formatError(this, false);\n\n // Include stack trace in error object\n if (Error.captureStackTrace) {\n // Chrome and NodeJS\n Error.captureStackTrace(this, this.constructor);\n } else {\n // FF, IE 10+ and Safari 6+. Fallback for others\n this.stack = (new Error()).stack || '';\n }\n}\n\n\n// Inherit from Error\nYAMLException$1.prototype = Object.create(Error.prototype);\nYAMLException$1.prototype.constructor = YAMLException$1;\n\n\nYAMLException$1.prototype.toString = function toString(compact) {\n return this.name + ': ' + formatError(this, compact);\n};\n\n\nvar exception = YAMLException$1;\n\n// get snippet for a single line, respecting maxLength\nfunction getLine(buffer, lineStart, lineEnd, position, maxLineLength) {\n var head = '';\n var tail = '';\n var maxHalfLength = Math.floor(maxLineLength / 2) - 1;\n\n if (position - lineStart > maxHalfLength) {\n head = ' ... ';\n lineStart = position - maxHalfLength + head.length;\n }\n\n if (lineEnd - position > maxHalfLength) {\n tail = ' ...';\n lineEnd = position + maxHalfLength - tail.length;\n }\n\n return {\n str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, '→') + tail,\n pos: position - lineStart + head.length // relative position\n };\n}\n\n\nfunction padStart(string, max) {\n return common.repeat(' ', max - string.length) + string;\n}\n\n\nfunction makeSnippet(mark, options) {\n options = Object.create(options || null);\n\n if (!mark.buffer) return null;\n\n if (!options.maxLength) options.maxLength = 79;\n if (typeof options.indent !== 'number') options.indent = 1;\n if (typeof options.linesBefore !== 'number') options.linesBefore = 3;\n if (typeof options.linesAfter !== 'number') options.linesAfter = 2;\n\n var re = /\\r?\\n|\\r|\\0/g;\n var lineStarts = [ 0 ];\n var lineEnds = [];\n var match;\n var foundLineNo = -1;\n\n while ((match = re.exec(mark.buffer))) {\n lineEnds.push(match.index);\n lineStarts.push(match.index + match[0].length);\n\n if (mark.position <= match.index && foundLineNo < 0) {\n foundLineNo = lineStarts.length - 2;\n }\n }\n\n if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;\n\n var result = '', i, line;\n var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;\n var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);\n\n for (i = 1; i <= options.linesBefore; i++) {\n if (foundLineNo - i < 0) break;\n line = getLine(\n mark.buffer,\n lineStarts[foundLineNo - i],\n lineEnds[foundLineNo - i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n maxLineLength\n );\n result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n' + result;\n }\n\n line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);\n result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n';\n result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\\n';\n\n for (i = 1; i <= options.linesAfter; i++) {\n if (foundLineNo + i >= lineEnds.length) break;\n line = getLine(\n mark.buffer,\n lineStarts[foundLineNo + i],\n lineEnds[foundLineNo + i],\n mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n maxLineLength\n );\n result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +\n ' | ' + line.str + '\\n';\n }\n\n return result.replace(/\\n$/, '');\n}\n\n\nvar snippet = makeSnippet;\n\nvar TYPE_CONSTRUCTOR_OPTIONS = [\n 'kind',\n 'multi',\n 'resolve',\n 'construct',\n 'instanceOf',\n 'predicate',\n 'represent',\n 'representName',\n 'defaultStyle',\n 'styleAliases'\n];\n\nvar YAML_NODE_KINDS = [\n 'scalar',\n 'sequence',\n 'mapping'\n];\n\nfunction compileStyleAliases(map) {\n var result = {};\n\n if (map !== null) {\n Object.keys(map).forEach(function (style) {\n map[style].forEach(function (alias) {\n result[String(alias)] = style;\n });\n });\n }\n\n return result;\n}\n\nfunction Type$1(tag, options) {\n options = options || {};\n\n Object.keys(options).forEach(function (name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new exception('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.');\n }\n });\n\n // TODO: Add tag format check.\n this.options = options; // keep original options in case user wants to extend this type later\n this.tag = tag;\n this.kind = options['kind'] || null;\n this.resolve = options['resolve'] || function () { return true; };\n this.construct = options['construct'] || function (data) { return data; };\n this.instanceOf = options['instanceOf'] || null;\n this.predicate = options['predicate'] || null;\n this.represent = options['represent'] || null;\n this.representName = options['representName'] || null;\n this.defaultStyle = options['defaultStyle'] || null;\n this.multi = options['multi'] || false;\n this.styleAliases = compileStyleAliases(options['styleAliases'] || null);\n\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new exception('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.');\n }\n}\n\nvar type = Type$1;\n\n/*eslint-disable max-len*/\n\n\n\n\n\nfunction compileList(schema, name) {\n var result = [];\n\n schema[name].forEach(function (currentType) {\n var newIndex = result.length;\n\n result.forEach(function (previousType, previousIndex) {\n if (previousType.tag === currentType.tag &&\n previousType.kind === currentType.kind &&\n previousType.multi === currentType.multi) {\n\n newIndex = previousIndex;\n }\n });\n\n result[newIndex] = currentType;\n });\n\n return result;\n}\n\n\nfunction compileMap(/* lists... */) {\n var result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {},\n multi: {\n scalar: [],\n sequence: [],\n mapping: [],\n fallback: []\n }\n }, index, length;\n\n function collectType(type) {\n if (type.multi) {\n result.multi[type.kind].push(type);\n result.multi['fallback'].push(type);\n } else {\n result[type.kind][type.tag] = result['fallback'][type.tag] = type;\n }\n }\n\n for (index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType);\n }\n return result;\n}\n\n\nfunction Schema$1(definition) {\n return this.extend(definition);\n}\n\n\nSchema$1.prototype.extend = function extend(definition) {\n var implicit = [];\n var explicit = [];\n\n if (definition instanceof type) {\n // Schema.extend(type)\n explicit.push(definition);\n\n } else if (Array.isArray(definition)) {\n // Schema.extend([ type1, type2, ... ])\n explicit = explicit.concat(definition);\n\n } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })\n if (definition.implicit) implicit = implicit.concat(definition.implicit);\n if (definition.explicit) explicit = explicit.concat(definition.explicit);\n\n } else {\n throw new exception('Schema.extend argument should be a Type, [ Type ], ' +\n 'or a schema definition ({ implicit: [...], explicit: [...] })');\n }\n\n implicit.forEach(function (type$1) {\n if (!(type$1 instanceof type)) {\n throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');\n }\n\n if (type$1.loadKind && type$1.loadKind !== 'scalar') {\n throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');\n }\n\n if (type$1.multi) {\n throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');\n }\n });\n\n explicit.forEach(function (type$1) {\n if (!(type$1 instanceof type)) {\n throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');\n }\n });\n\n var result = Object.create(Schema$1.prototype);\n\n result.implicit = (this.implicit || []).concat(implicit);\n result.explicit = (this.explicit || []).concat(explicit);\n\n result.compiledImplicit = compileList(result, 'implicit');\n result.compiledExplicit = compileList(result, 'explicit');\n result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);\n\n return result;\n};\n\n\nvar schema = Schema$1;\n\nvar str = new type('tag:yaml.org,2002:str', {\n kind: 'scalar',\n construct: function (data) { return data !== null ? data : ''; }\n});\n\nvar seq = new type('tag:yaml.org,2002:seq', {\n kind: 'sequence',\n construct: function (data) { return data !== null ? data : []; }\n});\n\nvar map = new type('tag:yaml.org,2002:map', {\n kind: 'mapping',\n construct: function (data) { return data !== null ? data : {}; }\n});\n\nvar failsafe = new schema({\n explicit: [\n str,\n seq,\n map\n ]\n});\n\nfunction resolveYamlNull(data) {\n if (data === null) return true;\n\n var max = data.length;\n\n return (max === 1 && data === '~') ||\n (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));\n}\n\nfunction constructYamlNull() {\n return null;\n}\n\nfunction isNull(object) {\n return object === null;\n}\n\nvar _null = new type('tag:yaml.org,2002:null', {\n kind: 'scalar',\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: function () { return '~'; },\n lowercase: function () { return 'null'; },\n uppercase: function () { return 'NULL'; },\n camelcase: function () { return 'Null'; },\n empty: function () { return ''; }\n },\n defaultStyle: 'lowercase'\n});\n\nfunction resolveYamlBoolean(data) {\n if (data === null) return false;\n\n var max = data.length;\n\n return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));\n}\n\nfunction constructYamlBoolean(data) {\n return data === 'true' ||\n data === 'True' ||\n data === 'TRUE';\n}\n\nfunction isBoolean(object) {\n return Object.prototype.toString.call(object) === '[object Boolean]';\n}\n\nvar bool = new type('tag:yaml.org,2002:bool', {\n kind: 'scalar',\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: function (object) { return object ? 'true' : 'false'; },\n uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },\n camelcase: function (object) { return object ? 'True' : 'False'; }\n },\n defaultStyle: 'lowercase'\n});\n\nfunction isHexCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||\n ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||\n ((0x61/* a */ <= c) && (c <= 0x66/* f */));\n}\n\nfunction isOctCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));\n}\n\nfunction isDecCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));\n}\n\nfunction resolveYamlInteger(data) {\n if (data === null) return false;\n\n var max = data.length,\n index = 0,\n hasDigits = false,\n ch;\n\n if (!max) return false;\n\n ch = data[index];\n\n // sign\n if (ch === '-' || ch === '+') {\n ch = data[++index];\n }\n\n if (ch === '0') {\n // 0\n if (index + 1 === max) return true;\n ch = data[++index];\n\n // base 2, base 8, base 16\n\n if (ch === 'b') {\n // base 2\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (ch !== '0' && ch !== '1') return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n\n if (ch === 'x') {\n // base 16\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isHexCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n\n if (ch === 'o') {\n // base 8\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isOctCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n }\n\n // base 10 (except 0)\n\n // value should not start with `_`;\n if (ch === '_') return false;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isDecCode(data.charCodeAt(index))) {\n return false;\n }\n hasDigits = true;\n }\n\n // Should have digits and should not end with `_`\n if (!hasDigits || ch === '_') return false;\n\n return true;\n}\n\nfunction constructYamlInteger(data) {\n var value = data, sign = 1, ch;\n\n if (value.indexOf('_') !== -1) {\n value = value.replace(/_/g, '');\n }\n\n ch = value[0];\n\n if (ch === '-' || ch === '+') {\n if (ch === '-') sign = -1;\n value = value.slice(1);\n ch = value[0];\n }\n\n if (value === '0') return 0;\n\n if (ch === '0') {\n if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);\n if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);\n if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);\n }\n\n return sign * parseInt(value, 10);\n}\n\nfunction isInteger(object) {\n return (Object.prototype.toString.call(object)) === '[object Number]' &&\n (object % 1 === 0 && !common.isNegativeZero(object));\n}\n\nvar int = new type('tag:yaml.org,2002:int', {\n kind: 'scalar',\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },\n octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); },\n decimal: function (obj) { return obj.toString(10); },\n /* eslint-disable max-len */\n hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }\n },\n defaultStyle: 'decimal',\n styleAliases: {\n binary: [ 2, 'bin' ],\n octal: [ 8, 'oct' ],\n decimal: [ 10, 'dec' ],\n hexadecimal: [ 16, 'hex' ]\n }\n});\n\nvar YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +\n // .2e4, .2\n // special case, seems not from spec\n '|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +\n // .inf\n '|[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$');\n\nfunction resolveYamlFloat(data) {\n if (data === null) return false;\n\n if (!YAML_FLOAT_PATTERN.test(data) ||\n // Quick hack to not allow integers end with `_`\n // Probably should update regexp & check speed\n data[data.length - 1] === '_') {\n return false;\n }\n\n return true;\n}\n\nfunction constructYamlFloat(data) {\n var value, sign;\n\n value = data.replace(/_/g, '').toLowerCase();\n sign = value[0] === '-' ? -1 : 1;\n\n if ('+-'.indexOf(value[0]) >= 0) {\n value = value.slice(1);\n }\n\n if (value === '.inf') {\n return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n\n } else if (value === '.nan') {\n return NaN;\n }\n return sign * parseFloat(value, 10);\n}\n\n\nvar SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\n\nfunction representYamlFloat(object, style) {\n var res;\n\n if (isNaN(object)) {\n switch (style) {\n case 'lowercase': return '.nan';\n case 'uppercase': return '.NAN';\n case 'camelcase': return '.NaN';\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '.inf';\n case 'uppercase': return '.INF';\n case 'camelcase': return '.Inf';\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '-.inf';\n case 'uppercase': return '-.INF';\n case 'camelcase': return '-.Inf';\n }\n } else if (common.isNegativeZero(object)) {\n return '-0.0';\n }\n\n res = object.toString(10);\n\n // JS stringifier can build scientific format without dots: 5e-100,\n // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;\n}\n\nfunction isFloat(object) {\n return (Object.prototype.toString.call(object) === '[object Number]') &&\n (object % 1 !== 0 || common.isNegativeZero(object));\n}\n\nvar float = new type('tag:yaml.org,2002:float', {\n kind: 'scalar',\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: 'lowercase'\n});\n\nvar json = failsafe.extend({\n implicit: [\n _null,\n bool,\n int,\n float\n ]\n});\n\nvar core = json;\n\nvar YAML_DATE_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9])' + // [2] month\n '-([0-9][0-9])$'); // [3] day\n\nvar YAML_TIMESTAMP_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9]?)' + // [2] month\n '-([0-9][0-9]?)' + // [3] day\n '(?:[Tt]|[ \\\\t]+)' + // ...\n '([0-9][0-9]?)' + // [4] hour\n ':([0-9][0-9])' + // [5] minute\n ':([0-9][0-9])' + // [6] second\n '(?:\\\\.([0-9]*))?' + // [7] fraction\n '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour\n '(?::([0-9][0-9]))?))?$'); // [11] tz_minute\n\nfunction resolveYamlTimestamp(data) {\n if (data === null) return false;\n if (YAML_DATE_REGEXP.exec(data) !== null) return true;\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n return false;\n}\n\nfunction constructYamlTimestamp(data) {\n var match, year, month, day, hour, minute, second, fraction = 0,\n delta = null, tz_hour, tz_minute, date;\n\n match = YAML_DATE_REGEXP.exec(data);\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n\n if (match === null) throw new Error('Date resolve error');\n\n // match: [1] year [2] month [3] day\n\n year = +(match[1]);\n month = +(match[2]) - 1; // JS month starts with 0\n day = +(match[3]);\n\n if (!match[4]) { // no hour\n return new Date(Date.UTC(year, month, day));\n }\n\n // match: [4] hour [5] minute [6] second [7] fraction\n\n hour = +(match[4]);\n minute = +(match[5]);\n second = +(match[6]);\n\n if (match[7]) {\n fraction = match[7].slice(0, 3);\n while (fraction.length < 3) { // milli-seconds\n fraction += '0';\n }\n fraction = +fraction;\n }\n\n // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute\n\n if (match[9]) {\n tz_hour = +(match[10]);\n tz_minute = +(match[11] || 0);\n delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds\n if (match[9] === '-') delta = -delta;\n }\n\n date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n\n if (delta) date.setTime(date.getTime() - delta);\n\n return date;\n}\n\nfunction representYamlTimestamp(object /*, style*/) {\n return object.toISOString();\n}\n\nvar timestamp = new type('tag:yaml.org,2002:timestamp', {\n kind: 'scalar',\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n});\n\nfunction resolveYamlMerge(data) {\n return data === '<<' || data === null;\n}\n\nvar merge = new type('tag:yaml.org,2002:merge', {\n kind: 'scalar',\n resolve: resolveYamlMerge\n});\n\n/*eslint-disable no-bitwise*/\n\n\n\n\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nvar BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r';\n\n\nfunction resolveYamlBinary(data) {\n if (data === null) return false;\n\n var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;\n\n // Convert one by one.\n for (idx = 0; idx < max; idx++) {\n code = map.indexOf(data.charAt(idx));\n\n // Skip CR/LF\n if (code > 64) continue;\n\n // Fail on illegal characters\n if (code < 0) return false;\n\n bitlen += 6;\n }\n\n // If there are any bits left, source was corrupted\n return (bitlen % 8) === 0;\n}\n\nfunction constructYamlBinary(data) {\n var idx, tailbits,\n input = data.replace(/[\\r\\n=]/g, ''), // remove CR/LF & padding to simplify scan\n max = input.length,\n map = BASE64_MAP,\n bits = 0,\n result = [];\n\n // Collect by 6*4 bits (3 bytes)\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 4 === 0) && idx) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n }\n\n bits = (bits << 6) | map.indexOf(input.charAt(idx));\n }\n\n // Dump tail\n\n tailbits = (max % 4) * 6;\n\n if (tailbits === 0) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n } else if (tailbits === 18) {\n result.push((bits >> 10) & 0xFF);\n result.push((bits >> 2) & 0xFF);\n } else if (tailbits === 12) {\n result.push((bits >> 4) & 0xFF);\n }\n\n return new Uint8Array(result);\n}\n\nfunction representYamlBinary(object /*, style*/) {\n var result = '', bits = 0, idx, tail,\n max = object.length,\n map = BASE64_MAP;\n\n // Convert every three bytes to 4 ASCII characters.\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 3 === 0) && idx) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n }\n\n bits = (bits << 8) + object[idx];\n }\n\n // Dump tail\n\n tail = max % 3;\n\n if (tail === 0) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n } else if (tail === 2) {\n result += map[(bits >> 10) & 0x3F];\n result += map[(bits >> 4) & 0x3F];\n result += map[(bits << 2) & 0x3F];\n result += map[64];\n } else if (tail === 1) {\n result += map[(bits >> 2) & 0x3F];\n result += map[(bits << 4) & 0x3F];\n result += map[64];\n result += map[64];\n }\n\n return result;\n}\n\nfunction isBinary(obj) {\n return Object.prototype.toString.call(obj) === '[object Uint8Array]';\n}\n\nvar binary = new type('tag:yaml.org,2002:binary', {\n kind: 'scalar',\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n});\n\nvar _hasOwnProperty$3 = Object.prototype.hasOwnProperty;\nvar _toString$2 = Object.prototype.toString;\n\nfunction resolveYamlOmap(data) {\n if (data === null) return true;\n\n var objectKeys = [], index, length, pair, pairKey, pairHasKey,\n object = data;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n pairHasKey = false;\n\n if (_toString$2.call(pair) !== '[object Object]') return false;\n\n for (pairKey in pair) {\n if (_hasOwnProperty$3.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true;\n else return false;\n }\n }\n\n if (!pairHasKey) return false;\n\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n else return false;\n }\n\n return true;\n}\n\nfunction constructYamlOmap(data) {\n return data !== null ? data : [];\n}\n\nvar omap = new type('tag:yaml.org,2002:omap', {\n kind: 'sequence',\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n});\n\nvar _toString$1 = Object.prototype.toString;\n\nfunction resolveYamlPairs(data) {\n if (data === null) return true;\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n if (_toString$1.call(pair) !== '[object Object]') return false;\n\n keys = Object.keys(pair);\n\n if (keys.length !== 1) return false;\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return true;\n}\n\nfunction constructYamlPairs(data) {\n if (data === null) return [];\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n keys = Object.keys(pair);\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return result;\n}\n\nvar pairs = new type('tag:yaml.org,2002:pairs', {\n kind: 'sequence',\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n});\n\nvar _hasOwnProperty$2 = Object.prototype.hasOwnProperty;\n\nfunction resolveYamlSet(data) {\n if (data === null) return true;\n\n var key, object = data;\n\n for (key in object) {\n if (_hasOwnProperty$2.call(object, key)) {\n if (object[key] !== null) return false;\n }\n }\n\n return true;\n}\n\nfunction constructYamlSet(data) {\n return data !== null ? data : {};\n}\n\nvar set = new type('tag:yaml.org,2002:set', {\n kind: 'mapping',\n resolve: resolveYamlSet,\n construct: constructYamlSet\n});\n\nvar _default = core.extend({\n implicit: [\n timestamp,\n merge\n ],\n explicit: [\n binary,\n omap,\n pairs,\n set\n ]\n});\n\n/*eslint-disable max-len,no-use-before-define*/\n\n\n\n\n\n\n\nvar _hasOwnProperty$1 = Object.prototype.hasOwnProperty;\n\n\nvar CONTEXT_FLOW_IN = 1;\nvar CONTEXT_FLOW_OUT = 2;\nvar CONTEXT_BLOCK_IN = 3;\nvar CONTEXT_BLOCK_OUT = 4;\n\n\nvar CHOMPING_CLIP = 1;\nvar CHOMPING_STRIP = 2;\nvar CHOMPING_KEEP = 3;\n\n\nvar PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\nvar PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\nvar PATTERN_FLOW_INDICATORS = /[,\\[\\]\\{\\}]/;\nvar PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\\-]+!)$/i;\nvar PATTERN_TAG_URI = /^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*'\\(\\)\\[\\]])*$/i;\n\n\nfunction _class(obj) { return Object.prototype.toString.call(obj); }\n\nfunction is_EOL(c) {\n return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);\n}\n\nfunction is_WHITE_SPACE(c) {\n return (c === 0x09/* Tab */) || (c === 0x20/* Space */);\n}\n\nfunction is_WS_OR_EOL(c) {\n return (c === 0x09/* Tab */) ||\n (c === 0x20/* Space */) ||\n (c === 0x0A/* LF */) ||\n (c === 0x0D/* CR */);\n}\n\nfunction is_FLOW_INDICATOR(c) {\n return c === 0x2C/* , */ ||\n c === 0x5B/* [ */ ||\n c === 0x5D/* ] */ ||\n c === 0x7B/* { */ ||\n c === 0x7D/* } */;\n}\n\nfunction fromHexCode(c) {\n var lc;\n\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n /*eslint-disable no-bitwise*/\n lc = c | 0x20;\n\n if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {\n return lc - 0x61 + 10;\n }\n\n return -1;\n}\n\nfunction escapedHexLen(c) {\n if (c === 0x78/* x */) { return 2; }\n if (c === 0x75/* u */) { return 4; }\n if (c === 0x55/* U */) { return 8; }\n return 0;\n}\n\nfunction fromDecimalCode(c) {\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n return -1;\n}\n\nfunction simpleEscapeSequence(c) {\n /* eslint-disable indent */\n return (c === 0x30/* 0 */) ? '\\x00' :\n (c === 0x61/* a */) ? '\\x07' :\n (c === 0x62/* b */) ? '\\x08' :\n (c === 0x74/* t */) ? '\\x09' :\n (c === 0x09/* Tab */) ? '\\x09' :\n (c === 0x6E/* n */) ? '\\x0A' :\n (c === 0x76/* v */) ? '\\x0B' :\n (c === 0x66/* f */) ? '\\x0C' :\n (c === 0x72/* r */) ? '\\x0D' :\n (c === 0x65/* e */) ? '\\x1B' :\n (c === 0x20/* Space */) ? ' ' :\n (c === 0x22/* \" */) ? '\\x22' :\n (c === 0x2F/* / */) ? '/' :\n (c === 0x5C/* \\ */) ? '\\x5C' :\n (c === 0x4E/* N */) ? '\\x85' :\n (c === 0x5F/* _ */) ? '\\xA0' :\n (c === 0x4C/* L */) ? '\\u2028' :\n (c === 0x50/* P */) ? '\\u2029' : '';\n}\n\nfunction charFromCodepoint(c) {\n if (c <= 0xFFFF) {\n return String.fromCharCode(c);\n }\n // Encode UTF-16 surrogate pair\n // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n return String.fromCharCode(\n ((c - 0x010000) >> 10) + 0xD800,\n ((c - 0x010000) & 0x03FF) + 0xDC00\n );\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty(object, key, value) {\n // used for this specific key only because Object.defineProperty is slow\n if (key === '__proto__') {\n Object.defineProperty(object, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: value\n });\n } else {\n object[key] = value;\n }\n}\n\nvar simpleEscapeCheck = new Array(256); // integer, for fast access\nvar simpleEscapeMap = new Array(256);\nfor (var i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n simpleEscapeMap[i] = simpleEscapeSequence(i);\n}\n\n\nfunction State$1(input, options) {\n this.input = input;\n\n this.filename = options['filename'] || null;\n this.schema = options['schema'] || _default;\n this.onWarning = options['onWarning'] || null;\n // (Hidden) Remove? makes the loader to expect YAML 1.1 documents\n // if such documents have no explicit %YAML directive\n this.legacy = options['legacy'] || false;\n\n this.json = options['json'] || false;\n this.listener = options['listener'] || null;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.typeMap = this.schema.compiledTypeMap;\n\n this.length = input.length;\n this.position = 0;\n this.line = 0;\n this.lineStart = 0;\n this.lineIndent = 0;\n\n // position of first leading tab in the current line,\n // used to make sure there are no tabs in the indentation\n this.firstTabInLine = -1;\n\n this.documents = [];\n\n /*\n this.version;\n this.checkLineBreaks;\n this.tagMap;\n this.anchorMap;\n this.tag;\n this.anchor;\n this.kind;\n this.result;*/\n\n}\n\n\nfunction generateError(state, message) {\n var mark = {\n name: state.filename,\n buffer: state.input.slice(0, -1), // omit trailing \\0\n position: state.position,\n line: state.line,\n column: state.position - state.lineStart\n };\n\n mark.snippet = snippet(mark);\n\n return new exception(message, mark);\n}\n\nfunction throwError(state, message) {\n throw generateError(state, message);\n}\n\nfunction throwWarning(state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message));\n }\n}\n\n\nvar directiveHandlers = {\n\n YAML: function handleYamlDirective(state, name, args) {\n\n var match, major, minor;\n\n if (state.version !== null) {\n throwError(state, 'duplication of %YAML directive');\n }\n\n if (args.length !== 1) {\n throwError(state, 'YAML directive accepts exactly one argument');\n }\n\n match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n\n if (match === null) {\n throwError(state, 'ill-formed argument of the YAML directive');\n }\n\n major = parseInt(match[1], 10);\n minor = parseInt(match[2], 10);\n\n if (major !== 1) {\n throwError(state, 'unacceptable YAML version of the document');\n }\n\n state.version = args[0];\n state.checkLineBreaks = (minor < 2);\n\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, 'unsupported YAML version of the document');\n }\n },\n\n TAG: function handleTagDirective(state, name, args) {\n\n var handle, prefix;\n\n if (args.length !== 2) {\n throwError(state, 'TAG directive accepts exactly two arguments');\n }\n\n handle = args[0];\n prefix = args[1];\n\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');\n }\n\n if (_hasOwnProperty$1.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle');\n }\n\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');\n }\n\n try {\n prefix = decodeURIComponent(prefix);\n } catch (err) {\n throwError(state, 'tag prefix is malformed: ' + prefix);\n }\n\n state.tagMap[handle] = prefix;\n }\n};\n\n\nfunction captureSegment(state, start, end, checkJson) {\n var _position, _length, _character, _result;\n\n if (start < end) {\n _result = state.input.slice(start, end);\n\n if (checkJson) {\n for (_position = 0, _length = _result.length; _position < _length; _position += 1) {\n _character = _result.charCodeAt(_position);\n if (!(_character === 0x09 ||\n (0x20 <= _character && _character <= 0x10FFFF))) {\n throwError(state, 'expected valid JSON character');\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, 'the stream contains non-printable characters');\n }\n\n state.result += _result;\n }\n}\n\nfunction mergeMappings(state, destination, source, overridableKeys) {\n var sourceKeys, key, index, quantity;\n\n if (!common.isObject(source)) {\n throwError(state, 'cannot merge mappings; the provided source object is unacceptable');\n }\n\n sourceKeys = Object.keys(source);\n\n for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n key = sourceKeys[index];\n\n if (!_hasOwnProperty$1.call(destination, key)) {\n setProperty(destination, key, source[key]);\n overridableKeys[key] = true;\n }\n }\n}\n\nfunction storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,\n startLine, startLineStart, startPos) {\n\n var index, quantity;\n\n // The output is a plain object here, so keys can only be strings.\n // We need to convert keyNode to a string, but doing so can hang the process\n // (deeply nested arrays that explode exponentially using aliases).\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode);\n\n for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, 'nested arrays are not supported inside keys');\n }\n\n if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n keyNode[index] = '[object Object]';\n }\n }\n }\n\n // Avoid code execution in load() via toString property\n // (still use its own toString for arrays, timestamps,\n // and whatever user schema extensions happen to have @@toStringTag)\n if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n keyNode = '[object Object]';\n }\n\n\n keyNode = String(keyNode);\n\n if (_result === null) {\n _result = {};\n }\n\n if (keyTag === 'tag:yaml.org,2002:merge') {\n if (Array.isArray(valueNode)) {\n for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n mergeMappings(state, _result, valueNode[index], overridableKeys);\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys);\n }\n } else {\n if (!state.json &&\n !_hasOwnProperty$1.call(overridableKeys, keyNode) &&\n _hasOwnProperty$1.call(_result, keyNode)) {\n state.line = startLine || state.line;\n state.lineStart = startLineStart || state.lineStart;\n state.position = startPos || state.position;\n throwError(state, 'duplicated mapping key');\n }\n\n setProperty(_result, keyNode, valueNode);\n delete overridableKeys[keyNode];\n }\n\n return _result;\n}\n\nfunction readLineBreak(state) {\n var ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x0A/* LF */) {\n state.position++;\n } else if (ch === 0x0D/* CR */) {\n state.position++;\n if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n state.position++;\n }\n } else {\n throwError(state, 'a line break is expected');\n }\n\n state.line += 1;\n state.lineStart = state.position;\n state.firstTabInLine = -1;\n}\n\nfunction skipSeparationSpace(state, allowComments, checkIndent) {\n var lineBreaks = 0,\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {\n state.firstTabInLine = state.position;\n }\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (allowComments && ch === 0x23/* # */) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);\n }\n\n if (is_EOL(ch)) {\n readLineBreak(state);\n\n ch = state.input.charCodeAt(state.position);\n lineBreaks++;\n state.lineIndent = 0;\n\n while (ch === 0x20/* Space */) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n } else {\n break;\n }\n }\n\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, 'deficient indentation');\n }\n\n return lineBreaks;\n}\n\nfunction testDocumentSeparator(state) {\n var _position = state.position,\n ch;\n\n ch = state.input.charCodeAt(_position);\n\n // Condition state.position === state.lineStart is tested\n // in parent on each call, for efficiency. No needs to test here again.\n if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n ch === state.input.charCodeAt(_position + 1) &&\n ch === state.input.charCodeAt(_position + 2)) {\n\n _position += 3;\n\n ch = state.input.charCodeAt(_position);\n\n if (ch === 0 || is_WS_OR_EOL(ch)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction writeFoldedLines(state, count) {\n if (count === 1) {\n state.result += ' ';\n } else if (count > 1) {\n state.result += common.repeat('\\n', count - 1);\n }\n}\n\n\nfunction readPlainScalar(state, nodeIndent, withinFlowCollection) {\n var preceding,\n following,\n captureStart,\n captureEnd,\n hasPendingContent,\n _line,\n _lineStart,\n _lineIndent,\n _kind = state.kind,\n _result = state.result,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (is_WS_OR_EOL(ch) ||\n is_FLOW_INDICATOR(ch) ||\n ch === 0x23/* # */ ||\n ch === 0x26/* & */ ||\n ch === 0x2A/* * */ ||\n ch === 0x21/* ! */ ||\n ch === 0x7C/* | */ ||\n ch === 0x3E/* > */ ||\n ch === 0x27/* ' */ ||\n ch === 0x22/* \" */ ||\n ch === 0x25/* % */ ||\n ch === 0x40/* @ */ ||\n ch === 0x60/* ` */) {\n return false;\n }\n\n if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n return false;\n }\n }\n\n state.kind = 'scalar';\n state.result = '';\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n\n while (ch !== 0) {\n if (ch === 0x3A/* : */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n break;\n }\n\n } else if (ch === 0x23/* # */) {\n preceding = state.input.charCodeAt(state.position - 1);\n\n if (is_WS_OR_EOL(preceding)) {\n break;\n }\n\n } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n withinFlowCollection && is_FLOW_INDICATOR(ch)) {\n break;\n\n } else if (is_EOL(ch)) {\n _line = state.line;\n _lineStart = state.lineStart;\n _lineIndent = state.lineIndent;\n skipSeparationSpace(state, false, -1);\n\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true;\n ch = state.input.charCodeAt(state.position);\n continue;\n } else {\n state.position = captureEnd;\n state.line = _line;\n state.lineStart = _lineStart;\n state.lineIndent = _lineIndent;\n break;\n }\n }\n\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false);\n writeFoldedLines(state, state.line - _line);\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n }\n\n if (!is_WHITE_SPACE(ch)) {\n captureEnd = state.position + 1;\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, captureEnd, false);\n\n if (state.result) {\n return true;\n }\n\n state.kind = _kind;\n state.result = _result;\n return false;\n}\n\nfunction readSingleQuotedScalar(state, nodeIndent) {\n var ch,\n captureStart, captureEnd;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x27/* ' */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x27/* ' */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x27/* ' */) {\n captureStart = state.position;\n state.position++;\n captureEnd = state.position;\n } else {\n return true;\n }\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a single quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a single quoted scalar');\n}\n\nfunction readDoubleQuotedScalar(state, nodeIndent) {\n var captureStart,\n captureEnd,\n hexLength,\n hexResult,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x22/* \" */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x22/* \" */) {\n captureSegment(state, captureStart, state.position, true);\n state.position++;\n return true;\n\n } else if (ch === 0x5C/* \\ */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (is_EOL(ch)) {\n skipSeparationSpace(state, false, nodeIndent);\n\n // TODO: rework to inline fn with no type cast?\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch];\n state.position++;\n\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n hexLength = tmp;\n hexResult = 0;\n\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position);\n\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp;\n\n } else {\n throwError(state, 'expected hexadecimal character');\n }\n }\n\n state.result += charFromCodepoint(hexResult);\n\n state.position++;\n\n } else {\n throwError(state, 'unknown escape sequence');\n }\n\n captureStart = captureEnd = state.position;\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a double quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a double quoted scalar');\n}\n\nfunction readFlowCollection(state, nodeIndent) {\n var readNext = true,\n _line,\n _lineStart,\n _pos,\n _tag = state.tag,\n _result,\n _anchor = state.anchor,\n following,\n terminator,\n isPair,\n isExplicitPair,\n isMapping,\n overridableKeys = Object.create(null),\n keyNode,\n keyTag,\n valueNode,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x5B/* [ */) {\n terminator = 0x5D;/* ] */\n isMapping = false;\n _result = [];\n } else if (ch === 0x7B/* { */) {\n terminator = 0x7D;/* } */\n isMapping = true;\n _result = {};\n } else {\n return false;\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === terminator) {\n state.position++;\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = isMapping ? 'mapping' : 'sequence';\n state.result = _result;\n return true;\n } else if (!readNext) {\n throwError(state, 'missed comma between flow collection entries');\n } else if (ch === 0x2C/* , */) {\n // \"flow collection entries can never be completely empty\", as per YAML 1.2, section 7.4\n throwError(state, \"expected the node content, but found ','\");\n }\n\n keyTag = keyNode = valueNode = null;\n isPair = isExplicitPair = false;\n\n if (ch === 0x3F/* ? */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following)) {\n isPair = isExplicitPair = true;\n state.position++;\n skipSeparationSpace(state, true, nodeIndent);\n }\n }\n\n _line = state.line; // Save the current line.\n _lineStart = state.lineStart;\n _pos = state.position;\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n keyTag = state.tag;\n keyNode = state.result;\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n isPair = true;\n ch = state.input.charCodeAt(++state.position);\n skipSeparationSpace(state, true, nodeIndent);\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n valueNode = state.result;\n }\n\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));\n } else {\n _result.push(keyNode);\n }\n\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x2C/* , */) {\n readNext = true;\n ch = state.input.charCodeAt(++state.position);\n } else {\n readNext = false;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a flow collection');\n}\n\nfunction readBlockScalar(state, nodeIndent) {\n var captureStart,\n folding,\n chomping = CHOMPING_CLIP,\n didReadContent = false,\n detectedIndent = false,\n textIndent = nodeIndent,\n emptyLines = 0,\n atMoreIndented = false,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x7C/* | */) {\n folding = false;\n } else if (ch === 0x3E/* > */) {\n folding = true;\n } else {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n if (CHOMPING_CLIP === chomping) {\n chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;\n } else {\n throwError(state, 'repeat of a chomping mode identifier');\n }\n\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1;\n detectedIndent = true;\n } else {\n throwError(state, 'repeat of an indentation width identifier');\n }\n\n } else {\n break;\n }\n }\n\n if (is_WHITE_SPACE(ch)) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (is_WHITE_SPACE(ch));\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (!is_EOL(ch) && (ch !== 0));\n }\n }\n\n while (ch !== 0) {\n readLineBreak(state);\n state.lineIndent = 0;\n\n ch = state.input.charCodeAt(state.position);\n\n while ((!detectedIndent || state.lineIndent < textIndent) &&\n (ch === 0x20/* Space */)) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent;\n }\n\n if (is_EOL(ch)) {\n emptyLines++;\n continue;\n }\n\n // End of the scalar.\n if (state.lineIndent < textIndent) {\n\n // Perform the chomping.\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) { // i.e. only if the scalar is not empty.\n state.result += '\\n';\n }\n }\n\n // Break this `while` cycle and go to the funciton's epilogue.\n break;\n }\n\n // Folded style: use fancy rules to handle line breaks.\n if (folding) {\n\n // Lines starting with white space characters (more-indented lines) are not folded.\n if (is_WHITE_SPACE(ch)) {\n atMoreIndented = true;\n // except for the first content line (cf. Example 8.1)\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n\n // End of more-indented block.\n } else if (atMoreIndented) {\n atMoreIndented = false;\n state.result += common.repeat('\\n', emptyLines + 1);\n\n // Just one line break - perceive as the same line.\n } else if (emptyLines === 0) {\n if (didReadContent) { // i.e. only if we have already read some scalar content.\n state.result += ' ';\n }\n\n // Several line breaks - perceive as different lines.\n } else {\n state.result += common.repeat('\\n', emptyLines);\n }\n\n // Literal style: just add exact number of line breaks between content lines.\n } else {\n // Keep all line breaks except the header line break.\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n }\n\n didReadContent = true;\n detectedIndent = true;\n emptyLines = 0;\n captureStart = state.position;\n\n while (!is_EOL(ch) && (ch !== 0)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, state.position, false);\n }\n\n return true;\n}\n\nfunction readBlockSequence(state, nodeIndent) {\n var _line,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = [],\n following,\n detected = false,\n ch;\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n if (state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine;\n throwError(state, 'tab characters must not be used in indentation');\n }\n\n if (ch !== 0x2D/* - */) {\n break;\n }\n\n following = state.input.charCodeAt(state.position + 1);\n\n if (!is_WS_OR_EOL(following)) {\n break;\n }\n\n detected = true;\n state.position++;\n\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null);\n ch = state.input.charCodeAt(state.position);\n continue;\n }\n }\n\n _line = state.line;\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n _result.push(state.result);\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a sequence entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'sequence';\n state.result = _result;\n return true;\n }\n return false;\n}\n\nfunction readBlockMapping(state, nodeIndent, flowIndent) {\n var following,\n allowCompact,\n _line,\n _keyLine,\n _keyLineStart,\n _keyPos,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = {},\n overridableKeys = Object.create(null),\n keyTag = null,\n keyNode = null,\n valueNode = null,\n atExplicitKey = false,\n detected = false,\n ch;\n\n // there is a leading tab before this token, so it can't be a block sequence/mapping;\n // it can still be flow sequence/mapping or a scalar\n if (state.firstTabInLine !== -1) return false;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n if (!atExplicitKey && state.firstTabInLine !== -1) {\n state.position = state.firstTabInLine;\n throwError(state, 'tab characters must not be used in indentation');\n }\n\n following = state.input.charCodeAt(state.position + 1);\n _line = state.line; // Save the current line.\n\n //\n // Explicit notation case. There are two separate blocks:\n // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n //\n if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {\n\n if (ch === 0x3F/* ? */) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = true;\n allowCompact = true;\n\n } else if (atExplicitKey) {\n // i.e. 0x3A/* : */ === character after the explicit key.\n atExplicitKey = false;\n allowCompact = true;\n\n } else {\n throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');\n }\n\n state.position += 1;\n ch = following;\n\n //\n // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n //\n } else {\n _keyLine = state.line;\n _keyLineStart = state.lineStart;\n _keyPos = state.position;\n\n if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n // Neither implicit nor explicit notation.\n // Reading is done. Go to the epilogue.\n break;\n }\n\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position);\n\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x3A/* : */) {\n ch = state.input.charCodeAt(++state.position);\n\n if (!is_WS_OR_EOL(ch)) {\n throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');\n }\n\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = false;\n allowCompact = false;\n keyTag = state.tag;\n keyNode = state.result;\n\n } else if (detected) {\n throwError(state, 'can not read an implicit mapping pair; a colon is missed');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n\n } else if (detected) {\n throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n }\n\n //\n // Common reading code for both explicit and implicit notations.\n //\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (atExplicitKey) {\n _keyLine = state.line;\n _keyLineStart = state.lineStart;\n _keyPos = state.position;\n }\n\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result;\n } else {\n valueNode = state.result;\n }\n }\n\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);\n keyTag = keyNode = valueNode = null;\n }\n\n skipSeparationSpace(state, true, -1);\n ch = state.input.charCodeAt(state.position);\n }\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a mapping entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n //\n // Epilogue.\n //\n\n // Special case: last mapping's node contains only the key in explicit notation.\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n }\n\n // Expose the resulting mapping.\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'mapping';\n state.result = _result;\n }\n\n return detected;\n}\n\nfunction readTagProperty(state) {\n var _position,\n isVerbatim = false,\n isNamed = false,\n tagHandle,\n tagName,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x21/* ! */) return false;\n\n if (state.tag !== null) {\n throwError(state, 'duplication of a tag property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x3C/* < */) {\n isVerbatim = true;\n ch = state.input.charCodeAt(++state.position);\n\n } else if (ch === 0x21/* ! */) {\n isNamed = true;\n tagHandle = '!!';\n ch = state.input.charCodeAt(++state.position);\n\n } else {\n tagHandle = '!';\n }\n\n _position = state.position;\n\n if (isVerbatim) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && ch !== 0x3E/* > */);\n\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position);\n ch = state.input.charCodeAt(++state.position);\n } else {\n throwError(state, 'unexpected end of the stream within a verbatim tag');\n }\n } else {\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n\n if (ch === 0x21/* ! */) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1);\n\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, 'named tag handle cannot contain such characters');\n }\n\n isNamed = true;\n _position = state.position + 1;\n } else {\n throwError(state, 'tag suffix cannot contain exclamation marks');\n }\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n tagName = state.input.slice(_position, state.position);\n\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, 'tag suffix cannot contain flow indicator characters');\n }\n }\n\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, 'tag name cannot contain such characters: ' + tagName);\n }\n\n try {\n tagName = decodeURIComponent(tagName);\n } catch (err) {\n throwError(state, 'tag name is malformed: ' + tagName);\n }\n\n if (isVerbatim) {\n state.tag = tagName;\n\n } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName;\n\n } else if (tagHandle === '!') {\n state.tag = '!' + tagName;\n\n } else if (tagHandle === '!!') {\n state.tag = 'tag:yaml.org,2002:' + tagName;\n\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"');\n }\n\n return true;\n}\n\nfunction readAnchorProperty(state) {\n var _position,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x26/* & */) return false;\n\n if (state.anchor !== null) {\n throwError(state, 'duplication of an anchor property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an anchor node must contain at least one character');\n }\n\n state.anchor = state.input.slice(_position, state.position);\n return true;\n}\n\nfunction readAlias(state) {\n var _position, alias,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x2A/* * */) return false;\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an alias node must contain at least one character');\n }\n\n alias = state.input.slice(_position, state.position);\n\n if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"');\n }\n\n state.result = state.anchorMap[alias];\n skipSeparationSpace(state, true, -1);\n return true;\n}\n\nfunction composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n var allowBlockStyles,\n allowBlockScalars,\n allowBlockCollections,\n indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent\n atNewLine = false,\n hasContent = false,\n typeIndex,\n typeQuantity,\n typeList,\n type,\n flowIndent,\n blockIndent;\n\n if (state.listener !== null) {\n state.listener('open', state);\n }\n\n state.tag = null;\n state.anchor = null;\n state.kind = null;\n state.result = null;\n\n allowBlockStyles = allowBlockScalars = allowBlockCollections =\n CONTEXT_BLOCK_OUT === nodeContext ||\n CONTEXT_BLOCK_IN === nodeContext;\n\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n }\n }\n\n if (indentStatus === 1) {\n while (readTagProperty(state) || readAnchorProperty(state)) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n allowBlockCollections = allowBlockStyles;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n } else {\n allowBlockCollections = false;\n }\n }\n }\n\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact;\n }\n\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent;\n } else {\n flowIndent = parentIndent + 1;\n }\n\n blockIndent = state.position - state.lineStart;\n\n if (indentStatus === 1) {\n if (allowBlockCollections &&\n (readBlockSequence(state, blockIndent) ||\n readBlockMapping(state, blockIndent, flowIndent)) ||\n readFlowCollection(state, flowIndent)) {\n hasContent = true;\n } else {\n if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n readSingleQuotedScalar(state, flowIndent) ||\n readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true;\n\n } else if (readAlias(state)) {\n hasContent = true;\n\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, 'alias node should not have any properties');\n }\n\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true;\n\n if (state.tag === null) {\n state.tag = '?';\n }\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n } else if (indentStatus === 0) {\n // Special case: block sequences are allowed to have same indentation level as the parent.\n // http://www.yaml.org/spec/1.2/spec.html#id2799784\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n }\n }\n\n if (state.tag === null) {\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n\n } else if (state.tag === '?') {\n // Implicit resolving is not allowed for non-scalar types, and '?'\n // non-specific tag is only automatically assigned to plain scalars.\n //\n // We only need to check kind conformity in case user explicitly assigns '?'\n // tag, for example like this: \"!<?> [0]\"\n //\n if (state.result !== null && state.kind !== 'scalar') {\n throwError(state, 'unacceptable node kind for !<?> tag; it should be \"scalar\", not \"' + state.kind + '\"');\n }\n\n for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type = state.implicitTypes[typeIndex];\n\n if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n state.result = type.construct(state.result);\n state.tag = type.tag;\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n break;\n }\n }\n } else if (state.tag !== '!') {\n if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n type = state.typeMap[state.kind || 'fallback'][state.tag];\n } else {\n // looking for multi type\n type = null;\n typeList = state.typeMap.multi[state.kind || 'fallback'];\n\n for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {\n if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n type = typeList[typeIndex];\n break;\n }\n }\n }\n\n if (!type) {\n throwError(state, 'unknown tag !<' + state.tag + '>');\n }\n\n if (state.result !== null && type.kind !== state.kind) {\n throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"');\n }\n\n if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched\n throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');\n } else {\n state.result = type.construct(state.result, state.tag);\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n }\n\n if (state.listener !== null) {\n state.listener('close', state);\n }\n return state.tag !== null || state.anchor !== null || hasContent;\n}\n\nfunction readDocument(state) {\n var documentStart = state.position,\n _position,\n directiveName,\n directiveArgs,\n hasDirectives = false,\n ch;\n\n state.version = null;\n state.checkLineBreaks = state.legacy;\n state.tagMap = Object.create(null);\n state.anchorMap = Object.create(null);\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n break;\n }\n\n hasDirectives = true;\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveName = state.input.slice(_position, state.position);\n directiveArgs = [];\n\n if (directiveName.length < 1) {\n throwError(state, 'directive name must not be less than one character in length');\n }\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && !is_EOL(ch));\n break;\n }\n\n if (is_EOL(ch)) break;\n\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveArgs.push(state.input.slice(_position, state.position));\n }\n\n if (ch !== 0) readLineBreak(state);\n\n if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs);\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"');\n }\n }\n\n skipSeparationSpace(state, true, -1);\n\n if (state.lineIndent === 0 &&\n state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n\n } else if (hasDirectives) {\n throwError(state, 'directives end mark is expected');\n }\n\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n skipSeparationSpace(state, true, -1);\n\n if (state.checkLineBreaks &&\n PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, 'non-ASCII line breaks are interpreted as content');\n }\n\n state.documents.push(state.result);\n\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n\n if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n }\n return;\n }\n\n if (state.position < (state.length - 1)) {\n throwError(state, 'end of the stream or a document separator is expected');\n } else {\n return;\n }\n}\n\n\nfunction loadDocuments(input, options) {\n input = String(input);\n options = options || {};\n\n if (input.length !== 0) {\n\n // Add tailing `\\n` if not exists\n if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n input += '\\n';\n }\n\n // Strip BOM\n if (input.charCodeAt(0) === 0xFEFF) {\n input = input.slice(1);\n }\n }\n\n var state = new State$1(input, options);\n\n var nullpos = input.indexOf('\\0');\n\n if (nullpos !== -1) {\n state.position = nullpos;\n throwError(state, 'null byte is not allowed in input');\n }\n\n // Use 0 as string terminator. That significantly simplifies bounds check.\n state.input += '\\0';\n\n while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n state.lineIndent += 1;\n state.position += 1;\n }\n\n while (state.position < (state.length - 1)) {\n readDocument(state);\n }\n\n return state.documents;\n}\n\n\nfunction loadAll$1(input, iterator, options) {\n if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n options = iterator;\n iterator = null;\n }\n\n var documents = loadDocuments(input, options);\n\n if (typeof iterator !== 'function') {\n return documents;\n }\n\n for (var index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index]);\n }\n}\n\n\nfunction load$1(input, options) {\n var documents = loadDocuments(input, options);\n\n if (documents.length === 0) {\n /*eslint-disable no-undefined*/\n return undefined;\n } else if (documents.length === 1) {\n return documents[0];\n }\n throw new exception('expected a single document in the stream, but found more');\n}\n\n\nvar loadAll_1 = loadAll$1;\nvar load_1 = load$1;\n\nvar loader = {\n\tloadAll: loadAll_1,\n\tload: load_1\n};\n\n/*eslint-disable no-use-before-define*/\n\n\n\n\n\nvar _toString = Object.prototype.toString;\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar CHAR_BOM = 0xFEFF;\nvar CHAR_TAB = 0x09; /* Tab */\nvar CHAR_LINE_FEED = 0x0A; /* LF */\nvar CHAR_CARRIAGE_RETURN = 0x0D; /* CR */\nvar CHAR_SPACE = 0x20; /* Space */\nvar CHAR_EXCLAMATION = 0x21; /* ! */\nvar CHAR_DOUBLE_QUOTE = 0x22; /* \" */\nvar CHAR_SHARP = 0x23; /* # */\nvar CHAR_PERCENT = 0x25; /* % */\nvar CHAR_AMPERSAND = 0x26; /* & */\nvar CHAR_SINGLE_QUOTE = 0x27; /* ' */\nvar CHAR_ASTERISK = 0x2A; /* * */\nvar CHAR_COMMA = 0x2C; /* , */\nvar CHAR_MINUS = 0x2D; /* - */\nvar CHAR_COLON = 0x3A; /* : */\nvar CHAR_EQUALS = 0x3D; /* = */\nvar CHAR_GREATER_THAN = 0x3E; /* > */\nvar CHAR_QUESTION = 0x3F; /* ? */\nvar CHAR_COMMERCIAL_AT = 0x40; /* @ */\nvar CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */\nvar CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */\nvar CHAR_GRAVE_ACCENT = 0x60; /* ` */\nvar CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */\nvar CHAR_VERTICAL_LINE = 0x7C; /* | */\nvar CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */\n\nvar ESCAPE_SEQUENCES = {};\n\nESCAPE_SEQUENCES[0x00] = '\\\\0';\nESCAPE_SEQUENCES[0x07] = '\\\\a';\nESCAPE_SEQUENCES[0x08] = '\\\\b';\nESCAPE_SEQUENCES[0x09] = '\\\\t';\nESCAPE_SEQUENCES[0x0A] = '\\\\n';\nESCAPE_SEQUENCES[0x0B] = '\\\\v';\nESCAPE_SEQUENCES[0x0C] = '\\\\f';\nESCAPE_SEQUENCES[0x0D] = '\\\\r';\nESCAPE_SEQUENCES[0x1B] = '\\\\e';\nESCAPE_SEQUENCES[0x22] = '\\\\\"';\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\';\nESCAPE_SEQUENCES[0x85] = '\\\\N';\nESCAPE_SEQUENCES[0xA0] = '\\\\_';\nESCAPE_SEQUENCES[0x2028] = '\\\\L';\nESCAPE_SEQUENCES[0x2029] = '\\\\P';\n\nvar DEPRECATED_BOOLEANS_SYNTAX = [\n 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n];\n\nvar DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/;\n\nfunction compileStyleMap(schema, map) {\n var result, keys, index, length, tag, style, type;\n\n if (map === null) return {};\n\n result = {};\n keys = Object.keys(map);\n\n for (index = 0, length = keys.length; index < length; index += 1) {\n tag = keys[index];\n style = String(map[tag]);\n\n if (tag.slice(0, 2) === '!!') {\n tag = 'tag:yaml.org,2002:' + tag.slice(2);\n }\n type = schema.compiledTypeMap['fallback'][tag];\n\n if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n style = type.styleAliases[style];\n }\n\n result[tag] = style;\n }\n\n return result;\n}\n\nfunction encodeHex(character) {\n var string, handle, length;\n\n string = character.toString(16).toUpperCase();\n\n if (character <= 0xFF) {\n handle = 'x';\n length = 2;\n } else if (character <= 0xFFFF) {\n handle = 'u';\n length = 4;\n } else if (character <= 0xFFFFFFFF) {\n handle = 'U';\n length = 8;\n } else {\n throw new exception('code point within a string may not be greater than 0xFFFFFFFF');\n }\n\n return '\\\\' + handle + common.repeat('0', length - string.length) + string;\n}\n\n\nvar QUOTING_TYPE_SINGLE = 1,\n QUOTING_TYPE_DOUBLE = 2;\n\nfunction State(options) {\n this.schema = options['schema'] || _default;\n this.indent = Math.max(1, (options['indent'] || 2));\n this.noArrayIndent = options['noArrayIndent'] || false;\n this.skipInvalid = options['skipInvalid'] || false;\n this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);\n this.styleMap = compileStyleMap(this.schema, options['styles'] || null);\n this.sortKeys = options['sortKeys'] || false;\n this.lineWidth = options['lineWidth'] || 80;\n this.noRefs = options['noRefs'] || false;\n this.noCompatMode = options['noCompatMode'] || false;\n this.condenseFlow = options['condenseFlow'] || false;\n this.quotingType = options['quotingType'] === '\"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;\n this.forceQuotes = options['forceQuotes'] || false;\n this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.explicitTypes = this.schema.compiledExplicit;\n\n this.tag = null;\n this.result = '';\n\n this.duplicates = [];\n this.usedDuplicates = null;\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString(string, spaces) {\n var ind = common.repeat(' ', spaces),\n position = 0,\n next = -1,\n result = '',\n line,\n length = string.length;\n\n while (position < length) {\n next = string.indexOf('\\n', position);\n if (next === -1) {\n line = string.slice(position);\n position = length;\n } else {\n line = string.slice(position, next + 1);\n position = next + 1;\n }\n\n if (line.length && line !== '\\n') result += ind;\n\n result += line;\n }\n\n return result;\n}\n\nfunction generateNextLine(state, level) {\n return '\\n' + common.repeat(' ', state.indent * level);\n}\n\nfunction testImplicitResolving(state, str) {\n var index, length, type;\n\n for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n type = state.implicitTypes[index];\n\n if (type.resolve(str)) {\n return true;\n }\n }\n\n return false;\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace(c) {\n return c === CHAR_SPACE || c === CHAR_TAB;\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable(c) {\n return (0x00020 <= c && c <= 0x00007E)\n || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)\n || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)\n || (0x10000 <= c && c <= 0x10FFFF);\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char ::= b-line-feed | b-carriage-return\n// Including s-white (for some reason, examples doesn't match specs in this aspect)\n// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark\nfunction isNsCharOrWhitespace(c) {\n return isPrintable(c)\n && c !== CHAR_BOM\n // - b-char\n && c !== CHAR_CARRIAGE_RETURN\n && c !== CHAR_LINE_FEED;\n}\n\n// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out\n// c = flow-in ⇒ ns-plain-safe-in\n// c = block-key ⇒ ns-plain-safe-out\n// c = flow-key ⇒ ns-plain-safe-in\n// [128] ns-plain-safe-out ::= ns-char\n// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator\n// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )\n// | ( /* An ns-char preceding */ “#” )\n// | ( “:” /* Followed by an ns-plain-safe(c) */ )\nfunction isPlainSafe(c, prev, inblock) {\n var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);\n var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);\n return (\n // ns-plain-safe\n inblock ? // c = flow-in\n cIsNsCharOrWhitespace\n : cIsNsCharOrWhitespace\n // - c-flow-indicator\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n )\n // ns-plain-char\n && c !== CHAR_SHARP // false on '#'\n && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '\n || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'\n || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst(c) {\n // Uses a subset of ns-char - c-indicator\n // where ns-char = nb-char - s-white.\n // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part\n return isPrintable(c) && c !== CHAR_BOM\n && !isWhitespace(c) // - s-white\n // - (c-indicator ::=\n // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”\n && c !== CHAR_MINUS\n && c !== CHAR_QUESTION\n && c !== CHAR_COLON\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “\"”\n && c !== CHAR_SHARP\n && c !== CHAR_AMPERSAND\n && c !== CHAR_ASTERISK\n && c !== CHAR_EXCLAMATION\n && c !== CHAR_VERTICAL_LINE\n && c !== CHAR_EQUALS\n && c !== CHAR_GREATER_THAN\n && c !== CHAR_SINGLE_QUOTE\n && c !== CHAR_DOUBLE_QUOTE\n // | “%” | “@” | “`”)\n && c !== CHAR_PERCENT\n && c !== CHAR_COMMERCIAL_AT\n && c !== CHAR_GRAVE_ACCENT;\n}\n\n// Simplified test for values allowed as the last character in plain style.\nfunction isPlainSafeLast(c) {\n // just not whitespace or colon, it will be checked to be plain character later\n return !isWhitespace(c) && c !== CHAR_COLON;\n}\n\n// Same as 'string'.codePointAt(pos), but works in older browsers.\nfunction codePointAt(string, pos) {\n var first = string.charCodeAt(pos), second;\n if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {\n second = string.charCodeAt(pos + 1);\n if (second >= 0xDC00 && second <= 0xDFFF) {\n // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n }\n }\n return first;\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator(string) {\n var leadingSpaceRe = /^\\n* /;\n return leadingSpaceRe.test(string);\n}\n\nvar STYLE_PLAIN = 1,\n STYLE_SINGLE = 2,\n STYLE_LITERAL = 3,\n STYLE_FOLDED = 4,\n STYLE_DOUBLE = 5;\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n// STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,\n testAmbiguousType, quotingType, forceQuotes, inblock) {\n\n var i;\n var char = 0;\n var prevChar = null;\n var hasLineBreak = false;\n var hasFoldableLine = false; // only checked if shouldTrackWidth\n var shouldTrackWidth = lineWidth !== -1;\n var previousLineBreak = -1; // count the first line correctly\n var plain = isPlainSafeFirst(codePointAt(string, 0))\n && isPlainSafeLast(codePointAt(string, string.length - 1));\n\n if (singleLineOnly || forceQuotes) {\n // Case: no block styles.\n // Check for disallowed characters to rule out plain and single.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i);\n if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n plain = plain && isPlainSafe(char, prevChar, inblock);\n prevChar = char;\n }\n } else {\n // Case: block styles permitted.\n for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i);\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true;\n // Check if any line can be folded.\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine ||\n // Foldable line = too long, and not more-indented.\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' ');\n previousLineBreak = i;\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n plain = plain && isPlainSafe(char, prevChar, inblock);\n prevChar = char;\n }\n // in case the end is missing a \\n\n hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' '));\n }\n // Although every style can represent \\n without escaping, prefer block styles\n // for multiline, since they're more readable and they don't add empty lines.\n // Also prefer folding a super-long line.\n if (!hasLineBreak && !hasFoldableLine) {\n // Strings interpretable as another type have to be quoted;\n // e.g. the string 'true' vs. the boolean true.\n if (plain && !forceQuotes && !testAmbiguousType(string)) {\n return STYLE_PLAIN;\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n }\n // Edge case: block indentation indicator can only have one digit.\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE;\n }\n // At this point we know block styles are valid.\n // Prefer literal style unless we want to fold.\n if (!forceQuotes) {\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n }\n return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n// since the dumper adds its own newline. This always works:\n// • No ending newline => unaffected; already using strip \"-\" chomping.\n// • Ending newline => removed then restored.\n// Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar(state, string, level, iskey, inblock) {\n state.dump = (function () {\n if (string.length === 0) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? '\"\"' : \"''\";\n }\n if (!state.noCompatMode) {\n if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {\n return state.quotingType === QUOTING_TYPE_DOUBLE ? ('\"' + string + '\"') : (\"'\" + string + \"'\");\n }\n }\n\n var indent = state.indent * Math.max(1, level); // no 0-indent scalars\n // As indentation gets deeper, let the width decrease monotonically\n // to the lower bound min(state.lineWidth, 40).\n // Note that this implies\n // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.\n // state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n // This behaves better than a constant minimum width which disallows narrower options,\n // or an indent threshold which causes the width to suddenly increase.\n var lineWidth = state.lineWidth === -1\n ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n\n // Without knowing if keys are implicit/explicit, assume implicit for safety.\n var singleLineOnly = iskey\n // No block styles in flow mode.\n || (state.flowLevel > -1 && level >= state.flowLevel);\n function testAmbiguity(string) {\n return testImplicitResolving(state, string);\n }\n\n switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,\n testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {\n\n case STYLE_PLAIN:\n return string;\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\";\n case STYLE_LITERAL:\n return '|' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(string, indent));\n case STYLE_FOLDED:\n return '>' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n case STYLE_DOUBLE:\n return '\"' + escapeString(string) + '\"';\n default:\n throw new exception('impossible error: invalid scalar style');\n }\n }());\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader(string, indentPerLevel) {\n var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';\n\n // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n var clip = string[string.length - 1] === '\\n';\n var keep = clip && (string[string.length - 2] === '\\n' || string === '\\n');\n var chomp = keep ? '+' : (clip ? '' : '-');\n\n return indentIndicator + chomp + '\\n';\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline(string) {\n return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string;\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString(string, width) {\n // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n // unless they're before or after a more-indented line, or at the very\n // beginning or end, in which case $k$ maps to $k$.\n // Therefore, parse each chunk as newline(s) followed by a content line.\n var lineRe = /(\\n+)([^\\n]*)/g;\n\n // first line (possibly an empty line)\n var result = (function () {\n var nextLF = string.indexOf('\\n');\n nextLF = nextLF !== -1 ? nextLF : string.length;\n lineRe.lastIndex = nextLF;\n return foldLine(string.slice(0, nextLF), width);\n }());\n // If we haven't reached the first content line yet, don't add an extra \\n.\n var prevMoreIndented = string[0] === '\\n' || string[0] === ' ';\n var moreIndented;\n\n // rest of the lines\n var match;\n while ((match = lineRe.exec(string))) {\n var prefix = match[1], line = match[2];\n moreIndented = (line[0] === ' ');\n result += prefix\n + (!prevMoreIndented && !moreIndented && line !== ''\n ? '\\n' : '')\n + foldLine(line, width);\n prevMoreIndented = moreIndented;\n }\n\n return result;\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine(line, width) {\n if (line === '' || line[0] === ' ') return line;\n\n // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.\n var match;\n // start is an inclusive index. end, curr, and next are exclusive.\n var start = 0, end, curr = 0, next = 0;\n var result = '';\n\n // Invariants: 0 <= start <= length-1.\n // 0 <= curr <= next <= max(0, length-2). curr - start <= width.\n // Inside the loop:\n // A match implies length >= 2, so curr and next are <= length-2.\n while ((match = breakRe.exec(line))) {\n next = match.index;\n // maintain invariant: curr - start <= width\n if (next - start > width) {\n end = (curr > start) ? curr : next; // derive end <= length-2\n result += '\\n' + line.slice(start, end);\n // skip the space that was output as \\n\n start = end + 1; // derive start <= length-1\n }\n curr = next;\n }\n\n // By the invariants, start <= length-1, so there is something left over.\n // It is either the whole string or a part starting from non-whitespace.\n result += '\\n';\n // Insert a break if the remainder is too long and there is a break available.\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + '\\n' + line.slice(curr + 1);\n } else {\n result += line.slice(start);\n }\n\n return result.slice(1); // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString(string) {\n var result = '';\n var char = 0;\n var escapeSeq;\n\n for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n char = codePointAt(string, i);\n escapeSeq = ESCAPE_SEQUENCES[char];\n\n if (!escapeSeq && isPrintable(char)) {\n result += string[i];\n if (char >= 0x10000) result += string[i + 1];\n } else {\n result += escapeSeq || encodeHex(char);\n }\n }\n\n return result;\n}\n\nfunction writeFlowSequence(state, level, object) {\n var _result = '',\n _tag = state.tag,\n index,\n length,\n value;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n value = object[index];\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value);\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level, value, false, false) ||\n (typeof value === 'undefined' &&\n writeNode(state, level, null, false, false))) {\n\n if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = '[' + _result + ']';\n}\n\nfunction writeBlockSequence(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n index,\n length,\n value;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n value = object[index];\n\n if (state.replacer) {\n value = state.replacer.call(object, String(index), value);\n }\n\n // Write only valid elements, put null instead of invalid elements.\n if (writeNode(state, level + 1, value, true, true, false, true) ||\n (typeof value === 'undefined' &&\n writeNode(state, level + 1, null, true, true, false, true))) {\n\n if (!compact || _result !== '') {\n _result += generateNextLine(state, level);\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += '-';\n } else {\n _result += '- ';\n }\n\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = _result || '[]'; // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping(state, level, object) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n pairBuffer;\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n\n pairBuffer = '';\n if (_result !== '') pairBuffer += ', ';\n\n if (state.condenseFlow) pairBuffer += '\"';\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue);\n }\n\n if (!writeNode(state, level, objectKey, false, false)) {\n continue; // Skip this pair because of invalid key;\n }\n\n if (state.dump.length > 1024) pairBuffer += '? ';\n\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ');\n\n if (!writeNode(state, level, objectValue, false, false)) {\n continue; // Skip this pair because of invalid value.\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = '{' + _result + '}';\n}\n\nfunction writeBlockMapping(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n explicitPair,\n pairBuffer;\n\n // Allow sorting keys so that the output file is deterministic\n if (state.sortKeys === true) {\n // Default sorting\n objectKeyList.sort();\n } else if (typeof state.sortKeys === 'function') {\n // Custom sort function\n objectKeyList.sort(state.sortKeys);\n } else if (state.sortKeys) {\n // Something is wrong\n throw new exception('sortKeys must be a boolean or a function');\n }\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n pairBuffer = '';\n\n if (!compact || _result !== '') {\n pairBuffer += generateNextLine(state, level);\n }\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (state.replacer) {\n objectValue = state.replacer.call(object, objectKey, objectValue);\n }\n\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue; // Skip this pair because of invalid key.\n }\n\n explicitPair = (state.tag !== null && state.tag !== '?') ||\n (state.dump && state.dump.length > 1024);\n\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += '?';\n } else {\n pairBuffer += '? ';\n }\n }\n\n pairBuffer += state.dump;\n\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level);\n }\n\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue; // Skip this pair because of invalid value.\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += ':';\n } else {\n pairBuffer += ': ';\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = _result || '{}'; // Empty mapping if no valid pairs.\n}\n\nfunction detectType(state, object, explicit) {\n var _result, typeList, index, length, type, style;\n\n typeList = explicit ? state.explicitTypes : state.implicitTypes;\n\n for (index = 0, length = typeList.length; index < length; index += 1) {\n type = typeList[index];\n\n if ((type.instanceOf || type.predicate) &&\n (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n (!type.predicate || type.predicate(object))) {\n\n if (explicit) {\n if (type.multi && type.representName) {\n state.tag = type.representName(object);\n } else {\n state.tag = type.tag;\n }\n } else {\n state.tag = '?';\n }\n\n if (type.represent) {\n style = state.styleMap[type.tag] || type.defaultStyle;\n\n if (_toString.call(type.represent) === '[object Function]') {\n _result = type.represent(object, style);\n } else if (_hasOwnProperty.call(type.represent, style)) {\n _result = type.represent[style](object, style);\n } else {\n throw new exception('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style');\n }\n\n state.dump = _result;\n }\n\n return true;\n }\n }\n\n return false;\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode(state, level, object, block, compact, iskey, isblockseq) {\n state.tag = null;\n state.dump = object;\n\n if (!detectType(state, object, false)) {\n detectType(state, object, true);\n }\n\n var type = _toString.call(state.dump);\n var inblock = block;\n var tagStr;\n\n if (block) {\n block = (state.flowLevel < 0 || state.flowLevel > level);\n }\n\n var objectOrArray = type === '[object Object]' || type === '[object Array]',\n duplicateIndex,\n duplicate;\n\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object);\n duplicate = duplicateIndex !== -1;\n }\n\n if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n compact = false;\n }\n\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = '*ref_' + duplicateIndex;\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true;\n }\n if (type === '[object Object]') {\n if (block && (Object.keys(state.dump).length !== 0)) {\n writeBlockMapping(state, level, state.dump, compact);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowMapping(state, level, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object Array]') {\n if (block && (state.dump.length !== 0)) {\n if (state.noArrayIndent && !isblockseq && level > 0) {\n writeBlockSequence(state, level - 1, state.dump, compact);\n } else {\n writeBlockSequence(state, level, state.dump, compact);\n }\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowSequence(state, level, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object String]') {\n if (state.tag !== '?') {\n writeScalar(state, state.dump, level, iskey, inblock);\n }\n } else if (type === '[object Undefined]') {\n return false;\n } else {\n if (state.skipInvalid) return false;\n throw new exception('unacceptable kind of an object to dump ' + type);\n }\n\n if (state.tag !== null && state.tag !== '?') {\n // Need to encode all characters except those allowed by the spec:\n //\n // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */\n // [36] ns-hex-digit ::= ns-dec-digit\n // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */\n // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */\n // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”\n // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”\n // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”\n // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”\n //\n // Also need to encode '!' because it has special meaning (end of tag prefix).\n //\n tagStr = encodeURI(\n state.tag[0] === '!' ? state.tag.slice(1) : state.tag\n ).replace(/!/g, '%21');\n\n if (state.tag[0] === '!') {\n tagStr = '!' + tagStr;\n } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {\n tagStr = '!!' + tagStr.slice(18);\n } else {\n tagStr = '!<' + tagStr + '>';\n }\n\n state.dump = tagStr + ' ' + state.dump;\n }\n }\n\n return true;\n}\n\nfunction getDuplicateReferences(object, state) {\n var objects = [],\n duplicatesIndexes = [],\n index,\n length;\n\n inspectNode(object, objects, duplicatesIndexes);\n\n for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]]);\n }\n state.usedDuplicates = new Array(length);\n}\n\nfunction inspectNode(object, objects, duplicatesIndexes) {\n var objectKeyList,\n index,\n length;\n\n if (object !== null && typeof object === 'object') {\n index = objects.indexOf(object);\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index);\n }\n } else {\n objects.push(object);\n\n if (Array.isArray(object)) {\n for (index = 0, length = object.length; index < length; index += 1) {\n inspectNode(object[index], objects, duplicatesIndexes);\n }\n } else {\n objectKeyList = Object.keys(object);\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);\n }\n }\n }\n }\n}\n\nfunction dump$1(input, options) {\n options = options || {};\n\n var state = new State(options);\n\n if (!state.noRefs) getDuplicateReferences(input, state);\n\n var value = input;\n\n if (state.replacer) {\n value = state.replacer.call({ '': value }, '', value);\n }\n\n if (writeNode(state, 0, value, true, true)) return state.dump + '\\n';\n\n return '';\n}\n\nvar dump_1 = dump$1;\n\nvar dumper = {\n\tdump: dump_1\n};\n\nfunction renamed(from, to) {\n return function () {\n throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +\n 'Use yaml.' + to + ' instead, which is now safe by default.');\n };\n}\n\n\nvar Type = type;\nvar Schema = schema;\nvar FAILSAFE_SCHEMA = failsafe;\nvar JSON_SCHEMA = json;\nvar CORE_SCHEMA = core;\nvar DEFAULT_SCHEMA = _default;\nvar load = loader.load;\nvar loadAll = loader.loadAll;\nvar dump = dumper.dump;\nvar YAMLException = exception;\n\n// Re-export all types in case user wants to create custom schema\nvar types = {\n binary: binary,\n float: float,\n map: map,\n null: _null,\n pairs: pairs,\n set: set,\n timestamp: timestamp,\n bool: bool,\n int: int,\n merge: merge,\n omap: omap,\n seq: seq,\n str: str\n};\n\n// Removed functions from JS-YAML 3.0.x\nvar safeLoad = renamed('safeLoad', 'load');\nvar safeLoadAll = renamed('safeLoadAll', 'loadAll');\nvar safeDump = renamed('safeDump', 'dump');\n\nvar jsYaml = {\n\tType: Type,\n\tSchema: Schema,\n\tFAILSAFE_SCHEMA: FAILSAFE_SCHEMA,\n\tJSON_SCHEMA: JSON_SCHEMA,\n\tCORE_SCHEMA: CORE_SCHEMA,\n\tDEFAULT_SCHEMA: DEFAULT_SCHEMA,\n\tload: load,\n\tloadAll: loadAll,\n\tdump: dump,\n\tYAMLException: YAMLException,\n\ttypes: types,\n\tsafeLoad: safeLoad,\n\tsafeLoadAll: safeLoadAll,\n\tsafeDump: safeDump\n};\n\nexport { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, jsYaml as default, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types };\n","// Contract Integrity detector (ADR-010) — validates that Backstage\n// catalog-info.yaml references resolve to declared entities.\n//\n// Catches the \"dangling contract reference\" failure class: a repo declares it\n// CONSUMES an API (spec.consumesApis) that no repo PUBLISHES, or points at a\n// System / parent Component that doesn't exist. Each such PR is internally valid\n// and green; the break only exists across the system's contracts — which is\n// exactly what ordinary CI can't see.\n//\n// Resolution universe = entities declared across the catalog files in this PR,\n// unioned with an optional org catalog index (ctx.catalogKnownEntities). Local\n// structural refs (system / subcomponentOf) and owned refs (providesApis) must\n// resolve and warn when they don't; cross-repo contract refs (consumesApis /\n// dependsOn) warn only when an index is configured, otherwise advise.\n\nimport yaml from \"js-yaml\";\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst CATALOG_FILE = /(?:^|\\/)catalog-info\\.ya?ml$/i;\n\nexport type RefKind = \"local\" | \"owned\" | \"contract\";\n\nexport interface ContractRefFinding {\n file: string;\n field: string;\n ref: string;\n name: string;\n kind: RefKind;\n}\n\nexport function isCatalogFile(file: SubmissionFileInfo): boolean {\n return CATALOG_FILE.test(normalizePath(file.filename));\n}\n\n/** Backstage entity ref → bare name. \"component:default/foo\" → \"foo\". */\nfunction refName(ref: string): string {\n let s = String(ref).trim();\n const colon = s.indexOf(\":\");\n if (colon >= 0) s = s.slice(colon + 1); // strip \"kind:\"\n const slash = s.lastIndexOf(\"/\");\n if (slash >= 0) s = s.slice(slash + 1); // strip \"namespace/\"\n return s;\n}\n\nfunction asArray(value: unknown): string[] {\n if (Array.isArray(value))\n return value.filter((v): v is string => typeof v === \"string\");\n if (typeof value === \"string\") return [value];\n return [];\n}\n\n/** Parse every YAML doc in a catalog file; tolerate malformed docs (that's syntax_validity's job). */\nfunction parseDocs(content: string): Array<Record<string, unknown>> {\n const docs: Array<Record<string, unknown>> = [];\n try {\n yaml.loadAll(content, (doc) => {\n if (doc && typeof doc === \"object\") docs.push(doc as Record<string, unknown>);\n });\n } catch {\n // unparseable catalog — leave to syntax_validity; we simply can't analyze it\n }\n return docs;\n}\n\nfunction entityName(doc: Record<string, unknown>): string | null {\n const meta = doc.metadata as Record<string, unknown> | undefined;\n const name = meta?.name;\n return typeof name === \"string\" ? name : null;\n}\n\n/**\n * Core analysis shared by the detector and the self-heal lane: parse the PR's\n * catalog files, build the resolution universe, and return every reference that\n * doesn't resolve. Returns null when there are no catalog files to analyze.\n */\nexport function analyzeCatalogRefs(\n files: SubmissionFileInfo[],\n knownEntities?: Set<string>,\n): { findings: ContractRefFinding[]; hasOrgIndex: boolean } | null {\n const catalogFiles = files.filter(isCatalogFile);\n if (catalogFiles.length === 0) return null;\n\n // Parse once; remember which file each doc came from.\n const parsed = catalogFiles.map((file) => ({\n file,\n docs: parseDocs(fileContent(file)),\n }));\n\n // 1. Build the resolution universe: in-PR declarations ∪ configured org index.\n const declared = new Set<string>();\n for (const { docs } of parsed) {\n for (const doc of docs) {\n const name = entityName(doc);\n if (name) declared.add(name);\n }\n }\n const known = new Set<string>(declared);\n for (const name of knownEntities ?? []) known.add(name);\n const hasOrgIndex = (knownEntities?.size ?? 0) > 0;\n\n // 2. Walk references and collect anything that doesn't resolve.\n const findings: ContractRefFinding[] = [];\n const checkRef = (\n file: SubmissionFileInfo,\n field: string,\n ref: string,\n kind: RefKind,\n ) => {\n const name = refName(ref);\n if (!name || known.has(name)) return;\n findings.push({ file: normalizePath(file.filename), field, ref, name, kind });\n };\n\n for (const { file, docs } of parsed) {\n for (const doc of docs) {\n const spec = (doc.spec ?? {}) as Record<string, unknown>;\n if (typeof spec.system === \"string\") checkRef(file, \"system\", spec.system, \"local\");\n if (typeof spec.subcomponentOf === \"string\")\n checkRef(file, \"subcomponentOf\", spec.subcomponentOf, \"local\");\n for (const ref of asArray(spec.providesApis))\n checkRef(file, \"providesApis\", ref, \"owned\");\n for (const ref of asArray(spec.consumesApis))\n checkRef(file, \"consumesApis\", ref, \"contract\");\n for (const ref of asArray(spec.dependsOn))\n checkRef(file, \"dependsOn\", ref, \"contract\");\n }\n }\n\n return { findings, hasOrgIndex };\n}\n\nexport function detectContractIntegrity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const analysis = analyzeCatalogRefs(ctx.files, ctx.catalogKnownEntities);\n if (!analysis) return null;\n const { findings, hasOrgIndex } = analysis;\n\n if (findings.length === 0) return null;\n\n // 3. Severity: local/owned refs are structural (always warn). Cross-repo\n // contract refs warn only when an org index makes \"dangling\" decidable;\n // without one they're advisory (\"unverified\") to avoid single-repo FPs.\n const structural = findings.filter((f) => f.kind !== \"contract\");\n const contract = findings.filter((f) => f.kind === \"contract\");\n const severity: SubmissionCheckResult[\"severity\"] =\n structural.length > 0 || hasOrgIndex ? \"warn\" : \"advisory\";\n\n // Self-heal lane (ADR-010): a missing LOCAL entity (system / subcomponentOf\n // target) can be auto-declared in the same catalog file. See healers/catalog.ts.\n const localHealable = findings.some((f) => f.kind === \"local\");\n\n const lines = findings.map(\n (f) => `${f.file}: spec.${f.field} → \"${f.ref}\" (no declared entity \"${f.name}\")`,\n );\n const detailParts = [lines.join(\"; \")];\n if (contract.length > 0 && !hasOrgIndex) {\n detailParts.push(\n \"Cross-repo contract refs are UNVERIFIED — supply submission.contract_integrity.known_entities (an org catalog index) to enforce.\",\n );\n }\n\n return {\n code: \"contract_integrity\",\n severity,\n title:\n severity === \"warn\"\n ? \"Dangling catalog contract reference\"\n : \"Unverified catalog contract reference\",\n detail: detailParts.join(\" \"),\n files: [...new Set(findings.map((f) => f.file))],\n suggested_action:\n \"Declare the referenced entity in the owning repo's catalog-info.yaml (or fix the reference). \" +\n \"For cross-repo contracts, ensure the publishing repo declares the API and that it is in the org catalog index.\" +\n (localHealable\n ? \" A missing local entity (system / subcomponentOf target) can be auto-declared — Trailhead self-heal.\"\n : \"\"),\n autofix_eligible: localHealable,\n };\n}\n","// Safe Deprecation detector (ADR-010) — catalog coherence on retirement.\n//\n// When an entity is retired (a Backstage `catalog-info.yaml` doc with\n// `spec.lifecycle: deprecated`), nothing still ALIVE should keep depending on it.\n// A live component that still `consumesApis` / `dependsOn` / is `subcomponentOf`\n// / has `system` pointing at a deprecated entity is a zombie reference — the\n// retirement looks done but a live surface still wires to the corpse. This is the\n// catalog-level shape of the \"incomplete deprecation\" incident class.\n//\n// v1 is catalog-native (fully in-diff, high-confidence). Route/data-surface\n// coverage (redirect maps, route globs) needs full repo file contents and is a\n// tracked follow-up under ADR-010.\n\nimport yaml from \"js-yaml\";\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst CATALOG_FILE = /(?:^|\\/)catalog-info\\.ya?ml$/i;\n\nfunction isCatalogFile(file: SubmissionFileInfo): boolean {\n return CATALOG_FILE.test(normalizePath(file.filename));\n}\n\nfunction refName(ref: string): string {\n let s = String(ref).trim();\n const colon = s.indexOf(\":\");\n if (colon >= 0) s = s.slice(colon + 1);\n const slash = s.lastIndexOf(\"/\");\n if (slash >= 0) s = s.slice(slash + 1);\n return s;\n}\n\nfunction asArray(value: unknown): string[] {\n if (Array.isArray(value))\n return value.filter((v): v is string => typeof v === \"string\");\n if (typeof value === \"string\") return [value];\n return [];\n}\n\nfunction parseDocs(content: string): Array<Record<string, unknown>> {\n const docs: Array<Record<string, unknown>> = [];\n try {\n yaml.loadAll(content, (doc) => {\n if (doc && typeof doc === \"object\") docs.push(doc as Record<string, unknown>);\n });\n } catch {\n // malformed — leave to syntax_validity\n }\n return docs;\n}\n\nfunction entityName(doc: Record<string, unknown>): string | null {\n const meta = doc.metadata as Record<string, unknown> | undefined;\n return typeof meta?.name === \"string\" ? meta.name : null;\n}\n\nfunction isRetired(doc: Record<string, unknown>): boolean {\n const spec = (doc.spec ?? {}) as Record<string, unknown>;\n return spec.lifecycle === \"deprecated\";\n}\n\ninterface ZombieRef {\n file: string;\n from: string;\n field: string;\n to: string;\n}\n\nexport function detectSafeDeprecation(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const catalogFiles = ctx.files.filter(isCatalogFile);\n if (catalogFiles.length === 0) return null;\n\n const parsed = catalogFiles.map((file) => ({\n file,\n docs: parseDocs(fileContent(file)),\n }));\n\n // 1. Which entities are being retired?\n const retired = new Set<string>();\n for (const { docs } of parsed) {\n for (const doc of docs) {\n const name = entityName(doc);\n if (name && isRetired(doc)) retired.add(name);\n }\n }\n if (retired.size === 0) return null;\n\n // 2. A LIVE entity that still references a retired one is a zombie wire.\n const zombies: ZombieRef[] = [];\n for (const { file, docs } of parsed) {\n for (const doc of docs) {\n if (isRetired(doc)) continue; // a dying thing may reference another; ignore\n const from = entityName(doc) ?? \"(unnamed)\";\n const spec = (doc.spec ?? {}) as Record<string, unknown>;\n const check = (field: string, ref: string) => {\n const to = refName(ref);\n if (retired.has(to)) {\n zombies.push({ file: normalizePath(file.filename), from, field, to });\n }\n };\n if (typeof spec.system === \"string\") check(\"system\", spec.system);\n if (typeof spec.subcomponentOf === \"string\")\n check(\"subcomponentOf\", spec.subcomponentOf);\n for (const ref of asArray(spec.consumesApis)) check(\"consumesApis\", ref);\n for (const ref of asArray(spec.dependsOn)) check(\"dependsOn\", ref);\n }\n }\n\n if (zombies.length === 0) return null;\n\n const lines = zombies.map(\n (z) => `${z.file}: \"${z.from}\" still ${z.field} → \"${z.to}\" (deprecated)`,\n );\n return {\n code: \"safe_deprecation\",\n severity: \"warn\",\n title: \"Live entity depends on a retired one\",\n detail: `Deprecation left a live wire to a retired entity: ${lines.join(\"; \")}.`,\n files: [...new Set(zombies.map((z) => z.file))],\n suggested_action:\n \"Repoint the live reference to the surviving/canonical entity, or deprecate the dependent too. \" +\n \"Also confirm non-catalog surfaces (routes, redirects, listings) for the retired entity are covered.\",\n autofix_eligible: false,\n };\n}\n","// Destructive Change detector (ADR-010) — evidence-gated destructive migrations.\n//\n// `destructive_sql` already BLOCKS the always-bad shapes (DROP TABLE / TRUNCATE /\n// DELETE without WHERE). But it deliberately lets through *targeted* destructive\n// ops that are legitimate WITH due diligence: a `DELETE ... WHERE`, an\n// `ALTER ... DROP COLUMN`, a `DROP VIEW/TYPE/INDEX/...`, or a wide `UPDATE` with\n// no WHERE. Those are exactly the changes that should ship only with recorded\n// evidence — the FK / row-count / reversibility check a human does by hand today.\n//\n// This detector requires that evidence, inline in the migration, as a block:\n//\n// -- @destructive-change\n// -- fk-refs: 0 (or: names of referencing tables + how handled)\n// -- affected-rows: 1 (or an estimate)\n// -- reversible: re-seed; row carries no referenced data (or: no — <why ok>)\n// -- ack: dschirmer 2026-06-01\n//\n// Found a targeted destructive op but no complete evidence block → finding.\n// Ships `warn` (phase-0, per ADR-008); target state is `blocking` w/o evidence.\n// Self-heal follow-up: auto-run the FK/row probes and attach the evidence.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst SQL_FILE = /\\.sql$/i;\n\n/** Targeted destructive ops that `destructive_sql` allows but that warrant evidence. */\nconst DESTRUCTIVE_OPS: Array<{ label: string; pattern: RegExp }> = [\n // DELETE with a WHERE (destructive_sql only blocks DELETE *without* WHERE).\n { label: \"DELETE ... WHERE\", pattern: /\\bDELETE\\s+FROM\\s+[^\\n;]*?\\bWHERE\\b/i },\n // ALTER TABLE ... DROP COLUMN (data loss; not a bare DROP TABLE).\n {\n label: \"DROP COLUMN\",\n pattern: /\\bALTER\\s+TABLE\\b(?:(?!;)[\\s\\S])*?\\bDROP\\s+COLUMN\\b/i,\n },\n // DROP of other objects (view/type/index/function/sequence/schema/mat-view).\n {\n label: \"DROP <object>\",\n pattern:\n /\\bDROP\\s+(?:MATERIALIZED\\s+VIEW|VIEW|TYPE|INDEX|FUNCTION|SEQUENCE|SCHEMA)\\b/i,\n },\n // Wide UPDATE — a SET with no WHERE before the statement terminator.\n {\n label: \"UPDATE without WHERE\",\n pattern: /\\bUPDATE\\s+[^\\n;]+?\\bSET\\b(?:(?!\\bWHERE\\b)[^;])*;/i,\n },\n];\n\nconst EVIDENCE_FIELDS: Array<{ key: string; pattern: RegExp }> = [\n { key: \"fk-refs\", pattern: /\\bfk-refs\\s*:/i },\n { key: \"affected-rows\", pattern: /\\baffected-rows\\s*:/i },\n { key: \"reversible\", pattern: /\\breversible\\s*:/i },\n { key: \"ack\", pattern: /\\back\\s*:/i },\n];\n\nfunction isSqlFile(file: SubmissionFileInfo): boolean {\n return SQL_FILE.test(normalizePath(file.filename));\n}\n\ninterface FileFinding {\n file: string;\n ops: string[];\n missing: string[];\n}\n\nexport function detectDestructiveChange(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const sqlFiles = ctx.files.filter(isSqlFile);\n if (sqlFiles.length === 0) return null;\n\n const findings: FileFinding[] = [];\n for (const file of sqlFiles) {\n const content = fileContent(file);\n if (!content) continue;\n\n const ops = DESTRUCTIVE_OPS.filter((op) => op.pattern.test(content)).map(\n (op) => op.label,\n );\n if (ops.length === 0) continue;\n\n const missing = EVIDENCE_FIELDS.filter((f) => !f.pattern.test(content)).map(\n (f) => f.key,\n );\n if (missing.length === 0) continue; // op present, evidence complete → ok\n\n findings.push({ file: normalizePath(file.filename), ops, missing });\n }\n\n if (findings.length === 0) return null;\n\n const lines = findings.map(\n (f) => `${f.file}: ${f.ops.join(\", \")} — missing evidence: ${f.missing.join(\", \")}`,\n );\n\n return {\n code: \"destructive_change\",\n severity: \"warn\",\n title: \"Destructive migration without an evidence bundle\",\n detail: `Targeted destructive op(s) lack a complete evidence block: ${lines.join(\n \"; \",\n )}.`,\n files: findings.map((f) => f.file),\n suggested_action:\n \"Add an evidence block to the migration:\\n\" +\n \" -- @destructive-change\\n\" +\n \" -- fk-refs: <0 or referencing tables + how handled>\\n\" +\n \" -- affected-rows: <count or estimate>\\n\" +\n \" -- reversible: <how to undo, or 'no — <why acceptable>'>\\n\" +\n \" -- ack: <who/when>\",\n autofix_eligible: false,\n };\n}\n","// Claim Anchoring detector (ADR-010) — doc assertions should cite where they're true.\n//\n// Incident #3: a doc asserted \"redirects exist\" while the live canonical path had\n// none — the claim outlived the code. This detector flags assertive, *behavioral*\n// claims added to docs that carry no anchor (a file/path reference, a link, or a\n// `verified-by:` / `see:` pointer). It does NOT judge whether the claim is true —\n// it asks the author to point at where it's enforced/tested, so the claim and the\n// code can be cross-checked later. Advisory only (per ADR-008): informational, no\n// block. Self-heal follow-up: comment + open a test stub for the claim.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext, SubmissionFileInfo } from \"./types.js\";\nimport { fileContent, normalizePath } from \"./helpers.js\";\n\nconst DOC_FILE = /\\.mdx?$/i;\n\n// High-signal, behavioral, testable assertions. Kept tight to limit noise.\nconst CLAIM_PATTERNS: RegExp[] = [\n /\\bredirects?\\s+(?:exist|are\\s+in\\s+place|are\\s+configured|are\\s+handled)\\b/i,\n /\\bis\\s+(?:enforced|guaranteed|wired\\s+up|fully\\s+covered)\\b/i,\n /\\b(?:always|never)\\s+(?:redirects?|returns?|blocks?|allows?|runs?|fires?|resolves?)\\b/i,\n /\\bfully\\s+(?:covered|tested|implemented|wired)\\b/i,\n /\\b(?:every|all)\\s+\\w+\\s+(?:are\\s+)?(?:redirected|covered|validated|enforced)\\b/i,\n /\\bguaranteed\\s+to\\b/i,\n];\n\n// An anchor lets a reviewer cross-check the claim against reality.\nconst ANCHOR_PATTERNS: RegExp[] = [\n /`[^`]*[\\w.-]+\\.(?:ts|tsx|js|jsx|mjs|cjs|sql|ya?ml|json|py|go|rs)`/i, // code/path in backticks\n /`[^`]*\\/[^`]*`/, // any path-ish backtick span\n /\\]\\([^)]+\\)/, // markdown link\n /\\b(?:verified[ -]by|tested in|see|ref|test)\\s*[:=]/i, // explicit pointer\n /<!--\\s*claim-ok/i, // author override\n];\n\nfunction isDocFile(file: SubmissionFileInfo): boolean {\n return DOC_FILE.test(normalizePath(file.filename));\n}\n\nfunction hasAnchor(window: string): boolean {\n return ANCHOR_PATTERNS.some((re) => re.test(window));\n}\n\ninterface Unanchored {\n file: string;\n line: number;\n text: string;\n}\n\nexport function detectClaimAnchoring(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const docs = ctx.files.filter(isDocFile);\n if (docs.length === 0) return null;\n\n const unanchored: Unanchored[] = [];\n for (const file of docs) {\n const content = fileContent(file);\n if (!content) continue;\n const lines = content.split(\"\\n\");\n let inFence = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n if (/^\\s*```/.test(line)) {\n inFence = !inFence;\n continue;\n }\n if (inFence) continue; // claims inside code examples aren't doc assertions\n\n if (!CLAIM_PATTERNS.some((re) => re.test(line))) continue;\n\n // Anchor may sit on the claim line or an adjacent line.\n const windowText = [lines[i - 1] ?? \"\", line, lines[i + 1] ?? \"\"].join(\"\\n\");\n if (hasAnchor(windowText)) continue;\n\n unanchored.push({\n file: normalizePath(file.filename),\n line: i + 1,\n text: line.trim().slice(0, 120),\n });\n }\n }\n\n if (unanchored.length === 0) return null;\n\n const shown = unanchored.slice(0, 8);\n const lines = shown.map((u) => `${u.file}:${u.line} — \"${u.text}\"`);\n const more =\n unanchored.length > shown.length\n ? ` (+${unanchored.length - shown.length} more)`\n : \"\";\n\n return {\n code: \"claim_anchoring\",\n severity: \"advisory\",\n title: \"Behavioral claim in docs has no anchor\",\n detail:\n `Assertive claims with no reference to where they're enforced/tested: ${lines.join(\n \"; \",\n )}${more}. ` +\n \"Cite the code/test (a backtick path, a link, or `verified-by:`), or add `<!-- claim-ok -->` if intentional.\",\n files: [...new Set(unanchored.map((u) => u.file))],\n suggested_action:\n \"Anchor each claim to where it lives (e.g. `proxy.ts`, a test path, or a link), \" +\n \"so docs and reality can be cross-checked. This is the doc-vs-reality drift that let \" +\n '\"redirects exist\" outlive the missing /apps redirect.',\n autofix_eligible: false,\n };\n}\n","// Promotion Coherence detector (ADR-010) — guard env-branch promotions.\n//\n// Incident #5: work landed on `dev` behind an in-flight promotion, so the open\n// production release silently shipped without it — and a destructive migration\n// rode a staging→prod release to production. Ordinary detectors look at the diff;\n// this one looks at the *branch topology* of a promotion PR (base/head from\n// GITHUB_BASE_REF / GITHUB_HEAD_REF, threaded via ctx.promotion).\n//\n// v1 catches two in-reach signals on a promotion PR (env branch → env branch):\n// 1. Stage skip — a promotion straight into a production branch from `dev`\n// (bypassing staging). The ladder is dev → staging → master/main.\n// 2. Risky payload to prod — a promotion into production that carries SQL\n// migrations: confirm they belong in THIS release and carry destructive\n// evidence (see `destructive_change`).\n// Ships `warn` (phase-0). Follow-up: \"source has commits not in this PR\" (omitted\n// work) needs an octokit branch-compare, beyond the file-diff model — tracked.\n\nimport type { SubmissionCheckResult } from \"../types.js\";\nimport type { SubmissionCheckContext } from \"./types.js\";\nimport { normalizePath } from \"./helpers.js\";\n\nconst DEV_BRANCHES = new Set([\"dev\", \"develop\", \"development\"]);\nconst PREPROD_BRANCHES = new Set([\"staging\", \"stage\", \"preprod\", \"pre-prod\", \"release\"]);\nconst PROD_BRANCHES = new Set([\"master\", \"main\", \"production\", \"prod\"]);\nconst ENV_BRANCHES = new Set([...DEV_BRANCHES, ...PREPROD_BRANCHES, ...PROD_BRANCHES]);\n\n/** Strip refs/heads/ and any owner prefix; lower-case the bare branch name. */\nfunction bareBranch(ref: string | undefined): string {\n if (!ref) return \"\";\n let b = ref.trim();\n b = b.replace(/^refs\\/heads\\//, \"\");\n const slash = b.lastIndexOf(\":\");\n if (slash >= 0) b = b.slice(slash + 1);\n return b.toLowerCase();\n}\n\nfunction isMigration(path: string): boolean {\n return /\\.sql$/i.test(path);\n}\n\nexport function detectPromotionCoherence(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const base = bareBranch(ctx.promotion?.baseBranch);\n const head = bareBranch(ctx.promotion?.headBranch);\n // Dormant unless we actually have a promotion (env branch → env branch).\n if (!base || !head) return null;\n if (!ENV_BRANCHES.has(base) || !ENV_BRANCHES.has(head)) return null;\n\n const findings: string[] = [];\n\n // 1. Stage skip into production.\n if (PROD_BRANCHES.has(base) && DEV_BRANCHES.has(head)) {\n findings.push(\n `promotes ${head} → ${base}, skipping the pre-prod stage (ladder: dev → staging → ${base})`,\n );\n }\n\n // 2. Migrations entering production via a promotion.\n const migrations = ctx.files.map((f) => normalizePath(f.filename)).filter(isMigration);\n if (PROD_BRANCHES.has(base) && migrations.length > 0) {\n findings.push(\n `carries ${migrations.length} migration(s) into production (${migrations\n .slice(0, 5)\n .join(\n \", \",\n )}) — confirm they belong in this release and carry destructive_change evidence`,\n );\n }\n\n if (findings.length === 0) return null;\n\n return {\n code: \"promotion_coherence\",\n severity: \"warn\",\n title: \"Promotion coherence\",\n detail: `This promotion ${findings.join(\"; \")}.`,\n files: migrations,\n suggested_action:\n \"Promote through the full ladder (dev → staging → master/main), and double-check \" +\n \"the release contents (especially destructive migrations) match what you intend to ship.\",\n autofix_eligible: false,\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@swc/core\");","// Real parse-based syntax validation for Gate 1 (no bracket-count fallback).\n// Parses full file content only — never a partial diff hunk (see submission-gate.md).\n\nimport { parseSync, type ParseOptions } from \"@swc/core\";\nimport yaml from \"js-yaml\";\nimport { extensionOf } from \"./helpers.js\";\n\nconst PARSEABLE = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"] as const;\n\nfunction parserOptionsFor(ext: string): ParseOptions {\n const isTs = ext === \".ts\" || ext === \".tsx\";\n return {\n syntax: isTs ? \"typescript\" : \"ecmascript\",\n tsx: ext === \".tsx\",\n jsx: ext === \".jsx\",\n decorators: true,\n dynamicImport: true,\n };\n}\n\n/** Returns a one-line error message, or null when content parses cleanly. */\nexport function validateFileSyntax(filename: string, content: string): string | null {\n if (!content.trim()) return null;\n\n const ext = extensionOf(filename);\n try {\n if ((PARSEABLE as readonly string[]).includes(ext)) {\n parseSync(content, parserOptionsFor(ext));\n } else if (ext === \".json\") {\n JSON.parse(content);\n } else if (ext === \".yaml\" || ext === \".yml\") {\n yaml.load(content);\n } else if (ext === \".md\" && content.startsWith(\"---\")) {\n const end = content.indexOf(\"\\n---\", 3);\n if (end > 0) yaml.load(content.slice(3, end));\n }\n } catch (error) {\n const message = error instanceof Error ? error.message.split(\"\\n\")[0] : String(error);\n return message || \"Parse error\";\n }\n return null;\n}\n","// Pure risk scoring engine — no framework dependencies.\n// Shared across the GitHub Action, MCP server, and GitHub App.\n\n// ---------------------------------------------------------------------------\n// Interfaces (framework-agnostic mirrors of the Zod schemas in types.ts)\n// ---------------------------------------------------------------------------\n\nexport interface FileInfo {\n filename: string;\n additions?: number;\n deletions?: number;\n changes: number;\n patch?: string;\n}\n\nexport interface RiskFactorResult {\n type: string;\n score: number;\n detail?: Record<string, unknown>;\n}\n\nexport interface SensitivityConfig {\n high: string[];\n medium: string[];\n low: string[];\n}\n\nexport interface RiskProfileMatchDef {\n files_include: string[];\n files_exclude: string[];\n min_files?: number;\n max_files?: number;\n}\n\nexport interface RiskProfileDef {\n name?: string;\n match: RiskProfileMatchDef;\n weights: Record<string, number>;\n}\n\nexport interface RiskConfig {\n sensitivity?: SensitivityConfig;\n weights?: Record<string, number>;\n ignore?: string[];\n profiles?: RiskProfileDef[];\n /** Extra globs treated as non-source for sensitive_files + test_coverage (not file_count). */\n non_source_globs?: string[];\n}\n\nexport interface SecurityAlertCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n total: number;\n topRules?: string[];\n}\n\nexport interface DeploymentOutcomeSummary {\n recentFailures: number;\n recentTotal: number;\n lastDeployFailed: boolean;\n lastRollback: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Pattern constants\n// ---------------------------------------------------------------------------\n\nexport const TEST_FILE_PATTERN =\n /\\.(test|spec)\\.(ts|tsx|js|jsx)$|__tests__\\/|\\.cy\\.(ts|js)$/;\n\nexport const NON_SOURCE_PATTERN =\n /\\.(sql|ya?ml|json|md|css|svg|lock|txt|env|png|jpg|gif)$/i;\n\nexport const SENSITIVE_PATTERNS = [\n /(?:^|\\/)migrations\\//i,\n /(?:^|\\/)auth/i,\n /(?:^|\\/)security/i,\n /(?:^|\\/)payment/i,\n /(?:^|\\/)billing/i,\n /(?:^|\\/)webhook/i,\n /(?:^|\\/)infrastructure\\//i,\n /(?:^|\\/)\\.github\\/workflows\\//i,\n /(?:^|\\/)secrets/i,\n /(?:^|\\/)\\.env/i,\n];\n\nconst HIGH_SENSITIVITY_PATTERN = /(?:^|\\/)(?:auth|security|payment|billing|webhook)/i;\n\nconst INFRA_SENSITIVITY_PATTERN =\n /(?:^|\\/)(?:migrations|infrastructure|\\.github\\/workflows|secrets|\\.env)/i;\n\nexport const DEPENDENCY_FILES = [\n /^package\\.json$/,\n /^package-lock\\.json$/,\n /^yarn\\.lock$/,\n /^pnpm-lock\\.yaml$/,\n /^requirements\\.txt$/,\n /^Pipfile\\.lock$/,\n /^poetry\\.lock$/,\n /^go\\.mod$/,\n /^go\\.sum$/,\n /^Gemfile\\.lock$/,\n /^Cargo\\.lock$/,\n /^composer\\.lock$/,\n];\n\nconst PACKAGE_JSON_DEPENDENCY_FIELDS = new Set([\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n \"optionalDependencies\",\n \"bundledDependencies\",\n]);\n\n// ---------------------------------------------------------------------------\n// Factor weights (v3: includes security_alerts, deployment_history, canary_status)\n// ---------------------------------------------------------------------------\n\nexport const FACTOR_WEIGHTS: Record<string, number> = {\n code_churn: 3,\n test_coverage: 2,\n file_count: 2,\n sensitive_files: 3,\n author_history: 1,\n dependency_changes: 2,\n pr_age: 1,\n security_alerts: 4,\n deployment_history: 2,\n canary_status: 2,\n ci_integrity: 3,\n workflow_security: 4,\n prompt_injection_risk: 4,\n supply_chain: 3,\n pr_scope: 2,\n duplicate_logic: 1,\n cross_repo_impact: 2,\n};\n\n// ---------------------------------------------------------------------------\n// Glob matching\n// ---------------------------------------------------------------------------\n\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"<<GLOBSTAR>>\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/<<GLOBSTAR>>/g, \".*\")\n .replace(/\\?/g, \".\");\n return new RegExp(`^${escaped}$`, \"i\");\n}\n\nexport function matchesGlobs(filename: string, patterns: string[]): boolean {\n return patterns.some((p) => globToRegex(p).test(filename));\n}\n\n// ---------------------------------------------------------------------------\n// Risk profile matching\n// ---------------------------------------------------------------------------\n\nexport function matchRiskProfile(\n filenames: string[],\n profiles: RiskProfileDef[],\n): RiskProfileDef | null {\n if (profiles.length === 0) return null;\n\n for (const profile of profiles) {\n const m = profile.match;\n\n if (m.min_files !== undefined && filenames.length < m.min_files) continue;\n if (m.max_files !== undefined && filenames.length > m.max_files) continue;\n\n if (\n m.files_include.length > 0 &&\n !m.files_include.every((pattern) =>\n filenames.some((f) => matchesGlobs(f, [pattern])),\n )\n ) {\n continue;\n }\n\n if (\n m.files_exclude.length > 0 &&\n m.files_exclude.some((pattern) => filenames.some((f) => matchesGlobs(f, [pattern])))\n ) {\n continue;\n }\n\n return profile;\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// File classification helpers\n// ---------------------------------------------------------------------------\n\nexport function isTestFile(filename: string): boolean {\n return TEST_FILE_PATTERN.test(filename);\n}\n\nexport function isNonSourceFile(filename: string): boolean {\n return NON_SOURCE_PATTERN.test(filename);\n}\n\nexport function isWorkflowFile(filename: string): boolean {\n return /(?:^|\\/)\\.github\\/workflows\\//i.test(filename);\n}\n\n/** Non-source for risk-factor purposes (markdown, config, consumer-declared globs). */\nexport function isContentNonSource(\n filename: string,\n config?: RiskConfig | null,\n): boolean {\n if (/(?:^|\\/)migrations\\//i.test(filename)) return false;\n if (isNonSourceFile(filename) && !isWorkflowFile(filename)) return true;\n const extra = config?.non_source_globs ?? [];\n return extra.length > 0 && matchesGlobs(filename, extra);\n}\n\nexport function isTestableSourceFile(\n filename: string,\n config?: RiskConfig | null,\n): boolean {\n if (isTestFile(filename)) return false;\n if (/(?:^|\\/)migrations\\//i.test(filename)) return false;\n return !isContentNonSource(filename, config);\n}\n\nexport function isSensitiveFile(filename: string, config?: RiskConfig | null): boolean {\n if (isContentNonSource(filename, config) && !isWorkflowFile(filename)) return false;\n return SENSITIVE_PATTERNS.some((p) => p.test(filename));\n}\n\nexport function riskConfigFromRepo(\n repo?: {\n sensitivity?: SensitivityConfig;\n weights?: Record<string, number>;\n ignore?: string[];\n profiles?: RiskProfileDef[];\n risk?: { non_source_globs?: string[] };\n } | null,\n): RiskConfig | null {\n if (!repo) return null;\n return {\n sensitivity: repo.sensitivity,\n weights: repo.weights,\n ignore: repo.ignore,\n profiles: repo.profiles,\n non_source_globs: repo.risk?.non_source_globs,\n };\n}\n\nexport function sensitivityWeight(filename: string, config?: RiskConfig | null): number {\n if (config) {\n if (config.ignore?.length && matchesGlobs(filename, config.ignore)) return 0;\n if (\n config.sensitivity?.high.length &&\n matchesGlobs(filename, config.sensitivity.high)\n )\n return 3;\n if (\n config.sensitivity?.medium.length &&\n matchesGlobs(filename, config.sensitivity.medium)\n )\n return 2;\n if (config.sensitivity?.low.length && matchesGlobs(filename, config.sensitivity.low))\n return 0.5;\n }\n\n if (isTestFile(filename)) return 0.3;\n if (HIGH_SENSITIVITY_PATTERN.test(filename)) return 3;\n if (INFRA_SENSITIVITY_PATTERN.test(filename)) return 2;\n if (isNonSourceFile(filename)) return 0.5;\n return 1;\n}\n\n// ---------------------------------------------------------------------------\n// Weighted average\n// ---------------------------------------------------------------------------\n\nexport function weightedAverageScores(\n factors: RiskFactorResult[],\n overrides?: Record<string, number>,\n): number {\n if (factors.length === 0) return 0;\n let totalWeight = 0;\n let weightedSum = 0;\n for (const f of factors) {\n const w = overrides?.[f.type] ?? FACTOR_WEIGHTS[f.type] ?? 1;\n weightedSum += f.score * w;\n totalWeight += w;\n }\n const avg = Math.round(weightedSum / totalWeight);\n return Math.min(100, Math.max(0, avg));\n}\n\n// ---------------------------------------------------------------------------\n// Risk scoring (pure — no API calls)\n// ---------------------------------------------------------------------------\n\nexport function computeRiskScore(\n files: FileInfo[],\n config?: RiskConfig | null,\n): {\n score: number;\n factors: RiskFactorResult[];\n} {\n if (files.length === 0) {\n return { score: 0, factors: [] };\n }\n\n const ignorePatterns = config?.ignore ?? [];\n const effectiveFiles =\n ignorePatterns.length > 0\n ? files.filter((f) => !matchesGlobs(f.filename, ignorePatterns))\n : files;\n\n if (effectiveFiles.length === 0) {\n return { score: 0, factors: [] };\n }\n\n const factors: RiskFactorResult[] = [];\n const customWeights = config?.weights ?? {};\n\n const fileCount = effectiveFiles.length;\n const fileCountScore = Math.min(100, Math.round(30 * Math.log2(1 + fileCount)));\n factors.push({\n type: \"file_count\",\n score: fileCountScore,\n detail: { fileCount, description: \"Number of files changed\" },\n });\n\n const totalChanges = effectiveFiles.reduce((sum, f) => sum + f.changes, 0);\n const weightedChanges = effectiveFiles.reduce(\n (sum, f) => sum + f.changes * sensitivityWeight(f.filename, config),\n 0,\n );\n const churnScore = Math.min(100, Math.round(25 * Math.log2(1 + weightedChanges / 50)));\n factors.push({\n type: \"code_churn\",\n score: churnScore,\n detail: {\n totalChanges,\n weightedChanges: Math.round(weightedChanges),\n description: \"Sensitivity-weighted lines changed\",\n },\n });\n\n const testFileCount = effectiveFiles.filter((f) => isTestFile(f.filename)).length;\n const testableSourceFiles = effectiveFiles.filter((f) =>\n isTestableSourceFile(f.filename, config),\n );\n const nonSourceCount = effectiveFiles.filter(\n (f) => !isTestFile(f.filename) && isContentNonSource(f.filename, config),\n ).length;\n if (testableSourceFiles.length > 0) {\n const testRatio = testFileCount / testableSourceFiles.length;\n const testCoverageScore =\n testFileCount === 0\n ? 100\n : Math.round(\n Math.max(0, 100 - testRatio * 100 - Math.min(testFileCount, 5) * 10),\n );\n factors.push({\n type: \"test_coverage\",\n score: testCoverageScore,\n detail: {\n testFiles: testFileCount,\n sourceFiles: testableSourceFiles.length,\n nonSourceFiles: nonSourceCount,\n testRatio: Math.round(testRatio * 100) / 100,\n skipped: false,\n },\n });\n }\n\n const highSensPatterns = config?.sensitivity?.high ?? [];\n const sensitiveByConfig =\n highSensPatterns.length > 0\n ? effectiveFiles.filter((f) => matchesGlobs(f.filename, highSensPatterns))\n : [];\n const sensitiveByDefault = effectiveFiles.filter((f) =>\n isSensitiveFile(f.filename, config),\n );\n const sensitiveFilenames = new Set([\n ...sensitiveByConfig.map((f) => f.filename),\n ...sensitiveByDefault.map((f) => f.filename),\n ]);\n const sensitiveFiles = effectiveFiles.filter((f) => sensitiveFilenames.has(f.filename));\n\n if (sensitiveFiles.length > 0) {\n const sensitiveScore = Math.min(100, sensitiveFiles.length * 25);\n factors.push({\n type: \"sensitive_files\",\n score: sensitiveScore,\n detail: {\n count: sensitiveFiles.length,\n files: sensitiveFiles.map((f) => f.filename),\n description: \"High-risk files (migrations, auth, payments, CI)\",\n },\n });\n }\n\n return { score: weightedAverageScores(factors, customWeights), factors };\n}\n\n// ---------------------------------------------------------------------------\n// Dependency change detection\n// ---------------------------------------------------------------------------\n\nexport function detectDependencyChanges(files: FileInfo[]): RiskFactorResult | null {\n const depFiles = files.filter((f) =>\n DEPENDENCY_FILES.some((p) => p.test(f.filename.replace(/.*\\//, \"\"))),\n );\n if (depFiles.length === 0) return null;\n\n const isLockfile = (filename: string): boolean =>\n /\\.(lock|sum)$|lock\\.(json|yaml)$/.test(filename);\n\n const packageJsonTouchesDependencies = (patch?: string): boolean => {\n if (!patch) return true;\n let activeSection: string | null = null;\n let sectionDepth = 0;\n\n for (const rawLine of patch.split(\"\\n\")) {\n if (rawLine.startsWith(\"@@\")) continue;\n const prefix = rawLine[0];\n if (prefix !== \" \" && prefix !== \"+\" && prefix !== \"-\") continue;\n\n const line = rawLine.slice(1);\n const sectionMatch = line.match(/^\\s*\"([^\"]+)\"\\s*:\\s*\\{\\s*$/);\n if (sectionMatch) {\n const key = sectionMatch[1];\n if (PACKAGE_JSON_DEPENDENCY_FIELDS.has(key)) {\n activeSection = key;\n sectionDepth = 1;\n if (prefix !== \" \") return true;\n continue;\n }\n }\n\n if (!activeSection) continue;\n\n const openCount = (line.match(/\\{/g) ?? []).length;\n const closeCount = (line.match(/\\}/g) ?? []).length;\n sectionDepth += openCount - closeCount;\n\n if (prefix !== \" \" && /^\\s*\"[^\"]+\"\\s*:\\s*\".*\"\\s*,?\\s*$/.test(line)) {\n return true;\n }\n\n if (sectionDepth <= 0) {\n activeSection = null;\n sectionDepth = 0;\n }\n }\n\n return false;\n };\n\n const relevantDepFiles = depFiles.filter((f) => {\n const base = f.filename.replace(/.*\\//, \"\");\n if (base === \"package.json\") {\n return packageJsonTouchesDependencies(f.patch);\n }\n return true;\n });\n\n if (relevantDepFiles.length === 0) return null;\n\n const hasLockfile = relevantDepFiles.some((f) => isLockfile(f.filename));\n const hasManifest = relevantDepFiles.some((f) => !isLockfile(f.filename));\n const totalChanges = relevantDepFiles.reduce((s, f) => s + f.changes, 0);\n\n const score = Math.min(\n 100,\n (hasManifest && hasLockfile ? 40 : hasManifest ? 60 : 20) +\n Math.min(30, Math.round(totalChanges / 100)),\n );\n\n return {\n type: \"dependency_changes\",\n score,\n detail: {\n files: relevantDepFiles.map((f) => f.filename),\n hasManifest,\n hasLockfile,\n totalChanges,\n description: \"Dependency manifests/lockfiles changed\",\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Security alerts risk factor (computed from pre-fetched alert counts)\n// ---------------------------------------------------------------------------\n\nexport function computeSecurityFactor(\n alerts: SecurityAlertCounts,\n): RiskFactorResult | null {\n if (alerts.total === 0) return null;\n\n const score = Math.min(\n 100,\n alerts.critical * 30 + alerts.high * 15 + alerts.medium * 5 + alerts.low * 1,\n );\n\n return {\n type: \"security_alerts\",\n score,\n detail: {\n critical: alerts.critical,\n high: alerts.high,\n medium: alerts.medium,\n low: alerts.low,\n total: alerts.total,\n topRules: alerts.topRules,\n description: `${alerts.total} open security alert(s)`,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Deployment history risk factor\n// ---------------------------------------------------------------------------\n\nexport function computeDeploymentHistoryFactor(\n outcomes: DeploymentOutcomeSummary,\n): RiskFactorResult | null {\n if (outcomes.recentTotal === 0) return null;\n\n let score = 0;\n const reasons: string[] = [];\n\n if (outcomes.recentFailures > 0) {\n score += Math.min(40, outcomes.recentFailures * 20);\n reasons.push(`${outcomes.recentFailures} recent failure(s)`);\n }\n if (outcomes.lastRollback) {\n score += 30;\n reasons.push(\"last deploy was rolled back\");\n }\n if (outcomes.lastDeployFailed) {\n score += 20;\n reasons.push(\"last deploy failed\");\n }\n\n score = Math.min(100, score);\n if (score === 0) return null;\n\n return {\n type: \"deployment_history\",\n score,\n detail: {\n recentFailures: outcomes.recentFailures,\n recentTotal: outcomes.recentTotal,\n lastDeployFailed: outcomes.lastDeployFailed,\n lastRollback: outcomes.lastRollback,\n description: reasons.join(\"; \"),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Release freeze window check\n// ---------------------------------------------------------------------------\n\nexport interface FreezeWindowDef {\n days: string[];\n afterHour?: number;\n beforeHour?: number;\n timezone?: string;\n message?: string;\n}\n\nconst DAY_NAMES = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n];\n\nexport function isInFreezeWindow(\n freezes: FreezeWindowDef[],\n now?: Date,\n): { frozen: boolean; message?: string } {\n if (freezes.length === 0) return { frozen: false };\n\n const d = now ?? new Date();\n\n for (const freeze of freezes) {\n const dayName = DAY_NAMES[d.getUTCDay()];\n const matchesDay =\n freeze.days.length === 0 || freeze.days.some((fd) => fd.toLowerCase() === dayName);\n\n if (!matchesDay) continue;\n\n const hour = d.getUTCHours();\n const afterOk = freeze.afterHour === undefined || hour >= freeze.afterHour;\n const beforeOk = freeze.beforeHour === undefined || hour < freeze.beforeHour;\n\n if (afterOk && beforeOk) {\n return {\n frozen: true,\n message: freeze.message ?? `Deployment frozen (${dayName} ${hour}:00 UTC)`,\n };\n }\n }\n\n return { frozen: false };\n}\n\n// ---------------------------------------------------------------------------\n// Gate decision\n// ---------------------------------------------------------------------------\n\nexport type GateDecisionValue = \"allow\" | \"warn\" | \"block\";\n\nexport function decideGate(\n riskScore: number,\n healthScore: number,\n blockThreshold: number,\n warnThreshold?: number,\n): GateDecisionValue {\n const effectiveWarn = warnThreshold ?? blockThreshold - 15;\n if (riskScore > blockThreshold) return \"block\";\n if (riskScore > effectiveWarn || healthScore < 50) return \"warn\";\n return \"allow\";\n}\n\n// ---------------------------------------------------------------------------\n// Rollback detection\n// ---------------------------------------------------------------------------\n\nexport function isRollback(prTitle: string): boolean {\n return /\\brevert\\b/i.test(prTitle) || /\\brollback\\b/i.test(prTitle);\n}\n","// Default submission detector policy data (Komatik fleet rename vocabulary).\n\nexport interface RenamePatternEntry {\n oldName: string;\n newName: string;\n pattern: RegExp;\n}\n\nexport const DEFAULT_RENAME_PATTERNS: RenamePatternEntry[] = [\n { oldName: \"DeployGuard\", newName: \"Trailhead\", pattern: /\\bDeployGuard\\b/g },\n { oldName: \"Daydream Studio\", newName: \"Sundog\", pattern: /\\bDaydream Studio\\b/g },\n {\n oldName: \"Storyboard Studio\",\n newName: \"Kindling\",\n pattern: /\\bStoryboard Studio\\b/g,\n },\n { oldName: \"Cognitive Debt\", newName: \"Drift\", pattern: /\\bCognitive Debt\\b/g },\n { oldName: \"cognitive-debt\", newName: \"Drift\", pattern: /\\bcognitive-debt\\b/g },\n { oldName: \"Undercurrent\", newName: \"Slipstream\", pattern: /\\bUndercurrent\\b/g },\n { oldName: \"Yggdrasil\", newName: \"Cairn\", pattern: /\\bYggdrasil\\b/g },\n { oldName: \"Bored\", newName: \"Lodge\", pattern: /\\bBored\\b/g },\n { oldName: \"Forge\", newName: \"Pack\", pattern: /\\bForge\\b/g },\n];\n\n/** @deprecated use DEFAULT_RENAME_PATTERNS */\nexport const OLD_NAME_PATTERNS = DEFAULT_RENAME_PATTERNS;\n\nexport const DEFAULT_SLUG_ONLY_PATTERN_SOURCES = [\n \"\\\\bcognitive-debt\\\\b\",\n \"\\\\bstoryboard-studio\\\\b\",\n \"\\\\bdaydream-studio\\\\b\",\n \"\\\\bshadow-ai-governance\\\\b\",\n];\n\nexport const DEFAULT_ARTIFACT_FILE_GLOBS = [\"**/*.{ts,tsx,js,jsx,mjs,cjs}\"];\n\nfunction escapeRegexLiteral(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport function compileRenamePattern(\n oldName: string,\n newName: string,\n): RenamePatternEntry {\n return {\n oldName,\n newName,\n pattern: new RegExp(`\\\\b${escapeRegexLiteral(oldName)}\\\\b`, \"g\"),\n };\n}\n\nexport function compileSlugOnlyPatterns(sources: string[]): RegExp[] {\n return sources.map((source) => new RegExp(source, \"i\"));\n}\n","// Resolve submission detector policy from `.trailhead.yml` (issue #256).\n\nimport type {\n RemediationSeverity,\n SubmissionCheckCode,\n SubmissionConfig,\n SubmissionDetectorPolicyEntry,\n} from \"../types.js\";\nimport { SubmissionCheckCode as SubmissionCheckCodeEnum } from \"../types.js\";\nimport {\n compileRenamePattern,\n compileSlugOnlyPatterns,\n DEFAULT_ARTIFACT_FILE_GLOBS,\n DEFAULT_RENAME_PATTERNS,\n DEFAULT_SLUG_ONLY_PATTERN_SOURCES,\n type RenamePatternEntry,\n} from \"./policy-defaults.js\";\n\nexport type DetectorPolicyEntry = {\n enabled?: boolean;\n severity?: RemediationSeverity;\n fileGlobs?: string[];\n pathIgnore?: string[];\n};\n\nexport type DetectorPolicyMap = Partial<Record<SubmissionCheckCode, DetectorPolicyEntry>>;\n\nfunction normalizeSeverity(\n severity: NonNullable<SubmissionDetectorPolicyEntry[\"severity\"]>,\n): RemediationSeverity {\n if (severity === \"block\") return \"blocking\";\n return severity as RemediationSeverity;\n}\n\nexport function resolveDetectorPolicy(submission?: Partial<SubmissionConfig>): {\n policy: DetectorPolicyMap;\n warnings: string[];\n} {\n const raw = submission?.detectors ?? {};\n const warnings: string[] = [];\n const policy: DetectorPolicyMap = {};\n\n for (const [key, value] of Object.entries(raw)) {\n const parsed = SubmissionCheckCodeEnum.safeParse(key);\n if (!parsed.success) {\n warnings.push(`Unknown submission.detectors key \"${key}\" will be ignored.`);\n continue;\n }\n if (!value || typeof value !== \"object\") continue;\n\n policy[parsed.data] = {\n enabled: value.enabled,\n severity: value.severity ? normalizeSeverity(value.severity) : undefined,\n fileGlobs: value.file_globs,\n pathIgnore: value.path_ignore,\n };\n }\n\n return { policy, warnings };\n}\n\nexport function buildRenamePatterns(\n submission?: Partial<SubmissionConfig>,\n options?: { includeKomatikDefaults?: boolean },\n): RenamePatternEntry[] {\n const custom = (submission?.rename_patterns ?? []).map(({ old, new: newName }) =>\n compileRenamePattern(old, newName),\n );\n const defaults = options?.includeKomatikDefaults ? DEFAULT_RENAME_PATTERNS : [];\n return [...defaults, ...custom];\n}\n\nexport function buildSlugOnlyPatterns(submission?: Partial<SubmissionConfig>): RegExp[] {\n const sources = [\n ...DEFAULT_SLUG_ONLY_PATTERN_SOURCES,\n ...(submission?.slug_only_patterns ?? []),\n ];\n return compileSlugOnlyPatterns(sources);\n}\n\nexport function artifactFileGlobs(policy: DetectorPolicyMap): string[] {\n return policy.artifact_integrity?.fileGlobs ?? DEFAULT_ARTIFACT_FILE_GLOBS;\n}\n\nexport function applyDetectorPolicy(\n code: SubmissionCheckCode,\n check: import(\"../types.js\").SubmissionCheckResult | null,\n policy: DetectorPolicyMap,\n): import(\"../types.js\").SubmissionCheckResult | null {\n const entry = policy[code];\n if (entry?.enabled === false) return null;\n if (!check) return null;\n if (entry?.severity) {\n return { ...check, severity: entry.severity };\n }\n return check;\n}\n\nexport function getSubmissionConfigWarnings(\n submission?: Partial<SubmissionConfig>,\n): string[] {\n return resolveDetectorPolicy(submission).warnings;\n}\n","// Gate 1 detectors — ported from komatik-agents agent-gate-checks (patch/content based).\n\nimport type { SubmissionCheckResult, SubmissionCheckCode } from \"../types.js\";\nimport type { SubmissionCheckContext } from \"./types.js\";\nimport {\n addedLines,\n extensionOf,\n extractAllImports,\n fileContent,\n isStaleArchivedPath,\n isTestPath,\n lineCountFromPatch,\n linesForFreshnessScan,\n normalizePath,\n scanAddedContent,\n} from \"./helpers.js\";\nimport type { NamingAllowlistConfig } from \"./types.js\";\nimport { runPhase0Detectors } from \"./phase0-detectors.js\";\nimport { detectContractIntegrity } from \"./contract-integrity.js\";\nimport { detectSafeDeprecation } from \"./safe-deprecation.js\";\nimport { detectDestructiveChange } from \"./destructive-change.js\";\nimport { detectClaimAnchoring } from \"./claim-anchoring.js\";\nimport { detectPromotionCoherence } from \"./promotion-coherence.js\";\nimport { validateFileSyntax } from \"./syntax-validity.js\";\nimport { matchesGlobs } from \"../risk-engine.js\";\nimport { applyDetectorPolicy, artifactFileGlobs } from \"./detector-policy.js\";\nexport { DEFAULT_RENAME_PATTERNS, OLD_NAME_PATTERNS } from \"./policy-defaults.js\";\n\nconst MOCK_PATTERNS = [\n /\\bTODO\\s*\\(\\s*mock\\s*\\)/i,\n /\\bFIXME\\s*\\(\\s*mock\\s*\\)/i,\n /\\bMOCK_[A-Z0-9_]+\\b/,\n /\\bfakeImplementation\\b/,\n /\\bstubResponse\\s*\\(/i,\n /\\b(?:generate|create|build|get)(?:Mock|Fake|Dummy|Sample)\\w*/g,\n /\\b(?:mockData|fakeData|sampleData|dummyData|testData)\\b/g,\n /\\bTODO:\\s*implement\\b/gi,\n /\\bFIXME\\b/g,\n /\\bIn production,\\s*use\\b/i,\n /\\bplaceholder\\b/gi,\n /\\blorem ipsum\\b/gi,\n];\n\nconst SECRET_PATTERNS: Array<{ name: string; pattern: RegExp }> = [\n { name: \"AWS access key\", pattern: /\\bAKIA[0-9A-Z]{16}\\b/g },\n { name: \"GitHub token\", pattern: /\\bgh[pousr]_[A-Za-z0-9_]{20,}\\b/g },\n { name: \"Stripe live key\", pattern: /\\bsk_live_[A-Za-z0-9]{10,}\\b/g },\n { name: \"Stripe test key\", pattern: /\\bsk_test_[A-Za-z0-9]{10,}\\b/g },\n { name: \"Private key block\", pattern: /-----BEGIN [A-Z ]+PRIVATE KEY-----/g },\n {\n name: \"Generic API key assignment\",\n pattern: /api[_-]?key\\s*[:=]\\s*['\"][A-Za-z0-9_-]{32,}['\"]/gi,\n },\n];\n\nconst HARDCODED_ENV_PATTERNS: Array<{ name: string; pattern: RegExp }> = [\n { name: \"localhost with port\", pattern: /(?:['\"`])localhost:\\d{2,5}(?:['\"`])/g },\n {\n name: \"hardcoded private IP\",\n pattern:\n /(?:['\"`])(?:10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|172\\.(?:1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}|192\\.168\\.\\d{1,3}\\.\\d{1,3})(?::\\d+)?(?:['\"`])/g,\n },\n];\n\nconst NODE_BUILTINS = new Set([\n \"assert\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"dns\",\n \"events\",\n \"fs\",\n \"http\",\n \"http2\",\n \"https\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"process\",\n \"stream\",\n \"url\",\n \"util\",\n \"zlib\",\n]);\n\nfunction result(\n partial: Omit<SubmissionCheckResult, \"autofix_eligible\"> & {\n autofix_eligible?: boolean;\n },\n): SubmissionCheckResult {\n return { autofix_eligible: false, ...partial };\n}\n\nexport function detectMockPlaceholder(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits = scanAddedContent(ctx.files, (line, filename) => {\n if (isTestPath(filename)) return false;\n if (/\\.(md|txt)$/i.test(filename)) return false;\n return MOCK_PATTERNS.some((re) => {\n re.lastIndex = 0;\n return re.test(line);\n });\n });\n if (hits.length === 0) return null;\n return result({\n code: \"mock_placeholder\",\n severity: \"blocking\",\n title: \"Mock placeholder in production path\",\n detail: `Found mock/TODO placeholder patterns in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Remove mock placeholders and implement real behavior.\",\n });\n}\n\nexport function detectSecrets(ctx: SubmissionCheckContext): SubmissionCheckResult | null {\n const hits = scanAddedContent(ctx.files, (line) =>\n SECRET_PATTERNS.some((entry) => {\n entry.pattern.lastIndex = 0;\n return entry.pattern.test(line);\n }),\n );\n if (hits.length === 0) return null;\n return result({\n code: \"secrets\",\n severity: \"blocking\",\n title: \"Potential secret in diff\",\n detail: `Added lines match secret patterns in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Remove secrets; use environment variables or a secret manager.\",\n });\n}\n\nexport function detectDestructiveSql(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const sqlFiles = ctx.files.filter((f) => extensionOf(f.filename) === \".sql\");\n const hits = scanAddedContent(sqlFiles, (line) =>\n /\\b(DROP\\s+TABLE|TRUNCATE|DELETE\\s+FROM(?![^\\n]*\\bWHERE\\b))/i.test(line),\n );\n if (hits.length === 0) return null;\n return result({\n code: \"destructive_sql\",\n severity: \"blocking\",\n title: \"Destructive SQL in migration\",\n detail: `Added SQL contains destructive statements in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action:\n \"Use additive migrations; avoid DROP/TRUNCATE without human approval.\",\n });\n}\n\n// Only code files can carry hard file references; prose (.md/.mdx/.txt) merely\n// *mentions* paths and was the dominant artifact_integrity false-positive source.\nconst ARTIFACT_BARE_IGNORE = new Set([\n \"package.json\",\n \"package-lock.json\",\n \"tsconfig.json\",\n \"readme.md\",\n]);\n\nexport function detectArtifactIntegrity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const referenced = new Set<string>();\n const fileGlobs = artifactFileGlobs(ctx.detectorPolicy);\n const pathIgnore = ctx.detectorPolicy.artifact_integrity?.pathIgnore ?? [];\n // Only treat a path *literal* inside an import/require/export-from statement\n // as a hard reference — natural-language \"see X\" / \"fix Y\" / \"update Z\" in\n // prose is not a code dependency (the old prose trigger over-flagged docs).\n const importRefPattern =\n /(?:\\bimport\\b|\\bfrom\\b|\\brequire\\s*\\(|\\bexport\\b[^'\"`]*\\bfrom\\b)\\s*['\"`]([\\w@./-]+\\.(?:ts|tsx|js|jsx|sql|yml|yaml|json))['\"`]/g;\n\n for (const file of ctx.files) {\n if (!matchesGlobs(file.filename, fileGlobs)) continue;\n if (pathIgnore.length > 0 && matchesGlobs(file.filename, pathIgnore)) continue;\n\n for (const line of addedLines(file.patch)) {\n importRefPattern.lastIndex = 0;\n for (const match of line.matchAll(importRefPattern)) {\n const candidate = match[1]?.replace(/^\\.\\//, \"\");\n if (!candidate || candidate.includes(\"*\")) continue;\n if (candidate.startsWith(\"node:\")) continue;\n // Skip bare, repo-ubiquitous manifest names (package.json, etc.).\n const base = candidate.split(\"/\").pop()?.toLowerCase() ?? \"\";\n if (!candidate.includes(\"/\") && ARTIFACT_BARE_IGNORE.has(base)) continue;\n if (!ctx.prPaths.has(candidate)) {\n referenced.add(candidate);\n }\n }\n }\n }\n\n if (referenced.size === 0) return null;\n const missing = [...referenced].slice(0, 8);\n return result({\n code: \"artifact_integrity\",\n severity: \"blocking\",\n title: \"Referenced files missing from PR\",\n detail: `Added lines reference paths not in this PR: ${missing.join(\", \")}${referenced.size > 8 ? \"…\" : \"\"}.`,\n files: missing,\n suggested_action: \"Include referenced files or fix hallucinated paths.\",\n });\n}\n\nfunction isNamingAllowlisted(\n filename: string,\n line: string,\n allowlist: NamingAllowlistConfig = {},\n slugOnlyPatterns: RegExp[] = [],\n): boolean {\n const trimmed = line.trim();\n const path = normalizePath(filename);\n const ext = extensionOf(filename);\n const skipExtensions = allowlist.skip_extensions ?? [\".sql\"];\n const skipPathPatterns = allowlist.skip_path_patterns ?? [\"migrations/\", \"schema/\"];\n const skipCommentMarkers = allowlist.skip_comment_markers ?? [\n \"historical:\",\n \"migration:\",\n \"deprecated:\",\n ];\n\n if (\n allowlist.skip_in_imports !== false &&\n /^import\\s|^from\\s|require\\(/.test(trimmed)\n ) {\n return true;\n }\n if (skipExtensions.includes(ext)) return true;\n if (skipPathPatterns.some((pattern) => path.includes(pattern))) return true;\n if (\n skipCommentMarkers.some((marker) =>\n trimmed.toLowerCase().includes(marker.toLowerCase()),\n )\n ) {\n return true;\n }\n if (/\\/memory\\//.test(path)) return true;\n if (/RESEARCH\\.md$|BRAND\\.md$|CHANGELOG\\.md$/.test(path)) return true;\n if (/^\\[.*\\]\\(.*\\)/.test(trimmed) || /\\]\\(http/.test(trimmed)) return true;\n\n if (\n slugOnlyPatterns.some((p) => p.test(trimmed)) &&\n !/[A-Z]/.test(\n trimmed.match(\n /(?:cognitive-debt|storyboard-studio|daydream-studio|shadow-ai-governance)/,\n )?.[0] ?? \"\",\n )\n ) {\n return true;\n }\n\n if (/[\"'`/]/.test(trimmed)) {\n const inStringOrPath =\n /[\"'`/][^\"'`]*(?:deployguard|storyboard-studio|daydream-studio|cognitive-debt|shadow-ai-governance|komatik-yggdrasil)[^\"'`]*[\"'`/]/i;\n if (inStringOrPath.test(trimmed)) return true;\n }\n\n return false;\n}\n\nexport function detectContextFreshness(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (ctx.staleTerms.length === 0 && ctx.renamePatterns.length === 0) {\n return null;\n }\n\n const hits: string[] = [];\n for (const file of ctx.files) {\n if (isStaleArchivedPath(file.filename, ctx.pathIgnorePatterns)) continue;\n\n for (const line of linesForFreshnessScan(file)) {\n if (\n isNamingAllowlisted(\n file.filename,\n line,\n ctx.namingAllowlist,\n ctx.slugOnlyPatterns,\n )\n ) {\n continue;\n }\n\n for (const term of ctx.staleTerms) {\n if (line.toLowerCase().includes(term.toLowerCase())) hits.push(file.filename);\n }\n\n for (const entry of ctx.renamePatterns) {\n entry.pattern.lastIndex = 0;\n if (entry.pattern.test(line)) hits.push(file.filename);\n }\n }\n }\n\n const unique = [...new Set(hits)];\n if (unique.length === 0) return null;\n return result({\n code: \"context_freshness\",\n severity: \"warn\",\n title: \"Stale naming or deprecated terms\",\n detail: `Added lines reference deprecated terms in ${unique.join(\", \")}.`,\n files: unique,\n suggested_action: \"Update naming to current product vocabulary (see BRAND.md).\",\n autofix_eligible: true,\n });\n}\n\nexport function detectPathFormat(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (!ctx.komatikInstance) return null;\n const hits = ctx.files\n .map((f) => normalizePath(f.filename))\n .filter(\n (name) =>\n /^komatik-agents\\/agents\\//.test(name) ||\n /\\/agents\\/agents\\//.test(name) ||\n (!/^agents\\/[a-z][a-z0-9-]*\\/suggestions\\//.test(name) &&\n /\\/suggestions\\//.test(name) &&\n !name.startsWith(\"agents/\")),\n );\n if (hits.length === 0) return null;\n return result({\n code: \"path_format\",\n severity: \"warn\",\n title: \"Suspicious agent suggestion path\",\n detail: `Paths should match agents/<id>/suggestions/<project>/… — found: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Use canonical agent suggestion paths without repo prefix.\",\n });\n}\n\nexport function detectHardcodedEnv(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits = scanAddedContent(ctx.files, (line, filename) => {\n if (/\\.(md|txt)$/i.test(filename)) return false;\n if (/^\\s*\\/\\/|^\\s*\\*|^\\s*#/.test(line)) return false;\n return HARDCODED_ENV_PATTERNS.some((entry) => {\n entry.pattern.lastIndex = 0;\n return entry.pattern.test(line);\n });\n });\n if (hits.length === 0) return null;\n return result({\n code: \"hardcoded_env\",\n severity: \"blocking\",\n title: \"Hardcoded environment value\",\n detail: `Added lines contain hardcoded localhost/IP patterns in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action:\n \"Use environment variables or configuration instead of hardcoded hosts.\",\n });\n}\n\nexport function detectLargeFile(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits = ctx.files\n .filter((file) => {\n const lines =\n typeof file.content === \"string\"\n ? file.content.split(\"\\n\").length\n : lineCountFromPatch(file.patch);\n return lines > ctx.maxFileLines;\n })\n .map((f) => f.filename);\n if (hits.length === 0) return null;\n return result({\n code: \"large_file\",\n severity: \"warn\",\n title: \"Large file in PR\",\n detail: `Files exceed ${ctx.maxFileLines} lines: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Split large changes into smaller PRs.\",\n });\n}\n\nfunction extractRelativeImports(content: string): string[] {\n const imports: string[] = [];\n const patterns = [\n /\\bimport\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)?['\"](\\.\\.?[^'\"]+)['\"]/g,\n /\\brequire\\(\\s*['\"](\\.\\.?[^'\"]+)['\"]\\s*\\)/g,\n ];\n for (const pattern of patterns) {\n for (const match of content.matchAll(pattern)) {\n if (match[1]) imports.push(match[1]);\n }\n }\n return imports;\n}\n\nfunction resolveRelativeImport(\n fromFile: string,\n specifier: string,\n prPaths: Set<string>,\n): boolean {\n const clean = specifier.split(\"?\")[0].split(\"#\")[0];\n const baseDir = normalizePath(fromFile).split(\"/\").slice(0, -1);\n const segments = clean.replace(/^\\.\\//, \"\").split(\"/\");\n for (const segment of segments) {\n if (segment === \"..\") baseDir.pop();\n else if (segment !== \".\") baseDir.push(segment);\n }\n const resolved = baseDir.join(\"/\");\n const candidates = [\n resolved,\n `${resolved}.ts`,\n `${resolved}.tsx`,\n `${resolved}.js`,\n `${resolved}.jsx`,\n `${resolved}/index.ts`,\n `${resolved}/index.js`,\n ];\n return candidates.some((c) => prPaths.has(c));\n}\n\nexport function detectImportResolution(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const codeExts = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n const hits: string[] = [];\n\n for (const file of ctx.files) {\n if (!codeExts.has(extensionOf(file.filename))) continue;\n const content = fileContent(file);\n for (const specifier of extractRelativeImports(content)) {\n if (!resolveRelativeImport(file.filename, specifier, ctx.prPaths)) {\n hits.push(file.filename);\n break;\n }\n }\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"import_resolution\",\n severity: \"blocking\",\n title: \"Unresolved relative import\",\n detail: `Relative imports could not be resolved within this PR: ${[...new Set(hits)].join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action: \"Add missing files to the PR or fix import paths.\",\n });\n}\n\nexport function detectRlsNewTables(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const sqlFiles = ctx.files.filter((f) => extensionOf(f.filename) === \".sql\");\n const corpus = sqlFiles.map((f) => fileContent(f)).join(\"\\n\");\n const hits: string[] = [];\n const createTable =\n /\\bCREATE\\s+(?!TEMP(?:ORARY)?\\s+)TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?((?:\"?[A-Za-z_][\\w$]*\"?\\.)?\"?[A-Za-z_][\\w$]*\"?)/gi;\n\n for (const file of sqlFiles) {\n const content = fileContent(file);\n for (const match of content.matchAll(createTable)) {\n const table = match[1]?.replace(/\"/g, \"\") ?? \"\";\n const pattern = new RegExp(\n `ALTER\\\\s+TABLE\\\\s+(?:ONLY\\\\s+)?[\"']?${table.split(\".\").pop()}[\"']?\\\\s+ENABLE\\\\s+ROW\\\\s+LEVEL\\\\s+SECURITY`,\n \"i\",\n );\n if (!pattern.test(corpus)) hits.push(file.filename);\n }\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"rls_new_tables\",\n severity: \"blocking\",\n title: \"New table missing RLS\",\n detail: `CREATE TABLE without ENABLE ROW LEVEL SECURITY in ${[...new Set(hits)].join(\", \")}.`,\n files: [...new Set(hits)],\n suggested_action:\n \"Add ALTER TABLE ... ENABLE ROW LEVEL SECURITY for every new table.\",\n });\n}\n\nfunction isRouteAllowlisted(path: string, allowlist: string[]): boolean {\n return allowlist.some((entry) => path.includes(entry.replace(/^\\//, \"\")));\n}\n\nexport function detectAuthRouteAuth(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const routePattern =\n /(?:^|\\/)(?:app\\/api\\/.+\\/route|pages\\/api\\/.+)\\.(?:ts|tsx|js|jsx)$/;\n const authPattern =\n /\\b(getUser|getSession|getServerSession|auth|requireAuth|withAuth)\\s*\\(/;\n const hits: string[] = [];\n\n for (const file of ctx.files) {\n const normalized = normalizePath(file.filename);\n if (!routePattern.test(normalized)) continue;\n if (isRouteAllowlisted(normalized, ctx.authRouteAllowlist)) continue;\n if (!authPattern.test(fileContent(file))) hits.push(normalized);\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"auth_route_auth\",\n severity: \"blocking\",\n title: \"API route missing auth check\",\n detail: `Routes appear to lack session/user verification: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Verify authenticated user before handling the request.\",\n });\n}\n\nfunction packageNameFromSpecifier(specifier: string): string {\n if (specifier.startsWith(\"@\")) return specifier.split(\"/\").slice(0, 2).join(\"/\");\n return specifier.split(\"/\")[0];\n}\n\nfunction isNodeBuiltin(specifier: string): boolean {\n const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n return NODE_BUILTINS.has(bare.split(\"/\")[0]);\n}\n\nexport function detectExternalPackageDeps(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (ctx.declaredPackages.size === 0) return null;\n const codeExts = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n const hits: string[] = [];\n\n for (const file of ctx.files) {\n if (!codeExts.has(extensionOf(file.filename))) continue;\n\n for (const imp of extractAllImports(fileContent(file))) {\n const specifier = imp.specifier;\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) continue;\n if (specifier.startsWith(\"@/\") || specifier.startsWith(\"~/\")) continue;\n if (specifier.startsWith(\"http:\") || specifier.startsWith(\"https:\")) continue;\n if (isNodeBuiltin(specifier)) continue;\n const pkg = packageNameFromSpecifier(specifier);\n if (!ctx.declaredPackages.has(pkg)) hits.push(`${file.filename} → ${pkg}`);\n }\n }\n\n if (hits.length === 0) return null;\n return result({\n code: \"external_package_deps\",\n severity: \"warn\",\n title: \"Undeclared package import\",\n detail: hits.slice(0, 6).join(\"; \"),\n files: [...new Set(hits.map((h) => h.split(\" → \")[0]))],\n suggested_action: \"Add the package to package.json or remove the import.\",\n });\n}\n\nfunction stripSqlComments(content: string): string {\n return content.replace(/--[^\\n]*/g, \"\").replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n}\n\nfunction countPlpgsqlBlockBegins(sql: string): number {\n const re = /\\bBEGIN\\b(?!\\s+(?:TRANSACTION|WORK)\\b)/gi;\n return (sql.match(re) || []).length;\n}\n\nfunction countPlpgsqlBlockEnds(sql: string): number {\n const re = /\\bEND\\s*(?!IF\\b|LOOP\\b|CASE\\b)\\s*(?:;|\\$\\$)/gi;\n return (sql.match(re) || []).length;\n}\n\nexport function detectSqlSyntaxBasic(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const hits: string[] = [];\n for (const file of ctx.files.filter((f) => extensionOf(f.filename) === \".sql\")) {\n const stripped = stripSqlComments(fileContent(file));\n const beginCount = countPlpgsqlBlockBegins(stripped);\n const endCount = countPlpgsqlBlockEnds(stripped);\n if (beginCount > 0 && beginCount > endCount) hits.push(file.filename);\n }\n if (hits.length === 0) return null;\n return result({\n code: \"sql_syntax_basic\",\n severity: \"warn\",\n title: \"SQL block balance issue\",\n detail: `Possible unclosed BEGIN block in ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Verify PL/pgSQL block structure before merging.\",\n });\n}\n\nexport function detectSyntaxValidity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n const errors: string[] = [];\n\n for (const file of ctx.files) {\n // Real parsers need the whole file — skip patch-only inputs (PR diff fragments).\n if (typeof file.content !== \"string\") continue;\n\n const message = validateFileSyntax(file.filename, file.content);\n if (message) errors.push(`${file.filename}: ${message}`);\n }\n\n if (errors.length === 0) return null;\n return result({\n code: \"syntax_validity\",\n severity: \"blocking\",\n title: \"Syntax error in submitted file\",\n detail: errors.slice(0, 12).join(\"; \"),\n files: errors.map((e) => e.split(\": \")[0] ?? e),\n suggested_action: \"Fix the parse error before submitting.\",\n });\n}\n\nexport function detectSoulIntegrity(\n ctx: SubmissionCheckContext,\n): SubmissionCheckResult | null {\n if (!ctx.komatikInstance) return null;\n const hits = ctx.files\n .map((f) => normalizePath(f.filename))\n .filter((name) => /^agents\\/[a-z][a-z0-9-]*\\/SOUL\\.md$/.test(name));\n if (hits.length === 0) return null;\n return result({\n code: \"soul_integrity\",\n severity: \"blocking\",\n title: \"Agent SOUL.md modified\",\n detail: `SOUL changes require human review: ${hits.join(\", \")}.`,\n files: hits,\n suggested_action: \"Revert SOUL.md changes or request explicit human approval.\",\n });\n}\n\nexport function runAllDetectors(ctx: SubmissionCheckContext): SubmissionCheckResult[] {\n const policy = ctx.detectorPolicy;\n const finalize = (\n code: SubmissionCheckCode,\n check: SubmissionCheckResult | null,\n ): SubmissionCheckResult | null => applyDetectorPolicy(code, check, policy);\n\n const gate1 = [\n finalize(\"mock_placeholder\", detectMockPlaceholder(ctx)),\n finalize(\"secrets\", detectSecrets(ctx)),\n finalize(\"destructive_sql\", detectDestructiveSql(ctx)),\n finalize(\"syntax_validity\", detectSyntaxValidity(ctx)),\n finalize(\"import_resolution\", detectImportResolution(ctx)),\n finalize(\"rls_new_tables\", detectRlsNewTables(ctx)),\n finalize(\"auth_route_auth\", detectAuthRouteAuth(ctx)),\n finalize(\"hardcoded_env\", detectHardcodedEnv(ctx)),\n finalize(\"external_package_deps\", detectExternalPackageDeps(ctx)),\n finalize(\"sql_syntax_basic\", detectSqlSyntaxBasic(ctx)),\n finalize(\"large_file\", detectLargeFile(ctx)),\n finalize(\"artifact_integrity\", detectArtifactIntegrity(ctx)),\n finalize(\"context_freshness\", detectContextFreshness(ctx)),\n finalize(\"soul_integrity\", detectSoulIntegrity(ctx)),\n finalize(\"path_format\", detectPathFormat(ctx)),\n finalize(\"contract_integrity\", detectContractIntegrity(ctx)),\n finalize(\"safe_deprecation\", detectSafeDeprecation(ctx)),\n finalize(\"destructive_change\", detectDestructiveChange(ctx)),\n finalize(\"claim_anchoring\", detectClaimAnchoring(ctx)),\n finalize(\"promotion_coherence\", detectPromotionCoherence(ctx)),\n ].filter((check): check is SubmissionCheckResult => check !== null);\n\n const phase0 = runPhase0Detectors(ctx)\n .map((check) => finalize(check.code, check))\n .filter((check): check is SubmissionCheckResult => check !== null);\n\n return [...gate1, ...phase0];\n}\n","// Gate 1 — agent submission quality (Phase B1).\n// Pure module: no @actions/*, octokit, or Node I/O.\n\nimport { runAllDetectors } from \"./submission-checks/detectors.js\";\nimport type { SubmissionCheckContext } from \"./submission-checks/types.js\";\nimport { prPathSet } from \"./submission-checks/helpers.js\";\nimport {\n buildRenamePatterns,\n buildSlugOnlyPatterns,\n getSubmissionConfigWarnings,\n resolveDetectorPolicy,\n} from \"./submission-checks/detector-policy.js\";\nimport { SubmissionCheckCode } from \"./types.js\";\nimport type { RepoConfig, SubmissionCheckResult } from \"./types.js\";\n\nexport type { SubmissionFileInfo } from \"./submission-checks/types.js\";\nexport type { SubmissionCheckCode, SubmissionCheckResult } from \"./types.js\";\nexport { getSubmissionConfigWarnings };\n\n/** Gate 1 + Phase 0 submission check codes — keep in sync with A8 fixture manifest. */\nexport const SUBMISSION_CHECK_CODES = SubmissionCheckCode.options;\n\nconst DEFAULT_AUTH_ROUTE_ALLOWLIST = [\n \"/api/auth/\",\n \"/api/webhooks/\",\n \"/api/health/\",\n \"/api/metrics/\",\n];\n\n/** Package names declared in a package.json (legacy gate parity). */\nexport function declaredPackageNamesFromPackageJson(\n pkg: Record<string, unknown>,\n): string[] {\n const sections = [\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n \"optionalDependencies\",\n ] as const;\n return sections.flatMap((key) =>\n Object.keys((pkg[key] as Record<string, string> | undefined) ?? {}),\n );\n}\n\nexport interface SubmissionEngineOptions {\n files: import(\"./submission-checks/types.js\").SubmissionFileInfo[];\n repoConfig?: RepoConfig | null;\n komatikInstance?: boolean;\n mode?: \"warn\" | \"block\";\n /** Declared npm package names from root package.json (optional). */\n declaredPackages?: string[];\n /** Paths that exist in the target repo (e.g. `git ls-files`), optional. */\n repoPaths?: string[];\n /**\n * Org catalog entity names resolved by the caller (I/O layer) — e.g. loaded\n * from `submission.contract_integrity.catalog_index_path`. Merged with the\n * inline `known_entities` config for the `contract_integrity` detector.\n */\n catalogKnownEntities?: string[];\n /** Promotion branch topology (GITHUB_BASE_REF / GITHUB_HEAD_REF), set by the gate. */\n promotion?: { baseBranch?: string; headBranch?: string };\n}\n\nfunction buildContext(options: SubmissionEngineOptions): SubmissionCheckContext {\n const { files, repoConfig, komatikInstance = false } = options;\n const staleTerms = repoConfig?.submission?.stale_terms ?? [];\n\n const declared = new Set(options.declaredPackages ?? []);\n const { policy } = resolveDetectorPolicy(repoConfig?.submission);\n\n // contract_integrity (ADR-010): org catalog index = inline config ∪ caller-loaded.\n const inlineKnown = repoConfig?.submission?.contract_integrity?.known_entities ?? [];\n const catalogKnownEntities = new Set<string>([\n ...inlineKnown,\n ...(options.catalogKnownEntities ?? []),\n ]);\n\n return {\n files,\n prPaths: prPathSet(files),\n komatikInstance,\n staleTerms,\n namingAllowlist: repoConfig?.submission?.naming_allowlist ?? {},\n authRouteAllowlist:\n repoConfig?.submission?.auth_route_allowlist ?? DEFAULT_AUTH_ROUTE_ALLOWLIST,\n maxFileLines: repoConfig?.submission?.max_file_lines ?? 1000,\n declaredPackages: declared,\n pathIgnorePatterns: repoConfig?.submission?.path_ignore ?? [],\n renamePatterns: buildRenamePatterns(repoConfig?.submission, {\n includeKomatikDefaults: komatikInstance,\n }),\n slugOnlyPatterns: buildSlugOnlyPatterns(repoConfig?.submission),\n detectorPolicy: policy,\n repoPaths: options.repoPaths ? new Set(options.repoPaths) : undefined,\n catalogKnownEntities:\n catalogKnownEntities.size > 0 ? catalogKnownEntities : undefined,\n promotion: options.promotion,\n };\n}\n\nexport function runSubmissionGate(\n options: SubmissionEngineOptions,\n): SubmissionCheckResult[] {\n if (options.files.length === 0) return [];\n return runAllDetectors(buildContext(options));\n}\n\nexport function submissionGateShouldBlock(\n checks: SubmissionCheckResult[],\n mode: \"warn\" | \"block\" = \"block\",\n): boolean {\n if (mode !== \"block\") return false;\n return checks.some((check) => check.severity === \"blocking\");\n}\n","\nimport * as fs from \"node:fs\";\nimport { runInitWizard } from \"./init-wizard.js\";\nimport { runDoctorCommand } from \"./run-doctor.js\";\nimport {\n runSubmissionGate,\n submissionGateShouldBlock,\n} from \"./shared/submission-engine.js\";\n\nconst CLI_VERSION = \"4.4.5\";\n\nconst BOLD = \"\\x1b[1m\";\nconst GREEN = \"\\x1b[32m\";\nconst RESET = \"\\x1b[0m\";\n\nfunction print(msg: string) {\n process.stdout.write(msg + \"\\n\");\n}\n\nfunction asAddedPatch(content: string): string {\n const lines = content.split(\"\\n\");\n return `@@ -0,0 +1,${lines.length} @@\\n${lines.map((l) => `+${l}`).join(\"\\n\")}\\n`;\n}\n\nfunction runValidateSubmission(args: string[]): number {\n const inputIdx = args.indexOf(\"--input\");\n let raw: string;\n try {\n raw =\n inputIdx >= 0 && args[inputIdx + 1]\n ? fs.readFileSync(args[inputIdx + 1] as string, \"utf-8\")\n : fs.readFileSync(0, \"utf-8\");\n } catch {\n process.stderr.write(\"validate-submission: could not read input\\n\");\n return 2;\n }\n\n let payload: {\n files?: Array<{ filename: string; content?: string; patch?: string }>;\n komatikInstance?: boolean;\n komatik_instance?: boolean;\n repoPaths?: string[];\n repo_paths?: string[];\n declaredPackages?: string[];\n declared_packages?: string[];\n mode?: \"warn\" | \"block\";\n };\n try {\n payload = JSON.parse(raw);\n } catch {\n process.stderr.write(\"validate-submission: input is not valid JSON\\n\");\n return 2;\n }\n\n const mode = payload.mode ?? \"block\";\n const files = (payload.files ?? []).map((f) =>\n typeof f.content === \"string\" && !f.patch\n ? { ...f, patch: asAddedPatch(f.content) }\n : f,\n );\n const checks = runSubmissionGate({\n files,\n komatikInstance: payload.komatikInstance ?? payload.komatik_instance ?? false,\n repoPaths: payload.repoPaths ?? payload.repo_paths,\n declaredPackages: payload.declaredPackages ?? payload.declared_packages,\n mode,\n });\n\n const shouldBlock = submissionGateShouldBlock(checks, mode);\n const decision = shouldBlock\n ? \"block\"\n : checks.some((c) => c.severity === \"warn\")\n ? \"warn\"\n : \"allow\";\n\n process.stdout.write(\n JSON.stringify({ decision, shouldBlock, mode, checks }, null, 2) + \"\\n\",\n );\n return 0;\n}\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0];\n\n if (command === \"doctor\") {\n const code = await runDoctorCommand(args.slice(1));\n process.exit(code);\n }\n\n if (command === \"validate-submission\") {\n const code = runValidateSubmission(args.slice(1));\n process.exit(code);\n }\n\n if (command === \"init\") {\n const code = await runInitWizard(args.slice(1));\n process.exit(code);\n }\n\n print(`\n${BOLD}${GREEN}Trailhead CLI v${CLI_VERSION}${RESET}\n\n${BOLD}Usage:${RESET}\n npx @komatikai/trailhead init [--preset solo|team|agent|ops]\n npx @komatikai/trailhead doctor\n npx @komatikai/trailhead validate-submission\n\n${BOLD}Presets:${RESET} solo · team · agent · ops — see presets/ or docs/getting-started.md\n\n${BOLD}Learn more:${RESET}\n https://github.com/KomatikAI/trailhead\n`);\n}\n\nmain().catch((err) => {\n console.error(\"Error:\", err);\n process.exit(1);\n});\n"],"names":[],"sourceRoot":""}