@aglyn/plugins-ai 1.0.0-beta.270 → 1.0.0-beta.272

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 (281) hide show
  1. package/package.json +17 -17
  2. package/src/lib/activity/ai-activity-actions.d.ts +4 -3
  3. package/src/lib/activity/ai-activity-actions.js +4 -0
  4. package/src/lib/activity/ai-activity-actions.js.map +1 -1
  5. package/src/lib/assets/site-styles/beauty.webp +0 -0
  6. package/src/lib/assets/site-styles/blog.webp +0 -0
  7. package/src/lib/assets/site-styles/business.webp +0 -0
  8. package/src/lib/assets/site-styles/coming-soon.webp +0 -0
  9. package/src/lib/assets/site-styles/education.webp +0 -0
  10. package/src/lib/assets/site-styles/events.webp +0 -0
  11. package/src/lib/assets/site-styles/fitness.webp +0 -0
  12. package/src/lib/assets/site-styles/landing.webp +0 -0
  13. package/src/lib/assets/site-styles/music.webp +0 -0
  14. package/src/lib/assets/site-styles/nonprofit.webp +0 -0
  15. package/src/lib/assets/site-styles/personal.webp +0 -0
  16. package/src/lib/assets/site-styles/photography.webp +0 -0
  17. package/src/lib/assets/site-styles/portfolio.webp +0 -0
  18. package/src/lib/assets/site-styles/professional.webp +0 -0
  19. package/src/lib/assets/site-styles/realestate.webp +0 -0
  20. package/src/lib/assets/site-styles/restaurant.webp +0 -0
  21. package/src/lib/assets/site-styles/store.webp +0 -0
  22. package/src/lib/assets/site-styles/studio.webp +0 -0
  23. package/src/lib/assets/site-styles/trades.webp +0 -0
  24. package/src/lib/assets/site-styles/wellness.webp +0 -0
  25. package/src/lib/assets/site-styles/yoga.webp +0 -0
  26. package/src/lib/components/ai-credits-card.component.d.ts +4 -3
  27. package/src/lib/components/ai-credits-card.component.js +15 -15
  28. package/src/lib/components/ai-credits-card.component.js.map +1 -1
  29. package/src/lib/components/ai-job-input-form.component.d.ts +36 -0
  30. package/src/lib/components/ai-job-input-form.component.js +100 -0
  31. package/src/lib/components/ai-job-input-form.component.js.map +1 -0
  32. package/src/lib/components/ai-job-requests.d.ts +4 -0
  33. package/src/lib/components/ai-job-requests.js +4 -0
  34. package/src/lib/components/ai-job-requests.js.map +1 -1
  35. package/src/lib/components/ai-site-build-page.component.js +18 -0
  36. package/src/lib/components/ai-site-build-page.component.js.map +1 -1
  37. package/src/lib/components/ai-site-import-job.component.d.ts +41 -0
  38. package/src/lib/components/ai-site-import-job.component.js +707 -0
  39. package/src/lib/components/ai-site-import-job.component.js.map +1 -0
  40. package/src/lib/components/ai-site-import-start.component.d.ts +64 -0
  41. package/src/lib/components/ai-site-import-start.component.js +335 -0
  42. package/src/lib/components/ai-site-import-start.component.js.map +1 -0
  43. package/src/lib/components/ai-site-ownership-proof.component.d.ts +42 -0
  44. package/src/lib/components/ai-site-ownership-proof.component.js +353 -0
  45. package/src/lib/components/ai-site-ownership-proof.component.js.map +1 -0
  46. package/src/lib/components/ai-site-start-card.component.d.ts +1 -1
  47. package/src/lib/components/ai-site-start-card.component.js +261 -119
  48. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  49. package/src/lib/components/ai-site-start-steps.component.d.ts +43 -2
  50. package/src/lib/components/ai-site-start-steps.component.js +651 -15
  51. package/src/lib/components/ai-site-start-steps.component.js.map +1 -1
  52. package/src/lib/components/ai-site-start-tracking.d.ts +10 -0
  53. package/src/lib/components/ai-site-start-tracking.js +14 -0
  54. package/src/lib/components/ai-site-start-tracking.js.map +1 -1
  55. package/src/lib/components/ai-site-style-previews.js +26 -22
  56. package/src/lib/components/ai-site-style-previews.js.map +1 -1
  57. package/src/lib/components/ai-upsell-dialog.component.d.ts +7 -5
  58. package/src/lib/components/ai-upsell-dialog.component.js +8 -6
  59. package/src/lib/components/ai-upsell-dialog.component.js.map +1 -1
  60. package/src/lib/components/assist-build-card.component.js +11 -1
  61. package/src/lib/components/assist-build-card.component.js.map +1 -1
  62. package/src/lib/components/assist-jobs-drawer.component.js +9 -1
  63. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  64. package/src/lib/components/assist-panel.component.js +8 -4
  65. package/src/lib/components/assist-panel.component.js.map +1 -1
  66. package/src/lib/components/staff-org-ai-card.component.js +4 -7
  67. package/src/lib/components/staff-org-ai-card.component.js.map +1 -1
  68. package/src/lib/declarations.d.ts +2 -2
  69. package/src/lib/declarations.js +9 -5
  70. package/src/lib/declarations.js.map +1 -1
  71. package/src/lib/jobs/ai-build-capabilities.js +3 -1
  72. package/src/lib/jobs/ai-build-capabilities.js.map +1 -1
  73. package/src/lib/jobs/ai-business-profile-prefill.d.ts +1 -1
  74. package/src/lib/jobs/ai-business-profile-prefill.js +14 -3
  75. package/src/lib/jobs/ai-business-profile-prefill.js.map +1 -1
  76. package/src/lib/jobs/ai-job-build-step.js +5 -3
  77. package/src/lib/jobs/ai-job-build-step.js.map +1 -1
  78. package/src/lib/jobs/ai-job-drafts.d.ts +14 -0
  79. package/src/lib/jobs/ai-job-drafts.js +24 -0
  80. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  81. package/src/lib/jobs/ai-job-form-step.d.ts +15 -1
  82. package/src/lib/jobs/ai-job-form-step.js +75 -8
  83. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  84. package/src/lib/jobs/ai-job-import-step.d.ts +136 -0
  85. package/src/lib/jobs/ai-job-import-step.js +809 -0
  86. package/src/lib/jobs/ai-job-import-step.js.map +1 -0
  87. package/src/lib/jobs/ai-job-page-language.d.ts +52 -1
  88. package/src/lib/jobs/ai-job-page-language.js +99 -5
  89. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  90. package/src/lib/jobs/ai-job-page-step.d.ts +19 -2
  91. package/src/lib/jobs/ai-job-page-step.js +42 -18
  92. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  93. package/src/lib/jobs/ai-job-plan-step.d.ts +25 -2
  94. package/src/lib/jobs/ai-job-plan-step.js +103 -29
  95. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  96. package/src/lib/jobs/ai-job-settings-step.js +4 -3
  97. package/src/lib/jobs/ai-job-settings-step.js.map +1 -1
  98. package/src/lib/jobs/ai-job-site-datasets.d.ts +27 -0
  99. package/src/lib/jobs/ai-job-site-datasets.js +140 -14
  100. package/src/lib/jobs/ai-job-site-datasets.js.map +1 -1
  101. package/src/lib/jobs/ai-job-site-look.js +18 -5
  102. package/src/lib/jobs/ai-job-site-look.js.map +1 -1
  103. package/src/lib/jobs/ai-job-site-step.d.ts +16 -1
  104. package/src/lib/jobs/ai-job-site-step.js +95 -22
  105. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  106. package/src/lib/jobs/ai-job-text-step.d.ts +15 -1
  107. package/src/lib/jobs/ai-job-text-step.js.map +1 -1
  108. package/src/lib/jobs/ai-job-tracking-step.d.ts +14 -3
  109. package/src/lib/jobs/ai-job-tracking-step.js +28 -5
  110. package/src/lib/jobs/ai-job-tracking-step.js.map +1 -1
  111. package/src/lib/jobs/ai-jobs.d.ts +13 -1
  112. package/src/lib/jobs/ai-jobs.js +77 -10
  113. package/src/lib/jobs/ai-jobs.js.map +1 -1
  114. package/src/lib/jobs/ai-layout-owner-photos.d.ts +16 -1
  115. package/src/lib/jobs/ai-layout-owner-photos.js +47 -0
  116. package/src/lib/jobs/ai-layout-owner-photos.js.map +1 -1
  117. package/src/lib/jobs/ai-layout-stock-photos.d.ts +27 -2
  118. package/src/lib/jobs/ai-layout-stock-photos.js +190 -19
  119. package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
  120. package/src/lib/jobs/ai-site-inspiration-signals.d.ts +98 -0
  121. package/src/lib/jobs/ai-site-inspiration-signals.js +585 -0
  122. package/src/lib/jobs/ai-site-inspiration-signals.js.map +1 -0
  123. package/src/lib/jobs/ai-site-inspiration.d.ts +157 -0
  124. package/src/lib/jobs/ai-site-inspiration.js +346 -0
  125. package/src/lib/jobs/ai-site-inspiration.js.map +1 -0
  126. package/src/lib/jobs/ai-site-publish.d.ts +26 -1
  127. package/src/lib/jobs/ai-site-publish.js +162 -13
  128. package/src/lib/jobs/ai-site-publish.js.map +1 -1
  129. package/src/lib/jobs/ai-theme-brand-inputs.d.ts +77 -3
  130. package/src/lib/jobs/ai-theme-brand-inputs.js +135 -31
  131. package/src/lib/jobs/ai-theme-brand-inputs.js.map +1 -1
  132. package/src/lib/jobs/fixtures/ai-candle-shop-free-plan-recording.d.ts +97 -0
  133. package/src/lib/jobs/fixtures/ai-candle-shop-free-plan-recording.js +137 -0
  134. package/src/lib/jobs/fixtures/ai-candle-shop-free-plan-recording.js.map +1 -0
  135. package/src/lib/jobs/fixtures/ai-site-inspiration-pages.d.ts +38 -0
  136. package/src/lib/jobs/fixtures/ai-site-inspiration-pages.js +103 -0
  137. package/src/lib/jobs/fixtures/ai-site-inspiration-pages.js.map +1 -0
  138. package/src/lib/jobs/fixtures/ai-stock-photo-agl3988-recordings.d.ts +25 -0
  139. package/src/lib/jobs/fixtures/ai-stock-photo-agl3988-recordings.js +174 -0
  140. package/src/lib/jobs/fixtures/ai-stock-photo-agl3988-recordings.js.map +1 -0
  141. package/src/lib/layout-language/ai-layout-compiler.d.ts +1 -1
  142. package/src/lib/layout-language/ai-layout-compiler.js +438 -25
  143. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  144. package/src/lib/layout-language/ai-layout-contact.d.ts +57 -0
  145. package/src/lib/layout-language/ai-layout-contact.js +137 -0
  146. package/src/lib/layout-language/ai-layout-contact.js.map +1 -0
  147. package/src/lib/layout-language/ai-layout-copy.d.ts +12 -0
  148. package/src/lib/layout-language/ai-layout-copy.js +34 -2
  149. package/src/lib/layout-language/ai-layout-copy.js.map +1 -1
  150. package/src/lib/layout-language/ai-layout-design.d.ts +65 -8
  151. package/src/lib/layout-language/ai-layout-design.js +411 -97
  152. package/src/lib/layout-language/ai-layout-design.js.map +1 -1
  153. package/src/lib/layout-language/ai-layout-frame.js +23 -0
  154. package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
  155. package/src/lib/layout-language/ai-layout-labels.d.ts +2 -0
  156. package/src/lib/layout-language/ai-layout-labels.js +12 -6
  157. package/src/lib/layout-language/ai-layout-labels.js.map +1 -1
  158. package/src/lib/layout-language/ai-layout-language.d.ts +3 -2
  159. package/src/lib/layout-language/ai-layout-language.js +4 -3
  160. package/src/lib/layout-language/ai-layout-language.js.map +1 -1
  161. package/src/lib/layout-language/ai-layout-links.d.ts +13 -0
  162. package/src/lib/layout-language/ai-layout-links.js +30 -0
  163. package/src/lib/layout-language/ai-layout-links.js.map +1 -1
  164. package/src/lib/layout-language/ai-layout-pictures.d.ts +49 -6
  165. package/src/lib/layout-language/ai-layout-pictures.js +145 -22
  166. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
  167. package/src/lib/model/ai-build-job.d.ts +16 -1
  168. package/src/lib/model/ai-build-job.js +40 -0
  169. package/src/lib/model/ai-build-job.js.map +1 -1
  170. package/src/lib/model/ai-credit-estimate.d.ts +20 -0
  171. package/src/lib/model/ai-credit-estimate.js +13 -0
  172. package/src/lib/model/ai-credit-estimate.js.map +1 -1
  173. package/src/lib/model/ai-job-activity.d.ts +2 -2
  174. package/src/lib/model/ai-job-activity.js +6 -4
  175. package/src/lib/model/ai-job-activity.js.map +1 -1
  176. package/src/lib/model/ai-job-input.d.ts +33 -0
  177. package/src/lib/model/ai-job-input.js +59 -0
  178. package/src/lib/model/ai-job-input.js.map +1 -0
  179. package/src/lib/model/ai-job-notice.d.ts +4 -0
  180. package/src/lib/model/ai-job-notice.js +28 -4
  181. package/src/lib/model/ai-job-notice.js.map +1 -1
  182. package/src/lib/model/ai-jobs.types.d.ts +69 -3
  183. package/src/lib/model/ai-jobs.types.js +2 -1
  184. package/src/lib/model/ai-jobs.types.js.map +1 -1
  185. package/src/lib/model/ai-site-details.d.ts +122 -0
  186. package/src/lib/model/ai-site-details.js +300 -0
  187. package/src/lib/model/ai-site-details.js.map +1 -0
  188. package/src/lib/model/ai-site-entity.d.ts +181 -0
  189. package/src/lib/model/ai-site-entity.js +390 -0
  190. package/src/lib/model/ai-site-entity.js.map +1 -0
  191. package/src/lib/model/ai-site-import-view.d.ts +130 -0
  192. package/src/lib/model/ai-site-import-view.js +182 -0
  193. package/src/lib/model/ai-site-import-view.js.map +1 -0
  194. package/src/lib/model/ai-site-import.d.ts +302 -0
  195. package/src/lib/model/ai-site-import.js +526 -0
  196. package/src/lib/model/ai-site-import.js.map +1 -0
  197. package/src/lib/model/ai-site-inspiration.d.ts +72 -0
  198. package/src/lib/model/ai-site-inspiration.js +109 -0
  199. package/src/lib/model/ai-site-inspiration.js.map +1 -0
  200. package/src/lib/model/ai-site-job.d.ts +13 -1
  201. package/src/lib/model/ai-site-job.js +15 -2
  202. package/src/lib/model/ai-site-job.js.map +1 -1
  203. package/src/lib/model/ai-site-kinds.js +109 -21
  204. package/src/lib/model/ai-site-kinds.js.map +1 -1
  205. package/src/lib/model/ai-site-look.d.ts +10 -0
  206. package/src/lib/model/ai-site-look.js +24 -0
  207. package/src/lib/model/ai-site-look.js.map +1 -1
  208. package/src/lib/model/ai-site-start-seo.d.ts +19 -5
  209. package/src/lib/model/ai-site-start-seo.js +25 -7
  210. package/src/lib/model/ai-site-start-seo.js.map +1 -1
  211. package/src/lib/model/ai-site-start-steps.d.ts +9 -3
  212. package/src/lib/model/ai-site-start-steps.js +67 -5
  213. package/src/lib/model/ai-site-start-steps.js.map +1 -1
  214. package/src/lib/model/ai-site-start.d.ts +81 -4
  215. package/src/lib/model/ai-site-start.js +207 -13
  216. package/src/lib/model/ai-site-start.js.map +1 -1
  217. package/src/lib/model/ai-upsell-copy.js +4 -1
  218. package/src/lib/model/ai-upsell-copy.js.map +1 -1
  219. package/src/lib/plan-entitlements.d.ts +4 -3
  220. package/src/lib/plan-entitlements.js +3 -8
  221. package/src/lib/plan-entitlements.js.map +1 -1
  222. package/src/lib/runtime/ai-dataset-generation.d.ts +8 -1
  223. package/src/lib/runtime/ai-dataset-generation.js +12 -2
  224. package/src/lib/runtime/ai-dataset-generation.js.map +1 -1
  225. package/src/lib/runtime/ai-doctrine-validators.d.ts +26 -33
  226. package/src/lib/runtime/ai-doctrine-validators.js +54 -44
  227. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  228. package/src/lib/runtime/ai-doctrine.js +1 -1
  229. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  230. package/src/lib/runtime/ai-node-tree.d.ts +7 -0
  231. package/src/lib/runtime/ai-node-tree.js +9 -1
  232. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  233. package/src/lib/server/ai-create-route.d.ts +1 -1
  234. package/src/lib/server/ai-create-route.js +3 -4
  235. package/src/lib/server/ai-create-route.js.map +1 -1
  236. package/src/lib/server/ai-jobs-resume.js +27 -3
  237. package/src/lib/server/ai-jobs-resume.js.map +1 -1
  238. package/src/lib/server/ai-jobs-route.js +18 -0
  239. package/src/lib/server/ai-jobs-route.js.map +1 -1
  240. package/src/lib/server/ai-site-import-route.d.ts +89 -0
  241. package/src/lib/server/ai-site-import-route.js +356 -0
  242. package/src/lib/server/ai-site-import-route.js.map +1 -0
  243. package/src/lib/server.js +14 -0
  244. package/src/lib/server.js.map +1 -1
  245. package/src/lib/site-import/fixtures/site-import-crawl-recordings.d.ts +45 -0
  246. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js +313 -0
  247. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js.map +1 -0
  248. package/src/lib/site-import/fixtures/site-import-wave-recordings.d.ts +50 -0
  249. package/src/lib/site-import/fixtures/site-import-wave-recordings.js +217 -0
  250. package/src/lib/site-import/fixtures/site-import-wave-recordings.js.map +1 -0
  251. package/src/lib/site-import/site-import-crawl.d.ts +163 -0
  252. package/src/lib/site-import/site-import-crawl.js +467 -0
  253. package/src/lib/site-import/site-import-crawl.js.map +1 -0
  254. package/src/lib/site-import/site-import-flag.d.ts +23 -0
  255. package/src/lib/site-import/site-import-flag.js +23 -0
  256. package/src/lib/site-import/site-import-flag.js.map +1 -0
  257. package/src/lib/site-import/site-import-html.d.ts +94 -0
  258. package/src/lib/site-import/site-import-html.js +462 -0
  259. package/src/lib/site-import/site-import-html.js.map +1 -0
  260. package/src/lib/site-import/site-import-images.d.ts +54 -0
  261. package/src/lib/site-import/site-import-images.js +204 -0
  262. package/src/lib/site-import/site-import-images.js.map +1 -0
  263. package/src/lib/site-import/site-import-page.d.ts +48 -0
  264. package/src/lib/site-import/site-import-page.js +150 -0
  265. package/src/lib/site-import/site-import-page.js.map +1 -0
  266. package/src/lib/site-import/site-import-review.d.ts +40 -0
  267. package/src/lib/site-import/site-import-review.js +149 -0
  268. package/src/lib/site-import/site-import-review.js.map +1 -0
  269. package/src/lib/site-import/site-import-robots.d.ts +52 -0
  270. package/src/lib/site-import/site-import-robots.js +126 -0
  271. package/src/lib/site-import/site-import-robots.js.map +1 -0
  272. package/src/lib/usage/assist-credits.d.ts +4 -4
  273. package/src/lib/usage/assist-credits.js +4 -4
  274. package/src/lib/usage/assist-credits.js.map +1 -1
  275. package/src/lib/usage/staff-org-ai-view.js +6 -3
  276. package/src/lib/usage/staff-org-ai-view.js.map +1 -1
  277. package/src/lib/usage/staff-org-ai.d.ts +4 -2
  278. package/src/lib/usage/staff-org-ai.js +7 -7
  279. package/src/lib/usage/staff-org-ai.js.map +1 -1
  280. package/src/lib/usage/staff-org-usage-ai.js +2 -2
  281. package/src/lib/usage/staff-org-usage-ai.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/runtime/ai-node-tree.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AI_TEXT_LIMITS,\n isHeadlineVariant,\n nodeCapabilityProps,\n type AiPaletteEntry,\n type AiPropSchema,\n type AiSurface,\n} from './ai-palette'\nimport {\n AI_NODE_CAPABILITIES,\n AI_PALETTE,\n AI_SURFACES,\n AI_SX_TOKENS,\n} from './ai-palette.generated'\nimport { linealRelationshipPermits } from '@aglyn/aglyn/app-utils/lineal-order'\nimport {\n NODE_MAP_MAX_BYTES,\n nodeMapBytes,\n} from '@aglyn/aglyn/app-utils/measure-node-map'\nimport { parseMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\nimport {\n COMPONENT_PROP_NAME_PATTERN,\n REUSABLE_INSTANCE_COMPONENT_ID,\n REUSABLE_INSTANCE_PROP_VALUES_KEY,\n} from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport { createIdUrlSafe } from '@aglyn/aglyn/foundation/constants/app'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport type { AiComponentPropTypes } from '../model/ai-site-inventory'\nimport { AI_ICON_COMPONENT_ID, aiIconOfId } from './ai-icon-library'\nimport {\n AI_COMPONENT_VISIBILITY_PROPS,\n isAiComponentPropToken,\n} from './ai-component-bindings'\n\nimport { sanitizePortableDefinition } from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/**\n * The one path an AI-emitted node tree takes into storage (AGL-2905).\n *\n * A model answers with a flat node map in the shape the canvas persists.\n * Nothing about that map is trusted: the component ids, the parent/child\n * pairs, every prop and every `sx` key are what the model chose to write,\n * and the renderer spreads props onto the DOM. So the tree is first held to\n * the same sanitizer a marketplace install passes — reachability from the\n * root, the surface's component allowlist, the persisted node keys, `href`\n * and `src` protocols, a size cap — and then to what a listing never needed\n * checking because a human authored it in the editor:\n *\n * - the parent/child restrictions the besigner enforces on drop\n * (`restrictChildren` / `restrictParent`), and whether an element can hold\n * children at all;\n * - every prop against the generated palette's schema — unknown props are\n * dropped, enum values coerced case-insensitively, a required prop that is\n * missing refuses the tree;\n * - `sx` against a fixed key set and a value grammar of theme tokens, numbers\n * and CSS lengths or keywords, with nothing that can reach a URL or a\n * stylesheet;\n * - copy length by role — a headline, a paragraph, a button label;\n * - links to a screen the host has, a root-relative path or an `https:` URL,\n * and media to a DAM reference or an `https:` URL;\n * - the stored-node-map byte ceiling, measured the way the save measures it.\n *\n * ## The site's own records, when the caller names them (AGL-2935)\n *\n * A reusable-component instance, a form picked on the Forms page and a\n * dataset are each \"a reference into another document\", which is why the\n * palette leaves them off: from a description alone a model can only invent\n * an id. A generator that has read the site's inventory can name real ones,\n * and the building doctrine requires it to — a repeat is placed as\n * instances of one component, and a form is bound by id rather than drawn\n * inline. So the three are admitted exactly as screen links are: only\n * against the ids the caller supplies. With no `componentIds` an instance is\n * still refused; with no `formIds` or `datasetIds` the binding is dropped.\n *\n * What comes out is the flat `NodesMap` `encodeStoredNodes` takes, with every\n * id minted fresh the way a preset graft mints them, so nothing the model\n * wrote can collide with a node already on the canvas. `sourceIds` maps each\n * minted id back to the id the model wrote, so a caller can quote a refused\n * subtree in the model's own words. Every drop is listed in `repairs`; every\n * refusal names its `code`. The function never throws.\n */\n\nexport type AiNodeTreeRefusalCode =\n /** Not an object with a `rootId` and a `nodes` map, or an unknown surface. */\n | 'invalid-input'\n /** The root node carries a component the surface does not start with. */\n | 'root'\n /** A structural failure the sanitizer named: missing node, empty tree. */\n | 'structure'\n /** A component id outside the surface's allowlist. */\n | 'component'\n /** A parent/child pair the besigner would refuse on drop. */\n | 'lineage'\n /** A prop the palette marks required is absent. */\n | 'required-prop'\n /** Over the sanitizer's or the stored-node-map's byte ceiling. */\n | 'too-large'\n /** A component instance naming a component the site does not have. */\n | 'reference'\n\nexport type AiNodeTreeResult =\n | {\n ok: true\n rootId: string\n nodes: NodesMap\n repairs: string[]\n /** Each minted id → the id the model wrote for that node. */\n sourceIds: Record<string, string>\n }\n | { ok: false; error: string; code: AiNodeTreeRefusalCode }\n\nexport interface AiNodeTreeContext {\n /** Screen ids a `screen` prop may name. Absent: any well-formed id. */\n screenIds?: Iterable<string>\n /** DAM media ids a `media` prop may reference. Absent: any well-formed reference. */\n assetIds?: Iterable<string>\n /**\n * Reusable components an instance may place. Absent: no instance is\n * admitted, which is the palette's own rule for a tree nobody grounded.\n */\n componentIds?: Iterable<string>\n /** Declared props per component id, which an instance's values are held to. */\n componentProps?: Record<string, AiComponentPropTypes>\n /** Forms on the Forms page a Form element may bind by `formId`. */\n formIds?: Iterable<string>\n /** Datasets a Form element may write to by `datasetId`. */\n datasetIds?: Iterable<string>\n /**\n * Binding tokens a `url` or `media` prop may hold whole — an Image whose\n * `src` is `{{entry.coverImage}}` on a page template, filled per record\n * when the page renders (AGL-2909). Absent: a token in either role is\n * dropped like any other value that is not an address.\n */\n bindingTokens?: Iterable<string>\n /**\n * The tree defines a reusable component (AGL-2908). A field that is not\n * copy — a switch, a dropdown, a screen, an address, a picture, a number —\n * and the `hideIf` and `hideUnless` directives may then hold one of the\n * component's own `{{prop.<name>}}` tokens as their whole value, and a\n * placed component may be handed one in its `propValues`; each is kept as\n * written. Which property a token names, and whether its kind binds to that\n * field, is the component step's check (`ai-component-bindings.ts`).\n * Absent: such a token is dropped like any value the field cannot hold.\n */\n definesComponent?: boolean\n /**\n * The tree was composed by the platform's own code — the layout language\n * compiler (AGL-3660) — and not written by a model. The surface's code-only\n * elements are then admitted (an Icon, and a layout's Drawer with its Menu\n * Button), and an Icon keeps the id and the path the icon library gives\n * the id it names (`ai-icon-library.ts`): the path is the library's, never\n * the tree's. Absent: a model's tree, held to the surface's catalog.\n */\n codeBuilt?: boolean\n}\n\n/**\n * `sx` keys a model may set: spacing, color, typography, layout, borders,\n * display, flex and grid. Fixed rather than derived — MUI's system accepts\n * far more (pseudo-selectors, nested selectors, arbitrary CSS properties)\n * and every one of those is a way to reach outside the element.\n */\nexport const AI_SX_ALLOWED_KEYS: ReadonlySet<string> = new Set([\n // spacing\n 'm',\n 'mt',\n 'mr',\n 'mb',\n 'ml',\n 'mx',\n 'my',\n 'margin',\n 'marginTop',\n 'marginRight',\n 'marginBottom',\n 'marginLeft',\n 'p',\n 'pt',\n 'pr',\n 'pb',\n 'pl',\n 'px',\n 'py',\n 'padding',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n 'gap',\n 'rowGap',\n 'columnGap',\n // color\n 'color',\n 'bgcolor',\n 'backgroundColor',\n 'borderColor',\n 'opacity',\n // typography\n 'typography',\n 'fontSize',\n 'fontWeight',\n 'fontFamily',\n 'fontStyle',\n 'lineHeight',\n 'letterSpacing',\n 'textAlign',\n 'textTransform',\n 'textDecoration',\n 'whiteSpace',\n 'textOverflow',\n 'overflowWrap',\n 'wordBreak',\n // layout\n 'width',\n 'minWidth',\n 'maxWidth',\n 'height',\n 'minHeight',\n 'maxHeight',\n 'boxSizing',\n 'overflow',\n 'overflowX',\n 'overflowY',\n 'position',\n 'top',\n 'right',\n 'bottom',\n 'left',\n 'zIndex',\n 'aspectRatio',\n 'objectFit',\n // borders\n 'border',\n 'borderTop',\n 'borderRight',\n 'borderBottom',\n 'borderLeft',\n 'borderWidth',\n 'borderStyle',\n 'borderRadius',\n 'boxShadow',\n // display\n 'display',\n 'visibility',\n // flex\n 'flexDirection',\n 'flexWrap',\n 'justifyContent',\n 'alignItems',\n 'alignContent',\n 'alignSelf',\n 'justifySelf',\n 'flex',\n 'flexGrow',\n 'flexShrink',\n 'flexBasis',\n 'order',\n // grid\n 'gridTemplateColumns',\n 'gridTemplateRows',\n 'gridColumn',\n 'gridRow',\n 'gridArea',\n 'gridAutoFlow',\n 'gridAutoColumns',\n 'gridAutoRows',\n 'justifyItems',\n 'placeItems',\n 'placeContent',\n])\n\n/**\n * Substrings no string a model wrote may carry, in a prop or an `sx` value.\n * Exported for the theme tool's component style values (AGL-2938), which are\n * the same kind of CSS value written into a theme instead of a node.\n */\nexport const HOSTILE_TEXT =\n /<\\s*\\/?\\s*(script|iframe|object|embed|svg|style|link|meta|base|frame|form|input|img)\\b|javascript:|vbscript:|data:text\\/html|expression\\s*\\(|url\\s*\\(|@import|!important|\\bon[a-z]+\\s*=/i\n\n/**\n * A CSS value a model may write into `sx`: lengths, numbers, keywords,\n * shorthands (`1px solid`), functions with plain arguments (`repeat(3, 1fr)`,\n * `rgba(0, 0, 0, 0.2)`), hex colors and theme tokens. No quotes, no\n * semicolons, no braces, no angle brackets, no colons — which is what keeps\n * a `url(`, a selector or a second declaration out.\n */\nexport const SX_VALUE = /^[A-Za-z0-9#.,%()\\s\\-_/+*]{1,100}$/\n\n/**\n * Node fields the sanitizer strips that a model has no business writing —\n * each is a way to reach past the node's own box, and each is named in\n * `repairs` so a route can tell the model what it lost.\n */\nconst STRIPPED_NODE_KEYS = [\n 'className',\n 'interactions',\n 'styleOverrides',\n 'attrOverrides',\n 'presetRef',\n] as const\n\nconst SCREEN_ID = /^[A-Za-z0-9_-]{1,64}$/\n/** The field an icon is picked with; its value carries a drawing no model can write. */\nconst ICON_PICKER_FIELD = 'icon-picker'\nconst MAX_SX_KEYS = 40\n/** A string prop with no role of its own — a color, a CSS length, an icon id. */\nconst PLAIN_STRING_MAX = 500\n\nconst paletteTokens = new Set<string>(AI_SX_TOKENS.palette)\nconst breakpoints = new Set<string>(AI_SX_TOKENS.breakpoints)\nconst typographyVariants = new Set<string>(AI_SX_TOKENS.typographyVariants)\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** An `https:` address that parses as one. */\nexport function isHttpsUrl(value: string): boolean {\n if (!/^https:\\/\\//i.test(value)) return false\n try {\n return new URL(value).protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/** A path on this site: one leading slash, never a scheme-relative `//`. */\nexport function isRootRelativePath(value: string): boolean {\n return /^\\/(?!\\/)[^\\s<>\"'`\\\\]*$/.test(value)\n}\n\nfunction sxValueAllowed(key: string, value: unknown): boolean {\n if (typeof value === 'number') return Number.isFinite(value)\n if (typeof value !== 'string') return false\n const trimmed = value.trim()\n if (!trimmed || HOSTILE_TEXT.test(trimmed)) return false\n if (paletteTokens.has(trimmed)) return true\n if (key === 'typography' && typographyVariants.has(trimmed)) return true\n return SX_VALUE.test(trimmed)\n}\n\n/**\n * The allowed slice of an `sx` object, with a line per key or value dropped.\n * Responsive objects keep only breakpoint keys; anything deeper — a\n * pseudo-selector, a nested selector, an array — is not a value at all.\n */\nfunction sanitizeSx(\n nodeId: string,\n sx: unknown,\n repairs: string[],\n): Record<string, unknown> | undefined {\n if (!isRecord(sx)) {\n if (sx !== undefined)\n repairs.push(`${nodeId}: sx is not an object; dropped`)\n return undefined\n }\n const out: Record<string, unknown> = {}\n let kept = 0\n for (const [key, value] of Object.entries(sx)) {\n if (!AI_SX_ALLOWED_KEYS.has(key)) {\n repairs.push(`${nodeId}: sx.${key} is not an allowed style; dropped`)\n continue\n }\n if (kept >= MAX_SX_KEYS) {\n repairs.push(\n `${nodeId}: sx.${key} is past the ${MAX_SX_KEYS}-key ceiling; dropped`,\n )\n continue\n }\n if (isRecord(value)) {\n const responsive: Record<string, unknown> = {}\n for (const [breakpoint, inner] of Object.entries(value)) {\n if (!breakpoints.has(breakpoint)) {\n repairs.push(\n `${nodeId}: sx.${key}.${breakpoint} is not a breakpoint; dropped`,\n )\n continue\n }\n if (!sxValueAllowed(key, inner)) {\n repairs.push(\n `${nodeId}: sx.${key}.${breakpoint} is not an allowed value; dropped`,\n )\n continue\n }\n responsive[breakpoint] =\n typeof inner === 'string' ? inner.trim() : inner\n }\n if (Object.keys(responsive).length) {\n out[key] = responsive\n kept += 1\n }\n continue\n }\n if (!sxValueAllowed(key, value)) {\n repairs.push(`${nodeId}: sx.${key} is not an allowed value; dropped`)\n continue\n }\n out[key] = typeof value === 'string' ? value.trim() : value\n kept += 1\n }\n return kept ? out : undefined\n}\n\nfunction coerceEnum(schema: AiPropSchema, value: unknown): string | undefined {\n if (typeof value !== 'string' || !schema.enum) return undefined\n const wanted = value.trim().toLowerCase()\n return schema.enum.find((option) => option.toLowerCase() === wanted)\n}\n\nfunction coerceBoolean(value: unknown): boolean | undefined {\n if (typeof value === 'boolean') return value\n if (value === 'true') return true\n if (value === 'false') return false\n return undefined\n}\n\nfunction coerceNumber(\n schema: AiPropSchema,\n value: unknown,\n): number | undefined {\n const parsed =\n typeof value === 'number'\n ? value\n : typeof value === 'string' && value.trim() !== ''\n ? Number(value)\n : NaN\n if (!Number.isFinite(parsed)) return undefined\n if (schema.type === 'integer' && !Number.isInteger(parsed)) return undefined\n if (schema.minimum !== undefined && parsed < schema.minimum) return undefined\n if (schema.maximum !== undefined && parsed > schema.maximum) return undefined\n return parsed\n}\n\nfunction textLimitFor(\n entry: AiPaletteEntry,\n name: string,\n props: Record<string, unknown>,\n): number {\n const declared = entry.textLimits[name]\n // A heading's copy is held to the headline ceiling, decided by the variant\n // the same node carries; anything else keeps the ceiling the palette\n // assigned to the prop.\n if (name === 'children' && isHeadlineVariant(props.variant)) {\n return Math.min(declared ?? AI_TEXT_LIMITS.body, AI_TEXT_LIMITS.headline)\n }\n return declared ?? AI_TEXT_LIMITS.body\n}\n\n/**\n * One string prop against its role. Returns the value to store, or\n * `undefined` with the reason pushed to `repairs`. A binding token the\n * caller admitted passes a `url` or `media` role whole.\n */\nfunction sanitizeString(\n nodeId: string,\n entry: AiPaletteEntry,\n name: string,\n schema: AiPropSchema,\n raw: string,\n props: Record<string, unknown>,\n screenIds: Set<string> | null,\n assetIds: Set<string> | null,\n repairs: string[],\n bindingTokens: ReadonlySet<string> | null = null,\n): string | undefined {\n let value = raw.trim()\n if (HOSTILE_TEXT.test(value)) {\n repairs.push(`${nodeId}.${name} carried markup or script; dropped`)\n return undefined\n }\n // An icon is drawn from the path its picker stores beside the id, which a\n // model can never supply, so an icon a model names draws nothing where the\n // page is published (AGL-3054). The site owner picks it.\n if (entry.propFields[name] === ICON_PICKER_FIELD) {\n repairs.push(`${nodeId}.${name} is an icon, which the site owner picks from the library; dropped`)\n return undefined\n }\n const role = entry.propRoles[name]\n switch (role) {\n case 'text': {\n const limit = textLimitFor(entry, name, props)\n if (value.length > limit) {\n value = value.slice(0, limit).trimEnd()\n repairs.push(\n `${nodeId}.${name} was over ${limit} characters; truncated`,\n )\n }\n break\n }\n case 'url': {\n if (bindingTokens?.has(value)) break\n if (!isHttpsUrl(value) && !isRootRelativePath(value)) {\n repairs.push(\n `${nodeId}.${name} is neither an https: URL nor a path on this site; dropped`,\n )\n return undefined\n }\n break\n }\n case 'screen': {\n if (screenIds ? !screenIds.has(value) : !SCREEN_ID.test(value)) {\n repairs.push(\n `${nodeId}.${name} names a page this site does not have; dropped`,\n )\n return undefined\n }\n break\n }\n case 'media': {\n if (bindingTokens?.has(value)) break\n if (isHttpsUrl(value)) break\n const ref = parseMediaRef(value)\n if (!ref || (assetIds && !assetIds.has(ref.mediaId))) {\n repairs.push(\n `${nodeId}.${name} is neither a media reference this site holds nor an https: URL; dropped`,\n )\n return undefined\n }\n break\n }\n default: {\n if (value.length > PLAIN_STRING_MAX) {\n repairs.push(\n `${nodeId}.${name} is over ${PLAIN_STRING_MAX} characters; dropped`,\n )\n return undefined\n }\n }\n }\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) {\n repairs.push(`${nodeId}.${name} does not match its pattern; dropped`)\n return undefined\n }\n if (schema.minLength !== undefined && value.length < schema.minLength) {\n repairs.push(\n `${nodeId}.${name} is shorter than ${schema.minLength} characters; dropped`,\n )\n return undefined\n }\n if (schema.maxLength !== undefined && value.length > schema.maxLength) {\n value = value.slice(0, schema.maxLength).trimEnd()\n repairs.push(\n `${nodeId}.${name} was over ${schema.maxLength} characters; truncated`,\n )\n }\n return value\n}\n\n/**\n * The element's own declarations plus the node capabilities every element\n * carries (AGL-3156) — repeating, today. Two shapes only, so they are built\n * once each rather than per node: a capability prop is the same on every\n * element with the same child contract.\n *\n * The element wins a name collision. A component that declared a prop of its\n * own under a capability's name would be describing its own attribute, and the\n * validator has to hold it to that.\n */\nconst CAPABLE_ENTRIES = new WeakMap<AiPaletteEntry, AiPaletteEntry>()\n\nfunction withNodeCapabilities(entry: AiPaletteEntry): AiPaletteEntry {\n const cached = CAPABLE_ENTRIES.get(entry)\n if (cached) return cached\n const capability = nodeCapabilityProps(\n AI_NODE_CAPABILITIES,\n entry.acceptsChildren,\n )\n const merged: AiPaletteEntry = {\n ...entry,\n propsSchema: {\n ...entry.propsSchema,\n properties: {\n ...capability.properties,\n ...entry.propsSchema.properties,\n },\n },\n propRoles: { ...capability.propRoles, ...entry.propRoles },\n textLimits: { ...capability.textLimits, ...entry.textLimits },\n }\n CAPABLE_ENTRIES.set(entry, merged)\n return merged\n}\n\n/**\n * Plugins whose elements play audio (AGL-3716): the Music player. A model\n * never sources a recording and never vouches for one, so on their elements\n * `rightsConfirmed` is always dropped and `src` is kept only as a reference\n * to a file in the site's own library (which the asset check grounds) or a\n * binding. Named by plugin id, as the listings name their elements: a plugin\n * never imports another.\n */\nexport const AI_OWNER_AUDIO_PLUGIN_IDS: ReadonlySet<string> = new Set(['music'])\n\n/** Why an audio element's prop a model wrote is dropped, or null to keep it. */\nexport function aiOwnerAudioRefusal(\n pluginId: string | undefined,\n name: string,\n value: unknown,\n bindingTokens: ReadonlySet<string> | null = null,\n): string | null {\n if (!pluginId || !AI_OWNER_AUDIO_PLUGIN_IDS.has(pluginId)) return null\n if (name === 'rightsConfirmed') {\n return 'only the site owner can confirm they hold the rights to a recording'\n }\n if (name !== 'src') return null\n const text = typeof value === 'string' ? value.trim() : ''\n if (!text || parseMediaRef(text) || bindingTokens?.has(text)) return null\n return 'a player plays only audio from the owner’s own media library, never a recording from elsewhere'\n}\n\nfunction sanitizeProps(\n nodeId: string,\n paletteEntry: AiPaletteEntry,\n raw: unknown,\n screenIds: Set<string> | null,\n assetIds: Set<string> | null,\n repairs: string[],\n bindingTokens: ReadonlySet<string> | null = null,\n): { props: Record<string, unknown> } | { missing: string } {\n const entry = withNodeCapabilities(paletteEntry)\n const source = isRecord(raw) ? raw : {}\n const props: Record<string, unknown> = {}\n const declared = entry.propsSchema.properties\n for (const [name, value] of Object.entries(source)) {\n // `sx` is read off the node instead; a model that put it here meant the\n // same thing, and the caller has already moved it.\n if (name === 'sx' || value === undefined || value === null) continue\n // Audio is the owner's own, always (AGL-3716).\n const audioRefusal = aiOwnerAudioRefusal(entry.pluginId, name, value, bindingTokens)\n if (audioRefusal) {\n repairs.push(`${nodeId}.${name}: ${audioRefusal}; dropped`)\n continue\n }\n const schema = declared[name]\n if (!schema) {\n repairs.push(\n `${nodeId}.${name} is not a prop of ${entry.displayName}; dropped`,\n )\n continue\n }\n if (schema.enum) {\n const coerced = coerceEnum(schema, value)\n if (coerced === undefined) {\n repairs.push(\n `${nodeId}.${name} is not one of ${schema.enum.join('|')}; dropped`,\n )\n continue\n }\n if (coerced !== value) {\n repairs.push(\n `${nodeId}.${name} was spelled \"${String(value)}\"; normalized to \"${coerced}\"`,\n )\n }\n props[name] = coerced\n continue\n }\n switch (schema.type) {\n case 'boolean': {\n const coerced = coerceBoolean(value)\n if (coerced === undefined) {\n repairs.push(`${nodeId}.${name} is not a boolean; dropped`)\n continue\n }\n props[name] = coerced\n break\n }\n case 'number':\n case 'integer': {\n const coerced = coerceNumber(schema, value)\n if (coerced === undefined) {\n repairs.push(`${nodeId}.${name} is not a number in range; dropped`)\n continue\n }\n props[name] = coerced\n break\n }\n default: {\n const text =\n typeof value === 'string'\n ? value\n : typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : undefined\n if (text === undefined) {\n repairs.push(`${nodeId}.${name} is not text; dropped`)\n continue\n }\n const cleaned = sanitizeString(\n nodeId,\n entry,\n name,\n schema,\n text,\n source,\n screenIds,\n assetIds,\n repairs,\n bindingTokens,\n )\n if (cleaned === undefined) continue\n props[name] = cleaned\n }\n }\n }\n for (const name of entry.propsSchema.required) {\n if (props[name] === undefined) return { missing: name }\n }\n return { props }\n}\n\n/** Surfaces that compose page elements, and so may place a component instance. */\nconst INSTANCE_SURFACES: ReadonlySet<AiSurface> = new Set([\n 'screen',\n 'layout',\n 'component',\n])\n\nconst FORM_COMPONENT_ID = 'form'\n\n/** The prop a repeat over a dataset is stored under (the data plugin's `repeatDataset`). Persisted — never rename. */\nexport const AI_REPEAT_DATASET_PROP = 'repeatDataset'\n\n/** The instance prop naming the component it places; stored on every instance node. */\nexport const AI_INSTANCE_REF_PROP = 'refId'\n\ninterface ReferenceSets {\n componentIds: Set<string> | null\n componentProps: Record<string, AiComponentPropTypes>\n formIds: Set<string> | null\n datasetIds: Set<string> | null\n assetIds: Set<string> | null\n /** The tree defines a reusable component, which may hand its own property tokens on. */\n definesComponent: boolean\n}\n\n/**\n * One value an instance fills in for a declared prop, held to what the\n * declaration's type can hold: a picture from the library, a link, a number,\n * a switch, or copy.\n */\nfunction instancePropValue(\n nodeId: string,\n name: string,\n type: string,\n raw: unknown,\n assetIds: Set<string> | null,\n repairs: string[],\n): unknown {\n if (type === 'number') {\n const parsed = typeof raw === 'number' ? raw : Number(raw)\n if (raw === '' || !Number.isFinite(parsed)) {\n repairs.push(`${nodeId}.propValues.${name} is not a number; dropped`)\n return undefined\n }\n return parsed\n }\n if (type === 'boolean') {\n const coerced = coerceBoolean(raw)\n if (coerced === undefined) {\n repairs.push(`${nodeId}.propValues.${name} is not a boolean; dropped`)\n }\n return coerced\n }\n if (type === 'icon') {\n // A page cannot fill an icon: the pick is an id and the path drawn from\n // it, and a word in its place draws nothing (AGL-3054). The property is\n // left for the site owner to pick.\n repairs.push(`${nodeId}.propValues.${name} is an icon, which the site owner picks from the library; dropped`)\n return undefined\n }\n if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean') {\n repairs.push(`${nodeId}.propValues.${name} is not a value; dropped`)\n return undefined\n }\n const value = String(raw).trim()\n if (HOSTILE_TEXT.test(value)) {\n repairs.push(`${nodeId}.propValues.${name} carried markup or script; dropped`)\n return undefined\n }\n if (type === 'image') {\n if (isHttpsUrl(value)) return value\n const ref = parseMediaRef(value)\n if (!ref || (assetIds && !assetIds.has(ref.mediaId))) {\n repairs.push(\n `${nodeId}.propValues.${name} is neither a media reference this site holds nor an https: URL; dropped`,\n )\n return undefined\n }\n return value\n }\n if (type === 'href') {\n if (isHttpsUrl(value) || isRootRelativePath(value)) return value\n repairs.push(\n `${nodeId}.propValues.${name} is neither an https: URL nor a path on this site; dropped`,\n )\n return undefined\n }\n if (value.length > AI_TEXT_LIMITS.body) {\n repairs.push(\n `${nodeId}.propValues.${name} was over ${AI_TEXT_LIMITS.body} characters; truncated`,\n )\n return value.slice(0, AI_TEXT_LIMITS.body).trimEnd()\n }\n return value\n}\n\n/**\n * The site-record props of one node — an instance's `refId` and\n * `propValues`, a Form's `formId` and `datasetId` — checked against the ids\n * the caller supplied. They leave `props` before the palette pass, which\n * would drop them as undeclared, and come back in `kept` once checked.\n */\nfunction sanitizeReferenceProps(\n nodeId: string,\n componentId: string,\n props: Record<string, unknown>,\n refs: ReferenceSets,\n repairs: string[],\n): { props: Record<string, unknown>; kept: Record<string, unknown> } | { refusal: string } {\n const rest: Record<string, unknown> = { ...props }\n const kept: Record<string, unknown> = {}\n // A repeat over one of the site's datasets (AGL-3616), on any element: the\n // platform's own repeat, admitted against the datasets the caller supplies,\n // as a Form's dataset binding is. The palette leaves it off, since from a\n // description alone a model can only invent a dataset's id.\n if (AI_REPEAT_DATASET_PROP in rest) {\n const raw = rest[AI_REPEAT_DATASET_PROP]\n delete rest[AI_REPEAT_DATASET_PROP]\n const id = typeof raw === 'string' ? raw.trim() : ''\n if (id && refs.datasetIds?.has(id)) {\n kept[AI_REPEAT_DATASET_PROP] = id\n } else if (raw !== undefined && raw !== null && raw !== '') {\n repairs.push(`${nodeId}.${AI_REPEAT_DATASET_PROP} names a dataset this site does not have; dropped`)\n }\n }\n if (componentId === REUSABLE_INSTANCE_COMPONENT_ID) {\n const refId = typeof rest[AI_INSTANCE_REF_PROP] === 'string' ? String(rest[AI_INSTANCE_REF_PROP]).trim() : ''\n delete rest[AI_INSTANCE_REF_PROP]\n if (!refId || !refs.componentIds?.has(refId)) {\n return {\n refusal: `Reusable Component (${nodeId}) names a component this site does not have`,\n }\n }\n kept[AI_INSTANCE_REF_PROP] = refId\n const rawValues = rest[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n delete rest[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n if (rawValues !== undefined && !isRecord(rawValues)) {\n repairs.push(`${nodeId}.propValues is not an object; dropped`)\n }\n const declared = refs.componentProps[refId]\n const values: Record<string, unknown> = {}\n for (const [name, raw] of Object.entries(isRecord(rawValues) ? rawValues : {})) {\n if (raw === undefined || raw === null) continue\n if (!COMPONENT_PROP_NAME_PATTERN.test(name)) {\n repairs.push(`${nodeId}.propValues.${name} is not a prop name; dropped`)\n continue\n }\n if (declared && !(name in declared)) {\n repairs.push(`${nodeId}.propValues.${name} is not a prop of that component; dropped`)\n continue\n }\n if (refs.definesComponent && isAiComponentPropToken(raw)) {\n // A property of the component being defined, handed on whole; the\n // component step's check holds it to the kind this prop declares.\n values[name] = raw.trim()\n continue\n }\n const value = instancePropValue(\n nodeId,\n name,\n declared?.[name] ?? 'text',\n raw,\n refs.assetIds,\n repairs,\n )\n if (value !== undefined) values[name] = value\n }\n if (Object.keys(values).length) kept[REUSABLE_INSTANCE_PROP_VALUES_KEY] = values\n return { props: rest, kept }\n }\n if (componentId === FORM_COMPONENT_ID) {\n const bindings: Array<[prop: string, ids: Set<string> | null, record: string]> = [\n ['formId', refs.formIds, 'form'],\n ['datasetId', refs.datasetIds, 'dataset'],\n ]\n for (const [prop, ids, record] of bindings) {\n const raw = rest[prop]\n delete rest[prop]\n if (raw === undefined || raw === null || raw === '') continue\n const id = typeof raw === 'string' ? raw.trim() : ''\n if (id && ids?.has(id)) {\n kept[prop] = id\n } else {\n repairs.push(`${nodeId}.${prop} names a ${record} this site does not have; dropped`)\n }\n }\n }\n return { props: rest, kept }\n}\n\nfunction refusalCode(error: string): AiNodeTreeRefusalCode {\n if (/too large/i.test(error)) return 'too-large'\n if (/cannot be published/i.test(error)) return 'component'\n return 'structure'\n}\n\n/**\n * Whether the root the model wrote is the surface's root: the canvas wrapper\n * for a document surface (which the sanitizer exempts by the same shape), or\n * the named component otherwise.\n */\nfunction rootMatches(surfaceRoot: string, componentId: unknown): boolean {\n if (surfaceRoot === 'div') {\n return componentId == null || componentId === '' || componentId === 'div'\n }\n return componentId === surfaceRoot\n}\n\nexport function validateAiNodeTree(\n input: unknown,\n surface: AiSurface,\n context?: AiNodeTreeContext,\n): AiNodeTreeResult {\n try {\n return validate(input, surface, context)\n } catch (error) {\n return {\n ok: false,\n code: 'invalid-input',\n error: `The tree could not be read: ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n}\n\nexport type AiNodePatchResult =\n | {\n ok: true\n props: Record<string, unknown>\n sx: Record<string, unknown> | undefined\n repairs: string[]\n }\n | { ok: false; error: string; code: AiNodeTreeRefusalCode }\n\n/**\n * One element's prop and style patch, held to the rules `validateAiNodeTree`\n * holds an element it places — for an edit to an element already on the\n * canvas, where there is no tree to validate.\n *\n * The same passes run: unknown props dropped, enums coerced, every string\n * held to its role and screened for markup, `sx` held to the key set and the\n * value grammar. The one difference is `required`: a patch is merged over the\n * props the element already has, so a required prop the patch does not name\n * is not missing.\n */\nexport function validateAiNodePatch(\n componentId: string,\n patch: { props?: unknown; sx?: unknown },\n context?: AiNodeTreeContext,\n): AiNodePatchResult {\n const entry = AI_PALETTE[componentId]\n if (!entry) {\n return {\n ok: false,\n code: 'component',\n error: `Component \"${componentId}\" is not in the palette`,\n }\n }\n const repairs: string[] = []\n const props = sanitizeProps(\n componentId,\n { ...entry, propsSchema: { ...entry.propsSchema, required: [] } },\n patch.props,\n context?.screenIds ? new Set(context.screenIds) : null,\n context?.assetIds ? new Set(context.assetIds) : null,\n repairs,\n )\n const sx =\n patch.sx === undefined ? undefined : sanitizeSx(componentId, patch.sx, repairs)\n return {\n ok: true,\n props: 'props' in props ? props.props : {},\n sx,\n repairs,\n }\n}\n\nfunction validate(\n input: unknown,\n surface: AiSurface,\n context: AiNodeTreeContext | undefined,\n): AiNodeTreeResult {\n const definition = AI_SURFACES[surface]\n if (!definition) {\n return {\n ok: false,\n code: 'invalid-input',\n error: `Unknown surface \"${surface}\"`,\n }\n }\n if (\n !isRecord(input) ||\n typeof input.rootId !== 'string' ||\n !isRecord(input.nodes)\n ) {\n return {\n ok: false,\n code: 'invalid-input',\n error: 'Expected an object with a string rootId and a nodes map',\n }\n }\n const rootId = input.rootId\n const nodes = input.nodes as Record<string, unknown>\n const root = nodes[rootId]\n if (!isRecord(root)) {\n return {\n ok: false,\n code: 'structure',\n error: 'Definition has no root node',\n }\n }\n if (!rootMatches(definition.root, root.componentId)) {\n return {\n ok: false,\n code: 'root',\n error: `A ${surface} starts with ${definition.root === 'div' ? 'the document wrapper' : `\"${definition.root}\"`}, not \"${String(root.componentId)}\"`,\n }\n }\n\n // The sanitizer keeps only the persisted node keys, and `sx` is not one of\n // them for a listing. Read it off every node first — from the node field\n // or from `props.sx`, which a model writes just as readily — and put it\n // back, checked, on the nodes that survive.\n const sxByNodeId = new Map<string, unknown>()\n const hiddenByNodeId = new Set<string>()\n for (const [id, node] of Object.entries(nodes)) {\n if (!isRecord(node)) continue\n const sx =\n node.sx !== undefined\n ? node.sx\n : isRecord(node.props)\n ? node.props.sx\n : undefined\n if (sx !== undefined) sxByNodeId.set(id, sx)\n if (node.hidden === true) hiddenByNodeId.add(id)\n }\n\n // A DAM reference (a `media:` value) is not a URL the sanitizer's\n // `src` policy admits — a listing must not carry another tenant's asset —\n // but on the tenant's own page it is exactly what an image should name.\n // Lift those values out before sanitizing and hand them back to the prop\n // pass, which holds them to the asset set the caller supplied.\n // A binding token the caller admitted (AGL-2909) is lifted the same way:\n // `{{entry.coverImage}}` is no address the sanitizer knows, and the prop\n // pass holds it to the tokens the caller named.\n const bindingTokens = context?.bindingTokens ? new Set(context.bindingTokens) : null\n // A reusable component's own property tokens (AGL-2908) are lifted too, and\n // kept as written rather than handed back to the prop pass: `{{prop.variant}}`\n // is no value a dropdown, a switch, an address or a visibility directive\n // admits. Copy keeps its tokens without lifting, as the text they are.\n const definesComponent = context?.definesComponent === true\n const codeBuilt = context?.codeBuilt === true\n const mediaByNodeId = new Map<string, Record<string, string>>()\n const boundByNodeId = new Map<string, Record<string, string>>()\n // A code-built Icon's drawing, from the library by the id it names (AGL-3660).\n const iconByNodeId = new Map<string, { iconId: string; iconPath: string }>()\n const forSanitizer: Record<string, unknown> = {}\n for (const [id, node] of Object.entries(nodes)) {\n if (!isRecord(node) || !isRecord(node.props)) {\n forSanitizer[id] = node\n continue\n }\n if (codeBuilt && node.componentId === AI_ICON_COMPONENT_ID) {\n const { iconId, ...props } = node.props\n const rest = { ...props }\n delete rest['iconPath']\n const icon = aiIconOfId(iconId)\n if (icon) iconByNodeId.set(id, { iconId: icon.id, iconPath: icon.path })\n forSanitizer[id] = { ...node, props: rest }\n continue\n }\n const entry = AI_PALETTE[String(node.componentId)]\n const roles = entry?.propRoles ?? {}\n const props: Record<string, unknown> = { ...node.props }\n const lifted: Record<string, string> = {}\n const bound: Record<string, string> = {}\n for (const [key, value] of Object.entries(props)) {\n if (typeof value !== 'string') continue\n const role = roles[key]\n if (\n definesComponent &&\n isAiComponentPropToken(value) &&\n (AI_COMPONENT_VISIBILITY_PROPS.includes(key) ||\n (entry?.propsSchema.properties[key] !== undefined && role !== 'text'))\n ) {\n bound[key] = value.trim()\n delete props[key]\n continue\n }\n if (\n (role === 'media' && parseMediaRef(value.trim())) ||\n ((role === 'media' || role === 'url') && bindingTokens?.has(value.trim()))\n ) {\n lifted[key] = value\n delete props[key]\n }\n }\n if (Object.keys(lifted).length) mediaByNodeId.set(id, lifted)\n if (Object.keys(bound).length) boundByNodeId.set(id, bound)\n forSanitizer[id] = { ...node, props }\n }\n\n const refs: ReferenceSets = {\n componentIds: context?.componentIds ? new Set(context.componentIds) : null,\n componentProps: context?.componentProps ?? {},\n formIds: context?.formIds ? new Set(context.formIds) : null,\n datasetIds: context?.datasetIds ? new Set(context.datasetIds) : null,\n assetIds: context?.assetIds ? new Set(context.assetIds) : null,\n definesComponent,\n }\n // An instance is admitted only where the caller grounded it in the site's\n // components; the reference itself is checked on the node below.\n const surfaceAllow = codeBuilt ? [...definition.allow, ...(definition.codeOnly ?? [])] : definition.allow\n const allow =\n refs.componentIds && INSTANCE_SURFACES.has(surface)\n ? [...surfaceAllow, REUSABLE_INSTANCE_COMPONENT_ID]\n : surfaceAllow\n const sanitized = sanitizePortableDefinition(\n { rootId, nodes: forSanitizer },\n { componentIds: allow },\n )\n if (sanitized.ok === false) {\n return {\n ok: false,\n code: refusalCode(sanitized.error),\n error: sanitized.error,\n }\n }\n\n const screenIds = context?.screenIds ? new Set(context.screenIds) : null\n const assetIds = refs.assetIds\n const repairs: string[] = []\n const output: NodesMap = {}\n const rootIsWrapper =\n rootMatches('div', root.componentId) && definition.root === 'div'\n const minted = new Map<string, string>()\n const mint = (id: string): string => {\n const fresh =\n id === rootId && rootIsWrapper\n ? CANVAS_ROOT_ELEMENT_ID\n : createIdUrlSafe()\n minted.set(id, fresh)\n return fresh\n }\n\n /** Each visited node's parent by the model's own ids, for the parentId check. */\n const parentOf = new Map<string, string>()\n const queue: Array<{ id: string; parentId: string | null }> = [\n { id: rootId, parentId: null },\n ]\n mint(rootId)\n while (queue.length) {\n const { id, parentId } = queue.shift() as {\n id: string\n parentId: string | null\n }\n const node = sanitized.nodes[id]\n const entry = AI_PALETTE[node.componentId]\n if (!entry) {\n return {\n ok: false,\n code: 'component',\n error: `Component \"${node.componentId}\" is not in the palette`,\n }\n }\n const newId = minted.get(id) as string\n const raw = nodes[id]\n if (isRecord(raw)) {\n // The sanitizer drops silently; the model is told what went.\n for (const key of STRIPPED_NODE_KEYS) {\n if (raw[key] !== undefined) {\n repairs.push(\n `${id}.${key} is not something a generated node may set; dropped`,\n )\n }\n }\n if (raw.hidden !== undefined && typeof raw.hidden !== 'boolean') {\n repairs.push(`${id}.hidden is not a boolean; dropped`)\n }\n if (raw.nodes !== undefined && !Array.isArray(raw.nodes)) {\n repairs.push(\n `${id}.nodes is not a list of child ids; its children were dropped`,\n )\n }\n if (\n raw.parentId !== undefined &&\n raw.parentId !== null &&\n raw.parentId !== (parentId === null ? null : parentOf.get(id))\n ) {\n repairs.push(\n `${id}.parentId disagreed with where the tree places it; recomputed`,\n )\n }\n if (isRecord(raw.props)) {\n const lifted = mediaByNodeId.get(id) ?? {}\n const kept = boundByNodeId.get(id) ?? {}\n for (const key of Object.keys(raw.props)) {\n if (iconByNodeId.has(id) && (key === 'iconId' || key === 'iconPath')) continue\n if (\n key !== 'sx' &&\n lifted[key] === undefined &&\n kept[key] === undefined &&\n node.props?.[key] === undefined &&\n raw.props[key] !== undefined\n ) {\n repairs.push(\n `${id}.${key} was an unsafe handler, address or markup; dropped`,\n )\n }\n }\n }\n }\n const children: string[] = []\n for (const childId of node.nodes ?? []) {\n if (minted.has(childId)) {\n repairs.push(\n `${childId} was listed under more than one parent; the later listing was dropped`,\n )\n continue\n }\n const child = sanitized.nodes[childId]\n if (!child) continue\n const childEntry = AI_PALETTE[child.componentId]\n if (!childEntry) {\n return {\n ok: false,\n code: 'component',\n error: `Component \"${child.componentId}\" is not in the palette`,\n }\n }\n if (!entry.acceptsChildren) {\n return {\n ok: false,\n code: 'lineage',\n error: `${entry.displayName} (${id}) cannot hold other elements, but lists ${childId}`,\n }\n }\n if (\n !linealRelationshipPermits(\n {\n componentId: child.componentId,\n pluginId: childEntry.pluginId,\n restrictParent: childEntry.restrictParent,\n },\n {\n componentId: node.componentId,\n pluginId: entry.pluginId,\n restrictChildren: entry.restrictChildren,\n },\n )\n ) {\n return {\n ok: false,\n code: 'lineage',\n error: `${childEntry.displayName} (${childId}) cannot be placed inside ${entry.displayName} (${id})`,\n }\n }\n children.push(mint(childId))\n parentOf.set(childId, id)\n queue.push({ id: childId, parentId: newId })\n }\n\n const reference = sanitizeReferenceProps(\n id,\n node.componentId,\n { ...node.props, ...mediaByNodeId.get(id) },\n refs,\n repairs,\n )\n if ('refusal' in reference) {\n return { ok: false, code: 'reference', error: reference.refusal }\n }\n // A required prop the component binds is present: its value is the token.\n const boundProps = boundByNodeId.get(id)\n const propsResult = sanitizeProps(\n id,\n boundProps\n ? {\n ...entry,\n propsSchema: {\n ...entry.propsSchema,\n required: entry.propsSchema.required.filter((name) => boundProps[name] === undefined),\n },\n }\n : entry,\n reference.props,\n screenIds,\n assetIds,\n repairs,\n bindingTokens,\n )\n if ('missing' in propsResult) {\n return {\n ok: false,\n code: 'required-prop',\n error: `${entry.displayName} (${id}) is missing its required \"${propsResult.missing}\" prop`,\n }\n }\n const sx = sanitizeSx(id, sxByNodeId.get(id), repairs)\n output[newId] = {\n $id: newId,\n type: NodeType.NODE,\n componentId: node.componentId,\n pluginId: entry.pluginId,\n parentId,\n nodes: children,\n props: { ...propsResult.props, ...reference.kept, ...boundProps, ...iconByNodeId.get(id) },\n ...(sx ? { sx } : {}),\n ...(hiddenByNodeId.has(id) ? { hidden: true } : {}),\n }\n }\n\n // The save's own measurement (msgpack), not a JSON string length: the\n // ceiling is stated in those bytes, and a UTF-16 length reads multi-byte\n // copy as smaller than the document the save will refuse.\n const bytes = nodeMapBytes(output)\n if (bytes > NODE_MAP_MAX_BYTES) {\n return {\n ok: false,\n code: 'too-large',\n error: `The tree is ${bytes} bytes; the stored ceiling is ${NODE_MAP_MAX_BYTES}`,\n }\n }\n const sourceIds: Record<string, string> = {}\n for (const [source, fresh] of minted) sourceIds[fresh] = source\n return {\n ok: true,\n rootId: minted.get(rootId) as string,\n nodes: output,\n repairs,\n sourceIds,\n }\n}\n"],"names":["AI_TEXT_LIMITS","isHeadlineVariant","nodeCapabilityProps","AI_NODE_CAPABILITIES","AI_PALETTE","AI_SURFACES","AI_SX_TOKENS","linealRelationshipPermits","NODE_MAP_MAX_BYTES","nodeMapBytes","parseMediaRef","COMPONENT_PROP_NAME_PATTERN","REUSABLE_INSTANCE_COMPONENT_ID","REUSABLE_INSTANCE_PROP_VALUES_KEY","createIdUrlSafe","CANVAS_ROOT_ELEMENT_ID","NodeType","AI_ICON_COMPONENT_ID","aiIconOfId","AI_COMPONENT_VISIBILITY_PROPS","isAiComponentPropToken","sanitizePortableDefinition","AI_SX_ALLOWED_KEYS","Set","HOSTILE_TEXT","SX_VALUE","STRIPPED_NODE_KEYS","SCREEN_ID","ICON_PICKER_FIELD","MAX_SX_KEYS","PLAIN_STRING_MAX","paletteTokens","palette","breakpoints","typographyVariants","isRecord","value","Array","isArray","isHttpsUrl","test","URL","protocol","isRootRelativePath","sxValueAllowed","key","Number","isFinite","trimmed","trim","has","sanitizeSx","nodeId","sx","repairs","undefined","push","out","kept","Object","entries","responsive","breakpoint","inner","keys","length","coerceEnum","schema","enum","wanted","toLowerCase","find","option","coerceBoolean","coerceNumber","parsed","NaN","type","isInteger","minimum","maximum","textLimitFor","entry","name","props","declared","textLimits","variant","Math","min","body","headline","sanitizeString","raw","screenIds","assetIds","bindingTokens","propFields","role","propRoles","limit","slice","trimEnd","ref","mediaId","pattern","RegExp","minLength","maxLength","CAPABLE_ENTRIES","WeakMap","withNodeCapabilities","cached","get","capability","acceptsChildren","merged","propsSchema","properties","set","AI_OWNER_AUDIO_PLUGIN_IDS","aiOwnerAudioRefusal","pluginId","text","sanitizeProps","paletteEntry","source","audioRefusal","displayName","coerced","join","String","cleaned","required","missing","INSTANCE_SURFACES","FORM_COMPONENT_ID","AI_REPEAT_DATASET_PROP","AI_INSTANCE_REF_PROP","instancePropValue","sanitizeReferenceProps","componentId","refs","rest","id","datasetIds","refId","componentIds","refusal","rawValues","componentProps","values","definesComponent","bindings","formIds","prop","ids","record","refusalCode","error","rootMatches","surfaceRoot","validateAiNodeTree","input","surface","context","validate","ok","code","Error","message","validateAiNodePatch","patch","definition","rootId","nodes","root","sxByNodeId","Map","hiddenByNodeId","node","hidden","add","codeBuilt","mediaByNodeId","boundByNodeId","iconByNodeId","forSanitizer","iconId","icon","iconPath","path","roles","lifted","bound","includes","surfaceAllow","allow","codeOnly","sanitized","output","rootIsWrapper","minted","mint","fresh","parentOf","queue","parentId","shift","newId","children","childId","child","childEntry","restrictParent","restrictChildren","reference","boundProps","propsResult","filter","$id","NODE","bytes","sourceIds"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,iBAAiB,EACjBC,mBAAmB,QAId,kBAAc;AACrB,SACEC,oBAAoB,EACpBC,UAAU,EACVC,WAAW,EACXC,YAAY,QACP,4BAAwB;AAC/B,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,SACEC,kBAAkB,EAClBC,YAAY,QACP,0CAAyC;AAChD,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SACEC,2BAA2B,EAC3BC,8BAA8B,EAC9BC,iCAAiC,QAC5B,iDAAgD;AACvD,SAASC,eAAe,QAAQ,wCAAuC;AACvE,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,QAAQ,QAAuB,2BAA0B;AAElE,SAASC,oBAAoB,EAAEC,UAAU,QAAQ,uBAAmB;AACpE,SACEC,6BAA6B,EAC7BC,sBAAsB,QACjB,6BAAyB;AAEhC,SAASC,0BAA0B,QAAQ,mDAAkD;AA0H7F;;;;;CAKC,GACD,OAAO,MAAMC,qBAA0C,IAAIC,IAAI;IAC7D,UAAU;IACV;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,QAAQ;IACR;IACA;IACA;IACA;IACA;IACA,aAAa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAAS;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,UAAU;IACV;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,UAAU;IACV;IACA;IACA,OAAO;IACP;I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AoB;QAClF;IACF;IACA,MAAMuN,YAAoC,CAAC;IAC3C,KAAK,MAAM,CAACjG,QAAQ8E,MAAM,IAAIF,OAAQqB,SAAS,CAACnB,MAAM,GAAG9E;IACzD,OAAO;QACLyC,IAAI;QACJO,QAAQ4B,OAAOzF,GAAG,CAAC6D;QACnBC,OAAOyB;QACPlJ;QACAyK;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/runtime/ai-node-tree.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AI_TEXT_LIMITS,\n isHeadlineVariant,\n nodeCapabilityProps,\n type AiPaletteEntry,\n type AiPropSchema,\n type AiSurface,\n} from './ai-palette'\nimport {\n AI_NODE_CAPABILITIES,\n AI_PALETTE,\n AI_SURFACES,\n AI_SX_TOKENS,\n} from './ai-palette.generated'\nimport { linealRelationshipPermits } from '@aglyn/aglyn/app-utils/lineal-order'\nimport {\n NODE_MAP_MAX_BYTES,\n nodeMapBytes,\n} from '@aglyn/aglyn/app-utils/measure-node-map'\nimport { parseMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\nimport {\n COMPONENT_PROP_NAME_PATTERN,\n REUSABLE_INSTANCE_COMPONENT_ID,\n REUSABLE_INSTANCE_PROP_VALUES_KEY,\n} from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport { createIdUrlSafe } from '@aglyn/aglyn/foundation/constants/app'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport type { AiComponentPropTypes } from '../model/ai-site-inventory'\nimport { AI_ICON_COMPONENT_ID, aiIconOfId } from './ai-icon-library'\nimport {\n AI_COMPONENT_VISIBILITY_PROPS,\n isAiComponentPropToken,\n} from './ai-component-bindings'\n\nimport { sanitizePortableDefinition } from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/**\n * The one path an AI-emitted node tree takes into storage (AGL-2905).\n *\n * A model answers with a flat node map in the shape the canvas persists.\n * Nothing about that map is trusted: the component ids, the parent/child\n * pairs, every prop and every `sx` key are what the model chose to write,\n * and the renderer spreads props onto the DOM. So the tree is first held to\n * the same sanitizer a marketplace install passes — reachability from the\n * root, the surface's component allowlist, the persisted node keys, `href`\n * and `src` protocols, a size cap — and then to what a listing never needed\n * checking because a human authored it in the editor:\n *\n * - the parent/child restrictions the besigner enforces on drop\n * (`restrictChildren` / `restrictParent`), and whether an element can hold\n * children at all;\n * - every prop against the generated palette's schema — unknown props are\n * dropped, enum values coerced case-insensitively, a required prop that is\n * missing refuses the tree;\n * - `sx` against a fixed key set and a value grammar of theme tokens, numbers\n * and CSS lengths or keywords, with nothing that can reach a URL or a\n * stylesheet;\n * - copy length by role — a headline, a paragraph, a button label;\n * - links to a screen the host has, a root-relative path or an `https:` URL,\n * and media to a DAM reference or an `https:` URL;\n * - the stored-node-map byte ceiling, measured the way the save measures it.\n *\n * ## The site's own records, when the caller names them (AGL-2935)\n *\n * A reusable-component instance, a form picked on the Forms page and a\n * dataset are each \"a reference into another document\", which is why the\n * palette leaves them off: from a description alone a model can only invent\n * an id. A generator that has read the site's inventory can name real ones,\n * and the building doctrine requires it to — a repeat is placed as\n * instances of one component, and a form is bound by id rather than drawn\n * inline. So the three are admitted exactly as screen links are: only\n * against the ids the caller supplies. With no `componentIds` an instance is\n * still refused; with no `formIds` or `datasetIds` the binding is dropped.\n *\n * What comes out is the flat `NodesMap` `encodeStoredNodes` takes, with every\n * id minted fresh the way a preset graft mints them, so nothing the model\n * wrote can collide with a node already on the canvas. `sourceIds` maps each\n * minted id back to the id the model wrote, so a caller can quote a refused\n * subtree in the model's own words. Every drop is listed in `repairs`; every\n * refusal names its `code`. The function never throws.\n */\n\nexport type AiNodeTreeRefusalCode =\n /** Not an object with a `rootId` and a `nodes` map, or an unknown surface. */\n | 'invalid-input'\n /** The root node carries a component the surface does not start with. */\n | 'root'\n /** A structural failure the sanitizer named: missing node, empty tree. */\n | 'structure'\n /** A component id outside the surface's allowlist. */\n | 'component'\n /** A parent/child pair the besigner would refuse on drop. */\n | 'lineage'\n /** A prop the palette marks required is absent. */\n | 'required-prop'\n /** Over the sanitizer's or the stored-node-map's byte ceiling. */\n | 'too-large'\n /** A component instance naming a component the site does not have. */\n | 'reference'\n\nexport type AiNodeTreeResult =\n | {\n ok: true\n rootId: string\n nodes: NodesMap\n repairs: string[]\n /** Each minted id → the id the model wrote for that node. */\n sourceIds: Record<string, string>\n }\n | { ok: false; error: string; code: AiNodeTreeRefusalCode }\n\nexport interface AiNodeTreeContext {\n /** Screen ids a `screen` prop may name. Absent: any well-formed id. */\n screenIds?: Iterable<string>\n /** DAM media ids a `media` prop may reference. Absent: any well-formed reference. */\n assetIds?: Iterable<string>\n /**\n * Reusable components an instance may place. Absent: no instance is\n * admitted, which is the palette's own rule for a tree nobody grounded.\n */\n componentIds?: Iterable<string>\n /** Declared props per component id, which an instance's values are held to. */\n componentProps?: Record<string, AiComponentPropTypes>\n /** Forms on the Forms page a Form element may bind by `formId`. */\n formIds?: Iterable<string>\n /** Datasets a Form element may write to by `datasetId`. */\n datasetIds?: Iterable<string>\n /**\n * Binding tokens a `url` or `media` prop may hold whole — an Image whose\n * `src` is `{{entry.coverImage}}` on a page template, filled per record\n * when the page renders (AGL-2909). Absent: a token in either role is\n * dropped like any other value that is not an address.\n */\n bindingTokens?: Iterable<string>\n /**\n * The tree defines a reusable component (AGL-2908). A field that is not\n * copy — a switch, a dropdown, a screen, an address, a picture, a number —\n * and the `hideIf` and `hideUnless` directives may then hold one of the\n * component's own `{{prop.<name>}}` tokens as their whole value, and a\n * placed component may be handed one in its `propValues`; each is kept as\n * written. Which property a token names, and whether its kind binds to that\n * field, is the component step's check (`ai-component-bindings.ts`).\n * Absent: such a token is dropped like any value the field cannot hold.\n */\n definesComponent?: boolean\n /**\n * The tree was composed by the platform's own code — the layout language\n * compiler (AGL-3660) — and not written by a model. The surface's code-only\n * elements are then admitted (an Icon, and a layout's Drawer with its Menu\n * Button), and an Icon keeps the id and the path the icon library gives\n * the id it names (`ai-icon-library.ts`): the path is the library's, never\n * the tree's. Absent: a model's tree, held to the surface's catalog.\n */\n codeBuilt?: boolean\n}\n\n/**\n * `sx` keys a model may set: spacing, color, typography, layout, borders,\n * display, flex and grid. Fixed rather than derived — MUI's system accepts\n * far more (pseudo-selectors, nested selectors, arbitrary CSS properties)\n * and every one of those is a way to reach outside the element.\n */\nexport const AI_SX_ALLOWED_KEYS: ReadonlySet<string> = new Set([\n // spacing\n 'm',\n 'mt',\n 'mr',\n 'mb',\n 'ml',\n 'mx',\n 'my',\n 'margin',\n 'marginTop',\n 'marginRight',\n 'marginBottom',\n 'marginLeft',\n 'p',\n 'pt',\n 'pr',\n 'pb',\n 'pl',\n 'px',\n 'py',\n 'padding',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n 'gap',\n 'rowGap',\n 'columnGap',\n // color\n 'color',\n 'bgcolor',\n 'backgroundColor',\n 'borderColor',\n 'opacity',\n // typography\n 'typography',\n 'fontSize',\n 'fontWeight',\n 'fontFamily',\n 'fontStyle',\n 'lineHeight',\n 'letterSpacing',\n 'textAlign',\n 'textTransform',\n 'textDecoration',\n 'whiteSpace',\n 'textOverflow',\n 'overflowWrap',\n 'wordBreak',\n // layout\n 'width',\n 'minWidth',\n 'maxWidth',\n 'height',\n 'minHeight',\n 'maxHeight',\n 'boxSizing',\n 'overflow',\n 'overflowX',\n 'overflowY',\n 'position',\n 'top',\n 'right',\n 'bottom',\n 'left',\n 'zIndex',\n 'aspectRatio',\n 'objectFit',\n // borders\n 'border',\n 'borderTop',\n 'borderRight',\n 'borderBottom',\n 'borderLeft',\n 'borderWidth',\n 'borderStyle',\n 'borderRadius',\n 'boxShadow',\n // display\n 'display',\n 'visibility',\n // flex\n 'flexDirection',\n 'flexWrap',\n 'justifyContent',\n 'alignItems',\n 'alignContent',\n 'alignSelf',\n 'justifySelf',\n 'flex',\n 'flexGrow',\n 'flexShrink',\n 'flexBasis',\n 'order',\n // grid\n 'gridTemplateColumns',\n 'gridTemplateRows',\n 'gridColumn',\n 'gridRow',\n 'gridArea',\n 'gridAutoFlow',\n 'gridAutoColumns',\n 'gridAutoRows',\n 'justifyItems',\n 'placeItems',\n 'placeContent',\n])\n\n/**\n * Substrings no string a model wrote may carry, in a prop or an `sx` value.\n * Exported for the theme tool's component style values (AGL-2938), which are\n * the same kind of CSS value written into a theme instead of a node.\n */\nexport const HOSTILE_TEXT =\n /<\\s*\\/?\\s*(script|iframe|object|embed|svg|style|link|meta|base|frame|form|input|img)\\b|javascript:|vbscript:|data:text\\/html|expression\\s*\\(|url\\s*\\(|@import|!important|\\bon[a-z]+\\s*=/i\n\n/**\n * A CSS value a model may write into `sx`: lengths, numbers, keywords,\n * shorthands (`1px solid`), functions with plain arguments (`repeat(3, 1fr)`,\n * `rgba(0, 0, 0, 0.2)`), hex colors and theme tokens. No quotes, no\n * semicolons, no braces, no angle brackets, no colons — which is what keeps\n * a `url(`, a selector or a second declaration out.\n */\nexport const SX_VALUE = /^[A-Za-z0-9#.,%()\\s\\-_/+*]{1,100}$/\n\n/**\n * Node fields the sanitizer strips that a model has no business writing —\n * each is a way to reach past the node's own box, and each is named in\n * `repairs` so a route can tell the model what it lost.\n */\nconst STRIPPED_NODE_KEYS = [\n 'className',\n 'interactions',\n 'styleOverrides',\n 'attrOverrides',\n 'presetRef',\n] as const\n\nconst SCREEN_ID = /^[A-Za-z0-9_-]{1,64}$/\n/** The field an icon is picked with; its value carries a drawing no model can write. */\nconst ICON_PICKER_FIELD = 'icon-picker'\nconst MAX_SX_KEYS = 40\n/** A string prop with no role of its own — a color, a CSS length, an icon id. */\nconst PLAIN_STRING_MAX = 500\n\nconst paletteTokens = new Set<string>(AI_SX_TOKENS.palette)\nconst breakpoints = new Set<string>(AI_SX_TOKENS.breakpoints)\nconst typographyVariants = new Set<string>(AI_SX_TOKENS.typographyVariants)\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** An `https:` address that parses as one. */\nexport function isHttpsUrl(value: string): boolean {\n if (!/^https:\\/\\//i.test(value)) return false\n try {\n return new URL(value).protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/**\n * A link that calls or writes (AGL-3979): `tel:` and a phone number's digits,\n * a `+` only first, or `mailto:` and one address with nothing after it. The\n * number or address itself is held to the facts the job was given by the\n * layout's own contact check, which reads every prop.\n */\nexport function isContactHref(value: string): boolean {\n return /^tel:\\+?\\d{7,15}$/.test(value) || /^mailto:[^\\s@<>?#\"]+@[^\\s@<>?#\"]+\\.[^\\s@<>?#\".]{2,}$/i.test(value)\n}\n\n/** A path on this site: one leading slash, never a scheme-relative `//`. */\nexport function isRootRelativePath(value: string): boolean {\n return /^\\/(?!\\/)[^\\s<>\"'`\\\\]*$/.test(value)\n}\n\nfunction sxValueAllowed(key: string, value: unknown): boolean {\n if (typeof value === 'number') return Number.isFinite(value)\n if (typeof value !== 'string') return false\n const trimmed = value.trim()\n if (!trimmed || HOSTILE_TEXT.test(trimmed)) return false\n if (paletteTokens.has(trimmed)) return true\n if (key === 'typography' && typographyVariants.has(trimmed)) return true\n return SX_VALUE.test(trimmed)\n}\n\n/**\n * The allowed slice of an `sx` object, with a line per key or value dropped.\n * Responsive objects keep only breakpoint keys; anything deeper — a\n * pseudo-selector, a nested selector, an array — is not a value at all.\n */\nfunction sanitizeSx(\n nodeId: string,\n sx: unknown,\n repairs: string[],\n): Record<string, unknown> | undefined {\n if (!isRecord(sx)) {\n if (sx !== undefined)\n repairs.push(`${nodeId}: sx is not an object; dropped`)\n return undefined\n }\n const out: Record<string, unknown> = {}\n let kept = 0\n for (const [key, value] of Object.entries(sx)) {\n if (!AI_SX_ALLOWED_KEYS.has(key)) {\n repairs.push(`${nodeId}: sx.${key} is not an allowed style; dropped`)\n continue\n }\n if (kept >= MAX_SX_KEYS) {\n repairs.push(\n `${nodeId}: sx.${key} is past the ${MAX_SX_KEYS}-key ceiling; dropped`,\n )\n continue\n }\n if (isRecord(value)) {\n const responsive: Record<string, unknown> = {}\n for (const [breakpoint, inner] of Object.entries(value)) {\n if (!breakpoints.has(breakpoint)) {\n repairs.push(\n `${nodeId}: sx.${key}.${breakpoint} is not a breakpoint; dropped`,\n )\n continue\n }\n if (!sxValueAllowed(key, inner)) {\n repairs.push(\n `${nodeId}: sx.${key}.${breakpoint} is not an allowed value; dropped`,\n )\n continue\n }\n responsive[breakpoint] =\n typeof inner === 'string' ? inner.trim() : inner\n }\n if (Object.keys(responsive).length) {\n out[key] = responsive\n kept += 1\n }\n continue\n }\n if (!sxValueAllowed(key, value)) {\n repairs.push(`${nodeId}: sx.${key} is not an allowed value; dropped`)\n continue\n }\n out[key] = typeof value === 'string' ? value.trim() : value\n kept += 1\n }\n return kept ? out : undefined\n}\n\nfunction coerceEnum(schema: AiPropSchema, value: unknown): string | undefined {\n if (typeof value !== 'string' || !schema.enum) return undefined\n const wanted = value.trim().toLowerCase()\n return schema.enum.find((option) => option.toLowerCase() === wanted)\n}\n\nfunction coerceBoolean(value: unknown): boolean | undefined {\n if (typeof value === 'boolean') return value\n if (value === 'true') return true\n if (value === 'false') return false\n return undefined\n}\n\nfunction coerceNumber(\n schema: AiPropSchema,\n value: unknown,\n): number | undefined {\n const parsed =\n typeof value === 'number'\n ? value\n : typeof value === 'string' && value.trim() !== ''\n ? Number(value)\n : NaN\n if (!Number.isFinite(parsed)) return undefined\n if (schema.type === 'integer' && !Number.isInteger(parsed)) return undefined\n if (schema.minimum !== undefined && parsed < schema.minimum) return undefined\n if (schema.maximum !== undefined && parsed > schema.maximum) return undefined\n return parsed\n}\n\nfunction textLimitFor(\n entry: AiPaletteEntry,\n name: string,\n props: Record<string, unknown>,\n): number {\n const declared = entry.textLimits[name]\n // A heading's copy is held to the headline ceiling, decided by the variant\n // the same node carries; anything else keeps the ceiling the palette\n // assigned to the prop.\n if (name === 'children' && isHeadlineVariant(props.variant)) {\n return Math.min(declared ?? AI_TEXT_LIMITS.body, AI_TEXT_LIMITS.headline)\n }\n return declared ?? AI_TEXT_LIMITS.body\n}\n\n/**\n * One string prop against its role. Returns the value to store, or\n * `undefined` with the reason pushed to `repairs`. A binding token the\n * caller admitted passes a `url` or `media` role whole.\n */\nfunction sanitizeString(\n nodeId: string,\n entry: AiPaletteEntry,\n name: string,\n schema: AiPropSchema,\n raw: string,\n props: Record<string, unknown>,\n screenIds: Set<string> | null,\n assetIds: Set<string> | null,\n repairs: string[],\n bindingTokens: ReadonlySet<string> | null = null,\n): string | undefined {\n let value = raw.trim()\n if (HOSTILE_TEXT.test(value)) {\n repairs.push(`${nodeId}.${name} carried markup or script; dropped`)\n return undefined\n }\n // An icon is drawn from the path its picker stores beside the id, which a\n // model can never supply, so an icon a model names draws nothing where the\n // page is published (AGL-3054). The site owner picks it.\n if (entry.propFields[name] === ICON_PICKER_FIELD) {\n repairs.push(`${nodeId}.${name} is an icon, which the site owner picks from the library; dropped`)\n return undefined\n }\n const role = entry.propRoles[name]\n switch (role) {\n case 'text': {\n const limit = textLimitFor(entry, name, props)\n if (value.length > limit) {\n value = value.slice(0, limit).trimEnd()\n repairs.push(\n `${nodeId}.${name} was over ${limit} characters; truncated`,\n )\n }\n break\n }\n case 'url': {\n if (bindingTokens?.has(value)) break\n if (!isHttpsUrl(value) && !isRootRelativePath(value) && !isContactHref(value)) {\n repairs.push(\n `${nodeId}.${name} is neither an https: URL nor a path on this site; dropped`,\n )\n return undefined\n }\n break\n }\n case 'screen': {\n if (screenIds ? !screenIds.has(value) : !SCREEN_ID.test(value)) {\n repairs.push(\n `${nodeId}.${name} names a page this site does not have; dropped`,\n )\n return undefined\n }\n break\n }\n case 'media': {\n if (bindingTokens?.has(value)) break\n if (isHttpsUrl(value)) break\n const ref = parseMediaRef(value)\n if (!ref || (assetIds && !assetIds.has(ref.mediaId))) {\n repairs.push(\n `${nodeId}.${name} is neither a media reference this site holds nor an https: URL; dropped`,\n )\n return undefined\n }\n break\n }\n default: {\n if (value.length > PLAIN_STRING_MAX) {\n repairs.push(\n `${nodeId}.${name} is over ${PLAIN_STRING_MAX} characters; dropped`,\n )\n return undefined\n }\n }\n }\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) {\n repairs.push(`${nodeId}.${name} does not match its pattern; dropped`)\n return undefined\n }\n if (schema.minLength !== undefined && value.length < schema.minLength) {\n repairs.push(\n `${nodeId}.${name} is shorter than ${schema.minLength} characters; dropped`,\n )\n return undefined\n }\n if (schema.maxLength !== undefined && value.length > schema.maxLength) {\n value = value.slice(0, schema.maxLength).trimEnd()\n repairs.push(\n `${nodeId}.${name} was over ${schema.maxLength} characters; truncated`,\n )\n }\n return value\n}\n\n/**\n * The element's own declarations plus the node capabilities every element\n * carries (AGL-3156) — repeating, today. Two shapes only, so they are built\n * once each rather than per node: a capability prop is the same on every\n * element with the same child contract.\n *\n * The element wins a name collision. A component that declared a prop of its\n * own under a capability's name would be describing its own attribute, and the\n * validator has to hold it to that.\n */\nconst CAPABLE_ENTRIES = new WeakMap<AiPaletteEntry, AiPaletteEntry>()\n\nfunction withNodeCapabilities(entry: AiPaletteEntry): AiPaletteEntry {\n const cached = CAPABLE_ENTRIES.get(entry)\n if (cached) return cached\n const capability = nodeCapabilityProps(\n AI_NODE_CAPABILITIES,\n entry.acceptsChildren,\n )\n const merged: AiPaletteEntry = {\n ...entry,\n propsSchema: {\n ...entry.propsSchema,\n properties: {\n ...capability.properties,\n ...entry.propsSchema.properties,\n },\n },\n propRoles: { ...capability.propRoles, ...entry.propRoles },\n textLimits: { ...capability.textLimits, ...entry.textLimits },\n }\n CAPABLE_ENTRIES.set(entry, merged)\n return merged\n}\n\n/**\n * Plugins whose elements play audio (AGL-3716): the Music player. A model\n * never sources a recording and never vouches for one, so on their elements\n * `rightsConfirmed` is always dropped and `src` is kept only as a reference\n * to a file in the site's own library (which the asset check grounds) or a\n * binding. Named by plugin id, as the listings name their elements: a plugin\n * never imports another.\n */\nexport const AI_OWNER_AUDIO_PLUGIN_IDS: ReadonlySet<string> = new Set(['music'])\n\n/** Why an audio element's prop a model wrote is dropped, or null to keep it. */\nexport function aiOwnerAudioRefusal(\n pluginId: string | undefined,\n name: string,\n value: unknown,\n bindingTokens: ReadonlySet<string> | null = null,\n): string | null {\n if (!pluginId || !AI_OWNER_AUDIO_PLUGIN_IDS.has(pluginId)) return null\n if (name === 'rightsConfirmed') {\n return 'only the site owner can confirm they hold the rights to a recording'\n }\n if (name !== 'src') return null\n const text = typeof value === 'string' ? value.trim() : ''\n if (!text || parseMediaRef(text) || bindingTokens?.has(text)) return null\n return 'a player plays only audio from the owner’s own media library, never a recording from elsewhere'\n}\n\nfunction sanitizeProps(\n nodeId: string,\n paletteEntry: AiPaletteEntry,\n raw: unknown,\n screenIds: Set<string> | null,\n assetIds: Set<string> | null,\n repairs: string[],\n bindingTokens: ReadonlySet<string> | null = null,\n): { props: Record<string, unknown> } | { missing: string } {\n const entry = withNodeCapabilities(paletteEntry)\n const source = isRecord(raw) ? raw : {}\n const props: Record<string, unknown> = {}\n const declared = entry.propsSchema.properties\n for (const [name, value] of Object.entries(source)) {\n // `sx` is read off the node instead; a model that put it here meant the\n // same thing, and the caller has already moved it.\n if (name === 'sx' || value === undefined || value === null) continue\n // Audio is the owner's own, always (AGL-3716).\n const audioRefusal = aiOwnerAudioRefusal(entry.pluginId, name, value, bindingTokens)\n if (audioRefusal) {\n repairs.push(`${nodeId}.${name}: ${audioRefusal}; dropped`)\n continue\n }\n const schema = declared[name]\n if (!schema) {\n repairs.push(\n `${nodeId}.${name} is not a prop of ${entry.displayName}; dropped`,\n )\n continue\n }\n if (schema.enum) {\n const coerced = coerceEnum(schema, value)\n if (coerced === undefined) {\n repairs.push(\n `${nodeId}.${name} is not one of ${schema.enum.join('|')}; dropped`,\n )\n continue\n }\n if (coerced !== value) {\n repairs.push(\n `${nodeId}.${name} was spelled \"${String(value)}\"; normalized to \"${coerced}\"`,\n )\n }\n props[name] = coerced\n continue\n }\n switch (schema.type) {\n case 'boolean': {\n const coerced = coerceBoolean(value)\n if (coerced === undefined) {\n repairs.push(`${nodeId}.${name} is not a boolean; dropped`)\n continue\n }\n props[name] = coerced\n break\n }\n case 'number':\n case 'integer': {\n const coerced = coerceNumber(schema, value)\n if (coerced === undefined) {\n repairs.push(`${nodeId}.${name} is not a number in range; dropped`)\n continue\n }\n props[name] = coerced\n break\n }\n default: {\n const text =\n typeof value === 'string'\n ? value\n : typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : undefined\n if (text === undefined) {\n repairs.push(`${nodeId}.${name} is not text; dropped`)\n continue\n }\n const cleaned = sanitizeString(\n nodeId,\n entry,\n name,\n schema,\n text,\n source,\n screenIds,\n assetIds,\n repairs,\n bindingTokens,\n )\n if (cleaned === undefined) continue\n props[name] = cleaned\n }\n }\n }\n for (const name of entry.propsSchema.required) {\n if (props[name] === undefined) return { missing: name }\n }\n return { props }\n}\n\n/** Surfaces that compose page elements, and so may place a component instance. */\nconst INSTANCE_SURFACES: ReadonlySet<AiSurface> = new Set([\n 'screen',\n 'layout',\n 'component',\n])\n\nconst FORM_COMPONENT_ID = 'form'\n\n/** The prop a repeat over a dataset is stored under (the data plugin's `repeatDataset`). Persisted — never rename. */\nexport const AI_REPEAT_DATASET_PROP = 'repeatDataset'\n\n/** The instance prop naming the component it places; stored on every instance node. */\nexport const AI_INSTANCE_REF_PROP = 'refId'\n\ninterface ReferenceSets {\n componentIds: Set<string> | null\n componentProps: Record<string, AiComponentPropTypes>\n formIds: Set<string> | null\n datasetIds: Set<string> | null\n assetIds: Set<string> | null\n /** The tree defines a reusable component, which may hand its own property tokens on. */\n definesComponent: boolean\n}\n\n/**\n * One value an instance fills in for a declared prop, held to what the\n * declaration's type can hold: a picture from the library, a link, a number,\n * a switch, or copy.\n */\nfunction instancePropValue(\n nodeId: string,\n name: string,\n type: string,\n raw: unknown,\n assetIds: Set<string> | null,\n repairs: string[],\n): unknown {\n if (type === 'number') {\n const parsed = typeof raw === 'number' ? raw : Number(raw)\n if (raw === '' || !Number.isFinite(parsed)) {\n repairs.push(`${nodeId}.propValues.${name} is not a number; dropped`)\n return undefined\n }\n return parsed\n }\n if (type === 'boolean') {\n const coerced = coerceBoolean(raw)\n if (coerced === undefined) {\n repairs.push(`${nodeId}.propValues.${name} is not a boolean; dropped`)\n }\n return coerced\n }\n if (type === 'icon') {\n // A page cannot fill an icon: the pick is an id and the path drawn from\n // it, and a word in its place draws nothing (AGL-3054). The property is\n // left for the site owner to pick.\n repairs.push(`${nodeId}.propValues.${name} is an icon, which the site owner picks from the library; dropped`)\n return undefined\n }\n if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean') {\n repairs.push(`${nodeId}.propValues.${name} is not a value; dropped`)\n return undefined\n }\n const value = String(raw).trim()\n if (HOSTILE_TEXT.test(value)) {\n repairs.push(`${nodeId}.propValues.${name} carried markup or script; dropped`)\n return undefined\n }\n if (type === 'image') {\n if (isHttpsUrl(value)) return value\n const ref = parseMediaRef(value)\n if (!ref || (assetIds && !assetIds.has(ref.mediaId))) {\n repairs.push(\n `${nodeId}.propValues.${name} is neither a media reference this site holds nor an https: URL; dropped`,\n )\n return undefined\n }\n return value\n }\n if (type === 'href') {\n if (isHttpsUrl(value) || isRootRelativePath(value)) return value\n repairs.push(\n `${nodeId}.propValues.${name} is neither an https: URL nor a path on this site; dropped`,\n )\n return undefined\n }\n if (value.length > AI_TEXT_LIMITS.body) {\n repairs.push(\n `${nodeId}.propValues.${name} was over ${AI_TEXT_LIMITS.body} characters; truncated`,\n )\n return value.slice(0, AI_TEXT_LIMITS.body).trimEnd()\n }\n return value\n}\n\n/**\n * The site-record props of one node — an instance's `refId` and\n * `propValues`, a Form's `formId` and `datasetId` — checked against the ids\n * the caller supplied. They leave `props` before the palette pass, which\n * would drop them as undeclared, and come back in `kept` once checked.\n */\nfunction sanitizeReferenceProps(\n nodeId: string,\n componentId: string,\n props: Record<string, unknown>,\n refs: ReferenceSets,\n repairs: string[],\n): { props: Record<string, unknown>; kept: Record<string, unknown> } | { refusal: string } {\n const rest: Record<string, unknown> = { ...props }\n const kept: Record<string, unknown> = {}\n // A repeat over one of the site's datasets (AGL-3616), on any element: the\n // platform's own repeat, admitted against the datasets the caller supplies,\n // as a Form's dataset binding is. The palette leaves it off, since from a\n // description alone a model can only invent a dataset's id.\n if (AI_REPEAT_DATASET_PROP in rest) {\n const raw = rest[AI_REPEAT_DATASET_PROP]\n delete rest[AI_REPEAT_DATASET_PROP]\n const id = typeof raw === 'string' ? raw.trim() : ''\n if (id && refs.datasetIds?.has(id)) {\n kept[AI_REPEAT_DATASET_PROP] = id\n } else if (raw !== undefined && raw !== null && raw !== '') {\n repairs.push(`${nodeId}.${AI_REPEAT_DATASET_PROP} names a dataset this site does not have; dropped`)\n }\n }\n if (componentId === REUSABLE_INSTANCE_COMPONENT_ID) {\n const refId = typeof rest[AI_INSTANCE_REF_PROP] === 'string' ? String(rest[AI_INSTANCE_REF_PROP]).trim() : ''\n delete rest[AI_INSTANCE_REF_PROP]\n if (!refId || !refs.componentIds?.has(refId)) {\n return {\n refusal: `Reusable Component (${nodeId}) names a component this site does not have`,\n }\n }\n kept[AI_INSTANCE_REF_PROP] = refId\n const rawValues = rest[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n delete rest[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n if (rawValues !== undefined && !isRecord(rawValues)) {\n repairs.push(`${nodeId}.propValues is not an object; dropped`)\n }\n const declared = refs.componentProps[refId]\n const values: Record<string, unknown> = {}\n for (const [name, raw] of Object.entries(isRecord(rawValues) ? rawValues : {})) {\n if (raw === undefined || raw === null) continue\n if (!COMPONENT_PROP_NAME_PATTERN.test(name)) {\n repairs.push(`${nodeId}.propValues.${name} is not a prop name; dropped`)\n continue\n }\n if (declared && !(name in declared)) {\n repairs.push(`${nodeId}.propValues.${name} is not a prop of that component; dropped`)\n continue\n }\n if (refs.definesComponent && isAiComponentPropToken(raw)) {\n // A property of the component being defined, handed on whole; the\n // component step's check holds it to the kind this prop declares.\n values[name] = raw.trim()\n continue\n }\n const value = instancePropValue(\n nodeId,\n name,\n declared?.[name] ?? 'text',\n raw,\n refs.assetIds,\n repairs,\n )\n if (value !== undefined) values[name] = value\n }\n if (Object.keys(values).length) kept[REUSABLE_INSTANCE_PROP_VALUES_KEY] = values\n return { props: rest, kept }\n }\n if (componentId === FORM_COMPONENT_ID) {\n const bindings: Array<[prop: string, ids: Set<string> | null, record: string]> = [\n ['formId', refs.formIds, 'form'],\n ['datasetId', refs.datasetIds, 'dataset'],\n ]\n for (const [prop, ids, record] of bindings) {\n const raw = rest[prop]\n delete rest[prop]\n if (raw === undefined || raw === null || raw === '') continue\n const id = typeof raw === 'string' ? raw.trim() : ''\n if (id && ids?.has(id)) {\n kept[prop] = id\n } else {\n repairs.push(`${nodeId}.${prop} names a ${record} this site does not have; dropped`)\n }\n }\n }\n return { props: rest, kept }\n}\n\nfunction refusalCode(error: string): AiNodeTreeRefusalCode {\n if (/too large/i.test(error)) return 'too-large'\n if (/cannot be published/i.test(error)) return 'component'\n return 'structure'\n}\n\n/**\n * Whether the root the model wrote is the surface's root: the canvas wrapper\n * for a document surface (which the sanitizer exempts by the same shape), or\n * the named component otherwise.\n */\nfunction rootMatches(surfaceRoot: string, componentId: unknown): boolean {\n if (surfaceRoot === 'div') {\n return componentId == null || componentId === '' || componentId === 'div'\n }\n return componentId === surfaceRoot\n}\n\nexport function validateAiNodeTree(\n input: unknown,\n surface: AiSurface,\n context?: AiNodeTreeContext,\n): AiNodeTreeResult {\n try {\n return validate(input, surface, context)\n } catch (error) {\n return {\n ok: false,\n code: 'invalid-input',\n error: `The tree could not be read: ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n}\n\nexport type AiNodePatchResult =\n | {\n ok: true\n props: Record<string, unknown>\n sx: Record<string, unknown> | undefined\n repairs: string[]\n }\n | { ok: false; error: string; code: AiNodeTreeRefusalCode }\n\n/**\n * One element's prop and style patch, held to the rules `validateAiNodeTree`\n * holds an element it places — for an edit to an element already on the\n * canvas, where there is no tree to validate.\n *\n * The same passes run: unknown props dropped, enums coerced, every string\n * held to its role and screened for markup, `sx` held to the key set and the\n * value grammar. The one difference is `required`: a patch is merged over the\n * props the element already has, so a required prop the patch does not name\n * is not missing.\n */\nexport function validateAiNodePatch(\n componentId: string,\n patch: { props?: unknown; sx?: unknown },\n context?: AiNodeTreeContext,\n): AiNodePatchResult {\n const entry = AI_PALETTE[componentId]\n if (!entry) {\n return {\n ok: false,\n code: 'component',\n error: `Component \"${componentId}\" is not in the palette`,\n }\n }\n const repairs: string[] = []\n const props = sanitizeProps(\n componentId,\n { ...entry, propsSchema: { ...entry.propsSchema, required: [] } },\n patch.props,\n context?.screenIds ? new Set(context.screenIds) : null,\n context?.assetIds ? new Set(context.assetIds) : null,\n repairs,\n )\n const sx =\n patch.sx === undefined ? undefined : sanitizeSx(componentId, patch.sx, repairs)\n return {\n ok: true,\n props: 'props' in props ? props.props : {},\n sx,\n repairs,\n }\n}\n\nfunction validate(\n input: unknown,\n surface: AiSurface,\n context: AiNodeTreeContext | undefined,\n): AiNodeTreeResult {\n const definition = AI_SURFACES[surface]\n if (!definition) {\n return {\n ok: false,\n code: 'invalid-input',\n error: `Unknown surface \"${surface}\"`,\n }\n }\n if (\n !isRecord(input) ||\n typeof input.rootId !== 'string' ||\n !isRecord(input.nodes)\n ) {\n return {\n ok: false,\n code: 'invalid-input',\n error: 'Expected an object with a string rootId and a nodes map',\n }\n }\n const rootId = input.rootId\n const nodes = input.nodes as Record<string, unknown>\n const root = nodes[rootId]\n if (!isRecord(root)) {\n return {\n ok: false,\n code: 'structure',\n error: 'Definition has no root node',\n }\n }\n if (!rootMatches(definition.root, root.componentId)) {\n return {\n ok: false,\n code: 'root',\n error: `A ${surface} starts with ${definition.root === 'div' ? 'the document wrapper' : `\"${definition.root}\"`}, not \"${String(root.componentId)}\"`,\n }\n }\n\n // The sanitizer keeps only the persisted node keys, and `sx` is not one of\n // them for a listing. Read it off every node first — from the node field\n // or from `props.sx`, which a model writes just as readily — and put it\n // back, checked, on the nodes that survive.\n const sxByNodeId = new Map<string, unknown>()\n const hiddenByNodeId = new Set<string>()\n for (const [id, node] of Object.entries(nodes)) {\n if (!isRecord(node)) continue\n const sx =\n node.sx !== undefined\n ? node.sx\n : isRecord(node.props)\n ? node.props.sx\n : undefined\n if (sx !== undefined) sxByNodeId.set(id, sx)\n if (node.hidden === true) hiddenByNodeId.add(id)\n }\n\n // A DAM reference (a `media:` value) is not a URL the sanitizer's\n // `src` policy admits — a listing must not carry another tenant's asset —\n // but on the tenant's own page it is exactly what an image should name.\n // Lift those values out before sanitizing and hand them back to the prop\n // pass, which holds them to the asset set the caller supplied.\n // A binding token the caller admitted (AGL-2909) is lifted the same way:\n // `{{entry.coverImage}}` is no address the sanitizer knows, and the prop\n // pass holds it to the tokens the caller named.\n const bindingTokens = context?.bindingTokens ? new Set(context.bindingTokens) : null\n // A reusable component's own property tokens (AGL-2908) are lifted too, and\n // kept as written rather than handed back to the prop pass: `{{prop.variant}}`\n // is no value a dropdown, a switch, an address or a visibility directive\n // admits. Copy keeps its tokens without lifting, as the text they are.\n const definesComponent = context?.definesComponent === true\n const codeBuilt = context?.codeBuilt === true\n const mediaByNodeId = new Map<string, Record<string, string>>()\n const boundByNodeId = new Map<string, Record<string, string>>()\n // A code-built Icon's drawing, from the library by the id it names (AGL-3660).\n const iconByNodeId = new Map<string, { iconId: string; iconPath: string }>()\n const forSanitizer: Record<string, unknown> = {}\n for (const [id, node] of Object.entries(nodes)) {\n if (!isRecord(node) || !isRecord(node.props)) {\n forSanitizer[id] = node\n continue\n }\n if (codeBuilt && node.componentId === AI_ICON_COMPONENT_ID) {\n const { iconId, ...props } = node.props\n const rest = { ...props }\n delete rest['iconPath']\n const icon = aiIconOfId(iconId)\n if (icon) iconByNodeId.set(id, { iconId: icon.id, iconPath: icon.path })\n forSanitizer[id] = { ...node, props: rest }\n continue\n }\n const entry = AI_PALETTE[String(node.componentId)]\n const roles = entry?.propRoles ?? {}\n const props: Record<string, unknown> = { ...node.props }\n const lifted: Record<string, string> = {}\n const bound: Record<string, string> = {}\n for (const [key, value] of Object.entries(props)) {\n if (typeof value !== 'string') continue\n const role = roles[key]\n if (\n definesComponent &&\n isAiComponentPropToken(value) &&\n (AI_COMPONENT_VISIBILITY_PROPS.includes(key) ||\n (entry?.propsSchema.properties[key] !== undefined && role !== 'text'))\n ) {\n bound[key] = value.trim()\n delete props[key]\n continue\n }\n if (\n (role === 'media' && parseMediaRef(value.trim())) ||\n ((role === 'media' || role === 'url') && bindingTokens?.has(value.trim()))\n ) {\n lifted[key] = value\n delete props[key]\n }\n }\n if (Object.keys(lifted).length) mediaByNodeId.set(id, lifted)\n if (Object.keys(bound).length) boundByNodeId.set(id, bound)\n forSanitizer[id] = { ...node, props }\n }\n\n const refs: ReferenceSets = {\n componentIds: context?.componentIds ? new Set(context.componentIds) : null,\n componentProps: context?.componentProps ?? {},\n formIds: context?.formIds ? new Set(context.formIds) : null,\n datasetIds: context?.datasetIds ? new Set(context.datasetIds) : null,\n assetIds: context?.assetIds ? new Set(context.assetIds) : null,\n definesComponent,\n }\n // An instance is admitted only where the caller grounded it in the site's\n // components; the reference itself is checked on the node below.\n const surfaceAllow = codeBuilt ? [...definition.allow, ...(definition.codeOnly ?? [])] : definition.allow\n const allow =\n refs.componentIds && INSTANCE_SURFACES.has(surface)\n ? [...surfaceAllow, REUSABLE_INSTANCE_COMPONENT_ID]\n : surfaceAllow\n const sanitized = sanitizePortableDefinition(\n { rootId, nodes: forSanitizer },\n { componentIds: allow },\n )\n if (sanitized.ok === false) {\n return {\n ok: false,\n code: refusalCode(sanitized.error),\n error: sanitized.error,\n }\n }\n\n const screenIds = context?.screenIds ? new Set(context.screenIds) : null\n const assetIds = refs.assetIds\n const repairs: string[] = []\n const output: NodesMap = {}\n const rootIsWrapper =\n rootMatches('div', root.componentId) && definition.root === 'div'\n const minted = new Map<string, string>()\n const mint = (id: string): string => {\n const fresh =\n id === rootId && rootIsWrapper\n ? CANVAS_ROOT_ELEMENT_ID\n : createIdUrlSafe()\n minted.set(id, fresh)\n return fresh\n }\n\n /** Each visited node's parent by the model's own ids, for the parentId check. */\n const parentOf = new Map<string, string>()\n const queue: Array<{ id: string; parentId: string | null }> = [\n { id: rootId, parentId: null },\n ]\n mint(rootId)\n while (queue.length) {\n const { id, parentId } = queue.shift() as {\n id: string\n parentId: string | null\n }\n const node = sanitized.nodes[id]\n const entry = AI_PALETTE[node.componentId]\n if (!entry) {\n return {\n ok: false,\n code: 'component',\n error: `Component \"${node.componentId}\" is not in the palette`,\n }\n }\n const newId = minted.get(id) as string\n const raw = nodes[id]\n if (isRecord(raw)) {\n // The sanitizer drops silently; the model is told what went.\n for (const key of STRIPPED_NODE_KEYS) {\n if (raw[key] !== undefined) {\n repairs.push(\n `${id}.${key} is not something a generated node may set; dropped`,\n )\n }\n }\n if (raw.hidden !== undefined && typeof raw.hidden !== 'boolean') {\n repairs.push(`${id}.hidden is not a boolean; dropped`)\n }\n if (raw.nodes !== undefined && !Array.isArray(raw.nodes)) {\n repairs.push(\n `${id}.nodes is not a list of child ids; its children were dropped`,\n )\n }\n if (\n raw.parentId !== undefined &&\n raw.parentId !== null &&\n raw.parentId !== (parentId === null ? null : parentOf.get(id))\n ) {\n repairs.push(\n `${id}.parentId disagreed with where the tree places it; recomputed`,\n )\n }\n if (isRecord(raw.props)) {\n const lifted = mediaByNodeId.get(id) ?? {}\n const kept = boundByNodeId.get(id) ?? {}\n for (const key of Object.keys(raw.props)) {\n if (iconByNodeId.has(id) && (key === 'iconId' || key === 'iconPath')) continue\n if (\n key !== 'sx' &&\n lifted[key] === undefined &&\n kept[key] === undefined &&\n node.props?.[key] === undefined &&\n raw.props[key] !== undefined\n ) {\n repairs.push(\n `${id}.${key} was an unsafe handler, address or markup; dropped`,\n )\n }\n }\n }\n }\n const children: string[] = []\n for (const childId of node.nodes ?? []) {\n if (minted.has(childId)) {\n repairs.push(\n `${childId} was listed under more than one parent; the later listing was dropped`,\n )\n continue\n }\n const child = sanitized.nodes[childId]\n if (!child) continue\n const childEntry = AI_PALETTE[child.componentId]\n if (!childEntry) {\n return {\n ok: false,\n code: 'component',\n error: `Component \"${child.componentId}\" is not in the palette`,\n }\n }\n if (!entry.acceptsChildren) {\n return {\n ok: false,\n code: 'lineage',\n error: `${entry.displayName} (${id}) cannot hold other elements, but lists ${childId}`,\n }\n }\n if (\n !linealRelationshipPermits(\n {\n componentId: child.componentId,\n pluginId: childEntry.pluginId,\n restrictParent: childEntry.restrictParent,\n },\n {\n componentId: node.componentId,\n pluginId: entry.pluginId,\n restrictChildren: entry.restrictChildren,\n },\n )\n ) {\n return {\n ok: false,\n code: 'lineage',\n error: `${childEntry.displayName} (${childId}) cannot be placed inside ${entry.displayName} (${id})`,\n }\n }\n children.push(mint(childId))\n parentOf.set(childId, id)\n queue.push({ id: childId, parentId: newId })\n }\n\n const reference = sanitizeReferenceProps(\n id,\n node.componentId,\n { ...node.props, ...mediaByNodeId.get(id) },\n refs,\n repairs,\n )\n if ('refusal' in reference) {\n return { ok: false, code: 'reference', error: reference.refusal }\n }\n // A required prop the component binds is present: its value is the token.\n const boundProps = boundByNodeId.get(id)\n const propsResult = sanitizeProps(\n id,\n boundProps\n ? {\n ...entry,\n propsSchema: {\n ...entry.propsSchema,\n required: entry.propsSchema.required.filter((name) => boundProps[name] === undefined),\n },\n }\n : entry,\n reference.props,\n screenIds,\n assetIds,\n repairs,\n bindingTokens,\n )\n if ('missing' in propsResult) {\n return {\n ok: false,\n code: 'required-prop',\n error: `${entry.displayName} (${id}) is missing its required \"${propsResult.missing}\" prop`,\n }\n }\n const sx = sanitizeSx(id, sxByNodeId.get(id), repairs)\n output[newId] = {\n $id: newId,\n type: NodeType.NODE,\n componentId: node.componentId,\n pluginId: entry.pluginId,\n parentId,\n nodes: children,\n props: { ...propsResult.props, ...reference.kept, ...boundProps, ...iconByNodeId.get(id) },\n ...(sx ? { sx } : {}),\n ...(hiddenByNodeId.has(id) ? { hidden: true } : {}),\n }\n }\n\n // The save's own measurement (msgpack), not a JSON string length: the\n // ceiling is stated in those bytes, and a UTF-16 length reads multi-byte\n // copy as smaller than the document the save will refuse.\n const bytes = nodeMapBytes(output)\n if (bytes > NODE_MAP_MAX_BYTES) {\n return {\n ok: false,\n code: 'too-large',\n error: `The tree is ${bytes} bytes; the stored ceiling is ${NODE_MAP_MAX_BYTES}`,\n }\n }\n const sourceIds: Record<string, string> = {}\n for (const [source, fresh] of minted) sourceIds[fresh] = source\n return {\n ok: true,\n rootId: minted.get(rootId) as string,\n nodes: output,\n repairs,\n sourceIds,\n }\n}\n"],"names":["AI_TEXT_LIMITS","isHeadlineVariant","nodeCapabilityProps","AI_NODE_CAPABILITIES","AI_PALETTE","AI_SURFACES","AI_SX_TOKENS","linealRelationshipPermits","NODE_MAP_MAX_BYTES","nodeMapBytes","parseMediaRef","COMPONENT_PROP_NAME_PATTERN","REUSABLE_INSTANCE_COMPONENT_ID","REUSABLE_INSTANCE_PROP_VALUES_KEY","createIdUrlSafe","CANVAS_ROOT_ELEMENT_ID","NodeType","AI_ICON_COMPONENT_ID","aiIconOfId","AI_COMPONENT_VISIBILITY_PROPS","isAiComponentPropToken","sanitizePortableDefinition","AI_SX_ALLOWED_KEYS","Set","HOSTILE_TEXT","SX_VALUE","STRIPPED_NODE_KEYS","SCREEN_ID","ICON_PICKER_FIELD","MAX_SX_KEYS","PLAIN_STRING_MAX","paletteTokens","palette","breakpoints","typographyVariants","isRecord","value","Array","isArray","isHttpsUrl","test","URL","protocol","isContactHref","isRootRelativePath","sxValueAllowed","key","Number","isFinite","trimmed","trim","has","sanitizeSx","nodeId","sx","repairs","undefined","push","out","kept","Object","entries","responsive","breakpoint","inner","keys","length","coerceEnum","schema","enum","wanted","toLowerCase","find","option","coerceBoolean","coerceNumber","parsed","NaN","type","isInteger","minimum","maximum","textLimitFor","entry","name","props","declared","textLimits","variant","Math","min","body","headline","sanitizeString","raw","screenIds","assetIds","bindingTokens","propFields","role","propRoles","limit","slice","trimEnd","ref","mediaId","pattern","RegExp","minLength","maxLength","CAPABLE_ENTRIES","WeakMap","withNodeCapabilities","cached","get","capability","acceptsChildren","merged","propsSchema","properties","set","AI_OWNER_AUDIO_PLUGIN_IDS","aiOwnerAudioRefusal","pluginId","text","sanitizeProps","paletteEntry","source","audioRefusal","displayName","coerced","join","String","cleaned","required","missing","INSTANCE_SURFACES","FORM_COMPONENT_ID","AI_REPEAT_DATASET_PROP","AI_INSTANCE_REF_PROP","instancePropValue","sanitizeReferenceProps","componentId","refs","rest","id","datasetIds","refId","componentIds","refusal","rawValues","componentProps","values","definesComponent","bindings","formIds","prop","ids","record","refusalCode","error","rootMatches","surfaceRoot","validateAiNodeTree","input","surface","context","validate","ok","code","Error","message","validateAiNodePatch","patch","definition","rootId","nodes","root","sxByNodeId","Map","hiddenByNodeId","node","hidden","add","codeBuilt","mediaByNodeId","boundByNodeId","iconByNodeId","forSanitizer","iconId","icon","iconPath","path","roles","lifted","bound","includes","surfaceAllow","allow","codeOnly","sanitized","output","rootIsWrapper","minted","mint","fresh","parentOf","queue","parentId","shift","newId","children","childId","child","childEntry","restrictParent","restrictChildren","reference","boundProps","propsResult","filter","$id","NODE","bytes","sourceIds"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,iBAAiB,EACjBC,mBAAmB,QAId,kBAAc;AACrB,SACEC,oBAAoB,EACpBC,UAAU,EACVC,WAAW,EACXC,YAAY,QACP,4BAAwB;AAC/B,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,SACEC,kBAAkB,EAClBC,YAAY,QACP,0CAAyC;AAChD,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SACEC,2BAA2B,EAC3BC,8BAA8B,EAC9BC,iCAAiC,QAC5B,iDAAgD;AACvD,SAASC,eAAe,QAAQ,wCAAuC;AACvE,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,QAAQ,QAAuB,2BAA0B;AAElE,SAASC,oBAAoB,EAAEC,UAAU,QAAQ,uBAAmB;AACpE,SACEC,6BAA6B,EAC7BC,sBAAsB,QACjB,6BAAyB;AAEhC,SAASC,0BAA0B,QAAQ,mDAAkD;AA0H7F;;;;;CAKC,GACD,OAAO,MAAMC,qBAA0C,IAAIC,IAAI;IAC7D,UAAU;IACV;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,QAAQ;IACR;IACA;IACA;IACA;IACA;IACA,aAAa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,SAAS;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,UAAU;IACV;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,UAAU;IACV;IACA;IACA,OAAO;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,OAAO;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,EAAC;AAEF;;;;CAIC,GACD,OAAO,MAAMC,eACX,2LAA0L;AAE5L;;;;;;CAMC,GACD,OAAO,MAAMC,WAAW,qCAAoC;AAE5D;;;;CAIC,GACD,MAAMC,qBAAqB;IACzB;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,YAAY;AA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GAAG,CAAC6D;QACnBC,OAAOyB;QACPlJ;QACAyK;IACF;AACF"}
@@ -18,7 +18,7 @@ import type { AglynOrganization } from '@aglyn/aglyn/foundation/definitions/orga
18
18
  /**
19
19
  * Whether an add-on this workspace can buy grants `aiGenerative`: the
20
20
  * console's `entitlementPurchasable`, over the add-ons the AI plugin declares
21
- * on the server.
21
+ * on the server (`pluginSeatAddonSoldOn`).
22
22
  */
23
23
  export declare function aiGenerativePurchasable(org: Partial<AglynOrganization>): boolean;
24
24
  /** The door: whether a list draws Create with AI, as what, and every word its brief says. */
@@ -21,7 +21,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
21
21
  import { checkEntitlement } from "@aglyn/aglyn/server";
22
22
  import { COLLECTIONS_MAX_PER_HOST } from "@aglyn/aglyn/app-utils/collection-entries";
23
23
  import { aiAddonName, isUncappedPlanComp, orgSubscriptionState, resolveEffectivePlan } from "@aglyn/aglyn/app-utils/plan-entitlements";
24
- import { listPluginSeatAddons } from "@aglyn/aglyn/plugin-manager/plugin-entitlements";
24
+ import { listPluginSeatAddons, pluginSeatAddonSoldOn } from "@aglyn/aglyn/plugin-manager/plugin-entitlements";
25
25
  import { emailUnverifiedResponse, firebaseAdmin, isImpersonationSession } from "@aglyn/tenant-data-admin/server/firebase-admin";
26
26
  import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
27
27
  import { getOrgForUser, memberHasPermissionOnHost } from "@aglyn/tenant-data-admin/server/organizations";
@@ -92,15 +92,14 @@ async function doorCaller(request, orgId) {
92
92
  /**
93
93
  * Whether an add-on this workspace can buy grants `aiGenerative`: the
94
94
  * console's `entitlementPurchasable`, over the add-ons the AI plugin declares
95
- * on the server.
95
+ * on the server (`pluginSeatAddonSoldOn`).
96
96
  */ export function aiGenerativePurchasable(org) {
97
97
  const billing = org;
98
98
  if (orgSubscriptionState(billing) !== 'live') return false;
99
99
  const plan = resolveEffectivePlan(billing);
100
100
  return listPluginSeatAddons().some((addon)=>{
101
- var _addon_quota_perUnitByPlan_plan;
102
101
  var _addon_features;
103
- return ((_addon_features = addon.features) == null ? void 0 : _addon_features.includes('aiGenerative')) && (!addon.quota || ((_addon_quota_perUnitByPlan_plan = addon.quota.perUnitByPlan[plan]) != null ? _addon_quota_perUnitByPlan_plan : 0) > 0);
102
+ return ((_addon_features = addon.features) == null ? void 0 : _addon_features.includes('aiGenerative')) && pluginSeatAddonSoldOn(addon, plan);
104
103
  });
105
104
  }
106
105
  /** What is left of the month's credits, as the AI credits meter reads it. */ async function creditsFacts(firestore, orgId, org, now) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-create-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// lockdown-423: via libs/plugins/ai/src/lib/server/ai-jobs-gate.ts\n// The follow view climbs `aiJobsGate`, whose lockdown rung is the verdict. The\n// door answers what a list draws and starts nothing: a locked workspace's\n// start is refused by the jobs route's own ladder, in its own words.\n\nimport type { DecodedIdToken } from 'firebase-admin/auth'\nimport { checkEntitlement } from '@aglyn/aglyn/server'\nimport { COLLECTIONS_MAX_PER_HOST } from '@aglyn/aglyn/app-utils/collection-entries'\nimport {\n aiAddonName,\n isUncappedPlanComp,\n orgSubscriptionState,\n resolveEffectivePlan,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { listPluginSeatAddons } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { AglynOrganization, AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n} from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { getOrgForUser, memberHasPermissionOnHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { aiJobSiteRefusal } from '../jobs/ai-job-admission'\nimport { aiJobSummary, getAiJob, listAiJobs } from '../jobs/ai-jobs'\nimport {\n aiCreateDoorView,\n aiJobFollowView,\n isAiCreateKind,\n type AiCreateCreditsFacts,\n type AiCreateKind,\n} from '../model/ai-create-view'\nimport { AI_JOB_ACTIVE_STATUSES, AI_PAGE_BUILDING_JOB_KINDS, aiSiteBuildInFlight } from '../model/ai-job-activity'\nimport { aiTemplateCollectionOptions } from '../model/ai-template-collections'\nimport { assistSpendAfterReturnsUsd, ASSIST_RETURNED_USD_FIELD } from '../usage/assist-credit-returns'\nimport { assistBandRefuses, publicAssistCredits, resolveAssistBudgetUsd } from '../usage/assist-credits'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport { aiJobsGate } from './ai-jobs-gate'\n\n/**\n * `GET /api/ai/create?orgId&hostId&kind` — the door one list's \"Create with\n * AI\" reads in the apps (AGL-3854), and `GET /api/ai/create/:jobId?orgId` —\n * the job it started, as the dialog's follow card reads it.\n *\n * The console draws each entry from its shell's gates and its own components\n * (`ai-describe-button`, `ai-brief-dialog`, `ai-job-follow`); the apps have\n * neither, so these answer the same verdicts and the same words as data\n * (`model/ai-create-view.ts`). Both only read. Starting, confirming and\n * canceling go through the jobs routes the console calls, whose ladder decides\n * every request exactly as it does for the console.\n */\n\nfunction bearerToken(request: Request): string | undefined {\n const authorization = request.headers.get('authorization') ?? ''\n return authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined\n}\n\n/** Every rung the console's shell climbs before it draws the entry, in the jobs gate's order. */\ninterface DoorCaller {\n decoded: DecodedIdToken\n staff: boolean\n orgId: string\n org: Partial<AglynOrganization>\n member: AglynOrgMember | null\n}\n\nasync function doorCaller(request: Request, orgId: string): Promise<Response | DoorCaller> {\n const idToken = bearerToken(request)\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n let decoded: DecodedIdToken\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n throw error\n }\n if (!decoded.email_verified && !isImpersonationSession(decoded)) return emailUnverifiedResponse()\n if (!orgId) return Response.json({ error: 'Open a workspace before using this feature' }, { status: 400 })\n const resolved = await getOrgForUser(decoded.uid, orgId)\n if (!resolved || resolved.orgId !== orgId) {\n return Response.json({ error: 'You are not a member of that organization' }, { status: 403 })\n }\n return {\n decoded,\n staff: decoded['staff'] === true,\n orgId,\n org: resolved.org ?? {},\n member: resolved.member ?? null,\n }\n}\n\n/**\n * Whether an add-on this workspace can buy grants `aiGenerative`: the\n * console's `entitlementPurchasable`, over the add-ons the AI plugin declares\n * on the server.\n */\nexport function aiGenerativePurchasable(org: Partial<AglynOrganization>): boolean {\n const billing = org as Parameters<typeof checkEntitlement>[0]\n if (orgSubscriptionState(billing as never) !== 'live') return false\n const plan = resolveEffectivePlan(billing as never)\n return listPluginSeatAddons().some(\n (addon) =>\n addon.features?.includes('aiGenerative') && (!addon.quota || (addon.quota.perUnitByPlan[plan] ?? 0) > 0),\n )\n}\n\n/** What is left of the month's credits, as the AI credits meter reads it. */\nasync function creditsFacts(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n org: Partial<AglynOrganization>,\n now: Date,\n): Promise<AiCreateCreditsFacts> {\n if (resolveEffectivePlan(org as never) === 'free') {\n const left = await readFreeAiCreditsLeft(firestore, { orgId, org: org as object, now })\n return left ? { kind: 'free', left } : { kind: 'none' }\n }\n const budgetUsd = resolveAssistBudgetUsd(org as never)\n if (budgetUsd === null) return isUncappedPlanComp(org as never) ? { kind: 'unlimited' } : { kind: 'none' }\n const usage = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('assistUsage')\n .doc(now.toISOString().slice(0, 7))\n .get()\n const credits = publicAssistCredits(\n assistSpendAfterReturnsUsd(usage.get('estCostUsd'), usage.get(ASSIST_RETURNED_USD_FIELD)),\n budgetUsd,\n )\n if (credits.limit === null || credits.remaining === null) return { kind: 'none' }\n return {\n kind: 'band',\n used: credits.used,\n limit: credits.limit,\n remaining: credits.remaining,\n stopsAtBand: assistBandRefuses(org as never),\n }\n}\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The door: whether a list draws Create with AI, as what, and every word its brief says. */\nexport async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const kind = url.searchParams.get('kind') ?? ''\n if (!isAiCreateKind(kind)) {\n return Response.json({ error: 'kind must be one of page, template, layout, form, component' }, { status: 400 })\n }\n const hostId = url.searchParams.get('hostId') ?? ''\n if (!ID_CHARS.test(hostId)) return Response.json({ error: 'hostId is not a site id' }, { status: 400 })\n const caller = await doorCaller(request, (url.searchParams.get('orgId') ?? '').trim())\n if (caller instanceof Response) return caller\n const { staff, orgId, org, member } = caller\n const firestore = firebaseAdmin.app().firestore()\n const now = new Date()\n const hidden = () =>\n Response.json(\n aiCreateDoorView({\n kind,\n shown: false,\n entitled: false,\n purchasable: false,\n canManageBilling: false,\n credits: { kind: 'none' },\n addonName: aiAddonName(),\n }),\n { headers: { 'Cache-Control': 'no-store' } },\n )\n\n // The shell's rungs, in the jobs gate's order: the reader's `ai.generate`\n // on this site, the release flag, then the site's own AI switch. Any of\n // them draws no entry at all; staff pass the first two, as they do there.\n if (!staff && !(await memberHasPermissionOnHost(orgId, hostId, member, 'ai.generate'))) return hidden()\n if (!staff && !(await isServerReleaseFlagOnForOrg('release_ai_generative', orgId))) return hidden()\n if (await aiJobSiteRefusal({ firestore, org, hostId })) return hidden()\n\n const entitled = checkEntitlement(org as never, 'aiGenerative')\n if (!entitled) {\n // Its own upsell where only the add-on is missing (AGL-3601): the add-on\n // store open to this workspace, and an add-on it can buy that grants it.\n const storeOpen = staff || (await isServerReleaseFlagOnForOrg('release_addon_store', orgId))\n const purchasable = !staff && storeOpen && aiGenerativePurchasable(org)\n const canManageBilling = purchasable && (await memberHasPermissionOnHost(orgId, null, member, 'billing.manage'))\n return Response.json(\n aiCreateDoorView({\n kind,\n shown: true,\n entitled: false,\n purchasable,\n canManageBilling,\n credits: { kind: 'none' },\n addonName: aiAddonName(),\n }),\n { headers: { 'Cache-Control': 'no-store' } },\n )\n }\n\n const [credits, collections, buildInFlight] = await Promise.all([\n creditsFacts(firestore, orgId, org, now).catch((error) => {\n console.error('[ai-create] credits read failed', orgId, error)\n return { kind: 'none' } as const\n }),\n kind === 'template'\n ? firestore\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .limit(COLLECTIONS_MAX_PER_HOST)\n .get()\n .then((snapshot) => ({\n status: 'success' as const,\n options: aiTemplateCollectionOptions(\n snapshot.docs.map((doc) => ({ ...(doc.data() as Record<string, unknown>), $id: doc.id })),\n ),\n }))\n .catch(() => ({ status: 'error' as const, options: [] }))\n : Promise.resolve(null),\n kind === 'page'\n ? listAiJobs(firestore, orgId, { statuses: AI_JOB_ACTIVE_STATUSES })\n .then((jobs) => aiSiteBuildInFlight(jobs.map((job) => aiJobSummary(job, now)), { hostId }) !== null)\n .catch(() => false)\n : Promise.resolve(false),\n ])\n return Response.json(\n aiCreateDoorView({\n kind: kind as AiCreateKind,\n shown: true,\n entitled: true,\n purchasable: false,\n canManageBilling: false,\n credits,\n collections,\n buildInFlight,\n addonName: aiAddonName(),\n }),\n { headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\n/** The follow view: one job of the workspace's, as the dialog that started it reads it. */\nexport async function GET_FOLLOW(request: Request, { params }: { params: Promise<{ jobId: string }> }): Promise<Response> {\n const { jobId } = await params\n if (!ID_CHARS.test(jobId ?? '')) return Response.json({ error: 'Not found' }, { status: 404 })\n const url = new URL(request.url)\n const gate = await aiJobsGate(request, url.searchParams.get('orgId') ?? '')\n if (gate instanceof Response) return gate\n const now = new Date()\n const job = await getAiJob(gate.firestore, gate.orgId, jobId)\n if (!job) return Response.json({ error: 'Not found' }, { status: 404 })\n const summary = aiJobSummary(job, now)\n // Confirming builds pages while another job is building on the site\n // (AGL-3765): asked only while this one waits on its plan.\n const askInFlight =\n summary.status === 'needs_review' &&\n summary.review?.reason === 'plan' &&\n AI_PAGE_BUILDING_JOB_KINDS.includes(summary.kind)\n const buildInFlight = askInFlight\n ? await listAiJobs(gate.firestore, gate.orgId, { statuses: AI_JOB_ACTIVE_STATUSES })\n .then(\n (jobs) =>\n aiSiteBuildInFlight(\n jobs.map((one) => aiJobSummary(one, now)),\n { hostId: summary.hostId, exceptJobId: summary.id },\n ) !== null,\n )\n .catch(() => false)\n : false\n return Response.json(\n {\n job: summary,\n view: aiJobFollowView(summary, {\n // Console addresses name the workspace by its slug, as every link the apps resolve does.\n orgSlug: typeof gate.org.slug === 'string' ? gate.org.slug : null,\n staff: gate.staff,\n buildInFlight,\n now: now.getTime(),\n }),\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\n"],"names":["checkEntitlement","COLLECTIONS_MAX_PER_HOST","aiAddonName","isUncappedPlanComp","orgSubscriptionState","resolveEffectivePlan","listPluginSeatAddons","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","invalidIdTokenResponse","getOrgForUser","memberHasPermissionOnHost","isServerReleaseFlagOnForOrg","aiJobSiteRefusal","aiJobSummary","getAiJob","listAiJobs","aiCreateDoorView","aiJobFollowView","isAiCreateKind","AI_JOB_ACTIVE_STATUSES","AI_PAGE_BUILDING_JOB_KINDS","aiSiteBuildInFlight","aiTemplateCollectionOptions","assistSpendAfterReturnsUsd","ASSIST_RETURNED_USD_FIELD","assistBandRefuses","publicAssistCredits","resolveAssistBudgetUsd","readFreeAiCreditsLeft","aiJobsGate","bearerToken","request","authorization","headers","get","startsWith","slice","length","undefined","doorCaller","orgId","resolved","idToken","Response","json","error","status","decoded","app","auth","verifyIdToken","unauthenticated","email_verified","uid","staff","org","member","aiGenerativePurchasable","billing","plan","some","addon","features","includes","quota","perUnitByPlan","creditsFacts","firestore","now","left","kind","budgetUsd","usage","collection","doc","toISOString","credits","limit","remaining","used","stopsAtBand","ID_CHARS","GET","url","URL","searchParams","hostId","test","caller","trim","Date","hidden","shown","entitled","purchasable","canManageBilling","addonName","storeOpen","collections","buildInFlight","Promise","all","catch","console","then","snapshot","options","docs","map","data","$id","id","resolve","statuses","jobs","job","GET_FOLLOW","params","summary","jobId","gate","askInFlight","review","reason","one","exceptJobId","view","orgSlug","slug","getTime","dynamic"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,mEAAmE;AACnE,+EAA+E;AAC/E,0EAA0E;AAC1E,qEAAqE;;AAGrE,SAASA,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,wBAAwB,QAAQ,4CAA2C;AACpF,SACEC,WAAW,EACXC,kBAAkB,EAClBC,oBAAoB,EACpBC,oBAAoB,QACf,2CAA0C;AACjD,SAASC,oBAAoB,QAAQ,kDAAiD;AAEtF,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,QACjB,iDAAgD;AACvD,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,aAAa,EAAEC,yBAAyB,QAAQ,gDAA+C;AACxG,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,gBAAgB,QAAQ,8BAA0B;AAC3D,SAASC,YAAY,EAAEC,QAAQ,EAAEC,UAAU,QAAQ,qBAAiB;AACpE,SACEC,gBAAgB,EAChBC,eAAe,EACfC,cAAc,QAGT,6BAAyB;AAChC,SAASC,sBAAsB,EAAEC,0BAA0B,EAAEC,mBAAmB,QAAQ,8BAA0B;AAClH,SAASC,2BAA2B,QAAQ,sCAAkC;AAC9E,SAASC,0BAA0B,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AAOxE,SAASC,IAAI,CAAC;QAAEC,OAAO;IAAY,GAAG;QAAEC,QAAQ;IAAI;IACrE,MAAMwE,UAAUzG,aAAasG,KAAK/C;IAClC,oEAAoE;IACpE,2DAA2D;IAC3D,MAAMqD,cACJH,QAAQxE,MAAM,KAAK,kBACnBwE,EAAAA,kBAAAA,QAAQI,MAAM,qBAAdJ,gBAAgBK,MAAM,MAAK,UAC3BvG,2BAA2B2C,QAAQ,CAACuD,QAAQhD,IAAI;IAClD,MAAM6B,gBAAgBsB,cAClB,MAAM1G,WAAWyG,KAAKrD,SAAS,EAAEqD,KAAKhF,KAAK,EAAE;QAAEyE,UAAU9F;IAAuB,GAC7EqF,IAAI,CACH,CAACU,OACC7F,oBACE6F,KAAKN,GAAG,CAAC,CAACgB,MAAQ/G,aAAa+G,KAAKxD,OACpC;YAAEkB,QAAQgC,QAAQhC,MAAM;YAAEuC,aAAaP,QAAQP,EAAE;QAAC,OAC9C,MAETT,KAAK,CAAC,IAAM,SACf;IACJ,OAAO3D,SAASC,IAAI,CAClB;QACEuE,KAAKG;QACLQ,MAAM7G,gBAAgBqG,SAAS;YAC7B,yFAAyF;YACzFS,SAAS,OAAOP,KAAKjE,GAAG,CAACyE,IAAI,KAAK,WAAWR,KAAKjE,GAAG,CAACyE,IAAI,GAAG;YAC7D1E,OAAOkE,KAAKlE,KAAK;YACjB6C;YACA/B,KAAKA,IAAI6D,OAAO;QAClB;IACF,GACA;QAAEnF,QAAQ;QAAKb,SAAS;YAAE,iBAAiB;QAAW;IAAE;AAE5D;AAEA,OAAO,MAAMiG,UAAU,gBAAe"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-create-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// lockdown-423: via libs/plugins/ai/src/lib/server/ai-jobs-gate.ts\n// The follow view climbs `aiJobsGate`, whose lockdown rung is the verdict. The\n// door answers what a list draws and starts nothing: a locked workspace's\n// start is refused by the jobs route's own ladder, in its own words.\n\nimport type { DecodedIdToken } from 'firebase-admin/auth'\nimport { checkEntitlement } from '@aglyn/aglyn/server'\nimport { COLLECTIONS_MAX_PER_HOST } from '@aglyn/aglyn/app-utils/collection-entries'\nimport {\n aiAddonName,\n isUncappedPlanComp,\n orgSubscriptionState,\n resolveEffectivePlan,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { listPluginSeatAddons, pluginSeatAddonSoldOn } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { AglynOrganization, AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n} from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { getOrgForUser, memberHasPermissionOnHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { aiJobSiteRefusal } from '../jobs/ai-job-admission'\nimport { aiJobSummary, getAiJob, listAiJobs } from '../jobs/ai-jobs'\nimport {\n aiCreateDoorView,\n aiJobFollowView,\n isAiCreateKind,\n type AiCreateCreditsFacts,\n type AiCreateKind,\n} from '../model/ai-create-view'\nimport { AI_JOB_ACTIVE_STATUSES, AI_PAGE_BUILDING_JOB_KINDS, aiSiteBuildInFlight } from '../model/ai-job-activity'\nimport { aiTemplateCollectionOptions } from '../model/ai-template-collections'\nimport { assistSpendAfterReturnsUsd, ASSIST_RETURNED_USD_FIELD } from '../usage/assist-credit-returns'\nimport { assistBandRefuses, publicAssistCredits, resolveAssistBudgetUsd } from '../usage/assist-credits'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport { aiJobsGate } from './ai-jobs-gate'\n\n/**\n * `GET /api/ai/create?orgId&hostId&kind` — the door one list's \"Create with\n * AI\" reads in the apps (AGL-3854), and `GET /api/ai/create/:jobId?orgId` —\n * the job it started, as the dialog's follow card reads it.\n *\n * The console draws each entry from its shell's gates and its own components\n * (`ai-describe-button`, `ai-brief-dialog`, `ai-job-follow`); the apps have\n * neither, so these answer the same verdicts and the same words as data\n * (`model/ai-create-view.ts`). Both only read. Starting, confirming and\n * canceling go through the jobs routes the console calls, whose ladder decides\n * every request exactly as it does for the console.\n */\n\nfunction bearerToken(request: Request): string | undefined {\n const authorization = request.headers.get('authorization') ?? ''\n return authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined\n}\n\n/** Every rung the console's shell climbs before it draws the entry, in the jobs gate's order. */\ninterface DoorCaller {\n decoded: DecodedIdToken\n staff: boolean\n orgId: string\n org: Partial<AglynOrganization>\n member: AglynOrgMember | null\n}\n\nasync function doorCaller(request: Request, orgId: string): Promise<Response | DoorCaller> {\n const idToken = bearerToken(request)\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n let decoded: DecodedIdToken\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n throw error\n }\n if (!decoded.email_verified && !isImpersonationSession(decoded)) return emailUnverifiedResponse()\n if (!orgId) return Response.json({ error: 'Open a workspace before using this feature' }, { status: 400 })\n const resolved = await getOrgForUser(decoded.uid, orgId)\n if (!resolved || resolved.orgId !== orgId) {\n return Response.json({ error: 'You are not a member of that organization' }, { status: 403 })\n }\n return {\n decoded,\n staff: decoded['staff'] === true,\n orgId,\n org: resolved.org ?? {},\n member: resolved.member ?? null,\n }\n}\n\n/**\n * Whether an add-on this workspace can buy grants `aiGenerative`: the\n * console's `entitlementPurchasable`, over the add-ons the AI plugin declares\n * on the server (`pluginSeatAddonSoldOn`).\n */\nexport function aiGenerativePurchasable(org: Partial<AglynOrganization>): boolean {\n const billing = org as Parameters<typeof checkEntitlement>[0]\n if (orgSubscriptionState(billing as never) !== 'live') return false\n const plan = resolveEffectivePlan(billing as never)\n return listPluginSeatAddons().some(\n (addon) => addon.features?.includes('aiGenerative') && pluginSeatAddonSoldOn(addon, plan),\n )\n}\n\n/** What is left of the month's credits, as the AI credits meter reads it. */\nasync function creditsFacts(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n org: Partial<AglynOrganization>,\n now: Date,\n): Promise<AiCreateCreditsFacts> {\n if (resolveEffectivePlan(org as never) === 'free') {\n const left = await readFreeAiCreditsLeft(firestore, { orgId, org: org as object, now })\n return left ? { kind: 'free', left } : { kind: 'none' }\n }\n const budgetUsd = resolveAssistBudgetUsd(org as never)\n if (budgetUsd === null) return isUncappedPlanComp(org as never) ? { kind: 'unlimited' } : { kind: 'none' }\n const usage = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('assistUsage')\n .doc(now.toISOString().slice(0, 7))\n .get()\n const credits = publicAssistCredits(\n assistSpendAfterReturnsUsd(usage.get('estCostUsd'), usage.get(ASSIST_RETURNED_USD_FIELD)),\n budgetUsd,\n )\n if (credits.limit === null || credits.remaining === null) return { kind: 'none' }\n return {\n kind: 'band',\n used: credits.used,\n limit: credits.limit,\n remaining: credits.remaining,\n stopsAtBand: assistBandRefuses(org as never),\n }\n}\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The door: whether a list draws Create with AI, as what, and every word its brief says. */\nexport async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const kind = url.searchParams.get('kind') ?? ''\n if (!isAiCreateKind(kind)) {\n return Response.json({ error: 'kind must be one of page, template, layout, form, component' }, { status: 400 })\n }\n const hostId = url.searchParams.get('hostId') ?? ''\n if (!ID_CHARS.test(hostId)) return Response.json({ error: 'hostId is not a site id' }, { status: 400 })\n const caller = await doorCaller(request, (url.searchParams.get('orgId') ?? '').trim())\n if (caller instanceof Response) return caller\n const { staff, orgId, org, member } = caller\n const firestore = firebaseAdmin.app().firestore()\n const now = new Date()\n const hidden = () =>\n Response.json(\n aiCreateDoorView({\n kind,\n shown: false,\n entitled: false,\n purchasable: false,\n canManageBilling: false,\n credits: { kind: 'none' },\n addonName: aiAddonName(),\n }),\n { headers: { 'Cache-Control': 'no-store' } },\n )\n\n // The shell's rungs, in the jobs gate's order: the reader's `ai.generate`\n // on this site, the release flag, then the site's own AI switch. Any of\n // them draws no entry at all; staff pass the first two, as they do there.\n if (!staff && !(await memberHasPermissionOnHost(orgId, hostId, member, 'ai.generate'))) return hidden()\n if (!staff && !(await isServerReleaseFlagOnForOrg('release_ai_generative', orgId))) return hidden()\n if (await aiJobSiteRefusal({ firestore, org, hostId })) return hidden()\n\n const entitled = checkEntitlement(org as never, 'aiGenerative')\n if (!entitled) {\n // Its own upsell where only the add-on is missing (AGL-3601): the add-on\n // store open to this workspace, and an add-on it can buy that grants it.\n const storeOpen = staff || (await isServerReleaseFlagOnForOrg('release_addon_store', orgId))\n const purchasable = !staff && storeOpen && aiGenerativePurchasable(org)\n const canManageBilling = purchasable && (await memberHasPermissionOnHost(orgId, null, member, 'billing.manage'))\n return Response.json(\n aiCreateDoorView({\n kind,\n shown: true,\n entitled: false,\n purchasable,\n canManageBilling,\n credits: { kind: 'none' },\n addonName: aiAddonName(),\n }),\n { headers: { 'Cache-Control': 'no-store' } },\n )\n }\n\n const [credits, collections, buildInFlight] = await Promise.all([\n creditsFacts(firestore, orgId, org, now).catch((error) => {\n console.error('[ai-create] credits read failed', orgId, error)\n return { kind: 'none' } as const\n }),\n kind === 'template'\n ? firestore\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .limit(COLLECTIONS_MAX_PER_HOST)\n .get()\n .then((snapshot) => ({\n status: 'success' as const,\n options: aiTemplateCollectionOptions(\n snapshot.docs.map((doc) => ({ ...(doc.data() as Record<string, unknown>), $id: doc.id })),\n ),\n }))\n .catch(() => ({ status: 'error' as const, options: [] }))\n : Promise.resolve(null),\n kind === 'page'\n ? listAiJobs(firestore, orgId, { statuses: AI_JOB_ACTIVE_STATUSES })\n .then((jobs) => aiSiteBuildInFlight(jobs.map((job) => aiJobSummary(job, now)), { hostId }) !== null)\n .catch(() => false)\n : Promise.resolve(false),\n ])\n return Response.json(\n aiCreateDoorView({\n kind: kind as AiCreateKind,\n shown: true,\n entitled: true,\n purchasable: false,\n canManageBilling: false,\n credits,\n collections,\n buildInFlight,\n addonName: aiAddonName(),\n }),\n { headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\n/** The follow view: one job of the workspace's, as the dialog that started it reads it. */\nexport async function GET_FOLLOW(request: Request, { params }: { params: Promise<{ jobId: string }> }): Promise<Response> {\n const { jobId } = await params\n if (!ID_CHARS.test(jobId ?? '')) return Response.json({ error: 'Not found' }, { status: 404 })\n const url = new URL(request.url)\n const gate = await aiJobsGate(request, url.searchParams.get('orgId') ?? '')\n if (gate instanceof Response) return gate\n const now = new Date()\n const job = await getAiJob(gate.firestore, gate.orgId, jobId)\n if (!job) return Response.json({ error: 'Not found' }, { status: 404 })\n const summary = aiJobSummary(job, now)\n // Confirming builds pages while another job is building on the site\n // (AGL-3765): asked only while this one waits on its plan.\n const askInFlight =\n summary.status === 'needs_review' &&\n summary.review?.reason === 'plan' &&\n AI_PAGE_BUILDING_JOB_KINDS.includes(summary.kind)\n const buildInFlight = askInFlight\n ? await listAiJobs(gate.firestore, gate.orgId, { statuses: AI_JOB_ACTIVE_STATUSES })\n .then(\n (jobs) =>\n aiSiteBuildInFlight(\n jobs.map((one) => aiJobSummary(one, now)),\n { hostId: summary.hostId, exceptJobId: summary.id },\n ) !== null,\n )\n .catch(() => false)\n : false\n return Response.json(\n {\n job: summary,\n view: aiJobFollowView(summary, {\n // Console addresses name the workspace by its slug, as every link the apps resolve does.\n orgSlug: typeof gate.org.slug === 'string' ? gate.org.slug : null,\n staff: gate.staff,\n buildInFlight,\n now: now.getTime(),\n }),\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\n"],"names":["checkEntitlement","COLLECTIONS_MAX_PER_HOST","aiAddonName","isUncappedPlanComp","orgSubscriptionState","resolveEffectivePlan","listPluginSeatAddons","pluginSeatAddonSoldOn","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","invalidIdTokenResponse","getOrgForUser","memberHasPermissionOnHost","isServerReleaseFlagOnForOrg","aiJobSiteRefusal","aiJobSummary","getAiJob","listAiJobs","aiCreateDoorView","aiJobFollowView","isAiCreateKind","AI_JOB_ACTIVE_STATUSES","AI_PAGE_BUILDING_JOB_KINDS","aiSiteBuildInFlight","aiTemplateCollectionOptions","assistSpendAfterReturnsUsd","ASSIST_RETURNED_USD_FIELD","assistBandRefuses","publicAssistCredits","resolveAssistBudgetUsd","readFreeAiCreditsLeft","aiJobsGate","bearerToken","request","authorization","headers","get","startsWith","slice","length","undefined","doorCaller","orgId","resolved","idToken","Response","json","error","status","decoded","app","auth","verifyIdToken","unauthenticated","email_verified","uid","staff","org","member","aiGenerativePurchasable","billing","plan","some","addon","features","includes","creditsFacts","firestore","now","left","kind","budgetUsd","usage","collection","doc","toISOString","credits","limit","remaining","used","stopsAtBand","ID_CHARS","GET","url","URL","searchParams","hostId","test","caller","trim","Date","hidden","shown","entitled","purchasable","canManageBilling","addonName","storeOpen","collections","buildInFlight","Promise","all","catch","console","then","snapshot","options","docs","map","data","$id","id","resolve","statuses","jobs","job","GET_FOLLOW","params","summary","jobId","gate","askInFlight","review","reason","one","exceptJobId","view","orgSlug","slug","getTime","dynamic"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,mEAAmE;AACnE,+EAA+E;AAC/E,0EAA0E;AAC1E,qEAAqE;;AAGrE,SAASA,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,gBAAgBmG,SAAS;YAC7B,yFAAyF;YACzFS,SAAS,OAAOP,KAAK/D,GAAG,CAACuE,IAAI,KAAK,WAAWR,KAAK/D,GAAG,CAACuE,IAAI,GAAG;YAC7DxE,OAAOgE,KAAKhE,KAAK;YACjB2C;YACA/B,KAAKA,IAAI6D,OAAO;QAClB;IACF,GACA;QAAEjF,QAAQ;QAAKb,SAAS;YAAE,iBAAiB;QAAW;IAAE;AAE5D;AAEA,OAAO,MAAM+F,UAAU,gBAAe"}
@@ -22,12 +22,15 @@ import { AI_JOB_INLINE_BUDGET_MS, aiJobNextStepMinimumMs, aiJobSummary, getAiJob
22
22
  import { aiBuildFreeCreditsRefusal, aiBuildFreeTaste } from "../jobs/ai-job-build-step.js";
23
23
  import { aiBuildCreditRange, aiBuildFirstPagePlan, aiBuildRetryLedger, aiBuildUnits, aiLedgerUnits } from "../model/ai-build-job.js";
24
24
  import { aiCreditsConfirmation } from "../model/ai-credit-estimate.js";
25
+ import { aiJobInputProblems } from "../model/ai-job-input.js";
25
26
  import { FREE_AI_TASTE_CREDITS_PER_MONTH } from "../plan-entitlements.js";
26
27
  import { aiGateLadder } from "../runtime/ai-gate.js";
27
28
  import { releaseAssistMessage } from "../usage/assist-usage.js";
28
29
  /**
29
30
  * Resume a job that stopped for a person (AGL-2935): confirm its plan, or
30
- * try again the step whose answer broke a building rule on its re-ask.
31
+ * try again the step whose answer broke a building rule on its re-ask — or
32
+ * answer what a job waiting in `needs_input` asks (`input`, AGL-3978), which
33
+ * returns it to its plan card, or a 400 with `fieldErrors` by field.
31
34
  *
32
35
  * A door that SPENDS — the next step calls the provider — so it climbs the
33
36
  * whole ladder the create door climbs: `aiGenerative`,
@@ -46,7 +49,7 @@ import { releaseAssistMessage } from "../usage/assist-usage.js";
46
49
  };
47
50
  export async function POST(request, context) {
48
51
  var _ref, _existing_hostId, _gate_decoded_email, _ref1, _gate_decoded_email1;
49
- var _existing_review;
52
+ var _existing_input_fields, _existing_input, _existing_review;
50
53
  let payload;
51
54
  try {
52
55
  payload = await request.json();
@@ -167,6 +170,25 @@ export async function POST(request, context) {
167
170
  return refused(refusal);
168
171
  }
169
172
  }
173
+ // A job waiting for a person's answer (AGL-3978): every field must read
174
+ // before anything changes, and a refusal names each field it is about.
175
+ const answering = existing.status === 'needs_input' && Boolean((_existing_input = existing.input) == null ? void 0 : (_existing_input_fields = _existing_input.fields) == null ? void 0 : _existing_input_fields.length);
176
+ const rawInput = payload == null ? void 0 : payload['input'];
177
+ const answers = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput) ? rawInput : null;
178
+ if (answering && existing.input) {
179
+ const fieldErrors = aiJobInputProblems(existing.input, answers);
180
+ const first = Object.values(fieldErrors)[0];
181
+ if (first) {
182
+ await release();
183
+ return Response.json({
184
+ error: first,
185
+ fieldErrors,
186
+ job: aiJobSummary(existing, new Date())
187
+ }, {
188
+ status: 400
189
+ });
190
+ }
191
+ }
170
192
  // A confirmed plan runs the step that writes, and an allowance free when the
171
193
  // job was created may be used by now (AGL-2909): the kind is asked again
172
194
  // before anything runs, and a refusal leaves the job waiting for review.
@@ -218,6 +240,8 @@ export async function POST(request, context) {
218
240
  creditsConfirmed: confirmation
219
241
  }, reduced ? {
220
242
  reducePlan: aiBuildFirstPagePlan
243
+ } : {}, answering ? {
244
+ input: answers
221
245
  } : {}));
222
246
  if (!changed) {
223
247
  await release();
@@ -236,7 +260,7 @@ export async function POST(request, context) {
236
260
  jobId,
237
261
  after: {
238
262
  status: job.status,
239
- reason: retryFailedItems ? 'retry-failed-items' : (_ref1 = (_existing_review = existing.review) == null ? void 0 : _existing_review.reason) != null ? _ref1 : null,
263
+ reason: retryFailedItems ? 'retry-failed-items' : answering ? 'input' : (_ref1 = (_existing_review = existing.review) == null ? void 0 : _existing_review.reason) != null ? _ref1 : null,
240
264
  kind: existing.kind
241
265
  }
242
266
  });