pyric 0.0.1 → 0.1.0-alpha.10

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 (1204) hide show
  1. package/LICENSE +216 -0
  2. package/README.md +179 -2
  3. package/README.md.orig +54 -0
  4. package/dist/ai/backend.d.ts +35 -0
  5. package/dist/ai/backend.d.ts.map +1 -0
  6. package/dist/ai/backend.js +42 -0
  7. package/dist/ai/backend.js.map +1 -0
  8. package/dist/ai/broker/broker.d.ts +65 -0
  9. package/dist/ai/broker/broker.d.ts.map +1 -0
  10. package/dist/ai/broker/broker.js +184 -0
  11. package/dist/ai/broker/broker.js.map +1 -0
  12. package/dist/ai/broker/index.d.ts +12 -0
  13. package/dist/ai/broker/index.d.ts.map +1 -0
  14. package/dist/ai/broker/index.js +11 -0
  15. package/dist/ai/broker/index.js.map +1 -0
  16. package/dist/ai/broker/openai-engine.d.ts +175 -0
  17. package/dist/ai/broker/openai-engine.d.ts.map +1 -0
  18. package/dist/ai/broker/openai-engine.js +502 -0
  19. package/dist/ai/broker/openai-engine.js.map +1 -0
  20. package/dist/ai/broker/scripted-engine.d.ts +44 -0
  21. package/dist/ai/broker/scripted-engine.d.ts.map +1 -0
  22. package/dist/ai/broker/scripted-engine.js +218 -0
  23. package/dist/ai/broker/scripted-engine.js.map +1 -0
  24. package/dist/ai/broker/synthesizer.d.ts +100 -0
  25. package/dist/ai/broker/synthesizer.d.ts.map +1 -0
  26. package/dist/ai/broker/synthesizer.js +278 -0
  27. package/dist/ai/broker/synthesizer.js.map +1 -0
  28. package/dist/ai/broker/types.d.ts +210 -0
  29. package/dist/ai/broker/types.d.ts.map +1 -0
  30. package/dist/ai/broker/types.js +20 -0
  31. package/dist/ai/broker/types.js.map +1 -0
  32. package/dist/ai/enums.d.ts +174 -0
  33. package/dist/ai/enums.d.ts.map +1 -0
  34. package/dist/ai/enums.js +155 -0
  35. package/dist/ai/enums.js.map +1 -0
  36. package/dist/ai/errors.d.ts +66 -0
  37. package/dist/ai/errors.d.ts.map +1 -0
  38. package/dist/ai/errors.js +100 -0
  39. package/dist/ai/errors.js.map +1 -0
  40. package/dist/ai/index.d.ts +31 -0
  41. package/dist/ai/index.d.ts.map +1 -0
  42. package/dist/ai/index.js +27 -0
  43. package/dist/ai/index.js.map +1 -0
  44. package/dist/ai/instances.d.ts +15 -0
  45. package/dist/ai/instances.d.ts.map +1 -0
  46. package/dist/ai/instances.js +69 -0
  47. package/dist/ai/instances.js.map +1 -0
  48. package/dist/ai/internal.d.ts +13 -0
  49. package/dist/ai/internal.d.ts.map +1 -0
  50. package/dist/ai/internal.js +45 -0
  51. package/dist/ai/internal.js.map +1 -0
  52. package/dist/ai/models.d.ts +116 -0
  53. package/dist/ai/models.d.ts.map +1 -0
  54. package/dist/ai/models.js +213 -0
  55. package/dist/ai/models.js.map +1 -0
  56. package/dist/ai/request-helpers.d.ts +59 -0
  57. package/dist/ai/request-helpers.d.ts.map +1 -0
  58. package/dist/ai/request-helpers.js +157 -0
  59. package/dist/ai/request-helpers.js.map +1 -0
  60. package/dist/ai/response-helpers.d.ts +41 -0
  61. package/dist/ai/response-helpers.d.ts.map +1 -0
  62. package/dist/ai/response-helpers.js +204 -0
  63. package/dist/ai/response-helpers.js.map +1 -0
  64. package/dist/ai/sandbox-plane.d.ts +41 -0
  65. package/dist/ai/sandbox-plane.d.ts.map +1 -0
  66. package/dist/ai/sandbox-plane.js +159 -0
  67. package/dist/ai/sandbox-plane.js.map +1 -0
  68. package/dist/ai/schema.d.ts +105 -0
  69. package/dist/ai/schema.d.ts.map +1 -0
  70. package/dist/ai/schema.js +174 -0
  71. package/dist/ai/schema.js.map +1 -0
  72. package/dist/ai/scripting.d.ts +53 -0
  73. package/dist/ai/scripting.d.ts.map +1 -0
  74. package/dist/ai/scripting.js +73 -0
  75. package/dist/ai/scripting.js.map +1 -0
  76. package/dist/ai/target.d.ts +20 -0
  77. package/dist/ai/target.d.ts.map +1 -0
  78. package/dist/ai/target.js +29 -0
  79. package/dist/ai/target.js.map +1 -0
  80. package/dist/ai/types.d.ts +400 -0
  81. package/dist/ai/types.d.ts.map +1 -0
  82. package/dist/ai/types.js +10 -0
  83. package/dist/ai/types.js.map +1 -0
  84. package/dist/app/diagnostics.d.ts +29 -0
  85. package/dist/app/diagnostics.d.ts.map +1 -0
  86. package/dist/app/diagnostics.js +88 -0
  87. package/dist/app/diagnostics.js.map +1 -0
  88. package/dist/app/index.d.ts +7 -0
  89. package/dist/app/index.d.ts.map +1 -0
  90. package/dist/app/index.js +5 -0
  91. package/dist/app/index.js.map +1 -0
  92. package/dist/app/internal.d.ts +11 -0
  93. package/dist/app/internal.d.ts.map +1 -0
  94. package/dist/app/internal.js +18 -0
  95. package/dist/app/internal.js.map +1 -0
  96. package/dist/app/options.d.ts +3 -0
  97. package/dist/app/options.d.ts.map +1 -0
  98. package/dist/app/options.js +19 -0
  99. package/dist/app/options.js.map +1 -0
  100. package/dist/app/register.d.ts +4 -0
  101. package/dist/app/register.d.ts.map +1 -0
  102. package/dist/app/register.js +35 -0
  103. package/dist/app/register.js.map +1 -0
  104. package/dist/app/registry.d.ts +12 -0
  105. package/dist/app/registry.d.ts.map +1 -0
  106. package/dist/app/registry.js +147 -0
  107. package/dist/app/registry.js.map +1 -0
  108. package/dist/app/runtime.d.ts +18 -0
  109. package/dist/app/runtime.d.ts.map +1 -0
  110. package/dist/app/runtime.js +119 -0
  111. package/dist/app/runtime.js.map +1 -0
  112. package/dist/app/types.d.ts +21 -0
  113. package/dist/app/types.d.ts.map +1 -0
  114. package/dist/app/types.js +2 -0
  115. package/dist/app/types.js.map +1 -0
  116. package/dist/auth/action-code-url.d.ts +70 -0
  117. package/dist/auth/action-code-url.d.ts.map +1 -0
  118. package/dist/auth/action-code-url.js +124 -0
  119. package/dist/auth/action-code-url.js.map +1 -0
  120. package/dist/auth/action-codes.d.ts +201 -0
  121. package/dist/auth/action-codes.d.ts.map +1 -0
  122. package/dist/auth/action-codes.js +355 -0
  123. package/dist/auth/action-codes.js.map +1 -0
  124. package/dist/auth/auth-errors.d.ts +21 -0
  125. package/dist/auth/auth-errors.d.ts.map +1 -0
  126. package/dist/auth/auth-errors.js +23 -0
  127. package/dist/auth/auth-errors.js.map +1 -0
  128. package/dist/auth/config-tokens.d.ts +90 -0
  129. package/dist/auth/config-tokens.d.ts.map +1 -0
  130. package/dist/auth/config-tokens.js +86 -0
  131. package/dist/auth/config-tokens.js.map +1 -0
  132. package/dist/auth/credentials.d.ts +140 -0
  133. package/dist/auth/credentials.d.ts.map +1 -0
  134. package/dist/auth/credentials.js +194 -0
  135. package/dist/auth/credentials.js.map +1 -0
  136. package/dist/auth/email-link.d.ts +91 -0
  137. package/dist/auth/email-link.d.ts.map +1 -0
  138. package/dist/auth/email-link.js +172 -0
  139. package/dist/auth/email-link.js.map +1 -0
  140. package/dist/auth/enums.d.ts +210 -0
  141. package/dist/auth/enums.d.ts.map +1 -0
  142. package/dist/auth/enums.js +206 -0
  143. package/dist/auth/enums.js.map +1 -0
  144. package/dist/auth/index.d.ts +3 -0
  145. package/dist/auth/index.d.ts.map +1 -0
  146. package/dist/auth/index.js +3 -0
  147. package/dist/auth/index.js.map +1 -0
  148. package/dist/auth/instances.d.ts +14 -0
  149. package/dist/auth/instances.d.ts.map +1 -0
  150. package/dist/auth/instances.js +95 -0
  151. package/dist/auth/instances.js.map +1 -0
  152. package/dist/auth/linking.d.ts +93 -0
  153. package/dist/auth/linking.d.ts.map +1 -0
  154. package/dist/auth/linking.js +189 -0
  155. package/dist/auth/linking.js.map +1 -0
  156. package/dist/auth/modular.d.ts +22 -0
  157. package/dist/auth/modular.d.ts.map +1 -0
  158. package/dist/auth/modular.js +18 -0
  159. package/dist/auth/modular.js.map +1 -0
  160. package/dist/auth/password-policy.d.ts +60 -0
  161. package/dist/auth/password-policy.d.ts.map +1 -0
  162. package/dist/auth/password-policy.js +68 -0
  163. package/dist/auth/password-policy.js.map +1 -0
  164. package/dist/auth/providers.d.ts +153 -0
  165. package/dist/auth/providers.d.ts.map +1 -0
  166. package/dist/auth/providers.js +207 -0
  167. package/dist/auth/providers.js.map +1 -0
  168. package/dist/auth/reauth.d.ts +73 -0
  169. package/dist/auth/reauth.d.ts.map +1 -0
  170. package/dist/auth/reauth.js +148 -0
  171. package/dist/auth/reauth.js.map +1 -0
  172. package/dist/auth/sandbox/driver.d.ts +51 -0
  173. package/dist/auth/sandbox/driver.d.ts.map +1 -0
  174. package/dist/auth/sandbox/driver.js +88 -0
  175. package/dist/auth/sandbox/driver.js.map +1 -0
  176. package/dist/auth/sandbox/persistence.d.ts +7 -0
  177. package/dist/auth/sandbox/persistence.d.ts.map +1 -0
  178. package/dist/auth/sandbox/persistence.js +121 -0
  179. package/dist/auth/sandbox/persistence.js.map +1 -0
  180. package/dist/auth/sandbox/project-store.d.ts +15 -0
  181. package/dist/auth/sandbox/project-store.d.ts.map +1 -0
  182. package/dist/auth/sandbox/project-store.js +17 -0
  183. package/dist/auth/sandbox/project-store.js.map +1 -0
  184. package/dist/auth/sandbox-auth-flow.d.ts +173 -0
  185. package/dist/auth/sandbox-auth-flow.d.ts.map +1 -0
  186. package/dist/auth/sandbox-auth-flow.js +165 -0
  187. package/dist/auth/sandbox-auth-flow.js.map +1 -0
  188. package/dist/auth/sandbox-backend-types.d.ts +197 -0
  189. package/dist/auth/sandbox-backend-types.d.ts.map +1 -0
  190. package/dist/auth/sandbox-backend-types.js +18 -0
  191. package/dist/auth/sandbox-backend-types.js.map +1 -0
  192. package/dist/auth/sandbox-backend.d.ts +811 -0
  193. package/dist/auth/sandbox-backend.d.ts.map +1 -0
  194. package/dist/auth/sandbox-backend.js +2007 -0
  195. package/dist/auth/sandbox-backend.js.map +1 -0
  196. package/dist/auth/sandbox-credential-validators.d.ts +30 -0
  197. package/dist/auth/sandbox-credential-validators.d.ts.map +1 -0
  198. package/dist/auth/sandbox-credential-validators.js +47 -0
  199. package/dist/auth/sandbox-credential-validators.js.map +1 -0
  200. package/dist/auth/sandbox-token.d.ts +24 -0
  201. package/dist/auth/sandbox-token.d.ts.map +1 -0
  202. package/dist/auth/sandbox-token.js +32 -0
  203. package/dist/auth/sandbox-token.js.map +1 -0
  204. package/dist/auth/sign-in.d.ts +14 -0
  205. package/dist/auth/sign-in.d.ts.map +1 -0
  206. package/dist/auth/sign-in.js +140 -0
  207. package/dist/auth/sign-in.js.map +1 -0
  208. package/dist/auth/target.d.ts +29 -0
  209. package/dist/auth/target.d.ts.map +1 -0
  210. package/dist/auth/target.js +23 -0
  211. package/dist/auth/target.js.map +1 -0
  212. package/dist/auth/tokens.d.ts +54 -0
  213. package/dist/auth/tokens.d.ts.map +1 -0
  214. package/dist/auth/tokens.js +142 -0
  215. package/dist/auth/tokens.js.map +1 -0
  216. package/dist/auth/types.d.ts +283 -0
  217. package/dist/auth/types.d.ts.map +1 -0
  218. package/dist/auth/types.js +24 -0
  219. package/dist/auth/types.js.map +1 -0
  220. package/dist/auth/user-lifecycle.d.ts +17 -0
  221. package/dist/auth/user-lifecycle.d.ts.map +1 -0
  222. package/dist/auth/user-lifecycle.js +60 -0
  223. package/dist/auth/user-lifecycle.js.map +1 -0
  224. package/dist/database/index.d.ts +9 -0
  225. package/dist/database/index.d.ts.map +1 -0
  226. package/dist/database/index.js +9 -0
  227. package/dist/database/index.js.map +1 -0
  228. package/dist/database/listener-registry.d.ts +16 -0
  229. package/dist/database/listener-registry.d.ts.map +1 -0
  230. package/dist/database/listener-registry.js +68 -0
  231. package/dist/database/listener-registry.js.map +1 -0
  232. package/dist/database/modular.d.ts +632 -0
  233. package/dist/database/modular.d.ts.map +1 -0
  234. package/dist/database/modular.js +1071 -0
  235. package/dist/database/modular.js.map +1 -0
  236. package/dist/database/replay.d.ts +32 -0
  237. package/dist/database/replay.d.ts.map +1 -0
  238. package/dist/database/replay.js +124 -0
  239. package/dist/database/replay.js.map +1 -0
  240. package/dist/database/sandbox/backend-for.d.ts +10 -0
  241. package/dist/database/sandbox/backend-for.d.ts.map +1 -0
  242. package/dist/database/sandbox/backend-for.js +19 -0
  243. package/dist/database/sandbox/backend-for.js.map +1 -0
  244. package/dist/database/sandbox/backend.d.ts +407 -0
  245. package/dist/database/sandbox/backend.d.ts.map +1 -0
  246. package/dist/database/sandbox/backend.js +1495 -0
  247. package/dist/database/sandbox/backend.js.map +1 -0
  248. package/dist/database/sandbox/data-tree.d.ts +123 -0
  249. package/dist/database/sandbox/data-tree.d.ts.map +1 -0
  250. package/dist/database/sandbox/data-tree.js +310 -0
  251. package/dist/database/sandbox/data-tree.js.map +1 -0
  252. package/dist/database/sandbox/normalize.d.ts +77 -0
  253. package/dist/database/sandbox/normalize.d.ts.map +1 -0
  254. package/dist/database/sandbox/normalize.js +165 -0
  255. package/dist/database/sandbox/normalize.js.map +1 -0
  256. package/dist/database/sandbox/push-id.d.ts +32 -0
  257. package/dist/database/sandbox/push-id.d.ts.map +1 -0
  258. package/dist/database/sandbox/push-id.js +82 -0
  259. package/dist/database/sandbox/push-id.js.map +1 -0
  260. package/dist/database/sandbox/query.d.ts +175 -0
  261. package/dist/database/sandbox/query.d.ts.map +1 -0
  262. package/dist/database/sandbox/query.js +269 -0
  263. package/dist/database/sandbox/query.js.map +1 -0
  264. package/dist/database/sandbox/rules-eval.d.ts +87 -0
  265. package/dist/database/sandbox/rules-eval.d.ts.map +1 -0
  266. package/dist/database/sandbox/rules-eval.js +131 -0
  267. package/dist/database/sandbox/rules-eval.js.map +1 -0
  268. package/dist/database/sandbox/sentinels.d.ts +71 -0
  269. package/dist/database/sandbox/sentinels.d.ts.map +1 -0
  270. package/dist/database/sandbox/sentinels.js +92 -0
  271. package/dist/database/sandbox/sentinels.js.map +1 -0
  272. package/dist/database/sandbox-controls.d.ts +15 -0
  273. package/dist/database/sandbox-controls.d.ts.map +1 -0
  274. package/dist/database/sandbox-controls.js +18 -0
  275. package/dist/database/sandbox-controls.js.map +1 -0
  276. package/dist/firestore/aggregates.d.ts +50 -0
  277. package/dist/firestore/aggregates.d.ts.map +1 -0
  278. package/dist/firestore/aggregates.js +40 -0
  279. package/dist/firestore/aggregates.js.map +1 -0
  280. package/dist/firestore/equality.d.ts +5 -0
  281. package/dist/firestore/equality.d.ts.map +1 -0
  282. package/dist/firestore/equality.js +20 -0
  283. package/dist/firestore/equality.js.map +1 -0
  284. package/dist/firestore/field-values.d.ts +61 -0
  285. package/dist/firestore/field-values.d.ts.map +1 -0
  286. package/dist/firestore/field-values.js +167 -0
  287. package/dist/firestore/field-values.js.map +1 -0
  288. package/dist/firestore/index.d.ts +54 -0
  289. package/dist/firestore/index.d.ts.map +1 -0
  290. package/dist/firestore/index.js +54 -0
  291. package/dist/firestore/index.js.map +1 -0
  292. package/dist/firestore/instances.d.ts +123 -0
  293. package/dist/firestore/instances.d.ts.map +1 -0
  294. package/dist/firestore/instances.js +177 -0
  295. package/dist/firestore/instances.js.map +1 -0
  296. package/dist/firestore/internal/index.d.ts +2 -0
  297. package/dist/firestore/internal/index.d.ts.map +1 -0
  298. package/dist/firestore/internal/index.js +2 -0
  299. package/dist/firestore/internal/index.js.map +1 -0
  300. package/dist/firestore/internal/listener-routing.d.ts +4 -0
  301. package/dist/firestore/internal/listener-routing.d.ts.map +1 -0
  302. package/dist/firestore/internal/listener-routing.js +4 -0
  303. package/dist/firestore/internal/listener-routing.js.map +1 -0
  304. package/dist/firestore/listeners.d.ts +12 -0
  305. package/dist/firestore/listeners.d.ts.map +1 -0
  306. package/dist/firestore/listeners.js +200 -0
  307. package/dist/firestore/listeners.js.map +1 -0
  308. package/dist/firestore/persistence.d.ts +227 -0
  309. package/dist/firestore/persistence.d.ts.map +1 -0
  310. package/dist/firestore/persistence.js +245 -0
  311. package/dist/firestore/persistence.js.map +1 -0
  312. package/dist/firestore/query-constraints.d.ts +72 -0
  313. package/dist/firestore/query-constraints.d.ts.map +1 -0
  314. package/dist/firestore/query-constraints.js +168 -0
  315. package/dist/firestore/query-constraints.js.map +1 -0
  316. package/dist/firestore/reads.d.ts +12 -0
  317. package/dist/firestore/reads.d.ts.map +1 -0
  318. package/dist/firestore/reads.js +32 -0
  319. package/dist/firestore/reads.js.map +1 -0
  320. package/dist/firestore/refs.d.ts +27 -0
  321. package/dist/firestore/refs.d.ts.map +1 -0
  322. package/dist/firestore/refs.js +74 -0
  323. package/dist/firestore/refs.js.map +1 -0
  324. package/dist/firestore/sandbox-controls.d.ts +60 -0
  325. package/dist/firestore/sandbox-controls.d.ts.map +1 -0
  326. package/dist/firestore/sandbox-controls.js +77 -0
  327. package/dist/firestore/sandbox-controls.js.map +1 -0
  328. package/dist/firestore/snapshots.d.ts +71 -0
  329. package/dist/firestore/snapshots.d.ts.map +1 -0
  330. package/dist/firestore/snapshots.js +160 -0
  331. package/dist/firestore/snapshots.js.map +1 -0
  332. package/dist/firestore/state.d.ts +168 -0
  333. package/dist/firestore/state.d.ts.map +1 -0
  334. package/dist/firestore/state.js +260 -0
  335. package/dist/firestore/state.js.map +1 -0
  336. package/dist/firestore/tools.d.ts +71 -0
  337. package/dist/firestore/tools.d.ts.map +1 -0
  338. package/dist/firestore/tools.js +320 -0
  339. package/dist/firestore/tools.js.map +1 -0
  340. package/dist/firestore/transactions.d.ts +4 -0
  341. package/dist/firestore/transactions.d.ts.map +1 -0
  342. package/dist/firestore/transactions.js +14 -0
  343. package/dist/firestore/transactions.js.map +1 -0
  344. package/dist/firestore/types.d.ts +82 -0
  345. package/dist/firestore/types.d.ts.map +1 -0
  346. package/dist/firestore/types.js +15 -0
  347. package/dist/firestore/types.js.map +1 -0
  348. package/dist/firestore/writes.d.ts +43 -0
  349. package/dist/firestore/writes.d.ts.map +1 -0
  350. package/dist/firestore/writes.js +40 -0
  351. package/dist/firestore/writes.js.map +1 -0
  352. package/dist/firestore-values/index.d.ts +63 -0
  353. package/dist/firestore-values/index.d.ts.map +1 -0
  354. package/dist/firestore-values/index.js +148 -0
  355. package/dist/firestore-values/index.js.map +1 -0
  356. package/dist/messaging/broker/broker.d.ts +171 -0
  357. package/dist/messaging/broker/broker.d.ts.map +1 -0
  358. package/dist/messaging/broker/broker.js +400 -0
  359. package/dist/messaging/broker/broker.js.map +1 -0
  360. package/dist/messaging/broker/envelopes.d.ts +96 -0
  361. package/dist/messaging/broker/envelopes.d.ts.map +1 -0
  362. package/dist/messaging/broker/envelopes.js +132 -0
  363. package/dist/messaging/broker/envelopes.js.map +1 -0
  364. package/dist/messaging/broker/index.d.ts +27 -0
  365. package/dist/messaging/broker/index.d.ts.map +1 -0
  366. package/dist/messaging/broker/index.js +21 -0
  367. package/dist/messaging/broker/index.js.map +1 -0
  368. package/dist/messaging/broker/tokens.d.ts +22 -0
  369. package/dist/messaging/broker/tokens.d.ts.map +1 -0
  370. package/dist/messaging/broker/tokens.js +37 -0
  371. package/dist/messaging/broker/tokens.js.map +1 -0
  372. package/dist/messaging/broker/types.d.ts +117 -0
  373. package/dist/messaging/broker/types.d.ts.map +1 -0
  374. package/dist/messaging/broker/types.js +12 -0
  375. package/dist/messaging/broker/types.js.map +1 -0
  376. package/dist/messaging/broker/validate.d.ts +58 -0
  377. package/dist/messaging/broker/validate.d.ts.map +1 -0
  378. package/dist/messaging/broker/validate.js +196 -0
  379. package/dist/messaging/broker/validate.js.map +1 -0
  380. package/dist/messaging/client.d.ts +108 -0
  381. package/dist/messaging/client.d.ts.map +1 -0
  382. package/dist/messaging/client.js +65 -0
  383. package/dist/messaging/client.js.map +1 -0
  384. package/dist/messaging/index.d.ts +3 -0
  385. package/dist/messaging/index.d.ts.map +1 -0
  386. package/dist/messaging/index.js +3 -0
  387. package/dist/messaging/index.js.map +1 -0
  388. package/dist/messaging/instance.d.ts +72 -0
  389. package/dist/messaging/instance.d.ts.map +1 -0
  390. package/dist/messaging/instance.js +93 -0
  391. package/dist/messaging/instance.js.map +1 -0
  392. package/dist/messaging/internal.d.ts +12 -0
  393. package/dist/messaging/internal.d.ts.map +1 -0
  394. package/dist/messaging/internal.js +12 -0
  395. package/dist/messaging/internal.js.map +1 -0
  396. package/dist/messaging/sw.d.ts +49 -0
  397. package/dist/messaging/sw.d.ts.map +1 -0
  398. package/dist/messaging/sw.js +49 -0
  399. package/dist/messaging/sw.js.map +1 -0
  400. package/dist/project-scope.d.ts +5 -0
  401. package/dist/project-scope.d.ts.map +1 -0
  402. package/dist/project-scope.js +2 -0
  403. package/dist/project-scope.js.map +1 -0
  404. package/dist/rules/api/assert.d.ts +39 -0
  405. package/dist/rules/api/assert.d.ts.map +1 -0
  406. package/dist/rules/api/assert.js +93 -0
  407. package/dist/rules/api/assert.js.map +1 -0
  408. package/dist/rules/api/case-types.d.ts +141 -0
  409. package/dist/rules/api/case-types.d.ts.map +1 -0
  410. package/dist/rules/api/case-types.js +13 -0
  411. package/dist/rules/api/case-types.js.map +1 -0
  412. package/dist/rules/api/errors.d.ts +38 -0
  413. package/dist/rules/api/errors.d.ts.map +1 -0
  414. package/dist/rules/api/errors.js +47 -0
  415. package/dist/rules/api/errors.js.map +1 -0
  416. package/dist/rules/api/firestore.d.ts +34 -0
  417. package/dist/rules/api/firestore.d.ts.map +1 -0
  418. package/dist/rules/api/firestore.js +137 -0
  419. package/dist/rules/api/firestore.js.map +1 -0
  420. package/dist/rules/api/issue.d.ts +50 -0
  421. package/dist/rules/api/issue.d.ts.map +1 -0
  422. package/dist/rules/api/issue.js +66 -0
  423. package/dist/rules/api/issue.js.map +1 -0
  424. package/dist/rules/api/lint.d.ts +16 -0
  425. package/dist/rules/api/lint.d.ts.map +1 -0
  426. package/dist/rules/api/lint.js +60 -0
  427. package/dist/rules/api/lint.js.map +1 -0
  428. package/dist/rules/api/rtdb.d.ts +33 -0
  429. package/dist/rules/api/rtdb.d.ts.map +1 -0
  430. package/dist/rules/api/rtdb.js +166 -0
  431. package/dist/rules/api/rtdb.js.map +1 -0
  432. package/dist/rules/api/values.d.ts +51 -0
  433. package/dist/rules/api/values.d.ts.map +1 -0
  434. package/dist/rules/api/values.js +66 -0
  435. package/dist/rules/api/values.js.map +1 -0
  436. package/dist/rules/generators/assembler.d.ts +19 -0
  437. package/dist/rules/generators/assembler.d.ts.map +1 -0
  438. package/dist/rules/generators/assembler.js +292 -0
  439. package/dist/rules/generators/assembler.js.map +1 -0
  440. package/dist/rules/generators/expressions.d.ts +52 -0
  441. package/dist/rules/generators/expressions.d.ts.map +1 -0
  442. package/dist/rules/generators/expressions.js +117 -0
  443. package/dist/rules/generators/expressions.js.map +1 -0
  444. package/dist/rules/generators/grid.d.ts +22 -0
  445. package/dist/rules/generators/grid.d.ts.map +1 -0
  446. package/dist/rules/generators/grid.js +52 -0
  447. package/dist/rules/generators/grid.js.map +1 -0
  448. package/dist/rules/grammar/FirestoreAST.d.ts +129 -0
  449. package/dist/rules/grammar/FirestoreAST.d.ts.map +1 -0
  450. package/dist/rules/grammar/FirestoreAST.js +3 -0
  451. package/dist/rules/grammar/FirestoreAST.js.map +1 -0
  452. package/dist/rules/grammar/FirestoreAssembler.d.ts +5 -0
  453. package/dist/rules/grammar/FirestoreAssembler.d.ts.map +1 -0
  454. package/dist/rules/grammar/FirestoreAssembler.js +158 -0
  455. package/dist/rules/grammar/FirestoreAssembler.js.map +1 -0
  456. package/dist/rules/grammar/FirestoreParser.d.ts +46 -0
  457. package/dist/rules/grammar/FirestoreParser.d.ts.map +1 -0
  458. package/dist/rules/grammar/FirestoreParser.js +409 -0
  459. package/dist/rules/grammar/FirestoreParser.js.map +1 -0
  460. package/dist/rules/grammar/FirestoreRules.ohm +229 -0
  461. package/dist/rules/grammar/FirestoreRules.ohm.generated.d.ts +2 -0
  462. package/dist/rules/grammar/FirestoreRules.ohm.generated.d.ts.map +1 -0
  463. package/dist/rules/grammar/FirestoreRules.ohm.generated.js +234 -0
  464. package/dist/rules/grammar/FirestoreRules.ohm.generated.js.map +1 -0
  465. package/dist/rules/grammar/FirestoreValidator.d.ts +10 -0
  466. package/dist/rules/grammar/FirestoreValidator.d.ts.map +1 -0
  467. package/dist/rules/grammar/FirestoreValidator.js +482 -0
  468. package/dist/rules/grammar/FirestoreValidator.js.map +1 -0
  469. package/dist/rules/index.d.ts +41 -0
  470. package/dist/rules/index.d.ts.map +1 -0
  471. package/dist/rules/index.js +40 -0
  472. package/dist/rules/index.js.map +1 -0
  473. package/dist/rules/indexes/extract/annotation-collect.d.ts +42 -0
  474. package/dist/rules/indexes/extract/annotation-collect.d.ts.map +1 -0
  475. package/dist/rules/indexes/extract/annotation-collect.js +69 -0
  476. package/dist/rules/indexes/extract/annotation-collect.js.map +1 -0
  477. package/dist/rules/indexes/extract/annotations.d.ts +50 -0
  478. package/dist/rules/indexes/extract/annotations.d.ts.map +1 -0
  479. package/dist/rules/indexes/extract/annotations.js +144 -0
  480. package/dist/rules/indexes/extract/annotations.js.map +1 -0
  481. package/dist/rules/indexes/extract/ast.d.ts +54 -0
  482. package/dist/rules/indexes/extract/ast.d.ts.map +1 -0
  483. package/dist/rules/indexes/extract/ast.js +119 -0
  484. package/dist/rules/indexes/extract/ast.js.map +1 -0
  485. package/dist/rules/indexes/extract/classify.d.ts +41 -0
  486. package/dist/rules/indexes/extract/classify.d.ts.map +1 -0
  487. package/dist/rules/indexes/extract/classify.js +138 -0
  488. package/dist/rules/indexes/extract/classify.js.map +1 -0
  489. package/dist/rules/indexes/extract/composite.d.ts +38 -0
  490. package/dist/rules/indexes/extract/composite.d.ts.map +1 -0
  491. package/dist/rules/indexes/extract/composite.js +85 -0
  492. package/dist/rules/indexes/extract/composite.js.map +1 -0
  493. package/dist/rules/indexes/extract/dataflow.d.ts +45 -0
  494. package/dist/rules/indexes/extract/dataflow.d.ts.map +1 -0
  495. package/dist/rules/indexes/extract/dataflow.js +200 -0
  496. package/dist/rules/indexes/extract/dataflow.js.map +1 -0
  497. package/dist/rules/indexes/extract/enumerate.d.ts +41 -0
  498. package/dist/rules/indexes/extract/enumerate.d.ts.map +1 -0
  499. package/dist/rules/indexes/extract/enumerate.js +163 -0
  500. package/dist/rules/indexes/extract/enumerate.js.map +1 -0
  501. package/dist/rules/indexes/extract/extractor.d.ts +3 -0
  502. package/dist/rules/indexes/extract/extractor.d.ts.map +1 -0
  503. package/dist/rules/indexes/extract/extractor.js +274 -0
  504. package/dist/rules/indexes/extract/extractor.js.map +1 -0
  505. package/dist/rules/indexes/extract/types.d.ts +211 -0
  506. package/dist/rules/indexes/extract/types.d.ts.map +1 -0
  507. package/dist/rules/indexes/extract/types.js +14 -0
  508. package/dist/rules/indexes/extract/types.js.map +1 -0
  509. package/dist/rules/indexes/extractHandler.d.ts +16 -0
  510. package/dist/rules/indexes/extractHandler.d.ts.map +1 -0
  511. package/dist/rules/indexes/extractHandler.js +100 -0
  512. package/dist/rules/indexes/extractHandler.js.map +1 -0
  513. package/dist/rules/indexes/extractTool.d.ts +15 -0
  514. package/dist/rules/indexes/extractTool.d.ts.map +1 -0
  515. package/dist/rules/indexes/extractTool.js +55 -0
  516. package/dist/rules/indexes/extractTool.js.map +1 -0
  517. package/dist/rules/indexes/types.d.ts +71 -0
  518. package/dist/rules/indexes/types.d.ts.map +1 -0
  519. package/dist/rules/indexes/types.js +15 -0
  520. package/dist/rules/indexes/types.js.map +1 -0
  521. package/dist/rules/inspect/handler.d.ts +6 -0
  522. package/dist/rules/inspect/handler.d.ts.map +1 -0
  523. package/dist/rules/inspect/handler.js +144 -0
  524. package/dist/rules/inspect/handler.js.map +1 -0
  525. package/dist/rules/inspect/spec.d.ts +37 -0
  526. package/dist/rules/inspect/spec.d.ts.map +1 -0
  527. package/dist/rules/inspect/spec.js +2 -0
  528. package/dist/rules/inspect/spec.js.map +1 -0
  529. package/dist/rules/inspect/tools.d.ts +21 -0
  530. package/dist/rules/inspect/tools.d.ts.map +1 -0
  531. package/dist/rules/inspect/tools.js +21 -0
  532. package/dist/rules/inspect/tools.js.map +1 -0
  533. package/dist/rules/internal/extract.d.ts +28 -0
  534. package/dist/rules/internal/extract.d.ts.map +1 -0
  535. package/dist/rules/internal/extract.js +25 -0
  536. package/dist/rules/internal/extract.js.map +1 -0
  537. package/dist/rules/internal/index.d.ts +82 -0
  538. package/dist/rules/internal/index.d.ts.map +1 -0
  539. package/dist/rules/internal/index.js +103 -0
  540. package/dist/rules/internal/index.js.map +1 -0
  541. package/dist/rules/internal/node.d.ts +18 -0
  542. package/dist/rules/internal/node.d.ts.map +1 -0
  543. package/dist/rules/internal/node.js +27 -0
  544. package/dist/rules/internal/node.js.map +1 -0
  545. package/dist/rules/internal/rtdb.d.ts +20 -0
  546. package/dist/rules/internal/rtdb.d.ts.map +1 -0
  547. package/dist/rules/internal/rtdb.js +15 -0
  548. package/dist/rules/internal/rtdb.js.map +1 -0
  549. package/dist/rules/linter/ast-utils.d.ts +97 -0
  550. package/dist/rules/linter/ast-utils.d.ts.map +1 -0
  551. package/dist/rules/linter/ast-utils.js +491 -0
  552. package/dist/rules/linter/ast-utils.js.map +1 -0
  553. package/dist/rules/linter/hallucinations.d.ts +34 -0
  554. package/dist/rules/linter/hallucinations.d.ts.map +1 -0
  555. package/dist/rules/linter/hallucinations.js +334 -0
  556. package/dist/rules/linter/hallucinations.js.map +1 -0
  557. package/dist/rules/linter/linter.d.ts +84 -0
  558. package/dist/rules/linter/linter.d.ts.map +1 -0
  559. package/dist/rules/linter/linter.js +783 -0
  560. package/dist/rules/linter/linter.js.map +1 -0
  561. package/dist/rules/modules/resolver-browser.d.ts +41 -0
  562. package/dist/rules/modules/resolver-browser.d.ts.map +1 -0
  563. package/dist/rules/modules/resolver-browser.js +63 -0
  564. package/dist/rules/modules/resolver-browser.js.map +1 -0
  565. package/dist/rules/modules/resolver-core.d.ts +51 -0
  566. package/dist/rules/modules/resolver-core.d.ts.map +1 -0
  567. package/dist/rules/modules/resolver-core.js +338 -0
  568. package/dist/rules/modules/resolver-core.js.map +1 -0
  569. package/dist/rules/modules/resolver.d.ts +17 -0
  570. package/dist/rules/modules/resolver.d.ts.map +1 -0
  571. package/dist/rules/modules/resolver.js +49 -0
  572. package/dist/rules/modules/resolver.js.map +1 -0
  573. package/dist/rules/modules/stdlib/atomic.rules +52 -0
  574. package/dist/rules/modules/stdlib/atomic.test.json +152 -0
  575. package/dist/rules/modules/stdlib/auth.rules +7 -0
  576. package/dist/rules/modules/stdlib/auth.test.json +53 -0
  577. package/dist/rules/modules/stdlib/content.rules +50 -0
  578. package/dist/rules/modules/stdlib/content.test.json +238 -0
  579. package/dist/rules/modules/stdlib/counters.rules +41 -0
  580. package/dist/rules/modules/stdlib/counters.test.json +254 -0
  581. package/dist/rules/modules/stdlib/geometry.rules +43 -0
  582. package/dist/rules/modules/stdlib/geometry.test.json +200 -0
  583. package/dist/rules/modules/stdlib/joining.rules +49 -0
  584. package/dist/rules/modules/stdlib/joining.test.json +287 -0
  585. package/dist/rules/modules/stdlib/lifecycle.rules +51 -0
  586. package/dist/rules/modules/stdlib/lifecycle.test.json +288 -0
  587. package/dist/rules/modules/stdlib/lobby.rules +44 -0
  588. package/dist/rules/modules/stdlib/lobby.test.json +32 -0
  589. package/dist/rules/modules/stdlib/membership.rules +40 -0
  590. package/dist/rules/modules/stdlib/membership.test.json +107 -0
  591. package/dist/rules/modules/stdlib/spaces.rules +46 -0
  592. package/dist/rules/modules/stdlib/spaces.test.json +392 -0
  593. package/dist/rules/modules/stdlib/state.rules +28 -0
  594. package/dist/rules/modules/stdlib/state.test.json +55 -0
  595. package/dist/rules/modules/stdlib/timing.rules +20 -0
  596. package/dist/rules/modules/stdlib/timing.test.json +106 -0
  597. package/dist/rules/modules/stdlib/transitions.rules +34 -0
  598. package/dist/rules/modules/stdlib/transitions.test.json +86 -0
  599. package/dist/rules/modules/stdlib/turns.rules +27 -0
  600. package/dist/rules/modules/stdlib/turns.test.json +64 -0
  601. package/dist/rules/modules/stdlib/validation.rules +31 -0
  602. package/dist/rules/modules/stdlib/validation.test.json +184 -0
  603. package/dist/rules/modules/stdlib-content.d.ts +11 -0
  604. package/dist/rules/modules/stdlib-content.d.ts.map +1 -0
  605. package/dist/rules/modules/stdlib-content.js +590 -0
  606. package/dist/rules/modules/stdlib-content.js.map +1 -0
  607. package/dist/rules/rtdb/compiled-rules.d.ts +11 -0
  608. package/dist/rules/rtdb/compiled-rules.d.ts.map +1 -0
  609. package/dist/rules/rtdb/compiled-rules.js +95 -0
  610. package/dist/rules/rtdb/compiled-rules.js.map +1 -0
  611. package/dist/rules/rtdb/constraints/atoms.d.ts +29 -0
  612. package/dist/rules/rtdb/constraints/atoms.d.ts.map +1 -0
  613. package/dist/rules/rtdb/constraints/atoms.js +43 -0
  614. package/dist/rules/rtdb/constraints/atoms.js.map +1 -0
  615. package/dist/rules/rtdb/constraints/compose.d.ts +16 -0
  616. package/dist/rules/rtdb/constraints/compose.d.ts.map +1 -0
  617. package/dist/rules/rtdb/constraints/compose.js +15 -0
  618. package/dist/rules/rtdb/constraints/compose.js.map +1 -0
  619. package/dist/rules/rtdb/constraints/data.d.ts +30 -0
  620. package/dist/rules/rtdb/constraints/data.d.ts.map +1 -0
  621. package/dist/rules/rtdb/constraints/data.js +46 -0
  622. package/dist/rules/rtdb/constraints/data.js.map +1 -0
  623. package/dist/rules/rtdb/constraints/document.d.ts +57 -0
  624. package/dist/rules/rtdb/constraints/document.d.ts.map +1 -0
  625. package/dist/rules/rtdb/constraints/document.js +85 -0
  626. package/dist/rules/rtdb/constraints/document.js.map +1 -0
  627. package/dist/rules/rtdb/constraints/game.d.ts +30 -0
  628. package/dist/rules/rtdb/constraints/game.d.ts.map +1 -0
  629. package/dist/rules/rtdb/constraints/game.js +49 -0
  630. package/dist/rules/rtdb/constraints/game.js.map +1 -0
  631. package/dist/rules/rtdb/constraints/index.d.ts +12 -0
  632. package/dist/rules/rtdb/constraints/index.d.ts.map +1 -0
  633. package/dist/rules/rtdb/constraints/index.js +9 -0
  634. package/dist/rules/rtdb/constraints/index.js.map +1 -0
  635. package/dist/rules/rtdb/constraints/policies.d.ts +16 -0
  636. package/dist/rules/rtdb/constraints/policies.d.ts.map +1 -0
  637. package/dist/rules/rtdb/constraints/policies.js +17 -0
  638. package/dist/rules/rtdb/constraints/policies.js.map +1 -0
  639. package/dist/rules/rtdb/constraints/ruleset.d.ts +5 -0
  640. package/dist/rules/rtdb/constraints/ruleset.d.ts.map +1 -0
  641. package/dist/rules/rtdb/constraints/ruleset.js +132 -0
  642. package/dist/rules/rtdb/constraints/ruleset.js.map +1 -0
  643. package/dist/rules/rtdb/constraints/schema.d.ts +17 -0
  644. package/dist/rules/rtdb/constraints/schema.d.ts.map +1 -0
  645. package/dist/rules/rtdb/constraints/schema.js +74 -0
  646. package/dist/rules/rtdb/constraints/schema.js.map +1 -0
  647. package/dist/rules/rtdb/constraints/types.d.ts +22 -0
  648. package/dist/rules/rtdb/constraints/types.d.ts.map +1 -0
  649. package/dist/rules/rtdb/constraints/types.js +2 -0
  650. package/dist/rules/rtdb/constraints/types.js.map +1 -0
  651. package/dist/rules/rtdb/constraints/write-rules-file.d.ts +24 -0
  652. package/dist/rules/rtdb/constraints/write-rules-file.d.ts.map +1 -0
  653. package/dist/rules/rtdb/constraints/write-rules-file.js +30 -0
  654. package/dist/rules/rtdb/constraints/write-rules-file.js.map +1 -0
  655. package/dist/rules/rtdb/expression-engine.d.ts +8 -0
  656. package/dist/rules/rtdb/expression-engine.d.ts.map +1 -0
  657. package/dist/rules/rtdb/expression-engine.js +20 -0
  658. package/dist/rules/rtdb/expression-engine.js.map +1 -0
  659. package/dist/rules/rtdb/grammar/RtdbExpr.ohm +98 -0
  660. package/dist/rules/rtdb/grammar/RtdbExpr.ohm.generated.d.ts +2 -0
  661. package/dist/rules/rtdb/grammar/RtdbExpr.ohm.generated.d.ts.map +1 -0
  662. package/dist/rules/rtdb/grammar/RtdbExpr.ohm.generated.js +103 -0
  663. package/dist/rules/rtdb/grammar/RtdbExpr.ohm.generated.js.map +1 -0
  664. package/dist/rules/rtdb/grammar/RtdbExprParser.d.ts +3 -0
  665. package/dist/rules/rtdb/grammar/RtdbExprParser.d.ts.map +1 -0
  666. package/dist/rules/rtdb/grammar/RtdbExprParser.js +56 -0
  667. package/dist/rules/rtdb/grammar/RtdbExprParser.js.map +1 -0
  668. package/dist/rules/rtdb/grammar/linter.d.ts +3 -0
  669. package/dist/rules/rtdb/grammar/linter.d.ts.map +1 -0
  670. package/dist/rules/rtdb/grammar/linter.js +73 -0
  671. package/dist/rules/rtdb/grammar/linter.js.map +1 -0
  672. package/dist/rules/rtdb/grammar/simulator.d.ts +30 -0
  673. package/dist/rules/rtdb/grammar/simulator.d.ts.map +1 -0
  674. package/dist/rules/rtdb/grammar/simulator.js +282 -0
  675. package/dist/rules/rtdb/grammar/simulator.js.map +1 -0
  676. package/dist/rules/rtdb/grammar/validator.d.ts +3 -0
  677. package/dist/rules/rtdb/grammar/validator.d.ts.map +1 -0
  678. package/dist/rules/rtdb/grammar/validator.js +91 -0
  679. package/dist/rules/rtdb/grammar/validator.js.map +1 -0
  680. package/dist/rules/rtdb/simulation/handler.d.ts +6 -0
  681. package/dist/rules/rtdb/simulation/handler.d.ts.map +1 -0
  682. package/dist/rules/rtdb/simulation/handler.js +325 -0
  683. package/dist/rules/rtdb/simulation/handler.js.map +1 -0
  684. package/dist/rules/rtdb/simulation/spec.d.ts +102 -0
  685. package/dist/rules/rtdb/simulation/spec.d.ts.map +1 -0
  686. package/dist/rules/rtdb/simulation/spec.js +40 -0
  687. package/dist/rules/rtdb/simulation/spec.js.map +1 -0
  688. package/dist/rules/rtdb/types.d.ts +166 -0
  689. package/dist/rules/rtdb/types.d.ts.map +1 -0
  690. package/dist/rules/rtdb/types.js +21 -0
  691. package/dist/rules/rtdb/types.js.map +1 -0
  692. package/dist/rules/simulator/evaluator.d.ts +206 -0
  693. package/dist/rules/simulator/evaluator.d.ts.map +1 -0
  694. package/dist/rules/simulator/evaluator.js +1251 -0
  695. package/dist/rules/simulator/evaluator.js.map +1 -0
  696. package/dist/rules/simulator/expression/eval-errors.d.ts +86 -0
  697. package/dist/rules/simulator/expression/eval-errors.d.ts.map +1 -0
  698. package/dist/rules/simulator/expression/eval-errors.js +68 -0
  699. package/dist/rules/simulator/expression/eval-errors.js.map +1 -0
  700. package/dist/rules/simulator/expression/evaluator.d.ts +43 -0
  701. package/dist/rules/simulator/expression/evaluator.d.ts.map +1 -0
  702. package/dist/rules/simulator/expression/evaluator.js +298 -0
  703. package/dist/rules/simulator/expression/evaluator.js.map +1 -0
  704. package/dist/rules/simulator/expression/lexer.d.ts +36 -0
  705. package/dist/rules/simulator/expression/lexer.d.ts.map +1 -0
  706. package/dist/rules/simulator/expression/lexer.js +318 -0
  707. package/dist/rules/simulator/expression/lexer.js.map +1 -0
  708. package/dist/rules/simulator/expression/parser.d.ts +39 -0
  709. package/dist/rules/simulator/expression/parser.d.ts.map +1 -0
  710. package/dist/rules/simulator/expression/parser.js +329 -0
  711. package/dist/rules/simulator/expression/parser.js.map +1 -0
  712. package/dist/rules/simulator/expression/types.d.ts +137 -0
  713. package/dist/rules/simulator/expression/types.d.ts.map +1 -0
  714. package/dist/rules/simulator/expression/types.js +90 -0
  715. package/dist/rules/simulator/expression/types.js.map +1 -0
  716. package/dist/rules/simulator/expression/walk-data.d.ts +52 -0
  717. package/dist/rules/simulator/expression/walk-data.d.ts.map +1 -0
  718. package/dist/rules/simulator/expression/walk-data.js +167 -0
  719. package/dist/rules/simulator/expression/walk-data.js.map +1 -0
  720. package/dist/rules/simulator/firestore-set.d.ts +25 -0
  721. package/dist/rules/simulator/firestore-set.d.ts.map +1 -0
  722. package/dist/rules/simulator/firestore-set.js +89 -0
  723. package/dist/rules/simulator/firestore-set.js.map +1 -0
  724. package/dist/rules/simulator/handler.d.ts +47 -0
  725. package/dist/rules/simulator/handler.d.ts.map +1 -0
  726. package/dist/rules/simulator/handler.js +644 -0
  727. package/dist/rules/simulator/handler.js.map +1 -0
  728. package/dist/rules/simulator/mapdiff.d.ts +29 -0
  729. package/dist/rules/simulator/mapdiff.d.ts.map +1 -0
  730. package/dist/rules/simulator/mapdiff.js +72 -0
  731. package/dist/rules/simulator/mapdiff.js.map +1 -0
  732. package/dist/rules/simulator/project-after-state.d.ts +33 -0
  733. package/dist/rules/simulator/project-after-state.d.ts.map +1 -0
  734. package/dist/rules/simulator/project-after-state.js +88 -0
  735. package/dist/rules/simulator/project-after-state.js.map +1 -0
  736. package/dist/rules/simulator/query-proof.d.ts +80 -0
  737. package/dist/rules/simulator/query-proof.d.ts.map +1 -0
  738. package/dist/rules/simulator/query-proof.js +142 -0
  739. package/dist/rules/simulator/query-proof.js.map +1 -0
  740. package/dist/rules/simulator/value-equality.d.ts +8 -0
  741. package/dist/rules/simulator/value-equality.d.ts.map +1 -0
  742. package/dist/rules/simulator/value-equality.js +40 -0
  743. package/dist/rules/simulator/value-equality.js.map +1 -0
  744. package/dist/rules/simulator/wrappers/base.d.ts +129 -0
  745. package/dist/rules/simulator/wrappers/base.d.ts.map +1 -0
  746. package/dist/rules/simulator/wrappers/base.js +90 -0
  747. package/dist/rules/simulator/wrappers/base.js.map +1 -0
  748. package/dist/rules/simulator/wrappers/bytes.d.ts +45 -0
  749. package/dist/rules/simulator/wrappers/bytes.d.ts.map +1 -0
  750. package/dist/rules/simulator/wrappers/bytes.js +130 -0
  751. package/dist/rules/simulator/wrappers/bytes.js.map +1 -0
  752. package/dist/rules/simulator/wrappers/duration.d.ts +76 -0
  753. package/dist/rules/simulator/wrappers/duration.d.ts.map +1 -0
  754. package/dist/rules/simulator/wrappers/duration.js +176 -0
  755. package/dist/rules/simulator/wrappers/duration.js.map +1 -0
  756. package/dist/rules/simulator/wrappers/float.d.ts +52 -0
  757. package/dist/rules/simulator/wrappers/float.d.ts.map +1 -0
  758. package/dist/rules/simulator/wrappers/float.js +88 -0
  759. package/dist/rules/simulator/wrappers/float.js.map +1 -0
  760. package/dist/rules/simulator/wrappers/latlng.d.ts +40 -0
  761. package/dist/rules/simulator/wrappers/latlng.d.ts.map +1 -0
  762. package/dist/rules/simulator/wrappers/latlng.js +100 -0
  763. package/dist/rules/simulator/wrappers/latlng.js.map +1 -0
  764. package/dist/rules/simulator/wrappers/path.d.ts +75 -0
  765. package/dist/rules/simulator/wrappers/path.d.ts.map +1 -0
  766. package/dist/rules/simulator/wrappers/path.js +158 -0
  767. package/dist/rules/simulator/wrappers/path.js.map +1 -0
  768. package/dist/rules/simulator/wrappers/reference.d.ts +82 -0
  769. package/dist/rules/simulator/wrappers/reference.d.ts.map +1 -0
  770. package/dist/rules/simulator/wrappers/reference.js +145 -0
  771. package/dist/rules/simulator/wrappers/reference.js.map +1 -0
  772. package/dist/rules/simulator/wrappers/timestamp.d.ts +86 -0
  773. package/dist/rules/simulator/wrappers/timestamp.d.ts.map +1 -0
  774. package/dist/rules/simulator/wrappers/timestamp.js +207 -0
  775. package/dist/rules/simulator/wrappers/timestamp.js.map +1 -0
  776. package/dist/rules/simulator/wrappers/vector.d.ts +43 -0
  777. package/dist/rules/simulator/wrappers/vector.d.ts.map +1 -0
  778. package/dist/rules/simulator/wrappers/vector.js +80 -0
  779. package/dist/rules/simulator/wrappers/vector.js.map +1 -0
  780. package/dist/rules/simulator-tools-impl.d.ts +64 -0
  781. package/dist/rules/simulator-tools-impl.d.ts.map +1 -0
  782. package/dist/rules/simulator-tools-impl.js +462 -0
  783. package/dist/rules/simulator-tools-impl.js.map +1 -0
  784. package/dist/rules/simulator.d.ts +20 -0
  785. package/dist/rules/simulator.d.ts.map +1 -0
  786. package/dist/rules/simulator.js +24 -0
  787. package/dist/rules/simulator.js.map +1 -0
  788. package/dist/rules/stdlib-modules.d.ts +73 -0
  789. package/dist/rules/stdlib-modules.d.ts.map +1 -0
  790. package/dist/rules/stdlib-modules.js +837 -0
  791. package/dist/rules/stdlib-modules.js.map +1 -0
  792. package/dist/rules/stdlib-tools.d.ts +19 -0
  793. package/dist/rules/stdlib-tools.d.ts.map +1 -0
  794. package/dist/rules/stdlib-tools.js +164 -0
  795. package/dist/rules/stdlib-tools.js.map +1 -0
  796. package/dist/rules/test/handler.d.ts +21 -0
  797. package/dist/rules/test/handler.d.ts.map +1 -0
  798. package/dist/rules/test/handler.js +214 -0
  799. package/dist/rules/test/handler.js.map +1 -0
  800. package/dist/rules/test/spec.d.ts +677 -0
  801. package/dist/rules/test/spec.d.ts.map +1 -0
  802. package/dist/rules/test/spec.js +327 -0
  803. package/dist/rules/test/spec.js.map +1 -0
  804. package/dist/rules/tools.d.ts +41 -0
  805. package/dist/rules/tools.d.ts.map +1 -0
  806. package/dist/rules/tools.js +120 -0
  807. package/dist/rules/tools.js.map +1 -0
  808. package/dist/rules/write/handler.d.ts +6 -0
  809. package/dist/rules/write/handler.d.ts.map +1 -0
  810. package/dist/rules/write/handler.js +126 -0
  811. package/dist/rules/write/handler.js.map +1 -0
  812. package/dist/rules/write/spec.d.ts +28 -0
  813. package/dist/rules/write/spec.d.ts.map +1 -0
  814. package/dist/rules/write/spec.js +2 -0
  815. package/dist/rules/write/spec.js.map +1 -0
  816. package/dist/sandbox/admin-compat.d.ts +20 -0
  817. package/dist/sandbox/admin-compat.d.ts.map +1 -0
  818. package/dist/sandbox/admin-compat.js +19 -0
  819. package/dist/sandbox/admin-compat.js.map +1 -0
  820. package/dist/sandbox/admin-firestore/error-translation.d.ts +90 -0
  821. package/dist/sandbox/admin-firestore/error-translation.d.ts.map +1 -0
  822. package/dist/sandbox/admin-firestore/error-translation.js +214 -0
  823. package/dist/sandbox/admin-firestore/error-translation.js.map +1 -0
  824. package/dist/sandbox/admin-firestore/get-admin-firestore.d.ts +44 -0
  825. package/dist/sandbox/admin-firestore/get-admin-firestore.d.ts.map +1 -0
  826. package/dist/sandbox/admin-firestore/get-admin-firestore.js +62 -0
  827. package/dist/sandbox/admin-firestore/get-admin-firestore.js.map +1 -0
  828. package/dist/sandbox/admin-firestore/get-firestore.d.ts +34 -0
  829. package/dist/sandbox/admin-firestore/get-firestore.d.ts.map +1 -0
  830. package/dist/sandbox/admin-firestore/get-firestore.js +71 -0
  831. package/dist/sandbox/admin-firestore/get-firestore.js.map +1 -0
  832. package/dist/sandbox/admin-firestore/index.d.ts +36 -0
  833. package/dist/sandbox/admin-firestore/index.d.ts.map +1 -0
  834. package/dist/sandbox/admin-firestore/index.js +33 -0
  835. package/dist/sandbox/admin-firestore/index.js.map +1 -0
  836. package/dist/sandbox/admin-firestore/listeners.d.ts +46 -0
  837. package/dist/sandbox/admin-firestore/listeners.d.ts.map +1 -0
  838. package/dist/sandbox/admin-firestore/listeners.js +290 -0
  839. package/dist/sandbox/admin-firestore/listeners.js.map +1 -0
  840. package/dist/sandbox/admin-firestore/local-handle.d.ts +23 -0
  841. package/dist/sandbox/admin-firestore/local-handle.d.ts.map +1 -0
  842. package/dist/sandbox/admin-firestore/local-handle.js +74 -0
  843. package/dist/sandbox/admin-firestore/local-handle.js.map +1 -0
  844. package/dist/sandbox/admin-firestore/remote/batch.d.ts +6 -0
  845. package/dist/sandbox/admin-firestore/remote/batch.d.ts.map +1 -0
  846. package/dist/sandbox/admin-firestore/remote/batch.js +38 -0
  847. package/dist/sandbox/admin-firestore/remote/batch.js.map +1 -0
  848. package/dist/sandbox/admin-firestore/remote/channel.d.ts +22 -0
  849. package/dist/sandbox/admin-firestore/remote/channel.d.ts.map +1 -0
  850. package/dist/sandbox/admin-firestore/remote/channel.js +27 -0
  851. package/dist/sandbox/admin-firestore/remote/channel.js.map +1 -0
  852. package/dist/sandbox/admin-firestore/remote/doc-ref.d.ts +10 -0
  853. package/dist/sandbox/admin-firestore/remote/doc-ref.d.ts.map +1 -0
  854. package/dist/sandbox/admin-firestore/remote/doc-ref.js +88 -0
  855. package/dist/sandbox/admin-firestore/remote/doc-ref.js.map +1 -0
  856. package/dist/sandbox/admin-firestore/remote/errors.d.ts +17 -0
  857. package/dist/sandbox/admin-firestore/remote/errors.d.ts.map +1 -0
  858. package/dist/sandbox/admin-firestore/remote/errors.js +32 -0
  859. package/dist/sandbox/admin-firestore/remote/errors.js.map +1 -0
  860. package/dist/sandbox/admin-firestore/remote/listeners.d.ts +43 -0
  861. package/dist/sandbox/admin-firestore/remote/listeners.d.ts.map +1 -0
  862. package/dist/sandbox/admin-firestore/remote/listeners.js +89 -0
  863. package/dist/sandbox/admin-firestore/remote/listeners.js.map +1 -0
  864. package/dist/sandbox/admin-firestore/remote/query.d.ts +47 -0
  865. package/dist/sandbox/admin-firestore/remote/query.d.ts.map +1 -0
  866. package/dist/sandbox/admin-firestore/remote/query.js +186 -0
  867. package/dist/sandbox/admin-firestore/remote/query.js.map +1 -0
  868. package/dist/sandbox/admin-firestore/remote/remote-firestore.d.ts +55 -0
  869. package/dist/sandbox/admin-firestore/remote/remote-firestore.d.ts.map +1 -0
  870. package/dist/sandbox/admin-firestore/remote/remote-firestore.js +111 -0
  871. package/dist/sandbox/admin-firestore/remote/remote-firestore.js.map +1 -0
  872. package/dist/sandbox/admin-firestore/remote/snapshots.d.ts +10 -0
  873. package/dist/sandbox/admin-firestore/remote/snapshots.d.ts.map +1 -0
  874. package/dist/sandbox/admin-firestore/remote/snapshots.js +37 -0
  875. package/dist/sandbox/admin-firestore/remote/snapshots.js.map +1 -0
  876. package/dist/sandbox/admin-firestore/remote/transaction.d.ts +19 -0
  877. package/dist/sandbox/admin-firestore/remote/transaction.d.ts.map +1 -0
  878. package/dist/sandbox/admin-firestore/remote/transaction.js +105 -0
  879. package/dist/sandbox/admin-firestore/remote/transaction.js.map +1 -0
  880. package/dist/sandbox/admin-firestore/remote/value-codec.d.ts +52 -0
  881. package/dist/sandbox/admin-firestore/remote/value-codec.d.ts.map +1 -0
  882. package/dist/sandbox/admin-firestore/remote/value-codec.js +120 -0
  883. package/dist/sandbox/admin-firestore/remote/value-codec.js.map +1 -0
  884. package/dist/sandbox/admin-firestore/remote/wire-types.d.ts +111 -0
  885. package/dist/sandbox/admin-firestore/remote/wire-types.d.ts.map +1 -0
  886. package/dist/sandbox/admin-firestore/remote/wire-types.js +8 -0
  887. package/dist/sandbox/admin-firestore/remote/wire-types.js.map +1 -0
  888. package/dist/sandbox/admin-firestore/types.d.ts +59 -0
  889. package/dist/sandbox/admin-firestore/types.d.ts.map +1 -0
  890. package/dist/sandbox/admin-firestore/types.js +6 -0
  891. package/dist/sandbox/admin-firestore/types.js.map +1 -0
  892. package/dist/sandbox/branches/index.d.ts +141 -0
  893. package/dist/sandbox/branches/index.d.ts.map +1 -0
  894. package/dist/sandbox/branches/index.js +327 -0
  895. package/dist/sandbox/branches/index.js.map +1 -0
  896. package/dist/sandbox/firestore/admin-compat/batch.d.ts +34 -0
  897. package/dist/sandbox/firestore/admin-compat/batch.d.ts.map +1 -0
  898. package/dist/sandbox/firestore/admin-compat/batch.js +73 -0
  899. package/dist/sandbox/firestore/admin-compat/batch.js.map +1 -0
  900. package/dist/sandbox/firestore/admin-compat/doc-ref.d.ts +38 -0
  901. package/dist/sandbox/firestore/admin-compat/doc-ref.d.ts.map +1 -0
  902. package/dist/sandbox/firestore/admin-compat/doc-ref.js +154 -0
  903. package/dist/sandbox/firestore/admin-compat/doc-ref.js.map +1 -0
  904. package/dist/sandbox/firestore/admin-compat/firestore.d.ts +47 -0
  905. package/dist/sandbox/firestore/admin-compat/firestore.d.ts.map +1 -0
  906. package/dist/sandbox/firestore/admin-compat/firestore.js +117 -0
  907. package/dist/sandbox/firestore/admin-compat/firestore.js.map +1 -0
  908. package/dist/sandbox/firestore/admin-compat/index.d.ts +49 -0
  909. package/dist/sandbox/firestore/admin-compat/index.d.ts.map +1 -0
  910. package/dist/sandbox/firestore/admin-compat/index.js +27 -0
  911. package/dist/sandbox/firestore/admin-compat/index.js.map +1 -0
  912. package/dist/sandbox/firestore/admin-compat/paths.d.ts +37 -0
  913. package/dist/sandbox/firestore/admin-compat/paths.d.ts.map +1 -0
  914. package/dist/sandbox/firestore/admin-compat/paths.js +49 -0
  915. package/dist/sandbox/firestore/admin-compat/paths.js.map +1 -0
  916. package/dist/sandbox/firestore/admin-compat/query.d.ts +261 -0
  917. package/dist/sandbox/firestore/admin-compat/query.d.ts.map +1 -0
  918. package/dist/sandbox/firestore/admin-compat/query.js +758 -0
  919. package/dist/sandbox/firestore/admin-compat/query.js.map +1 -0
  920. package/dist/sandbox/firestore/admin-compat/read-translation.d.ts +8 -0
  921. package/dist/sandbox/firestore/admin-compat/read-translation.d.ts.map +1 -0
  922. package/dist/sandbox/firestore/admin-compat/read-translation.js +59 -0
  923. package/dist/sandbox/firestore/admin-compat/read-translation.js.map +1 -0
  924. package/dist/sandbox/firestore/admin-compat/snapshots.d.ts +39 -0
  925. package/dist/sandbox/firestore/admin-compat/snapshots.d.ts.map +1 -0
  926. package/dist/sandbox/firestore/admin-compat/snapshots.js +50 -0
  927. package/dist/sandbox/firestore/admin-compat/snapshots.js.map +1 -0
  928. package/dist/sandbox/firestore/admin-compat/transaction.d.ts +35 -0
  929. package/dist/sandbox/firestore/admin-compat/transaction.d.ts.map +1 -0
  930. package/dist/sandbox/firestore/admin-compat/transaction.js +88 -0
  931. package/dist/sandbox/firestore/admin-compat/transaction.js.map +1 -0
  932. package/dist/sandbox/firestore/admin-compat/types.d.ts +297 -0
  933. package/dist/sandbox/firestore/admin-compat/types.d.ts.map +1 -0
  934. package/dist/sandbox/firestore/admin-compat/types.js +127 -0
  935. package/dist/sandbox/firestore/admin-compat/types.js.map +1 -0
  936. package/dist/sandbox/firestore/admin-compat/value-order.d.ts +49 -0
  937. package/dist/sandbox/firestore/admin-compat/value-order.d.ts.map +1 -0
  938. package/dist/sandbox/firestore/admin-compat/value-order.js +172 -0
  939. package/dist/sandbox/firestore/admin-compat/value-order.js.map +1 -0
  940. package/dist/sandbox/firestore/auto-id.d.ts +26 -0
  941. package/dist/sandbox/firestore/auto-id.d.ts.map +1 -0
  942. package/dist/sandbox/firestore/auto-id.js +36 -0
  943. package/dist/sandbox/firestore/auto-id.js.map +1 -0
  944. package/dist/sandbox/firestore/converters/bytes-geopoint.d.ts +48 -0
  945. package/dist/sandbox/firestore/converters/bytes-geopoint.d.ts.map +1 -0
  946. package/dist/sandbox/firestore/converters/bytes-geopoint.js +85 -0
  947. package/dist/sandbox/firestore/converters/bytes-geopoint.js.map +1 -0
  948. package/dist/sandbox/firestore/converters/fieldvalue.d.ts +69 -0
  949. package/dist/sandbox/firestore/converters/fieldvalue.d.ts.map +1 -0
  950. package/dist/sandbox/firestore/converters/fieldvalue.js +166 -0
  951. package/dist/sandbox/firestore/converters/fieldvalue.js.map +1 -0
  952. package/dist/sandbox/firestore/converters/reference.d.ts +31 -0
  953. package/dist/sandbox/firestore/converters/reference.d.ts.map +1 -0
  954. package/dist/sandbox/firestore/converters/reference.js +51 -0
  955. package/dist/sandbox/firestore/converters/reference.js.map +1 -0
  956. package/dist/sandbox/firestore/converters/timestamp.d.ts +32 -0
  957. package/dist/sandbox/firestore/converters/timestamp.d.ts.map +1 -0
  958. package/dist/sandbox/firestore/converters/timestamp.js +63 -0
  959. package/dist/sandbox/firestore/converters/timestamp.js.map +1 -0
  960. package/dist/sandbox/firestore/converters/user-timestamp.d.ts +46 -0
  961. package/dist/sandbox/firestore/converters/user-timestamp.d.ts.map +1 -0
  962. package/dist/sandbox/firestore/converters/user-timestamp.js +65 -0
  963. package/dist/sandbox/firestore/converters/user-timestamp.js.map +1 -0
  964. package/dist/sandbox/firestore/converters/vector.d.ts +24 -0
  965. package/dist/sandbox/firestore/converters/vector.d.ts.map +1 -0
  966. package/dist/sandbox/firestore/converters/vector.js +53 -0
  967. package/dist/sandbox/firestore/converters/vector.js.map +1 -0
  968. package/dist/sandbox/firestore/errors.d.ts +82 -0
  969. package/dist/sandbox/firestore/errors.d.ts.map +1 -0
  970. package/dist/sandbox/firestore/errors.js +54 -0
  971. package/dist/sandbox/firestore/errors.js.map +1 -0
  972. package/dist/sandbox/firestore/event-log.d.ts +99 -0
  973. package/dist/sandbox/firestore/event-log.d.ts.map +1 -0
  974. package/dist/sandbox/firestore/event-log.js +67 -0
  975. package/dist/sandbox/firestore/event-log.js.map +1 -0
  976. package/dist/sandbox/firestore/field-merge.d.ts +64 -0
  977. package/dist/sandbox/firestore/field-merge.d.ts.map +1 -0
  978. package/dist/sandbox/firestore/field-merge.js +221 -0
  979. package/dist/sandbox/firestore/field-merge.js.map +1 -0
  980. package/dist/sandbox/firestore/list-query-proof.d.ts +77 -0
  981. package/dist/sandbox/firestore/list-query-proof.d.ts.map +1 -0
  982. package/dist/sandbox/firestore/list-query-proof.js +170 -0
  983. package/dist/sandbox/firestore/list-query-proof.js.map +1 -0
  984. package/dist/sandbox/firestore/local-environment.d.ts +825 -0
  985. package/dist/sandbox/firestore/local-environment.d.ts.map +1 -0
  986. package/dist/sandbox/firestore/local-environment.js +3129 -0
  987. package/dist/sandbox/firestore/local-environment.js.map +1 -0
  988. package/dist/sandbox/firestore/local-state.d.ts +196 -0
  989. package/dist/sandbox/firestore/local-state.d.ts.map +1 -0
  990. package/dist/sandbox/firestore/local-state.js +413 -0
  991. package/dist/sandbox/firestore/local-state.js.map +1 -0
  992. package/dist/sandbox/firestore/overlay-backing.d.ts +44 -0
  993. package/dist/sandbox/firestore/overlay-backing.d.ts.map +1 -0
  994. package/dist/sandbox/firestore/overlay-backing.js +82 -0
  995. package/dist/sandbox/firestore/overlay-backing.js.map +1 -0
  996. package/dist/sandbox/firestore/sentinel-capture.d.ts +30 -0
  997. package/dist/sandbox/firestore/sentinel-capture.d.ts.map +1 -0
  998. package/dist/sandbox/firestore/sentinel-capture.js +61 -0
  999. package/dist/sandbox/firestore/sentinel-capture.js.map +1 -0
  1000. package/dist/sandbox/firestore/snapshot-listeners.d.ts +290 -0
  1001. package/dist/sandbox/firestore/snapshot-listeners.d.ts.map +1 -0
  1002. package/dist/sandbox/firestore/snapshot-listeners.js +194 -0
  1003. package/dist/sandbox/firestore/snapshot-listeners.js.map +1 -0
  1004. package/dist/sandbox/firestore/topk.d.ts +12 -0
  1005. package/dist/sandbox/firestore/topk.d.ts.map +1 -0
  1006. package/dist/sandbox/firestore/topk.js +42 -0
  1007. package/dist/sandbox/firestore/topk.js.map +1 -0
  1008. package/dist/sandbox/firestore/transaction-merge.d.ts +55 -0
  1009. package/dist/sandbox/firestore/transaction-merge.d.ts.map +1 -0
  1010. package/dist/sandbox/firestore/transaction-merge.js +107 -0
  1011. package/dist/sandbox/firestore/transaction-merge.js.map +1 -0
  1012. package/dist/sandbox/firestore/transaction-types.d.ts +155 -0
  1013. package/dist/sandbox/firestore/transaction-types.d.ts.map +1 -0
  1014. package/dist/sandbox/firestore/transaction-types.js +10 -0
  1015. package/dist/sandbox/firestore/transaction-types.js.map +1 -0
  1016. package/dist/sandbox/firestore/transaction.d.ts +79 -0
  1017. package/dist/sandbox/firestore/transaction.d.ts.map +1 -0
  1018. package/dist/sandbox/firestore/transaction.js +95 -0
  1019. package/dist/sandbox/firestore/transaction.js.map +1 -0
  1020. package/dist/sandbox/firestore/value-equality.d.ts +2 -0
  1021. package/dist/sandbox/firestore/value-equality.d.ts.map +1 -0
  1022. package/dist/sandbox/firestore/value-equality.js +35 -0
  1023. package/dist/sandbox/firestore/value-equality.js.map +1 -0
  1024. package/dist/sandbox/firestore/value-resolver.d.ts +172 -0
  1025. package/dist/sandbox/firestore/value-resolver.d.ts.map +1 -0
  1026. package/dist/sandbox/firestore/value-resolver.js +221 -0
  1027. package/dist/sandbox/firestore/value-resolver.js.map +1 -0
  1028. package/dist/sandbox/firestore/wire-encoder.d.ts +14 -0
  1029. package/dist/sandbox/firestore/wire-encoder.d.ts.map +1 -0
  1030. package/dist/sandbox/firestore/wire-encoder.js +130 -0
  1031. package/dist/sandbox/firestore/wire-encoder.js.map +1 -0
  1032. package/dist/sandbox/index.d.ts +53 -0
  1033. package/dist/sandbox/index.d.ts.map +1 -0
  1034. package/dist/sandbox/index.js +65 -0
  1035. package/dist/sandbox/index.js.map +1 -0
  1036. package/dist/sandbox/internal/client-app.d.ts +29 -0
  1037. package/dist/sandbox/internal/client-app.d.ts.map +1 -0
  1038. package/dist/sandbox/internal/client-app.js +18 -0
  1039. package/dist/sandbox/internal/client-app.js.map +1 -0
  1040. package/dist/sandbox/internal/firebase-error.d.ts +14 -0
  1041. package/dist/sandbox/internal/firebase-error.d.ts.map +1 -0
  1042. package/dist/sandbox/internal/firebase-error.js +22 -0
  1043. package/dist/sandbox/internal/firebase-error.js.map +1 -0
  1044. package/dist/sandbox/internal/index.d.ts +39 -0
  1045. package/dist/sandbox/internal/index.d.ts.map +1 -0
  1046. package/dist/sandbox/internal/index.js +75 -0
  1047. package/dist/sandbox/internal/index.js.map +1 -0
  1048. package/dist/sandbox/internal/local-brand.d.ts +3 -0
  1049. package/dist/sandbox/internal/local-brand.d.ts.map +1 -0
  1050. package/dist/sandbox/internal/local-brand.js +3 -0
  1051. package/dist/sandbox/internal/local-brand.js.map +1 -0
  1052. package/dist/sandbox/internal/provenance.d.ts +16 -0
  1053. package/dist/sandbox/internal/provenance.d.ts.map +1 -0
  1054. package/dist/sandbox/internal/provenance.js +139 -0
  1055. package/dist/sandbox/internal/provenance.js.map +1 -0
  1056. package/dist/sandbox/internal/sandbox-impl.d.ts +328 -0
  1057. package/dist/sandbox/internal/sandbox-impl.d.ts.map +1 -0
  1058. package/dist/sandbox/internal/sandbox-impl.js +695 -0
  1059. package/dist/sandbox/internal/sandbox-impl.js.map +1 -0
  1060. package/dist/sandbox/operation-record.d.ts +48 -0
  1061. package/dist/sandbox/operation-record.d.ts.map +1 -0
  1062. package/dist/sandbox/operation-record.js +143 -0
  1063. package/dist/sandbox/operation-record.js.map +1 -0
  1064. package/dist/sandbox/persistence/backends.d.ts +37 -0
  1065. package/dist/sandbox/persistence/backends.d.ts.map +1 -0
  1066. package/dist/sandbox/persistence/backends.js +202 -0
  1067. package/dist/sandbox/persistence/backends.js.map +1 -0
  1068. package/dist/sandbox/persistence/chunk-format.d.ts +58 -0
  1069. package/dist/sandbox/persistence/chunk-format.d.ts.map +1 -0
  1070. package/dist/sandbox/persistence/chunk-format.js +163 -0
  1071. package/dist/sandbox/persistence/chunk-format.js.map +1 -0
  1072. package/dist/sandbox/persistence/controller.d.ts +39 -0
  1073. package/dist/sandbox/persistence/controller.d.ts.map +1 -0
  1074. package/dist/sandbox/persistence/controller.js +505 -0
  1075. package/dist/sandbox/persistence/controller.js.map +1 -0
  1076. package/dist/sandbox/persistence/index.d.ts +13 -0
  1077. package/dist/sandbox/persistence/index.d.ts.map +1 -0
  1078. package/dist/sandbox/persistence/index.js +5 -0
  1079. package/dist/sandbox/persistence/index.js.map +1 -0
  1080. package/dist/sandbox/persistence/serialize.d.ts +53 -0
  1081. package/dist/sandbox/persistence/serialize.d.ts.map +1 -0
  1082. package/dist/sandbox/persistence/serialize.js +98 -0
  1083. package/dist/sandbox/persistence/serialize.js.map +1 -0
  1084. package/dist/sandbox/persistence/types.d.ts +118 -0
  1085. package/dist/sandbox/persistence/types.d.ts.map +1 -0
  1086. package/dist/sandbox/persistence/types.js +15 -0
  1087. package/dist/sandbox/persistence/types.js.map +1 -0
  1088. package/dist/sandbox/remote.d.ts +118 -0
  1089. package/dist/sandbox/remote.d.ts.map +1 -0
  1090. package/dist/sandbox/remote.js +60 -0
  1091. package/dist/sandbox/remote.js.map +1 -0
  1092. package/dist/sandbox/replay/index.d.ts +106 -0
  1093. package/dist/sandbox/replay/index.d.ts.map +1 -0
  1094. package/dist/sandbox/replay/index.js +246 -0
  1095. package/dist/sandbox/replay/index.js.map +1 -0
  1096. package/dist/sandbox/sandbox-context.d.ts +48 -0
  1097. package/dist/sandbox/sandbox-context.d.ts.map +1 -0
  1098. package/dist/sandbox/sandbox-context.js +97 -0
  1099. package/dist/sandbox/sandbox-context.js.map +1 -0
  1100. package/dist/sandbox/tab-sync/index.d.ts +120 -0
  1101. package/dist/sandbox/tab-sync/index.d.ts.map +1 -0
  1102. package/dist/sandbox/tab-sync/index.js +273 -0
  1103. package/dist/sandbox/tab-sync/index.js.map +1 -0
  1104. package/dist/sandbox/types/auth-state.d.ts +23 -0
  1105. package/dist/sandbox/types/auth-state.d.ts.map +1 -0
  1106. package/dist/sandbox/types/auth-state.js +8 -0
  1107. package/dist/sandbox/types/auth-state.js.map +1 -0
  1108. package/dist/sandbox/types/context.d.ts +33 -0
  1109. package/dist/sandbox/types/context.d.ts.map +1 -0
  1110. package/dist/sandbox/types/context.js +5 -0
  1111. package/dist/sandbox/types/context.js.map +1 -0
  1112. package/dist/sandbox/types/errors.d.ts +109 -0
  1113. package/dist/sandbox/types/errors.d.ts.map +1 -0
  1114. package/dist/sandbox/types/errors.js +41 -0
  1115. package/dist/sandbox/types/errors.js.map +1 -0
  1116. package/dist/sandbox/types/events.d.ts +577 -0
  1117. package/dist/sandbox/types/events.d.ts.map +1 -0
  1118. package/dist/sandbox/types/events.js +7 -0
  1119. package/dist/sandbox/types/events.js.map +1 -0
  1120. package/dist/sandbox/types/index.d.ts +24 -0
  1121. package/dist/sandbox/types/index.d.ts.map +1 -0
  1122. package/dist/sandbox/types/index.js +17 -0
  1123. package/dist/sandbox/types/index.js.map +1 -0
  1124. package/dist/sandbox/types/operation.d.ts +60 -0
  1125. package/dist/sandbox/types/operation.d.ts.map +1 -0
  1126. package/dist/sandbox/types/operation.js +3 -0
  1127. package/dist/sandbox/types/operation.js.map +1 -0
  1128. package/dist/sandbox/types/persistence.d.ts +130 -0
  1129. package/dist/sandbox/types/persistence.d.ts.map +1 -0
  1130. package/dist/sandbox/types/persistence.js +7 -0
  1131. package/dist/sandbox/types/persistence.js.map +1 -0
  1132. package/dist/sandbox/types/service.d.ts +357 -0
  1133. package/dist/sandbox/types/service.d.ts.map +1 -0
  1134. package/dist/sandbox/types/service.js +6 -0
  1135. package/dist/sandbox/types/service.js.map +1 -0
  1136. package/dist/storage/admin/api.d.ts +206 -0
  1137. package/dist/storage/admin/api.d.ts.map +1 -0
  1138. package/dist/storage/admin/api.js +349 -0
  1139. package/dist/storage/admin/api.js.map +1 -0
  1140. package/dist/storage/admin/handler.d.ts +28 -0
  1141. package/dist/storage/admin/handler.d.ts.map +1 -0
  1142. package/dist/storage/admin/handler.js +82 -0
  1143. package/dist/storage/admin/handler.js.map +1 -0
  1144. package/dist/storage/admin/spec.d.ts +64 -0
  1145. package/dist/storage/admin/spec.d.ts.map +1 -0
  1146. package/dist/storage/admin/spec.js +8 -0
  1147. package/dist/storage/admin/spec.js.map +1 -0
  1148. package/dist/storage/admin/tools.d.ts +22 -0
  1149. package/dist/storage/admin/tools.d.ts.map +1 -0
  1150. package/dist/storage/admin/tools.js +90 -0
  1151. package/dist/storage/admin/tools.js.map +1 -0
  1152. package/dist/storage/download.d.ts +41 -0
  1153. package/dist/storage/download.d.ts.map +1 -0
  1154. package/dist/storage/download.js +137 -0
  1155. package/dist/storage/download.js.map +1 -0
  1156. package/dist/storage/enforce.d.ts +5 -0
  1157. package/dist/storage/enforce.d.ts.map +1 -0
  1158. package/dist/storage/enforce.js +147 -0
  1159. package/dist/storage/enforce.js.map +1 -0
  1160. package/dist/storage/errors.d.ts +44 -0
  1161. package/dist/storage/errors.d.ts.map +1 -0
  1162. package/dist/storage/errors.js +64 -0
  1163. package/dist/storage/errors.js.map +1 -0
  1164. package/dist/storage/index.d.ts +45 -0
  1165. package/dist/storage/index.d.ts.map +1 -0
  1166. package/dist/storage/index.js +39 -0
  1167. package/dist/storage/index.js.map +1 -0
  1168. package/dist/storage/instances.d.ts +9 -0
  1169. package/dist/storage/instances.d.ts.map +1 -0
  1170. package/dist/storage/instances.js +24 -0
  1171. package/dist/storage/instances.js.map +1 -0
  1172. package/dist/storage/internal.d.ts +18 -0
  1173. package/dist/storage/internal.d.ts.map +1 -0
  1174. package/dist/storage/internal.js +18 -0
  1175. package/dist/storage/internal.js.map +1 -0
  1176. package/dist/storage/list.d.ts +42 -0
  1177. package/dist/storage/list.d.ts.map +1 -0
  1178. package/dist/storage/list.js +83 -0
  1179. package/dist/storage/list.js.map +1 -0
  1180. package/dist/storage/metadata.d.ts +92 -0
  1181. package/dist/storage/metadata.d.ts.map +1 -0
  1182. package/dist/storage/metadata.js +164 -0
  1183. package/dist/storage/metadata.js.map +1 -0
  1184. package/dist/storage/persistence.d.ts +134 -0
  1185. package/dist/storage/persistence.d.ts.map +1 -0
  1186. package/dist/storage/persistence.js +132 -0
  1187. package/dist/storage/persistence.js.map +1 -0
  1188. package/dist/storage/reference.d.ts +57 -0
  1189. package/dist/storage/reference.d.ts.map +1 -0
  1190. package/dist/storage/reference.js +105 -0
  1191. package/dist/storage/reference.js.map +1 -0
  1192. package/dist/storage/rules.d.ts +339 -0
  1193. package/dist/storage/rules.d.ts.map +1 -0
  1194. package/dist/storage/rules.js +1334 -0
  1195. package/dist/storage/rules.js.map +1 -0
  1196. package/dist/storage/service.d.ts +122 -0
  1197. package/dist/storage/service.d.ts.map +1 -0
  1198. package/dist/storage/service.js +247 -0
  1199. package/dist/storage/service.js.map +1 -0
  1200. package/dist/storage/upload.d.ts +50 -0
  1201. package/dist/storage/upload.d.ts.map +1 -0
  1202. package/dist/storage/upload.js +246 -0
  1203. package/dist/storage/upload.js.map +1 -0
  1204. package/package.json +156 -3
@@ -0,0 +1,3129 @@
1
+ /**
2
+ * LocalEnvironment — stateful Firestore sandbox.
3
+ *
4
+ * Wraps LocalState + SimulateFirestoreRulesHandler + EventLog into a
5
+ * complete local development environment. Agents can seed data, deploy
6
+ * rules, execute operations, and undo — all without touching production.
7
+ */
8
+ import { LocalState, } from './local-state.js';
9
+ import { OverlayBacking } from './overlay-backing.js';
10
+ import { EventLog } from './event-log.js';
11
+ import { SimulateFirestoreRulesHandler, renderLegacyDebugMessages, projectEvaluatedRule } from 'pyric/rules/internal';
12
+ import { lintFirestoreRules, parseToAST } from 'pyric/rules/internal';
13
+ // RULES-B11 — query-proof gate for list reads ("rules are not filters").
14
+ import { proveListQuery } from './list-query-proof.js';
15
+ import { resolveValueTree, partitionDeletes, registerDefaultConverters, } from './value-resolver.js';
16
+ import { assertNoNestedDeleteField } from './field-merge.js';
17
+ import { Timestamp } from 'pyric/rules/internal';
18
+ import { makeError } from './errors.js';
19
+ import { generateAutoId } from './auto-id.js';
20
+ import { walkForSentinels } from './sentinel-capture.js';
21
+ import { TransactionContext } from './transaction.js';
22
+ import { mergeQueuedWrites } from './transaction-merge.js';
23
+ import { buildDocumentSnapshot, buildQuerySnapshot, SANDBOX_METADATA, SANDBOX_METADATA_PENDING, } from './snapshot-listeners.js';
24
+ // Register every shipped converter exactly once on module load. Idempotent
25
+ // per-converter, so re-imports are safe. Item 0 ships an empty registry;
26
+ // Items 1+ add converters here.
27
+ registerDefaultConverters();
28
+ /**
29
+ * Wallclock-aligned ISO string for `tc.requestTime`. Both `request.time`
30
+ * and any `serverTimestamp()` sentinel in this write must resolve to a
31
+ * field-equal Timestamp; we accomplish that by computing a single
32
+ * Timestamp here and forwarding the millisecond-precise ISO to handler.ts
33
+ * (which parses it back into a Timestamp via `Timestamp.fromIsoString`,
34
+ * lossless on the millisecond grid).
35
+ */
36
+ function isoFromTimestamp(ts) {
37
+ return new Date(ts.toMillis()).toISOString();
38
+ }
39
+ /**
40
+ * Thrown by `LocalEnvironment.execute` / `.batch` when the simulator
41
+ * abstained on a rule (state: UNSUPPORTED). The agent's rule may be
42
+ * correct — the simulator just doesn't implement the feature it uses.
43
+ *
44
+ * Returning `allowed: false` here would silently re-create the
45
+ * misleading-DENY pattern that Item 0.A is designed to prevent (the
46
+ * agent can't tell sim-gap apart from real rule bug). Throwing forces
47
+ * the test to fail loudly with an actionable message pointing at the
48
+ * production Test API as the workaround.
49
+ */
50
+ export class SimulatorUnsupportedError extends Error {
51
+ method;
52
+ path;
53
+ debugMessages;
54
+ constructor(message, method, path, debugMessages) {
55
+ super(message);
56
+ this.method = method;
57
+ this.path = path;
58
+ this.debugMessages = debugMessages;
59
+ this.name = 'SimulatorUnsupportedError';
60
+ }
61
+ }
62
+ function unsupportedMessage(method, path, debugMessages) {
63
+ const reasons = debugMessages
64
+ .filter(m => m.includes('unsupported:'))
65
+ .map(m => m.replace(/^.*unsupported:\s*/, ''))
66
+ .join('; ');
67
+ const reasonClause = reasons ? ` Reason(s): ${reasons}.` : '';
68
+ return (`Simulator cannot decide ${method} on ${path} — the rule uses a feature ` +
69
+ `the local simulator does not yet implement.${reasonClause} ` +
70
+ `Verify this rule against production using TestFirestoreRulesHandler, ` +
71
+ `or file a sim-gap entry in REBUILD_PLAN.md.`);
72
+ }
73
+ /**
74
+ * Compare two doc payloads for snapshot-suppression purposes. `null`
75
+ * means the doc is absent. Equality test uses `JSON.stringify` to
76
+ * mirror `computeChanges` in `snapshot-listeners.ts` — keeps the two
77
+ * change-detection paths consistent and good enough for sandbox data
78
+ * (all `DocumentData` is JSON-serialisable post-sentinel-resolution).
79
+ */
80
+ function docDataEqual(a, b) {
81
+ if (a === null && b === null)
82
+ return true;
83
+ if (a === null || b === null)
84
+ return false;
85
+ return JSON.stringify(a) === JSON.stringify(b);
86
+ }
87
+ /**
88
+ * True if any path in `paths` is a direct child document of
89
+ * `collection`. Used as a cheap pre-filter for query-listener
90
+ * notifications: we only re-read the collection when something it
91
+ * could plausibly contain was just touched. Slice 6 may revisit when
92
+ * subcollection-aware queries land — current shape keeps the filter
93
+ * conservative (no false negatives) at the cost of an occasional
94
+ * false positive that the change-set diff then suppresses.
95
+ */
96
+ function anyPathInCollection(paths, collection) {
97
+ const prefix = `${collection}/`;
98
+ for (const p of paths) {
99
+ if (!p.startsWith(prefix))
100
+ continue;
101
+ const remaining = p.slice(prefix.length);
102
+ if (remaining.length > 0 && !remaining.includes('/'))
103
+ return true;
104
+ }
105
+ return false;
106
+ }
107
+ let _requestEventSeq = 0;
108
+ function nextRequestEventId() {
109
+ // Monotonic + random tail. Stable for the lifetime of the JS process;
110
+ // doesn't try to be cryptographically unique because consumers use it
111
+ // as a React list key, not a security token.
112
+ _requestEventSeq = (_requestEventSeq + 1) >>> 0;
113
+ return `req-${_requestEventSeq.toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
114
+ }
115
+ /**
116
+ * Parse `Rule #N (ops...) → ALLOW/deny` lines out of the simulator's
117
+ * debug messages. The simulator emits one such line per evaluated rule
118
+ * in the matched match block (see `evaluateRules` in
119
+ * `pyric/rules/handler.ts`). For allowed outcomes
120
+ * the last `→ ALLOW` rule wins; for denials we surface the first rule
121
+ * that even tried to match this op-set.
122
+ */
123
+ function parseMatchedRule(debugMessages, result) {
124
+ const wantAllow = result === 'allow';
125
+ let last;
126
+ for (const msg of debugMessages) {
127
+ const m = /^Rule #(\d+) \(([^)]+)\) → (ALLOW|deny|unsupported)/.exec(msg);
128
+ if (!m)
129
+ continue;
130
+ const candidate = {
131
+ ruleIndex: Number(m[1]),
132
+ operations: m[2].split(',').map((s) => s.trim()),
133
+ };
134
+ if (wantAllow && m[3] === 'ALLOW')
135
+ return candidate;
136
+ last = candidate;
137
+ }
138
+ return last;
139
+ }
140
+ function buildRequestEvent(input) {
141
+ const out = {
142
+ kind: 'request',
143
+ id: nextRequestEventId(),
144
+ at: input.at,
145
+ evalMs: input.evalMs,
146
+ method: input.method,
147
+ path: input.path,
148
+ auth: input.auth ? { uid: input.auth.uid, ...(input.auth.token ? { token: input.auth.token } : {}) } : null,
149
+ result: input.result,
150
+ reasons: input.debugMessages,
151
+ origin: input.origin,
152
+ };
153
+ if (input.resourceData !== undefined) {
154
+ out.request = { resourceData: input.resourceData };
155
+ }
156
+ if (input.resourceBefore !== undefined) {
157
+ out.resourceBefore = input.resourceBefore;
158
+ }
159
+ if (input.resourceAfter !== undefined) {
160
+ out.resourceAfter = input.resourceAfter;
161
+ }
162
+ const matched = parseMatchedRule(input.debugMessages, input.result);
163
+ if (matched)
164
+ out.matchedRule = matched;
165
+ // The structured deciding-rule projection (verdict + line + expression
166
+ // trace) rides alongside the flat `reasons` on rules-evaluated results —
167
+ // the allowing rule on an allow, the denying rule on a deny. Unsupported
168
+ // results have no deciding rule (the simulator abstained).
169
+ if (input.result !== 'unsupported' && input.evaluatedRule) {
170
+ out.evaluatedRule = input.evaluatedRule;
171
+ }
172
+ if (input.groupId !== undefined) {
173
+ out.groupId = input.groupId;
174
+ // Disambiguates 'origin' for consumers that want the group kind
175
+ // without re-parsing the prefix.
176
+ if (input.origin === 'batch')
177
+ out.groupKind = 'batch';
178
+ else if (input.origin === 'transaction')
179
+ out.groupKind = 'transaction';
180
+ }
181
+ if (input.triggeredBy !== undefined)
182
+ out.triggeredBy = input.triggeredBy;
183
+ if (input.detail !== undefined)
184
+ out.detail = input.detail;
185
+ if (input.provenance !== undefined)
186
+ Object.assign(out, input.provenance);
187
+ return out;
188
+ }
189
+ function listQueryFromStructured(structured) {
190
+ if (structured.limit == null && structured.offset == null && structured.orderBy == null) {
191
+ return undefined;
192
+ }
193
+ return {
194
+ ...(structured.limit != null ? { limit: structured.limit } : {}),
195
+ ...(structured.offset != null ? { offset: structured.offset } : {}),
196
+ ...(structured.orderBy != null ? { orderBy: structured.orderBy } : {}),
197
+ };
198
+ }
199
+ /**
200
+ * A synthetic all-ALLOW {@link TestResult} for the admin-bypass path
201
+ * (Pyric Studio Gap #2). Returned by {@link LocalEnvironment.runSimulate}
202
+ * instead of calling the rules engine when an op carries `bypassRules`.
203
+ * `state: 'PASSED'` + `decision: 'ALLOW'` is exactly the shape every
204
+ * write/read site downstream of a `simulate()` call already branches on,
205
+ * so the bypass reuses the entire existing execute/batch/transaction
206
+ * apply + emit machinery unchanged — only the rule decision is forced.
207
+ * The `notes` line makes the bypass legible in the `debugMessages` trail
208
+ * that surfaces on the traffic log.
209
+ */
210
+ function adminBypassResult(description = '') {
211
+ return {
212
+ description,
213
+ expectation: 'ALLOW',
214
+ state: 'PASSED',
215
+ decision: 'ALLOW',
216
+ trace: [],
217
+ notes: ['admin lens — rules bypassed (Studio Gap #2)'],
218
+ };
219
+ }
220
+ /**
221
+ * Default ruleset for a freshly-constructed sandbox. Open read+write
222
+ * on every path — the right behavior for the quickstart / local dev
223
+ * loop where rules haven't been considered yet. Callers tighten this
224
+ * via `setRules(...)`; production code never relies on the default.
225
+ */
226
+ const DEFAULT_OPEN_RULES = `rules_version = '2';
227
+ service cloud.firestore {
228
+ match /databases/{database}/documents {
229
+ match /{document=**} {
230
+ allow read, write: if true;
231
+ }
232
+ }
233
+ }
234
+ `;
235
+ export class LocalEnvironment {
236
+ state;
237
+ eventLog;
238
+ simulator;
239
+ rulesSource;
240
+ seedSnapshot;
241
+ /**
242
+ * Subscribers notified after every `permission-denied` is constructed,
243
+ * regardless of whether downstream user code catches the resulting
244
+ * throw. Lets host environments (the playground runner, tests) surface
245
+ * denials with full eval context even when test code wraps the call
246
+ * in try/catch — the catch otherwise hides everything past `e.code`.
247
+ */
248
+ denialListeners = new Set();
249
+ /**
250
+ * Subscribers notified for every evaluated op (issue #307). Each
251
+ * receives a public-shape `RequestEvent`. Re-shape from the internal
252
+ * eval payload happens in {@link emitRequest} so the env's hot path
253
+ * doesn't allocate the event object until we know someone's listening.
254
+ *
255
+ * Listener throws are swallowed (same rationale as `denialListeners`).
256
+ */
257
+ requestListeners = new Set();
258
+ /**
259
+ * Subscribers notified for every COMMITTED write (issue #307). Fires
260
+ * after the keyspace successfully applied the write — denied or
261
+ * rolled-back writes don't emit here (they surface as a request-deny
262
+ * RequestEvent instead). Bridged to `Sandbox.onEvent` consumers via
263
+ * SandboxImpl's attachToEnv.
264
+ */
265
+ writeListeners = new Set();
266
+ /**
267
+ * Subscribers notified for every snapshot DELIVERED to a user
268
+ * `onSnapshot` callback. Fires after the suppress-check in
269
+ * notify*Listener, so this count tracks real callback invocations
270
+ * (in contrast to `requestListeners[origin='listener']`, which used
271
+ * to over-count before the step-5 refactor).
272
+ */
273
+ deliveryListeners = new Set();
274
+ /**
275
+ * Subscribers notified for every listener re-eval that was suppressed
276
+ * before reaching the user callback — Slice 3's no-op suppression
277
+ * surfaces here. Useful for "why didn't my listener fire" debugging.
278
+ */
279
+ suppressedListeners = new Set();
280
+ /**
281
+ * Subscribers notified for listener attach / detach lifecycle. Errored
282
+ * still routes through onSnapshotError (bridged to listener_errored
283
+ * in SandboxImpl) so this channel only carries attach + detach.
284
+ */
285
+ lifecycleListeners = new Set();
286
+ /**
287
+ * The user-origin op that's currently triggering a listener re-eval,
288
+ * if any. Set by the execute / batch / transaction call sites
289
+ * immediately before `notifyListenersForPaths`. Call sites use a
290
+ * **save/restore** pattern — a listener callback may itself issue a
291
+ * write, recursing through execute and setting up its own trigger; we
292
+ * must put the outer trigger back when the nested call returns so the
293
+ * remaining listeners in the outer fan-out still attribute correctly.
294
+ *
295
+ * Listener-origin RequestEvents copy this into `triggeredBy`. Undefined
296
+ * for the initial-fire path and for deployRules re-evaluation.
297
+ */
298
+ currentTrigger;
299
+ /**
300
+ * RULES-B11 — parsed-AST cache for the query-proof gate. The proof
301
+ * needs the matched `list` rule's condition AST on EVERY list read;
302
+ * re-parsing the (unchanging) rules source per read would be O(source)
303
+ * on the listener hot path. Keyed on the exact source string so
304
+ * `deployRules` / `seed` invalidate it for free.
305
+ */
306
+ parsedRulesCache = null;
307
+ /**
308
+ * Subscribers notified when a snapshot listener is marked errored
309
+ * (Slice 7). Mirrors `denialListeners` but fires from the listener
310
+ * dispatch path, not from one-shot operation evaluation. Two-level
311
+ * model per source survey section 9: the listener's own `errorCallback`
312
+ * receives the error AND every env-level subscriber receives it —
313
+ * the playground subscribes here to surface stream errors as toasts
314
+ * the same way it surfaces denials today.
315
+ */
316
+ snapshotErrorListeners = new Set();
317
+ /**
318
+ * Active `onSnapshot` listeners. Slice 1 — registry only; the dispatch
319
+ * path is wired in Slices 2 (initial fire), 3 (change detection), and
320
+ * 5 (transaction/batch deferral). Stored as a flat `Map<id, record>`
321
+ * per the implementation plan; query-canonicalization-based dedup
322
+ * (production's `EventManager` shape) is layered on later when caching
323
+ * actually saves work — see source survey section 2 for the eventual target
324
+ * shape. Each record carries its own target so future slices can scan
325
+ * and group on demand without restructuring the registry first.
326
+ */
327
+ snapshotListeners = new Map();
328
+ nextListenerId = 0;
329
+ /**
330
+ * Deferred listener deliveries — the shared delivery scheduler (items
331
+ * 3 + 5). Production never invokes an `onSnapshot` callback synchronously
332
+ * on the registering/writing stack: the initial snapshot arrives after
333
+ * the listen round-trip (COMPAT firestore#80 — "asynchronous, never
334
+ * during register"), and a local write's echo + server ack arrive on the
335
+ * async event queue (firestore#85). The sandbox mirrors that by enqueuing
336
+ * every user-facing delivery here and draining it off-stack, on a
337
+ * `queueMicrotask` boundary — which satisfies the "asynchronous" contract
338
+ * without a macrotask's extra latency (the prototype in the deep-divergence
339
+ * review measured identical behavior for micro- vs macro-task deferral).
340
+ *
341
+ * Per-listener FIFO order is preserved: deliveries enqueued *during* a
342
+ * drain — a callback that itself writes, or the item-3 metadata ack a
343
+ * write echo schedules — are appended and drained in the same pass, so a
344
+ * write settles fully before control returns to the microtask loop.
345
+ */
346
+ deliveryQueue = [];
347
+ deliveryScheduled = false;
348
+ constructor() {
349
+ this.state = new LocalState();
350
+ this.eventLog = new EventLog();
351
+ this.simulator = new SimulateFirestoreRulesHandler();
352
+ // Default to an allow-all ruleset so a freshly-constructed sandbox
353
+ // works for the quickstart `addDoc` / `getDoc` flow without forcing
354
+ // the caller to call `setRules(...)` first. The empty string used
355
+ // to live here and made the simulator throw `Failed to parse rules
356
+ // source` on first write — the most common failure mode for new
357
+ // users running `bun start` from `pyric init`. Callers who care
358
+ // about real rule enforcement still call `setRules(...)` explicitly;
359
+ // the default is just "don't blow up before you've thought about
360
+ // rules."
361
+ this.rulesSource = DEFAULT_OPEN_RULES;
362
+ this.seedSnapshot = {};
363
+ }
364
+ /**
365
+ * Subscribe to permission-denied events. Returns an unsubscribe fn.
366
+ * The callback receives the structured `FirestoreSimError` carrying
367
+ * `request` / `resource` (when populated) — so subscribers can render
368
+ * a debugger-style frame without re-deriving any state.
369
+ *
370
+ * Listener throws are swallowed to keep the simulator hot path
371
+ * resilient — a faulty subscriber should not change rule semantics.
372
+ */
373
+ onDenial(cb) {
374
+ this.denialListeners.add(cb);
375
+ return () => { this.denialListeners.delete(cb); };
376
+ }
377
+ emitDenial(err) {
378
+ if (this.denialListeners.size === 0)
379
+ return;
380
+ for (const cb of this.denialListeners) {
381
+ try {
382
+ cb(err);
383
+ }
384
+ catch { /* ignore — see onDenial doc */ }
385
+ }
386
+ }
387
+ /**
388
+ * Subscribe to every evaluated op (issue #307). Returns an unsubscribe
389
+ * fn. The emit sites in `execute`, `batch`, `silentReadDoc`,
390
+ * `silentReadCollection` build the public-shape event lazily — when
391
+ * no subscribers are attached, eval doesn't pay the allocation cost.
392
+ */
393
+ onRequest(cb) {
394
+ this.requestListeners.add(cb);
395
+ return () => { this.requestListeners.delete(cb); };
396
+ }
397
+ /**
398
+ * Subscribe to committed-write events. Internal — bridged to the
399
+ * public `Sandbox.onEvent` channel by SandboxImpl. Fires AFTER the
400
+ * keyspace applies the write; denied / rolled-back writes don't
401
+ * emit here.
402
+ */
403
+ onWrite(cb) {
404
+ this.writeListeners.add(cb);
405
+ return () => { this.writeListeners.delete(cb); };
406
+ }
407
+ /** Internal — bridge for sandbox-level `onEvent` to receive
408
+ * snapshot-delivery events. Fires after the user callback runs. */
409
+ onSnapshotDelivery(cb) {
410
+ this.deliveryListeners.add(cb);
411
+ return () => { this.deliveryListeners.delete(cb); };
412
+ }
413
+ /** Internal bridge for snapshot_suppressed events — re-evals that
414
+ * didn't deliver because diffing found no observable change. */
415
+ onSnapshotSuppressed(cb) {
416
+ this.suppressedListeners.add(cb);
417
+ return () => { this.suppressedListeners.delete(cb); };
418
+ }
419
+ /** Internal bridge for listener attach/detach lifecycle. Errored
420
+ * routes through onSnapshotError separately. */
421
+ onListenerLifecycle(cb) {
422
+ this.lifecycleListeners.add(cb);
423
+ return () => { this.lifecycleListeners.delete(cb); };
424
+ }
425
+ emitSnapshotDelivery(input) {
426
+ if (this.deliveryListeners.size === 0)
427
+ return;
428
+ const event = {
429
+ kind: 'snapshot_delivery',
430
+ id: nextRequestEventId().replace(/^req-/, 'snd-'),
431
+ at: Date.now(),
432
+ listenerId: input.listenerId,
433
+ target: input.target,
434
+ auth: input.auth
435
+ ? { uid: input.auth.uid, ...(input.auth.token ? { token: input.auth.token } : {}) }
436
+ : null,
437
+ addedCount: input.addedCount,
438
+ modifiedCount: input.modifiedCount,
439
+ removedCount: input.removedCount,
440
+ size: input.size,
441
+ ...(input.sample ? { sample: input.sample } : {}),
442
+ ...(input.triggeredBy ? { triggeredBy: input.triggeredBy } : {}),
443
+ };
444
+ for (const cb of this.deliveryListeners) {
445
+ try {
446
+ cb(event);
447
+ }
448
+ catch { /* swallow */ }
449
+ }
450
+ }
451
+ emitSnapshotSuppressed(input) {
452
+ if (this.suppressedListeners.size === 0)
453
+ return;
454
+ const event = {
455
+ kind: 'snapshot_suppressed',
456
+ id: nextRequestEventId().replace(/^req-/, 'sup-'),
457
+ at: Date.now(),
458
+ listenerId: input.listenerId,
459
+ target: input.target,
460
+ auth: input.auth
461
+ ? { uid: input.auth.uid, ...(input.auth.token ? { token: input.auth.token } : {}) }
462
+ : null,
463
+ reason: 'no-op',
464
+ ...(input.triggeredBy ? { triggeredBy: input.triggeredBy } : {}),
465
+ };
466
+ for (const cb of this.suppressedListeners) {
467
+ try {
468
+ cb(event);
469
+ }
470
+ catch { /* swallow */ }
471
+ }
472
+ }
473
+ emitLifecycle(input) {
474
+ if (this.lifecycleListeners.size === 0)
475
+ return;
476
+ const event = {
477
+ kind: input.phase,
478
+ id: nextRequestEventId().replace(/^req-/, 'lc-'),
479
+ at: Date.now(),
480
+ listenerId: input.listenerId,
481
+ target: input.target,
482
+ auth: input.auth
483
+ ? { uid: input.auth.uid, ...(input.auth.token ? { token: input.auth.token } : {}) }
484
+ : null,
485
+ };
486
+ for (const cb of this.lifecycleListeners) {
487
+ try {
488
+ cb(event);
489
+ }
490
+ catch { /* swallow */ }
491
+ }
492
+ }
493
+ /**
494
+ * Build and dispatch a `WriteSandboxEvent`. Same sync-throw +
495
+ * async-rejection isolation as emitRequest. Bails early when no
496
+ * subscribers are attached so the hot path stays allocation-free.
497
+ *
498
+ * `sentinels` and `autoId` are reserved fields the caller can
499
+ * populate when the replay-engine work lands. v1 always passes
500
+ * undefined for both.
501
+ */
502
+ emitWrite(input) {
503
+ if (this.writeListeners.size === 0)
504
+ return;
505
+ const event = {
506
+ kind: 'write',
507
+ id: nextRequestEventId().replace(/^req-/, 'wr-'),
508
+ at: Date.now(),
509
+ method: input.method,
510
+ path: input.path,
511
+ auth: input.auth
512
+ ? { uid: input.auth.uid, ...(input.auth.token ? { token: input.auth.token } : {}) }
513
+ : null,
514
+ ...(input.data !== undefined ? { data: input.data } : {}),
515
+ priorState: input.priorState,
516
+ nextState: input.nextState,
517
+ ...(input.groupId !== undefined ? { groupId: input.groupId } : {}),
518
+ ...(input.groupKind !== undefined ? { groupKind: input.groupKind } : {}),
519
+ ...(input.sentinels && input.sentinels.length > 0 ? { sentinels: input.sentinels } : {}),
520
+ ...(input.autoId !== undefined ? { autoId: input.autoId } : {}),
521
+ requestTime: { seconds: input.requestTime.seconds, nanoseconds: input.requestTime.nanos },
522
+ ...(input.detail !== undefined ? { detail: input.detail } : {}),
523
+ ...(input.provenance ?? {}),
524
+ };
525
+ for (const cb of this.writeListeners) {
526
+ try {
527
+ const result = cb(event);
528
+ if (result && typeof result.then === 'function') {
529
+ result.catch(() => { });
530
+ }
531
+ }
532
+ catch { /* see emitRequest doc */ }
533
+ }
534
+ }
535
+ /**
536
+ * Build and dispatch a `RequestEvent` to all `onRequest` subscribers.
537
+ * Bails early when no one's listening so the hot path doesn't allocate
538
+ * an event object. Per the V1 probe numbers, eval rate can reach
539
+ * ~4500/sec in listener-storm scenarios — every cycle matters.
540
+ *
541
+ * Subscriber-throw isolation has two layers:
542
+ * - Sync throws are caught by the try/catch around the invocation.
543
+ * - Async subscribers that return a rejected Promise (e.g.
544
+ * `async (e) => { throw }`) have the rejection silently swallowed
545
+ * by attaching a noop `.catch`. Without this, an
546
+ * `unhandledRejection` would terminate the sandbox process on
547
+ * Node ≥15 default config — one bad subscriber would kill every
548
+ * other observer.
549
+ *
550
+ * Subscriber callbacks are observational; the sandbox doesn't await
551
+ * them and doesn't propagate their errors.
552
+ */
553
+ emitRequest(input) {
554
+ if (this.requestListeners.size === 0)
555
+ return;
556
+ const event = buildRequestEvent(input);
557
+ for (const cb of this.requestListeners) {
558
+ try {
559
+ const result = cb(event);
560
+ if (result && typeof result.then === 'function') {
561
+ result.catch(() => { });
562
+ }
563
+ }
564
+ catch { /* see method doc */ }
565
+ }
566
+ }
567
+ /**
568
+ * Subscribe to snapshot-listener stream errors (Slice 7). Returns an
569
+ * unsubscribe fn. Fires every time a snapshot listener is marked
570
+ * errored — initial fire denial, change-driven re-read denial, or
571
+ * `deployRules` re-evaluation flipping a listener allowed → denied.
572
+ *
573
+ * The callback receives the structured `FirestoreSimError` plus the
574
+ * listener's `SnapshotTarget` so the host UI can attribute the error
575
+ * to a specific watch (e.g. "listener on `games/g1` errored").
576
+ *
577
+ * Per source survey section 9, this is the playground-side channel: stream
578
+ * errors fan out to both the listener's own `errorCallback` AND every
579
+ * env-level subscriber here. Subscriber throws are swallowed so a
580
+ * faulty UI handler can't destabilize the simulator.
581
+ */
582
+ onSnapshotError(cb) {
583
+ this.snapshotErrorListeners.add(cb);
584
+ return () => { this.snapshotErrorListeners.delete(cb); };
585
+ }
586
+ emitSnapshotError(err, target, listenerId) {
587
+ if (this.snapshotErrorListeners.size === 0)
588
+ return;
589
+ for (const cb of this.snapshotErrorListeners) {
590
+ try {
591
+ cb(err, target, listenerId);
592
+ }
593
+ catch { /* ignore — see onSnapshotError doc */ }
594
+ }
595
+ }
596
+ // ═══ Snapshot listeners (Slices 1+2) ═══
597
+ /**
598
+ * Register a snapshot listener. Returns an `Unsubscribe` function
599
+ * matching the Web SDK's contract — a zero-arg call that detaches
600
+ * the listener. Idempotent: calling the returned function more than
601
+ * once after the first detach is a no-op.
602
+ *
603
+ * Slice 2: fires the **initial snapshot** synchronously after the
604
+ * record is registered. The current matching docs are read under
605
+ * `auth`'s rules — denied reads invoke `errorCallback` and mark the
606
+ * listener `errored` (no further notifications). Slice 3 will add
607
+ * change-driven fires; Slice 5 batches them through `applyBatch`.
608
+ *
609
+ * `auth` is captured at registration so notifications later evaluate
610
+ * rules under the auth that subscribed — not whatever auth happens
611
+ * to be active when a write triggers the dispatch.
612
+ */
613
+ addSnapshotListener(target, callback, options = {}, auth = null, errorCallback,
614
+ /**
615
+ * `true` when the registering Firestore handle was a `sandbox-live`
616
+ * (`getFirestore(sandbox)`) target — its identity follows
617
+ * `sandbox.currentUser`, so this listener re-evaluates on a
618
+ * `currentUser` change (see {@link reevaluateLiveListeners}).
619
+ * `false` (default) for frozen-ctx (`getFirestore(ctx)`) listeners,
620
+ * which stay pinned to the auth they captured at registration.
621
+ */
622
+ followsCurrentUser = false,
623
+ /** Preserve the admin lens for the listener's full lifetime. */
624
+ bypassRules = false,
625
+ /** Named app session identity; undefined means the ambient session. */
626
+ authScope) {
627
+ const id = String(this.nextListenerId++);
628
+ const record = {
629
+ id,
630
+ target,
631
+ callback,
632
+ auth,
633
+ bypassRules,
634
+ followsCurrentUser,
635
+ ...(authScope ? { authScope } : {}),
636
+ options,
637
+ currentSnapshot: undefined,
638
+ errored: false,
639
+ ...(errorCallback ? { errorCallback } : {}),
640
+ };
641
+ this.snapshotListeners.set(id, record);
642
+ // Issue #307 — emit lifecycle BEFORE the initial fire so observers
643
+ // see attach → delivery in causal order.
644
+ this.emitLifecycle({
645
+ phase: 'listener_attach',
646
+ listenerId: id,
647
+ target: target.kind === 'doc'
648
+ ? { kind: 'doc', path: target.path }
649
+ : { kind: 'query', collection: target.collection },
650
+ auth,
651
+ });
652
+ // Items 3 + 5 — the initial snapshot is delivered off-stack through the
653
+ // delivery scheduler, never synchronously during register. Production's
654
+ // event queue schedules even a *cached* initial event asynchronously
655
+ // (COMPAT firestore#80: "asynchronous, never during register"), so the
656
+ // register-then-read-synchronously agent pattern that returns `undefined`
657
+ // on prod also returns `undefined` here — the sandbox no longer trains
658
+ // users into a pattern prod breaks. The unsubscribe-before-drain guard
659
+ // mirrors prod: a listener detached before its first fire never sees one.
660
+ // Errors still route through the listener's `errorCallback` (inside
661
+ // `fireInitialSnapshot`), never thrown out of `addSnapshotListener`.
662
+ this.scheduleDelivery(() => {
663
+ if (!this.snapshotListeners.has(id))
664
+ return;
665
+ this.fireInitialSnapshot(record);
666
+ });
667
+ return () => {
668
+ const stillRegistered = this.snapshotListeners.has(id);
669
+ this.snapshotListeners.delete(id);
670
+ // Only emit detach if the listener was actually registered when
671
+ // the unsubscribe was called. Idempotent calls and listeners
672
+ // dropped by `reset()` don't double-emit.
673
+ if (stillRegistered) {
674
+ this.emitLifecycle({
675
+ phase: 'listener_detach',
676
+ listenerId: id,
677
+ target: target.kind === 'doc'
678
+ ? { kind: 'doc', path: target.path }
679
+ : { kind: 'query', collection: target.collection },
680
+ auth,
681
+ });
682
+ }
683
+ };
684
+ }
685
+ /**
686
+ * Compute and deliver the initial snapshot for a freshly-registered
687
+ * listener. Reads under the listener's `auth` and respects the
688
+ * deployed rules — denied reads route to `errorCallback` and mark
689
+ * the record `errored`. Splits doc vs query targets along the same
690
+ * seam {@link execute} uses, but does **not** append to the event
691
+ * log: listener reads are bookkeeping, not user-visible operations,
692
+ * and would otherwise drown the event log under any non-trivial UI.
693
+ */
694
+ fireInitialSnapshot(record) {
695
+ if (record.target.kind === 'doc') {
696
+ const result = this.silentReadDoc(record.target.path, record.auth, record.bypassRules);
697
+ if (!result.allowed) {
698
+ this.markErrored(record, result.error);
699
+ return;
700
+ }
701
+ const snap = buildDocumentSnapshot(record.target.path, result.data);
702
+ record.currentSnapshot = snap;
703
+ record.currentDocData = result.data;
704
+ try {
705
+ record.callback(snap);
706
+ }
707
+ catch {
708
+ /* swallow — same rationale as emitDenial; a faulty consumer
709
+ * callback must not destabilize the simulator. */
710
+ }
711
+ // Issue #307 — initial fire counts as a delivery. No triggeredBy
712
+ // because there was no user op that caused this; the listener
713
+ // just attached.
714
+ this.emitSnapshotDelivery({
715
+ listenerId: record.id,
716
+ target: { kind: 'doc', path: record.target.path },
717
+ auth: record.auth,
718
+ addedCount: result.data !== null ? 1 : 0,
719
+ modifiedCount: 0,
720
+ removedCount: 0,
721
+ size: result.data !== null ? 1 : 0,
722
+ sample: { docs: [{ path: record.target.path, data: result.data }] },
723
+ });
724
+ return;
725
+ }
726
+ // Query target.
727
+ const result = this.silentReadCollection(record.target.collection, record.auth, record.target.constraints, record.bypassRules);
728
+ if (!result.allowed) {
729
+ this.markErrored(record, result.error);
730
+ return;
731
+ }
732
+ const snap = buildQuerySnapshot({ path: record.target.collection }, result.docs, { excludesMetadataChanges: !record.options.includeMetadataChanges });
733
+ record.currentSnapshot = snap;
734
+ record.currentDocs = result.docs;
735
+ try {
736
+ record.callback(snap);
737
+ }
738
+ catch {
739
+ /* swallow — see above */
740
+ }
741
+ this.emitSnapshotDelivery({
742
+ listenerId: record.id,
743
+ target: { kind: 'query', collection: record.target.collection },
744
+ auth: record.auth,
745
+ // Initial fire: every doc surfaces as `added`.
746
+ addedCount: result.docs.length,
747
+ modifiedCount: 0,
748
+ removedCount: 0,
749
+ size: result.docs.length,
750
+ sample: { docs: result.docs.map((d) => ({ path: d.path, data: d.data })) },
751
+ });
752
+ }
753
+ // ═══ Delivery scheduler (items 3 + 5) ═══
754
+ /**
755
+ * Enqueue a listener delivery and ensure an off-stack drain is pending.
756
+ * See {@link deliveryQueue}.
757
+ */
758
+ scheduleDelivery(deliver) {
759
+ this.deliveryQueue.push(deliver);
760
+ if (this.deliveryScheduled)
761
+ return;
762
+ this.deliveryScheduled = true;
763
+ queueMicrotask(() => this.drainDeliveries());
764
+ }
765
+ /**
766
+ * Enqueue a write-driven delivery, restoring the triggering op while it
767
+ * runs so listener-origin RequestEvents / delivery events still attribute
768
+ * to the write (`triggeredBy`) even though the callback now fires off the
769
+ * writing stack. See {@link currentTrigger}.
770
+ */
771
+ scheduleTriggeredDelivery(trigger, deliver) {
772
+ this.scheduleDelivery(() => {
773
+ const prevTrigger = this.currentTrigger;
774
+ this.currentTrigger = trigger;
775
+ try {
776
+ deliver();
777
+ }
778
+ finally {
779
+ this.currentTrigger = prevTrigger;
780
+ }
781
+ });
782
+ }
783
+ /**
784
+ * Drain queued deliveries in FIFO order. A delivery may enqueue more (a
785
+ * callback that writes; the item-3 metadata ack a write echo schedules) —
786
+ * those are appended and drained in the same pass.
787
+ */
788
+ drainDeliveries() {
789
+ this.deliveryScheduled = false;
790
+ while (this.deliveryQueue.length > 0) {
791
+ const deliver = this.deliveryQueue.shift();
792
+ deliver();
793
+ }
794
+ }
795
+ /**
796
+ * Synchronously deliver all pending snapshot fires. Test-only seam:
797
+ * production consumers observe deliveries via the microtask drain, but a
798
+ * synchronous test body calls this to settle the queue deterministically
799
+ * before asserting fire counts / snapshot contents. Idempotent — a no-op
800
+ * on an empty queue, and safe when a microtask drain is also pending (that
801
+ * drain then finds the queue already empty).
802
+ */
803
+ flushListeners() {
804
+ this.drainDeliveries();
805
+ }
806
+ // ═══ Slice 3 — change-driven notification ═══
807
+ /**
808
+ * Walk every active snapshot listener and fire those whose target
809
+ * intersects `touchedPaths`. Called by the write-path commit hooks
810
+ * — `execute` (single write) and the two `applyBatch` call-sites
811
+ * (batch + transaction). Suppresses no-op snapshots per findings section 5
812
+ * (View-level suppression rather than `isEqual`): doc listeners only
813
+ * fire when the underlying data shape changes; query listeners only
814
+ * fire when the change list is non-empty.
815
+ *
816
+ * Iteration walks a snapshotted list of records — a callback is
817
+ * allowed to add or remove listeners (StrictMode + HMR routinely do)
818
+ * and we must not iterate a mutating Map.
819
+ *
820
+ * Items 3 + 5 — each per-listener fire is enqueued on the delivery
821
+ * scheduler rather than run inline, so the write echo lands off the
822
+ * writing stack (like prod's async event queue) and stays ordered behind
823
+ * any still-pending initial fire for the same listener. The errored /
824
+ * unsubscribe checks are re-run at delivery time because a listener may
825
+ * detach or error between this write and the drain.
826
+ */
827
+ notifyListenersForPaths(touchedPaths) {
828
+ if (touchedPaths.size === 0)
829
+ return;
830
+ if (this.snapshotListeners.size === 0)
831
+ return;
832
+ // Capture the triggering op now; the deliveries run off-stack, by which
833
+ // time `currentTrigger` has been restored to the microtask loop's state.
834
+ const trigger = this.currentTrigger;
835
+ const records = Array.from(this.snapshotListeners.values());
836
+ for (const record of records) {
837
+ this.scheduleTriggeredDelivery(trigger, () => {
838
+ if (!this.snapshotListeners.has(record.id))
839
+ return;
840
+ if (record.errored)
841
+ return;
842
+ if (record.target.kind === 'doc') {
843
+ this.notifyDocListener(record, touchedPaths);
844
+ }
845
+ else {
846
+ this.notifyQueryListener(record, touchedPaths);
847
+ }
848
+ });
849
+ }
850
+ }
851
+ notifyDocListener(record, touchedPaths) {
852
+ if (record.target.kind !== 'doc')
853
+ return;
854
+ if (!touchedPaths.has(record.target.path))
855
+ return;
856
+ const result = this.silentReadDoc(record.target.path, record.auth, record.bypassRules);
857
+ if (!result.allowed) {
858
+ this.markErrored(record, result.error);
859
+ return;
860
+ }
861
+ // Suppression: identical underlying data (existence + shape) ⇒ no
862
+ // fire. Production's View suppresses by absence rather than by
863
+ // building-then-comparing snapshots; we approximate the same shape
864
+ // by comparing the raw data we'd hand to `buildDocumentSnapshot`.
865
+ const prev = record.currentDocData ?? null;
866
+ if (docDataEqual(prev, result.data)) {
867
+ // Issue #307 — surface the suppressed re-eval so inspector-style
868
+ // consumers can answer "the listener woke up but had nothing to
869
+ // deliver".
870
+ this.emitSnapshotSuppressed({
871
+ listenerId: record.id,
872
+ target: { kind: 'doc', path: record.target.path },
873
+ auth: record.auth,
874
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
875
+ });
876
+ return;
877
+ }
878
+ // Item 3 — the local write echo carries hasPendingWrites:true (prod's
879
+ // optimistic local fire, delivered before the server round-trip). The
880
+ // settled server ack (hasPendingWrites:false) is scheduled below, but
881
+ // only includeMetadataChanges listeners observe it — a default listener's
882
+ // last-seen snapshot stays `pending:true` (COMPAT firestore#85).
883
+ const path = record.target.path;
884
+ const snap = buildDocumentSnapshot(path, result.data, SANDBOX_METADATA_PENDING);
885
+ record.currentSnapshot = snap;
886
+ record.currentDocData = result.data;
887
+ // Compute change shape for the delivery event. Doc listeners deliver
888
+ // exactly one of added / modified / removed per fire.
889
+ const wasExists = prev !== null;
890
+ const isExists = result.data !== null;
891
+ const addedCount = !wasExists && isExists ? 1 : 0;
892
+ const removedCount = wasExists && !isExists ? 1 : 0;
893
+ const modifiedCount = wasExists && isExists ? 1 : 0;
894
+ try {
895
+ record.callback(snap);
896
+ }
897
+ catch {
898
+ /* swallow — see fireInitialSnapshot doc */
899
+ }
900
+ // Emit delivery AFTER the user callback runs so subscribers see
901
+ // the same ordering as the user code: callback first, observer second.
902
+ this.emitSnapshotDelivery({
903
+ listenerId: record.id,
904
+ target: { kind: 'doc', path },
905
+ auth: record.auth,
906
+ addedCount,
907
+ modifiedCount,
908
+ removedCount,
909
+ size: isExists ? 1 : 0,
910
+ sample: { docs: [{ path, data: result.data }] },
911
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
912
+ });
913
+ this.scheduleDocMetadataAck(record, path, result.data);
914
+ }
915
+ /**
916
+ * Item 3 — schedule the server-ack fire that follows a write echo. Only
917
+ * fires for includeMetadataChanges listeners (default listeners never see
918
+ * the metadata-only ack; their snapshot stays `pending:true`). Re-delivers
919
+ * the just-echoed data with `hasPendingWrites:false`, as a metadata-only
920
+ * change (no added/modified/removed). Rides the delivery scheduler so it
921
+ * lands off the echo's stack, matching prod's async ack rather than a
922
+ * synchronous same-tick fire. `data` is captured from the echo so a later
923
+ * write can't retroactively change what this ack reports. COMPAT firestore#85.
924
+ */
925
+ scheduleDocMetadataAck(record, path, data) {
926
+ if (!record.options.includeMetadataChanges)
927
+ return;
928
+ this.scheduleTriggeredDelivery(this.currentTrigger, () => {
929
+ if (!this.snapshotListeners.has(record.id))
930
+ return;
931
+ if (record.errored)
932
+ return;
933
+ const ack = buildDocumentSnapshot(path, data, SANDBOX_METADATA);
934
+ record.currentSnapshot = ack;
935
+ try {
936
+ record.callback(ack);
937
+ }
938
+ catch {
939
+ /* swallow — see fireInitialSnapshot doc */
940
+ }
941
+ this.emitSnapshotDelivery({
942
+ listenerId: record.id,
943
+ target: { kind: 'doc', path },
944
+ auth: record.auth,
945
+ addedCount: 0,
946
+ modifiedCount: 0,
947
+ removedCount: 0,
948
+ size: data !== null ? 1 : 0,
949
+ sample: { docs: [{ path, data }] },
950
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
951
+ });
952
+ });
953
+ }
954
+ notifyQueryListener(record, touchedPaths) {
955
+ if (record.target.kind !== 'query')
956
+ return;
957
+ // Cheap pre-filter: if no touched path lives in this collection,
958
+ // skip the rules eval entirely. {@link silentReadCollection}'s
959
+ // query-proof gate handles read-side visibility; this filter is
960
+ // purely a write-path optimization.
961
+ if (!anyPathInCollection(touchedPaths, record.target.collection))
962
+ return;
963
+ const result = this.silentReadCollection(record.target.collection, record.auth, record.target.constraints, record.bypassRules);
964
+ if (!result.allowed) {
965
+ this.markErrored(record, result.error);
966
+ return;
967
+ }
968
+ const collection = record.target.collection;
969
+ const prevDocs = record.currentDocs ?? [];
970
+ // Item 3 — the write echo carries hasPendingWrites:true; the settled ack
971
+ // (scheduled below for includeMetadataChanges listeners) carries false.
972
+ const snap = buildQuerySnapshot({ path: collection }, result.docs, { excludesMetadataChanges: !record.options.includeMetadataChanges }, prevDocs, SANDBOX_METADATA_PENDING);
973
+ // Suppression: empty change set ⇒ nothing observable changed for
974
+ // this listener (e.g., a write that landed under a different
975
+ // collection but tripped the cheap pre-filter, or a write whose
976
+ // post-image equals its pre-image). Match findings section 5.
977
+ const changes = snap.docChanges();
978
+ if (changes.length === 0) {
979
+ this.emitSnapshotSuppressed({
980
+ listenerId: record.id,
981
+ target: { kind: 'query', collection },
982
+ auth: record.auth,
983
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
984
+ });
985
+ return;
986
+ }
987
+ record.currentSnapshot = snap;
988
+ record.currentDocs = result.docs;
989
+ let addedCount = 0, modifiedCount = 0, removedCount = 0;
990
+ for (const c of changes) {
991
+ if (c.type === 'added')
992
+ addedCount++;
993
+ else if (c.type === 'modified')
994
+ modifiedCount++;
995
+ else if (c.type === 'removed')
996
+ removedCount++;
997
+ }
998
+ try {
999
+ record.callback(snap);
1000
+ }
1001
+ catch {
1002
+ /* swallow — see fireInitialSnapshot doc */
1003
+ }
1004
+ this.emitSnapshotDelivery({
1005
+ listenerId: record.id,
1006
+ target: { kind: 'query', collection },
1007
+ auth: record.auth,
1008
+ addedCount,
1009
+ modifiedCount,
1010
+ removedCount,
1011
+ size: result.docs.length,
1012
+ sample: { docs: result.docs.map((d) => ({ path: d.path, data: d.data })) },
1013
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1014
+ });
1015
+ this.scheduleQueryMetadataAck(record, collection, result.docs);
1016
+ }
1017
+ /**
1018
+ * Item 3 — query counterpart of {@link scheduleDocMetadataAck}. Re-delivers
1019
+ * the echoed doc set with `hasPendingWrites:false` as a metadata-only change
1020
+ * (no added/modified/removed — `prevDocs` equals the current docs), for
1021
+ * includeMetadataChanges listeners only. COMPAT firestore#85.
1022
+ */
1023
+ scheduleQueryMetadataAck(record, collection, docs) {
1024
+ if (!record.options.includeMetadataChanges)
1025
+ return;
1026
+ this.scheduleTriggeredDelivery(this.currentTrigger, () => {
1027
+ if (!this.snapshotListeners.has(record.id))
1028
+ return;
1029
+ if (record.errored)
1030
+ return;
1031
+ const ack = buildQuerySnapshot({ path: collection }, docs, { excludesMetadataChanges: false }, docs, SANDBOX_METADATA);
1032
+ record.currentSnapshot = ack;
1033
+ try {
1034
+ record.callback(ack);
1035
+ }
1036
+ catch {
1037
+ /* swallow — see fireInitialSnapshot doc */
1038
+ }
1039
+ this.emitSnapshotDelivery({
1040
+ listenerId: record.id,
1041
+ target: { kind: 'query', collection },
1042
+ auth: record.auth,
1043
+ addedCount: 0,
1044
+ modifiedCount: 0,
1045
+ removedCount: 0,
1046
+ size: docs.length,
1047
+ sample: { docs: docs.map((d) => ({ path: d.path, data: d.data })) },
1048
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1049
+ });
1050
+ });
1051
+ }
1052
+ /**
1053
+ * Run a `get` through the rules without touching the event log.
1054
+ * Returns the read shape used by listener-snapshot construction.
1055
+ *
1056
+ * Throws `SimulatorUnsupportedError` on UNSUPPORTED — same loud
1057
+ * surface as {@link execute}; the caller is then responsible for
1058
+ * propagating it. Listener-init paths catch nothing: an unsupported
1059
+ * rule is a sandbox limitation worth surfacing to the agent
1060
+ * verbatim, not silently rerouting through `errorCallback`.
1061
+ */
1062
+ silentReadDoc(path, auth, bypassRules = false) {
1063
+ if (bypassRules) {
1064
+ const data = this.state.get(path);
1065
+ this.emitRequest({
1066
+ at: Date.now(),
1067
+ evalMs: 0,
1068
+ method: 'get',
1069
+ path,
1070
+ auth,
1071
+ result: 'allow',
1072
+ debugMessages: ['admin lens — rules bypassed'],
1073
+ origin: 'listener',
1074
+ resourceBefore: { data, exists: data !== null },
1075
+ detail: { admin: true },
1076
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1077
+ });
1078
+ return { allowed: true, data };
1079
+ }
1080
+ const readServerTime = Timestamp.fromMillis(Date.now());
1081
+ const testCase = this.buildTestCase({ method: 'get', path, auth }, readServerTime);
1082
+ // Issue #307 — time the simulate call for listener-origin RequestEvents.
1083
+ const evalAt = Date.now();
1084
+ const evalStart = performance.now();
1085
+ const simResult = this.simulator.simulate(this.rulesSource, [testCase], {
1086
+ getDoc: (path) => this.state.get(path),
1087
+ });
1088
+ const evalMs = performance.now() - evalStart;
1089
+ if (!simResult.success) {
1090
+ this.emitRequest({
1091
+ at: evalAt, evalMs, method: 'get', path, auth, result: 'deny',
1092
+ debugMessages: [`Simulation error: ${simResult.error.message}`],
1093
+ origin: 'listener',
1094
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1095
+ });
1096
+ return {
1097
+ allowed: false,
1098
+ error: makeError('permission-denied', `get ${path} simulator error`, {
1099
+ request: { method: 'get', path, auth },
1100
+ }),
1101
+ };
1102
+ }
1103
+ const result = simResult.data.results[0];
1104
+ if (result.state === 'UNSUPPORTED') {
1105
+ this.emitRequest({
1106
+ at: evalAt, evalMs, method: 'get', path, auth, result: 'unsupported',
1107
+ debugMessages: renderLegacyDebugMessages(result), origin: 'listener',
1108
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1109
+ });
1110
+ throw new SimulatorUnsupportedError(unsupportedMessage('get', path, renderLegacyDebugMessages(result)), 'get', path, renderLegacyDebugMessages(result));
1111
+ }
1112
+ const isAllowed = result.state === 'PASSED';
1113
+ const data = this.state.get(path);
1114
+ this.emitRequest({
1115
+ at: evalAt, evalMs, method: 'get', path, auth,
1116
+ result: isAllowed ? 'allow' : 'deny',
1117
+ debugMessages: renderLegacyDebugMessages(result),
1118
+ evaluatedRule: projectEvaluatedRule(result), origin: 'listener',
1119
+ resourceBefore: { data, exists: data !== null },
1120
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1121
+ });
1122
+ if (!isAllowed) {
1123
+ return {
1124
+ allowed: false,
1125
+ error: makeError('permission-denied', `get ${path} denied by rules`, {
1126
+ request: { method: 'get', path, auth },
1127
+ resource: { data, exists: data !== null },
1128
+ }),
1129
+ };
1130
+ }
1131
+ return { allowed: true, data };
1132
+ }
1133
+ /**
1134
+ * RULES-B11 — the parsed rules AST for the query-proof gate, cached
1135
+ * per source string. `null` when the source doesn't parse (the
1136
+ * simulate() call then reports the failure on its own).
1137
+ */
1138
+ rulesAst() {
1139
+ if (this.parsedRulesCache?.source !== this.rulesSource) {
1140
+ this.parsedRulesCache = {
1141
+ source: this.rulesSource,
1142
+ ast: parseToAST(this.rulesSource),
1143
+ };
1144
+ }
1145
+ return this.parsedRulesCache.ast;
1146
+ }
1147
+ /**
1148
+ * Collection variant of {@link silentReadDoc}. Returns docs in
1149
+ * `LocalState.list` order. Phantom parents are dropped here;
1150
+ * agent-visible snapshots only contain real docs.
1151
+ *
1152
+ * **RULES-B11 — query-proof enforcement ("rules are not filters").**
1153
+ * Production never filters a query down to the readable subset: the
1154
+ * `list` rule is proven against the query's constraints, and an
1155
+ * unprovable query is DENIED whole (firebase.google.com/docs/firestore/
1156
+ * security/rules-query). The gate here:
1157
+ * 1. `proveListQuery` decides PROVABLE / UNPROVABLE from the matched
1158
+ * `list`/`read` rule conditions + the structured `where`
1159
+ * constraints carried on the applier (FS-B2 threading).
1160
+ * 2. UNPROVABLE → one deny request event + `permission-denied` for
1161
+ * the WHOLE query — no silent truncation.
1162
+ * 3. PROVABLE → the ordinary simulate() run evaluates the residual
1163
+ * (auth / time / request.query) condition; doc-data conjuncts the
1164
+ * query pins are evaluated against the synthetic representative
1165
+ * resource (see `list-query-proof.ts`).
1166
+ * Per-doc `get` rules do NOT filter query results — prod queries are
1167
+ * governed by the `list` rule alone (the old per-doc filter loop was
1168
+ * the rules-as-filters divergence this replaces). UNSUPPORTED still
1169
+ * bubbles through unchanged.
1170
+ */
1171
+ silentReadCollection(collection, auth, constraints, bypassRules = false) {
1172
+ const readServerTime = Timestamp.fromMillis(Date.now());
1173
+ // List rules are defined at the document-match level, so the
1174
+ // simulator expects a document-style path with a synthetic
1175
+ // placeholder segment (matches the convention used by
1176
+ // local-env-reads tests). Without it, a `list` against a bare
1177
+ // collection path falls through to no match and is denied.
1178
+ const listPath = `${collection}/__listPlaceholder__`;
1179
+ const structured = constraints?.structured ?? {};
1180
+ const requestQuery = listQueryFromStructured(structured);
1181
+ const detailFields = {
1182
+ ...(bypassRules ? { admin: true } : {}),
1183
+ ...(requestQuery ? { query: requestQuery } : {}),
1184
+ };
1185
+ const requestDetail = Object.keys(detailFields).length > 0 ? detailFields : undefined;
1186
+ const evalAt = Date.now();
1187
+ const evalStart = performance.now();
1188
+ if (bypassRules) {
1189
+ const docs = this.state.list(collection)
1190
+ .filter((document) => !document.phantom)
1191
+ .map((document) => ({ path: document.path, data: document.data }));
1192
+ const constrained = constraints ? constraints(docs) : docs;
1193
+ this.emitRequest({
1194
+ at: evalAt,
1195
+ evalMs: 0,
1196
+ method: 'list',
1197
+ path: collection,
1198
+ auth,
1199
+ result: 'allow',
1200
+ debugMessages: ['admin lens — rules bypassed'],
1201
+ origin: 'listener',
1202
+ ...(requestDetail ? { detail: requestDetail } : {}),
1203
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1204
+ });
1205
+ return { allowed: true, docs: constrained };
1206
+ }
1207
+ // ── RULES-B11 gate: prove the query before evaluating the rule. ──
1208
+ const proof = proveListQuery(this.rulesAst(), listPath, auth, structured);
1209
+ if (proof.kind === 'unprovable') {
1210
+ const evalMs = performance.now() - evalStart;
1211
+ const message = `list ${collection} denied: unprovable query — rules are not filters (${proof.reason})`;
1212
+ this.emitRequest({
1213
+ at: evalAt, evalMs, method: 'list', path: collection, auth, result: 'deny',
1214
+ debugMessages: [message], origin: 'listener',
1215
+ ...(requestDetail ? { detail: requestDetail } : {}),
1216
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1217
+ });
1218
+ return {
1219
+ allowed: false,
1220
+ error: makeError('permission-denied', message, {
1221
+ request: { method: 'list', path: collection, auth },
1222
+ }),
1223
+ };
1224
+ }
1225
+ const testCase = this.buildTestCase({ method: 'list', path: listPath, auth }, readServerTime);
1226
+ this.applyListProof(testCase, proof, structured);
1227
+ // Issue #307 — time the outer list eval.
1228
+ const simResult = this.simulator.simulate(this.rulesSource, [testCase], {
1229
+ getDoc: (path) => this.state.get(path),
1230
+ });
1231
+ const evalMs = performance.now() - evalStart;
1232
+ if (!simResult.success) {
1233
+ this.emitRequest({
1234
+ at: evalAt, evalMs, method: 'list', path: collection, auth, result: 'deny',
1235
+ debugMessages: [`Simulation error: ${simResult.error.message}`],
1236
+ origin: 'listener',
1237
+ ...(requestDetail ? { detail: requestDetail } : {}),
1238
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1239
+ });
1240
+ return {
1241
+ allowed: false,
1242
+ error: makeError('permission-denied', `list ${collection} simulator error`, {
1243
+ request: { method: 'list', path: collection, auth },
1244
+ }),
1245
+ };
1246
+ }
1247
+ const result = simResult.data.results[0];
1248
+ if (result.state === 'UNSUPPORTED') {
1249
+ this.emitRequest({
1250
+ at: evalAt, evalMs, method: 'list', path: collection, auth, result: 'unsupported',
1251
+ debugMessages: renderLegacyDebugMessages(result), origin: 'listener',
1252
+ ...(requestDetail ? { detail: requestDetail } : {}),
1253
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1254
+ });
1255
+ throw new SimulatorUnsupportedError(unsupportedMessage('list', collection, renderLegacyDebugMessages(result)), 'list', collection, renderLegacyDebugMessages(result));
1256
+ }
1257
+ if (result.state !== 'PASSED') {
1258
+ this.emitRequest({
1259
+ at: evalAt, evalMs, method: 'list', path: collection, auth, result: 'deny',
1260
+ debugMessages: renderLegacyDebugMessages(result),
1261
+ evaluatedRule: projectEvaluatedRule(result), origin: 'listener',
1262
+ ...(requestDetail ? { detail: requestDetail } : {}),
1263
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1264
+ });
1265
+ return {
1266
+ allowed: false,
1267
+ error: makeError('permission-denied', `list ${collection} denied by rules`, {
1268
+ request: { method: 'list', path: collection, auth },
1269
+ }),
1270
+ };
1271
+ }
1272
+ // One allow event for the whole list — one query listener fire =
1273
+ // one event in the consumer's stream.
1274
+ this.emitRequest({
1275
+ at: evalAt, evalMs, method: 'list', path: collection, auth, result: 'allow',
1276
+ debugMessages: renderLegacyDebugMessages(result),
1277
+ evaluatedRule: projectEvaluatedRule(result), origin: 'listener',
1278
+ ...(requestDetail ? { detail: requestDetail } : {}),
1279
+ ...(this.currentTrigger ? { triggeredBy: this.currentTrigger } : {}),
1280
+ });
1281
+ // RULES-B11 — the proof + list-rule eval decided the WHOLE query; no
1282
+ // per-doc `get` re-evaluation. Production queries are governed by the
1283
+ // `list` rule alone — a per-doc filter here was the rules-as-filters
1284
+ // divergence (docs the user couldn't `get` were silently omitted
1285
+ // where prod would have returned them, list rule permitting).
1286
+ const docs = this.state.list(collection)
1287
+ .filter((d) => !d.phantom)
1288
+ .map((d) => ({ path: d.path, data: d.data }));
1289
+ // FS-B2 — apply the query's where / orderBy / cursor / limit
1290
+ // constraints, so a filtered listener delivers the same membership a
1291
+ // one-shot `getDocs(query(...))` would (instead of the whole
1292
+ // collection). The proof above guaranteed the rule holds for every
1293
+ // doc the constraints admit.
1294
+ const constrained = constraints ? constraints(docs) : docs;
1295
+ return { allowed: true, docs: constrained };
1296
+ }
1297
+ /**
1298
+ * RULES-B11 — apply a PROVABLE proof to the `list` test case before the
1299
+ * residual simulate() run:
1300
+ * - inject the synthetic representative `resource` (the fields the
1301
+ * query pins with `where(field, ==, value)`) so doc-data conjuncts
1302
+ * evaluate against what every returnable doc is guaranteed to carry;
1303
+ * - populate `request.query` from the structured constraints so rules
1304
+ * reading `request.query.limit` / `.orderBy` see the real values.
1305
+ */
1306
+ applyListProof(testCase, proof, structured) {
1307
+ if (proof.kind === 'provable' && proof.syntheticResource) {
1308
+ testCase.resource = proof.syntheticResource;
1309
+ }
1310
+ if (structured.limit != null || structured.offset != null || structured.orderBy != null) {
1311
+ testCase.query = {
1312
+ ...(structured.limit != null ? { limit: structured.limit } : {}),
1313
+ ...(structured.offset != null ? { offset: structured.offset } : {}),
1314
+ ...(structured.orderBy != null ? { orderBy: structured.orderBy } : {}),
1315
+ };
1316
+ }
1317
+ }
1318
+ /**
1319
+ * Mark a listener as errored and fan the error out to two channels:
1320
+ * 1. The listener's own `errorCallback` (per-listener handler the
1321
+ * Web SDK consumer registered via `onSnapshot(next, error)`).
1322
+ * 2. Every env-level `onSnapshotError` subscriber (Slice 7) — the
1323
+ * playground UI surfaces stream errors here without each
1324
+ * listener needing to register its own toast handler.
1325
+ *
1326
+ * Fan-out is unconditional even when `errorCallback` is missing: the
1327
+ * env-level channel is the catch-all so the host environment can
1328
+ * surface errors from listeners that didn't supply their own handler.
1329
+ */
1330
+ markErrored(record, error) {
1331
+ record.errored = true;
1332
+ this.emitSnapshotError(error, record.target, record.id);
1333
+ if (!record.errorCallback)
1334
+ return;
1335
+ try {
1336
+ record.errorCallback(error);
1337
+ }
1338
+ catch {
1339
+ /* see emitDenial doc */
1340
+ }
1341
+ }
1342
+ /**
1343
+ * Test seam — exposes registry size without leaking the records.
1344
+ * Slice 2+ may add a richer accessor when the diff path needs to
1345
+ * iterate; for now this is enough to assert add/remove correctness.
1346
+ */
1347
+ getSnapshotListenerCount() {
1348
+ return this.snapshotListeners.size;
1349
+ }
1350
+ /**
1351
+ * Tear down the environment's listener registries (Slice 8).
1352
+ *
1353
+ * Clears every snapshot listener, denial subscriber, and snapshot-error
1354
+ * subscriber so the environment drops its references to consumer
1355
+ * callbacks. Use case: a host (e.g. the playground runner) is about to
1356
+ * discard this `LocalEnvironment` in favor of a fresh one — calling
1357
+ * `dispose()` first guarantees that any orphan callbacks held by the
1358
+ * outgoing env can no longer be invoked, even if some external code path
1359
+ * still holds a reference to the old instance.
1360
+ *
1361
+ * Idempotent: clearing already-empty sets is a no-op. Does not touch
1362
+ * data state (`state` / `eventLog` / `rulesSource`) — `dispose()` is
1363
+ * about *callback ownership*, not data lifecycle. Construct a fresh
1364
+ * `LocalEnvironment` (or call `seed()`) to reset data.
1365
+ */
1366
+ dispose() {
1367
+ this.snapshotListeners.clear();
1368
+ this.denialListeners.clear();
1369
+ this.snapshotErrorListeners.clear();
1370
+ this.requestListeners.clear();
1371
+ this.writeListeners.clear();
1372
+ this.deliveryListeners.clear();
1373
+ this.suppressedListeners.clear();
1374
+ this.lifecycleListeners.clear();
1375
+ // Drop any queued-but-undelivered fires so a disposed env can't invoke
1376
+ // an outgoing consumer's callback on a later microtask drain.
1377
+ this.deliveryQueue.length = 0;
1378
+ this.deliveryScheduled = false;
1379
+ }
1380
+ /** Seed the environment with rules and initial data. */
1381
+ seed(options) {
1382
+ this.rulesSource = options.rules;
1383
+ // `baseDocuments` (branch fork): wrap the snapshot as an immutable CoW base
1384
+ // instead of cloning it, so the fork is O(1). Reads fall through to the base;
1385
+ // branch writes land in the overlay.
1386
+ this.state = options.baseDocuments
1387
+ ? new LocalState({}, new OverlayBacking(options.baseDocuments))
1388
+ : new LocalState(options.documents ?? {});
1389
+ // The reset baseline. For a branch it aliases the immutable base (no clone;
1390
+ // it is already a stable snapshot). seedSnapshot has no reader today; if a
1391
+ // future reset does state.restore(seedSnapshot), clone it first so the base's
1392
+ // nested refs are not aliased back into the live keyspace.
1393
+ this.seedSnapshot = options.baseDocuments ?? this.state.snapshot();
1394
+ this.eventLog.clear();
1395
+ return lintFirestoreRules(options.rules);
1396
+ }
1397
+ /**
1398
+ * Deploy new rules (re-lint, swap for next operation).
1399
+ *
1400
+ * **Slice 6 — re-evaluation.** After a successful swap, every active
1401
+ * listener is re-evaluated under the new rules. This **diverges from
1402
+ * production** (where rule changes don't affect already-attached
1403
+ * listeners) and is intentional per the design rationale
1404
+ * section 4.1 — the playground's value is seeing rule changes reflected
1405
+ * immediately in live UI. Concretely:
1406
+ * - A doc that was unreadable but is now readable fires a snapshot
1407
+ * (and clears the listener's `errored` flag if applicable).
1408
+ * - A doc that was readable but is now unreadable marks the listener
1409
+ * errored via {@link markErrored}.
1410
+ * - Query listeners diff old↔new readable doc sets; flips surface as
1411
+ * `added` / `removed` change entries.
1412
+ */
1413
+ deployRules(source) {
1414
+ const lint = lintFirestoreRules(source);
1415
+ // **Always install.** The previous behavior gated install on
1416
+ // `errors.length === 0` and silently no-op'd otherwise — that
1417
+ // caused a 51-tool-call debug session where an agent couldn't
1418
+ // figure out why its rules weren't applied (CLAUDE_DEBUG_SESSION.md).
1419
+ // Lint is *diagnosis*, not enforcement. The dev-loop sandbox installs
1420
+ // whatever the caller asks for; CI or a release workflow can enforce a
1421
+ // stricter policy before shipping. Callers that care about
1422
+ // the lint result still get it back; the `sandbox_inspect`
1423
+ // MCP tool surfaces it for agents.
1424
+ this.rulesSource = source;
1425
+ this.reEvaluateAllListeners();
1426
+ return lint;
1427
+ }
1428
+ /**
1429
+ * Walk every active listener and recompute its snapshot under the
1430
+ * current rules. Called by {@link deployRules} after a successful
1431
+ * rules swap (Slice 6 section 4.1). Iteration follows the same
1432
+ * snapshot-then-skip-orphans pattern as {@link notifyListenersForPaths}
1433
+ * — a callback may add or remove listeners (StrictMode + HMR both
1434
+ * routinely do this), and the dispatch loop must not iterate a
1435
+ * mutating Map.
1436
+ */
1437
+ reEvaluateAllListeners() {
1438
+ if (this.snapshotListeners.size === 0)
1439
+ return;
1440
+ const records = Array.from(this.snapshotListeners.values());
1441
+ for (const record of records) {
1442
+ if (!this.snapshotListeners.has(record.id))
1443
+ continue;
1444
+ if (record.target.kind === 'doc') {
1445
+ this.reEvaluateDocListener(record);
1446
+ }
1447
+ else {
1448
+ this.reEvaluateQueryListener(record);
1449
+ }
1450
+ }
1451
+ }
1452
+ /**
1453
+ * Re-evaluate every LIVE listener against a new session auth.
1454
+ *
1455
+ * Called when the sandbox's `currentUser` changes (sign-out / sign-in
1456
+ * as a different user). Production re-establishes the listen stream on
1457
+ * a session auth change — an auth-gated listener loses access on
1458
+ * sign-out and re-reads under the new identity on sign-in. The sandbox
1459
+ * matches that here: for each listener with `followsCurrentUser`, we
1460
+ * set `record.auth = newAuth` and re-run the SAME per-listener
1461
+ * evaluation `deployRules` uses ({@link reEvaluateDocListener} /
1462
+ * {@link reEvaluateQueryListener}) — which re-reads under the new auth
1463
+ * and flips allowed↔denied (delivering a fresh snapshot, or marking
1464
+ * the listener errored with `permission-denied` when the new auth
1465
+ * can't read).
1466
+ *
1467
+ * Frozen-ctx listeners (`followsCurrentUser === false`) are left
1468
+ * untouched — they stay pinned to the identity chosen at
1469
+ * `getFirestore(ctx)` time. WRITE-driven re-eval is unaffected: a
1470
+ * write by another user still re-evaluates each listener against ITS
1471
+ * OWN captured `auth` (this method only runs on auth change, and only
1472
+ * touches live listeners' captured auth).
1473
+ *
1474
+ * No-op when there are no live listeners. Iteration follows the same
1475
+ * snapshot-then-skip-orphans pattern as {@link notifyListenersForPaths}
1476
+ * — a callback may add or remove listeners during dispatch.
1477
+ */
1478
+ reevaluateLiveListeners(newAuth, authScope) {
1479
+ if (this.snapshotListeners.size === 0)
1480
+ return;
1481
+ const records = Array.from(this.snapshotListeners.values());
1482
+ for (const record of records) {
1483
+ if (!record.followsCurrentUser)
1484
+ continue;
1485
+ if (record.authScope !== authScope)
1486
+ continue;
1487
+ if (!this.snapshotListeners.has(record.id))
1488
+ continue;
1489
+ // Re-capture the session's new auth, then re-read under it. This is
1490
+ // the live-listener counterpart to prod re-establishing the stream
1491
+ // under the new identity.
1492
+ record.auth = newAuth;
1493
+ if (record.target.kind === 'doc') {
1494
+ this.reEvaluateDocListener(record);
1495
+ }
1496
+ else {
1497
+ this.reEvaluateQueryListener(record);
1498
+ }
1499
+ }
1500
+ }
1501
+ /**
1502
+ * Doc-listener re-evaluation. Three flip cases matter:
1503
+ * - Allowed → denied: mark errored (unless already errored, in which
1504
+ * case the error is not re-delivered — matches production's
1505
+ * once-per-stream error contract).
1506
+ * - Errored → allowed: clear `errored` and fire as an initial
1507
+ * snapshot (the listener gets a fresh baseline; suppression cannot
1508
+ * apply because there is no comparable `currentDocData` from the
1509
+ * errored state).
1510
+ * - Allowed → allowed: behaves like a write-driven re-fire — diff
1511
+ * against `currentDocData` and suppress if unchanged.
1512
+ */
1513
+ reEvaluateDocListener(record) {
1514
+ if (record.target.kind !== 'doc')
1515
+ return;
1516
+ const result = this.silentReadDoc(record.target.path, record.auth, record.bypassRules);
1517
+ if (!result.allowed) {
1518
+ if (record.errored)
1519
+ return;
1520
+ this.markErrored(record, result.error);
1521
+ return;
1522
+ }
1523
+ if (record.errored) {
1524
+ record.errored = false;
1525
+ const snap = buildDocumentSnapshot(record.target.path, result.data);
1526
+ record.currentSnapshot = snap;
1527
+ record.currentDocData = result.data;
1528
+ try {
1529
+ record.callback(snap);
1530
+ }
1531
+ catch {
1532
+ /* swallow — see fireInitialSnapshot doc */
1533
+ }
1534
+ return;
1535
+ }
1536
+ const prev = record.currentDocData ?? null;
1537
+ if (docDataEqual(prev, result.data))
1538
+ return;
1539
+ const snap = buildDocumentSnapshot(record.target.path, result.data);
1540
+ record.currentSnapshot = snap;
1541
+ record.currentDocData = result.data;
1542
+ try {
1543
+ record.callback(snap);
1544
+ }
1545
+ catch {
1546
+ /* swallow — see fireInitialSnapshot doc */
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Query-listener re-evaluation. Flip semantics mirror the doc path:
1551
+ * {@link silentReadCollection} re-runs the query-proof gate + `list`
1552
+ * rule under the new rules — a query that flipped unprovable/denied
1553
+ * surfaces as a stream error, one that flipped allowed re-delivers,
1554
+ * and the diff against `currentDocs` is computed by the same
1555
+ * `buildQuerySnapshot` path the write-driven notifier uses.
1556
+ */
1557
+ reEvaluateQueryListener(record) {
1558
+ if (record.target.kind !== 'query')
1559
+ return;
1560
+ const result = this.silentReadCollection(record.target.collection, record.auth, record.target.constraints, record.bypassRules);
1561
+ if (!result.allowed) {
1562
+ if (record.errored)
1563
+ return;
1564
+ this.markErrored(record, result.error);
1565
+ return;
1566
+ }
1567
+ if (record.errored) {
1568
+ record.errored = false;
1569
+ // No prevDocs — every readable doc surfaces as `added`, matching
1570
+ // initial-fire semantics. The errored state had no comparable
1571
+ // baseline, so a clean reset is the correct contract.
1572
+ const snap = buildQuerySnapshot({ path: record.target.collection }, result.docs, { excludesMetadataChanges: !record.options.includeMetadataChanges });
1573
+ record.currentSnapshot = snap;
1574
+ record.currentDocs = result.docs;
1575
+ try {
1576
+ record.callback(snap);
1577
+ }
1578
+ catch {
1579
+ /* swallow — see fireInitialSnapshot doc */
1580
+ }
1581
+ return;
1582
+ }
1583
+ const prevDocs = record.currentDocs ?? [];
1584
+ const snap = buildQuerySnapshot({ path: record.target.collection }, result.docs, { excludesMetadataChanges: !record.options.includeMetadataChanges }, prevDocs);
1585
+ const changes = snap.docChanges();
1586
+ if (changes.length === 0)
1587
+ return;
1588
+ record.currentSnapshot = snap;
1589
+ record.currentDocs = result.docs;
1590
+ try {
1591
+ record.callback(snap);
1592
+ }
1593
+ catch {
1594
+ /* swallow — see fireInitialSnapshot doc */
1595
+ }
1596
+ }
1597
+ /** Get current rules source. */
1598
+ getRules() {
1599
+ return this.rulesSource;
1600
+ }
1601
+ // ═══ Read operations (bypass rules — admin access) ═══
1602
+ /** Read a document from local state (admin, no rules). */
1603
+ getDocument(path) {
1604
+ return this.state.get(path);
1605
+ }
1606
+ /**
1607
+ * List documents in a collection (admin, no rules).
1608
+ *
1609
+ * Includes phantom parent docs (records synthesized for any parent path
1610
+ * that has descendants but no stored data of its own). Phantom records
1611
+ * carry `phantom: true` and `data: {}` so the discover crawler — which
1612
+ * walks structure rather than data — sees the same shape live Firestore
1613
+ * would expose. See {@link LocalState#list} for the contract.
1614
+ */
1615
+ listDocuments(collection) {
1616
+ return this.state.list(collection);
1617
+ }
1618
+ /**
1619
+ * Scan documents under a path through the {@link DocStore} seam (admin, no
1620
+ * rules). The query engine gathers candidates with `{ directOnly: true }` for
1621
+ * a collection's real direct children (no phantoms); the discover crawler
1622
+ * still uses {@link listDocuments}, which adds phantom parents.
1623
+ */
1624
+ scanDocuments(prefix, opts) {
1625
+ return this.state.scan(prefix, opts);
1626
+ }
1627
+ /**
1628
+ * Rule-enforced collection read — the query (`getDocs` / `Query.get` /
1629
+ * aggregate) read path for the web-modular + auth-scoped admin-compat
1630
+ * surfaces. **Unlike {@link listDocuments} this evaluates security
1631
+ * rules** (FS-B1 / RULES-B1): query reads must not be a silent total
1632
+ * bypass when single-doc reads (`DocumentReference.get`) are enforced.
1633
+ *
1634
+ * Semantics mirror the listener read path ({@link silentReadCollection}):
1635
+ * 1. RULES-B11 — prove the query against the matched `list` rule
1636
+ * ("rules are not filters"): an unprovable query returns
1637
+ * `{ allowed: false, error }` for the WHOLE query — the caller
1638
+ * throws `permission-denied`. No silent truncation.
1639
+ * 2. Evaluate the `list` rule's residual condition once under `auth`
1640
+ * (with the synthetic representative resource when the proof
1641
+ * pinned doc-data fields). A denial (or simulator error) returns
1642
+ * `{ allowed: false, error }`.
1643
+ * 3. On PASS every candidate is returned — production queries are
1644
+ * governed by the `list` rule alone; per-doc `get` rules do not
1645
+ * filter query results.
1646
+ *
1647
+ * `candidates` is supplied by the caller so collection-group queries
1648
+ * (whose candidate set is a cross-collection scan, not a single
1649
+ * `state.list`) can reuse the same enforcement. `listPath` is the
1650
+ * collection path the `list` rule evaluates against; for
1651
+ * collection-group reads the caller passes the group id's match path.
1652
+ * `query` is the structured `where`/`limit`/`orderBy` view the proof
1653
+ * consumes (the caller still applies the actual row filtering).
1654
+ *
1655
+ * Emits `origin: 'user'` request events (one per `list`) so inspector
1656
+ * consumers see query reads the same way they see writes. UNSUPPORTED
1657
+ * rules still bubble as {@link SimulatorUnsupportedError}.
1658
+ */
1659
+ readQueryCandidates(candidates, listPath, auth, query, bypassRules) {
1660
+ const structured = query ?? {};
1661
+ const requestQuery = listQueryFromStructured(structured);
1662
+ const requestDetail = {
1663
+ ...(bypassRules ? { admin: true } : {}),
1664
+ ...(requestQuery ? { query: requestQuery } : {}),
1665
+ };
1666
+ const detail = Object.keys(requestDetail).length > 0 ? requestDetail : undefined;
1667
+ // Studio admin lens (Gap #2): skip the query-proof gate + `list` rule
1668
+ // eval entirely and return every candidate. The proof model ("rules
1669
+ // are not filters") doesn't apply when rules are off — admin sees the
1670
+ // whole collection. Emit a single `allow` list event so the read still
1671
+ // shows up on the traffic log, mirroring the rule-allowed branch below.
1672
+ if (bypassRules) {
1673
+ this.emitRequest({
1674
+ at: Date.now(), evalMs: 0, method: 'list', path: listPath, auth, result: 'allow',
1675
+ debugMessages: ['admin lens — rules bypassed (Studio Gap #2)'], origin: 'user',
1676
+ ...(detail ? { detail } : {}),
1677
+ });
1678
+ return { allowed: true, docs: candidates };
1679
+ }
1680
+ const readServerTime = Timestamp.fromMillis(Date.now());
1681
+ // List rules match at the document level, so the `list` eval needs a
1682
+ // document-style path with a synthetic placeholder segment (same
1683
+ // convention as silentReadCollection).
1684
+ const placeholderPath = `${listPath}/__listPlaceholder__`;
1685
+ const evalAt = Date.now();
1686
+ const evalStart = performance.now();
1687
+ // ── RULES-B11 gate: prove the query before evaluating the rule. ──
1688
+ const proof = proveListQuery(this.rulesAst(), placeholderPath, auth, structured);
1689
+ if (proof.kind === 'unprovable') {
1690
+ const evalMs = performance.now() - evalStart;
1691
+ const message = `list ${listPath} denied: unprovable query — rules are not filters (${proof.reason})`;
1692
+ this.emitRequest({
1693
+ at: evalAt, evalMs, method: 'list', path: listPath, auth, result: 'deny',
1694
+ debugMessages: [message], origin: 'user',
1695
+ ...(detail ? { detail } : {}),
1696
+ });
1697
+ const error = makeError('permission-denied', message, {
1698
+ request: { method: 'list', path: listPath, auth },
1699
+ });
1700
+ this.emitDenial(error);
1701
+ return { allowed: false, error };
1702
+ }
1703
+ const testCase = this.buildTestCase({ method: 'list', path: placeholderPath, auth }, readServerTime);
1704
+ this.applyListProof(testCase, proof, structured);
1705
+ const simResult = this.simulator.simulate(this.rulesSource, [testCase], {
1706
+ getDoc: (path) => this.state.get(path),
1707
+ });
1708
+ const evalMs = performance.now() - evalStart;
1709
+ if (!simResult.success) {
1710
+ this.emitRequest({
1711
+ at: evalAt, evalMs, method: 'list', path: listPath, auth, result: 'deny',
1712
+ debugMessages: [`Simulation error: ${simResult.error.message}`], origin: 'user',
1713
+ ...(detail ? { detail } : {}),
1714
+ });
1715
+ return {
1716
+ allowed: false,
1717
+ error: makeError('permission-denied', `list ${listPath} simulator error`, {
1718
+ request: { method: 'list', path: listPath, auth },
1719
+ }),
1720
+ };
1721
+ }
1722
+ const result = simResult.data.results[0];
1723
+ if (result.state === 'UNSUPPORTED') {
1724
+ this.emitRequest({
1725
+ at: evalAt, evalMs, method: 'list', path: listPath, auth, result: 'unsupported',
1726
+ debugMessages: renderLegacyDebugMessages(result), origin: 'user',
1727
+ ...(detail ? { detail } : {}),
1728
+ });
1729
+ throw new SimulatorUnsupportedError(unsupportedMessage('list', listPath, renderLegacyDebugMessages(result)), 'list', listPath, renderLegacyDebugMessages(result));
1730
+ }
1731
+ if (result.state !== 'PASSED') {
1732
+ const debugMessages = renderLegacyDebugMessages(result);
1733
+ this.emitRequest({
1734
+ at: evalAt, evalMs, method: 'list', path: listPath, auth, result: 'deny',
1735
+ debugMessages, evaluatedRule: projectEvaluatedRule(result), origin: 'user',
1736
+ ...(detail ? { detail } : {}),
1737
+ });
1738
+ const error = makeError('permission-denied', `list ${listPath} denied by rules`, {
1739
+ request: { method: 'list', path: listPath, auth },
1740
+ });
1741
+ this.emitDenial(error);
1742
+ return { allowed: false, error };
1743
+ }
1744
+ // List allowed — one allow event covers the whole query read.
1745
+ this.emitRequest({
1746
+ at: evalAt, evalMs, method: 'list', path: listPath, auth, result: 'allow',
1747
+ debugMessages: renderLegacyDebugMessages(result),
1748
+ evaluatedRule: projectEvaluatedRule(result), origin: 'user',
1749
+ ...(detail ? { detail } : {}),
1750
+ });
1751
+ // RULES-B11 — no per-doc `get` filtering: the proof + list rule
1752
+ // decided the whole query (prod's model — the old per-doc loop was
1753
+ // the rules-as-filters divergence this replaces).
1754
+ return { allowed: true, docs: candidates };
1755
+ }
1756
+ /**
1757
+ * List root collection IDs derived from the in-memory keyspace.
1758
+ * Used by the discover/crawler adapter so `firestore_discover_paths`
1759
+ * can run against the simulator without hitting live Firestore.
1760
+ */
1761
+ listRootCollections() {
1762
+ return this.state.listRootCollections();
1763
+ }
1764
+ /**
1765
+ * List subcollection IDs underneath the given document path.
1766
+ * Companion to {@link listRootCollections} for the discover/crawler adapter.
1767
+ */
1768
+ listSubcollections(docPath) {
1769
+ return this.state.listSubcollections(docPath);
1770
+ }
1771
+ /** Get full state snapshot. */
1772
+ snapshot() {
1773
+ return this.state.snapshot();
1774
+ }
1775
+ /**
1776
+ * Capture the prior state of just the given paths (for single-write / batch
1777
+ * undo), as `{ path: priorData | null }` where `null` records a doc that did
1778
+ * not exist. The affected-path alternative to a whole-keyspace
1779
+ * {@link snapshot}, so the undo stack stays O(affected) not O(keyspace).
1780
+ * Must be called BEFORE the write applies.
1781
+ */
1782
+ capturePriors(paths) {
1783
+ const priors = {};
1784
+ for (const path of paths) {
1785
+ const prior = this.state.get(path);
1786
+ priors[path] = prior ? { ...prior } : null;
1787
+ }
1788
+ return priors;
1789
+ }
1790
+ // ═══ Write operations (bypass rules — admin access) ═══
1791
+ /**
1792
+ * Replace a document at `path` (admin, no rules). `set` semantics —
1793
+ * creates if absent, overwrites if present, no merge. Wakes any
1794
+ * active listeners attached to `path` so subscriptions see the
1795
+ * change live, mirroring what a rule-allowed `set` would do.
1796
+ */
1797
+ adminSetDocument(path, data) {
1798
+ this.state.set(path, data ?? {});
1799
+ this.notifyListenersForPaths(new Set([path]));
1800
+ }
1801
+ /**
1802
+ * Delete a document at `path` (admin, no rules). Returns
1803
+ * `{ deleted }` reflecting whether a doc was actually removed
1804
+ * (`false` if the path didn't exist). Idempotent — a no-op on a
1805
+ * missing path does not throw. Wakes listeners on `path`.
1806
+ */
1807
+ adminDeleteDocument(path) {
1808
+ const r = this.state.delete(path);
1809
+ if (r.success) {
1810
+ this.notifyListenersForPaths(new Set([path]));
1811
+ }
1812
+ return { deleted: r.success };
1813
+ }
1814
+ /**
1815
+ * Run the rules engine for the given test cases — UNLESS `bypassRules`
1816
+ * is set, in which case the rules engine is skipped entirely and a
1817
+ * synthetic all-ALLOW result is returned (Pyric Studio Gap #2 admin
1818
+ * lens). Every `simulate()` call site in `execute` / `batch` /
1819
+ * `transaction` routes through here so the bypass is centralized and
1820
+ * the rules-enforced path is byte-for-byte unchanged when `bypassRules`
1821
+ * is absent/false.
1822
+ *
1823
+ * The synthetic result mirrors the engine's success shape
1824
+ * (`{ success: true, data: { results, passed, failed, unsupported } }`)
1825
+ * with one PASSED entry per test case, so callers that read
1826
+ * `simResult.data.results[i]` see a normal ALLOW with no special-casing.
1827
+ */
1828
+ runSimulate(testCases, bypassRules, batchProjection) {
1829
+ if (bypassRules) {
1830
+ const results = testCases.map((tc) => adminBypassResult(tc.description));
1831
+ return {
1832
+ success: true,
1833
+ data: { passed: results.length, failed: 0, unsupported: 0, results },
1834
+ };
1835
+ }
1836
+ return this.simulator.simulate(this.rulesSource, testCases, {
1837
+ getDoc: (path) => this.state.get(path),
1838
+ ...(batchProjection ? { batchProjection } : {}),
1839
+ });
1840
+ }
1841
+ /**
1842
+ * getafter-batch fix — build the shared post-commit projection for an
1843
+ * atomic batch/transaction, ONCE, before evaluating any per-op rule.
1844
+ * Every op in `testCases` gets folded in: `create`/`update` project to
1845
+ * the full post-write document (already merged by `buildTestCase`),
1846
+ * `delete` projects to `null` (doc gone). `get`/`list` ops don't write
1847
+ * and are skipped — they never change what `getAfter` should see.
1848
+ *
1849
+ * Passing the SAME map into every per-op `simulate()` call for the group
1850
+ * is what lets doc A's rule see doc B's pending write via `getAfter(B)`
1851
+ * — mirrors the RTDB rules multi-path projection (one shared tree built
1852
+ * up front, read by every path's rule eval) applied to Firestore's
1853
+ * per-document `getAfter()`.
1854
+ */
1855
+ buildBatchProjection(testCases) {
1856
+ const projection = new Map();
1857
+ for (const tc of testCases) {
1858
+ if (tc.method === 'get' || tc.method === 'list')
1859
+ continue;
1860
+ projection.set(tc.path, tc.method === 'delete' ? null : (tc.data ?? {}));
1861
+ }
1862
+ return projection;
1863
+ }
1864
+ // ═══ Single operation (rules evaluated) ═══
1865
+ /** Execute a single operation. Rules are evaluated against local state.
1866
+ * When `operation.bypassRules` is set, rule evaluation is skipped (admin
1867
+ * lens — Studio Gap #2): the op is treated as ALLOW and routed through
1868
+ * the same apply + emit path, so structural preconditions, events, and
1869
+ * listeners behave exactly as a rule-allowed op would. */
1870
+ execute(operation) {
1871
+ const { method, path, auth, data, autoId, requestTime: pinnedRequestTime, merge, bypassRules } = operation;
1872
+ const detail = bypassRules ? { admin: true } : undefined;
1873
+ // Reads — evaluate rules (denied reads return no data)
1874
+ if (method === 'get' || method === 'list') {
1875
+ // No data to resolve on reads, but still pin a serverTime so the
1876
+ // handler's `request.time` is deterministic relative to anything
1877
+ // observed by debug messages (Item 1).
1878
+ const readServerTime = Timestamp.fromMillis(Date.now());
1879
+ const testCase = this.buildTestCase(operation, readServerTime);
1880
+ // Issue #307 — time the simulate call for RequestEvent.evalMs.
1881
+ const evalAt = Date.now();
1882
+ const evalStart = performance.now();
1883
+ const simResult = this.runSimulate([testCase], bypassRules);
1884
+ const evalMs = performance.now() - evalStart;
1885
+ if (!simResult.success) {
1886
+ const event = this.eventLog.append({
1887
+ type: 'single', method, path, auth: auth ? { uid: auth.uid } : null,
1888
+ allowed: false, debugMessages: [`Simulation error: ${simResult.error.message}`],
1889
+ });
1890
+ // Issue #307 — simulator failures are still requests worth surfacing.
1891
+ this.emitRequest({
1892
+ at: evalAt, evalMs, method, path, auth, result: 'deny',
1893
+ debugMessages: [`Simulation error: ${simResult.error.message}`],
1894
+ origin: 'user',
1895
+ ...(detail ? { detail } : {}),
1896
+ });
1897
+ return { allowed: false, debugMessages: [simResult.error.message], event };
1898
+ }
1899
+ const result = simResult.data.results[0];
1900
+ if (result.state === 'UNSUPPORTED') {
1901
+ // Issue #307 — surface the eval-time event BEFORE throwing so
1902
+ // subscribers see the unsupported request alongside everything else.
1903
+ this.emitRequest({
1904
+ at: evalAt, evalMs, method, path, auth, result: 'unsupported',
1905
+ debugMessages: renderLegacyDebugMessages(result), origin: 'user',
1906
+ ...(detail ? { detail } : {}),
1907
+ });
1908
+ throw new SimulatorUnsupportedError(unsupportedMessage(method, path, renderLegacyDebugMessages(result)), method, path, renderLegacyDebugMessages(result));
1909
+ }
1910
+ const isAllowed = result.state === 'PASSED';
1911
+ let readData;
1912
+ if (isAllowed) {
1913
+ readData = method === 'get' ? this.state.get(path) : this.state.list(path);
1914
+ }
1915
+ const event = this.eventLog.append({
1916
+ type: 'single', method, path, auth: auth ? { uid: auth.uid } : null,
1917
+ allowed: isAllowed, debugMessages: renderLegacyDebugMessages(result),
1918
+ });
1919
+ // Item 6: reads only fail with permission-denied (no structural
1920
+ // not-found here — read of a missing doc is allowed-with-empty
1921
+ // by Firestore's contract; the rule decides visibility).
1922
+ const out = {
1923
+ allowed: isAllowed,
1924
+ data: isAllowed ? readData : undefined,
1925
+ debugMessages: renderLegacyDebugMessages(result),
1926
+ event,
1927
+ };
1928
+ if (!isAllowed) {
1929
+ // Item 6+: surface the eval-time request + resource on the
1930
+ // error so callers (sandbox / playground) can render a "why
1931
+ // did this denial happen" frame without re-deriving state.
1932
+ // For `list`, `resource` is intentionally omitted — the rule
1933
+ // evaluated against a collection, not a single doc.
1934
+ const reqRead = { method, path, auth };
1935
+ const resRead = method === 'get'
1936
+ ? { data: this.state.get(path), exists: this.state.get(path) !== null }
1937
+ : undefined;
1938
+ out.error = makeError('permission-denied', `${method} ${path} denied by rules`, { request: reqRead, ...(resRead ? { resource: resRead } : {}) });
1939
+ this.emitDenial(out.error);
1940
+ }
1941
+ // Issue #307 — emit the request event for every read, allow or deny.
1942
+ // resourceBefore mirrors what the rule saw on `resource`: populated for
1943
+ // `get` (the single doc); omitted for `list` (the rule didn't evaluate
1944
+ // against a single resource).
1945
+ this.emitRequest({
1946
+ at: evalAt, evalMs, method, path, auth,
1947
+ result: isAllowed ? 'allow' : 'deny',
1948
+ debugMessages: renderLegacyDebugMessages(result),
1949
+ evaluatedRule: projectEvaluatedRule(result),
1950
+ origin: 'user',
1951
+ ...(method === 'get'
1952
+ ? { resourceBefore: { data: this.state.get(path), exists: this.state.get(path) !== null } }
1953
+ : {}),
1954
+ ...(detail ? { detail } : {}),
1955
+ });
1956
+ return out;
1957
+ }
1958
+ // Write operations: evaluate rules. Capture only this path's prior state
1959
+ // for undo (single write touches one doc); `snapshot[path]` reads below stay
1960
+ // valid since the affected path is present, and undo stays O(1) not O(keyspace).
1961
+ const snapshot = this.capturePriors([path]);
1962
+ // Item 1: pin a single serverTime for this write. Both the resolver
1963
+ // (for any serverTimestamp sentinels in `data`) and the handler (for
1964
+ // `request.time`) must see field-equal values, otherwise rules like
1965
+ // `data.createdAt == request.time` flake on sub-millisecond drift.
1966
+ // Replay engine: `operation.requestTime` (when provided) overrides
1967
+ // Date.now() so the rule eval re-evaluates against the captured
1968
+ // wall-clock instant, eliminating time-drift on replay.
1969
+ const serverTime = pinnedRequestTime ?? Timestamp.fromMillis(Date.now());
1970
+ // Resolve the write payload BEFORE rule evaluation so rules see the
1971
+ // same shape storage will see (Item 0: write-boundary value-resolve).
1972
+ // LocalState will resolve again in applyWrite — converters are
1973
+ // required to be idempotent so the second pass is a no-op.
1974
+ //
1975
+ // Item 2: a converter (e.g., `increment` against a string-typed
1976
+ // prior) may throw. Surface as a denial — the agent's rule was
1977
+ // never given a chance to evaluate, but the operation is rejected.
1978
+ let resolvedData;
1979
+ try {
1980
+ resolvedData = data
1981
+ ? resolveValueTree({ ...data }, {
1982
+ path,
1983
+ method: method,
1984
+ prior: this.state.get(path),
1985
+ serverTime,
1986
+ })
1987
+ : data;
1988
+ // FS-B13 — `deleteField()` may only appear at the top level of an
1989
+ // `update` (whole field value or dot-path key); nested in a map
1990
+ // literal it is invalid and prod throws `invalid-argument` rather than
1991
+ // silently destroying the sibling map. (`set`/`create` without merge
1992
+ // resolve deleteField via partitionDeletes, which the dispatch below
1993
+ // handles; the merge path adds it to the field mask.)
1994
+ if (method === 'update' && resolvedData) {
1995
+ assertNoNestedDeleteField(resolvedData);
1996
+ }
1997
+ }
1998
+ catch (e) {
1999
+ const msg = e.message;
2000
+ const event = this.eventLog.append({
2001
+ type: 'single', method, path, auth: auth ? { uid: auth.uid } : null,
2002
+ data, allowed: false, priorDocs: snapshot,
2003
+ debugMessages: [`FieldValue resolve error: ${msg}`],
2004
+ });
2005
+ // Issue #307 — sentinel-resolution failures never reached the rules
2006
+ // engine but the user's op still produced a denial. evalMs is 0
2007
+ // because no simulate call happened.
2008
+ this.emitRequest({
2009
+ at: Date.now(), evalMs: 0, method, path, auth, result: 'deny',
2010
+ debugMessages: [`FieldValue resolve error: ${msg}`],
2011
+ ...(resolvedData ? { resourceData: resolvedData } : data ? { resourceData: data } : {}),
2012
+ resourceBefore: { data: snapshot[path] ?? null, exists: (snapshot[path] ?? null) !== null },
2013
+ origin: 'user',
2014
+ ...(detail ? { detail } : {}),
2015
+ });
2016
+ // Item 6: a sentinel-resolution throw maps to `invalid-argument`.
2017
+ // The admin SDK throws the same code when a FieldValue is malformed
2018
+ // for the prior data shape (e.g., increment on a non-number).
2019
+ return {
2020
+ allowed: false,
2021
+ debugMessages: [msg],
2022
+ event,
2023
+ error: makeError('invalid-argument', msg),
2024
+ };
2025
+ }
2026
+ const testCase = this.buildTestCase({ ...operation, data: resolvedData }, serverTime);
2027
+ // Issue #307 — time the simulate call for RequestEvent.evalMs.
2028
+ const evalAt = Date.now();
2029
+ const evalStart = performance.now();
2030
+ const simResult = this.runSimulate([testCase], bypassRules);
2031
+ const evalMs = performance.now() - evalStart;
2032
+ if (!simResult.success) {
2033
+ const event = this.eventLog.append({
2034
+ type: 'single', method, path, auth: auth ? { uid: auth.uid } : null,
2035
+ data: resolvedData, allowed: false, priorDocs: snapshot,
2036
+ debugMessages: [`Simulation error: ${simResult.error.message}`],
2037
+ });
2038
+ this.emitRequest({
2039
+ at: evalAt, evalMs, method, path, auth, result: 'deny',
2040
+ debugMessages: [`Simulation error: ${simResult.error.message}`],
2041
+ ...(data ? { resourceData: data } : {}),
2042
+ resourceBefore: { data: snapshot[path] ?? null, exists: (snapshot[path] ?? null) !== null },
2043
+ origin: 'user',
2044
+ ...(detail ? { detail } : {}),
2045
+ });
2046
+ // Item 6: a simulator-internal failure isn't a rules denial — map
2047
+ // it to invalid-argument so callers can distinguish "the rule
2048
+ // text or test case is wrong" from "the rule denied your write".
2049
+ return {
2050
+ allowed: false,
2051
+ debugMessages: [simResult.error.message],
2052
+ event,
2053
+ error: makeError('invalid-argument', simResult.error.message),
2054
+ };
2055
+ }
2056
+ const result = simResult.data.results[0];
2057
+ if (result.state === 'UNSUPPORTED') {
2058
+ this.emitRequest({
2059
+ at: evalAt, evalMs, method, path, auth, result: 'unsupported',
2060
+ debugMessages: renderLegacyDebugMessages(result),
2061
+ ...(data ? { resourceData: data } : {}),
2062
+ resourceBefore: { data: snapshot[path] ?? null, exists: (snapshot[path] ?? null) !== null },
2063
+ origin: 'user',
2064
+ ...(detail ? { detail } : {}),
2065
+ });
2066
+ throw new SimulatorUnsupportedError(unsupportedMessage(method, path, renderLegacyDebugMessages(result)), method, path, renderLegacyDebugMessages(result));
2067
+ }
2068
+ // The simulation returns PASSED if the outcome matches the expectation.
2069
+ // Since we always set expectation to ALLOW, PASSED = allowed, FAILED = denied.
2070
+ let isAllowed = result.state === 'PASSED';
2071
+ let writeError = null;
2072
+ if (isAllowed) {
2073
+ // Item 6: rules said yes; the keyspace may still say no (create-
2074
+ // already-exists, update/delete-missing). applyWrite returns the
2075
+ // structural error if so. Demote `allowed` and surface the code
2076
+ // — matches prod, which evaluates rules then preconditions and
2077
+ // returns the precondition error when it loses.
2078
+ writeError = this.applyWrite(method, path, resolvedData, merge);
2079
+ if (writeError)
2080
+ isAllowed = false;
2081
+ }
2082
+ const event = this.eventLog.append({
2083
+ type: 'single', method, path, auth: auth ? { uid: auth.uid } : null,
2084
+ data: resolvedData, allowed: isAllowed, priorDocs: isAllowed ? snapshot : undefined,
2085
+ debugMessages: renderLegacyDebugMessages(result),
2086
+ });
2087
+ const out = {
2088
+ allowed: isAllowed,
2089
+ debugMessages: renderLegacyDebugMessages(result),
2090
+ event,
2091
+ };
2092
+ if (!isAllowed) {
2093
+ // Structural error wins over a synthesized permission-denied —
2094
+ // it's the more specific signal. The structural-error branch
2095
+ // skips eval context (already-exists / not-found don't depend on
2096
+ // auth or resource shape).
2097
+ if (writeError) {
2098
+ out.error = writeError;
2099
+ }
2100
+ else {
2101
+ const priorDoc = snapshot[path] ?? null;
2102
+ // `set` denials surface under the rule clause that actually
2103
+ // ran — `create` for absent docs, `update` for existing ones
2104
+ // — so downstream consumers reading `error.request.method`
2105
+ // see the same value the rules engine saw.
2106
+ const evalMethod = method === 'set'
2107
+ ? (priorDoc !== null ? 'update' : 'create')
2108
+ : method;
2109
+ out.error = makeError('permission-denied', `${method} ${path} denied by rules`, {
2110
+ request: {
2111
+ method: evalMethod,
2112
+ path,
2113
+ auth,
2114
+ ...(data ? { resourceData: data } : {}),
2115
+ },
2116
+ resource: { data: priorDoc, exists: priorDoc !== null },
2117
+ });
2118
+ this.emitDenial(out.error);
2119
+ }
2120
+ }
2121
+ // Issue #307 — emit the request event before fan-out so subscribers
2122
+ // see the user-origin event before any listener-origin events that
2123
+ // notifyListenersForPaths will spawn. resourceAfter is the post-write
2124
+ // state when the write committed; for denials/structural-errors it's
2125
+ // the unchanged prior (matches what callers see on rollback).
2126
+ const priorDoc = snapshot[path] ?? null;
2127
+ const finalDoc = isAllowed ? this.state.get(path) : priorDoc;
2128
+ this.emitRequest({
2129
+ at: evalAt, evalMs, method, path, auth,
2130
+ result: isAllowed ? 'allow' : 'deny',
2131
+ debugMessages: renderLegacyDebugMessages(result),
2132
+ evaluatedRule: projectEvaluatedRule(result),
2133
+ ...(data ? { resourceData: data } : {}),
2134
+ resourceBefore: { data: priorDoc, exists: priorDoc !== null },
2135
+ ...(method !== 'delete'
2136
+ ? { resourceAfter: { data: finalDoc, exists: finalDoc !== null } }
2137
+ : { resourceAfter: { data: null, exists: false } }),
2138
+ origin: 'user',
2139
+ ...(detail ? { detail } : {}),
2140
+ });
2141
+ // Issue #307 — emit a committed-write event for the post-apply state.
2142
+ // Only fires on successful commit; rule denials and structural errors
2143
+ // surface as the request-deny RequestEvent above. `method` is already
2144
+ // narrowed to write verbs by this point (reads return earlier).
2145
+ if (isAllowed) {
2146
+ // Sentinels extracted from the PRE-resolution `data` (in scope from
2147
+ // the operation destructure); needed for replay so the engine can
2148
+ // re-issue the same FieldValue.* markers without consulting the
2149
+ // resolved values.
2150
+ const sentinels = data ? walkForSentinels(data) : undefined;
2151
+ // Auto-id signal: createWithAutoId sets operation.autoId=true.
2152
+ // The last path segment IS the minted id; capture it so replay
2153
+ // mints a fresh one.
2154
+ const mintedAutoId = autoId && method === 'create' ? path.split('/').pop() : undefined;
2155
+ this.emitWrite({
2156
+ method: method,
2157
+ path,
2158
+ auth,
2159
+ ...(method !== 'delete' && data ? { data } : {}),
2160
+ priorState: priorDoc,
2161
+ nextState: method === 'delete' ? null : finalDoc,
2162
+ ...(sentinels && sentinels.length > 0 ? { sentinels } : {}),
2163
+ ...(mintedAutoId ? { autoId: mintedAutoId } : {}),
2164
+ requestTime: serverTime,
2165
+ ...(detail ? { detail } : {}),
2166
+ });
2167
+ }
2168
+ // Slice 3 — fan out the write to any matching snapshot listeners.
2169
+ // Only fires on a successful commit; rule denials and structural
2170
+ // errors leave state unchanged so listeners have nothing to see.
2171
+ // Method-aware: list/get never reach this branch (the early
2172
+ // read-return above), so anything getting here is a write whose
2173
+ // path is the touched key.
2174
+ if (isAllowed) {
2175
+ // Issue #307 — set the trigger so listener re-eval emits can
2176
+ // attribute themselves to this user op via `triggeredBy`.
2177
+ // Save/restore (not clear-on-finally) because a listener callback
2178
+ // may itself call execute() — that nested call's finally would
2179
+ // otherwise wipe our trigger before subsequent listeners fire.
2180
+ const prevTrigger = this.currentTrigger;
2181
+ this.currentTrigger = { method, path };
2182
+ try {
2183
+ this.notifyListenersForPaths(new Set([path]));
2184
+ }
2185
+ finally {
2186
+ this.currentTrigger = prevTrigger;
2187
+ }
2188
+ }
2189
+ return out;
2190
+ }
2191
+ // ═══ Auto-ID create ═══
2192
+ /**
2193
+ * Item 7 — `addDoc()`-style create with a Firestore-compatible auto ID.
2194
+ *
2195
+ * Mirrors the live SDK's `addDoc(collection(db, c), data)` flow: mint a
2196
+ * 20-char alphanumeric document ID, append it to the collection path,
2197
+ * then run the same `execute({ method: 'create', ... })` pipeline that
2198
+ * an explicit-ID create would (rules, sentinel resolution, applyWrite).
2199
+ * The minted path is returned so callers can re-read the doc without
2200
+ * having to capture the ID via a side channel.
2201
+ */
2202
+ createWithAutoId(collection, data, auth, bypassRules) {
2203
+ const trimmed = collection.endsWith('/') ? collection.slice(0, -1) : collection;
2204
+ const id = generateAutoId();
2205
+ const path = `${trimmed}/${id}`;
2206
+ // Signal that this create came via auto-id minting so emitWrite
2207
+ // populates WriteSandboxEvent.autoId. The replay engine reads this
2208
+ // to know the path's last segment should alias to a fresh mint on
2209
+ // replay rather than reuse the original ID.
2210
+ const result = this.execute({ method: 'create', path, auth, data, autoId: true, bypassRules });
2211
+ return { path, result };
2212
+ }
2213
+ // ═══ Batch operations ═══
2214
+ /** Execute multiple writes atomically. All must pass rules or none apply. */
2215
+ batch(operations, auth, bypassRules) {
2216
+ const detail = bypassRules ? { admin: true } : undefined;
2217
+ // Capture priors for just the operations' paths (undo is O(affected)).
2218
+ const snapshot = this.capturePriors(operations.map((o) => o.path));
2219
+ const results = [];
2220
+ // Item 1: one serverTime for the whole batch — all sentinels and
2221
+ // every per-op `request.time` resolve to the same wall-clock instant.
2222
+ const serverTime = Timestamp.fromMillis(Date.now());
2223
+ // Issue #307 — shared groupId so the consumer can fold sub-ops into
2224
+ // a single batch row.
2225
+ const groupId = `batch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
2226
+ // Track per-op events to emit (one per resolved op). We build them
2227
+ // lazily and dispatch after applyBatch so resourceAfter reflects the
2228
+ // committed (or rolled-back) state, matching execute()'s ordering.
2229
+ const pendingEmits = [];
2230
+ // Resolve every op's payload up front against CURRENT state (no
2231
+ // cross-visibility, mirroring how the rules pass evaluates them).
2232
+ // Item 0: write-boundary value-resolve. Item 2: sentinels in batch
2233
+ // ops resolve against the right prior; a converter throw rejects
2234
+ // the whole batch (atomic semantics).
2235
+ const resolvedOps = [];
2236
+ for (const op of operations) {
2237
+ try {
2238
+ resolvedOps.push({
2239
+ ...op,
2240
+ data: op.data
2241
+ ? resolveValueTree({ ...op.data }, {
2242
+ path: op.path,
2243
+ method: op.method,
2244
+ prior: this.state.get(op.path),
2245
+ serverTime,
2246
+ })
2247
+ : op.data,
2248
+ });
2249
+ }
2250
+ catch (e) {
2251
+ const msg = e.message;
2252
+ const event = this.eventLog.append({
2253
+ type: 'batch', method: 'batch', path: '',
2254
+ auth: auth ? { uid: auth.uid } : null,
2255
+ allowed: false,
2256
+ operations: operations.map((o) => ({
2257
+ method: o.method, path: o.path, data: o.data, allowed: false,
2258
+ })),
2259
+ debugMessages: [`FieldValue resolve error on '${op.path}': ${msg}`],
2260
+ });
2261
+ // Issue #307 — emit the failing op (and only the failing op;
2262
+ // earlier ops in the loop succeeded and their events were
2263
+ // queued, later ops never reached evaluation).
2264
+ this.emitRequest({
2265
+ at: Date.now(), evalMs: 0,
2266
+ method: op.method, path: op.path, auth, result: 'deny',
2267
+ debugMessages: [`FieldValue resolve error: ${msg}`],
2268
+ ...(op.data ? { resourceData: op.data } : {}),
2269
+ resourceBefore: { data: snapshot[op.path] ?? null, exists: (snapshot[op.path] ?? null) !== null },
2270
+ origin: 'batch', groupId,
2271
+ ...(detail ? { detail } : {}),
2272
+ });
2273
+ // Item 6: same code as the single-op resolver throw —
2274
+ // invalid-argument is the admin-SDK signal for malformed
2275
+ // FieldValue. The whole batch rolls back atomically; only the
2276
+ // failing op gets the per-op error attached.
2277
+ const batchError = makeError('invalid-argument', msg);
2278
+ return {
2279
+ allowed: false,
2280
+ results: operations.map((o) => ({
2281
+ path: o.path,
2282
+ allowed: false,
2283
+ debugMessages: [msg],
2284
+ ...(o.path === op.path ? { error: batchError } : {}),
2285
+ })),
2286
+ event,
2287
+ error: batchError,
2288
+ };
2289
+ }
2290
+ }
2291
+ // Evaluate rules for each operation. `request`/`resource` (the doc's
2292
+ // OWN pre/post state) still resolve against CURRENT pre-batch state —
2293
+ // no cross-visibility there, matching how request.resource.data works
2294
+ // in production. `getAfter()` on a SIBLING doc is different: it must
2295
+ // see this batch's other pending writes, so we build one shared
2296
+ // post-commit projection up front (getafter-batch fix) and hand the
2297
+ // same map to every op's simulate() call below.
2298
+ const batchTestCases = resolvedOps.map((op) => this.buildTestCase({ method: op.method, path: op.path, auth, data: op.data }, serverTime));
2299
+ const batchProjection = this.buildBatchProjection(batchTestCases);
2300
+ let allAllowed = true;
2301
+ for (let i = 0; i < resolvedOps.length; i++) {
2302
+ const op = resolvedOps[i];
2303
+ // Pre-resolution payload from the original operations array (parallel
2304
+ // to resolvedOps by index). Emitted on RequestEvent/WriteSandboxEvent
2305
+ // so consumers see the user's INTENT (with FieldValue.* markers),
2306
+ // not the materialized values.
2307
+ const preData = operations[i]?.data;
2308
+ const testCase = batchTestCases[i];
2309
+ const evalAt = Date.now();
2310
+ const evalStart = performance.now();
2311
+ const simResult = this.runSimulate([testCase], bypassRules, batchProjection);
2312
+ const evalMs = performance.now() - evalStart;
2313
+ if (!simResult.success) {
2314
+ // Item 6: per-op simulator failure — same invalid-argument signal
2315
+ // as the single-op path uses.
2316
+ results.push({
2317
+ path: op.path,
2318
+ allowed: false,
2319
+ debugMessages: [simResult.error.message],
2320
+ error: makeError('invalid-argument', simResult.error.message),
2321
+ });
2322
+ pendingEmits.push({
2323
+ at: evalAt, evalMs, method: op.method, path: op.path, auth,
2324
+ result: 'deny',
2325
+ debugMessages: [`Simulation error: ${simResult.error.message}`],
2326
+ ...(preData ? { resourceData: preData } : {}),
2327
+ resourceBefore: { data: snapshot[op.path] ?? null, exists: (snapshot[op.path] ?? null) !== null },
2328
+ origin: 'batch', groupId,
2329
+ ...(detail ? { detail } : {}),
2330
+ });
2331
+ allAllowed = false;
2332
+ continue;
2333
+ }
2334
+ const r = simResult.data.results[0];
2335
+ if (r.state === 'UNSUPPORTED') {
2336
+ // Emit the unsupported event before throwing — same contract as execute().
2337
+ this.emitRequest({
2338
+ at: evalAt, evalMs, method: op.method, path: op.path, auth,
2339
+ result: 'unsupported', debugMessages: renderLegacyDebugMessages(r),
2340
+ ...(preData ? { resourceData: preData } : {}),
2341
+ resourceBefore: { data: snapshot[op.path] ?? null, exists: (snapshot[op.path] ?? null) !== null },
2342
+ origin: 'batch', groupId,
2343
+ ...(detail ? { detail } : {}),
2344
+ });
2345
+ throw new SimulatorUnsupportedError(unsupportedMessage(op.method, op.path, renderLegacyDebugMessages(r)), op.method, op.path, renderLegacyDebugMessages(r));
2346
+ }
2347
+ const isAllowed = r.state === 'PASSED';
2348
+ const entry = {
2349
+ path: op.path,
2350
+ allowed: isAllowed,
2351
+ debugMessages: renderLegacyDebugMessages(r),
2352
+ };
2353
+ if (!isAllowed) {
2354
+ // Item 6: rule denied this op — permission-denied. Structural
2355
+ // errors are surfaced separately below if rules pass. The
2356
+ // per-op `request`/`resource` is captured against the pre-batch
2357
+ // snapshot since rules eval has no inter-write visibility
2358
+ // (matches `batch()` semantics).
2359
+ const priorDoc = snapshot[op.path] ?? null;
2360
+ entry.error = makeError('permission-denied', `${op.method} ${op.path} denied by rules`, {
2361
+ request: {
2362
+ method: op.method,
2363
+ path: op.path,
2364
+ auth,
2365
+ ...(preData ? { resourceData: preData } : {}),
2366
+ },
2367
+ resource: { data: priorDoc, exists: priorDoc !== null },
2368
+ });
2369
+ this.emitDenial(entry.error);
2370
+ allAllowed = false;
2371
+ }
2372
+ // Issue #307 — queue per-op event. resourceAfter is filled in
2373
+ // below once we know whether applyBatch committed (allAllowed) or
2374
+ // rolled back.
2375
+ pendingEmits.push({
2376
+ at: evalAt, evalMs, method: op.method, path: op.path, auth,
2377
+ result: isAllowed ? 'allow' : 'deny',
2378
+ debugMessages: renderLegacyDebugMessages(r),
2379
+ ...(preData ? { resourceData: preData } : {}),
2380
+ resourceBefore: { data: snapshot[op.path] ?? null, exists: (snapshot[op.path] ?? null) !== null },
2381
+ origin: 'batch', groupId,
2382
+ ...(detail ? { detail } : {}),
2383
+ });
2384
+ results.push(entry);
2385
+ }
2386
+ // Apply all or none
2387
+ let batchStructuralError = null;
2388
+ if (allAllowed) {
2389
+ const batchOps = resolvedOps.map(op => ({
2390
+ method: op.method,
2391
+ path: op.path,
2392
+ data: op.data,
2393
+ }));
2394
+ const batchResult = this.state.applyBatch(batchOps);
2395
+ if (!batchResult.success) {
2396
+ allAllowed = false;
2397
+ // Item 6: applyBatch returns indexed structural errors. Map the
2398
+ // first one and pin it to the offending per-op result. Mirrors
2399
+ // single-op precondition mapping (create→already-exists,
2400
+ // update/delete→not-found).
2401
+ const first = batchResult.errors?.[0];
2402
+ if (first !== undefined) {
2403
+ const failingOp = resolvedOps[first.index];
2404
+ const code = failingOp?.method === 'create' ? 'already-exists' : 'not-found';
2405
+ batchStructuralError = makeError(code, first.error);
2406
+ // Demote the per-op result for the offender — its rules said
2407
+ // PASSED but the keyspace overruled.
2408
+ const failingResult = results[first.index];
2409
+ if (failingResult) {
2410
+ failingResult.allowed = false;
2411
+ failingResult.error = batchStructuralError;
2412
+ }
2413
+ }
2414
+ }
2415
+ }
2416
+ const event = this.eventLog.append({
2417
+ type: 'batch', method: 'batch', path: '',
2418
+ auth: auth ? { uid: auth.uid } : null,
2419
+ allowed: allAllowed,
2420
+ priorDocs: allAllowed ? snapshot : undefined,
2421
+ operations: resolvedOps.map((op, i) => ({
2422
+ method: op.method, path: op.path, data: op.data,
2423
+ allowed: results[i]?.allowed ?? false,
2424
+ })),
2425
+ debugMessages: allAllowed ? ['Batch committed'] : ['Batch rolled back — one or more operations denied'],
2426
+ });
2427
+ // Item 6: top-level batch error — pick the first per-op error if
2428
+ // any, or a structural error if rules passed but applyBatch rejected.
2429
+ let topError;
2430
+ if (!allAllowed) {
2431
+ topError =
2432
+ batchStructuralError ??
2433
+ results.find((r) => r.error)?.error ??
2434
+ makeError('permission-denied', 'Batch denied');
2435
+ }
2436
+ // Issue #307 — flush per-op events now that applyBatch has decided.
2437
+ // resourceAfter reflects the post-commit state on success; for
2438
+ // rollbacks (allAllowed false, or structural error demoting a
2439
+ // PASSED op) it mirrors the prior — no change happened. Delete
2440
+ // ops always end up exists:false on commit; on rollback they revert.
2441
+ for (let i = 0; i < pendingEmits.length; i++) {
2442
+ const e = pendingEmits[i];
2443
+ if (!e)
2444
+ continue;
2445
+ const opCommitted = allAllowed && results[i]?.allowed === true;
2446
+ if (opCommitted) {
2447
+ const finalDoc = this.state.get(e.path);
2448
+ if (e.method !== 'delete') {
2449
+ e.resourceAfter = { data: finalDoc, exists: finalDoc !== null };
2450
+ }
2451
+ else {
2452
+ e.resourceAfter = { data: null, exists: false };
2453
+ }
2454
+ }
2455
+ else {
2456
+ // rollback or structural-error demotion — state didn't change.
2457
+ const priorDoc = snapshot[e.path] ?? null;
2458
+ e.resourceAfter = { data: priorDoc, exists: priorDoc !== null };
2459
+ }
2460
+ this.emitRequest(e);
2461
+ // Issue #307 — committed-write event for sub-ops that actually
2462
+ // applied. Mirrors the per-sub-op groupId on the RequestEvent.
2463
+ if (opCommitted && e.method !== 'get' && e.method !== 'list') {
2464
+ const priorDoc = snapshot[e.path] ?? null;
2465
+ // Sentinels: walk the PRE-resolution data from `operations[i]`
2466
+ // (parallel to resolvedOps and pendingEmits — built in order
2467
+ // earlier in this method).
2468
+ const preOp = operations[i];
2469
+ const sentinels = preOp && 'data' in preOp && preOp.data ? walkForSentinels(preOp.data) : undefined;
2470
+ this.emitWrite({
2471
+ method: e.method,
2472
+ path: e.path,
2473
+ auth,
2474
+ ...(e.method !== 'delete' && e.resourceData ? { data: e.resourceData } : {}),
2475
+ priorState: priorDoc,
2476
+ nextState: e.method === 'delete' ? null : this.state.get(e.path),
2477
+ ...(e.groupId ? { groupId: e.groupId, groupKind: 'batch' } : {}),
2478
+ ...(sentinels && sentinels.length > 0 ? { sentinels } : {}),
2479
+ requestTime: serverTime,
2480
+ ...(detail ? { detail } : {}),
2481
+ });
2482
+ }
2483
+ }
2484
+ // Slice 3 — fan out batch writes to listeners. Single fire after
2485
+ // commit (matches the Slice 5 design — fire-once-per-batch is what
2486
+ // we want long-term; doing it here means Slice 5 only needs to
2487
+ // hoist the call point, not invent it). Skipped on rollback —
2488
+ // nothing in `state` actually changed.
2489
+ if (allAllowed) {
2490
+ const touched = new Set();
2491
+ for (const op of resolvedOps)
2492
+ touched.add(op.path);
2493
+ // Issue #307 — listener re-evals during this fan-out attribute
2494
+ // themselves to the batch as a whole. Path is the first sub-op
2495
+ // (best-effort — batches touch N paths, the UI can join via groupId
2496
+ // if it needs to show the full set).
2497
+ const firstOp = resolvedOps[0];
2498
+ const prevTrigger = this.currentTrigger;
2499
+ this.currentTrigger = firstOp
2500
+ ? { method: 'batch', path: firstOp.path }
2501
+ : { method: 'batch', path: '' };
2502
+ try {
2503
+ this.notifyListenersForPaths(touched);
2504
+ }
2505
+ finally {
2506
+ this.currentTrigger = prevTrigger;
2507
+ }
2508
+ }
2509
+ return {
2510
+ allowed: allAllowed,
2511
+ results,
2512
+ event,
2513
+ ...(topError ? { error: topError } : {}),
2514
+ };
2515
+ }
2516
+ transaction(fn, options) {
2517
+ const auth = options.auth;
2518
+ const snapshot = this.state.snapshot();
2519
+ const reader = (path) => this.state.get(path);
2520
+ const ctx = new TransactionContext(reader);
2521
+ // ─── Step 2 — run the callback ───────────────────────────────────
2522
+ let cbResult;
2523
+ try {
2524
+ cbResult = fn(ctx);
2525
+ }
2526
+ catch (e) {
2527
+ // Sync throw before any await: log + re-throw immediately.
2528
+ this.logAbortedTransaction(ctx, auth, e);
2529
+ throw e;
2530
+ }
2531
+ // Async path — await, then commit. Reject mirrors the sync throw
2532
+ // case (probe 0.G: original error reference re-thrown).
2533
+ if (cbResult !== null && typeof cbResult?.then === 'function') {
2534
+ return cbResult.then((returnValue) => this.commitTransaction(ctx, auth, snapshot, options, returnValue), (e) => {
2535
+ this.logAbortedTransaction(ctx, auth, e);
2536
+ throw e;
2537
+ });
2538
+ }
2539
+ // Sync path.
2540
+ return this.commitTransaction(ctx, auth, snapshot, options, cbResult);
2541
+ }
2542
+ /**
2543
+ * Commit phase shared by sync + async transaction paths. Runs after
2544
+ * the callback has fully completed (sync return or awaited resolve).
2545
+ * Splitting this out keeps `transaction()` readable and keeps the
2546
+ * commit logic from being duplicated across the two branches.
2547
+ */
2548
+ commitTransaction(ctx, auth, snapshot, options, returnValue) {
2549
+ const { reads, writes } = ctx.consume();
2550
+ const detail = options.bypassRules ? { admin: true } : undefined;
2551
+ // Issue #307 — shared groupId so consumers can fold tx sub-ops
2552
+ // together the same way they fold batch sub-ops.
2553
+ const txId = `tx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
2554
+ // Per-write `RequestEvent`s queued during evaluation; emitted at
2555
+ // the end of step 6 with finalized `resourceAfter`. Mirrors the
2556
+ // pattern used in `batch()` (see line ~1410).
2557
+ const pendingEmits = [];
2558
+ // ─── Read-only short-circuit ─────────────────────────────────────
2559
+ // Zero queued writes is the locked happy path for read-only
2560
+ // transactions (probe 0.F): commit cleanly with `writes: []`.
2561
+ if (writes.length === 0) {
2562
+ const event = this.eventLog.append({
2563
+ type: 'transaction',
2564
+ method: 'transaction',
2565
+ path: '',
2566
+ auth: auth ? { uid: auth.uid } : null,
2567
+ allowed: true,
2568
+ reads: reads.map((r) => ({ path: r.path, data: r.data })),
2569
+ operations: [],
2570
+ snapshot,
2571
+ debugMessages: ['Transaction committed (read-only — no writes queued)'],
2572
+ });
2573
+ return {
2574
+ allowed: true,
2575
+ reads: [...reads],
2576
+ writes: [],
2577
+ returnValue,
2578
+ event,
2579
+ };
2580
+ }
2581
+ // ─── Step 3 — merge same-path queued writes ──────────────────────
2582
+ let mergedOps;
2583
+ try {
2584
+ mergedOps = mergeQueuedWrites(writes);
2585
+ }
2586
+ catch (e) {
2587
+ const err = e;
2588
+ this.eventLog.append({
2589
+ type: 'transaction',
2590
+ method: 'transaction',
2591
+ path: '',
2592
+ auth: auth ? { uid: auth.uid } : null,
2593
+ allowed: false,
2594
+ aborted: true,
2595
+ reads: reads.map((r) => ({ path: r.path, data: r.data })),
2596
+ error: { name: err.name, message: err.message, code: 'failed-precondition' },
2597
+ debugMessages: [`Transaction aborted at merge: ${err.message}`],
2598
+ });
2599
+ // Re-throw the original — callers that want a typed code can
2600
+ // catch `AmbiguousPostDeleteWriteError` from transaction-merge.ts.
2601
+ throw e;
2602
+ }
2603
+ // ─── Step 4 — resolve sentinels ──────────────────────────────────
2604
+ // One serverTime for the whole tx; matches batch() and single-op
2605
+ // semantics so `request.time` and any `serverTimestamp()` resolve
2606
+ // to the same wall-clock instant within a tx.
2607
+ const serverTime = Timestamp.fromMillis(Date.now());
2608
+ const resolvedOps = [];
2609
+ for (const op of mergedOps) {
2610
+ if (op.method === 'delete') {
2611
+ resolvedOps.push(op);
2612
+ continue;
2613
+ }
2614
+ try {
2615
+ const resolved = resolveValueTree({ ...op.data }, {
2616
+ path: op.path,
2617
+ method: op.method,
2618
+ prior: this.state.get(op.path),
2619
+ serverTime,
2620
+ });
2621
+ resolvedOps.push({ ...op, data: resolved });
2622
+ }
2623
+ catch (e) {
2624
+ const msg = e.message;
2625
+ const wrapped = makeError('invalid-argument', msg);
2626
+ const event = this.eventLog.append({
2627
+ type: 'transaction',
2628
+ method: 'transaction',
2629
+ path: '',
2630
+ auth: auth ? { uid: auth.uid } : null,
2631
+ allowed: false,
2632
+ reads: reads.map((r) => ({ path: r.path, data: r.data })),
2633
+ operations: mergedOps.map((o) => ({
2634
+ method: o.method,
2635
+ path: o.path,
2636
+ data: o.data,
2637
+ allowed: false,
2638
+ })),
2639
+ debugMessages: [`FieldValue resolve error on '${op.path}': ${msg}`],
2640
+ });
2641
+ // Issue #307 — surface the failing op as a denied request
2642
+ // (mirrors the batch() resolve-error path at line ~1438).
2643
+ // Earlier ops in the loop succeeded silently; later ops never
2644
+ // reached evaluation. Only the failing op emits.
2645
+ const opRuleMethod = (op.method === 'set'
2646
+ ? this.state.get(op.path) !== null
2647
+ ? 'update'
2648
+ : 'create'
2649
+ : op.method);
2650
+ const priorDoc = snapshot[op.path] ?? null;
2651
+ this.emitRequest({
2652
+ at: Date.now(), evalMs: 0,
2653
+ method: opRuleMethod, path: op.path, auth, result: 'deny',
2654
+ debugMessages: [`FieldValue resolve error: ${msg}`],
2655
+ ...(op.data && opRuleMethod !== 'delete' ? { resourceData: op.data } : {}),
2656
+ resourceBefore: { data: priorDoc, exists: priorDoc !== null },
2657
+ origin: 'transaction', groupId: txId,
2658
+ ...(detail ? { detail } : {}),
2659
+ provenance: options.provenance,
2660
+ });
2661
+ return {
2662
+ allowed: false,
2663
+ reads: [...reads],
2664
+ writes: mergedOps.map((o) => {
2665
+ const ruleMethod = o.method === 'set'
2666
+ ? this.state.get(o.path) !== null
2667
+ ? 'update'
2668
+ : 'create'
2669
+ : o.method;
2670
+ return {
2671
+ path: o.path,
2672
+ method: ruleMethod,
2673
+ allowed: false,
2674
+ debugMessages: o.path === op.path ? [msg] : [],
2675
+ ...(o.path === op.path ? { error: wrapped } : {}),
2676
+ };
2677
+ }),
2678
+ returnValue,
2679
+ event,
2680
+ error: wrapped,
2681
+ };
2682
+ }
2683
+ }
2684
+ // ─── Step 5 — per-op rules evaluation against pre-tx state ───────
2685
+ // getafter-batch fix: build the shared post-commit projection ONCE for
2686
+ // the whole transaction (same approach as batch(), same helper) so
2687
+ // `getAfter()` on a sibling write-in-progress doc sees this
2688
+ // transaction's other pending writes, not just its own.
2689
+ const txTestCases = resolvedOps.map((op) => {
2690
+ const exists = this.state.get(op.path) !== null;
2691
+ const ruleMethod = (op.method === 'set'
2692
+ ? exists
2693
+ ? 'update'
2694
+ : 'create'
2695
+ : op.method);
2696
+ return this.buildTestCase({ method: ruleMethod, path: op.path, auth, data: op.data }, serverTime);
2697
+ });
2698
+ const txProjection = this.buildBatchProjection(txTestCases);
2699
+ const writeResults = [];
2700
+ let allAllowed = true;
2701
+ for (let i = 0; i < resolvedOps.length; i++) {
2702
+ const op = resolvedOps[i];
2703
+ // Pre-resolution payload (parallel to resolvedOps by index).
2704
+ // Emitted on RequestEvent/WriteSandboxEvent so consumers see the
2705
+ // user's INTENT with FieldValue.* markers, not materialized values.
2706
+ const preData = mergedOps[i]?.data;
2707
+ // Translate `set` → `create`/`update` for rules-eval purposes
2708
+ // only; applyBatch keeps `set` semantics. Admin's rules engine
2709
+ // dispatches a `set` to whichever lifecycle matches the pre-tx
2710
+ // state, and we mirror that.
2711
+ const exists = this.state.get(op.path) !== null;
2712
+ const ruleMethod = (op.method === 'set'
2713
+ ? exists
2714
+ ? 'update'
2715
+ : 'create'
2716
+ : op.method);
2717
+ const priorDoc = snapshot[op.path] ?? null;
2718
+ const testCase = txTestCases[i];
2719
+ const evalAt = Date.now();
2720
+ const evalStart = performance.now();
2721
+ const sim = this.runSimulate([testCase], options.bypassRules, txProjection);
2722
+ const evalMs = performance.now() - evalStart;
2723
+ if (!sim.success) {
2724
+ writeResults.push({
2725
+ path: op.path,
2726
+ method: ruleMethod,
2727
+ allowed: false,
2728
+ debugMessages: [sim.error.message],
2729
+ error: makeError('invalid-argument', sim.error.message),
2730
+ });
2731
+ pendingEmits.push({
2732
+ at: evalAt, evalMs, method: ruleMethod, path: op.path, auth,
2733
+ result: 'deny',
2734
+ debugMessages: [`Simulation error: ${sim.error.message}`],
2735
+ ...(preData && ruleMethod !== 'delete' ? { resourceData: preData } : {}),
2736
+ resourceBefore: { data: priorDoc, exists: priorDoc !== null },
2737
+ origin: 'transaction', groupId: txId,
2738
+ ...(detail ? { detail } : {}),
2739
+ provenance: options.provenance,
2740
+ });
2741
+ allAllowed = false;
2742
+ continue;
2743
+ }
2744
+ const r = sim.data.results[0];
2745
+ if (r.state === 'UNSUPPORTED') {
2746
+ // Surface the unsupported event before throwing — same
2747
+ // contract as execute() / batch().
2748
+ this.emitRequest({
2749
+ at: evalAt, evalMs, method: ruleMethod, path: op.path, auth,
2750
+ result: 'unsupported', debugMessages: renderLegacyDebugMessages(r),
2751
+ ...(preData && ruleMethod !== 'delete' ? { resourceData: preData } : {}),
2752
+ resourceBefore: { data: priorDoc, exists: priorDoc !== null },
2753
+ origin: 'transaction', groupId: txId,
2754
+ ...(detail ? { detail } : {}),
2755
+ provenance: options.provenance,
2756
+ });
2757
+ throw new SimulatorUnsupportedError(unsupportedMessage(ruleMethod, op.path, renderLegacyDebugMessages(r)), ruleMethod, op.path, renderLegacyDebugMessages(r));
2758
+ }
2759
+ const isAllowed = r.state === 'PASSED';
2760
+ const entry = {
2761
+ path: op.path,
2762
+ method: ruleMethod,
2763
+ allowed: isAllowed,
2764
+ debugMessages: renderLegacyDebugMessages(r),
2765
+ };
2766
+ // Queue the per-write RequestEvent. resourceAfter is filled in
2767
+ // after the atomic apply below (step 6) so denied ops show the
2768
+ // pre-tx state and committed ops show the post-tx state.
2769
+ pendingEmits.push({
2770
+ at: evalAt, evalMs, method: ruleMethod, path: op.path, auth,
2771
+ result: isAllowed ? 'allow' : 'deny',
2772
+ debugMessages: renderLegacyDebugMessages(r),
2773
+ ...(preData && ruleMethod !== 'delete' ? { resourceData: preData } : {}),
2774
+ resourceBefore: { data: priorDoc, exists: priorDoc !== null },
2775
+ origin: 'transaction', groupId: txId,
2776
+ ...(detail ? { detail } : {}),
2777
+ provenance: options.provenance,
2778
+ });
2779
+ if (!isAllowed) {
2780
+ // Per-op `request`/`resource` captured against pre-tx snapshot
2781
+ // so a denial inside a transaction shows the same shape as a
2782
+ // single-op denial (auth + resourceData + existing doc).
2783
+ const priorDoc = snapshot[op.path] ?? null;
2784
+ entry.error = makeError('permission-denied', `${ruleMethod} ${op.path} denied by rules`, {
2785
+ request: {
2786
+ method: ruleMethod,
2787
+ path: op.path,
2788
+ auth,
2789
+ ...(preData && ruleMethod !== 'delete' ? { resourceData: preData } : {}),
2790
+ },
2791
+ resource: { data: priorDoc, exists: priorDoc !== null },
2792
+ });
2793
+ this.emitDenial(entry.error);
2794
+ allAllowed = false;
2795
+ }
2796
+ writeResults.push(entry);
2797
+ }
2798
+ // ─── Step 6 — atomic apply (only if all rules passed) ────────────
2799
+ let structuralError = null;
2800
+ if (allAllowed) {
2801
+ const applyResult = this.state.applyBatch(resolvedOps);
2802
+ if (!applyResult.success) {
2803
+ allAllowed = false;
2804
+ const first = applyResult.errors?.[0];
2805
+ if (first !== undefined) {
2806
+ const failingOp = resolvedOps[first.index];
2807
+ // `set` cannot raise a structural error in applyBatch; only
2808
+ // create/update/delete can — so this branch hits only those
2809
+ // methods. The ternary keeps the type narrow.
2810
+ const code = failingOp?.method === 'create' ? 'already-exists' : 'not-found';
2811
+ structuralError = makeError(code, first.error);
2812
+ const failingResult = writeResults[first.index];
2813
+ if (failingResult) {
2814
+ failingResult.allowed = false;
2815
+ failingResult.error = structuralError;
2816
+ }
2817
+ }
2818
+ }
2819
+ }
2820
+ // ─── Step 7 — log event + assemble result ────────────────────────
2821
+ const event = this.eventLog.append({
2822
+ type: 'transaction',
2823
+ method: 'transaction',
2824
+ path: '',
2825
+ auth: auth ? { uid: auth.uid } : null,
2826
+ allowed: allAllowed,
2827
+ reads: reads.map((r) => ({ path: r.path, data: r.data })),
2828
+ operations: resolvedOps.map((op, i) => ({
2829
+ method: op.method,
2830
+ path: op.path,
2831
+ data: op.data,
2832
+ allowed: writeResults[i]?.allowed ?? false,
2833
+ })),
2834
+ // Snapshot is captured for undo only on success — a rolled-back
2835
+ // tx mutated nothing, so there's nothing to restore. Matches
2836
+ // batch() behavior exactly.
2837
+ snapshot: allAllowed ? snapshot : undefined,
2838
+ debugMessages: allAllowed
2839
+ ? ['Transaction committed']
2840
+ : ['Transaction rolled back — one or more operations denied'],
2841
+ });
2842
+ // Issue #307 — fire the per-write RequestEvents + WriteSandboxEvents
2843
+ // queued in step 5. resourceAfter mirrors `batch()`: committed ops
2844
+ // show the post-apply doc; denied/rolled-back ops show the pre-tx
2845
+ // state. Only committed writes emit a WriteSandboxEvent.
2846
+ for (let i = 0; i < pendingEmits.length; i++) {
2847
+ const e = pendingEmits[i];
2848
+ const opCommitted = allAllowed && writeResults[i]?.allowed === true;
2849
+ if (opCommitted) {
2850
+ const finalDoc = this.state.get(e.path);
2851
+ if (e.method !== 'delete') {
2852
+ e.resourceAfter = { data: finalDoc, exists: finalDoc !== null };
2853
+ }
2854
+ else {
2855
+ e.resourceAfter = { data: null, exists: false };
2856
+ }
2857
+ }
2858
+ else {
2859
+ const priorDoc = snapshot[e.path] ?? null;
2860
+ e.resourceAfter = { data: priorDoc, exists: priorDoc !== null };
2861
+ }
2862
+ this.emitRequest(e);
2863
+ if (opCommitted && e.method !== 'get' && e.method !== 'list') {
2864
+ const priorDoc = snapshot[e.path] ?? null;
2865
+ // Sentinels: walk the PRE-resolution data from `mergedOps[i]`
2866
+ // (parallel to resolvedOps and pendingEmits).
2867
+ const preOp = mergedOps[i];
2868
+ const sentinels = preOp && preOp.method !== 'delete' && preOp.data
2869
+ ? walkForSentinels(preOp.data)
2870
+ : undefined;
2871
+ this.emitWrite({
2872
+ method: e.method,
2873
+ path: e.path,
2874
+ auth,
2875
+ ...(e.method !== 'delete' && e.resourceData ? { data: e.resourceData } : {}),
2876
+ priorState: priorDoc,
2877
+ nextState: e.method === 'delete' ? null : this.state.get(e.path),
2878
+ ...(e.groupId ? { groupId: e.groupId, groupKind: 'transaction' } : {}),
2879
+ ...(sentinels && sentinels.length > 0 ? { sentinels } : {}),
2880
+ requestTime: serverTime,
2881
+ ...(detail ? { detail } : {}),
2882
+ provenance: options.provenance,
2883
+ });
2884
+ }
2885
+ }
2886
+ let topError;
2887
+ if (!allAllowed) {
2888
+ topError =
2889
+ structuralError ??
2890
+ writeResults.find((w) => w.error)?.error ??
2891
+ makeError('permission-denied', 'Transaction denied');
2892
+ }
2893
+ const result = {
2894
+ allowed: allAllowed,
2895
+ reads: [...reads],
2896
+ writes: writeResults,
2897
+ returnValue,
2898
+ event,
2899
+ ...(topError ? { error: topError } : {}),
2900
+ };
2901
+ // Probe 0.H side-finding: warn-not-throw on writes inside a
2902
+ // readOnly tx. v1 still queues + commits the write; v2 may flip to
2903
+ // strict (throw at the call site).
2904
+ if (options.readOnly && ctx.hadWrites()) {
2905
+ result.readOnlyViolation = true;
2906
+ }
2907
+ // Slice 3 — fan out transaction writes after a successful commit.
2908
+ // Aborted transactions never reach here (the throw in `transaction`
2909
+ // bypasses commit entirely), and rolled-back commits leave state
2910
+ // unchanged so we'd suppress everything anyway. Single fire per
2911
+ // transaction matches the Slice 5 design.
2912
+ if (allAllowed) {
2913
+ const touched = new Set();
2914
+ for (const op of resolvedOps)
2915
+ touched.add(op.path);
2916
+ // Issue #307 — listener re-evals attribute to the transaction.
2917
+ const firstOp = resolvedOps[0];
2918
+ const prevTrigger = this.currentTrigger;
2919
+ this.currentTrigger = firstOp
2920
+ ? { method: 'transaction', path: firstOp.path }
2921
+ : { method: 'transaction', path: '' };
2922
+ try {
2923
+ this.notifyListenersForPaths(touched);
2924
+ }
2925
+ finally {
2926
+ this.currentTrigger = prevTrigger;
2927
+ }
2928
+ }
2929
+ return result;
2930
+ }
2931
+ /**
2932
+ * Append an aborted-transaction event for a callback throw (sync or
2933
+ * async path). The original Error is re-thrown by the caller —
2934
+ * probe 0.G locks "exceptions propagate unchanged", so this helper
2935
+ * never throws on its own.
2936
+ */
2937
+ logAbortedTransaction(ctx, auth, err) {
2938
+ const errWithCode = err;
2939
+ const { reads } = ctx.consume();
2940
+ this.eventLog.append({
2941
+ type: 'transaction',
2942
+ method: 'transaction',
2943
+ path: '',
2944
+ auth: auth ? { uid: auth.uid } : null,
2945
+ allowed: false,
2946
+ aborted: true,
2947
+ reads: reads.map((r) => ({ path: r.path, data: r.data })),
2948
+ error: {
2949
+ name: err.name,
2950
+ message: err.message,
2951
+ ...(errWithCode.code !== undefined ? { code: String(errWithCode.code) } : {}),
2952
+ },
2953
+ debugMessages: [`Transaction aborted: ${err.message}`],
2954
+ });
2955
+ }
2956
+ // ═══ Undo / Redo ═══
2957
+ /** Undo the last write operation. Restores the affected paths (single-write /
2958
+ * batch) or the whole keyspace (transaction) to their pre-write state. */
2959
+ undo() {
2960
+ const event = this.eventLog.popLastWrite();
2961
+ if (!event)
2962
+ return null;
2963
+ if (event.priorDocs)
2964
+ this.state.restorePaths(event.priorDocs);
2965
+ else if (event.snapshot)
2966
+ this.state.restore(event.snapshot);
2967
+ else
2968
+ return null;
2969
+ return event;
2970
+ }
2971
+ /** Redo the last undone operation. Re-applies the write directly
2972
+ * without going through execute() (which would clear the redo stack). */
2973
+ redo() {
2974
+ const event = this.eventLog.popLastUndo();
2975
+ if (!event)
2976
+ return null;
2977
+ // Capture prior state BEFORE re-applying (for a future undo of this redo),
2978
+ // matching the kind the event used: affected paths for single-write / batch,
2979
+ // the whole keyspace for a transaction.
2980
+ const affectedPaths = (event.type === 'batch' && event.operations)
2981
+ ? event.operations.map((op) => op.path)
2982
+ : event.path ? [event.path] : [];
2983
+ const useFullSnapshot = !!event.snapshot;
2984
+ const priorDocs = useFullSnapshot ? undefined : this.capturePriors(affectedPaths);
2985
+ const snapshot = useFullSnapshot ? this.state.snapshot() : undefined;
2986
+ // Re-apply the write directly to state
2987
+ if (event.type === 'batch' && event.operations) {
2988
+ for (const op of event.operations) {
2989
+ if (op.allowed)
2990
+ this.applyWrite(op.method, op.path, op.data);
2991
+ }
2992
+ }
2993
+ else if (event.allowed) {
2994
+ this.applyWrite(event.method, event.path, event.data);
2995
+ }
2996
+ // Re-append with preserveRedo=true so remaining redos aren't lost
2997
+ const newEvent = this.eventLog.append({
2998
+ ...event,
2999
+ snapshot,
3000
+ priorDocs,
3001
+ }, true);
3002
+ return {
3003
+ allowed: event.allowed,
3004
+ debugMessages: ['Redo: ' + (event.allowed ? 'applied' : 'skipped (was denied)')],
3005
+ event: newEvent,
3006
+ };
3007
+ }
3008
+ // ═══ Event log access ═══
3009
+ /** Get all events. */
3010
+ getEvents() {
3011
+ return this.eventLog.getEvents();
3012
+ }
3013
+ /** Get event count. */
3014
+ getEventCount() {
3015
+ return this.eventLog.size();
3016
+ }
3017
+ // ═══ Private helpers ═══
3018
+ buildTestCase(operation, serverTime) {
3019
+ const existingDoc = this.state.get(operation.path);
3020
+ // Translate `set` to the rules-engine clause it routes through —
3021
+ // `create` for missing docs, `update` for existing. Storage stays
3022
+ // `set` (handled in applyWrite) so the post-write doc is the
3023
+ // replacement payload, not a merge.
3024
+ const ruleMethod = operation.method === 'set'
3025
+ ? (existingDoc !== null ? 'update' : 'create')
3026
+ : operation.method;
3027
+ // For reads: no request data (reads don't send data)
3028
+ // For writes: build the FULL post-write document
3029
+ let requestData = operation.data;
3030
+ if (operation.method === 'get' || operation.method === 'list') {
3031
+ requestData = undefined;
3032
+ }
3033
+ else if (operation.method === 'update' && existingDoc && operation.data) {
3034
+ // Merge: existing + updates = full post-write document. Item 2:
3035
+ // partition DELETE_FIELD markers so the rules see the same shape
3036
+ // storage will see (deleted keys absent, not present-with-symbol).
3037
+ // The data has already been resolved upstream — partitionDeletes
3038
+ // is idempotent on already-partitioned trees.
3039
+ const { writes, deletedKeys } = partitionDeletes(operation.data);
3040
+ const merged = { ...existingDoc, ...writes };
3041
+ for (const k of deletedKeys)
3042
+ delete merged[k];
3043
+ requestData = merged;
3044
+ }
3045
+ else if (operation.data) {
3046
+ // create / set: the resolved data IS the full post-write doc
3047
+ // (set replaces). Strip any DELETE_FIELD markers so they don't
3048
+ // reach the handler.
3049
+ requestData = partitionDeletes(operation.data).writes;
3050
+ }
3051
+ return {
3052
+ description: `${operation.method} ${operation.path}`,
3053
+ expectation: 'ALLOW', // We always test against ALLOW; FAILED = denied
3054
+ method: ruleMethod,
3055
+ path: operation.path,
3056
+ auth: operation.auth ? { uid: operation.auth.uid, token: operation.auth.token } : null,
3057
+ data: requestData,
3058
+ resource: existingDoc ?? undefined,
3059
+ // Phase 2: no whole-keyspace functionMocks dump. get()/exists() in rules
3060
+ // fault in lazily through the `getDoc` resolver passed to simulate() (a
3061
+ // DocStore point-read), resolving only the paths a ruleset actually touches.
3062
+ // Item 1: forward the resolver's serverTime as ISO so handler.ts's
3063
+ // `request.time` is field-equal to any resolved sentinel.
3064
+ // Millisecond-precise round-trip via Date(ms).toISOString() ↔
3065
+ // Timestamp.fromIsoString.
3066
+ ...(serverTime ? { requestTime: isoFromTimestamp(serverTime) } : {}),
3067
+ };
3068
+ }
3069
+ /**
3070
+ * Apply a write to local state, returning a structural error when
3071
+ * the underlying state operation rejects (Item 6). Rules have already
3072
+ * decided to ALLOW by the time we get here; what's left are the
3073
+ * preconditions only the keyspace knows about — `create` of an
3074
+ * existing path, `update`/`delete` of a missing path. The simulator
3075
+ * previously dropped these silently (state.create returned
3076
+ * `{success:false}` and we ignored it), which let `allowed:true`
3077
+ * results coexist with no actual mutation. Returning the failure
3078
+ * lets `execute()` demote `allowed` and surface the right error code.
3079
+ */
3080
+ applyWrite(method, path, data, merge) {
3081
+ // FS-B6: a merge write (`setDoc(data, {merge})`) deep-merges into the
3082
+ // existing doc (creating it when absent), regardless of whether rule
3083
+ // eval ran as create or update. Route both to `setMerge`.
3084
+ if (merge !== undefined && merge !== false && (method === 'create' || method === 'update')) {
3085
+ const mergeFields = merge === true ? undefined : merge.mergeFields;
3086
+ this.state.setMerge(path, data ?? {}, mergeFields);
3087
+ return null;
3088
+ }
3089
+ switch (method) {
3090
+ case 'create': {
3091
+ const r = this.state.create(path, data ?? {});
3092
+ if (!r.success) {
3093
+ return makeError('already-exists', r.error ?? `Document '${path}' already exists`);
3094
+ }
3095
+ return null;
3096
+ }
3097
+ case 'update': {
3098
+ const r = this.state.update(path, data ?? {});
3099
+ if (!r.success) {
3100
+ return makeError('not-found', r.error ?? `Document '${path}' does not exist`);
3101
+ }
3102
+ return null;
3103
+ }
3104
+ case 'set': {
3105
+ // Replace semantics. `state.set` always succeeds (creates if
3106
+ // absent, replaces if present) — matches Firestore `set()`
3107
+ // without merge options.
3108
+ this.state.set(path, data ?? {});
3109
+ return null;
3110
+ }
3111
+ case 'delete': {
3112
+ // `deleteDoc` on a missing doc is a no-op in production
3113
+ // `firebase/firestore` (and the Admin SDK): rules already
3114
+ // allowed, the doc isn't there to remove, and the call
3115
+ // resolves without throwing. Locked by oracle observation
3116
+ // `packages/conformance/observations/firestore/firestore-deletedoc-missing.json`
3117
+ // (matrix row Firestore #39). `state.delete` returns
3118
+ // `success:false` for a missing path; we collapse that into
3119
+ // null (no error) so `execute()` reports the delete as
3120
+ // allowed with no mutation, matching prod.
3121
+ this.state.delete(path);
3122
+ return null;
3123
+ }
3124
+ default:
3125
+ return null;
3126
+ }
3127
+ }
3128
+ }
3129
+ //# sourceMappingURL=local-environment.js.map