@happyvertical/smrt-planner 0.57.7 → 0.57.8

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 (478) hide show
  1. package/app/404.html +18 -18
  2. package/app/_app/immutable/chunks/{D3lXu_rt.js → B45qMR8U.js} +21 -21
  3. package/app/_app/immutable/chunks/{Bhd-3niN.js → BU0vd8nA.js} +1 -1
  4. package/app/_app/immutable/chunks/{JqlEoPqZ.js → BWd9iJf7.js} +1 -1
  5. package/app/_app/immutable/chunks/BeJxxDXZ.js +1 -0
  6. package/app/_app/immutable/chunks/{BeL8dJx9.js → BfeotTF9.js} +3 -3
  7. package/app/_app/immutable/chunks/{BdOPgmQ_.js → BlJ-05MM.js} +1 -1
  8. package/app/_app/immutable/chunks/{Vt9hDpHd.js → C6HSENij.js} +1 -1
  9. package/app/_app/immutable/chunks/{DmHVTNcC.js → C7boms_S.js} +1 -1
  10. package/app/_app/immutable/chunks/{C8FX0hli.js → C8kJ-wTn.js} +1 -1
  11. package/app/_app/immutable/chunks/CKd9O-eU.js +1 -0
  12. package/app/_app/immutable/chunks/{CYhwv6d2.js → COQVmnKJ.js} +1 -1
  13. package/app/_app/immutable/chunks/{DIgo5ngo.js → CTlovRev.js} +1 -1
  14. package/app/_app/immutable/chunks/{DmdvNG82.js → CaiMTXlW.js} +1 -1
  15. package/app/_app/immutable/chunks/{BqEBz5Vq.js → CiNYyHrL.js} +1 -1
  16. package/app/_app/immutable/chunks/{B2uXaQfZ.js → Cmh0yR4f.js} +1 -1
  17. package/app/_app/immutable/chunks/{BQLQsso4.js → Ct5r3XV1.js} +1 -1
  18. package/app/_app/immutable/chunks/{CdKHckEF.js → D0m3WNVh.js} +1 -1
  19. package/app/_app/immutable/chunks/{ICDFUCZL.js → DKi2uwTq.js} +1 -1
  20. package/app/_app/immutable/chunks/{D8MqcCKq.js → DWeCJh9N.js} +1 -1
  21. package/app/_app/immutable/chunks/{TcjpRcdI.js → D_xoWitl.js} +1 -1
  22. package/app/_app/immutable/chunks/Dg4KRWOz.js +1 -0
  23. package/app/_app/immutable/chunks/{Db12RzZi.js → DmvHEN1v.js} +1 -1
  24. package/app/_app/immutable/chunks/{DfN2k_EX.js → DoGeTgSe.js} +1 -1
  25. package/app/_app/immutable/chunks/{C6AANt9H.js → DqrQeG8L.js} +1 -1
  26. package/app/_app/immutable/chunks/{C2OYATC6.js → DziaAoFY.js} +1 -1
  27. package/app/_app/immutable/chunks/{FeyhlLIZ.js → QJX7BlhI.js} +1 -1
  28. package/app/_app/immutable/chunks/{Cwz7QFS4.js → Ywu-998J.js} +2 -2
  29. package/app/_app/immutable/chunks/{lUJaueNM.js → nB-x9BEp.js} +1 -1
  30. package/app/_app/immutable/chunks/{DwIRC3h5.js → ptmcJq5j.js} +1 -1
  31. package/app/_app/immutable/entry/{app.C5bxPKCP.js → app.g4Bu04a3.js} +2 -2
  32. package/app/_app/immutable/entry/start.C4bzxGdW.js +1 -0
  33. package/app/_app/immutable/nodes/{0.DFJFBCCB.js → 0.C6N6B83E.js} +1 -1
  34. package/app/_app/immutable/nodes/{1.D_79m87b.js → 1.9pTjyJp5.js} +1 -1
  35. package/app/_app/immutable/nodes/{10.20u2-jxn.js → 10.BkbBDSaP.js} +1 -1
  36. package/app/_app/immutable/nodes/{11.CvMq32jC.js → 11.BcVi4XqZ.js} +1 -1
  37. package/app/_app/immutable/nodes/{12.Cd0cy1AC.js → 12.j9PkVob2.js} +1 -1
  38. package/app/_app/immutable/nodes/{13.DYYS3YVQ.js → 13.BOUYEx8n.js} +1 -1
  39. package/app/_app/immutable/nodes/{14.BEf5BJDn.js → 14.CuMuuCU7.js} +1 -1
  40. package/app/_app/immutable/nodes/{2.C_kLkHNl.js → 2.BHCkcrHF.js} +3 -3
  41. package/app/_app/immutable/nodes/{3.CZw3hv8O.js → 3.D6l9gEJu.js} +1 -1
  42. package/app/_app/immutable/nodes/{4.WMU9NDex.js → 4.BUHWJvB3.js} +1 -1
  43. package/app/_app/immutable/nodes/{5.CuqxSfl4.js → 5.C1jfy8Yg.js} +1 -1
  44. package/app/_app/immutable/nodes/{6.BXLQB7tR.js → 6.LSyNtBLJ.js} +1 -1
  45. package/app/_app/immutable/nodes/{7.BZvxNeL2.js → 7.CC7rRIn7.js} +1 -1
  46. package/app/_app/immutable/nodes/{8.Bj2O4pyx.js → 8.S9H6LDRX.js} +1 -1
  47. package/app/_app/immutable/nodes/{9.yeFzeUHj.js → 9.BPt57fDH.js} +1 -1
  48. package/app/_app/version.json +1 -1
  49. package/app/advanced-styles/index.html +21 -21
  50. package/app/ai/index.html +24 -24
  51. package/app/blueprint/index.html +19 -19
  52. package/app/cookbook/index.html +19 -19
  53. package/app/index.html +27 -27
  54. package/app/m/ads/AdDeliveryTier/index.html +23 -23
  55. package/app/m/ads/AdEvent/index.html +23 -23
  56. package/app/m/ads/AdFormat/index.html +23 -23
  57. package/app/m/ads/AdGroup/index.html +23 -23
  58. package/app/m/ads/AdVariation/index.html +23 -23
  59. package/app/m/analytics/AnalyticsDataStream/index.html +23 -23
  60. package/app/m/analytics/AnalyticsEvent/index.html +23 -23
  61. package/app/m/analytics/AnalyticsProperty/index.html +23 -23
  62. package/app/m/analytics/AnalyticsReport/index.html +23 -23
  63. package/app/m/approvals/ApprovalEvent/index.html +23 -23
  64. package/app/m/approvals/ApprovalPolicy/index.html +23 -23
  65. package/app/m/approvals/ApprovalRequest/index.html +23 -23
  66. package/app/m/assets/Asset/attachments/index.html +24 -24
  67. package/app/m/assets/Asset/index.html +23 -23
  68. package/app/m/assets/AssetAssociation/index.html +23 -23
  69. package/app/m/assets/AssetMetafield/index.html +23 -23
  70. package/app/m/assets/AssetStatus/index.html +23 -23
  71. package/app/m/assets/AssetType/index.html +23 -23
  72. package/app/m/assets/Folder/index.html +23 -23
  73. package/app/m/chat/AgentSession/index.html +23 -23
  74. package/app/m/chat/ChatMessage/index.html +23 -23
  75. package/app/m/chat/ChatParticipant/index.html +23 -23
  76. package/app/m/chat/ChatReaction/index.html +23 -23
  77. package/app/m/chat/ChatRoom/index.html +23 -23
  78. package/app/m/chat/ChatThread/index.html +23 -23
  79. package/app/m/chat/VoiceGatewayTurn/index.html +23 -23
  80. package/app/m/chat/VoiceSession/index.html +23 -23
  81. package/app/m/commerce/Agreement/index.html +23 -23
  82. package/app/m/commerce/Cart/index.html +23 -23
  83. package/app/m/commerce/Contract/index.html +23 -23
  84. package/app/m/commerce/ContractLineItem/index.html +23 -23
  85. package/app/m/commerce/Customer/index.html +23 -23
  86. package/app/m/commerce/DocumentTax/index.html +23 -23
  87. package/app/m/commerce/Estimate/index.html +23 -23
  88. package/app/m/commerce/Fulfillment/index.html +23 -23
  89. package/app/m/commerce/FulfillmentLineItem/index.html +23 -23
  90. package/app/m/commerce/HistoricalCustomerFunds/index.html +23 -23
  91. package/app/m/commerce/HistoricalCustomerFundsAllocation/index.html +23 -23
  92. package/app/m/commerce/HistoricalSalesLine/index.html +23 -23
  93. package/app/m/commerce/Invoice/index.html +23 -23
  94. package/app/m/commerce/InvoiceLineItem/index.html +23 -23
  95. package/app/m/commerce/Lease/index.html +23 -23
  96. package/app/m/commerce/LicenseSale/index.html +23 -23
  97. package/app/m/commerce/Order/index.html +23 -23
  98. package/app/m/commerce/Payment/index.html +23 -23
  99. package/app/m/commerce/PaymentAllocation/index.html +23 -23
  100. package/app/m/commerce/PaymentInstrument/index.html +23 -23
  101. package/app/m/commerce/PaymentIntent/index.html +23 -23
  102. package/app/m/commerce/Payout/index.html +23 -23
  103. package/app/m/commerce/ProductionOrder/index.html +23 -23
  104. package/app/m/commerce/PurchaseContract/index.html +23 -23
  105. package/app/m/commerce/PurchaseOrder/index.html +23 -23
  106. package/app/m/commerce/SalesContract/index.html +23 -23
  107. package/app/m/commerce/SupplierQuote/index.html +23 -23
  108. package/app/m/commerce/TaxCode/index.html +23 -23
  109. package/app/m/commerce/TaxComponent/index.html +23 -23
  110. package/app/m/commerce/TaxSettings/index.html +23 -23
  111. package/app/m/commerce/TaxSummaryReport/index.html +23 -23
  112. package/app/m/commerce/Vendor/index.html +23 -23
  113. package/app/m/commerce/WholesaleOrder/index.html +23 -23
  114. package/app/m/content/Content/index.html +23 -23
  115. package/app/m/content/ContentContribution/index.html +23 -23
  116. package/app/m/content/ContentContributionAttachment/index.html +23 -23
  117. package/app/m/content/ContentContributionRevision/index.html +23 -23
  118. package/app/m/content/ContentContributionType/index.html +23 -23
  119. package/app/m/content/ContentContributor/index.html +23 -23
  120. package/app/m/content/ContentCorrection/index.html +23 -23
  121. package/app/m/content/ContentFeedSource/index.html +23 -23
  122. package/app/m/content/ContentGovernanceAssignment/index.html +23 -23
  123. package/app/m/content/ContentGovernancePolicy/index.html +23 -23
  124. package/app/m/content/ContentGovernanceProfile/index.html +23 -23
  125. package/app/m/content/ContentReference/index.html +23 -23
  126. package/app/m/content/ContentReview/index.html +23 -23
  127. package/app/m/content/ContentVersion/index.html +23 -23
  128. package/app/m/events/Event/index.html +23 -23
  129. package/app/m/events/EventParticipant/index.html +23 -23
  130. package/app/m/events/EventSeries/index.html +23 -23
  131. package/app/m/events/EventType/index.html +23 -23
  132. package/app/m/expenses/Expense/index.html +23 -23
  133. package/app/m/facts/Fact/index.html +23 -23
  134. package/app/m/facts/FactContent/index.html +23 -23
  135. package/app/m/facts/FactEvidence/index.html +23 -23
  136. package/app/m/facts/FactSource/index.html +23 -23
  137. package/app/m/facts/FactSubject/index.html +23 -23
  138. package/app/m/facts/FactTag/index.html +23 -23
  139. package/app/m/fields/FieldPolicy/index.html +23 -23
  140. package/app/m/fields/FieldPolicySuggestion/index.html +23 -23
  141. package/app/m/fields/FieldUsageCounter/index.html +23 -23
  142. package/app/m/images/Image/index.html +23 -23
  143. package/app/m/inventory/InventoryLocation/index.html +23 -23
  144. package/app/m/inventory/StockLevel/index.html +23 -23
  145. package/app/m/inventory/StockMovement/index.html +23 -23
  146. package/app/m/ledgers/Account/index.html +23 -23
  147. package/app/m/ledgers/Journal/index.html +23 -23
  148. package/app/m/ledgers/JournalEntry/index.html +23 -23
  149. package/app/m/ledgers/Ledger/index.html +23 -23
  150. package/app/m/manufacturing/Assembly/index.html +23 -23
  151. package/app/m/manufacturing/BillOfMaterials/index.html +23 -23
  152. package/app/m/manufacturing/BomLine/index.html +23 -23
  153. package/app/m/manufacturing/Operation/index.html +23 -23
  154. package/app/m/manufacturing/ProductionRun/index.html +23 -23
  155. package/app/m/manufacturing/ProductionRunCompletion/index.html +23 -23
  156. package/app/m/manufacturing/RoutingStep/index.html +23 -23
  157. package/app/m/marketing/Campaign/index.html +23 -23
  158. package/app/m/marketing/CampaignChannel/index.html +23 -23
  159. package/app/m/marketing/CampaignMetricSnapshot/index.html +23 -23
  160. package/app/m/messages/Account/index.html +23 -23
  161. package/app/m/messages/Attachment/index.html +23 -23
  162. package/app/m/messages/Blacklist/index.html +23 -23
  163. package/app/m/messages/Email/failed-sends/index.html +24 -24
  164. package/app/m/messages/Email/index.html +23 -23
  165. package/app/m/messages/Email/mailbox/index.html +24 -24
  166. package/app/m/messages/EmailAccount/index.html +23 -23
  167. package/app/m/messages/EmailAttachment/index.html +23 -23
  168. package/app/m/messages/EmailFolder/index.html +23 -23
  169. package/app/m/messages/Message/index.html +23 -23
  170. package/app/m/messages/MessagingEndpoint/index.html +23 -23
  171. package/app/m/messages/PersonaMessageRoute/index.html +23 -23
  172. package/app/m/messages/SlackAccount/index.html +23 -23
  173. package/app/m/messages/SlackMessage/index.html +23 -23
  174. package/app/m/messages/TelegramAccount/index.html +23 -23
  175. package/app/m/messages/Tweet/index.html +23 -23
  176. package/app/m/messages/TwitterAccount/index.html +23 -23
  177. package/app/m/messages/Whitelist/index.html +23 -23
  178. package/app/m/messages/ZulipAccount/index.html +23 -23
  179. package/app/m/places/Place/index.html +23 -23
  180. package/app/m/places/PlaceType/index.html +23 -23
  181. package/app/m/products/Category/index.html +23 -23
  182. package/app/m/products/Material/index.html +23 -23
  183. package/app/m/products/Product/index.html +23 -23
  184. package/app/m/products/Product/ingredients/index.html +24 -24
  185. package/app/m/products/ProductVariant/index.html +23 -23
  186. package/app/m/products/Sku/index.html +23 -23
  187. package/app/m/profiles/ApiKey/index.html +23 -23
  188. package/app/m/profiles/Bot/index.html +23 -23
  189. package/app/m/profiles/MagicLinkToken/index.html +23 -23
  190. package/app/m/profiles/NostrIdentity/index.html +23 -23
  191. package/app/m/profiles/OidcIdentity/index.html +23 -23
  192. package/app/m/profiles/Organization/index.html +23 -23
  193. package/app/m/profiles/Person/index.html +23 -23
  194. package/app/m/profiles/Profile/index.html +23 -23
  195. package/app/m/profiles/ProfileMetadata/index.html +23 -23
  196. package/app/m/profiles/ProfileMetafield/index.html +23 -23
  197. package/app/m/profiles/ProfileRelationship/index.html +23 -23
  198. package/app/m/profiles/ProfileRelationshipTerm/index.html +23 -23
  199. package/app/m/profiles/ProfileRelationshipType/index.html +23 -23
  200. package/app/m/profiles/ProfileType/index.html +23 -23
  201. package/app/m/projects/Comment/index.html +23 -23
  202. package/app/m/projects/Issue/index.html +23 -23
  203. package/app/m/projects/Label/index.html +23 -23
  204. package/app/m/projects/Project/index.html +23 -23
  205. package/app/m/projects/ProjectIntegration/index.html +23 -23
  206. package/app/m/projects/PullRequest/index.html +23 -23
  207. package/app/m/projects/Repository/index.html +23 -23
  208. package/app/m/properties/Property/index.html +23 -23
  209. package/app/m/properties/Zone/index.html +23 -23
  210. package/app/m/reports/RuntimeReport/index.html +23 -23
  211. package/app/m/reports/SmrtPrincipalReportRefreshTask/index.html +23 -23
  212. package/app/m/reports/SmrtReportLock/index.html +23 -23
  213. package/app/m/reports/SmrtReportRefreshTask/index.html +23 -23
  214. package/app/m/reports/SmrtReportRun/index.html +23 -23
  215. package/app/m/reports/SmrtReportSchedule/index.html +23 -23
  216. package/app/m/reports/SmrtReportWatermark/index.html +23 -23
  217. package/app/m/sales/Agreement/index.html +23 -23
  218. package/app/m/sales/AttributionException/index.html +23 -23
  219. package/app/m/sales/AttributionPolicy/index.html +23 -23
  220. package/app/m/sales/Commission/index.html +23 -23
  221. package/app/m/sales/CommissionAdjustment/index.html +23 -23
  222. package/app/m/sales/CommissionPayout/index.html +23 -23
  223. package/app/m/sales/CommissionPlan/index.html +23 -23
  224. package/app/m/sales/Earner/index.html +23 -23
  225. package/app/m/sales/EarnerSourceAttribution/index.html +23 -23
  226. package/app/m/sales/EarningEvent/index.html +23 -23
  227. package/app/m/sales/ExecutedAgreement/index.html +23 -23
  228. package/app/m/sales/Lead/index.html +23 -23
  229. package/app/m/sales/Opportunity/index.html +23 -23
  230. package/app/m/sales/OpportunityConversion/index.html +23 -23
  231. package/app/m/sales/PipelineDefinition/index.html +23 -23
  232. package/app/m/sales/PipelineStage/index.html +23 -23
  233. package/app/m/sales/Referral/index.html +23 -23
  234. package/app/m/sales/ReferralAgreement/index.html +23 -23
  235. package/app/m/sales/ReferralLink/index.html +23 -23
  236. package/app/m/sales/ReferralProgram/index.html +23 -23
  237. package/app/m/sales/ReferralTermSnapshot/index.html +23 -23
  238. package/app/m/sales/ReferralTouch/index.html +23 -23
  239. package/app/m/sales/Referrer/index.html +23 -23
  240. package/app/m/sales/SalesActivity/index.html +23 -23
  241. package/app/m/sales/SalesRepresentative/index.html +23 -23
  242. package/app/m/sites/Site/index.html +23 -23
  243. package/app/m/sites/SiteAgentBinding/index.html +23 -23
  244. package/app/m/social/OAuthState/index.html +23 -23
  245. package/app/m/social/SocialAccount/index.html +23 -23
  246. package/app/m/social/SocialPost/index.html +23 -23
  247. package/app/m/social/SocialPostAnalyticsSnapshot/index.html +23 -23
  248. package/app/m/subscriptions/BillingAdjustment/index.html +23 -23
  249. package/app/m/subscriptions/ClientCharge/index.html +23 -23
  250. package/app/m/subscriptions/CreditGrant/index.html +23 -23
  251. package/app/m/subscriptions/PricingRule/index.html +23 -23
  252. package/app/m/subscriptions/RetailCharge/index.html +23 -23
  253. package/app/m/subscriptions/SpendingPolicy/index.html +23 -23
  254. package/app/m/subscriptions/SubscriptionPlan/index.html +23 -23
  255. package/app/m/subscriptions/TenantSubscription/index.html +23 -23
  256. package/app/m/subscriptions/TenantUsageMetric/index.html +23 -23
  257. package/app/m/support/ServiceTimeEntry/index.html +23 -23
  258. package/app/m/support/SupportAiRun/index.html +23 -23
  259. package/app/m/support/SupportAvailability/index.html +23 -23
  260. package/app/m/support/SupportCase/index.html +23 -23
  261. package/app/m/support/SupportCaseEvent/index.html +23 -23
  262. package/app/m/support/SupportChannelBinding/index.html +23 -23
  263. package/app/m/support/SupportCharge/index.html +23 -23
  264. package/app/m/support/SupportCompensation/index.html +23 -23
  265. package/app/m/support/SupportCompensationPlan/index.html +23 -23
  266. package/app/m/support/SupportEscalation/index.html +23 -23
  267. package/app/m/support/SupportInteraction/index.html +23 -23
  268. package/app/m/support/SupportPlan/index.html +23 -23
  269. package/app/m/support/SupportPolicy/index.html +23 -23
  270. package/app/m/support/SupportQualification/index.html +23 -23
  271. package/app/m/support/SupportServiceTarget/index.html +23 -23
  272. package/app/m/support/SupportSpecialist/index.html +23 -23
  273. package/app/m/support/SupportWorkLink/index.html +23 -23
  274. package/app/m/tags/Tag/index.html +23 -23
  275. package/app/m/tags/TagAlias/index.html +23 -23
  276. package/app/m/timesheets/AttendanceBreak/index.html +23 -23
  277. package/app/m/timesheets/AttendancePunch/index.html +23 -23
  278. package/app/m/timesheets/AttendanceSegment/index.html +23 -23
  279. package/app/m/timesheets/ServiceChargeSnapshot/index.html +23 -23
  280. package/app/m/timesheets/ServiceCompensationSnapshot/index.html +23 -23
  281. package/app/m/timesheets/ServiceTimeEntry/index.html +23 -23
  282. package/app/m/users/Group/index.html +23 -23
  283. package/app/m/users/GroupMember/index.html +23 -23
  284. package/app/m/users/GroupRole/index.html +23 -23
  285. package/app/m/users/Membership/index.html +23 -23
  286. package/app/m/users/MembershipOverride/index.html +23 -23
  287. package/app/m/users/Permission/index.html +23 -23
  288. package/app/m/users/Role/index.html +23 -23
  289. package/app/m/users/RolePermission/index.html +23 -23
  290. package/app/m/users/Session/index.html +23 -23
  291. package/app/m/users/Tenant/index.html +23 -23
  292. package/app/m/users/TenantIntegration/index.html +23 -23
  293. package/app/m/users/TenantPermissionOverride/index.html +23 -23
  294. package/app/m/users/User/index.html +23 -23
  295. package/app/m/video/Character/index.html +23 -23
  296. package/app/m/video/CharacterAsset/index.html +23 -23
  297. package/app/m/video/CompositeJob/index.html +23 -23
  298. package/app/m/video/Performer/index.html +23 -23
  299. package/app/m/video/PerformerAsset/index.html +23 -23
  300. package/app/m/video/Scene/index.html +23 -23
  301. package/app/m/video/SceneAsset/index.html +23 -23
  302. package/app/m/video/VideoComposition/index.html +23 -23
  303. package/app/m/video/VideoCompositionAsset/index.html +23 -23
  304. package/app/m/video/VideoSequence/index.html +23 -23
  305. package/app/m/video/VideoSequenceAsset/index.html +23 -23
  306. package/app/m/video/VideoShot/index.html +23 -23
  307. package/app/m/video/VideoShotAsset/index.html +23 -23
  308. package/app/m/video/VideoShotCharacter/index.html +23 -23
  309. package/app/m/video/VideoWorkflow/index.html +23 -23
  310. package/app/m/voice/VoiceOutput/index.html +23 -23
  311. package/app/m/voice/VoiceProfile/index.html +23 -23
  312. package/app/m/voice/VoiceSample/index.html +23 -23
  313. package/app/mcp.html +2 -2
  314. package/app/packages/ads/index.html +21 -21
  315. package/app/packages/analytics/index.html +21 -21
  316. package/app/packages/approvals/index.html +21 -21
  317. package/app/packages/assets/index.html +21 -21
  318. package/app/packages/chat/index.html +21 -21
  319. package/app/packages/comments/index.html +21 -21
  320. package/app/packages/commerce/index.html +21 -21
  321. package/app/packages/content/index.html +21 -21
  322. package/app/packages/events/index.html +21 -21
  323. package/app/packages/expenses/index.html +21 -21
  324. package/app/packages/facts/index.html +21 -21
  325. package/app/packages/fields/index.html +21 -21
  326. package/app/packages/human-resources/index.html +21 -21
  327. package/app/packages/images/index.html +21 -21
  328. package/app/packages/index.html +20 -20
  329. package/app/packages/ingestion/index.html +21 -21
  330. package/app/packages/inventory/index.html +21 -21
  331. package/app/packages/ledgers/index.html +21 -21
  332. package/app/packages/manufacturing/index.html +21 -21
  333. package/app/packages/marketing/index.html +21 -21
  334. package/app/packages/messages/index.html +21 -21
  335. package/app/packages/places/index.html +21 -21
  336. package/app/packages/preferences/index.html +21 -21
  337. package/app/packages/products/index.html +21 -21
  338. package/app/packages/profiles/index.html +21 -21
  339. package/app/packages/projects/index.html +21 -21
  340. package/app/packages/properties/index.html +21 -21
  341. package/app/packages/reports/index.html +21 -21
  342. package/app/packages/sales/index.html +21 -21
  343. package/app/packages/sites/index.html +21 -21
  344. package/app/packages/social/index.html +21 -21
  345. package/app/packages/subscriptions/index.html +21 -21
  346. package/app/packages/support/index.html +21 -21
  347. package/app/packages/tags/index.html +21 -21
  348. package/app/packages/timesheets/index.html +21 -21
  349. package/app/packages/users/index.html +21 -21
  350. package/app/packages/video/index.html +21 -21
  351. package/app/packages/voice/index.html +21 -21
  352. package/app/packages/webhooks/index.html +21 -21
  353. package/app/recipes/account-access/help/index.html +22 -22
  354. package/app/recipes/account-access/index.html +23 -23
  355. package/app/recipes/activity/help/index.html +21 -21
  356. package/app/recipes/activity/index.html +23 -23
  357. package/app/recipes/agreements/help/index.html +21 -21
  358. package/app/recipes/agreements/index.html +23 -23
  359. package/app/recipes/analytics.reports/help/index.html +21 -21
  360. package/app/recipes/analytics.reports/index.html +23 -23
  361. package/app/recipes/assets/help/index.html +21 -21
  362. package/app/recipes/assets/index.html +23 -23
  363. package/app/recipes/billing/help/index.html +21 -21
  364. package/app/recipes/billing/index.html +23 -23
  365. package/app/recipes/chat.assistant/help/index.html +21 -21
  366. package/app/recipes/chat.assistant/index.html +23 -23
  367. package/app/recipes/comments/help/index.html +21 -21
  368. package/app/recipes/comments/index.html +23 -23
  369. package/app/recipes/commerce.customers/help/index.html +21 -21
  370. package/app/recipes/commerce.customers/index.html +23 -23
  371. package/app/recipes/commerce.estimates/help/index.html +21 -21
  372. package/app/recipes/commerce.estimates/index.html +23 -23
  373. package/app/recipes/commerce.purchases/help/index.html +21 -21
  374. package/app/recipes/commerce.purchases/index.html +23 -23
  375. package/app/recipes/commerce.sales/help/index.html +21 -21
  376. package/app/recipes/commerce.sales/index.html +23 -23
  377. package/app/recipes/commerce.vendors/help/index.html +21 -21
  378. package/app/recipes/commerce.vendors/index.html +23 -23
  379. package/app/recipes/commerce.wholesale/help/index.html +21 -21
  380. package/app/recipes/commerce.wholesale/index.html +23 -23
  381. package/app/recipes/events.calendar/help/index.html +21 -21
  382. package/app/recipes/events.calendar/index.html +23 -23
  383. package/app/recipes/expenses.tracking/help/index.html +21 -21
  384. package/app/recipes/expenses.tracking/index.html +23 -23
  385. package/app/recipes/fields.form-customization/help/index.html +21 -21
  386. package/app/recipes/fields.form-customization/index.html +23 -23
  387. package/app/recipes/ingestion/help/index.html +21 -21
  388. package/app/recipes/ingestion/index.html +23 -23
  389. package/app/recipes/integrations/help/index.html +21 -21
  390. package/app/recipes/integrations/index.html +23 -23
  391. package/app/recipes/inventory.stock/help/index.html +21 -21
  392. package/app/recipes/inventory.stock/index.html +23 -23
  393. package/app/recipes/ledgers.bookkeeping/help/index.html +21 -21
  394. package/app/recipes/ledgers.bookkeeping/index.html +23 -23
  395. package/app/recipes/messages/help/index.html +21 -21
  396. package/app/recipes/messages/index.html +23 -23
  397. package/app/recipes/products/help/index.html +21 -21
  398. package/app/recipes/products/index.html +23 -23
  399. package/app/recipes/projects.tracker/help/index.html +21 -21
  400. package/app/recipes/projects.tracker/index.html +23 -23
  401. package/app/recipes/reports.materialized/help/index.html +21 -21
  402. package/app/recipes/reports.materialized/index.html +23 -23
  403. package/app/recipes/reports.runtime/help/index.html +21 -21
  404. package/app/recipes/reports.runtime/index.html +23 -23
  405. package/app/recipes/sales.pipeline/help/index.html +21 -21
  406. package/app/recipes/sales.pipeline/index.html +23 -23
  407. package/app/recipes/tags.taxonomy/help/index.html +21 -21
  408. package/app/recipes/tags.taxonomy/index.html +23 -23
  409. package/app/recipes/team-collaboration/help/index.html +21 -21
  410. package/app/recipes/team-collaboration/index.html +23 -23
  411. package/app/recipes/timesheets.time-entries/help/index.html +21 -21
  412. package/app/recipes/timesheets.time-entries/index.html +23 -23
  413. package/app/s/custom-accounts/index.html +19 -19
  414. package/app/s/custom-appointments/index.html +19 -19
  415. package/app/s/custom-billing/index.html +19 -19
  416. package/app/s/custom-bookings/index.html +19 -19
  417. package/app/s/custom-buying/index.html +19 -19
  418. package/app/s/custom-checkout/index.html +19 -19
  419. package/app/s/custom-classes/index.html +19 -19
  420. package/app/s/custom-clients/index.html +19 -19
  421. package/app/s/custom-events/index.html +19 -19
  422. package/app/s/custom-fleet/index.html +19 -19
  423. package/app/s/custom-gigs/index.html +19 -19
  424. package/app/s/custom-giving/index.html +19 -19
  425. package/app/s/custom-instruments/index.html +19 -19
  426. package/app/s/custom-jobs/index.html +19 -19
  427. package/app/s/custom-kitchen/index.html +19 -19
  428. package/app/s/custom-lessons/index.html +19 -19
  429. package/app/s/custom-material/index.html +19 -19
  430. package/app/s/custom-meetings/index.html +19 -19
  431. package/app/s/custom-members/index.html +19 -19
  432. package/app/s/custom-merch/index.html +19 -19
  433. package/app/s/custom-money/index.html +19 -19
  434. package/app/s/custom-paint/index.html +19 -19
  435. package/app/s/custom-parts/index.html +19 -19
  436. package/app/s/custom-rentals/index.html +19 -19
  437. package/app/s/custom-roastery/index.html +19 -19
  438. package/app/s/custom-schedule/index.html +19 -19
  439. package/app/s/custom-shelf/index.html +19 -19
  440. package/app/s/custom-shop/index.html +19 -19
  441. package/app/s/custom-students/index.html +19 -19
  442. package/app/s/custom-wholesale/index.html +19 -19
  443. package/app/s/custom-work/index.html +19 -19
  444. package/app/s/custom-yard/index.html +19 -19
  445. package/app/s/section-access-control/index.html +19 -19
  446. package/app/s/section-account-security/index.html +19 -19
  447. package/app/s/section-accounting/index.html +19 -19
  448. package/app/s/section-activity/index.html +19 -19
  449. package/app/s/section-agreements/index.html +19 -19
  450. package/app/s/section-analytics/index.html +19 -19
  451. package/app/s/section-assets/index.html +19 -19
  452. package/app/s/section-billing/index.html +19 -19
  453. package/app/s/section-calendar/index.html +19 -19
  454. package/app/s/section-catalog/index.html +19 -19
  455. package/app/s/section-chat.assistant/index.html +19 -19
  456. package/app/s/section-comments/index.html +19 -19
  457. package/app/s/section-fields.form-customization/index.html +19 -19
  458. package/app/s/section-ingestion/index.html +19 -19
  459. package/app/s/section-integrations/index.html +19 -19
  460. package/app/s/section-messages/index.html +19 -19
  461. package/app/s/section-more/index.html +19 -19
  462. package/app/s/section-operations/index.html +19 -19
  463. package/app/s/section-projects/index.html +19 -19
  464. package/app/s/section-purchasing/index.html +19 -19
  465. package/app/s/section-reports.materialized/index.html +19 -19
  466. package/app/s/section-reports.runtime/index.html +19 -19
  467. package/app/s/section-sales/index.html +19 -19
  468. package/app/s/section-taxonomy/index.html +19 -19
  469. package/app/s/section-team/index.html +19 -19
  470. package/app/s/section-work/index.html +19 -19
  471. package/dist/catalog/catalog.json +50 -38
  472. package/dist/smrt-version.d.ts +1 -1
  473. package/dist/smrt-version.js +1 -1
  474. package/package.json +54 -54
  475. package/app/_app/immutable/chunks/DGaFQflg.js +0 -1
  476. package/app/_app/immutable/chunks/IDZmjRDr.js +0 -1
  477. package/app/_app/immutable/chunks/ezs6CGyc.js +0 -1
  478. package/app/_app/immutable/entry/start.CZvO61qD.js +0 -1
@@ -1 +1 @@
1
- import{O as e,u as t}from"./D3lXu_rt.js";import{v as n}from"./lUJaueNM.js";import{c as r}from"./CdKHckEF.js";var i=`@happyvertical/smrt-reports:RuntimeReport`;function a(e){switch(e.type){case`text`:return`string`;case`integer`:return`integer`;case`decimal`:return`decimal`;case`boolean`:return`boolean`;case`datetime`:return`datetime`;case`foreignKey`:case`crossPackageRef`:return`id`;default:return null}}function o(e){let t=e.replace(/([a-z\d])([A-Z])/g,`$1_$2`).toLowerCase();return/(series|species)$/.test(t)?t:/[^aeiou]y$/.test(t)?`${t.slice(0,-1)}ies`:/(s|x|z|ch|sh)$/.test(t)?`${t}es`:`${t}s`}var s=[`totalAmount`,`total`,`amount`];function c(n,i,c=o(n.name)){let l=[{name:`id`,type:`string`}];for(let r of n.fields){let n=a(r);if(!n||r.system||l.some(e=>e.name===r.name))continue;let i=e(r)?`money`:n===`datetime`&&r.ui?.format===`date`?`date`:void 0;l.push({name:r.name,type:n,label:t(r),...i?{format:i}:{},...n===`string`&&r.enum?.length?{enum:r.enum}:{}})}let u=l.filter(e=>e.format===`money`),d=s.map(e=>u.find(t=>t.name===e)).find(Boolean),f={id:c,label:i,...n.description?{description:n.description}:{},schema:l,model:n,...d?{amountField:d.name}:{}},p=r([f],c).defaultTimeField;return p?{...f,dateField:p}:f}function l(e,t){let r=new Set(e),i=new Map;for(let e of t)if(r.has(e.id))for(let t of n(e))t.model.id!==`@happyvertical/smrt-reports:RuntimeReport`&&i.set(t.model.id,[...i.get(t.model.id)??[],t]);let a=new Map,s=new Set;for(let[e,t]of i){let n=t.find(e=>!e.filter)??t[0],r=o(n.model.name);s.has(r)&&(r=`${n.packageId}.${r}`),s.add(r),a.set(e,c(n.model,n.label,r))}return[...a.values()]}export{l as n,i as t};
1
+ import{O as e,u as t}from"./B45qMR8U.js";import{v as n}from"./nB-x9BEp.js";import{c as r}from"./D0m3WNVh.js";var i=`@happyvertical/smrt-reports:RuntimeReport`;function a(e){switch(e.type){case`text`:return`string`;case`integer`:return`integer`;case`decimal`:return`decimal`;case`boolean`:return`boolean`;case`datetime`:return`datetime`;case`foreignKey`:case`crossPackageRef`:return`id`;default:return null}}function o(e){let t=e.replace(/([a-z\d])([A-Z])/g,`$1_$2`).toLowerCase();return/(series|species)$/.test(t)?t:/[^aeiou]y$/.test(t)?`${t.slice(0,-1)}ies`:/(s|x|z|ch|sh)$/.test(t)?`${t}es`:`${t}s`}var s=[`totalAmount`,`total`,`amount`];function c(n,i,c=o(n.name)){let l=[{name:`id`,type:`string`}];for(let r of n.fields){let n=a(r);if(!n||r.system||l.some(e=>e.name===r.name))continue;let i=e(r)?`money`:n===`datetime`&&r.ui?.format===`date`?`date`:void 0;l.push({name:r.name,type:n,label:t(r),...i?{format:i}:{},...n===`string`&&r.enum?.length?{enum:r.enum}:{}})}let u=l.filter(e=>e.format===`money`),d=s.map(e=>u.find(t=>t.name===e)).find(Boolean),f={id:c,label:i,...n.description?{description:n.description}:{},schema:l,model:n,...d?{amountField:d.name}:{}},p=r([f],c).defaultTimeField;return p?{...f,dateField:p}:f}function l(e,t){let r=new Set(e),i=new Map;for(let e of t)if(r.has(e.id))for(let t of n(e))t.model.id!==`@happyvertical/smrt-reports:RuntimeReport`&&i.set(t.model.id,[...i.get(t.model.id)??[],t]);let a=new Map,s=new Set;for(let[e,t]of i){let n=t.find(e=>!e.filter)??t[0],r=o(n.model.name);s.has(r)&&(r=`${n.packageId}.${r}`),s.add(r),a.set(e,c(n.model,n.label,r))}return[...a.values()]}export{l as n,i as t};
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./D7hhQvDO.js","./C7zBd-pD.js","./CA-A9Ngs.js","./uBIymjUX.js","./BBmlFBgo.js","./COiEfhsA.js","./C5qDLfXy.js","./BxyJ_Q7v.js","./CsaWd8kG.js","./DG3qFFTE.js","./xihTtKlq.js","./YUSKx8_q.js","./DK8Blf1Y.js","../assets/currency-metadata.ksbBA8-C.css","./DF-0MxNw.js","../assets/SegmentedControl.DMqHG5fn.css","../assets/forms.BRdbPdvs.css","./Dbjm4OuC.js"])))=>i.map(i=>d[i]);
2
- import{n as e}from"./COiEfhsA.js";import{t}from"./uBIymjUX.js";import{c as n,l as r,o as i,s as a,u as o}from"./BeL8dJx9.js";import{M as s}from"./C6AANt9H.js";import{a as c,i as l,n as u,o as d,r as f,s as p,t as m}from"./C7zBd-pD.js";import{t as h}from"./D7hhQvDO.js";import"./BxyJ_Q7v.js";function g(e){return!e.type||e.type===`webllm`}function _(e){return e.type===`transformers-llm`}async function v(e={}){if(g(e)){let{WebLLMAdapter:n}=await t(async()=>{let{WebLLMAdapter:e}=await import(`./D7hhQvDO.js`);return{WebLLMAdapter:e}},__vite__mapDeps([0,1,2,3]),import.meta.url);return new n(e)}throw _(e)?new p(`transformers-llm`,[`webllm`]):new p(String(e.type),[`webllm`,`transformers-llm`])}function y(e){return!e.type||e.type===`browser-speech`}function b(e){return e.type===`whisper-local`||e.type===`whisper-wasm`||e.type===`moonshine`}function x(e){return e.type===`whisper-cpp`}async function S(e={}){if(y(e)){let{BrowserSpeechSTTAdapter:n}=await t(async()=>{let{BrowserSpeechSTTAdapter:e}=await import(`./BBmlFBgo.js`).then(e=>e.t);return{BrowserSpeechSTTAdapter:e}},__vite__mapDeps([4,5,1]),import.meta.url);return new n(e)}if(x(e)){let{WhisperCppSTTAdapter:n}=await t(async()=>{let{WhisperCppSTTAdapter:e}=await import(`./C5qDLfXy.js`).then(e=>e.t);return{WhisperCppSTTAdapter:e}},__vite__mapDeps([6,5,1,2,3]),import.meta.url);return new n(e)}if(b(e)){let{LocalSpeechSTTAdapter:n}=await t(async()=>{let{LocalSpeechSTTAdapter:e}=await import(`./BxyJ_Q7v.js`).then(e=>e.t);return{LocalSpeechSTTAdapter:e}},__vite__mapDeps([7,5,8,9,10,11,12,13,14,15,16,1,2,3]),import.meta.url);return new n(e)}throw new p(String(e.type),[`browser-speech`,`whisper-cpp`,`whisper-local`,`whisper-wasm`,`moonshine`])}function C(e={type:`browser-speech`}){let t=null;return()=>(t??=(async()=>{let t=await S(e);return t.getCapabilities().requiresDownload||await t.ensureInitialized(),t})().catch(e=>{throw t=null,e}),t)}function w(e){return!e.type||e.type===`browser-synthesis`}function T(e){return e.type===`transformers`}async function E(e={}){if(w(e)){let{BrowserSynthesisTTSAdapter:n}=await t(async()=>{let{BrowserSynthesisTTSAdapter:e}=await import(`./Dbjm4OuC.js`);return{BrowserSynthesisTTSAdapter:e}},__vite__mapDeps([17,1]),import.meta.url);return new n(e)}throw T(e)?new p(`transformers`,[`browser-synthesis`]):new p(String(e.type),[`browser-synthesis`])}var D=e({BrowserAIError:()=>m,CapabilityNotAvailableError:()=>u,InitializationError:()=>f,ModelLoadError:()=>l,ModelNotDownloadedError:()=>c,PermissionDeniedError:()=>d,RECOMMENDED_MODELS:()=>h,UnsupportedAdapterError:()=>p,WHISPER_LOCAL_DEFAULT_MODEL:()=>WHISPER_LOCAL_DEFAULT_MODEL,WHISPER_LOCAL_DEFAULT_SIZE_BYTES:()=>WHISPER_LOCAL_DEFAULT_SIZE_BYTES,canEnableSmrtMode:()=>i,detectCapabilities:()=>a,getLLM:()=>v,getSTT:()=>S,getTTS:()=>E,hasLLM:()=>n,hasSTT:()=>r,hasTTS:()=>o,probeBrowserSpeech:()=>s});export{C as n,D as t};
2
+ import{n as e}from"./COiEfhsA.js";import{t}from"./uBIymjUX.js";import{c as n,l as r,o as i,s as a,u as o}from"./BfeotTF9.js";import{M as s}from"./DqrQeG8L.js";import{a as c,i as l,n as u,o as d,r as f,s as p,t as m}from"./C7zBd-pD.js";import{t as h}from"./D7hhQvDO.js";import"./BxyJ_Q7v.js";function g(e){return!e.type||e.type===`webllm`}function _(e){return e.type===`transformers-llm`}async function v(e={}){if(g(e)){let{WebLLMAdapter:n}=await t(async()=>{let{WebLLMAdapter:e}=await import(`./D7hhQvDO.js`);return{WebLLMAdapter:e}},__vite__mapDeps([0,1,2,3]),import.meta.url);return new n(e)}throw _(e)?new p(`transformers-llm`,[`webllm`]):new p(String(e.type),[`webllm`,`transformers-llm`])}function y(e){return!e.type||e.type===`browser-speech`}function b(e){return e.type===`whisper-local`||e.type===`whisper-wasm`||e.type===`moonshine`}function x(e){return e.type===`whisper-cpp`}async function S(e={}){if(y(e)){let{BrowserSpeechSTTAdapter:n}=await t(async()=>{let{BrowserSpeechSTTAdapter:e}=await import(`./BBmlFBgo.js`).then(e=>e.t);return{BrowserSpeechSTTAdapter:e}},__vite__mapDeps([4,5,1]),import.meta.url);return new n(e)}if(x(e)){let{WhisperCppSTTAdapter:n}=await t(async()=>{let{WhisperCppSTTAdapter:e}=await import(`./C5qDLfXy.js`).then(e=>e.t);return{WhisperCppSTTAdapter:e}},__vite__mapDeps([6,5,1,2,3]),import.meta.url);return new n(e)}if(b(e)){let{LocalSpeechSTTAdapter:n}=await t(async()=>{let{LocalSpeechSTTAdapter:e}=await import(`./BxyJ_Q7v.js`).then(e=>e.t);return{LocalSpeechSTTAdapter:e}},__vite__mapDeps([7,5,8,9,10,11,12,13,14,15,16,1,2,3]),import.meta.url);return new n(e)}throw new p(String(e.type),[`browser-speech`,`whisper-cpp`,`whisper-local`,`whisper-wasm`,`moonshine`])}function C(e={type:`browser-speech`}){let t=null;return()=>(t??=(async()=>{let t=await S(e);return t.getCapabilities().requiresDownload||await t.ensureInitialized(),t})().catch(e=>{throw t=null,e}),t)}function w(e){return!e.type||e.type===`browser-synthesis`}function T(e){return e.type===`transformers`}async function E(e={}){if(w(e)){let{BrowserSynthesisTTSAdapter:n}=await t(async()=>{let{BrowserSynthesisTTSAdapter:e}=await import(`./Dbjm4OuC.js`);return{BrowserSynthesisTTSAdapter:e}},__vite__mapDeps([17,1]),import.meta.url);return new n(e)}throw T(e)?new p(`transformers`,[`browser-synthesis`]):new p(String(e.type),[`browser-synthesis`])}var D=e({BrowserAIError:()=>m,CapabilityNotAvailableError:()=>u,InitializationError:()=>f,ModelLoadError:()=>l,ModelNotDownloadedError:()=>c,PermissionDeniedError:()=>d,RECOMMENDED_MODELS:()=>h,UnsupportedAdapterError:()=>p,WHISPER_LOCAL_DEFAULT_MODEL:()=>WHISPER_LOCAL_DEFAULT_MODEL,WHISPER_LOCAL_DEFAULT_SIZE_BYTES:()=>WHISPER_LOCAL_DEFAULT_SIZE_BYTES,canEnableSmrtMode:()=>i,detectCapabilities:()=>a,getLLM:()=>v,getSTT:()=>S,getTTS:()=>E,hasLLM:()=>n,hasSTT:()=>r,hasTTS:()=>o,probeBrowserSpeech:()=>s});export{C as n,D as t};
@@ -1 +1 @@
1
- import{D as e,M as t,w as n}from"./D3lXu_rt.js";import{r}from"./C2OYATC6.js";var i=`@happyvertical/smrt-assets:Asset`,a=`@happyvertical/smrt-products:ProductAsset`,o=`assets.library`;function s(e,t,n){let r=new Map(t.map(e=>[e.id,e]));return n.filter(t=>t.productId===e).flatMap(e=>{let t=r.get(String(e.assetId)),n=t?.sourceUri;return!t||typeof n!=`string`?[]:[{id:t.id,name:String(t.name??`Product image`),sourceUri:n,mimeType:String(t.mimeType??`image/*`),description:String(t.description??``),sortOrder:Number(e.sortOrder??0)}]}).sort((e,t)=>e.sortOrder-t.sortOrder||e.name.localeCompare(t.name))}function c(e,t,n,o){return[{op:`save`,as:`asset`,model:r(i),values:{name:t.name||`Product image`,sourceUri:n,mimeType:t.type||`image/*`,description:`Image selected for this product in the browser demo.`,sourceType:`browser-demo`}},{op:`save`,model:r(a),values:{productId:e,assetId:{ref:`asset`},relationship:`gallery`,sortOrder:o}}]}function l(e,t){return t.filter(t=>t.productId===e).flatMap(e=>[{op:`delete`,model:r(a),id:e.id},{op:`delete`,model:r(i),id:String(e.assetId)}])}var u=`@happyvertical/smrt-products:Product`,d=`@happyvertical/smrt-products:ProductVariant`,f=`@happyvertical/smrt-products:Sku`,p=`@happyvertical/smrt-inventory:StockLevel`,m=`@happyvertical/smrt-profiles:ProfileType`,h=`@happyvertical/smrt-inventory:InventoryLocation`;function g(r){return{[h]:{from:[],make:()=>(t().locations??[]).map((e,t)=>({id:n(`${h}:sample:${t}`),...e,placeId:``,active:!0}))},[f]:{from:[r(u)],make:([e])=>(e??[]).map((e,t)=>({id:n(`${f}:sample:${e.id}`),productId:e.id,code:`SKU-${String(t+1).padStart(3,`0`)}`,barcode:``,name:String(e.name??``),attributes:``,parentSkuId:``,active:!0}))},[p]:{from:[r(f),r(h)],make:([r,i])=>{let a=t(),o=new Map(a.products.map(e=>[e.name,e.at]));return(r??[]).flatMap(t=>(i??[]).flatMap((r,i)=>{let a=e(`${t.id}:${r.id}`),s=o.get(String(t.name));if(s!==void 0){if(s!==i)return[]}else if(i>0&&a%3==0)return[];let c=10+a%4*5;return[{id:n(`${p}:sample:${t.id}:${r.id}`),skuId:t.id,locationId:r.id,state:`available`,qty:a%5==0?c-3:c+a%40,reorderPoint:c,reorderQuantity:c*3}]}))}}}}function _(e,t){let n=new Map(e.map(e=>[e.id,e.productId])),r=new Map;for(let e of t){let t=n.get(String(e.skuId));typeof t==`string`&&r.set(t,(r.get(t)??0)+Number(e.qty??0))}return r}function v(e,t,n,r=[]){return[...l(e,r),...t.flatMap(e=>[{op:`delete`,model:n(p),match:{skuId:e.id}},{op:`delete`,model:n(f),id:e.id}]),{op:`delete`,model:n(d),match:{productId:e}},{op:`delete`,model:n(u),id:e}]}export{d as a,g as c,a as d,c as f,p as i,i as l,m as n,v as o,s as p,f as r,_ as s,u as t,o as u};
1
+ import{D as e,M as t,w as n}from"./B45qMR8U.js";import{r}from"./DziaAoFY.js";var i=`@happyvertical/smrt-assets:Asset`,a=`@happyvertical/smrt-products:ProductAsset`,o=`assets.library`;function s(e,t,n){let r=new Map(t.map(e=>[e.id,e]));return n.filter(t=>t.productId===e).flatMap(e=>{let t=r.get(String(e.assetId)),n=t?.sourceUri;return!t||typeof n!=`string`?[]:[{id:t.id,name:String(t.name??`Product image`),sourceUri:n,mimeType:String(t.mimeType??`image/*`),description:String(t.description??``),sortOrder:Number(e.sortOrder??0)}]}).sort((e,t)=>e.sortOrder-t.sortOrder||e.name.localeCompare(t.name))}function c(e,t,n,o){return[{op:`save`,as:`asset`,model:r(i),values:{name:t.name||`Product image`,sourceUri:n,mimeType:t.type||`image/*`,description:`Image selected for this product in the browser demo.`,sourceType:`browser-demo`}},{op:`save`,model:r(a),values:{productId:e,assetId:{ref:`asset`},relationship:`gallery`,sortOrder:o}}]}function l(e,t){return t.filter(t=>t.productId===e).flatMap(e=>[{op:`delete`,model:r(a),id:e.id},{op:`delete`,model:r(i),id:String(e.assetId)}])}var u=`@happyvertical/smrt-products:Product`,d=`@happyvertical/smrt-products:ProductVariant`,f=`@happyvertical/smrt-products:Sku`,p=`@happyvertical/smrt-inventory:StockLevel`,m=`@happyvertical/smrt-profiles:ProfileType`,h=`@happyvertical/smrt-inventory:InventoryLocation`;function g(r){return{[h]:{from:[],make:()=>(t().locations??[]).map((e,t)=>({id:n(`${h}:sample:${t}`),...e,placeId:``,active:!0}))},[f]:{from:[r(u)],make:([e])=>(e??[]).map((e,t)=>({id:n(`${f}:sample:${e.id}`),productId:e.id,code:`SKU-${String(t+1).padStart(3,`0`)}`,barcode:``,name:String(e.name??``),attributes:``,parentSkuId:``,active:!0}))},[p]:{from:[r(f),r(h)],make:([r,i])=>{let a=t(),o=new Map(a.products.map(e=>[e.name,e.at]));return(r??[]).flatMap(t=>(i??[]).flatMap((r,i)=>{let a=e(`${t.id}:${r.id}`),s=o.get(String(t.name));if(s!==void 0){if(s!==i)return[]}else if(i>0&&a%3==0)return[];let c=10+a%4*5;return[{id:n(`${p}:sample:${t.id}:${r.id}`),skuId:t.id,locationId:r.id,state:`available`,qty:a%5==0?c-3:c+a%40,reorderPoint:c,reorderQuantity:c*3}]}))}}}}function _(e,t){let n=new Map(e.map(e=>[e.id,e.productId])),r=new Map;for(let e of t){let t=n.get(String(e.skuId));typeof t==`string`&&r.set(t,(r.get(t)??0)+Number(e.qty??0))}return r}function v(e,t,n,r=[]){return[...l(e,r),...t.flatMap(e=>[{op:`delete`,model:n(p),match:{skuId:e.id}},{op:`delete`,model:n(f),id:e.id}]),{op:`delete`,model:n(d),match:{productId:e}},{op:`delete`,model:n(u),id:e}]}export{d as a,g as c,a as d,c as f,p as i,i as l,m as n,v as o,s as p,f as r,_ as s,u as t,o as u};
@@ -1 +1 @@
1
- import{$ as e,Ct as t,Dt as n,E as r,Ft as i,G as a,Ot as o,U as s,a as c,ft as l,ht as u,st as d,v as f}from"./DG3qFFTE.js";import"./xihTtKlq.js";import{t as p}from"./D3lXu_rt.js";import{tt as m}from"./lUJaueNM.js";var h=a(`<div><a class="svelte-1fbsd8p"><!></a> <a class="svelte-1fbsd8p"><!></a></div>`);function g(a,g){o(g,!0);let _=c(g,`compact`,3,!1),v=t(()=>`${p(`/recipes/${g.section}/help/`)}${g.helpAnchor?`#${g.helpAnchor}`:``}`);var y=h();let b;var x=l(y),S=l(x);{let n=t(()=>_()?16:22);m(S,{path:`M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z`,get size(){return e(n)}})}i(x);var C=u(x,2),w=l(C);{let n=t(()=>_()?16:22);m(w,{path:`M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z`,get size(){return e(n)}})}i(C),i(y),d(t=>{b=r(y,1,`icons svelte-1fbsd8p`,null,b,{compact:_()}),f(x,`href`,e(v)),f(x,`title`,`${g.label} help`),f(x,`aria-label`,`${g.label} help`),f(x,`aria-current`,g.current===`help`?`page`:void 0),f(C,`href`,t),f(C,`title`,`${g.label} options`),f(C,`aria-label`,`${g.label} options`),f(C,`aria-current`,g.current===`options`?`page`:void 0)},[()=>p(`/recipes/${g.section}/`)]),s(a,y),n()}export{g as t};
1
+ import{$ as e,Ct as t,Dt as n,E as r,Ft as i,G as a,Ot as o,U as s,a as c,ft as l,ht as u,st as d,v as f}from"./DG3qFFTE.js";import"./xihTtKlq.js";import{t as p}from"./B45qMR8U.js";import{tt as m}from"./nB-x9BEp.js";var h=a(`<div><a class="svelte-1fbsd8p"><!></a> <a class="svelte-1fbsd8p"><!></a></div>`);function g(a,g){o(g,!0);let _=c(g,`compact`,3,!1),v=t(()=>`${p(`/recipes/${g.section}/help/`)}${g.helpAnchor?`#${g.helpAnchor}`:``}`);var y=h();let b;var x=l(y),S=l(x);{let n=t(()=>_()?16:22);m(S,{path:`M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z`,get size(){return e(n)}})}i(x);var C=u(x,2),w=l(C);{let n=t(()=>_()?16:22);m(w,{path:`M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.488.488 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z`,get size(){return e(n)}})}i(C),i(y),d(t=>{b=r(y,1,`icons svelte-1fbsd8p`,null,b,{compact:_()}),f(x,`href`,e(v)),f(x,`title`,`${g.label} help`),f(x,`aria-label`,`${g.label} help`),f(x,`aria-current`,g.current===`help`?`page`:void 0),f(C,`href`,t),f(C,`title`,`${g.label} options`),f(C,`aria-label`,`${g.label} options`),f(C,`aria-current`,g.current===`options`?`page`:void 0)},[()=>p(`/recipes/${g.section}/`)]),s(a,y),n()}export{g as t};
@@ -1 +1 @@
1
- import{$ as e,B as t,Ct as n,Dt as r,E as i,Ft as a,G as o,H as s,J as c,L as l,Ot as u,Pt as d,U as f,W as p,Y as m,a as h,bt as ee,d as g,ft as _,ht as v,mt as y,n as b,nt as te,o as x,pt as S,q as C,r as w,st as T,tt as ne,v as E,vt as re}from"./DG3qFFTE.js";import"./xihTtKlq.js";import"./Bv5jGtB8.js";import{t as ie}from"./YUSKx8_q.js";import"./D3lXu_rt.js";import{n as D}from"./DK8Blf1Y.js";import{C as O,T as k,f as ae,p as oe}from"./BeL8dJx9.js";import{n as se}from"./DF-0MxNw.js";import{o as A,u as j}from"./DIE02RSm.js";import{i as M}from"./CsaWd8kG.js";var N=new Set([`$$slots`,`$$events`,`$$legacy`]);function P(e,t){u(t,!0);let n=k(),i=x(t,N),a=null;w(()=>{a=n.registerFocusTool(i)}),b(()=>{a?.()}),r()}var ce=o(`<!> <!>`,1),le=o(`<span class="smrt-shell-layout-editor__muted svelte-xzk327"> </span>`),ue=o(`<div class="smrt-shell-layout-editor__row svelte-xzk327"><!></div>`),de=o(`<strong> </strong>`),fe=o(`<!> <!> <!> <!>`,1),F=o(`<span> </span> <!>`,1),I=o(`<div class="smrt-shell-layout-editor__preview"><h3 class="svelte-xzk327"> </h3> <div class="smrt-shell-layout-editor__preview-frame svelte-xzk327" role="group" inert=""><!></div></div>`),L=o(`<section class="smrt-shell-layout-editor svelte-xzk327" data-smrt-component="ShellLayoutEditor"><header class="svelte-xzk327"><div><h2 class="svelte-xzk327"> </h2> <p class="svelte-xzk327"> </p></div> <!></header> <fieldset class="smrt-shell-layout-editor__panels svelte-xzk327"><legend class="svelte-xzk327"> </legend> <!></fieldset> <div class="smrt-shell-layout-editor__body svelte-xzk327"><div class="smrt-shell-layout-editor__nav"><div class="smrt-shell-layout-editor__nav-head svelte-xzk327"><h3 class="svelte-xzk327"> </h3> <!></div> <!></div> <!></div></section>`);function R(o,m){let b=C();u(m,!0);let x=h(m,`preview`,3,!0),{t:w}=ie(),k=te(()=>m.controller??j()),N=`${b}-heading`,P=n(()=>k.sections),R=n(()=>k.panels),z=n(()=>k.applied),B=n(()=>e(P).map(e=>({id:e.id,label:e.heading??w(O[`ui.shell_layout_editor.top_level`]),fixed:e.group===null,root:e.group===null,hidden:e.hidden,custom:e.custom,titleVisible:e.titleVisible,count:e.items.length}))),V=n(()=>e(P).flatMap(e=>e.items.map(t=>({id:t.id,containerId:e.id,label:t.label}))));function H(e,t){t?k.show(e):k.hide(e)}let U=ee(void 0);function pe(t,n){let r=n.currentTarget;k.renameSection(t,r.value),r.value=e(B).find(e=>e.id===t)?.label??``}async function me(){let t=k.createSection(w(O[`ui.shell_layout_editor.new_section_label`]));if(!t)return;await ne();let n=e(U)?.querySelector(`input[data-section-name="${CSS.escape(t)}"]`);n?.focus(),n?.select()}function he(e,t,n){n>0&&!globalThis.confirm?.(w(O[`ui.shell_layout_editor.delete_confirm`],{label:t}))||k.deleteSection(e)}function ge(e){k.moveItem(e.item.id,e.target.containerId,e.target.index)}function _e(e){k.moveSection(e.container.id,e.target)}var W=L(),G=_(W),K=_(G),q=_(K),ve=y(q,!0),ye=v(q,2),be=y(ye,!0);a(K);var xe=v(K,2);{let t=n(()=>!k.customized);D(xe,{variant:`secondary`,size:`sm`,get disabled(){return e(t)},onclick:()=>k.reset(),children:(e,t)=>{d();var n=c();T(e=>s(n,e),[()=>w(O[`ui.shell_layout_editor.reset`])]),f(e,n)},$$slots:{default:!0}})}a(G);var J=v(G,2),Y=_(J),Se=y(Y,!0),Ce=v(Y,2);l(Ce,17,()=>e(R),e=>e.edge,(r,i)=>{var o=ue(),c=_(o),l=t=>{var r=ce(),a=S(r);{let t=n(()=>w(O[`ui.shell_layout_editor.show_panel`],{panel:e(i).label}));M(a,{interaction:!1,get checked(){return e(i).visible},get label(){return e(t)},onchange:t=>k.setPanel(e(i).edge,{visible:t.currentTarget.checked})})}var o=v(a,2);{let t=n(()=>e(i).initial===`expanded`),r=n(()=>!e(i).visible),a=n(()=>w(O[`ui.shell_layout_editor.start_expanded`],{panel:e(i).label}));M(o,{interaction:!1,get checked(){return e(t)},get disabled(){return e(r)},get label(){return e(a)},onchange:t=>k.setPanel(e(i).edge,{initial:t.currentTarget.checked?`expanded`:`collapsed`})})}f(t,r)},u=t=>{var n=le(),r=y(n,!0);T(e=>s(r,e),[()=>w(O[`ui.shell_layout_editor.panel_unavailable`],{panel:e(i).label})]),f(t,n)};t(c,t=>{e(i).available?t(l):t(u,-1)}),a(o),T(()=>E(o,`data-edge`,e(i).edge)),f(r,o)}),a(J);var X=v(J,2),Z=_(X),Q=_(Z),$=_(Q),we=y($,!0),Te=v($,2);D(Te,{variant:`secondary`,size:`sm`,onclick:me,children:(e,t)=>{d();var n=c();T(e=>s(n,e),[()=>w(O[`ui.shell_layout_editor.new_section`])]),f(e,n)},$$slots:{default:!0}}),a(Q);var Ee=v(Q,2);{let r=(r,i)=>{let a=()=>(i?.()).container,o=n(()=>e(B).find(e=>e.id===a().id));var c=p(),l=S(c),u=e=>{var t=de(),n=y(t,!0);T(()=>s(n,a().label)),f(e,t)},d=r=>{var i=fe(),s=S(i);{let t=n(()=>w(O[`ui.shell_layout_editor.section_name`],{label:a().label}));se(s,{class:`smrt-shell-layout-editor__name`,interaction:!1,get"data-section-name"(){return a().id},get"aria-label"(){return e(t)},get value(){return a().label},onchange:e=>pe(a().id,e)})}var c=v(s,2);{let t=n(()=>e(o)?.hidden?`eyeOff`:`eye`),r=n(()=>!e(o)?.hidden),i=n(()=>w(O[`ui.shell_layout_editor.show_entry`],{label:a().label}));A(c,{get icon(){return e(t)},get pressed(){return e(r)},get label(){return e(i)},onclick:()=>H(a().id,!!e(o)?.hidden)})}var l=v(c,2);{let t=n(()=>e(o)?.titleVisible===!1?`headingOff`:`heading`),r=n(()=>e(o)?.titleVisible??!0),i=n(()=>w(O[`ui.shell_layout_editor.show_title_for`],{label:a().label}));A(l,{get icon(){return e(t)},get pressed(){return e(r)},get label(){return e(i)},onclick:()=>k.setSectionTitleVisible(a().id,!(e(o)?.titleVisible??!0))})}var u=v(l,2),d=t=>{{let r=n(()=>w(O[`ui.shell_layout_editor.delete_section`],{label:a().label}));A(t,{icon:`trash`,get label(){return e(r)},onclick:()=>he(a().id,a().label,e(o).count)})}};t(u,t=>{e(o)?.custom&&t(d)}),f(r,i)};t(l,t=>{e(o)?.root?t(u):t(d,-1)}),f(r,c)},a=(t,r)=>{let a=()=>(r?.()).item,o=()=>(r?.()).container,c=n(()=>k.isHidden(a().id));var l=F(),u=S(l);let d;var p=y(u,!0),m=v(u,2);{let t=n(()=>e(c)?`eyeOff`:`eye`),r=n(()=>!e(c)),i=n(()=>w(O[`ui.shell_layout_editor.show_entry`],{label:a().label}));A(m,{get icon(){return e(t)},get pressed(){return e(r)},get label(){return e(i)},onclick:()=>H(a().id,e(c))})}T(e=>{d=i(u,1,`smrt-shell-layout-editor__label svelte-xzk327`,null,d,{"smrt-shell-layout-editor__muted":e}),s(p,a().label)},[()=>e(c)||k.isHidden(o().id)]),f(t,l)},o=n(()=>w(O[`ui.shell_layout_editor.sortable_label`]));oe(Ee,{get containers(){return e(B)},get items(){return e(V)},get label(){return e(o)},reorderContainers:!0,onmove:ge,oncontainermove:_e,containerHeader:r,item:a,$$slots:{containerHeader:!0,item:!0}})}a(Z);var De=v(Z,2),Oe=t=>{var r=I(),i=_(r),o=y(i,!0),c=v(i,2),l=_(c);{let t=n(()=>w(O[`ui.shell_layout_editor.preview_label`]));ae(l,{get items(){return e(z).nav},get groups(){return e(z).groups},get iconComponent(){return m.iconComponent},get"aria-label"(){return e(t)}})}a(c),a(r),T((e,t)=>{s(o,e),E(c,`aria-label`,t)},[()=>w(O[`ui.shell_layout_editor.preview`]),()=>w(O[`ui.shell_layout_editor.preview_label`])]),f(t,r)};t(De,e=>{x()&&e(Oe)}),a(X),a(W),g(W,e=>re(U,e),()=>e(U)),T((e,t,n,r)=>{E(W,`aria-labelledby`,N),E(q,`id`,N),s(ve,e),s(be,t),s(Se,n),s(we,r)},[()=>w(O[`ui.shell_layout_editor.heading`]),()=>w(O[`ui.shell_layout_editor.description`]),()=>w(O[`ui.shell_layout_editor.panels`]),()=>w(O[`ui.shell_layout_editor.navigation`])]),f(o,W),r()}m([`click`]);export{P as n,R as t};
1
+ import{$ as e,B as t,Ct as n,Dt as r,E as i,Ft as a,G as o,H as s,J as c,L as l,Ot as u,Pt as d,U as f,W as p,Y as m,a as h,bt as ee,d as g,ft as _,ht as v,mt as y,n as b,nt as te,o as x,pt as S,q as C,r as w,st as T,tt as ne,v as E,vt as re}from"./DG3qFFTE.js";import"./xihTtKlq.js";import"./Bv5jGtB8.js";import{t as ie}from"./YUSKx8_q.js";import"./B45qMR8U.js";import{n as D}from"./DK8Blf1Y.js";import{C as O,T as k,f as ae,p as oe}from"./BfeotTF9.js";import{n as se}from"./DF-0MxNw.js";import{o as A,u as j}from"./DIE02RSm.js";import{i as M}from"./CsaWd8kG.js";var N=new Set([`$$slots`,`$$events`,`$$legacy`]);function P(e,t){u(t,!0);let n=k(),i=x(t,N),a=null;w(()=>{a=n.registerFocusTool(i)}),b(()=>{a?.()}),r()}var ce=o(`<!> <!>`,1),le=o(`<span class="smrt-shell-layout-editor__muted svelte-xzk327"> </span>`),ue=o(`<div class="smrt-shell-layout-editor__row svelte-xzk327"><!></div>`),de=o(`<strong> </strong>`),fe=o(`<!> <!> <!> <!>`,1),F=o(`<span> </span> <!>`,1),I=o(`<div class="smrt-shell-layout-editor__preview"><h3 class="svelte-xzk327"> </h3> <div class="smrt-shell-layout-editor__preview-frame svelte-xzk327" role="group" inert=""><!></div></div>`),L=o(`<section class="smrt-shell-layout-editor svelte-xzk327" data-smrt-component="ShellLayoutEditor"><header class="svelte-xzk327"><div><h2 class="svelte-xzk327"> </h2> <p class="svelte-xzk327"> </p></div> <!></header> <fieldset class="smrt-shell-layout-editor__panels svelte-xzk327"><legend class="svelte-xzk327"> </legend> <!></fieldset> <div class="smrt-shell-layout-editor__body svelte-xzk327"><div class="smrt-shell-layout-editor__nav"><div class="smrt-shell-layout-editor__nav-head svelte-xzk327"><h3 class="svelte-xzk327"> </h3> <!></div> <!></div> <!></div></section>`);function R(o,m){let b=C();u(m,!0);let x=h(m,`preview`,3,!0),{t:w}=ie(),k=te(()=>m.controller??j()),N=`${b}-heading`,P=n(()=>k.sections),R=n(()=>k.panels),z=n(()=>k.applied),B=n(()=>e(P).map(e=>({id:e.id,label:e.heading??w(O[`ui.shell_layout_editor.top_level`]),fixed:e.group===null,root:e.group===null,hidden:e.hidden,custom:e.custom,titleVisible:e.titleVisible,count:e.items.length}))),V=n(()=>e(P).flatMap(e=>e.items.map(t=>({id:t.id,containerId:e.id,label:t.label}))));function H(e,t){t?k.show(e):k.hide(e)}let U=ee(void 0);function pe(t,n){let r=n.currentTarget;k.renameSection(t,r.value),r.value=e(B).find(e=>e.id===t)?.label??``}async function me(){let t=k.createSection(w(O[`ui.shell_layout_editor.new_section_label`]));if(!t)return;await ne();let n=e(U)?.querySelector(`input[data-section-name="${CSS.escape(t)}"]`);n?.focus(),n?.select()}function he(e,t,n){n>0&&!globalThis.confirm?.(w(O[`ui.shell_layout_editor.delete_confirm`],{label:t}))||k.deleteSection(e)}function ge(e){k.moveItem(e.item.id,e.target.containerId,e.target.index)}function _e(e){k.moveSection(e.container.id,e.target)}var W=L(),G=_(W),K=_(G),q=_(K),ve=y(q,!0),ye=v(q,2),be=y(ye,!0);a(K);var xe=v(K,2);{let t=n(()=>!k.customized);D(xe,{variant:`secondary`,size:`sm`,get disabled(){return e(t)},onclick:()=>k.reset(),children:(e,t)=>{d();var n=c();T(e=>s(n,e),[()=>w(O[`ui.shell_layout_editor.reset`])]),f(e,n)},$$slots:{default:!0}})}a(G);var J=v(G,2),Y=_(J),Se=y(Y,!0),Ce=v(Y,2);l(Ce,17,()=>e(R),e=>e.edge,(r,i)=>{var o=ue(),c=_(o),l=t=>{var r=ce(),a=S(r);{let t=n(()=>w(O[`ui.shell_layout_editor.show_panel`],{panel:e(i).label}));M(a,{interaction:!1,get checked(){return e(i).visible},get label(){return e(t)},onchange:t=>k.setPanel(e(i).edge,{visible:t.currentTarget.checked})})}var o=v(a,2);{let t=n(()=>e(i).initial===`expanded`),r=n(()=>!e(i).visible),a=n(()=>w(O[`ui.shell_layout_editor.start_expanded`],{panel:e(i).label}));M(o,{interaction:!1,get checked(){return e(t)},get disabled(){return e(r)},get label(){return e(a)},onchange:t=>k.setPanel(e(i).edge,{initial:t.currentTarget.checked?`expanded`:`collapsed`})})}f(t,r)},u=t=>{var n=le(),r=y(n,!0);T(e=>s(r,e),[()=>w(O[`ui.shell_layout_editor.panel_unavailable`],{panel:e(i).label})]),f(t,n)};t(c,t=>{e(i).available?t(l):t(u,-1)}),a(o),T(()=>E(o,`data-edge`,e(i).edge)),f(r,o)}),a(J);var X=v(J,2),Z=_(X),Q=_(Z),$=_(Q),we=y($,!0),Te=v($,2);D(Te,{variant:`secondary`,size:`sm`,onclick:me,children:(e,t)=>{d();var n=c();T(e=>s(n,e),[()=>w(O[`ui.shell_layout_editor.new_section`])]),f(e,n)},$$slots:{default:!0}}),a(Q);var Ee=v(Q,2);{let r=(r,i)=>{let a=()=>(i?.()).container,o=n(()=>e(B).find(e=>e.id===a().id));var c=p(),l=S(c),u=e=>{var t=de(),n=y(t,!0);T(()=>s(n,a().label)),f(e,t)},d=r=>{var i=fe(),s=S(i);{let t=n(()=>w(O[`ui.shell_layout_editor.section_name`],{label:a().label}));se(s,{class:`smrt-shell-layout-editor__name`,interaction:!1,get"data-section-name"(){return a().id},get"aria-label"(){return e(t)},get value(){return a().label},onchange:e=>pe(a().id,e)})}var c=v(s,2);{let t=n(()=>e(o)?.hidden?`eyeOff`:`eye`),r=n(()=>!e(o)?.hidden),i=n(()=>w(O[`ui.shell_layout_editor.show_entry`],{label:a().label}));A(c,{get icon(){return e(t)},get pressed(){return e(r)},get label(){return e(i)},onclick:()=>H(a().id,!!e(o)?.hidden)})}var l=v(c,2);{let t=n(()=>e(o)?.titleVisible===!1?`headingOff`:`heading`),r=n(()=>e(o)?.titleVisible??!0),i=n(()=>w(O[`ui.shell_layout_editor.show_title_for`],{label:a().label}));A(l,{get icon(){return e(t)},get pressed(){return e(r)},get label(){return e(i)},onclick:()=>k.setSectionTitleVisible(a().id,!(e(o)?.titleVisible??!0))})}var u=v(l,2),d=t=>{{let r=n(()=>w(O[`ui.shell_layout_editor.delete_section`],{label:a().label}));A(t,{icon:`trash`,get label(){return e(r)},onclick:()=>he(a().id,a().label,e(o).count)})}};t(u,t=>{e(o)?.custom&&t(d)}),f(r,i)};t(l,t=>{e(o)?.root?t(u):t(d,-1)}),f(r,c)},a=(t,r)=>{let a=()=>(r?.()).item,o=()=>(r?.()).container,c=n(()=>k.isHidden(a().id));var l=F(),u=S(l);let d;var p=y(u,!0),m=v(u,2);{let t=n(()=>e(c)?`eyeOff`:`eye`),r=n(()=>!e(c)),i=n(()=>w(O[`ui.shell_layout_editor.show_entry`],{label:a().label}));A(m,{get icon(){return e(t)},get pressed(){return e(r)},get label(){return e(i)},onclick:()=>H(a().id,e(c))})}T(e=>{d=i(u,1,`smrt-shell-layout-editor__label svelte-xzk327`,null,d,{"smrt-shell-layout-editor__muted":e}),s(p,a().label)},[()=>e(c)||k.isHidden(o().id)]),f(t,l)},o=n(()=>w(O[`ui.shell_layout_editor.sortable_label`]));oe(Ee,{get containers(){return e(B)},get items(){return e(V)},get label(){return e(o)},reorderContainers:!0,onmove:ge,oncontainermove:_e,containerHeader:r,item:a,$$slots:{containerHeader:!0,item:!0}})}a(Z);var De=v(Z,2),Oe=t=>{var r=I(),i=_(r),o=y(i,!0),c=v(i,2),l=_(c);{let t=n(()=>w(O[`ui.shell_layout_editor.preview_label`]));ae(l,{get items(){return e(z).nav},get groups(){return e(z).groups},get iconComponent(){return m.iconComponent},get"aria-label"(){return e(t)}})}a(c),a(r),T((e,t)=>{s(o,e),E(c,`aria-label`,t)},[()=>w(O[`ui.shell_layout_editor.preview`]),()=>w(O[`ui.shell_layout_editor.preview_label`])]),f(t,r)};t(De,e=>{x()&&e(Oe)}),a(X),a(W),g(W,e=>re(U,e),()=>e(U)),T((e,t,n,r)=>{E(W,`aria-labelledby`,N),E(q,`id`,N),s(ve,e),s(be,t),s(Se,n),s(we,r)},[()=>w(O[`ui.shell_layout_editor.heading`]),()=>w(O[`ui.shell_layout_editor.description`]),()=>w(O[`ui.shell_layout_editor.panels`]),()=>w(O[`ui.shell_layout_editor.navigation`])]),f(o,W),r()}m([`click`]);export{P as n,R as t};
@@ -1 +1 @@
1
- import{$ as e,bt as t,ct as n,gt as r,nt as i,ot as a,vt as o}from"./DG3qFFTE.js";import{F as s,lt as c}from"./D3lXu_rt.js";import{g as l}from"./BeL8dJx9.js";import{a as u,c as d,h as f,n as p,o as m}from"./Cwz7QFS4.js";import{b as h,c as g,o as _,r as v}from"./lUJaueNM.js";import{n as y}from"./FeyhlLIZ.js";var b=[`material`,`glass`,`studio`,`smrt`,`happyvertical`],x=`@happyvertical/smrt-commerce:`,S={currency:[`Order`,`PurchaseOrder`,`WholesaleOrder`,`Estimate`,`Invoice`,`Agreement`].map(e=>({model:`${x}${e}`,field:`currency`})),taxRate:[`InvoiceLineItem`,`ContractLineItem`].map(e=>({model:`${x}${e}`,field:`taxRate`})),pricesIncludeTax:[`Invoice`,`Contract`].map(e=>({model:`${x}${e}`,field:`lineAmountType`})),taxRounding:[`Invoice`,`Contract`].map(e=>({model:`${x}${e}`,field:`taxRoundingScope`})),paymentTerms:[...[`Order`,`WholesaleOrder`,`Estimate`,`Invoice`,`Agreement`].map(e=>({model:`${x}${e}`,field:`terms`})),{model:`${x}Customer`,field:`paymentTerms`}]},C={id:`more`,label:`More`},w=/^@[^/]+\/(?:smrt-)?([^:]+):(.+)$/;function T(e,t){let n=e.models.find(e=>e.id===t);if(n)return{packageId:n.packageId,name:n.name};let r=w.exec(t);return r?{packageId:r[1],name:r[2]}:{packageId:`unknown`,name:t}}var E=(e,t,n)=>`item:${e}:${t}${n?`:${n}`:``}`,D=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase()),O=(e,t)=>D(T(e,t).name);function ee(e,t){let n=new Map(e.recipes.map(e=>[e.id,e])),r=new Map;for(let i of[...t.recipes].sort()){let t=n.get(i);if(!t)continue;let a=t.section??{id:t.group?.id??t.id,label:t.group?.label??t.label},o=`section:${a.id}`,s=r.get(o)??{id:o,label:a.label,items:[]};for(let n of t.nav){let{packageId:t,name:r}=T(e,n.model),i=E(t,r,n.key);s.items.some(e=>e.id===i)||s.items.push({id:i,label:n.label})}r.set(o,s)}let i=[...r.values()].filter(e=>e.items.length>0),a=new Set(e.models.filter(e=>e.exposed!==!1).map(e=>e.id)),o=t.features.filter(e=>a.has(e));return o.length&&i.push({id:`section:${C.id}`,label:C.label,items:o.map(t=>{let{packageId:n,name:r}=T(e,t);return{id:E(n,r),label:D(r)}})}),i}var k=(e,t)=>{if(!t?.length)return e;let n=e=>{let n=t.indexOf(e);return n<0?2**53-1:n};return[...e].sort((e,t)=>n(e.id)-n(t.id))};function te(e,t){let n=t.layout,r=ee(e,t).map(e=>({id:e.id,label:e.label,defaultLabel:e.label,custom:!1,hidden:!1,items:e.items.map(e=>({id:e.id,label:e.label,defaultLabel:e.label,hidden:!1}))}));for(let e of n?.customSections??[])r.some(t=>t.id===e.id)||r.push({id:e.id,label:e.label,defaultLabel:e.label,custom:!0,hidden:!1,items:[]});for(let[e,t]of Object.entries(n?.moved??{})){let n=r.find(e=>e.id===t);if(n)for(let t of r){let r=t.items.findIndex(t=>t.id===e);r>=0&&t!==n&&n.items.push(...t.items.splice(r,1))}}let i=new Set(n?.hidden??[]);for(let e of r){let t=n?.sections?.[e.id]?.label?.trim();t&&!e.custom&&(e.label=t),e.hidden=i.has(e.id),e.items=k(e.items,n?.itemOrder?.[e.id]);for(let t of e.items){let e=n?.items?.[t.id]?.label?.trim();e&&(t.label=e),t.hidden=i.has(t.id)}}return k(r.filter(e=>e.custom||e.items.length>0),n?.sectionOrder)}var A=(e,t)=>e.models.find(e=>e.id===t),ne=e=>{let t={...e};for(let e of[`hidden`,`customSections`,`sectionOrder`])t[e]?.length||delete t[e];for(let e of[`sections`,`items`,`itemOrder`,`moved`,`panels`,`placements`])t[e]&&Object.keys(t[e]).length===0&&delete t[e];return Object.keys(t).length>1?t:void 0};function re(e,t,n){let r=e?structuredClone(e):{version:1},i=n.trim();if(t.custom)return i?(r.customSections=r.customSections?.map(e=>e.id===t.id?{...e,label:i}:e),ne(r)):e;let a={...r.sections??{}},o={...a[t.id]??{}};return!i||i===t.defaultLabel?delete o.label:o.label=i,Object.keys(o).length?a[t.id]=o:delete a[t.id],r.sections=a,ne(r)}function ie(e,t,n){let r=e?structuredClone(e):{version:1},i=n?.trim()??``,a={...r.items??{}},o={...a[t.id]??{}};return!i||i===t.defaultLabel?delete o.label:o.label=i,Object.keys(o).length?a[t.id]=o:delete a[t.id],r.items=a,ne(r)}function ae(e,t,n){let r=e?structuredClone(e):{version:1},i=(r.hidden??[]).filter(e=>e!==t);return r.hidden=n?[...i,t]:i,ne(r)}var oe=`https://s-m-r-t.dev/schemas/cookbook/v1.json`,se=new Set([`basic`,`advanced`,`hidden`]),ce=new Set([`api`,`mcp`,`cli`]),le=new Set([`light`,`dark`,`system`]),ue={borderRadius:[`none`,`sm`,`md`,`lg`,`xl`,`full`],density:[`comfortable`,`touch`],contrast:[`auto`,`standard`,`more`]},de=new Set([`header.start`,`header.center`,`header.end`,`footer.start`,`footer.center`,`footer.end`,`leftSidebar.header`,`leftSidebar.footer`,`rightSidebar.header`,`rightSidebar.footer`]),j=e=>typeof e==`object`&&!!e&&!Array.isArray(e),M=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),fe=(e,t)=>j(e)&&!Object.hasOwn(e,`__proto__`)&&Object.values(e).every(t),pe=(e,t,n,r,i)=>{e.push({severity:t,code:n,path:r,message:i})},N=(e,t,n,r)=>pe(e,`error`,t,n,r),P=(e,t,n,r)=>pe(e,`warning`,t,n,r);function me(e,t,n){if(!j(e))return N(n,`invalid_type`,t,`${t} must be an object`);for(let r of[`objectRef`,`fieldName`])(typeof e[r]!=`string`||!e[r])&&N(n,`invalid_value`,`${t}.${r}`,`${t}.${r} must be a non-empty string`);e.scopeType!==`app`&&N(n,`invalid_value`,`${t}.scopeType`,`${t}.scopeType must be "app"`);for(let r of[`defaultValue`,`help`,`label`]){let i=e[r];i!=null&&typeof i!=`string`&&N(n,`invalid_type`,`${t}.${r}`,`${t}.${r} must be a string or null`)}let r=e.visibility;r!=null&&!(typeof r==`string`&&se.has(r))&&N(n,`invalid_value`,`${t}.visibility`,`${t}.visibility must be basic, advanced or hidden`);let i=e.displayOrder;i!=null&&!(typeof i==`number`&&Number.isFinite(i))&&N(n,`invalid_value`,`${t}.displayOrder`,`${t}.displayOrder must be a finite number`),e.locked!=null&&typeof e.locked!=`boolean`&&N(n,`invalid_type`,`${t}.locked`,`${t}.locked must be a boolean`)}function he(e,t){if(!j(e)||e.version!==1)return N(t,`invalid_value`,`layout`,`layout must be an object with version 1`);for(let n of[`sectionOrder`,`hidden`])e[n]!==void 0&&!M(e[n])&&N(t,`invalid_type`,`layout.${n}`,`layout.${n} must be a list of strings`);for(let n of[`itemOrder`,`moved`,`placements`]){let r=e[n];r!==void 0&&((n===`itemOrder`?fe(r,M):fe(r,e=>typeof e==`string`))||N(t,`invalid_type`,`layout.${n}`,n===`itemOrder`?`layout.itemOrder must map ids to lists of strings`:`layout.${n} must map ids to strings`))}if(j(e.placements))for(let[n,r]of Object.entries(e.placements))typeof r==`string`&&!de.has(r)&&N(t,`unknown_layout_slot`,`layout.placements.${n}`,`Unknown shell slot "${r}".`);for(let n of[`sections`,`items`,`panels`])e[n]!==void 0&&!fe(e[n],e=>j(e))&&N(t,`invalid_type`,`layout.${n}`,`layout.${n} must map ids to objects`);let n=e.customSections;n!==void 0&&!(Array.isArray(n)&&n.every(e=>j(e)&&typeof e.id==`string`&&typeof e.label==`string`))&&N(t,`invalid_type`,`layout.customSections`,`layout.customSections must be a list of { id, label }`)}function ge(e,t){if(!j(e))return N(t,`invalid_type`,`theme`,`theme must be an object`);e.preset!==void 0&&typeof e.preset!=`string`&&N(t,`invalid_type`,`theme.preset`,`theme.preset must be a string`),e.fontFamily!==void 0&&(typeof e.fontFamily!=`string`||!e.fontFamily)&&N(t,`invalid_value`,`theme.fontFamily`,`theme.fontFamily must be a non-empty string`),e.customCss!==void 0&&(typeof e.customCss==`string`?Array.from(e.customCss).length>65536&&N(t,`invalid_value`,`theme.customCss`,`theme.customCss must be at most 65,536 characters`):N(t,`invalid_type`,`theme.customCss`,`theme.customCss must be a string`)),e.colorScheme!==void 0&&!(typeof e.colorScheme==`string`&&le.has(e.colorScheme))&&N(t,`invalid_value`,`theme.colorScheme`,`theme.colorScheme must be light, dark or system`);for(let n of[`borderRadius`,`density`,`contrast`]){let r=ue[n],i=e[n];i!==void 0&&!(typeof i==`string`&&r.includes(i))&&N(t,`invalid_value`,`theme.${n}`,`theme.${n} must be one of ${r.join(`, `)}`)}let n=e.custom;n!==void 0&&(!j(n)||typeof n.primary!=`string`?N(t,`invalid_value`,`theme.custom`,`theme.custom must be an object with a string primary`):/^#[0-9a-fA-F]{6}$/.test(n.primary)?n.fontFamily!==void 0&&typeof n.fontFamily!=`string`&&N(t,`invalid_type`,`theme.custom.fontFamily`,`theme.custom.fontFamily must be a string`):N(t,`invalid_value`,`theme.custom.primary`,`theme.custom.primary must be a hex colour like #c2410c`))}var _e=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/,ve=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,ye=/^[a-z][a-z0-9-]{0,31}$/,be=e=>e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)||typeof e==`boolean`;function xe(e,t,n){return j(e)?[typeof e.id==`string`&&ve.test(e.id),typeof e.type==`string`&&ye.test(e.type),typeof e.span==`number`&&Number.isInteger(e.span)&&e.span>=1&&e.span<=4,j(e.options)&&Object.values(e.options).every(be),e.version===void 0||typeof e.version==`number`&&Number.isInteger(e.version)&&e.version>=1].every(Boolean)?e:(P(n,`malformed_overview_widget`,t,`${t} was dropped because it is not a valid overview widget`),null):(P(n,`malformed_overview_widget`,t,`${t} was dropped`),null)}function Se(e,t,n){return j(e)?(e.span===void 0||typeof e.span==`number`&&Number.isInteger(e.span)&&e.span>=1&&e.span<=4)&&(e.options===void 0||j(e.options)&&Object.values(e.options).every(be))&&(e.version===void 0||typeof e.version==`number`&&Number.isInteger(e.version)&&e.version>=1)?e:(P(n,`malformed_overview_change`,t,`${t} was dropped because it is not a valid widget change`),null):(P(n,`malformed_overview_change`,t,`${t} was dropped`),null)}function Ce(e,t,n){if(!j(e)||e.version!==1)return P(n,`malformed_overview`,t,`${t} was dropped because it must be an object with version 1`),null;let r={...e,version:1};for(let i of[`order`,`removed`])e[i]!==void 0&&!M(e[i])?(P(n,`malformed_overview_list`,`${t}.${i}`,`${t}.${i} was dropped because it must be a list of strings`),delete r[i]):e[i]!==void 0&&(r[i]=[...new Set(e[i])]);if(e.added!==void 0){if(!Array.isArray(e.added))P(n,`malformed_overview_widgets`,`${t}.added`,`${t}.added was dropped because it must be a list of widgets`),delete r.added;else{let i=e.added.flatMap((e,r)=>{let i=xe(e,`${t}.added[${r}]`,n);return i?[i]:[]});i.length?r.added=i:delete r.added}}if(e.changed!==void 0){if(!j(e.changed)||Object.hasOwn(e.changed,`__proto__`))P(n,`malformed_overview_changes`,`${t}.changed`,`${t}.changed was dropped because it must map widget ids to objects`),delete r.changed;else{let i={};for(let[r,a]of Object.entries(e.changed)){if(!ve.test(r)){P(n,`malformed_overview_change`,`${t}.changed.${r}`,`${t}.changed.${r} was dropped because its widget id is invalid`);continue}let e=Se(a,`${t}.changed.${r}`,n);e&&(i[r]=e)}Object.keys(i).length?r.changed=i:delete r.changed}}return r}function we(e,t={}){let n=[];if(!j(e))return N(n,`invalid_type`,``,`expected a JSON object`),{ok:!1,errors:[`expected a JSON object`],diagnostics:n};let{$schema:r,version:i}=e;r!==void 0&&r!==`https://s-m-r-t.dev/schemas/cookbook/v1.json`&&r!==`https://s-m-r-t.dev/schemas/blueprint/v1.json`&&N(n,`invalid_schema`,`$schema`,`$schema must be ${oe}`),i===void 0?N(n,`missing_field`,`version`,`version is required`):typeof i!=`number`||!Number.isInteger(i)?N(n,`invalid_type`,`version`,`version must be a whole number`):i>1?N(n,`unsupported_version`,`version`,`version ${i} is newer than this reader understands (1)`):i!==1&&N(n,`unsupported_version`,`version`,`version ${i} is not supported`),r===`https://s-m-r-t.dev/schemas/blueprint/v1.json`&&P(n,`migrated_schema`,`$schema`,`$schema uses the legacy blueprint URL; migrated`);for(let t of[`name`,`description`])e[t]!==void 0&&typeof e[t]!=`string`&&N(n,`invalid_type`,t,`${t} must be a string`);let a=[];if(!M(e.recipes))N(n,`invalid_type`,`recipes`,`recipes must be a list of recipe ids`);else if(a=[...new Set(e.recipes)].sort(),t.recipes){let r=new Set(t.recipes);for(let t of a)r.has(t)||N(n,`unknown_recipe`,`recipes[${e.recipes.indexOf(t)}]`,`recipes: unknown recipe "${t}"`)}let o=[];e.features!==void 0&&(M(e.features)?(o=[...new Set(e.features)].sort(),o.length!==e.features.length&&P(n,`duplicate_value`,`features`,`features listed a model more than once; deduplicated`)):N(n,`invalid_type`,`features`,`features must be a list of model names`));let s=[];if(!Array.isArray(e.policies))N(n,`invalid_type`,`policies`,`policies must be a list`);else for(let[t,r]of e.policies.entries())me(r,`policies[${t}]`,n),s.push(r);if(e.exposure!==void 0&&(fe(e.exposure,e=>M(e)&&e.every(e=>ce.has(e)))||N(n,`invalid_value`,`exposure`,`exposure must map model names to lists of api, mcp or cli`)),e.layout!==void 0&&he(e.layout,n),e.theme!==void 0&&ge(e.theme,n),j(e.theme)&&typeof e.theme.preset==`string`){let r=t.themePresets?new Set(t.themePresets):void 0;r&&!r.has(e.theme.preset)&&N(n,`unknown_theme_preset`,`theme.preset`,`Unknown theme preset "${e.theme.preset}".`)}if(j(e.layout)&&e.layout.version===1&&t.layout){let r=t.layout.sections?new Set(t.layout.sections):void 0,i=t.layout.items?new Set(t.layout.items):void 0,a=t.layout.placementItems?new Set(t.layout.placementItems):void 0;if(r&&Array.isArray(e.layout.customSections))for(let t of e.layout.customSections)j(t)&&typeof t.id==`string`&&r.add(t.id);let o=(e,t)=>t===`section`?r?.has(e)!==!1:t===`item`?i?.has(e)!==!1:r?.has(e)===!0||i?.has(e)===!0||!r&&!i,s=(e,t,r)=>{typeof e==`string`&&!o(e,r)&&N(n,`unknown_layout_id`,t,`Unknown layout ${r===`either`?`section or item`:r} "${e}".`)};if(M(e.layout.sectionOrder)&&e.layout.sectionOrder.forEach((e,t)=>{s(e,`layout.sectionOrder[${t}]`,`section`)}),M(e.layout.hidden)&&e.layout.hidden.forEach((e,t)=>{s(e,`layout.hidden[${t}]`,`either`)}),j(e.layout.itemOrder))for(let[t,n]of Object.entries(e.layout.itemOrder))s(t,`layout.itemOrder.${t}`,`section`),M(n)&&n.forEach((e,n)=>{s(e,`layout.itemOrder.${t}[${n}]`,`item`)});if(j(e.layout.moved))for(let[t,n]of Object.entries(e.layout.moved))s(t,`layout.moved.${t}`,`item`),s(n,`layout.moved.${t}`,`section`);for(let t of[`sections`,`items`])if(j(e.layout[t]))for(let n of Object.keys(e.layout[t]))s(n,`layout.${t}.${n}`,t===`sections`?`section`:`item`);if(j(e.layout.placements))for(let t of Object.keys(e.layout.placements))a&&!a.has(t)&&N(n,`unknown_layout_id`,`layout.placements.${t}`,`Unknown layout placement item "${t}".`)}let c={};if(e.overviews!==void 0){if(!j(e.overviews)||Object.hasOwn(e.overviews,`__proto__`))N(n,`invalid_type`,`overviews`,`overviews must map overview ids to overrides`);else{let r=t.overviewIds?new Set(t.overviewIds):void 0;for(let[i,a]of Object.entries(e.overviews)){let e=`overviews.${i}`;if(!_e.test(i)){P(n,`invalid_overview_id`,e,`${e} was dropped because its overview id is invalid`);continue}if(r&&!r.has(i)){P(n,`unknown_overview`,e,`Unknown overview "${i}" was dropped.`);continue}let o=Ce(a,e,n);if(!o)continue;if(!t.validateOverview){c[i]=o;continue}let s;try{s=t.validateOverview(i,o)}catch{P(n,`overview_validation_failed`,e,`Overview "${i}" was dropped because its host validator failed.`);continue}for(let t of s.diagnostics??[])P(n,t.code,t.path||e,t.message);!s.ok&&s.diagnostics.length===0&&P(n,`overview_rejected`,e,`Overview "${i}" was rejected by its host validator and dropped.`),s.ok&&s.override&&(c[i]=s.override)}}}let l=n.filter(e=>e.severity===`error`).map(e=>e.message);if(l.length)return{ok:!1,errors:l,diagnostics:n};let u={...e,$schema:oe,version:1,recipes:a,features:o,policies:s};return e.exposure!==void 0&&(u.exposure=e.exposure),e.layout!==void 0&&(u.layout=e.layout),e.theme!==void 0&&(u.theme=e.theme),delete u.overviews,Object.keys(c).length&&(u.overviews=c),{ok:!0,cookbook:u,warnings:n.filter(e=>e.severity===`warning`).map(e=>e.message),diagnostics:n}}var F=e=>e===void 0?e:structuredClone(e),Te=(e,t)=>JSON.stringify(e??null)===JSON.stringify(t??null),Ee=()=>({$schema:oe,version:1,recipes:[],features:[],policies:[]});function De(e){return!e.recipes.length&&!e.features.length&&!e.policies.length&&!Object.keys(e.exposure??{}).length&&!e.layout&&!e.theme&&!Object.keys(e.overviews??{}).length}var Oe=e=>[...new Set(e)].sort();function ke(e){let t=new Set([`$schema`,`version`,`name`,`description`,`recipes`,`features`,`policies`,`exposure`,`layout`,`theme`,`overviews`]),n={$schema:oe,version:1,...e.name?{name:e.name}:{},...e.description?{description:e.description}:{},recipes:Oe(e.recipes),features:Oe(e.features),policies:[...e.policies].sort((e,t)=>e.objectRef.localeCompare(t.objectRef)||e.fieldName.localeCompare(t.fieldName)).map(e=>({...e}))},r=Object.fromEntries(Object.keys(e.exposure??{}).sort().filter(t=>e.exposure?.[t]?.length).map(t=>[t,[...e.exposure?.[t]??[]].sort()]));Object.keys(r).length&&(n.exposure=r),e.layout&&(n.layout=F(e.layout));let i=Xe(e.theme);i&&(n.theme=i);let a=Object.entries(e.overviews??{}).sort(([e],[t])=>e<t?-1:+(e>t));a.length&&(n.overviews=Object.fromEntries(a.map(([e,t])=>[e,F(t)])));for(let[r,i]of Object.entries(e))t.has(r)||(n[r]=F(i));return n}var I=e=>new Map(e.recipes.map(e=>[e.id,e]));function Ae(e,t){let n=new Set,r=e=>{let i=t.get(e);if(i&&!n.has(e)){n.add(e);for(let e of i.requires)r(e)}};for(let t of e)r(t);let i=!0;for(;i;){i=!1;for(let e of[...n])for(let a of t.get(e)?.requiresAny??[]){if(a.some(e=>n.has(e)))continue;let e=a.find(e=>t.has(e));e&&(r(e),i=!0)}}return Oe(n)}function je(e,t){let n=I(e);return new Set([...t.recipes.flatMap(e=>n.get(e)?.models??[]),...t.features])}function Me(e){return e.settingTargets??S}function Ne(e,t){return Object.values(Me(e)).some(e=>e.some(e=>e.model===t.objectRef&&e.field===t.fieldName))}function Pe(e,t){let n=je(e,t),r={...t,policies:t.policies.filter(t=>n.has(t.objectRef)||Ne(e,t))};if(t.exposure){let e=Object.fromEntries(Object.entries(t.exposure).filter(([e])=>n.has(e)));Object.keys(e).length?r.exposure=e:delete r.exposure}return r}var Fe=(e,t)=>{let n=I(e);return t.recipes.filter(e=>n.has(e))},Ie=(e,t)=>{let n=I(e);return t.recipes.filter(e=>!n.has(e))};function Le(e,t){let n=new Set(e),r=new Set(t);return{added:t.filter(e=>!n.has(e)),removed:e.filter(e=>!r.has(e))}}function Re(e,t,n){let r=I(e),i=Fe(e,t),a=Ae([...i,...n],r);return{doc:{...t,recipes:Oe([...a,...Ie(e,t)])},changes:{...Le(i,a),kept:[]}}}function ze(e,t,n){let r=I(e),i=Fe(e,t),a=new Set(n),o=Ae(i.filter(e=>!a.has(e)),r),s=Pe(e,{...t,recipes:Oe([...o,...Ie(e,t)])}),{added:c,removed:l}=Le(i,o);return{doc:s,changes:{added:c,removed:l,kept:n.filter(e=>o.includes(e)&&i.includes(e))}}}function Be(e,t,n,r){let i=new Set(t.features);for(let e of n)r?i.add(e):i.delete(e);let a=[...i].sort(),o={...t,features:a};return r||(o=Pe(e,o)),{doc:o,changes:{...Le(t.features,a),kept:[]}}}var Ve=(e,t)=>({added:[...e.added,...t.added],removed:[...e.removed,...t.removed],kept:[...e.kept,...t.kept]}),He={currency:`USD`,taxRate:0,paymentTerms:``,pricesIncludeTax:!1,taxRounding:`line`},Ue=[`currency`,`taxRate`,`paymentTerms`,`pricesIncludeTax`,`taxRounding`];function We(e){if(e?.defaultValue!==void 0&&e.defaultValue!==null)try{return JSON.parse(e.defaultValue)}catch{return}}var Ge=(e,t,n)=>e.find(e=>e.scopeType===`app`&&e.objectRef===t&&e.fieldName===n);function Ke(e,t){let n=Me(e),r={...He},i=(e,r)=>{for(let{model:i,field:a}of n[e]){let e=We(Ge(t.policies,i,a));if(typeof e===r)return e}},a=i(`currency`,`string`),o=i(`taxRate`,`number`),s=i(`paymentTerms`,`string`),c=i(`pricesIncludeTax`,`string`),l=i(`taxRounding`,`string`);return typeof a==`string`&&(r.currency=a),typeof o==`number`&&(r.taxRate=o),typeof s==`string`&&(r.paymentTerms=s),(c===`inclusive`||c===`exclusive`)&&(r.pricesIncludeTax=c===`inclusive`),(l===`line`||l===`document`)&&(r.taxRounding=l),r}var qe=e=>e==null||e===``;function Je(e,t,n,r){let i=I(e);for(let e of t.recipes){let t=i.get(e)?.options?.[n]?.fields?.[r];if(t&&`default`in t)return t.default}return A(e,n)?.fields?.find(e=>e.name===r)?.default}function Ye(e,t,n){let r=Me(e),i=t.policies.map(e=>({...e}));for(let a of Ue){let o=n[a],s=a===`paymentTerms`?String(o).trim():a===`currency`?String(o).trim().toUpperCase():a===`pricesIncludeTax`?o?`inclusive`:`exclusive`:o;for(let{model:n,field:o}of r[a]){let r=Je(e,t,n,o),c=!qe(s)&&!(!qe(r)&&r===s)&&!(qe(r)&&a===`taxRate`&&s===0),l=Ge(i,n,o);if(c){let e=JSON.stringify(s);l?l.defaultValue=e:i.push({objectRef:n,fieldName:o,scopeType:`app`,defaultValue:e})}else l&&(delete l.defaultValue,Object.keys(l).length<=3&&(i=i.filter(e=>e!==l)))}}return{...t,policies:i}}function Xe(e){if(!e)return;let t={};return e.preset&&(t.preset=e.preset),e.colorScheme&&(t.colorScheme=e.colorScheme),e.borderRadius&&(t.borderRadius=e.borderRadius),e.density&&(t.density=e.density),e.contrast&&(t.contrast=e.contrast),e.fontFamily&&(t.fontFamily=e.fontFamily),e.custom&&(t.custom={...e.custom}),e.customCss&&(t.customCss=e.customCss),Object.keys(t).length?t:void 0}function Ze(e){let t=e?.colorScheme??`system`,n=e?.custom?`brand colour ${e.custom.primary}`:e?.preset??`smrt`;return t===`system`?n:`${n}, ${t}`}function Qe(e,t){let n={...e.theme??{}};t.preset&&(n.preset=t.preset,delete n.custom),t.primary&&(n.custom={primary:t.primary.toLowerCase(),...e.theme?.custom?.fontFamily?{fontFamily:e.theme.custom.fontFamily}:{}}),t.colorScheme&&(n.colorScheme=t.colorScheme),t.borderRadius&&(n.borderRadius=t.borderRadius),t.density&&(n.density=t.density),t.contrast&&(n.contrast=t.contrast),t.fontFamily===null?(delete n.fontFamily,n.custom?.fontFamily&&(n.custom={primary:n.custom.primary})):t.fontFamily!==void 0&&(n.fontFamily=t.fontFamily);let r=Xe(n),i={...e};return r?i.theme=r:delete i.theme,i}function $e(e,t){let n=[],r=(e,t,r,i)=>n.push({severity:e,code:t,path:r,message:i}),i=we(t);if(!i.ok){for(let e of i.diagnostics.filter(e=>e.severity===`error`))r(`error`,`invalid_document`,e.path,e.message);return n}for(let e of i.diagnostics)r(e.severity,e.code===`migrated_schema`?`migrated`:e.code,e.path,e.message);let a=i.cookbook,o=I(e),s=te(e,{...a,layout:void 0}),c=we(a,{themePresets:e.themePresets??b,layout:{sections:s.map(e=>e.id),items:s.flatMap(e=>e.items.map(e=>e.id)),...e.placementItems?{placementItems:e.placementItems}:{}},overviewIds:[...s.map(e=>e.id),...(a.layout?.customSections??[]).map(e=>e.id)]});for(let e of c.diagnostics)(e.code===`unknown_theme_preset`||e.code===`unknown_layout_id`||e.code===`unknown_overview`)&&r(e.code===`unknown_layout_id`&&!e.path.startsWith(`layout.placements.`)?`warning`:e.severity,e.code===`unknown_theme_preset`?`unknown_preset`:e.code,e.path,e.message);for(let[e,t]of a.recipes.entries())o.has(t)||r(`error`,`unknown_recipe`,`recipes[${e}]`,`Unknown recipe "${t}".`);let l=new Set(Ae(a.recipes,o));for(let e of l)a.recipes.includes(e)||r(`error`,`missing_requirement`,`recipes`,`A recipe needs "${e}", which is not listed.`);for(let[t,n]of a.features.entries()){let i=A(e,n);i?i.exposed===!1&&r(`error`,`model_not_exposed`,`features[${t}]`,`${n} cannot be added as a feature.`):r(`error`,`unknown_model`,`features[${t}]`,`Unknown model "${n}".`)}let u=je(e,a);for(let[t,n]of a.policies.entries()){let i=`policies[${t}]`,a=A(e,n.objectRef);a?(a.fields&&!a.fields.some(e=>e.name===n.fieldName&&!e.system)&&r(`error`,`unknown_field`,`${i}.fieldName`,`${a.name} has no field "${n.fieldName}".`),!u.has(n.objectRef)&&!Ne(e,n)&&r(`warning`,`policy_not_covered`,i,`${a.name} is not in the app, so this row has no effect.`)):r(`error`,`unknown_model`,`${i}.objectRef`,`Unknown model "${n.objectRef}".`)}for(let t of Object.keys(a.exposure??{}))A(e,t)||r(`error`,`unknown_model`,`exposure.${t}`,`Unknown model "${t}".`);return n}var L=(e,t,n={})=>({ok:!1,error:{code:e,message:t,...n}}),R=(e,t=``,n={})=>({ok:!0,state:e,summary:t,...n}),et=`This replaces the recipes, options, menu and look. Send replace: true to confirm.`,z=e=>e.join(`, `);function tt(e){return`${(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`my-app`}.cookbook.json`}var nt=e=>`${JSON.stringify(e,null,2)}\n`;function rt(e,t){let n=new Map(e.recipes.map(e=>[e.id,e])),r=t.recipes.filter(e=>n.has(e)),i=t.recipes.filter(e=>!n.has(e));return ke(Pe(e,{...F(t),recipes:[...Ae(r,n),...i]}))}function it(e,t){return t?e.cookbooks?.find(e=>e.id===t)?.name:void 0}var at=(e,t)=>{let n=t=>e.recipes.find(e=>e.id===t)?.label??t;return[t.added.length?`Added ${z(t.added.map(n))}.`:``,t.removed.length?`Removed ${z(t.removed.map(n))}.`:``,t.kept.length?`Kept ${z(t.kept.map(n))} (needed).`:``].filter(Boolean).join(` `)},ot=(e,t)=>[t.added.length?`Added ${z(t.added.map(t=>O(e,t)))}.`:``,t.removed.length?`Removed ${z(t.removed.map(t=>O(e,t)))}.`:``].filter(Boolean).join(` `),st=e=>`${Number((e*100).toFixed(4))}%`,B=(e,t)=>({...e,doc:ke(t)});function ct(e,t){let n=te(e,t);return{sections:n,section:e=>n.find(t=>t.id===e),item:e=>n.flatMap(e=>e.items).find(t=>t.id===e)}}var lt=(e,t)=>{let n={...e};return t?n.layout=t:delete n.layout,n},ut={add_recipes(e,t,{ids:n}){let r=n.filter(t=>!e.recipes.some(e=>e.id===t));if(r.length)return L(`not_found`,`No such recipe: ${z(r)}.`,{path:`input.ids`});let{doc:i,changes:a}=Re(e,t.doc,n);return R(B(t,i),at(e,a),{changes:a})},remove_recipes(e,t,{ids:n}){let{doc:r,changes:i}=ze(e,t.doc,n);return R(B(t,r),at(e,i),{changes:i})},add_features(e,t,{ids:n}){let r=n.filter(t=>!A(e,t)?.exposed);if(r.length)return L(`not_found`,`No such model to add: ${z(r)}.`,{path:`input.ids`});let{doc:i,changes:a}=Be(e,t.doc,n,!0);return R(B(t,i),ot(e,a),{changes:a})},remove_features(e,t,{ids:n}){let{doc:r,changes:i}=Be(e,t.doc,n,!1);return R(B(t,r),ot(e,i),{changes:i})},add_cookbook(e,t,{id:n}){let r=e.cookbooks?.find(e=>e.id===n);if(!r)return L(`not_found`,`No cookbook "${n}".`,{path:`input.id`});let i=Re(e,t.doc,r.document.recipes),a=Be(e,i.doc,r.document.features.filter(t=>A(e,t)?.exposed),!0),o=Ve(i.changes,a.changes);return R(B(t,a.doc),o.added.length?`Added the ${r.name} cookbook.`:``,{changes:o})},remove_cookbook(e,t,{id:n}){let r=e.cookbooks?.find(e=>e.id===n);if(!r)return L(`not_found`,`No cookbook "${n}".`,{path:`input.id`});let i=ze(e,t.doc,r.document.recipes),a=Be(e,i.doc,r.document.features,!1),o=Ve(i.changes,a.changes);return R(B(t,a.doc),[at(e,i.changes),ot(e,a.changes)].filter(Boolean).join(` `),{changes:o})},apply_cookbook(e,t,{id:n,replace:r}){let i=e.cookbooks?.find(e=>e.id===n);return i?!r&&!De(t.doc)?L(`confirmation_required`,et):R({doc:rt(e,i.document),applied:n},`${i.name} set up.`):L(`not_found`,`No cookbook "${n}".`,{path:`input.id`})},import_cookbook(e,t,{document:n,replace:r}){let i=we(n);if(!i.ok)return L(`invalid_input`,i.errors[0]??`Not a cookbook.`,{path:`input.document`,details:{errors:i.errors}});if(!r&&!De(t.doc))return L(`confirmation_required`,et);let a=i.cookbook.recipes.length;return R({doc:rt(e,i.cookbook),applied:null},`Imported ${a} ${a===1?`recipe`:`recipes`}.`,i.warnings.length?{warnings:i.warnings}:{})},set_settings(e,t,n){let r=Ke(e,t.doc),i={...r},a=[];if(n.currency!==void 0){let t=n.currency.trim().toUpperCase();if(e.currencies&&!e.currencies.includes(t))return L(`invalid_input`,`${t} is not a known currency.`,{path:`input.currency`});if(!/^[A-Z]{3}$/.test(t))return L(`invalid_input`,`currency must be a three-letter code.`,{path:`input.currency`});t!==r.currency&&(i.currency=t,a.push(`currency ${t}`))}if(n.taxRate!==void 0){let e=Number((n.taxRate/100).toFixed(6));e!==r.taxRate&&(i.taxRate=e,a.push(`tax ${st(e)}`))}if(n.paymentTerms!==void 0){let e=[...n.paymentTerms].map(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127?` `:e).join(``).trim();if(!e)return L(`invalid_input`,`paymentTerms must not be empty.`,{path:`input.paymentTerms`});e!==r.paymentTerms&&(i.paymentTerms=e,a.push(`terms ${e}`))}if(n.pricesIncludeTax!==void 0&&n.pricesIncludeTax!==r.pricesIncludeTax&&(i.pricesIncludeTax=n.pricesIncludeTax,a.push(n.pricesIncludeTax?`prices include tax`:`prices exclude tax`)),n.taxRounding!==void 0&&n.taxRounding!==r.taxRounding&&(i.taxRounding=n.taxRounding,a.push(`${n.taxRounding} tax rounding`)),!a.length)return R(t);let o=a.join(`, `);return R(B(t,Ye(e,t.doc,i)),`${o[0].toUpperCase()}${o.slice(1)}.`)},set_policy(e,t,n){let r=A(e,n.model);if(!r)return L(`not_found`,`No such model: ${n.model}.`,{path:`input.model`});if(r.fields){let e=r.fields.find(e=>e.name===n.field);if(!e||e.system)return L(`not_found`,`${r.name} has no field ${n.field}.`,{path:`input.field`})}if(!je(e,t.doc).has(r.id))return L(`not_found`,`${D(r.name)} is not in the app yet; add its recipe or feature first.`,{path:`input.model`});if(t.doc.recipes.some(t=>e.recipes.find(e=>e.id===t)?.options?.[r.id]?.fields?.[n.field]?.locked))return L(`failed`,`${n.field} is locked by its recipe.`,{path:`input.field`});let i=t.doc.policies.map(e=>({...e})),a=i.find(e=>e.objectRef===r.id&&e.fieldName===n.field),o=a??{objectRef:r.id,fieldName:n.field,scopeType:`app`},s=JSON.stringify(o);for(let e of[`visibility`,`label`,`help`]){let t=n[e];t!==void 0&&(t===null?delete o[e]:o[e]=t)}if(n.defaultValue!==void 0){if(n.defaultValue===null)delete o.defaultValue;else{let e=JSON.stringify(n.defaultValue);if(e===void 0)return L(`invalid_input`,`defaultValue is not a JSON value.`,{path:`input.defaultValue`});o.defaultValue=e}}let c=Object.keys(o).length<=3;if(JSON.stringify(o)===s||c&&!a)return R(t);let l=i.filter(e=>e!==a);return R(B(t,{...t.doc,policies:c?l:[...l,o]}),`Updated ${D(r.name)} ${n.field}.`)},set_theme(e,t,n){let r=Qe(t.doc,n);return JSON.stringify(ke(r).theme??null)===JSON.stringify(t.doc.theme??null)?R(t):R(B(t,r),`Theme: ${Ze(ke(r).theme)}.`)},reset_theme(e,t){if(!t.doc.theme)return R(t);let n={...t.doc};return delete n.theme,R(B(t,n),`Theme: default.`)},set_name(e,t,n){let r={...t.doc};for(let e of[`name`,`description`]){let t=n[e];if(t===void 0)continue;let i=t?.trim();i?r[e]=i:delete r[e]}return JSON.stringify(ke(r))===JSON.stringify(t.doc)?R(t):R(B(t,r),n.name?`Named the app ${n.name.trim()}.`:`Updated the app details.`)},rename_section(e,t,{id:n,label:r}){let i=ct(e,t.doc).section(n);if(!i)return L(`not_found`,`No menu section "${n}".`,{path:`input.id`});let a=re(t.doc.layout,i,r);return JSON.stringify(a??null)===JSON.stringify(t.doc.layout??null)?R(t):R(B(t,lt(t.doc,a)),`Renamed the section to ${r.trim()}.`)},rename_item(e,t,{id:n,label:r}){let i=ct(e,t.doc).item(n);if(!i)return L(`not_found`,`No menu entry "${n}".`,{path:`input.id`});let a=ie(t.doc.layout,i,r);return JSON.stringify(a??null)===JSON.stringify(t.doc.layout??null)?R(t):R(B(t,lt(t.doc,a)),r?`Renamed the entry to ${r.trim()}.`:`Entry name restored.`)},hide(e,t,{id:n}){let r=ct(e,t.doc);return r.section(n)??r.item(n)?t.doc.layout?.hidden?.includes(n)?R(t):R(B(t,lt(t.doc,ae(t.doc.layout,n,!0))),`Hidden.`):L(`not_found`,`No menu section or entry "${n}".`,{path:`input.id`})},show(e,t,{id:n}){let r=ct(e,t.doc);return!r.section(n)&&!r.item(n)?L(`not_found`,`No menu section or entry "${n}".`,{path:`input.id`}):t.doc.layout?.hidden?.includes(n)?R(B(t,lt(t.doc,ae(t.doc.layout,n,!1))),`Shown.`):R(t)},validate(e,t){let n=$e(e,t.doc);return R(t,``,{data:{ok:!n.some(e=>e.severity===`error`),diagnostics:n}})},export_cookbook(e,t,{name:n}){return R(t,``,{data:{fileName:tt(n??t.doc.name??it(e,t.applied)),text:nt(t.doc),cookbook:F(t.doc)}})}};function dt(e,t,n,r){let i=ut[n];return i?i(e,t,r):L(`unknown_command`,`No command "${n}".`)}var ft=(e,t)=>({type:`array`,description:e,minItems:1,maxItems:50,items:t?.length?{type:`string`,enum:[...t]}:{type:`string`,minLength:1}}),pt=(e,t={})=>({type:`string`,description:e,minLength:1,maxLength:200,...t}),V=(e,t=[])=>({type:`object`,properties:e,...t.length?{required:t}:{},additionalProperties:!1});function mt(e){let t=e.recipes.map(e=>e.id),n=(e.cookbooks??[]).map(e=>e.id),r=e.themePresets??b,i=e=>({type:`string`,description:e,...n.length?{enum:[...n]}:{minLength:1}}),a=e=>pt(`The id of ${e}, as the plan snapshot's "sections" lists it.`),o={type:`boolean`,description:`Confirm replacing what is there.`};return[{name:`add_recipes`,description:`Switch recipes on. Recipes they require come along. Returns what was added.`,inputSchema:V({ids:ft(`Recipe ids to add.`,t)},[`ids`])},{name:`remove_recipes`,description:`Switch recipes off. A recipe another one needs is kept and reported.`,inputSchema:V({ids:ft(`Recipe ids to remove.`,t)},[`ids`])},{name:`add_features`,description:"Add single models no recipe covers, by qualified name (`@scope/pkg:Class`).",inputSchema:V({ids:ft(`Qualified model names to add.`)},[`ids`])},{name:`remove_features`,description:`Remove single models added with add_features.`,inputSchema:V({ids:ft(`Qualified model names to remove.`)},[`ids`])},{name:`add_cookbook`,description:`Add the recipes and features of a ready-made cookbook to the current app. Nothing is replaced.`,inputSchema:V({id:i(`The cookbook to add.`)},[`id`])},{name:`remove_cookbook`,description:`Remove the recipes and features a ready-made cookbook adds. Ones another recipe needs are kept.`,inputSchema:V({id:i(`The cookbook to remove.`)},[`id`])},{name:`apply_cookbook`,description:`Select a ready-made cookbook: replace the whole app (recipes, options, menu, theme) with it. When the app has anything in it, replace must be true.`,inputSchema:V({id:i(`The cookbook to set up.`),replace:o},[`id`])},{name:`import_cookbook`,description:`Replace the whole app with a cookbook document (version 1). Checked strictly; nothing is applied if it is invalid. When the app has anything in it, replace must be true.`,inputSchema:V({document:{type:`object`,description:`A cookbook document, version 1.`},replace:o},[`document`])},{name:`set_settings`,description:`Change app settings: currency, default tax rate (percent), default payment terms. Applies to new records only.`,inputSchema:V({currency:e.currencies?.length?{type:`string`,description:`ISO 4217 code, e.g. CAD.`,enum:[...e.currencies]}:{type:`string`,description:`ISO 4217 code, e.g. CAD.`,pattern:`^[A-Z]{3}$`},taxRate:{type:`number`,description:`Default tax rate in percent, 0 to 100.`,minimum:0,maximum:100},paymentTerms:{type:`string`,description:`Default payment terms, e.g. "Net 30".`,minLength:1,maxLength:40},pricesIncludeTax:{type:`boolean`,description:`Whether new document prices include tax.`},taxRounding:{enum:[`line`,`document`],description:`Whether tax rounds per line or per document.`}})},{name:`set_policy`,description:`Set one field's policy: default value, visibility, label or help. The model must be covered by a recipe or feature that is on. null clears a part.`,inputSchema:V({model:pt(`Qualified model name, e.g. @happyvertical/smrt-commerce:Order.`),field:pt(`The model field name.`),defaultValue:{description:`The default as a JSON value (a string, number or boolean). null clears it.`},visibility:{enum:[`basic`,`advanced`,`hidden`,null],description:`Whether the field shows in forms and lists.`},label:{type:[`string`,`null`],description:`A different label.`,maxLength:120},help:{type:[`string`,`null`],description:`Help text under the field.`,maxLength:400}},[`model`,`field`])},{name:`set_theme`,description:`Change the look: a preset, a brand colour, light or dark. A preset replaces a brand colour.`,inputSchema:V({preset:{enum:[...r],description:`A built-in theme.`},primary:{type:`string`,description:`Brand colour as #rrggbb.`,pattern:`^#[0-9a-fA-F]{6}$`},colorScheme:{enum:[`light`,`dark`,`system`],description:`Light, dark or follow the device.`},fontFamily:{type:[`string`,`null`],minLength:1,description:`Font key. Null restores the preset font.`},borderRadius:{enum:[`none`,`sm`,`md`,`lg`,`xl`,`full`],description:`Corner roundness.`},density:{enum:[`comfortable`,`touch`],description:`Control size: comfortable, or larger touch targets.`},contrast:{enum:[`auto`,`standard`,`more`],description:`Contrast: auto follows the device, or force standard or more.`}})},{name:`reset_theme`,description:`Go back to the default look.`,inputSchema:V({})},{name:`set_name`,description:`Name and describe the app. null clears a part.`,inputSchema:V({name:{type:[`string`,`null`],minLength:1,maxLength:60},description:{type:[`string`,`null`],minLength:1,maxLength:400}})},{name:`rename_section`,description:`Rename a menu section.`,inputSchema:V({id:a(`the section`),label:pt(`The new name.`,{maxLength:60})},[`id`,`label`])},{name:`rename_item`,description:`Rename a menu entry. A null label restores its own name.`,inputSchema:V({id:a(`the entry`),label:{type:[`string`,`null`],minLength:1,maxLength:60}},[`id`,`label`])},{name:`hide`,description:`Hide a menu section or entry. Nothing is deleted.`,inputSchema:V({id:a(`the section or entry`)},[`id`])},{name:`show`,description:`Show a hidden menu section or entry again.`,inputSchema:V({id:a(`the section or entry`)},[`id`])},{name:`validate`,description:`Check the current cookbook against the catalog and report typed diagnostics. Changes nothing.`,inputSchema:V({})},{name:`export_cookbook`,description:`The cookbook as a <name>.cookbook.json file (text in the result). Changes nothing.`,inputSchema:V({name:pt(`A name for the file.`,{maxLength:60})})},{name:`undo`,description:`Undo an earlier change by the undoId its receipt carried. Refused with a conflict when the plan changed since, unless force is true.`,inputSchema:V({undoId:pt(`The undoId from a receipt.`),force:{type:`boolean`,description:`Undo even after later edits.`}},[`undoId`])}]}function ht(e){return{name:`run_batch`,description:`Run several commands as one atomic batch: all apply or none does. A failure names the command and leaves the plan unchanged.`,inputSchema:{type:`object`,properties:{id:{type:`string`,minLength:1,maxLength:200},expectedRevision:{type:`integer`,minimum:0},commands:{type:`array`,minItems:1,maxItems:50,items:{oneOf:mt(e).map(e=>({type:`object`,properties:{name:{const:e.name},input:e.inputSchema},required:[`name`],additionalProperties:!1}))}}},required:[`commands`],additionalProperties:!1}}}var gt=e=>e===null?`null`:Array.isArray(e)?`array`:Number.isInteger(e)?`integer`:typeof e;function _t(e,t){let n=gt(t);return n===e||e===`number`&&n===`integer`}function vt(e,t,n=`input`){let r=e=>({path:n,message:`${n} ${e}`}),i=e.type;if(i){let e=Array.isArray(i)?i:[i];if(!e.some(e=>_t(e,t)))return r(`must be ${e.join(` or `)}`)}let a=e.enum;if(a&&!a.includes(t))return r(a.length>12?`is not a known value`:`must be one of ${a.map(e=>JSON.stringify(e)).join(`, `)}`);if(typeof t==`string`){let{minLength:n,maxLength:i,pattern:a}=e;if(n!==void 0&&t.length<n)return r(`must not be empty`);if(i!==void 0&&t.length>i)return r(`must be at most ${i} characters`);if(a&&!new RegExp(a).test(t))return r(`has the wrong format`)}if(typeof t==`number`){let{minimum:n,maximum:i}=e;if(!Number.isFinite(t))return r(`must be a finite number`);if(n!==void 0&&t<n)return r(`must be at least ${n}`);if(i!==void 0&&t>i)return r(`must be at most ${i}`)}if(Array.isArray(t)){let{minItems:i,maxItems:a,items:o}=e;if(i!==void 0&&t.length<i)return r(`needs at least ${i} item${i===1?``:`s`}`);if(a!==void 0&&t.length>a)return r(`takes at most ${a} items`);if(o)for(let[e,r]of t.entries()){let t=vt(o,r,`${n}[${e}]`);if(t)return t}}if(gt(t)===`object`){let r=t,{properties:i,required:a,additionalProperties:o}=e;for(let e of a??[])if(r[e]===void 0)return{path:`${n}.${e}`,message:`${n}.${e} is required`};for(let[e,t]of Object.entries(r)){let r=i?.[e];if(!r){if(o===!1)return{path:`${n}.${e}`,message:`${n}.${e} is not an option of this command`};continue}if(t===void 0)continue;let a=vt(r,t,`${n}.${e}`);if(a)return a}}return null}function yt(e){return Object.fromEntries(mt(e).map(e=>[e.name,e.inputSchema]))}var H=(e,t,n={})=>({code:e,message:t,...n}),bt=e=>Array.isArray(e)?e.map(bt):e&&typeof e==`object`?Object.fromEntries(Object.keys(e).sort().map(t=>[t,bt(e[t])])):e,xt=e=>{try{return JSON.stringify(bt(e))??`undefined`}catch{return`unserializable`}};function St(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return{ok:!1,error:H(`unknown_command`,`A command is an object: { name, input }.`)};let r=e,{name:i,input:a={}}=r;if(typeof i!=`string`||!Object.hasOwn(t,i))return{ok:!1,error:H(`unknown_command`,`Unknown command ${JSON.stringify(i)}.`)};for(let e of Object.keys(r))if(e!==`name`&&e!==`input`&&!n.includes(e))return{ok:!1,error:H(`invalid_input`,`${e} is not part of a command.`,{path:e})};let o=vt(t[i],a);return o?{ok:!1,error:H(`invalid_input`,o.message,{path:o.path})}:{ok:!0,name:i,input:a}}var Ct=e=>e===void 0||typeof e==`string`&&e.length>0&&e.length<=200?null:H(`invalid_input`,`id must be a non-empty string of at most 200 characters.`,{path:`id`}),wt=e=>e===void 0||Number.isInteger(e)&&e>=0?null:H(`invalid_input`,`expectedRevision must be a whole number.`,{path:`expectedRevision`});function Tt(e){let{catalog:t}=e,n=yt(t),r=mt(t),i=ht(t),a=e.maxJournal??500,o=e.maxUndo??20,s,c=0,l=new Map;if(e.state){let n=e.state,r=we(n.cookbook);if(!r.ok)throw Error(`Invalid saved cookbook: ${r.errors.join(`; `)}`);if(!Number.isInteger(n.revision)||n.revision<0)throw Error(`Invalid saved revision.`);s={doc:rt(t,r.cookbook),applied:n.applied??null},c=n.revision;for(let e of n.journal??[])l.set(e.id,F(e))}else if(e.cookbook!==void 0){let n=we(e.cookbook);if(!n.ok)throw Error(`Invalid cookbook: ${n.errors.join(`; `)}`);s={doc:rt(t,n.cookbook),applied:null}}else s={doc:rt(t,Ee()),applied:null};let u=new Map,d=[],f=0,p=new Map;function m(e,n){let{doc:r}=e,i=new Map(t.recipes.map(e=>[e.id,e])),a=Ke(t,r),o=new Set(t.models.filter(e=>e.exposed!==!1).map(e=>e.id));return{version:1,revision:n,app:{name:r.name??it(t,e.applied)??`my-app`,description:r.description??null,cookbook:e.applied},recipes:r.recipes.flatMap(e=>{let t=i.get(e);return t?[{id:e,label:t.label}]:[]}),features:r.features.filter(e=>o.has(e)),unavailable:[...r.recipes.filter(e=>!i.has(e)),...r.features.filter(e=>!o.has(e))],settings:{currency:a.currency,taxRate:Number((a.taxRate*100).toFixed(4)),paymentTerms:a.paymentTerms,pricesIncludeTax:a.pricesIncludeTax,taxRounding:a.taxRounding},theme:{text:Ze(r.theme),preset:r.theme?.preset??null,primary:r.theme?.custom?.primary??null,colorScheme:r.theme?.colorScheme??`system`,borderRadius:r.theme?.borderRadius??null,density:r.theme?.density??null,contrast:r.theme?.contrast??null},sections:te(t,r).map(e=>({id:e.id,label:e.label,hidden:e.hidden,items:e.items.map(e=>({id:e.id,label:e.label,hidden:e.hidden}))})),policies:r.policies.length,undo:[...d]}}let h=()=>m(s,c);function g(){for(let[e,t]of p)t!==c&&(p.set(e,c),e(h()))}function _(e,t,n){if(e!==void 0)for(l.set(e,{id:e,fingerprint:t,result:F(n)});l.size>a;){let e=l.keys().next().value;if(e===void 0)break;l.delete(e)}}function v(e,t){if(e===void 0)return null;let n=l.get(e);return n?n.fingerprint===t?{...F(n.result),replayed:!0}:{ok:!1,id:e,error:H(`id_reuse`,`The id "${e}" was already used for a different command.`,{path:`id`})}:null}function y(t,n){let r=`${e.undoPrefix??`undo`}-${++f}`;u.set(r,{before:F(t),after:F(n)}),d=[...d,r].slice(-o);for(let e of[...u.keys()])d.includes(e)||u.delete(e);return r}let b=(e,t)=>e.applied!==t.applied||!Te(e.doc,t.doc);function x(e,t,n,r,i,a,o){return{ok:!0,...e===void 0?{}:{id:e},snapshot:a,receipt:{name:t,...e===void 0?{}:{id:e},summary:i===r?``:n.summary,changed:i!==r,revisionBefore:r,revisionAfter:i,...o?{undoId:o}:{},...n.changes?{changes:n.changes}:{},...n.warnings?{warnings:n.warnings}:{}},...n.data===void 0?{}:{data:n.data}}}function S(e,t){let n=u.get(t.undoId);if(!n)return{ok:!1,...e===void 0?{}:{id:e},error:H(`not_found`,`Nothing to undo for "${t.undoId}".`,{path:`input.undoId`})};if(!t.force&&b(s,n.after))return{ok:!1,...e===void 0?{}:{id:e},error:H(`conflict`,`The plan changed since; send force: true to undo anyway.`,{details:{currentRevision:c}})};let r=c,i=F(n.before),a=b(s,i);s=i,a&&(c+=1),u.delete(t.undoId),d=d.filter(e=>e!==t.undoId);let o=x(e,`undo`,{ok:!0,state:s,summary:`Undone.`},r,c,h());return g(),o}function C(e,r={}){try{let i=e&&typeof e==`object`&&!Array.isArray(e)?e:void 0,a=i?.id,o=Ct(a);if(o)return{ok:!1,error:o};let l=i?.expectedRevision??r.expectedRevision,u=wt(l);if(u)return{ok:!1,...a===void 0?{}:{id:a},error:u};let d=xt({name:i?.name,input:i?.input??{},expectedRevision:l}),f=v(a,d);if(f)return f;let p=e=>(_(a,d,e),e),m=e=>({ok:!1,...a===void 0?{}:{id:a},error:e}),C=St(e,n,[`id`,`expectedRevision`]);if(!C.ok)return p(m(C.error));if(l!==void 0&&l!==c)return p(m(H(`conflict`,`The plan is at revision ${c}, not ${l}. Read the snapshot and try again.`,{details:{expectedRevision:l,currentRevision:c}})));if(C.name===`undo`)return p(S(a,C.input));let w=s,T=dt(t,w,C.name,C.input);if(!T.ok)return p(m(T.error));let E=c,D=b(w,T.state),O;D&&(s=T.state,c+=1,O=y(w,T.state));let ee=p(x(a,C.name,T,E,c,h(),O));return g(),ee}catch(e){return{ok:!1,error:H(`failed`,e instanceof Error?e.message:String(e))}}}function w(e){let r=(e,t)=>({ok:!1,...t===void 0?{}:{id:t},error:e,snapshot:h()});try{if(!e||typeof e!=`object`||Array.isArray(e))return r(H(`invalid_input`,`A batch is an object: { commands }.`));let i=e,a=i.id,o=Ct(a);if(o)return r(o);let l=wt(i.expectedRevision);if(l)return r(l,a);let u=xt({commands:i.commands,expectedRevision:i.expectedRevision}),d=v(a,u);if(d)return`results`in d||`snapshot`in d?d:r(d.error,a);let f=e=>(_(a,u,e),e),p=i.commands;if(!Array.isArray(p)||p.length===0||p.length>50)return f(r(H(`invalid_input`,`commands must be a list of 1 to 50 commands.`,{path:`commands`}),a));let S=i.expectedRevision;if(S!==void 0&&S!==c)return f(r(H(`conflict`,`The plan is at revision ${c}, not ${S}. Read the snapshot and try again.`,{details:{expectedRevision:S,currentRevision:c}}),a));let C=(e,t,n)=>f(r(H(`batch_failed`,`Command ${e+1} (${String(t)}) failed: ${n.message}`,{path:`commands[${e}]`,details:{index:e,cause:n}}),a)),w=s,T=c,E=w,D=T,O=[];for(let[e,r]of p.entries()){let i=St(r,n,[]);if(!i.ok)return C(e,r?.name,i.error);if(i.name===`undo`)return C(e,`undo`,H(`invalid_input`,`undo cannot run inside a batch.`));let a=dt(t,E,i.name,i.input);if(!a.ok)return C(e,i.name,a.error);let o=D;b(E,a.state)&&(D+=1),E=a.state,O.push(x(void 0,i.name,a,o,D,m(E,D)))}let ee=D!==T,k;if(ee){s=E,c=D,k=y(w,E);for(let e of O)e.receipt.changed&&delete e.receipt.undoId}let te=f({ok:!0,...a===void 0?{}:{id:a},snapshot:h(),receipt:{...a===void 0?{}:{id:a},count:O.length,changed:ee,revisionBefore:T,revisionAfter:D,...k?{undoId:k}:{}},results:O});return g(),te}catch(e){return r(H(`failed`,e instanceof Error?e.message:String(e)))}}return{run:C,batch:w,snapshot:h,cookbook:()=>F(s.doc),state:()=>({version:1,revision:c,applied:s.applied,cookbook:F(s.doc),journal:[...l.values()].map(e=>F(e))}),subscribe(e){return p.set(e,c),e(h()),()=>{p.delete(e)}},tools:r,batchTool:i}}var Et=new Set(`AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BRL BSD BTN BWP BYN BZD CAD CDF CHF CLP CNY COP CRC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD UYU UZS VES VND VUV WST XAF XCD XOF XPF YER ZAR ZMW ZWG`.split(` `));function Dt(){let e=c.packages.flatMap(e=>e.models.map(t=>({id:t.id,name:t.name,packageId:e.id,...t.description?{description:t.description}:{},exposed:t.exposed,fields:t.fields.map(e=>({name:e.name,...e.system?{system:!0}:{},...e.default===void 0?{}:{default:e.default}}))})));return{recipes:h,models:e,cookbooks:y.map(e=>({id:e.id,name:e.name,document:e.document})),themePresets:f,currencies:[...Et],settingTargets:v}}var Ot;function kt(){return Ot??=Dt(),Ot}var At=[`cookbooks`,`recipes`,`features`,`layout`,`theme`,`settings`,`export`],jt={name:`focus`,description:`Move the planner's view to a tab and/or a menu section. Navigation only; it changes nothing in the plan.`,inputSchema:{type:`object`,properties:{tab:{enum:[...At],description:`The tab to open.`},section:{type:`string`,minLength:1,maxLength:200,description:`The id of a menu section, as the plan snapshot's "sections" lists it.`}},additionalProperties:!1}};function Mt(e){return[...mt(e),jt]}function Nt(e,t){return Mt({...kt(),recipes:e.map(e=>({id:e,label:e,models:[],nav:[],requires:[]})),cookbooks:t.map(e=>({id:e,name:e,document:{}}))})}var Pt=Nt(h.map(e=>e.id),y.map(e=>e.id));Object.fromEntries(Pt.map(e=>[e.name,e.inputSchema])),Pt.map(e=>e.name);function Ft(e,t,n=`input`){return vt(e,t,n)?.message??null}function It(e){let t=e;return{get:()=>t,set:e=>{t=e}}}var U=(e,t,n={})=>({code:e,message:t,...n}),W=(e,t)=>({ok:!1,...t===void 0?{}:{id:t},error:e}),G=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Lt=new Set([`apply_cookbook`,`import_cookbook`]),Rt=e=>e instanceof Error?e.message:String(e);function zt(e,t){if(!G(e))return JSON.stringify([t,e??null]);let{overviews:n,...r}=e;return JSON.stringify([t,r])}function Bt(e){let{catalog:t,port:n,options:r={},env:i={}}=e,a=i.section??It(null),o=i.tab??It(null),s=Mt(t),c=e=>s.find(t=>t.name===e)?.inputSchema,l=c(`focus`),u=c(`undo`),d,f=``,p=null,m=new Map,h=new Map,g=0,_=new Map,v=()=>n?.applied?.()??null,y=()=>r.navigation?.getTab()??o.get();function b(){if(!n?.read){d=Tt(e.cookbook===void 0?{catalog:t}:{catalog:t,state:{version:1,revision:0,applied:null,cookbook:e.cookbook,journal:[]}});return}let r=n.read();f=zt(r,v());try{d=Tt({catalog:t,state:{version:1,revision:0,applied:v(),cookbook:r,journal:[]}})}catch(e){d=Tt({catalog:t}),p=Rt(e)}}b();function x(e,n){let r=d.state();try{d=Tt({catalog:t,state:{version:1,revision:r.revision+1,applied:v(),cookbook:e,journal:r.journal}}),p=null}catch(e){p=Rt(e)}m=new Map,h=new Map,f=n}function S(){if(n?.read)try{let e=n.read(),t=zt(e,v());if(t===f)return;x(e,t)}catch(e){p=Rt(e)}}let C=()=>U(`failed`,`The app's document is not one the planner can read (${p}). Fix it or reset the cookbook, then try again.`),w=e=>W(C(),e);function T(e){if(!e)return;let t=m.get(e);return t||(t=`undo-${++g}`,m.set(e,t),h.set(t,e)),t}function E(e){let t=new Set(e);for(let[e,n]of m)t.has(e)||(m.delete(e),h.delete(n))}let D=e=>({...e,undo:e.undo.map(e=>T(e)),focus:{tab:y(),section:a.get()}});function O(){let e=d.snapshot();return E(e.undo),D(e)}function ee(e){if(!n?.read)return e;try{let t=n.read(),r=G(t)?t.overviews:void 0,{overviews:i,...a}=e;return ke(G(r)&&Object.keys(r).length?{...a,overviews:r}:a)}catch{return e}}function k(e){if(!e.ok)return e;let{receipt:t}=e,n=e.replayed?void 0:T(t.undoId),{undoId:r,...i}=t,a=e.data;if(t.name===`export_cookbook`&&G(a)&&!e.replayed){let e=ee(a.cookbook);a={...a,cookbook:e,text:`${JSON.stringify(e,null,2)}\n`}}return{...e,...a===void 0?{}:{data:a},snapshot:O(),receipt:{...i,...n?{undoId:n}:{}}}}function te(e,t){if(!n?.write)return;let i=d.snapshot().app.cookbook,a=e.includes(`apply_cookbook`)||i!==null&&i!==t;n.write(d.cookbook(),{commands:e,replaced:e.some(e=>Lt.has(e)),applied:i,libraryApplied:a}),n.read&&(f=zt(n.read(),v())),a&&r.onReplaced?.()}function A(){if(!_.size)return;S();let e=O(),t=JSON.stringify(e);for(let[n,r]of _)r!==t&&(_.set(n,t),n(e))}function ne(e,t){for(let t of Object.keys(e))if(![`name`,`input`,`id`,`expectedRevision`].includes(t))return U(`invalid_input`,`${t} is not part of a command.`,{path:t});let{id:n}=e;if(n!==void 0&&!(typeof n==`string`&&n.length>0&&n.length<=200))return U(`invalid_input`,`id must be a non-empty string of at most 200 characters.`,{path:`id`});let r=e.expectedRevision??t.expectedRevision;return r!==void 0&&!(Number.isInteger(r)&&r>=0)?U(`invalid_input`,`expectedRevision must be a whole number.`,{path:`expectedRevision`}):null}function re(e,t){let n=ne(e,t),i=typeof e.id==`string`?e.id:void 0;if(n)return W(n,i);let s=e.expectedRevision??t.expectedRevision,c=e.input??{},u=Ft(l,c);if(u)return W(U(`invalid_input`,u,{path:`input`}),i);let f=d.snapshot().revision;if(s!==void 0&&s!==f)return W(U(`conflict`,`The plan is at revision ${f}, not ${s}. Read the snapshot and try again.`,{details:{expectedRevision:s,currentRevision:f}}),i);if(c.section!==void 0&&!O().sections.some(e=>e.id===c.section))return W(U(`not_found`,`No menu section "${c.section}".`,{path:`input.section`}),i);let p=!1;c.tab&&At.includes(c.tab)&&(p||=y()!==c.tab,o.set(c.tab),r.navigation?.setTab(c.tab)),c.section!==void 0&&(p||=a.get()!==c.section,a.set(c.section),r.navigation?.setSection?.(c.section));let m={ok:!0,...i===void 0?{}:{id:i},snapshot:O(),receipt:{name:`focus`,...i===void 0?{}:{id:i},summary:``,changed:p,revisionBefore:f,revisionAfter:f}};return A(),m}function ie(e){let t=e.input;if(!n?.prepareImport||!G(t))return{raw:e};let r=n.prepareImport(t.document);return r.ok?{raw:{...e,input:{...t,document:r.cookbook}},dropped:r.dropped}:W(U(`invalid_input`,r.error,{path:`input.document`}),e.id)}function ae(e){if(n?.read&&e.some(e=>typeof e==`string`&&Lt.has(e)))try{let e=n.read();if(De(d.cookbook())&&!De(e)){let n=d.state();d=Tt({catalog:t,state:{version:1,revision:n.revision,applied:v(),cookbook:e,journal:n.journal}}),m=new Map,h=new Map,f=zt(e,v())}}catch(e){p=Rt(e)}}function oe(e,t={}){try{if(S(),p)return w(G(e)&&typeof e.id==`string`?e.id:void 0);if(!G(e))return k(d.run(e,t));if(e.name===`focus`)return re(e,t);if(ae([e.name]),p)return w(typeof e.id==`string`?e.id:void 0);let n=e,r;if(e.name===`import_cookbook`){let t=ie(e);if(`ok`in t)return t;n=t.raw,r=t.dropped}let i=d.snapshot().app.cookbook,a=se(n),o=a?ce(n,t,a):k(d.run(n,t));if(!o.ok)return o;!o.replayed&&o.receipt.changed&&te([String(n.name)],i);let s=o;return r?.length&&(s={...o,receipt:{...o.receipt,warnings:[...o.receipt.warnings??[],...r.map(e=>`Not imported: ${e}`)]}}),A(),s.ok?{...s,snapshot:O()}:s}catch(e){return W(U(`failed`,Rt(e)))}}function se(e){let n=e.input;if(e.name!==`apply_cookbook`||!G(n))return;let r=t.cookbooks?.find(e=>e.id===n.id);if(!r)return;let i=d.cookbook().theme;if(!i)return;let a=r.document.theme;if(a)return a.colorScheme||!i.colorScheme?void 0:{colorScheme:i.colorScheme};let o={};return i.preset&&(o.preset=i.preset),i.custom?.primary&&(o.primary=i.custom.primary),i.colorScheme&&(o.colorScheme=i.colorScheme),i.borderRadius&&(o.borderRadius=i.borderRadius),i.density&&(o.density=i.density),i.contrast&&(o.contrast=i.contrast),Object.keys(o).length?o:void 0}function ce(e,t,n){let r=d.batch({...e.id===void 0?{}:{id:e.id},expectedRevision:e.expectedRevision??t.expectedRevision,commands:[e,{name:`set_theme`,input:n}].map(({id:e,expectedRevision:t,...n})=>n)});if(!r.ok){let t=r.error.details?.cause;return W(r.error.code===`batch_failed`&&t?t:r.error,e.id)}let i=r.results[0],a=r.replayed?void 0:T(r.receipt.undoId);return{...i,...r.id===void 0?{}:{id:r.id},...r.replayed?{replayed:!0}:{},snapshot:O(),receipt:{...i.receipt,...r.id===void 0?{}:{id:r.id},revisionBefore:r.receipt.revisionBefore,revisionAfter:r.receipt.revisionAfter,changed:r.receipt.changed,...a?{undoId:a}:{}}}}function le(e){try{if(S(),p)return{ok:!1,error:C(),snapshot:O()};let t=G(e)&&Array.isArray(e.commands)?e.commands:[];if(ae(t.map(e=>G(e)?e.name:void 0)),p)return{ok:!1,error:C(),snapshot:O()};let n=d.snapshot().app.cookbook,r=d.batch(e);if(!r.ok)return{...r,snapshot:O()};!r.replayed&&r.receipt.changed&&te(t.map(e=>String(e?.name)),n);let i=r.replayed?void 0:T(r.receipt.undoId),{undoId:a,...o}=r.receipt,s=O(),c={...r,snapshot:s,receipt:{...o,...i?{undoId:i}:{}},results:r.results.map(e=>({...e,snapshot:r.replayed?s:D(e.snapshot)}))};return A(),c}catch(e){return{ok:!1,error:U(`failed`,Rt(e)),snapshot:O()}}}function ue(e){if(!G(e)||e.name!==`undo`||!G(e.input))return e;let t=e.input.undoId;return typeof t==`string`?{...e,input:{...e.input,undoId:h.get(t)??``}}:e}function de(e,t){if(e.ok||e.error.code!==`not_found`)return e;let n=h.get(t);return n?{...e,error:{...e.error,message:e.error.message.replace(`"${n}"`,`"${t}"`)}}:e}let j=(e,t)=>{if(G(e)&&e.name===`undo`&&G(e.input)){let n=e.input.undoId;if(typeof n==`string`&&Ft(u,e.input)===null)return S(),O(),h.has(n)?de(oe(ue(e),t),n):W(U(`not_found`,`Nothing to undo for "${n}".`,{path:`input.undoId`}),e.id)}return oe(ue(e),t)};return{run:j,batch:le,snapshot(){return S(),O()},cookbook(){return S(),ee(d.cookbook())},undo(){S();let e=O().undo.at(-1);return e?j({name:`undo`,input:{undoId:e}}):W(U(`not_found`,`Nothing to undo.`))},state:()=>d.state(),get tools(){return s},get batchTool(){return d.batchTool},observe(){return S(),JSON.stringify(O())},deliver:A,subscribe(e){i.watch?.start(),S();let t=O();return _.set(e,JSON.stringify(t)),e(t),()=>{_.delete(e),_.size||i.watch?.stop()}}}}function Vt(e){return e.recipes.length===0&&e.features.length===0&&e.policies.length===0&&Object.keys(e.exposure??{}).length===0&&e.theme===void 0&&l(e.layout)}function Ht(e){if(!e.theme?.colorScheme)return e;let{colorScheme:t,...n}=e.theme;return{...e,theme:Object.keys(n).length?n:void 0}}function Ut(e){return JSON.stringify(Ht(e))}function Wt(e,t){let n=Ht(e);return Vt(n)?!1:t===null||JSON.stringify(n)!==t}function Gt(e,t,n){return t(n?g(structuredClone(e.document),n):e.document)}var Kt=`smrt-planner:cookbook`,qt=`smrt-planner:cookbook-applied`,Jt=new class{#e=t(null);get active(){return e(this.#e)}set active(e){o(this.#e,e,!0)}#t=t(null);get appliedWork(){return e(this.#t)}set appliedWork(e){o(this.#t,e,!0)}load(e=u()){try{this.active=e?.getItem(`smrt-planner:cookbook`)??null,this.appliedWork=e?.getItem(`smrt-planner:cookbook-applied`)??null}catch{this.active=null,this.appliedWork=null}s(this.active)}select(e,t=null,n=u()){this.active=e,this.appliedWork=t;try{n?.setItem(Kt,e),t===null?n?.removeItem(qt):n?.setItem(qt,t)}catch{}}};function Yt(n){let i=t(r(n));return{get:()=>e(i),set:e=>{o(i,e,!0)}}}function Xt(e){return{read:()=>e.snapshot(),applied:()=>Jt.active,prepareImport:e=>m(e),write(t,{replaced:n,applied:r,libraryApplied:i}){let a=n?t:{...t,overviews:e.snapshot().overviews};n?e.replace(a):e.apply(a),i&&r&&(Jt.select(r,Ut(e.snapshot())),s(r))}}}function Zt(e=p,t={}){let r,o=Bt({catalog:kt(),port:Xt(e),options:t,env:{section:Yt(null),tab:Yt(null),watch:{start(){r||=a(()=>{n(()=>{o.observe(),i(o.deliver)})})},stop(){r?.(),r=void 0}}}});return o}var Qt=()=>({$schema:d,version:1,recipes:[],features:[],policies:[]});function $t(e){let{store:t,settings:n,theme:r}=e;return{read(){let e={...Qt(),recipes:[...t.ids].sort()};n&&(e=g(e,n.read()));let i=r?.read();return i?{...e,theme:i}:e},write(e){let i=new Set(e.recipes),a=new Set(t.ids),o=[...a].filter(e=>!i.has(e));o.length&&t.remove(...o);let s=[...i].filter(e=>!a.has(e));s.length&&t.add(...s),n&&n.write(_(e)),r?.write(e.theme)}}}function en(e,t={}){return Bt({catalog:kt(),port:$t(e),options:t})}var tn=[`cookbooks`,`recipes`,`features`,`layout`,`theme`,`settings`,`export`];function nn(e,t=`cookbooks`){let n=new URLSearchParams(e).get(`tab`);return tn.find(e=>e===n)??t}var rn=new class{#e=t(`cookbooks`);get active(){return e(this.#e)}set active(e){o(this.#e,e,!0)}fromSearch(e,t=`cookbooks`){this.active=nn(e,t)}leaveExport(e=`cookbooks`){this.active===`export`&&(this.active=e)}},an={},on=Zt(p,{navigation:{getTab:()=>rn.active,setTab:e=>{rn.active=e},setSection:e=>an.openSection?.(e)},onReplaced:()=>an.onReplaced?.()}),sn=class extends Error{code;category;details;cause;constructor(e,t,n,r,i){super(e),this.name=this.constructor.name,this.code=t,this.category=n,this.details=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,category:this.category,details:this.details,stack:this.stack,cause:this.cause?{name:this.cause.name,message:this.cause.message,stack:this.cause.stack}:void 0}}},K=Object.freeze({maxTitleLength:120,maxDescriptionLength:500,maxDimensions:4,maxMeasures:6,maxFilters:12,maxHaving:4,maxSort:3,maxInValues:100,maxStringValueLength:256,defaultRowLimit:100,maxRowLimit:1e3,maxAliasLength:40,maxFieldNameLength:64,maxSourceIdLength:120}),cn=[`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`],ln=[`count`,`countDistinct`,`sum`,`avg`,`min`,`max`],un=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`contains`,`isNull`,`isNotNull`],dn=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`],fn=[`table`,`bar`,`line`,`pie`,`stat`],q=class extends sn{code;path;status;constructor(e,t,n){super(t?`${t}: ${n}`:n,e,`validation`),this.name=`RuntimeReportError`,this.code=e,this.path=t,this.status=e===`tenant_required`||e===`confirmation_required`?403:e===`invalid_result`?500:422}};function J(e,t){throw new q(`invalid_spec`,e,t)}var pn=new Set(`all.and.as.asc.between.by.case.cast.check.column.constraint.create.cross.default.delete.desc.distinct.drop.else.end.except.exists.false.for.foreign.from.full.group.having.in.inner.insert.intersect.into.is.join.left.like.limit.natural.not.null.offset.on.or.order.outer.primary.references.right.select.set.table.then.to.true.union.unique.update.user.using.values.when.where.with`.split(`.`)),mn=/^[a-z][a-z0-9_]*$/,hn=/^[A-Za-z][A-Za-z0-9_]*$/,gn=/^[A-Za-z@][A-Za-z0-9_@./:-]*$/;function _n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Y(e,t,n){_n(e)||J(t,`must be an object`);for(let r of Object.keys(e))n.includes(r)||J(`${t}.${r}`,`is not a known key`);return e}function X(e,t,n,r=0){return e===void 0?[]:(Array.isArray(e)||J(t,`must be an array`),e.length>n&&J(t,`must have at most ${n} entries`),e.length<r&&J(t,`must have at least ${r} entries`),e)}function vn(e,t,n,r={}){if(typeof e!=`string`){if(r.optional&&e===void 0)return``;J(t,`must be a string`)}let i=e.trim();return i.length===0&&!r.optional&&J(t,`must not be empty`),i.length>n&&J(t,`must be at most ${n} characters`),/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(i)&&J(t,`must not contain control characters`),i}function yn(e,t,n){return(typeof e!=`string`||!n.includes(e))&&J(t,`must be one of: ${n.join(`, `)}`),e}function bn(e,t){return typeof e!=`string`&&J(t,`must be a string`),(e.length===0||e.length>K.maxFieldNameLength||!hn.test(e))&&J(t,`must be a plain field name (letters, digits, underscore)`),e}function Z(e,t){return typeof e!=`string`&&J(t,`must be a string`),(e.length===0||e.length>K.maxAliasLength||!mn.test(e))&&J(t,`must be a lowercase identifier of at most ${K.maxAliasLength} characters (a-z, 0-9, underscore)`),pn.has(e)&&J(t,`'${e}' is a reserved word`),e}function xn(e,t){return typeof e==`string`?(e.length>K.maxStringValueLength&&J(t,`must be at most ${K.maxStringValueLength} characters`),e.includes(`\0`)&&J(t,`must not contain NUL`),e):typeof e==`number`?(Number.isFinite(e)||J(t,`must be a finite number`),e):typeof e==`boolean`?e:J(t,`must be a string, number or boolean`)}function Sn(e){return e.replace(/([a-z\d])([A-Z])/g,`$1_$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1_$2`).toLowerCase()}function Cn(e,t){let n=Y(e,t,[`field`,`as`,`bucket`]),r=bn(n.field,`${t}.field`),i=n.bucket===void 0?void 0:yn(n.bucket,`${t}.bucket`,cn);return{field:r,as:n.as===void 0?Z(i?`${Sn(r)}_${i}`:Sn(r),`${t}.as`):Z(n.as,`${t}.as`),...i?{bucket:i}:{}}}function wn(e,t){let n=Y(e,t,[`fn`,`field`,`as`]),r=yn(n.fn,`${t}.fn`,ln),i=n.field===void 0?void 0:bn(n.field,`${t}.field`);!i&&r!==`count`&&J(`${t}.field`,`is required for ${r}`);let a=n.as===void 0?Z(i?`${Sn(r)}_${Sn(i)}`:`row_count`,`${t}.as`):Z(n.as,`${t}.as`);return{fn:r,...i?{field:i}:{},as:a}}function Tn(e,t){let n=Y(e,t,[`field`,`op`,`value`]),r=bn(n.field,`${t}.field`),i=yn(n.op,`${t}.op`,un);if(i===`isNull`||i===`isNotNull`)return n.value!==void 0&&J(`${t}.value`,`must be omitted for ${i}`),{field:r,op:i};if(n.value===void 0&&J(`${t}.value`,`is required for ${i}`),i===`in`||i===`notIn`)return{field:r,op:i,value:X(n.value,`${t}.value`,K.maxInValues,1).map((e,n)=>xn(e,`${t}.value[${n}]`))};Array.isArray(n.value)&&J(`${t}.value`,`must be a scalar for ${i}`);let a=xn(n.value,`${t}.value`);return i===`contains`&&typeof a!=`string`&&J(`${t}.value`,`must be a string for contains`),{field:r,op:i,value:a}}function En(e,t){let n=Y(e,t,[`measure`,`op`,`value`]),r=Z(n.measure,`${t}.measure`),i=yn(n.op,`${t}.op`,dn);return(typeof n.value!=`number`||!Number.isFinite(n.value))&&J(`${t}.value`,`must be a finite number`),{measure:r,op:i,value:n.value}}function Dn(e,t){let n=Y(e,t,[`by`,`direction`]);return{by:Z(n.by,`${t}.by`),direction:n.direction===void 0?`asc`:yn(n.direction,`${t}.direction`,[`asc`,`desc`])}}function On(e){let t=e;if(typeof e==`string`){e.length>65536&&J(``,`spec JSON is too large`);try{t=JSON.parse(e)}catch{J(``,`spec is not valid JSON`)}}let n=Y(t,`spec`,[`version`,`title`,`description`,`source`,`dimensions`,`measures`,`filters`,`having`,`sort`,`limit`,`chart`]);n.version!==void 0&&n.version!==1&&J(`spec.version`,`unsupported version (expected 1)`);let r=vn(n.title,`spec.title`,K.maxTitleLength),i=vn(n.description,`spec.description`,K.maxDescriptionLength,{optional:!0});(typeof n.source!=`string`||n.source.length===0||n.source.length>K.maxSourceIdLength||!gn.test(n.source))&&J(`spec.source`,`must be a source id`);let a=X(n.dimensions,`spec.dimensions`,K.maxDimensions).map((e,t)=>Cn(e,`spec.dimensions[${t}]`)),o=X(n.measures,`spec.measures`,K.maxMeasures,1).map((e,t)=>wn(e,`spec.measures[${t}]`)),s=X(n.filters,`spec.filters`,K.maxFilters).map((e,t)=>Tn(e,`spec.filters[${t}]`)),c=X(n.having,`spec.having`,K.maxHaving).map((e,t)=>En(e,`spec.having[${t}]`)),l=X(n.sort,`spec.sort`,K.maxSort).map((e,t)=>Dn(e,`spec.sort[${t}]`)),u=new Set,d=new Set,f=new Set;for(let[e,t]of a.entries())f.has(t.as)&&J(`spec.dimensions[${e}].as`,`duplicate alias '${t.as}'`),f.add(t.as),u.add(t.as);for(let[e,t]of o.entries())f.has(t.as)&&J(`spec.measures[${e}].as`,`duplicate alias '${t.as}'`),f.add(t.as),d.add(t.as);for(let[e,t]of c.entries())d.has(t.measure)||J(`spec.having[${e}].measure`,`must be a declared measure alias`);for(let[e,t]of l.entries())f.has(t.by)||J(`spec.sort[${e}].by`,`must be a declared dimension or measure alias`);let p=K.defaultRowLimit;n.limit!==void 0&&((typeof n.limit!=`number`||!Number.isSafeInteger(n.limit)||n.limit<1||n.limit>K.maxRowLimit)&&J(`spec.limit`,`must be an integer between 1 and ${K.maxRowLimit}`),p=n.limit);let m={type:`table`};if(n.chart!==void 0){let e=Y(n.chart,`spec.chart`,[`type`,`x`,`y`]),t=yn(e.type,`spec.chart.type`,fn),r=e.x===void 0?void 0:Z(e.x,`spec.chart.x`);r!==void 0&&!u.has(r)&&J(`spec.chart.x`,`must be a declared dimension alias`);let i=X(e.y,`spec.chart.y`,K.maxMeasures).map((e,t)=>Z(e,`spec.chart.y[${t}]`));for(let[e,t]of i.entries())d.has(t)||J(`spec.chart.y[${e}]`,`must be a declared measure alias`);m={type:t,...r?{x:r}:{},...i.length>0?{y:i}:{}}}return{version:1,title:r,...i?{description:i}:{},source:n.source,dimensions:a,measures:o,filters:s,having:c,sort:l,limit:p,chart:m}}function kn(e){return Array.isArray(e)?e.map(kn):_n(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,kn(e[t])])):e}function An(e){return JSON.stringify(kn(e))}async function jn(e){let t=globalThis.crypto?.subtle;if(!t)throw Error(`runtimeReportSpecDigest needs Web Crypto (crypto.subtle), which browsers offer only in a secure context`);let n=new TextEncoder().encode(An(e)),r=new Uint8Array(await t.digest(`SHA-256`,n));return Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``)}var Mn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Nn(e){return e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).replace(/^./,e=>e.toUpperCase())}function Pn(e,t){throw new q(`unknown_field`,e,`'${t}' is not a field available on this source`)}function Fn(e,t){throw new q(`invalid_operation`,e,t)}function In(e,t){throw new q(`invalid_value`,e,t)}var Ln={string:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`contains`,`isNull`,`isNotNull`],integer:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`isNull`,`isNotNull`],decimal:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`isNull`,`isNotNull`],datetime:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`isNull`,`isNotNull`],boolean:[`eq`,`ne`,`isNull`,`isNotNull`],id:[`eq`,`ne`,`in`,`notIn`,`isNull`,`isNotNull`]};function Rn(e){return e===`integer`||e===`decimal`?[`count`,`countDistinct`,`sum`,`avg`,`min`,`max`]:e===`datetime`?[`count`,`countDistinct`,`min`,`max`]:[`count`,`countDistinct`]}function zn(e,t,n){Ln[t].includes(e.op)||Fn(`${n}.op`,`'${e.op}' is not valid for ${t} fields`)}function Bn(e,t,n){switch(e){case`string`:return typeof t!=`string`&&In(n,`must be a string`),t;case`integer`:return(typeof t!=`number`||!Number.isSafeInteger(t))&&In(n,`must be a safe integer`),t;case`decimal`:return(typeof t!=`number`||!Number.isFinite(t))&&In(n,`must be a finite number`),t;case`boolean`:return typeof t!=`boolean`&&In(n,`must be true or false`),t;case`datetime`:{typeof t!=`string`&&In(n,`must be an ISO-8601 string`);let e=new Date(t);return(Number.isNaN(e.getTime())||!/^\d{4}-\d{2}-\d{2}/.test(t))&&In(n,`must be an ISO-8601 date or timestamp`),e}case`id`:return(typeof t!=`string`||!Mn.test(t))&&In(n,`must be a UUID`),t.toLowerCase()}}function Vn(e,t){let n=n=>{let r=e[n];if(r!==void 0){if(!Array.isArray(r)||Array.from(r).some(e=>typeof e!=`string`||!t.has(e)))throw new q(`unsupported_source`,`source.${n}`,`${n} must contain canonical field names declared on the source`);return new Set(r)}},r=n(`fields`),i=n(`excludeFields`);if(n(`dimensions`),e.timeField!==void 0&&(typeof e.timeField!=`string`||!t.has(e.timeField)))throw new q(`unsupported_source`,`source.timeField`,`timeField must be a canonical field name declared on the source`);return{...r?{included:r}:{},...i?{excluded:i}:{}}}function Hn(e,t){return e===`count`||e===`countDistinct`?`integer`:e===`avg`?`decimal`:t?.type??`decimal`}function Un(e,t){let n=(e,n)=>{let r=t.get(e);return r||Pn(n,e),r},r=[];for(let[t,i]of e.dimensions.entries()){let e=`spec.dimensions[${t}]`,a=n(i.field,`${e}.field`);i.bucket&&a.type!==`datetime`&&Fn(`${e}.bucket`,`buckets are only valid on datetime fields`),r.push({id:i.as,label:Nn(i.as),role:`dimension`,type:i.bucket?`datetime`:a.type,field:a.name,...i.bucket?{bucket:i.bucket}:{},...a.format&&!i.bucket?{format:a.format}:{}})}for(let[t,i]of e.measures.entries()){let e=`spec.measures[${t}]`,a=i.field?n(i.field,`${e}.field`):void 0;(i.fn===`sum`||i.fn===`avg`)&&a?.type!==`integer`&&a?.type!==`decimal`&&Fn(`${e}.fn`,`${i.fn} requires a numeric field`),(i.fn===`min`||i.fn===`max`)&&a?.type!==`integer`&&a?.type!==`decimal`&&a?.type!==`datetime`&&Fn(`${e}.fn`,`${i.fn} requires a numeric or datetime field`);let o=a?.format&&(i.fn===`sum`||i.fn===`min`||i.fn===`max`||i.fn===`avg`);r.push({id:i.as,label:Nn(i.as),role:`measure`,type:Hn(i.fn,a),...a?{field:a.name}:{},fn:i.fn,...o?{format:a?.format}:{}})}return r}function Wn(e,t){if(t==null)return null;if(t instanceof Date)return t.toISOString();if(typeof t==`bigint`){let n=Number(t);if(!Number.isSafeInteger(n))throw new q(`invalid_result`,e.id,`integer result exceeds the JavaScript safe range`);return n}if(e.type===`boolean`){if(t===1||t===`1`||t===`true`||t===!0)return!0;if(t===0||t===`0`||t===`false`||t===!1)return!1}if(e.type===`integer`||e.type===`decimal`){let n=typeof t==`number`?t:Number(t);if(!Number.isFinite(n))throw new q(`invalid_result`,e.id,`numeric result is not finite`);if(e.type===`integer`&&!Number.isSafeInteger(n))throw new q(`invalid_result`,e.id,`integer result exceeds the JavaScript safe range`);return n}return typeof t==`string`||typeof t==`number`||typeof t==`boolean`?t:String(t)}var Gn=/^(?:id|_.*)$|(?:Hash|Json|Token|Secret|Signature|Authority|Snapshot|Checksum|Cursor|Etag)$|^(?:external|historical)[A-Z]/,Kn=/^(?:created|updated|deleted|synced|archived)At$|^last[A-Z]\w*At$/,qn=/^(?:status|state)$|(?:Status|State)$/,Jn=/^(?:kind|type|category|method|channel|stage|priority|segment|tier|source)$|(?:Kind|Type|Category|Method|Channel|Stage|Priority|Segment|Tier)$/,Yn=/^(?:customer|vendor|supplier|client|member|employee|owner|assignee|product|location|project|account|contact)Id$/,Xn=50;function Zn(e){if(e.type===`datetime`)return e.name===`deletedAt`?void 0:`time`;if(!Gn.test(e.name)){if(e.type===`boolean`||e.type===`string`&&e.enum&&e.enum.length>0&&e.enum.length<=Xn)return`category`;if(e.type===`id`&&/Id$/.test(e.name))return`relation`}}function Qn(e){return e.type===`boolean`?10:e.type===`id`?Yn.test(e.name)?70:30:qn.test(e.name)?100:Jn.test(e.name)?80:50}function $n(e,t={}){let n=[...e.values()],r=new Map;for(let e of n){let t=Zn(e);t&&r.set(e.name,t)}let i=n.filter(e=>r.get(e.name)===`time`),a=(t.timeField&&e.get(t.timeField)?.type===`datetime`?t.timeField:void 0)??i.find(e=>e.businessDate)?.name??i.find(e=>!Kn.test(e.name))?.name??i.find(e=>e.name===`createdAt`)?.name??i[0]?.name,o=[...a?[a]:[],...i.map(e=>e.name).filter(e=>e!==a)],s;if(t.dimensions){s=t.dimensions.filter(t=>e.has(t)&&e.get(t)?.type!==`datetime`);for(let t of s)r.has(t)||r.set(t,e.get(t)?.type===`id`?`relation`:`category`);for(let[e,t]of[...r])t!==`time`&&!s.includes(e)&&r.delete(e)}else s=n.filter(e=>{let t=r.get(e.name);return t===`category`||t===`relation`}).map((e,t)=>({field:e,index:t})).sort((e,t)=>Qn(t.field)-Qn(e.field)||e.index-t.index).map(({field:e})=>e.name);return{kinds:r,timeFields:o,...a?{defaultTimeField:a}:{},dimensions:s}}function er(e,t={}){let n=$n(e,t);return{fields:[...e.values()].map(e=>{let t=n.kinds.get(e.name);return{name:e.name,label:e.label,type:e.type,...e.format?{format:e.format}:{},...e.enum?{enum:e.enum}:{},...t?{dimension:t}:{},filterOperators:Ln[e.type],aggregates:Rn(e.type)}}),timeFields:n.timeFields,...n.defaultTimeField?{defaultTimeField:n.defaultTimeField}:{},dimensions:n.dimensions}}var tr=new Set([`tenantId`,`tenant_id`]);function nr(e,t){let n=e.find(e=>e.id===t);if(!n)throw new q(`unknown_source`,`spec.source`,`'${t}' is not an available report source`);return n}function rr(e){let{included:t,excluded:n}=Vn(e,new Set(e.schema.map(e=>e.name))),r=new Map;for(let i of e.schema)i.name.startsWith(`_`)||tr.has(i.name)||n?.has(i.name)||t&&!t.has(i.name)||r.has(i.name)||r.set(i.name,{name:i.name,type:i.type,...i.format?{format:i.format}:{},...i.type===`string`&&i.enum?.length?{enum:i.enum}:{},...i.type===`datetime`&&i.format===`date`?{businessDate:!0}:{},label:i.label??Nn(i.name)});return r}function ir(e,t){let n=nr(e,t);return{id:n.id,label:n.label??Nn(n.id),...n.description?{description:n.description}:{},...er(rr(n),n)}}function ar(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function or(e,t){let n=e[t.name];if(n==null)return null;switch(t.type){case`integer`:case`decimal`:{if(typeof n==`bigint`){if(n>BigInt(2**53-1)||n<BigInt(-(2**53-1)))throw new q(`invalid_result`,t.name,`integer value exceeds the JavaScript safe range`);return Number(n)}let e=typeof n==`number`?n:typeof n==`string`&&n.trim()!==``?Number(n):NaN;return Number.isFinite(e)?e:null}case`boolean`:return n===!0||n===1||n===`1`||n===`true`?!0:n===!1||n===0||n===`0`||n===`false`?!1:null;case`datetime`:return ar(n);default:return typeof n==`string`?n:String(n)}}function sr(e,t){let n=e instanceof Date?e.getTime():e,r=t instanceof Date?t.getTime():t;return typeof n==`boolean`||typeof r==`boolean`?Number(n)-Number(r):n<r?-1:+(n>r)}function cr(e,t,n){zn(e,t.type,n);let r=e=>or(e,t);switch(e.op){case`isNull`:return e=>r(e)===null;case`isNotNull`:return e=>r(e)!==null;case`in`:case`notIn`:{let i=e.value.map((e,r)=>Bn(t.type,e,`${n}.value[${r}]`)),a=e=>i.some(t=>sr(e,t)===0);return e.op===`in`?e=>{let t=r(e);return t!==null&&a(t)}:e=>{let t=r(e);return t!==null&&!a(t)}}case`contains`:{let i=Bn(t.type,e.value,`${n}.value`);return e=>{let t=r(e);return typeof t==`string`&&t.includes(i)}}default:{let i=Bn(t.type,e.value,`${n}.value`),a={eq:e=>e===0,ne:e=>e!==0,gt:e=>e>0,gte:e=>e>=0,lt:e=>e<0,lte:e=>e<=0}[e.op];return e=>{let t=r(e);return t!==null&&a(sr(t,i))}}}}function lr(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate();switch(t){case`minute`:return new Date(Date.UTC(n,r,i,e.getUTCHours(),e.getUTCMinutes()));case`hour`:return new Date(Date.UTC(n,r,i,e.getUTCHours()));case`day`:return new Date(Date.UTC(n,r,i));case`week`:{let t=(e.getUTCDay()+6)%7;return new Date(Date.UTC(n,r,i-t))}case`month`:return new Date(Date.UTC(n,r,1));case`quarter`:return new Date(Date.UTC(n,Math.floor(r/3)*3,1));case`year`:return new Date(Date.UTC(n,0,1))}}function ur(e){return e===null?`n`:e instanceof Date?`d${e.getTime()}`:`${typeof e}:${String(e)}`}function dr(e,t,n){if(t===null)return n;let r=t.filter(e=>e!==null);switch(e){case`count`:return r.length;case`countDistinct`:return new Set(r.map(ur)).size;case`sum`:return r.length===0?null:r.reduce((e,t)=>e+t,0);case`avg`:return r.length===0?null:r.reduce((e,t)=>e+t,0)/r.length;case`min`:case`max`:{if(r.length===0)return null;let t=r[0];for(let n of r.slice(1)){let r=sr(n,t);(e===`min`?r<0:r>0)&&(t=n)}return t}default:return null}}function fr(e,t){if(typeof t!=`number`)return!1;switch(e.op){case`eq`:return t===e.value;case`ne`:return t!==e.value;case`gt`:return t>e.value;case`gte`:return t>=e.value;case`lt`:return t<e.value;case`lte`:return t<=e.value}}function pr(e,t,n){let r;return r=e===null&&t===null?0:e===null?-1:t===null?1:sr(e,t),n===`desc`?-r:r}async function mr(e,t,n){let r=On(e),i=nr(n.sources,r.source),a=rr(i),o=Un(r,a),s=(e,t)=>{let n=a.get(e);return n||Pn(t,e),n},c=[];i.schema.some(e=>e.name===`deletedAt`)&&c.push(e=>e.deletedAt===null||e.deletedAt===void 0);for(let[e,t]of r.filters.entries()){let n=`spec.filters[${e}]`;c.push(cr(t,s(t.field,`${n}.field`),n))}let l=t.filter(e=>c.every(t=>t(e))),u=r.dimensions.map(e=>{let t=a.get(e.field);return n=>{let r=or(n,t);return e.bucket&&r instanceof Date?lr(r,e.bucket):r}}),d=new Map;if(r.dimensions.length===0)d.set(``,{key:[],rows:l});else for(let e of l){let t=u.map(t=>t(e)),n=JSON.stringify(t.map(ur)),r=d.get(n);r?r.rows.push(e):d.set(n,{key:t,rows:[e]})}let f=r.measures.map(e=>e.field?a.get(e.field):null),p=[...d.values()].map(e=>{let t={};return r.dimensions.forEach((n,r)=>{t[n.as]=e.key[r]}),r.measures.forEach((n,r)=>{let i=f[r];t[n.as]=dr(n.fn,i?e.rows.map(e=>or(e,i)):null,e.rows.length)}),t});r.having.length>0&&(p=p.filter(e=>r.having.every(t=>fr(t,e[t.measure]))));let m=r.sort.length>0?r.sort:r.dimensions.length>0?[{by:r.dimensions[0].as,direction:`asc`}]:[];m.length>0&&(p=p.map((e,t)=>({values:e,index:t})).sort((e,t)=>{for(let n of m){let r=pr(e.values[n.by],t.values[n.by],n.direction);if(r!==0)return r}return e.index-t.index}).map(({values:e})=>e));let h=Math.min(r.limit,n.maxRows??K.maxRowLimit),g=p.length>h,_=p.slice(0,h).map(e=>{let t={};for(let n of o)t[n.id]=Wn(n,e[n.id]);return t});return{version:1,specHash:await jn(r),title:r.title,columns:o,rows:_,rowCount:_.length,truncated:g,ranAt:(n.now?.()??new Date).toISOString(),chart:r.chart}}var Q=864e5,hr=e=>new Date(e).toISOString().slice(0,10),gr=[`january`,`february`,`march`,`april`,`may`,`june`,`july`,`august`,`september`,`october`,`november`,`december`],_r={first:1,second:2,third:3,fourth:4},vr=[[`minute`,/\b(?:minutely|(?:per|by|each|every|a) minute|minute by minute)\b/],[`hour`,/\b(?:hourly|(?:per|by|each|every|an?) hour|hour by hour)\b/],[`day`,/\b(?:daily|(?:per|by|each|every|a) day|day by day)\b/],[`week`,/\b(?:weekly|(?:per|by|each|every|a) week|week by week|week over week)\b/],[`month`,/\b(?:monthly|(?:per|by|each|every|a) month|month by month|month over month)\b/],[`quarter`,/\b(?:quarterly|(?:per|by|each|every|a) quarter|quarter by quarter|quarter over quarter)\b/],[`year`,/\b(?:yearly|annually|annual|(?:per|by|each|every|a) year|year by year|year over year)\b/]],yr=/\b(?:over time|trends?|trending|timeline|history)\b/;function br(e){return e===null?`month`:e<=31?`day`:e<=92?`week`:e<=1098?`month`:`quarter`}function xr(e){return Math.round((Date.parse(`${e.to}T00:00:00Z`)-Date.parse(`${e.from}T00:00:00Z`))/Q)}function Sr(e,t){let n=e.toLowerCase().replace(/[_-]+/g,` `).replace(/\s+/g,` `),r=t.getUTCFullYear(),i=t.getUTCMonth(),a=Date.UTC(r,i,t.getUTCDate()),o=a+Q,s=a-(t.getUTCDay()+6)%7*Q,c=Math.floor(i/3)*3,l=(e,t,n)=>({from:hr(e),to:hr(t),label:n}),u=/\b(?:last|past|previous|trailing)\s+(\d{1,4})\s+(day|week|month|year)s?\b/.exec(n);if(u){let e=Number(u[1]),n=u[2];if(e>0)return l(n===`day`?o-e*Q:n===`week`?o-e*7*Q:n===`month`?Date.UTC(r,i-e,t.getUTCDate()+1):Date.UTC(r-e,i,t.getUTCDate()+1),o,`last ${e} ${n}${e===1?``:`s`}`)}let d=/\bq([1-4])(?:\s*(?:of\s*)?((?:19|20)\d{2}))?\b/.exec(n)??/\b(first|second|third|fourth) quarter(?: (?:of )?((?:19|20)\d{2}))?\b/.exec(n);if(d){let e=/^\d$/.test(d[1])?Number(d[1]):_r[d[1]],t=(e-1)*3,n=d[2]?Number(d[2]):Date.UTC(r,t,1)<=a?r:r-1;return l(Date.UTC(n,t,1),Date.UTC(n,t+3,1),`Q${e} ${n}`)}if(/\b(?:year to date|ytd)\b/.test(n))return l(Date.UTC(r,0,1),o,`year to date`);if(/\b(?:month to date|mtd)\b/.test(n))return l(Date.UTC(r,i,1),o,`month to date`);if(/\btoday\b/.test(n))return l(a,o,`today`);if(/\byesterday\b/.test(n))return l(a-Q,a,`yesterday`);let f=/\b(this|current|last|previous|past) (week|month|quarter|year)\b/.exec(n);if(f){let e=f[1]!==`this`&&f[1]!==`current`,t=f[2],n=`${e?`last`:`this`} ${t}`;switch(t){case`week`:return e?l(s-7*Q,s,n):l(s,s+7*Q,n);case`month`:return e?l(Date.UTC(r,i-1,1),Date.UTC(r,i,1),n):l(Date.UTC(r,i,1),Date.UTC(r,i+1,1),n);case`quarter`:return e?l(Date.UTC(r,c-3,1),Date.UTC(r,c,1),n):l(Date.UTC(r,c,1),Date.UTC(r,c+3,1),n);default:return e?l(Date.UTC(r-1,0,1),Date.UTC(r,0,1),n):l(Date.UTC(r,0,1),Date.UTC(r+1,0,1),n)}}let p=RegExp(`\\b(${gr.join(`|`)})(?: ((?:19|20)\\d{2}))?\\b`).exec(n);if(p&&(p[1]!==`may`||p[2])){let e=p,t=gr.indexOf(e[1]),n=e[2]?Number(e[2]):Date.UTC(r,t,1)<=a?r:r-1,i=e[1].charAt(0).toUpperCase()+e[1].slice(1);return l(Date.UTC(n,t,1),Date.UTC(n,t+1,1),`${i} ${n}`)}let m=/\b(?:in|for|during)\s+((?:19|20)\d{2})\b/.exec(n)??/^\s*((?:19|20)\d{2})\s*$/.exec(n);if(m){let e=Number(m[1]);return l(Date.UTC(e,0,1),Date.UTC(e+1,0,1),String(e))}return null}function Cr(e,t){let n=e.toLowerCase(),r=Sr(n,t)??void 0,i=vr.find(([,e])=>e.test(n))?.[0],a=yr.test(n);!i&&a&&(i=br(r?xr(r):null));let o=!!(i||r||a)||/\b(?:date|dates|time|when|minute|hour|day|week|month|quarter|year)s?\b/.test(n);return{...i?{bucket:i}:{},...r?{range:r}:{},mentionsTime:o}}var wr=[`today`,`yesterday`,`this_week`,`last_week`,`this_month`,`last_month`,`this_quarter`,`last_quarter`,`this_year`,`last_year`,`all_time`],Tr=[`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`],Er=[`count`,`sum`,`avg`,`min`,`max`],Dr=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`],Or=4,kr=3,Ar=64,jr=8;function Mr(e){let t={type:`string`,maxLength:Ar};return{type:[`object`,`null`],properties:{source:e.length?{enum:[...e]}:{type:`string`,maxLength:K.maxSourceIdLength},measures:{type:`array`,maxItems:Or,items:{type:`object`,properties:{fn:{enum:[...Er]},field:t},required:[`fn`],additionalProperties:!1}},groupBy:t,bucket:{enum:[...Tr]},period:{enum:[...wr]},range:{type:`string`,maxLength:40},dateField:t,filters:{type:`array`,maxItems:kr,items:{type:`object`,properties:{field:t,op:{enum:[...Dr]},value:{type:[`string`,`number`,`boolean`]}},required:[`field`,`op`,`value`],additionalProperties:!1}},title:{type:`string`,maxLength:K.maxTitleLength}},required:[`source`],additionalProperties:!1}}var Nr=(e,t)=>typeof e==`string`&&t.includes(e)?e:void 0,Pr=(e,t=Ar)=>typeof e==`string`&&e.trim()&&e.trim().length<=t?e.trim():void 0;function Fr(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=Pr(t.source,K.maxSourceIdLength);if(!n)return null;let r=e=>t[e]!==void 0&&t[e]!==null,i=Array.isArray(t.unreadable)?t.unreadable.filter(e=>typeof e==`string`&&e.trim().length>0).slice(0,jr).map(e=>e.trim().slice(0,Ar)):[];r(`measures`)&&!Array.isArray(t.measures)&&i.push(`the measures`),r(`filters`)&&!Array.isArray(t.filters)&&i.push(`the filters`);let a=Array.isArray(t.measures)?t.measures.slice(0,Or).flatMap(e=>{let t=e&&typeof e==`object`?e:{},n=Nr(t.fn,Er);if(!n)return i.push(`a measure`),[];let r=Pr(t.field);return[{fn:n,...r?{field:r}:{}}]}):[],o=Array.isArray(t.filters)?t.filters.slice(0,kr).flatMap(e=>{let t=e&&typeof e==`object`?e:{},n=Pr(t.field),r=Nr(t.op,Dr),a=t.value;return!n||!r||!(typeof a==`string`&&a.length<=256||typeof a==`number`&&Number.isFinite(a)||typeof a==`boolean`)?(i.push(n?`the ${n} filter`:`a filter`),[]):[{field:n,op:r,value:a}]}):[];Array.isArray(t.measures)&&t.measures.length>Or&&i.push(`more than ${Or} measures`),Array.isArray(t.filters)&&t.filters.length>kr&&i.push(`more than ${kr} filters`);let s=Pr(t.groupBy),c=Nr(t.bucket,Tr),l=Nr(t.period,wr),u=Pr(t.dateField),d=Pr(t.range,40),f=Pr(t.title,K.maxTitleLength);return r(`range`)&&!d&&i.push(`the period`),r(`groupBy`)&&!s&&i.push(`the grouping`),r(`bucket`)&&!c&&i.push(`the time grouping`),r(`period`)&&!l&&i.push(`the period`),r(`dateField`)&&!u&&i.push(`the date`),{source:n,...a.length?{measures:a}:{},...s?{groupBy:s}:{},...c?{bucket:c}:{},...l?{period:l}:{},...d?{range:d}:{},...u?{dateField:u}:{},...o.length?{filters:o}:{},...f?{title:f}:{},...i.length?{unreadable:i}:{}}}var Ir=e=>e.toLowerCase().replace(/[^a-z0-9]/g,``);function Lr(e,t,n=()=>!0){let r=Ir(e),i=t.filter(n);return i.find(t=>t.name===e)??i.find(e=>Ir(e.name)===r)??i.find(e=>Ir(e.label)===r)}function Rr(e){let t=e.slice(0,6),n=e.length>t.length?`, …`:``;return t.length<=1?`${t.join(``)}${n}`:`${t.slice(0,-1).join(`, `)}${n} or ${t[t.length-1]}`}var $=e=>({ok:!1,question:e}),zr=e=>e.options.length?{ok:!1,question:e.prompt,followUp:{...e,default:e.options[0].value}}:{ok:!1,question:e.prompt.replace(/…$/,` what?`)},Br=8;function Vr(e){let t=e=>(e.amountField?2:0)+ +!!e.dateField;return[...e].sort((e,n)=>t(n)-t(e))}function Hr(e){let t=Vr(e).slice(0,Br);return t.length?{field:`source`,label:`Records`,prompt:`Which records should the report cover?`,options:t.map(e=>({value:e.id,label:e.label,apply:{source:e.id}})),default:t[0].id}:null}function Ur(e){return e.length?`Which records should the report cover?`:`Which records should the report cover? Add a recipe with records first, such as invoicing?`}var Wr={minute:`minute`,minutely:`minute`,hour:`hour`,hourly:`hour`,day:`day`,daily:`day`,week:`week`,weekly:`week`,month:`month`,monthly:`month`,quarter:`quarter`,quarterly:`quarter`,year:`year`,yearly:`year`,annual:`year`,annually:`year`},Gr=new Set([`by`,`per`,`the`,`each`,`every`,`a`,`over`,`time`,`date`,`dates`,`in`]);function Kr(e){let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),n,r=!1,i=[];for(let e of t){let t=e.endsWith(`s`)?e.slice(0,-1):e,a=Wr[e]??Wr[t];a?(n??=a,r=!0):Gr.has(e)?(e===`date`||e===`dates`||e===`time`)&&(r=!0):i.push(e)}return{...n?{bucket:n}:{},rest:i.join(` `),time:r}}var qr=[{value:`this month`,label:`This month`},{value:`last month`,label:`Last month`},{value:`this quarter`,label:`This quarter`},{value:`last quarter`,label:`Last quarter`},{value:`this year`,label:`This year`},{value:`last year`,label:`Last year`},{value:`all time`,label:`All time`}];function Jr(e,t,n){let r=e=>e.replace(/([a-z\d])([A-Z])/g,`$1_$2`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`);return(e===`count`||!t?`number_of_${r(n)}`:e===`sum`?r(t).startsWith(`total`)?r(t):`total_${r(t)}`:`${{avg:`average`,min:`lowest`,max:`highest`}[e]}_${r(t)}`).slice(0,K.maxAliasLength).replace(/_+$/,``)}var Yr={eq:`is`,ne:`is not`,gt:`over`,gte:`at least`,lt:`under`,lte:`at most`,contains:`contains`},Xr=/^-?\s*[$€£¥]?\s*-?(\d{1,3}(,\d{3})+|\d+)(\.\d{1,2})?$/;function Zr(e){if(typeof e==`number`)return Number.isFinite(e)?Math.round(e*100):null;if(typeof e!=`string`)return null;let t=e.trim();if(!Xr.test(t))return null;let n=Number(t.replace(/[^0-9.-]/g,``));return Number.isFinite(n)?Math.round(n*100):null}var Qr=e=>e.type===`integer`||e.type===`decimal`;function $r(e,t,n,r=``){let i=t.find(t=>t.id===e.source);if(!i){let e=Hr(t);return e?{ok:!1,question:e.prompt,followUp:e}:$(Ur(t))}let a=ir(t,i.id),{fields:o}=a,s=i.label,c=e=>o.find(t=>t.name===e)?.label??e;if(e.unreadable?.length)return $(`I could not read ${Rr(e.unreadable).replace(/ or ([^,]+)$/,` and $1`)} for the ${s} report. Can you say that again?`);let l=Cr(r,n),u=e.measures?.length?e.measures:[{fn:`count`},...i.amountField?[{fn:`sum`,field:i.amountField}]:[]],d=[];for(let[e,t]of u.entries()){if(t.fn===`count`){d.some(e=>e.fn===`count`)||d.push({fn:`count`,as:Jr(`count`,void 0,i.id)});continue}let n=t.field??i.amountField,r=n?Lr(n,o,e=>t.fn===`min`||t.fn===`max`?Qr(e)||e.type===`datetime`:Qr(e)):void 0;if(!r){let n=o.filter(e=>Qr(e)&&e.name!==`id`);if(!n.length)return $(`${s} have no amounts to total. Should I count them instead?`);let r=[...n.filter(e=>e.name===i.amountField),...n.filter(e=>e.format===`money`&&e.name!==i.amountField),...n.filter(e=>e.format!==`money`)].slice(0,Br);return zr({field:`measure`,label:t.fn===`sum`?`Total`:`Amount`,prompt:`Which amount on ${s} should I ${t.fn===`sum`?`total`:`take the ${t.fn} of`}?`,options:r.map(n=>({value:n.name,label:n.label,apply:{measures:u.map((r,i)=>i===e?{fn:t.fn,field:n.name}:r)}}))})}d.push({fn:t.fn,field:r.name,as:Jr(t.fn,r.name,i.id)})}let f=e.groupBy,p=e.dateField,m=e.bucket;if(f){let e=Kr(f),t=Lr(f,o,e=>e.type===`datetime`);if(t)p??=t.name,m??=`month`,f=void 0;else if(e.time){let t=e.rest?Lr(e.rest,o,e=>e.type===`datetime`):void 0;(!e.rest||t)&&(t&&(p??=t.name),m??=e.bucket??l.bucket??`month`,f=void 0)}}m??=l.bucket;let h=null;if(e.range){if(h=Sr(e.range,n),!h&&!/\ball\s*time\b|\bever\b/i.test(e.range))return zr({field:`period`,label:`Period`,prompt:`Which period should the ${s} report cover?`,options:qr.map(e=>({...e,apply:{range:e.value,period:void 0}}))})}else e.period&&e.period!==`all_time`?h=Sr(e.period,n):e.period||(h=l.range??null);let g;if((m||h)&&(g=p?Lr(p,o,e=>e.type===`datetime`):a.defaultTimeField?o.find(e=>e.name===a.defaultTimeField):void 0,!g)){let e=a.timeFields.slice(0,Br);return e.length?zr({field:`dateField`,label:`Date`,prompt:`Which date on ${s} should the report use?`,options:e.map(e=>({value:e,label:c(e),apply:{dateField:e}}))}):$(`${s} have no date to group or filter by. Should the report cover all of them?`)}let _=[];if(f){let e=new Set(a.dimensions),t=Lr(f,o,t=>e.has(t.name))??Lr(f,o,e=>e.type!==`datetime`);if(t)_.push({field:t.name});else if(!(m&&g))return zr(ei(a,s,c,l.mentionsTime))}m&&g&&_.push({field:g.name,bucket:m});let v=[];h&&g&&(v.push({field:g.name,op:`gte`,value:h.from}),v.push({field:g.name,op:`lt`,value:h.to}));let y=[];for(let t of e.filters??[]){let e=Lr(t.field,o);if(!e)return $(`Which field on ${s} should "${t.field}" filter: ${Rr(o.map(e=>e.label))}?`);if(e.format===`money`){let n=Zr(t.value);if(n===null)return $(`What amount should ${e.label} be compared with?`);v.push({field:e.name,op:t.op,value:n}),y.push(`${e.label} ${Yr[t.op]} ${(n/100).toFixed(2)}`)}else v.push({field:e.name,op:t.op,value:t.value}),y.push(`${e.label} ${Yr[t.op]} ${String(t.value)}`)}let b=e.title??[[s,..._.map(e=>e.bucket?`by ${e.bucket}`:`by ${c(e.field).toLowerCase()}`)].join(` `),h?.label??``].filter(Boolean).join(`, `),x=y.join(`; `)||void 0,S=e=>e.measures.map(e=>e.as);try{let e=On({title:b,...x?{description:x}:{},source:i.id,dimensions:_,measures:d,filters:v}),t=e.measures.filter(e=>e.fn!==`count`),n=(t[0]??e.measures[0]).as,r=e.dimensions.find(e=>e.bucket),a=e.dimensions.find(e=>!e.bucket);return{ok:!0,spec:On({...e,sort:a&&!r?[{by:n,direction:`desc`}]:[],chart:e.dimensions.length?{type:r&&!a?`line`:`bar`,x:(a??r)?.as,y:t.length?t.map(e=>e.as):S(e)}:{type:`stat`,y:S(e)}}),source:i}}catch(e){if(e instanceof q)return $(`I could not build that report (${e.message}). What should it show?`);throw e}}function ei(e,t,n,r){let i=e.defaultTimeField,a=i?[`month`,`week`,`quarter`].map(e=>({value:`${i}:${e}`,label:`${n(i)} by ${e}`,keywords:[`${e}ly`,`date`,`time`,`per`,e],apply:{groupBy:void 0,bucket:e,dateField:i}})):[],o=e.dimensions.map(e=>({value:e,label:n(e),apply:{groupBy:e}})),s=r?[...a,...o]:[...o.slice(0,4),...a.slice(0,1),...o.slice(4),...a.slice(1)];return{field:`groupBy`,label:`Group by`,prompt:`Group ${t} by…`,options:s.slice(0,Br)}}function ti(e,t){return e.code===`invalid_value`?`That value does not fit ${t.label} (${e.message}). What value did you mean?`:e.code===`invalid_operation`?`I cannot use that on ${t.label} (${e.message}). What should the report show instead?`:`I could not build that report (${e.message}). What should it show?`}export{Et as C,At as S,en as _,$r as a,Ut as b,ir as c,mr as d,jn as f,rn as g,an as h,Hr as i,On as l,on as m,ti as n,Ur as o,An as p,Mr as r,q as s,Fr as t,Sr as u,Jt as v,Wt as x,Gt as y};
1
+ import{$ as e,bt as t,ct as n,gt as r,nt as i,ot as a,vt as o}from"./DG3qFFTE.js";import{F as s,lt as c}from"./B45qMR8U.js";import{g as l}from"./BfeotTF9.js";import{a as u,c as d,h as f,n as p,o as m}from"./Ywu-998J.js";import{b as h,c as g,o as _,r as v}from"./nB-x9BEp.js";import{n as y}from"./QJX7BlhI.js";var b=[`material`,`glass`,`studio`,`smrt`,`happyvertical`],x=`@happyvertical/smrt-commerce:`,S={currency:[`Order`,`PurchaseOrder`,`WholesaleOrder`,`Estimate`,`Invoice`,`Agreement`].map(e=>({model:`${x}${e}`,field:`currency`})),taxRate:[`InvoiceLineItem`,`ContractLineItem`].map(e=>({model:`${x}${e}`,field:`taxRate`})),pricesIncludeTax:[`Invoice`,`Contract`].map(e=>({model:`${x}${e}`,field:`lineAmountType`})),taxRounding:[`Invoice`,`Contract`].map(e=>({model:`${x}${e}`,field:`taxRoundingScope`})),paymentTerms:[...[`Order`,`WholesaleOrder`,`Estimate`,`Invoice`,`Agreement`].map(e=>({model:`${x}${e}`,field:`terms`})),{model:`${x}Customer`,field:`paymentTerms`}]},C={id:`more`,label:`More`},w=/^@[^/]+\/(?:smrt-)?([^:]+):(.+)$/;function T(e,t){let n=e.models.find(e=>e.id===t);if(n)return{packageId:n.packageId,name:n.name};let r=w.exec(t);return r?{packageId:r[1],name:r[2]}:{packageId:`unknown`,name:t}}var E=(e,t,n)=>`item:${e}:${t}${n?`:${n}`:``}`,D=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase()),O=(e,t)=>D(T(e,t).name);function ee(e,t){let n=new Map(e.recipes.map(e=>[e.id,e])),r=new Map;for(let i of[...t.recipes].sort()){let t=n.get(i);if(!t)continue;let a=t.section??{id:t.group?.id??t.id,label:t.group?.label??t.label},o=`section:${a.id}`,s=r.get(o)??{id:o,label:a.label,items:[]};for(let n of t.nav){let{packageId:t,name:r}=T(e,n.model),i=E(t,r,n.key);s.items.some(e=>e.id===i)||s.items.push({id:i,label:n.label})}r.set(o,s)}let i=[...r.values()].filter(e=>e.items.length>0),a=new Set(e.models.filter(e=>e.exposed!==!1).map(e=>e.id)),o=t.features.filter(e=>a.has(e));return o.length&&i.push({id:`section:${C.id}`,label:C.label,items:o.map(t=>{let{packageId:n,name:r}=T(e,t);return{id:E(n,r),label:D(r)}})}),i}var k=(e,t)=>{if(!t?.length)return e;let n=e=>{let n=t.indexOf(e);return n<0?2**53-1:n};return[...e].sort((e,t)=>n(e.id)-n(t.id))};function te(e,t){let n=t.layout,r=ee(e,t).map(e=>({id:e.id,label:e.label,defaultLabel:e.label,custom:!1,hidden:!1,items:e.items.map(e=>({id:e.id,label:e.label,defaultLabel:e.label,hidden:!1}))}));for(let e of n?.customSections??[])r.some(t=>t.id===e.id)||r.push({id:e.id,label:e.label,defaultLabel:e.label,custom:!0,hidden:!1,items:[]});for(let[e,t]of Object.entries(n?.moved??{})){let n=r.find(e=>e.id===t);if(n)for(let t of r){let r=t.items.findIndex(t=>t.id===e);r>=0&&t!==n&&n.items.push(...t.items.splice(r,1))}}let i=new Set(n?.hidden??[]);for(let e of r){let t=n?.sections?.[e.id]?.label?.trim();t&&!e.custom&&(e.label=t),e.hidden=i.has(e.id),e.items=k(e.items,n?.itemOrder?.[e.id]);for(let t of e.items){let e=n?.items?.[t.id]?.label?.trim();e&&(t.label=e),t.hidden=i.has(t.id)}}return k(r.filter(e=>e.custom||e.items.length>0),n?.sectionOrder)}var A=(e,t)=>e.models.find(e=>e.id===t),ne=e=>{let t={...e};for(let e of[`hidden`,`customSections`,`sectionOrder`])t[e]?.length||delete t[e];for(let e of[`sections`,`items`,`itemOrder`,`moved`,`panels`,`placements`])t[e]&&Object.keys(t[e]).length===0&&delete t[e];return Object.keys(t).length>1?t:void 0};function re(e,t,n){let r=e?structuredClone(e):{version:1},i=n.trim();if(t.custom)return i?(r.customSections=r.customSections?.map(e=>e.id===t.id?{...e,label:i}:e),ne(r)):e;let a={...r.sections??{}},o={...a[t.id]??{}};return!i||i===t.defaultLabel?delete o.label:o.label=i,Object.keys(o).length?a[t.id]=o:delete a[t.id],r.sections=a,ne(r)}function ie(e,t,n){let r=e?structuredClone(e):{version:1},i=n?.trim()??``,a={...r.items??{}},o={...a[t.id]??{}};return!i||i===t.defaultLabel?delete o.label:o.label=i,Object.keys(o).length?a[t.id]=o:delete a[t.id],r.items=a,ne(r)}function ae(e,t,n){let r=e?structuredClone(e):{version:1},i=(r.hidden??[]).filter(e=>e!==t);return r.hidden=n?[...i,t]:i,ne(r)}var oe=`https://s-m-r-t.dev/schemas/cookbook/v1.json`,se=new Set([`basic`,`advanced`,`hidden`]),ce=new Set([`api`,`mcp`,`cli`]),le=new Set([`light`,`dark`,`system`]),ue={borderRadius:[`none`,`sm`,`md`,`lg`,`xl`,`full`],density:[`comfortable`,`touch`],contrast:[`auto`,`standard`,`more`]},de=new Set([`header.start`,`header.center`,`header.end`,`footer.start`,`footer.center`,`footer.end`,`leftSidebar.header`,`leftSidebar.footer`,`rightSidebar.header`,`rightSidebar.footer`]),j=e=>typeof e==`object`&&!!e&&!Array.isArray(e),M=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),fe=(e,t)=>j(e)&&!Object.hasOwn(e,`__proto__`)&&Object.values(e).every(t),pe=(e,t,n,r,i)=>{e.push({severity:t,code:n,path:r,message:i})},N=(e,t,n,r)=>pe(e,`error`,t,n,r),P=(e,t,n,r)=>pe(e,`warning`,t,n,r);function me(e,t,n){if(!j(e))return N(n,`invalid_type`,t,`${t} must be an object`);for(let r of[`objectRef`,`fieldName`])(typeof e[r]!=`string`||!e[r])&&N(n,`invalid_value`,`${t}.${r}`,`${t}.${r} must be a non-empty string`);e.scopeType!==`app`&&N(n,`invalid_value`,`${t}.scopeType`,`${t}.scopeType must be "app"`);for(let r of[`defaultValue`,`help`,`label`]){let i=e[r];i!=null&&typeof i!=`string`&&N(n,`invalid_type`,`${t}.${r}`,`${t}.${r} must be a string or null`)}let r=e.visibility;r!=null&&!(typeof r==`string`&&se.has(r))&&N(n,`invalid_value`,`${t}.visibility`,`${t}.visibility must be basic, advanced or hidden`);let i=e.displayOrder;i!=null&&!(typeof i==`number`&&Number.isFinite(i))&&N(n,`invalid_value`,`${t}.displayOrder`,`${t}.displayOrder must be a finite number`),e.locked!=null&&typeof e.locked!=`boolean`&&N(n,`invalid_type`,`${t}.locked`,`${t}.locked must be a boolean`)}function he(e,t){if(!j(e)||e.version!==1)return N(t,`invalid_value`,`layout`,`layout must be an object with version 1`);for(let n of[`sectionOrder`,`hidden`])e[n]!==void 0&&!M(e[n])&&N(t,`invalid_type`,`layout.${n}`,`layout.${n} must be a list of strings`);for(let n of[`itemOrder`,`moved`,`placements`]){let r=e[n];r!==void 0&&((n===`itemOrder`?fe(r,M):fe(r,e=>typeof e==`string`))||N(t,`invalid_type`,`layout.${n}`,n===`itemOrder`?`layout.itemOrder must map ids to lists of strings`:`layout.${n} must map ids to strings`))}if(j(e.placements))for(let[n,r]of Object.entries(e.placements))typeof r==`string`&&!de.has(r)&&N(t,`unknown_layout_slot`,`layout.placements.${n}`,`Unknown shell slot "${r}".`);for(let n of[`sections`,`items`,`panels`])e[n]!==void 0&&!fe(e[n],e=>j(e))&&N(t,`invalid_type`,`layout.${n}`,`layout.${n} must map ids to objects`);let n=e.customSections;n!==void 0&&!(Array.isArray(n)&&n.every(e=>j(e)&&typeof e.id==`string`&&typeof e.label==`string`))&&N(t,`invalid_type`,`layout.customSections`,`layout.customSections must be a list of { id, label }`)}function ge(e,t){if(!j(e))return N(t,`invalid_type`,`theme`,`theme must be an object`);e.preset!==void 0&&typeof e.preset!=`string`&&N(t,`invalid_type`,`theme.preset`,`theme.preset must be a string`),e.fontFamily!==void 0&&(typeof e.fontFamily!=`string`||!e.fontFamily)&&N(t,`invalid_value`,`theme.fontFamily`,`theme.fontFamily must be a non-empty string`),e.customCss!==void 0&&(typeof e.customCss==`string`?Array.from(e.customCss).length>65536&&N(t,`invalid_value`,`theme.customCss`,`theme.customCss must be at most 65,536 characters`):N(t,`invalid_type`,`theme.customCss`,`theme.customCss must be a string`)),e.colorScheme!==void 0&&!(typeof e.colorScheme==`string`&&le.has(e.colorScheme))&&N(t,`invalid_value`,`theme.colorScheme`,`theme.colorScheme must be light, dark or system`);for(let n of[`borderRadius`,`density`,`contrast`]){let r=ue[n],i=e[n];i!==void 0&&!(typeof i==`string`&&r.includes(i))&&N(t,`invalid_value`,`theme.${n}`,`theme.${n} must be one of ${r.join(`, `)}`)}let n=e.custom;n!==void 0&&(!j(n)||typeof n.primary!=`string`?N(t,`invalid_value`,`theme.custom`,`theme.custom must be an object with a string primary`):/^#[0-9a-fA-F]{6}$/.test(n.primary)?n.fontFamily!==void 0&&typeof n.fontFamily!=`string`&&N(t,`invalid_type`,`theme.custom.fontFamily`,`theme.custom.fontFamily must be a string`):N(t,`invalid_value`,`theme.custom.primary`,`theme.custom.primary must be a hex colour like #c2410c`))}var _e=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/,ve=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,ye=/^[a-z][a-z0-9-]{0,31}$/,be=e=>e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)||typeof e==`boolean`;function xe(e,t,n){return j(e)?[typeof e.id==`string`&&ve.test(e.id),typeof e.type==`string`&&ye.test(e.type),typeof e.span==`number`&&Number.isInteger(e.span)&&e.span>=1&&e.span<=4,j(e.options)&&Object.values(e.options).every(be),e.version===void 0||typeof e.version==`number`&&Number.isInteger(e.version)&&e.version>=1].every(Boolean)?e:(P(n,`malformed_overview_widget`,t,`${t} was dropped because it is not a valid overview widget`),null):(P(n,`malformed_overview_widget`,t,`${t} was dropped`),null)}function Se(e,t,n){return j(e)?(e.span===void 0||typeof e.span==`number`&&Number.isInteger(e.span)&&e.span>=1&&e.span<=4)&&(e.options===void 0||j(e.options)&&Object.values(e.options).every(be))&&(e.version===void 0||typeof e.version==`number`&&Number.isInteger(e.version)&&e.version>=1)?e:(P(n,`malformed_overview_change`,t,`${t} was dropped because it is not a valid widget change`),null):(P(n,`malformed_overview_change`,t,`${t} was dropped`),null)}function Ce(e,t,n){if(!j(e)||e.version!==1)return P(n,`malformed_overview`,t,`${t} was dropped because it must be an object with version 1`),null;let r={...e,version:1};for(let i of[`order`,`removed`])e[i]!==void 0&&!M(e[i])?(P(n,`malformed_overview_list`,`${t}.${i}`,`${t}.${i} was dropped because it must be a list of strings`),delete r[i]):e[i]!==void 0&&(r[i]=[...new Set(e[i])]);if(e.added!==void 0){if(!Array.isArray(e.added))P(n,`malformed_overview_widgets`,`${t}.added`,`${t}.added was dropped because it must be a list of widgets`),delete r.added;else{let i=e.added.flatMap((e,r)=>{let i=xe(e,`${t}.added[${r}]`,n);return i?[i]:[]});i.length?r.added=i:delete r.added}}if(e.changed!==void 0){if(!j(e.changed)||Object.hasOwn(e.changed,`__proto__`))P(n,`malformed_overview_changes`,`${t}.changed`,`${t}.changed was dropped because it must map widget ids to objects`),delete r.changed;else{let i={};for(let[r,a]of Object.entries(e.changed)){if(!ve.test(r)){P(n,`malformed_overview_change`,`${t}.changed.${r}`,`${t}.changed.${r} was dropped because its widget id is invalid`);continue}let e=Se(a,`${t}.changed.${r}`,n);e&&(i[r]=e)}Object.keys(i).length?r.changed=i:delete r.changed}}return r}function we(e,t={}){let n=[];if(!j(e))return N(n,`invalid_type`,``,`expected a JSON object`),{ok:!1,errors:[`expected a JSON object`],diagnostics:n};let{$schema:r,version:i}=e;r!==void 0&&r!==`https://s-m-r-t.dev/schemas/cookbook/v1.json`&&r!==`https://s-m-r-t.dev/schemas/blueprint/v1.json`&&N(n,`invalid_schema`,`$schema`,`$schema must be ${oe}`),i===void 0?N(n,`missing_field`,`version`,`version is required`):typeof i!=`number`||!Number.isInteger(i)?N(n,`invalid_type`,`version`,`version must be a whole number`):i>1?N(n,`unsupported_version`,`version`,`version ${i} is newer than this reader understands (1)`):i!==1&&N(n,`unsupported_version`,`version`,`version ${i} is not supported`),r===`https://s-m-r-t.dev/schemas/blueprint/v1.json`&&P(n,`migrated_schema`,`$schema`,`$schema uses the legacy blueprint URL; migrated`);for(let t of[`name`,`description`])e[t]!==void 0&&typeof e[t]!=`string`&&N(n,`invalid_type`,t,`${t} must be a string`);let a=[];if(!M(e.recipes))N(n,`invalid_type`,`recipes`,`recipes must be a list of recipe ids`);else if(a=[...new Set(e.recipes)].sort(),t.recipes){let r=new Set(t.recipes);for(let t of a)r.has(t)||N(n,`unknown_recipe`,`recipes[${e.recipes.indexOf(t)}]`,`recipes: unknown recipe "${t}"`)}let o=[];e.features!==void 0&&(M(e.features)?(o=[...new Set(e.features)].sort(),o.length!==e.features.length&&P(n,`duplicate_value`,`features`,`features listed a model more than once; deduplicated`)):N(n,`invalid_type`,`features`,`features must be a list of model names`));let s=[];if(!Array.isArray(e.policies))N(n,`invalid_type`,`policies`,`policies must be a list`);else for(let[t,r]of e.policies.entries())me(r,`policies[${t}]`,n),s.push(r);if(e.exposure!==void 0&&(fe(e.exposure,e=>M(e)&&e.every(e=>ce.has(e)))||N(n,`invalid_value`,`exposure`,`exposure must map model names to lists of api, mcp or cli`)),e.layout!==void 0&&he(e.layout,n),e.theme!==void 0&&ge(e.theme,n),j(e.theme)&&typeof e.theme.preset==`string`){let r=t.themePresets?new Set(t.themePresets):void 0;r&&!r.has(e.theme.preset)&&N(n,`unknown_theme_preset`,`theme.preset`,`Unknown theme preset "${e.theme.preset}".`)}if(j(e.layout)&&e.layout.version===1&&t.layout){let r=t.layout.sections?new Set(t.layout.sections):void 0,i=t.layout.items?new Set(t.layout.items):void 0,a=t.layout.placementItems?new Set(t.layout.placementItems):void 0;if(r&&Array.isArray(e.layout.customSections))for(let t of e.layout.customSections)j(t)&&typeof t.id==`string`&&r.add(t.id);let o=(e,t)=>t===`section`?r?.has(e)!==!1:t===`item`?i?.has(e)!==!1:r?.has(e)===!0||i?.has(e)===!0||!r&&!i,s=(e,t,r)=>{typeof e==`string`&&!o(e,r)&&N(n,`unknown_layout_id`,t,`Unknown layout ${r===`either`?`section or item`:r} "${e}".`)};if(M(e.layout.sectionOrder)&&e.layout.sectionOrder.forEach((e,t)=>{s(e,`layout.sectionOrder[${t}]`,`section`)}),M(e.layout.hidden)&&e.layout.hidden.forEach((e,t)=>{s(e,`layout.hidden[${t}]`,`either`)}),j(e.layout.itemOrder))for(let[t,n]of Object.entries(e.layout.itemOrder))s(t,`layout.itemOrder.${t}`,`section`),M(n)&&n.forEach((e,n)=>{s(e,`layout.itemOrder.${t}[${n}]`,`item`)});if(j(e.layout.moved))for(let[t,n]of Object.entries(e.layout.moved))s(t,`layout.moved.${t}`,`item`),s(n,`layout.moved.${t}`,`section`);for(let t of[`sections`,`items`])if(j(e.layout[t]))for(let n of Object.keys(e.layout[t]))s(n,`layout.${t}.${n}`,t===`sections`?`section`:`item`);if(j(e.layout.placements))for(let t of Object.keys(e.layout.placements))a&&!a.has(t)&&N(n,`unknown_layout_id`,`layout.placements.${t}`,`Unknown layout placement item "${t}".`)}let c={};if(e.overviews!==void 0){if(!j(e.overviews)||Object.hasOwn(e.overviews,`__proto__`))N(n,`invalid_type`,`overviews`,`overviews must map overview ids to overrides`);else{let r=t.overviewIds?new Set(t.overviewIds):void 0;for(let[i,a]of Object.entries(e.overviews)){let e=`overviews.${i}`;if(!_e.test(i)){P(n,`invalid_overview_id`,e,`${e} was dropped because its overview id is invalid`);continue}if(r&&!r.has(i)){P(n,`unknown_overview`,e,`Unknown overview "${i}" was dropped.`);continue}let o=Ce(a,e,n);if(!o)continue;if(!t.validateOverview){c[i]=o;continue}let s;try{s=t.validateOverview(i,o)}catch{P(n,`overview_validation_failed`,e,`Overview "${i}" was dropped because its host validator failed.`);continue}for(let t of s.diagnostics??[])P(n,t.code,t.path||e,t.message);!s.ok&&s.diagnostics.length===0&&P(n,`overview_rejected`,e,`Overview "${i}" was rejected by its host validator and dropped.`),s.ok&&s.override&&(c[i]=s.override)}}}let l=n.filter(e=>e.severity===`error`).map(e=>e.message);if(l.length)return{ok:!1,errors:l,diagnostics:n};let u={...e,$schema:oe,version:1,recipes:a,features:o,policies:s};return e.exposure!==void 0&&(u.exposure=e.exposure),e.layout!==void 0&&(u.layout=e.layout),e.theme!==void 0&&(u.theme=e.theme),delete u.overviews,Object.keys(c).length&&(u.overviews=c),{ok:!0,cookbook:u,warnings:n.filter(e=>e.severity===`warning`).map(e=>e.message),diagnostics:n}}var F=e=>e===void 0?e:structuredClone(e),Te=(e,t)=>JSON.stringify(e??null)===JSON.stringify(t??null),Ee=()=>({$schema:oe,version:1,recipes:[],features:[],policies:[]});function De(e){return!e.recipes.length&&!e.features.length&&!e.policies.length&&!Object.keys(e.exposure??{}).length&&!e.layout&&!e.theme&&!Object.keys(e.overviews??{}).length}var Oe=e=>[...new Set(e)].sort();function ke(e){let t=new Set([`$schema`,`version`,`name`,`description`,`recipes`,`features`,`policies`,`exposure`,`layout`,`theme`,`overviews`]),n={$schema:oe,version:1,...e.name?{name:e.name}:{},...e.description?{description:e.description}:{},recipes:Oe(e.recipes),features:Oe(e.features),policies:[...e.policies].sort((e,t)=>e.objectRef.localeCompare(t.objectRef)||e.fieldName.localeCompare(t.fieldName)).map(e=>({...e}))},r=Object.fromEntries(Object.keys(e.exposure??{}).sort().filter(t=>e.exposure?.[t]?.length).map(t=>[t,[...e.exposure?.[t]??[]].sort()]));Object.keys(r).length&&(n.exposure=r),e.layout&&(n.layout=F(e.layout));let i=Xe(e.theme);i&&(n.theme=i);let a=Object.entries(e.overviews??{}).sort(([e],[t])=>e<t?-1:+(e>t));a.length&&(n.overviews=Object.fromEntries(a.map(([e,t])=>[e,F(t)])));for(let[r,i]of Object.entries(e))t.has(r)||(n[r]=F(i));return n}var I=e=>new Map(e.recipes.map(e=>[e.id,e]));function Ae(e,t){let n=new Set,r=e=>{let i=t.get(e);if(i&&!n.has(e)){n.add(e);for(let e of i.requires)r(e)}};for(let t of e)r(t);let i=!0;for(;i;){i=!1;for(let e of[...n])for(let a of t.get(e)?.requiresAny??[]){if(a.some(e=>n.has(e)))continue;let e=a.find(e=>t.has(e));e&&(r(e),i=!0)}}return Oe(n)}function je(e,t){let n=I(e);return new Set([...t.recipes.flatMap(e=>n.get(e)?.models??[]),...t.features])}function Me(e){return e.settingTargets??S}function Ne(e,t){return Object.values(Me(e)).some(e=>e.some(e=>e.model===t.objectRef&&e.field===t.fieldName))}function Pe(e,t){let n=je(e,t),r={...t,policies:t.policies.filter(t=>n.has(t.objectRef)||Ne(e,t))};if(t.exposure){let e=Object.fromEntries(Object.entries(t.exposure).filter(([e])=>n.has(e)));Object.keys(e).length?r.exposure=e:delete r.exposure}return r}var Fe=(e,t)=>{let n=I(e);return t.recipes.filter(e=>n.has(e))},Ie=(e,t)=>{let n=I(e);return t.recipes.filter(e=>!n.has(e))};function Le(e,t){let n=new Set(e),r=new Set(t);return{added:t.filter(e=>!n.has(e)),removed:e.filter(e=>!r.has(e))}}function Re(e,t,n){let r=I(e),i=Fe(e,t),a=Ae([...i,...n],r);return{doc:{...t,recipes:Oe([...a,...Ie(e,t)])},changes:{...Le(i,a),kept:[]}}}function ze(e,t,n){let r=I(e),i=Fe(e,t),a=new Set(n),o=Ae(i.filter(e=>!a.has(e)),r),s=Pe(e,{...t,recipes:Oe([...o,...Ie(e,t)])}),{added:c,removed:l}=Le(i,o);return{doc:s,changes:{added:c,removed:l,kept:n.filter(e=>o.includes(e)&&i.includes(e))}}}function Be(e,t,n,r){let i=new Set(t.features);for(let e of n)r?i.add(e):i.delete(e);let a=[...i].sort(),o={...t,features:a};return r||(o=Pe(e,o)),{doc:o,changes:{...Le(t.features,a),kept:[]}}}var Ve=(e,t)=>({added:[...e.added,...t.added],removed:[...e.removed,...t.removed],kept:[...e.kept,...t.kept]}),He={currency:`USD`,taxRate:0,paymentTerms:``,pricesIncludeTax:!1,taxRounding:`line`},Ue=[`currency`,`taxRate`,`paymentTerms`,`pricesIncludeTax`,`taxRounding`];function We(e){if(e?.defaultValue!==void 0&&e.defaultValue!==null)try{return JSON.parse(e.defaultValue)}catch{return}}var Ge=(e,t,n)=>e.find(e=>e.scopeType===`app`&&e.objectRef===t&&e.fieldName===n);function Ke(e,t){let n=Me(e),r={...He},i=(e,r)=>{for(let{model:i,field:a}of n[e]){let e=We(Ge(t.policies,i,a));if(typeof e===r)return e}},a=i(`currency`,`string`),o=i(`taxRate`,`number`),s=i(`paymentTerms`,`string`),c=i(`pricesIncludeTax`,`string`),l=i(`taxRounding`,`string`);return typeof a==`string`&&(r.currency=a),typeof o==`number`&&(r.taxRate=o),typeof s==`string`&&(r.paymentTerms=s),(c===`inclusive`||c===`exclusive`)&&(r.pricesIncludeTax=c===`inclusive`),(l===`line`||l===`document`)&&(r.taxRounding=l),r}var qe=e=>e==null||e===``;function Je(e,t,n,r){let i=I(e);for(let e of t.recipes){let t=i.get(e)?.options?.[n]?.fields?.[r];if(t&&`default`in t)return t.default}return A(e,n)?.fields?.find(e=>e.name===r)?.default}function Ye(e,t,n){let r=Me(e),i=t.policies.map(e=>({...e}));for(let a of Ue){let o=n[a],s=a===`paymentTerms`?String(o).trim():a===`currency`?String(o).trim().toUpperCase():a===`pricesIncludeTax`?o?`inclusive`:`exclusive`:o;for(let{model:n,field:o}of r[a]){let r=Je(e,t,n,o),c=!qe(s)&&!(!qe(r)&&r===s)&&!(qe(r)&&a===`taxRate`&&s===0),l=Ge(i,n,o);if(c){let e=JSON.stringify(s);l?l.defaultValue=e:i.push({objectRef:n,fieldName:o,scopeType:`app`,defaultValue:e})}else l&&(delete l.defaultValue,Object.keys(l).length<=3&&(i=i.filter(e=>e!==l)))}}return{...t,policies:i}}function Xe(e){if(!e)return;let t={};return e.preset&&(t.preset=e.preset),e.colorScheme&&(t.colorScheme=e.colorScheme),e.borderRadius&&(t.borderRadius=e.borderRadius),e.density&&(t.density=e.density),e.contrast&&(t.contrast=e.contrast),e.fontFamily&&(t.fontFamily=e.fontFamily),e.custom&&(t.custom={...e.custom}),e.customCss&&(t.customCss=e.customCss),Object.keys(t).length?t:void 0}function Ze(e){let t=e?.colorScheme??`system`,n=e?.custom?`brand colour ${e.custom.primary}`:e?.preset??`smrt`;return t===`system`?n:`${n}, ${t}`}function Qe(e,t){let n={...e.theme??{}};t.preset&&(n.preset=t.preset,delete n.custom),t.primary&&(n.custom={primary:t.primary.toLowerCase(),...e.theme?.custom?.fontFamily?{fontFamily:e.theme.custom.fontFamily}:{}}),t.colorScheme&&(n.colorScheme=t.colorScheme),t.borderRadius&&(n.borderRadius=t.borderRadius),t.density&&(n.density=t.density),t.contrast&&(n.contrast=t.contrast),t.fontFamily===null?(delete n.fontFamily,n.custom?.fontFamily&&(n.custom={primary:n.custom.primary})):t.fontFamily!==void 0&&(n.fontFamily=t.fontFamily);let r=Xe(n),i={...e};return r?i.theme=r:delete i.theme,i}function $e(e,t){let n=[],r=(e,t,r,i)=>n.push({severity:e,code:t,path:r,message:i}),i=we(t);if(!i.ok){for(let e of i.diagnostics.filter(e=>e.severity===`error`))r(`error`,`invalid_document`,e.path,e.message);return n}for(let e of i.diagnostics)r(e.severity,e.code===`migrated_schema`?`migrated`:e.code,e.path,e.message);let a=i.cookbook,o=I(e),s=te(e,{...a,layout:void 0}),c=we(a,{themePresets:e.themePresets??b,layout:{sections:s.map(e=>e.id),items:s.flatMap(e=>e.items.map(e=>e.id)),...e.placementItems?{placementItems:e.placementItems}:{}},overviewIds:[...s.map(e=>e.id),...(a.layout?.customSections??[]).map(e=>e.id)]});for(let e of c.diagnostics)(e.code===`unknown_theme_preset`||e.code===`unknown_layout_id`||e.code===`unknown_overview`)&&r(e.code===`unknown_layout_id`&&!e.path.startsWith(`layout.placements.`)?`warning`:e.severity,e.code===`unknown_theme_preset`?`unknown_preset`:e.code,e.path,e.message);for(let[e,t]of a.recipes.entries())o.has(t)||r(`error`,`unknown_recipe`,`recipes[${e}]`,`Unknown recipe "${t}".`);let l=new Set(Ae(a.recipes,o));for(let e of l)a.recipes.includes(e)||r(`error`,`missing_requirement`,`recipes`,`A recipe needs "${e}", which is not listed.`);for(let[t,n]of a.features.entries()){let i=A(e,n);i?i.exposed===!1&&r(`error`,`model_not_exposed`,`features[${t}]`,`${n} cannot be added as a feature.`):r(`error`,`unknown_model`,`features[${t}]`,`Unknown model "${n}".`)}let u=je(e,a);for(let[t,n]of a.policies.entries()){let i=`policies[${t}]`,a=A(e,n.objectRef);a?(a.fields&&!a.fields.some(e=>e.name===n.fieldName&&!e.system)&&r(`error`,`unknown_field`,`${i}.fieldName`,`${a.name} has no field "${n.fieldName}".`),!u.has(n.objectRef)&&!Ne(e,n)&&r(`warning`,`policy_not_covered`,i,`${a.name} is not in the app, so this row has no effect.`)):r(`error`,`unknown_model`,`${i}.objectRef`,`Unknown model "${n.objectRef}".`)}for(let t of Object.keys(a.exposure??{}))A(e,t)||r(`error`,`unknown_model`,`exposure.${t}`,`Unknown model "${t}".`);return n}var L=(e,t,n={})=>({ok:!1,error:{code:e,message:t,...n}}),R=(e,t=``,n={})=>({ok:!0,state:e,summary:t,...n}),et=`This replaces the recipes, options, menu and look. Send replace: true to confirm.`,z=e=>e.join(`, `);function tt(e){return`${(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`my-app`}.cookbook.json`}var nt=e=>`${JSON.stringify(e,null,2)}\n`;function rt(e,t){let n=new Map(e.recipes.map(e=>[e.id,e])),r=t.recipes.filter(e=>n.has(e)),i=t.recipes.filter(e=>!n.has(e));return ke(Pe(e,{...F(t),recipes:[...Ae(r,n),...i]}))}function it(e,t){return t?e.cookbooks?.find(e=>e.id===t)?.name:void 0}var at=(e,t)=>{let n=t=>e.recipes.find(e=>e.id===t)?.label??t;return[t.added.length?`Added ${z(t.added.map(n))}.`:``,t.removed.length?`Removed ${z(t.removed.map(n))}.`:``,t.kept.length?`Kept ${z(t.kept.map(n))} (needed).`:``].filter(Boolean).join(` `)},ot=(e,t)=>[t.added.length?`Added ${z(t.added.map(t=>O(e,t)))}.`:``,t.removed.length?`Removed ${z(t.removed.map(t=>O(e,t)))}.`:``].filter(Boolean).join(` `),st=e=>`${Number((e*100).toFixed(4))}%`,B=(e,t)=>({...e,doc:ke(t)});function ct(e,t){let n=te(e,t);return{sections:n,section:e=>n.find(t=>t.id===e),item:e=>n.flatMap(e=>e.items).find(t=>t.id===e)}}var lt=(e,t)=>{let n={...e};return t?n.layout=t:delete n.layout,n},ut={add_recipes(e,t,{ids:n}){let r=n.filter(t=>!e.recipes.some(e=>e.id===t));if(r.length)return L(`not_found`,`No such recipe: ${z(r)}.`,{path:`input.ids`});let{doc:i,changes:a}=Re(e,t.doc,n);return R(B(t,i),at(e,a),{changes:a})},remove_recipes(e,t,{ids:n}){let{doc:r,changes:i}=ze(e,t.doc,n);return R(B(t,r),at(e,i),{changes:i})},add_features(e,t,{ids:n}){let r=n.filter(t=>!A(e,t)?.exposed);if(r.length)return L(`not_found`,`No such model to add: ${z(r)}.`,{path:`input.ids`});let{doc:i,changes:a}=Be(e,t.doc,n,!0);return R(B(t,i),ot(e,a),{changes:a})},remove_features(e,t,{ids:n}){let{doc:r,changes:i}=Be(e,t.doc,n,!1);return R(B(t,r),ot(e,i),{changes:i})},add_cookbook(e,t,{id:n}){let r=e.cookbooks?.find(e=>e.id===n);if(!r)return L(`not_found`,`No cookbook "${n}".`,{path:`input.id`});let i=Re(e,t.doc,r.document.recipes),a=Be(e,i.doc,r.document.features.filter(t=>A(e,t)?.exposed),!0),o=Ve(i.changes,a.changes);return R(B(t,a.doc),o.added.length?`Added the ${r.name} cookbook.`:``,{changes:o})},remove_cookbook(e,t,{id:n}){let r=e.cookbooks?.find(e=>e.id===n);if(!r)return L(`not_found`,`No cookbook "${n}".`,{path:`input.id`});let i=ze(e,t.doc,r.document.recipes),a=Be(e,i.doc,r.document.features,!1),o=Ve(i.changes,a.changes);return R(B(t,a.doc),[at(e,i.changes),ot(e,a.changes)].filter(Boolean).join(` `),{changes:o})},apply_cookbook(e,t,{id:n,replace:r}){let i=e.cookbooks?.find(e=>e.id===n);return i?!r&&!De(t.doc)?L(`confirmation_required`,et):R({doc:rt(e,i.document),applied:n},`${i.name} set up.`):L(`not_found`,`No cookbook "${n}".`,{path:`input.id`})},import_cookbook(e,t,{document:n,replace:r}){let i=we(n);if(!i.ok)return L(`invalid_input`,i.errors[0]??`Not a cookbook.`,{path:`input.document`,details:{errors:i.errors}});if(!r&&!De(t.doc))return L(`confirmation_required`,et);let a=i.cookbook.recipes.length;return R({doc:rt(e,i.cookbook),applied:null},`Imported ${a} ${a===1?`recipe`:`recipes`}.`,i.warnings.length?{warnings:i.warnings}:{})},set_settings(e,t,n){let r=Ke(e,t.doc),i={...r},a=[];if(n.currency!==void 0){let t=n.currency.trim().toUpperCase();if(e.currencies&&!e.currencies.includes(t))return L(`invalid_input`,`${t} is not a known currency.`,{path:`input.currency`});if(!/^[A-Z]{3}$/.test(t))return L(`invalid_input`,`currency must be a three-letter code.`,{path:`input.currency`});t!==r.currency&&(i.currency=t,a.push(`currency ${t}`))}if(n.taxRate!==void 0){let e=Number((n.taxRate/100).toFixed(6));e!==r.taxRate&&(i.taxRate=e,a.push(`tax ${st(e)}`))}if(n.paymentTerms!==void 0){let e=[...n.paymentTerms].map(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127?` `:e).join(``).trim();if(!e)return L(`invalid_input`,`paymentTerms must not be empty.`,{path:`input.paymentTerms`});e!==r.paymentTerms&&(i.paymentTerms=e,a.push(`terms ${e}`))}if(n.pricesIncludeTax!==void 0&&n.pricesIncludeTax!==r.pricesIncludeTax&&(i.pricesIncludeTax=n.pricesIncludeTax,a.push(n.pricesIncludeTax?`prices include tax`:`prices exclude tax`)),n.taxRounding!==void 0&&n.taxRounding!==r.taxRounding&&(i.taxRounding=n.taxRounding,a.push(`${n.taxRounding} tax rounding`)),!a.length)return R(t);let o=a.join(`, `);return R(B(t,Ye(e,t.doc,i)),`${o[0].toUpperCase()}${o.slice(1)}.`)},set_policy(e,t,n){let r=A(e,n.model);if(!r)return L(`not_found`,`No such model: ${n.model}.`,{path:`input.model`});if(r.fields){let e=r.fields.find(e=>e.name===n.field);if(!e||e.system)return L(`not_found`,`${r.name} has no field ${n.field}.`,{path:`input.field`})}if(!je(e,t.doc).has(r.id))return L(`not_found`,`${D(r.name)} is not in the app yet; add its recipe or feature first.`,{path:`input.model`});if(t.doc.recipes.some(t=>e.recipes.find(e=>e.id===t)?.options?.[r.id]?.fields?.[n.field]?.locked))return L(`failed`,`${n.field} is locked by its recipe.`,{path:`input.field`});let i=t.doc.policies.map(e=>({...e})),a=i.find(e=>e.objectRef===r.id&&e.fieldName===n.field),o=a??{objectRef:r.id,fieldName:n.field,scopeType:`app`},s=JSON.stringify(o);for(let e of[`visibility`,`label`,`help`]){let t=n[e];t!==void 0&&(t===null?delete o[e]:o[e]=t)}if(n.defaultValue!==void 0){if(n.defaultValue===null)delete o.defaultValue;else{let e=JSON.stringify(n.defaultValue);if(e===void 0)return L(`invalid_input`,`defaultValue is not a JSON value.`,{path:`input.defaultValue`});o.defaultValue=e}}let c=Object.keys(o).length<=3;if(JSON.stringify(o)===s||c&&!a)return R(t);let l=i.filter(e=>e!==a);return R(B(t,{...t.doc,policies:c?l:[...l,o]}),`Updated ${D(r.name)} ${n.field}.`)},set_theme(e,t,n){let r=Qe(t.doc,n);return JSON.stringify(ke(r).theme??null)===JSON.stringify(t.doc.theme??null)?R(t):R(B(t,r),`Theme: ${Ze(ke(r).theme)}.`)},reset_theme(e,t){if(!t.doc.theme)return R(t);let n={...t.doc};return delete n.theme,R(B(t,n),`Theme: default.`)},set_name(e,t,n){let r={...t.doc};for(let e of[`name`,`description`]){let t=n[e];if(t===void 0)continue;let i=t?.trim();i?r[e]=i:delete r[e]}return JSON.stringify(ke(r))===JSON.stringify(t.doc)?R(t):R(B(t,r),n.name?`Named the app ${n.name.trim()}.`:`Updated the app details.`)},rename_section(e,t,{id:n,label:r}){let i=ct(e,t.doc).section(n);if(!i)return L(`not_found`,`No menu section "${n}".`,{path:`input.id`});let a=re(t.doc.layout,i,r);return JSON.stringify(a??null)===JSON.stringify(t.doc.layout??null)?R(t):R(B(t,lt(t.doc,a)),`Renamed the section to ${r.trim()}.`)},rename_item(e,t,{id:n,label:r}){let i=ct(e,t.doc).item(n);if(!i)return L(`not_found`,`No menu entry "${n}".`,{path:`input.id`});let a=ie(t.doc.layout,i,r);return JSON.stringify(a??null)===JSON.stringify(t.doc.layout??null)?R(t):R(B(t,lt(t.doc,a)),r?`Renamed the entry to ${r.trim()}.`:`Entry name restored.`)},hide(e,t,{id:n}){let r=ct(e,t.doc);return r.section(n)??r.item(n)?t.doc.layout?.hidden?.includes(n)?R(t):R(B(t,lt(t.doc,ae(t.doc.layout,n,!0))),`Hidden.`):L(`not_found`,`No menu section or entry "${n}".`,{path:`input.id`})},show(e,t,{id:n}){let r=ct(e,t.doc);return!r.section(n)&&!r.item(n)?L(`not_found`,`No menu section or entry "${n}".`,{path:`input.id`}):t.doc.layout?.hidden?.includes(n)?R(B(t,lt(t.doc,ae(t.doc.layout,n,!1))),`Shown.`):R(t)},validate(e,t){let n=$e(e,t.doc);return R(t,``,{data:{ok:!n.some(e=>e.severity===`error`),diagnostics:n}})},export_cookbook(e,t,{name:n}){return R(t,``,{data:{fileName:tt(n??t.doc.name??it(e,t.applied)),text:nt(t.doc),cookbook:F(t.doc)}})}};function dt(e,t,n,r){let i=ut[n];return i?i(e,t,r):L(`unknown_command`,`No command "${n}".`)}var ft=(e,t)=>({type:`array`,description:e,minItems:1,maxItems:50,items:t?.length?{type:`string`,enum:[...t]}:{type:`string`,minLength:1}}),pt=(e,t={})=>({type:`string`,description:e,minLength:1,maxLength:200,...t}),V=(e,t=[])=>({type:`object`,properties:e,...t.length?{required:t}:{},additionalProperties:!1});function mt(e){let t=e.recipes.map(e=>e.id),n=(e.cookbooks??[]).map(e=>e.id),r=e.themePresets??b,i=e=>({type:`string`,description:e,...n.length?{enum:[...n]}:{minLength:1}}),a=e=>pt(`The id of ${e}, as the plan snapshot's "sections" lists it.`),o={type:`boolean`,description:`Confirm replacing what is there.`};return[{name:`add_recipes`,description:`Switch recipes on. Recipes they require come along. Returns what was added.`,inputSchema:V({ids:ft(`Recipe ids to add.`,t)},[`ids`])},{name:`remove_recipes`,description:`Switch recipes off. A recipe another one needs is kept and reported.`,inputSchema:V({ids:ft(`Recipe ids to remove.`,t)},[`ids`])},{name:`add_features`,description:"Add single models no recipe covers, by qualified name (`@scope/pkg:Class`).",inputSchema:V({ids:ft(`Qualified model names to add.`)},[`ids`])},{name:`remove_features`,description:`Remove single models added with add_features.`,inputSchema:V({ids:ft(`Qualified model names to remove.`)},[`ids`])},{name:`add_cookbook`,description:`Add the recipes and features of a ready-made cookbook to the current app. Nothing is replaced.`,inputSchema:V({id:i(`The cookbook to add.`)},[`id`])},{name:`remove_cookbook`,description:`Remove the recipes and features a ready-made cookbook adds. Ones another recipe needs are kept.`,inputSchema:V({id:i(`The cookbook to remove.`)},[`id`])},{name:`apply_cookbook`,description:`Select a ready-made cookbook: replace the whole app (recipes, options, menu, theme) with it. When the app has anything in it, replace must be true.`,inputSchema:V({id:i(`The cookbook to set up.`),replace:o},[`id`])},{name:`import_cookbook`,description:`Replace the whole app with a cookbook document (version 1). Checked strictly; nothing is applied if it is invalid. When the app has anything in it, replace must be true.`,inputSchema:V({document:{type:`object`,description:`A cookbook document, version 1.`},replace:o},[`document`])},{name:`set_settings`,description:`Change app settings: currency, default tax rate (percent), default payment terms. Applies to new records only.`,inputSchema:V({currency:e.currencies?.length?{type:`string`,description:`ISO 4217 code, e.g. CAD.`,enum:[...e.currencies]}:{type:`string`,description:`ISO 4217 code, e.g. CAD.`,pattern:`^[A-Z]{3}$`},taxRate:{type:`number`,description:`Default tax rate in percent, 0 to 100.`,minimum:0,maximum:100},paymentTerms:{type:`string`,description:`Default payment terms, e.g. "Net 30".`,minLength:1,maxLength:40},pricesIncludeTax:{type:`boolean`,description:`Whether new document prices include tax.`},taxRounding:{enum:[`line`,`document`],description:`Whether tax rounds per line or per document.`}})},{name:`set_policy`,description:`Set one field's policy: default value, visibility, label or help. The model must be covered by a recipe or feature that is on. null clears a part.`,inputSchema:V({model:pt(`Qualified model name, e.g. @happyvertical/smrt-commerce:Order.`),field:pt(`The model field name.`),defaultValue:{description:`The default as a JSON value (a string, number or boolean). null clears it.`},visibility:{enum:[`basic`,`advanced`,`hidden`,null],description:`Whether the field shows in forms and lists.`},label:{type:[`string`,`null`],description:`A different label.`,maxLength:120},help:{type:[`string`,`null`],description:`Help text under the field.`,maxLength:400}},[`model`,`field`])},{name:`set_theme`,description:`Change the look: a preset, a brand colour, light or dark. A preset replaces a brand colour.`,inputSchema:V({preset:{enum:[...r],description:`A built-in theme.`},primary:{type:`string`,description:`Brand colour as #rrggbb.`,pattern:`^#[0-9a-fA-F]{6}$`},colorScheme:{enum:[`light`,`dark`,`system`],description:`Light, dark or follow the device.`},fontFamily:{type:[`string`,`null`],minLength:1,description:`Font key. Null restores the preset font.`},borderRadius:{enum:[`none`,`sm`,`md`,`lg`,`xl`,`full`],description:`Corner roundness.`},density:{enum:[`comfortable`,`touch`],description:`Control size: comfortable, or larger touch targets.`},contrast:{enum:[`auto`,`standard`,`more`],description:`Contrast: auto follows the device, or force standard or more.`}})},{name:`reset_theme`,description:`Go back to the default look.`,inputSchema:V({})},{name:`set_name`,description:`Name and describe the app. null clears a part.`,inputSchema:V({name:{type:[`string`,`null`],minLength:1,maxLength:60},description:{type:[`string`,`null`],minLength:1,maxLength:400}})},{name:`rename_section`,description:`Rename a menu section.`,inputSchema:V({id:a(`the section`),label:pt(`The new name.`,{maxLength:60})},[`id`,`label`])},{name:`rename_item`,description:`Rename a menu entry. A null label restores its own name.`,inputSchema:V({id:a(`the entry`),label:{type:[`string`,`null`],minLength:1,maxLength:60}},[`id`,`label`])},{name:`hide`,description:`Hide a menu section or entry. Nothing is deleted.`,inputSchema:V({id:a(`the section or entry`)},[`id`])},{name:`show`,description:`Show a hidden menu section or entry again.`,inputSchema:V({id:a(`the section or entry`)},[`id`])},{name:`validate`,description:`Check the current cookbook against the catalog and report typed diagnostics. Changes nothing.`,inputSchema:V({})},{name:`export_cookbook`,description:`The cookbook as a <name>.cookbook.json file (text in the result). Changes nothing.`,inputSchema:V({name:pt(`A name for the file.`,{maxLength:60})})},{name:`undo`,description:`Undo an earlier change by the undoId its receipt carried. Refused with a conflict when the plan changed since, unless force is true.`,inputSchema:V({undoId:pt(`The undoId from a receipt.`),force:{type:`boolean`,description:`Undo even after later edits.`}},[`undoId`])}]}function ht(e){return{name:`run_batch`,description:`Run several commands as one atomic batch: all apply or none does. A failure names the command and leaves the plan unchanged.`,inputSchema:{type:`object`,properties:{id:{type:`string`,minLength:1,maxLength:200},expectedRevision:{type:`integer`,minimum:0},commands:{type:`array`,minItems:1,maxItems:50,items:{oneOf:mt(e).map(e=>({type:`object`,properties:{name:{const:e.name},input:e.inputSchema},required:[`name`],additionalProperties:!1}))}}},required:[`commands`],additionalProperties:!1}}}var gt=e=>e===null?`null`:Array.isArray(e)?`array`:Number.isInteger(e)?`integer`:typeof e;function _t(e,t){let n=gt(t);return n===e||e===`number`&&n===`integer`}function vt(e,t,n=`input`){let r=e=>({path:n,message:`${n} ${e}`}),i=e.type;if(i){let e=Array.isArray(i)?i:[i];if(!e.some(e=>_t(e,t)))return r(`must be ${e.join(` or `)}`)}let a=e.enum;if(a&&!a.includes(t))return r(a.length>12?`is not a known value`:`must be one of ${a.map(e=>JSON.stringify(e)).join(`, `)}`);if(typeof t==`string`){let{minLength:n,maxLength:i,pattern:a}=e;if(n!==void 0&&t.length<n)return r(`must not be empty`);if(i!==void 0&&t.length>i)return r(`must be at most ${i} characters`);if(a&&!new RegExp(a).test(t))return r(`has the wrong format`)}if(typeof t==`number`){let{minimum:n,maximum:i}=e;if(!Number.isFinite(t))return r(`must be a finite number`);if(n!==void 0&&t<n)return r(`must be at least ${n}`);if(i!==void 0&&t>i)return r(`must be at most ${i}`)}if(Array.isArray(t)){let{minItems:i,maxItems:a,items:o}=e;if(i!==void 0&&t.length<i)return r(`needs at least ${i} item${i===1?``:`s`}`);if(a!==void 0&&t.length>a)return r(`takes at most ${a} items`);if(o)for(let[e,r]of t.entries()){let t=vt(o,r,`${n}[${e}]`);if(t)return t}}if(gt(t)===`object`){let r=t,{properties:i,required:a,additionalProperties:o}=e;for(let e of a??[])if(r[e]===void 0)return{path:`${n}.${e}`,message:`${n}.${e} is required`};for(let[e,t]of Object.entries(r)){let r=i?.[e];if(!r){if(o===!1)return{path:`${n}.${e}`,message:`${n}.${e} is not an option of this command`};continue}if(t===void 0)continue;let a=vt(r,t,`${n}.${e}`);if(a)return a}}return null}function yt(e){return Object.fromEntries(mt(e).map(e=>[e.name,e.inputSchema]))}var H=(e,t,n={})=>({code:e,message:t,...n}),bt=e=>Array.isArray(e)?e.map(bt):e&&typeof e==`object`?Object.fromEntries(Object.keys(e).sort().map(t=>[t,bt(e[t])])):e,xt=e=>{try{return JSON.stringify(bt(e))??`undefined`}catch{return`unserializable`}};function St(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return{ok:!1,error:H(`unknown_command`,`A command is an object: { name, input }.`)};let r=e,{name:i,input:a={}}=r;if(typeof i!=`string`||!Object.hasOwn(t,i))return{ok:!1,error:H(`unknown_command`,`Unknown command ${JSON.stringify(i)}.`)};for(let e of Object.keys(r))if(e!==`name`&&e!==`input`&&!n.includes(e))return{ok:!1,error:H(`invalid_input`,`${e} is not part of a command.`,{path:e})};let o=vt(t[i],a);return o?{ok:!1,error:H(`invalid_input`,o.message,{path:o.path})}:{ok:!0,name:i,input:a}}var Ct=e=>e===void 0||typeof e==`string`&&e.length>0&&e.length<=200?null:H(`invalid_input`,`id must be a non-empty string of at most 200 characters.`,{path:`id`}),wt=e=>e===void 0||Number.isInteger(e)&&e>=0?null:H(`invalid_input`,`expectedRevision must be a whole number.`,{path:`expectedRevision`});function Tt(e){let{catalog:t}=e,n=yt(t),r=mt(t),i=ht(t),a=e.maxJournal??500,o=e.maxUndo??20,s,c=0,l=new Map;if(e.state){let n=e.state,r=we(n.cookbook);if(!r.ok)throw Error(`Invalid saved cookbook: ${r.errors.join(`; `)}`);if(!Number.isInteger(n.revision)||n.revision<0)throw Error(`Invalid saved revision.`);s={doc:rt(t,r.cookbook),applied:n.applied??null},c=n.revision;for(let e of n.journal??[])l.set(e.id,F(e))}else if(e.cookbook!==void 0){let n=we(e.cookbook);if(!n.ok)throw Error(`Invalid cookbook: ${n.errors.join(`; `)}`);s={doc:rt(t,n.cookbook),applied:null}}else s={doc:rt(t,Ee()),applied:null};let u=new Map,d=[],f=0,p=new Map;function m(e,n){let{doc:r}=e,i=new Map(t.recipes.map(e=>[e.id,e])),a=Ke(t,r),o=new Set(t.models.filter(e=>e.exposed!==!1).map(e=>e.id));return{version:1,revision:n,app:{name:r.name??it(t,e.applied)??`my-app`,description:r.description??null,cookbook:e.applied},recipes:r.recipes.flatMap(e=>{let t=i.get(e);return t?[{id:e,label:t.label}]:[]}),features:r.features.filter(e=>o.has(e)),unavailable:[...r.recipes.filter(e=>!i.has(e)),...r.features.filter(e=>!o.has(e))],settings:{currency:a.currency,taxRate:Number((a.taxRate*100).toFixed(4)),paymentTerms:a.paymentTerms,pricesIncludeTax:a.pricesIncludeTax,taxRounding:a.taxRounding},theme:{text:Ze(r.theme),preset:r.theme?.preset??null,primary:r.theme?.custom?.primary??null,colorScheme:r.theme?.colorScheme??`system`,borderRadius:r.theme?.borderRadius??null,density:r.theme?.density??null,contrast:r.theme?.contrast??null},sections:te(t,r).map(e=>({id:e.id,label:e.label,hidden:e.hidden,items:e.items.map(e=>({id:e.id,label:e.label,hidden:e.hidden}))})),policies:r.policies.length,undo:[...d]}}let h=()=>m(s,c);function g(){for(let[e,t]of p)t!==c&&(p.set(e,c),e(h()))}function _(e,t,n){if(e!==void 0)for(l.set(e,{id:e,fingerprint:t,result:F(n)});l.size>a;){let e=l.keys().next().value;if(e===void 0)break;l.delete(e)}}function v(e,t){if(e===void 0)return null;let n=l.get(e);return n?n.fingerprint===t?{...F(n.result),replayed:!0}:{ok:!1,id:e,error:H(`id_reuse`,`The id "${e}" was already used for a different command.`,{path:`id`})}:null}function y(t,n){let r=`${e.undoPrefix??`undo`}-${++f}`;u.set(r,{before:F(t),after:F(n)}),d=[...d,r].slice(-o);for(let e of[...u.keys()])d.includes(e)||u.delete(e);return r}let b=(e,t)=>e.applied!==t.applied||!Te(e.doc,t.doc);function x(e,t,n,r,i,a,o){return{ok:!0,...e===void 0?{}:{id:e},snapshot:a,receipt:{name:t,...e===void 0?{}:{id:e},summary:i===r?``:n.summary,changed:i!==r,revisionBefore:r,revisionAfter:i,...o?{undoId:o}:{},...n.changes?{changes:n.changes}:{},...n.warnings?{warnings:n.warnings}:{}},...n.data===void 0?{}:{data:n.data}}}function S(e,t){let n=u.get(t.undoId);if(!n)return{ok:!1,...e===void 0?{}:{id:e},error:H(`not_found`,`Nothing to undo for "${t.undoId}".`,{path:`input.undoId`})};if(!t.force&&b(s,n.after))return{ok:!1,...e===void 0?{}:{id:e},error:H(`conflict`,`The plan changed since; send force: true to undo anyway.`,{details:{currentRevision:c}})};let r=c,i=F(n.before),a=b(s,i);s=i,a&&(c+=1),u.delete(t.undoId),d=d.filter(e=>e!==t.undoId);let o=x(e,`undo`,{ok:!0,state:s,summary:`Undone.`},r,c,h());return g(),o}function C(e,r={}){try{let i=e&&typeof e==`object`&&!Array.isArray(e)?e:void 0,a=i?.id,o=Ct(a);if(o)return{ok:!1,error:o};let l=i?.expectedRevision??r.expectedRevision,u=wt(l);if(u)return{ok:!1,...a===void 0?{}:{id:a},error:u};let d=xt({name:i?.name,input:i?.input??{},expectedRevision:l}),f=v(a,d);if(f)return f;let p=e=>(_(a,d,e),e),m=e=>({ok:!1,...a===void 0?{}:{id:a},error:e}),C=St(e,n,[`id`,`expectedRevision`]);if(!C.ok)return p(m(C.error));if(l!==void 0&&l!==c)return p(m(H(`conflict`,`The plan is at revision ${c}, not ${l}. Read the snapshot and try again.`,{details:{expectedRevision:l,currentRevision:c}})));if(C.name===`undo`)return p(S(a,C.input));let w=s,T=dt(t,w,C.name,C.input);if(!T.ok)return p(m(T.error));let E=c,D=b(w,T.state),O;D&&(s=T.state,c+=1,O=y(w,T.state));let ee=p(x(a,C.name,T,E,c,h(),O));return g(),ee}catch(e){return{ok:!1,error:H(`failed`,e instanceof Error?e.message:String(e))}}}function w(e){let r=(e,t)=>({ok:!1,...t===void 0?{}:{id:t},error:e,snapshot:h()});try{if(!e||typeof e!=`object`||Array.isArray(e))return r(H(`invalid_input`,`A batch is an object: { commands }.`));let i=e,a=i.id,o=Ct(a);if(o)return r(o);let l=wt(i.expectedRevision);if(l)return r(l,a);let u=xt({commands:i.commands,expectedRevision:i.expectedRevision}),d=v(a,u);if(d)return`results`in d||`snapshot`in d?d:r(d.error,a);let f=e=>(_(a,u,e),e),p=i.commands;if(!Array.isArray(p)||p.length===0||p.length>50)return f(r(H(`invalid_input`,`commands must be a list of 1 to 50 commands.`,{path:`commands`}),a));let S=i.expectedRevision;if(S!==void 0&&S!==c)return f(r(H(`conflict`,`The plan is at revision ${c}, not ${S}. Read the snapshot and try again.`,{details:{expectedRevision:S,currentRevision:c}}),a));let C=(e,t,n)=>f(r(H(`batch_failed`,`Command ${e+1} (${String(t)}) failed: ${n.message}`,{path:`commands[${e}]`,details:{index:e,cause:n}}),a)),w=s,T=c,E=w,D=T,O=[];for(let[e,r]of p.entries()){let i=St(r,n,[]);if(!i.ok)return C(e,r?.name,i.error);if(i.name===`undo`)return C(e,`undo`,H(`invalid_input`,`undo cannot run inside a batch.`));let a=dt(t,E,i.name,i.input);if(!a.ok)return C(e,i.name,a.error);let o=D;b(E,a.state)&&(D+=1),E=a.state,O.push(x(void 0,i.name,a,o,D,m(E,D)))}let ee=D!==T,k;if(ee){s=E,c=D,k=y(w,E);for(let e of O)e.receipt.changed&&delete e.receipt.undoId}let te=f({ok:!0,...a===void 0?{}:{id:a},snapshot:h(),receipt:{...a===void 0?{}:{id:a},count:O.length,changed:ee,revisionBefore:T,revisionAfter:D,...k?{undoId:k}:{}},results:O});return g(),te}catch(e){return r(H(`failed`,e instanceof Error?e.message:String(e)))}}return{run:C,batch:w,snapshot:h,cookbook:()=>F(s.doc),state:()=>({version:1,revision:c,applied:s.applied,cookbook:F(s.doc),journal:[...l.values()].map(e=>F(e))}),subscribe(e){return p.set(e,c),e(h()),()=>{p.delete(e)}},tools:r,batchTool:i}}var Et=new Set(`AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BRL BSD BTN BWP BYN BZD CAD CDF CHF CLP CNY COP CRC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD UYU UZS VES VND VUV WST XAF XCD XOF XPF YER ZAR ZMW ZWG`.split(` `));function Dt(){let e=c.packages.flatMap(e=>e.models.map(t=>({id:t.id,name:t.name,packageId:e.id,...t.description?{description:t.description}:{},exposed:t.exposed,fields:t.fields.map(e=>({name:e.name,...e.system?{system:!0}:{},...e.default===void 0?{}:{default:e.default}}))})));return{recipes:h,models:e,cookbooks:y.map(e=>({id:e.id,name:e.name,document:e.document})),themePresets:f,currencies:[...Et],settingTargets:v}}var Ot;function kt(){return Ot??=Dt(),Ot}var At=[`cookbooks`,`recipes`,`features`,`layout`,`theme`,`settings`,`export`],jt={name:`focus`,description:`Move the planner's view to a tab and/or a menu section. Navigation only; it changes nothing in the plan.`,inputSchema:{type:`object`,properties:{tab:{enum:[...At],description:`The tab to open.`},section:{type:`string`,minLength:1,maxLength:200,description:`The id of a menu section, as the plan snapshot's "sections" lists it.`}},additionalProperties:!1}};function Mt(e){return[...mt(e),jt]}function Nt(e,t){return Mt({...kt(),recipes:e.map(e=>({id:e,label:e,models:[],nav:[],requires:[]})),cookbooks:t.map(e=>({id:e,name:e,document:{}}))})}var Pt=Nt(h.map(e=>e.id),y.map(e=>e.id));Object.fromEntries(Pt.map(e=>[e.name,e.inputSchema])),Pt.map(e=>e.name);function Ft(e,t,n=`input`){return vt(e,t,n)?.message??null}function It(e){let t=e;return{get:()=>t,set:e=>{t=e}}}var U=(e,t,n={})=>({code:e,message:t,...n}),W=(e,t)=>({ok:!1,...t===void 0?{}:{id:t},error:e}),G=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Lt=new Set([`apply_cookbook`,`import_cookbook`]),Rt=e=>e instanceof Error?e.message:String(e);function zt(e,t){if(!G(e))return JSON.stringify([t,e??null]);let{overviews:n,...r}=e;return JSON.stringify([t,r])}function Bt(e){let{catalog:t,port:n,options:r={},env:i={}}=e,a=i.section??It(null),o=i.tab??It(null),s=Mt(t),c=e=>s.find(t=>t.name===e)?.inputSchema,l=c(`focus`),u=c(`undo`),d,f=``,p=null,m=new Map,h=new Map,g=0,_=new Map,v=()=>n?.applied?.()??null,y=()=>r.navigation?.getTab()??o.get();function b(){if(!n?.read){d=Tt(e.cookbook===void 0?{catalog:t}:{catalog:t,state:{version:1,revision:0,applied:null,cookbook:e.cookbook,journal:[]}});return}let r=n.read();f=zt(r,v());try{d=Tt({catalog:t,state:{version:1,revision:0,applied:v(),cookbook:r,journal:[]}})}catch(e){d=Tt({catalog:t}),p=Rt(e)}}b();function x(e,n){let r=d.state();try{d=Tt({catalog:t,state:{version:1,revision:r.revision+1,applied:v(),cookbook:e,journal:r.journal}}),p=null}catch(e){p=Rt(e)}m=new Map,h=new Map,f=n}function S(){if(n?.read)try{let e=n.read(),t=zt(e,v());if(t===f)return;x(e,t)}catch(e){p=Rt(e)}}let C=()=>U(`failed`,`The app's document is not one the planner can read (${p}). Fix it or reset the cookbook, then try again.`),w=e=>W(C(),e);function T(e){if(!e)return;let t=m.get(e);return t||(t=`undo-${++g}`,m.set(e,t),h.set(t,e)),t}function E(e){let t=new Set(e);for(let[e,n]of m)t.has(e)||(m.delete(e),h.delete(n))}let D=e=>({...e,undo:e.undo.map(e=>T(e)),focus:{tab:y(),section:a.get()}});function O(){let e=d.snapshot();return E(e.undo),D(e)}function ee(e){if(!n?.read)return e;try{let t=n.read(),r=G(t)?t.overviews:void 0,{overviews:i,...a}=e;return ke(G(r)&&Object.keys(r).length?{...a,overviews:r}:a)}catch{return e}}function k(e){if(!e.ok)return e;let{receipt:t}=e,n=e.replayed?void 0:T(t.undoId),{undoId:r,...i}=t,a=e.data;if(t.name===`export_cookbook`&&G(a)&&!e.replayed){let e=ee(a.cookbook);a={...a,cookbook:e,text:`${JSON.stringify(e,null,2)}\n`}}return{...e,...a===void 0?{}:{data:a},snapshot:O(),receipt:{...i,...n?{undoId:n}:{}}}}function te(e,t){if(!n?.write)return;let i=d.snapshot().app.cookbook,a=e.includes(`apply_cookbook`)||i!==null&&i!==t;n.write(d.cookbook(),{commands:e,replaced:e.some(e=>Lt.has(e)),applied:i,libraryApplied:a}),n.read&&(f=zt(n.read(),v())),a&&r.onReplaced?.()}function A(){if(!_.size)return;S();let e=O(),t=JSON.stringify(e);for(let[n,r]of _)r!==t&&(_.set(n,t),n(e))}function ne(e,t){for(let t of Object.keys(e))if(![`name`,`input`,`id`,`expectedRevision`].includes(t))return U(`invalid_input`,`${t} is not part of a command.`,{path:t});let{id:n}=e;if(n!==void 0&&!(typeof n==`string`&&n.length>0&&n.length<=200))return U(`invalid_input`,`id must be a non-empty string of at most 200 characters.`,{path:`id`});let r=e.expectedRevision??t.expectedRevision;return r!==void 0&&!(Number.isInteger(r)&&r>=0)?U(`invalid_input`,`expectedRevision must be a whole number.`,{path:`expectedRevision`}):null}function re(e,t){let n=ne(e,t),i=typeof e.id==`string`?e.id:void 0;if(n)return W(n,i);let s=e.expectedRevision??t.expectedRevision,c=e.input??{},u=Ft(l,c);if(u)return W(U(`invalid_input`,u,{path:`input`}),i);let f=d.snapshot().revision;if(s!==void 0&&s!==f)return W(U(`conflict`,`The plan is at revision ${f}, not ${s}. Read the snapshot and try again.`,{details:{expectedRevision:s,currentRevision:f}}),i);if(c.section!==void 0&&!O().sections.some(e=>e.id===c.section))return W(U(`not_found`,`No menu section "${c.section}".`,{path:`input.section`}),i);let p=!1;c.tab&&At.includes(c.tab)&&(p||=y()!==c.tab,o.set(c.tab),r.navigation?.setTab(c.tab)),c.section!==void 0&&(p||=a.get()!==c.section,a.set(c.section),r.navigation?.setSection?.(c.section));let m={ok:!0,...i===void 0?{}:{id:i},snapshot:O(),receipt:{name:`focus`,...i===void 0?{}:{id:i},summary:``,changed:p,revisionBefore:f,revisionAfter:f}};return A(),m}function ie(e){let t=e.input;if(!n?.prepareImport||!G(t))return{raw:e};let r=n.prepareImport(t.document);return r.ok?{raw:{...e,input:{...t,document:r.cookbook}},dropped:r.dropped}:W(U(`invalid_input`,r.error,{path:`input.document`}),e.id)}function ae(e){if(n?.read&&e.some(e=>typeof e==`string`&&Lt.has(e)))try{let e=n.read();if(De(d.cookbook())&&!De(e)){let n=d.state();d=Tt({catalog:t,state:{version:1,revision:n.revision,applied:v(),cookbook:e,journal:n.journal}}),m=new Map,h=new Map,f=zt(e,v())}}catch(e){p=Rt(e)}}function oe(e,t={}){try{if(S(),p)return w(G(e)&&typeof e.id==`string`?e.id:void 0);if(!G(e))return k(d.run(e,t));if(e.name===`focus`)return re(e,t);if(ae([e.name]),p)return w(typeof e.id==`string`?e.id:void 0);let n=e,r;if(e.name===`import_cookbook`){let t=ie(e);if(`ok`in t)return t;n=t.raw,r=t.dropped}let i=d.snapshot().app.cookbook,a=se(n),o=a?ce(n,t,a):k(d.run(n,t));if(!o.ok)return o;!o.replayed&&o.receipt.changed&&te([String(n.name)],i);let s=o;return r?.length&&(s={...o,receipt:{...o.receipt,warnings:[...o.receipt.warnings??[],...r.map(e=>`Not imported: ${e}`)]}}),A(),s.ok?{...s,snapshot:O()}:s}catch(e){return W(U(`failed`,Rt(e)))}}function se(e){let n=e.input;if(e.name!==`apply_cookbook`||!G(n))return;let r=t.cookbooks?.find(e=>e.id===n.id);if(!r)return;let i=d.cookbook().theme;if(!i)return;let a=r.document.theme;if(a)return a.colorScheme||!i.colorScheme?void 0:{colorScheme:i.colorScheme};let o={};return i.preset&&(o.preset=i.preset),i.custom?.primary&&(o.primary=i.custom.primary),i.colorScheme&&(o.colorScheme=i.colorScheme),i.borderRadius&&(o.borderRadius=i.borderRadius),i.density&&(o.density=i.density),i.contrast&&(o.contrast=i.contrast),Object.keys(o).length?o:void 0}function ce(e,t,n){let r=d.batch({...e.id===void 0?{}:{id:e.id},expectedRevision:e.expectedRevision??t.expectedRevision,commands:[e,{name:`set_theme`,input:n}].map(({id:e,expectedRevision:t,...n})=>n)});if(!r.ok){let t=r.error.details?.cause;return W(r.error.code===`batch_failed`&&t?t:r.error,e.id)}let i=r.results[0],a=r.replayed?void 0:T(r.receipt.undoId);return{...i,...r.id===void 0?{}:{id:r.id},...r.replayed?{replayed:!0}:{},snapshot:O(),receipt:{...i.receipt,...r.id===void 0?{}:{id:r.id},revisionBefore:r.receipt.revisionBefore,revisionAfter:r.receipt.revisionAfter,changed:r.receipt.changed,...a?{undoId:a}:{}}}}function le(e){try{if(S(),p)return{ok:!1,error:C(),snapshot:O()};let t=G(e)&&Array.isArray(e.commands)?e.commands:[];if(ae(t.map(e=>G(e)?e.name:void 0)),p)return{ok:!1,error:C(),snapshot:O()};let n=d.snapshot().app.cookbook,r=d.batch(e);if(!r.ok)return{...r,snapshot:O()};!r.replayed&&r.receipt.changed&&te(t.map(e=>String(e?.name)),n);let i=r.replayed?void 0:T(r.receipt.undoId),{undoId:a,...o}=r.receipt,s=O(),c={...r,snapshot:s,receipt:{...o,...i?{undoId:i}:{}},results:r.results.map(e=>({...e,snapshot:r.replayed?s:D(e.snapshot)}))};return A(),c}catch(e){return{ok:!1,error:U(`failed`,Rt(e)),snapshot:O()}}}function ue(e){if(!G(e)||e.name!==`undo`||!G(e.input))return e;let t=e.input.undoId;return typeof t==`string`?{...e,input:{...e.input,undoId:h.get(t)??``}}:e}function de(e,t){if(e.ok||e.error.code!==`not_found`)return e;let n=h.get(t);return n?{...e,error:{...e.error,message:e.error.message.replace(`"${n}"`,`"${t}"`)}}:e}let j=(e,t)=>{if(G(e)&&e.name===`undo`&&G(e.input)){let n=e.input.undoId;if(typeof n==`string`&&Ft(u,e.input)===null)return S(),O(),h.has(n)?de(oe(ue(e),t),n):W(U(`not_found`,`Nothing to undo for "${n}".`,{path:`input.undoId`}),e.id)}return oe(ue(e),t)};return{run:j,batch:le,snapshot(){return S(),O()},cookbook(){return S(),ee(d.cookbook())},undo(){S();let e=O().undo.at(-1);return e?j({name:`undo`,input:{undoId:e}}):W(U(`not_found`,`Nothing to undo.`))},state:()=>d.state(),get tools(){return s},get batchTool(){return d.batchTool},observe(){return S(),JSON.stringify(O())},deliver:A,subscribe(e){i.watch?.start(),S();let t=O();return _.set(e,JSON.stringify(t)),e(t),()=>{_.delete(e),_.size||i.watch?.stop()}}}}function Vt(e){return e.recipes.length===0&&e.features.length===0&&e.policies.length===0&&Object.keys(e.exposure??{}).length===0&&e.theme===void 0&&l(e.layout)}function Ht(e){if(!e.theme?.colorScheme)return e;let{colorScheme:t,...n}=e.theme;return{...e,theme:Object.keys(n).length?n:void 0}}function Ut(e){return JSON.stringify(Ht(e))}function Wt(e,t){let n=Ht(e);return Vt(n)?!1:t===null||JSON.stringify(n)!==t}function Gt(e,t,n){return t(n?g(structuredClone(e.document),n):e.document)}var Kt=`smrt-planner:cookbook`,qt=`smrt-planner:cookbook-applied`,Jt=new class{#e=t(null);get active(){return e(this.#e)}set active(e){o(this.#e,e,!0)}#t=t(null);get appliedWork(){return e(this.#t)}set appliedWork(e){o(this.#t,e,!0)}load(e=u()){try{this.active=e?.getItem(`smrt-planner:cookbook`)??null,this.appliedWork=e?.getItem(`smrt-planner:cookbook-applied`)??null}catch{this.active=null,this.appliedWork=null}s(this.active)}select(e,t=null,n=u()){this.active=e,this.appliedWork=t;try{n?.setItem(Kt,e),t===null?n?.removeItem(qt):n?.setItem(qt,t)}catch{}}};function Yt(n){let i=t(r(n));return{get:()=>e(i),set:e=>{o(i,e,!0)}}}function Xt(e){return{read:()=>e.snapshot(),applied:()=>Jt.active,prepareImport:e=>m(e),write(t,{replaced:n,applied:r,libraryApplied:i}){let a=n?t:{...t,overviews:e.snapshot().overviews};n?e.replace(a):e.apply(a),i&&r&&(Jt.select(r,Ut(e.snapshot())),s(r))}}}function Zt(e=p,t={}){let r,o=Bt({catalog:kt(),port:Xt(e),options:t,env:{section:Yt(null),tab:Yt(null),watch:{start(){r||=a(()=>{n(()=>{o.observe(),i(o.deliver)})})},stop(){r?.(),r=void 0}}}});return o}var Qt=()=>({$schema:d,version:1,recipes:[],features:[],policies:[]});function $t(e){let{store:t,settings:n,theme:r}=e;return{read(){let e={...Qt(),recipes:[...t.ids].sort()};n&&(e=g(e,n.read()));let i=r?.read();return i?{...e,theme:i}:e},write(e){let i=new Set(e.recipes),a=new Set(t.ids),o=[...a].filter(e=>!i.has(e));o.length&&t.remove(...o);let s=[...i].filter(e=>!a.has(e));s.length&&t.add(...s),n&&n.write(_(e)),r?.write(e.theme)}}}function en(e,t={}){return Bt({catalog:kt(),port:$t(e),options:t})}var tn=[`cookbooks`,`recipes`,`features`,`layout`,`theme`,`settings`,`export`];function nn(e,t=`cookbooks`){let n=new URLSearchParams(e).get(`tab`);return tn.find(e=>e===n)??t}var rn=new class{#e=t(`cookbooks`);get active(){return e(this.#e)}set active(e){o(this.#e,e,!0)}fromSearch(e,t=`cookbooks`){this.active=nn(e,t)}leaveExport(e=`cookbooks`){this.active===`export`&&(this.active=e)}},an={},on=Zt(p,{navigation:{getTab:()=>rn.active,setTab:e=>{rn.active=e},setSection:e=>an.openSection?.(e)},onReplaced:()=>an.onReplaced?.()}),sn=class extends Error{code;category;details;cause;constructor(e,t,n,r,i){super(e),this.name=this.constructor.name,this.code=t,this.category=n,this.details=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,category:this.category,details:this.details,stack:this.stack,cause:this.cause?{name:this.cause.name,message:this.cause.message,stack:this.cause.stack}:void 0}}},K=Object.freeze({maxTitleLength:120,maxDescriptionLength:500,maxDimensions:4,maxMeasures:6,maxFilters:12,maxHaving:4,maxSort:3,maxInValues:100,maxStringValueLength:256,defaultRowLimit:100,maxRowLimit:1e3,maxAliasLength:40,maxFieldNameLength:64,maxSourceIdLength:120}),cn=[`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`],ln=[`count`,`countDistinct`,`sum`,`avg`,`min`,`max`],un=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`contains`,`isNull`,`isNotNull`],dn=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`],fn=[`table`,`bar`,`line`,`pie`,`stat`],q=class extends sn{code;path;status;constructor(e,t,n){super(t?`${t}: ${n}`:n,e,`validation`),this.name=`RuntimeReportError`,this.code=e,this.path=t,this.status=e===`tenant_required`||e===`confirmation_required`?403:e===`invalid_result`?500:422}};function J(e,t){throw new q(`invalid_spec`,e,t)}var pn=new Set(`all.and.as.asc.between.by.case.cast.check.column.constraint.create.cross.default.delete.desc.distinct.drop.else.end.except.exists.false.for.foreign.from.full.group.having.in.inner.insert.intersect.into.is.join.left.like.limit.natural.not.null.offset.on.or.order.outer.primary.references.right.select.set.table.then.to.true.union.unique.update.user.using.values.when.where.with`.split(`.`)),mn=/^[a-z][a-z0-9_]*$/,hn=/^[A-Za-z][A-Za-z0-9_]*$/,gn=/^[A-Za-z@][A-Za-z0-9_@./:-]*$/;function _n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Y(e,t,n){_n(e)||J(t,`must be an object`);for(let r of Object.keys(e))n.includes(r)||J(`${t}.${r}`,`is not a known key`);return e}function X(e,t,n,r=0){return e===void 0?[]:(Array.isArray(e)||J(t,`must be an array`),e.length>n&&J(t,`must have at most ${n} entries`),e.length<r&&J(t,`must have at least ${r} entries`),e)}function vn(e,t,n,r={}){if(typeof e!=`string`){if(r.optional&&e===void 0)return``;J(t,`must be a string`)}let i=e.trim();return i.length===0&&!r.optional&&J(t,`must not be empty`),i.length>n&&J(t,`must be at most ${n} characters`),/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(i)&&J(t,`must not contain control characters`),i}function yn(e,t,n){return(typeof e!=`string`||!n.includes(e))&&J(t,`must be one of: ${n.join(`, `)}`),e}function bn(e,t){return typeof e!=`string`&&J(t,`must be a string`),(e.length===0||e.length>K.maxFieldNameLength||!hn.test(e))&&J(t,`must be a plain field name (letters, digits, underscore)`),e}function Z(e,t){return typeof e!=`string`&&J(t,`must be a string`),(e.length===0||e.length>K.maxAliasLength||!mn.test(e))&&J(t,`must be a lowercase identifier of at most ${K.maxAliasLength} characters (a-z, 0-9, underscore)`),pn.has(e)&&J(t,`'${e}' is a reserved word`),e}function xn(e,t){return typeof e==`string`?(e.length>K.maxStringValueLength&&J(t,`must be at most ${K.maxStringValueLength} characters`),e.includes(`\0`)&&J(t,`must not contain NUL`),e):typeof e==`number`?(Number.isFinite(e)||J(t,`must be a finite number`),e):typeof e==`boolean`?e:J(t,`must be a string, number or boolean`)}function Sn(e){return e.replace(/([a-z\d])([A-Z])/g,`$1_$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1_$2`).toLowerCase()}function Cn(e,t){let n=Y(e,t,[`field`,`as`,`bucket`]),r=bn(n.field,`${t}.field`),i=n.bucket===void 0?void 0:yn(n.bucket,`${t}.bucket`,cn);return{field:r,as:n.as===void 0?Z(i?`${Sn(r)}_${i}`:Sn(r),`${t}.as`):Z(n.as,`${t}.as`),...i?{bucket:i}:{}}}function wn(e,t){let n=Y(e,t,[`fn`,`field`,`as`]),r=yn(n.fn,`${t}.fn`,ln),i=n.field===void 0?void 0:bn(n.field,`${t}.field`);!i&&r!==`count`&&J(`${t}.field`,`is required for ${r}`);let a=n.as===void 0?Z(i?`${Sn(r)}_${Sn(i)}`:`row_count`,`${t}.as`):Z(n.as,`${t}.as`);return{fn:r,...i?{field:i}:{},as:a}}function Tn(e,t){let n=Y(e,t,[`field`,`op`,`value`]),r=bn(n.field,`${t}.field`),i=yn(n.op,`${t}.op`,un);if(i===`isNull`||i===`isNotNull`)return n.value!==void 0&&J(`${t}.value`,`must be omitted for ${i}`),{field:r,op:i};if(n.value===void 0&&J(`${t}.value`,`is required for ${i}`),i===`in`||i===`notIn`)return{field:r,op:i,value:X(n.value,`${t}.value`,K.maxInValues,1).map((e,n)=>xn(e,`${t}.value[${n}]`))};Array.isArray(n.value)&&J(`${t}.value`,`must be a scalar for ${i}`);let a=xn(n.value,`${t}.value`);return i===`contains`&&typeof a!=`string`&&J(`${t}.value`,`must be a string for contains`),{field:r,op:i,value:a}}function En(e,t){let n=Y(e,t,[`measure`,`op`,`value`]),r=Z(n.measure,`${t}.measure`),i=yn(n.op,`${t}.op`,dn);return(typeof n.value!=`number`||!Number.isFinite(n.value))&&J(`${t}.value`,`must be a finite number`),{measure:r,op:i,value:n.value}}function Dn(e,t){let n=Y(e,t,[`by`,`direction`]);return{by:Z(n.by,`${t}.by`),direction:n.direction===void 0?`asc`:yn(n.direction,`${t}.direction`,[`asc`,`desc`])}}function On(e){let t=e;if(typeof e==`string`){e.length>65536&&J(``,`spec JSON is too large`);try{t=JSON.parse(e)}catch{J(``,`spec is not valid JSON`)}}let n=Y(t,`spec`,[`version`,`title`,`description`,`source`,`dimensions`,`measures`,`filters`,`having`,`sort`,`limit`,`chart`]);n.version!==void 0&&n.version!==1&&J(`spec.version`,`unsupported version (expected 1)`);let r=vn(n.title,`spec.title`,K.maxTitleLength),i=vn(n.description,`spec.description`,K.maxDescriptionLength,{optional:!0});(typeof n.source!=`string`||n.source.length===0||n.source.length>K.maxSourceIdLength||!gn.test(n.source))&&J(`spec.source`,`must be a source id`);let a=X(n.dimensions,`spec.dimensions`,K.maxDimensions).map((e,t)=>Cn(e,`spec.dimensions[${t}]`)),o=X(n.measures,`spec.measures`,K.maxMeasures,1).map((e,t)=>wn(e,`spec.measures[${t}]`)),s=X(n.filters,`spec.filters`,K.maxFilters).map((e,t)=>Tn(e,`spec.filters[${t}]`)),c=X(n.having,`spec.having`,K.maxHaving).map((e,t)=>En(e,`spec.having[${t}]`)),l=X(n.sort,`spec.sort`,K.maxSort).map((e,t)=>Dn(e,`spec.sort[${t}]`)),u=new Set,d=new Set,f=new Set;for(let[e,t]of a.entries())f.has(t.as)&&J(`spec.dimensions[${e}].as`,`duplicate alias '${t.as}'`),f.add(t.as),u.add(t.as);for(let[e,t]of o.entries())f.has(t.as)&&J(`spec.measures[${e}].as`,`duplicate alias '${t.as}'`),f.add(t.as),d.add(t.as);for(let[e,t]of c.entries())d.has(t.measure)||J(`spec.having[${e}].measure`,`must be a declared measure alias`);for(let[e,t]of l.entries())f.has(t.by)||J(`spec.sort[${e}].by`,`must be a declared dimension or measure alias`);let p=K.defaultRowLimit;n.limit!==void 0&&((typeof n.limit!=`number`||!Number.isSafeInteger(n.limit)||n.limit<1||n.limit>K.maxRowLimit)&&J(`spec.limit`,`must be an integer between 1 and ${K.maxRowLimit}`),p=n.limit);let m={type:`table`};if(n.chart!==void 0){let e=Y(n.chart,`spec.chart`,[`type`,`x`,`y`]),t=yn(e.type,`spec.chart.type`,fn),r=e.x===void 0?void 0:Z(e.x,`spec.chart.x`);r!==void 0&&!u.has(r)&&J(`spec.chart.x`,`must be a declared dimension alias`);let i=X(e.y,`spec.chart.y`,K.maxMeasures).map((e,t)=>Z(e,`spec.chart.y[${t}]`));for(let[e,t]of i.entries())d.has(t)||J(`spec.chart.y[${e}]`,`must be a declared measure alias`);m={type:t,...r?{x:r}:{},...i.length>0?{y:i}:{}}}return{version:1,title:r,...i?{description:i}:{},source:n.source,dimensions:a,measures:o,filters:s,having:c,sort:l,limit:p,chart:m}}function kn(e){return Array.isArray(e)?e.map(kn):_n(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,kn(e[t])])):e}function An(e){return JSON.stringify(kn(e))}async function jn(e){let t=globalThis.crypto?.subtle;if(!t)throw Error(`runtimeReportSpecDigest needs Web Crypto (crypto.subtle), which browsers offer only in a secure context`);let n=new TextEncoder().encode(An(e)),r=new Uint8Array(await t.digest(`SHA-256`,n));return Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``)}var Mn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Nn(e){return e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).replace(/^./,e=>e.toUpperCase())}function Pn(e,t){throw new q(`unknown_field`,e,`'${t}' is not a field available on this source`)}function Fn(e,t){throw new q(`invalid_operation`,e,t)}function In(e,t){throw new q(`invalid_value`,e,t)}var Ln={string:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`contains`,`isNull`,`isNotNull`],integer:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`isNull`,`isNotNull`],decimal:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`isNull`,`isNotNull`],datetime:[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`notIn`,`isNull`,`isNotNull`],boolean:[`eq`,`ne`,`isNull`,`isNotNull`],id:[`eq`,`ne`,`in`,`notIn`,`isNull`,`isNotNull`]};function Rn(e){return e===`integer`||e===`decimal`?[`count`,`countDistinct`,`sum`,`avg`,`min`,`max`]:e===`datetime`?[`count`,`countDistinct`,`min`,`max`]:[`count`,`countDistinct`]}function zn(e,t,n){Ln[t].includes(e.op)||Fn(`${n}.op`,`'${e.op}' is not valid for ${t} fields`)}function Bn(e,t,n){switch(e){case`string`:return typeof t!=`string`&&In(n,`must be a string`),t;case`integer`:return(typeof t!=`number`||!Number.isSafeInteger(t))&&In(n,`must be a safe integer`),t;case`decimal`:return(typeof t!=`number`||!Number.isFinite(t))&&In(n,`must be a finite number`),t;case`boolean`:return typeof t!=`boolean`&&In(n,`must be true or false`),t;case`datetime`:{typeof t!=`string`&&In(n,`must be an ISO-8601 string`);let e=new Date(t);return(Number.isNaN(e.getTime())||!/^\d{4}-\d{2}-\d{2}/.test(t))&&In(n,`must be an ISO-8601 date or timestamp`),e}case`id`:return(typeof t!=`string`||!Mn.test(t))&&In(n,`must be a UUID`),t.toLowerCase()}}function Vn(e,t){let n=n=>{let r=e[n];if(r!==void 0){if(!Array.isArray(r)||Array.from(r).some(e=>typeof e!=`string`||!t.has(e)))throw new q(`unsupported_source`,`source.${n}`,`${n} must contain canonical field names declared on the source`);return new Set(r)}},r=n(`fields`),i=n(`excludeFields`);if(n(`dimensions`),e.timeField!==void 0&&(typeof e.timeField!=`string`||!t.has(e.timeField)))throw new q(`unsupported_source`,`source.timeField`,`timeField must be a canonical field name declared on the source`);return{...r?{included:r}:{},...i?{excluded:i}:{}}}function Hn(e,t){return e===`count`||e===`countDistinct`?`integer`:e===`avg`?`decimal`:t?.type??`decimal`}function Un(e,t){let n=(e,n)=>{let r=t.get(e);return r||Pn(n,e),r},r=[];for(let[t,i]of e.dimensions.entries()){let e=`spec.dimensions[${t}]`,a=n(i.field,`${e}.field`);i.bucket&&a.type!==`datetime`&&Fn(`${e}.bucket`,`buckets are only valid on datetime fields`),r.push({id:i.as,label:Nn(i.as),role:`dimension`,type:i.bucket?`datetime`:a.type,field:a.name,...i.bucket?{bucket:i.bucket}:{},...a.format&&!i.bucket?{format:a.format}:{}})}for(let[t,i]of e.measures.entries()){let e=`spec.measures[${t}]`,a=i.field?n(i.field,`${e}.field`):void 0;(i.fn===`sum`||i.fn===`avg`)&&a?.type!==`integer`&&a?.type!==`decimal`&&Fn(`${e}.fn`,`${i.fn} requires a numeric field`),(i.fn===`min`||i.fn===`max`)&&a?.type!==`integer`&&a?.type!==`decimal`&&a?.type!==`datetime`&&Fn(`${e}.fn`,`${i.fn} requires a numeric or datetime field`);let o=a?.format&&(i.fn===`sum`||i.fn===`min`||i.fn===`max`||i.fn===`avg`);r.push({id:i.as,label:Nn(i.as),role:`measure`,type:Hn(i.fn,a),...a?{field:a.name}:{},fn:i.fn,...o?{format:a?.format}:{}})}return r}function Wn(e,t){if(t==null)return null;if(t instanceof Date)return t.toISOString();if(typeof t==`bigint`){let n=Number(t);if(!Number.isSafeInteger(n))throw new q(`invalid_result`,e.id,`integer result exceeds the JavaScript safe range`);return n}if(e.type===`boolean`){if(t===1||t===`1`||t===`true`||t===!0)return!0;if(t===0||t===`0`||t===`false`||t===!1)return!1}if(e.type===`integer`||e.type===`decimal`){let n=typeof t==`number`?t:Number(t);if(!Number.isFinite(n))throw new q(`invalid_result`,e.id,`numeric result is not finite`);if(e.type===`integer`&&!Number.isSafeInteger(n))throw new q(`invalid_result`,e.id,`integer result exceeds the JavaScript safe range`);return n}return typeof t==`string`||typeof t==`number`||typeof t==`boolean`?t:String(t)}var Gn=/^(?:id|_.*)$|(?:Hash|Json|Token|Secret|Signature|Authority|Snapshot|Checksum|Cursor|Etag)$|^(?:external|historical)[A-Z]/,Kn=/^(?:created|updated|deleted|synced|archived)At$|^last[A-Z]\w*At$/,qn=/^(?:status|state)$|(?:Status|State)$/,Jn=/^(?:kind|type|category|method|channel|stage|priority|segment|tier|source)$|(?:Kind|Type|Category|Method|Channel|Stage|Priority|Segment|Tier)$/,Yn=/^(?:customer|vendor|supplier|client|member|employee|owner|assignee|product|location|project|account|contact)Id$/,Xn=50;function Zn(e){if(e.type===`datetime`)return e.name===`deletedAt`?void 0:`time`;if(!Gn.test(e.name)){if(e.type===`boolean`||e.type===`string`&&e.enum&&e.enum.length>0&&e.enum.length<=Xn)return`category`;if(e.type===`id`&&/Id$/.test(e.name))return`relation`}}function Qn(e){return e.type===`boolean`?10:e.type===`id`?Yn.test(e.name)?70:30:qn.test(e.name)?100:Jn.test(e.name)?80:50}function $n(e,t={}){let n=[...e.values()],r=new Map;for(let e of n){let t=Zn(e);t&&r.set(e.name,t)}let i=n.filter(e=>r.get(e.name)===`time`),a=(t.timeField&&e.get(t.timeField)?.type===`datetime`?t.timeField:void 0)??i.find(e=>e.businessDate)?.name??i.find(e=>!Kn.test(e.name))?.name??i.find(e=>e.name===`createdAt`)?.name??i[0]?.name,o=[...a?[a]:[],...i.map(e=>e.name).filter(e=>e!==a)],s;if(t.dimensions){s=t.dimensions.filter(t=>e.has(t)&&e.get(t)?.type!==`datetime`);for(let t of s)r.has(t)||r.set(t,e.get(t)?.type===`id`?`relation`:`category`);for(let[e,t]of[...r])t!==`time`&&!s.includes(e)&&r.delete(e)}else s=n.filter(e=>{let t=r.get(e.name);return t===`category`||t===`relation`}).map((e,t)=>({field:e,index:t})).sort((e,t)=>Qn(t.field)-Qn(e.field)||e.index-t.index).map(({field:e})=>e.name);return{kinds:r,timeFields:o,...a?{defaultTimeField:a}:{},dimensions:s}}function er(e,t={}){let n=$n(e,t);return{fields:[...e.values()].map(e=>{let t=n.kinds.get(e.name);return{name:e.name,label:e.label,type:e.type,...e.format?{format:e.format}:{},...e.enum?{enum:e.enum}:{},...t?{dimension:t}:{},filterOperators:Ln[e.type],aggregates:Rn(e.type)}}),timeFields:n.timeFields,...n.defaultTimeField?{defaultTimeField:n.defaultTimeField}:{},dimensions:n.dimensions}}var tr=new Set([`tenantId`,`tenant_id`]);function nr(e,t){let n=e.find(e=>e.id===t);if(!n)throw new q(`unknown_source`,`spec.source`,`'${t}' is not an available report source`);return n}function rr(e){let{included:t,excluded:n}=Vn(e,new Set(e.schema.map(e=>e.name))),r=new Map;for(let i of e.schema)i.name.startsWith(`_`)||tr.has(i.name)||n?.has(i.name)||t&&!t.has(i.name)||r.has(i.name)||r.set(i.name,{name:i.name,type:i.type,...i.format?{format:i.format}:{},...i.type===`string`&&i.enum?.length?{enum:i.enum}:{},...i.type===`datetime`&&i.format===`date`?{businessDate:!0}:{},label:i.label??Nn(i.name)});return r}function ir(e,t){let n=nr(e,t);return{id:n.id,label:n.label??Nn(n.id),...n.description?{description:n.description}:{},...er(rr(n),n)}}function ar(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function or(e,t){let n=e[t.name];if(n==null)return null;switch(t.type){case`integer`:case`decimal`:{if(typeof n==`bigint`){if(n>BigInt(2**53-1)||n<BigInt(-(2**53-1)))throw new q(`invalid_result`,t.name,`integer value exceeds the JavaScript safe range`);return Number(n)}let e=typeof n==`number`?n:typeof n==`string`&&n.trim()!==``?Number(n):NaN;return Number.isFinite(e)?e:null}case`boolean`:return n===!0||n===1||n===`1`||n===`true`?!0:n===!1||n===0||n===`0`||n===`false`?!1:null;case`datetime`:return ar(n);default:return typeof n==`string`?n:String(n)}}function sr(e,t){let n=e instanceof Date?e.getTime():e,r=t instanceof Date?t.getTime():t;return typeof n==`boolean`||typeof r==`boolean`?Number(n)-Number(r):n<r?-1:+(n>r)}function cr(e,t,n){zn(e,t.type,n);let r=e=>or(e,t);switch(e.op){case`isNull`:return e=>r(e)===null;case`isNotNull`:return e=>r(e)!==null;case`in`:case`notIn`:{let i=e.value.map((e,r)=>Bn(t.type,e,`${n}.value[${r}]`)),a=e=>i.some(t=>sr(e,t)===0);return e.op===`in`?e=>{let t=r(e);return t!==null&&a(t)}:e=>{let t=r(e);return t!==null&&!a(t)}}case`contains`:{let i=Bn(t.type,e.value,`${n}.value`);return e=>{let t=r(e);return typeof t==`string`&&t.includes(i)}}default:{let i=Bn(t.type,e.value,`${n}.value`),a={eq:e=>e===0,ne:e=>e!==0,gt:e=>e>0,gte:e=>e>=0,lt:e=>e<0,lte:e=>e<=0}[e.op];return e=>{let t=r(e);return t!==null&&a(sr(t,i))}}}}function lr(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate();switch(t){case`minute`:return new Date(Date.UTC(n,r,i,e.getUTCHours(),e.getUTCMinutes()));case`hour`:return new Date(Date.UTC(n,r,i,e.getUTCHours()));case`day`:return new Date(Date.UTC(n,r,i));case`week`:{let t=(e.getUTCDay()+6)%7;return new Date(Date.UTC(n,r,i-t))}case`month`:return new Date(Date.UTC(n,r,1));case`quarter`:return new Date(Date.UTC(n,Math.floor(r/3)*3,1));case`year`:return new Date(Date.UTC(n,0,1))}}function ur(e){return e===null?`n`:e instanceof Date?`d${e.getTime()}`:`${typeof e}:${String(e)}`}function dr(e,t,n){if(t===null)return n;let r=t.filter(e=>e!==null);switch(e){case`count`:return r.length;case`countDistinct`:return new Set(r.map(ur)).size;case`sum`:return r.length===0?null:r.reduce((e,t)=>e+t,0);case`avg`:return r.length===0?null:r.reduce((e,t)=>e+t,0)/r.length;case`min`:case`max`:{if(r.length===0)return null;let t=r[0];for(let n of r.slice(1)){let r=sr(n,t);(e===`min`?r<0:r>0)&&(t=n)}return t}default:return null}}function fr(e,t){if(typeof t!=`number`)return!1;switch(e.op){case`eq`:return t===e.value;case`ne`:return t!==e.value;case`gt`:return t>e.value;case`gte`:return t>=e.value;case`lt`:return t<e.value;case`lte`:return t<=e.value}}function pr(e,t,n){let r;return r=e===null&&t===null?0:e===null?-1:t===null?1:sr(e,t),n===`desc`?-r:r}async function mr(e,t,n){let r=On(e),i=nr(n.sources,r.source),a=rr(i),o=Un(r,a),s=(e,t)=>{let n=a.get(e);return n||Pn(t,e),n},c=[];i.schema.some(e=>e.name===`deletedAt`)&&c.push(e=>e.deletedAt===null||e.deletedAt===void 0);for(let[e,t]of r.filters.entries()){let n=`spec.filters[${e}]`;c.push(cr(t,s(t.field,`${n}.field`),n))}let l=t.filter(e=>c.every(t=>t(e))),u=r.dimensions.map(e=>{let t=a.get(e.field);return n=>{let r=or(n,t);return e.bucket&&r instanceof Date?lr(r,e.bucket):r}}),d=new Map;if(r.dimensions.length===0)d.set(``,{key:[],rows:l});else for(let e of l){let t=u.map(t=>t(e)),n=JSON.stringify(t.map(ur)),r=d.get(n);r?r.rows.push(e):d.set(n,{key:t,rows:[e]})}let f=r.measures.map(e=>e.field?a.get(e.field):null),p=[...d.values()].map(e=>{let t={};return r.dimensions.forEach((n,r)=>{t[n.as]=e.key[r]}),r.measures.forEach((n,r)=>{let i=f[r];t[n.as]=dr(n.fn,i?e.rows.map(e=>or(e,i)):null,e.rows.length)}),t});r.having.length>0&&(p=p.filter(e=>r.having.every(t=>fr(t,e[t.measure]))));let m=r.sort.length>0?r.sort:r.dimensions.length>0?[{by:r.dimensions[0].as,direction:`asc`}]:[];m.length>0&&(p=p.map((e,t)=>({values:e,index:t})).sort((e,t)=>{for(let n of m){let r=pr(e.values[n.by],t.values[n.by],n.direction);if(r!==0)return r}return e.index-t.index}).map(({values:e})=>e));let h=Math.min(r.limit,n.maxRows??K.maxRowLimit),g=p.length>h,_=p.slice(0,h).map(e=>{let t={};for(let n of o)t[n.id]=Wn(n,e[n.id]);return t});return{version:1,specHash:await jn(r),title:r.title,columns:o,rows:_,rowCount:_.length,truncated:g,ranAt:(n.now?.()??new Date).toISOString(),chart:r.chart}}var Q=864e5,hr=e=>new Date(e).toISOString().slice(0,10),gr=[`january`,`february`,`march`,`april`,`may`,`june`,`july`,`august`,`september`,`october`,`november`,`december`],_r={first:1,second:2,third:3,fourth:4},vr=[[`minute`,/\b(?:minutely|(?:per|by|each|every|a) minute|minute by minute)\b/],[`hour`,/\b(?:hourly|(?:per|by|each|every|an?) hour|hour by hour)\b/],[`day`,/\b(?:daily|(?:per|by|each|every|a) day|day by day)\b/],[`week`,/\b(?:weekly|(?:per|by|each|every|a) week|week by week|week over week)\b/],[`month`,/\b(?:monthly|(?:per|by|each|every|a) month|month by month|month over month)\b/],[`quarter`,/\b(?:quarterly|(?:per|by|each|every|a) quarter|quarter by quarter|quarter over quarter)\b/],[`year`,/\b(?:yearly|annually|annual|(?:per|by|each|every|a) year|year by year|year over year)\b/]],yr=/\b(?:over time|trends?|trending|timeline|history)\b/;function br(e){return e===null?`month`:e<=31?`day`:e<=92?`week`:e<=1098?`month`:`quarter`}function xr(e){return Math.round((Date.parse(`${e.to}T00:00:00Z`)-Date.parse(`${e.from}T00:00:00Z`))/Q)}function Sr(e,t){let n=e.toLowerCase().replace(/[_-]+/g,` `).replace(/\s+/g,` `),r=t.getUTCFullYear(),i=t.getUTCMonth(),a=Date.UTC(r,i,t.getUTCDate()),o=a+Q,s=a-(t.getUTCDay()+6)%7*Q,c=Math.floor(i/3)*3,l=(e,t,n)=>({from:hr(e),to:hr(t),label:n}),u=/\b(?:last|past|previous|trailing)\s+(\d{1,4})\s+(day|week|month|year)s?\b/.exec(n);if(u){let e=Number(u[1]),n=u[2];if(e>0)return l(n===`day`?o-e*Q:n===`week`?o-e*7*Q:n===`month`?Date.UTC(r,i-e,t.getUTCDate()+1):Date.UTC(r-e,i,t.getUTCDate()+1),o,`last ${e} ${n}${e===1?``:`s`}`)}let d=/\bq([1-4])(?:\s*(?:of\s*)?((?:19|20)\d{2}))?\b/.exec(n)??/\b(first|second|third|fourth) quarter(?: (?:of )?((?:19|20)\d{2}))?\b/.exec(n);if(d){let e=/^\d$/.test(d[1])?Number(d[1]):_r[d[1]],t=(e-1)*3,n=d[2]?Number(d[2]):Date.UTC(r,t,1)<=a?r:r-1;return l(Date.UTC(n,t,1),Date.UTC(n,t+3,1),`Q${e} ${n}`)}if(/\b(?:year to date|ytd)\b/.test(n))return l(Date.UTC(r,0,1),o,`year to date`);if(/\b(?:month to date|mtd)\b/.test(n))return l(Date.UTC(r,i,1),o,`month to date`);if(/\btoday\b/.test(n))return l(a,o,`today`);if(/\byesterday\b/.test(n))return l(a-Q,a,`yesterday`);let f=/\b(this|current|last|previous|past) (week|month|quarter|year)\b/.exec(n);if(f){let e=f[1]!==`this`&&f[1]!==`current`,t=f[2],n=`${e?`last`:`this`} ${t}`;switch(t){case`week`:return e?l(s-7*Q,s,n):l(s,s+7*Q,n);case`month`:return e?l(Date.UTC(r,i-1,1),Date.UTC(r,i,1),n):l(Date.UTC(r,i,1),Date.UTC(r,i+1,1),n);case`quarter`:return e?l(Date.UTC(r,c-3,1),Date.UTC(r,c,1),n):l(Date.UTC(r,c,1),Date.UTC(r,c+3,1),n);default:return e?l(Date.UTC(r-1,0,1),Date.UTC(r,0,1),n):l(Date.UTC(r,0,1),Date.UTC(r+1,0,1),n)}}let p=RegExp(`\\b(${gr.join(`|`)})(?: ((?:19|20)\\d{2}))?\\b`).exec(n);if(p&&(p[1]!==`may`||p[2])){let e=p,t=gr.indexOf(e[1]),n=e[2]?Number(e[2]):Date.UTC(r,t,1)<=a?r:r-1,i=e[1].charAt(0).toUpperCase()+e[1].slice(1);return l(Date.UTC(n,t,1),Date.UTC(n,t+1,1),`${i} ${n}`)}let m=/\b(?:in|for|during)\s+((?:19|20)\d{2})\b/.exec(n)??/^\s*((?:19|20)\d{2})\s*$/.exec(n);if(m){let e=Number(m[1]);return l(Date.UTC(e,0,1),Date.UTC(e+1,0,1),String(e))}return null}function Cr(e,t){let n=e.toLowerCase(),r=Sr(n,t)??void 0,i=vr.find(([,e])=>e.test(n))?.[0],a=yr.test(n);!i&&a&&(i=br(r?xr(r):null));let o=!!(i||r||a)||/\b(?:date|dates|time|when|minute|hour|day|week|month|quarter|year)s?\b/.test(n);return{...i?{bucket:i}:{},...r?{range:r}:{},mentionsTime:o}}var wr=[`today`,`yesterday`,`this_week`,`last_week`,`this_month`,`last_month`,`this_quarter`,`last_quarter`,`this_year`,`last_year`,`all_time`],Tr=[`minute`,`hour`,`day`,`week`,`month`,`quarter`,`year`],Er=[`count`,`sum`,`avg`,`min`,`max`],Dr=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`],Or=4,kr=3,Ar=64,jr=8;function Mr(e){let t={type:`string`,maxLength:Ar};return{type:[`object`,`null`],properties:{source:e.length?{enum:[...e]}:{type:`string`,maxLength:K.maxSourceIdLength},measures:{type:`array`,maxItems:Or,items:{type:`object`,properties:{fn:{enum:[...Er]},field:t},required:[`fn`],additionalProperties:!1}},groupBy:t,bucket:{enum:[...Tr]},period:{enum:[...wr]},range:{type:`string`,maxLength:40},dateField:t,filters:{type:`array`,maxItems:kr,items:{type:`object`,properties:{field:t,op:{enum:[...Dr]},value:{type:[`string`,`number`,`boolean`]}},required:[`field`,`op`,`value`],additionalProperties:!1}},title:{type:`string`,maxLength:K.maxTitleLength}},required:[`source`],additionalProperties:!1}}var Nr=(e,t)=>typeof e==`string`&&t.includes(e)?e:void 0,Pr=(e,t=Ar)=>typeof e==`string`&&e.trim()&&e.trim().length<=t?e.trim():void 0;function Fr(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=Pr(t.source,K.maxSourceIdLength);if(!n)return null;let r=e=>t[e]!==void 0&&t[e]!==null,i=Array.isArray(t.unreadable)?t.unreadable.filter(e=>typeof e==`string`&&e.trim().length>0).slice(0,jr).map(e=>e.trim().slice(0,Ar)):[];r(`measures`)&&!Array.isArray(t.measures)&&i.push(`the measures`),r(`filters`)&&!Array.isArray(t.filters)&&i.push(`the filters`);let a=Array.isArray(t.measures)?t.measures.slice(0,Or).flatMap(e=>{let t=e&&typeof e==`object`?e:{},n=Nr(t.fn,Er);if(!n)return i.push(`a measure`),[];let r=Pr(t.field);return[{fn:n,...r?{field:r}:{}}]}):[],o=Array.isArray(t.filters)?t.filters.slice(0,kr).flatMap(e=>{let t=e&&typeof e==`object`?e:{},n=Pr(t.field),r=Nr(t.op,Dr),a=t.value;return!n||!r||!(typeof a==`string`&&a.length<=256||typeof a==`number`&&Number.isFinite(a)||typeof a==`boolean`)?(i.push(n?`the ${n} filter`:`a filter`),[]):[{field:n,op:r,value:a}]}):[];Array.isArray(t.measures)&&t.measures.length>Or&&i.push(`more than ${Or} measures`),Array.isArray(t.filters)&&t.filters.length>kr&&i.push(`more than ${kr} filters`);let s=Pr(t.groupBy),c=Nr(t.bucket,Tr),l=Nr(t.period,wr),u=Pr(t.dateField),d=Pr(t.range,40),f=Pr(t.title,K.maxTitleLength);return r(`range`)&&!d&&i.push(`the period`),r(`groupBy`)&&!s&&i.push(`the grouping`),r(`bucket`)&&!c&&i.push(`the time grouping`),r(`period`)&&!l&&i.push(`the period`),r(`dateField`)&&!u&&i.push(`the date`),{source:n,...a.length?{measures:a}:{},...s?{groupBy:s}:{},...c?{bucket:c}:{},...l?{period:l}:{},...d?{range:d}:{},...u?{dateField:u}:{},...o.length?{filters:o}:{},...f?{title:f}:{},...i.length?{unreadable:i}:{}}}var Ir=e=>e.toLowerCase().replace(/[^a-z0-9]/g,``);function Lr(e,t,n=()=>!0){let r=Ir(e),i=t.filter(n);return i.find(t=>t.name===e)??i.find(e=>Ir(e.name)===r)??i.find(e=>Ir(e.label)===r)}function Rr(e){let t=e.slice(0,6),n=e.length>t.length?`, …`:``;return t.length<=1?`${t.join(``)}${n}`:`${t.slice(0,-1).join(`, `)}${n} or ${t[t.length-1]}`}var $=e=>({ok:!1,question:e}),zr=e=>e.options.length?{ok:!1,question:e.prompt,followUp:{...e,default:e.options[0].value}}:{ok:!1,question:e.prompt.replace(/…$/,` what?`)},Br=8;function Vr(e){let t=e=>(e.amountField?2:0)+ +!!e.dateField;return[...e].sort((e,n)=>t(n)-t(e))}function Hr(e){let t=Vr(e).slice(0,Br);return t.length?{field:`source`,label:`Records`,prompt:`Which records should the report cover?`,options:t.map(e=>({value:e.id,label:e.label,apply:{source:e.id}})),default:t[0].id}:null}function Ur(e){return e.length?`Which records should the report cover?`:`Which records should the report cover? Add a recipe with records first, such as invoicing?`}var Wr={minute:`minute`,minutely:`minute`,hour:`hour`,hourly:`hour`,day:`day`,daily:`day`,week:`week`,weekly:`week`,month:`month`,monthly:`month`,quarter:`quarter`,quarterly:`quarter`,year:`year`,yearly:`year`,annual:`year`,annually:`year`},Gr=new Set([`by`,`per`,`the`,`each`,`every`,`a`,`over`,`time`,`date`,`dates`,`in`]);function Kr(e){let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),n,r=!1,i=[];for(let e of t){let t=e.endsWith(`s`)?e.slice(0,-1):e,a=Wr[e]??Wr[t];a?(n??=a,r=!0):Gr.has(e)?(e===`date`||e===`dates`||e===`time`)&&(r=!0):i.push(e)}return{...n?{bucket:n}:{},rest:i.join(` `),time:r}}var qr=[{value:`this month`,label:`This month`},{value:`last month`,label:`Last month`},{value:`this quarter`,label:`This quarter`},{value:`last quarter`,label:`Last quarter`},{value:`this year`,label:`This year`},{value:`last year`,label:`Last year`},{value:`all time`,label:`All time`}];function Jr(e,t,n){let r=e=>e.replace(/([a-z\d])([A-Z])/g,`$1_$2`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`);return(e===`count`||!t?`number_of_${r(n)}`:e===`sum`?r(t).startsWith(`total`)?r(t):`total_${r(t)}`:`${{avg:`average`,min:`lowest`,max:`highest`}[e]}_${r(t)}`).slice(0,K.maxAliasLength).replace(/_+$/,``)}var Yr={eq:`is`,ne:`is not`,gt:`over`,gte:`at least`,lt:`under`,lte:`at most`,contains:`contains`},Xr=/^-?\s*[$€£¥]?\s*-?(\d{1,3}(,\d{3})+|\d+)(\.\d{1,2})?$/;function Zr(e){if(typeof e==`number`)return Number.isFinite(e)?Math.round(e*100):null;if(typeof e!=`string`)return null;let t=e.trim();if(!Xr.test(t))return null;let n=Number(t.replace(/[^0-9.-]/g,``));return Number.isFinite(n)?Math.round(n*100):null}var Qr=e=>e.type===`integer`||e.type===`decimal`;function $r(e,t,n,r=``){let i=t.find(t=>t.id===e.source);if(!i){let e=Hr(t);return e?{ok:!1,question:e.prompt,followUp:e}:$(Ur(t))}let a=ir(t,i.id),{fields:o}=a,s=i.label,c=e=>o.find(t=>t.name===e)?.label??e;if(e.unreadable?.length)return $(`I could not read ${Rr(e.unreadable).replace(/ or ([^,]+)$/,` and $1`)} for the ${s} report. Can you say that again?`);let l=Cr(r,n),u=e.measures?.length?e.measures:[{fn:`count`},...i.amountField?[{fn:`sum`,field:i.amountField}]:[]],d=[];for(let[e,t]of u.entries()){if(t.fn===`count`){d.some(e=>e.fn===`count`)||d.push({fn:`count`,as:Jr(`count`,void 0,i.id)});continue}let n=t.field??i.amountField,r=n?Lr(n,o,e=>t.fn===`min`||t.fn===`max`?Qr(e)||e.type===`datetime`:Qr(e)):void 0;if(!r){let n=o.filter(e=>Qr(e)&&e.name!==`id`);if(!n.length)return $(`${s} have no amounts to total. Should I count them instead?`);let r=[...n.filter(e=>e.name===i.amountField),...n.filter(e=>e.format===`money`&&e.name!==i.amountField),...n.filter(e=>e.format!==`money`)].slice(0,Br);return zr({field:`measure`,label:t.fn===`sum`?`Total`:`Amount`,prompt:`Which amount on ${s} should I ${t.fn===`sum`?`total`:`take the ${t.fn} of`}?`,options:r.map(n=>({value:n.name,label:n.label,apply:{measures:u.map((r,i)=>i===e?{fn:t.fn,field:n.name}:r)}}))})}d.push({fn:t.fn,field:r.name,as:Jr(t.fn,r.name,i.id)})}let f=e.groupBy,p=e.dateField,m=e.bucket;if(f){let e=Kr(f),t=Lr(f,o,e=>e.type===`datetime`);if(t)p??=t.name,m??=`month`,f=void 0;else if(e.time){let t=e.rest?Lr(e.rest,o,e=>e.type===`datetime`):void 0;(!e.rest||t)&&(t&&(p??=t.name),m??=e.bucket??l.bucket??`month`,f=void 0)}}m??=l.bucket;let h=null;if(e.range){if(h=Sr(e.range,n),!h&&!/\ball\s*time\b|\bever\b/i.test(e.range))return zr({field:`period`,label:`Period`,prompt:`Which period should the ${s} report cover?`,options:qr.map(e=>({...e,apply:{range:e.value,period:void 0}}))})}else e.period&&e.period!==`all_time`?h=Sr(e.period,n):e.period||(h=l.range??null);let g;if((m||h)&&(g=p?Lr(p,o,e=>e.type===`datetime`):a.defaultTimeField?o.find(e=>e.name===a.defaultTimeField):void 0,!g)){let e=a.timeFields.slice(0,Br);return e.length?zr({field:`dateField`,label:`Date`,prompt:`Which date on ${s} should the report use?`,options:e.map(e=>({value:e,label:c(e),apply:{dateField:e}}))}):$(`${s} have no date to group or filter by. Should the report cover all of them?`)}let _=[];if(f){let e=new Set(a.dimensions),t=Lr(f,o,t=>e.has(t.name))??Lr(f,o,e=>e.type!==`datetime`);if(t)_.push({field:t.name});else if(!(m&&g))return zr(ei(a,s,c,l.mentionsTime))}m&&g&&_.push({field:g.name,bucket:m});let v=[];h&&g&&(v.push({field:g.name,op:`gte`,value:h.from}),v.push({field:g.name,op:`lt`,value:h.to}));let y=[];for(let t of e.filters??[]){let e=Lr(t.field,o);if(!e)return $(`Which field on ${s} should "${t.field}" filter: ${Rr(o.map(e=>e.label))}?`);if(e.format===`money`){let n=Zr(t.value);if(n===null)return $(`What amount should ${e.label} be compared with?`);v.push({field:e.name,op:t.op,value:n}),y.push(`${e.label} ${Yr[t.op]} ${(n/100).toFixed(2)}`)}else v.push({field:e.name,op:t.op,value:t.value}),y.push(`${e.label} ${Yr[t.op]} ${String(t.value)}`)}let b=e.title??[[s,..._.map(e=>e.bucket?`by ${e.bucket}`:`by ${c(e.field).toLowerCase()}`)].join(` `),h?.label??``].filter(Boolean).join(`, `),x=y.join(`; `)||void 0,S=e=>e.measures.map(e=>e.as);try{let e=On({title:b,...x?{description:x}:{},source:i.id,dimensions:_,measures:d,filters:v}),t=e.measures.filter(e=>e.fn!==`count`),n=(t[0]??e.measures[0]).as,r=e.dimensions.find(e=>e.bucket),a=e.dimensions.find(e=>!e.bucket);return{ok:!0,spec:On({...e,sort:a&&!r?[{by:n,direction:`desc`}]:[],chart:e.dimensions.length?{type:r&&!a?`line`:`bar`,x:(a??r)?.as,y:t.length?t.map(e=>e.as):S(e)}:{type:`stat`,y:S(e)}}),source:i}}catch(e){if(e instanceof q)return $(`I could not build that report (${e.message}). What should it show?`);throw e}}function ei(e,t,n,r){let i=e.defaultTimeField,a=i?[`month`,`week`,`quarter`].map(e=>({value:`${i}:${e}`,label:`${n(i)} by ${e}`,keywords:[`${e}ly`,`date`,`time`,`per`,e],apply:{groupBy:void 0,bucket:e,dateField:i}})):[],o=e.dimensions.map(e=>({value:e,label:n(e),apply:{groupBy:e}})),s=r?[...a,...o]:[...o.slice(0,4),...a.slice(0,1),...o.slice(4),...a.slice(1)];return{field:`groupBy`,label:`Group by`,prompt:`Group ${t} by…`,options:s.slice(0,Br)}}function ti(e,t){return e.code===`invalid_value`?`That value does not fit ${t.label} (${e.message}). What value did you mean?`:e.code===`invalid_operation`?`I cannot use that on ${t.label} (${e.message}). What should the report show instead?`:`I could not build that report (${e.message}). What should it show?`}export{Et as C,At as S,en as _,$r as a,Ut as b,ir as c,mr as d,jn as f,rn as g,an as h,Hr as i,On as l,on as m,ti as n,Ur as o,An as p,Mr as r,q as s,Fr as t,Sr as u,Jt as v,Wt as x,Gt as y};