@transcend-io/cli 12.1.5 → 13.0.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.
Files changed (215) hide show
  1. package/README.md +64 -14
  2. package/dist/{app-BMLQABJX.mjs → app-CCGKgPiC.mjs} +19 -19
  3. package/dist/app-CCGKgPiC.mjs.map +1 -0
  4. package/dist/{approvePrivacyRequests-CY6rQT4J.mjs → approvePrivacyRequests-BBcqydVb.mjs} +2 -2
  5. package/dist/{approvePrivacyRequests-CY6rQT4J.mjs.map → approvePrivacyRequests-BBcqydVb.mjs.map} +1 -1
  6. package/dist/bin/bash-complete.mjs +1 -1
  7. package/dist/bin/cli.mjs +1 -1
  8. package/dist/bin/deprecated-command.mjs +1 -1
  9. package/dist/{buildExamples-BNGtj-DW.mjs → buildExamples-DRU0o6EK.mjs} +2 -2
  10. package/dist/{buildExamples-BNGtj-DW.mjs.map → buildExamples-DRU0o6EK.mjs.map} +1 -1
  11. package/dist/{buildXdiSyncEndpoint-BNCfOc-g.mjs → buildXdiSyncEndpoint-CSjQKSn3.mjs} +2 -2
  12. package/dist/{buildXdiSyncEndpoint-BNCfOc-g.mjs.map → buildXdiSyncEndpoint-CSjQKSn3.mjs.map} +1 -1
  13. package/dist/{bulkRestartRequests-CGvODu3r.mjs → bulkRestartRequests-Cx5LfpdX.mjs} +2 -2
  14. package/dist/{bulkRestartRequests-CGvODu3r.mjs.map → bulkRestartRequests-Cx5LfpdX.mjs.map} +1 -1
  15. package/dist/{bulkRetryEnrichers-BgDd4GWH.mjs → bulkRetryEnrichers-BSJtvqJD.mjs} +2 -2
  16. package/dist/{bulkRetryEnrichers-BgDd4GWH.mjs.map → bulkRetryEnrichers-BSJtvqJD.mjs.map} +1 -1
  17. package/dist/{cancelPrivacyRequests-Ccsiwrnu.mjs → cancelPrivacyRequests-Cy48R4tJ.mjs} +2 -2
  18. package/dist/{cancelPrivacyRequests-Ccsiwrnu.mjs.map → cancelPrivacyRequests-Cy48R4tJ.mjs.map} +1 -1
  19. package/dist/codecs-8T8Jhxsr.mjs +2 -0
  20. package/dist/codecs-8T8Jhxsr.mjs.map +1 -0
  21. package/dist/{command-BjzdoKgJ.mjs → command-Gip5wB8W.mjs} +2 -2
  22. package/dist/{command-BjzdoKgJ.mjs.map → command-Gip5wB8W.mjs.map} +1 -1
  23. package/dist/constants-D6y_AX3P.mjs +2 -0
  24. package/dist/constants-D6y_AX3P.mjs.map +1 -0
  25. package/dist/{constants-FDjw7bPS.mjs → constants-DAx9VK1C.mjs} +2 -2
  26. package/dist/{constants-FDjw7bPS.mjs.map → constants-DAx9VK1C.mjs.map} +1 -1
  27. package/dist/{createPoolingCommandUi-BdtnLBBM.mjs → createPoolingCommandUi-DZx16Cn8.mjs} +2 -2
  28. package/dist/{createPoolingCommandUi-BdtnLBBM.mjs.map → createPoolingCommandUi-DZx16Cn8.mjs.map} +1 -1
  29. package/dist/{downloadPrivacyRequestFiles-C9-xSCpt.mjs → downloadPrivacyRequestFiles-DBeuW9b3.mjs} +2 -2
  30. package/dist/{downloadPrivacyRequestFiles-C9-xSCpt.mjs.map → downloadPrivacyRequestFiles-DBeuW9b3.mjs.map} +1 -1
  31. package/dist/fetchAllRequests-BV9K0wXv.mjs +2 -0
  32. package/dist/fetchAllRequests-BV9K0wXv.mjs.map +1 -0
  33. package/dist/{fuzzyMatchColumns-D18n9Beu.mjs → fuzzyMatchColumns-Djl3a7lV.mjs} +2 -2
  34. package/dist/{fuzzyMatchColumns-D18n9Beu.mjs.map → fuzzyMatchColumns-Djl3a7lV.mjs.map} +1 -1
  35. package/dist/{generateCrossAccountApiKeys-FtWwlf_L.mjs → generateCrossAccountApiKeys-CjmSyfwm.mjs} +2 -2
  36. package/dist/{generateCrossAccountApiKeys-FtWwlf_L.mjs.map → generateCrossAccountApiKeys-CjmSyfwm.mjs.map} +1 -1
  37. package/dist/{impl-Dg7XSQdO2.mjs → impl-7qTKg-YP2.mjs} +2 -2
  38. package/dist/{impl-Dg7XSQdO2.mjs.map → impl-7qTKg-YP2.mjs.map} +1 -1
  39. package/dist/{impl-D58JUOdA.mjs → impl-9W0QG6fB.mjs} +2 -2
  40. package/dist/{impl-D58JUOdA.mjs.map → impl-9W0QG6fB.mjs.map} +1 -1
  41. package/dist/{impl-B94dMG4x2.mjs → impl-B-BkGfqq2.mjs} +2 -2
  42. package/dist/{impl-B94dMG4x2.mjs.map → impl-B-BkGfqq2.mjs.map} +1 -1
  43. package/dist/{impl-yIVxAhCG2.mjs → impl-B8DsKzNn2.mjs} +2 -2
  44. package/dist/{impl-yIVxAhCG2.mjs.map → impl-B8DsKzNn2.mjs.map} +1 -1
  45. package/dist/impl-B9jwlKCX2.mjs +2 -0
  46. package/dist/impl-B9jwlKCX2.mjs.map +1 -0
  47. package/dist/{impl-C3vTm9zQ.mjs → impl-BIhXJ0Nw.mjs} +2 -2
  48. package/dist/{impl-C3vTm9zQ.mjs.map → impl-BIhXJ0Nw.mjs.map} +1 -1
  49. package/dist/{impl-B_N_fOq0.mjs → impl-BLM6rMBq.mjs} +2 -2
  50. package/dist/{impl-B_N_fOq0.mjs.map → impl-BLM6rMBq.mjs.map} +1 -1
  51. package/dist/{impl-Hj5CgbWd.mjs → impl-BPmzcgpy.mjs} +2 -2
  52. package/dist/{impl-Hj5CgbWd.mjs.map → impl-BPmzcgpy.mjs.map} +1 -1
  53. package/dist/{impl-COqlYiiw.mjs → impl-BUKV7sYp.mjs} +2 -2
  54. package/dist/{impl-COqlYiiw.mjs.map → impl-BUKV7sYp.mjs.map} +1 -1
  55. package/dist/{impl-DFnWzZyY.mjs → impl-BahDGEJJ.mjs} +2 -2
  56. package/dist/{impl-DFnWzZyY.mjs.map → impl-BahDGEJJ.mjs.map} +1 -1
  57. package/dist/{impl-qNF5eqX-.mjs → impl-BfU0GFmW.mjs} +1 -1
  58. package/dist/{impl-qNF5eqX-.mjs.map → impl-BfU0GFmW.mjs.map} +1 -1
  59. package/dist/{impl-DDVhG8Gf.mjs → impl-Bh1CkZhV.mjs} +2 -2
  60. package/dist/{impl-DDVhG8Gf.mjs.map → impl-Bh1CkZhV.mjs.map} +1 -1
  61. package/dist/{impl-BvwRiPSG.mjs → impl-BkQryDNq.mjs} +2 -2
  62. package/dist/{impl-BvwRiPSG.mjs.map → impl-BkQryDNq.mjs.map} +1 -1
  63. package/dist/{impl-bl6NF3Lr.mjs → impl-BsdneZZP.mjs} +2 -2
  64. package/dist/{impl-bl6NF3Lr.mjs.map → impl-BsdneZZP.mjs.map} +1 -1
  65. package/dist/{impl-D6rMLiNB2.mjs → impl-BuOc87b6.mjs} +2 -2
  66. package/dist/impl-BuOc87b6.mjs.map +1 -0
  67. package/dist/{impl-DUYRVzMo.mjs → impl-BzzkiK_b.mjs} +1 -1
  68. package/dist/{impl-DUYRVzMo.mjs.map → impl-BzzkiK_b.mjs.map} +1 -1
  69. package/dist/{impl-ClT3G845.mjs → impl-C2BYhujB.mjs} +2 -2
  70. package/dist/{impl-ClT3G845.mjs.map → impl-C2BYhujB.mjs.map} +1 -1
  71. package/dist/{impl-DnDM9zcu.mjs → impl-C5qif_gE.mjs} +2 -2
  72. package/dist/{impl-DnDM9zcu.mjs.map → impl-C5qif_gE.mjs.map} +1 -1
  73. package/dist/{impl-BLtOfbtk.mjs → impl-C8auyA7u.mjs} +2 -2
  74. package/dist/{impl-BLtOfbtk.mjs.map → impl-C8auyA7u.mjs.map} +1 -1
  75. package/dist/{impl-BEiCEzl_2.mjs → impl-CHoglMch.mjs} +1 -1
  76. package/dist/impl-CHoglMch.mjs.map +1 -0
  77. package/dist/{impl-QD3_9HTk.mjs → impl-CJ4oVuXN.mjs} +2 -2
  78. package/dist/{impl-QD3_9HTk.mjs.map → impl-CJ4oVuXN.mjs.map} +1 -1
  79. package/dist/{impl-DhXzxQDN2.mjs → impl-CRif3TpB2.mjs} +2 -2
  80. package/dist/{impl-DhXzxQDN2.mjs.map → impl-CRif3TpB2.mjs.map} +1 -1
  81. package/dist/{impl-Cvyc-iTI2.mjs → impl-CWINXCFq2.mjs} +2 -2
  82. package/dist/{impl-Cvyc-iTI2.mjs.map → impl-CWINXCFq2.mjs.map} +1 -1
  83. package/dist/{impl-Dd39KsYO.mjs → impl-C_lIkMLn2.mjs} +2 -2
  84. package/dist/impl-C_lIkMLn2.mjs.map +1 -0
  85. package/dist/{impl-EDwngLc7.mjs → impl-CcPwm8a4.mjs} +2 -2
  86. package/dist/{impl-EDwngLc7.mjs.map → impl-CcPwm8a4.mjs.map} +1 -1
  87. package/dist/{impl-DGtCNANL.mjs → impl-CjjiXsMh.mjs} +2 -2
  88. package/dist/{impl-DGtCNANL.mjs.map → impl-CjjiXsMh.mjs.map} +1 -1
  89. package/dist/{impl-BLOhoP-b2.mjs → impl-CzFfjx8n2.mjs} +2 -2
  90. package/dist/{impl-BLOhoP-b2.mjs.map → impl-CzFfjx8n2.mjs.map} +1 -1
  91. package/dist/{impl-BXGpJz21.mjs → impl-D6e2LNBm.mjs} +2 -2
  92. package/dist/{impl-BXGpJz21.mjs.map → impl-D6e2LNBm.mjs.map} +1 -1
  93. package/dist/{impl-SOebshza.mjs → impl-D8yF0jw9.mjs} +2 -2
  94. package/dist/{impl-SOebshza.mjs.map → impl-D8yF0jw9.mjs.map} +1 -1
  95. package/dist/{impl-DeCRXfAh2.mjs → impl-DEF-meSg2.mjs} +2 -2
  96. package/dist/{impl-DeCRXfAh2.mjs.map → impl-DEF-meSg2.mjs.map} +1 -1
  97. package/dist/{impl-DZoTWLfw2.mjs → impl-DEPuP4Oy2.mjs} +2 -2
  98. package/dist/{impl-DZoTWLfw2.mjs.map → impl-DEPuP4Oy2.mjs.map} +1 -1
  99. package/dist/impl-DGLrKNNs2.mjs +2 -0
  100. package/dist/impl-DGLrKNNs2.mjs.map +1 -0
  101. package/dist/{impl-XxYQHKO5.mjs → impl-DPq1O87s.mjs} +2 -2
  102. package/dist/{impl-XxYQHKO5.mjs.map → impl-DPq1O87s.mjs.map} +1 -1
  103. package/dist/{impl-ChQAmyBN.mjs → impl-DiaD11OP.mjs} +2 -2
  104. package/dist/{impl-ChQAmyBN.mjs.map → impl-DiaD11OP.mjs.map} +1 -1
  105. package/dist/{impl-0-_oxvck.mjs → impl-DioQW8jR.mjs} +2 -2
  106. package/dist/{impl-0-_oxvck.mjs.map → impl-DioQW8jR.mjs.map} +1 -1
  107. package/dist/{impl-D6frX-PK.mjs → impl-DjBbx05w.mjs} +2 -2
  108. package/dist/{impl-D6frX-PK.mjs.map → impl-DjBbx05w.mjs.map} +1 -1
  109. package/dist/{impl-BCKUj-ko.mjs → impl-DnBmd-wi.mjs} +2 -2
  110. package/dist/{impl-BCKUj-ko.mjs.map → impl-DnBmd-wi.mjs.map} +1 -1
  111. package/dist/{impl-Cp5o0Q2g.mjs → impl-Do3hnGHt.mjs} +2 -2
  112. package/dist/{impl-Cp5o0Q2g.mjs.map → impl-Do3hnGHt.mjs.map} +1 -1
  113. package/dist/{impl-VSo8bO-J.mjs → impl-DqbJ33ve.mjs} +2 -2
  114. package/dist/{impl-VSo8bO-J.mjs.map → impl-DqbJ33ve.mjs.map} +1 -1
  115. package/dist/{impl-Cb-7C1Ml2.mjs → impl-DvHiVaGW.mjs} +12 -105
  116. package/dist/impl-DvHiVaGW.mjs.map +1 -0
  117. package/dist/{impl-CTOgxZFi.mjs → impl-Dx8BYv7U.mjs} +2 -2
  118. package/dist/{impl-CTOgxZFi.mjs.map → impl-Dx8BYv7U.mjs.map} +1 -1
  119. package/dist/{impl-Bz1wZxa-.mjs → impl-GphhprmF.mjs} +2 -2
  120. package/dist/{impl-Bz1wZxa-.mjs.map → impl-GphhprmF.mjs.map} +1 -1
  121. package/dist/{impl-agm4lpyq.mjs → impl-HsRwcfRu.mjs} +2 -2
  122. package/dist/{impl-agm4lpyq.mjs.map → impl-HsRwcfRu.mjs.map} +1 -1
  123. package/dist/{impl-BHEAKFX02.mjs → impl-LT1FBKID2.mjs} +2 -2
  124. package/dist/{impl-BHEAKFX02.mjs.map → impl-LT1FBKID2.mjs.map} +1 -1
  125. package/dist/{impl-xY_5o78i.mjs → impl-Nwbb2xaH.mjs} +2 -2
  126. package/dist/{impl-xY_5o78i.mjs.map → impl-Nwbb2xaH.mjs.map} +1 -1
  127. package/dist/{impl-CSnBFv5P.mjs → impl-SKxxByoN.mjs} +2 -2
  128. package/dist/{impl-CSnBFv5P.mjs.map → impl-SKxxByoN.mjs.map} +1 -1
  129. package/dist/{impl-ojAnhhbi.mjs → impl-bUltX0u3.mjs} +2 -2
  130. package/dist/{impl-ojAnhhbi.mjs.map → impl-bUltX0u3.mjs.map} +1 -1
  131. package/dist/{impl-Bs2pNgMK.mjs → impl-cU3bjY3P.mjs} +2 -2
  132. package/dist/{impl-Bs2pNgMK.mjs.map → impl-cU3bjY3P.mjs.map} +1 -1
  133. package/dist/{impl-xVmMN-Vt.mjs → impl-h0z8OSQY.mjs} +2 -2
  134. package/dist/{impl-xVmMN-Vt.mjs.map → impl-h0z8OSQY.mjs.map} +1 -1
  135. package/dist/{impl-Ay6JeH-7.mjs → impl-kuuX5KaC.mjs} +2 -2
  136. package/dist/{impl-Ay6JeH-7.mjs.map → impl-kuuX5KaC.mjs.map} +1 -1
  137. package/dist/{impl-Ar7VAh0Z.mjs → impl-nYlbrsD7.mjs} +2 -2
  138. package/dist/{impl-Ar7VAh0Z.mjs.map → impl-nYlbrsD7.mjs.map} +1 -1
  139. package/dist/{impl-zZd6fuXS.mjs → impl-nte7qanu.mjs} +2 -2
  140. package/dist/{impl-zZd6fuXS.mjs.map → impl-nte7qanu.mjs.map} +1 -1
  141. package/dist/{impl-ApZGIx6l.mjs → impl-o66EB2o7.mjs} +2 -2
  142. package/dist/{impl-ApZGIx6l.mjs.map → impl-o66EB2o7.mjs.map} +1 -1
  143. package/dist/{impl-BpVe6fMe.mjs → impl-yxR3rwGm.mjs} +2 -2
  144. package/dist/{impl-BpVe6fMe.mjs.map → impl-yxR3rwGm.mjs.map} +1 -1
  145. package/dist/index.d.mts +36 -26
  146. package/dist/index.d.mts.map +1 -1
  147. package/dist/index.mjs +1 -1
  148. package/dist/{inquirer-jzIQWAvq.mjs → inquirer-DK1JbPA0.mjs} +2 -2
  149. package/dist/{inquirer-jzIQWAvq.mjs.map → inquirer-DK1JbPA0.mjs.map} +1 -1
  150. package/dist/{markRequestDataSiloIdsCompleted-JGJf33yp.mjs → markRequestDataSiloIdsCompleted-loC-xyyW.mjs} +2 -2
  151. package/dist/{markRequestDataSiloIdsCompleted-JGJf33yp.mjs.map → markRequestDataSiloIdsCompleted-loC-xyyW.mjs.map} +1 -1
  152. package/dist/{markSilentPrivacyRequests-BTI3rH-V.mjs → markSilentPrivacyRequests-D7ncAg8k.mjs} +2 -2
  153. package/dist/{markSilentPrivacyRequests-BTI3rH-V.mjs.map → markSilentPrivacyRequests-D7ncAg8k.mjs.map} +1 -1
  154. package/dist/{mergeTranscendInputs-B7WjxYMN.mjs → mergeTranscendInputs-9kQ3t5VY.mjs} +2 -2
  155. package/dist/{mergeTranscendInputs-B7WjxYMN.mjs.map → mergeTranscendInputs-9kQ3t5VY.mjs.map} +1 -1
  156. package/dist/{notifyPrivacyRequestsAdditionalTime-n5fvOJaA.mjs → notifyPrivacyRequestsAdditionalTime-DpCfIR_O.mjs} +2 -2
  157. package/dist/{notifyPrivacyRequestsAdditionalTime-n5fvOJaA.mjs.map → notifyPrivacyRequestsAdditionalTime-DpCfIR_O.mjs.map} +1 -1
  158. package/dist/{policy-bundle-manifest-DbbTXe0u.mjs → policy-bundle-manifest-DW3Wilp8.mjs} +2 -2
  159. package/dist/{policy-bundle-manifest-DbbTXe0u.mjs.map → policy-bundle-manifest-DW3Wilp8.mjs.map} +1 -1
  160. package/dist/{policy-project-discovery-DTSl0Gfl.mjs → policy-project-discovery-CND7N2HI.mjs} +4 -4
  161. package/dist/policy-project-discovery-CND7N2HI.mjs.map +1 -0
  162. package/dist/{policy-scaffold-config-RpxwwZ2H.mjs → policy-scaffold-config-CwY0QZC0.mjs} +8 -8
  163. package/dist/policy-scaffold-config-CwY0QZC0.mjs.map +1 -0
  164. package/dist/{project-discovery-BkHpTXDx.mjs → project-discovery-g29vd44a.mjs} +2 -2
  165. package/dist/{project-discovery-BkHpTXDx.mjs.map → project-discovery-g29vd44a.mjs.map} +1 -1
  166. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DbybCU2T.mjs → pullChunkedCustomSiloOutstandingIdentifiers-7qvaMN58.mjs} +2 -2
  167. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DbybCU2T.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-7qvaMN58.mjs.map} +1 -1
  168. package/dist/{pullManualEnrichmentIdentifiersToCsv-CxTPUfpV.mjs → pullManualEnrichmentIdentifiersToCsv-CWPs7VeX.mjs} +2 -2
  169. package/dist/{pullManualEnrichmentIdentifiersToCsv-CxTPUfpV.mjs.map → pullManualEnrichmentIdentifiersToCsv-CWPs7VeX.mjs.map} +1 -1
  170. package/dist/{pushCronIdentifiersFromCsv-CeRVlbFE.mjs → pushCronIdentifiersFromCsv-DQoliMdQ.mjs} +2 -2
  171. package/dist/{pushCronIdentifiersFromCsv-CeRVlbFE.mjs.map → pushCronIdentifiersFromCsv-DQoliMdQ.mjs.map} +1 -1
  172. package/dist/{pushManualEnrichmentIdentifiersFromCsv--4dYCvyv.mjs → pushManualEnrichmentIdentifiersFromCsv-R9BXYuFk.mjs} +2 -2
  173. package/dist/{pushManualEnrichmentIdentifiersFromCsv--4dYCvyv.mjs.map → pushManualEnrichmentIdentifiersFromCsv-R9BXYuFk.mjs.map} +1 -1
  174. package/dist/{readTranscendYaml-BfqQbPiT.mjs → readTranscendYaml-D576bvzR.mjs} +2 -2
  175. package/dist/{readTranscendYaml-BfqQbPiT.mjs.map → readTranscendYaml-D576bvzR.mjs.map} +1 -1
  176. package/dist/{removeUnverifiedRequestIdentifiers-CV6JGgt_.mjs → removeUnverifiedRequestIdentifiers-CgnfHdbc.mjs} +2 -2
  177. package/dist/{removeUnverifiedRequestIdentifiers-CV6JGgt_.mjs.map → removeUnverifiedRequestIdentifiers-CgnfHdbc.mjs.map} +1 -1
  178. package/dist/{retryRequestDataSilos-_OThvVwU.mjs → retryRequestDataSilos-BrLLNQqT.mjs} +2 -2
  179. package/dist/{retryRequestDataSilos-_OThvVwU.mjs.map → retryRequestDataSilos-BrLLNQqT.mjs.map} +1 -1
  180. package/dist/runRegalLintStep-DPaMm7Gg.mjs +3 -0
  181. package/dist/runRegalLintStep-DPaMm7Gg.mjs.map +1 -0
  182. package/dist/{scaffold-planning-BrX-pcz6.mjs → scaffold-planning-Bp_yqZWx.mjs} +2 -2
  183. package/dist/{scaffold-planning-BrX-pcz6.mjs.map → scaffold-planning-Bp_yqZWx.mjs.map} +1 -1
  184. package/dist/{skipPreflightJobs-D8og5pKe.mjs → skipPreflightJobs-CqjpB7ug.mjs} +2 -2
  185. package/dist/{skipPreflightJobs-D8og5pKe.mjs.map → skipPreflightJobs-CqjpB7ug.mjs.map} +1 -1
  186. package/dist/{skipRequestDataSilos-DUQ6AD_O.mjs → skipRequestDataSilos-DPi6-XVr.mjs} +2 -2
  187. package/dist/{skipRequestDataSilos-DUQ6AD_O.mjs.map → skipRequestDataSilos-DPi6-XVr.mjs.map} +1 -1
  188. package/dist/{streamPrivacyRequestsToCsv-BApu4dvI.mjs → streamPrivacyRequestsToCsv-DVPQ860_.mjs} +2 -2
  189. package/dist/{streamPrivacyRequestsToCsv-BApu4dvI.mjs.map → streamPrivacyRequestsToCsv-DVPQ860_.mjs.map} +1 -1
  190. package/dist/{updateConsentManagerVersionToLatest-BrgPZ5hX.mjs → updateConsentManagerVersionToLatest-gJMWny-i.mjs} +2 -2
  191. package/dist/{updateConsentManagerVersionToLatest-BrgPZ5hX.mjs.map → updateConsentManagerVersionToLatest-gJMWny-i.mjs.map} +1 -1
  192. package/dist/{uploadConsents-DRlDHQak.mjs → uploadConsents-5HlMj7EK.mjs} +2 -2
  193. package/dist/{uploadConsents-DRlDHQak.mjs.map → uploadConsents-5HlMj7EK.mjs.map} +1 -1
  194. package/dist/uploadPrivacyRequestsFromCsv-Dh8KEW3n.mjs +2 -0
  195. package/dist/uploadPrivacyRequestsFromCsv-Dh8KEW3n.mjs.map +1 -0
  196. package/dist/{validateTranscendAuth-D-dDINof.mjs → validateTranscendAuth-BrVGfq6X.mjs} +2 -2
  197. package/dist/{validateTranscendAuth-D-dDINof.mjs.map → validateTranscendAuth-BrVGfq6X.mjs.map} +1 -1
  198. package/package.json +22 -22
  199. package/dist/app-BMLQABJX.mjs.map +0 -1
  200. package/dist/codecs-CfcaFoZR.mjs +0 -2
  201. package/dist/codecs-CfcaFoZR.mjs.map +0 -1
  202. package/dist/constants-DlH2vWm_.mjs +0 -2
  203. package/dist/constants-DlH2vWm_.mjs.map +0 -1
  204. package/dist/fetchAllRequests-BI0tFl_a.mjs +0 -2
  205. package/dist/fetchAllRequests-BI0tFl_a.mjs.map +0 -1
  206. package/dist/impl-BEiCEzl_2.mjs.map +0 -1
  207. package/dist/impl-Cb-7C1Ml2.mjs.map +0 -1
  208. package/dist/impl-D6rMLiNB2.mjs.map +0 -1
  209. package/dist/impl-DNOgBcsu.mjs +0 -3
  210. package/dist/impl-DNOgBcsu.mjs.map +0 -1
  211. package/dist/impl-Dd39KsYO.mjs.map +0 -1
  212. package/dist/policy-project-discovery-DTSl0Gfl.mjs.map +0 -1
  213. package/dist/policy-scaffold-config-RpxwwZ2H.mjs.map +0 -1
  214. package/dist/uploadPrivacyRequestsFromCsv-FAGllBdd.mjs +0 -2
  215. package/dist/uploadPrivacyRequestsFromCsv-FAGllBdd.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"policy-bundle-manifest-DbbTXe0u.mjs","names":[],"sources":["../src/lib/policy/rego-reference.ts","../src/lib/policy/policy-bundle-manifest.ts"],"sourcesContent":["/** Parsed static Rego reference. */\ninterface StaticRegoReference {\n /** Source representation of the reference. */\n source: string;\n /** Logical document path segments. */\n segments: string[];\n /** Offset immediately after the reference. */\n end: number;\n}\n\n/** Matches the beginning of a Rego package declaration. */\nconst PACKAGE_DECLARATION_PATTERN = /^\\s*package\\s+/mu;\n\n/**\n * Read an identifier at a source offset.\n *\n * @param source - Rego source\n * @param start - Candidate identifier offset\n * @returns Identifier and following offset\n */\nfunction readIdentifier(\n source: string,\n start: number,\n): { identifier: string; end: number } | undefined {\n const match = /^[A-Za-z_][A-Za-z0-9_]*/u.exec(source.slice(start));\n return match ? { identifier: match[0], end: start + match[0].length } : undefined;\n}\n\n/**\n * Advance past Rego whitespace.\n *\n * @param source - Rego source\n * @param start - Initial source offset\n * @returns First non-whitespace offset\n */\nfunction skipWhitespace(source: string, start: number): number {\n let current = start;\n while (current < source.length && /\\s/u.test(source[current]!)) {\n current += 1;\n }\n return current;\n}\n\n/**\n * Read a quoted or raw Rego string.\n *\n * @param source - Rego source\n * @param start - Opening quote offset\n * @returns Decoded string and following offset\n */\nfunction readQuotedString(\n source: string,\n start: number,\n): { value: string; end: number } | undefined {\n if (source[start] === '`') {\n const closingQuote = source.indexOf('`', start + 1);\n return closingQuote === -1\n ? undefined\n : { value: source.slice(start + 1, closingQuote), end: closingQuote + 1 };\n }\n if (source[start] !== '\"') {\n return undefined;\n }\n let current = start + 1;\n while (current < source.length) {\n if (source[current] === '\\\\') {\n current += 2;\n continue;\n }\n if (source[current] === '\"') {\n const raw = source.slice(start, current + 1);\n try {\n return { value: JSON.parse(raw) as string, end: current + 1 };\n } catch {\n return undefined;\n }\n }\n current += 1;\n }\n return undefined;\n}\n\n/**\n * Parse a static Rego reference with dotted or quoted bracket segments.\n *\n * @param source - Rego source\n * @param start - First identifier offset\n * @returns Parsed reference\n */\nfunction parseStaticRegoReference(source: string, start: number): StaticRegoReference | undefined {\n const first = readIdentifier(source, start);\n if (!first) {\n return undefined;\n }\n const segments = [first.identifier];\n let current = first.end;\n while (current < source.length) {\n const separator = skipWhitespace(source, current);\n if (source[separator] === '.') {\n const identifierStart = skipWhitespace(source, separator + 1);\n const identifier = readIdentifier(source, identifierStart);\n if (!identifier) {\n break;\n }\n segments.push(identifier.identifier);\n current = identifier.end;\n continue;\n }\n if (source[separator] === '[') {\n const stringStart = skipWhitespace(source, separator + 1);\n const value = readQuotedString(source, stringStart);\n if (!value) {\n break;\n }\n const closingBracket = skipWhitespace(source, value.end);\n if (source[closingBracket] !== ']') {\n break;\n }\n segments.push(value.value);\n current = closingBracket + 1;\n continue;\n }\n break;\n }\n return {\n source: source.slice(start, current),\n segments,\n end: current,\n };\n}\n\n/**\n * Read the package reference declared by Rego source.\n *\n * @param contents - Rego source\n * @returns Package reference, or undefined when no declaration is present\n */\nexport function parseRegoPackageReference(\n contents: string,\n): Omit<StaticRegoReference, 'end'> | undefined {\n const declaration = PACKAGE_DECLARATION_PATTERN.exec(contents);\n if (!declaration) {\n return undefined;\n }\n const reference = parseStaticRegoReference(contents, declaration.index + declaration[0].length);\n return reference ? { source: reference.source, segments: reference.segments } : undefined;\n}\n\n/**\n * Skip a string literal while scanning executable Rego source.\n *\n * @param source - Rego source\n * @param start - Opening delimiter offset\n * @returns Offset immediately after the string\n */\nfunction skipStringLiteral(source: string, start: number): number {\n const delimiter = source[start]!;\n let current = start + 1;\n while (current < source.length) {\n if (delimiter === '\"' && source[current] === '\\\\') {\n current += 2;\n continue;\n }\n if (source[current] === delimiter) {\n return current + 1;\n }\n current += 1;\n }\n return current;\n}\n\n/**\n * Find executable static `data` references outside imports.\n *\n * @param contents - Rego source\n * @returns References with one-based source lines\n */\nexport function findDirectDataReferences(\n contents: string,\n): { reference: StaticRegoReference; line: number }[] {\n const references: { reference: StaticRegoReference; line: number }[] = [];\n let current = 0;\n while (current < contents.length) {\n if (contents[current] === '#') {\n const newline = contents.indexOf('\\n', current);\n current = newline === -1 ? contents.length : newline + 1;\n continue;\n }\n if (contents[current] === '\"' || contents[current] === '`') {\n current = skipStringLiteral(contents, current);\n continue;\n }\n const identifier = readIdentifier(contents, current);\n if (!identifier) {\n current += 1;\n continue;\n }\n if (identifier.identifier !== 'data') {\n current = identifier.end;\n continue;\n }\n const reference = parseStaticRegoReference(contents, current);\n if (!reference || reference.segments.length === 1) {\n current = identifier.end;\n continue;\n }\n const lineStart = contents.lastIndexOf('\\n', current - 1) + 1;\n if (!/^\\s*import\\s+$/u.test(contents.slice(lineStart, current))) {\n references.push({\n reference,\n line: contents.slice(0, current).split('\\n').length,\n });\n }\n current = reference.end;\n }\n return references;\n}\n","import {\n POLICY_MANIFEST_FILENAME,\n POLICY_MANIFEST_TRANSCEND_METADATA_KEY,\n POLICY_TEMPLATE_NAMES,\n type PolicyTemplateName,\n} from './policy-scaffold-templates.js';\nimport { findDirectDataReferences, parseRegoPackageReference } from './rego-reference.js';\n\n/** Shape of the policy bundle `.manifest` accepted by Policy Engine. */\nexport interface PolicyBundleManifest {\n /** Roots of the bundle, such as `policy_engine/transcend`. */\n roots: string[];\n /**\n * Optional scaffold template from `metadata.transcend.io.template`.\n *\n * Authoring hint only — upload does not branch on it. Permissions API\n * still keys off the remote bundle name `permissions`.\n */\n template?: PolicyTemplateName;\n}\n\n/** In-memory Rego file used to validate a policy bundle. */\nexport interface PolicyBundleRegoFile {\n /** POSIX-style path relative to the policy bundle directory. */\n path: string;\n /** Rego source contents. */\n contents: string;\n}\n\n/** Validated publishable policy bundle contents. */\nexport interface ValidatedPolicyBundleContents {\n /** Parsed and validated bundle manifest. */\n manifest: PolicyBundleManifest;\n /** Publishable Rego paths, excluding local test modules. */\n publishableRegoPaths: string[];\n}\n\n/**\n * Returns whether a relative path is a publishable Rego policy file.\n *\n * OPA test files (`*_test.rego`) are local-only and excluded from uploads.\n *\n * @param relativePath - Path relative to the bundle directory\n * @returns Whether the file belongs in the uploaded archive\n */\nexport function isPublishableRegoFile(relativePath: string): boolean {\n return relativePath.endsWith('.rego') && !relativePath.endsWith('_test.rego');\n}\n\n/**\n * Parse and validate the Policy Engine bundle manifest.\n *\n * @param contents - Raw manifest contents, or undefined when absent\n * @returns Parsed manifest\n */\nexport function parsePolicyBundleManifest(contents: string | undefined): PolicyBundleManifest {\n if (contents === undefined) {\n throw new Error(`Policy bundle directory must contain a ${POLICY_MANIFEST_FILENAME} file.`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(contents);\n } catch (error) {\n throw new Error(\n `${POLICY_MANIFEST_FILENAME} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${POLICY_MANIFEST_FILENAME} must contain a JSON object.`);\n }\n\n const roots = (parsed as { roots?: unknown }).roots;\n if (!Array.isArray(roots) || roots.length === 0) {\n throw new Error(\n `${POLICY_MANIFEST_FILENAME} must declare \"roots\" as a non-empty array of strings (e.g. {\"roots\":[\"policy_engine\"]}).`,\n );\n }\n if (!roots.every((root) => typeof root === 'string' && root.length > 0)) {\n throw new Error(`${POLICY_MANIFEST_FILENAME} \"roots\" must be an array of non-empty strings.`);\n }\n if (\n !roots.every((root) =>\n root.split('/').every((segment: string) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(segment)),\n )\n ) {\n throw new Error(\n `${POLICY_MANIFEST_FILENAME} \"roots\" must contain slash-separated Rego identifiers so Policy Engine can re-namespace them safely.`,\n );\n }\n\n const template = parseOptionalManifestTemplate(parsed);\n\n return template === undefined ? { roots } : { roots, template };\n}\n\n/**\n * Read an optional `metadata.transcend.io.template` authoring hint.\n *\n * Invalid or unknown values are ignored so upload validation stays focused on\n * roots and Rego coverage.\n *\n * @param parsed - Parsed `.manifest` object\n * @returns Known template name, or undefined\n */\nfunction parseOptionalManifestTemplate(parsed: object): PolicyTemplateName | undefined {\n const metadata = (parsed as { metadata?: unknown }).metadata;\n if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {\n return undefined;\n }\n const transcend = (metadata as Record<string, unknown>)[POLICY_MANIFEST_TRANSCEND_METADATA_KEY];\n if (!transcend || typeof transcend !== 'object' || Array.isArray(transcend)) {\n return undefined;\n }\n const template = (transcend as { template?: unknown }).template;\n if (typeof template !== 'string') {\n return undefined;\n }\n return POLICY_TEMPLATE_NAMES.includes(template as PolicyTemplateName)\n ? (template as PolicyTemplateName)\n : undefined;\n}\n\n/**\n * Determine whether one document path starts with another.\n *\n * @param segments - Complete document path\n * @param prefix - Candidate root\n * @returns Whether the root covers the document path\n */\nfunction hasSegmentPrefix(segments: readonly string[], prefix: readonly string[]): boolean {\n return (\n segments.length >= prefix.length &&\n prefix.every((segment, index) => segment === segments[index])\n );\n}\n\n/**\n * Match the package syntax supported by Policy Engine activation.\n *\n * Bracketed segments remain supported below a declared dotted root.\n *\n * @param reference - Parsed package reference\n * @param root - Declared manifest root\n * @returns Whether activation can re-namespace the package\n */\nfunction rootCoversPackage(reference: { source: string }, root: readonly string[]): boolean {\n const dottedRoot = root.join('.');\n const suffix = reference.source.slice(dottedRoot.length);\n return (\n reference.source.startsWith(dottedRoot) &&\n (suffix === '' || suffix.startsWith('.') || /^\\s*\\[/u.test(suffix))\n );\n}\n\n/**\n * Determine whether `data.<root>` is referenced directly.\n *\n * @param segments - Parsed `data` reference segments\n * @param root - Declared manifest root\n * @returns Whether the reference targets the declared root\n */\nfunction referencesDeclaredRoot(segments: readonly string[], root: readonly string[]): boolean {\n return hasSegmentPrefix(segments.slice(1), root);\n}\n\n/**\n * Validate the manifest, publishable file requirement, and root coverage.\n *\n * This is the shared pure upload contract used by both `policy lint` and\n * `policy publish`.\n *\n * @param manifestContents - Raw manifest contents, or undefined when absent\n * @param regoFiles - All Rego files in the policy directory\n * @returns Validated manifest and publishable paths\n */\nexport function validatePolicyBundleContents(\n manifestContents: string | undefined,\n regoFiles: readonly PolicyBundleRegoFile[],\n): ValidatedPolicyBundleContents {\n const manifest = parsePolicyBundleManifest(manifestContents);\n const renderedRoots = manifest.roots.join(', ');\n const publishableFiles = regoFiles\n .filter(({ path }) => isPublishableRegoFile(path))\n .slice()\n .sort((left, right) => left.path.localeCompare(right.path));\n if (publishableFiles.length === 0) {\n throw new Error('Policy bundle directory must contain at least one .rego policy file.');\n }\n\n const rootPrefixes = manifest.roots.map((root) => root.split('/'));\n const uncovered = publishableFiles.flatMap(({ path, contents }) => {\n const packageReference = parseRegoPackageReference(contents);\n if (\n !packageReference ||\n rootPrefixes.some((prefix) => rootCoversPackage(packageReference, prefix))\n ) {\n return [];\n }\n return [\n ` - ${path} (package ${packageReference.source}) is not covered by roots [${renderedRoots}]`,\n ];\n });\n if (uncovered.length > 0) {\n throw new Error(\n [\n `${POLICY_MANIFEST_FILENAME} \"roots\" do not cover all Rego packages in the bundle; ` +\n 'uncovered packages will fail-closed at decide time. Either broaden \"roots\" or move the policy under a covered package:',\n ...uncovered,\n ].join('\\n'),\n );\n }\n\n const unsupportedReferences = publishableFiles.flatMap(({ path, contents }) =>\n findDirectDataReferences(contents)\n .filter(({ reference }) =>\n rootPrefixes.some((prefix) => referencesDeclaredRoot(reference.segments, prefix)),\n )\n .map(\n ({ reference, line }) =>\n ` - ${path}:${line} references ${reference.source}; import that package and use its local name`,\n ),\n );\n if (unsupportedReferences.length > 0) {\n throw new Error(\n [\n 'Publishable Rego must not reference its declared bundle roots directly because Policy Engine re-namespaces package imports during activation:',\n ...unsupportedReferences,\n ].join('\\n'),\n );\n }\n\n return {\n manifest,\n publishableRegoPaths: publishableFiles.map(({ path }) => path),\n };\n}\n"],"mappings":"0EAWA,MAAM,EAA8B,mBASpC,SAAS,EACP,EACA,EACiD,CACjD,IAAM,EAAQ,2BAA2B,KAAK,EAAO,MAAM,EAAM,CAAC,CAClE,OAAO,EAAQ,CAAE,WAAY,EAAM,GAAI,IAAK,EAAQ,EAAM,GAAG,OAAQ,CAAG,IAAA,GAU1E,SAAS,EAAe,EAAgB,EAAuB,CAC7D,IAAI,EAAU,EACd,KAAO,EAAU,EAAO,QAAU,MAAM,KAAK,EAAO,GAAU,EAC5D,GAAW,EAEb,OAAO,EAUT,SAAS,EACP,EACA,EAC4C,CAC5C,GAAI,EAAO,KAAW,IAAK,CACzB,IAAM,EAAe,EAAO,QAAQ,I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K,cAAc,EAAU,OAAO,8CACtD,CACJ,CACD,GAAI,EAAsB,OAAS,EACjC,MAAU,MACR,CACE,gJACA,GAAG,EACJ,CAAC,KAAK;EAAK,CACb,CAGH,MAAO,CACL,WACA,qBAAsB,EAAiB,KAAK,CAAE,UAAW,EAAK,CAC/D"}
1
+ {"version":3,"file":"policy-bundle-manifest-DW3Wilp8.mjs","names":[],"sources":["../src/lib/policy/rego-reference.ts","../src/lib/policy/policy-bundle-manifest.ts"],"sourcesContent":["/** Parsed static Rego reference. */\ninterface StaticRegoReference {\n /** Source representation of the reference. */\n source: string;\n /** Logical document path segments. */\n segments: string[];\n /** Offset immediately after the reference. */\n end: number;\n}\n\n/** Matches the beginning of a Rego package declaration. */\nconst PACKAGE_DECLARATION_PATTERN = /^\\s*package\\s+/mu;\n\n/**\n * Read an identifier at a source offset.\n *\n * @param source - Rego source\n * @param start - Candidate identifier offset\n * @returns Identifier and following offset\n */\nfunction readIdentifier(\n source: string,\n start: number,\n): { identifier: string; end: number } | undefined {\n const match = /^[A-Za-z_][A-Za-z0-9_]*/u.exec(source.slice(start));\n return match ? { identifier: match[0], end: start + match[0].length } : undefined;\n}\n\n/**\n * Advance past Rego whitespace.\n *\n * @param source - Rego source\n * @param start - Initial source offset\n * @returns First non-whitespace offset\n */\nfunction skipWhitespace(source: string, start: number): number {\n let current = start;\n while (current < source.length && /\\s/u.test(source[current]!)) {\n current += 1;\n }\n return current;\n}\n\n/**\n * Read a quoted or raw Rego string.\n *\n * @param source - Rego source\n * @param start - Opening quote offset\n * @returns Decoded string and following offset\n */\nfunction readQuotedString(\n source: string,\n start: number,\n): { value: string; end: number } | undefined {\n if (source[start] === '`') {\n const closingQuote = source.indexOf('`', start + 1);\n return closingQuote === -1\n ? undefined\n : { value: source.slice(start + 1, closingQuote), end: closingQuote + 1 };\n }\n if (source[start] !== '\"') {\n return undefined;\n }\n let current = start + 1;\n while (current < source.length) {\n if (source[current] === '\\\\') {\n current += 2;\n continue;\n }\n if (source[current] === '\"') {\n const raw = source.slice(start, current + 1);\n try {\n return { value: JSON.parse(raw) as string, end: current + 1 };\n } catch {\n return undefined;\n }\n }\n current += 1;\n }\n return undefined;\n}\n\n/**\n * Parse a static Rego reference with dotted or quoted bracket segments.\n *\n * @param source - Rego source\n * @param start - First identifier offset\n * @returns Parsed reference\n */\nfunction parseStaticRegoReference(source: string, start: number): StaticRegoReference | undefined {\n const first = readIdentifier(source, start);\n if (!first) {\n return undefined;\n }\n const segments = [first.identifier];\n let current = first.end;\n while (current < source.length) {\n const separator = skipWhitespace(source, current);\n if (source[separator] === '.') {\n const identifierStart = skipWhitespace(source, separator + 1);\n const identifier = readIdentifier(source, identifierStart);\n if (!identifier) {\n break;\n }\n segments.push(identifier.identifier);\n current = identifier.end;\n continue;\n }\n if (source[separator] === '[') {\n const stringStart = skipWhitespace(source, separator + 1);\n const value = readQuotedString(source, stringStart);\n if (!value) {\n break;\n }\n const closingBracket = skipWhitespace(source, value.end);\n if (source[closingBracket] !== ']') {\n break;\n }\n segments.push(value.value);\n current = closingBracket + 1;\n continue;\n }\n break;\n }\n return {\n source: source.slice(start, current),\n segments,\n end: current,\n };\n}\n\n/**\n * Read the package reference declared by Rego source.\n *\n * @param contents - Rego source\n * @returns Package reference, or undefined when no declaration is present\n */\nexport function parseRegoPackageReference(\n contents: string,\n): Omit<StaticRegoReference, 'end'> | undefined {\n const declaration = PACKAGE_DECLARATION_PATTERN.exec(contents);\n if (!declaration) {\n return undefined;\n }\n const reference = parseStaticRegoReference(contents, declaration.index + declaration[0].length);\n return reference ? { source: reference.source, segments: reference.segments } : undefined;\n}\n\n/**\n * Skip a string literal while scanning executable Rego source.\n *\n * @param source - Rego source\n * @param start - Opening delimiter offset\n * @returns Offset immediately after the string\n */\nfunction skipStringLiteral(source: string, start: number): number {\n const delimiter = source[start]!;\n let current = start + 1;\n while (current < source.length) {\n if (delimiter === '\"' && source[current] === '\\\\') {\n current += 2;\n continue;\n }\n if (source[current] === delimiter) {\n return current + 1;\n }\n current += 1;\n }\n return current;\n}\n\n/**\n * Find executable static `data` references outside imports.\n *\n * @param contents - Rego source\n * @returns References with one-based source lines\n */\nexport function findDirectDataReferences(\n contents: string,\n): { reference: StaticRegoReference; line: number }[] {\n const references: { reference: StaticRegoReference; line: number }[] = [];\n let current = 0;\n while (current < contents.length) {\n if (contents[current] === '#') {\n const newline = contents.indexOf('\\n', current);\n current = newline === -1 ? contents.length : newline + 1;\n continue;\n }\n if (contents[current] === '\"' || contents[current] === '`') {\n current = skipStringLiteral(contents, current);\n continue;\n }\n const identifier = readIdentifier(contents, current);\n if (!identifier) {\n current += 1;\n continue;\n }\n if (identifier.identifier !== 'data') {\n current = identifier.end;\n continue;\n }\n const reference = parseStaticRegoReference(contents, current);\n if (!reference || reference.segments.length === 1) {\n current = identifier.end;\n continue;\n }\n const lineStart = contents.lastIndexOf('\\n', current - 1) + 1;\n if (!/^\\s*import\\s+$/u.test(contents.slice(lineStart, current))) {\n references.push({\n reference,\n line: contents.slice(0, current).split('\\n').length,\n });\n }\n current = reference.end;\n }\n return references;\n}\n","import {\n POLICY_MANIFEST_FILENAME,\n POLICY_MANIFEST_TRANSCEND_METADATA_KEY,\n POLICY_TEMPLATE_NAMES,\n type PolicyTemplateName,\n} from './policy-scaffold-templates.js';\nimport { findDirectDataReferences, parseRegoPackageReference } from './rego-reference.js';\n\n/** Shape of the policy bundle `.manifest` accepted by Policy Engine. */\nexport interface PolicyBundleManifest {\n /** Roots of the bundle, such as `policy_engine/transcend`. */\n roots: string[];\n /**\n * Optional scaffold template from `metadata.transcend.io.template`.\n *\n * Authoring hint only — upload does not branch on it. Permissions API\n * still keys off the remote bundle name `permissions`.\n */\n template?: PolicyTemplateName;\n}\n\n/** In-memory Rego file used to validate a policy bundle. */\nexport interface PolicyBundleRegoFile {\n /** POSIX-style path relative to the policy bundle directory. */\n path: string;\n /** Rego source contents. */\n contents: string;\n}\n\n/** Validated publishable policy bundle contents. */\nexport interface ValidatedPolicyBundleContents {\n /** Parsed and validated bundle manifest. */\n manifest: PolicyBundleManifest;\n /** Publishable Rego paths, excluding local test modules. */\n publishableRegoPaths: string[];\n}\n\n/**\n * Returns whether a relative path is a publishable Rego policy file.\n *\n * OPA test files (`*_test.rego`) are local-only and excluded from uploads.\n *\n * @param relativePath - Path relative to the bundle directory\n * @returns Whether the file belongs in the uploaded archive\n */\nexport function isPublishableRegoFile(relativePath: string): boolean {\n return relativePath.endsWith('.rego') && !relativePath.endsWith('_test.rego');\n}\n\n/**\n * Parse and validate the Policy Engine bundle manifest.\n *\n * @param contents - Raw manifest contents, or undefined when absent\n * @returns Parsed manifest\n */\nexport function parsePolicyBundleManifest(contents: string | undefined): PolicyBundleManifest {\n if (contents === undefined) {\n throw new Error(`Policy bundle directory must contain a ${POLICY_MANIFEST_FILENAME} file.`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(contents);\n } catch (error) {\n throw new Error(\n `${POLICY_MANIFEST_FILENAME} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${POLICY_MANIFEST_FILENAME} must contain a JSON object.`);\n }\n\n const roots = (parsed as { roots?: unknown }).roots;\n if (!Array.isArray(roots) || roots.length === 0) {\n throw new Error(\n `${POLICY_MANIFEST_FILENAME} must declare \"roots\" as a non-empty array of strings (e.g. {\"roots\":[\"policy_engine\"]}).`,\n );\n }\n if (!roots.every((root) => typeof root === 'string' && root.length > 0)) {\n throw new Error(`${POLICY_MANIFEST_FILENAME} \"roots\" must be an array of non-empty strings.`);\n }\n if (\n !roots.every((root) =>\n root.split('/').every((segment: string) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(segment)),\n )\n ) {\n throw new Error(\n `${POLICY_MANIFEST_FILENAME} \"roots\" must contain slash-separated Rego identifiers so Policy Engine can re-namespace them safely.`,\n );\n }\n\n const template = parseOptionalManifestTemplate(parsed);\n\n return template === undefined ? { roots } : { roots, template };\n}\n\n/**\n * Read an optional `metadata.transcend.io.template` authoring hint.\n *\n * Invalid or unknown values are ignored so upload validation stays focused on\n * roots and Rego coverage.\n *\n * @param parsed - Parsed `.manifest` object\n * @returns Known template name, or undefined\n */\nfunction parseOptionalManifestTemplate(parsed: object): PolicyTemplateName | undefined {\n const metadata = (parsed as { metadata?: unknown }).metadata;\n if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {\n return undefined;\n }\n const transcend = (metadata as Record<string, unknown>)[POLICY_MANIFEST_TRANSCEND_METADATA_KEY];\n if (!transcend || typeof transcend !== 'object' || Array.isArray(transcend)) {\n return undefined;\n }\n const template = (transcend as { template?: unknown }).template;\n if (typeof template !== 'string') {\n return undefined;\n }\n return POLICY_TEMPLATE_NAMES.includes(template as PolicyTemplateName)\n ? (template as PolicyTemplateName)\n : undefined;\n}\n\n/**\n * Determine whether one document path starts with another.\n *\n * @param segments - Complete document path\n * @param prefix - Candidate root\n * @returns Whether the root covers the document path\n */\nfunction hasSegmentPrefix(segments: readonly string[], prefix: readonly string[]): boolean {\n return (\n segments.length >= prefix.length &&\n prefix.every((segment, index) => segment === segments[index])\n );\n}\n\n/**\n * Match the package syntax supported by Policy Engine activation.\n *\n * Bracketed segments remain supported below a declared dotted root.\n *\n * @param reference - Parsed package reference\n * @param root - Declared manifest root\n * @returns Whether activation can re-namespace the package\n */\nfunction rootCoversPackage(reference: { source: string }, root: readonly string[]): boolean {\n const dottedRoot = root.join('.');\n const suffix = reference.source.slice(dottedRoot.length);\n return (\n reference.source.startsWith(dottedRoot) &&\n (suffix === '' || suffix.startsWith('.') || /^\\s*\\[/u.test(suffix))\n );\n}\n\n/**\n * Determine whether `data.<root>` is referenced directly.\n *\n * @param segments - Parsed `data` reference segments\n * @param root - Declared manifest root\n * @returns Whether the reference targets the declared root\n */\nfunction referencesDeclaredRoot(segments: readonly string[], root: readonly string[]): boolean {\n return hasSegmentPrefix(segments.slice(1), root);\n}\n\n/**\n * Validate the manifest, publishable file requirement, and root coverage.\n *\n * This is the shared pure upload contract used by both `policy check` and\n * `policy publish`.\n *\n * @param manifestContents - Raw manifest contents, or undefined when absent\n * @param regoFiles - All Rego files in the policy directory\n * @returns Validated manifest and publishable paths\n */\nexport function validatePolicyBundleContents(\n manifestContents: string | undefined,\n regoFiles: readonly PolicyBundleRegoFile[],\n): ValidatedPolicyBundleContents {\n const manifest = parsePolicyBundleManifest(manifestContents);\n const renderedRoots = manifest.roots.join(', ');\n const publishableFiles = regoFiles\n .filter(({ path }) => isPublishableRegoFile(path))\n .slice()\n .sort((left, right) => left.path.localeCompare(right.path));\n if (publishableFiles.length === 0) {\n throw new Error('Policy bundle directory must contain at least one .rego policy file.');\n }\n\n const rootPrefixes = manifest.roots.map((root) => root.split('/'));\n const uncovered = publishableFiles.flatMap(({ path, contents }) => {\n const packageReference = parseRegoPackageReference(contents);\n if (\n !packageReference ||\n rootPrefixes.some((prefix) => rootCoversPackage(packageReference, prefix))\n ) {\n return [];\n }\n return [\n ` - ${path} (package ${packageReference.source}) is not covered by roots [${renderedRoots}]`,\n ];\n });\n if (uncovered.length > 0) {\n throw new Error(\n [\n `${POLICY_MANIFEST_FILENAME} \"roots\" do not cover all Rego packages in the bundle; ` +\n 'uncovered packages will fail-closed at decide time. Either broaden \"roots\" or move the policy under a covered package:',\n ...uncovered,\n ].join('\\n'),\n );\n }\n\n const unsupportedReferences = publishableFiles.flatMap(({ path, contents }) =>\n findDirectDataReferences(contents)\n .filter(({ reference }) =>\n rootPrefixes.some((prefix) => referencesDeclaredRoot(reference.segments, prefix)),\n )\n .map(\n ({ reference, line }) =>\n ` - ${path}:${line} references ${reference.source}; import that package and use its local name`,\n ),\n );\n if (unsupportedReferences.length > 0) {\n throw new Error(\n [\n 'Publishable Rego must not reference its declared bundle roots directly because Policy Engine re-namespaces package imports during activation:',\n ...unsupportedReferences,\n ].join('\\n'),\n );\n }\n\n return {\n manifest,\n publishableRegoPaths: publishableFiles.map(({ path }) => path),\n };\n}\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,GACD,EAAa,KAAM,GAAW,EAAkB,EAAkB,EAAO,CAAC,CAEnE,EAAE,CAEJ,CACL,OAAO,EAAK,YAAY,EAAiB,OAAO,6BAA6B,EAAc,GAC5F,EACD,CACF,GAAI,EAAU,OAAS,EACrB,MAAU,MACR,CACE,GAAG,EAAyB,+KAE5B,GAAG,EACJ,CAAC,KAAK;EAAK,CACb,CAGH,IAAM,EAAwB,EAAiB,SAAS,CAAE,OAAM,cAC9D,EAAyB,EAAS,CAC/B,QAAQ,CAAE,eACT,EAAa,KAAM,GAAW,EAAuB,EAAU,SAAU,EAAO,CAAC,CAClF,CACA,KACE,CAAE,YAAW,UACZ,OAAO,EAAK,GAAG,EAAK,cAAc,EAAU,OAAO,8CACtD,CACJ,CACD,GAAI,EAAsB,OAAS,EACjC,MAAU,MACR,CACE,gJACA,GAAG,EACJ,CAAC,KAAK;EAAK,CACb,CAGH,MAAO,CACL,WACA,qBAAsB,EAAiB,KAAK,CAAE,UAAW,EAAK,CAC/D"}
@@ -1,4 +1,4 @@
1
- import{g as e}from"./constants-FDjw7bPS.mjs";import{n as t,r as n}from"./project-discovery-CWRjlFnC.mjs";import{join as r,resolve as i}from"node:path";import a from"js-yaml";var o=`https://raw.githubusercontent.com/transcend-io/tools/main/packages/cli/schema/permissions-policy-input.json`,s=[{preferences:[{name:`Analytics`,choice:!0,days_since_choice:42},{name:`SaleOfInfo`,choice:null}],context:{region:`US-CA`}}],c={$schema:`http://json-schema.org/draft-07/schema#`,$id:o,title:`Permissions API policy input`,description:"JSON document Sombra posts as `{ input }` when evaluating a Permissions policy bundle via the OPA Data API.",type:`object`,additionalProperties:!1,required:[`preferences`,`context`],properties:{preferences:{type:`array`,description:`Purpose preference rows from Preference Store for the current subject.`,items:{type:`object`,additionalProperties:!1,required:[`name`,`choice`],properties:{name:{type:`string`,description:`Purpose slug (for example Analytics or SaleOfInfo).`},choice:{type:[`boolean`,`null`],description:`true when opted in, false when opted out, or null when unset.`},days_since_choice:{type:`integer`,minimum:0,description:`Whole days since the preference was last set. Omitted when no timestamp is available.`}}}},context:{type:`object`,description:`Caller-supplied context for the decision (for example region). Use an empty object when none is provided.`,additionalProperties:!0}},examples:s};const l=o,u=`1.18.2`,d=`example`,f=`${d}-bundle`,p=`input.schema.json`,m=`.manifest`,h=`permissions`,g=`transcend.io`,_={Generic:`generic`,Permissions:`permissions`},v=[_.Generic,_.Permissions];function y(t,n=_.Generic){return`{
1
+ import{g as e}from"./constants-DAx9VK1C.mjs";import{n as t,r as n}from"./project-discovery-CWRjlFnC.mjs";import{join as r,resolve as i}from"node:path";import a from"js-yaml";var o=`https://raw.githubusercontent.com/transcend-io/tools/main/packages/cli/schema/permissions-policy-input.json`,s=[{preferences:[{name:`Analytics`,choice:!0,days_since_choice:42},{name:`SaleOfInfo`,choice:null}],context:{region:`US-CA`}}],c={$schema:`http://json-schema.org/draft-07/schema#`,$id:o,title:`Permissions API policy input`,description:"JSON document Sombra posts as `{ input }` when evaluating a Permissions policy bundle via the OPA Data API.",type:`object`,additionalProperties:!1,required:[`preferences`,`context`],properties:{preferences:{type:`array`,description:`Purpose preference rows from Preference Store for the current subject.`,items:{type:`object`,additionalProperties:!1,required:[`name`,`choice`],properties:{name:{type:`string`,description:`Purpose slug (for example Analytics or SaleOfInfo).`},choice:{type:[`boolean`,`null`],description:`true when opted in, false when opted out, or null when unset.`},days_since_choice:{type:`integer`,minimum:0,description:`Whole days since the preference was last set. Omitted when no timestamp is available.`}}}},context:{type:`object`,description:`Caller-supplied context for the decision (for example region). Use an empty object when none is provided.`,additionalProperties:!0}},examples:s};const l=o,u=`1.18.2`,d=`example`,f=`${d}-bundle`,p=`input.schema.json`,m=`.manifest`,h=`permissions`,g=`transcend.io`,_={Generic:`generic`,Permissions:`permissions`},v=[_.Generic,_.Permissions];function y(t,n=_.Generic){return`{
2
2
  "$schema": "https://openpolicyagent.org/schemas/bundle/v1/manifest.schema.json",
3
3
  "revision": "",
4
4
  "roots": ["${t}"],
@@ -48,7 +48,7 @@ transcend policy new
48
48
  transcend policy init # create the workspace
49
49
  transcend policy new --template generic # add a bundle from a template
50
50
 
51
- transcend policy lint --noInteractive
51
+ transcend policy check --noInteractive
52
52
  transcend policy test
53
53
  transcend policy eval transcend/policy/example-bundle \\
54
54
  --package=data.example.result \\
@@ -56,7 +56,7 @@ transcend policy eval transcend/policy/example-bundle \\
56
56
  \`\`\`
57
57
 
58
58
  \`policy new\` also writes a gitignored \`input.json\` (copy of \`input.example.json\`)
59
- for local Evaluate. \`policy lint\` / \`policy test\` default to every child with a
59
+ for local Evaluate. \`policy check\` / \`policy test\` default to every child with a
60
60
  \`.manifest\` and use bundle-mode \`opa test -b\`, so both input files can coexist
61
61
  without a merge error.
62
62
 
@@ -427,4 +427,4 @@ package ${e}.purposes
427
427
  import rego.v1
428
428
  `,description:`Create the purposes entrypoint`},{path:`${n}/input.example.json`,contents:r,description:`Create a sanitized permissions evaluation input example`},{path:`${n}/input.json`,contents:r,description:`Create a local evaluation input (gitignored copy of the example)`},{path:`${n}/.gitignore`,contents:w,description:`Ignore only the private local input file`}]}function I(e,t,n=A(t)){switch(e){case _.Generic:return M(t,n);case _.Permissions:return F(t,n);default:throw Error(`Unknown policy template: ${String(e)}`)}}function L(e){let{bundleDirectory:t,root:n,template:r}=e,i=r===_.Permissions?`data.${n}.purposes`:`data.${n}.result`;return[`transcend policy eval ${t} \\`,` --package=${i} \\`,` --input=${t}/input.json \\`,` --schema=${t}/${p}`].join(`
429
429
  `)}const R=`transcend/policy`;function z(e,t=R){return i(e,t)}function B(e,t){if(!e.fs.existsSync(t)||!e.fs.statSync(t).isDirectory())return[];let n=r(t,m);return e.fs.existsSync(n)&&e.fs.statSync(n).isFile()?[t]:e.fs.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>r(t,e.name)).filter(t=>{let n=r(t,m);return e.fs.existsSync(n)&&e.fs.statSync(n).isFile()}).sort((e,t)=>e.localeCompare(t))}function V(e,r=R){let i=e.process.cwd(),a=z(i,r);if(e.fs.existsSync(a)&&!e.fs.statSync(a).isDirectory())throw Error(`Policy target is not a directory: ${a}`);return{invocationDirectory:i,targetDirectory:a,...n(e,{invocationDirectory:i,targetDirectory:a,standaloneProjectRoot:i}),relativePaths:t(e,a),relativeFilePaths:t(e,a,{includeDirectories:!1})}}export{j as S,A as _,h as a,D as b,m as c,u as d,d as f,_ as g,O as h,z as i,g as l,v as m,B as n,l as o,k as p,V as r,p as s,R as t,f as u,L as v,x,I as y};
430
- //# sourceMappingURL=policy-project-discovery-DTSl0Gfl.mjs.map
430
+ //# sourceMappingURL=policy-project-discovery-CND7N2HI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-project-discovery-CND7N2HI.mjs","names":["permissionsPolicyInputSchema.$id","CLI_VERSION","permissionsPolicyInputSchema","permissionsPolicyInputSchema.examples"],"sources":["../schema/permissions-policy-input.json","../src/lib/policy/policy-scaffold-templates.ts","../src/lib/policy/policy-project-discovery.ts"],"sourcesContent":["","import yaml from 'js-yaml';\n\nimport permissionsPolicyInputSchema from '../../../schema/permissions-policy-input.json' with { type: 'json' };\nimport { version as CLI_VERSION } from '../../constants.js';\n\n/** Published Permissions API OPA input schema `$id` (raw GitHub URL). */\nexport const PERMISSIONS_POLICY_INPUT_SCHEMA_ID = permissionsPolicyInputSchema.$id;\n\n/** OPA version targeted by generated policy authoring configuration. */\nexport const POLICY_STARTER_OPA_VERSION = '1.18.2';\n\n/**\n * Package-path prefix for the disposable starter bundle.\n *\n * Matches OPA `.manifest` `roots` and Regal `project.roots` (not a filesystem\n * folder name by itself). The default publish directory is `{root}-bundle/`;\n * `policy new --bundle-dir` can override that basename.\n */\nexport const POLICY_STARTER_ROOT = 'example';\n\n/** Publish directory name for the disposable starter (`{root}-bundle`). */\nexport const POLICY_STARTER_BUNDLE_DIRECTORY = `${POLICY_STARTER_ROOT}-bundle`;\n\n/** Input JSON Schema filename written beside each publish directory's fixtures. */\nexport const POLICY_INPUT_SCHEMA_FILENAME = 'input.schema.json';\n\n/** One deterministic file in the safe policy starter. */\nexport interface PolicyStarterFile {\n /** POSIX-style path relative to the policy workspace directory. */\n path: string;\n /** Complete UTF-8 file contents. */\n contents: string;\n /** Human-readable reason shown in the plan. */\n description: string;\n}\n\n/** OPA bundle manifest filename used for local authoring and upload. */\nexport const POLICY_MANIFEST_FILENAME = '.manifest';\n\n/**\n * Remote bundle name reserved for Permissions API.\n *\n * Upload treats every bundle the same; Sombra's Permissions API always queries\n * this fixed name (never taken from the request body).\n */\nexport const PERMISSIONS_POLICY_BUNDLE_NAME = 'permissions';\n\n/** OPA `.manifest` `metadata` key for Transcend authoring hints. */\nexport const POLICY_MANIFEST_TRANSCEND_METADATA_KEY = 'transcend.io';\n\n/** Supported policy bundle templates (enum-style constants). */\nexport const PolicyTemplate = {\n Generic: 'generic',\n Permissions: 'permissions',\n} as const;\n\n/** Supported policy bundle template names. */\nexport const POLICY_TEMPLATE_NAMES = [PolicyTemplate.Generic, PolicyTemplate.Permissions] as const;\n\n/** A supported policy bundle template name. */\nexport type PolicyTemplateName = (typeof PolicyTemplate)[keyof typeof PolicyTemplate];\n\n/**\n * OPA `.manifest` `metadata.transcend.io` key for the CLI version that\n * generated the scaffold template.\n */\nexport const POLICY_MANIFEST_TEMPLATE_VERSION_KEY = 'templateVersion';\n\n/**\n * Build an OPA bundle manifest for a given root and scaffold template.\n *\n * `metadata.transcend.io.template` and `templateVersion` are authoring hints\n * only — Policy Engine upload does not branch on them. Permissions API still\n * keys off the remote bundle name {@link PERMISSIONS_POLICY_BUNDLE_NAME}.\n * `templateVersion` records the `@transcend-io/cli` package version used to\n * generate the scaffold.\n *\n * @param root - Package root\n * @param template - Scaffold template that produced this bundle\n * @returns Manifest JSON\n */\nexport function buildPolicyManifestTemplate(\n root: string,\n template: PolicyTemplateName = PolicyTemplate.Generic,\n): string {\n return `{\n \"$schema\": \"https://openpolicyagent.org/schemas/bundle/v1/manifest.schema.json\",\n \"revision\": \"\",\n \"roots\": [\"${root}\"],\n \"rego_version\": 1,\n \"metadata\": {\n \"${POLICY_MANIFEST_TRANSCEND_METADATA_KEY}\": {\n \"template\": \"${template}\",\n \"${POLICY_MANIFEST_TEMPLATE_VERSION_KEY}\": \"${CLI_VERSION}\"\n }\n }\n}\n`;\n}\n\n/** OPA bundle manifest for the disposable starter publish directory. */\nexport const POLICY_MANIFEST_TEMPLATE = buildPolicyManifestTemplate(\n POLICY_STARTER_ROOT,\n PolicyTemplate.Generic,\n);\n\n/**\n * Build workspace-level Regal configuration for given roots.\n *\n * `project.roots` are package-path prefixes (same meaning as OPA `.manifest`\n * roots), not filesystem folders.\n *\n * @param roots - Package-path roots\n * @returns YAML configuration\n */\nexport function buildPolicyRegalConfigTemplate(roots: readonly string[]): string {\n const rootsSection =\n roots.length === 0\n ? ' roots: []'\n : ` roots:\\n${roots.map((root) => ` - ${root}`).join('\\n')}`;\n return `# Workspace-level Regal config for both publishable bundles under this tree.\n# \\`project.roots\\` are package-path prefixes (same meaning as OPA \\`.manifest\\`\n# roots), not filesystem folders. Each bundle also has its own \\`.manifest\\`.\ncapabilities:\n from:\n engine: opa\n version: v${POLICY_STARTER_OPA_VERSION}\nproject:\n${rootsSection}\n rego-version: 1\n`;\n}\n\n/**\n * Merge one package-path root into an existing Regal config without wiping\n * unrelated keys (custom rules, ignores, etc.).\n *\n * Comments and key order may be reformatted by the YAML serializer. Invalid\n * `project.roots` shapes throw instead of silently dropping prior roots.\n *\n * @param existingContents - Current `.regal/config.yaml` contents\n * @param rootToAdd - Package-path root to include\n * @returns Updated file contents and the full roots list\n */\nexport function mergePolicyRegalConfigRoots(\n existingContents: string,\n rootToAdd: string,\n): { contents: string; roots: string[] } {\n const trimmed = existingContents.trim();\n if (trimmed.length === 0) {\n const roots = [rootToAdd];\n return { contents: buildPolicyRegalConfigTemplate(roots), roots };\n }\n\n let parsed: unknown;\n try {\n parsed = yaml.load(existingContents);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(`.regal/config.yaml is not valid YAML: ${detail}`);\n }\n\n if (parsed === null || parsed === undefined) {\n const roots = [rootToAdd];\n return { contents: buildPolicyRegalConfigTemplate(roots), roots };\n }\n if (typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('.regal/config.yaml must be a YAML mapping at the top level.');\n }\n\n const config = { ...(parsed as Record<string, unknown>) };\n const existingProject = config.project;\n if (\n existingProject !== undefined &&\n existingProject !== null &&\n (typeof existingProject !== 'object' || Array.isArray(existingProject))\n ) {\n throw new Error('.regal/config.yaml project must be a YAML mapping when present.');\n }\n\n const project: Record<string, unknown> = {\n ...((existingProject as Record<string, unknown> | undefined) ?? {}),\n };\n const existingRoots = project.roots;\n let roots: string[];\n if (existingRoots === undefined) {\n roots = [rootToAdd];\n } else if (\n Array.isArray(existingRoots) &&\n existingRoots.every((root): root is string => typeof root === 'string')\n ) {\n roots = [...new Set([...existingRoots, rootToAdd])].sort((left, right) =>\n left.localeCompare(right),\n );\n } else {\n throw new Error(\n '.regal/config.yaml project.roots must be an array of strings. ' +\n 'Fix the Regal config before running `transcend policy new`.',\n );\n }\n\n project.roots = roots;\n if (project['rego-version'] === undefined) {\n project['rego-version'] = 1;\n }\n config.project = project;\n\n if (config.capabilities === undefined) {\n config.capabilities = {\n from: {\n engine: 'opa',\n version: `v${POLICY_STARTER_OPA_VERSION}`,\n },\n };\n }\n\n const dumped = yaml.dump(config, {\n lineWidth: -1,\n noRefs: true,\n sortKeys: false,\n });\n return {\n contents: dumped.endsWith('\\n') ? dumped : `${dumped}\\n`,\n roots,\n };\n}\n\n/**\n * Workspace-level Regal configuration.\n *\n * `project.roots` are package-path prefixes (same meaning as OPA `.manifest`\n * roots), not filesystem folders.\n */\nexport const POLICY_REGAL_CONFIG_TEMPLATE = buildPolicyRegalConfigTemplate([POLICY_STARTER_ROOT]);\n\n/** Regal config for an empty workspace with no bundles yet. */\nexport const POLICY_REGAL_CONFIG_EMPTY_TEMPLATE = buildPolicyRegalConfigTemplate([]);\n\n/** Disposable, fail-closed example policy. */\nexport const POLICY_RESULT_REGO_TEMPLATE = `# METADATA\n# title: Disposable example result\n# description: |\n# A fail-closed teaching entrypoint. Replace this example with the document\n# tree and result contract required by your application.\n# scope: package\n# entrypoint: true\npackage ${POLICY_STARTER_ROOT}.result\n\nimport rego.v1\n\ndefault decision := \"deny\"\n\ndecision := \"allow\" if {\n\tinput.subject.trusted == true\n}\n\ndefault reason_code := \"untrusted_or_invalid_input\"\n\nreason_code := \"trusted_subject\" if {\n\tdecision == \"allow\"\n}\n`;\n\n/** Executable tests adjacent to the disposable example policy. */\nexport const POLICY_RESULT_TEST_REGO_TEMPLATE = `package ${POLICY_STARTER_ROOT}.result_test\n\nimport data.${POLICY_STARTER_ROOT}.result\nimport rego.v1\n\ntest_denies_untrusted_subject if {\n\tresult.decision == \"deny\" with input as {\"subject\": {\"trusted\": false}}\n\tresult.reason_code == \"untrusted_or_invalid_input\" with input as {\"subject\": {\"trusted\": false}}\n}\n\ntest_fails_closed_for_missing_subject if {\n\tresult.decision == \"deny\" with input as {}\n\tresult.reason_code == \"untrusted_or_invalid_input\" with input as {}\n}\n\ntest_allows_trusted_subject if {\n\tresult.decision == \"allow\" with input as {\"subject\": {\"trusted\": true}}\n\tresult.reason_code == \"trusted_subject\" with input as {\"subject\": {\"trusted\": true}}\n}\n`;\n\n/** Sanitized local input example containing no credentials or personal data. */\nexport const POLICY_INPUT_EXAMPLE_TEMPLATE = `{\n \"subject\": {\n \"trusted\": false\n }\n}\n`;\n\n/** Input JSON Schema for the disposable starter (editor + \\`opa check -s\\`). */\nexport const POLICY_INPUT_SCHEMA_TEMPLATE = `{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"https://transcend.io/policy-schemas/${POLICY_STARTER_ROOT}/input.json\",\n \"title\": \"Example policy input\",\n \"description\": \"Disposable teaching envelope for the example bundle.\",\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"properties\": {\n \"subject\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"properties\": {\n \"trusted\": {\n \"type\": \"boolean\",\n \"description\": \"When true, the example policy allows; otherwise it denies.\"\n }\n }\n }\n }\n}\n`;\n\n/** Target-local ignore rules for private evaluation input only. */\nexport const POLICY_GITIGNORE_TEMPLATE = `# Local policy evaluation input (VS Code / Regal look for input.json here).\n/input.json\n`;\n\n/** Concise workspace-local authoring guide (multi-bundle, empty workspace). */\nexport const POLICY_README_TEMPLATE = `# Transcend Policy\n\nMulti-bundle workspace for Transcend Policy Engine bundles\n(OPA / Rego v1). Requires **Transcend CLI ≥ 11** (\\`transcend policy --help\\`\nshould list \\`init\\`, \\`new\\`, and positional \\`[directory]\\` args).\n\nEach \\`*-bundle/\\` directory is a separate publishable unit (own \\`.manifest\\`,\ninput, and query path). Add a new bundle with:\n\n\\`\\`\\`sh\ntranscend policy new\n\\`\\`\\`\n\n## Quick start\n\n\\`\\`\\`sh\ntranscend policy init # create the workspace\ntranscend policy new --template generic # add a bundle from a template\n\ntranscend policy check --noInteractive\ntranscend policy test\ntranscend policy eval transcend/policy/example-bundle \\\\\n --package=data.example.result \\\\\n --input=transcend/policy/example-bundle/input.json\n\\`\\`\\`\n\n\\`policy new\\` also writes a gitignored \\`input.json\\` (copy of \\`input.example.json\\`)\nfor local Evaluate. \\`policy check\\` / \\`policy test\\` default to every child with a\n\\`.manifest\\` and use bundle-mode \\`opa test -b\\`, so both input files can coexist\nwithout a merge error.\n\n## Layout\n\n\\`\\`\\`\ntranscend/policy/\n example-bundle/ # publish directory (added by policy new)\n example/ # package root (matches .manifest roots)\n input.example.json\n input.json # local only (gitignored)\n input.schema.json # input JSON Schema (editor + opa --schema)\n .regal/config.yaml\n\\`\\`\\`\n\nReplace or delete example bundles when you have a real policy. Publish each\nbundle separately (\\`transcend policy publish --remote-bundle-name … <dir>\\`).\n\n## Permissions API\n\nScaffold the Permissions starter, then simulate the query Sombra runs:\n\n\\`\\`\\`sh\ntranscend policy new \\\\\n --template permissions \\\\\n --name ${PERMISSIONS_POLICY_BUNDLE_NAME} \\\\\n --bundle-dir ${PERMISSIONS_POLICY_BUNDLE_NAME}-bundle \\\\\n --yes\n\ntranscend policy eval transcend/policy/${PERMISSIONS_POLICY_BUNDLE_NAME}-bundle \\\\\n --package=data.${PERMISSIONS_POLICY_BUNDLE_NAME}.purposes \\\\\n --input=transcend/policy/${PERMISSIONS_POLICY_BUNDLE_NAME}-bundle/input.json \\\\\n --schema=transcend/policy/${PERMISSIONS_POLICY_BUNDLE_NAME}-bundle/input.schema.json\n\\`\\`\\`\n\nUpload does **not** distinguish bundle kinds. What makes a bundle “Permissions”\nis the remote name plus where Sombra queries it:\n\n- **Permissions API** always loads the fixed remote bundle name\n \\`${PERMISSIONS_POLICY_BUNDLE_NAME}\\`. Publish that starter with\n \\`--remote-bundle-name=${PERMISSIONS_POLICY_BUNDLE_NAME}\\`.\n- **Generic / decide** bundles use any other \\`--remote-bundle-name\\` and the decide\n path.\n\nScaffolded \\`.manifest\\` files may include \\`metadata.transcend.io.template\\`\n(\\`generic\\` or \\`permissions\\`) and \\`templateVersion\\` (the \\`@transcend-io/cli\\`\nversion that generated the scaffold) as authoring hints. Upload ignores them;\n\\`policy publish\\` may warn when the template hint and \\`--remote-bundle-name\\` disagree.\n`;\n\n/** Workspace-relative path to the disposable example entrypoint. */\nexport const POLICY_STARTER_RESULT_REGO_PATH = `${POLICY_STARTER_BUNDLE_DIRECTORY}/${POLICY_STARTER_ROOT}/result/result.rego`;\n\n/** Workspace-relative path to the disposable example tests. */\nexport const POLICY_STARTER_RESULT_TEST_REGO_PATH = `${POLICY_STARTER_BUNDLE_DIRECTORY}/${POLICY_STARTER_ROOT}/result/result_test.rego`;\n\n/** Complete safe starter in deterministic plan order. */\nconst POLICY_STARTER_FILES: readonly PolicyStarterFile[] = [\n {\n path: `${POLICY_STARTER_BUNDLE_DIRECTORY}/${POLICY_MANIFEST_FILENAME}`,\n contents: POLICY_MANIFEST_TEMPLATE,\n description: 'Create the OPA bundle .manifest',\n },\n {\n path: '.regal/config.yaml',\n contents: POLICY_REGAL_CONFIG_TEMPLATE,\n description: `Pin strict Rego v1 linting to OPA ${POLICY_STARTER_OPA_VERSION} capabilities`,\n },\n {\n path: `${POLICY_STARTER_BUNDLE_DIRECTORY}/${POLICY_INPUT_SCHEMA_FILENAME}`,\n contents: POLICY_INPUT_SCHEMA_TEMPLATE,\n description: 'Create the input JSON Schema for the example bundle',\n },\n {\n path: POLICY_STARTER_RESULT_REGO_PATH,\n contents: POLICY_RESULT_REGO_TEMPLATE,\n description: 'Create a documented fail-closed result entrypoint',\n },\n {\n path: POLICY_STARTER_RESULT_TEST_REGO_PATH,\n contents: POLICY_RESULT_TEST_REGO_TEMPLATE,\n description: 'Create executable tests for allow and fail-closed decisions',\n },\n {\n path: `${POLICY_STARTER_BUNDLE_DIRECTORY}/input.example.json`,\n contents: POLICY_INPUT_EXAMPLE_TEMPLATE,\n description: 'Create a sanitized local evaluation input',\n },\n {\n path: `${POLICY_STARTER_BUNDLE_DIRECTORY}/.gitignore`,\n contents: POLICY_GITIGNORE_TEMPLATE,\n description: 'Ignore only the private local input file',\n },\n {\n path: 'README.md',\n contents: POLICY_README_TEMPLATE,\n description: 'Create the concise policy project guide',\n },\n];\n\n/**\n * Generate an independent copy of the safe policy starter.\n *\n * @returns Deterministic relative files\n */\nexport function generatePolicyStarterFiles(): PolicyStarterFile[] {\n return POLICY_STARTER_FILES.map((file) => ({ ...file }));\n}\n\n// ---------------------------------------------------------------------------\n// Workspace-only init files (no bundles)\n// ---------------------------------------------------------------------------\n\n/** Files created by `policy init` — empty workspace only. */\nconst POLICY_INIT_WORKSPACE_FILES: readonly PolicyStarterFile[] = [\n {\n path: '.regal/config.yaml',\n contents: POLICY_REGAL_CONFIG_EMPTY_TEMPLATE,\n description: `Pin strict Rego v1 linting to OPA ${POLICY_STARTER_OPA_VERSION} capabilities`,\n },\n {\n path: 'README.md',\n contents: POLICY_README_TEMPLATE,\n description: 'Create the concise multi-bundle workspace guide',\n },\n];\n\n/**\n * Generate files for an empty workspace (init without bundles).\n *\n * @returns Deterministic workspace files\n */\nexport function generatePolicyWorkspaceFiles(): PolicyStarterFile[] {\n return POLICY_INIT_WORKSPACE_FILES.map((file) => ({ ...file }));\n}\n\n// ---------------------------------------------------------------------------\n// Policy bundle templates (used by `policy new`)\n// ---------------------------------------------------------------------------\n\n/** Interactive labels for each policy template. */\nexport const POLICY_TEMPLATE_PROMPT_LABELS: Record<PolicyTemplateName, string> = {\n [PolicyTemplate.Generic]: 'Generic example',\n [PolicyTemplate.Permissions]: 'Permission API starter',\n};\n\n/** Default root names for each template. */\nexport const POLICY_TEMPLATE_DEFAULT_ROOTS: Record<PolicyTemplateName, string> = {\n [PolicyTemplate.Generic]: 'example',\n [PolicyTemplate.Permissions]: PERMISSIONS_POLICY_BUNDLE_NAME,\n};\n\n/**\n * Build the bundle directory name from a root.\n *\n * @param root - Package root\n * @returns Bundle directory name\n */\nexport function buildBundleDirectoryName(root: string): string {\n return `${root}-bundle`;\n}\n\n/**\n * Validate a local bundle directory basename (under the policy workspace).\n *\n * @param value - Proposed directory basename\n * @returns True or error message\n */\nexport function validateBundleDirectoryName(value: string): true | string {\n if (!value) {\n return 'Enter a bundle directory name.';\n }\n if (value === '.' || value === '..' || value.includes('/') || value.includes('\\\\')) {\n return 'Bundle directory must be a single path segment (no slashes).';\n }\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(value)) {\n return 'Bundle directory must be alphanumeric (plus ., _, -), e.g. \"my-bundle\".';\n }\n if (value.length > 128) {\n return 'Bundle directory cannot exceed 128 characters.';\n }\n return true;\n}\n\n/**\n * Generate bundle files for the generic template.\n *\n * @param root - Package root name\n * @param bundleDir - Publish directory basename under the workspace\n * @returns Bundle files relative to the workspace\n */\nexport function generateGenericBundleFiles(\n root: string,\n bundleDir: string = buildBundleDirectoryName(root),\n): PolicyStarterFile[] {\n const bundle = bundleDir;\n return [\n {\n path: `${bundle}/${POLICY_MANIFEST_FILENAME}`,\n contents: buildPolicyManifestTemplate(root, PolicyTemplate.Generic),\n description: 'Create the OPA bundle .manifest',\n },\n {\n path: `${bundle}/${POLICY_INPUT_SCHEMA_FILENAME}`,\n contents: `{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"https://transcend.io/policy-schemas/${root}/input.json\",\n \"title\": \"${root === 'example' ? 'Example policy input' : `${root} policy input`}\",\n \"description\": \"${root === 'example' ? 'Disposable teaching envelope for the example bundle.' : `Input envelope for the ${root} bundle.`}\",\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"properties\": {\n \"subject\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"properties\": {\n \"trusted\": {\n \"type\": \"boolean\",\n \"description\": \"When true, the ${root === 'example' ? 'example' : root} policy allows; otherwise it denies.\"\n }\n }\n }\n }\n}\n`,\n description: `Create the input JSON Schema for the ${root} bundle`,\n },\n {\n path: `${bundle}/${root}/result/result.rego`,\n contents: `# METADATA\n# title: ${root === 'example' ? 'Disposable example result' : `${root} result`}\n# description: |\n# A fail-closed ${root === 'example' ? 'teaching ' : ''}entrypoint. Replace this ${root === 'example' ? 'example ' : ''}with the document\n# tree and result contract required by your application.\n# scope: package\n# entrypoint: true\npackage ${root}.result\n\nimport rego.v1\n\ndefault decision := \"deny\"\n\ndecision := \"allow\" if {\n\\tinput.subject.trusted == true\n}\n\ndefault reason_code := \"untrusted_or_invalid_input\"\n\nreason_code := \"trusted_subject\" if {\n\\tdecision == \"allow\"\n}\n`,\n description: 'Create a documented fail-closed result entrypoint',\n },\n {\n path: `${bundle}/${root}/result/result_test.rego`,\n contents: `package ${root}.result_test\n\nimport data.${root}.result\nimport rego.v1\n\ntest_denies_untrusted_subject if {\n\\tresult.decision == \"deny\" with input as {\"subject\": {\"trusted\": false}}\n\\tresult.reason_code == \"untrusted_or_invalid_input\" with input as {\"subject\": {\"trusted\": false}}\n}\n\ntest_fails_closed_for_missing_subject if {\n\\tresult.decision == \"deny\" with input as {}\n\\tresult.reason_code == \"untrusted_or_invalid_input\" with input as {}\n}\n\ntest_allows_trusted_subject if {\n\\tresult.decision == \"allow\" with input as {\"subject\": {\"trusted\": true}}\n\\tresult.reason_code == \"trusted_subject\" with input as {\"subject\": {\"trusted\": true}}\n}\n`,\n description: 'Create executable tests for allow and fail-closed decisions',\n },\n {\n path: `${bundle}/input.example.json`,\n contents: POLICY_INPUT_EXAMPLE_TEMPLATE,\n description: 'Create a sanitized local evaluation input example',\n },\n {\n path: `${bundle}/input.json`,\n contents: POLICY_INPUT_EXAMPLE_TEMPLATE,\n description: 'Create a local evaluation input (gitignored copy of the example)',\n },\n {\n path: `${bundle}/.gitignore`,\n contents: POLICY_GITIGNORE_TEMPLATE,\n description: 'Ignore only the private local input file',\n },\n ];\n}\n\n/**\n * Generate bundle files for the permissions template.\n *\n * @param root - Package root name\n * @returns Bundle files relative to the workspace\n */\n/**\n * Serialize the published Permissions input schema for the local bundle path.\n *\n * Written as `{bundle}/input.schema.json` so editors and `opa --schema` can\n * type-check the envelope offline without a workspace `schemas/` directory.\n *\n * @returns Schema file contents ending in a trailing newline\n */\nexport function buildPermissionsInputSchemaContents(): string {\n return `${JSON.stringify(permissionsPolicyInputSchema, null, 2)}\\n`;\n}\n\n/**\n * Serialize the published Permissions input example for local evaluation.\n *\n * @returns Example input JSON ending in a trailing newline\n */\nexport function buildPermissionsInputExampleContents(): string {\n const [example] = permissionsPolicyInputSchema.examples;\n if (!example) {\n throw new Error('permissions-policy-input.json must declare at least one example');\n }\n return `${JSON.stringify(example, null, 2)}\\n`;\n}\n\n/**\n * Generate bundle files for the permissions template.\n *\n * @param root - Package root name\n * @param bundleDir - Publish directory basename under the workspace\n * @returns Bundle files relative to the workspace\n */\nexport function generatePermissionsBundleFiles(\n root: string,\n bundleDir: string = buildBundleDirectoryName(root),\n): PolicyStarterFile[] {\n const bundle = bundleDir;\n const inputExample = buildPermissionsInputExampleContents();\n return [\n {\n path: `${bundle}/${POLICY_MANIFEST_FILENAME}`,\n contents: buildPolicyManifestTemplate(root, PolicyTemplate.Permissions),\n description: 'Create the OPA bundle .manifest',\n },\n {\n path: `${bundle}/${POLICY_INPUT_SCHEMA_FILENAME}`,\n contents: buildPermissionsInputSchemaContents(),\n description: `Create the input JSON Schema for the ${root} bundle (from published permissions-policy-input.json)`,\n },\n {\n path: `${bundle}/${root}/config/config.rego`,\n contents: `# METADATA\n# title: Permissions config\n# description: |\n# Static bundle configuration. Values come from data.json in this directory.\npackage ${root}.config\n\nimport rego.v1\n`,\n description: 'Create the static bundle configuration package',\n },\n {\n path: `${bundle}/${root}/config/data.json`,\n contents: `{\n \"default_consent_allowed\": true,\n \"purposes\": [\n \"Analytics\",\n \"SaleOfInfo\"\n ],\n \"default_consent\": {}\n}\n`,\n description: 'Create the static purpose configuration data',\n },\n {\n path: `${bundle}/${root}/helpers/preference/preference.rego`,\n contents: `# METADATA\n# title: Purpose preference resolution\n# description: |\n# Resolves the subject's recorded choice for one purpose from the OPA\n# \\`input.preferences\\` array Sombra injects (one \\`{name, choice,\n# days_since_choice?}\\` entry per purpose; \\`choice\\` may be null when unset).\npackage ${root}.helpers.preference\n\nimport rego.v1\n\nimport data.${root}.config\n\nraw_preferences := object.get(input, \"preferences\", [])\n\nsource_available if {\n\\tis_array(raw_preferences)\n\\tevery entry in raw_preferences {\n\\t\\tis_object(entry)\n\\t\\tis_string(entry.name)\n\\t\\tentry.name != \"\"\n\\t}\n}\n\n# Boolean choice for a purpose, last-wins across duplicate entries (matching\n# Sombra's own dedup semantics). Returns the boolean only when a usable choice\n# exists; otherwise the rule is undefined and the purpose is undecided.\nchoice(name) := choice if {\n\\tsource_available\n\\tmatching := [entry | some entry in raw_preferences; entry.name == name]\n\\tcount(matching) > 0\n\\tlast := matching[count(matching) - 1]\n\\tchoice := object.get(last, \"choice\", null)\n\\tis_boolean(choice)\n}\n\nenabled(name) if choice(name) == true\n\ndisabled(name) if choice(name) == false\n\ndecided(name) if enabled(name)\n\ndecided(name) if disabled(name)\n\n# A configured purpose with no usable boolean choice is undecided: the subject\n# never chose, so the resolved default applies (not an opt-out).\nundecided(name) if {\n\\tname in config.purposes\n\\tnot enabled(name)\n\\tnot disabled(name)\n}\n`,\n description: 'Create purpose preference resolution helpers',\n },\n {\n path: `${bundle}/${root}/helpers/preference/preference_test.rego`,\n contents: `# Mechanical tests for purpose preference resolution.\n# Policy outcomes are tested beside the public entrypoint.\npackage ${root}.helpers.preference_test\n\nimport rego.v1\n\nimport data.${root}.helpers.preference\n\ngiven(preferences) := {\"preferences\": preferences}\n\ntest_treats_an_absent_preferences_array_as_no_recorded_choices if {\n\\tfixture := {}\n\n\\tpreference.source_available with input as fixture\n\\tpreference.undecided(\"Analytics\") with input as fixture\n}\n\ntest_accepts_an_empty_preferences_array if {\n\\tfixture := given([])\n\n\\tpreference.source_available with input as fixture\n\\tpreference.undecided(\"Analytics\") with input as fixture\n}\n\ntest_reports_a_non_array_preferences_as_unavailable if {\n\\tnot preference.source_available with input as {\"preferences\": {\"Analytics\": true}}\n}\n\ntest_reports_entries_without_a_usable_name_as_unavailable if {\n\\tnot preference.source_available with input as {\"preferences\": [{}]}\n\\tnot preference.source_available with input as {\"preferences\": [{\"name\": \"\"}]}\n\\tnot preference.source_available with input as {\"preferences\": [{\"choice\": true}]}\n}\n\ntest_distinguishes_enabled_and_disabled_choices if {\n\\tfixture := given([\n\\t\\t{\"name\": \"Analytics\", \"choice\": true},\n\\t\\t{\"name\": \"SaleOfInfo\", \"choice\": false},\n\\t])\n\n\\tpreference.enabled(\"Analytics\") with input as fixture\n\\tpreference.disabled(\"SaleOfInfo\") with input as fixture\n\\tpreference.decided(\"Analytics\") with input as fixture\n\\tpreference.decided(\"SaleOfInfo\") with input as fixture\n\\tnot preference.undecided(\"Analytics\") with input as fixture\n}\n\ntest_treats_a_null_choice_as_undecided if {\n\\tfixture := given([{\"name\": \"Analytics\", \"choice\": null}])\n\n\\tpreference.undecided(\"Analytics\") with input as fixture\n\\tnot preference.decided(\"Analytics\") with input as fixture\n}\n\ntest_treats_an_absent_choice_key_as_undecided if {\n\\tfixture := given([{\"name\": \"Analytics\", \"channel\": \"email\"}])\n\n\\tpreference.undecided(\"Analytics\") with input as fixture\n}\n\ntest_treats_a_non_boolean_choice_as_undecided if {\n\\tfixture := given([{\"name\": \"SaleOfInfo\", \"choice\": \"Daily\"}])\n\n\\tpreference.undecided(\"SaleOfInfo\") with input as fixture\n\\tnot preference.decided(\"SaleOfInfo\") with input as fixture\n}\n\n# Sombra dedupes by purpose before sending; last-wins keeps the bundle correct\n# against hand-crafted input that names the same purpose twice.\ntest_last_wins_on_duplicate_entries if {\n\\tfixture := given([\n\\t\\t{\"name\": \"SaleOfInfo\", \"choice\": true},\n\\t\\t{\"name\": \"SaleOfInfo\", \"choice\": false},\n\\t])\n\n\\tpreference.disabled(\"SaleOfInfo\") with input as fixture\n\\tnot preference.enabled(\"SaleOfInfo\") with input as fixture\n}\n\n# Extra fields on an entry (evidence, days_since_choice, channel) are ignored\n# rather than treated as a choice.\ntest_ignores_fields_beyond_the_recorded_choice if {\n\\tfixture := given([{\n\\t\\t\"name\": \"Analytics\",\n\\t\\t\"choice\": true,\n\\t\\t\"evidence\": \"consent_banner\",\n\\t\\t\"days_since_choice\": 45,\n\\t\\t\"channel\": \"email\",\n\\t}])\n\n\\tpreference.enabled(\"Analytics\") with input as fixture\n}\n`,\n description: 'Create preference resolution tests',\n },\n {\n path: `${bundle}/${root}/purposes/analytics/analytics.rego`,\n contents: `# METADATA\n# title: Analytics purpose decision\n# description: |\n# The Analytics purpose's verdict as a \\`result\\` document\n# (\\`data.${root}.purposes.analytics.result\\`).\npackage ${root}.purposes.analytics\n\nimport rego.v1\n\nimport data.${root}.helpers.preference\n\ndefault result := {\n\\t\"decision\": \"deny\",\n\\t\"reason_code\": \"default_deny\",\n}\n\nresult := {\n\\t\"decision\": \"allow\",\n\\t\"reason_code\": \"explicit_allow\",\n} if {\n\\tpreference.enabled(\"Analytics\")\n}\n\nresult := {\n\\t\"decision\": \"deny\",\n\\t\"reason_code\": \"explicit_deny\",\n} if {\n\\tpreference.disabled(\"Analytics\")\n}\n\nresult := {\n\\t\"decision\": \"allow\",\n\\t\"reason_code\": \"default_allow\",\n} if {\n\\tpreference.undecided(\"Analytics\")\n}\n`,\n description: 'Create the analytics purpose decision rule',\n },\n {\n path: `${bundle}/${root}/purposes/analytics/analytics_test.rego`,\n contents: `# Policy outcomes for the Analytics purpose (the queried document).\npackage ${root}.purposes.analytics_test\n\nimport rego.v1\n\nimport data.${root}.purposes.analytics\n\ngiven(preferences) := {\"preferences\": preferences}\n\ntest_explicit_allow if {\n\\tresult := analytics.result with input as given([{\"name\": \"Analytics\", \"choice\": true}])\n\\tresult == {\n\\t\\t\"decision\": \"allow\",\n\\t\\t\"reason_code\": \"explicit_allow\",\n\\t}\n}\n\ntest_explicit_deny if {\n\\tresult := analytics.result with input as given([{\"name\": \"Analytics\", \"choice\": false}])\n\\tresult == {\n\\t\\t\"decision\": \"deny\",\n\\t\\t\"reason_code\": \"explicit_deny\",\n\\t}\n}\n\ntest_undecided_resolves_to_default_allow if {\n\\tresult := analytics.result with input as given([])\n\\tresult == {\n\\t\\t\"decision\": \"allow\",\n\\t\\t\"reason_code\": \"default_allow\",\n\\t}\n}\n\ntest_missing_preferences_resolves_to_default_allow if {\n\\tresult := analytics.result with input as {}\n\\tresult == {\n\\t\\t\"decision\": \"allow\",\n\\t\\t\"reason_code\": \"default_allow\",\n\\t}\n}\n\ntest_non_boolean_choice_falls_back_to_default_allow if {\n\\tresult := analytics.result with input as given([{\"name\": \"Analytics\", \"choice\": \"yes\"}])\n\\tresult == {\n\\t\\t\"decision\": \"allow\",\n\\t\\t\"reason_code\": \"default_allow\",\n\\t}\n}\n\ntest_malformed_preferences_are_treated_as_undecided if {\n\\t# source_available is false, so enabled/disabled never fire; undecided still\n\\t# holds for configured purposes (not enabled and not disabled).\n\\tresult := analytics.result with input as {\"preferences\": {\"Analytics\": true}}\n\\tresult == {\n\\t\\t\"decision\": \"allow\",\n\\t\\t\"reason_code\": \"default_allow\",\n\\t}\n}\n`,\n description: 'Create analytics purpose decision tests',\n },\n {\n path: `${bundle}/${root}/purposes/entrypoint.rego`,\n contents: `# METADATA\n# title: Purpose decisions\n# description: Returns each purpose's decision and reason code.\n# scope: package\n# entrypoint: true\npackage ${root}.purposes\n\nimport rego.v1\n`,\n description: 'Create the purposes entrypoint',\n },\n {\n path: `${bundle}/input.example.json`,\n contents: inputExample,\n description: 'Create a sanitized permissions evaluation input example',\n },\n {\n path: `${bundle}/input.json`,\n contents: inputExample,\n description: 'Create a local evaluation input (gitignored copy of the example)',\n },\n {\n path: `${bundle}/.gitignore`,\n contents: POLICY_GITIGNORE_TEMPLATE,\n description: 'Ignore only the private local input file',\n },\n ];\n}\n\n/**\n * Generate bundle files for a given template and root.\n *\n * @param template - Template name\n * @param root - Package root name\n * @param bundleDir - Publish directory basename under the workspace\n * @returns Bundle files relative to the workspace\n */\nexport function generatePolicyBundleFiles(\n template: PolicyTemplateName,\n root: string,\n bundleDir: string = buildBundleDirectoryName(root),\n): PolicyStarterFile[] {\n switch (template) {\n case PolicyTemplate.Generic:\n return generateGenericBundleFiles(root, bundleDir);\n case PolicyTemplate.Permissions:\n return generatePermissionsBundleFiles(root, bundleDir);\n default:\n throw new Error(`Unknown policy template: ${String(template)}`);\n }\n}\n\n/**\n * Build the suggested `policy eval` follow-up after `policy new`.\n *\n * @param options - Bundle display path, package root, and template\n * @returns Multi-line shell command ready to paste\n */\nexport function buildPolicyBundleEvalNextStep(options: {\n /** Workspace-relative publish directory (e.g. `transcend/policy/permissions-bundle`). */\n bundleDirectory: string;\n /** Rego / `.manifest` package root. */\n root: string;\n /** Scaffold template that determined the query path. */\n template: PolicyTemplateName;\n}): string {\n const { bundleDirectory, root, template } = options;\n const packagePath =\n template === PolicyTemplate.Permissions ? `data.${root}.purposes` : `data.${root}.result`;\n return [\n `transcend policy eval ${bundleDirectory} \\\\`,\n ` --package=${packagePath} \\\\`,\n ` --input=${bundleDirectory}/input.json \\\\`,\n ` --schema=${bundleDirectory}/${POLICY_INPUT_SCHEMA_FILENAME}`,\n ].join('\\n');\n}\n","import { join, resolve } from 'node:path';\n\nimport type { LocalContext } from '../../context.js';\nimport {\n collectProjectRelativePaths,\n discoverProjectRepository,\n} from '../scaffolding/project-discovery.js';\nimport type { PolicyProjectState } from './policy-scaffold-model.js';\nimport {\n POLICY_MANIFEST_FILENAME,\n POLICY_STARTER_BUNDLE_DIRECTORY,\n} from './policy-scaffold-templates.js';\n\n/** Default local policy workspace directory (shared Regal config + bundles). */\nexport const DEFAULT_POLICY_PROJECT_DIRECTORY = 'transcend/policy';\n\n/**\n * Resolve a selected policy project relative to the invocation directory.\n *\n * @param invocationDirectory - CLI working directory\n * @param directory - User-selected project directory\n * @returns Absolute policy project directory\n */\nexport function resolvePolicyProjectDirectory(\n invocationDirectory: string,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n): string {\n return resolve(invocationDirectory, directory);\n}\n\n/**\n * Absolute path to the disposable starter publish directory under a workspace.\n *\n * @param workspaceDirectory - Absolute policy workspace directory\n * @returns Absolute starter bundle directory\n */\nexport function getPolicyStarterBundleDirectory(workspaceDirectory: string): string {\n return join(workspaceDirectory, POLICY_STARTER_BUNDLE_DIRECTORY);\n}\n\n/**\n * Resolve publishable bundle directories under a path.\n *\n * - If `directory` itself contains a `.manifest`, it is treated as one bundle.\n * - Otherwise immediate child directories that contain a `.manifest` are\n * returned in sorted order (multi-bundle workspace). Folder names are not\n * required to end in `-bundle`; that suffix is only the `policy new`\n * scaffolding convention.\n *\n * @param context - Filesystem-bearing CLI context\n * @param directory - Absolute workspace or bundle directory\n * @returns Absolute bundle directories to lint / test\n */\nexport function discoverPolicyBundleDirectories(\n context: Pick<LocalContext, 'fs'>,\n directory: string,\n): string[] {\n if (!context.fs.existsSync(directory) || !context.fs.statSync(directory).isDirectory()) {\n return [];\n }\n const manifestAtRoot = join(directory, POLICY_MANIFEST_FILENAME);\n if (context.fs.existsSync(manifestAtRoot) && context.fs.statSync(manifestAtRoot).isFile()) {\n return [directory];\n }\n return context.fs\n .readdirSync(directory, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => join(directory, entry.name))\n .filter((bundleDirectory) => {\n const manifestPath = join(bundleDirectory, POLICY_MANIFEST_FILENAME);\n return context.fs.existsSync(manifestPath) && context.fs.statSync(manifestPath).isFile();\n })\n .sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Collect repository state required by the pure policy planner.\n *\n * @param context - CLI context\n * @param directory - User-selected target directory\n * @returns Policy project discovery state\n */\nexport function discoverPolicyProject(\n context: LocalContext,\n directory: string = DEFAULT_POLICY_PROJECT_DIRECTORY,\n): PolicyProjectState {\n const invocationDirectory = context.process.cwd();\n const targetDirectory = resolvePolicyProjectDirectory(invocationDirectory, directory);\n if (\n context.fs.existsSync(targetDirectory) &&\n !context.fs.statSync(targetDirectory).isDirectory()\n ) {\n throw new Error(`Policy target is not a directory: ${targetDirectory}`);\n }\n const repository = discoverProjectRepository(context, {\n invocationDirectory,\n targetDirectory,\n standaloneProjectRoot: invocationDirectory,\n });\n return {\n invocationDirectory,\n targetDirectory,\n ...repository,\n relativePaths: collectProjectRelativePaths(context, targetDirectory),\n relativeFilePaths: collectProjectRelativePaths(context, targetDirectory, {\n includeDirectories: false,\n }),\n };\n}\n\n/**\n * Resolve the starter bundle manifest path for a discovered workspace.\n *\n * @param state - Policy project state\n * @returns Absolute manifest path under the starter `{root}-bundle/`\n */\nexport function getPolicyManifestPath(state: PolicyProjectState): string {\n return join(getPolicyStarterBundleDirectory(state.targetDirectory), POLICY_MANIFEST_FILENAME);\n}\n"],"mappings":"g6CCMA,MAAa,EAAqCA,EAGrC,EAA6B,SAS7B,EAAsB,UAGtB,EAAkC,GAAG,EAAoB,SAGzD,EAA+B,oBAa/B,EAA2B,YAQ3B,EAAiC,cAGjC,EAAyC,eAGzC,EAAiB,CAC5B,QAAS,UACT,YAAa,cACd,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GAAG,SAAS,EAAe,CAAC,QAAQ,CAChF,CAAC,EAAU,CAEb,EAAQ,GACZ,YAAY,EAAW,CAAE,cAAe,GAAM,CAAC,CAC/C,OAAQ,GAAU,EAAM,aAAa,CAAC,CACtC,IAAK,GAAU,EAAK,EAAW,EAAM,KAAK,CAAC,CAC3C,OAAQ,GAAoB,CAC3B,IAAM,EAAe,EAAK,EAAiB,EAAyB,CACpE,OAAO,EAAQ,GAAG,WAAW,EAAa,EAAI,EAAQ,GAAG,SAAS,EAAa,CAAC,QAAQ,EACxF,CACD,MAAM,EAAM,IAAU,EAAK,cAAc,EAAM,CAAC,CAUrD,SAAgB,EACd,EACA,EAAoB,EACA,CACpB,IAAM,EAAsB,EAAQ,QAAQ,KAAK,CAC3C,EAAkB,EAA8B,EAAqB,EAAU,CACrF,GACE,EAAQ,GAAG,WAAW,EAAgB,EACtC,CAAC,EAAQ,GAAG,SAAS,EAAgB,CAAC,aAAa,CAEnD,MAAU,MAAM,qCAAqC,IAAkB,CAOzE,MAAO,CACL,sBACA,kBACA,GARiB,EAA0B,EAAS,CACpD,sBACA,kBACA,sBAAuB,EACxB,CAIc,CACb,cAAe,EAA4B,EAAS,EAAgB,CACpE,kBAAmB,EAA4B,EAAS,EAAiB,CACvE,mBAAoB,GACrB,CAAC,CACH"}
@@ -1,5 +1,5 @@
1
- import{_ as e,c as t,d as n,f as r,g as i,o as a,s as o,u as s}from"./policy-project-discovery-DTSl0Gfl.mjs";import{n as c,r as l,t as u}from"./jsonc-CdTubr53.mjs";import{posix as d,relative as f,sep as p}from"node:path";const m=`0.42.0`,h=`.github/workflows/transcend-policy.yml`,g=`d23441a48e516b6c34aea4fa41551a30e30af803`,_=`b2b258e089860efaadaaf71bf6e3aecb4a3eeff1`,v=`761188c3b435761fa254beca508a44875619648f`;function y(e,t){return e===`.`?t:d.join(e,t)}function b(e){let t=e.bundleDirectories??[y(e.workspaceDirectory,s)],r=[y(e.workspaceDirectory,`**/*.rego`),y(e.workspaceDirectory,`**/*.json`),y(e.workspaceDirectory,`**/*.yaml`),y(e.workspaceDirectory,`**/*.yml`),y(e.workspaceDirectory,`**/.manifest`),y(e.workspaceDirectory,`.regal/config.yaml`),y(e.workspaceDirectory,`.regal.yaml`),h].map(e=>` - ${JSON.stringify(e)}`).join(`
2
- `),i;return i=t.length===0?` lint:
1
+ import{_ as e,c as t,d as n,f as r,g as i,o as a,s as o,u as s}from"./policy-project-discovery-CND7N2HI.mjs";import{n as c,r as l,t as u}from"./jsonc-CdTubr53.mjs";import{posix as d,relative as f,sep as p}from"node:path";const m=`0.42.0`,h=`.github/workflows/transcend-policy.yml`,g=`d23441a48e516b6c34aea4fa41551a30e30af803`,_=`b2b258e089860efaadaaf71bf6e3aecb4a3eeff1`,v=`761188c3b435761fa254beca508a44875619648f`;function y(e,t){return e===`.`?t:d.join(e,t)}function b(e){let t=e.bundleDirectories??[y(e.workspaceDirectory,s)],r=[y(e.workspaceDirectory,`**/*.rego`),y(e.workspaceDirectory,`**/*.json`),y(e.workspaceDirectory,`**/*.yaml`),y(e.workspaceDirectory,`**/*.yml`),y(e.workspaceDirectory,`**/.manifest`),y(e.workspaceDirectory,`.regal/config.yaml`),y(e.workspaceDirectory,`.regal.yaml`),h].map(e=>` - ${JSON.stringify(e)}`).join(`
2
+ `),i;return i=t.length===0?` check:
3
3
  runs-on: ubuntu-latest
4
4
  steps:
5
5
  - uses: actions/checkout@${g} # v6
@@ -7,7 +7,7 @@ import{_ as e,c as t,d as n,f as r,g as i,o as a,s as o,u as s}from"./policy-pro
7
7
  run: >-
8
8
  echo "Run transcend policy new to add a bundle;
9
9
  policy new refreshes this workflow automatically."
10
- `:t.length===1?` lint:
10
+ `:t.length===1?` check:
11
11
  runs-on: ubuntu-latest
12
12
  steps:
13
13
  - uses: actions/checkout@${g} # v6
@@ -25,11 +25,11 @@ import{_ as e,c as t,d as n,f as r,g as i,o as a,s as o,u as s}from"./policy-pro
25
25
  env:
26
26
  POLICY_DIRECTORY: ${JSON.stringify(t[0])}
27
27
  run: >-
28
- transcend policy lint
28
+ transcend policy check
29
29
  "$POLICY_DIRECTORY"
30
30
  --noInteractive
31
31
  --json
32
- `:` lint:
32
+ `:` check:
33
33
  runs-on: ubuntu-latest
34
34
  strategy:
35
35
  fail-fast: false
@@ -52,7 +52,7 @@ ${t.map(e=>` - ${JSON.stringify(e)}`).join(`
52
52
  - name: Validate Policy Engine project
53
53
  env:
54
54
  POLICY_DIRECTORY: \${{ matrix.policy_directory }}
55
- run: transcend policy lint "$POLICY_DIRECTORY" --noInteractive --json
55
+ run: transcend policy check "$POLICY_DIRECTORY" --noInteractive --json
56
56
  `,`# Generated by transcend policy init.
57
57
  name: Transcend Policy
58
58
 
@@ -74,5 +74,5 @@ ${i}`}const x=`tsandall.opa`,S=`glebbash.opa-highlight-only`;function C(t,n){ret
74
74
  `,t)}}catch(t){return{contents:e??`{}
75
75
  `,warning:`${t instanceof Error?t.message:String(t)} Existing content was left unchanged.`}}}function E(e,t,n,r){if(t.length===0)return{contents:e??`{}
76
76
  `,warnings:r};try{return{contents:u(e,t,n),warnings:r}}catch(t){return{contents:e??`{}
77
- `,warnings:[...r,`${t instanceof Error?t.message:String(t)} Existing content was left unchanged.`]}}}function D(e,t,n,r){t.forEach(({path:t,value:i,label:a})=>{let o=t.reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e);o===void 0?n.push({path:t,value:i}):w(o,i)||r.push(`VS Code setting "${a}" has a repository-specific value and was left unchanged.`)})}function O(e){return e===`.`?"${workspaceFolder}":`\${workspaceFolder}/${e}`}function k(e,t){return f(e,t).split(p).join(`/`)||`.`}function A(e,t,n=C(r)){let i=k(e,t);return O(i===`.`?n.bundleDir:`${i}/${n.bundleDir}`)}function j(e,n){let r=k(e,n);return r===`.`?`**/${t}`:`**/${r}/**/${t}`}function M(e,t,n=C(r)){let s=k(e,t),c=s===`.`?`/${n.bundleDir}`:`/${s}/${n.bundleDir}`,l=n.template===i.Permissions?a:s===`.`?`./${n.bundleDir}/${o}`:`./${s}/${n.bundleDir}/${o}`;return{fileMatch:[`${c}/input.json`,`${c}/input.example.json`],url:l}}function N(e,t,n,r){let i=T(e,`VS Code policy settings`);if(`warning`in i)return{contents:i.contents,warnings:[i.warning]};let{current:a}=i,o=[],s=[];if(r&&r.length>0){let e=a[`opa.roots`],i=r.map(e=>A(t,n,e));if(e===void 0)o.push({path:[`opa.roots`],value:i});else if(Array.isArray(e)&&e.every(e=>typeof e==`string`)){let t=c(e,i);w(t,e)||o.push({path:[`opa.roots`],value:t})}else s.push(`VS Code setting "opa.roots" is customized and was left unchanged.`)}D(a,[{path:[`opa.checkOnSave`],value:!0,label:`opa.checkOnSave`},{path:[`opa.strictMode`],value:!0,label:`opa.strictMode`},{path:[`opa.bundleMode`],value:!0,label:`opa.bundleMode`},{path:[`opa.formatter`],value:`opa-fmt-rego-v1`,label:`opa.formatter`}],o,s);let l=a[`files.associations`],u=j(t,n);if(l===void 0?o.push({path:[`files.associations`],value:{[u]:`json`}}):typeof l==`object`&&l&&!Array.isArray(l)?D(a,[{path:[`files.associations`,u],value:`json`,label:`files.associations."${u}"`}],o,s):s.push(`VS Code setting "files.associations" is customized and was left unchanged.`),r&&r.length>0){let e=r.map(e=>M(t,n,e)),i=a[`json.schemas`];if(i===void 0)o.push({path:[`json.schemas`],value:e});else if(Array.isArray(i)){let t=[...i];e.forEach(e=>{if(t.some(t=>typeof t==`object`&&!!t&&!Array.isArray(t)&&w(t,e)))return;let n=t.findIndex(t=>typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.url==`string`&&t.url===e.url);if(n===-1){t=[...t,e];return}let r=t[n],i=r.fileMatch;if(!Array.isArray(i)||!i.every(e=>typeof e==`string`)){s.push(`VS Code setting "json.schemas" has a repository-specific entry for the ${e.url} schema and was left unchanged.`);return}let a=c(i,e.fileMatch);w(a,i)||(t=t.map((e,t)=>t===n?{...r,fileMatch:a}:e))}),w(t,i)||o.push({path:[`json.schemas`],value:t})}else s.push(`VS Code setting "json.schemas" is customized and was left unchanged.`)}let d=a[`[rego]`];return d===void 0?o.push({path:[`[rego]`],value:{"editor.defaultFormatter":x,"editor.formatOnSave":!0,"editor.insertSpaces":!1,"editor.tabSize":4}}):typeof d==`object`&&d&&!Array.isArray(d)?D(a,[{path:[`[rego]`,`editor.defaultFormatter`],value:x,label:`[rego].editor.defaultFormatter`},{path:[`[rego]`,`editor.formatOnSave`],value:!0,label:`[rego].editor.formatOnSave`},{path:[`[rego]`,`editor.insertSpaces`],value:!1,label:`[rego].editor.insertSpaces`},{path:[`[rego]`,`editor.tabSize`],value:4,label:`[rego].editor.tabSize`}],o,s):s.push(`VS Code language setting "[rego]" is customized and was left unchanged.`),E(e,o,`VS Code policy settings`,s)}function P(e){let t=T(e,`VS Code policy extension recommendations`);if(`warning`in t)return{contents:t.contents,warnings:[t.warning]};let{current:n}=t,r=[],i=[],a=n.recommendations;if(a===void 0||Array.isArray(a)&&a.every(e=>typeof e==`string`)){let e=a??[],t=c(e,[x]).filter(e=>e!==S);w(e,t)||r.push({path:[`recommendations`],value:t})}else i.push(`VS Code extension recommendations use an unknown shape and were left unchanged.`);let o=n.unwantedRecommendations;if(o===void 0||Array.isArray(o)&&o.every(e=>typeof e==`string`)){let e=o??[],t=c(e,[S]);w(e,t)||r.push({path:[`unwantedRecommendations`],value:t})}else i.push(`VS Code unwanted extension recommendations use an unknown shape and were left unchanged.`);return E(e,r,`VS Code policy extension recommendations`,i)}function F(e,t,n=C(r)){let i=k(e,t),a=i===`.`?n.bundleDir:`${i}/${n.bundleDir}`;return{label:`policy: lint ${n.root}`,type:`process`,command:`transcend`,args:[`policy`,`lint`,a,`--noInteractive`],group:{kind:`test`,isDefault:!1},problemMatcher:[]}}function I(e){return{label:`policy: lint`,dependsOn:e.map(e=>`policy: lint ${e.root}`),dependsOrder:`sequence`,group:{kind:`test`,isDefault:!0},problemMatcher:[]}}function L(e,t,n,r){let i=T(e,`VS Code policy tasks`);if(`warning`in i)return{contents:i.contents,warnings:[i.warning]};let{current:a}=i,o=[],s=[],c=a.version;if(c===void 0?o.push({path:[`version`],value:`2.0.0`}):c!==`2.0.0`&&s.push(`VS Code task schema version is customized and was left unchanged.`),!r||r.length===0)return E(e,o,`VS Code policy tasks`,s);let l=r.map(e=>F(t,n,e)),u=I(r),d=[...l,u],f=new Set(d.map(e=>e.label)),p=a.tasks;if(p===void 0)o.push({path:[`tasks`],value:d});else if(Array.isArray(p)){let e=[...p],t=!1;d.forEach(n=>{let r=n.label,i=e.findIndex(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.label===r);if(i===-1){e=[...e,n],t=!0;return}w(e[i],n)||(f.has(r)?(e=e.map((e,t)=>t===i?n:e),t=!0):s.push(`VS Code task "${r}" has repository-specific customization and was left unchanged.`))}),t&&o.push({path:[`tasks`],value:e})}else s.push(`VS Code tasks use an unknown shape and were left unchanged.`);return E(e,o,`VS Code policy tasks`,s)}export{h as a,C as i,N as n,b as o,L as r,P as t};
78
- //# sourceMappingURL=policy-scaffold-config-RpxwwZ2H.mjs.map
77
+ `,warnings:[...r,`${t instanceof Error?t.message:String(t)} Existing content was left unchanged.`]}}}function D(e,t,n,r){t.forEach(({path:t,value:i,label:a})=>{let o=t.reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e);o===void 0?n.push({path:t,value:i}):w(o,i)||r.push(`VS Code setting "${a}" has a repository-specific value and was left unchanged.`)})}function O(e){return e===`.`?"${workspaceFolder}":`\${workspaceFolder}/${e}`}function k(e,t){return f(e,t).split(p).join(`/`)||`.`}function A(e,t,n=C(r)){let i=k(e,t);return O(i===`.`?n.bundleDir:`${i}/${n.bundleDir}`)}function j(e,n){let r=k(e,n);return r===`.`?`**/${t}`:`**/${r}/**/${t}`}function M(e,t,n=C(r)){let s=k(e,t),c=s===`.`?`/${n.bundleDir}`:`/${s}/${n.bundleDir}`,l=n.template===i.Permissions?a:s===`.`?`./${n.bundleDir}/${o}`:`./${s}/${n.bundleDir}/${o}`;return{fileMatch:[`${c}/input.json`,`${c}/input.example.json`],url:l}}function N(e,t,n,r){let i=T(e,`VS Code policy settings`);if(`warning`in i)return{contents:i.contents,warnings:[i.warning]};let{current:a}=i,o=[],s=[];if(r&&r.length>0){let e=a[`opa.roots`],i=r.map(e=>A(t,n,e));if(e===void 0)o.push({path:[`opa.roots`],value:i});else if(Array.isArray(e)&&e.every(e=>typeof e==`string`)){let t=c(e,i);w(t,e)||o.push({path:[`opa.roots`],value:t})}else s.push(`VS Code setting "opa.roots" is customized and was left unchanged.`)}D(a,[{path:[`opa.checkOnSave`],value:!0,label:`opa.checkOnSave`},{path:[`opa.strictMode`],value:!0,label:`opa.strictMode`},{path:[`opa.bundleMode`],value:!0,label:`opa.bundleMode`},{path:[`opa.formatter`],value:`opa-fmt-rego-v1`,label:`opa.formatter`}],o,s);let l=a[`files.associations`],u=j(t,n);if(l===void 0?o.push({path:[`files.associations`],value:{[u]:`json`}}):typeof l==`object`&&l&&!Array.isArray(l)?D(a,[{path:[`files.associations`,u],value:`json`,label:`files.associations."${u}"`}],o,s):s.push(`VS Code setting "files.associations" is customized and was left unchanged.`),r&&r.length>0){let e=r.map(e=>M(t,n,e)),i=a[`json.schemas`];if(i===void 0)o.push({path:[`json.schemas`],value:e});else if(Array.isArray(i)){let t=[...i];e.forEach(e=>{if(t.some(t=>typeof t==`object`&&!!t&&!Array.isArray(t)&&w(t,e)))return;let n=t.findIndex(t=>typeof t==`object`&&!!t&&!Array.isArray(t)&&typeof t.url==`string`&&t.url===e.url);if(n===-1){t=[...t,e];return}let r=t[n],i=r.fileMatch;if(!Array.isArray(i)||!i.every(e=>typeof e==`string`)){s.push(`VS Code setting "json.schemas" has a repository-specific entry for the ${e.url} schema and was left unchanged.`);return}let a=c(i,e.fileMatch);w(a,i)||(t=t.map((e,t)=>t===n?{...r,fileMatch:a}:e))}),w(t,i)||o.push({path:[`json.schemas`],value:t})}else s.push(`VS Code setting "json.schemas" is customized and was left unchanged.`)}let d=a[`[rego]`];return d===void 0?o.push({path:[`[rego]`],value:{"editor.defaultFormatter":x,"editor.formatOnSave":!0,"editor.insertSpaces":!1,"editor.tabSize":4}}):typeof d==`object`&&d&&!Array.isArray(d)?D(a,[{path:[`[rego]`,`editor.defaultFormatter`],value:x,label:`[rego].editor.defaultFormatter`},{path:[`[rego]`,`editor.formatOnSave`],value:!0,label:`[rego].editor.formatOnSave`},{path:[`[rego]`,`editor.insertSpaces`],value:!1,label:`[rego].editor.insertSpaces`},{path:[`[rego]`,`editor.tabSize`],value:4,label:`[rego].editor.tabSize`}],o,s):s.push(`VS Code language setting "[rego]" is customized and was left unchanged.`),E(e,o,`VS Code policy settings`,s)}function P(e){let t=T(e,`VS Code policy extension recommendations`);if(`warning`in t)return{contents:t.contents,warnings:[t.warning]};let{current:n}=t,r=[],i=[],a=n.recommendations;if(a===void 0||Array.isArray(a)&&a.every(e=>typeof e==`string`)){let e=a??[],t=c(e,[x]).filter(e=>e!==S);w(e,t)||r.push({path:[`recommendations`],value:t})}else i.push(`VS Code extension recommendations use an unknown shape and were left unchanged.`);let o=n.unwantedRecommendations;if(o===void 0||Array.isArray(o)&&o.every(e=>typeof e==`string`)){let e=o??[],t=c(e,[S]);w(e,t)||r.push({path:[`unwantedRecommendations`],value:t})}else i.push(`VS Code unwanted extension recommendations use an unknown shape and were left unchanged.`);return E(e,r,`VS Code policy extension recommendations`,i)}function F(e,t,n=C(r)){let i=k(e,t),a=i===`.`?n.bundleDir:`${i}/${n.bundleDir}`;return{label:`policy: check ${n.root}`,type:`process`,command:`transcend`,args:[`policy`,`check`,a,`--noInteractive`],group:{kind:`test`,isDefault:!1},problemMatcher:[]}}function I(e){return{label:`policy: check`,dependsOn:e.map(e=>`policy: check ${e.root}`),dependsOrder:`sequence`,group:{kind:`test`,isDefault:!0},problemMatcher:[]}}function L(e){return typeof e==`string`&&(e===`policy: check`||e.startsWith(`policy: check `)||e===`policy: lint`||e.startsWith(`policy: lint `))}function R(e,t,n,r){let i=T(e,`VS Code policy tasks`);if(`warning`in i)return{contents:i.contents,warnings:[i.warning]};let{current:a}=i,o=[],s=[],c=a.version;if(c===void 0?o.push({path:[`version`],value:`2.0.0`}):c!==`2.0.0`&&s.push(`VS Code task schema version is customized and was left unchanged.`),!r||r.length===0)return E(e,o,`VS Code policy tasks`,s);let l=r.map(e=>F(t,n,e)),u=I(r),d=[...l,u],f=new Set(d.map(e=>e.label)),p=a.tasks;if(p===void 0)o.push({path:[`tasks`],value:d});else if(Array.isArray(p)){let e=p.filter(e=>{if(typeof e!=`object`||!e||Array.isArray(e))return!0;let t=e.label;return!L(t)||f.has(t)}),t=e.length!==p.length;d.forEach(n=>{let r=n.label,i=e.findIndex(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.label===r);if(i===-1){e=[...e,n],t=!0;return}w(e[i],n)||(f.has(r)?(e=e.map((e,t)=>t===i?n:e),t=!0):s.push(`VS Code task "${r}" has repository-specific customization and was left unchanged.`))}),t&&o.push({path:[`tasks`],value:e})}else s.push(`VS Code tasks use an unknown shape and were left unchanged.`);return E(e,o,`VS Code policy tasks`,s)}export{h as a,C as i,N as n,b as o,R as r,P as t};
78
+ //# sourceMappingURL=policy-scaffold-config-CwY0QZC0.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-scaffold-config-CwY0QZC0.mjs","names":[],"sources":["../src/lib/policy/policy-scaffold-artifacts.ts","../src/lib/policy/policy-scaffold-config.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport {\n POLICY_STARTER_BUNDLE_DIRECTORY,\n POLICY_STARTER_OPA_VERSION,\n} from './policy-scaffold-templates.js';\n\n/** Regal version pinned by generated policy validation. */\nexport const POLICY_STARTER_REGAL_VERSION = '0.42.0';\n\n/** Repository-relative generated workflow path. */\nexport const POLICY_CI_WORKFLOW_PATH = '.github/workflows/transcend-policy.yml';\n\n/** Immutable actions/checkout v6 release commit. */\nexport const ACTIONS_CHECKOUT_SHA = 'd23441a48e516b6c34aea4fa41551a30e30af803';\n\n/** Immutable open-policy-agent/setup-opa v2.4.0 release commit. */\nexport const SETUP_OPA_SHA = 'b2b258e089860efaadaaf71bf6e3aecb4a3eeff1';\n\n/** Immutable open-policy-agent/setup-regal v2.0.0 release commit. */\nexport const SETUP_REGAL_SHA = '761188c3b435761fa254beca508a44875619648f';\n\n/**\n * Prefix a path below the repository-relative policy workspace.\n *\n * @param workspaceDirectory - POSIX repository-relative workspace\n * @param child - POSIX workspace-relative path or pattern\n * @returns Repository-relative path or pattern\n */\nfunction workspacePath(workspaceDirectory: string, child: string): string {\n return workspaceDirectory === '.' ? child : posix.join(workspaceDirectory, child);\n}\n\n/**\n * Generate credential-free, validation-only Policy Engine CI.\n *\n * Path filters watch the whole policy workspace. Lint runs against each\n * publishable `{root}-bundle/` directory.\n *\n * @param options - Repository paths and exact CLI release\n * @returns Complete GitHub Actions workflow YAML\n */\nexport function generatePolicyGithubActionsWorkflow(options: {\n /** Exact released Transcend CLI version. */\n cliVersion: string;\n /** Policy workspace directory relative to the repository root. */\n workspaceDirectory: string;\n /**\n * Publish directories to check, relative to the repository root.\n *\n * Pass an empty array for a workspace with no bundles yet (`policy init`).\n * Defaults to the disposable starter bundle under the workspace when omitted.\n */\n bundleDirectories?: readonly string[];\n}): string {\n const bundleDirectories = options.bundleDirectories ?? [\n workspacePath(options.workspaceDirectory, POLICY_STARTER_BUNDLE_DIRECTORY),\n ];\n const watchedPaths = [\n workspacePath(options.workspaceDirectory, '**/*.rego'),\n workspacePath(options.workspaceDirectory, '**/*.json'),\n workspacePath(options.workspaceDirectory, '**/*.yaml'),\n workspacePath(options.workspaceDirectory, '**/*.yml'),\n workspacePath(options.workspaceDirectory, '**/.manifest'),\n workspacePath(options.workspaceDirectory, '.regal/config.yaml'),\n workspacePath(options.workspaceDirectory, '.regal.yaml'),\n POLICY_CI_WORKFLOW_PATH,\n ];\n const pathFilters = watchedPaths.map((path) => ` - ${JSON.stringify(path)}`).join('\\n');\n\n let checkJob: string;\n if (bundleDirectories.length === 0) {\n checkJob = ` check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@${ACTIONS_CHECKOUT_SHA} # v6\n - name: No publishable bundles yet\n run: >-\n echo \"Run transcend policy new to add a bundle;\n policy new refreshes this workflow automatically.\"\n`;\n } else if (bundleDirectories.length === 1) {\n checkJob = ` check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@${ACTIONS_CHECKOUT_SHA} # v6\n - name: Set up OPA\n uses: open-policy-agent/setup-opa@${SETUP_OPA_SHA} # v2.4.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_OPA_VERSION)}\n - name: Set up Regal\n uses: open-policy-agent/setup-regal@${SETUP_REGAL_SHA} # v2.0.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_REGAL_VERSION)}\n - name: Install the Transcend CLI\n run: npm install --global @transcend-io/cli@${options.cliVersion}\n - name: Validate Policy Engine project\n env:\n POLICY_DIRECTORY: ${JSON.stringify(bundleDirectories[0])}\n run: >-\n transcend policy check\n \"$POLICY_DIRECTORY\"\n --noInteractive\n --json\n`;\n } else {\n checkJob = ` check:\n runs-on: ubuntu-latest\n strategy:\n fail-fast: false\n matrix:\n policy_directory:\n${bundleDirectories.map((directory) => ` - ${JSON.stringify(directory)}`).join('\\n')}\n steps:\n - uses: actions/checkout@${ACTIONS_CHECKOUT_SHA} # v6\n - name: Set up OPA\n uses: open-policy-agent/setup-opa@${SETUP_OPA_SHA} # v2.4.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_OPA_VERSION)}\n - name: Set up Regal\n uses: open-policy-agent/setup-regal@${SETUP_REGAL_SHA} # v2.0.0\n with:\n version: ${JSON.stringify(POLICY_STARTER_REGAL_VERSION)}\n - name: Install the Transcend CLI\n run: npm install --global @transcend-io/cli@${options.cliVersion}\n - name: Validate Policy Engine project\n env:\n POLICY_DIRECTORY: \\${{ matrix.policy_directory }}\n run: transcend policy check \"$POLICY_DIRECTORY\" --noInteractive --json\n`;\n }\n\n return `# Generated by transcend policy init.\nname: Transcend Policy\n\non:\n pull_request:\n paths:\n${pathFilters}\n push:\n branches:\n - main\n paths:\n${pathFilters}\n\npermissions:\n contents: read\n\njobs:\n${checkJob}`;\n}\n","import { relative, sep } from 'node:path';\n\nimport {\n mergeJsonc,\n mergeStringArray,\n parseJsoncObject,\n type JsoncUpdate,\n} from '../scaffolding/jsonc.js';\nimport {\n buildBundleDirectoryName,\n PERMISSIONS_POLICY_INPUT_SCHEMA_ID,\n POLICY_INPUT_SCHEMA_FILENAME,\n POLICY_MANIFEST_FILENAME,\n POLICY_STARTER_ROOT,\n PolicyTemplate,\n type PolicyTemplateName,\n} from './policy-scaffold-templates.js';\n\n/** Recommended VS Code extension for OPA and Regal authoring. */\nexport const POLICY_VSCODE_EXTENSION = 'tsandall.opa';\n\n/** Conflicting syntax-only VS Code extension. */\nexport const CONFLICTING_POLICY_VSCODE_EXTENSION = 'glebbash.opa-highlight-only';\n\n/**\n * Local publish unit: Rego package root plus its workspace-relative folder basename.\n *\n * `bundleDir` is not required to be `{root}-bundle` — `policy new --bundle-dir` may override it.\n */\nexport interface PolicyBundleRef {\n /** Package-path root (`.manifest` / Regal `project.roots`). */\n root: string;\n /** Basename of the publish directory under the policy workspace. */\n bundleDir: string;\n /**\n * Scaffold template that produced this bundle, when known.\n *\n * Permissions bundles point VS Code `json.schemas` at the published input\n * schema `$id` so editor validation tracks the live contract.\n */\n template?: PolicyTemplateName;\n}\n\n/**\n * Build a bundle ref with the default `{root}-bundle` directory.\n *\n * @param root - Package root\n * @param template - Optional scaffold template\n * @returns Bundle ref\n */\nexport function policyBundleRef(root: string, template?: PolicyTemplateName): PolicyBundleRef {\n return template === undefined\n ? { root, bundleDir: buildBundleDirectoryName(root) }\n : { root, bundleDir: buildBundleDirectoryName(root), template };\n}\n\n/** Result of safely merging one repository editor artifact. */\nexport interface PolicyEditorMergeResult {\n /** Complete merged contents, or the unchanged original when unsafe. */\n contents: string;\n /** Actionable preservation warnings. */\n warnings: string[];\n}\n\n/** One desired scalar setting that must not replace a customization. */\ninterface DesiredSetting {\n /** JSONC object path. */\n path: string[];\n /** Desired generated value. */\n value: unknown;\n /** Human-readable setting key. */\n label: string;\n}\n\n/**\n * Compare JSON-compatible configuration values.\n *\n * @param left - Existing value\n * @param right - Desired value\n * @returns Whether the values are structurally equal\n */\nfunction configurationValuesEqual(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\n/**\n * Parse an editor object while preserving malformed existing content.\n *\n * @param contents - Existing JSONC, or null\n * @param label - Configuration label\n * @returns Parsed object or a preservation result\n */\nfunction parseEditorObject(\n contents: string | null,\n label: string,\n):\n | {\n /** Parsed JSONC object. */\n current: Record<string, unknown>;\n }\n | {\n /** Complete unchanged contents. */\n contents: string;\n /** Actionable warning. */\n warning: string;\n } {\n try {\n return { current: parseJsoncObject(contents ?? '{}\\n', label) };\n } catch (error) {\n return {\n contents: contents ?? '{}\\n',\n warning: `${error instanceof Error ? error.message : String(error)} Existing content was left unchanged.`,\n };\n }\n}\n\n/**\n * Apply safe JSONC updates or preserve the existing file when comments prevent it.\n *\n * @param contents - Existing JSONC\n * @param updates - Proven-safe updates\n * @param label - Configuration label\n * @param warnings - Existing merge warnings\n * @returns Complete contents and warnings\n */\nfunction applyEditorUpdates(\n contents: string | null,\n updates: readonly JsoncUpdate[],\n label: string,\n warnings: string[],\n): PolicyEditorMergeResult {\n if (updates.length === 0) {\n return { contents: contents ?? '{}\\n', warnings };\n }\n try {\n return {\n contents: mergeJsonc(contents, updates, label),\n warnings,\n };\n } catch (error) {\n return {\n contents: contents ?? '{}\\n',\n warnings: [\n ...warnings,\n `${error instanceof Error ? error.message : String(error)} Existing content was left unchanged.`,\n ],\n };\n }\n}\n\n/**\n * Add absent scalar settings without replacing repository customizations.\n *\n * @param current - Parsed editor object\n * @param desired - Desired settings\n * @param updates - Safe updates to append to\n * @param warnings - Conflict warnings to append to\n */\nfunction collectSafeScalarUpdates(\n current: Record<string, unknown>,\n desired: readonly DesiredSetting[],\n updates: JsoncUpdate[],\n warnings: string[],\n): void {\n desired.forEach(({ path, value, label }) => {\n const existing = path.reduce<unknown>((parent, key) => {\n return parent && typeof parent === 'object' && !Array.isArray(parent)\n ? (parent as Record<string, unknown>)[key]\n : undefined;\n }, current);\n if (existing === undefined) {\n updates.push({ path, value });\n } else if (!configurationValuesEqual(existing, value)) {\n warnings.push(\n `VS Code setting \"${label}\" has a repository-specific value and was left unchanged.`,\n );\n }\n });\n}\n\n/**\n * Build a `${workspaceFolder}/…` path for a repository-relative POSIX path.\n *\n * @param repositoryRelativePath - Path relative to the repository root\n * @returns VS Code workspace path\n */\nfunction buildWorkspaceFolderPath(repositoryRelativePath: string): string {\n return repositoryRelativePath === '.'\n ? '${workspaceFolder}'\n : `\\${workspaceFolder}/${repositoryRelativePath}`;\n}\n\n/**\n * Repository-relative POSIX path from the root that owns `.vscode`.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param absolutePath - Absolute path below the repository\n * @returns POSIX repository-relative path\n */\nfunction repositoryRelativePosix(repositoryRoot: string, absolutePath: string): string {\n return relative(repositoryRoot, absolutePath).split(sep).join('/') || '.';\n}\n\n/**\n * Build the workspace-relative OPA publish root for a bundle.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param workspaceDirectory - Selected policy workspace directory\n * @param bundle - Package root and local directory basename\n * @returns VS Code workspace path\n */\nfunction buildOpaBundleRoot(\n repositoryRoot: string,\n workspaceDirectory: string,\n bundle: PolicyBundleRef = policyBundleRef(POLICY_STARTER_ROOT),\n): string {\n const workspace = repositoryRelativePosix(repositoryRoot, workspaceDirectory);\n const path = workspace === '.' ? bundle.bundleDir : `${workspace}/${bundle.bundleDir}`;\n return buildWorkspaceFolderPath(path);\n}\n\n/**\n * Build a `files.associations` glob for every `.manifest` under the workspace.\n *\n * Patterns that contain `/` are matched against the absolute file path, so a\n * leading `**\\/` prefix is required for a portable workspace-relative association.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param workspaceDirectory - Selected policy workspace directory\n * @returns Association pattern key\n */\nfunction buildPolicyManifestAssociationPattern(\n repositoryRoot: string,\n workspaceDirectory: string,\n): string {\n const workspace = repositoryRelativePosix(repositoryRoot, workspaceDirectory);\n return workspace === '.'\n ? `**/${POLICY_MANIFEST_FILENAME}`\n : `**/${workspace}/**/${POLICY_MANIFEST_FILENAME}`;\n}\n\n/**\n * Build `json.schemas` fileMatch globs for a bundle's input documents.\n *\n * Permissions templates use the published schema `$id` so VS Code validation\n * tracks the live contract. Generic bundles use the local `input.schema.json`\n * (OPA / offline tooling still always use the local file via `--schema`).\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param workspaceDirectory - Selected policy workspace directory\n * @param bundle - Package root and local directory basename\n * @returns Absolute-style fileMatch paths and schema URL\n */\nfunction buildBundleInputJsonSchema(\n repositoryRoot: string,\n workspaceDirectory: string,\n bundle: PolicyBundleRef = policyBundleRef(POLICY_STARTER_ROOT),\n): {\n /** VS Code fileMatch globs (leading slash = workspace-relative). */\n fileMatch: string[];\n /** Schema URL (local path or published Permissions `$id`). */\n url: string;\n} {\n const workspace = repositoryRelativePosix(repositoryRoot, workspaceDirectory);\n const bundlePrefix =\n workspace === '.' ? `/${bundle.bundleDir}` : `/${workspace}/${bundle.bundleDir}`;\n const schemaUrl =\n bundle.template === PolicyTemplate.Permissions\n ? PERMISSIONS_POLICY_INPUT_SCHEMA_ID\n : workspace === '.'\n ? `./${bundle.bundleDir}/${POLICY_INPUT_SCHEMA_FILENAME}`\n : `./${workspace}/${bundle.bundleDir}/${POLICY_INPUT_SCHEMA_FILENAME}`;\n return {\n fileMatch: [`${bundlePrefix}/input.json`, `${bundlePrefix}/input.example.json`],\n url: schemaUrl,\n };\n}\n\n/**\n * Merge strict workspace-scoped OPA and Rego editor settings.\n *\n * Setting names match the authoritative `open-policy-agent/vscode-opa`\n * extension metadata. Existing conflicting values are preserved and reported.\n *\n * When `bundles` is provided, `opa.roots` and `json.schemas` are populated\n * for those bundles. When omitted (init without bundles), `opa.roots` and\n * `json.schemas` are left empty or unset.\n *\n * @param contents - Existing `.vscode/settings.json` JSONC\n * @param repositoryRoot - Root that owns `.vscode`\n * @param workspaceDirectory - Selected policy workspace directory\n * @param bundles - Local publish units to add to `opa.roots` and `json.schemas`\n * @returns Merged settings and conflict warnings\n */\nexport function mergePolicyEditorSettings(\n contents: string | null,\n repositoryRoot: string,\n workspaceDirectory: string,\n bundles?: readonly PolicyBundleRef[],\n): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy settings');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n\n if (bundles && bundles.length > 0) {\n const roots = current['opa.roots'];\n const desiredRoots = bundles.map((bundle) =>\n buildOpaBundleRoot(repositoryRoot, workspaceDirectory, bundle),\n );\n if (roots === undefined) {\n updates.push({ path: ['opa.roots'], value: desiredRoots });\n } else if (Array.isArray(roots) && roots.every((value) => typeof value === 'string')) {\n const merged = mergeStringArray(roots, desiredRoots);\n if (!configurationValuesEqual(merged, roots)) {\n updates.push({ path: ['opa.roots'], value: merged });\n }\n } else {\n warnings.push('VS Code setting \"opa.roots\" is customized and was left unchanged.');\n }\n }\n\n collectSafeScalarUpdates(\n current,\n [\n { path: ['opa.checkOnSave'], value: true, label: 'opa.checkOnSave' },\n { path: ['opa.strictMode'], value: true, label: 'opa.strictMode' },\n { path: ['opa.bundleMode'], value: true, label: 'opa.bundleMode' },\n { path: ['opa.formatter'], value: 'opa-fmt-rego-v1', label: 'opa.formatter' },\n ],\n updates,\n warnings,\n );\n\n const associations = current['files.associations'];\n const manifestAssociation = buildPolicyManifestAssociationPattern(\n repositoryRoot,\n workspaceDirectory,\n );\n if (associations === undefined) {\n updates.push({\n path: ['files.associations'],\n value: { [manifestAssociation]: 'json' },\n });\n } else if (\n associations !== null &&\n typeof associations === 'object' &&\n !Array.isArray(associations)\n ) {\n collectSafeScalarUpdates(\n current,\n [\n {\n path: ['files.associations', manifestAssociation],\n value: 'json',\n label: `files.associations.\"${manifestAssociation}\"`,\n },\n ],\n updates,\n warnings,\n );\n } else {\n warnings.push('VS Code setting \"files.associations\" is customized and was left unchanged.');\n }\n\n if (bundles && bundles.length > 0) {\n const desiredJsonSchemas = bundles.map((bundle) =>\n buildBundleInputJsonSchema(repositoryRoot, workspaceDirectory, bundle),\n );\n const jsonSchemas = current['json.schemas'];\n if (jsonSchemas === undefined) {\n updates.push({ path: ['json.schemas'], value: desiredJsonSchemas });\n } else if (Array.isArray(jsonSchemas)) {\n let merged = [...jsonSchemas];\n desiredJsonSchemas.forEach((desired) => {\n const hasExactMatch = merged.some(\n (entry) =>\n entry !== null &&\n typeof entry === 'object' &&\n !Array.isArray(entry) &&\n configurationValuesEqual(entry, desired),\n );\n if (hasExactMatch) {\n return;\n }\n const sameUrlIndex = merged.findIndex(\n (entry) =>\n entry !== null &&\n typeof entry === 'object' &&\n !Array.isArray(entry) &&\n typeof (entry as Record<string, unknown>).url === 'string' &&\n (entry as Record<string, unknown>).url === desired.url,\n );\n if (sameUrlIndex === -1) {\n merged = [...merged, desired];\n return;\n }\n const existing = merged[sameUrlIndex] as Record<string, unknown>;\n const existingMatches = existing.fileMatch;\n if (\n !Array.isArray(existingMatches) ||\n !existingMatches.every((m) => typeof m === 'string')\n ) {\n warnings.push(\n `VS Code setting \"json.schemas\" has a repository-specific entry for the ${desired.url} schema and was left unchanged.`,\n );\n return;\n }\n const unioned = mergeStringArray(existingMatches, desired.fileMatch);\n if (!configurationValuesEqual(unioned, existingMatches)) {\n merged = merged.map((entry, index) =>\n index === sameUrlIndex ? { ...existing, fileMatch: unioned } : entry,\n );\n }\n });\n if (!configurationValuesEqual(merged, jsonSchemas)) {\n updates.push({ path: ['json.schemas'], value: merged });\n }\n } else {\n warnings.push('VS Code setting \"json.schemas\" is customized and was left unchanged.');\n }\n }\n\n const regoSettings = current['[rego]'];\n if (regoSettings === undefined) {\n updates.push({\n path: ['[rego]'],\n value: {\n 'editor.defaultFormatter': POLICY_VSCODE_EXTENSION,\n 'editor.formatOnSave': true,\n 'editor.insertSpaces': false,\n 'editor.tabSize': 4,\n },\n });\n } else if (\n regoSettings !== null &&\n typeof regoSettings === 'object' &&\n !Array.isArray(regoSettings)\n ) {\n collectSafeScalarUpdates(\n current,\n [\n {\n path: ['[rego]', 'editor.defaultFormatter'],\n value: POLICY_VSCODE_EXTENSION,\n label: '[rego].editor.defaultFormatter',\n },\n {\n path: ['[rego]', 'editor.formatOnSave'],\n value: true,\n label: '[rego].editor.formatOnSave',\n },\n {\n path: ['[rego]', 'editor.insertSpaces'],\n value: false,\n label: '[rego].editor.insertSpaces',\n },\n {\n path: ['[rego]', 'editor.tabSize'],\n value: 4,\n label: '[rego].editor.tabSize',\n },\n ],\n updates,\n warnings,\n );\n } else {\n warnings.push('VS Code language setting \"[rego]\" is customized and was left unchanged.');\n }\n\n return applyEditorUpdates(contents, updates, 'VS Code policy settings', warnings);\n}\n\n/**\n * Merge OPA extension recommendations without disturbing unknown entries.\n *\n * VS Code's `extensions.json` schema supports `unwantedRecommendations`, so\n * the syntax-only extension can be removed from recommendations and discouraged.\n *\n * @param contents - Existing `.vscode/extensions.json` JSONC\n * @returns Merged extension recommendations and warnings\n */\nexport function mergePolicyEditorExtensions(contents: string | null): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy extension recommendations');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n\n const recommendations = current.recommendations;\n if (\n recommendations === undefined ||\n (Array.isArray(recommendations) && recommendations.every((value) => typeof value === 'string'))\n ) {\n const existing = recommendations ?? [];\n const desired = mergeStringArray(existing, [POLICY_VSCODE_EXTENSION]).filter(\n (value) => value !== CONFLICTING_POLICY_VSCODE_EXTENSION,\n );\n if (!configurationValuesEqual(existing, desired)) {\n updates.push({ path: ['recommendations'], value: desired });\n }\n } else {\n warnings.push(\n 'VS Code extension recommendations use an unknown shape and were left unchanged.',\n );\n }\n\n const unwanted = current.unwantedRecommendations;\n if (\n unwanted === undefined ||\n (Array.isArray(unwanted) && unwanted.every((value) => typeof value === 'string'))\n ) {\n const existing = unwanted ?? [];\n const desired = mergeStringArray(existing, [CONFLICTING_POLICY_VSCODE_EXTENSION]);\n if (!configurationValuesEqual(existing, desired)) {\n updates.push({ path: ['unwantedRecommendations'], value: desired });\n }\n } else {\n warnings.push(\n 'VS Code unwanted extension recommendations use an unknown shape and were left unchanged.',\n );\n }\n\n return applyEditorUpdates(\n contents,\n updates,\n 'VS Code policy extension recommendations',\n warnings,\n );\n}\n\n/**\n * Build a VS Code check task for one bundle.\n *\n * @param repositoryRoot - Root that owns `.vscode`\n * @param workspaceDirectory - Selected policy workspace directory\n * @param bundle - Package root and local directory basename\n * @returns VS Code task object\n */\nexport function buildPolicyCheckTask(\n repositoryRoot: string,\n workspaceDirectory: string,\n bundle: PolicyBundleRef = policyBundleRef(POLICY_STARTER_ROOT),\n): Record<string, unknown> {\n const workspace = repositoryRelativePosix(repositoryRoot, workspaceDirectory);\n const path = workspace === '.' ? bundle.bundleDir : `${workspace}/${bundle.bundleDir}`;\n return {\n label: `policy: check ${bundle.root}`,\n type: 'process',\n command: 'transcend',\n args: ['policy', 'check', path, '--noInteractive'],\n group: {\n kind: 'test',\n isDefault: false,\n },\n problemMatcher: [],\n };\n}\n\n/**\n * Build the aggregate \"policy: check\" task (runs all bundles).\n *\n * @param bundles - Local publish units\n * @returns VS Code task object\n */\nexport function buildPolicyAggregateCheckTask(\n bundles: readonly PolicyBundleRef[],\n): Record<string, unknown> {\n return {\n label: 'policy: check',\n dependsOn: bundles.map((bundle) => `policy: check ${bundle.root}`),\n dependsOrder: 'sequence',\n group: {\n kind: 'test',\n isDefault: true,\n },\n problemMatcher: [],\n };\n}\n\n/**\n * Whether a VS Code task label is a managed policy verification task.\n *\n * Includes legacy `policy: lint*` labels so re-running editor setup migrates\n * them to `policy: check*`.\n *\n * @param label - Task label\n * @returns True when the task is managed by policy scaffolding\n */\nfunction isManagedPolicyVerificationTaskLabel(label: unknown): boolean {\n return (\n typeof label === 'string' &&\n (label === 'policy: check' ||\n label.startsWith('policy: check ') ||\n label === 'policy: lint' ||\n label.startsWith('policy: lint '))\n );\n}\n\n/**\n * Merge policy check tasks while preserving custom tasks.\n *\n * When `bundles` is provided, creates per-bundle tasks and an aggregate.\n * Managed `policy: check*` tasks are updated in place as roots grow. Legacy\n * `policy: lint*` tasks are removed so editor setup migrates to `check`.\n * When omitted, skips task creation (init without bundles).\n *\n * @param contents - Existing `.vscode/tasks.json` JSONC\n * @param repositoryRoot - Root that owns `.vscode`\n * @param workspaceDirectory - Selected policy workspace directory\n * @param bundles - Local publish units to generate tasks for\n * @returns Merged task configuration and warnings\n */\nexport function mergePolicyEditorTasks(\n contents: string | null,\n repositoryRoot: string,\n workspaceDirectory: string,\n bundles?: readonly PolicyBundleRef[],\n): PolicyEditorMergeResult {\n const parsed = parseEditorObject(contents, 'VS Code policy tasks');\n if ('warning' in parsed) {\n return { contents: parsed.contents, warnings: [parsed.warning] };\n }\n const { current } = parsed;\n const updates: JsoncUpdate[] = [];\n const warnings: string[] = [];\n const version = current.version;\n if (version === undefined) {\n updates.push({ path: ['version'], value: '2.0.0' });\n } else if (version !== '2.0.0') {\n warnings.push('VS Code task schema version is customized and was left unchanged.');\n }\n\n if (!bundles || bundles.length === 0) {\n return applyEditorUpdates(contents, updates, 'VS Code policy tasks', warnings);\n }\n\n const desiredPerBundleTasks = bundles.map((bundle) =>\n buildPolicyCheckTask(repositoryRoot, workspaceDirectory, bundle),\n );\n const desiredAggregateTask = buildPolicyAggregateCheckTask(bundles);\n const desiredTasks = [...desiredPerBundleTasks, desiredAggregateTask];\n const managedLabels = new Set(desiredTasks.map((task) => task.label as string));\n const tasks = current.tasks;\n if (tasks === undefined) {\n updates.push({ path: ['tasks'], value: desiredTasks });\n } else if (Array.isArray(tasks)) {\n let merged = tasks.filter((task) => {\n if (task === null || typeof task !== 'object' || Array.isArray(task)) {\n return true;\n }\n const label = (task as Record<string, unknown>).label;\n return !isManagedPolicyVerificationTaskLabel(label) || managedLabels.has(label as string);\n });\n let changed = merged.length !== tasks.length;\n desiredTasks.forEach((desired) => {\n const label = desired.label as string;\n const matchingIndex = merged.findIndex(\n (task) =>\n task !== null &&\n typeof task === 'object' &&\n !Array.isArray(task) &&\n (task as Record<string, unknown>).label === label,\n );\n if (matchingIndex === -1) {\n merged = [...merged, desired];\n changed = true;\n return;\n }\n if (!configurationValuesEqual(merged[matchingIndex], desired)) {\n if (managedLabels.has(label)) {\n merged = merged.map((task, index) => (index === matchingIndex ? desired : task));\n changed = true;\n } else {\n warnings.push(\n `VS Code task \"${label}\" has repository-specific customization and was left unchanged.`,\n );\n }\n }\n });\n if (changed) {\n updates.push({ path: ['tasks'], value: merged });\n }\n } else {\n warnings.push('VS Code tasks use an unknown shape and were left unchanged.');\n }\n\n return applyEditorUpdates(contents, updates, 'VS Code policy tasks', warnings);\n}\n"],"mappings":"6NAQA,MAAa,EAA+B,SAG/B,EAA0B,yCAG1B,EAAuB,2CAGvB,EAAgB,2CAGhB,EAAkB,2CAS/B,SAAS,EAAc,EAA4B,EAAuB,CACxE,OAAO,IAAuB,IAAM,EAAQ,EAAM,KAAK,EAAoB,EAAM,CAYnF,SAAgB,EAAoC,EAYzC,CACT,IAAM,EAAoB,EAAQ,mBAAqB,CACrD,EAAc,EAAQ,mBAAoB,EAAgC,CAC3E,CAWK,EAAc,CATlB,EAAc,EAAQ,mBAAoB,YAAY,CACtD,EAAc,EAAQ,mBAAoB,YAAY,CACtD,EAAc,EAAQ,mBAAoB,YAAY,CACtD,EAAc,EAAQ,mBAAoB,WAAW,CACrD,EAAc,EAAQ,mBAAoB,eAAe,CACzD,EAAc,EAAQ,mBAAoB,qBAAqB,CAC/D,EAAc,EAAQ,mBAAoB,cAA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W,IAAU,EAAgB,EAAU,EAAM,CAChF,EAAU,IAEV,EAAS,KACP,iBAAiB,EAAM,iEACxB,GAGL,CACE,GACF,EAAQ,KAAK,CAAE,KAAM,CAAC,QAAQ,CAAE,MAAO,EAAQ,CAAC,MAGlD,EAAS,KAAK,8DAA8D,CAG9E,OAAO,EAAmB,EAAU,EAAS,uBAAwB,EAAS"}
@@ -1,2 +1,2 @@
1
- import{i as e}from"./paths-J5KScOaQ.mjs";import{a as t,i as n,n as r,r as i}from"./project-discovery-CWRjlFnC.mjs";import{a}from"./readTranscendYaml-BfqQbPiT.mjs";import{CustomFunctionPayloadType as o,CustomFunctionType as s}from"@transcend-io/privacy-types";import{dirname as c,extname as l,isAbsolute as u,join as d,relative as f,resolve as p,sep as m}from"node:path";import h from"js-yaml";import{existsSync as g,readFileSync as _,writeFileSync as v}from"node:fs";import{decodeCodec as y}from"@transcend-io/type-utils";import*as b from"io-ts";import{isMap as x,isScalar as S,isSeq as C,parseDocument as w}from"yaml";import{Buffer as T}from"node:buffer";import{isIP as E}from"node:net";const D=64*1024,O=new Set([`DENO_CERT`,`DENO_DIR`,`DENO_TLS_CA_STORE`,`HTTP_PROXY`,`HTTPS_PROXY`,`NODE_EXTRA_CA_CERTS`,`NO_COLOR`,`NO_PROXY`,`NPM_CONFIG_REGISTRY`]);function k(e){let t=/^\[([^\]]+)\](?::(\d+))?$/u.exec(e);if(t){let e=t[2];return E(t[1])===6&&(!e||Number(e)>0&&Number(e)<=65535)}if(E(e)>0)return!0;let n=/^([^:]+):(\d+)$/u.exec(e),r=n?.[1]??e,i=n?.[2];return(!i||Number(i)>0&&Number(i)<=65535)&&r.length<=253&&r.split(`.`).every(e=>e.length>0&&e.length<=63&&/^[A-Za-z\d](?:[A-Za-z\d-]*[A-Za-z\d])?$/u.test(e))}function A(e){let t=e.env??{},n=Object.keys(t),r=n.filter(e=>!/^[A-Za-z][A-Za-z\d_]*$/u.test(e)),i=n.filter(e=>O.has(e)||e.startsWith(`DENO_`));if(r.length>0||i.length>0)throw Error([r.length>0?`Invalid environment variable names: ${r.join(`, `)}`:void 0,i.length>0?`Reserved environment variable names: ${i.join(`, `)}`:void 0].filter(Boolean).join(`. `));let a=n.filter(e=>T.byteLength(t[e])>D);if(a.length>0)throw Error(`Environment values exceed ${D} bytes: ${a.join(`, `)}`);let o=e.allowedHosts??[];if(o.length>1&&o.includes(`*`))throw Error(`allowed-hosts cannot combine "*" with specific hosts.`);let s=o.filter(e=>e!==`*`&&!k(e));if(s.length>0)throw Error(`Invalid allowed-hosts: ${s.join(`, `)}`)}const j=b.intersection([b.type({name:b.string,code:b.string}),b.partial({id:b.string,description:b.string,type:b.union([b.literal(s.Dsr),b.literal(s.General)]),"data-silo-id":b.string,"sombra-id":b.string,"sombra-auth-env":b.string,"allowed-hosts":b.array(b.string),"timeout-ms":b.number,"allow-third-party-imports":b.boolean,env:b.record(b.string,b.string),"test-payload":b.string,"test-payload-type":b.union([b.literal(o.DataPoint),b.literal(o.RequestEnricher)]),"test-payloads":b.array(b.intersection([b.type({payload:b.string}),b.partial({"payload-type":b.union([b.literal(o.DataPoint),b.literal(o.RequestEnricher)])})]))})]),M=b.type({functions:b.array(j)});function N(e){let t=p(`/`,`__custom-function-manifest__`),n=f(t,p(t,e));return n!==`..`&&!n.startsWith(`..${m}`)&&!u(n)}function P(e,t={}){let n=e.functions.map(({id:e})=>e).filter((e,t,n)=>e!==void 0&&n.indexOf(e)!==t);if(n.length>0)throw Error(`Duplicate custom function ids in manifest: ${[...new Set(n)].join(`, `)}`);let r=e.functions.map(({name:e})=>e),i=e.functions.filter(({id:e,name:t})=>e===void 0&&r.filter(e=>e===t).length>1).map(({name:e})=>e);if(i.length>0)throw Error(`Duplicate custom function names in manifest without ids: ${[...new Set(i)].join(`, `)}. Add an \`id\` field to each duplicated entry to disambiguate.`);e.functions.forEach(e=>{if(e[`test-payload`]!==void 0&&e[`test-payloads`]!==void 0)throw Error(`Custom function "${e.name}" sets both test-payload and test-payloads — use test-payloads alone to define multiple payloads.`);if(e[`test-payload-type`]!==void 0&&e[`test-payload`]===void 0)throw Error(`Custom function "${e.name}" sets test-payload-type without test-payload — set payload-type per item in test-payloads instead.`);if(e.type!==s.Dsr&&(e[`test-payload-type`]!==void 0||e[`test-payloads`]?.some(({"payload-type":e})=>e!==void 0)))throw Error(`Custom function "${e.name}" sets a DSR payload type but is not type DSR.`);[{field:`code`,path:e.code},...e[`test-payload`]===void 0?[]:[{field:`test-payload`,path:e[`test-payload`]}],...(e[`test-payloads`]??[]).map(({payload:e},t)=>({field:`test-payloads[${t}].payload`,path:e}))].forEach(({field:n,path:r})=>{if(!t.skipPathValidation&&!N(r))throw Error(`Custom function "${e.name}" has a ${n} path outside the manifest directory: ${r}`)})})}function F(e,t={}){let n=y(M,h.load(e));return P(n,t),n}function I(e,t,n){let r=c(p(e)),i=(e,t)=>{let i=p(r,t);if(n?.(i),!g(i))throw Error(`Test payload file for custom function "${e}" does not exist: ${i}`);let a=_(i,`utf-8`);try{return JSON.parse(a)}catch(t){throw Error(`Test payload file for custom function "${e}" is not valid JSON (${i}): ${t.message}`)}};return t.functions.map(e=>{A({...e.env?{env:e.env}:{},...e[`allowed-hosts`]?{allowedHosts:e[`allowed-hosts`]}:{}});let t=p(r,e.code);if(n?.(t),!g(t))throw Error(`Code file for custom function "${e.name}" does not exist: ${t}`);let a;return e[`test-payload`]===void 0?e[`test-payloads`]!==void 0&&e[`test-payloads`].length>0&&(a=e[`test-payloads`].map(t=>({payload:i(e.name,t.payload),...t[`payload-type`]===void 0?{}:{payloadType:t[`payload-type`]}}))):a=[{payload:i(e.name,e[`test-payload`]),...e[`test-payload-type`]===void 0?{}:{payloadType:e[`test-payload-type`]}}],{name:e.name,code:_(t,`utf-8`),...e.id===void 0?{}:{id:e.id},...e.description===void 0?{}:{description:e.description},...e.type===void 0?{}:{type:e.type},...e[`data-silo-id`]===void 0?{}:{dataSiloId:e[`data-silo-id`]},...e[`sombra-id`]===void 0?{}:{sombraId:e[`sombra-id`]},...e[`sombra-auth-env`]===void 0?{}:{sombraAuthEnv:e[`sombra-auth-env`]},...e[`allowed-hosts`]===void 0?{}:{allowedHosts:e[`allowed-hosts`]},...e[`timeout-ms`]===void 0?{}:{timeoutMs:e[`timeout-ms`]},...e[`allow-third-party-imports`]===void 0?{}:{allowThirdPartyImports:e[`allow-third-party-imports`]},...e.env===void 0?{}:{env:e.env},...a===void 0?{}:{testPayloads:a}}})}function L(e,t={},n){return I(e,F(a(_(e,`utf-8`),t,`Also check that there are no extra variables defined in your manifest: ${e}`)),n)}function R(e,t,n={},r){let i=F(a(h.dump({functions:[t]}),n,`Also check that there are no extra variables defined for "${t.name}" in: ${e}`)),o=i.functions[0],s=p(c(p(e)),o.code);return{config:I(e,i,r)[0],sourcePath:s}}function z(e,t){let n=w(e);if(n.errors.length>0)throw n.errors[0];let r=n.get(`functions`);if(!C(r))throw Error("Expected a `functions` list in custom function manifest");r.items.length===0&&(r.flow=!1),r.add(n.createNode(t));let i=n.toString();return F(i),i}function B(e,t){let n=w(_(e,`utf-8`)),r=n.get(`functions`);if(!C(r))throw Error(`Expected a \`functions\` list in manifest: ${e}`);let i=0;return r.items.forEach((e,r)=>{let a=t[r];if(!a||!x(e))return;let o=!1;if(a.id&&!e.has(`id`)&&(e.items.unshift(n.createPair(`id`,a.id)),o=!0),a.dataSiloId&&!e.has(`data-silo-id`)){let t=e.items.findIndex(e=>S(e.key)&&e.key.value===`id`);e.items.splice(t+1,0,n.createPair(`data-silo-id`,a.dataSiloId)),o=!0}o&&(i+=1)}),i>0&&v(e,n.toString()),i}function V(e,r){let i=n(e,r),a=t(e,i)??i,o=[],s=t=>{e.fs.readdirSync(t,{withFileTypes:!0}).forEach(n=>{if(n.name===`.git`||n.name===`.worktrees`||n.name===`node_modules`)return;let r=d(t,n.name);if(n.isDirectory()&&!n.isSymbolicLink())s(r);else if(n.isFile()){if(n.name===`transcend-functions.yml`){o.push(r);return}if([`.yml`,`.yaml`].includes(l(n.name)))try{if(e.fs.statSync(r).size>256e3)return;F(e.fs.readFileSync(r,`utf8`),{skipPathValidation:!0}),o.push(r)}catch{}}})};return s(a),o.sort((e,t)=>e.localeCompare(t))}function H(t,n){let a=t.process.cwd(),{manifestDirectory:o,manifestPath:s,targetDirectory:c}=e(a,n),l=i(t,{invocationDirectory:a,targetDirectory:c,standaloneProjectRoot:c===p(a,`transcend/custom-functions`)?a:c}),u=d(o,`deno.jsonc`),f=d(o,`deno.json`),m=t.fs.existsSync(u)?u:f;return{invocationDirectory:a,targetDirectory:c,...l,manifestDirectory:o,manifestPath:s,denoConfigPath:m,relativePaths:r(t,o)}}export{F as a,B as c,N as i,A as l,H as n,R as o,z as r,L as s,V as t};
2
- //# sourceMappingURL=project-discovery-BkHpTXDx.mjs.map
1
+ import{i as e}from"./paths-J5KScOaQ.mjs";import{a as t,i as n,n as r,r as i}from"./project-discovery-CWRjlFnC.mjs";import{a}from"./readTranscendYaml-D576bvzR.mjs";import{CustomFunctionPayloadType as o,CustomFunctionType as s}from"@transcend-io/privacy-types";import{dirname as c,extname as l,isAbsolute as u,join as d,relative as f,resolve as p,sep as m}from"node:path";import h from"js-yaml";import{existsSync as g,readFileSync as _,writeFileSync as v}from"node:fs";import{decodeCodec as y}from"@transcend-io/type-utils";import*as b from"io-ts";import{isMap as x,isScalar as S,isSeq as C,parseDocument as w}from"yaml";import{Buffer as T}from"node:buffer";import{isIP as E}from"node:net";const D=64*1024,O=new Set([`DENO_CERT`,`DENO_DIR`,`DENO_TLS_CA_STORE`,`HTTP_PROXY`,`HTTPS_PROXY`,`NODE_EXTRA_CA_CERTS`,`NO_COLOR`,`NO_PROXY`,`NPM_CONFIG_REGISTRY`]);function k(e){let t=/^\[([^\]]+)\](?::(\d+))?$/u.exec(e);if(t){let e=t[2];return E(t[1])===6&&(!e||Number(e)>0&&Number(e)<=65535)}if(E(e)>0)return!0;let n=/^([^:]+):(\d+)$/u.exec(e),r=n?.[1]??e,i=n?.[2];return(!i||Number(i)>0&&Number(i)<=65535)&&r.length<=253&&r.split(`.`).every(e=>e.length>0&&e.length<=63&&/^[A-Za-z\d](?:[A-Za-z\d-]*[A-Za-z\d])?$/u.test(e))}function A(e){let t=e.env??{},n=Object.keys(t),r=n.filter(e=>!/^[A-Za-z][A-Za-z\d_]*$/u.test(e)),i=n.filter(e=>O.has(e)||e.startsWith(`DENO_`));if(r.length>0||i.length>0)throw Error([r.length>0?`Invalid environment variable names: ${r.join(`, `)}`:void 0,i.length>0?`Reserved environment variable names: ${i.join(`, `)}`:void 0].filter(Boolean).join(`. `));let a=n.filter(e=>T.byteLength(t[e])>D);if(a.length>0)throw Error(`Environment values exceed ${D} bytes: ${a.join(`, `)}`);let o=e.allowedHosts??[];if(o.length>1&&o.includes(`*`))throw Error(`allowed-hosts cannot combine "*" with specific hosts.`);let s=o.filter(e=>e!==`*`&&!k(e));if(s.length>0)throw Error(`Invalid allowed-hosts: ${s.join(`, `)}`)}const j=b.intersection([b.type({name:b.string,code:b.string}),b.partial({id:b.string,description:b.string,type:b.union([b.literal(s.Dsr),b.literal(s.General)]),"data-silo-id":b.string,"sombra-id":b.string,"sombra-auth-env":b.string,"allowed-hosts":b.array(b.string),"timeout-ms":b.number,"allow-third-party-imports":b.boolean,env:b.record(b.string,b.string),"test-payload":b.string,"test-payload-type":b.union([b.literal(o.DataPoint),b.literal(o.RequestEnricher)]),"test-payloads":b.array(b.intersection([b.type({payload:b.string}),b.partial({"payload-type":b.union([b.literal(o.DataPoint),b.literal(o.RequestEnricher)])})]))})]),M=b.type({functions:b.array(j)});function N(e){let t=p(`/`,`__custom-function-manifest__`),n=f(t,p(t,e));return n!==`..`&&!n.startsWith(`..${m}`)&&!u(n)}function P(e,t={}){let n=e.functions.map(({id:e})=>e).filter((e,t,n)=>e!==void 0&&n.indexOf(e)!==t);if(n.length>0)throw Error(`Duplicate custom function ids in manifest: ${[...new Set(n)].join(`, `)}`);let r=e.functions.map(({name:e})=>e),i=e.functions.filter(({id:e,name:t})=>e===void 0&&r.filter(e=>e===t).length>1).map(({name:e})=>e);if(i.length>0)throw Error(`Duplicate custom function names in manifest without ids: ${[...new Set(i)].join(`, `)}. Add an \`id\` field to each duplicated entry to disambiguate.`);e.functions.forEach(e=>{if(e[`test-payload`]!==void 0&&e[`test-payloads`]!==void 0)throw Error(`Custom function "${e.name}" sets both test-payload and test-payloads — use test-payloads alone to define multiple payloads.`);if(e[`test-payload-type`]!==void 0&&e[`test-payload`]===void 0)throw Error(`Custom function "${e.name}" sets test-payload-type without test-payload — set payload-type per item in test-payloads instead.`);if(e.type!==s.Dsr&&(e[`test-payload-type`]!==void 0||e[`test-payloads`]?.some(({"payload-type":e})=>e!==void 0)))throw Error(`Custom function "${e.name}" sets a DSR payload type but is not type DSR.`);[{field:`code`,path:e.code},...e[`test-payload`]===void 0?[]:[{field:`test-payload`,path:e[`test-payload`]}],...(e[`test-payloads`]??[]).map(({payload:e},t)=>({field:`test-payloads[${t}].payload`,path:e}))].forEach(({field:n,path:r})=>{if(!t.skipPathValidation&&!N(r))throw Error(`Custom function "${e.name}" has a ${n} path outside the manifest directory: ${r}`)})})}function F(e,t={}){let n=y(M,h.load(e));return P(n,t),n}function I(e,t,n){let r=c(p(e)),i=(e,t)=>{let i=p(r,t);if(n?.(i),!g(i))throw Error(`Test payload file for custom function "${e}" does not exist: ${i}`);let a=_(i,`utf-8`);try{return JSON.parse(a)}catch(t){throw Error(`Test payload file for custom function "${e}" is not valid JSON (${i}): ${t.message}`)}};return t.functions.map(e=>{A({...e.env?{env:e.env}:{},...e[`allowed-hosts`]?{allowedHosts:e[`allowed-hosts`]}:{}});let t=p(r,e.code);if(n?.(t),!g(t))throw Error(`Code file for custom function "${e.name}" does not exist: ${t}`);let a;return e[`test-payload`]===void 0?e[`test-payloads`]!==void 0&&e[`test-payloads`].length>0&&(a=e[`test-payloads`].map(t=>({payload:i(e.name,t.payload),...t[`payload-type`]===void 0?{}:{payloadType:t[`payload-type`]}}))):a=[{payload:i(e.name,e[`test-payload`]),...e[`test-payload-type`]===void 0?{}:{payloadType:e[`test-payload-type`]}}],{name:e.name,code:_(t,`utf-8`),...e.id===void 0?{}:{id:e.id},...e.description===void 0?{}:{description:e.description},...e.type===void 0?{}:{type:e.type},...e[`data-silo-id`]===void 0?{}:{dataSiloId:e[`data-silo-id`]},...e[`sombra-id`]===void 0?{}:{sombraId:e[`sombra-id`]},...e[`sombra-auth-env`]===void 0?{}:{sombraAuthEnv:e[`sombra-auth-env`]},...e[`allowed-hosts`]===void 0?{}:{allowedHosts:e[`allowed-hosts`]},...e[`timeout-ms`]===void 0?{}:{timeoutMs:e[`timeout-ms`]},...e[`allow-third-party-imports`]===void 0?{}:{allowThirdPartyImports:e[`allow-third-party-imports`]},...e.env===void 0?{}:{env:e.env},...a===void 0?{}:{testPayloads:a}}})}function L(e,t={},n){return I(e,F(a(_(e,`utf-8`),t,`Also check that there are no extra variables defined in your manifest: ${e}`)),n)}function R(e,t,n={},r){let i=F(a(h.dump({functions:[t]}),n,`Also check that there are no extra variables defined for "${t.name}" in: ${e}`)),o=i.functions[0],s=p(c(p(e)),o.code);return{config:I(e,i,r)[0],sourcePath:s}}function z(e,t){let n=w(e);if(n.errors.length>0)throw n.errors[0];let r=n.get(`functions`);if(!C(r))throw Error("Expected a `functions` list in custom function manifest");r.items.length===0&&(r.flow=!1),r.add(n.createNode(t));let i=n.toString();return F(i),i}function B(e,t){let n=w(_(e,`utf-8`)),r=n.get(`functions`);if(!C(r))throw Error(`Expected a \`functions\` list in manifest: ${e}`);let i=0;return r.items.forEach((e,r)=>{let a=t[r];if(!a||!x(e))return;let o=!1;if(a.id&&!e.has(`id`)&&(e.items.unshift(n.createPair(`id`,a.id)),o=!0),a.dataSiloId&&!e.has(`data-silo-id`)){let t=e.items.findIndex(e=>S(e.key)&&e.key.value===`id`);e.items.splice(t+1,0,n.createPair(`data-silo-id`,a.dataSiloId)),o=!0}o&&(i+=1)}),i>0&&v(e,n.toString()),i}function V(e,r){let i=n(e,r),a=t(e,i)??i,o=[],s=t=>{e.fs.readdirSync(t,{withFileTypes:!0}).forEach(n=>{if(n.name===`.git`||n.name===`.worktrees`||n.name===`node_modules`)return;let r=d(t,n.name);if(n.isDirectory()&&!n.isSymbolicLink())s(r);else if(n.isFile()){if(n.name===`transcend-functions.yml`){o.push(r);return}if([`.yml`,`.yaml`].includes(l(n.name)))try{if(e.fs.statSync(r).size>256e3)return;F(e.fs.readFileSync(r,`utf8`),{skipPathValidation:!0}),o.push(r)}catch{}}})};return s(a),o.sort((e,t)=>e.localeCompare(t))}function H(t,n){let a=t.process.cwd(),{manifestDirectory:o,manifestPath:s,targetDirectory:c}=e(a,n),l=i(t,{invocationDirectory:a,targetDirectory:c,standaloneProjectRoot:c===p(a,`transcend/custom-functions`)?a:c}),u=d(o,`deno.jsonc`),f=d(o,`deno.json`),m=t.fs.existsSync(u)?u:f;return{invocationDirectory:a,targetDirectory:c,...l,manifestDirectory:o,manifestPath:s,denoConfigPath:m,relativePaths:r(t,o)}}export{F as a,B as c,N as i,A as l,H as n,R as o,z as r,L as s,V as t};
2
+ //# sourceMappingURL=project-discovery-g29vd44a.mjs.map