apexrest 2.1.0 → 2.8.0

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 (613) hide show
  1. package/README.md +76 -101
  2. package/dist/codex-compat/.claude-plugin/marketplace.json +2 -2
  3. package/dist/codex-compat/plugins/apexrest-apex/.claude-plugin/plugin.json +5 -2
  4. package/dist/codex-compat/plugins/apexrest-apex/.codex-plugin/plugin.json +1 -1
  5. package/dist/codex-compat/plugins/apexrest-apex/.mcp.json +4 -1
  6. package/dist/codex-compat/plugins/apexrest-apex/resources/blocks/generator.json +1 -1
  7. package/dist/codex-compat/plugins/apexrest-apex/resources/blueprints/crm-26.2.yaml +1 -0
  8. package/dist/codex-compat/plugins/apexrest-apex/resources/blueprints/crm.yaml +1 -0
  9. package/dist/codex-compat/plugins/apexrest-apex/resources/blueprints/service-desk-26.2.yaml +1 -0
  10. package/dist/codex-compat/plugins/apexrest-apex/resources/blueprints/service-desk.yaml +1 -0
  11. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-alert-confirm.md +177 -0
  12. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-cancel-dialog.md +220 -0
  13. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-close-dialog.md +224 -0
  14. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-debounce-throttle.md +330 -0
  15. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-delete-notification.md +199 -0
  16. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-refresh-after-dialog.md +282 -0
  17. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-region-class.md +193 -0
  18. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-show-error-message.md +154 -0
  19. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/dynamic-actions.md +9 -1
  20. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/processes/parameters.md +32618 -0
  21. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/processes/recipes/processes-close-dialog.md +269 -0
  22. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/processes/recipes/processes-execute-code.md +201 -0
  23. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/processes/recipes/processes-form-initialization.md +239 -0
  24. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/processes/source-examples.md +938 -0
  25. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/processes.md +31 -0
  26. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/validations/recipes/validations-plsql-error.md +205 -0
  27. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/business-logic/validations.md +2 -1
  28. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/icon/recipes/button-trigger-action.md +139 -0
  29. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/icon.md +2 -1
  30. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/text/recipes/button-confirmation.md +128 -0
  31. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/text/recipes/button-server-side-condition.md +160 -0
  32. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/text/recipes/button-submit-request.md +183 -0
  33. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/text-with-icon/recipes/button-dynamic-action.md +137 -0
  34. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/text-with-icon/recipes/button-redirect-items.md +155 -0
  35. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/text-with-icon.md +3 -1
  36. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/buttons/text.md +4 -1
  37. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/catalog.md +7 -1
  38. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/checkbox-group/recipes/item-checkbox-group-columns.md +125 -0
  39. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/checkbox-group.md +2 -1
  40. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/date-picker/recipes/item-date-picker-range.md +121 -0
  41. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/date-picker.md +2 -1
  42. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/display-image/parameters.md +7998 -0
  43. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/display-image/recipes/item-display-image.md +118 -0
  44. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/display-image.md +27 -0
  45. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/geocoded-address/parameters.md +8564 -0
  46. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/geocoded-address/recipes/item-geocoded-address.md +137 -0
  47. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/geocoded-address.md +27 -0
  48. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/number-field/recipes/item-number-field-format-mask.md +123 -0
  49. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/number-field.md +2 -1
  50. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/popup-lov/recipes/item-popup-lov-display-null.md +128 -0
  51. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/popup-lov.md +2 -1
  52. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/radio-group/recipes/item-radio-group-columns.md +123 -0
  53. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/radio-group.md +2 -1
  54. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/rich-text-editor/parameters.md +8003 -0
  55. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/rich-text-editor/recipes/item-rich-text-editor.md +126 -0
  56. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/rich-text-editor.md +27 -0
  57. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/select-list/recipes/item-select-list-shared-lov.md +149 -0
  58. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/select-list.md +2 -1
  59. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/shuttle/recipes/item-shuttle-shared-lov.md +157 -0
  60. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/shuttle.md +2 -1
  61. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/switch/recipes/item-switch-custom-values.md +123 -0
  62. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/switch.md +2 -1
  63. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/textarea/recipes/item-textarea-required-length.md +123 -0
  64. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/items/textarea.md +2 -1
  65. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/breadcrumb/parameters.md +13322 -0
  66. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/breadcrumb/recipes/breadcrumb.md +137 -0
  67. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/breadcrumb/source-examples.md +20 -0
  68. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/breadcrumb.md +29 -0
  69. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-create-event-on-select.md +252 -0
  70. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-custom-navigation.md +360 -0
  71. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-custom-styling.md +156 -0
  72. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-delete-or-copy-on-click.md +271 -0
  73. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-standard-monthly.md +147 -0
  74. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-status-tracking.md +259 -0
  75. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-weekly-conference.md +153 -0
  76. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-weekly-drag-drop.md +146 -0
  77. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar/recipes/calendar-weekly-time-format-toggle.md +330 -0
  78. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/calendar.md +10 -1
  79. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/cards/recipes/cards-actions.md +193 -0
  80. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/cards.md +2 -1
  81. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-3d-effect.md +176 -0
  82. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-area-custom-legend.md +226 -0
  83. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-bar-dual-axis.md +203 -0
  84. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-bar-stacked-horizontal.md +170 -0
  85. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-bubble.md +171 -0
  86. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-custom-tooltip.md +156 -0
  87. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-dashboard-combination.md +234 -0
  88. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-data-densification.md +169 -0
  89. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-gantt.md +188 -0
  90. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-line-with-area.md +197 -0
  91. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-links.md +188 -0
  92. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-scatter.md +167 -0
  93. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-series-color.md +143 -0
  94. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-status-meter-gauge.md +142 -0
  95. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-stock.md +173 -0
  96. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart/recipes/chart-zoom-scroll.md +168 -0
  97. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/chart.md +17 -1
  98. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-calendar.md +352 -0
  99. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-cards.md +430 -0
  100. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-content-row.md +599 -0
  101. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-dashboard.md +883 -0
  102. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-directory-groups.md +514 -0
  103. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-grouped-rows.md +663 -0
  104. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-map.md +379 -0
  105. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-search-only-report.md +408 -0
  106. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search/recipes/faceted-search-timeline.md +510 -0
  107. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/faceted-search.md +10 -1
  108. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/form/recipes/form-dialog-buttons.md +247 -0
  109. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/form/recipes/sectioned-form-expense-report.md +938 -0
  110. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/form.md +3 -1
  111. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/help-text/parameters.md +11842 -0
  112. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/help-text/recipes/help-text.md +137 -0
  113. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/help-text.md +27 -0
  114. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-bbox-static.md +152 -0
  115. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-browser-location.md +138 -0
  116. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-extruded-polygons.md +155 -0
  117. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-geojson-icon-points.md +150 -0
  118. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-heat-map.md +143 -0
  119. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-lines-geojson.md +147 -0
  120. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-multi-layer-legend.md +220 -0
  121. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-points-lonlat.md +148 -0
  122. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map/recipes/map-polygons-color-scheme.md +160 -0
  123. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/map.md +10 -1
  124. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/region-display-selector/recipes/region-display-selector-icons.md +161 -0
  125. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/region-display-selector.md +2 -1
  126. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/static-content/recipes/static-content-accordion.md +152 -0
  127. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/static-content/recipes/static-content-collection-toolbar.md +205 -0
  128. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/static-content/recipes/static-content-dividers.md +155 -0
  129. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/static-content/recipes/static-content-empty-state.md +139 -0
  130. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/regions/static-content.md +5 -1
  131. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/classic-report/recipes/classic-report-notifications.md +141 -0
  132. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/classic-report/recipes/classic-report-percent-graph.md +151 -0
  133. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/classic-report/recipes/classic-report-suggestions.md +134 -0
  134. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/classic-report.md +4 -1
  135. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/contextual-info/recipes/contextual-info-row-based.md +138 -0
  136. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/contextual-info.md +2 -1
  137. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/interactive-grid/recipes/editable-grid-expense-lines.md +378 -0
  138. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/interactive-grid/recipes/interactive-grid-toolbar-download.md +200 -0
  139. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/interactive-grid.md +3 -1
  140. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/interactive-report/recipes/interactive-report-full-options.md +227 -0
  141. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/interactive-report/recipes/interactive-report-search-bar-actions.md +206 -0
  142. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/interactive-report/recipes/interactive-report-secondary.md +161 -0
  143. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/reports/interactive-report.md +4 -1
  144. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/template-components/content-row/recipes/directory-hero-search-content-row.md +476 -0
  145. package/dist/codex-compat/plugins/apexrest-apex/resources/components/documents/template-components/content-row.md +2 -1
  146. package/dist/codex-compat/plugins/apexrest-apex/resources/components/index.json +3485 -739
  147. package/dist/codex-compat/plugins/apexrest-apex/resources/components/manifest.json +245 -38
  148. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/compiler-evidence.json +2103 -422
  149. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-breadcrumb/pages/p00001-home.apx +46 -0
  150. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-breadcrumb/shared-components/breadcrumbs.apx +17 -0
  151. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-button-confirmation/pages/p00001-home.apx +60 -0
  152. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-button-dynamic-action/pages/p00001-home.apx +69 -0
  153. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-button-redirect-items/pages/p00001-home.apx +87 -0
  154. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-button-server-side-condition/pages/p00001-home.apx +90 -0
  155. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-button-submit-request/pages/p00001-home.apx +113 -0
  156. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-button-trigger-action/pages/p00001-home.apx +71 -0
  157. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-create-event-on-select/pages/p00001-home.apx +181 -0
  158. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-custom-navigation/pages/p00001-home.apx +292 -0
  159. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-custom-styling/pages/p00001-home.apx +88 -0
  160. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-delete-or-copy-on-click/pages/p00001-home.apx +200 -0
  161. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-standard-monthly/pages/p00001-home.apx +79 -0
  162. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-status-tracking/pages/p00001-home.apx +191 -0
  163. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-weekly-conference/pages/p00001-home.apx +85 -0
  164. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-weekly-drag-drop/pages/p00001-home.apx +78 -0
  165. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-calendar-weekly-time-format-toggle/pages/p00001-home.apx +260 -0
  166. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-cards-actions/pages/p00001-home.apx +125 -0
  167. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-3d-effect/pages/p00001-home.apx +108 -0
  168. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-area-custom-legend/pages/p00001-home.apx +158 -0
  169. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-bar-dual-axis/pages/p00001-home.apx +135 -0
  170. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-bar-stacked-horizontal/pages/p00001-home.apx +102 -0
  171. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-bubble/pages/p00001-home.apx +103 -0
  172. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-custom-tooltip/pages/p00001-home.apx +88 -0
  173. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-dashboard-combination/pages/p00001-home.apx +166 -0
  174. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-data-densification/pages/p00001-home.apx +101 -0
  175. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-gantt/pages/p00001-home.apx +120 -0
  176. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-line-with-area/pages/p00001-home.apx +129 -0
  177. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-links/pages/p00001-home.apx +120 -0
  178. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-scatter/pages/p00001-home.apx +99 -0
  179. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-series-color/pages/p00001-home.apx +75 -0
  180. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-status-meter-gauge/pages/p00001-home.apx +74 -0
  181. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-stock/pages/p00001-home.apx +105 -0
  182. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-chart-zoom-scroll/pages/p00001-home.apx +100 -0
  183. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-classic-report-notifications/pages/p00001-home.apx +73 -0
  184. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-classic-report-percent-graph/pages/p00001-home.apx +83 -0
  185. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-classic-report-suggestions/pages/p00001-home.apx +66 -0
  186. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-contextual-info-row-based/pages/p00001-home.apx +70 -0
  187. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-directory-hero-search-content-row/pages/p00001-home.apx +406 -0
  188. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-alert-confirm/pages/p00001-home.apx +109 -0
  189. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-cancel-dialog/pages/p00001-home.apx +48 -0
  190. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-cancel-dialog/pages/p00002-dialog.apx +98 -0
  191. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-close-dialog/pages/p00001-home.apx +48 -0
  192. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-close-dialog/pages/p00002-dialog.apx +102 -0
  193. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-debounce-throttle/pages/p00001-home.apx +262 -0
  194. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-delete-notification/pages/p00001-home.apx +129 -0
  195. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-refresh-after-dialog/pages/p00001-home.apx +109 -0
  196. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-refresh-after-dialog/pages/p00002-dialog.apx +99 -0
  197. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-region-class/pages/p00001-home.apx +125 -0
  198. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-dynamic-actions-show-error-message/pages/p00001-home.apx +86 -0
  199. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-editable-grid-expense-lines/pages/p00001-home.apx +310 -0
  200. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-calendar/pages/p00001-home.apx +284 -0
  201. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-cards/pages/p00001-home.apx +362 -0
  202. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-content-row/pages/p00001-home.apx +531 -0
  203. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-dashboard/pages/p00001-home.apx +809 -0
  204. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-directory-groups/pages/p00001-home.apx +446 -0
  205. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-grouped-rows/pages/p00001-home.apx +595 -0
  206. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-map/pages/p00001-home.apx +311 -0
  207. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-search-only-report/pages/p00001-home.apx +340 -0
  208. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-faceted-search-timeline/pages/p00001-home.apx +442 -0
  209. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-form-dialog-buttons/pages/p00001-home.apx +179 -0
  210. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-help-text/pages/p00001-home.apx +69 -0
  211. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-interactive-grid-toolbar-download/pages/p00001-home.apx +132 -0
  212. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-interactive-report-full-options/pages/p00001-home.apx +159 -0
  213. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-interactive-report-search-bar-actions/pages/p00001-home.apx +138 -0
  214. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-interactive-report-secondary/pages/p00001-home.apx +93 -0
  215. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-checkbox-group-columns/pages/p00001-home.apx +55 -0
  216. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-date-picker-range/pages/p00001-home.apx +51 -0
  217. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-display-image/pages/p00001-home.apx +50 -0
  218. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-geocoded-address/pages/p00001-home.apx +66 -0
  219. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-number-field-format-mask/pages/p00001-home.apx +53 -0
  220. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-popup-lov-display-null/pages/p00001-home.apx +58 -0
  221. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-radio-group-columns/pages/p00001-home.apx +53 -0
  222. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-rich-text-editor/pages/p00001-home.apx +56 -0
  223. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-select-list-shared-lov/pages/p00001-home.apx +48 -0
  224. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-select-list-shared-lov/shared-components/lovs.apx +25 -0
  225. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-shuttle-shared-lov/pages/p00001-home.apx +50 -0
  226. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-shuttle-shared-lov/shared-components/lovs.apx +31 -0
  227. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-switch-custom-values/pages/p00001-home.apx +53 -0
  228. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-item-textarea-required-length/pages/p00001-home.apx +53 -0
  229. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-bbox-static/pages/p00001-home.apx +82 -0
  230. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-browser-location/pages/p00001-home.apx +70 -0
  231. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-extruded-polygons/pages/p00001-home.apx +87 -0
  232. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-geojson-icon-points/pages/p00001-home.apx +82 -0
  233. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-heat-map/pages/p00001-home.apx +75 -0
  234. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-lines-geojson/pages/p00001-home.apx +79 -0
  235. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-multi-layer-legend/pages/p00001-home.apx +152 -0
  236. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-points-lonlat/pages/p00001-home.apx +80 -0
  237. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-map-polygons-color-scheme/pages/p00001-home.apx +92 -0
  238. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-processes-close-dialog/pages/p00001-home.apx +48 -0
  239. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-processes-close-dialog/pages/p00002-dialog.apx +145 -0
  240. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-processes-execute-code/pages/p00001-home.apx +130 -0
  241. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-processes-form-initialization/pages/p00001-home.apx +171 -0
  242. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-region-display-selector-icons/pages/p00001-home.apx +93 -0
  243. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-sectioned-form-expense-report/pages/p00001-home.apx +870 -0
  244. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-static-content-accordion/pages/p00001-home.apx +84 -0
  245. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-static-content-collection-toolbar/pages/p00001-home.apx +137 -0
  246. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-static-content-dividers/pages/p00001-home.apx +87 -0
  247. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-static-content-empty-state/pages/p00001-home.apx +71 -0
  248. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/internet-validations-plsql-error/pages/p00001-home.apx +134 -0
  249. package/dist/codex-compat/plugins/apexrest-apex/resources/components/recipes/registry.json +4973 -0
  250. package/dist/codex-compat/plugins/apexrest-apex/resources/patterns/docs/metrics/capacity-summary/recipes/unit-aware.md +3 -3
  251. package/dist/codex-compat/plugins/apexrest-apex/resources/patterns/index.json +408 -408
  252. package/dist/codex-compat/plugins/apexrest-apex/resources/patterns/manifest.json +8 -8
  253. package/dist/codex-compat/plugins/apexrest-apex/resources/patterns/recipes/compiler-evidence.json +3 -3
  254. package/dist/codex-compat/plugins/apexrest-apex/resources/patterns/recipes/registry.json +1 -1
  255. package/dist/codex-compat/plugins/apexrest-apex/resources/patterns/recipes/ux-extra-metrics-capacity-summary-unit-aware/pages/p00001-home.apx +2 -2
  256. package/dist/codex-compat/plugins/apexrest-apex/resources/policy/deployment-safety.md +197 -20
  257. package/dist/codex-compat/plugins/apexrest-apex/resources/references/26.2/guides/upgrade-audit.md +13 -1
  258. package/dist/codex-compat/plugins/apexrest-apex/resources/references/26.2/guides.json +1 -1
  259. package/dist/codex-compat/plugins/apexrest-apex/resources/references/26.2/index.json +3 -3
  260. package/dist/codex-compat/plugins/apexrest-apex/resources/references/26.2/oracle-snapshot.json +2 -2
  261. package/dist/codex-compat/plugins/apexrest-apex/resources/references/26.2/search.json +1 -1
  262. package/dist/codex-compat/plugins/apexrest-apex/resources/scaffold/observations.sql +126 -0
  263. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-blueprint.schema.json +17 -17
  264. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-contract.schema.json +9 -2
  265. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-entity.schema.json +5 -3
  266. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-field.schema.json +4 -1
  267. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-instance.schema.json +2 -8
  268. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-parameters.schema.json +1 -5
  269. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-plan.schema.json +102 -5
  270. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-shared-resource.schema.json +82 -0
  271. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/composer-state.schema.json +88 -0
  272. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/deploy-plan.schema.json +75 -3
  273. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/operations.schema.json +488 -17
  274. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/policy.schema.json +1 -1
  275. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/project.schema.json +61 -5
  276. package/dist/codex-compat/plugins/apexrest-apex/resources/schemas/sync-state.schema.json +8 -0
  277. package/dist/codex-compat/plugins/apexrest-apex/resources/templates/blank-app/application/application.apx +1 -0
  278. package/dist/codex-compat/plugins/apexrest-apex/resources/toolchains/sources.lock.json +1 -1
  279. package/dist/codex-compat/plugins/apexrest-apex/runtime/apexrest.mjs +154 -52
  280. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-26MTCOZK.mjs +239 -0
  281. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-47GDU535.mjs +1020 -0
  282. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-4LEHTNYH.mjs +252 -0
  283. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-4MIZ34V4.mjs +280 -0
  284. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-6JZB7NDZ.mjs +33342 -0
  285. package/dist/{runtime/chunk-U7MVLA3R.mjs → codex-compat/plugins/apexrest-apex/runtime/chunk-CI5IU2PI.mjs} +433 -181
  286. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-JZ5FIGSS.mjs → chunk-DJPW35KJ.mjs} +5 -5
  287. package/dist/{runtime/chunk-BLB5JLWO.mjs → codex-compat/plugins/apexrest-apex/runtime/chunk-GHVRIHN6.mjs} +834 -4808
  288. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-JJYHZOQR.mjs +6608 -0
  289. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-AESZGFM2.mjs → chunk-LCNHRIKE.mjs} +6 -3
  290. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-YEGSGHTV.mjs → chunk-LIG5PZ4K.mjs} +44 -12
  291. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-2YXH4VEB.mjs → chunk-LIGDVE6F.mjs} +438 -154
  292. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-WK445BKL.mjs → chunk-M5EC4OUI.mjs} +116 -41
  293. package/dist/{runtime/chunk-TE5VTEAH.mjs → codex-compat/plugins/apexrest-apex/runtime/chunk-MPKKOQVI.mjs} +349 -446
  294. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-N3KQBIVW.mjs +252 -0
  295. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-PFOHMLO4.mjs +141 -0
  296. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-PNGZYZE7.mjs +4703 -0
  297. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-NBA54QYW.mjs → chunk-PS2GKOR2.mjs} +9 -6
  298. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-T3UX6AQO.mjs → chunk-TBHIU7PZ.mjs} +170 -3432
  299. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-TDM3E2NK.mjs +161 -0
  300. package/dist/{runtime/chunk-ZSDDYNF5.mjs → codex-compat/plugins/apexrest-apex/runtime/chunk-UKXRUJT4.mjs} +7 -5
  301. package/dist/codex-compat/plugins/apexrest-apex/runtime/{chunk-BZZ3RV7L.mjs → chunk-XJ7FW7XH.mjs} +4 -4
  302. package/dist/codex-compat/plugins/apexrest-apex/runtime/mcp.mjs +1 -1
  303. package/dist/codex-compat/plugins/apexrest-apex/runtime/preview-oracle-worker.mjs +57 -0
  304. package/dist/codex-compat/plugins/apexrest-apex/skills/apexrest-apexlang/SKILL.md +11 -13
  305. package/dist/codex-compat/plugins/apexrest-apex/skills/apexrest-oracle-sync/SKILL.md +5 -1
  306. package/dist/codex-compat/plugins/apexrest-apex/skills/apexrest-oracle-sync/references/oracle-skills.md +19 -0
  307. package/dist/codex-compat/plugins/apexrest-apex/skills/apexrest-work/SKILL.md +14 -11
  308. package/dist/codex-compat/plugins/apexrest-apex/skills/apexrest-work/references/peer-review.md +12 -0
  309. package/dist/codex-compat/plugins/apexrest-apex/skills/apexrest-work/references/scaffold.md +115 -0
  310. package/dist/codex-compat/plugins/apexrest-apex/skills/apexrest-work/references/upgrade.md +11 -0
  311. package/dist/resources/blocks/generator.json +1 -1
  312. package/dist/resources/blueprints/crm-26.2.yaml +1 -0
  313. package/dist/resources/blueprints/crm.yaml +1 -0
  314. package/dist/resources/blueprints/service-desk-26.2.yaml +1 -0
  315. package/dist/resources/blueprints/service-desk.yaml +1 -0
  316. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-alert-confirm.md +177 -0
  317. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-cancel-dialog.md +220 -0
  318. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-close-dialog.md +224 -0
  319. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-debounce-throttle.md +330 -0
  320. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-delete-notification.md +199 -0
  321. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-refresh-after-dialog.md +282 -0
  322. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-region-class.md +193 -0
  323. package/dist/resources/components/documents/business-logic/dynamic-actions/recipes/dynamic-actions-show-error-message.md +154 -0
  324. package/dist/resources/components/documents/business-logic/dynamic-actions.md +9 -1
  325. package/dist/resources/components/documents/business-logic/processes/parameters.md +32618 -0
  326. package/dist/resources/components/documents/business-logic/processes/recipes/processes-close-dialog.md +269 -0
  327. package/dist/resources/components/documents/business-logic/processes/recipes/processes-execute-code.md +201 -0
  328. package/dist/resources/components/documents/business-logic/processes/recipes/processes-form-initialization.md +239 -0
  329. package/dist/resources/components/documents/business-logic/processes/source-examples.md +938 -0
  330. package/dist/resources/components/documents/business-logic/processes.md +31 -0
  331. package/dist/resources/components/documents/business-logic/validations/recipes/validations-plsql-error.md +205 -0
  332. package/dist/resources/components/documents/business-logic/validations.md +2 -1
  333. package/dist/resources/components/documents/buttons/icon/recipes/button-trigger-action.md +139 -0
  334. package/dist/resources/components/documents/buttons/icon.md +2 -1
  335. package/dist/resources/components/documents/buttons/text/recipes/button-confirmation.md +128 -0
  336. package/dist/resources/components/documents/buttons/text/recipes/button-server-side-condition.md +160 -0
  337. package/dist/resources/components/documents/buttons/text/recipes/button-submit-request.md +183 -0
  338. package/dist/resources/components/documents/buttons/text-with-icon/recipes/button-dynamic-action.md +137 -0
  339. package/dist/resources/components/documents/buttons/text-with-icon/recipes/button-redirect-items.md +155 -0
  340. package/dist/resources/components/documents/buttons/text-with-icon.md +3 -1
  341. package/dist/resources/components/documents/buttons/text.md +4 -1
  342. package/dist/resources/components/documents/catalog.md +7 -1
  343. package/dist/resources/components/documents/items/checkbox-group/recipes/item-checkbox-group-columns.md +125 -0
  344. package/dist/resources/components/documents/items/checkbox-group.md +2 -1
  345. package/dist/resources/components/documents/items/date-picker/recipes/item-date-picker-range.md +121 -0
  346. package/dist/resources/components/documents/items/date-picker.md +2 -1
  347. package/dist/resources/components/documents/items/display-image/parameters.md +7998 -0
  348. package/dist/resources/components/documents/items/display-image/recipes/item-display-image.md +118 -0
  349. package/dist/resources/components/documents/items/display-image.md +27 -0
  350. package/dist/resources/components/documents/items/geocoded-address/parameters.md +8564 -0
  351. package/dist/resources/components/documents/items/geocoded-address/recipes/item-geocoded-address.md +137 -0
  352. package/dist/resources/components/documents/items/geocoded-address.md +27 -0
  353. package/dist/resources/components/documents/items/number-field/recipes/item-number-field-format-mask.md +123 -0
  354. package/dist/resources/components/documents/items/number-field.md +2 -1
  355. package/dist/resources/components/documents/items/popup-lov/recipes/item-popup-lov-display-null.md +128 -0
  356. package/dist/resources/components/documents/items/popup-lov.md +2 -1
  357. package/dist/resources/components/documents/items/radio-group/recipes/item-radio-group-columns.md +123 -0
  358. package/dist/resources/components/documents/items/radio-group.md +2 -1
  359. package/dist/resources/components/documents/items/rich-text-editor/parameters.md +8003 -0
  360. package/dist/resources/components/documents/items/rich-text-editor/recipes/item-rich-text-editor.md +126 -0
  361. package/dist/resources/components/documents/items/rich-text-editor.md +27 -0
  362. package/dist/resources/components/documents/items/select-list/recipes/item-select-list-shared-lov.md +149 -0
  363. package/dist/resources/components/documents/items/select-list.md +2 -1
  364. package/dist/resources/components/documents/items/shuttle/recipes/item-shuttle-shared-lov.md +157 -0
  365. package/dist/resources/components/documents/items/shuttle.md +2 -1
  366. package/dist/resources/components/documents/items/switch/recipes/item-switch-custom-values.md +123 -0
  367. package/dist/resources/components/documents/items/switch.md +2 -1
  368. package/dist/resources/components/documents/items/textarea/recipes/item-textarea-required-length.md +123 -0
  369. package/dist/resources/components/documents/items/textarea.md +2 -1
  370. package/dist/resources/components/documents/regions/breadcrumb/parameters.md +13322 -0
  371. package/dist/resources/components/documents/regions/breadcrumb/recipes/breadcrumb.md +137 -0
  372. package/dist/resources/components/documents/regions/breadcrumb/source-examples.md +20 -0
  373. package/dist/resources/components/documents/regions/breadcrumb.md +29 -0
  374. package/dist/resources/components/documents/regions/calendar/recipes/calendar-create-event-on-select.md +252 -0
  375. package/dist/resources/components/documents/regions/calendar/recipes/calendar-custom-navigation.md +360 -0
  376. package/dist/resources/components/documents/regions/calendar/recipes/calendar-custom-styling.md +156 -0
  377. package/dist/resources/components/documents/regions/calendar/recipes/calendar-delete-or-copy-on-click.md +271 -0
  378. package/dist/resources/components/documents/regions/calendar/recipes/calendar-standard-monthly.md +147 -0
  379. package/dist/resources/components/documents/regions/calendar/recipes/calendar-status-tracking.md +259 -0
  380. package/dist/resources/components/documents/regions/calendar/recipes/calendar-weekly-conference.md +153 -0
  381. package/dist/resources/components/documents/regions/calendar/recipes/calendar-weekly-drag-drop.md +146 -0
  382. package/dist/resources/components/documents/regions/calendar/recipes/calendar-weekly-time-format-toggle.md +330 -0
  383. package/dist/resources/components/documents/regions/calendar.md +10 -1
  384. package/dist/resources/components/documents/regions/cards/recipes/cards-actions.md +193 -0
  385. package/dist/resources/components/documents/regions/cards.md +2 -1
  386. package/dist/resources/components/documents/regions/chart/recipes/chart-3d-effect.md +176 -0
  387. package/dist/resources/components/documents/regions/chart/recipes/chart-area-custom-legend.md +226 -0
  388. package/dist/resources/components/documents/regions/chart/recipes/chart-bar-dual-axis.md +203 -0
  389. package/dist/resources/components/documents/regions/chart/recipes/chart-bar-stacked-horizontal.md +170 -0
  390. package/dist/resources/components/documents/regions/chart/recipes/chart-bubble.md +171 -0
  391. package/dist/resources/components/documents/regions/chart/recipes/chart-custom-tooltip.md +156 -0
  392. package/dist/resources/components/documents/regions/chart/recipes/chart-dashboard-combination.md +234 -0
  393. package/dist/resources/components/documents/regions/chart/recipes/chart-data-densification.md +169 -0
  394. package/dist/resources/components/documents/regions/chart/recipes/chart-gantt.md +188 -0
  395. package/dist/resources/components/documents/regions/chart/recipes/chart-line-with-area.md +197 -0
  396. package/dist/resources/components/documents/regions/chart/recipes/chart-links.md +188 -0
  397. package/dist/resources/components/documents/regions/chart/recipes/chart-scatter.md +167 -0
  398. package/dist/resources/components/documents/regions/chart/recipes/chart-series-color.md +143 -0
  399. package/dist/resources/components/documents/regions/chart/recipes/chart-status-meter-gauge.md +142 -0
  400. package/dist/resources/components/documents/regions/chart/recipes/chart-stock.md +173 -0
  401. package/dist/resources/components/documents/regions/chart/recipes/chart-zoom-scroll.md +168 -0
  402. package/dist/resources/components/documents/regions/chart.md +17 -1
  403. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-calendar.md +352 -0
  404. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-cards.md +430 -0
  405. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-content-row.md +599 -0
  406. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-dashboard.md +883 -0
  407. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-directory-groups.md +514 -0
  408. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-grouped-rows.md +663 -0
  409. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-map.md +379 -0
  410. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-search-only-report.md +408 -0
  411. package/dist/resources/components/documents/regions/faceted-search/recipes/faceted-search-timeline.md +510 -0
  412. package/dist/resources/components/documents/regions/faceted-search.md +10 -1
  413. package/dist/resources/components/documents/regions/form/recipes/form-dialog-buttons.md +247 -0
  414. package/dist/resources/components/documents/regions/form/recipes/sectioned-form-expense-report.md +938 -0
  415. package/dist/resources/components/documents/regions/form.md +3 -1
  416. package/dist/resources/components/documents/regions/help-text/parameters.md +11842 -0
  417. package/dist/resources/components/documents/regions/help-text/recipes/help-text.md +137 -0
  418. package/dist/resources/components/documents/regions/help-text.md +27 -0
  419. package/dist/resources/components/documents/regions/map/recipes/map-bbox-static.md +152 -0
  420. package/dist/resources/components/documents/regions/map/recipes/map-browser-location.md +138 -0
  421. package/dist/resources/components/documents/regions/map/recipes/map-extruded-polygons.md +155 -0
  422. package/dist/resources/components/documents/regions/map/recipes/map-geojson-icon-points.md +150 -0
  423. package/dist/resources/components/documents/regions/map/recipes/map-heat-map.md +143 -0
  424. package/dist/resources/components/documents/regions/map/recipes/map-lines-geojson.md +147 -0
  425. package/dist/resources/components/documents/regions/map/recipes/map-multi-layer-legend.md +220 -0
  426. package/dist/resources/components/documents/regions/map/recipes/map-points-lonlat.md +148 -0
  427. package/dist/resources/components/documents/regions/map/recipes/map-polygons-color-scheme.md +160 -0
  428. package/dist/resources/components/documents/regions/map.md +10 -1
  429. package/dist/resources/components/documents/regions/region-display-selector/recipes/region-display-selector-icons.md +161 -0
  430. package/dist/resources/components/documents/regions/region-display-selector.md +2 -1
  431. package/dist/resources/components/documents/regions/static-content/recipes/static-content-accordion.md +152 -0
  432. package/dist/resources/components/documents/regions/static-content/recipes/static-content-collection-toolbar.md +205 -0
  433. package/dist/resources/components/documents/regions/static-content/recipes/static-content-dividers.md +155 -0
  434. package/dist/resources/components/documents/regions/static-content/recipes/static-content-empty-state.md +139 -0
  435. package/dist/resources/components/documents/regions/static-content.md +5 -1
  436. package/dist/resources/components/documents/reports/classic-report/recipes/classic-report-notifications.md +141 -0
  437. package/dist/resources/components/documents/reports/classic-report/recipes/classic-report-percent-graph.md +151 -0
  438. package/dist/resources/components/documents/reports/classic-report/recipes/classic-report-suggestions.md +134 -0
  439. package/dist/resources/components/documents/reports/classic-report.md +4 -1
  440. package/dist/resources/components/documents/reports/contextual-info/recipes/contextual-info-row-based.md +138 -0
  441. package/dist/resources/components/documents/reports/contextual-info.md +2 -1
  442. package/dist/resources/components/documents/reports/interactive-grid/recipes/editable-grid-expense-lines.md +378 -0
  443. package/dist/resources/components/documents/reports/interactive-grid/recipes/interactive-grid-toolbar-download.md +200 -0
  444. package/dist/resources/components/documents/reports/interactive-grid.md +3 -1
  445. package/dist/resources/components/documents/reports/interactive-report/recipes/interactive-report-full-options.md +227 -0
  446. package/dist/resources/components/documents/reports/interactive-report/recipes/interactive-report-search-bar-actions.md +206 -0
  447. package/dist/resources/components/documents/reports/interactive-report/recipes/interactive-report-secondary.md +161 -0
  448. package/dist/resources/components/documents/reports/interactive-report.md +4 -1
  449. package/dist/resources/components/documents/template-components/content-row/recipes/directory-hero-search-content-row.md +476 -0
  450. package/dist/resources/components/documents/template-components/content-row.md +2 -1
  451. package/dist/resources/components/index.json +3485 -739
  452. package/dist/resources/components/manifest.json +245 -38
  453. package/dist/resources/components/recipes/compiler-evidence.json +2103 -422
  454. package/dist/resources/components/recipes/internet-breadcrumb/pages/p00001-home.apx +46 -0
  455. package/dist/resources/components/recipes/internet-breadcrumb/shared-components/breadcrumbs.apx +17 -0
  456. package/dist/resources/components/recipes/internet-button-confirmation/pages/p00001-home.apx +60 -0
  457. package/dist/resources/components/recipes/internet-button-dynamic-action/pages/p00001-home.apx +69 -0
  458. package/dist/resources/components/recipes/internet-button-redirect-items/pages/p00001-home.apx +87 -0
  459. package/dist/resources/components/recipes/internet-button-server-side-condition/pages/p00001-home.apx +90 -0
  460. package/dist/resources/components/recipes/internet-button-submit-request/pages/p00001-home.apx +113 -0
  461. package/dist/resources/components/recipes/internet-button-trigger-action/pages/p00001-home.apx +71 -0
  462. package/dist/resources/components/recipes/internet-calendar-create-event-on-select/pages/p00001-home.apx +181 -0
  463. package/dist/resources/components/recipes/internet-calendar-custom-navigation/pages/p00001-home.apx +292 -0
  464. package/dist/resources/components/recipes/internet-calendar-custom-styling/pages/p00001-home.apx +88 -0
  465. package/dist/resources/components/recipes/internet-calendar-delete-or-copy-on-click/pages/p00001-home.apx +200 -0
  466. package/dist/resources/components/recipes/internet-calendar-standard-monthly/pages/p00001-home.apx +79 -0
  467. package/dist/resources/components/recipes/internet-calendar-status-tracking/pages/p00001-home.apx +191 -0
  468. package/dist/resources/components/recipes/internet-calendar-weekly-conference/pages/p00001-home.apx +85 -0
  469. package/dist/resources/components/recipes/internet-calendar-weekly-drag-drop/pages/p00001-home.apx +78 -0
  470. package/dist/resources/components/recipes/internet-calendar-weekly-time-format-toggle/pages/p00001-home.apx +260 -0
  471. package/dist/resources/components/recipes/internet-cards-actions/pages/p00001-home.apx +125 -0
  472. package/dist/resources/components/recipes/internet-chart-3d-effect/pages/p00001-home.apx +108 -0
  473. package/dist/resources/components/recipes/internet-chart-area-custom-legend/pages/p00001-home.apx +158 -0
  474. package/dist/resources/components/recipes/internet-chart-bar-dual-axis/pages/p00001-home.apx +135 -0
  475. package/dist/resources/components/recipes/internet-chart-bar-stacked-horizontal/pages/p00001-home.apx +102 -0
  476. package/dist/resources/components/recipes/internet-chart-bubble/pages/p00001-home.apx +103 -0
  477. package/dist/resources/components/recipes/internet-chart-custom-tooltip/pages/p00001-home.apx +88 -0
  478. package/dist/resources/components/recipes/internet-chart-dashboard-combination/pages/p00001-home.apx +166 -0
  479. package/dist/resources/components/recipes/internet-chart-data-densification/pages/p00001-home.apx +101 -0
  480. package/dist/resources/components/recipes/internet-chart-gantt/pages/p00001-home.apx +120 -0
  481. package/dist/resources/components/recipes/internet-chart-line-with-area/pages/p00001-home.apx +129 -0
  482. package/dist/resources/components/recipes/internet-chart-links/pages/p00001-home.apx +120 -0
  483. package/dist/resources/components/recipes/internet-chart-scatter/pages/p00001-home.apx +99 -0
  484. package/dist/resources/components/recipes/internet-chart-series-color/pages/p00001-home.apx +75 -0
  485. package/dist/resources/components/recipes/internet-chart-status-meter-gauge/pages/p00001-home.apx +74 -0
  486. package/dist/resources/components/recipes/internet-chart-stock/pages/p00001-home.apx +105 -0
  487. package/dist/resources/components/recipes/internet-chart-zoom-scroll/pages/p00001-home.apx +100 -0
  488. package/dist/resources/components/recipes/internet-classic-report-notifications/pages/p00001-home.apx +73 -0
  489. package/dist/resources/components/recipes/internet-classic-report-percent-graph/pages/p00001-home.apx +83 -0
  490. package/dist/resources/components/recipes/internet-classic-report-suggestions/pages/p00001-home.apx +66 -0
  491. package/dist/resources/components/recipes/internet-contextual-info-row-based/pages/p00001-home.apx +70 -0
  492. package/dist/resources/components/recipes/internet-directory-hero-search-content-row/pages/p00001-home.apx +406 -0
  493. package/dist/resources/components/recipes/internet-dynamic-actions-alert-confirm/pages/p00001-home.apx +109 -0
  494. package/dist/resources/components/recipes/internet-dynamic-actions-cancel-dialog/pages/p00001-home.apx +48 -0
  495. package/dist/resources/components/recipes/internet-dynamic-actions-cancel-dialog/pages/p00002-dialog.apx +98 -0
  496. package/dist/resources/components/recipes/internet-dynamic-actions-close-dialog/pages/p00001-home.apx +48 -0
  497. package/dist/resources/components/recipes/internet-dynamic-actions-close-dialog/pages/p00002-dialog.apx +102 -0
  498. package/dist/resources/components/recipes/internet-dynamic-actions-debounce-throttle/pages/p00001-home.apx +262 -0
  499. package/dist/resources/components/recipes/internet-dynamic-actions-delete-notification/pages/p00001-home.apx +129 -0
  500. package/dist/resources/components/recipes/internet-dynamic-actions-refresh-after-dialog/pages/p00001-home.apx +109 -0
  501. package/dist/resources/components/recipes/internet-dynamic-actions-refresh-after-dialog/pages/p00002-dialog.apx +99 -0
  502. package/dist/resources/components/recipes/internet-dynamic-actions-region-class/pages/p00001-home.apx +125 -0
  503. package/dist/resources/components/recipes/internet-dynamic-actions-show-error-message/pages/p00001-home.apx +86 -0
  504. package/dist/resources/components/recipes/internet-editable-grid-expense-lines/pages/p00001-home.apx +310 -0
  505. package/dist/resources/components/recipes/internet-faceted-search-calendar/pages/p00001-home.apx +284 -0
  506. package/dist/resources/components/recipes/internet-faceted-search-cards/pages/p00001-home.apx +362 -0
  507. package/dist/resources/components/recipes/internet-faceted-search-content-row/pages/p00001-home.apx +531 -0
  508. package/dist/resources/components/recipes/internet-faceted-search-dashboard/pages/p00001-home.apx +809 -0
  509. package/dist/resources/components/recipes/internet-faceted-search-directory-groups/pages/p00001-home.apx +446 -0
  510. package/dist/resources/components/recipes/internet-faceted-search-grouped-rows/pages/p00001-home.apx +595 -0
  511. package/dist/resources/components/recipes/internet-faceted-search-map/pages/p00001-home.apx +311 -0
  512. package/dist/resources/components/recipes/internet-faceted-search-search-only-report/pages/p00001-home.apx +340 -0
  513. package/dist/resources/components/recipes/internet-faceted-search-timeline/pages/p00001-home.apx +442 -0
  514. package/dist/resources/components/recipes/internet-form-dialog-buttons/pages/p00001-home.apx +179 -0
  515. package/dist/resources/components/recipes/internet-help-text/pages/p00001-home.apx +69 -0
  516. package/dist/resources/components/recipes/internet-interactive-grid-toolbar-download/pages/p00001-home.apx +132 -0
  517. package/dist/resources/components/recipes/internet-interactive-report-full-options/pages/p00001-home.apx +159 -0
  518. package/dist/resources/components/recipes/internet-interactive-report-search-bar-actions/pages/p00001-home.apx +138 -0
  519. package/dist/resources/components/recipes/internet-interactive-report-secondary/pages/p00001-home.apx +93 -0
  520. package/dist/resources/components/recipes/internet-item-checkbox-group-columns/pages/p00001-home.apx +55 -0
  521. package/dist/resources/components/recipes/internet-item-date-picker-range/pages/p00001-home.apx +51 -0
  522. package/dist/resources/components/recipes/internet-item-display-image/pages/p00001-home.apx +50 -0
  523. package/dist/resources/components/recipes/internet-item-geocoded-address/pages/p00001-home.apx +66 -0
  524. package/dist/resources/components/recipes/internet-item-number-field-format-mask/pages/p00001-home.apx +53 -0
  525. package/dist/resources/components/recipes/internet-item-popup-lov-display-null/pages/p00001-home.apx +58 -0
  526. package/dist/resources/components/recipes/internet-item-radio-group-columns/pages/p00001-home.apx +53 -0
  527. package/dist/resources/components/recipes/internet-item-rich-text-editor/pages/p00001-home.apx +56 -0
  528. package/dist/resources/components/recipes/internet-item-select-list-shared-lov/pages/p00001-home.apx +48 -0
  529. package/dist/resources/components/recipes/internet-item-select-list-shared-lov/shared-components/lovs.apx +25 -0
  530. package/dist/resources/components/recipes/internet-item-shuttle-shared-lov/pages/p00001-home.apx +50 -0
  531. package/dist/resources/components/recipes/internet-item-shuttle-shared-lov/shared-components/lovs.apx +31 -0
  532. package/dist/resources/components/recipes/internet-item-switch-custom-values/pages/p00001-home.apx +53 -0
  533. package/dist/resources/components/recipes/internet-item-textarea-required-length/pages/p00001-home.apx +53 -0
  534. package/dist/resources/components/recipes/internet-map-bbox-static/pages/p00001-home.apx +82 -0
  535. package/dist/resources/components/recipes/internet-map-browser-location/pages/p00001-home.apx +70 -0
  536. package/dist/resources/components/recipes/internet-map-extruded-polygons/pages/p00001-home.apx +87 -0
  537. package/dist/resources/components/recipes/internet-map-geojson-icon-points/pages/p00001-home.apx +82 -0
  538. package/dist/resources/components/recipes/internet-map-heat-map/pages/p00001-home.apx +75 -0
  539. package/dist/resources/components/recipes/internet-map-lines-geojson/pages/p00001-home.apx +79 -0
  540. package/dist/resources/components/recipes/internet-map-multi-layer-legend/pages/p00001-home.apx +152 -0
  541. package/dist/resources/components/recipes/internet-map-points-lonlat/pages/p00001-home.apx +80 -0
  542. package/dist/resources/components/recipes/internet-map-polygons-color-scheme/pages/p00001-home.apx +92 -0
  543. package/dist/resources/components/recipes/internet-processes-close-dialog/pages/p00001-home.apx +48 -0
  544. package/dist/resources/components/recipes/internet-processes-close-dialog/pages/p00002-dialog.apx +145 -0
  545. package/dist/resources/components/recipes/internet-processes-execute-code/pages/p00001-home.apx +130 -0
  546. package/dist/resources/components/recipes/internet-processes-form-initialization/pages/p00001-home.apx +171 -0
  547. package/dist/resources/components/recipes/internet-region-display-selector-icons/pages/p00001-home.apx +93 -0
  548. package/dist/resources/components/recipes/internet-sectioned-form-expense-report/pages/p00001-home.apx +870 -0
  549. package/dist/resources/components/recipes/internet-static-content-accordion/pages/p00001-home.apx +84 -0
  550. package/dist/resources/components/recipes/internet-static-content-collection-toolbar/pages/p00001-home.apx +137 -0
  551. package/dist/resources/components/recipes/internet-static-content-dividers/pages/p00001-home.apx +87 -0
  552. package/dist/resources/components/recipes/internet-static-content-empty-state/pages/p00001-home.apx +71 -0
  553. package/dist/resources/components/recipes/internet-validations-plsql-error/pages/p00001-home.apx +134 -0
  554. package/dist/resources/components/recipes/registry.json +4973 -0
  555. package/dist/resources/patterns/docs/metrics/capacity-summary/recipes/unit-aware.md +3 -3
  556. package/dist/resources/patterns/index.json +408 -408
  557. package/dist/resources/patterns/manifest.json +8 -8
  558. package/dist/resources/patterns/recipes/compiler-evidence.json +3 -3
  559. package/dist/resources/patterns/recipes/registry.json +1 -1
  560. package/dist/resources/patterns/recipes/ux-extra-metrics-capacity-summary-unit-aware/pages/p00001-home.apx +2 -2
  561. package/dist/resources/policy/deployment-safety.md +197 -20
  562. package/dist/resources/references/26.2/guides/upgrade-audit.md +13 -1
  563. package/dist/resources/references/26.2/guides.json +1 -1
  564. package/dist/resources/references/26.2/index.json +3 -3
  565. package/dist/resources/references/26.2/oracle-snapshot.json +2 -2
  566. package/dist/resources/references/26.2/search.json +1 -1
  567. package/dist/resources/scaffold/observations.sql +126 -0
  568. package/dist/resources/schemas/composer-blueprint.schema.json +17 -17
  569. package/dist/resources/schemas/composer-contract.schema.json +9 -2
  570. package/dist/resources/schemas/composer-entity.schema.json +5 -3
  571. package/dist/resources/schemas/composer-field.schema.json +4 -1
  572. package/dist/resources/schemas/composer-instance.schema.json +2 -8
  573. package/dist/resources/schemas/composer-parameters.schema.json +1 -5
  574. package/dist/resources/schemas/composer-plan.schema.json +102 -5
  575. package/dist/resources/schemas/composer-shared-resource.schema.json +82 -0
  576. package/dist/resources/schemas/composer-state.schema.json +88 -0
  577. package/dist/resources/schemas/deploy-plan.schema.json +75 -3
  578. package/dist/resources/schemas/operations.schema.json +488 -17
  579. package/dist/resources/schemas/policy.schema.json +1 -1
  580. package/dist/resources/schemas/project.schema.json +61 -5
  581. package/dist/resources/schemas/sync-state.schema.json +8 -0
  582. package/dist/resources/templates/blank-app/application/application.apx +1 -0
  583. package/dist/resources/toolchains/sources.lock.json +1 -1
  584. package/dist/runtime/apexrest.mjs +154 -52
  585. package/dist/runtime/chunk-26MTCOZK.mjs +239 -0
  586. package/dist/runtime/chunk-47GDU535.mjs +1020 -0
  587. package/dist/runtime/chunk-4LEHTNYH.mjs +252 -0
  588. package/dist/runtime/chunk-4MIZ34V4.mjs +280 -0
  589. package/dist/runtime/chunk-6JZB7NDZ.mjs +33342 -0
  590. package/dist/{codex-compat/plugins/apexrest-apex/runtime/chunk-U7MVLA3R.mjs → runtime/chunk-CI5IU2PI.mjs} +433 -181
  591. package/dist/runtime/{chunk-JZ5FIGSS.mjs → chunk-DJPW35KJ.mjs} +5 -5
  592. package/dist/{codex-compat/plugins/apexrest-apex/runtime/chunk-BLB5JLWO.mjs → runtime/chunk-GHVRIHN6.mjs} +834 -4808
  593. package/dist/runtime/chunk-JJYHZOQR.mjs +6608 -0
  594. package/dist/runtime/{chunk-AESZGFM2.mjs → chunk-LCNHRIKE.mjs} +6 -3
  595. package/dist/runtime/{chunk-YEGSGHTV.mjs → chunk-LIG5PZ4K.mjs} +44 -12
  596. package/dist/runtime/{chunk-2YXH4VEB.mjs → chunk-LIGDVE6F.mjs} +438 -154
  597. package/dist/runtime/{chunk-WK445BKL.mjs → chunk-M5EC4OUI.mjs} +116 -41
  598. package/dist/{codex-compat/plugins/apexrest-apex/runtime/chunk-TE5VTEAH.mjs → runtime/chunk-MPKKOQVI.mjs} +349 -446
  599. package/dist/runtime/chunk-N3KQBIVW.mjs +252 -0
  600. package/dist/runtime/chunk-PFOHMLO4.mjs +141 -0
  601. package/dist/runtime/chunk-PNGZYZE7.mjs +4703 -0
  602. package/dist/runtime/{chunk-NBA54QYW.mjs → chunk-PS2GKOR2.mjs} +9 -6
  603. package/dist/runtime/{chunk-T3UX6AQO.mjs → chunk-TBHIU7PZ.mjs} +170 -3432
  604. package/dist/runtime/chunk-TDM3E2NK.mjs +161 -0
  605. package/dist/{codex-compat/plugins/apexrest-apex/runtime/chunk-ZSDDYNF5.mjs → runtime/chunk-UKXRUJT4.mjs} +7 -5
  606. package/dist/runtime/{chunk-BZZ3RV7L.mjs → chunk-XJ7FW7XH.mjs} +4 -4
  607. package/dist/runtime/mcp.mjs +1 -1
  608. package/dist/runtime/preview-oracle-worker.mjs +57 -0
  609. package/package.json +8 -5
  610. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-A7ESH6F5.mjs +0 -31
  611. package/dist/codex-compat/plugins/apexrest-apex/runtime/chunk-I5KYBPSK.mjs +0 -419
  612. package/dist/runtime/chunk-A7ESH6F5.mjs +0 -31
  613. package/dist/runtime/chunk-I5KYBPSK.mjs +0 -419
@@ -0,0 +1,4703 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ isProductionTarget,
4
+ loadProject,
5
+ managedHome,
6
+ parse,
7
+ refName,
8
+ relativePath,
9
+ targetDigest
10
+ } from "./chunk-LIG5PZ4K.mjs";
11
+ import {
12
+ closeSqlclReadScope,
13
+ runPooledSqlcl
14
+ } from "./chunk-4LEHTNYH.mjs";
15
+ import {
16
+ atomicWrite,
17
+ canonical,
18
+ contained,
19
+ exists,
20
+ hash,
21
+ inventory,
22
+ readJson,
23
+ withLock,
24
+ writeJson
25
+ } from "./chunk-26MTCOZK.mjs";
26
+ import {
27
+ SQLCL_READ_TIMEOUT_MS,
28
+ SQLCL_WRITE_TIMEOUT_MS,
29
+ SqlclMcpClient,
30
+ emitSqlclTiming,
31
+ executionTiming,
32
+ mcpCallOptions,
33
+ mcpFailure,
34
+ mcpResult,
35
+ recordSqlclTiming,
36
+ recordStatementTimings,
37
+ runProcess,
38
+ runSqlclMcp
39
+ } from "./chunk-MPKKOQVI.mjs";
40
+ import {
41
+ Fault,
42
+ __export,
43
+ external_exports
44
+ } from "./chunk-CI5IU2PI.mjs";
45
+
46
+ // plugins/metadata.json
47
+ var metadata_default = {
48
+ name: "apexrest-apex",
49
+ version: "2.8.0",
50
+ description: "Develop, deploy and test Oracle APEX applications from Codex or Claude Code.",
51
+ author: {
52
+ name: "APEXREST",
53
+ url: "https://apexrest-dev.github.io/apexrest/"
54
+ },
55
+ license: "Apache-2.0",
56
+ interface: {
57
+ displayName: "APEXREST for Codex and Claude Code",
58
+ shortDescription: "Oracle APEX development workflows",
59
+ longDescription: "Oracle APEX development, controlled deployment and testing directly in your current Codex or Claude Code session.",
60
+ developerName: "APEXREST",
61
+ websiteURL: "https://apexrest-dev.github.io/apexrest/",
62
+ composerIcon: "./assets/apexrest-icon.svg",
63
+ logo: "./assets/apexrest-logo.svg",
64
+ logoDark: "./assets/apexrest-logo.svg",
65
+ category: "Productivity",
66
+ capabilities: ["Read", "Write"],
67
+ defaultPrompt: [
68
+ "Use $apexrest-work to build or change my Oracle APEX application in this session.",
69
+ "Use $apexrest-setup to check my tools and connection references.",
70
+ "Use $apexrest-safety to explain what blocked my APEX deployment or test."
71
+ ]
72
+ }
73
+ };
74
+
75
+ // packages/core/src/version.ts
76
+ var VERSION = metadata_default.version;
77
+
78
+ // packages/core/src/partial-import.ts
79
+ import path4 from "node:path";
80
+ import { cp as cp2, mkdir as mkdir2, rename, rm as rm2 } from "node:fs/promises";
81
+
82
+ // packages/core/src/sync.ts
83
+ import path2 from "node:path";
84
+ import { lstat, mkdir, readdir as readdir2, realpath, open, cp, chmod } from "node:fs/promises";
85
+
86
+ // packages/core/src/deployment-control.ts
87
+ import path from "node:path";
88
+ import { hostname } from "node:os";
89
+ import { readdir, rm } from "node:fs/promises";
90
+ function coordination(env) {
91
+ return {
92
+ backend: "local",
93
+ scope: "managed-home-schema",
94
+ // Bind plans to the history store. Moving a plan to a fresh home is not migration recovery.
95
+ storeDigest: hash(canonical({ home: managedHome(), ...env.databaseIdentity, schema: env.parsingSchema }))
96
+ };
97
+ }
98
+ var ownerSchema = external_exports.strictObject({
99
+ runId: external_exports.string(),
100
+ pid: external_exports.number().int().positive(),
101
+ hostname: external_exports.string(),
102
+ phase: external_exports.enum(["preparing", "writing"]),
103
+ createdAt: external_exports.string()
104
+ });
105
+ var digestSchema = external_exports.string().regex(/^[a-f0-9]{64}$/);
106
+ var serviceBindingSchema = external_exports.strictObject({ serviceName: external_exports.string().min(1), directory: digestSchema });
107
+ var packagesSchema = external_exports.record(external_exports.string(), external_exports.string().regex(/^[a-f0-9]{64}$/));
108
+ var historySchema = external_exports.array(
109
+ external_exports.strictObject({
110
+ version: external_exports.string(),
111
+ checksum: external_exports.string().regex(/^[a-f0-9]{64}$/),
112
+ status: external_exports.enum(["started", "succeeded"]),
113
+ run_id: external_exports.string()
114
+ })
115
+ );
116
+ var LocalDeploymentControl = class {
117
+ directory;
118
+ serviceBinding;
119
+ serviceName;
120
+ root;
121
+ constructor(env) {
122
+ const { dbUniqueName, serviceName } = env.databaseIdentity;
123
+ const schema = env.parsingSchema;
124
+ this.root = path.join(managedHome(), "deployment-control");
125
+ this.directory = path.join(this.root, hash(canonical({ dbUniqueName, serviceName, schema })));
126
+ this.serviceName = serviceName;
127
+ this.serviceBinding = path.join(
128
+ this.root,
129
+ "schema-services",
130
+ hash(canonical({ dbUniqueName, schema })) + ".json"
131
+ );
132
+ }
133
+ file(name) {
134
+ return path.join(this.directory, name);
135
+ }
136
+ async hasScriptHistory(directory) {
137
+ const history = path.join(directory, "history.json");
138
+ const packages = path.join(directory, "packages.json");
139
+ return await exists(history) && parse(historySchema, await readJson(history)).length > 0 || await exists(packages) && Object.keys(parse(packagesSchema, await readJson(packages))).length > 0;
140
+ }
141
+ /** Register a known original store after a read-only plan has verified its target. */
142
+ async registerExisting() {
143
+ if (await this.hasScriptHistory(this.directory)) await this.checkService(true);
144
+ }
145
+ async checkService(bind = false) {
146
+ const check = async () => {
147
+ let binding;
148
+ try {
149
+ binding = parse(serviceBindingSchema, await readJson(this.serviceBinding));
150
+ } catch (error) {
151
+ if (error.code !== "ENOENT") throw error;
152
+ }
153
+ const directory = path.basename(this.directory);
154
+ if (binding && (binding.serviceName !== this.serviceName || binding.directory !== directory))
155
+ throw new Fault(
156
+ "CONTROL_SERVICE_CHANGED",
157
+ "This database name and schema already use a different Oracle service in the managed deployment store. Use the existing service to preserve migration history and reconcile interrupted runs.",
158
+ 5,
159
+ "conflict"
160
+ );
161
+ if (!bind || binding) return;
162
+ const bindings = path.dirname(this.serviceBinding);
163
+ const recognized = /* @__PURE__ */ new Set([directory]);
164
+ for (const file of (await readdir(bindings)).filter((name) => /^[a-f0-9]{64}\.json$/.test(name))) {
165
+ recognized.add(parse(serviceBindingSchema, await readJson(path.join(bindings, file))).directory);
166
+ }
167
+ const knownHistory = await this.hasScriptHistory(this.directory);
168
+ let unregisteredHistory = false;
169
+ for (const entry of await readdir(this.root, { withFileTypes: true })) {
170
+ if (!entry.isDirectory() || !digestSchema.safeParse(entry.name).success || recognized.has(entry.name))
171
+ continue;
172
+ const legacy = path.join(this.root, entry.name);
173
+ if (await exists(path.join(legacy, "active.json")))
174
+ throw new Fault(
175
+ "LEGACY_CONTROL_OWNER_UNRESOLVED",
176
+ "An older deployment store still has active ownership. Resolve that run using its original service before binding a different store.",
177
+ 5,
178
+ "conflict"
179
+ );
180
+ if (!knownHistory && !unregisteredHistory) unregisteredHistory = await this.hasScriptHistory(legacy);
181
+ }
182
+ if (unregisteredHistory)
183
+ throw new Fault(
184
+ "LEGACY_CONTROL_HISTORY_UNREGISTERED",
185
+ "An older deployment store has unregistered migration or package history. Run a full read-only deployment plan for each original environment using its original Oracle service before binding a new store.",
186
+ 5,
187
+ "conflict"
188
+ );
189
+ await writeJson(this.serviceBinding, { serviceName: this.serviceName, directory });
190
+ };
191
+ if (bind) await withLock(path.join(path.dirname(this.serviceBinding), "bindings.lock"), check);
192
+ else await check();
193
+ }
194
+ async history() {
195
+ await this.checkService();
196
+ const file = this.file("history.json");
197
+ return await exists(file) ? parse(historySchema, await readJson(file)) : [];
198
+ }
199
+ /**
200
+ * Checksum of each package script last applied successfully, by project-relative file. Package
201
+ * scripts are re-runnable, so a plan only re-applies the ones that changed since then.
202
+ */
203
+ async packages(projectId) {
204
+ await this.checkService();
205
+ const file = this.file("packages.json");
206
+ const all = await exists(file) ? parse(packagesSchema, await readJson(file)) : {};
207
+ const prefix = projectId + ":";
208
+ return Object.fromEntries(
209
+ Object.entries(all).filter(([key]) => key.startsWith(prefix)).map(([key, sha]) => [key.slice(prefix.length), sha])
210
+ );
211
+ }
212
+ async packageApplied(runId, projectId, file, checksum) {
213
+ await withLock(this.file("control.lock"), async () => {
214
+ await this.assertOwner(runId);
215
+ const target = this.file("packages.json");
216
+ const all = await exists(target) ? parse(packagesSchema, await readJson(target)) : {};
217
+ all[projectId + ":" + file] = checksum;
218
+ await writeJson(target, Object.fromEntries(Object.entries(all).sort(([a], [b]) => a.localeCompare(b))));
219
+ });
220
+ }
221
+ async owner() {
222
+ await this.checkService();
223
+ const file = this.file("active.json");
224
+ try {
225
+ return parse(ownerSchema, await readJson(file));
226
+ } catch (error) {
227
+ if (error.code === "ENOENT") return void 0;
228
+ throw error;
229
+ }
230
+ }
231
+ async acquire(runId, bindService = true) {
232
+ await this.checkService(bindService);
233
+ await withLock(this.file("control.lock"), async () => {
234
+ const owner = await this.owner();
235
+ if (owner) {
236
+ let dead = false;
237
+ if (owner.hostname === hostname()) {
238
+ try {
239
+ process.kill(owner.pid, 0);
240
+ } catch (e) {
241
+ dead = e.code === "ESRCH";
242
+ }
243
+ }
244
+ if (!dead || owner.phase === "writing")
245
+ throw new Fault(
246
+ "TARGET_LOCKED",
247
+ "A runner owns this schema or an interrupted write needs reconciliation. Preserve its control state.",
248
+ 5,
249
+ "conflict"
250
+ );
251
+ }
252
+ await writeJson(this.file("active.json"), {
253
+ runId,
254
+ pid: process.pid,
255
+ hostname: hostname(),
256
+ phase: "preparing",
257
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
258
+ });
259
+ });
260
+ }
261
+ async assertOwner(runId) {
262
+ const owner = await this.owner();
263
+ if (owner?.runId !== runId || owner.pid !== process.pid || owner.hostname !== hostname())
264
+ throw new Fault(
265
+ "LEASE_LOST",
266
+ "Local deployment ownership is no longer confirmed.",
267
+ 6,
268
+ "outcome_unknown"
269
+ );
270
+ return owner;
271
+ }
272
+ async markWriting(runId) {
273
+ await withLock(this.file("control.lock"), async () => {
274
+ await writeJson(this.file("active.json"), { ...await this.assertOwner(runId), phase: "writing" });
275
+ });
276
+ }
277
+ async migration(runId, version, checksum, status) {
278
+ await withLock(this.file("control.lock"), async () => {
279
+ await this.assertOwner(runId);
280
+ const history = await this.history(), previous = history.find((row) => row.version === version);
281
+ if (status === "started" ? Boolean(previous) : !previous || previous.run_id !== runId || previous.checksum !== checksum || previous.status !== "started")
282
+ throw new Fault(
283
+ "MIGRATION_HISTORY_CONFLICT",
284
+ "Migration history requires reconciliation; it cannot be replayed or overwritten.",
285
+ 5
286
+ );
287
+ const next = history.filter((row) => row.version !== version);
288
+ next.push({ version, checksum, status, run_id: runId });
289
+ await writeJson(
290
+ this.file("history.json"),
291
+ next.sort((a, b) => a.version.localeCompare(b.version))
292
+ );
293
+ });
294
+ }
295
+ async release(runId) {
296
+ await withLock(this.file("control.lock"), async () => {
297
+ await this.assertOwner(runId);
298
+ await rm(this.file("active.json"));
299
+ });
300
+ }
301
+ /** Release only the reconciled run after its worker has stopped. Keep history. */
302
+ async claimReconciled(runId) {
303
+ await this.checkService(true);
304
+ await withLock(this.file("control.lock"), async () => {
305
+ const owner = await this.owner();
306
+ if (!owner) {
307
+ await writeJson(this.file("active.json"), {
308
+ runId,
309
+ pid: process.pid,
310
+ hostname: hostname(),
311
+ phase: "preparing",
312
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
313
+ });
314
+ return;
315
+ }
316
+ if (owner.runId !== runId || owner.hostname !== hostname())
317
+ throw new Fault(
318
+ "TARGET_LOCKED",
319
+ "Another runner owns this target; reconciliation cannot clear its ownership.",
320
+ 5
321
+ );
322
+ if (owner.pid !== process.pid) {
323
+ let dead = false;
324
+ try {
325
+ process.kill(owner.pid, 0);
326
+ } catch (error) {
327
+ dead = error.code === "ESRCH";
328
+ }
329
+ if (!dead)
330
+ throw new Fault(
331
+ "TARGET_LOCKED",
332
+ "The import worker is still alive; wait for its terminal result.",
333
+ 5
334
+ );
335
+ }
336
+ await writeJson(this.file("active.json"), { ...owner, pid: process.pid, phase: "preparing" });
337
+ });
338
+ }
339
+ };
340
+
341
+ // packages/core/src/sync.ts
342
+ var digest = external_exports.string().regex(/^[a-f0-9]{64}$/);
343
+ var snapshotSchema = external_exports.strictObject({
344
+ directory: relativePath,
345
+ files: external_exports.record(relativePath, digest),
346
+ digest
347
+ });
348
+ var serverMetadataSchema = external_exports.strictObject({
349
+ lastUpdatedOn: external_exports.string().nullable(),
350
+ lastUpdatedBy: external_exports.string().nullable()
351
+ });
352
+ var syncStateSchema = external_exports.strictObject({
353
+ schemaVersion: external_exports.literal(1),
354
+ syncId: external_exports.uuid(),
355
+ revision: external_exports.number().int().nonnegative(),
356
+ projectRoot: external_exports.string(),
357
+ projectId: external_exports.string(),
358
+ environment: external_exports.string(),
359
+ targetDigest: digest,
360
+ target: external_exports.record(external_exports.string(), external_exports.unknown()),
361
+ sourceDir: relativePath,
362
+ toolchainDigest: digest,
363
+ runtimeVersion: external_exports.string(),
364
+ compilerVersion: external_exports.string().min(1),
365
+ exportedAt: external_exports.iso.datetime(),
366
+ baseline: snapshotSchema,
367
+ backup: external_exports.strictObject({ backupId: external_exports.uuid(), checksum: digest }),
368
+ observedMetadata: serverMetadataSchema,
369
+ lastSuccessfulImport: external_exports.strictObject({
370
+ at: external_exports.iso.datetime(),
371
+ runId: external_exports.uuid(),
372
+ snapshot: snapshotSchema,
373
+ verifiedFiles: external_exports.array(relativePath).optional()
374
+ }).nullable(),
375
+ recoveryCheckpoint: external_exports.strictObject({ at: external_exports.iso.datetime(), runId: external_exports.uuid(), snapshot: snapshotSchema }).nullable().optional(),
376
+ status: external_exports.enum(["ready", "importing", "verification_failed", "outcome_unknown", "invalidated"]),
377
+ importingRunId: external_exports.uuid().nullable()
378
+ });
379
+ async function syncPath(ctx, relative) {
380
+ const file = await contained(ctx.root, relative);
381
+ let probe = ctx.root;
382
+ for (const part of path2.relative(ctx.root, file).split(path2.sep).filter(Boolean)) {
383
+ probe = path2.join(probe, part);
384
+ if (await exists(probe)) {
385
+ if ((await lstat(probe)).isSymbolicLink())
386
+ throw new Fault("SYNC_PATH_UNSAFE", "Working-copy storage rejects symlinks.", 5);
387
+ }
388
+ }
389
+ return file;
390
+ }
391
+ async function privateCopy(source, destination) {
392
+ await cp(source, destination, { recursive: true });
393
+ async function secure(directory) {
394
+ await chmod(directory, 448);
395
+ for (const entry of await readdir2(directory, { withFileTypes: true })) {
396
+ if (entry.isSymbolicLink()) throw new Fault("SYNC_PATH_UNSAFE", "Private copies reject symlinks.", 5);
397
+ const file = path2.join(directory, entry.name);
398
+ if (entry.isDirectory()) await secure(file);
399
+ else if (entry.isFile()) await chmod(file, 384);
400
+ else throw new Fault("SYNC_PATH_UNSAFE", "Private copies accept regular files only.", 5);
401
+ }
402
+ }
403
+ await secure(destination);
404
+ }
405
+ async function checkSnapshot(ctx, snapshot) {
406
+ if (!snapshot.directory.startsWith(".apexrest/"))
407
+ throw new Fault("SYNC_ARTIFACT_INVALID", "Snapshot must be private project storage.", 5);
408
+ const actual = await inventory(await syncPath(ctx, snapshot.directory));
409
+ if (!Object.keys(actual).length || canonical(actual) !== canonical(snapshot.files) || hash(canonical(actual)) !== snapshot.digest)
410
+ throw new Fault("SYNC_ARTIFACT_INVALID", "Working-copy snapshot checksum verification failed.", 5);
411
+ return actual;
412
+ }
413
+ async function checkSyncBackup(ctx, backup, envDigest, environmentName) {
414
+ const directory = await syncPath(ctx, ".apexrest/backups/" + backup.backupId);
415
+ const metadata = await readJson(
416
+ await syncPath(ctx, ".apexrest/backups/" + backup.backupId + "/backup.json")
417
+ );
418
+ const files = await inventory(await syncPath(ctx, ".apexrest/backups/" + backup.backupId + "/application"));
419
+ if (metadata.schemaVersion !== 1 || metadata.environment !== environmentName || metadata.backupId !== backup.backupId || metadata.targetDigest !== envDigest || metadata.digest !== backup.checksum || hash(canonical(files)) !== backup.checksum || canonical(metadata.files) !== canonical(files) || !Object.keys(files).length)
420
+ throw new Fault("BACKUP_INVALID", "Initial source backup checksum or target verification failed.", 5);
421
+ }
422
+ function checkpoint(state) {
423
+ return state.recoveryCheckpoint?.snapshot ?? state.lastSuccessfulImport?.snapshot ?? state.baseline;
424
+ }
425
+ var SyncStore = class {
426
+ constructor(ctx, env, name) {
427
+ this.ctx = ctx;
428
+ this.env = env;
429
+ this.name = name;
430
+ }
431
+ ctx;
432
+ env;
433
+ name;
434
+ async file(key = targetDigest(this.env)) {
435
+ return syncPath(this.ctx, ".apexrest/sync/" + key + "/state.json");
436
+ }
437
+ async lock(action) {
438
+ return withLock(await syncPath(this.ctx, ".apexrest/sync/state.lock"), action);
439
+ }
440
+ /** Scan environment records so a changed target cannot silently become a legacy project. */
441
+ async read(allowMappingChange = false) {
442
+ const base = await syncPath(this.ctx, ".apexrest/sync");
443
+ if (!await exists(base)) return null;
444
+ const matches = [];
445
+ for (const entry of await readdir2(base, { withFileTypes: true })) {
446
+ if (entry.isSymbolicLink()) throw new Fault("SYNC_PATH_UNSAFE", "Sync storage contains a symlink.", 5);
447
+ if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;
448
+ const file = await this.file(entry.name);
449
+ if (!await exists(file)) {
450
+ if (await exists(await syncPath(this.ctx, ".apexrest/sync/" + entry.name + "/journal.jsonl")))
451
+ throw new Fault(
452
+ "SYNC_STATE_INVALID",
453
+ "A durable sync journal exists but its state is missing. Recover it explicitly; no export fallback.",
454
+ 5
455
+ );
456
+ continue;
457
+ }
458
+ let state2;
459
+ try {
460
+ state2 = syncStateSchema.parse(await readJson(file));
461
+ } catch {
462
+ throw new Fault(
463
+ "SYNC_STATE_INVALID",
464
+ "Corrupt working-copy state requires explicit recovery; no export fallback.",
465
+ 5
466
+ );
467
+ }
468
+ if (state2.targetDigest !== entry.name)
469
+ throw new Fault("SYNC_STATE_INVALID", "Sync record storage key differs from its target.", 5);
470
+ if (state2.targetDigest === targetDigest(this.env) && state2.environment !== this.name && state2.status !== "invalidated")
471
+ throw new Fault(
472
+ "SYNC_MAPPING_CHANGED",
473
+ "This target is bound to another environment. Explicitly invalidate the previous mapping first.",
474
+ 5
475
+ );
476
+ if (state2.environment === this.name && (state2.status !== "invalidated" || state2.targetDigest === targetDigest(this.env)))
477
+ matches.push(state2);
478
+ }
479
+ const active = matches.filter((s) => s.status !== "invalidated");
480
+ if (active.length > 1)
481
+ throw new Fault("SYNC_STATE_INVALID", "Multiple active records require reconciliation.", 5);
482
+ const state = active[0] ?? matches[0] ?? null;
483
+ if (state && state.status !== "invalidated" && !allowMappingChange) await this.checkMapping(state);
484
+ return state;
485
+ }
486
+ async checkMapping(state) {
487
+ const { readFile: readFile8 } = await import("node:fs/promises");
488
+ if (state.projectRoot !== await realpath(this.ctx.root) || state.projectId !== this.ctx.config.projectId || state.environment !== this.name || state.targetDigest !== targetDigest(this.env) || state.sourceDir !== this.ctx.config.application.sourceDir || state.runtimeVersion !== VERSION || state.toolchainDigest !== hash(await readFile8(await contained(this.ctx.root, this.ctx.config.toolchain.lockFile))) || await isProductionTarget(this.env))
489
+ throw new Fault(
490
+ "SYNC_MAPPING_CHANGED",
491
+ "Project, target, source directory or toolchain changed. Explicit refresh or invalidate is required.",
492
+ 5
493
+ );
494
+ }
495
+ async validate(state, ready = true) {
496
+ await this.checkMapping(state);
497
+ if (ready && state.status !== "ready")
498
+ throw new Fault(
499
+ "SYNC_BLOCKED",
500
+ `Working copy is ${state.status}. Inspect the existing run and reconcile before writes.`,
501
+ 5
502
+ );
503
+ const validRunSnapshot = (reference) => {
504
+ const base = ".apexrest/deployments/" + reference.runId + "/";
505
+ if (["snapshot", "server"].some(
506
+ (kind) => reference.snapshot.directory === base + kind + "/" + state.sourceDir
507
+ ))
508
+ return true;
509
+ const relative = reference.snapshot.directory.startsWith(base) ? reference.snapshot.directory.slice(base.length) : "";
510
+ return /^recovery\/\d{10,17}\/application$/.test(relative);
511
+ };
512
+ if (state.baseline.directory !== ".apexrest/sync/" + state.targetDigest + "/baselines/" + state.syncId + "/application" || state.lastSuccessfulImport && !validRunSnapshot(state.lastSuccessfulImport) || state.recoveryCheckpoint && !validRunSnapshot(state.recoveryCheckpoint))
513
+ throw new Fault(
514
+ "SYNC_ARTIFACT_INVALID",
515
+ "Snapshot reference does not match its sync or deployment owner.",
516
+ 5
517
+ );
518
+ if (state.status === "ready" && (await new LocalDeploymentControl(this.env).owner())?.phase === "writing")
519
+ throw new Fault("SYNC_BLOCKED", "A writing owner must complete or be reconciled before reuse.", 5);
520
+ await checkSnapshot(this.ctx, state.baseline);
521
+ if (state.lastSuccessfulImport) await checkSnapshot(this.ctx, state.lastSuccessfulImport.snapshot);
522
+ if (state.recoveryCheckpoint) await checkSnapshot(this.ctx, state.recoveryCheckpoint.snapshot);
523
+ await checkSyncBackup(this.ctx, state.backup, state.targetDigest, this.name);
524
+ }
525
+ async write(state) {
526
+ const valid = syncStateSchema.parse(state);
527
+ const file = await this.file(valid.targetDigest);
528
+ await mkdir(path2.dirname(file), { recursive: true, mode: 448 });
529
+ const journalFile = await syncPath(this.ctx, ".apexrest/sync/" + valid.targetDigest + "/journal.jsonl");
530
+ const journal = await open(journalFile, "a", 384);
531
+ try {
532
+ await journal.writeFile(
533
+ JSON.stringify({
534
+ at: (/* @__PURE__ */ new Date()).toISOString(),
535
+ syncId: valid.syncId,
536
+ revision: valid.revision,
537
+ status: valid.status,
538
+ importingRunId: valid.importingRunId,
539
+ baseline: valid.baseline.directory,
540
+ backupId: valid.backup.backupId,
541
+ latestApplied: valid.lastSuccessfulImport?.snapshot.directory ?? null
542
+ }) + "\n"
543
+ );
544
+ await journal.sync();
545
+ } finally {
546
+ await journal.close();
547
+ }
548
+ await writeJson(file, valid);
549
+ const directory = process.platform !== "win32" ? await open(path2.dirname(file), "r") : null;
550
+ try {
551
+ await directory?.sync();
552
+ } finally {
553
+ await directory?.close();
554
+ }
555
+ }
556
+ async status() {
557
+ const state = await this.read(true);
558
+ if (!state) return { mode: "full-export", status: "absent", serverFreshness: "not-checked" };
559
+ let blockedReason = null;
560
+ try {
561
+ await this.validate(state, false);
562
+ } catch (error) {
563
+ blockedReason = error instanceof Fault ? error.code : "SYNC_ARTIFACT_INVALID";
564
+ }
565
+ if ((await new LocalDeploymentControl(this.env).owner())?.phase === "writing")
566
+ blockedReason = "SYNC_BLOCKED";
567
+ const source = await syncPath(this.ctx, state.sourceDir);
568
+ const files = await exists(source) ? await inventory(source) : {};
569
+ return {
570
+ mode: state.status === "invalidated" ? "full-export" : "working-copy",
571
+ syncId: state.syncId,
572
+ revision: state.revision,
573
+ status: state.status,
574
+ exportedAt: state.exportedAt,
575
+ lastSuccessfulImport: state.lastSuccessfulImport ? {
576
+ at: state.lastSuccessfulImport.at,
577
+ runId: state.lastSuccessfulImport.runId,
578
+ digest: state.lastSuccessfulImport.snapshot.digest,
579
+ verifiedFiles: state.lastSuccessfulImport.verifiedFiles ?? null
580
+ } : null,
581
+ backupId: state.backup.backupId,
582
+ importingRunId: state.importingRunId,
583
+ dirty: canonical(files) !== canonical(checkpoint(state).files),
584
+ blocked: !!blockedReason || !["ready", "invalidated"].includes(state.status),
585
+ blockedReason,
586
+ serverFreshness: "not-checked",
587
+ assumption: "selected-content-conflicts; independent managed homes require external serialization"
588
+ };
589
+ }
590
+ };
591
+
592
+ // packages/core/src/apexlang-equivalence.ts
593
+ import path3 from "node:path";
594
+ import { readFile } from "node:fs/promises";
595
+ var APEXLANG_EQUIVALENCE_POLICY = "apex262-selected-source-v1";
596
+ var formattingRule = "structural-whitespace-and-comments";
597
+ var defaultRule = "pageItem.selectList.layout.startNewRow:true-default";
598
+ var pageDefaultRule = "page.security.pageAccessProtection:argumentsMustHaveChecksum-default";
599
+ var regionDefaultRule = "region.layout.startNewRow:true-default";
600
+ var chartDefaultRule = "region.chart.type:bar-default";
601
+ var cursorDefaultRule = "page.navigation.cursorFocus:doNotFocusCursor-default";
602
+ var autocompleteDefaultRule = "page.security.formAutoComplete:false-default";
603
+ var paginationDefaultRule = "region.classicReport.pagination.type:nextAndPreviousLinks-default";
604
+ var orderRule = "explicit-unique-region-and-chart-component-order";
605
+ var columnOrderRule = "explicit-unique-report-column-order";
606
+ var memberOrderRule = "unique-property-and-group-order";
607
+ var quotedLiteralRule = "single-line-literal-quoting";
608
+ var invokeDefaultRule = "invokeApi.parameter.direction:in,dataType:varchar2,ignoreOutput:false-default";
609
+ var invokeCaseRule = "invokeApi.invoke.identifier-case";
610
+ var eventDefaultRule = "dynamicAction.when.items.event:change-default";
611
+ var componentOrderRule = "key-ordered-page-components";
612
+ var lovNullDefaultRule = "pageItem.selectList.lov.displayNullValue:true-default";
613
+ var buttonActionDefaultRule = "button.behavior.action:submitPage-default";
614
+ var assignedIdentifierRule = "process.advanced.executionMappingIdentifier:server-assigned";
615
+ var limit = 8 * 1024 * 1024;
616
+ function readStructure(source) {
617
+ if (Buffer.byteLength(source) > limit) throw new Error("Source exceeds the comparison limit.");
618
+ const lines = source.match(/[^\r\n]*(?:\r\n|\r|\n|$)/g)?.filter(Boolean) ?? [];
619
+ const roots = [];
620
+ const stack = [];
621
+ const append = (node) => (stack.at(-1)?.children ?? roots).push(node);
622
+ for (let index = 0; index < lines.length; index++) {
623
+ const raw = lines[index];
624
+ const line = raw.replace(/[\r\n]+$/, "");
625
+ const trimmed = line.trim();
626
+ if (!trimmed || trimmed.startsWith("//")) continue;
627
+ if (trimmed.startsWith("/*")) {
628
+ let comment = trimmed;
629
+ while (!comment.includes("*/") && ++index < lines.length) comment += lines[index];
630
+ const end = comment.indexOf("*/");
631
+ if (end < 0 || comment.slice(end + 2).trim()) throw new Error("Unsupported comment boundary.");
632
+ continue;
633
+ }
634
+ if (trimmed.startsWith("```")) {
635
+ if (!/^```[A-Za-z0-9_-]*[ \t]*$/.test(trimmed)) throw new Error("Unsupported fenced literal.");
636
+ let literal = line.replace(/^[ \t]*/, "") + raw.slice(line.length);
637
+ let closed = false;
638
+ while (++index < lines.length) {
639
+ const next = lines[index];
640
+ if (/^[ \t]*```[ \t]*(?:\r\n|\r|\n)?$/.test(next)) {
641
+ literal += next.replace(/^[ \t]*/, "");
642
+ closed = true;
643
+ break;
644
+ }
645
+ literal += next;
646
+ }
647
+ if (!closed) throw new Error("Unclosed fenced literal.");
648
+ const siblings = stack.at(-1)?.children ?? roots;
649
+ const owner = siblings.at(-1);
650
+ if (owner?.kind === "property" && owner.value === "" && owner.literal === void 0) {
651
+ owner.literal = literal;
652
+ owner.indent = /^[ \t]*/.exec(line)[0];
653
+ } else append({ kind: "literal", value: literal });
654
+ continue;
655
+ }
656
+ const property = /^[ \t]*([A-Za-z][\w]*):[ \t]*(.*)$/.exec(line);
657
+ if (property) {
658
+ const value = property[2];
659
+ if (value.includes("```") || value.startsWith('"""') || value.startsWith("'''"))
660
+ throw new Error("Unsupported inline or multiline literal.");
661
+ if (value === "{") {
662
+ const node = { kind: "map", name: property[1], key: "", children: [] };
663
+ append(node);
664
+ stack.push(node);
665
+ } else if (value === "[") {
666
+ const items = [];
667
+ let closed = false;
668
+ while (++index < lines.length) {
669
+ const entry = lines[index].trim();
670
+ if (entry === "]") {
671
+ closed = true;
672
+ break;
673
+ }
674
+ if (!entry || /[[\]{}()]$|^```/.test(entry)) throw new Error("Unsupported list entry.");
675
+ items.push(entry);
676
+ }
677
+ if (!closed) throw new Error("Unclosed list.");
678
+ append({ kind: "property", name: property[1], value: "[" + items.join("\n") + "]" });
679
+ } else append({ kind: "property", name: property[1], value });
680
+ continue;
681
+ }
682
+ const component = /^([A-Za-z][\w]*)(?:[ \t]+(.*?))?[ \t]*\([ \t]*$/.exec(trimmed);
683
+ if (component) {
684
+ const node = { kind: "component", name: component[1], key: component[2] ?? "", children: [] };
685
+ append(node);
686
+ stack.push(node);
687
+ continue;
688
+ }
689
+ const group = /^([A-Za-z][\w]*)[ \t]*\{[ \t]*$/.exec(trimmed);
690
+ if (group) {
691
+ const node = { kind: "group", name: group[1], key: "", children: [] };
692
+ append(node);
693
+ stack.push(node);
694
+ continue;
695
+ }
696
+ if (trimmed === ")" || trimmed === "}") {
697
+ const node = stack.pop();
698
+ if (!node || trimmed === ")" !== (node.kind === "component"))
699
+ throw new Error("Unbalanced structural boundary.");
700
+ continue;
701
+ }
702
+ throw new Error("Unsupported source form.");
703
+ }
704
+ if (stack.length) throw new Error("Unclosed structural boundary.");
705
+ return roots;
706
+ }
707
+ function removeQualifiedDefault(nodes, parent) {
708
+ return nodes.map((node) => {
709
+ if (!("children" in node)) return node;
710
+ let children = node.children;
711
+ if (node.kind === "component" && node.name === "pageItem" && parent?.kind === "component" && parent.name === "page") {
712
+ const types = children.filter((child) => child.kind === "property" && child.name === "type");
713
+ const layouts = children.filter((child) => child.kind === "group" && child.name === "layout");
714
+ if (types.length === 1 && types[0].kind === "property" && types[0].value === "selectList" && layouts.length === 1) {
715
+ children = children.map((child) => {
716
+ if (child.kind !== "group" || child.name !== "layout") return child;
717
+ const rows = child.children.filter(
718
+ (entry) => entry.kind === "property" && entry.name === "startNewRow"
719
+ );
720
+ const layouts2 = child.children.filter(
721
+ (entry) => entry.kind === "property" && entry.name === "startNewLayout"
722
+ );
723
+ if (rows.length !== 1 || rows[0].kind !== "property" || rows[0].value !== "true" || layouts2.length > 1 || layouts2.length === 1 && (layouts2[0].kind !== "property" || layouts2[0].value !== "false"))
724
+ return child;
725
+ return { ...child, children: child.children.filter((entry) => entry !== rows[0]) };
726
+ });
727
+ }
728
+ }
729
+ return { ...node, children: removeQualifiedDefault(children, node) };
730
+ });
731
+ }
732
+ function normalizeExport(nodes, rules, parent) {
733
+ const result = nodes.map((node) => {
734
+ if (!("children" in node)) return node;
735
+ let children = normalizeExport(node.children, rules, node);
736
+ const property = (name) => children.filter((entry) => entry.kind === "property" && entry.name === name);
737
+ const omit = (name, value, rule) => {
738
+ const matches = property(name);
739
+ if (matches.length === 1 && matches[0].kind === "property" && matches[0].value === value) {
740
+ children = children.filter((entry) => entry !== matches[0]);
741
+ rules.add(rule);
742
+ }
743
+ };
744
+ if (node.kind === "group" && node.name === "security" && parent?.name === "page") {
745
+ omit("pageAccessProtection", "argumentsMustHaveChecksum", pageDefaultRule);
746
+ omit("formAutoComplete", "false", autocompleteDefaultRule);
747
+ }
748
+ if (node.kind === "group" && node.name === "navigation" && parent?.name === "page")
749
+ omit("cursorFocus", "doNotFocusCursor", cursorDefaultRule);
750
+ if (node.kind === "group" && node.name === "pagination" && parent?.kind === "component" && parent.name === "region" && parent.children.some(
751
+ (entry) => entry.kind === "property" && entry.name === "type" && entry.value === "classicReport"
752
+ ))
753
+ omit("type", "nextAndPreviousLinks", paginationDefaultRule);
754
+ if (node.kind === "group" && node.name === "layout" && parent?.kind === "component" && parent.name === "region") {
755
+ const starts = property("startNewLayout");
756
+ if (!starts.length || starts.length === 1 && starts[0].kind === "property" && starts[0].value === "false")
757
+ omit("startNewRow", "true", regionDefaultRule);
758
+ }
759
+ if (node.kind === "group" && node.name === "chart" && parent?.kind === "component" && parent.name === "region" && parent.children.some(
760
+ (entry) => entry.kind === "property" && entry.name === "type" && entry.value === "chart"
761
+ ))
762
+ omit("type", "bar", chartDefaultRule);
763
+ const identities = node.children.filter((entry) => entry.kind !== "literal").map(
764
+ (entry) => entry.kind + ":" + ("name" in entry ? entry.name : "") + ":" + ("key" in entry ? entry.key : "")
765
+ );
766
+ if (new Set(identities).size !== identities.length) throw new Error("Duplicate structural identity.");
767
+ const sortable = children.filter(
768
+ (entry) => entry.kind === "component" && (node.name === "page" && entry.name === "region" || node.name === "region" && node.children.some(
769
+ (child) => child.kind === "property" && child.name === "type" && child.value === "chart"
770
+ ) && ["axis", "series"].includes(entry.name) || node.name === "region" && node.children.some(
771
+ (child) => child.kind === "property" && child.name === "type" && child.value === "classicReport"
772
+ ) && entry.name === "column")
773
+ );
774
+ if (sortable.length > 1) {
775
+ const sequence = (entry) => {
776
+ if (!("children" in entry)) return void 0;
777
+ if (entry.name === "axis") return entry.key === "x" || entry.key === "y" ? entry.key : void 0;
778
+ const group = entry.children.find(
779
+ (child) => child.kind === "group" && child.name === (entry.name === "series" ? "execution" : "layout")
780
+ );
781
+ const value = group && "children" in group ? group.children.find((child) => child.kind === "property" && child.name === "sequence") : void 0;
782
+ return value?.kind === "property" && /^\d+$/.test(value.value) ? entry.name + ":" + value.value : void 0;
783
+ };
784
+ const sequences = sortable.map(sequence);
785
+ if (sequences.every(Boolean) && new Set(sequences).size === sequences.length) {
786
+ const sorted = [...sortable].sort(
787
+ (left, right) => ("name" in left ? left.name : "").localeCompare("name" in right ? right.name : "") || ("key" in left ? left.key : "").localeCompare("key" in right ? right.key : "")
788
+ );
789
+ let index = 0;
790
+ children = children.map((entry) => sortable.includes(entry) ? sorted[index++] : entry);
791
+ rules.add(
792
+ sortable.some((entry) => "name" in entry && entry.name === "column") ? columnOrderRule : orderRule
793
+ );
794
+ }
795
+ }
796
+ return { ...node, children };
797
+ });
798
+ return result.filter(
799
+ (node) => !("children" in node && !node.children.length && node.kind === "group" && (parent?.name === "page" && ["security", "navigation"].includes(node.name) || parent?.name === "region" && ["chart", "layout", "pagination"].includes(node.name)))
800
+ );
801
+ }
802
+ var identifier = /^[A-Za-z][A-Za-z0-9_$#]*$/;
803
+ function normalizeForms(nodes, rules, parent) {
804
+ const result = [];
805
+ for (const node of nodes) {
806
+ if (node.kind === "property") {
807
+ if (node.literal !== void 0) {
808
+ const lines = node.literal.split(/\r\n|\r|\n/);
809
+ const content = lines.length === 4 && lines[3] === "" ? lines[1] : void 0;
810
+ if (content !== void 0 && content.startsWith(node.indent ?? "") && lines[2] === "```") {
811
+ result.push({
812
+ kind: "property",
813
+ name: node.name,
814
+ value: JSON.stringify(content.slice((node.indent ?? "").length))
815
+ });
816
+ rules.add(quotedLiteralRule);
817
+ continue;
818
+ }
819
+ result.push(node);
820
+ continue;
821
+ }
822
+ if (/^".*"$/.test(node.value)) {
823
+ try {
824
+ const decoded = JSON.parse(node.value);
825
+ if (typeof decoded === "string" && JSON.stringify(decoded) !== node.value) {
826
+ result.push({ ...node, value: JSON.stringify(decoded) });
827
+ continue;
828
+ }
829
+ } catch {
830
+ }
831
+ }
832
+ if (parent?.kind === "group" && parent.name === "invoke" && ["package", "procedureOrFunction"].includes(node.name) && identifier.test(node.value)) {
833
+ if (node.value !== node.value.toUpperCase()) rules.add(invokeCaseRule);
834
+ result.push({ ...node, value: node.value.toUpperCase() });
835
+ continue;
836
+ }
837
+ result.push(node);
838
+ continue;
839
+ }
840
+ if (!("children" in node)) {
841
+ result.push(node);
842
+ continue;
843
+ }
844
+ let children = normalizeForms(node.children, rules, node);
845
+ const scalar = (name) => {
846
+ const matches = children.filter((entry) => entry.kind === "property" && entry.name === name);
847
+ return matches.length === 1 && matches[0].kind === "property" ? matches[0] : void 0;
848
+ };
849
+ if (node.kind === "group" && node.name === "parameter" && parent?.kind === "component" && parent.name === "parameter") {
850
+ for (const [name, value] of [
851
+ ["direction", "in"],
852
+ ["dataType", "varchar2"],
853
+ ["ignoreOutput", "false"]
854
+ ]) {
855
+ const entry = scalar(name);
856
+ if (entry?.kind === "property" && entry.value === value) {
857
+ children = children.filter((child) => child !== entry);
858
+ rules.add(invokeDefaultRule);
859
+ }
860
+ }
861
+ if (!children.length) {
862
+ rules.add(invokeDefaultRule);
863
+ continue;
864
+ }
865
+ }
866
+ if (node.kind === "group" && node.name === "when" && parent?.kind === "component" && parent.name === "dynamicAction") {
867
+ const event = scalar("event"), selection = scalar("selectionType");
868
+ if (event?.kind === "property" && event.value === "change" && selection?.kind === "property" && selection.value === "items") {
869
+ children = children.filter((child) => child !== event);
870
+ rules.add(eventDefaultRule);
871
+ }
872
+ }
873
+ if (node.kind === "group" && node.name === "lov" && parent?.kind === "component" && parent.name === "pageItem" && parent.children.some(
874
+ (entry) => entry.kind === "property" && entry.name === "type" && entry.value === "selectList"
875
+ )) {
876
+ const entry = scalar("displayNullValue");
877
+ if (entry?.kind === "property" && entry.value === "true") {
878
+ children = children.filter((child) => child !== entry);
879
+ rules.add(lovNullDefaultRule);
880
+ }
881
+ }
882
+ if (node.kind === "group" && node.name === "behavior" && parent?.kind === "component" && parent.name === "button") {
883
+ const entry = scalar("action");
884
+ if (entry?.kind === "property" && entry.value === "submitPage") {
885
+ children = children.filter((child) => child !== entry);
886
+ rules.add(buttonActionDefaultRule);
887
+ if (!children.length) continue;
888
+ }
889
+ }
890
+ result.push({ ...node, children });
891
+ }
892
+ return result;
893
+ }
894
+ function dropAssignedIdentifiers(expected, actual, rules) {
895
+ const group = (node, name) => node && "children" in node ? node.children.filter((child) => child.kind === "group" && child.name === name) : [];
896
+ const identifier2 = (process2) => group(process2, "advanced").flatMap(
897
+ (advanced) => "children" in advanced ? advanced.children.filter(
898
+ (child) => child.kind === "property" && child.name === "executionMappingIdentifier"
899
+ ) : []
900
+ );
901
+ return actual.map((page) => {
902
+ if (!("children" in page) || page.kind !== "component" || page.name !== "page") return page;
903
+ const reviewedPages = expected.filter(
904
+ (node) => "children" in node && node.kind === "component" && node.name === "page" && node.key === page.key
905
+ );
906
+ if (reviewedPages.length !== 1) return page;
907
+ const reviewedPage = reviewedPages[0];
908
+ return {
909
+ ...page,
910
+ children: page.children.map((process2) => {
911
+ if (!("children" in process2) || process2.kind !== "component" || process2.name !== "process")
912
+ return process2;
913
+ const reviewed = reviewedPage.children.filter(
914
+ (node) => "children" in node && node.kind === "component" && node.name === "process" && node.key === process2.key
915
+ );
916
+ const assigned = identifier2(process2);
917
+ if (reviewed.length !== 1 || identifier2(reviewed[0]).length || assigned.length !== 1 || assigned[0].kind !== "property" || !/^\d+$/.test(assigned[0].value))
918
+ return process2;
919
+ rules.add(assignedIdentifierRule);
920
+ return {
921
+ ...process2,
922
+ children: process2.children.map(
923
+ (child) => "children" in child && child.kind === "group" && child.name === "advanced" ? { ...child, children: child.children.filter((entry) => entry !== assigned[0]) } : child
924
+ ).filter(
925
+ (child) => !("children" in child && child.kind === "group" && child.name === "advanced" && !child.children.length)
926
+ )
927
+ };
928
+ })
929
+ };
930
+ });
931
+ }
932
+ var sequencedComponents = {
933
+ page: {
934
+ region: ["layout", "sequence"],
935
+ pageItem: ["layout", "sequence"],
936
+ button: ["layout", "sequence"],
937
+ dynamicAction: ["execution", "sequence"],
938
+ validation: ["execution", "sequence"],
939
+ process: ["execution", "sequence"],
940
+ computation: ["execution", "sequence"],
941
+ branch: ["execution", "sequence"]
942
+ },
943
+ process: { parameter: ["advanced", "displaySequence"] },
944
+ dynamicAction: { action: ["execution", "sequence"] }
945
+ };
946
+ var componentKey = (node) => ("name" in node ? node.name : "") + ":" + ("key" in node ? node.key : "");
947
+ function orderComponents(nodes, rules) {
948
+ return nodes.map((node) => {
949
+ if (!("children" in node)) return node;
950
+ let children = orderComponents(node.children, rules);
951
+ const allowed = node.kind === "component" ? sequencedComponents[node.name] : void 0;
952
+ const components = children.filter((child) => child.kind === "component");
953
+ if (allowed && components.length > 1) {
954
+ const qualified = components.every((child) => {
955
+ if (child.kind !== "component" || !allowed[child.name]) return false;
956
+ const [groupName, propertyName] = allowed[child.name];
957
+ const group = child.children.find((entry) => entry.kind === "group" && entry.name === groupName);
958
+ return !!group && "children" in group && group.children.some(
959
+ (entry) => entry.kind === "property" && entry.name === propertyName && /^\d+$/.test(entry.value)
960
+ );
961
+ });
962
+ const keys = components.map(componentKey);
963
+ if (qualified && new Set(keys).size === keys.length) {
964
+ const sorted = [...components].sort(
965
+ (left, right) => componentKey(left).localeCompare(componentKey(right))
966
+ );
967
+ if (sorted.some((child, index2) => child !== components[index2])) rules.add(componentOrderRule);
968
+ let index = 0;
969
+ children = children.map((child) => child.kind === "component" ? sorted[index++] : child);
970
+ }
971
+ }
972
+ return { ...node, children };
973
+ });
974
+ }
975
+ function orderMembers(nodes, rules) {
976
+ return nodes.map((node) => {
977
+ if (!("children" in node)) return node;
978
+ let children = orderMembers(node.children, rules);
979
+ if (!children.some((child) => child.kind === "literal")) {
980
+ const members = children.filter((child) => child.kind !== "component");
981
+ const names = members.map((child) => child.kind + ":" + ("name" in child ? child.name : ""));
982
+ if (new Set(names).size === names.length) {
983
+ const sorted = [...members].sort(
984
+ (left, right) => (left.kind + ":" + ("name" in left ? left.name : "")).localeCompare(
985
+ right.kind + ":" + ("name" in right ? right.name : "")
986
+ )
987
+ );
988
+ if (sorted.some((child, index) => child !== members[index])) rules.add(memberOrderRule);
989
+ children = [...sorted, ...children.filter((child) => child.kind === "component")];
990
+ }
991
+ }
992
+ return { ...node, children };
993
+ });
994
+ }
995
+ function compareApexlangSource(expected, actual) {
996
+ if (expected === actual) return { equivalent: true, rules: [] };
997
+ try {
998
+ const left = readStructure(expected), right = readStructure(actual);
999
+ if (canonical(left) === canonical(right)) return { equivalent: true, rules: [formattingRule] };
1000
+ if (canonical(removeQualifiedDefault(left)) === canonical(removeQualifiedDefault(right)))
1001
+ return { equivalent: true, rules: [formattingRule, defaultRule] };
1002
+ const rules = /* @__PURE__ */ new Set();
1003
+ if (canonical(left) !== canonical(removeQualifiedDefault(left)) || canonical(right) !== canonical(removeQualifiedDefault(right)))
1004
+ rules.add(defaultRule);
1005
+ if (canonical(normalizeExport(removeQualifiedDefault(left), rules)) === canonical(normalizeExport(removeQualifiedDefault(right), rules)))
1006
+ return { equivalent: true, rules: [formattingRule, ...rules] };
1007
+ const formRules = new Set(rules);
1008
+ const normalized = (nodes) => orderComponents(
1009
+ orderMembers(
1010
+ normalizeExport(normalizeForms(removeQualifiedDefault(nodes), formRules), formRules),
1011
+ formRules
1012
+ ),
1013
+ formRules
1014
+ );
1015
+ if (canonical(normalized(left)) === canonical(normalized(right)))
1016
+ return { equivalent: true, rules: [formattingRule, ...formRules] };
1017
+ const assignedRules = new Set(formRules);
1018
+ if (canonical(normalized(left)) === canonical(normalized(dropAssignedIdentifiers(left, right, assignedRules))))
1019
+ return { equivalent: true, rules: [formattingRule, ...assignedRules] };
1020
+ return {
1021
+ equivalent: false,
1022
+ rules: [],
1023
+ reason: "Source differs beyond the qualified formatting/default rules."
1024
+ };
1025
+ } catch (error) {
1026
+ return {
1027
+ equivalent: false,
1028
+ rules: [],
1029
+ reason: error instanceof Error ? error.message : "Source form is unsupported."
1030
+ };
1031
+ }
1032
+ }
1033
+ async function compareApplicationExports(expectedRoot, actualRoot, expectedFiles, actualFiles, allowedFiles) {
1034
+ const allowed = new Set(allowedFiles);
1035
+ const result = {
1036
+ equivalent: true,
1037
+ policy: APEXLANG_EQUIVALENCE_POLICY,
1038
+ normalizations: [],
1039
+ mismatchedFiles: [],
1040
+ mismatches: []
1041
+ };
1042
+ for (const file of [.../* @__PURE__ */ new Set([...Object.keys(expectedFiles), ...Object.keys(actualFiles)])].sort()) {
1043
+ if (expectedFiles[file] === actualFiles[file]) continue;
1044
+ let reason = "File bytes differ outside the selected APEXlang normalization scope.";
1045
+ if (expectedFiles[file] && actualFiles[file] && allowed.has(file) && path3.posix.extname(file) === ".apx") {
1046
+ const [expected, actual] = await Promise.all([
1047
+ readFile(await contained(expectedRoot, file)),
1048
+ readFile(await contained(actualRoot, file))
1049
+ ]);
1050
+ if (hash(expected) !== expectedFiles[file] || hash(actual) !== actualFiles[file])
1051
+ reason = "Source changed during readback comparison.";
1052
+ else {
1053
+ const decoder = new TextDecoder("utf-8", { fatal: true });
1054
+ let comparison;
1055
+ try {
1056
+ comparison = compareApexlangSource(decoder.decode(expected), decoder.decode(actual));
1057
+ } catch {
1058
+ comparison = { equivalent: false, rules: [], reason: "Source is not valid UTF-8." };
1059
+ }
1060
+ if (comparison.equivalent) {
1061
+ result.normalizations.push({
1062
+ file,
1063
+ expectedSha256: expectedFiles[file],
1064
+ actualSha256: actualFiles[file],
1065
+ rules: comparison.rules
1066
+ });
1067
+ continue;
1068
+ }
1069
+ reason = comparison.reason ?? reason;
1070
+ }
1071
+ }
1072
+ result.equivalent = false;
1073
+ result.mismatchedFiles.push(file);
1074
+ result.mismatches.push({ file, reason });
1075
+ }
1076
+ return result;
1077
+ }
1078
+
1079
+ // packages/core/src/partial-import.ts
1080
+ var importSelectionSchema = external_exports.strictObject({
1081
+ requestedMode: external_exports.enum(["auto", "full", "files"]),
1082
+ resolvedMode: external_exports.enum(["full", "files"]),
1083
+ files: external_exports.array(relativePath),
1084
+ reasons: external_exports.array(external_exports.string()),
1085
+ dependencies: external_exports.array(relativePath),
1086
+ before: snapshotSchema.nullable(),
1087
+ effective: snapshotSchema.nullable(),
1088
+ capabilities: external_exports.record(external_exports.string(), external_exports.unknown()),
1089
+ readbackPolicy: external_exports.literal(APEXLANG_EQUIVALENCE_POLICY).optional(),
1090
+ exportScope: external_exports.enum(["selected", "full"]).optional()
1091
+ });
1092
+ function importOptions(value = {}) {
1093
+ const mode = value.importMode ?? "auto";
1094
+ if ((value.files?.length ?? 0) > 1e3)
1095
+ throw new Fault("INVALID_INPUT", "Select at most 1000 files in one import.", 2);
1096
+ if (!["auto", "full", "files", "none"].includes(mode))
1097
+ throw new Fault("INVALID_INPUT", "Unknown import mode.", 2);
1098
+ if (mode === "files" !== !!value.files?.length)
1099
+ throw new Fault(
1100
+ "INVALID_INPUT",
1101
+ "files mode requires a nonempty file list; other modes do not accept files.",
1102
+ 2
1103
+ );
1104
+ const files = (value.files ?? []).map((file) => {
1105
+ if (!relativePath.safeParse(file).success || /[\\*?\[\]]/.test(file) || /^[A-Za-z]:/.test(file) || file.startsWith("-") || path4.posix.normalize(file) !== file || file === ".")
1106
+ throw new Fault(
1107
+ "IMPORT_FILE_UNSAFE",
1108
+ "Use normalized application-relative file paths without globs.",
1109
+ 2
1110
+ );
1111
+ return file;
1112
+ });
1113
+ if (new Set(files).size !== files.length)
1114
+ throw new Fault("IMPORT_FILE_UNSAFE", "Duplicate import files are not allowed.", 2);
1115
+ return { importMode: mode, files: files.sort() };
1116
+ }
1117
+ async function sourceRelease(root) {
1118
+ try {
1119
+ const value = await readJson(path4.join(root, ".apex/apexlang.json"));
1120
+ return typeof value.mmdVersion === "string" ? value.mmdVersion.match(/^\d+\.\d+/)?.[0] ?? null : null;
1121
+ } catch {
1122
+ return null;
1123
+ }
1124
+ }
1125
+ function supportedFile(file) {
1126
+ return /^pages\/p\d{5}[-\w]*\.apx$/.test(file) || /^shared-components\/.+\.apx$/.test(file) && !/(?:^|\/)(?:themes?|templates?|plugins?|plug-ins?|static-files|files|authentications?|authorizations?)(?:[/.]|$)/i.test(
1127
+ file
1128
+ );
1129
+ }
1130
+ function scopedExportFile(file) {
1131
+ return /^pages\/p\d{5}[-\w]*\.apx$/.test(file);
1132
+ }
1133
+ function pickFiles(files, selected) {
1134
+ return Object.fromEntries(selected.filter((file) => files[file]).map((file) => [file, files[file]]));
1135
+ }
1136
+ async function overlaySelection(source, exported, files, destination) {
1137
+ await privateCopy(source, destination);
1138
+ const observed = await inventory(exported);
1139
+ for (const file of files) {
1140
+ const target = await contained(destination, file);
1141
+ if (!observed[file]) await rm2(target, { force: true });
1142
+ else {
1143
+ await mkdir2(path4.dirname(target), { recursive: true, mode: 448 });
1144
+ await cp2(await contained(exported, file), target);
1145
+ }
1146
+ }
1147
+ return destination;
1148
+ }
1149
+ function changedFiles(before, after) {
1150
+ return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((file) => before[file] !== after[file]).sort();
1151
+ }
1152
+ function selectImport(base, local, remote, options) {
1153
+ const requested = importOptions(options);
1154
+ const localChanges = changedFiles(base, local);
1155
+ const remoteChanges = changedFiles(base, remote);
1156
+ const selected = requested.importMode === "files" ? requested.files : localChanges;
1157
+ for (const file of selected)
1158
+ if (!Object.hasOwn(local, file) && requested.importMode === "files")
1159
+ throw new Fault("IMPORT_FILE_MISSING", `Selected file is missing: ${file}`, 2);
1160
+ const conflicts = localChanges.filter(
1161
+ (file) => remoteChanges.includes(file) && local[file] !== remote[file]
1162
+ );
1163
+ if (conflicts.length)
1164
+ throw new Fault(
1165
+ "IMPORT_CONFLICT",
1166
+ `Local and server changes overlap; reconcile before planning: ${conflicts.join(", ")}`,
1167
+ 5,
1168
+ "blocked",
1169
+ { conflicts }
1170
+ );
1171
+ const reasons = [];
1172
+ if (selected.some((file) => !Object.hasOwn(local, file))) reasons.push("deleted-files-require-full-import");
1173
+ if (selected.some((file) => !supportedFile(file))) reasons.push("unsupported-component-files");
1174
+ const files = selected.filter((file) => local[file] !== remote[file]);
1175
+ if (!files.length) reasons.push("no-changed-files");
1176
+ const effective = { ...remote };
1177
+ for (const file of files) {
1178
+ if (local[file]) effective[file] = local[file];
1179
+ else delete effective[file];
1180
+ }
1181
+ return { files, reasons, remoteChanges, effective: Object.fromEntries(Object.entries(effective).sort()) };
1182
+ }
1183
+ async function persistSnapshot(ctx, source, directory) {
1184
+ const destination = await syncPath(ctx, directory);
1185
+ await mkdir2(path4.dirname(destination), { recursive: true, mode: 448 });
1186
+ await privateCopy(source, destination);
1187
+ const files = await inventory(destination);
1188
+ return { directory, files, digest: hash(canonical(files)) };
1189
+ }
1190
+ async function stageSelection(ctx, before, localRoot, files, expected, directory) {
1191
+ const root = await syncPath(ctx, directory);
1192
+ await mkdir2(path4.dirname(root), { recursive: true, mode: 448 });
1193
+ await privateCopy(await syncPath(ctx, before.directory), root);
1194
+ for (const file of files) {
1195
+ const destination = await contained(root, file);
1196
+ await mkdir2(path4.dirname(destination), { recursive: true, mode: 448 });
1197
+ await cp2(await contained(localRoot, file), destination);
1198
+ }
1199
+ const actual = await inventory(root);
1200
+ if (canonical(actual) !== canonical(expected))
1201
+ throw new Fault("SOURCE_DRIFT", "Source changed while preparing the selected import.", 5);
1202
+ return { directory, files: actual, digest: hash(canonical(actual)) };
1203
+ }
1204
+ async function rebaseAfterImport(ctx, runId, reviewedLocal, before, server, selected) {
1205
+ await checkSnapshot(ctx, server);
1206
+ const localRoot = await syncPath(ctx, ctx.config.application.sourceDir);
1207
+ if (canonical(await inventory(localRoot)) !== canonical(reviewedLocal))
1208
+ throw new Fault(
1209
+ "LOCAL_RECONCILIATION_REQUIRED",
1210
+ "Import confirmed; local files changed during execution. Reconcile them before another import.",
1211
+ 5
1212
+ );
1213
+ const base = ".apexrest/deployments/" + runId;
1214
+ const replacement = await syncPath(ctx, base + "/rebased-source");
1215
+ const retained = await syncPath(ctx, base + "/local-before-rebase");
1216
+ await privateCopy(localRoot, replacement);
1217
+ const remoteOnly = changedFiles(before, server.files).filter(
1218
+ (file) => selected.includes(file) || reviewedLocal[file] === before[file]
1219
+ );
1220
+ for (const file of /* @__PURE__ */ new Set([...remoteOnly, ...selected])) {
1221
+ const destination = await contained(replacement, file);
1222
+ if (!server.files[file]) await rm2(destination, { force: true });
1223
+ else {
1224
+ await mkdir2(path4.dirname(destination), { recursive: true });
1225
+ await cp2(await contained(await syncPath(ctx, server.directory), file), destination);
1226
+ }
1227
+ }
1228
+ if (canonical(await inventory(localRoot)) !== canonical(reviewedLocal))
1229
+ throw new Fault(
1230
+ "LOCAL_RECONCILIATION_REQUIRED",
1231
+ "Import confirmed; concurrent local edits prevented rebase.",
1232
+ 5
1233
+ );
1234
+ await rename(localRoot, retained);
1235
+ if (canonical(await inventory(retained)) !== canonical(reviewedLocal)) {
1236
+ await rename(retained, localRoot);
1237
+ throw new Fault(
1238
+ "LOCAL_RECONCILIATION_REQUIRED",
1239
+ "Import confirmed; concurrent local edits were preserved.",
1240
+ 5
1241
+ );
1242
+ }
1243
+ try {
1244
+ await rename(replacement, localRoot);
1245
+ } catch (error) {
1246
+ await rename(retained, localRoot);
1247
+ throw error;
1248
+ }
1249
+ }
1250
+
1251
+ // packages/core/src/project.ts
1252
+ import path14 from "node:path";
1253
+ import { cp as cp4, mkdir as mkdir5, lstat as lstat3, readdir as readdir6, writeFile, mkdtemp as mkdtemp2, rm as rm6, rename as rename3 } from "node:fs/promises";
1254
+ import { fileURLToPath } from "node:url";
1255
+
1256
+ // packages/core/src/oracle.ts
1257
+ var oracle_exports = {};
1258
+ __export(oracle_exports, {
1259
+ OracleAdapter: () => OracleAdapter,
1260
+ SCRIPT_RESTRICT_LEVEL: () => SCRIPT_RESTRICT_LEVEL,
1261
+ compilerDetails: () => compilerDetails,
1262
+ compilerFault: () => compilerFault,
1263
+ compilerSucceeded: () => compilerSucceeded,
1264
+ diagnosticHint: () => diagnosticHint,
1265
+ installSources: () => installSources,
1266
+ jsonDocuments: () => jsonDocuments,
1267
+ missingSavedConnection: () => missingSavedConnection,
1268
+ oracleDiagnostics: () => oracleDiagnostics,
1269
+ parseCompilerDiagnostics: () => parseCompilerDiagnostics,
1270
+ parseStatementMs: () => parseStatementMs,
1271
+ resetCapabilityCache: () => resetCapabilityCache,
1272
+ sqlLiteral: () => sqlLiteral,
1273
+ sqlclToken: () => sqlclToken,
1274
+ targetIdentitySql: () => targetIdentitySql
1275
+ });
1276
+
1277
+ // packages/core/src/contract-hints.ts
1278
+ import path6 from "node:path";
1279
+ import { readdir as readdir4, readFile as readFile4 } from "node:fs/promises";
1280
+
1281
+ // packages/core/src/component-examples.ts
1282
+ import path5 from "node:path";
1283
+ import { readdir as readdir3, readFile as readFile3 } from "node:fs/promises";
1284
+
1285
+ // packages/core/src/reference-index.ts
1286
+ var referenceWords = (text) => text.replace(/([a-z\d])([A-Z])/g, "$1 $2").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
1287
+ function buildReferencePostings(entries) {
1288
+ const postings = /* @__PURE__ */ Object.create(null);
1289
+ entries.forEach((entry, position) => {
1290
+ for (const word of new Set(referenceWords(entry.id + " " + (entry.title ?? "") + " " + entry.text)))
1291
+ (postings[word] ??= []).push(position);
1292
+ });
1293
+ return postings;
1294
+ }
1295
+ var stopwords = /* @__PURE__ */ new Set(["a", "an", "the", "for", "with", "and", "of", "to", "in", "on", "by"]);
1296
+ var cyrillic = /^[Ѐ-ӿ]+$/u;
1297
+ var ukrainianSuffixes = [
1298
+ "\u0430\u043C\u0438",
1299
+ "\u044F\u043C\u0438",
1300
+ "\u043E\u0432\u0456",
1301
+ "\u0435\u0432\u0456",
1302
+ "\u043E\u0433\u043E",
1303
+ "\u043E\u043C\u0443",
1304
+ "\u0438\u043C\u0438",
1305
+ "\u0456\u043C\u0438",
1306
+ "\u0456\u0441\u0442\u044C",
1307
+ "\u044F\u0445",
1308
+ "\u0430\u0445",
1309
+ "\u0456\u0432",
1310
+ "\u0457\u0432",
1311
+ "\u0430\u043C",
1312
+ "\u044F\u043C",
1313
+ "\u043E\u044E",
1314
+ "\u0435\u044E",
1315
+ "\u0454\u044E",
1316
+ "\u043E\u043C",
1317
+ "\u0435\u043C",
1318
+ "\u0438\u0439",
1319
+ "\u0456\u0439",
1320
+ "\u043E\u0457",
1321
+ "\u0438\u0445",
1322
+ "\u0456\u0445",
1323
+ "\u0430",
1324
+ "\u044F",
1325
+ "\u0443",
1326
+ "\u044E",
1327
+ "\u0456",
1328
+ "\u0438",
1329
+ "\u0435",
1330
+ "\u0454",
1331
+ "\u043E",
1332
+ "\u044C",
1333
+ "\u0439"
1334
+ ];
1335
+ function referenceStem(word) {
1336
+ if (cyrillic.test(word)) {
1337
+ if (word.length < 4) return word;
1338
+ for (const suffix of ukrainianSuffixes)
1339
+ if (word.endsWith(suffix) && word.length - suffix.length >= 3) return word.slice(0, -suffix.length);
1340
+ return word;
1341
+ }
1342
+ if (word.length < 4 || /\d$/.test(word)) return word;
1343
+ if (word.endsWith("ies")) return word.slice(0, -3) + "y";
1344
+ if (word.endsWith("sses")) return word.slice(0, -2);
1345
+ if (/(?:x|ch|sh|ss)es$/.test(word)) return word.slice(0, -2);
1346
+ if (word.endsWith("s") && !/(?:ss|us|is)$/.test(word)) return word.slice(0, -1);
1347
+ return word;
1348
+ }
1349
+ var referenceTerms = (text) => referenceWords(text).filter((word) => !stopwords.has(word));
1350
+ var referenceStems = (text) => referenceTerms(text).map(referenceStem);
1351
+ var stemmedReference = (text) => " " + referenceStems(text).join(" ") + " ";
1352
+ var aliases = {
1353
+ textarea: [["text", "area"]],
1354
+ textfield: [["text", "field"]],
1355
+ textbox: [["text", "field"]],
1356
+ datepicker: [["date", "picker"]],
1357
+ dropdown: [["select", "list"]],
1358
+ combo: [["combobox"]],
1359
+ toggle: [["switch"]],
1360
+ graph: [["chart"]],
1361
+ lov: [["list", "value"]],
1362
+ ir: [["interactive", "report"]],
1363
+ ig: [["interactive", "grid"]],
1364
+ da: [["dynamic", "action"]],
1365
+ nav: [["navigation"]],
1366
+ auth: [["authentication"], ["authorization"]],
1367
+ javascript: [["java", "script"]],
1368
+ plsql: [["pl", "sql"]],
1369
+ \u043A\u043D\u043E\u043F\u043A: [["button"]],
1370
+ \u0441\u0442\u043E\u0440\u0456\u043D\u043A: [["page"]],
1371
+ \u0444\u043E\u0440\u043C: [["form"]],
1372
+ \u0434\u0456\u0430\u0433\u0440\u0430\u043C: [["chart"]],
1373
+ \u0433\u0440\u0430\u0444\u0456\u043A: [["chart"]],
1374
+ \u0437\u0432\u0456\u0442: [["report"]],
1375
+ \u0456\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D: [["interactive"]],
1376
+ \u043A\u0430\u0440\u0442\u043A: [["card"]],
1377
+ \u043A\u0430\u043B\u0435\u043D\u0434\u0430\u0440: [["calendar"]],
1378
+ \u043F\u0435\u0440\u0435\u043C\u0438\u043A\u0430\u0447: [["switch"]],
1379
+ \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u043A: [["validation"]],
1380
+ \u0432\u0430\u043B\u0456\u0434\u0430\u0446\u0456: [["validation"]],
1381
+ \u043F\u0440\u043E\u0446\u0435\u0441: [["process"]],
1382
+ \u043E\u0431\u0447\u0438\u0441\u043B\u0435\u043D\u043D: [["computation"]],
1383
+ \u0434\u0438\u043D\u0430\u043C\u0456\u0447\u043D: [["dynamic"]],
1384
+ \u0434\u0456\u044F: [["action"]],
1385
+ \u0434\u0456\u0457: [["action"]],
1386
+ \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0456: [["authorization"]],
1387
+ \u0430\u0432\u0442\u0435\u043D\u0442\u0438\u0444\u0456\u043A\u0430\u0446\u0456: [["authentication"]],
1388
+ \u043D\u0430\u0432\u0456\u0433\u0430\u0446\u0456: [["navigation"]],
1389
+ \u043C\u0435\u043D\u044E: [["menu"]],
1390
+ \u0440\u0435\u0433\u0456\u043E\u043D: [["region"]],
1391
+ \u0444\u0430\u0441\u0435\u0442\u043D: [["faceted"]],
1392
+ \u043F\u043E\u0448\u0443\u043A: [["search"]],
1393
+ \u043C\u043E\u0434\u0430\u043B\u044C\u043D: [["modal"]],
1394
+ \u0432\u0456\u043A\u043D: [["dialog"]],
1395
+ \u0434\u0456\u0430\u043B\u043E\u0433: [["dialog"]],
1396
+ \u0437\u0430\u0432\u0430\u043D\u0442\u0430\u0436\u0435\u043D\u043D: [["upload"]],
1397
+ \u0444\u0430\u0439\u043B: [["file"]],
1398
+ \u0434\u0430\u0442: [["date"]],
1399
+ \u0442\u0435\u043A\u0441\u0442: [["text"]],
1400
+ \u043F\u043E\u043B: [["field"]],
1401
+ \u043F\u0440\u0438\u0445\u043E\u0432\u0430\u043D: [["hidden"]],
1402
+ \u0435\u043B\u0435\u043C\u0435\u043D\u0442: [["item"]],
1403
+ \u0441\u043F\u0438\u0441\u043E\u043A: [["list"]],
1404
+ \u0441\u043F\u0438\u0441\u043A: [["list"]],
1405
+ \u0437\u043D\u0430\u0447\u0435\u043D\u043D: [["value"]],
1406
+ \u0441\u0442\u0430\u0442\u0438\u0447\u043D: [["static"]],
1407
+ \u0432\u043C\u0456\u0441\u0442: [["content"]],
1408
+ \u0441\u0456\u0442\u043A: [["grid"]],
1409
+ \u0433\u0440\u0456\u0434: [["grid"]],
1410
+ \u0440\u0435\u0434\u0430\u0433\u0443\u0432\u0430\u043D\u043D: [["edit"]],
1411
+ \u0440\u0435\u0434\u0430\u0433\u043E\u0432\u0430\u043D: [["editable"]],
1412
+ \u0432\u0438\u0431\u0456\u0440: [["select"]],
1413
+ \u043F\u0435\u0440\u0435\u0445\u0456\u0434: [["redirect"], ["branch"]],
1414
+ \u0433\u0456\u043B\u043A: [["branch"]],
1415
+ \u043E\u043D\u043E\u0432\u043B\u0435\u043D\u043D: [["refresh"]],
1416
+ \u043F\u043E\u043A\u0430\u0437\u043D\u0438\u043A: [["metric"]],
1417
+ \u043F\u0430\u043D\u0435\u043B: [["dashboard"], ["panel"]],
1418
+ \u0433\u043E\u043B\u043E\u0432\u043D: [["home"]],
1419
+ \u0432\u0445\u0456\u0434: [["login"]],
1420
+ \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D: [["global"]],
1421
+ \u043F\u0456\u043A\u0442\u043E\u0433\u0440\u0430\u043C: [["icon"]],
1422
+ \u0456\u043A\u043E\u043D\u043A: [["icon"]],
1423
+ \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A: [["title"]],
1424
+ \u043A\u043E\u043B\u043E\u043D\u043A: [["column"]],
1425
+ \u0441\u0442\u043E\u0432\u043F\u0447\u0438\u043A: [["bar"]],
1426
+ \u043B\u0456\u043D\u0456\u0439\u043D: [["line"]],
1427
+ \u043A\u0440\u0443\u0433\u043E\u0432: [["pie"]],
1428
+ \u043C\u0430\u043F: [["map"]],
1429
+ \u043A\u0430\u0440\u0442: [["map"]],
1430
+ \u0441\u0435\u043A\u0446\u0456: [["section"]],
1431
+ \u0432\u0432\u0435\u0434\u0435\u043D\u043D: [["entry"], ["data", "entry"]]
1432
+ };
1433
+ function referenceQueryTerms(query, limit2 = 16) {
1434
+ const seen = /* @__PURE__ */ new Set();
1435
+ const terms = [];
1436
+ for (const stem of referenceStems(query)) {
1437
+ if (seen.has(stem)) continue;
1438
+ seen.add(stem);
1439
+ terms.push({ stem, alternatives: [[stem], ...aliases[stem] ?? []] });
1440
+ if (terms.length === limit2) break;
1441
+ }
1442
+ return terms;
1443
+ }
1444
+ var queryPhrase = (terms) => " " + terms.map((term) => term.stem).join(" ") + " ";
1445
+ var routingPattern = /(?:^|[._/])_(?:index|common|shared|template_options|configuration-modules|common_variables)\b|(?:^|\/)README$/;
1446
+ var routingReference = (id, title) => routingPattern.test(id) || routingPattern.test(title);
1447
+ var navigationalWords = /* @__PURE__ */ new Set([
1448
+ "index",
1449
+ "common",
1450
+ "readme",
1451
+ "routing",
1452
+ "contract",
1453
+ "contracts",
1454
+ "load",
1455
+ "order"
1456
+ ]);
1457
+ var navigationalQuery = (query) => /[:/]/.test(query.trim()) || referenceWords(query).some((word) => navigationalWords.has(word));
1458
+ function primaryCodeBlock(text, limit2 = 2500) {
1459
+ const lines = text.split("\n");
1460
+ const blocks2 = [];
1461
+ let open4;
1462
+ for (const line of lines) {
1463
+ if (open4) {
1464
+ const close = line.match(/^(\s*)(`{3,}|~{3,})\s*$/);
1465
+ if (close && close[1] === open4.indent && close[2][0] === open4.fence[0] && close[2].length >= open4.fence.length) {
1466
+ blocks2.push({ language: open4.language, lines: open4.lines });
1467
+ open4 = void 0;
1468
+ } else open4.lines.push(line.startsWith(open4.indent) ? line.slice(open4.indent.length) : line);
1469
+ continue;
1470
+ }
1471
+ const start = line.match(/^(\s*)(`{3,}|~{3,})\s*([\w.+-]*)\s*$/);
1472
+ if (start) open4 = { indent: start[1], fence: start[2], language: start[3].toLowerCase(), lines: [] };
1473
+ }
1474
+ const chosen = blocks2.find((block) => block.language === "apexlang") ?? blocks2.find((block) => !block.language) ?? blocks2.sort((a, b) => b.lines.join("\n").length - a.lines.join("\n").length)[0];
1475
+ if (!chosen) return null;
1476
+ const full = chosen.lines.join("\n");
1477
+ if (!full.trim()) return null;
1478
+ return boundCode({ language: chosen.language, text: full, truncated: false, length: full.length }, limit2);
1479
+ }
1480
+ function boundCode(code, limit2) {
1481
+ if (code.text.length <= limit2) return code;
1482
+ const cut = code.text.lastIndexOf("\n", limit2);
1483
+ return { ...code, text: code.text.slice(0, cut > limit2 / 2 ? cut : limit2), truncated: true };
1484
+ }
1485
+ function codeWanted(include, offset, position) {
1486
+ return include === "code" || include !== "metadata" && offset === 0 && position === 0;
1487
+ }
1488
+ var CODE_LIMIT = 2500;
1489
+ var SEARCH_LINKS = 3;
1490
+ function fitResults(results, budget, size) {
1491
+ const halve = (hit, floor) => {
1492
+ if (typeof hit.text !== "string" || hit.text.length <= floor) return false;
1493
+ const next = Math.floor(hit.text.length / 2);
1494
+ hit.text = hit.text.slice(0, Math.max(floor, next));
1495
+ return true;
1496
+ };
1497
+ const shrinkCode = (hit, floor) => {
1498
+ if (!hit.code || hit.code.text.length <= floor) return false;
1499
+ hit.code = boundCode(hit.code, Math.max(floor, Math.floor(hit.code.text.length / 2)));
1500
+ return true;
1501
+ };
1502
+ while (size(results) > budget) {
1503
+ if (results.slice(1).some((hit) => halve(hit, 300))) continue;
1504
+ if (results.some((hit) => shrinkCode(hit, 600))) continue;
1505
+ if (results.slice(1).some((hit) => "relatedReferences" in hit && delete hit.relatedReferences)) continue;
1506
+ if (results.slice(1).some((hit) => "requiresReferences" in hit && delete hit.requiresReferences))
1507
+ continue;
1508
+ if (results.some((hit) => halve(hit, 100))) continue;
1509
+ if (results.some((hit) => hit.code && delete hit.code)) continue;
1510
+ break;
1511
+ }
1512
+ return results;
1513
+ }
1514
+ var identifierQuery = (query) => /^[A-Za-z][\w.:/-]*$/.test(query.trim()) && /[a-z][A-Z]|[-_.:/]/.test(query.trim());
1515
+ var canonicalPattern = /[._/](?:standard|basic|minimal|example|default)(?:-[a-z-]+)?$|\/recipes\/basic$/;
1516
+ var canonicalReference = (id) => canonicalPattern.test(id);
1517
+ var lengthPenalty = (length) => Math.min(150, Math.max(0, Math.log2(length / 2e3)) * 25);
1518
+ function scoreReference(input) {
1519
+ const { terms, matched } = input;
1520
+ if (matched * 2 < terms.length && !input.exact) return null;
1521
+ let titleHits = 0;
1522
+ let titleOrder = 0;
1523
+ for (let i = 0; i < terms.length; i++) {
1524
+ const term = terms[i];
1525
+ let hit = false;
1526
+ for (const alternative of term.alternatives) {
1527
+ hit = true;
1528
+ for (const stem of alternative) if (!input.titleStems.has(stem)) hit = false;
1529
+ if (hit) break;
1530
+ }
1531
+ if (hit) {
1532
+ titleHits++;
1533
+ titleOrder += 50 + 10 * (terms.length - i);
1534
+ }
1535
+ }
1536
+ const coverage = matched / terms.length;
1537
+ let score = (input.exact ? 1e4 : 0) + (input.titleText === input.phrase || input.titleText.startsWith(input.phrase) ? input.titleWeight : 0) + (input.titleText.includes(input.phrase) ? 400 : 0) + titleOrder + (titleHits === terms.length ? 200 : 0) + 300 * coverage * coverage + (input.quoted ? 150 : 0) + input.prior + // Routing documents sink below concrete templates unless the query asks for them.
1538
+ (input.routing ? input.navigational ? 150 : -250 : 0) + (input.canonical && !input.navigational ? 60 : 0) - lengthPenalty(input.length) + 1 / (1 + input.length / 1e3);
1539
+ if (input.bodyText && terms.length) {
1540
+ const body = input.bodyText();
1541
+ if (body.includes(input.phrase)) score += 40;
1542
+ for (let i = 1; i < terms.length; i++)
1543
+ if (body.includes(" " + terms[i - 1].stem + " " + terms[i].stem + " ")) score += 60;
1544
+ }
1545
+ return score;
1546
+ }
1547
+
1548
+ // packages/core/src/component-examples.ts
1549
+ var MIN_BLOCK = 250;
1550
+ var MAX_BLOCK = 4e3;
1551
+ var KEEP = 8;
1552
+ var TYPE_LINE = /^\s*type: (?:[A-Za-z]+\/)?([A-Za-z][A-Za-z0-9]*)\s*$/u;
1553
+ var SOURCE_TYPES = /* @__PURE__ */ new Set([
1554
+ "sql",
1555
+ "query",
1556
+ "plsql",
1557
+ "function",
1558
+ "body",
1559
+ "expression",
1560
+ "static",
1561
+ "table",
1562
+ "local",
1563
+ "item",
1564
+ "page",
1565
+ "region",
1566
+ "none",
1567
+ "default",
1568
+ "code"
1569
+ ]);
1570
+ var OPENER = /^(\s*)([a-z][A-Za-z]*)\b.*\($/u;
1571
+ var USAGE_KINDS = /* @__PURE__ */ new Set([
1572
+ "region",
1573
+ "pageItem",
1574
+ "button",
1575
+ "process",
1576
+ "dynamicAction",
1577
+ "validation",
1578
+ "branch"
1579
+ ]);
1580
+ var MAX_VALUES = 32;
1581
+ var examples;
1582
+ var indent = (line) => line.length - line.trimStart().length;
1583
+ function sourceOf(document) {
1584
+ const begin = document.indexOf("````apexlang\n");
1585
+ if (begin < 0) return void 0;
1586
+ const end = document.indexOf("\n````", begin + 13);
1587
+ return end < 0 ? void 0 : document.slice(begin + 13, end);
1588
+ }
1589
+ function* blocks(lines) {
1590
+ for (const [start, line] of lines.entries()) {
1591
+ const opener = OPENER.exec(line.trimEnd());
1592
+ if (!opener) continue;
1593
+ const depth = opener[1].length;
1594
+ let end = start + 1;
1595
+ while (end < lines.length && !(lines[end].trim() === ")" && indent(lines[end]) === depth)) end += 1;
1596
+ if (end >= lines.length) continue;
1597
+ let type;
1598
+ for (let at = start + 1; at < end && !type; at += 1)
1599
+ if (indent(lines[at]) === depth + 4) type = TYPE_LINE.exec(lines[at])?.[1];
1600
+ yield { keyword: opener[2], type, text: lines.slice(start, end + 1).join("\n") };
1601
+ }
1602
+ }
1603
+ function ownProperties(text) {
1604
+ const lines = text.split("\n");
1605
+ const depth = indent(lines[0]);
1606
+ const found = /* @__PURE__ */ new Map();
1607
+ let group = "";
1608
+ let skip = -1;
1609
+ for (const line of lines.slice(1, -1)) {
1610
+ const at = indent(line);
1611
+ if (!line.trim() || skip >= 0 && at > skip) continue;
1612
+ skip = -1;
1613
+ if (at === depth + 4) {
1614
+ group = /^\s*([A-Za-z]\w*) \{$/u.exec(line)?.[1] ?? "";
1615
+ if (OPENER.test(line.trimEnd())) skip = at;
1616
+ }
1617
+ const property = /^\s*([A-Za-z]\w*): (\S.*)$/u.exec(line);
1618
+ if (property && (at === depth + 4 || group && at === depth + 8))
1619
+ found.set(at === depth + 4 ? property[1] : `${group}.${property[1]}`, property[2].trimEnd());
1620
+ }
1621
+ return found;
1622
+ }
1623
+ function keep(index, key, example) {
1624
+ const list2 = index.get(key) ?? [];
1625
+ list2.push(example);
1626
+ list2.sort((a, b) => a.text.length - b.text.length);
1627
+ index.set(key, list2.slice(0, KEEP));
1628
+ }
1629
+ async function load() {
1630
+ const root = path5.join(resourceRoot(), "public-templates", "26.2", "documents");
1631
+ const index = /* @__PURE__ */ new Map();
1632
+ const usage = /* @__PURE__ */ new Map();
1633
+ let applications;
1634
+ try {
1635
+ applications = (await readdir3(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
1636
+ } catch {
1637
+ return { index, usage };
1638
+ }
1639
+ for (const application of applications.sort()) {
1640
+ const pages2 = (await readdir3(path5.join(root, application))).filter((f) => /^p\d+.*\.md$/u.test(f)).sort();
1641
+ for (const page of pages2) {
1642
+ const source = sourceOf(await readFile3(path5.join(root, application, page), "utf8"));
1643
+ if (!source) continue;
1644
+ const id = `oracle:26.2:public-template/${application}/${page.replace(/\.md$/u, "")}`;
1645
+ for (const block of blocks(source.split("\n"))) {
1646
+ const key = block.type ? `${block.keyword}:${block.type}` : block.keyword;
1647
+ if (USAGE_KINDS.has(block.keyword)) {
1648
+ const counted = usage.get(key) ?? { blocks: 0, properties: /* @__PURE__ */ new Map() };
1649
+ counted.blocks += 1;
1650
+ for (const [property, value] of ownProperties(block.text)) {
1651
+ const seen = counted.properties.get(property) ?? { count: 0, values: /* @__PURE__ */ new Map() };
1652
+ seen.count += 1;
1653
+ if (/^[A-Za-z][\w/-]*$/u.test(value) && (seen.values.has(value) || seen.values.size < MAX_VALUES))
1654
+ seen.values.set(value, (seen.values.get(value) ?? 0) + 1);
1655
+ counted.properties.set(property, seen);
1656
+ }
1657
+ usage.set(key, counted);
1658
+ }
1659
+ if (block.text.length < MIN_BLOCK || block.text.length > MAX_BLOCK) continue;
1660
+ const types = new Set(
1661
+ [...block.text.matchAll(/^\s*type: (?:[A-Za-z]+\/)?([A-Za-z]\w*)\s*$/gmu)].flatMap((m) => referenceStems(m[1])).filter((stem) => !SOURCE_TYPES.has(stem))
1662
+ );
1663
+ const chartType = block.keyword === "region" && block.type === "chart" ? /\n\s*chart \{\s*\n\s*type: (\w+)/u.exec(block.text)?.[1]?.toLowerCase() ?? "bar" : void 0;
1664
+ if (chartType) types.add(chartType);
1665
+ const example = {
1666
+ id,
1667
+ text: block.text,
1668
+ stems: new Set(referenceStems(block.text)),
1669
+ types,
1670
+ chartType
1671
+ };
1672
+ keep(index, key, example);
1673
+ if (block.keyword === "region" && block.type === "chart")
1674
+ for (const variant of types) keep(index, `${key}:${variant}`, example);
1675
+ if (block.type) keep(index, `*:${block.type}`, example);
1676
+ }
1677
+ }
1678
+ }
1679
+ return { index, usage };
1680
+ }
1681
+ async function componentUsage(kind, type) {
1682
+ examples ??= load();
1683
+ const counted = (await examples).usage.get(type ? `${kind}:${type}` : kind);
1684
+ if (!counted) return [];
1685
+ return [...counted.properties].map(([property, seen]) => {
1686
+ const values = [...seen.values].sort((a, b) => b[1] - a[1]);
1687
+ const total = values.reduce((sum, [, count]) => sum + count, 0);
1688
+ return {
1689
+ property,
1690
+ share: seen.count / counted.blocks,
1691
+ values: values.map(([value]) => value),
1692
+ dominance: total ? values[0][1] / total : 1
1693
+ };
1694
+ }).sort((a, b) => b.share - a.share);
1695
+ }
1696
+ async function componentExample(type, options = {}) {
1697
+ examples ??= load();
1698
+ const { index } = await examples;
1699
+ const key = type ? `${options.kind ?? "*"}:${type}` : options.kind;
1700
+ const list2 = key ? index.get(key) ?? (type ? index.get(`*:${type}`) : void 0) : void 0;
1701
+ if (!list2?.length) return void 0;
1702
+ const wanted = new Set(referenceStems(options.request ?? ""));
1703
+ const overlap = (example) => (example.chartType && wanted.has(example.chartType) ? 1e3 : 0) + [...wanted].reduce(
1704
+ (score, stem) => score + (example.types.has(stem) ? 100 : 0) + (example.stems.has(stem) ? 1 : 0),
1705
+ 0
1706
+ );
1707
+ const variants = type === "chart" ? [...wanted].flatMap((stem) => index.get(`region:chart:${stem}`) ?? []) : [];
1708
+ const best = [...list2, ...variants].reduce((a, b) => overlap(b) > overlap(a) ? b : a);
1709
+ return { id: best.id, text: best.text };
1710
+ }
1711
+ function contractComponentType(title) {
1712
+ const name = title.split(" \u2014 ")[0].split("/").at(-1).trim();
1713
+ return /^[A-Za-z][A-Za-z0-9]*$/u.test(name) ? name : void 0;
1714
+ }
1715
+ function contractComponent(id) {
1716
+ const at = id.indexOf("inventory/app/page/");
1717
+ if (at < 0) return void 0;
1718
+ const segments = id.slice(at + "inventory/app/page/".length).split("/");
1719
+ const camel2 = (s) => s.replace(/-([a-z])/gu, (_m, c) => c.toUpperCase());
1720
+ const variant = segments.findIndex((s) => s === "plugin-variants" || s === "template-component");
1721
+ if (variant === 1) return { kind: camel2(segments[0]), type: camel2(segments[2]) };
1722
+ if (segments.length === 2 && segments[0] === segments[1]) return { kind: camel2(segments[0]) };
1723
+ return void 0;
1724
+ }
1725
+ var PAGE_PATTERNS = [
1726
+ {
1727
+ pattern: "modal form page (create, save, delete, cancel, close dialog, row processing)",
1728
+ request: [/\b(?:modal|dialog)\b/iu, /\bform\b/iu],
1729
+ contains: [
1730
+ /^\s*pageMode: modalDialog\s*$/mu,
1731
+ /^\s{4}region \S+ \(\n\s+name: .*\n\s+type: form\s*$/mu,
1732
+ /^\s*type: formAutoRowProcessing\s*$/mu,
1733
+ /^\s*type: closeDialog\s*$/mu,
1734
+ /^\s*type: formInitialization\s*$/mu,
1735
+ /^\s{4}button create \(/mu,
1736
+ /^\s{4}button delete \(/mu,
1737
+ /^\s{4}button save \(/mu,
1738
+ /^\s{4}dynamicAction /mu
1739
+ ]
1740
+ }
1741
+ ];
1742
+ var MAX_PAGE = 9e3;
1743
+ var pages;
1744
+ async function loadPages() {
1745
+ const root = path5.join(resourceRoot(), "public-templates", "26.2", "documents");
1746
+ const best = /* @__PURE__ */ new Map();
1747
+ let applications;
1748
+ try {
1749
+ applications = (await readdir3(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
1750
+ } catch {
1751
+ return best;
1752
+ }
1753
+ for (const application of applications.sort())
1754
+ for (const page of (await readdir3(path5.join(root, application))).filter((f) => /^p\d+.*\.md$/u.test(f)).sort()) {
1755
+ const text = sourceOf(await readFile3(path5.join(root, application, page), "utf8"));
1756
+ if (!text || text.length > MAX_PAGE) continue;
1757
+ for (const { pattern, contains } of PAGE_PATTERNS) {
1758
+ if (!contains.every((re) => re.test(text))) continue;
1759
+ const current = best.get(pattern);
1760
+ if (!current || text.length < current.text.length)
1761
+ best.set(pattern, {
1762
+ id: `oracle:26.2:public-template/${application}/${page.replace(/\.md$/u, "")}`,
1763
+ text
1764
+ });
1765
+ }
1766
+ }
1767
+ return best;
1768
+ }
1769
+ async function pageExamples(request) {
1770
+ const wanted = PAGE_PATTERNS.filter(({ request: words }) => words.every((re) => re.test(request)));
1771
+ if (!wanted.length) return [];
1772
+ pages ??= loadPages();
1773
+ const found = await pages;
1774
+ return wanted.flatMap(({ pattern }) => {
1775
+ const page = found.get(pattern);
1776
+ return page ? [{ pattern, ...page }] : [];
1777
+ });
1778
+ }
1779
+
1780
+ // packages/core/src/contract-hints.ts
1781
+ var contracts;
1782
+ var camel = (s) => s.replace(/-([a-z])/gu, (_m, c) => c.toUpperCase());
1783
+ function parseContract(text, segments) {
1784
+ const kind = /^- componentType: `([^`]+)`/mu.exec(text)?.[1];
1785
+ if (!kind) return void 0;
1786
+ const at = segments.findIndex((s) => s === "plugin-variants" || s === "template-component");
1787
+ const properties = [];
1788
+ let group = "";
1789
+ for (const line of text.split("\n")) {
1790
+ const heading = /^### (\S+)/u.exec(line);
1791
+ if (heading) {
1792
+ group = line.includes("(direct group)") ? "" : heading[1];
1793
+ continue;
1794
+ }
1795
+ const property = /^- `([A-Za-z][\w]*)` — .*; (—|`.*`);\s*$/u.exec(line);
1796
+ if (!property) continue;
1797
+ const condition = property[2] === "\u2014" ? void 0 : property[2].replace(/`/gu, "").replace(/\b[A-Za-z]+\[([^\]]+)\]/gu, "$1").split(" or ").map((clause) => [...new Set(clause.split(" and "))].join(" and ")).filter((clause, i, all) => all.indexOf(clause) === i).join(" or ").slice(0, 240);
1798
+ const type = / — `(<[^`]+>)`/u.exec(line)?.[1];
1799
+ const required = /`; [^;]*; (Yes|No); /u.exec(line)?.[1];
1800
+ const enumeration = /`<enum:\[(.*?)\]>`/u.exec(line)?.[1];
1801
+ const labelled = enumeration ? [...enumeration.matchAll(/(?:^|, )([\w-]+):"/gu)].map((m) => m[1]) : void 0;
1802
+ const plain = enumeration && !labelled.length ? enumeration.split(", ") : [];
1803
+ const values = labelled?.length ? [...new Set(labelled)] : plain.every((name) => /^[A-Za-z][\w-]*$/u.test(name)) ? [...new Set(plain)] : void 0;
1804
+ properties.push({
1805
+ group,
1806
+ name: property[1],
1807
+ ...condition ? { condition } : {},
1808
+ ...type ? { type } : {},
1809
+ ...required ? { required: required === "Yes" } : {},
1810
+ ...values?.length ? { values } : {},
1811
+ .../; lovType=EVENTS; /u.test(line) ? { namedList: true } : {}
1812
+ });
1813
+ }
1814
+ const parentType = /^- appliesWhen: `[a-zA-Z]+\[identification\.type\] = ([A-Za-z]\w*)`\s*$/mu.exec(
1815
+ text
1816
+ )?.[1];
1817
+ return {
1818
+ kind,
1819
+ ...at >= 0 ? { variant: camel(segments[at + 1]) } : {},
1820
+ segments,
1821
+ ...parentType ? { parentType } : {},
1822
+ properties
1823
+ };
1824
+ }
1825
+ async function load2() {
1826
+ const root = path6.join(resourceRoot(), "references", "26.2", "documents", "app");
1827
+ const found = [];
1828
+ const walk = async (dir, segments) => {
1829
+ let entries;
1830
+ try {
1831
+ entries = await readdir4(dir, { withFileTypes: true });
1832
+ } catch {
1833
+ return;
1834
+ }
1835
+ for (const entry of entries) {
1836
+ if (entry.isDirectory()) await walk(path6.join(dir, entry.name), [...segments, entry.name]);
1837
+ else if (entry.name.endsWith(".md") && entry.name === `${segments.at(-1)}.md`) {
1838
+ const contract = parseContract(await readFile4(path6.join(dir, entry.name), "utf8"), segments);
1839
+ if (contract) found.push(contract);
1840
+ }
1841
+ }
1842
+ };
1843
+ await walk(root, []);
1844
+ return found;
1845
+ }
1846
+ function labels(hint) {
1847
+ return hint.replace(/^inside /u, "").split(" of ").map((part) => {
1848
+ const match = /^(\S+)(?: ([^\s(]+))?(?: \(type: ([^)]+)\))?$/u.exec(part.trim());
1849
+ if (!match) return { kind: "" };
1850
+ const type = match[3]?.split("/").at(-1);
1851
+ return { kind: match[1], ...match[2] ? { name: match[2] } : {}, ...type ? { type } : {} };
1852
+ });
1853
+ }
1854
+ function contractFor(all, component, parent) {
1855
+ const kebab = parent?.kind.replace(/[A-Z]/gu, (c) => `-${c.toLowerCase()}`);
1856
+ const pick = (matching) => parent?.type && matching.find((c) => c.parentType === parent.type) || kebab && matching.find((c) => c.segments.includes(kebab)) || matching[0];
1857
+ const variant = pick(
1858
+ all.filter(
1859
+ (c) => c.kind === component.kind && (component.type ? c.variant === component.type : !c.variant)
1860
+ )
1861
+ );
1862
+ if (variant || !component.type) return variant;
1863
+ const plain = pick(all.filter((c) => c.kind === component.kind && !c.variant));
1864
+ return plain?.properties.some((p) => !p.group && p.name === "type" && p.values?.includes(component.type)) ? plain : void 0;
1865
+ }
1866
+ var list = (names) => [...new Set(names)].slice(0, 30).join(", ");
1867
+ async function propertyFix(type, message, hint) {
1868
+ if (type === "DUPLICATED_COMPONENT" && /executionMappingIdentifier: null/u.test(message))
1869
+ return "give every process of the page its own advanced { executionMappingIdentifier: <distinct numeric identifier> }";
1870
+ if (type.startsWith("MISSING_REQUIRED")) return missingFix(message, hint);
1871
+ if (type !== "INVALID_PROPERTY" || !hint) return void 0;
1872
+ const property = /Invalid property: ([A-Za-z]\w*)/u.exec(message)?.[1];
1873
+ if (!property) return void 0;
1874
+ try {
1875
+ contracts ??= load2();
1876
+ const all = await contracts;
1877
+ const chain = labels(hint);
1878
+ const named = chain.findIndex((label) => label.name);
1879
+ if (named < 0) return void 0;
1880
+ const group = chain.slice(0, named).map((label) => label.kind).reverse().join(".");
1881
+ if (group === "heading" && chain[named].kind === "column" && chain[named].type === "hidden" && chain[named + 1]?.type === "classicReport")
1882
+ return `remove the whole heading { \u2026 } group from column ${chain[named].name}: a hidden classicReport column takes no heading (keep layout { sequence })`;
1883
+ const contract = contractFor(all, chain[named], chain[named + 1]);
1884
+ if (!contract) return void 0;
1885
+ const where = contract.properties.filter((p) => p.name === property);
1886
+ const component = `${contract.kind}${contract.variant ? ` (type: ${contract.variant})` : ""}`;
1887
+ if (where.length) {
1888
+ const here = where.filter((p) => p.group === group);
1889
+ if (here.length && here.every((p) => p.condition))
1890
+ return `${property} applies to ${component} only when ${[...new Set(here.map((p) => p.condition))].join(" or ")}`;
1891
+ if (!here.length && new Set(where.map((p) => p.group)).size === 1)
1892
+ return `${property} belongs in ${where.map((p) => p.group ? `group ${p.group}` : "the component itself (no group)").filter((v, i, a) => a.indexOf(v) === i).join(" or ")} of ${component}${where[0].condition ? ` when ${where[0].condition}` : ""}`;
1893
+ if (here.length) return void 0;
1894
+ }
1895
+ const valid = contract.properties.filter((p) => p.group === group).map((p) => p.name);
1896
+ if (where.length)
1897
+ return `${property} is not valid in ${group || "the component itself"} of ${component}; valid there: ${list(valid)}`;
1898
+ return valid.length ? `${component} has no ${property}; ${group || "its direct properties"}: ${list(valid)}` : `${component} has no ${property} and no group ${group}; groups: ${list(contract.properties.map((p) => p.group).filter(Boolean))}`;
1899
+ } catch {
1900
+ return void 0;
1901
+ }
1902
+ }
1903
+ var choices = (values, limit2) => values.slice(0, limit2).join(" | ") + (values.length > limit2 ? ` | \u2026 ${values.length - limit2} more` : "");
1904
+ async function missingFix(message, hint) {
1905
+ const missing = /Missing required parameter(?: \(\d+\))?: (\w+) - (\w+)(?: \((\w+)\))?/u.exec(message);
1906
+ if (!missing) return void 0;
1907
+ const group = missing[1] === "identification" ? "" : missing[1];
1908
+ const name = missing[2];
1909
+ let value = `<${missing[3] ?? "value"}>`;
1910
+ let target = "the component that starts at the reported line";
1911
+ let note = "";
1912
+ try {
1913
+ const chain = hint ? labels(hint) : [];
1914
+ const component = chain[0]?.name ? chain[0] : void 0;
1915
+ contracts ??= load2();
1916
+ const contract = component && contractFor(await contracts, component, chain[1]);
1917
+ const found = contract?.properties.filter((p) => p.group === group && p.name === name) ?? [];
1918
+ if (component && found.length) {
1919
+ target = `${component.kind} ${component.name}`;
1920
+ const used = (await componentUsage(component.kind, component.type)).find(
1921
+ (entry) => entry.property === (group ? `${group}.${name}` : name)
1922
+ );
1923
+ const values = valueList(contract, group, name, void 0, used?.values ?? []);
1924
+ const sample = (await componentExample(component.type, { kind: component.kind }))?.text.match(
1925
+ new RegExp(`^\\s*${name}: (\\S{1,80})$`, "mu")
1926
+ )?.[1];
1927
+ if (values) value = values;
1928
+ else if (sample?.startsWith("@/")) value = sample;
1929
+ else if (found[0].type) value = found[0].type;
1930
+ const condition = found.every((p) => p.condition) ? found[0].condition : "";
1931
+ if (condition && !condition.includes("= sample")) note = ` (required when ${condition.slice(0, 160)})`;
1932
+ }
1933
+ } catch {
1934
+ }
1935
+ return `add to ${target}: ${group ? `${group} { ${name}: ${value} }` : `${name}: ${value}`}${note}`;
1936
+ }
1937
+ function componentNote(kind) {
1938
+ return kind === "process" ? "Keep advanced { executionMappingIdentifier } on every process, a different integer for each process of the page (for example page * 100 + n): 26.2 reports DUPLICATED_COMPONENT without it." : void 0;
1939
+ }
1940
+ var COMMON_SHARE = 0.25;
1941
+ var PARTIAL = "(most used in Oracle samples; the compiler error lists all)";
1942
+ function valueList(contract, group, name, shown, sampled) {
1943
+ const defined = contract.properties.filter((p) => p.group === group && p.name === name);
1944
+ const lists = [
1945
+ ...new Map(defined.flatMap((p) => p.values ? [[p.values.join(), p.values]] : [])).values()
1946
+ ];
1947
+ if (!lists.length) {
1948
+ const used = sampled.filter((value) => !value.includes("/")).slice(0, 12);
1949
+ return defined.some((p) => p.namedList) && used.length ? `${used.join(" | ")} | \u2026 ${PARTIAL}` : void 0;
1950
+ }
1951
+ const score = (list2) => (shown && list2.includes(shown) ? 1e3 : 0) + sampled.filter((value) => list2.includes(value)).length;
1952
+ const ranked = lists.map((list2) => ({ list: list2, score: score(list2) })).sort((a, b) => b.score - a.score);
1953
+ if (ranked.length > 1 && ranked[0].score === ranked[1].score) return void 0;
1954
+ return ranked[0].list.length > 1 ? choices(ranked[0].list, 12) : void 0;
1955
+ }
1956
+ async function exampleValues(text, id) {
1957
+ try {
1958
+ contracts ??= load2();
1959
+ const all = await contracts;
1960
+ const at = id?.indexOf("inventory/app/") ?? -1;
1961
+ const path15 = at < 0 ? void 0 : id.slice(at + "inventory/app/".length).split("/").slice(0, -1).join("/");
1962
+ const root = path15 === void 0 ? void 0 : all.find((c) => c.segments.join("/") === path15);
1963
+ const lines = text.split("\n");
1964
+ const indent2 = (line) => line.length - line.trimStart().length;
1965
+ const found = /* @__PURE__ */ new Map();
1966
+ const usage = /* @__PURE__ */ new Map();
1967
+ const sampled = async (label, property) => {
1968
+ const key = `${label.kind}:${label.type ?? ""}`;
1969
+ if (!usage.has(key)) usage.set(key, await componentUsage(label.kind, label.type));
1970
+ return usage.get(key).find((entry) => entry.property === property);
1971
+ };
1972
+ const stack = [];
1973
+ let first;
1974
+ for (const [i, line] of lines.entries()) {
1975
+ if (!line.trim()) continue;
1976
+ const depth = indent2(line);
1977
+ while (stack.length && stack.at(-1).depth >= depth) stack.pop();
1978
+ const parent = stack.at(-1);
1979
+ const opener = /^\s*([a-z][A-Za-z]*)(?: (\S+))? \($/u.exec(line);
1980
+ if (opener) {
1981
+ let type;
1982
+ for (let j = i + 1; j < lines.length && !type; j += 1) {
1983
+ if (lines[j].trim() && indent2(lines[j]) <= depth) break;
1984
+ if (indent2(lines[j]) === depth + 4)
1985
+ type = /^\s*type: (?:[A-Za-z]+\/)?([A-Za-z]\w*)\s*$/u.exec(lines[j])?.[1];
1986
+ }
1987
+ const label = { kind: opener[1], ...type ? { type } : {} };
1988
+ const contract = !stack.length && root ? root : contractFor(all, label, parent?.label);
1989
+ stack.push({ depth, label, contract, path: stack.length ? `${parent.path}${opener[1]}.` : "" });
1990
+ first ??= stack[0];
1991
+ continue;
1992
+ }
1993
+ if (!parent) continue;
1994
+ const group = /^\s*([A-Za-z]\w*) \{$/u.exec(line)?.[1];
1995
+ if (group) {
1996
+ stack.push({ ...parent, depth, group: parent.group ? `${parent.group}.${group}` : group });
1997
+ continue;
1998
+ }
1999
+ const property = /^\s*([A-Za-z]\w*): (\S.*)$/u.exec(line);
2000
+ if (!property || !parent.contract || property[1] === "type" && !parent.group) continue;
2001
+ const name = `${parent.group ? `${parent.group}.` : ""}${property[1]}`;
2002
+ if (found.has(parent.path + name)) continue;
2003
+ const used = await sampled(parent.label, name);
2004
+ const values = valueList(
2005
+ parent.contract,
2006
+ parent.group ?? "",
2007
+ property[1],
2008
+ property[2].trimEnd(),
2009
+ used?.values ?? []
2010
+ );
2011
+ if (values)
2012
+ found.set(parent.path + name, {
2013
+ values,
2014
+ nested: Boolean(parent.path),
2015
+ open: used ? used.share * (1 - used.dominance) : 0
2016
+ });
2017
+ }
2018
+ if (first?.contract)
2019
+ for (const entry of await componentUsage(first.label.kind, first.label.type)) {
2020
+ if (entry.share < COMMON_SHARE) break;
2021
+ const [group, name] = entry.property.split(".");
2022
+ if (!name || found.has(entry.property)) continue;
2023
+ const values = valueList(first.contract, group, name, void 0, entry.values);
2024
+ if (values)
2025
+ found.set(entry.property, { values, nested: false, open: entry.share * (1 - entry.dominance) });
2026
+ }
2027
+ const rank = (entry) => (entry.open <= 0 ? 4 : entry.nested ? 2 : 0) - (entry.values.endsWith(PARTIAL) ? 1 : entry.open);
2028
+ const ordered = [...found].sort((a, b) => rank(a[1]) - rank(b[1]));
2029
+ return ordered.length ? Object.fromEntries(ordered.map(([key, entry]) => [key, entry.values])) : void 0;
2030
+ } catch {
2031
+ return void 0;
2032
+ }
2033
+ }
2034
+ var SKELETON_SKIP = /* @__PURE__ */ new Set([
2035
+ "security",
2036
+ "config",
2037
+ "comments",
2038
+ "serverSideCondition",
2039
+ "help",
2040
+ "userDefinedAttributes",
2041
+ "clickCounting",
2042
+ "advanced"
2043
+ ]);
2044
+ async function contractSkeleton(id) {
2045
+ const at = id.indexOf("inventory/app/");
2046
+ if (at < 0) return void 0;
2047
+ const segments = id.slice(at + "inventory/app/".length).split("/").slice(0, -1);
2048
+ try {
2049
+ contracts ??= load2();
2050
+ const contract = (await contracts).find((c) => c.segments.join("/") === segments.join("/"));
2051
+ if (!contract) return void 0;
2052
+ const value = (p) => p.values ? p.values.slice(0, 6).join(" | ") + (p.values.length > 6 ? " | \u2026" : "") : p.type ?? "<value>";
2053
+ const shown = contract.properties.filter((p) => !p.condition && !SKELETON_SKIP.has(p.group));
2054
+ const groups = [...new Set(shown.map((p) => p.group))];
2055
+ const lines = [`${contract.kind} <name> (`];
2056
+ for (const group of groups) {
2057
+ const members = shown.filter((p) => p.group === group);
2058
+ const rows = members.map((p) => `${p.name}: ${value(p)}${p.required ? "" : " (optional)"}`);
2059
+ if (!group) lines.push(...rows.map((row) => ` ${row}`));
2060
+ else lines.push(` ${group} {`, ...rows.map((row) => ` ${row}`), " }");
2061
+ }
2062
+ lines.push(")");
2063
+ return lines.join("\n");
2064
+ } catch {
2065
+ return void 0;
2066
+ }
2067
+ }
2068
+
2069
+ // packages/core/src/oracle.ts
2070
+ import { performance as performance2 } from "node:perf_hooks";
2071
+ import path13 from "node:path";
2072
+ import { randomUUID as randomUUID2 } from "node:crypto";
2073
+ import { cp as cp3, mkdir as mkdir4, mkdtemp, readFile as readFile7, readdir as readdir5, realpath as realpath5, rename as rename2, rm as rm5, stat as stat3 } from "node:fs/promises";
2074
+
2075
+ // packages/core/src/connections.ts
2076
+ import path8 from "node:path";
2077
+ import { chmod as chmod2, constants as constants2, lstat as lstat2, mkdir as mkdir3, open as open3, realpath as realpath3, rm as rm3, stat } from "node:fs/promises";
2078
+
2079
+ // packages/core/src/local-env.ts
2080
+ import path7 from "node:path";
2081
+ import { constants, open as open2, realpath as realpath2 } from "node:fs/promises";
2082
+ function parseLocalEnv(contents) {
2083
+ const result = /* @__PURE__ */ Object.create(null);
2084
+ for (const line of contents.split(/\r?\n/)) {
2085
+ if (!line.trim() || line.trimStart().startsWith("#")) continue;
2086
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line.trim());
2087
+ if (!match || Object.hasOwn(result, match[1]))
2088
+ throw new Fault("ENV_FILE_INVALID", "The local ENV file has an invalid or duplicate entry.", 2);
2089
+ let value = match[2];
2090
+ if (value.startsWith('"') || value.startsWith("'")) {
2091
+ const quote = value[0], end = value.lastIndexOf(quote);
2092
+ if (end === 0 || !/^\s*(?:#.*)?$/.test(value.slice(end + 1)))
2093
+ throw new Fault("ENV_FILE_INVALID", "The local ENV file has an invalid quoted entry.", 2);
2094
+ value = value.slice(1, end);
2095
+ } else value = value.replace(/\s+#.*$/, "").trimEnd();
2096
+ result[match[1]] = value;
2097
+ }
2098
+ return result;
2099
+ }
2100
+ async function readLocalEnv(file) {
2101
+ const requested = path7.resolve(file), physical = await realpath2(requested);
2102
+ if (requested !== physical)
2103
+ throw new Fault("ENV_FILE_UNSAFE", "Credential ENV paths cannot use symlink aliases.", 2);
2104
+ const cwd = path7.dirname(physical);
2105
+ const root = await runProcess({
2106
+ executable: "git",
2107
+ args: ["rev-parse", "--show-toplevel"],
2108
+ cwd,
2109
+ timeoutMs: 5e3
2110
+ });
2111
+ if (root.code !== 0)
2112
+ throw new Fault("ENV_FILE_UNSAFE", "Credential ENV files must belong to a Git working tree.", 2);
2113
+ const relative = path7.relative(root.stdout.trim(), physical);
2114
+ const tracked = await runProcess({
2115
+ executable: "git",
2116
+ args: ["ls-files", "--error-unmatch", "--", relative],
2117
+ cwd: root.stdout.trim(),
2118
+ timeoutMs: 5e3
2119
+ });
2120
+ const ignored = await runProcess({
2121
+ executable: "git",
2122
+ args: ["check-ignore", "-q", "--", relative],
2123
+ cwd: root.stdout.trim(),
2124
+ timeoutMs: 5e3
2125
+ });
2126
+ if (tracked.code === 0 || ignored.code !== 0)
2127
+ throw new Fault(
2128
+ "ENV_FILE_UNSAFE",
2129
+ "Credential ENV files must be ignored by Git and absent from tracked files.",
2130
+ 2
2131
+ );
2132
+ const handle = await open2(physical, constants.O_RDONLY | constants.O_NOFOLLOW);
2133
+ try {
2134
+ const info = await handle.stat();
2135
+ if (!info.isFile() || info.size > 65536 || typeof process.getuid === "function" && info.uid !== process.getuid())
2136
+ throw new Fault(
2137
+ "ENV_FILE_UNSAFE",
2138
+ "Credential ENV files must be bounded regular files owned by the current user.",
2139
+ 2
2140
+ );
2141
+ return parseLocalEnv(await handle.readFile("utf8"));
2142
+ } finally {
2143
+ await handle.close();
2144
+ }
2145
+ }
2146
+
2147
+ // packages/core/src/connections.ts
2148
+ var savedConnectionName = external_exports.string().min(1).max(512).regex(/^[^\x00-\x1f\x7f-\x9f]+$/);
2149
+ var ordsUrl = external_exports.string().url().max(2048).refine((value) => {
2150
+ const url = new URL(value);
2151
+ return ["http:", "https:"].includes(url.protocol) && // Plaintext HTTP would expose the ORDS password; allow it for loopback only.
2152
+ (url.protocol === "https:" || ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) && !url.username && !url.password && !url.search && !url.hash && url.pathname.endsWith("/") && !url.pathname.replace(/\/+$/, "").endsWith("/_/sql") && !/[\s"\x00-\x1f]/.test(value);
2153
+ }, "Use the ORDS schema HTTPS URL ending in / (HTTP only for localhost), without credentials, query or fragment.");
2154
+ var ordsUsername = external_exports.string().min(1).max(128).regex(/^[^"\x00-\x1f\x7f-\x9f]+$/);
2155
+ var ordsSchema = external_exports.strictObject({ url: ordsUrl, username: ordsUsername });
2156
+ var connectionSchema = external_exports.strictObject({
2157
+ kind: external_exports.literal("sqlcl-store"),
2158
+ name: savedConnectionName.optional(),
2159
+ ords: ordsSchema.optional()
2160
+ }).refine((value) => !!(value.name || value.ords), "Configure a direct connection or ORDS endpoint.");
2161
+ var storeSchema = external_exports.record(refName, connectionSchema);
2162
+ var references = /* @__PURE__ */ new WeakMap();
2163
+ var connectionReference = (connection) => references.get(connection);
2164
+ var credentialSchema = ordsSchema.extend({ password: external_exports.string().min(1).max(4096) }).strict();
2165
+ function checkPassword(password) {
2166
+ if (!password || password.length > 4096 || /["\x00-\x1f\x7f-\x9f]/.test(password))
2167
+ throw new Fault(
2168
+ "INVALID_ORDS_PASSWORD",
2169
+ "ORDS passwords must be nonempty and cannot contain control characters or double quotes.",
2170
+ 2
2171
+ );
2172
+ return password;
2173
+ }
2174
+ async function credentialPath(name) {
2175
+ parse(refName, name);
2176
+ return contained(managedHome(), path8.join("credentials", name + ".json"));
2177
+ }
2178
+ async function ordsCredentials(connection) {
2179
+ const name = references.get(connection);
2180
+ if (!name || !connection.ords)
2181
+ throw new Fault(
2182
+ "ORDS_CONNECTION_REQUIRED",
2183
+ "Configure this connection reference with a plugin-level ORDS endpoint and credentials.",
2184
+ 3,
2185
+ "blocked"
2186
+ );
2187
+ const file = await credentialPath(name);
2188
+ if (!await exists(file))
2189
+ throw new Fault(
2190
+ "ORDS_CREDENTIALS_REQUIRED",
2191
+ "Save the ORDS password locally in plugin connection settings.",
2192
+ 3,
2193
+ "blocked"
2194
+ );
2195
+ if (process.platform !== "win32" && ((await stat(file)).mode & 63) !== 0)
2196
+ throw new Fault(
2197
+ "ORDS_CREDENTIAL_PERMISSIONS",
2198
+ "ORDS credential files must only be readable by their owner (0600).",
2199
+ 3,
2200
+ "blocked"
2201
+ );
2202
+ let value;
2203
+ try {
2204
+ value = parse(credentialSchema, await readJson(file));
2205
+ } catch {
2206
+ throw new Fault(
2207
+ "ORDS_CREDENTIALS_INVALID",
2208
+ "The local ORDS credential file is invalid. Save it again in plugin settings.",
2209
+ 3,
2210
+ "blocked"
2211
+ );
2212
+ }
2213
+ if (value.url !== connection.ords.url || value.username !== connection.ords.username)
2214
+ throw new Fault(
2215
+ "ORDS_CREDENTIALS_REQUIRED",
2216
+ "Save credentials for the configured ORDS endpoint and username.",
2217
+ 3,
2218
+ "blocked"
2219
+ );
2220
+ checkPassword(value.password);
2221
+ return value;
2222
+ }
2223
+ async function connections() {
2224
+ const file = path8.join(managedHome(), "connections.json");
2225
+ return Object.assign(
2226
+ /* @__PURE__ */ Object.create(null),
2227
+ await exists(file) ? parse(storeSchema, await readJson(file)) : {}
2228
+ );
2229
+ }
2230
+ async function resolveConnection(name) {
2231
+ const connection = (await connections())[name];
2232
+ if (!connection)
2233
+ throw new Fault(
2234
+ "CONNECTION_REQUIRED",
2235
+ "Configure the requested SQLcl connection reference locally; do not send credentials in chat.",
2236
+ 3,
2237
+ "blocked"
2238
+ );
2239
+ references.set(connection, name);
2240
+ return connection;
2241
+ }
2242
+ async function editConnection(name, value) {
2243
+ parse(refName, name);
2244
+ return withLock(path8.join(managedHome(), "connections.lock"), async () => {
2245
+ const current = await connections();
2246
+ let credentialsDeleted = false;
2247
+ if (value) current[name] = parse(connectionSchema, { ...current[name], ...value });
2248
+ else {
2249
+ delete current[name];
2250
+ const file = await credentialPath(name);
2251
+ credentialsDeleted = await exists(file);
2252
+ await rm3(file, { force: true });
2253
+ }
2254
+ await writeJson(path8.join(managedHome(), "connections.json"), current);
2255
+ return { name, status: value ? "configured" : "removed", credentialsDeleted };
2256
+ });
2257
+ }
2258
+ function isChild(root, file) {
2259
+ const relative = path8.relative(root, file);
2260
+ return relative !== "" && relative !== ".." && !relative.startsWith(".." + path8.sep) && !path8.isAbsolute(relative);
2261
+ }
2262
+ async function readPasswordFile(file, roots) {
2263
+ const candidates = roots.filter((root) => isChild(root, file));
2264
+ if (!candidates.length)
2265
+ throw new Fault(
2266
+ "PASSWORD_FILE_UNSAFE",
2267
+ "The password file must be inside the managed home, the project directory or the current working directory.",
2268
+ 2
2269
+ );
2270
+ let handle;
2271
+ let before;
2272
+ let physical;
2273
+ try {
2274
+ before = await lstat2(file);
2275
+ if (before.isSymbolicLink() || !before.isFile())
2276
+ throw new Fault("PASSWORD_FILE_UNSAFE", "The password file must be a regular non-symlink file.", 2);
2277
+ physical = await realpath3(file);
2278
+ const resolved = await Promise.all(candidates.map((root) => realpath3(root).catch(() => null)));
2279
+ if (!resolved.some((root) => root !== null && isChild(root, physical)))
2280
+ throw new Fault(
2281
+ "PASSWORD_FILE_UNSAFE",
2282
+ "The password file must resolve inside the managed home, the project directory or the current working directory.",
2283
+ 2
2284
+ );
2285
+ handle = await open3(
2286
+ physical,
2287
+ constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0) | (constants2.O_NONBLOCK ?? 0)
2288
+ );
2289
+ } catch (error) {
2290
+ if (error instanceof Fault) throw error;
2291
+ const code = error.code;
2292
+ throw new Fault(
2293
+ "PASSWORD_FILE_UNSAFE",
2294
+ code === "ELOOP" || code === "EMLINK" ? "The password file must not be a symbolic link." : "The password file cannot be opened.",
2295
+ 2
2296
+ );
2297
+ }
2298
+ try {
2299
+ const info = await handle.stat();
2300
+ const current = await lstat2(file);
2301
+ if (!info.isFile() || !current.isFile() || current.isSymbolicLink() || await realpath3(file) !== physical || before.dev !== info.dev || before.ino !== info.ino || current.dev !== info.dev || current.ino !== info.ino)
2302
+ throw new Fault("PASSWORD_FILE_UNSAFE", "The password file changed or is not a regular file.", 2);
2303
+ if (process.platform !== "win32" && ((info.mode & 63) !== 0 || typeof process.getuid === "function" && info.uid !== process.getuid()))
2304
+ throw new Fault(
2305
+ "PASSWORD_FILE_UNSAFE",
2306
+ "The password file must belong to the current user and only be accessible by that user (chmod 600).",
2307
+ 2
2308
+ );
2309
+ const buffer = Buffer.alloc(4 * 4096 + 3);
2310
+ if (info.size >= buffer.length)
2311
+ throw new Fault("PASSWORD_FILE_UNSAFE", "The password file exceeds the maximum credential size.", 2);
2312
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
2313
+ if (bytesRead !== info.size)
2314
+ throw new Fault("PASSWORD_FILE_UNSAFE", "The password file changed while being read.", 2);
2315
+ return buffer.toString("utf8", 0, bytesRead);
2316
+ } catch (error) {
2317
+ if (error instanceof Fault) throw error;
2318
+ throw new Fault("PASSWORD_FILE_UNSAFE", "The password file could not be verified and read.", 2);
2319
+ } finally {
2320
+ await handle.close();
2321
+ }
2322
+ }
2323
+ async function configureConnection(name, input) {
2324
+ parse(refName, name);
2325
+ if (input.envFile) {
2326
+ if (input.password !== void 0 || input.passwordFile)
2327
+ throw new Fault("INVALID_INPUT", "Select one local credential source.", 2);
2328
+ const values = await readLocalEnv(input.envFile);
2329
+ const password = values[input.passwordKey ?? "ORDS_PASSWORD"];
2330
+ const username = values[input.usernameKey ?? "ORDS_USERNAME"];
2331
+ const url = values[input.urlKey ?? "ORDS_URL"];
2332
+ if (!password || !(input.ordsUsername ?? username) || !(input.ordsUrl ?? url))
2333
+ throw new Fault("ENV_CREDENTIALS_MISSING", "The selected local ENV credential keys are missing.", 2);
2334
+ input = {
2335
+ ...input,
2336
+ password,
2337
+ ordsUsername: input.ordsUsername ?? username,
2338
+ ordsUrl: input.ordsUrl ?? url
2339
+ };
2340
+ }
2341
+ return withLock(path8.join(managedHome(), "connections.lock"), async () => {
2342
+ const current = await connections();
2343
+ const previous = current[name];
2344
+ const ords = input.ordsUrl || input.ordsUsername ? parse(ordsSchema, { url: input.ordsUrl, username: input.ordsUsername }) : previous?.ords;
2345
+ const value = parse(connectionSchema, {
2346
+ ...previous,
2347
+ kind: "sqlcl-store",
2348
+ ...input.sqlclName ? { name: input.sqlclName } : {},
2349
+ ...ords ? { ords } : {}
2350
+ });
2351
+ let password = input.password;
2352
+ if (input.passwordFile) {
2353
+ if (password !== void 0) throw new Fault("INVALID_INPUT", "Supply one local password source.", 2);
2354
+ const file = path8.resolve(input.passwordFile);
2355
+ const roots = [managedHome(), process.cwd()];
2356
+ if (input.project && !roots.some((root) => isChild(root, file))) {
2357
+ const requested = path8.resolve(input.project);
2358
+ if (requested !== path8.parse(requested).root && isChild(requested, file)) {
2359
+ try {
2360
+ await loadProject(requested);
2361
+ } catch {
2362
+ throw new Fault(
2363
+ "PASSWORD_FILE_UNSAFE",
2364
+ "Use a configured project to bound its password file.",
2365
+ 2
2366
+ );
2367
+ }
2368
+ roots.push(requested);
2369
+ }
2370
+ }
2371
+ password = (await readPasswordFile(file, roots)).replace(/\r?\n$/, "");
2372
+ }
2373
+ if (password !== void 0 && !ords)
2374
+ throw new Fault(
2375
+ "INVALID_INPUT",
2376
+ "Configure the ORDS endpoint and username before saving its password.",
2377
+ 2
2378
+ );
2379
+ if (ords && (input.ordsUrl || input.ordsUsername || password !== void 0)) {
2380
+ if (password !== void 0) {
2381
+ const folder = await contained(managedHome(), "credentials");
2382
+ await mkdir3(folder, { recursive: true, mode: 448 });
2383
+ if (process.platform !== "win32") await chmod2(folder, 448);
2384
+ await writeJson(await credentialPath(name), { ...ords, password: checkPassword(password) });
2385
+ } else {
2386
+ references.set(value, name);
2387
+ await ordsCredentials(value);
2388
+ }
2389
+ }
2390
+ current[name] = value;
2391
+ await writeJson(path8.join(managedHome(), "connections.json"), current);
2392
+ return { name, status: "configured" };
2393
+ });
2394
+ }
2395
+
2396
+ // packages/core/src/sqlcl-config.ts
2397
+ import path9 from "node:path";
2398
+ var sqlclMode = external_exports.enum(["cli", "mcp"]);
2399
+ var sqlclRestriction = external_exports.enum(["4", "1"]);
2400
+ var databaseTransport = external_exports.enum(["direct", "ords"]);
2401
+ var sqlclConfigSchema = external_exports.strictObject({
2402
+ schemaVersion: external_exports.literal(1),
2403
+ mode: sqlclMode,
2404
+ mcpRestrictLevel: sqlclRestriction,
2405
+ databaseTransport: databaseTransport.optional()
2406
+ });
2407
+ async function sqlclConfig() {
2408
+ const home = managedHome();
2409
+ if (!await exists(home)) return { schemaVersion: 1, mode: "cli", mcpRestrictLevel: "4" };
2410
+ const file = await contained(home, "sqlcl.json");
2411
+ return await exists(file) ? parse(sqlclConfigSchema, await readJson(file)) : { schemaVersion: 1, mode: "cli", mcpRestrictLevel: "4" };
2412
+ }
2413
+ async function configureSqlcl(mode, level, transport) {
2414
+ const home = managedHome();
2415
+ return withLock(path9.join(home, "sqlcl-config.lock"), async () => {
2416
+ const previous = await sqlclConfig();
2417
+ const configuration = parse(sqlclConfigSchema, {
2418
+ ...previous,
2419
+ mode,
2420
+ mcpRestrictLevel: level ?? previous.mcpRestrictLevel,
2421
+ ...transport ? { databaseTransport: transport } : {}
2422
+ });
2423
+ if (configuration.mode === "mcp" && configuration.databaseTransport === "ords")
2424
+ throw new Fault(
2425
+ "ORDS_CLI_REQUIRED",
2426
+ "ORDS HTTP requires SQLcl CLI mode. Select CLI execution for this transport.",
2427
+ 3,
2428
+ "blocked"
2429
+ );
2430
+ await writeJson(await contained(home, "sqlcl.json"), configuration);
2431
+ return configuration;
2432
+ });
2433
+ }
2434
+
2435
+ // packages/core/src/sqlcl-read-scope.ts
2436
+ import { AsyncLocalStorage } from "node:async_hooks";
2437
+ import { randomUUID } from "node:crypto";
2438
+ var storage = new AsyncLocalStorage();
2439
+ function connectedReadsDisabled() {
2440
+ return /^(?:0|false|off)$/i.test(process.env.APEXREST_CONNECTED_READS ?? "");
2441
+ }
2442
+ async function withConnectedReads(action) {
2443
+ if (storage.getStore() || connectedReadsDisabled()) return action();
2444
+ const scope = { id: randomUUID() };
2445
+ try {
2446
+ return await storage.run(scope, action);
2447
+ } finally {
2448
+ await closeSqlclReadScope(scope.id);
2449
+ }
2450
+ }
2451
+ function currentReadScope() {
2452
+ return storage.getStore()?.id;
2453
+ }
2454
+
2455
+ // packages/core/src/sqlcl-warm.ts
2456
+ import { performance } from "node:perf_hooks";
2457
+ var READY_TIMEOUT_MS = 6e4;
2458
+ var PROBE = "APEXREST_RESTRICT_PROBE";
2459
+ function warmImportDisabled() {
2460
+ return /^(?:0|false|off)$/i.test(process.env.APEXREST_WARM_IMPORT ?? "");
2461
+ }
2462
+ var WarmImportServer = class {
2463
+ constructor(request) {
2464
+ this.request = request;
2465
+ this.client = new SqlclMcpClient({
2466
+ executable: request.executable,
2467
+ args: ["-R", request.restrictLevel, "-mcp"],
2468
+ cwd: request.cwd,
2469
+ ...request.env ? { env: request.env } : {}
2470
+ });
2471
+ this.ready = this.prepare().catch(() => false);
2472
+ }
2473
+ request;
2474
+ client;
2475
+ started = performance.now();
2476
+ ready;
2477
+ taken = false;
2478
+ closed = false;
2479
+ warmMs;
2480
+ async prepare() {
2481
+ const deadline = Date.now() + READY_TIMEOUT_MS;
2482
+ const options = mcpCallOptions({ timeoutMs: READY_TIMEOUT_MS }, deadline);
2483
+ await this.client.open(options());
2484
+ const probe = this.client.text(await this.client.execute(`host echo ${PROBE}`, options, () => false));
2485
+ if (!/SP2-0738/.test(probe) || probe.split(/\r?\n/).some((line) => line.trim() === PROBE)) return false;
2486
+ await this.client.execute(this.request.warmup, options, () => false);
2487
+ this.warmMs = performance.now() - this.started;
2488
+ return this.client.alive && !this.closed;
2489
+ }
2490
+ /**
2491
+ * Run the import batch. Resolves `undefined` when the server cannot be used and
2492
+ * nothing was submitted (the caller then runs the ordinary process). After the
2493
+ * batch is submitted every failure is reported like an interrupted import process.
2494
+ */
2495
+ async run(request) {
2496
+ if (this.taken || this.closed) return void 0;
2497
+ this.taken = true;
2498
+ const started = performance.now();
2499
+ const timing = executionTiming("mcp", true, true);
2500
+ timing.reused = true;
2501
+ let submitted = false;
2502
+ let executeStarted;
2503
+ const deadline = Date.now() + (request.timeoutMs ?? SQLCL_WRITE_TIMEOUT_MS);
2504
+ const options = mcpCallOptions(request, deadline);
2505
+ try {
2506
+ if (!await this.ready || request.signal?.aborted) return void 0;
2507
+ timing.queueMs = performance.now() - started;
2508
+ const connectStarted = performance.now();
2509
+ let connected;
2510
+ try {
2511
+ connected = await this.client.connect(request.connectionName, options, true);
2512
+ } catch {
2513
+ return void 0;
2514
+ }
2515
+ timing.connectMs = performance.now() - connectStarted;
2516
+ if (connected.isError) return void 0;
2517
+ submitted = true;
2518
+ executeStarted = performance.now();
2519
+ const result = await this.client.execute(request.input ?? "", options, () => true);
2520
+ return mcpResult(result, this.client.text(result, true));
2521
+ } catch (error) {
2522
+ if (!submitted) return void 0;
2523
+ const interrupted = request.signal?.aborted ? "cancelled" : Date.now() >= deadline ? "timedOut" : void 0;
2524
+ if (interrupted)
2525
+ return {
2526
+ code: null,
2527
+ stdout: "",
2528
+ stderr: "",
2529
+ timedOut: interrupted === "timedOut",
2530
+ cancelled: interrupted === "cancelled",
2531
+ truncated: false
2532
+ };
2533
+ throw mcpFailure(error, { ...this.request, args: [], mutation: true }, true);
2534
+ } finally {
2535
+ if (executeStarted !== void 0) timing.executeMs = performance.now() - executeStarted;
2536
+ await this.close();
2537
+ if (submitted) emitSqlclTiming(request.onSqlclTiming, timing, started);
2538
+ }
2539
+ }
2540
+ async close() {
2541
+ if (this.closed) return;
2542
+ this.closed = true;
2543
+ await this.client.close();
2544
+ }
2545
+ };
2546
+
2547
+ // packages/core/src/ords.ts
2548
+ import path10 from "node:path";
2549
+ import { realpath as realpath4, rm as rm4 } from "node:fs/promises";
2550
+ async function sqlclHome(executable) {
2551
+ const candidates = path10.isAbsolute(executable) ? [executable] : executable.includes(path10.sep) ? [path10.resolve(executable)] : (process.env.PATH ?? "").split(path10.delimiter).flatMap(
2552
+ (directory) => process.platform === "win32" ? ["", ".exe", ".cmd", ".bat"].map((extension) => path10.join(directory, executable + extension)) : [path10.join(directory, executable)]
2553
+ );
2554
+ for (const candidate of candidates) {
2555
+ if (!await exists(candidate)) continue;
2556
+ const home = path10.dirname(path10.dirname(await realpath4(candidate)));
2557
+ if (await exists(path10.join(home, "lib", "jdbcrest.jar"))) return home;
2558
+ break;
2559
+ }
2560
+ throw new Fault(
2561
+ "ORDS_SQLCL_LIBRARIES_REQUIRED",
2562
+ "ORDS APEX operations require the selected SQLcl installation with lib/jdbcrest.jar and the Oracle APEXlang compiler. Set APEXREST_SQLCL to its bin/sql executable.",
2563
+ 3,
2564
+ "blocked"
2565
+ );
2566
+ }
2567
+ async function resolveOrdsJava(javaHome, stage, env, signal, runner = runProcess) {
2568
+ const executableName = process.platform === "win32" ? "java.exe" : "java";
2569
+ const candidates = [
2570
+ ...[javaHome, process.env.JAVA_HOME].filter((home) => !!home).map((home) => ({ executable: path10.join(home, "bin", executableName), javaHome: home })),
2571
+ { executable: executableName, javaHome: void 0 }
2572
+ ];
2573
+ const attempted = /* @__PURE__ */ new Set();
2574
+ for (const candidate of candidates) {
2575
+ if (attempted.has(candidate.executable)) continue;
2576
+ attempted.add(candidate.executable);
2577
+ if (signal?.aborted) throw new Fault("CANCELLED", "ORDS operation cancelled.", 6, "cancelled");
2578
+ try {
2579
+ const result = await runner({
2580
+ executable: candidate.executable,
2581
+ args: ["--list-modules"],
2582
+ cwd: stage,
2583
+ env: { ...env, JAVA_HOME: candidate.javaHome },
2584
+ timeoutMs: 1e4,
2585
+ ...signal ? { signal } : {}
2586
+ });
2587
+ if (result.cancelled || signal?.aborted)
2588
+ throw new Fault("CANCELLED", "ORDS operation cancelled.", 6, "cancelled");
2589
+ const major = Number(result.stdout.match(/^java\.base@(\d+)/m)?.[1] ?? 0);
2590
+ if (result.code === 0 && !result.timedOut && !result.truncated && major >= 21 && /^jdk\.compiler@/m.test(result.stdout))
2591
+ return candidate;
2592
+ } catch (error) {
2593
+ if (!(error instanceof Fault) || error.code !== "DEPENDENCY_MISSING") throw error;
2594
+ }
2595
+ }
2596
+ throw new Fault(
2597
+ "ORDS_JDK_REQUIRED",
2598
+ "ORDS APEX operations need an installed JDK 21 or newer with jdk.compiler. The configured Java runtime and JAVA_HOME/PATH do not provide one. Set APEXREST_JAVA_HOME or JAVA_HOME to an existing JDK; ordinary SQLcl can continue using its managed JRE.",
2599
+ 3,
2600
+ "blocked"
2601
+ );
2602
+ }
2603
+ async function runOrdsBridge(settings, job, credentials, stage, signal, runner = runProcess) {
2604
+ if (signal?.aborted) throw new Fault("CANCELLED", "ORDS operation cancelled.", 6, "cancelled");
2605
+ const home = await sqlclHome(settings.executable);
2606
+ const helper = path10.join(resourceRoot(), "ords", "OrdsBridge.java");
2607
+ if (!await exists(helper))
2608
+ throw new Fault("ORDS_HELPER_REQUIRED", "The installed plugin is missing its ORDS helper.", 3, "blocked");
2609
+ const jobFile = path10.join(stage, "ords-job.json");
2610
+ const output = path10.join(stage, "ords-result.json");
2611
+ await rm4(output, { force: true });
2612
+ await writeJson(jobFile, { ...job, output });
2613
+ const env = { ...process.env, JAVA_HOME: settings.javaHome };
2614
+ delete env.NODE_OPTIONS;
2615
+ delete env.JAVA_TOOL_OPTIONS;
2616
+ delete env._JAVA_OPTIONS;
2617
+ delete env.JDK_JAVA_OPTIONS;
2618
+ const java = await resolveOrdsJava(settings.javaHome, stage, env, signal, runner);
2619
+ env.JAVA_HOME = java.javaHome;
2620
+ const mutation = job.operation === "import" || job.operation === "script";
2621
+ const processResult = await runner({
2622
+ executable: java.executable,
2623
+ args: [
2624
+ "-cp",
2625
+ [path10.join(home, "lib", "*"), path10.join(home, "lib", "ext", "*")].join(path10.delimiter),
2626
+ helper,
2627
+ jobFile
2628
+ ],
2629
+ cwd: stage,
2630
+ env,
2631
+ input: credentials ? JSON.stringify(credentials) : "",
2632
+ timeoutMs: mutation ? SQLCL_WRITE_TIMEOUT_MS : SQLCL_READ_TIMEOUT_MS,
2633
+ ...signal ? { signal } : {}
2634
+ });
2635
+ if (processResult.timedOut || processResult.cancelled || processResult.truncated)
2636
+ throw new Fault(
2637
+ processResult.truncated ? "OUTPUT_LIMIT" : processResult.cancelled ? "CANCELLED" : "TIMEOUT",
2638
+ "The ORDS helper did not confirm completion. Reconcile any import before retrying.",
2639
+ 6,
2640
+ mutation ? "outcome_unknown" : "cancelled"
2641
+ );
2642
+ let result;
2643
+ if (await exists(output)) {
2644
+ try {
2645
+ const value = await readJson(output);
2646
+ if (value && value.operation === job.operation && ["succeeded", "failed"].includes(value.status))
2647
+ result = value;
2648
+ } catch {
2649
+ }
2650
+ }
2651
+ if (processResult.code !== 0 || result?.status !== "succeeded" || !processResult.stdout.split(/\r?\n/).some((line) => line.trim() === "APEXREST_ORDS_COMPLETE")) {
2652
+ const unknown = mutation && (!result || result.writeStarted === true);
2653
+ throw new Fault(
2654
+ unknown ? "ORDS_OUTCOME_UNKNOWN" : result?.code ?? "ORDS_BRIDGE_FAILED",
2655
+ unknown ? "ORDS import did not confirm a complete outcome; reconcile the target before retrying." : "The Oracle ORDS helper failed. Check the SQLcl/Java prerequisites, ORDS authentication and schema privileges.",
2656
+ unknown ? 6 : 1,
2657
+ unknown ? "outcome_unknown" : "failed"
2658
+ );
2659
+ }
2660
+ return result;
2661
+ }
2662
+
2663
+ // packages/core/src/compatibility.ts
2664
+ import path11 from "node:path";
2665
+ import { readFile as readFile5 } from "node:fs/promises";
2666
+ var APEX_262_PROFILE = {
2667
+ id: "apex262-sqlcl263-mmd3479",
2668
+ apex: "26.2",
2669
+ sqlcl: "26.3.0.260.1620",
2670
+ mmd: "26.2.0+3479",
2671
+ qualification: "partial-local"
2672
+ };
2673
+ function databaseMeetsApex262Minimum(version) {
2674
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:\.|$)/.exec(version);
2675
+ if (!match) return false;
2676
+ const major = Number(match[1]), minor = Number(match[2]);
2677
+ if (major === 23) return minor >= 26;
2678
+ return major > 19 || major === 19 && minor >= 18;
2679
+ }
2680
+ async function sourceMmdVersion(source) {
2681
+ try {
2682
+ const value = JSON.parse(await readFile5(path11.join(source, ".apex/apexlang.json"), "utf8"));
2683
+ const version = value?.mmdVersion;
2684
+ return typeof version === "string" && /^\d+\.\d+\.\d+\+\d+$/.test(version) ? version : null;
2685
+ } catch {
2686
+ return null;
2687
+ }
2688
+ }
2689
+ function evaluatePartialImportCompatibility(input) {
2690
+ const reasons = [];
2691
+ if (input.mode !== "cli" || input.databaseTransport !== "direct")
2692
+ reasons.push("Partial import requires direct SQLcl CLI transport.");
2693
+ if (!input.importFiles) reasons.push("The selected SQLcl import help does not advertise -files.");
2694
+ if (!input.compilerVersion.includes(APEX_262_PROFILE.sqlcl))
2695
+ reasons.push("The SQLcl build is outside the reviewed partial-import profile.");
2696
+ if (input.mmdVersion !== APEX_262_PROFILE.mmd)
2697
+ reasons.push("Source MMD is outside the reviewed APEX 26.2 profile.");
2698
+ if (!/^26\.2(?:\.|$)/.test(input.apexVersion))
2699
+ reasons.push("The target APEX release is outside the reviewed 26.2 profile.");
2700
+ if (!databaseMeetsApex262Minimum(input.databaseVersion))
2701
+ reasons.push("Target database release is unconfirmed or below the APEX 26.2 minimum.");
2702
+ return { ...input, supported: reasons.length === 0, reasons };
2703
+ }
2704
+
2705
+ // packages/core/src/upgrade-audit.ts
2706
+ import path12 from "node:path";
2707
+ import { readFile as readFile6, stat as stat2, opendir } from "node:fs/promises";
2708
+ function parseCodeScan(output, source) {
2709
+ const clean = output.replace(/\x1b\[[0-9;]*m/g, "");
2710
+ const from = clean.indexOf("["), to = clean.lastIndexOf("]");
2711
+ if (from < 0 || to < from) throw new Error("CodeScan did not return its JSON report.");
2712
+ const report = JSON.parse(clean.slice(from, to + 1));
2713
+ if (!Array.isArray(report)) throw new Error("CodeScan report is not a list.");
2714
+ const findings = [];
2715
+ for (const entry of report) {
2716
+ if (!entry || typeof entry.file !== "string" || !Array.isArray(entry.issues))
2717
+ throw new Error("CodeScan report entry is incomplete.");
2718
+ const file = path12.relative(source, path12.resolve(source, entry.file)).replaceAll(path12.sep, "/");
2719
+ if (!file || file.startsWith("../") || path12.isAbsolute(file))
2720
+ throw new Error("CodeScan returned a file outside the inspected source.");
2721
+ for (const issue of entry.issues) {
2722
+ if (typeof issue?.ruleNo !== "string" || typeof issue.msg !== "string" || !Number.isInteger(issue.line) || issue.line < 0 || !Number.isInteger(issue.col) || issue.col < 0)
2723
+ throw new Error("CodeScan issue is incomplete.");
2724
+ findings.push({
2725
+ code: issue.ruleNo,
2726
+ file,
2727
+ line: issue.line,
2728
+ column: issue.col,
2729
+ message: issue.msg,
2730
+ severity: "warning"
2731
+ });
2732
+ }
2733
+ }
2734
+ return findings;
2735
+ }
2736
+ var upgradeRules = [
2737
+ {
2738
+ code: "APEX262_AI_TOOL_CALLS",
2739
+ pattern: /\btool_calls\b/i,
2740
+ message: "Review legacy AI tool_calls handling against the APEX 26.2 response contract."
2741
+ },
2742
+ {
2743
+ code: "APEX262_AI_MESSAGE",
2744
+ pattern: /\bt_chat_response\b/i,
2745
+ message: "Review APEX_AI t_chat_response and response.message usage against the 26.2 response contract."
2746
+ },
2747
+ {
2748
+ code: "APEX262_ASSSO",
2749
+ pattern: /\bASSSO\b/i,
2750
+ message: "Review legacy ASSSO authentication against the APEX 26.2 desupport guidance."
2751
+ },
2752
+ {
2753
+ code: "APEX262_REST_RESOURCE",
2754
+ pattern: /\bAPEX_REST_RESOURCE\b/i,
2755
+ message: "Review legacy APEX_REST_RESOURCE references against APEX 26.2 migration guidance."
2756
+ },
2757
+ {
2758
+ code: "APEX262_ADVISOR",
2759
+ pattern: /\b(?:apex_advisor|advisor)\b/i,
2760
+ message: "Review Advisor references against the APEX 26.2 Advisor changes; this text match may be unrelated."
2761
+ }
2762
+ ];
2763
+ async function auditUpgradeSource(source) {
2764
+ const files = [], directories = [""];
2765
+ const findings = [], skipped = [];
2766
+ let inspected = 0, traversalTruncated = false;
2767
+ discovery: while (directories.length) {
2768
+ const relative = directories.pop();
2769
+ for await (const entry of await opendir(path12.join(source, relative))) {
2770
+ if (++inspected > 1e4) {
2771
+ traversalTruncated = true;
2772
+ break discovery;
2773
+ }
2774
+ const file = path12.posix.join(relative, entry.name);
2775
+ if (entry.isSymbolicLink()) skipped.push(file);
2776
+ else if (entry.isDirectory()) directories.push(file);
2777
+ else if (entry.isFile() && /\.(?:apx|sql|js)$/i.test(file)) files.push(file);
2778
+ }
2779
+ }
2780
+ files.sort();
2781
+ let bytes = 0, scannedFiles = 0;
2782
+ for (const file of files) {
2783
+ const absolute = path12.join(source, file), size = (await stat2(absolute)).size;
2784
+ if (size > 1024 * 1024 || bytes + size > 16 * 1024 * 1024 || scannedFiles >= 2e3) {
2785
+ skipped.push(file);
2786
+ continue;
2787
+ }
2788
+ bytes += size;
2789
+ scannedFiles++;
2790
+ const lines = (await readFile6(absolute, "utf8")).split(/\r?\n/);
2791
+ for (const rule of upgradeRules) {
2792
+ const at = lines.findIndex((line) => rule.pattern.test(line));
2793
+ if (at >= 0)
2794
+ findings.push({ code: rule.code, file, line: at + 1, message: rule.message, severity: "warning" });
2795
+ }
2796
+ }
2797
+ return {
2798
+ status: "advisory",
2799
+ targetRelease: "26.2",
2800
+ scannedFiles,
2801
+ findings,
2802
+ skipped,
2803
+ traversalTruncated,
2804
+ limitation: "Source text review hints only; not a complete dependency, SQL, security or runtime audit."
2805
+ };
2806
+ }
2807
+
2808
+ // packages/core/src/locality.ts
2809
+ import { hostname as hostname2 } from "node:os";
2810
+ var loopback = (host) => ["localhost", "127.0.0.1", "::1", "[::1]"].includes(host.toLowerCase());
2811
+ function localConnectionEndpoint(description) {
2812
+ const jdbc = /jdbc:oracle:(thin|oci):(?:[^@\r\n]*@)?([^\r\n]*)/i.exec(description);
2813
+ if (!jdbc) return { local: false, evidence: "unconfirmed-connection-endpoint" };
2814
+ if (jdbc[1].toLowerCase() === "oci" && !jdbc[2].trim())
2815
+ return { local: true, evidence: "native-local-transport" };
2816
+ const address = jdbc[2].trim();
2817
+ const descriptorHosts = [...address.matchAll(/\(host\s*=\s*([^\s)]+)\)/gi)].map((m) => m[1]);
2818
+ const easy = /^(?:\/\/)?(\[[^\]]+\]|[^/:,?\s]+)(?::\d+)?(?:\/|:)/.exec(address);
2819
+ const hosts = descriptorHosts.length ? descriptorHosts : easy ? [easy[1]] : [];
2820
+ return {
2821
+ local: hosts.length > 0 && hosts.every(loopback),
2822
+ evidence: hosts.length && hosts.every(loopback) ? "effective-loopback-endpoint" : "remote-or-unresolved-endpoint"
2823
+ };
2824
+ }
2825
+ async function localServerHost(serverHost) {
2826
+ const host = serverHost.toLowerCase();
2827
+ if (loopback(host) || host === hostname2().toLowerCase()) return true;
2828
+ const engines = [
2829
+ "docker",
2830
+ "podman",
2831
+ ...process.platform === "darwin" ? ["/opt/podman/bin/podman", "/Applications/Docker.app/Contents/Resources/bin/docker"] : []
2832
+ ];
2833
+ for (const executable of engines) {
2834
+ const podman = executable.endsWith("podman");
2835
+ try {
2836
+ if (podman) {
2837
+ if (process.env.CONTAINER_HOST && !process.env.CONTAINER_HOST.startsWith("unix://")) continue;
2838
+ if (process.platform !== "linux") {
2839
+ const connections2 = await runProcess({
2840
+ executable,
2841
+ args: ["system", "connection", "list", "--format", "json"],
2842
+ cwd: process.cwd(),
2843
+ timeoutMs: 5e3
2844
+ });
2845
+ const entries = JSON.parse(connections2.stdout);
2846
+ const active = process.env.CONTAINER_CONNECTION ? entries.find((entry) => entry.Name === process.env.CONTAINER_CONNECTION) : entries.find((entry) => entry.Default);
2847
+ if (!active?.URI) continue;
2848
+ const endpoint = new URL(active.URI);
2849
+ if (!loopback(endpoint.hostname)) continue;
2850
+ const machines = await runProcess({
2851
+ executable,
2852
+ args: ["machine", "list", "--format", "json"],
2853
+ cwd: process.cwd(),
2854
+ timeoutMs: 5e3
2855
+ });
2856
+ if (machines.code !== 0 || !JSON.parse(machines.stdout).some(
2857
+ (machine) => machine.Running && machine.Port === Number(endpoint.port)
2858
+ ))
2859
+ continue;
2860
+ }
2861
+ } else {
2862
+ const context = process.env.DOCKER_HOST ?? (await runProcess({
2863
+ executable,
2864
+ args: ["context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
2865
+ cwd: process.cwd(),
2866
+ timeoutMs: 5e3
2867
+ })).stdout.trim();
2868
+ if (!/^(unix|npipe):\/\//.test(context)) continue;
2869
+ }
2870
+ const list2 = await runProcess({ executable, args: ["ps", "-q"], cwd: process.cwd(), timeoutMs: 5e3 });
2871
+ const ids = list2.stdout.trim().split(/\s+/).filter((id) => /^[a-f0-9]{12,64}$/.test(id));
2872
+ if (list2.code !== 0 || !ids.length) continue;
2873
+ const names = await runProcess({
2874
+ executable,
2875
+ args: ["inspect", "--format", "{{.Config.Hostname}}", ...ids],
2876
+ cwd: process.cwd(),
2877
+ timeoutMs: 5e3
2878
+ });
2879
+ if (names.code === 0 && names.stdout.trim().split(/\s+/).some((name) => name.toLowerCase() === host))
2880
+ return true;
2881
+ } catch {
2882
+ }
2883
+ }
2884
+ return false;
2885
+ }
2886
+
2887
+ // packages/core/src/oracle.ts
2888
+ var targetIdentitySql = `select 'identity' target_record,
2889
+ sys_context('USERENV','DB_UNIQUE_NAME') db_unique_name,
2890
+ sys_context('USERENV','SERVICE_NAME') service_name,
2891
+ sys_context('USERENV','CURRENT_SCHEMA') parsing_schema,
2892
+ cast(null as varchar2(64)) workspace_id, null workspace, null application_id, null alias, null owner
2893
+ from dual
2894
+ union all
2895
+ select 'workspace', null, null, null, to_char(workspace_id, 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,'''), workspace, null, null, null
2896
+ from apex_workspaces where workspace = :p_workspace
2897
+ union all
2898
+ select 'application', null, null, null, null, workspace, application_id, alias, owner
2899
+ from apex_applications where application_id = :p_app_id`;
2900
+ function workspaceIdentifier(value) {
2901
+ if (typeof value === "string" && /^(?:0|[1-9][0-9]{0,63})$/.test(value)) return value;
2902
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
2903
+ throw new Fault(
2904
+ "WORKSPACE_ID_UNCONFIRMED",
2905
+ "Workspace identity requires exact decimal text. An unsafe legacy numeric ID cannot be reconstructed. Preserve held recovery evidence and obtain a fresh exact observation.",
2906
+ 3,
2907
+ "blocked",
2908
+ {
2909
+ nextActions: [
2910
+ "Obtain a fresh exact-string target observation and create a new apexrest_ship mode:plan. Preserve saved numeric plans, fingerprints and history.",
2911
+ "For a completed ready working copy, use apexrest_apex_sync action:refresh with clean sources before replanning. A 26.2 full plan can obtain a fresh target without changing the stored baseline.",
2912
+ "For importing or outcome_unknown runs, keep ownership and the original recovery evidence. Reconcile the original run before retry, refresh or invalidate."
2913
+ ]
2914
+ }
2915
+ );
2916
+ }
2917
+ var applicationMetadataSql = `select to_char(last_updated_on, 'YYYY-MM-DD"T"HH24:MI:SS', 'NLS_DATE_LANGUAGE=American') last_updated_on,
2918
+ last_updated_by,
2919
+ case when last_updated_on is null then 'Y' else 'N' end last_updated_on_is_null,
2920
+ case when last_updated_by is null then 'Y' else 'N' end last_updated_by_is_null
2921
+ from apex_applications
2922
+ where application_id = :p_app_id and workspace = :p_workspace and owner = :p_owner`;
2923
+ function parseApplicationMetadata(rows) {
2924
+ const row = rows[0];
2925
+ if (row && !Object.hasOwn(row, "last_updated_on") && row.last_updated_on_is_null === "Y")
2926
+ row.last_updated_on = null;
2927
+ if (row && !Object.hasOwn(row, "last_updated_by") && row.last_updated_by_is_null === "Y")
2928
+ row.last_updated_by = null;
2929
+ if (rows.length !== 1 || !row || !Object.hasOwn(row, "last_updated_on") || !Object.hasOwn(row, "last_updated_by"))
2930
+ throw new Fault("SYNC_METADATA_UNCONFIRMED", "Application update metadata is absent or inaccessible.", 5);
2931
+ if ([row.last_updated_on, row.last_updated_by].some((v) => v !== null && typeof v !== "string"))
2932
+ throw new Fault("SYNC_METADATA_UNCONFIRMED", "Unexpected application update metadata.", 5);
2933
+ return {
2934
+ lastUpdatedOn: row.last_updated_on,
2935
+ lastUpdatedBy: row.last_updated_by
2936
+ };
2937
+ }
2938
+ var targetVersionSql = "select (select version_no from apex_release) apex_version, version_full database_version from product_component_version where product like 'Oracle%Database%'";
2939
+ function parseStatementMs(output) {
2940
+ const tail = output.slice(output.lastIndexOf("}") + 1);
2941
+ const matches = [...tail.matchAll(/^Elapsed: (\d+):(\d{2}):(\d{2}(?:\.\d+)?)\s*$/gm)];
2942
+ if (matches.length !== 1)
2943
+ throw new Fault("SQLCL_TIMING_UNCONFIRMED", "SQLcl did not return one statement elapsed interval.", 1);
2944
+ const m = matches[0];
2945
+ const value = (Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3])) * 1e3;
2946
+ if (!Number.isFinite(value) || Number(m[2]) >= 60 || Number(m[3]) >= 60)
2947
+ throw new Fault("SQLCL_TIMING_UNCONFIRMED", "Invalid SQLcl statement elapsed interval.", 1);
2948
+ return value;
2949
+ }
2950
+ var capabilityCache = /* @__PURE__ */ new Map();
2951
+ var CAPABILITY_CACHE_MS = 24 * 60 * 60 * 1e3;
2952
+ var importHelpCache = /* @__PURE__ */ new Map();
2953
+ function resetCapabilityCache() {
2954
+ capabilityCache.clear();
2955
+ importHelpCache.clear();
2956
+ }
2957
+ function raceCancellation(promise, signal, message) {
2958
+ const cancelled = () => new Fault("CANCELLED", message, 6, "cancelled");
2959
+ if (!signal) return promise;
2960
+ if (signal.aborted) return Promise.reject(cancelled());
2961
+ return new Promise((resolve, reject) => {
2962
+ const abort = () => reject(cancelled());
2963
+ signal.addEventListener("abort", abort, { once: true });
2964
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
2965
+ });
2966
+ }
2967
+ function sqlclToken(value) {
2968
+ if (!value || /[\r\n\x00"&]/.test(value))
2969
+ throw new Fault(
2970
+ "INVALID_SQLCL_TOKEN",
2971
+ "SQLcl argument contains a forbidden quote, newline or substitution character.",
2972
+ 2
2973
+ );
2974
+ return '"' + value.replaceAll("\\", "/") + '"';
2975
+ }
2976
+ function sqlLiteral(value) {
2977
+ if (/[\x00-\x1f]/.test(value) || value.length > 1024)
2978
+ throw new Fault("INVALID_SQL_LITERAL", "Invalid SQL literal.", 2);
2979
+ return "'" + value.replaceAll("'", "''") + "'";
2980
+ }
2981
+ function oracleDiagnostics(r, mutation = false, format = "text", captureCompilerOutput = false) {
2982
+ const stdout = r.stdout.replace(/\x1b\[[0-9;]*m/g, ""), stderr = r.stderr.replace(/\x1b\[[0-9;]*m/g, ""), output = stdout + "\n" + stderr;
2983
+ if (r.cancelled || r.timedOut || r.truncated)
2984
+ throw new Fault(
2985
+ r.truncated ? "OUTPUT_LIMIT" : r.cancelled ? "CANCELLED" : "TIMEOUT",
2986
+ "SQLcl did not complete with a confirmed outcome.",
2987
+ 6,
2988
+ mutation ? "outcome_unknown" : "cancelled"
2989
+ );
2990
+ let diagnostics = output;
2991
+ if (format === "json") {
2992
+ diagnostics = stripEnvelopeRows(stdout) + "\n" + stderr;
2993
+ }
2994
+ const missingConnection = r.code !== 0 ? missingSavedConnection(diagnostics) : void 0;
2995
+ if (missingConnection !== void 0)
2996
+ throw new Fault(
2997
+ "SQLCL_CONNECTION_NOT_FOUND",
2998
+ `SQLcl has no saved connection named ${missingConnection}. Create it in SQLcl (conn -save ${missingConnection} ...) or point the APEXREST reference at an existing saved name; the application sources were not checked.`,
2999
+ 3,
3000
+ "blocked",
3001
+ { savedConnection: missingConnection }
3002
+ );
3003
+ if (/ORA-01017|ORA-28000|ORA-28001/i.test(diagnostics))
3004
+ throw new Fault("AUTHENTICATION_FAILED", "Oracle authentication failed.", 4, "blocked");
3005
+ if (/ORA-01031/i.test(diagnostics))
3006
+ throw new Fault("DB_PRIVILEGE", "Oracle privileges are insufficient.", 4, "blocked");
3007
+ if (r.code !== 0 || /(?:ORA-|PLS-|SP2-|SQLCL-)[0-9]+|(?:^|\n)\s*(?:Error(?:\s|:)|Unknown command|Invalid command|Invalid option|Compilation failed|Validation failed)|not connected|Unable to|No APEXlang files/i.test(
3008
+ diagnostics
3009
+ ))
3010
+ throw new Fault(
3011
+ "ORACLE_COMMAND_FAILED",
3012
+ output.trim().slice(0, 6e3) || "SQLcl exited without success.",
3013
+ 1,
3014
+ "failed",
3015
+ captureCompilerOutput ? { output } : void 0
3016
+ );
3017
+ return output;
3018
+ }
3019
+ function missingSavedConnection(output) {
3020
+ const match = /(?:^|\n)[ \t]*(?:Unknown connection|Connection not found|No (?:saved )?connection (?:named|found(?: with name)?))[: \t]+["']?([^\r\n"']*[^\s"'])["']?[ \t.]*(?:\r?\n|$)/i.exec(
3021
+ output
3022
+ ) ?? /(?:^|\n)[ \t]*(?:The )?(?:saved )?connection[ \t]+["']?([^\s"']+?)["']?[ \t]+(?:was not found|not found|does not exist|doesn't exist)\b/i.exec(
3023
+ output
3024
+ );
3025
+ return match ? match[1] : void 0;
3026
+ }
3027
+ function jsonDocuments(text) {
3028
+ const spans = [];
3029
+ let depth = 0, start = -1, quoted = false;
3030
+ for (let i = 0; i < text.length; i++) {
3031
+ const c = text[i];
3032
+ if (quoted) {
3033
+ if (c === "\\") i++;
3034
+ else if (c === '"') quoted = false;
3035
+ } else if (c === '"') quoted = true;
3036
+ else if (c === "{") {
3037
+ if (depth++ === 0) start = i;
3038
+ } else if (c === "}" && depth > 0 && --depth === 0) spans.push([start, i + 1]);
3039
+ }
3040
+ return spans;
3041
+ }
3042
+ function stripEnvelopeRows(stdout) {
3043
+ let result = "", cursor = 0;
3044
+ for (const [start, end] of jsonDocuments(stdout)) {
3045
+ let replacement = stdout.slice(start, end);
3046
+ try {
3047
+ const envelope = JSON.parse(replacement);
3048
+ if (Array.isArray(envelope.results) && envelope.results.length > 0 && envelope.results.every((entry) => Array.isArray(entry.items)))
3049
+ replacement = JSON.stringify({
3050
+ ...envelope,
3051
+ results: envelope.results.map(({ items: _items, ...metadata }) => metadata)
3052
+ });
3053
+ } catch {
3054
+ }
3055
+ result += stdout.slice(cursor, start) + replacement;
3056
+ cursor = end;
3057
+ }
3058
+ return result + stdout.slice(cursor);
3059
+ }
3060
+ var SCRIPT_RESTRICT_LEVEL = "2";
3061
+ var OracleAdapter = class {
3062
+ constructor(runner = runProcess, executable = process.env.APEXREST_SQLCL ?? "sql", mcpRunner = runSqlclMcp) {
3063
+ this.runner = runner;
3064
+ this.executable = executable;
3065
+ this.mcpRunner = mcpRunner;
3066
+ }
3067
+ runner;
3068
+ executable;
3069
+ mcpRunner;
3070
+ selectedTransport;
3071
+ selectedConnections = /* @__PURE__ */ new Map();
3072
+ async settings() {
3073
+ const file = path13.join(managedHome(), "runtime.json");
3074
+ const state = await exists(file) ? await readJson(file) : {};
3075
+ const transport = await (this.selectedTransport ??= sqlclConfig());
3076
+ return {
3077
+ ...transport,
3078
+ executable: process.env.APEXREST_SQLCL ?? state.sqlcl ?? this.executable,
3079
+ javaHome: process.env.APEXREST_JAVA_HOME ?? (state.java ? path13.dirname(path13.dirname(state.java)) : process.env.JAVA_HOME)
3080
+ };
3081
+ }
3082
+ async selectedConnection(connection) {
3083
+ const settings = await this.settings();
3084
+ const key = connectionReference(connection) ?? JSON.stringify(connection);
3085
+ let selected = this.selectedConnections.get(key);
3086
+ if (!selected) {
3087
+ selected = (async () => {
3088
+ if (settings.databaseTransport === "ords") {
3089
+ if (settings.mode !== "cli")
3090
+ throw new Fault("ORDS_CLI_REQUIRED", "ORDS HTTP requires SQLcl CLI mode.", 3, "blocked");
3091
+ return { ords: await ordsCredentials(connection) };
3092
+ }
3093
+ if (!connection.name)
3094
+ throw new Fault(
3095
+ "DIRECT_CONNECTION_REQUIRED",
3096
+ "Configure a direct SQLcl saved connection for this reference or select ORDS HTTP in plugin settings.",
3097
+ 3,
3098
+ "blocked"
3099
+ );
3100
+ return { name: parse(savedConnectionName, connection.name) };
3101
+ })();
3102
+ this.selectedConnections.set(key, selected);
3103
+ }
3104
+ return selected;
3105
+ }
3106
+ async session(input, connection, mutation = false, signal, cwd, format = "text", restrictLevel, isolated = false, label = "session", warm) {
3107
+ if (restrictLevel && (await this.settings()).mode === "mcp")
3108
+ throw new Fault(
3109
+ "SQLCL_MCP_SCRIPT_RESTRICT_UNAVAILABLE",
3110
+ "Restricted script operations require SQLcl CLI mode with -R 2; MCP does not provide an equivalent restriction.",
3111
+ 3,
3112
+ "blocked"
3113
+ );
3114
+ const work = cwd ?? await this.stage();
3115
+ try {
3116
+ return await this.sessionIn(
3117
+ work,
3118
+ input,
3119
+ connection,
3120
+ mutation,
3121
+ signal,
3122
+ format,
3123
+ restrictLevel,
3124
+ isolated,
3125
+ label,
3126
+ warm
3127
+ );
3128
+ } finally {
3129
+ if (!cwd) await this.discardStage(work);
3130
+ }
3131
+ }
3132
+ async sessionIn(work, input, connection, mutation, signal, format, restrictLevel, isolated, label, warm) {
3133
+ const settings = await this.settings();
3134
+ if (mutation) await this.requireMutationSupport();
3135
+ const selected = connection ? await this.selectedConnection(connection) : void 0;
3136
+ const args = [
3137
+ "-S",
3138
+ "-L",
3139
+ ...restrictLevel ? ["-R", restrictLevel] : [],
3140
+ ...selected?.name ? ["-name", selected.name] : ["/nolog"]
3141
+ ];
3142
+ const env = {
3143
+ ...process.env,
3144
+ SQLPATH: "",
3145
+ ORACLE_PATH: "",
3146
+ TNS_ADMIN: process.env.TNS_ADMIN,
3147
+ JAVA_HOME: settings.javaHome
3148
+ };
3149
+ delete env.NODE_OPTIONS;
3150
+ delete env.JAVA_TOOL_OPTIONS;
3151
+ delete env._JAVA_OPTIONS;
3152
+ delete env.JDK_JAVA_OPTIONS;
3153
+ const preamble = "set define off\nset echo off\nset feedback off\n" + (settings.mode === "mcp" && settings.mcpRestrictLevel === "4" ? "" : "whenever oserror exit failure rollback\nwhenever sqlerror exit failure rollback\n");
3154
+ const connect = selected?.ords ? `set history filter default connect
3155
+ connect -orest -user "${selected.ords.username}" -password "${selected.ords.password}" -url "${selected.ords.url}"
3156
+ ` : "";
3157
+ const marker = `APEXREST_COMPLETE_${randomUUID2().replaceAll("-", "")}`;
3158
+ let timingRecorded = false;
3159
+ const request = {
3160
+ mutation,
3161
+ sqlclConnected: !!selected,
3162
+ onSqlclTiming: (timing) => {
3163
+ timingRecorded = true;
3164
+ recordSqlclTiming(label, timing);
3165
+ },
3166
+ executable: settings.executable,
3167
+ args,
3168
+ cwd: work,
3169
+ env,
3170
+ input: preamble + connect + input + "\nexit\n",
3171
+ timeoutMs: mutation ? SQLCL_WRITE_TIMEOUT_MS : SQLCL_READ_TIMEOUT_MS,
3172
+ ...signal ? { signal } : {}
3173
+ };
3174
+ const readScope = !mutation && !restrictLevel && !isolated && selected?.name && !selected.ords ? currentReadScope() : void 0;
3175
+ const pooled = !isolated && (settings.mode === "mcp" ? this.mcpRunner === runSqlclMcp : this.runner === runProcess && (!selected || !!readScope) && settings.databaseTransport !== "ords");
3176
+ let viaServer = settings.mode === "mcp" || pooled;
3177
+ const executionStarted = performance2.now();
3178
+ let raw;
3179
+ try {
3180
+ if (warm && mutation && !viaServer && selected?.name && !selected.ords) {
3181
+ raw = await warm.run({
3182
+ input: preamble + "set serveroutput off\nset sqlformat default\n" + input + `
3183
+ commit;
3184
+ prompt
3185
+ prompt ${marker}
3186
+ `,
3187
+ timeoutMs: SQLCL_WRITE_TIMEOUT_MS,
3188
+ ...signal ? { signal } : {},
3189
+ onSqlclTiming: request.onSqlclTiming,
3190
+ connectionName: selected.name,
3191
+ completionMarker: marker
3192
+ });
3193
+ if (raw) viaServer = true;
3194
+ }
3195
+ raw ??= viaServer ? await (pooled ? runPooledSqlcl : this.mcpRunner)({
3196
+ ...request,
3197
+ cwd: pooled ? await this.sessionHome() : work,
3198
+ // Let SQLcl apply its MCP default. In 26.1, explicit -R 4
3199
+ // also suppresses connmgr output, unlike the default MCP profile.
3200
+ args: settings.mode === "mcp" ? settings.mcpRestrictLevel === "4" ? ["-mcp"] : ["-R", "1", "-mcp"] : [...restrictLevel ? ["-R", restrictLevel] : [], "-mcp"],
3201
+ // CLI's final EXIT commits on success. Preserve that transaction
3202
+ // boundary before acknowledging a write over a persistent session.
3203
+ input: (settings.mode === "cli" ? preamble.replace(/exit failure rollback/g, "continue") : preamble) + // Persistent servers keep SET state between batches; start neutral.
3204
+ (selected?.name ? "rollback;\nbegin dbms_session.reset_package; execute immediate 'alter session set current_schema = ' || dbms_assert.enquote_name(sys_context('USERENV', 'SESSION_USER'), false); end;\n/\n" : "") + "set serveroutput off\nset sqlformat default\n" + input + (mutation ? "\ncommit;\n" : "\n") + // SQLcl 26.3's JSON formatter can omit its final newline; an empty
3205
+ // PROMPT keeps the completion marker on a line of its own.
3206
+ `prompt
3207
+ prompt ${marker}
3208
+ `,
3209
+ mutation,
3210
+ completionMarker: marker,
3211
+ ...selected?.name ? { connectionName: selected.name } : {},
3212
+ ...pooled && settings.mode === "cli" ? { commandConnect: true } : {},
3213
+ ...readScope && pooled ? { readScope } : {}
3214
+ }) : await this.runner(request);
3215
+ } finally {
3216
+ if (!timingRecorded) {
3217
+ const elapsed = performance2.now() - executionStarted;
3218
+ recordSqlclTiming(label, {
3219
+ queueMs: 0,
3220
+ spawnMs: null,
3221
+ connectMs: null,
3222
+ executeMs: elapsed,
3223
+ totalMs: elapsed,
3224
+ reused: false,
3225
+ mutation,
3226
+ connected: !!selected,
3227
+ transport: viaServer ? pooled ? "mcp-pool" : "mcp" : "cli"
3228
+ });
3229
+ }
3230
+ }
3231
+ const secret = selected?.ords?.password;
3232
+ const result = secret && format !== "json" ? {
3233
+ ...raw,
3234
+ stdout: raw.stdout.replaceAll(secret, "[REDACTED]"),
3235
+ stderr: raw.stderr.replaceAll(secret, "[REDACTED]")
3236
+ } : raw;
3237
+ let output;
3238
+ try {
3239
+ output = oracleDiagnostics(result, mutation, format, label === "validate" || label === "import");
3240
+ } catch (error) {
3241
+ if (secret && error instanceof Error) error.message = error.message.replaceAll(secret, "[REDACTED]");
3242
+ throw error;
3243
+ }
3244
+ if (viaServer && !output.split(/\r?\n/).some((line) => line.trim() === marker))
3245
+ throw new Fault(
3246
+ "SQLCL_MCP_INCOMPLETE",
3247
+ "SQLcl MCP did not confirm the complete command batch.",
3248
+ 6,
3249
+ mutation ? "outcome_unknown" : "failed"
3250
+ );
3251
+ return { ...result, output: viaServer ? output.replace(marker, "").trim() : output, work };
3252
+ }
3253
+ /** Working directory of pooled SQLcl servers: a durable private directory, never a per-call stage. */
3254
+ async sessionHome() {
3255
+ const root = path13.join(managedHome(), "staging");
3256
+ await mkdir4(root, { recursive: true, mode: 448 });
3257
+ return root;
3258
+ }
3259
+ async requireMutationSupport() {
3260
+ const settings = await this.settings();
3261
+ if (settings.databaseTransport === "ords" && settings.mode !== "cli")
3262
+ throw new Fault("ORDS_CLI_REQUIRED", "ORDS HTTP requires SQLcl CLI mode.", 3, "blocked");
3263
+ if (settings.mode === "mcp" && settings.mcpRestrictLevel !== "1")
3264
+ throw new Fault(
3265
+ "SQLCL_MCP_RESTRICTED",
3266
+ "SQLcl MCP restrict level 4 cannot provide fail-stop scripts for writes. Explicitly select MCP restrict level 1 in SQLcl settings for authorized deployment/scripts.",
3267
+ 3,
3268
+ "blocked"
3269
+ );
3270
+ }
3271
+ async stage() {
3272
+ const root = path13.join(managedHome(), "staging");
3273
+ await mkdir4(root, { recursive: true, mode: 448 });
3274
+ return mkdtemp(path13.join(root, "oracle-"));
3275
+ }
3276
+ /** Remove a private staging directory created by stage(). Other paths are never removed. */
3277
+ async discardStage(stage) {
3278
+ if (!stage) return;
3279
+ const relative = path13.relative(path13.join(managedHome(), "staging"), path13.resolve(stage));
3280
+ if (!/^oracle-[^/\\]+$/.test(relative)) return;
3281
+ await rm5(stage, { recursive: true, force: true });
3282
+ }
3283
+ async ordsBridge(job, connection, signal, stage) {
3284
+ const settings = await this.settings();
3285
+ const selected = connection ? await this.selectedConnection(connection) : void 0;
3286
+ if (connection && !selected?.ords)
3287
+ throw new Fault(
3288
+ "ORDS_CONNECTION_REQUIRED",
3289
+ "Select the ORDS transport for this operation.",
3290
+ 3,
3291
+ "blocked"
3292
+ );
3293
+ const work = stage ?? await this.stage();
3294
+ try {
3295
+ return await runOrdsBridge(settings, job, selected?.ords, work, signal, this.runner);
3296
+ } finally {
3297
+ if (!stage) await this.discardStage(work);
3298
+ }
3299
+ }
3300
+ async capabilityKey(settings) {
3301
+ if (!path13.isAbsolute(settings.executable)) return;
3302
+ try {
3303
+ const executable = await realpath5(settings.executable);
3304
+ const bin = path13.dirname(executable);
3305
+ if (path13.basename(bin) !== "bin") return;
3306
+ const lib = path13.join(path13.dirname(bin), "lib");
3307
+ const mark = async (file, required) => {
3308
+ try {
3309
+ const info = await stat3(file, { bigint: true });
3310
+ return [info.dev, info.ino, info.mode, info.size, info.mtimeNs, info.ctimeNs].map(String);
3311
+ } catch (error) {
3312
+ if (required) throw error;
3313
+ return "absent";
3314
+ }
3315
+ };
3316
+ const marks = {
3317
+ executable: await mark(executable, true),
3318
+ lib: await mark(lib, true),
3319
+ apex: await mark(path13.join(lib, "dbtools-apex.jar"), false),
3320
+ apexlang: await mark(path13.join(lib, "apexlang-compiler.jar"), false),
3321
+ ext: await mark(path13.join(lib, "ext"), false),
3322
+ extApex: await mark(path13.join(lib, "ext/dbtools-apex.jar"), false),
3323
+ extApexlang: await mark(path13.join(lib, "ext/apexlang-compiler.jar"), false)
3324
+ };
3325
+ const { executable: _executable, ...rest } = settings;
3326
+ return hash(canonical({ ...rest, executable, marks }));
3327
+ } catch {
3328
+ return;
3329
+ }
3330
+ }
3331
+ /**
3332
+ * Capabilities of an unchanged SQLcl installation, kept across processes. Each
3333
+ * deployment worker is a new process and would otherwise start two SQLcl JVMs
3334
+ * (`-version`, `help apex`) before its first read. The key covers the launcher,
3335
+ * the compiler libraries and the settings, so a changed installation probes
3336
+ * again; entries expire after a day. Injected test runners never use it.
3337
+ */
3338
+ async capabilityFile(key) {
3339
+ if (!key || this.runner !== runProcess || /^(?:0|false|off)$/i.test(process.env.APEXREST_CAPABILITY_CACHE ?? ""))
3340
+ return void 0;
3341
+ return path13.join(managedHome(), "cache", "sqlcl-capabilities", key + ".json");
3342
+ }
3343
+ async storedCapabilities(key) {
3344
+ const file = await this.capabilityFile(key);
3345
+ if (!file) return void 0;
3346
+ try {
3347
+ const stored = await readJson(file);
3348
+ const value = stored.capabilities;
3349
+ if (typeof stored.savedAt !== "number" || Date.now() - stored.savedAt > CAPABILITY_CACHE_MS || stored.savedAt > Date.now() || !value || typeof value.version !== "string" || typeof value.help !== "string" || value.helpHash !== hash(value.help) || typeof value.commands !== "object")
3350
+ return void 0;
3351
+ return value;
3352
+ } catch {
3353
+ return void 0;
3354
+ }
3355
+ }
3356
+ async storeCapabilities(key, capabilities) {
3357
+ const file = await this.capabilityFile(key);
3358
+ if (file && capabilities.version && key === await this.capabilityKey(await this.settings()))
3359
+ try {
3360
+ await mkdir4(path13.dirname(file), { recursive: true, mode: 448 });
3361
+ await writeJson(file, { savedAt: Date.now(), capabilities });
3362
+ } catch {
3363
+ }
3364
+ return capabilities;
3365
+ }
3366
+ async probeCapabilities(settings, key) {
3367
+ const versionStage = await this.stage();
3368
+ let version;
3369
+ try {
3370
+ version = await this.runner({
3371
+ executable: settings.executable,
3372
+ args: ["-version"],
3373
+ cwd: versionStage,
3374
+ env: { ...process.env, JAVA_HOME: settings.javaHome },
3375
+ timeoutMs: 15e3
3376
+ });
3377
+ } finally {
3378
+ await this.discardStage(versionStage);
3379
+ }
3380
+ oracleDiagnostics(version);
3381
+ const help = (await this.session(
3382
+ "help apex",
3383
+ void 0,
3384
+ false,
3385
+ void 0,
3386
+ void 0,
3387
+ "text",
3388
+ void 0,
3389
+ false,
3390
+ "capability"
3391
+ )).output;
3392
+ if (key && key !== await this.capabilityKey(settings)) capabilityCache.delete(key);
3393
+ const commands = Object.fromEntries(
3394
+ ["generate", "export", "validate", "import"].map((command) => [
3395
+ command,
3396
+ new RegExp("\\b" + command + "\\b", "i").test(help)
3397
+ ])
3398
+ );
3399
+ return { version: version.stdout.trim(), commands, helpHash: hash(help), help };
3400
+ }
3401
+ async capabilities(signal) {
3402
+ const settings = await this.settings();
3403
+ const key = await this.capabilityKey(settings);
3404
+ let pending = key ? capabilityCache.get(key) : void 0;
3405
+ if (!pending) {
3406
+ pending = this.storedCapabilities(key).then(
3407
+ (stored) => stored ?? this.probeCapabilities(settings, key).then((probed) => this.storeCapabilities(key, probed))
3408
+ );
3409
+ if (key) {
3410
+ capabilityCache.set(key, pending);
3411
+ pending.catch(() => {
3412
+ if (capabilityCache.get(key) === pending) capabilityCache.delete(key);
3413
+ });
3414
+ } else pending.catch(() => {
3415
+ });
3416
+ }
3417
+ return raceCancellation(pending, signal, "Capability check cancelled.");
3418
+ }
3419
+ async requireCapability(name, signal) {
3420
+ const capabilities = await this.capabilities(signal);
3421
+ if (!capabilities.commands[name])
3422
+ throw new Fault("UNSUPPORTED_CAPABILITY", `This SQLcl does not advertise apex ${name}.`, 3, "blocked");
3423
+ return { version: capabilities.version, helpHash: capabilities.helpHash };
3424
+ }
3425
+ /** Inspect selected-file support without connecting or trusting the generic APEX help. */
3426
+ async importHelp(signal) {
3427
+ const key = await this.capabilityKey(await this.settings());
3428
+ let pending = key ? importHelpCache.get(key) : void 0;
3429
+ if (!pending) {
3430
+ pending = this.storedImportHelp(key).then(
3431
+ (stored) => stored ?? this.session("help apex import").then((result) => result.output.replace(/\x1b\[[0-9;]*m/g, "")).then((help) => this.storeImportHelp(key, help))
3432
+ );
3433
+ if (key) {
3434
+ importHelpCache.set(key, pending);
3435
+ pending.catch(() => importHelpCache.delete(key));
3436
+ }
3437
+ }
3438
+ return raceCancellation(pending, signal, "Import capability check cancelled.");
3439
+ }
3440
+ /**
3441
+ * `help apex import` of an unchanged SQLcl installation, kept across processes like the
3442
+ * capabilities above: a deployment worker otherwise starts one more SQLcl JVM to read it.
3443
+ */
3444
+ async importHelpFile(key) {
3445
+ const file = await this.capabilityFile(key);
3446
+ return file?.replace(/\.json$/, ".import-help.json");
3447
+ }
3448
+ async storedImportHelp(key) {
3449
+ const file = await this.importHelpFile(key);
3450
+ if (!file) return void 0;
3451
+ try {
3452
+ const stored = await readJson(file);
3453
+ if (typeof stored.savedAt !== "number" || Date.now() - stored.savedAt > CAPABILITY_CACHE_MS || stored.savedAt > Date.now() || typeof stored.help !== "string" || !stored.help || stored.helpHash !== hash(stored.help))
3454
+ return void 0;
3455
+ return stored.help;
3456
+ } catch {
3457
+ return void 0;
3458
+ }
3459
+ }
3460
+ async storeImportHelp(key, help) {
3461
+ const file = await this.importHelpFile(key);
3462
+ if (file && help && key === await this.capabilityKey(await this.settings()))
3463
+ try {
3464
+ await mkdir4(path13.dirname(file), { recursive: true, mode: 448 });
3465
+ await writeJson(file, { savedAt: Date.now(), help, helpHash: hash(help) });
3466
+ } catch {
3467
+ }
3468
+ return help;
3469
+ }
3470
+ async partialImportCapabilities(source, target, signal) {
3471
+ const compiler = await this.requireCapability("import", signal);
3472
+ const settings = await this.settings();
3473
+ const help = await this.importHelp(signal);
3474
+ return evaluatePartialImportCompatibility({
3475
+ ...target,
3476
+ compilerVersion: compiler.version,
3477
+ mmdVersion: await sourceMmdVersion(source),
3478
+ importFiles: /(?:^|\s)-files(?:\s|\|)/m.test(help),
3479
+ mode: settings.mode,
3480
+ databaseTransport: settings.databaseTransport ?? "direct",
3481
+ helpHash: hash(help)
3482
+ });
3483
+ }
3484
+ async codeScan(source, signal) {
3485
+ const compiler = await this.capabilities(signal);
3486
+ if (!/Release 26\.3\./.test(compiler.version))
3487
+ return {
3488
+ status: "unavailable",
3489
+ findings: [],
3490
+ reason: "APEXlang CodeScan is qualified only for SQLcl 26.3."
3491
+ };
3492
+ const stage = await this.stage(), copy = path13.join(stage, "application");
3493
+ try {
3494
+ await cp3(source, copy, { recursive: true });
3495
+ const help = (await this.session("help codescan", void 0, false, signal)).output;
3496
+ if (!/\.apx\b/i.test(help) || !/-extensions\b/i.test(help))
3497
+ return {
3498
+ status: "unavailable",
3499
+ findings: [],
3500
+ reason: "Selected SQLcl does not advertise APEXlang CodeScan."
3501
+ };
3502
+ const result = await this.session(
3503
+ `codescan -path ${sqlclToken(copy)} -extensions apx -format json`,
3504
+ void 0,
3505
+ false,
3506
+ signal
3507
+ );
3508
+ return { status: "advisory", findings: parseCodeScan(result.output, copy) };
3509
+ } catch (error) {
3510
+ if (signal?.aborted || error instanceof Fault && error.code === "CANCELLED") throw error;
3511
+ return {
3512
+ status: "unavailable",
3513
+ findings: [],
3514
+ reason: error instanceof Error ? error.message : "CodeScan did not complete."
3515
+ };
3516
+ } finally {
3517
+ await this.discardStage(stage);
3518
+ }
3519
+ }
3520
+ async generate(name, alias) {
3521
+ const compiler = await this.requireCapability("generate");
3522
+ const stage = await this.stage();
3523
+ const result = await this.session(
3524
+ `apex generate -name ${sqlclToken(name)} -alias ${sqlclToken(parse(refName, alias))} -dir ${sqlclToken(stage)}`,
3525
+ void 0,
3526
+ false,
3527
+ void 0,
3528
+ stage,
3529
+ "text",
3530
+ void 0,
3531
+ // SQLcl 26.3 rejects freshly generated MMD when generation and validation
3532
+ // share a JVM. The cause is in the vendor process state. Keep
3533
+ // generation disposable; do not close pools used by other callers.
3534
+ /Release 26\.3\./.test(compiler.version)
3535
+ );
3536
+ const directory = await this.findApplication(stage);
3537
+ return { directory, compiler, output: result.output, files: await inventory(directory) };
3538
+ }
3539
+ async findApplication(root) {
3540
+ if (await exists(path13.join(root, "application.apx"))) return root;
3541
+ const found = [];
3542
+ for (const entry of await readdir5(root, { withFileTypes: true }))
3543
+ if (entry.isDirectory()) {
3544
+ const dir = path13.join(root, entry.name);
3545
+ if (await exists(path13.join(dir, "application.apx"))) found.push(dir);
3546
+ else
3547
+ for (const sub of await readdir5(dir, { withFileTypes: true }))
3548
+ if (sub.isDirectory() && await exists(path13.join(dir, sub.name, "application.apx")))
3549
+ found.push(path13.join(dir, sub.name));
3550
+ }
3551
+ if (found.length !== 1)
3552
+ throw new Fault(
3553
+ "ORACLE_OUTPUT_MISSING",
3554
+ "Expected exactly one generated/exported APEXlang application.",
3555
+ 1
3556
+ );
3557
+ return found[0];
3558
+ }
3559
+ /**
3560
+ * `metadataFile` supplies Oracle-generated `.apex/apexlang.json` from elsewhere (the nearest
3561
+ * project) for a source tree without its own; it is copied into the staged copy only.
3562
+ */
3563
+ async validate(source, signal, options = {}) {
3564
+ const compiler = await this.requireCapability("validate", signal);
3565
+ const before = await inventory(source);
3566
+ const metadataFile = before[".apex/apexlang.json"] ? path13.join(source, ".apex/apexlang.json") : options.metadataFile;
3567
+ if (!metadataFile)
3568
+ throw new Fault(
3569
+ "MMD_METADATA_REQUIRED",
3570
+ "Preserve Oracle-generated .apex/apexlang.json before validation.",
3571
+ 3
3572
+ );
3573
+ const metadata = await readFile7(metadataFile);
3574
+ const expected = { ...before, ".apex/apexlang.json": hash(metadata) };
3575
+ if (before[".apex/apexlang.json"] && before[".apex/apexlang.json"] !== expected[".apex/apexlang.json"])
3576
+ throw new Fault("SOURCE_DRIFT", "Metadata changed before validation.", 5);
3577
+ const stage = await this.stage(), copy = path13.join(stage, "application");
3578
+ let result;
3579
+ try {
3580
+ await cp3(source, copy, { recursive: true });
3581
+ if (!before[".apex/apexlang.json"]) {
3582
+ await mkdir4(path13.join(copy, ".apex"), { recursive: true });
3583
+ await cp3(metadataFile, path13.join(copy, ".apex/apexlang.json"));
3584
+ }
3585
+ if (canonical(await inventory(copy)) !== canonical(expected))
3586
+ throw new Fault("SOURCE_DRIFT", "Source changed while staging validation.", 5);
3587
+ result = await this.session(
3588
+ `apex validate -input ${sqlclToken(copy)}`,
3589
+ void 0,
3590
+ false,
3591
+ signal,
3592
+ stage,
3593
+ "text",
3594
+ void 0,
3595
+ false,
3596
+ "validate"
3597
+ );
3598
+ } catch (error) {
3599
+ if (error instanceof Fault && error.code === "ORACLE_COMMAND_FAILED" && !error.details?.diagnostics) {
3600
+ const output = typeof error.details?.output === "string" ? error.details.output : error.message;
3601
+ const details = await compilerDetails(output, source);
3602
+ if (details) throw new Fault("VALIDATION_FAILED", error.message, 1, "failed", details);
3603
+ }
3604
+ throw error;
3605
+ } finally {
3606
+ await this.discardStage(stage);
3607
+ }
3608
+ if (!compilerSucceeded(result.output)) throw await compilerFault(result.output, source);
3609
+ if (canonical(before) !== canonical(await inventory(source)))
3610
+ throw new Fault("SOURCE_DRIFT", "Source changed during validation.", 5);
3611
+ if (hash(await readFile7(metadataFile)) !== expected[".apex/apexlang.json"])
3612
+ throw new Fault("SOURCE_DRIFT", "Metadata changed during validation.", 5);
3613
+ return {
3614
+ status: "passed",
3615
+ compiler,
3616
+ mmd: JSON.parse(metadata.toString("utf8")),
3617
+ sourceDigest: hash(canonical(before)),
3618
+ output: result.output
3619
+ };
3620
+ }
3621
+ async exportApplication(env, connection, format = "APEXLANG") {
3622
+ const compiler = await this.requireCapability("export");
3623
+ const stage = await this.stage();
3624
+ const ords = (await this.settings()).databaseTransport === "ords";
3625
+ const exportRoot = ords ? path13.join(stage, "export") : stage;
3626
+ const result = ords ? {
3627
+ output: String(
3628
+ (await this.ordsBridge(
3629
+ {
3630
+ operation: "export",
3631
+ applicationId: env.applicationId,
3632
+ exportType: format,
3633
+ split: format === "APEXLANG",
3634
+ outputDirectory: exportRoot
3635
+ },
3636
+ connection,
3637
+ void 0,
3638
+ stage
3639
+ )).message ?? "Export successful"
3640
+ )
3641
+ } : await this.session(
3642
+ `apex export -applicationid ${env.applicationId} -exptype ${format} -skipExportDate -expOriginalIds -dir ${sqlclToken(stage)}`,
3643
+ connection,
3644
+ false,
3645
+ void 0,
3646
+ stage,
3647
+ "text",
3648
+ void 0,
3649
+ false,
3650
+ "export"
3651
+ );
3652
+ const directory = format === "APEXLANG" ? await this.findApplication(exportRoot) : exportRoot;
3653
+ const files = await inventory(directory);
3654
+ if (!Object.keys(files).length || format === "SQL" && !Object.keys(files).some((f) => f.endsWith(".sql")))
3655
+ throw new Fault("EMPTY_BACKUP", "Oracle export produced no usable files.", 1);
3656
+ return {
3657
+ directory,
3658
+ files,
3659
+ digest: hash(canonical(files)),
3660
+ format,
3661
+ compiler,
3662
+ output: result.output,
3663
+ stage
3664
+ };
3665
+ }
3666
+ /** Native page export; shared files use an explicitly bound full APEXlang observation. */
3667
+ async exportSelection(env, connection, selected, source, knownFiles = {}, exportScope = "selected") {
3668
+ if (!selected.length || new Set(selected).size !== selected.length || selected.some((file) => !(exportScope === "selected" ? scopedExportFile(file) : supportedFile(file))))
3669
+ throw new Fault(
3670
+ "PARTIAL_EXPORT_UNSUPPORTED",
3671
+ "Selection has no qualified native component export mapping.",
3672
+ 3
3673
+ );
3674
+ const settings = await this.settings();
3675
+ if (settings.mode !== "cli" || (settings.databaseTransport ?? "direct") !== "direct")
3676
+ throw new Fault(
3677
+ "PARTIAL_EXPORT_UNSUPPORTED",
3678
+ "Component export requires direct SQLcl CLI transport.",
3679
+ 3
3680
+ );
3681
+ const compiler = await this.requireCapability("export");
3682
+ const stage = await this.stage(), directory = path13.join(stage, "selection");
3683
+ await mkdir4(directory, { mode: 448 });
3684
+ try {
3685
+ if (exportScope === "full") {
3686
+ const exported = await this.exportApplication(env, connection, "APEXLANG");
3687
+ try {
3688
+ for (const file of selected) {
3689
+ const pageId = /^pages\/p(\d{5})/.exec(file)?.[1];
3690
+ const matches = Object.keys(exported.files).filter(
3691
+ (candidate) => pageId ? /^pages\/p(\d{5})/.exec(candidate)?.[1] === pageId : candidate === file
3692
+ );
3693
+ if (matches.length > 1)
3694
+ throw new Fault("PARTIAL_EXPORT_AMBIGUOUS", "Export has duplicate selected identities.", 5);
3695
+ if (!matches.length) continue;
3696
+ const target = await contained(directory, file);
3697
+ await mkdir4(path13.dirname(target), { recursive: true, mode: 448 });
3698
+ await cp3(await contained(exported.directory, matches[0]), target);
3699
+ }
3700
+ const files2 = await inventory(directory);
3701
+ return {
3702
+ directory,
3703
+ files: files2,
3704
+ digest: hash(canonical(files2)),
3705
+ format: "APEXLANG",
3706
+ compiler,
3707
+ output: exported.output,
3708
+ stage
3709
+ };
3710
+ } finally {
3711
+ await this.discardStage(exported.stage);
3712
+ }
3713
+ }
3714
+ const mappings = [];
3715
+ const queries = [];
3716
+ if (selected.some((file) => file.startsWith("pages/") && !knownFiles[file]))
3717
+ queries.push(
3718
+ "select 'PAGE' component_type, to_char(page_id) component_id, to_char(page_id) component_name from apex_application_pages where application_id = :p_app"
3719
+ );
3720
+ const metadata = queries.length ? await this.jsonQuery(queries.join(" union all "), connection, { p_app: env.applicationId }) : [];
3721
+ for (const file of selected) {
3722
+ const page = /^pages\/p(\d{5})/.exec(file);
3723
+ if (page) {
3724
+ const id = String(Number(page[1]));
3725
+ if (knownFiles[file] || metadata.some((row) => row.component_type === "PAGE" && row.component_id === id))
3726
+ mappings.push({ file, type: "PAGE", id });
3727
+ }
3728
+ }
3729
+ if (new Set(mappings.map((entry) => entry.type + ":" + entry.id)).size !== mappings.length)
3730
+ throw new Fault(
3731
+ "PARTIAL_EXPORT_AMBIGUOUS",
3732
+ "Multiple selected files map to one server component.",
3733
+ 5
3734
+ );
3735
+ let output = "Selected components are absent; no previous source export required.";
3736
+ const outputs = [];
3737
+ const observed = /* @__PURE__ */ new Set();
3738
+ for (const [index, mapping] of mappings.entries()) {
3739
+ const exportDirectory = path13.join(stage, "component-" + (index + 1));
3740
+ await mkdir4(exportDirectory, { mode: 448 });
3741
+ const result = await this.session(
3742
+ `apex export -applicationid ${env.applicationId} -exptype APEXLANG -skipExportDate -expOriginalIds -dir ${sqlclToken(exportDirectory)} -expComponents ${sqlclToken(mapping.type + ":" + mapping.id)}`,
3743
+ connection,
3744
+ false,
3745
+ void 0,
3746
+ exportDirectory
3747
+ );
3748
+ outputs.push(result.output);
3749
+ const emitted = await inventory(exportDirectory);
3750
+ for (const [file] of Object.entries(emitted)) {
3751
+ if (!file.endsWith(".apx"))
3752
+ throw new Fault(
3753
+ "PARTIAL_EXPORT_SCOPE_FAILED",
3754
+ "Native export emitted an unexpected artifact.",
3755
+ 5
3756
+ );
3757
+ const exportedPage = /(?:^|\/)pages\/p(\d{5})[-\w]*\.apx$/.exec(file);
3758
+ if (mapping.type !== "PAGE" || !exportedPage || mapping.id !== String(Number(exportedPage[1])) || observed.has(mapping.file))
3759
+ throw new Fault(
3760
+ "PARTIAL_EXPORT_SCOPE_FAILED",
3761
+ "Native export emitted an unselected or ambiguous page identity.",
3762
+ 5
3763
+ );
3764
+ observed.add(mapping.file);
3765
+ const target = await contained(directory, mapping.file);
3766
+ await mkdir4(path13.dirname(target), { recursive: true, mode: 448 });
3767
+ await cp3(await contained(exportDirectory, file), target);
3768
+ }
3769
+ }
3770
+ if (outputs.length) output = outputs.join("\n");
3771
+ const files = await inventory(directory);
3772
+ return {
3773
+ directory,
3774
+ files,
3775
+ digest: hash(canonical(files)),
3776
+ format: "APEXLANG",
3777
+ compiler,
3778
+ output,
3779
+ stage
3780
+ };
3781
+ } catch (error) {
3782
+ await this.discardStage(stage);
3783
+ throw error;
3784
+ }
3785
+ }
3786
+ async connectionLocality(connection) {
3787
+ const selected = await this.selectedConnection(connection);
3788
+ if (selected.ords) {
3789
+ const host = new URL(selected.ords.url).hostname;
3790
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(host))
3791
+ return { local: false, evidence: "remote-ords-endpoint" };
3792
+ }
3793
+ const endpoint = selected.ords ? { local: true, evidence: "effective-loopback-ords-endpoint" } : localConnectionEndpoint((await this.session("show connection", connection)).output);
3794
+ if (!endpoint.local) return endpoint;
3795
+ const rows = await this.jsonQuery(
3796
+ "select sys_context('USERENV','SERVER_HOST') server_host from dual",
3797
+ connection
3798
+ );
3799
+ const verified = typeof rows[0]?.server_host === "string" && await localServerHost(rows[0].server_host);
3800
+ return {
3801
+ local: verified,
3802
+ evidence: verified ? endpoint.evidence + "+local-server-identity" : "loopback-server-identity-unconfirmed"
3803
+ };
3804
+ }
3805
+ async databaseDependencies(schema, object, connection) {
3806
+ const identifier2 = /^(?:"(?:[^"]|"")+"|[A-Za-z][A-Za-z0-9_$#]*)$/;
3807
+ const parts = object.match(/"(?:[^"]|"")+"|[A-Za-z][A-Za-z0-9_$#]*/g) ?? [];
3808
+ if (!parts.length || parts.length > 2 || parts.join(".") !== object || !parts.every((part) => identifier2.test(part)))
3809
+ throw new Fault(
3810
+ "DATABASE_DEPENDENCY_UNRESOLVED",
3811
+ "Cannot resolve the reviewed object name for dependency inspection.",
3812
+ 4
3813
+ );
3814
+ const value = (part) => part.startsWith('"') ? part.slice(1, -1).replaceAll('""', '"') : part.toUpperCase();
3815
+ if (parts.length === 2) schema = value(parts[0]);
3816
+ object = value(parts.at(-1));
3817
+ return this.jsonQuery(
3818
+ "select owner, name, type from all_dependencies where referenced_owner=:p_owner and referenced_name=:p_name order by owner,name,type",
3819
+ connection,
3820
+ { p_owner: schema, p_name: object }
3821
+ );
3822
+ }
3823
+ async savedConnections(signal) {
3824
+ const marker = `APEXREST_CONNECTIONS_${randomUUID2().replaceAll("-", "")}`;
3825
+ const result = await this.session(
3826
+ `prompt ${marker}_BEGIN
3827
+ connmgr list -flat
3828
+ prompt ${marker}_END`,
3829
+ void 0,
3830
+ false,
3831
+ signal
3832
+ );
3833
+ const lines = result.output.split(/\r?\n/).map((line) => line.trim());
3834
+ const start = lines.indexOf(`${marker}_BEGIN`), end = lines.indexOf(`${marker}_END`);
3835
+ if (start < 0 || end <= start)
3836
+ throw new Fault(
3837
+ "CONNECTION_LIST_UNCONFIRMED",
3838
+ "SQLcl did not return a complete saved connection list.",
3839
+ 3
3840
+ );
3841
+ const names = [...new Set(lines.slice(start + 1, end).filter(Boolean))];
3842
+ return {
3843
+ source: "sqlcl-store",
3844
+ connections: names.map((name) => ({ name: parse(savedConnectionName, name) }))
3845
+ };
3846
+ }
3847
+ bindPreamble(bindings, ords) {
3848
+ return Object.entries(bindings).map(([key, value]) => {
3849
+ if (!/^p_[a-z_]+$/.test(key)) throw new Fault("INVALID_BIND", "Invalid internal bind name.", 2);
3850
+ const declaration = `variable ${key} ${typeof value === "number" ? "number" : "varchar2(1024)"}`;
3851
+ const literal = typeof value === "number" ? value : sqlLiteral(value);
3852
+ if (ords) {
3853
+ if (typeof value === "string" && /[\x00-\x1f\x7f-\x9f]/.test(value))
3854
+ throw new Fault(
3855
+ "INVALID_BIND",
3856
+ "ORDS metadata bind values cannot contain control characters.",
3857
+ 2
3858
+ );
3859
+ return `${declaration} = ${typeof value === "number" ? value : `'${value}'`}`;
3860
+ }
3861
+ return `${declaration}
3862
+ exec :${key} := ${literal};`;
3863
+ }).join("\n");
3864
+ }
3865
+ parseRows(output) {
3866
+ const start = output.indexOf("{"), end = output.lastIndexOf("}");
3867
+ if (start < 0) throw new Fault("EMPTY_QUERY_RESULT", "SQLcl did not return its JSON result envelope.", 1);
3868
+ let json;
3869
+ try {
3870
+ json = JSON.parse(output.slice(start, end + 1));
3871
+ } catch {
3872
+ throw new Fault("INVALID_ORACLE_JSON", "Cannot decode Oracle metadata result.", 1);
3873
+ }
3874
+ const resultSets = json.results;
3875
+ if (!Array.isArray(resultSets) || !Array.isArray(resultSets[0]?.items))
3876
+ throw new Fault("INVALID_ORACLE_JSON", "SQLcl result has no items collection.", 1);
3877
+ return resultSets[0].items;
3878
+ }
3879
+ async jsonQuery(sql, connection, bindings = {}, signal, label = "metadata-batch") {
3880
+ const ords = (await this.settings()).databaseTransport === "ords";
3881
+ const result = await this.session(
3882
+ `${this.bindPreamble(bindings, ords)}
3883
+ set sqlformat json
3884
+ ${sql};`,
3885
+ connection,
3886
+ false,
3887
+ signal,
3888
+ void 0,
3889
+ "json",
3890
+ void 0,
3891
+ false,
3892
+ label
3893
+ );
3894
+ return this.parseRows(result.output);
3895
+ }
3896
+ /**
3897
+ * Several read-only queries in one SQLcl session. Each query's rows are
3898
+ * delimited by a private marker; a missing marker fails the whole batch and
3899
+ * never yields a partial result.
3900
+ */
3901
+ async jsonQueryBatch(queries, connection, signal, label = "metadata-batch", debugTimings = false) {
3902
+ if (!queries.length) return [];
3903
+ const ords = (await this.settings()).databaseTransport === "ords";
3904
+ const token = `APEXREST_ROWS_${randomUUID2().replaceAll("-", "")}`;
3905
+ const input = queries.map(
3906
+ (query, index) => `${this.bindPreamble(query.bindings ?? {}, ords)}
3907
+ set sqlformat json
3908
+ ${debugTimings ? "set timing on\n" : ""}${query.sql};
3909
+ ${debugTimings ? "set timing off\n" : ""}prompt ${token}_${index}`
3910
+ ).join("\n");
3911
+ const result = await this.session(
3912
+ input,
3913
+ connection,
3914
+ false,
3915
+ signal,
3916
+ void 0,
3917
+ "json",
3918
+ void 0,
3919
+ false,
3920
+ label
3921
+ );
3922
+ const lines = result.output.replace(new RegExp(`}(?=${token}_\\d+[ \\t]*(?:\\r?\\n|$))`, "g"), "}\n").split(/\r?\n/);
3923
+ const rows = [];
3924
+ const statementMs = [];
3925
+ let from = 0;
3926
+ for (let index = 0; index < queries.length; index++) {
3927
+ const at = lines.findIndex((line, i) => i >= from && line.trim() === `${token}_${index}`);
3928
+ if (at < 0)
3929
+ throw new Fault("EMPTY_QUERY_RESULT", "SQLcl did not return every JSON result envelope.", 1);
3930
+ const block = lines.slice(from, at).join("\n");
3931
+ rows.push(this.parseRows(block));
3932
+ if (debugTimings) statementMs.push(parseStatementMs(block));
3933
+ from = at + 1;
3934
+ }
3935
+ if (debugTimings) recordStatementTimings(label, statementMs);
3936
+ return rows;
3937
+ }
3938
+ async identity(connection, signal) {
3939
+ const rows = await this.jsonQuery(
3940
+ "select sys_context('USERENV','DB_UNIQUE_NAME') db_unique_name, sys_context('USERENV','SERVICE_NAME') service_name, sys_context('USERENV','CURRENT_SCHEMA') parsing_schema from dual",
3941
+ connection,
3942
+ {},
3943
+ signal
3944
+ );
3945
+ if (rows.length !== 1) throw new Fault("IDENTITY_UNCONFIRMED", "Database identity was not confirmed.", 3);
3946
+ return rows[0];
3947
+ }
3948
+ /** Read-only release discovery, separate from identity checks for legacy callers. */
3949
+ async targetVersions(connection, signal) {
3950
+ const rows = await this.jsonQuery(targetVersionSql, connection, {}, signal);
3951
+ return this.parseTargetVersions(rows);
3952
+ }
3953
+ parseTargetVersions(rows) {
3954
+ const row = rows[0];
3955
+ if (rows.length !== 1 || typeof row?.apex_version !== "string" || typeof row.database_version !== "string" || !/^\d+\.\d+(?:\.\d+)*$/.test(row.apex_version) || !/^\d+\.\d+(?:\.\d+)*$/.test(row.database_version))
3956
+ throw new Fault(
3957
+ "TARGET_VERSION_UNCONFIRMED",
3958
+ "APEX and database releases could not be confirmed.",
3959
+ 3,
3960
+ "blocked"
3961
+ );
3962
+ return { apexVersion: row.apex_version, databaseVersion: row.database_version };
3963
+ }
3964
+ async verifyTarget(env, connection, observed) {
3965
+ const rows = observed ?? await this.jsonQuery(
3966
+ targetIdentitySql,
3967
+ connection,
3968
+ {
3969
+ p_workspace: env.workspace,
3970
+ p_app_id: env.applicationId
3971
+ },
3972
+ void 0,
3973
+ "verifyTarget"
3974
+ );
3975
+ const identities = rows.filter((row) => row.target_record === "identity");
3976
+ if (identities.length !== 1)
3977
+ throw new Fault("IDENTITY_UNCONFIRMED", "Database identity was not confirmed.", 3);
3978
+ const identity = {
3979
+ db_unique_name: identities[0].db_unique_name,
3980
+ service_name: identities[0].service_name,
3981
+ parsing_schema: identities[0].parsing_schema
3982
+ };
3983
+ if (identity.db_unique_name !== env.databaseIdentity.dbUniqueName || identity.service_name !== env.databaseIdentity.serviceName || identity.parsing_schema !== env.parsingSchema)
3984
+ throw new Fault(
3985
+ "TARGET_MISMATCH",
3986
+ "Connection does not match the configured database/service/schema.",
3987
+ 5,
3988
+ "conflict"
3989
+ );
3990
+ const workspaces = rows.filter((row) => row.target_record === "workspace").map((row) => ({ workspace_id: workspaceIdentifier(row.workspace_id), workspace: row.workspace }));
3991
+ if (workspaces.length !== 1)
3992
+ throw new Fault(
3993
+ "WORKSPACE_UNCONFIRMED",
3994
+ "Configured workspace is absent or inaccessible.",
3995
+ 4,
3996
+ "blocked"
3997
+ );
3998
+ const applications = rows.filter((row) => row.target_record === "application").map((row) => ({
3999
+ application_id: row.application_id,
4000
+ alias: row.alias,
4001
+ owner: row.owner,
4002
+ workspace: row.workspace
4003
+ }));
4004
+ if (applications.length > 1 || applications.some((a) => a.workspace !== env.workspace || a.owner !== env.parsingSchema))
4005
+ throw new Fault(
4006
+ "APPLICATION_TARGET_MISMATCH",
4007
+ "Application belongs to a different workspace or parsing schema.",
4008
+ 5
4009
+ );
4010
+ return { identity, workspace: workspaces[0], application: applications[0] ?? null };
4011
+ }
4012
+ /** Other applications of the workspace that already use this alias (APEX aliases are case-insensitive). */
4013
+ async aliasHolders(env, connection, alias) {
4014
+ const rows = await this.jsonQuery(
4015
+ `select application_id from apex_applications
4016
+ where workspace = :p_workspace and upper(alias) = upper(:p_alias) and application_id <> :p_app_id`,
4017
+ connection,
4018
+ { p_workspace: env.workspace, p_alias: alias, p_app_id: env.applicationId },
4019
+ void 0,
4020
+ "metadata-batch"
4021
+ );
4022
+ return rows.map((row) => Number(row.application_id)).filter((id) => Number.isFinite(id));
4023
+ }
4024
+ /** Fresh identity and versions share one read-only SQLcl session. */
4025
+ async versionedTarget(env, connection) {
4026
+ const [identity, versions] = await this.jsonQueryBatch(
4027
+ [
4028
+ { sql: targetIdentitySql, bindings: { p_workspace: env.workspace, p_app_id: env.applicationId } },
4029
+ { sql: targetVersionSql }
4030
+ ],
4031
+ connection
4032
+ );
4033
+ return {
4034
+ target: await this.verifyTarget(env, connection, identity),
4035
+ versions: this.parseTargetVersions(versions)
4036
+ };
4037
+ }
4038
+ async applicationMetadata(env, connection) {
4039
+ const rows = await this.jsonQuery(
4040
+ applicationMetadataSql,
4041
+ connection,
4042
+ { p_app_id: env.applicationId, p_workspace: env.workspace, p_owner: env.parsingSchema },
4043
+ void 0,
4044
+ "applicationMetadata"
4045
+ );
4046
+ return parseApplicationMetadata(rows);
4047
+ }
4048
+ async targetWithMetadata(env, connection) {
4049
+ const rows = await this.jsonQueryBatch(
4050
+ [
4051
+ { sql: targetIdentitySql, bindings: { p_workspace: env.workspace, p_app_id: env.applicationId } },
4052
+ {
4053
+ sql: applicationMetadataSql,
4054
+ bindings: { p_app_id: env.applicationId, p_workspace: env.workspace, p_owner: env.parsingSchema }
4055
+ }
4056
+ ],
4057
+ connection,
4058
+ void 0,
4059
+ "targetWithMetadata"
4060
+ );
4061
+ if (rows.length !== 2)
4062
+ throw new Fault("EMPTY_QUERY_RESULT", "SQLcl did not answer the complete target observation.", 1);
4063
+ const target = await this.verifyTarget(env, connection, rows[0]);
4064
+ return { target, metadata: parseApplicationMetadata(rows[1]) };
4065
+ }
4066
+ async nativeDeployment(ctx, env, source) {
4067
+ const output = path13.join(await this.stage(), "deployment.json");
4068
+ const defaults = path13.join(source, "deployments/default.json");
4069
+ const native = await exists(defaults) ? JSON.parse(await readFile7(defaults, "utf8")) : {};
4070
+ const oldApp = native.app ?? {};
4071
+ await writeJson(output, {
4072
+ ...native,
4073
+ app: {
4074
+ ...oldApp,
4075
+ id: env.applicationId,
4076
+ alias: ctx.config.application.alias,
4077
+ databaseSession: { ...oldApp.databaseSession ?? {}, parsingSchema: env.parsingSchema }
4078
+ },
4079
+ workspace: { name: env.workspace }
4080
+ });
4081
+ return output;
4082
+ }
4083
+ async importApplication(ctx, env, connection, source, signal, selectedFiles) {
4084
+ await this.requireCapability("import", signal);
4085
+ if (selectedFiles !== void 0) {
4086
+ const settings = await this.settings();
4087
+ if (settings.mode !== "cli" || (settings.databaseTransport ?? "direct") !== "direct")
4088
+ throw new Fault(
4089
+ "PARTIAL_IMPORT_TRANSPORT_UNSUPPORTED",
4090
+ "Partial import requires direct SQLcl CLI transport.",
4091
+ 3,
4092
+ "blocked"
4093
+ );
4094
+ if (!selectedFiles.length || new Set(selectedFiles).size !== selectedFiles.length)
4095
+ throw new Fault(
4096
+ "PARTIAL_IMPORT_FILES_INVALID",
4097
+ "Select a nonempty, unique list of APEXlang files.",
4098
+ 2
4099
+ );
4100
+ for (const file of selectedFiles) {
4101
+ if (!/^[A-Za-z0-9_./-]+\.apx$/.test(file) || path13.isAbsolute(file) || file.split("/").some((part) => !part || part === "." || part === ".."))
4102
+ throw new Fault(
4103
+ "PARTIAL_IMPORT_FILES_INVALID",
4104
+ "Partial-import files must be literal contained APEXlang paths without globs.",
4105
+ 2
4106
+ );
4107
+ let valid = false;
4108
+ try {
4109
+ const physical = await realpath5(await contained(source, file));
4110
+ valid = path13.relative(await realpath5(source), physical).replaceAll(path13.sep, "/") === file && (await stat3(physical)).isFile();
4111
+ } catch {
4112
+ }
4113
+ if (!valid)
4114
+ throw new Fault(
4115
+ "PARTIAL_IMPORT_FILES_INVALID",
4116
+ "Partial-import files must be regular contained files without aliases.",
4117
+ 2
4118
+ );
4119
+ }
4120
+ const help = await this.importHelp(signal);
4121
+ if (!/(?:^|\s)-files(?:\s|\|)/m.test(help))
4122
+ throw new Fault(
4123
+ "PARTIAL_IMPORT_UNSUPPORTED",
4124
+ "The selected SQLcl does not advertise apex import -files.",
4125
+ 3,
4126
+ "blocked"
4127
+ );
4128
+ }
4129
+ const config = await this.nativeDeployment(ctx, env, source);
4130
+ try {
4131
+ return await this.importWith(env, connection, source, config, signal, selectedFiles);
4132
+ } finally {
4133
+ await this.discardStage(path13.dirname(config));
4134
+ }
4135
+ }
4136
+ warmImport;
4137
+ /**
4138
+ * Start loading the APEXlang compiler for an import of `source` that this
4139
+ * deployment is about to run (sqlcl-warm.ts). Returns nothing when the transport
4140
+ * is not a saved SQLcl connection in CLI mode; the import then runs as before.
4141
+ * The caller closes the returned handle when the deployment ends.
4142
+ *
4143
+ * A selected-file import names its files relative to SQLcl's working directory.
4144
+ * `importDirectory` is the existing directory that import will read; the server
4145
+ * starts in it and serves only a selected-file import of exactly that directory.
4146
+ * Without it the server serves a full import.
4147
+ */
4148
+ async prepareImport(source, connection, importDirectory) {
4149
+ if (warmImportDisabled() || this.runner !== runProcess || this.warmImport) return void 0;
4150
+ const settings = await this.settings();
4151
+ if (settings.mode !== "cli" || (settings.databaseTransport ?? "direct") !== "direct") return void 0;
4152
+ const selected = await this.selectedConnection(connection);
4153
+ if (!selected?.name || selected.ords) return void 0;
4154
+ const env = {
4155
+ ...process.env,
4156
+ SQLPATH: "",
4157
+ ORACLE_PATH: "",
4158
+ TNS_ADMIN: process.env.TNS_ADMIN,
4159
+ JAVA_HOME: settings.javaHome
4160
+ };
4161
+ delete env.NODE_OPTIONS;
4162
+ delete env.JAVA_TOOL_OPTIONS;
4163
+ delete env._JAVA_OPTIONS;
4164
+ delete env.JDK_JAVA_OPTIONS;
4165
+ env.JAVA_TOOL_OPTIONS = "-XX:ActiveProcessorCount=2";
4166
+ const server = new WarmImportServer({
4167
+ executable: settings.executable,
4168
+ cwd: importDirectory ?? await this.sessionHome(),
4169
+ env,
4170
+ restrictLevel: SCRIPT_RESTRICT_LEVEL,
4171
+ warmup: `apex validate -input ${sqlclToken(source)}`
4172
+ });
4173
+ const entry = {
4174
+ source: path13.resolve(source),
4175
+ server,
4176
+ ...importDirectory ? { importDirectory: path13.resolve(importDirectory) } : {}
4177
+ };
4178
+ this.warmImport = entry;
4179
+ return {
4180
+ close: async () => {
4181
+ if (this.warmImport === entry) this.warmImport = void 0;
4182
+ await server.close();
4183
+ }
4184
+ };
4185
+ }
4186
+ /**
4187
+ * The prepared server serves one import: a full import of any frozen copy of the application
4188
+ * it was started for, or a selected-file import of the directory it was started in. A server
4189
+ * prepared for the other kind is left for its owner to close.
4190
+ */
4191
+ takeWarmImport(source, selected) {
4192
+ const entry = this.warmImport;
4193
+ if (!entry || selected !== !!entry.importDirectory) return void 0;
4194
+ if (selected && entry.importDirectory !== path13.resolve(source)) return void 0;
4195
+ this.warmImport = void 0;
4196
+ return entry.server;
4197
+ }
4198
+ async importWith(env, connection, source, config, signal, selectedFiles) {
4199
+ if ((await this.settings()).databaseTransport === "ords") {
4200
+ await this.requireMutationSupport();
4201
+ const result2 = await this.ordsBridge(
4202
+ {
4203
+ operation: "import",
4204
+ input: source,
4205
+ deployment: config,
4206
+ applicationId: env.applicationId,
4207
+ workspace: env.workspace,
4208
+ parsingSchema: env.parsingSchema
4209
+ },
4210
+ connection,
4211
+ signal
4212
+ );
4213
+ return String(result2.message ?? "Import successful");
4214
+ }
4215
+ let result;
4216
+ try {
4217
+ result = await this.session(
4218
+ `apex import -input ${sqlclToken(source)} -deployment ${sqlclToken(config)} -workspace ${sqlclToken(env.workspace)} -schema ${sqlclToken(env.parsingSchema)} -id ${env.applicationId}${selectedFiles ? " -files " + selectedFiles.map((file) => sqlclToken(file)).join(" ") : ""}`,
4219
+ connection,
4220
+ true,
4221
+ signal,
4222
+ selectedFiles ? source : void 0,
4223
+ "text",
4224
+ SCRIPT_RESTRICT_LEVEL,
4225
+ false,
4226
+ "import",
4227
+ this.takeWarmImport(source, selectedFiles !== void 0)
4228
+ );
4229
+ } catch (error) {
4230
+ if (error instanceof Fault && error.code === "ORACLE_COMMAND_FAILED" && !error.details?.diagnostics) {
4231
+ const output = typeof error.details?.output === "string" ? error.details.output : error.message;
4232
+ error.details = { ...error.details, ...await compilerDetails(output, source) };
4233
+ }
4234
+ throw error;
4235
+ }
4236
+ if (!/import.*(?:success|complete)|successfully.*import/is.test(result.output))
4237
+ throw new Fault(
4238
+ "IMPORT_UNCONFIRMED",
4239
+ "Import returned without a tested success marker; reconcile the target.",
4240
+ 6,
4241
+ "outcome_unknown"
4242
+ );
4243
+ return result.output;
4244
+ }
4245
+ async restoreApplication(env, connection, sql, signal) {
4246
+ const setup = `begin
4247
+ apex_application_install.set_workspace(${sqlLiteral(env.workspace)});
4248
+ apex_application_install.set_schema(${sqlLiteral(env.parsingSchema)});
4249
+ apex_application_install.set_application_id(${env.applicationId});
4250
+ end;
4251
+ /
4252
+ `;
4253
+ const ords = (await this.settings()).databaseTransport === "ords";
4254
+ const stage = await this.stage();
4255
+ try {
4256
+ const input = path13.join(stage, "restore.sql");
4257
+ if (ords) {
4258
+ await this.requireMutationSupport();
4259
+ await atomicWrite(input, Buffer.concat([Buffer.from(setup), sql]));
4260
+ return await this.ordsBridge({ operation: "script", input }, connection, signal, stage);
4261
+ }
4262
+ await atomicWrite(input, sql);
4263
+ return await this.session(
4264
+ setup + `@${sqlclToken(input)}`,
4265
+ connection,
4266
+ true,
4267
+ signal,
4268
+ stage,
4269
+ "text",
4270
+ SCRIPT_RESTRICT_LEVEL
4271
+ );
4272
+ } finally {
4273
+ await this.discardStage(stage);
4274
+ }
4275
+ }
4276
+ };
4277
+ function parseCompilerDiagnostics(output) {
4278
+ const diagnostics = [];
4279
+ let current, values;
4280
+ const flush = () => {
4281
+ if (current?.file && current.type && current.message !== void 0)
4282
+ diagnostics.push({
4283
+ code: current.type,
4284
+ severity: current.severity ?? "error",
4285
+ file: current.file,
4286
+ line: current.line ?? 0,
4287
+ column: current.column ?? 0,
4288
+ type: current.type,
4289
+ message: current.message,
4290
+ ...values?.length ? { validValues: values } : {}
4291
+ });
4292
+ current = void 0;
4293
+ values = void 0;
4294
+ };
4295
+ for (const raw of output.replace(/\x1b\[[0-9;]*m/g, "").split(/\r?\n/)) {
4296
+ const line = raw.trimEnd();
4297
+ const field = line.match(/^\s*(File|Line|Column|Type|Error|Warning|Warn):\s?(.*)$/i);
4298
+ const name = field?.[1]?.toLowerCase();
4299
+ if (/^\s*(?:APEXlang Compile (?:Errors|Warnings):|Validation (?:successful|complete))/i.test(line)) {
4300
+ flush();
4301
+ } else if (name === "file") {
4302
+ flush();
4303
+ current = { file: field[2].trim() };
4304
+ } else if (!current) {
4305
+ const unlocated = /^\s*(?:\[(warn(?:ing)?|error)\]|(warn(?:ing)?|error):)\s*(.+)$/i.exec(line);
4306
+ if (unlocated) {
4307
+ const severity = /^warn/i.test(unlocated[1] ?? unlocated[2]) ? "warning" : "error";
4308
+ diagnostics.push({
4309
+ code: severity === "warning" ? "COMPILER_WARNING" : "COMPILER_ERROR",
4310
+ severity,
4311
+ file: "",
4312
+ line: 0,
4313
+ column: 0,
4314
+ type: severity === "warning" ? "COMPILER_WARNING" : "COMPILER_ERROR",
4315
+ message: unlocated[3]
4316
+ });
4317
+ }
4318
+ } else if (name === "line") current.line = Number(field[2]);
4319
+ else if (name === "column") current.column = Number(field[2]);
4320
+ else if (name === "type") current.type = field[2].trim();
4321
+ else if (name === "error" || name === "warning" || name === "warn") {
4322
+ current.message = field[2].trim();
4323
+ current.severity = name === "error" ? "error" : "warning";
4324
+ } else if (!line.trim()) flush();
4325
+ else if (current.message === void 0) continue;
4326
+ else {
4327
+ const valid = line.match(/^Valid (?:parameters|values|options) are\s*:\s*(.*)$/i);
4328
+ if (valid) values = valid[1].trim() ? [valid[1].trim()] : [];
4329
+ else if (values) values.push(line.trim().replace(/^-/, ""));
4330
+ else current.message += " " + line.trim();
4331
+ }
4332
+ }
4333
+ flush();
4334
+ return diagnostics;
4335
+ }
4336
+ async function diagnosticHint(root, diagnostic) {
4337
+ return diagnosticHintFromSource(root, diagnostic);
4338
+ }
4339
+ async function diagnosticHintFromSource(root, diagnostic, sourceLines) {
4340
+ if (!diagnostic.line || !/^INVALID_PROPERTY|MISSING_REQUIRED|_NOT_FOUND$|INVALID_/.test(diagnostic.type))
4341
+ return;
4342
+ try {
4343
+ const file = await contained(root, diagnostic.file);
4344
+ let pending = sourceLines?.get(file);
4345
+ if (!pending) {
4346
+ pending = readFile7(file, "utf8").then((text) => text.split(/\r?\n/));
4347
+ sourceLines?.set(file, pending);
4348
+ }
4349
+ const lines = await pending;
4350
+ const indent2 = (text) => text.match(/^\s*/)[0].length;
4351
+ const open4 = /^\s*([A-Za-z][\w-]*)(?:\s+([^\s({]+))?\s*[({]\s*$/;
4352
+ const chain = [];
4353
+ const reported = lines[diagnostic.line - 1] ?? "";
4354
+ const own = /^MISSING_REQUIRED/.test(diagnostic.type) && /\(\s*$/.test(reported) && open4.test(reported);
4355
+ let level = indent2(reported) + (own ? 1 : 0);
4356
+ for (let i = diagnostic.line - (own ? 1 : 2); i >= 0 && chain.length < 3; i--) {
4357
+ const text = lines[i];
4358
+ if (!text.trim() || indent2(text) >= level) continue;
4359
+ const match = text.match(open4);
4360
+ if (!match) continue;
4361
+ level = indent2(text);
4362
+ const kind = match[1], name = match[2];
4363
+ let label = name ? `${kind} ${name}` : kind;
4364
+ if (name) {
4365
+ for (let j = i + 1; j < lines.length && j < i + 40; j++) {
4366
+ const property = lines[j].match(/^\s*type:\s*(\S+)/);
4367
+ if (indent2(lines[j]) <= level && lines[j].trim()) break;
4368
+ if (property && indent2(lines[j]) === level + (indent2(lines[i + 1] ?? "") - level || 4)) {
4369
+ label += ` (type: ${property[1]})`;
4370
+ break;
4371
+ }
4372
+ }
4373
+ }
4374
+ chain.push(label);
4375
+ }
4376
+ return chain.length ? `inside ${chain.join(" of ")}` : void 0;
4377
+ } catch {
4378
+ return;
4379
+ }
4380
+ }
4381
+ async function compilerDetails(output, root) {
4382
+ const diagnostics = parseCompilerDiagnostics(output);
4383
+ if (root) {
4384
+ const sourceLines = /* @__PURE__ */ new Map();
4385
+ for (const diagnostic of diagnostics) {
4386
+ const hint = await diagnosticHintFromSource(root, diagnostic, sourceLines);
4387
+ if (hint) diagnostic.hint = hint;
4388
+ const fix = await propertyFix(diagnostic.type, diagnostic.message, hint);
4389
+ if (fix) diagnostic.hint = hint ? `${hint}. Fix: ${fix}` : `Fix: ${fix}`;
4390
+ }
4391
+ }
4392
+ return diagnostics.length ? { diagnostics, output } : void 0;
4393
+ }
4394
+ async function compilerFault(output, root) {
4395
+ const details = await compilerDetails(output, root);
4396
+ const count = details?.diagnostics.length ?? 0;
4397
+ const message = output.length > 4e3 ? `${output.slice(0, 4e3)}
4398
+ \u2026 report truncated${count ? `; all ${count} diagnostics are in details.diagnostics` : ""}.` : output;
4399
+ return new Fault(
4400
+ details ? "VALIDATION_FAILED" : "VALIDATION_UNCONFIRMED",
4401
+ message || "Compiler returned no success marker.",
4402
+ 1,
4403
+ "failed",
4404
+ details
4405
+ );
4406
+ }
4407
+ function compilerSucceeded(output) {
4408
+ const success = /validat(?:ion|ed).*?(?:success|complete)|successfully.*validat|compil(?:ation|ed).*?(?:success|complete)|successfully.*compil/is.test(
4409
+ output
4410
+ );
4411
+ const counted = [...output.matchAll(/\b(\d+)\s+(?:errors?|failures?)\b/gi)].some(
4412
+ (match) => Number(match[1]) > 0
4413
+ );
4414
+ const failed = /(?:^|\n)\s*(?:error\b|errors?:)|\bwith\s+errors?\b|compile\s+errors?|\bfail(?:ed|ure)\b|\bunsuccessful\b|\bnot\s+successful\b/i.test(
4415
+ output
4416
+ );
4417
+ return success && !counted && !failed && !parseCompilerDiagnostics(output).some((entry) => entry.severity === "error");
4418
+ }
4419
+ async function installSources(source, root, destination) {
4420
+ const target = await contained(root, destination);
4421
+ if (await exists(target))
4422
+ throw new Fault(
4423
+ "LOCAL_EDITS_CONFLICT",
4424
+ "Destination already exists; export remains in staging. Review and merge explicitly.",
4425
+ 5,
4426
+ "conflict"
4427
+ );
4428
+ await mkdir4(path13.dirname(target), { recursive: true });
4429
+ const staging = await mkdtemp(path13.join(path13.dirname(target), ".apexrest-copy-"));
4430
+ await inventory(source);
4431
+ await cp3(source, staging, { recursive: true });
4432
+ await rename2(staging, target);
4433
+ return { directory: target, files: await inventory(target) };
4434
+ }
4435
+
4436
+ // packages/core/src/project.ts
4437
+ function resourceRoot() {
4438
+ return process.env.APEXREST_RESOURCES ?? path14.resolve(path14.dirname(fileURLToPath(import.meta.url)), "../resources");
4439
+ }
4440
+ async function projectInit(directory, template, alias) {
4441
+ parse(refName, alias);
4442
+ const destination = path14.resolve(directory);
4443
+ await mkdir5(path14.dirname(destination), { recursive: true });
4444
+ return withLock(destination + ".init.lock", async () => {
4445
+ if (await exists(destination)) {
4446
+ if (!(await lstat3(destination)).isDirectory() || (await readdir6(destination)).length)
4447
+ throw new Fault("LOCAL_EDITS_CONFLICT", "Project init requires an empty directory.", 5, "conflict");
4448
+ }
4449
+ const root = await mkdtemp2(destination + ".init-");
4450
+ try {
4451
+ const conflict = () => new Fault(
4452
+ "LOCAL_EDITS_CONFLICT",
4453
+ "Project init requires an empty folder or a new directory. Existing files were left unchanged.",
4454
+ 5,
4455
+ "conflict"
4456
+ );
4457
+ if (!await exists(root)) await mkdir5(root, { recursive: true, mode: 448 });
4458
+ if (!(await lstat3(root)).isDirectory() || (await readdir6(root)).length !== 0) throw conflict();
4459
+ const createFile = async (file, content) => {
4460
+ try {
4461
+ await writeFile(file, content, { flag: "wx", mode: 384 });
4462
+ } catch (error) {
4463
+ if (error.code === "EEXIST") throw conflict();
4464
+ throw error;
4465
+ }
4466
+ };
4467
+ const config = {
4468
+ schemaVersion: 1,
4469
+ projectId: alias,
4470
+ application: { sourceDir: "src/apex/" + alias, alias },
4471
+ database: {
4472
+ migrationsDir: "src/database/migrations",
4473
+ packagesDir: "src/database/packages"
4474
+ },
4475
+ toolchain: { lockFile: "apexrest.toolchain.lock.json" },
4476
+ environments: {},
4477
+ artifacts: { directory: ".apexrest/artifacts", retentionDays: 7 }
4478
+ };
4479
+ await createFile(path14.join(root, "apexrest.json"), JSON.stringify(config, null, 2) + "\n");
4480
+ await createFile(path14.join(root, ".gitignore"), ".apexrest/\nnode_modules/\n.env\n");
4481
+ for (const dir of Object.values(config.database))
4482
+ await mkdir5(path14.join(root, dir), { recursive: true });
4483
+ await cp4(
4484
+ path14.join(resourceRoot(), "toolchains/toolchain.lock.json"),
4485
+ path14.join(root, config.toolchain.lockFile),
4486
+ { force: false, errorOnExist: true }
4487
+ );
4488
+ if (template !== "existing-app") {
4489
+ const generated = await new OracleAdapter().generate(alias, alias);
4490
+ await installSources(generated.directory, root, config.application.sourceDir);
4491
+ const release = await sourceRelease(path14.join(root, config.application.sourceDir));
4492
+ if (release === "26.2") {
4493
+ config.toolchain.profile = "26.2";
4494
+ await cp4(
4495
+ path14.join(resourceRoot(), "toolchains/toolchain-26.2.lock.json"),
4496
+ path14.join(root, config.toolchain.lockFile)
4497
+ );
4498
+ await atomicWrite(path14.join(root, "apexrest.json"), JSON.stringify(config, null, 2) + "\n");
4499
+ }
4500
+ if (template === "customer-crm") {
4501
+ await cp4(path14.join(resourceRoot(), "templates/customer-crm/project"), root, { recursive: true });
4502
+ await cp4(
4503
+ path14.join(
4504
+ resourceRoot(),
4505
+ "templates/customer-crm",
4506
+ release === "26.2" ? "apex-overlay-26.2" : "apex-overlay"
4507
+ ),
4508
+ path14.join(root, config.application.sourceDir),
4509
+ { recursive: true }
4510
+ );
4511
+ const { readFile: readFile8 } = await import("node:fs/promises");
4512
+ const file = path14.join(
4513
+ root,
4514
+ config.application.sourceDir,
4515
+ release === "26.2" ? "shared-components/lists/navigation-menu.apx" : "shared-components/lists.apx"
4516
+ );
4517
+ const lists = await readFile8(file, "utf8"), index = lists.lastIndexOf(")");
4518
+ if (index < 0 || !lists.includes("list navigation-menu ("))
4519
+ throw new Fault(
4520
+ "UNSUPPORTED_TEMPLATE",
4521
+ "Starter navigation does not match the reviewed fixture.",
4522
+ 3
4523
+ );
4524
+ const entries = ["customers", "dashboard"].map(
4525
+ (label, i) => ` entry ${label} (
4526
+ label: ${label[0].toUpperCase() + label.slice(1)}
4527
+ layout {
4528
+ sequence: ${(i + 2) * 10}
4529
+ }
4530
+ link {
4531
+ target: {
4532
+ page: ${(i + 1) * 10}
4533
+ }
4534
+ }
4535
+ )
4536
+ `
4537
+ ).join("");
4538
+ await atomicWrite(file, lists.slice(0, index) + entries + lists.slice(index));
4539
+ }
4540
+ }
4541
+ if (await exists(destination)) {
4542
+ if ((await readdir6(destination)).length) throw conflict();
4543
+ const moved = [];
4544
+ try {
4545
+ for (const entry of await readdir6(root)) {
4546
+ await rename3(path14.join(root, entry), path14.join(destination, entry));
4547
+ moved.push(entry);
4548
+ }
4549
+ } catch (error) {
4550
+ for (const entry of moved.reverse())
4551
+ await rename3(path14.join(destination, entry), path14.join(root, entry));
4552
+ throw error;
4553
+ }
4554
+ } else await rename3(root, destination);
4555
+ return {
4556
+ root: destination,
4557
+ template,
4558
+ configuration: config,
4559
+ nextActions: [
4560
+ "Configure explicit target identity and connection references.",
4561
+ "Review the target and sources; the application task authorizes its dev/QA/test import."
4562
+ ]
4563
+ };
4564
+ } finally {
4565
+ await rm6(root, { recursive: true, force: true });
4566
+ }
4567
+ }).catch((error) => {
4568
+ if (error instanceof Fault && error.code === "LOCKED")
4569
+ throw new Fault(
4570
+ "LOCAL_EDITS_CONFLICT",
4571
+ "Another project initialization owns this directory.",
4572
+ 5,
4573
+ "conflict"
4574
+ );
4575
+ throw error;
4576
+ });
4577
+ }
4578
+ function projectSummary(ctx) {
4579
+ const environments = Object.entries(ctx.config.environments);
4580
+ return {
4581
+ projectId: ctx.config.projectId,
4582
+ root: ctx.root,
4583
+ sourceDirectories: {
4584
+ apex: ctx.config.application.sourceDir,
4585
+ ...ctx.config.database
4586
+ },
4587
+ toolchainLock: ctx.config.toolchain.lockFile,
4588
+ verification: "host-browser",
4589
+ authoring: "Pin toolchain.profile to 26.1/26.2; project action:scaffold with specFile supports IR/classic reports, form controls, cards, charts, calendars, navigation and server processes; custom components: reference mode:select",
4590
+ environments: environments.slice(0, 8).map(([name, env]) => ({
4591
+ name,
4592
+ kind: env.kind,
4593
+ applicationId: env.applicationId,
4594
+ workspace: env.workspace,
4595
+ parsingSchema: env.parsingSchema
4596
+ })),
4597
+ environmentsOmitted: Math.max(0, environments.length - 8),
4598
+ targetVerified: false
4599
+ };
4600
+ }
4601
+ async function projectInspect(ctx, detail = "full") {
4602
+ return detail === "summary" ? projectSummary(ctx) : projectInventory(ctx);
4603
+ }
4604
+ async function projectInventory(ctx) {
4605
+ const sources = {};
4606
+ for (const [kind, relative] of Object.entries({
4607
+ apex: ctx.config.application.sourceDir,
4608
+ ...ctx.config.database
4609
+ })) {
4610
+ const dir = await contained(ctx.root, relative);
4611
+ sources[kind] = await exists(dir) ? await inventory(dir) : null;
4612
+ }
4613
+ return {
4614
+ projectId: ctx.config.projectId,
4615
+ root: ctx.root,
4616
+ configurationDigest: hash(canonical(ctx.config)),
4617
+ environments: Object.entries(ctx.config.environments).map(([name, env]) => ({
4618
+ name,
4619
+ kind: env.kind,
4620
+ applicationId: env.applicationId,
4621
+ workspace: env.workspace
4622
+ })),
4623
+ sources
4624
+ };
4625
+ }
4626
+
4627
+ export {
4628
+ readLocalEnv,
4629
+ savedConnectionName,
4630
+ ordsUrl,
4631
+ ordsUsername,
4632
+ connections,
4633
+ resolveConnection,
4634
+ editConnection,
4635
+ configureConnection,
4636
+ coordination,
4637
+ LocalDeploymentControl,
4638
+ VERSION,
4639
+ syncPath,
4640
+ privateCopy,
4641
+ checkSnapshot,
4642
+ checkSyncBackup,
4643
+ checkpoint,
4644
+ SyncStore,
4645
+ APEXLANG_EQUIVALENCE_POLICY,
4646
+ compareApplicationExports,
4647
+ importSelectionSchema,
4648
+ importOptions,
4649
+ sourceRelease,
4650
+ supportedFile,
4651
+ scopedExportFile,
4652
+ pickFiles,
4653
+ overlaySelection,
4654
+ changedFiles,
4655
+ selectImport,
4656
+ persistSnapshot,
4657
+ stageSelection,
4658
+ rebaseAfterImport,
4659
+ resourceRoot,
4660
+ projectInit,
4661
+ projectInspect,
4662
+ referenceWords,
4663
+ buildReferencePostings,
4664
+ referenceStem,
4665
+ referenceTerms,
4666
+ referenceStems,
4667
+ stemmedReference,
4668
+ referenceQueryTerms,
4669
+ queryPhrase,
4670
+ routingReference,
4671
+ navigationalQuery,
4672
+ primaryCodeBlock,
4673
+ boundCode,
4674
+ codeWanted,
4675
+ CODE_LIMIT,
4676
+ SEARCH_LINKS,
4677
+ fitResults,
4678
+ identifierQuery,
4679
+ canonicalReference,
4680
+ scoreReference,
4681
+ componentExample,
4682
+ contractComponentType,
4683
+ contractComponent,
4684
+ pageExamples,
4685
+ componentNote,
4686
+ exampleValues,
4687
+ contractSkeleton,
4688
+ sqlclMode,
4689
+ sqlclRestriction,
4690
+ databaseTransport,
4691
+ sqlclConfig,
4692
+ configureSqlcl,
4693
+ withConnectedReads,
4694
+ APEX_262_PROFILE,
4695
+ databaseMeetsApex262Minimum,
4696
+ auditUpgradeSource,
4697
+ targetIdentitySql,
4698
+ sqlclToken,
4699
+ SCRIPT_RESTRICT_LEVEL,
4700
+ OracleAdapter,
4701
+ installSources,
4702
+ oracle_exports
4703
+ };