@dereekb/firebase-server 12.7.0 → 13.0.1

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 (343) hide show
  1. package/LICENSE +1 -1
  2. package/index.cjs.default.js +1 -0
  3. package/index.cjs.js +2859 -0
  4. package/index.cjs.mjs +2 -0
  5. package/index.esm.js +2699 -0
  6. package/mailgun/index.cjs.default.js +1 -0
  7. package/mailgun/{src/lib/auth.mailgun.js → index.cjs.js} +6 -6
  8. package/mailgun/index.cjs.mjs +2 -0
  9. package/mailgun/index.esm.js +39 -0
  10. package/mailgun/package.json +20 -5
  11. package/model/index.cjs.default.js +1 -0
  12. package/model/index.cjs.js +4767 -0
  13. package/model/index.cjs.mjs +2 -0
  14. package/model/index.d.ts +1 -0
  15. package/model/index.esm.js +4630 -0
  16. package/model/package.json +28 -4
  17. package/model/src/lib/notification/notification.module.d.ts +10 -10
  18. package/model/src/lib/storagefile/storagefile.task.service.handler.d.ts +3 -14
  19. package/package.json +49 -47
  20. package/src/lib/auth/auth.context.d.ts +1 -1
  21. package/src/lib/auth/auth.service.d.ts +1 -1
  22. package/src/lib/function/assert.d.ts +2 -2
  23. package/src/lib/function/context.d.ts +1 -1
  24. package/src/lib/function/error.d.ts +0 -8
  25. package/src/lib/index.d.ts +1 -0
  26. package/src/lib/nest/app.d.ts +1 -1
  27. package/src/lib/nest/development/development.app.function.d.ts +1 -2
  28. package/src/lib/nest/function/call.d.ts +1 -1
  29. package/src/lib/nest/function/context.d.ts +0 -4
  30. package/src/lib/nest/function/index.d.ts +0 -1
  31. package/src/lib/nest/function/nest.d.ts +1 -1
  32. package/src/lib/nest/function/v2/blocking.d.ts +3 -2
  33. package/src/lib/nest/model/crud.assert.function.d.ts +0 -4
  34. package/src/lib/storage/storage.d.ts +1 -1
  35. package/src/lib/type.d.ts +9 -0
  36. package/test/index.cjs.default.js +1 -0
  37. package/test/index.cjs.js +1258 -0
  38. package/test/index.cjs.mjs +2 -0
  39. package/test/index.d.ts +1 -0
  40. package/test/index.esm.js +1181 -0
  41. package/test/package.json +31 -4
  42. package/test/src/lib/firebase/firebase.admin.auth.d.ts +22 -13
  43. package/test/src/lib/firebase/firebase.admin.collection.d.ts +6 -6
  44. package/test/src/lib/firebase/firebase.admin.d.ts +10 -10
  45. package/test/src/lib/firebase/firebase.admin.function.d.ts +9 -9
  46. package/test/src/lib/firebase/firebase.admin.nest.d.ts +8 -8
  47. package/test/src/lib/firebase/firebase.admin.nest.function.d.ts +9 -9
  48. package/test/src/lib/firebase/firebase.test.d.ts +30 -0
  49. package/test/src/lib/firebase/index.d.ts +1 -1
  50. package/test/src/lib/firestore/firestore.admin.d.ts +3 -3
  51. package/test/src/lib/firestore/firestore.d.ts +2 -2
  52. package/test/src/lib/storage/storage.admin.d.ts +3 -3
  53. package/test/src/lib/storage/storage.d.ts +2 -2
  54. package/zoho/LICENSE +1 -1
  55. package/zoho/index.cjs.default.js +1 -0
  56. package/zoho/index.cjs.js +82 -85
  57. package/zoho/index.cjs.mjs +2 -0
  58. package/zoho/index.d.ts +1 -0
  59. package/zoho/index.esm.js +84 -87
  60. package/zoho/package.json +15 -15
  61. package/CHANGELOG.md +0 -2237
  62. package/mailgun/src/index.js +0 -5
  63. package/mailgun/src/index.js.map +0 -1
  64. package/mailgun/src/lib/auth.mailgun.js.map +0 -1
  65. package/mailgun/src/lib/index.js +0 -5
  66. package/mailgun/src/lib/index.js.map +0 -1
  67. package/model/src/index.js +0 -5
  68. package/model/src/index.js.map +0 -1
  69. package/model/src/lib/index.js +0 -7
  70. package/model/src/lib/index.js.map +0 -1
  71. package/model/src/lib/mailgun/index.js +0 -5
  72. package/model/src/lib/mailgun/index.js.map +0 -1
  73. package/model/src/lib/mailgun/notification.send.service.mailgun.js +0 -68
  74. package/model/src/lib/mailgun/notification.send.service.mailgun.js.map +0 -1
  75. package/model/src/lib/notification/index.js +0 -20
  76. package/model/src/lib/notification/index.js.map +0 -1
  77. package/model/src/lib/notification/notification.action.init.service.js +0 -230
  78. package/model/src/lib/notification/notification.action.init.service.js.map +0 -1
  79. package/model/src/lib/notification/notification.action.service.js +0 -1487
  80. package/model/src/lib/notification/notification.action.service.js.map +0 -1
  81. package/model/src/lib/notification/notification.config.js +0 -13
  82. package/model/src/lib/notification/notification.config.js.map +0 -1
  83. package/model/src/lib/notification/notification.config.service.js +0 -60
  84. package/model/src/lib/notification/notification.config.service.js.map +0 -1
  85. package/model/src/lib/notification/notification.create.run.js +0 -59
  86. package/model/src/lib/notification/notification.create.run.js.map +0 -1
  87. package/model/src/lib/notification/notification.error.js +0 -87
  88. package/model/src/lib/notification/notification.error.js.map +0 -1
  89. package/model/src/lib/notification/notification.expedite.service.js +0 -112
  90. package/model/src/lib/notification/notification.expedite.service.js.map +0 -1
  91. package/model/src/lib/notification/notification.module.js +0 -106
  92. package/model/src/lib/notification/notification.module.js.map +0 -1
  93. package/model/src/lib/notification/notification.send.js +0 -3
  94. package/model/src/lib/notification/notification.send.js.map +0 -1
  95. package/model/src/lib/notification/notification.send.service.js +0 -10
  96. package/model/src/lib/notification/notification.send.service.js.map +0 -1
  97. package/model/src/lib/notification/notification.send.service.notificationsummary.js +0 -104
  98. package/model/src/lib/notification/notification.send.service.notificationsummary.js.map +0 -1
  99. package/model/src/lib/notification/notification.send.service.text.js +0 -29
  100. package/model/src/lib/notification/notification.send.service.text.js.map +0 -1
  101. package/model/src/lib/notification/notification.task.service.handler.js +0 -65
  102. package/model/src/lib/notification/notification.task.service.handler.js.map +0 -1
  103. package/model/src/lib/notification/notification.task.service.js +0 -10
  104. package/model/src/lib/notification/notification.task.service.js.map +0 -1
  105. package/model/src/lib/notification/notification.task.service.util.js +0 -27
  106. package/model/src/lib/notification/notification.task.service.util.js.map +0 -1
  107. package/model/src/lib/notification/notification.task.subtask.handler.js +0 -256
  108. package/model/src/lib/notification/notification.task.subtask.handler.js.map +0 -1
  109. package/model/src/lib/notification/notification.util.js +0 -478
  110. package/model/src/lib/notification/notification.util.js.map +0 -1
  111. package/model/src/lib/storagefile/index.js +0 -12
  112. package/model/src/lib/storagefile/index.js.map +0 -1
  113. package/model/src/lib/storagefile/storagefile.action.init.service.js +0 -155
  114. package/model/src/lib/storagefile/storagefile.action.init.service.js.map +0 -1
  115. package/model/src/lib/storagefile/storagefile.action.server.js +0 -797
  116. package/model/src/lib/storagefile/storagefile.action.server.js.map +0 -1
  117. package/model/src/lib/storagefile/storagefile.error.js +0 -106
  118. package/model/src/lib/storagefile/storagefile.error.js.map +0 -1
  119. package/model/src/lib/storagefile/storagefile.module.js +0 -64
  120. package/model/src/lib/storagefile/storagefile.module.js.map +0 -1
  121. package/model/src/lib/storagefile/storagefile.task.service.handler.js +0 -287
  122. package/model/src/lib/storagefile/storagefile.task.service.handler.js.map +0 -1
  123. package/model/src/lib/storagefile/storagefile.upload.service.initializer.js +0 -180
  124. package/model/src/lib/storagefile/storagefile.upload.service.initializer.js.map +0 -1
  125. package/model/src/lib/storagefile/storagefile.upload.service.js +0 -10
  126. package/model/src/lib/storagefile/storagefile.upload.service.js.map +0 -1
  127. package/model/src/lib/storagefile/storagefile.util.js +0 -54
  128. package/model/src/lib/storagefile/storagefile.util.js.map +0 -1
  129. package/src/index.js +0 -5
  130. package/src/index.js.map +0 -1
  131. package/src/lib/auth/auth.context.js +0 -13
  132. package/src/lib/auth/auth.context.js.map +0 -1
  133. package/src/lib/auth/auth.service.error.js +0 -34
  134. package/src/lib/auth/auth.service.error.js.map +0 -1
  135. package/src/lib/auth/auth.service.js +0 -427
  136. package/src/lib/auth/auth.service.js.map +0 -1
  137. package/src/lib/auth/auth.util.js +0 -23
  138. package/src/lib/auth/auth.util.js.map +0 -1
  139. package/src/lib/auth/index.js +0 -8
  140. package/src/lib/auth/index.js.map +0 -1
  141. package/src/lib/env/env.service.js +0 -7
  142. package/src/lib/env/env.service.js.map +0 -1
  143. package/src/lib/env/index.js +0 -5
  144. package/src/lib/env/index.js.map +0 -1
  145. package/src/lib/firestore/array.js +0 -34
  146. package/src/lib/firestore/array.js.map +0 -1
  147. package/src/lib/firestore/driver.accessor.batch.js +0 -93
  148. package/src/lib/firestore/driver.accessor.batch.js.map +0 -1
  149. package/src/lib/firestore/driver.accessor.default.js +0 -62
  150. package/src/lib/firestore/driver.accessor.default.js.map +0 -1
  151. package/src/lib/firestore/driver.accessor.js +0 -50
  152. package/src/lib/firestore/driver.accessor.js.map +0 -1
  153. package/src/lib/firestore/driver.accessor.transaction.js +0 -96
  154. package/src/lib/firestore/driver.accessor.transaction.js.map +0 -1
  155. package/src/lib/firestore/driver.js +0 -14
  156. package/src/lib/firestore/driver.js.map +0 -1
  157. package/src/lib/firestore/driver.query.js +0 -55
  158. package/src/lib/firestore/driver.query.js.map +0 -1
  159. package/src/lib/firestore/firestore.js +0 -10
  160. package/src/lib/firestore/firestore.js.map +0 -1
  161. package/src/lib/firestore/increment.js +0 -17
  162. package/src/lib/firestore/increment.js.map +0 -1
  163. package/src/lib/firestore/index.js +0 -9
  164. package/src/lib/firestore/index.js.map +0 -1
  165. package/src/lib/function/assert.js +0 -68
  166. package/src/lib/function/assert.js.map +0 -1
  167. package/src/lib/function/context.js +0 -14
  168. package/src/lib/function/context.js.map +0 -1
  169. package/src/lib/function/error.auth.js +0 -25
  170. package/src/lib/function/error.auth.js.map +0 -1
  171. package/src/lib/function/error.js +0 -221
  172. package/src/lib/function/error.js.map +0 -1
  173. package/src/lib/function/index.js +0 -9
  174. package/src/lib/function/index.js.map +0 -1
  175. package/src/lib/function/type.js +0 -3
  176. package/src/lib/function/type.js.map +0 -1
  177. package/src/lib/index.js +0 -11
  178. package/src/lib/index.js.map +0 -1
  179. package/src/lib/nest/app.js +0 -114
  180. package/src/lib/nest/app.js.map +0 -1
  181. package/src/lib/nest/auth/auth.module.js +0 -60
  182. package/src/lib/nest/auth/auth.module.js.map +0 -1
  183. package/src/lib/nest/auth/auth.util.js +0 -72
  184. package/src/lib/nest/auth/auth.util.js.map +0 -1
  185. package/src/lib/nest/auth/index.js +0 -6
  186. package/src/lib/nest/auth/index.js.map +0 -1
  187. package/src/lib/nest/development/development.app.function.js +0 -38
  188. package/src/lib/nest/development/development.app.function.js.map +0 -1
  189. package/src/lib/nest/development/development.assert.function.js +0 -3
  190. package/src/lib/nest/development/development.assert.function.js.map +0 -1
  191. package/src/lib/nest/development/development.function.js +0 -41
  192. package/src/lib/nest/development/development.function.js.map +0 -1
  193. package/src/lib/nest/development/development.schedule.function.error.js +0 -35
  194. package/src/lib/nest/development/development.schedule.function.error.js.map +0 -1
  195. package/src/lib/nest/development/development.schedule.function.js +0 -54
  196. package/src/lib/nest/development/development.schedule.function.js.map +0 -1
  197. package/src/lib/nest/development/index.js +0 -9
  198. package/src/lib/nest/development/index.js.map +0 -1
  199. package/src/lib/nest/env/env.service.js +0 -19
  200. package/src/lib/nest/env/env.service.js.map +0 -1
  201. package/src/lib/nest/env/env.util.js +0 -12
  202. package/src/lib/nest/env/env.util.js.map +0 -1
  203. package/src/lib/nest/env/index.js +0 -6
  204. package/src/lib/nest/env/index.js.map +0 -1
  205. package/src/lib/nest/firebase/firebase.module.js +0 -17
  206. package/src/lib/nest/firebase/firebase.module.js.map +0 -1
  207. package/src/lib/nest/firebase/index.js +0 -5
  208. package/src/lib/nest/firebase/index.js.map +0 -1
  209. package/src/lib/nest/firestore/firestore.module.js +0 -86
  210. package/src/lib/nest/firestore/firestore.module.js.map +0 -1
  211. package/src/lib/nest/firestore/index.js +0 -5
  212. package/src/lib/nest/firestore/index.js.map +0 -1
  213. package/src/lib/nest/function/call.js +0 -46
  214. package/src/lib/nest/function/call.js.map +0 -1
  215. package/src/lib/nest/function/context.js +0 -79
  216. package/src/lib/nest/function/context.js.map +0 -1
  217. package/src/lib/nest/function/index.js +0 -10
  218. package/src/lib/nest/function/index.js.map +0 -1
  219. package/src/lib/nest/function/nest.js +0 -17
  220. package/src/lib/nest/function/nest.js.map +0 -1
  221. package/src/lib/nest/function/schedule.js +0 -8
  222. package/src/lib/nest/function/schedule.js.map +0 -1
  223. package/src/lib/nest/function/v1/call.d.ts +0 -59
  224. package/src/lib/nest/function/v1/call.js +0 -55
  225. package/src/lib/nest/function/v1/call.js.map +0 -1
  226. package/src/lib/nest/function/v1/event.d.ts +0 -80
  227. package/src/lib/nest/function/v1/event.js +0 -52
  228. package/src/lib/nest/function/v1/event.js.map +0 -1
  229. package/src/lib/nest/function/v1/index.d.ts +0 -3
  230. package/src/lib/nest/function/v1/index.js +0 -7
  231. package/src/lib/nest/function/v1/index.js.map +0 -1
  232. package/src/lib/nest/function/v1/schedule.d.ts +0 -47
  233. package/src/lib/nest/function/v1/schedule.js +0 -68
  234. package/src/lib/nest/function/v1/schedule.js.map +0 -1
  235. package/src/lib/nest/function/v2/blocking.js +0 -38
  236. package/src/lib/nest/function/v2/blocking.js.map +0 -1
  237. package/src/lib/nest/function/v2/call.js +0 -31
  238. package/src/lib/nest/function/v2/call.js.map +0 -1
  239. package/src/lib/nest/function/v2/event.js +0 -25
  240. package/src/lib/nest/function/v2/event.js.map +0 -1
  241. package/src/lib/nest/function/v2/index.js +0 -9
  242. package/src/lib/nest/function/v2/index.js.map +0 -1
  243. package/src/lib/nest/function/v2/schedule.js +0 -56
  244. package/src/lib/nest/function/v2/schedule.js.map +0 -1
  245. package/src/lib/nest/function/v2/taskqueue.js +0 -26
  246. package/src/lib/nest/function/v2/taskqueue.js.map +0 -1
  247. package/src/lib/nest/index.js +0 -15
  248. package/src/lib/nest/index.js.map +0 -1
  249. package/src/lib/nest/middleware/appcheck.decorator.js +0 -12
  250. package/src/lib/nest/middleware/appcheck.decorator.js.map +0 -1
  251. package/src/lib/nest/middleware/appcheck.js +0 -3
  252. package/src/lib/nest/middleware/appcheck.js.map +0 -1
  253. package/src/lib/nest/middleware/appcheck.middleware.js +0 -74
  254. package/src/lib/nest/middleware/appcheck.middleware.js.map +0 -1
  255. package/src/lib/nest/middleware/appcheck.module.js +0 -21
  256. package/src/lib/nest/middleware/appcheck.module.js.map +0 -1
  257. package/src/lib/nest/middleware/globalprefix.js +0 -11
  258. package/src/lib/nest/middleware/globalprefix.js.map +0 -1
  259. package/src/lib/nest/middleware/index.js +0 -10
  260. package/src/lib/nest/middleware/index.js.map +0 -1
  261. package/src/lib/nest/middleware/rawbody.middleware.js +0 -16
  262. package/src/lib/nest/middleware/rawbody.middleware.js.map +0 -1
  263. package/src/lib/nest/middleware/webhook.js +0 -24
  264. package/src/lib/nest/middleware/webhook.js.map +0 -1
  265. package/src/lib/nest/model/call.model.function.js +0 -73
  266. package/src/lib/nest/model/call.model.function.js.map +0 -1
  267. package/src/lib/nest/model/create.model.function.js +0 -27
  268. package/src/lib/nest/model/create.model.function.js.map +0 -1
  269. package/src/lib/nest/model/crud.assert.function.js +0 -3
  270. package/src/lib/nest/model/crud.assert.function.js.map +0 -1
  271. package/src/lib/nest/model/delete.model.function.js +0 -27
  272. package/src/lib/nest/model/delete.model.function.js.map +0 -1
  273. package/src/lib/nest/model/index.js +0 -11
  274. package/src/lib/nest/model/index.js.map +0 -1
  275. package/src/lib/nest/model/permission.error.js +0 -24
  276. package/src/lib/nest/model/permission.error.js.map +0 -1
  277. package/src/lib/nest/model/read.model.function.js +0 -27
  278. package/src/lib/nest/model/read.model.function.js.map +0 -1
  279. package/src/lib/nest/model/specifier.function.js +0 -35
  280. package/src/lib/nest/model/specifier.function.js.map +0 -1
  281. package/src/lib/nest/model/update.model.function.js +0 -27
  282. package/src/lib/nest/model/update.model.function.js.map +0 -1
  283. package/src/lib/nest/nest.provider.js +0 -89
  284. package/src/lib/nest/nest.provider.js.map +0 -1
  285. package/src/lib/nest/storage/index.js +0 -5
  286. package/src/lib/nest/storage/index.js.map +0 -1
  287. package/src/lib/nest/storage/storage.module.js +0 -112
  288. package/src/lib/nest/storage/storage.module.js.map +0 -1
  289. package/src/lib/storage/driver.accessor.js +0 -299
  290. package/src/lib/storage/driver.accessor.js.map +0 -1
  291. package/src/lib/storage/driver.js +0 -12
  292. package/src/lib/storage/driver.js.map +0 -1
  293. package/src/lib/storage/index.js +0 -8
  294. package/src/lib/storage/index.js.map +0 -1
  295. package/src/lib/storage/storage.js +0 -20
  296. package/src/lib/storage/storage.js.map +0 -1
  297. package/src/lib/storage/storage.service.js +0 -26
  298. package/src/lib/storage/storage.service.js.map +0 -1
  299. package/test/src/index.js +0 -5
  300. package/test/src/index.js.map +0 -1
  301. package/test/src/lib/firebase/firebase.admin.auth.js +0 -260
  302. package/test/src/lib/firebase/firebase.admin.auth.js.map +0 -1
  303. package/test/src/lib/firebase/firebase.admin.collection.js +0 -108
  304. package/test/src/lib/firebase/firebase.admin.collection.js.map +0 -1
  305. package/test/src/lib/firebase/firebase.admin.function.js +0 -132
  306. package/test/src/lib/firebase/firebase.admin.function.js.map +0 -1
  307. package/test/src/lib/firebase/firebase.admin.js +0 -174
  308. package/test/src/lib/firebase/firebase.admin.js.map +0 -1
  309. package/test/src/lib/firebase/firebase.admin.nest.function.callable.context.js +0 -42
  310. package/test/src/lib/firebase/firebase.admin.nest.function.callable.context.js.map +0 -1
  311. package/test/src/lib/firebase/firebase.admin.nest.function.cloud.context.js +0 -40
  312. package/test/src/lib/firebase/firebase.admin.nest.function.cloud.context.js.map +0 -1
  313. package/test/src/lib/firebase/firebase.admin.nest.function.js +0 -64
  314. package/test/src/lib/firebase/firebase.admin.nest.function.js.map +0 -1
  315. package/test/src/lib/firebase/firebase.admin.nest.js +0 -107
  316. package/test/src/lib/firebase/firebase.admin.nest.js.map +0 -1
  317. package/test/src/lib/firebase/firebase.admin.test.server.js +0 -37
  318. package/test/src/lib/firebase/firebase.admin.test.server.js.map +0 -1
  319. package/test/src/lib/firebase/firebase.function.js +0 -58
  320. package/test/src/lib/firebase/firebase.function.js.map +0 -1
  321. package/test/src/lib/firebase/firebase.jest.d.ts +0 -21
  322. package/test/src/lib/firebase/firebase.jest.js +0 -45
  323. package/test/src/lib/firebase/firebase.jest.js.map +0 -1
  324. package/test/src/lib/firebase/firebase.js +0 -74
  325. package/test/src/lib/firebase/firebase.js.map +0 -1
  326. package/test/src/lib/firebase/index.js +0 -15
  327. package/test/src/lib/firebase/index.js.map +0 -1
  328. package/test/src/lib/firestore/firestore.admin.js +0 -21
  329. package/test/src/lib/firestore/firestore.admin.js.map +0 -1
  330. package/test/src/lib/firestore/firestore.js +0 -57
  331. package/test/src/lib/firestore/firestore.js.map +0 -1
  332. package/test/src/lib/firestore/index.js +0 -6
  333. package/test/src/lib/firestore/index.js.map +0 -1
  334. package/test/src/lib/index.js +0 -7
  335. package/test/src/lib/index.js.map +0 -1
  336. package/test/src/lib/storage/index.js +0 -6
  337. package/test/src/lib/storage/index.js.map +0 -1
  338. package/test/src/lib/storage/storage.admin.js +0 -21
  339. package/test/src/lib/storage/storage.admin.js.map +0 -1
  340. package/test/src/lib/storage/storage.js +0 -59
  341. package/test/src/lib/storage/storage.js.map +0 -1
  342. /package/{zoho/index.cjs.d.ts → index.d.ts} +0 -0
  343. /package/{zoho/index.esm.d.ts → mailgun/index.d.ts} +0 -0
package/index.cjs.js ADDED
@@ -0,0 +1,2859 @@
1
+ 'use strict';
2
+
3
+ var firebase = require('@dereekb/firebase');
4
+ var util = require('@dereekb/util');
5
+ var https = require('firebase-functions/https');
6
+ var date = require('@dereekb/date');
7
+ var makeError = require('make-error');
8
+ var rxjs = require('rxjs');
9
+ var firestore = require('@google-cloud/firestore');
10
+ var common = require('@nestjs/common');
11
+ var nestjs = require('@dereekb/nestjs');
12
+ var v2 = require('firebase-functions/v2');
13
+ var model = require('@dereekb/model');
14
+ var admin = require('firebase-admin');
15
+ var storage = require('@google-cloud/storage');
16
+ var dateFns = require('date-fns');
17
+ var types = require('util/types');
18
+ var core = require('@nestjs/core');
19
+ var platformExpress = require('@nestjs/platform-express');
20
+ var express = require('express');
21
+
22
+ function unauthenticatedContextHasNoAuthData() {
23
+ return unauthenticatedError({
24
+ message: 'expected auth',
25
+ code: firebase.DBX_FIREBASE_SERVER_NO_AUTH_ERROR_CODE
26
+ });
27
+ }
28
+ function unauthenticatedContextHasNoUidError() {
29
+ return unauthenticatedError({
30
+ message: 'no user uid',
31
+ code: firebase.DBX_FIREBASE_SERVER_NO_AUTH_ERROR_CODE
32
+ });
33
+ }
34
+ // MARK: General Errors
35
+ const UNAUTHENTICATED_ERROR_CODE = 'UNAUTHENTICATED';
36
+ function unauthenticatedError(messageOrError) {
37
+ const serverError = util.partialServerError(messageOrError);
38
+ return new https.HttpsError('unauthenticated', serverError?.message || 'unauthenticated', {
39
+ status: 401,
40
+ code: UNAUTHENTICATED_ERROR_CODE,
41
+ ...serverError,
42
+ _error: undefined
43
+ });
44
+ }
45
+ const FORBIDDEN_ERROR_CODE = 'FORBIDDEN';
46
+ function forbiddenError(messageOrError) {
47
+ const serverError = util.partialServerError(messageOrError);
48
+ return new https.HttpsError('permission-denied', serverError?.message || 'forbidden', {
49
+ status: 403,
50
+ code: FORBIDDEN_ERROR_CODE,
51
+ ...serverError,
52
+ _error: undefined
53
+ });
54
+ }
55
+ const PERMISSION_DENIED_ERROR_CODE = 'PERMISSION_DENIED';
56
+ function permissionDeniedError(messageOrError) {
57
+ const serverError = util.partialServerError(messageOrError);
58
+ return new https.HttpsError('permission-denied', serverError?.message || 'permission denied', {
59
+ status: 403,
60
+ code: PERMISSION_DENIED_ERROR_CODE,
61
+ ...serverError,
62
+ _error: undefined
63
+ });
64
+ }
65
+ const NOT_FOUND_ERROR_CODE = 'NOT_FOUND';
66
+ function notFoundError(messageOrError) {
67
+ const serverError = util.partialServerError(messageOrError);
68
+ return new https.HttpsError('not-found', serverError?.message || 'not found', {
69
+ status: 404,
70
+ code: NOT_FOUND_ERROR_CODE,
71
+ ...serverError,
72
+ _error: undefined
73
+ });
74
+ }
75
+ const MODEL_NOT_AVAILABLE_ERROR_CODE = 'MODEL_NOT_AVAILABLE';
76
+ function modelNotAvailableError(messageOrError) {
77
+ const serverError = util.partialServerError(messageOrError);
78
+ return new https.HttpsError('not-found', serverError?.message || 'model was not available', {
79
+ status: 404,
80
+ code: MODEL_NOT_AVAILABLE_ERROR_CODE,
81
+ ...serverError,
82
+ _error: undefined
83
+ });
84
+ }
85
+ const BAD_REQUEST_ERROR_CODE = 'BAD_REQUEST';
86
+ function badRequestError(messageOrError) {
87
+ const serverError = util.partialServerError(messageOrError);
88
+ return new https.HttpsError('invalid-argument', serverError?.message || 'bad request', {
89
+ status: 400,
90
+ code: BAD_REQUEST_ERROR_CODE,
91
+ ...serverError,
92
+ _error: undefined
93
+ });
94
+ }
95
+ const CONFLICT_ERROR_CODE = 'CONFLICT';
96
+ function preconditionConflictError(messageOrError) {
97
+ const serverError = util.partialServerError(messageOrError);
98
+ return new https.HttpsError('failed-precondition', serverError?.message || 'conflict', {
99
+ status: 409,
100
+ code: CONFLICT_ERROR_CODE,
101
+ ...serverError,
102
+ _error: undefined
103
+ });
104
+ }
105
+ const ALREADY_EXISTS_ERROR_CODE = 'ALREADY_EXISTS';
106
+ function alreadyExistsError(messageOrError) {
107
+ const serverError = util.partialServerError(messageOrError);
108
+ return new https.HttpsError('already-exists', serverError?.message || 'already exists', {
109
+ status: 409,
110
+ code: ALREADY_EXISTS_ERROR_CODE,
111
+ ...serverError,
112
+ _error: undefined
113
+ });
114
+ }
115
+ const UNAVAILABLE_ERROR_CODE = 'UNAVAILABLE';
116
+ function unavailableError(messageOrError) {
117
+ const serverError = util.partialServerError(messageOrError);
118
+ return new https.HttpsError('unavailable', serverError?.message || 'service unavailable', {
119
+ status: 503,
120
+ code: UNAVAILABLE_ERROR_CODE,
121
+ ...serverError,
122
+ _error: undefined
123
+ });
124
+ }
125
+ const UNAVAILABLE_OR_DEACTIVATED_FUNCTION_ERROR_CODE = 'UNAVAILABLE_OR_DEACTIVATED_FUNCTION';
126
+ function unavailableOrDeactivatedFunctionError(messageOrError) {
127
+ const serverError = util.partialServerError(messageOrError);
128
+ return new https.HttpsError('unimplemented', serverError?.message || 'the requested function is not available or has been deactivated for use', {
129
+ status: 501,
130
+ code: UNAVAILABLE_OR_DEACTIVATED_FUNCTION_ERROR_CODE,
131
+ ...serverError,
132
+ _error: undefined
133
+ });
134
+ }
135
+ const INTERNAL_SERVER_ERROR_CODE = 'INTERNAL_ERROR';
136
+ function internalServerError(messageOrError) {
137
+ const serverError = util.partialServerError(messageOrError);
138
+ return new https.HttpsError('internal', serverError?.message || 'internal error', {
139
+ status: 500,
140
+ code: INTERNAL_SERVER_ERROR_CODE,
141
+ ...serverError,
142
+ _error: undefined
143
+ });
144
+ }
145
+ function isFirebaseHttpsError(input) {
146
+ return typeof input === 'object' && input.code != null && input.httpErrorCode != null && input.toJSON != null;
147
+ }
148
+ function isFirebaseError(input) {
149
+ return typeof input === 'object' && input.code != null && input.message != null && input.toJSON != null;
150
+ }
151
+ /**
152
+ * Creates a FirebaseServerErrorInfo from the input.
153
+ *
154
+ * @param e
155
+ * @returns
156
+ */
157
+ function firebaseServerErrorInfo(e) {
158
+ let type = 'unknown';
159
+ let httpsError;
160
+ let firebaseError;
161
+ let firebaseErrorCode;
162
+ let httpsErrorDetailsServerError;
163
+ let serverErrorCode;
164
+ if (e != null) {
165
+ if (isFirebaseHttpsError(e)) {
166
+ type = 'httpsError';
167
+ httpsError = e;
168
+ firebaseErrorCode = httpsError.code;
169
+ if (httpsError.details && util.isServerError(httpsError.details)) {
170
+ httpsErrorDetailsServerError = httpsError.details;
171
+ serverErrorCode = httpsErrorDetailsServerError.code;
172
+ }
173
+ }
174
+ else if (isFirebaseError(e)) {
175
+ type = 'firebaseError';
176
+ firebaseError = e;
177
+ firebaseErrorCode = firebaseError.code;
178
+ }
179
+ }
180
+ return {
181
+ httpsError,
182
+ firebaseError,
183
+ firebaseErrorCode,
184
+ httpsErrorDetailsServerError,
185
+ serverErrorCode,
186
+ type,
187
+ e
188
+ };
189
+ }
190
+ function firebaseServerErrorInfoCodePair(e) {
191
+ const info = firebaseServerErrorInfo(e);
192
+ return [info.firebaseErrorCode, info];
193
+ }
194
+ function firebaseServerErrorInfoServerErrorPair(e) {
195
+ const info = firebaseServerErrorInfo(e);
196
+ return [info.httpsErrorDetailsServerError, info];
197
+ }
198
+ function firebaseServerErrorInfoServerErrorCodePair(e) {
199
+ const info = firebaseServerErrorInfo(e);
200
+ return [info.serverErrorCode, info];
201
+ }
202
+ function handleFirebaseError(e, handleFirebaseErrorFn) {
203
+ const firebaseError = e.code ? e : undefined;
204
+ if (firebaseError) {
205
+ handleFirebaseErrorFn(firebaseError);
206
+ }
207
+ }
208
+
209
+ function isContextWithAuthData(context) {
210
+ return Boolean(context.auth !== null && context.auth?.uid);
211
+ }
212
+ function assertIsContextWithAuthData(context) {
213
+ if (!isContextWithAuthData(context)) {
214
+ throw unauthenticatedContextHasNoAuthData();
215
+ }
216
+ }
217
+
218
+ function firebaseAuthTokenFromDecodedIdToken(token) {
219
+ return {
220
+ email: token.email,
221
+ emailVerified: token.email_verified,
222
+ phoneNumber: token.phone_number,
223
+ lastSignInTime: new Date(token.auth_time).toISOString(),
224
+ lastRefreshTime: new Date(token.iat).toISOString()
225
+ };
226
+ }
227
+
228
+ /**
229
+ * Awaits the load result from the input promise. If it encounters a FIREBASE_AUTH_USER_NOT_FOUND_ERROR, then returns undefined. Throws the error otherwise.
230
+ * @param promise
231
+ * @returns
232
+ */
233
+ async function getAuthUserOrUndefined(promise) {
234
+ try {
235
+ return await promise;
236
+ }
237
+ catch (error) {
238
+ if (error?.code === firebase.FIREBASE_AUTH_USER_NOT_FOUND_ERROR) {
239
+ return undefined;
240
+ }
241
+ else {
242
+ throw error;
243
+ }
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Thrown by sendSetupDetails() if the user has no setup configuration available, meaning they probably already have accepted their invite or is in an invalid state.
249
+ */
250
+ class FirebaseServerAuthNewUserSendSetupDetailsNoSetupConfigError extends makeError.BaseError {
251
+ constructor() {
252
+ super(`This user has no setup configuration available.`);
253
+ }
254
+ }
255
+ /**
256
+ * Thrown by sendSetupDetails() if the user was recently sent details.
257
+ */
258
+ class FirebaseServerAuthNewUserSendSetupDetailsThrottleError extends makeError.BaseError {
259
+ lastSentAt;
260
+ constructor(lastSentAt) {
261
+ super(`This user was recently sent details. Try again later.`);
262
+ this.lastSentAt = lastSentAt;
263
+ }
264
+ }
265
+ /**
266
+ * Thrown by sendSetupDetails() if the user was recently sent details.
267
+ */
268
+ class FirebaseServerAuthNewUserSendSetupDetailsSendOnceError extends makeError.BaseError {
269
+ constructor() {
270
+ super(`The user has been sent details before and the sendSetupDetailsOnce configuration was true.`);
271
+ }
272
+ }
273
+
274
+ const DEFAULT_FIREBASE_PASSWORD_NUMBER_GENERATOR = util.randomNumberFactory({ min: 100000, max: 1000000, round: 'floor' }); // 6 digits
275
+ class AbstractFirebaseServerAuthUserContext {
276
+ _service;
277
+ _uid;
278
+ _loadRecord = util.cachedGetter(() => this._service.auth.getUser(this._uid));
279
+ constructor(service, uid) {
280
+ this._service = service;
281
+ this._uid = uid;
282
+ }
283
+ get service() {
284
+ return this._service;
285
+ }
286
+ get uid() {
287
+ return this._uid;
288
+ }
289
+ async exists() {
290
+ return getAuthUserOrUndefined(this._loadRecord()).then((x) => Boolean(x));
291
+ }
292
+ loadRecord() {
293
+ return this._loadRecord();
294
+ }
295
+ loadDetails() {
296
+ return this.loadRecord().then((record) => this.service.authDetailsForRecord(record));
297
+ }
298
+ _generateResetPasswordKey() {
299
+ return String(DEFAULT_FIREBASE_PASSWORD_NUMBER_GENERATOR());
300
+ }
301
+ async beginResetPassword() {
302
+ const password = this._generateResetPasswordKey();
303
+ const passwordClaimsData = {
304
+ [firebase.FIREBASE_SERVER_AUTH_CLAIMS_RESET_PASSWORD_KEY]: password,
305
+ [firebase.FIREBASE_SERVER_AUTH_CLAIMS_RESET_LAST_COM_DATE_KEY]: date.toISODateString(new Date())
306
+ };
307
+ // set the claims
308
+ await this.updateClaims(passwordClaimsData);
309
+ // update the user
310
+ await this.updateUser({ password });
311
+ return passwordClaimsData;
312
+ }
313
+ async loadResetPasswordClaims() {
314
+ const claims = await this.loadClaims();
315
+ if (claims.resetPassword != null) {
316
+ return claims;
317
+ }
318
+ else {
319
+ return undefined;
320
+ }
321
+ }
322
+ /**
323
+ * Sets the user's password.
324
+ */
325
+ async setPassword(password) {
326
+ const record = await this.updateUser({ password });
327
+ // clear password reset claims
328
+ await this.updateClaims({
329
+ [firebase.FIREBASE_SERVER_AUTH_CLAIMS_RESET_PASSWORD_KEY]: null,
330
+ [firebase.FIREBASE_SERVER_AUTH_CLAIMS_RESET_LAST_COM_DATE_KEY]: null
331
+ });
332
+ return record;
333
+ }
334
+ async updateUser(template) {
335
+ return this.service.auth.updateUser(this.uid, template);
336
+ }
337
+ async loadRoles() {
338
+ const claims = await this.loadClaims();
339
+ return this.service.readRoles(claims);
340
+ }
341
+ async addRoles(roles) {
342
+ const claims = this._claimsForRolesChange(roles);
343
+ return this.updateClaims(claims);
344
+ }
345
+ async removeRoles(roles) {
346
+ const baseClaims = this._claimsForRolesChange(roles);
347
+ const claims = {};
348
+ util.forEachKeyValue(baseClaims, {
349
+ forEach: ([key]) => {
350
+ claims[key] = null; // set null on every key
351
+ },
352
+ filter: util.KeyValueTypleValueFilter.NONE // don't skip any key/value
353
+ });
354
+ return this.updateClaims(claims);
355
+ }
356
+ /**
357
+ * Sets the claims using the input roles and roles set.
358
+ *
359
+ * All other claims are cleared.
360
+ *
361
+ * Use the claimsToRetain input to retain other claims that are outside of the roles.
362
+ *
363
+ * @param roles
364
+ * @param claimsToRetain
365
+ * @returns
366
+ */
367
+ async setRoles(roles, claimsToRetain) {
368
+ const claims = {
369
+ ...claimsToRetain,
370
+ ...this._claimsForRolesChange(Array.from(roles))
371
+ };
372
+ return this.setClaims(claims);
373
+ }
374
+ _claimsForRolesChange(roles) {
375
+ // filter null/undefined since the claims will contain null values for claims that are not related.
376
+ return util.filterNullAndUndefinedValues(this.service.claimsForRoles(util.asSet(roles)));
377
+ }
378
+ loadClaims() {
379
+ return this.loadRecord().then((x) => (x.customClaims ?? {}));
380
+ }
381
+ async updateClaims(claims) {
382
+ const currentClaims = await this.loadClaims();
383
+ let newClaims;
384
+ if (currentClaims) {
385
+ newClaims = {
386
+ ...currentClaims,
387
+ ...util.filterUndefinedValues(claims, false)
388
+ };
389
+ newClaims = util.filterNullAndUndefinedValues(newClaims);
390
+ }
391
+ else {
392
+ newClaims = claims;
393
+ }
394
+ return this.setClaims(newClaims);
395
+ }
396
+ clearClaims() {
397
+ return this.setClaims(null);
398
+ }
399
+ setClaims(claims) {
400
+ return this.service.auth.setCustomUserClaims(this.uid, claims).then(() => {
401
+ this._loadRecord.reset(); // reset the cache
402
+ });
403
+ }
404
+ }
405
+ class AbstractFirebaseServerAuthContext {
406
+ _service;
407
+ _context;
408
+ _authRoles = util.cachedGetter(() => this.service.readRoles(this.claims));
409
+ _isAdmin = util.cachedGetter(() => this.service.isAdminInRoles(this._authRoles()));
410
+ _hasSignedTos = util.cachedGetter(() => this.service.hasSignedTosInRoles(this._authRoles()));
411
+ _userContext = util.cachedGetter(() => this.service.userContext(this.context.auth.uid));
412
+ constructor(service, context) {
413
+ this._service = service;
414
+ this._context = context;
415
+ }
416
+ get service() {
417
+ return this._service;
418
+ }
419
+ get context() {
420
+ return this._context;
421
+ }
422
+ get userContext() {
423
+ return this._userContext();
424
+ }
425
+ get isAdmin() {
426
+ return this._isAdmin();
427
+ }
428
+ get hasSignedTos() {
429
+ return this._hasSignedTos();
430
+ }
431
+ get authRoles() {
432
+ return this._authRoles();
433
+ }
434
+ get token() {
435
+ return this.context.auth.token;
436
+ }
437
+ get claims() {
438
+ return this.context.auth.token;
439
+ }
440
+ // MARK: FirebaseServerAuthUserContext
441
+ get uid() {
442
+ return this.userContext.uid;
443
+ }
444
+ }
445
+ /**
446
+ * 1 hour
447
+ */
448
+ const DEFAULT_SETUP_COM_THROTTLE_TIME = date.hoursToMs(1);
449
+ function userContextFromUid(authService, userContextOrUid) {
450
+ const userContext = typeof userContextOrUid === 'string' ? authService.userContext(userContextOrUid) : userContextOrUid;
451
+ return userContext;
452
+ }
453
+ class AbstractFirebaseServerNewUserService {
454
+ _authService;
455
+ setupThrottleTime = DEFAULT_SETUP_COM_THROTTLE_TIME;
456
+ constructor(authService) {
457
+ this._authService = authService;
458
+ }
459
+ get authService() {
460
+ return this._authService;
461
+ }
462
+ async initializeNewUser(input) {
463
+ const { uid, email, phone, sendSetupContent, sendSetupContentIfUserExists, sendSetupDetailsOnce, sendSetupIgnoreThrottle, sendSetupThrowErrors, data, sendDetailsInTestEnvironment } = input;
464
+ let userRecordPromise;
465
+ if (uid) {
466
+ userRecordPromise = this.authService.auth.getUser(uid);
467
+ }
468
+ else if (email) {
469
+ userRecordPromise = this.authService.auth.getUserByEmail(email);
470
+ }
471
+ else if (phone) {
472
+ userRecordPromise = this.authService.auth.getUserByPhoneNumber(phone);
473
+ }
474
+ else {
475
+ throw new Error('email or phone is required to initialize a new user.');
476
+ }
477
+ let userRecord = await getAuthUserOrUndefined(userRecordPromise);
478
+ let userRecordId;
479
+ let createdUser = false;
480
+ if (!userRecord) {
481
+ const createResult = await this.createNewUser(input);
482
+ // add the setup password to the user's credentials
483
+ const userContext = this.authService.userContext(createResult.user.uid);
484
+ await this.addNewUserSetupClaims(userContext, createResult.password);
485
+ createdUser = true;
486
+ userRecordId = userContext.uid;
487
+ userRecord = await userContext.loadRecord();
488
+ }
489
+ else {
490
+ userRecordId = userRecord.uid;
491
+ }
492
+ // send content if necessary
493
+ if ((createdUser && sendSetupContent === true) || sendSetupContentIfUserExists) {
494
+ const sentEmail = await this.sendSetupContent(userRecordId, { data, sendSetupDetailsOnce, ignoreSendThrottleTime: sendSetupIgnoreThrottle, throwErrors: sendSetupThrowErrors, sendDetailsInTestEnvironment });
495
+ // reload the user record
496
+ if (sentEmail) {
497
+ const userContext = this.authService.userContext(userRecordId);
498
+ userRecord = await userContext.loadRecord();
499
+ }
500
+ }
501
+ return userRecord;
502
+ }
503
+ async addNewUserSetupClaims(userContextOrUid, setupPassword) {
504
+ const password = setupPassword ?? this.generateRandomSetupPassword();
505
+ const userContext = userContextFromUid(this.authService, userContextOrUid);
506
+ await userContext.updateClaims({
507
+ [firebase.FIREBASE_SERVER_AUTH_CLAIMS_SETUP_PASSWORD_KEY]: password
508
+ });
509
+ return userContext;
510
+ }
511
+ async sendSetupContent(userContextOrUid, config) {
512
+ const setupDetails = await this.loadSetupDetails(userContextOrUid, config);
513
+ let sentContent = false;
514
+ if (setupDetails) {
515
+ const { setupCommunicationAt } = setupDetails.claims;
516
+ const hasSentCommunication = Boolean(setupCommunicationAt);
517
+ if (config?.sendSetupDetailsOnce && hasSentCommunication) {
518
+ // do not send.
519
+ if (config?.throwErrors) {
520
+ throw new FirebaseServerAuthNewUserSendSetupDetailsSendOnceError();
521
+ }
522
+ }
523
+ else {
524
+ const lastSentAt = setupCommunicationAt ? new Date(setupCommunicationAt) : undefined;
525
+ const sendIsThrottled = hasSentCommunication && !config?.ignoreSendThrottleTime && util.isThrottled(this.setupThrottleTime, lastSentAt);
526
+ if (!sendIsThrottled) {
527
+ await this.sendSetupContentToUser(setupDetails);
528
+ await this.updateSetupContentSentTime(setupDetails);
529
+ sentContent = true;
530
+ }
531
+ else if (config?.throwErrors) {
532
+ throw new FirebaseServerAuthNewUserSendSetupDetailsThrottleError(lastSentAt);
533
+ }
534
+ }
535
+ }
536
+ else if (config?.throwErrors) {
537
+ throw new FirebaseServerAuthNewUserSendSetupDetailsNoSetupConfigError();
538
+ }
539
+ return sentContent;
540
+ }
541
+ async loadSetupDetails(userContextOrUid, config) {
542
+ const userContext = userContextFromUid(this.authService, userContextOrUid);
543
+ const userExists = await userContext.exists();
544
+ let details;
545
+ if (userExists) {
546
+ details = await this.loadSetupDetailsForUserContext(userContext, config);
547
+ }
548
+ return details;
549
+ }
550
+ async loadSetupDetailsForUserContext(userContext, config) {
551
+ let details;
552
+ const { setupPassword, setupCommunicationAt } = await userContext.loadClaims();
553
+ if (setupPassword) {
554
+ details = {
555
+ userContext,
556
+ claims: {
557
+ setupPassword,
558
+ setupCommunicationAt
559
+ },
560
+ data: config?.data,
561
+ sendDetailsInTestEnvironment: config?.sendDetailsInTestEnvironment
562
+ };
563
+ }
564
+ return details;
565
+ }
566
+ async updateSetupContentSentTime(details) {
567
+ const setupCommunicationAt = date.toISODateString(new Date());
568
+ await details.userContext.updateClaims({
569
+ setupCommunicationAt
570
+ });
571
+ }
572
+ /**
573
+ * Update a user's claims to clear any setup-related content.
574
+ *
575
+ * Returns true if a user was updated.
576
+ *
577
+ * @param uid
578
+ */
579
+ async markUserSetupAsComplete(uid) {
580
+ const userContext = this.authService.userContext(uid);
581
+ const userExists = await userContext.exists();
582
+ if (userExists) {
583
+ await this.updateClaimsToClearUser(userContext);
584
+ }
585
+ return userExists;
586
+ }
587
+ async createNewUser(input) {
588
+ const { uid, displayName, email, phone: phoneNumber, setupPassword: inputPassword } = input;
589
+ const password = inputPassword ?? this.generateRandomSetupPassword();
590
+ const user = await this.authService.auth.createUser({
591
+ uid,
592
+ displayName,
593
+ email,
594
+ phoneNumber,
595
+ password
596
+ });
597
+ return {
598
+ user,
599
+ password
600
+ };
601
+ }
602
+ generateRandomSetupPassword() {
603
+ return `${DEFAULT_FIREBASE_PASSWORD_NUMBER_GENERATOR()}`;
604
+ }
605
+ async updateClaimsToClearUser(userContext) {
606
+ await userContext.updateClaims({
607
+ [firebase.FIREBASE_SERVER_AUTH_CLAIMS_SETUP_PASSWORD_KEY]: null,
608
+ [firebase.FIREBASE_SERVER_AUTH_CLAIMS_SETUP_LAST_COM_DATE_KEY]: null
609
+ });
610
+ }
611
+ }
612
+ class NoSetupContentFirebaseServerNewUserService extends AbstractFirebaseServerNewUserService {
613
+ async sendSetupContentToUser(user) {
614
+ // send nothing.
615
+ }
616
+ }
617
+ /**
618
+ * FirebaseServer auth service that provides accessors to auth-related components.
619
+ */
620
+ class FirebaseServerAuthService {
621
+ }
622
+ /**
623
+ * Abstract FirebaseServerAuthService implementation.
624
+ */
625
+ class AbstractFirebaseServerAuthService {
626
+ _auth;
627
+ constructor(auth) {
628
+ this._auth = auth;
629
+ }
630
+ get auth() {
631
+ return this._auth;
632
+ }
633
+ context(context) {
634
+ assertIsContextWithAuthData(context);
635
+ return this._context(context);
636
+ }
637
+ isAdmin(claims) {
638
+ return this.isAdminInRoles(this.readRoles(claims));
639
+ }
640
+ isAdminInRoles(roles) {
641
+ return roles.has(util.AUTH_ADMIN_ROLE);
642
+ }
643
+ hasSignedTos(claims) {
644
+ return this.hasSignedTosInRoles(this.readRoles(claims));
645
+ }
646
+ hasSignedTosInRoles(roles) {
647
+ return roles.has(util.AUTH_TOS_SIGNED_ROLE);
648
+ }
649
+ newUser() {
650
+ return new NoSetupContentFirebaseServerNewUserService(this);
651
+ }
652
+ authContextInfo(context) {
653
+ const { auth } = context;
654
+ let result;
655
+ if (auth) {
656
+ const _roles = util.cachedGetter(() => this.readRoles(auth.token));
657
+ const getClaims = () => auth.token;
658
+ result = {
659
+ uid: auth.uid,
660
+ isAdmin: () => this.isAdminInRoles(_roles()),
661
+ getClaims,
662
+ getAuthRoles: _roles,
663
+ token: firebaseAuthTokenFromDecodedIdToken(auth.token)
664
+ };
665
+ }
666
+ return result;
667
+ }
668
+ authDetailsForRecord(record) {
669
+ return {
670
+ uid: record.uid,
671
+ email: record.email,
672
+ emailVerified: record.emailVerified,
673
+ phoneNumber: record.phoneNumber,
674
+ disabled: record.disabled,
675
+ displayName: record.displayName,
676
+ photoURL: record.photoURL,
677
+ creationTime: record.metadata.creationTime ? new Date(record.metadata.creationTime).toISOString() : undefined,
678
+ lastSignInTime: record.metadata.lastSignInTime ? new Date(record.metadata.lastSignInTime).toISOString() : undefined,
679
+ lastRefreshTime: record.metadata.lastRefreshTime ? new Date(record.metadata.lastRefreshTime).toISOString() : undefined
680
+ };
681
+ }
682
+ }
683
+
684
+ class FirebaseServerEnvService {
685
+ }
686
+
687
+ /**
688
+ * Creates UpdateData corresponding to the input increment update.
689
+ *
690
+ * @param input
691
+ * @returns
692
+ */
693
+ function firestoreServerIncrementUpdateToUpdateData(input) {
694
+ return util.mapObjectMap(input, (incrementValue) => {
695
+ return firestore.FieldValue.increment(incrementValue ?? 0);
696
+ });
697
+ }
698
+
699
+ /**
700
+ * Creates UpdateData corresponding to the input array update.
701
+ *
702
+ * @param input
703
+ * @returns
704
+ */
705
+ function firestoreServerArrayUpdateToUpdateData(input) {
706
+ const union = input?.union;
707
+ const remove = input?.remove;
708
+ function createUpdatesWithArrayFunction(fieldUpdate, arrayUpdateFunction) {
709
+ let result;
710
+ if (fieldUpdate) {
711
+ result = util.mapObjectMap(fieldUpdate, (arrayUpdate) => {
712
+ let result;
713
+ if (arrayUpdate) {
714
+ result = arrayUpdateFunction(...arrayUpdate); // use spread operator to insert each value as an argument, as "nested arrays" are not allowed in the Firestore
715
+ }
716
+ return result;
717
+ });
718
+ }
719
+ return result;
720
+ }
721
+ const updateData = {
722
+ ...createUpdatesWithArrayFunction(union, firestore.FieldValue.arrayUnion),
723
+ ...createUpdatesWithArrayFunction(remove, firestore.FieldValue.arrayRemove)
724
+ };
725
+ return updateData;
726
+ }
727
+
728
+ // MARK: Accessor
729
+ /**
730
+ * FirestoreDocumentDataAccessor implementation for a batch.
731
+ */
732
+ class WriteBatchFirestoreDocumentDataAccessor {
733
+ documentRef;
734
+ _batch;
735
+ constructor(batch, documentRef) {
736
+ this.documentRef = documentRef;
737
+ this._batch = batch;
738
+ }
739
+ get batch() {
740
+ return this._batch;
741
+ }
742
+ stream() {
743
+ return rxjs.from(this.get()); // todo
744
+ }
745
+ create(data) {
746
+ this.batch.create(this.documentRef, data);
747
+ return Promise.resolve();
748
+ }
749
+ exists() {
750
+ return this.get().then((x) => x.exists);
751
+ }
752
+ get() {
753
+ return this.documentRef.get();
754
+ }
755
+ getWithConverter(converter) {
756
+ return this.documentRef.withConverter(converter).get();
757
+ }
758
+ delete(params) {
759
+ this.batch.delete(this.documentRef, params?.precondition);
760
+ return Promise.resolve();
761
+ }
762
+ set(data) {
763
+ this.batch.set(this.documentRef, data);
764
+ return Promise.resolve();
765
+ }
766
+ increment(data, params) {
767
+ return this.update(firestoreServerIncrementUpdateToUpdateData(data), params);
768
+ }
769
+ arrayUpdate(data, params) {
770
+ return this.update(firestoreServerArrayUpdateToUpdateData(data), params);
771
+ }
772
+ update(data, params) {
773
+ if (params?.precondition != null) {
774
+ this.batch.update(this.documentRef, data, params?.precondition);
775
+ }
776
+ else {
777
+ this.batch.update(this.documentRef, data);
778
+ }
779
+ return Promise.resolve();
780
+ }
781
+ }
782
+ /**
783
+ * Creates a new FirestoreDocumentDataAccessorFactory for a Batch.
784
+ *
785
+ * @param batch
786
+ * @returns
787
+ */
788
+ function writeBatchAccessorFactory(writeBatch) {
789
+ return {
790
+ accessorFor: (ref) => new WriteBatchFirestoreDocumentDataAccessor(writeBatch, ref)
791
+ };
792
+ }
793
+ // MARK: Context
794
+ class WriteBatchFirestoreDocumentContext {
795
+ _batch;
796
+ contextType = firebase.FirestoreDocumentContextType.BATCH;
797
+ accessorFactory;
798
+ constructor(batch) {
799
+ this._batch = batch;
800
+ this.accessorFactory = writeBatchAccessorFactory(batch);
801
+ }
802
+ get batch() {
803
+ return this._batch;
804
+ }
805
+ }
806
+ function writeBatchDocumentContext(batch) {
807
+ return new WriteBatchFirestoreDocumentContext(batch);
808
+ }
809
+
810
+ // MARK: Accessor
811
+ class DefaultFirestoreDocumentDataAccessor {
812
+ _documentRef;
813
+ constructor(documentRef) {
814
+ this._documentRef = documentRef;
815
+ }
816
+ get documentRef() {
817
+ return this._documentRef;
818
+ }
819
+ stream() {
820
+ return firebase.streamFromOnSnapshot(({ next, error }) => this.documentRef.onSnapshot(next, error));
821
+ }
822
+ create(data) {
823
+ return this.documentRef.create(data);
824
+ }
825
+ exists() {
826
+ return this.get().then((x) => x.exists);
827
+ }
828
+ get() {
829
+ return this.documentRef.get();
830
+ }
831
+ getWithConverter(converter) {
832
+ return this.documentRef.withConverter(converter).get();
833
+ }
834
+ delete(params) {
835
+ return this.documentRef.delete(params?.precondition);
836
+ }
837
+ set(data, options) {
838
+ return options ? this.documentRef.set(data, options) : this.documentRef.set(data);
839
+ }
840
+ increment(data, params) {
841
+ return this.update(firestoreServerIncrementUpdateToUpdateData(data), params);
842
+ }
843
+ arrayUpdate(data, params) {
844
+ return this.update(firestoreServerArrayUpdateToUpdateData(data), params);
845
+ }
846
+ update(data, params) {
847
+ return params?.precondition ? this.documentRef.update(data, params.precondition) : this.documentRef.update(data);
848
+ }
849
+ }
850
+ function defaultFirestoreAccessorFactory() {
851
+ return {
852
+ accessorFor: (ref) => new DefaultFirestoreDocumentDataAccessor(ref)
853
+ };
854
+ }
855
+ // MARK: Context
856
+ function defaultFirestoreDocumentContext() {
857
+ return {
858
+ contextType: firebase.FirestoreDocumentContextType.NONE,
859
+ accessorFactory: defaultFirestoreAccessorFactory()
860
+ };
861
+ }
862
+
863
+ // MARK: Accessor
864
+ /**
865
+ * FirestoreDocumentDataAccessor implementation for a transaction.
866
+ */
867
+ class TransactionFirestoreDocumentDataAccessor {
868
+ _transaction;
869
+ _documentRef;
870
+ constructor(transaction, documentRef) {
871
+ this._transaction = transaction;
872
+ this._documentRef = documentRef;
873
+ }
874
+ get transaction() {
875
+ return this._transaction;
876
+ }
877
+ get documentRef() {
878
+ return this._documentRef;
879
+ }
880
+ stream() {
881
+ return rxjs.from(this.get());
882
+ }
883
+ create(data) {
884
+ this.transaction.create(this.documentRef, data);
885
+ return Promise.resolve();
886
+ }
887
+ exists() {
888
+ return this.get().then((x) => x.exists);
889
+ }
890
+ get() {
891
+ return this.transaction.get(this.documentRef);
892
+ }
893
+ getWithConverter(converter) {
894
+ return this.transaction.get(this.documentRef.withConverter(converter));
895
+ }
896
+ delete() {
897
+ this.transaction.delete(this.documentRef);
898
+ return Promise.resolve();
899
+ }
900
+ set(data, options) {
901
+ this.transaction.set(this.documentRef, data, options);
902
+ return Promise.resolve();
903
+ }
904
+ increment(data, params) {
905
+ return this.update(firestoreServerIncrementUpdateToUpdateData(data), params);
906
+ }
907
+ arrayUpdate(data, params) {
908
+ return this.update(firestoreServerArrayUpdateToUpdateData(data), params);
909
+ }
910
+ update(data, params) {
911
+ if (params?.precondition) {
912
+ this.transaction.update(this.documentRef, data, params?.precondition);
913
+ }
914
+ else {
915
+ this.transaction.update(this.documentRef, data);
916
+ }
917
+ return Promise.resolve();
918
+ }
919
+ }
920
+ /**
921
+ * Creates a new FirestoreDocumentDataAccessorFactory for a Transaction.
922
+ *
923
+ * @param transaction
924
+ * @returns
925
+ */
926
+ function transactionAccessorFactory(transaction) {
927
+ return {
928
+ accessorFor: (ref) => new TransactionFirestoreDocumentDataAccessor(transaction, ref)
929
+ };
930
+ }
931
+ // MARK: Context
932
+ class TransactionFirestoreDocumentContext {
933
+ _transaction;
934
+ contextType = firebase.FirestoreDocumentContextType.TRANSACTION;
935
+ accessorFactory;
936
+ constructor(transaction) {
937
+ this._transaction = transaction;
938
+ this.accessorFactory = transactionAccessorFactory(transaction);
939
+ }
940
+ get transaction() {
941
+ return this._transaction;
942
+ }
943
+ }
944
+ function transactionDocumentContext(transaction) {
945
+ return new TransactionFirestoreDocumentContext(transaction);
946
+ }
947
+
948
+ function collectionRefForPath(start, path, pathSegments) {
949
+ let ref = start.collection(path);
950
+ if (pathSegments?.length) {
951
+ if (pathSegments?.length % 2 !== 0) {
952
+ throw new Error(`Invalid number of path segments provided for collection. Path: "${path}" + "${pathSegments}"`);
953
+ }
954
+ const batches = util.batch(pathSegments, 2); // batch to tuple [string, string]
955
+ batches.forEach((x) => {
956
+ const [first, second] = x;
957
+ ref = ref.doc(first).collection(second);
958
+ });
959
+ }
960
+ return ref;
961
+ }
962
+ function docRefForPath(start, path, pathSegments) {
963
+ let doc = (path ? start.doc(path) : start.doc());
964
+ if (pathSegments?.length) {
965
+ const batches = util.batch(pathSegments, 2); // batch to tuple [string, string]
966
+ batches.forEach((x) => {
967
+ const [first, second] = x;
968
+ const collection = doc.collection(first);
969
+ doc = second ? collection.doc(second) : collection.doc();
970
+ });
971
+ }
972
+ return doc;
973
+ }
974
+ function googleCloudFirestoreAccessorDriver() {
975
+ return {
976
+ doc: (collection, path, ...pathSegments) => docRefForPath(collection, path, pathSegments),
977
+ docAtPath: (firestore, fullPath) => firestore.doc(fullPath),
978
+ collectionGroup: (firestore, collectionId) => firestore.collectionGroup(collectionId),
979
+ collection: (firestore, path, ...pathSegments) => collectionRefForPath(firestore, path, pathSegments),
980
+ subcollection: (document, path, ...pathSegments) => collectionRefForPath(document, path, pathSegments),
981
+ transactionFactoryForFirestore: (firestore) => async (fn) => await firestore.runTransaction(fn),
982
+ writeBatchFactoryForFirestore: (firestore) => () => firestore.batch(),
983
+ defaultContextFactory: defaultFirestoreDocumentContext,
984
+ transactionContextFactory: transactionDocumentContext,
985
+ writeBatchContextFactory: writeBatchDocumentContext
986
+ };
987
+ }
988
+
989
+ const FIRESTORE_CLIENT_QUERY_CONSTRAINT_HANDLER_MAPPING = {
990
+ [firebase.FIRESTORE_LIMIT_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.limit(data.limit),
991
+ [firebase.FIRESTORE_LIMIT_TO_LAST_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.limitToLast(data.limit),
992
+ [firebase.FIRESTORE_ORDER_BY_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.orderBy(data.fieldPath, data.directionStr),
993
+ [firebase.FIRESTORE_ORDER_BY_DOCUMENT_ID_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.orderBy(firestore.FieldPath.documentId(), data.directionStr),
994
+ [firebase.FIRESTORE_WHERE_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.where(data.fieldPath, data.opStr, data.value),
995
+ [firebase.FIRESTORE_WHERE_DOCUMENT_ID_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.where(firestore.FieldPath.documentId(), data.opStr, data.value),
996
+ [firebase.FIRESTORE_OFFSET_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.offset(data.offset),
997
+ [firebase.FIRESTORE_START_AT_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.startAt(data.snapshot),
998
+ [firebase.FIRESTORE_START_AT_VALUE_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.startAt(...data.fieldValues),
999
+ [firebase.FIRESTORE_START_AFTER_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.startAfter(data.snapshot),
1000
+ [firebase.FIRESTORE_END_AT_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.endAt(data.snapshot),
1001
+ [firebase.FIRESTORE_END_AT_VALUE_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.endAt(...data.fieldValues),
1002
+ [firebase.FIRESTORE_END_BEFORE_QUERY_CONSTRAINT_TYPE]: (builder, data) => builder.endBefore(data.snapshot)
1003
+ };
1004
+ function firestoreClientQueryConstraintFunctionsDriver() {
1005
+ return firebase.makeFirestoreQueryConstraintFunctionsDriver({
1006
+ mapping: FIRESTORE_CLIENT_QUERY_CONSTRAINT_HANDLER_MAPPING,
1007
+ init: (query) => query,
1008
+ build: (query) => query,
1009
+ documentIdFieldPath: () => firestore.FieldPath.documentId()
1010
+ });
1011
+ }
1012
+ function googleCloudFirestoreQueryDriver() {
1013
+ return {
1014
+ ...firestoreClientQueryConstraintFunctionsDriver(),
1015
+ countDocs(query) {
1016
+ return query
1017
+ .count()
1018
+ .get()
1019
+ .then((x) => x.data().count);
1020
+ },
1021
+ getDocs(query, transaction) {
1022
+ let result;
1023
+ if (transaction) {
1024
+ result = transaction.get(query);
1025
+ }
1026
+ else {
1027
+ result = query.get();
1028
+ }
1029
+ return result;
1030
+ },
1031
+ streamDocs(query) {
1032
+ return firebase.streamFromOnSnapshot(({ next, error }) => query.onSnapshot(next, error));
1033
+ }
1034
+ };
1035
+ }
1036
+
1037
+ function googleCloudFirestoreDrivers() {
1038
+ return {
1039
+ firestoreDriverIdentifier: '@google-cloud/firestore',
1040
+ firestoreDriverType: 'production',
1041
+ firestoreAccessorDriver: googleCloudFirestoreAccessorDriver(),
1042
+ firestoreQueryDriver: googleCloudFirestoreQueryDriver()
1043
+ };
1044
+ }
1045
+
1046
+ /**
1047
+ * Creates a FirestoreContextFactory that uses the @'@google-cloud/firestore package.
1048
+ */
1049
+ const googleCloudFirestoreContextFactory = firebase.firestoreContextFactory(googleCloudFirestoreDrivers());
1050
+
1051
+ function assertContextHasAuth(context) {
1052
+ if (!isContextWithAuthData(context)) {
1053
+ throw unauthenticatedContextHasNoUidError();
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Attempts to load data from the document. A modelNotAvailableError is thrown if the snapshot data is null/undefined (the document does not exist).
1058
+ *
1059
+ * @param document
1060
+ * @param message
1061
+ * @returns
1062
+ */
1063
+ async function assertSnapshotData(document, message) {
1064
+ const data = await document.snapshotData();
1065
+ if (data == null) {
1066
+ throw modelNotAvailableError({
1067
+ message: message ?? `The ${document.modelType} was unavailable.`
1068
+ });
1069
+ }
1070
+ return data;
1071
+ }
1072
+ /**
1073
+ * Convenience function for assertSnapshotData that also attaches the id and key of the document to the data.
1074
+ *
1075
+ * @param document
1076
+ * @param message
1077
+ * @returns
1078
+ */
1079
+ async function assertSnapshotDataWithKey(document, message) {
1080
+ const data = await assertSnapshotData(document, message);
1081
+ return firebase.setIdAndKeyFromKeyIdRefOnDocumentData(data, document);
1082
+ }
1083
+ /**
1084
+ * Asserts that the document exists. A modelNotAvailableError is thrown if the document does not exist.
1085
+ *
1086
+ * @param document
1087
+ * @param message
1088
+ * @returns
1089
+ */
1090
+ async function assertDocumentExists(document, message) {
1091
+ const exists = await document.exists();
1092
+ if (!exists) {
1093
+ throw documentModelNotAvailableError(document, message);
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Error thrown by assertDocumentExists().
1098
+ *
1099
+ * @param document
1100
+ * @param message
1101
+ * @returns
1102
+ */
1103
+ function documentModelNotAvailableError(document, message) {
1104
+ return modelNotAvailableError({
1105
+ message: message ?? `The ${document.modelType} was unavailable.`
1106
+ });
1107
+ }
1108
+
1109
+ const PHONE_NUMBER_ALREADY_EXISTS_ERROR_CODE = 'PHONE_NUMBER_ALREADY_EXISTS';
1110
+ function phoneNumberAlreadyExistsError() {
1111
+ return preconditionConflictError({
1112
+ code: PHONE_NUMBER_ALREADY_EXISTS_ERROR_CODE,
1113
+ message: 'This phone number already exists in the system.'
1114
+ });
1115
+ }
1116
+ function handleFirebaseAuthError(e, handleUnknownCode) {
1117
+ handleFirebaseError(e, (firebaseError) => {
1118
+ switch (firebaseError.code) {
1119
+ case 'auth/phone-number-already-exists':
1120
+ throw phoneNumberAlreadyExistsError();
1121
+ default:
1122
+ handleUnknownCode?.(firebaseError);
1123
+ break;
1124
+ }
1125
+ });
1126
+ }
1127
+
1128
+ /******************************************************************************
1129
+ Copyright (c) Microsoft Corporation.
1130
+
1131
+ Permission to use, copy, modify, and/or distribute this software for any
1132
+ purpose with or without fee is hereby granted.
1133
+
1134
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1135
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1136
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1137
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1138
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1139
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1140
+ PERFORMANCE OF THIS SOFTWARE.
1141
+ ***************************************************************************** */
1142
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
1143
+
1144
+
1145
+ function __decorate(decorators, target, key, desc) {
1146
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1147
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1148
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1149
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1150
+ }
1151
+
1152
+ function __param(paramIndex, decorator) {
1153
+ return function (target, key) { decorator(target, key, paramIndex); }
1154
+ }
1155
+
1156
+ function __metadata(metadataKey, metadataValue) {
1157
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
1158
+ }
1159
+
1160
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1161
+ var e = new Error(message);
1162
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1163
+ };
1164
+
1165
+ // MARK: Tokens
1166
+ /**
1167
+ * Nest Injection Token to access the
1168
+ */
1169
+ const FIREBASE_APP_TOKEN = 'FIREBASE_APP_TOKEN';
1170
+ // MARK: Firebase Admin Provider
1171
+ function firebaseServerAppTokenProvider(useFactory) {
1172
+ return {
1173
+ provide: FIREBASE_APP_TOKEN,
1174
+ useFactory
1175
+ };
1176
+ }
1177
+
1178
+ // MARK: Tokens
1179
+ /**
1180
+ * Token to access the Auth for the app.
1181
+ */
1182
+ const FIREBASE_AUTH_TOKEN = 'FIREBASE_AUTH_TOKEN';
1183
+ /**
1184
+ * Nest provider module for Firebase that provides a firestore, etc. from the firestore token.
1185
+ */
1186
+ exports.FirebaseServerAuthModule = class FirebaseServerAuthModule {
1187
+ };
1188
+ exports.FirebaseServerAuthModule = __decorate([
1189
+ common.Module({
1190
+ providers: [
1191
+ {
1192
+ provide: FIREBASE_AUTH_TOKEN,
1193
+ useFactory: (app) => app.auth(),
1194
+ inject: [FIREBASE_APP_TOKEN]
1195
+ }
1196
+ ],
1197
+ exports: [FIREBASE_AUTH_TOKEN]
1198
+ })
1199
+ ], exports.FirebaseServerAuthModule);
1200
+ function provideFirebaseServerAuthService(provider) {
1201
+ return [
1202
+ {
1203
+ ...provider,
1204
+ inject: provider.inject ?? [FIREBASE_AUTH_TOKEN]
1205
+ },
1206
+ {
1207
+ provide: FirebaseServerAuthService,
1208
+ useExisting: provider.provide
1209
+ }
1210
+ ];
1211
+ }
1212
+ /**
1213
+ * Convenience function used to generate ModuleMetadata for an app's Auth related modules and FirebaseServerAuthService provider.
1214
+ *
1215
+ * @param provide
1216
+ * @param useFactory
1217
+ * @returns
1218
+ */
1219
+ function firebaseServerAuthModuleMetadata(config) {
1220
+ return nestjs.mergeModuleMetadata({
1221
+ imports: [exports.FirebaseServerAuthModule],
1222
+ exports: [exports.FirebaseServerAuthModule, config.serviceProvider.provide],
1223
+ providers: provideFirebaseServerAuthService(config.serviceProvider)
1224
+ }, config);
1225
+ }
1226
+
1227
+ function assertIsAdminInRequest(request) {
1228
+ if (!isAdminInRequest(request)) {
1229
+ throw forbiddenError();
1230
+ }
1231
+ }
1232
+ function isAdminInRequest(request) {
1233
+ return request.nest.authService.context(request).isAdmin;
1234
+ }
1235
+ function assertIsAdminOrTargetUserInRequestData(request, requireUid) {
1236
+ if (!isAdminOrTargetUserInRequestData(request, requireUid)) {
1237
+ throw forbiddenError();
1238
+ }
1239
+ return request.data.uid ?? request.auth?.uid;
1240
+ }
1241
+ function isAdminOrTargetUserInRequestData(request, requireUid = false) {
1242
+ const uid = request.data.uid;
1243
+ const authUid = request.auth?.uid;
1244
+ let isAdminOrTargetUser = true;
1245
+ if ((requireUid && uid == null) || (uid != null && uid !== authUid)) {
1246
+ isAdminOrTargetUser = request.nest.authService.context(request).isAdmin;
1247
+ }
1248
+ return isAdminOrTargetUser;
1249
+ }
1250
+ function assertHasSignedTosInRequest(request) {
1251
+ if (!hasSignedTosInRequest(request)) {
1252
+ throw forbiddenError({
1253
+ message: 'ToS has not been signed.'
1254
+ });
1255
+ }
1256
+ }
1257
+ function hasSignedTosInRequest(request) {
1258
+ return request.nest.authService.context(request).hasSignedTos;
1259
+ }
1260
+ function assertHasRolesInRequest(request, authRoles) {
1261
+ if (!hasAuthRolesInRequest(request, authRoles)) {
1262
+ throw forbiddenError({
1263
+ message: 'Missing required auth roles.',
1264
+ data: {
1265
+ roles: util.asArray(authRoles)
1266
+ }
1267
+ });
1268
+ }
1269
+ }
1270
+ function hasAuthRolesInRequest(request, authRoles) {
1271
+ return util.containsAllValues(request.nest.authService.context(request).authRoles, authRoles);
1272
+ }
1273
+ /**
1274
+ * Returns true if the claims have a FIREBASE_SERVER_AUTH_CLAIMS_SETUP_PASSWORD_KEY claims value, indicating they are a newly invited user.
1275
+ *
1276
+ * This may be used to filter out new users that were not invited from finishing their onboarding.
1277
+ *
1278
+ * @param request
1279
+ */
1280
+ function hasNewUserSetupPasswordInRequest(request) {
1281
+ const claims = request.nest.authService.context(request).claims;
1282
+ return claims[firebase.FIREBASE_SERVER_AUTH_CLAIMS_SETUP_PASSWORD_KEY] != null;
1283
+ }
1284
+
1285
+ /**
1286
+ * Creates a OnCallWithAuthorizedNestContext function for creating a model.
1287
+ *
1288
+ * @param map
1289
+ * @returns
1290
+ */
1291
+ function onCallDevelopmentFunction(map, config = {}) {
1292
+ const { preAssert = () => undefined } = config;
1293
+ return (request) => {
1294
+ const specifier = request.data.specifier;
1295
+ const devFn = map[specifier];
1296
+ if (devFn) {
1297
+ preAssert({ request, specifier });
1298
+ return devFn({
1299
+ ...request,
1300
+ specifier,
1301
+ data: request.data.data
1302
+ });
1303
+ }
1304
+ else {
1305
+ throw developmentUnknownSpecifierError(specifier);
1306
+ }
1307
+ };
1308
+ }
1309
+ function developmentUnknownSpecifierError(specifier) {
1310
+ return badRequestError(util.serverError({
1311
+ status: 400,
1312
+ code: 'UNKNOWN_SPECIFIER_ERROR',
1313
+ message: `Invalid specifier "${specifier}" to run.`,
1314
+ data: {
1315
+ specifier
1316
+ }
1317
+ }));
1318
+ }
1319
+
1320
+ const NO_RUN_NAME_SPECIFIED_FOR_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_CODE = 'NO_RUN_NAME_SPECIFIED_FOR_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION';
1321
+ function noRunNameSpecifiedForScheduledFunctionDevelopmentFunction() {
1322
+ return badRequestError({
1323
+ code: NO_RUN_NAME_SPECIFIED_FOR_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_CODE,
1324
+ message: `Must specify run parameter.`
1325
+ });
1326
+ }
1327
+ const UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_NAME_CODE = 'UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_NAME';
1328
+ function unknownScheduledFunctionDevelopmentFunctionName(name) {
1329
+ return badRequestError({
1330
+ code: UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_NAME_CODE,
1331
+ message: `Unknown function with name "${name}"`,
1332
+ data: {
1333
+ name
1334
+ }
1335
+ });
1336
+ }
1337
+ const UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_TYPE_CODE = 'UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_TYPE';
1338
+ function unknownScheduledFunctionDevelopmentFunctionType(type) {
1339
+ return badRequestError({
1340
+ code: UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_TYPE_CODE,
1341
+ message: `Unknown type "${type}"`,
1342
+ data: {
1343
+ type
1344
+ }
1345
+ });
1346
+ }
1347
+
1348
+ function makeScheduledFunctionDevelopmentFunction(config) {
1349
+ const { allScheduledFunctions } = config;
1350
+ const getListValues = util.cachedGetter(() => {
1351
+ const result = [];
1352
+ util.forEachKeyValue(allScheduledFunctions, {
1353
+ forEach: (x) => {
1354
+ const [functionName, config] = x;
1355
+ result.push({
1356
+ name: functionName.toString()
1357
+ });
1358
+ }
1359
+ });
1360
+ return result;
1361
+ });
1362
+ return async (request) => {
1363
+ const { data } = request;
1364
+ const { type } = data;
1365
+ switch (type) {
1366
+ case 'run':
1367
+ const targetRunName = data.run;
1368
+ if (!targetRunName) {
1369
+ throw noRunNameSpecifiedForScheduledFunctionDevelopmentFunction();
1370
+ }
1371
+ const targetFunction = allScheduledFunctions[targetRunName];
1372
+ if (!targetFunction) {
1373
+ throw unknownScheduledFunctionDevelopmentFunctionName(targetRunName);
1374
+ }
1375
+ try {
1376
+ await targetFunction._runNow();
1377
+ }
1378
+ catch (e) {
1379
+ console.error(`Failed manually running task "${targetRunName}".`, e);
1380
+ throw e;
1381
+ }
1382
+ return {
1383
+ type: 'run',
1384
+ success: true
1385
+ };
1386
+ case 'list':
1387
+ return {
1388
+ type: 'list',
1389
+ list: getListValues()
1390
+ };
1391
+ default:
1392
+ throw unknownScheduledFunctionDevelopmentFunctionType(type);
1393
+ }
1394
+ };
1395
+ }
1396
+
1397
+ function setNestContextOnRequest(makeNestContext, request) {
1398
+ request.nest = makeNestContext(request.nestApplication);
1399
+ return request;
1400
+ }
1401
+ /**
1402
+ * Wraps the input OnCallWithNestContext function to flag it as optional to have auth data.
1403
+ *
1404
+ * @param fn
1405
+ * @returns
1406
+ */
1407
+ function optionalAuthContext(fn) {
1408
+ const fnWithOptionalAuth = ((request) => fn(request));
1409
+ fnWithOptionalAuth._requireAuth = false;
1410
+ return fnWithOptionalAuth;
1411
+ }
1412
+ /**
1413
+ * Asserts that the input request has auth data if the inputOnCallWithAuthAwareNestRequireAuthRef object is flagged to require auth.
1414
+ *
1415
+ * @param fn
1416
+ * @param request
1417
+ */
1418
+ function assertRequestRequiresAuthForFunction(fn, request) {
1419
+ if (fn._requireAuth !== false) {
1420
+ assertIsContextWithAuthData(request);
1421
+ }
1422
+ }
1423
+ /**
1424
+ * Creates an OnCallWithNestContext wrapper that validates the input CallableContext to assert the context has auth data before entering the function.
1425
+ *
1426
+ * @param fn
1427
+ * @returns
1428
+ */
1429
+ function inAuthContext(fn) {
1430
+ return (request) => {
1431
+ assertIsContextWithAuthData(request);
1432
+ return fn(request);
1433
+ };
1434
+ }
1435
+
1436
+ function firebaseServerDevFunctions(config) {
1437
+ const { enabled, secure, nest, developerFunctionsMap, onCallFactory, allScheduledFunctions, disableDevelopmentScheduleFunction } = config;
1438
+ let dev;
1439
+ if (enabled) {
1440
+ const fullFunctionsMap = {
1441
+ ...developerFunctionsMap
1442
+ };
1443
+ if (allScheduledFunctions && disableDevelopmentScheduleFunction !== false) {
1444
+ fullFunctionsMap[firebase.SCHEDULED_FUNCTION_DEV_FUNCTION_SPECIFIER] = makeScheduledFunctionDevelopmentFunction({
1445
+ allScheduledFunctions
1446
+ });
1447
+ }
1448
+ let onCallFunction = onCallDevelopmentFunction(fullFunctionsMap);
1449
+ if (secure != false) {
1450
+ onCallFunction = inAuthContext(onCallFunction);
1451
+ }
1452
+ dev = onCallFactory(onCallFunction)(nest);
1453
+ }
1454
+ else {
1455
+ dev = onCallFactory(async (x) => {
1456
+ throw unavailableError({
1457
+ message: 'developer tools service is not enabled.'
1458
+ });
1459
+ })(nest);
1460
+ }
1461
+ return {
1462
+ dev
1463
+ };
1464
+ }
1465
+
1466
+ exports.DefaultFirebaseServerEnvService = class DefaultFirebaseServerEnvService extends nestjs.ServerEnvironmentService {
1467
+ /**
1468
+ * Enabled when not in production and not in a testing environment.
1469
+ */
1470
+ get developmentSchedulerEnabled() {
1471
+ return !this.isProduction && !this.isTestingEnv;
1472
+ }
1473
+ };
1474
+ exports.DefaultFirebaseServerEnvService = __decorate([
1475
+ common.Injectable()
1476
+ ], exports.DefaultFirebaseServerEnvService);
1477
+
1478
+ function nestAppIsProductionEnvironment(nest) {
1479
+ return () => nest().then((x) => x.get(FirebaseServerEnvService).isProduction);
1480
+ }
1481
+ function nestAppHasDevelopmentSchedulerEnabled(nest) {
1482
+ return () => nest().then((x) => x.get(FirebaseServerEnvService).developmentSchedulerEnabled);
1483
+ }
1484
+
1485
+ // MARK: Tokens
1486
+ /**
1487
+ * Token to access the Firestore.
1488
+ */
1489
+ const FIREBASE_FIRESTORE_TOKEN = 'FIREBASE_FIRESTORE_TOKEN';
1490
+ /**
1491
+ * Token to access the root FirestoreContext for a server.
1492
+ */
1493
+ const FIREBASE_FIRESTORE_CONTEXT_TOKEN = 'FIREBASE_FIRESTORE_CONTEXT_TOKEN';
1494
+ /**
1495
+ * Nest provider module for Firebase that provides a firestore, etc. from the firestore token.
1496
+ */
1497
+ exports.FirebaseServerFirestoreModule = class FirebaseServerFirestoreModule {
1498
+ };
1499
+ exports.FirebaseServerFirestoreModule = __decorate([
1500
+ common.Module({
1501
+ providers: [
1502
+ {
1503
+ provide: FIREBASE_FIRESTORE_TOKEN,
1504
+ useFactory: (app) => app.firestore(),
1505
+ inject: [FIREBASE_APP_TOKEN]
1506
+ }
1507
+ ],
1508
+ exports: [FIREBASE_FIRESTORE_TOKEN]
1509
+ })
1510
+ ], exports.FirebaseServerFirestoreModule);
1511
+ /**
1512
+ * Nest provider module for firebase that includes the FirebaseServerFirestoreModule and provides a value for FIRESTORE_CONTEXT_TOKEN using the googleCloudFirestoreContextFactory.
1513
+ */
1514
+ exports.FirebaseServerFirestoreContextModule = class FirebaseServerFirestoreContextModule {
1515
+ };
1516
+ exports.FirebaseServerFirestoreContextModule = __decorate([
1517
+ common.Module({
1518
+ imports: [exports.FirebaseServerFirestoreModule],
1519
+ providers: [
1520
+ {
1521
+ provide: FIREBASE_FIRESTORE_CONTEXT_TOKEN,
1522
+ useFactory: googleCloudFirestoreContextFactory,
1523
+ inject: [FIREBASE_FIRESTORE_TOKEN]
1524
+ }
1525
+ ],
1526
+ exports: [exports.FirebaseServerFirestoreModule, FIREBASE_FIRESTORE_CONTEXT_TOKEN]
1527
+ })
1528
+ ], exports.FirebaseServerFirestoreContextModule);
1529
+ /**
1530
+ * Used to configure a Nestjs provider for a FirestoreCollections-type object that is initialized with a FirestoreContext.
1531
+ *
1532
+ * @param type
1533
+ * @param useFactory
1534
+ * @returns
1535
+ */
1536
+ function provideAppFirestoreCollections({ provide, useFactory }) {
1537
+ return [
1538
+ {
1539
+ provide,
1540
+ useFactory,
1541
+ inject: [FIREBASE_FIRESTORE_CONTEXT_TOKEN]
1542
+ }
1543
+ ];
1544
+ }
1545
+ /**
1546
+ * Convenience function used to generate ModuleMetadata for an app's Firestore related modules and an appFirestoreCollection
1547
+ *
1548
+ * @param provide
1549
+ * @param useFactory
1550
+ * @returns
1551
+ */
1552
+ function appFirestoreModuleMetadata(config) {
1553
+ return {
1554
+ imports: [exports.FirebaseServerFirestoreContextModule, ...(config.imports ?? [])],
1555
+ exports: [exports.FirebaseServerFirestoreContextModule, config.provide, ...(config.exports ?? [])],
1556
+ providers: [...provideAppFirestoreCollections(config), ...(config.providers ?? [])]
1557
+ };
1558
+ }
1559
+
1560
+ /**
1561
+ * Creates a BlockingFunctionWithHandler from the input.
1562
+ *
1563
+ * @param blockingFunctionBuilder
1564
+ * @param handler
1565
+ * @returns
1566
+ */
1567
+ function makeBlockingFunctionWithHandler(blockingFunctionBuilder, handler, opts) {
1568
+ const blockingFn = opts != null ? blockingFunctionBuilder(opts, handler) : blockingFunctionBuilder(handler);
1569
+ blockingFn.__handler = handler;
1570
+ return blockingFn;
1571
+ }
1572
+ /**
1573
+ * Creates a BlockingFunctionHandlerWithNestContextFactory.
1574
+ *
1575
+ * @param appFactory
1576
+ * @param makeNestContext
1577
+ * @returns
1578
+ */
1579
+ function blockingFunctionHandlerWithNestContextFactory(makeNestContext) {
1580
+ return (fn) => {
1581
+ return (nestAppPromiseGetter) => {
1582
+ const handlerBuilder = (handler) => {
1583
+ const fnHandler = (event) => nestAppPromiseGetter().then((nestApplication) => handler({
1584
+ ...event,
1585
+ nest: makeNestContext(nestApplication)
1586
+ }));
1587
+ return fnHandler;
1588
+ };
1589
+ return fn(handlerBuilder);
1590
+ };
1591
+ };
1592
+ }
1593
+
1594
+ /**
1595
+ * Creates a factory for generating OnCallWithNestApplication (firebase-functions v2) functions.
1596
+ *
1597
+ * @param opts
1598
+ * @returns
1599
+ */
1600
+ function onCallHandlerWithNestApplicationFactory(defaultOpts = {}) {
1601
+ return (fn, opts) => {
1602
+ return (nestAppPromiseGetter) => v2.https.onCall({ ...defaultOpts, ...opts }, (request) => nestAppPromiseGetter().then((nestApplication) => fn({
1603
+ ...request,
1604
+ nestApplication
1605
+ })));
1606
+ };
1607
+ }
1608
+ /**
1609
+ * Creates a factory for generating OnCallWithNestContext functions with a nest context object that is generated by the input function.
1610
+ *
1611
+ * @param appFactory
1612
+ * @param makeNestContext
1613
+ * @returns
1614
+ */
1615
+ function onCallHandlerWithNestContextFactory(appFactory, makeNestContext) {
1616
+ return (fn, opts) => appFactory((request) => fn(setNestContextOnRequest(makeNestContext, request)), opts);
1617
+ }
1618
+
1619
+ /**
1620
+ * Creates a CloudEventHandlerWithNestContextFactory.
1621
+ *
1622
+ * @param appFactory
1623
+ * @param makeNestContext
1624
+ * @returns
1625
+ */
1626
+ function cloudEventHandlerWithNestContextFactory(makeNestContext) {
1627
+ return (fn) => {
1628
+ return (nestAppPromiseGetter) => {
1629
+ const handlerBuilder = (handler) => {
1630
+ const fnHandler = (event) => nestAppPromiseGetter().then((nestApplication) => handler({
1631
+ ...event,
1632
+ nest: makeNestContext(nestApplication)
1633
+ }));
1634
+ return fnHandler;
1635
+ };
1636
+ return fn(handlerBuilder);
1637
+ };
1638
+ };
1639
+ }
1640
+
1641
+ function setNestContextOnScheduleRequest(makeNestContext, request) {
1642
+ request.nest = makeNestContext(request.nestApplication);
1643
+ return request;
1644
+ }
1645
+
1646
+ function makeOnScheduleHandlerWithNestApplicationRequest(nestApplication, scheduleContext) {
1647
+ return {
1648
+ nestApplication,
1649
+ scheduleContext
1650
+ };
1651
+ }
1652
+ /**
1653
+ * Creates a factory for generating OnCallWithNestApplication functions.
1654
+ *
1655
+ * @param nestAppPromiseGetter
1656
+ * @returns
1657
+ */
1658
+ function onScheduleHandlerWithNestApplicationFactory(baseScheduleConfig) {
1659
+ return (inputSchedule, fn) => {
1660
+ const schedule = util.mergeObjects([baseScheduleConfig, inputSchedule]);
1661
+ if (!schedule.schedule) {
1662
+ if (schedule.cron) {
1663
+ if (typeof schedule.cron === 'number') {
1664
+ schedule.schedule = util.cronExpressionRepeatingEveryNMinutes(schedule.cron);
1665
+ }
1666
+ else {
1667
+ schedule.schedule = schedule.cron;
1668
+ }
1669
+ }
1670
+ else {
1671
+ throw new Error('Missing required "cron" or "schedule" variable for configuration.');
1672
+ }
1673
+ }
1674
+ return (nestAppPromiseGetter) => {
1675
+ const runNow = (scheduleContext) => nestAppPromiseGetter().then((x) => fn(makeOnScheduleHandlerWithNestApplicationRequest(x, scheduleContext)));
1676
+ const fnn = v2.scheduler.onSchedule(schedule, runNow);
1677
+ fnn._schedule = schedule;
1678
+ fnn._runNow = runNow;
1679
+ return fnn;
1680
+ };
1681
+ };
1682
+ }
1683
+ /**
1684
+ * Creates a factory for generating OnCallWithNestContext functions with a nest context object that is generated by the input function.
1685
+ *
1686
+ * @param appFactory
1687
+ * @param makeNestContext
1688
+ * @returns
1689
+ */
1690
+ function onScheduleHandlerWithNestContextFactory(appFactory, makeNestContext) {
1691
+ return (schedule, fn) => appFactory(schedule, (request) => fn(setNestContextOnScheduleRequest(makeNestContext, request)));
1692
+ }
1693
+
1694
+ /**
1695
+ * Creates a TaskQueueFunctionHandlerWithNestContextFactory.
1696
+ *
1697
+ * @param appFactory
1698
+ * @param makeNestContext
1699
+ * @returns
1700
+ */
1701
+ function taskQueueFunctionHandlerWithNestContextFactory(makeNestContext) {
1702
+ return (fn) => {
1703
+ return (nestAppPromiseGetter) => {
1704
+ const handlerBuilder = (handler) => {
1705
+ const fnHandler = (taskRequest) => nestAppPromiseGetter().then((nestApplication) => handler({
1706
+ ...taskRequest,
1707
+ nest: makeNestContext(nestApplication)
1708
+ }));
1709
+ return fnHandler;
1710
+ };
1711
+ return fn(handlerBuilder);
1712
+ };
1713
+ };
1714
+ }
1715
+ // TODO(FUTURE): Add factory that also adds onTaskDispatched usage, as the above is incomplete for full usage and only sets up a function for the request.
1716
+
1717
+ class AbstractFirebaseServerActionsContext {
1718
+ }
1719
+ function firebaseServerActionsContext(options) {
1720
+ return {
1721
+ ...firebaseServerActionsTransformContext(options)
1722
+ };
1723
+ }
1724
+ const defaultFirebaseServerActionsTransformFactoryLogErrorFunction = (details) => {
1725
+ console.log('firebaseServerActionsTransformFactory() encountered validation error: ', details);
1726
+ };
1727
+ function firebaseServerActionsTransformContext(options) {
1728
+ const firebaseServerActionTransformFactory = firebaseServerActionsTransformFactory(options);
1729
+ const firebaseServerActionTransformFunctionFactory = model.toTransformAndValidateFunctionResultFactory(firebaseServerActionTransformFactory);
1730
+ return {
1731
+ firebaseServerActionTransformFactory,
1732
+ firebaseServerActionTransformFunctionFactory
1733
+ };
1734
+ }
1735
+ const FIREBASE_SERVER_VALIDATION_ERROR_CODE = 'VALIDATION_ERROR';
1736
+ /**
1737
+ *
1738
+ * @param validationError
1739
+ * @returns
1740
+ */
1741
+ function firebaseServerValidationServerError(validationError) {
1742
+ const nestValidationExceptionFactory = new common.ValidationPipe({
1743
+ forbidUnknownValues: false
1744
+ }).createExceptionFactory();
1745
+ const nestError = nestValidationExceptionFactory(validationError);
1746
+ const data = nestError.getResponse();
1747
+ return {
1748
+ message: 'One or more data/form validation errors occurred.',
1749
+ code: FIREBASE_SERVER_VALIDATION_ERROR_CODE,
1750
+ data
1751
+ };
1752
+ }
1753
+ /**
1754
+ * Creates a new badRequestError with the validation error details as the response data.
1755
+ *
1756
+ * @param validationError
1757
+ * @returns
1758
+ */
1759
+ function firebaseServerValidationError(validationError) {
1760
+ const serverError = firebaseServerValidationServerError(validationError);
1761
+ return badRequestError(serverError);
1762
+ }
1763
+ function firebaseServerActionsTransformFactory(options) {
1764
+ const { logError, defaultValidationOptions } = options ?? {};
1765
+ const logErrorFunction = logError !== false ? (typeof logError === 'function' ? logError : defaultFirebaseServerActionsTransformFactoryLogErrorFunction) : util.mapIdentityFunction;
1766
+ return model.transformAndValidateObjectFactory({
1767
+ handleValidationError: (validationError) => {
1768
+ const serverError = firebaseServerValidationServerError(validationError);
1769
+ const { data } = serverError;
1770
+ logErrorFunction(data);
1771
+ throw badRequestError(serverError);
1772
+ },
1773
+ defaultValidationOptions
1774
+ });
1775
+ }
1776
+
1777
+ function injectNestIntoRequest(nest, request) {
1778
+ return {
1779
+ ...request,
1780
+ nest
1781
+ };
1782
+ }
1783
+ function injectNestApplicationContextIntoRequest(nestContext, request) {
1784
+ return {
1785
+ ...request,
1786
+ nestApplication: nestContext
1787
+ };
1788
+ }
1789
+
1790
+ /**
1791
+ * Can be injected to retrieve information about the global prefix configured for the app.
1792
+ */
1793
+ class GlobalRoutePrefixConfig {
1794
+ globalApiRoutePrefix;
1795
+ }
1796
+
1797
+ /**
1798
+ * Middleware that verifies the X-Firebase-AppCheck header using admin.
1799
+ *
1800
+ * It ignores all webhook paths by default.
1801
+ */
1802
+ exports.FirebaseAppCheckMiddleware = class FirebaseAppCheckMiddleware {
1803
+ globalRoutePrefixConfig;
1804
+ logger = new common.Logger('FirebaseAppCheckMiddleware');
1805
+ _ignoredWebhookPath;
1806
+ constructor(globalRoutePrefixConfig) {
1807
+ this.globalRoutePrefixConfig = globalRoutePrefixConfig;
1808
+ this._ignoredWebhookPath = this.globalRoutePrefixConfig?.globalApiRoutePrefix ? `${this.globalRoutePrefixConfig.globalApiRoutePrefix}${nestjs.DEFAULT_BASE_WEBHOOK_PATH}` : nestjs.DEFAULT_BASE_WEBHOOK_PATH;
1809
+ }
1810
+ async use(req, res, next) {
1811
+ const isIgnoredRoute = this.isIgnoredRequest(req);
1812
+ let error;
1813
+ if (!isIgnoredRoute) {
1814
+ error = await verifyAppCheckInRequest(req);
1815
+ if (error) {
1816
+ this.logger.error('app check token failed verify');
1817
+ }
1818
+ }
1819
+ next(error);
1820
+ }
1821
+ isIgnoredRequest(req) {
1822
+ const isIgnoredRoute = req.skipAppCheck || this.isIgnoredPath(req.baseUrl);
1823
+ return isIgnoredRoute;
1824
+ }
1825
+ isIgnoredPath(path) {
1826
+ return path.startsWith(this._ignoredWebhookPath);
1827
+ }
1828
+ };
1829
+ exports.FirebaseAppCheckMiddleware = __decorate([
1830
+ common.Injectable(),
1831
+ __param(0, common.Optional()),
1832
+ __param(0, common.Inject(GlobalRoutePrefixConfig)),
1833
+ __metadata("design:paramtypes", [Object])
1834
+ ], exports.FirebaseAppCheckMiddleware);
1835
+ /**
1836
+ * Verifies the AppCheck parameter. If it fails, a value is returned.
1837
+ *
1838
+ * @param req
1839
+ * @param res
1840
+ * @param next
1841
+ * @returns
1842
+ */
1843
+ async function verifyAppCheckInRequest(req) {
1844
+ const appCheckToken = req.header('X-Firebase-AppCheck');
1845
+ let error;
1846
+ if (!appCheckToken) {
1847
+ error = new common.ForbiddenException();
1848
+ }
1849
+ else {
1850
+ // verify the token
1851
+ try {
1852
+ await admin.appCheck().verifyToken(appCheckToken);
1853
+ }
1854
+ catch (e) {
1855
+ error = new common.ForbiddenException();
1856
+ }
1857
+ }
1858
+ return error;
1859
+ }
1860
+
1861
+ /**
1862
+ * Convenience class that mirrors the ConfigureAppCheckMiddlewareModule class in @dereekb/nestjs, but for Firebase apps.
1863
+ */
1864
+ exports.ConfigureFirebaseAppCheckMiddlewareModule = class ConfigureFirebaseAppCheckMiddlewareModule {
1865
+ logger = new common.Logger('ConfigureFirebaseAppCheckMiddlewareModule');
1866
+ configure(consumer) {
1867
+ consumer.apply(exports.FirebaseAppCheckMiddleware).forRoutes('*');
1868
+ this.logger.debug('Configured firebase webhook routes with proper middleware.');
1869
+ }
1870
+ };
1871
+ exports.ConfigureFirebaseAppCheckMiddlewareModule = __decorate([
1872
+ common.Module({})
1873
+ ], exports.ConfigureFirebaseAppCheckMiddlewareModule);
1874
+
1875
+ /**
1876
+ * nestjs decorator that will instruct FirebaseAppCheckMiddleware to skip AppCheck for related requests.
1877
+ */
1878
+ const SkipAppCheck = common.createParamDecorator(async (_, context) => {
1879
+ const req = context.switchToHttp().getRequest();
1880
+ req.skipAppCheck = true;
1881
+ });
1882
+
1883
+ exports.FirebaseRawBodyMiddleware = class FirebaseRawBodyMiddleware {
1884
+ use(req, res, next) {
1885
+ req.body = req.rawBody;
1886
+ next();
1887
+ }
1888
+ };
1889
+ exports.FirebaseRawBodyMiddleware = __decorate([
1890
+ common.Injectable()
1891
+ ], exports.FirebaseRawBodyMiddleware);
1892
+
1893
+ /**
1894
+ * Convenience class that mirrors the ConfigureWebhookMiddlewareModule class in @dereekb/nestjs, but for Firebase apps.
1895
+ *
1896
+ * Requests to /webhook/* have their request.body value set to the rawBody.
1897
+ */
1898
+ exports.ConfigureFirebaseWebhookMiddlewareModule = class ConfigureFirebaseWebhookMiddlewareModule {
1899
+ logger = new common.Logger('ConfigureFirebaseWebhookMiddlewareModule');
1900
+ configure(consumer) {
1901
+ consumer.apply(exports.FirebaseRawBodyMiddleware).forRoutes(nestjs.DEFAULT_WEBHOOK_MIDDLEWARE_ROUTE_INFO);
1902
+ this.logger.debug('Configured firebase webhook routes with proper middleware.');
1903
+ }
1904
+ };
1905
+ exports.ConfigureFirebaseWebhookMiddlewareModule = __decorate([
1906
+ common.Module({})
1907
+ ], exports.ConfigureFirebaseWebhookMiddlewareModule);
1908
+
1909
+ const nestFirebaseDoesNotExistError = (firebaseContextGrantedModelRoles) => {
1910
+ return modelNotAvailableError({
1911
+ data: {
1912
+ id: firebaseContextGrantedModelRoles.data?.document.key,
1913
+ type: firebaseContextGrantedModelRoles.data?.document.modelType
1914
+ }
1915
+ });
1916
+ };
1917
+ const nestFirebaseForbiddenPermissionError = (firebaseContextGrantedModelRoles, roles) => {
1918
+ return forbiddenError({
1919
+ data: {
1920
+ id: firebaseContextGrantedModelRoles.data?.document.key,
1921
+ type: firebaseContextGrantedModelRoles.data?.document.modelType,
1922
+ roles
1923
+ }
1924
+ });
1925
+ };
1926
+
1927
+ function onCallSpecifierHandler(config) {
1928
+ const map = util.objectToMap(config);
1929
+ const fn = (request) => {
1930
+ const { specifier = firebase.MODEL_FUNCTION_FIREBASE_CRUD_FUNCTION_SPECIFIER_DEFAULT } = request;
1931
+ const handler = map.get(specifier);
1932
+ if (handler != null) {
1933
+ assertRequestRequiresAuthForFunction(handler, request);
1934
+ return handler(request);
1935
+ }
1936
+ else {
1937
+ throw unknownModelCrudFunctionSpecifierError(specifier);
1938
+ }
1939
+ };
1940
+ fn._requireAuth = false;
1941
+ return fn;
1942
+ }
1943
+ function unknownModelCrudFunctionSpecifierError(specifier) {
1944
+ return badRequestError(util.serverError({
1945
+ status: 400,
1946
+ code: 'UNKNOWN_SPECIFIER_ERROR',
1947
+ message: 'Invalid/unknown specifier for this function.',
1948
+ data: {
1949
+ specifier
1950
+ }
1951
+ }));
1952
+ }
1953
+
1954
+ /**
1955
+ * Creates a OnCallWithAuthorizedNestContext function for creating a model.
1956
+ *
1957
+ * @param map
1958
+ * @returns
1959
+ */
1960
+ function onCallModel(map, config = {}) {
1961
+ const { preAssert = () => undefined } = config;
1962
+ return (request) => {
1963
+ const call = request.data?.call;
1964
+ if (call) {
1965
+ const callFn = map[call];
1966
+ if (callFn) {
1967
+ const { specifier, modelType } = request.data;
1968
+ preAssert({ call, request, modelType, specifier });
1969
+ return callFn(request);
1970
+ }
1971
+ else {
1972
+ throw onCallModelUnknownCallTypeError(call);
1973
+ }
1974
+ }
1975
+ else {
1976
+ throw onCallModelMissingCallTypeError();
1977
+ }
1978
+ };
1979
+ }
1980
+ function onCallModelMissingCallTypeError() {
1981
+ return badRequestError(util.serverError({
1982
+ status: 400,
1983
+ code: 'CALL_TYPE_MISSING_ERROR',
1984
+ message: `The call type was missing from the request.`
1985
+ }));
1986
+ }
1987
+ function onCallModelUnknownCallTypeError(call) {
1988
+ return badRequestError(util.serverError({
1989
+ status: 400,
1990
+ code: 'UNKNOWN_CALL_TYPE_ERROR',
1991
+ message: `Unknown call type "${call}".`,
1992
+ data: {
1993
+ call
1994
+ }
1995
+ }));
1996
+ }
1997
+ function _onCallWithCallTypeFunction(map, config) {
1998
+ const { callType, crudType, preAssert = () => undefined, throwOnUnknownModelType } = config;
1999
+ return (request) => {
2000
+ const modelType = request.data?.modelType;
2001
+ const crudFn = map[modelType];
2002
+ if (crudFn) {
2003
+ const specifier = request.data.specifier;
2004
+ assertRequestRequiresAuthForFunction(crudFn, request);
2005
+ preAssert({ call: callType, request, modelType, specifier });
2006
+ return crudFn({
2007
+ ...request,
2008
+ specifier,
2009
+ data: request.data.data
2010
+ });
2011
+ }
2012
+ else {
2013
+ throw throwOnUnknownModelType(modelType);
2014
+ }
2015
+ };
2016
+ }
2017
+
2018
+ function onCallCreateModel(map, config = {}) {
2019
+ const { preAssert } = config;
2020
+ return _onCallWithCallTypeFunction(map, {
2021
+ callType: 'create',
2022
+ crudType: 'create',
2023
+ preAssert,
2024
+ throwOnUnknownModelType: createModelUnknownModelTypeError
2025
+ });
2026
+ }
2027
+ function createModelUnknownModelTypeError(modelType) {
2028
+ return badRequestError(util.serverError({
2029
+ status: 400,
2030
+ code: 'UNKNOWN_TYPE_ERROR',
2031
+ message: `Invalid type "${modelType}" to create.`,
2032
+ data: {
2033
+ modelType
2034
+ }
2035
+ }));
2036
+ }
2037
+
2038
+ function onCallReadModel(map, config = {}) {
2039
+ const { preAssert } = config;
2040
+ return _onCallWithCallTypeFunction(map, {
2041
+ callType: 'read',
2042
+ crudType: 'read',
2043
+ preAssert,
2044
+ throwOnUnknownModelType: readModelUnknownModelTypeError
2045
+ });
2046
+ }
2047
+ function readModelUnknownModelTypeError(modelType) {
2048
+ return badRequestError(util.serverError({
2049
+ status: 400,
2050
+ code: 'UNKNOWN_TYPE_ERROR',
2051
+ message: 'Invalid type to read.',
2052
+ data: {
2053
+ modelType
2054
+ }
2055
+ }));
2056
+ }
2057
+
2058
+ function onCallUpdateModel(map, config = {}) {
2059
+ const { preAssert } = config;
2060
+ return _onCallWithCallTypeFunction(map, {
2061
+ callType: 'update',
2062
+ crudType: 'update',
2063
+ preAssert,
2064
+ throwOnUnknownModelType: updateModelUnknownModelTypeError
2065
+ });
2066
+ }
2067
+ function updateModelUnknownModelTypeError(modelType) {
2068
+ return badRequestError(util.serverError({
2069
+ status: 400,
2070
+ code: 'UNKNOWN_TYPE_ERROR',
2071
+ message: 'Invalid type to update.',
2072
+ data: {
2073
+ modelType
2074
+ }
2075
+ }));
2076
+ }
2077
+
2078
+ function onCallDeleteModel(map, config = {}) {
2079
+ const { preAssert } = config;
2080
+ return _onCallWithCallTypeFunction(map, {
2081
+ callType: 'delete',
2082
+ crudType: 'delete',
2083
+ preAssert,
2084
+ throwOnUnknownModelType: deleteModelUnknownModelTypeError
2085
+ });
2086
+ }
2087
+ function deleteModelUnknownModelTypeError(modelType) {
2088
+ return badRequestError(util.serverError({
2089
+ status: 400,
2090
+ code: 'UNKNOWN_TYPE_ERROR',
2091
+ message: 'Invalid type to delete.',
2092
+ data: {
2093
+ modelType
2094
+ }
2095
+ }));
2096
+ }
2097
+
2098
+ function googleCloudStorageBucketForStorageFilePath(storage, path) {
2099
+ return storage.bucket(path.bucketId);
2100
+ }
2101
+ function googleCloudStorageFileForStorageFilePath(storage, path) {
2102
+ return googleCloudStorageBucketForStorageFilePath(storage, path).file(path.pathString);
2103
+ }
2104
+ function googleCloudFileMetadataToStorageMetadata(file, metadata) {
2105
+ const fullPath = file.name;
2106
+ const generation = String(metadata.generation ?? file.generation);
2107
+ const metageneration = String(metadata.metageneration);
2108
+ const size = Number(metadata.size);
2109
+ const customMetadata = metadata.metadata;
2110
+ return {
2111
+ bucket: file.bucket.name,
2112
+ fullPath,
2113
+ generation,
2114
+ metageneration,
2115
+ name: file.name,
2116
+ size,
2117
+ timeCreated: metadata.timeCreated,
2118
+ updated: metadata.updated,
2119
+ md5Hash: metadata.md5Hash,
2120
+ cacheControl: metadata.cacheControl,
2121
+ contentDisposition: metadata.contentDisposition,
2122
+ contentEncoding: metadata.contentEncoding,
2123
+ contentLanguage: metadata.contentLanguage,
2124
+ contentType: metadata.contentType,
2125
+ customMetadata
2126
+ };
2127
+ }
2128
+ function googleCloudStorageAccessorFile(storage$1, storagePath) {
2129
+ const file = googleCloudStorageFileForStorageFilePath(storage$1, storagePath);
2130
+ function makeDownloadOptions(maxDownloadSizeBytes) {
2131
+ return {
2132
+ ...(maxDownloadSizeBytes
2133
+ ? {
2134
+ // end is inclusive
2135
+ end: maxDownloadSizeBytes - 1
2136
+ }
2137
+ : undefined)
2138
+ };
2139
+ }
2140
+ function _configureMetadata(options) {
2141
+ const customMetadata = util.filterUndefinedValues({
2142
+ ...options.metadata?.customMetadata,
2143
+ ...options?.customMetadata
2144
+ });
2145
+ return util.filterUndefinedValues({
2146
+ cacheControl: options.metadata?.cacheControl,
2147
+ contentDisposition: options.metadata?.contentDisposition,
2148
+ contentEncoding: options.metadata?.contentEncoding,
2149
+ contentLanguage: options.metadata?.contentLanguage,
2150
+ contentType: options.metadata?.contentType,
2151
+ metadata: !util.objectHasNoKeys(customMetadata) ? customMetadata : undefined
2152
+ });
2153
+ }
2154
+ function makeUploadOptions(options) {
2155
+ let metadata;
2156
+ if (options != null) {
2157
+ metadata = _configureMetadata({
2158
+ metadata: {
2159
+ ...options.metadata,
2160
+ contentType: options.contentType ?? options.metadata?.contentType
2161
+ },
2162
+ customMetadata: options.customMetadata
2163
+ });
2164
+ }
2165
+ return {
2166
+ // non-resumable
2167
+ resumable: false,
2168
+ // add content type and other custom metadata
2169
+ ...(metadata ? { metadata } : undefined)
2170
+ };
2171
+ }
2172
+ function asFileMetadata(metadata) {
2173
+ return _configureMetadata({ metadata });
2174
+ }
2175
+ function makeStoragePathForPath(newPath) {
2176
+ let path;
2177
+ if (typeof newPath === 'string') {
2178
+ path = {
2179
+ bucketId: file.bucket.name,
2180
+ pathString: newPath
2181
+ };
2182
+ }
2183
+ else {
2184
+ path = newPath;
2185
+ }
2186
+ return path;
2187
+ }
2188
+ async function copy(newPath, options) {
2189
+ const newStoragePath = makeStoragePathForPath(newPath);
2190
+ const newFile = googleCloudStorageAccessorFile(storage$1, newStoragePath);
2191
+ return _copyWithFile(newFile, options);
2192
+ }
2193
+ async function _copyWithFile(newFile, options) {
2194
+ const copyOptions = {
2195
+ ...options
2196
+ };
2197
+ await file.copy(newFile.reference, copyOptions);
2198
+ return newFile;
2199
+ }
2200
+ /**
2201
+ * Configuration for the public ACL.
2202
+ */
2203
+ const PUBLIC_ACL = {
2204
+ entity: 'allUsers',
2205
+ role: 'READER'
2206
+ };
2207
+ const accessorFile = {
2208
+ reference: file,
2209
+ storagePath,
2210
+ exists: () => file.exists().then((x) => x[0]),
2211
+ getDownloadUrl: () => file.getMetadata().then(() => file.publicUrl()),
2212
+ getSignedUrl: async (input) => {
2213
+ const expires = input?.expiresAt ??
2214
+ (input?.expiresIn != null
2215
+ ? dateFns.addMilliseconds(new Date(), input.expiresIn) // use expiresIn if provided
2216
+ : dateFns.addHours(new Date(), 1)); // default expiration in 1 hour
2217
+ const config = {
2218
+ ...input,
2219
+ action: input?.action ?? 'read',
2220
+ expires,
2221
+ expiresIn: undefined, // clear from input
2222
+ expiresAt: undefined
2223
+ };
2224
+ return file
2225
+ .getSignedUrl(config)
2226
+ .then((x) => x[0])
2227
+ .catch((e) => {
2228
+ let publicUrlBackup;
2229
+ if (e && e.name === 'SigningError' && (nestjs.isTestNodeEnv() || process.env.FIREBASE_STORAGE_EMULATOR_HOST)) {
2230
+ // NOTE: Signing does not behave properly in the emulator as it is not supported.
2231
+ // https://github.com/firebase/firebase-tools/issues/3400
2232
+ // we can return the public url instead.
2233
+ // This is fine, as in production this file url is protected by ACLs anyways.
2234
+ publicUrlBackup = file.publicUrl();
2235
+ }
2236
+ else {
2237
+ throw e;
2238
+ }
2239
+ return publicUrlBackup;
2240
+ });
2241
+ },
2242
+ getMetadata: () => file.getMetadata().then((x) => googleCloudFileMetadataToStorageMetadata(file, x[0])),
2243
+ setMetadata: (metadata) => file.setMetadata(asFileMetadata(metadata)).then((x) => googleCloudFileMetadataToStorageMetadata(file, x[0])),
2244
+ getBytes: (maxDownloadSizeBytes) => file.download(makeDownloadOptions(maxDownloadSizeBytes)).then((x) => x[0]),
2245
+ getStream: (maxDownloadSizeBytes) => file.createReadStream(makeDownloadOptions(maxDownloadSizeBytes)),
2246
+ upload: async (input, options) => {
2247
+ let dataToUpload;
2248
+ if (typeof input === 'string') {
2249
+ const parsedStringFormat = firebase.assertStorageUploadOptionsStringFormat(options);
2250
+ const stringFormat = parsedStringFormat === 'raw' ? 'utf-8' : parsedStringFormat;
2251
+ if (stringFormat === 'data_url') {
2252
+ // TODO(FUTURE): support this later if necessary. Server should really never see this type.
2253
+ throw new Error('"data_url" is unsupported.');
2254
+ }
2255
+ dataToUpload = Buffer.from(input, stringFormat);
2256
+ }
2257
+ else {
2258
+ if (Buffer.isBuffer(input)) {
2259
+ dataToUpload = input;
2260
+ }
2261
+ else if (types.isUint8Array(input)) {
2262
+ dataToUpload = Buffer.from(input);
2263
+ }
2264
+ else {
2265
+ // NOTE: these values shouldn't ever be encountered in the NodeJS environment. May remove later.
2266
+ if (types.isArrayBuffer(input)) {
2267
+ dataToUpload = Buffer.from(input);
2268
+ }
2269
+ else {
2270
+ dataToUpload = input.arrayBuffer().then((x) => Buffer.from(x));
2271
+ }
2272
+ }
2273
+ }
2274
+ const data = await dataToUpload;
2275
+ return file.save(data, makeUploadOptions(options));
2276
+ },
2277
+ uploadStream: (options) => file.createWriteStream(makeUploadOptions(options)),
2278
+ move: async (newPath, options) => {
2279
+ const newStoragePath = makeStoragePathForPath(newPath);
2280
+ const newFile = googleCloudStorageAccessorFile(storage$1, newStoragePath);
2281
+ const moveOptions = {
2282
+ ...options
2283
+ };
2284
+ await file.moveFileAtomic(newFile.reference, moveOptions).catch(async (e) => {
2285
+ if (e instanceof storage.ApiError && e.response?.statusMessage === 'Not Implemented') {
2286
+ // NOTE: This is not implemented in storage emulator, so it will fail with this error in testing.
2287
+ // https://github.com/firebase/firebase-tools/issues/3751
2288
+ // we can perform the same task using copy and then deleting this file.
2289
+ await copy(newPath, moveOptions);
2290
+ await accessorFile.delete();
2291
+ }
2292
+ else {
2293
+ throw e;
2294
+ }
2295
+ });
2296
+ return newFile;
2297
+ },
2298
+ copy,
2299
+ delete: (options) => file.delete(options).then((x) => undefined),
2300
+ isPublic: () => file.isPublic().then((x) => x[0]),
2301
+ makePublic: (setPublic) => (setPublic !== false ? file.acl.add(PUBLIC_ACL) : file.acl.delete({ entity: PUBLIC_ACL.entity })).then(() => undefined),
2302
+ makePrivate: (options) => file.makePrivate(options).then(() => undefined),
2303
+ getAcls: (options) => file.acl.get(options).then((x) => ({ acls: x[0], metadata: x[1] }))
2304
+ };
2305
+ return accessorFile;
2306
+ }
2307
+ const googleCloudStorageListFilesResultFactory = firebase.storageListFilesResultFactory({
2308
+ hasItems(result) {
2309
+ return Boolean(result.apiResponse.items || result.apiResponse.prefixes);
2310
+ },
2311
+ hasNext: (result) => {
2312
+ return result.nextQuery != null;
2313
+ },
2314
+ nextPageTokenFromResult(result) {
2315
+ return result.nextQuery?.pageToken;
2316
+ },
2317
+ next(storage, options, folder, result) {
2318
+ return folder.list({ ...options, ...result.nextQuery });
2319
+ },
2320
+ file(storage, fileResult) {
2321
+ return googleCloudStorageAccessorFile(storage, fileResult.storagePath);
2322
+ },
2323
+ folder(storage, folderResult) {
2324
+ return googleCloudStorageAccessorFolder(storage, folderResult.storagePath);
2325
+ },
2326
+ filesFromResult(result) {
2327
+ const items = result.apiResponse?.items ?? [];
2328
+ return items.map((x) => ({ raw: x, name: util.slashPathName(x.name), storagePath: { bucketId: x.bucket, pathString: x.name } }));
2329
+ },
2330
+ foldersFromResult(result, folder) {
2331
+ const items = result.apiResponse?.prefixes ?? [];
2332
+ return items.map((prefix) => ({ raw: prefix, name: util.slashPathName(prefix), storagePath: { bucketId: folder.storagePath.bucketId, pathString: prefix } }));
2333
+ }
2334
+ });
2335
+ function googleCloudStorageAccessorFolder(storage, storagePath) {
2336
+ const bucket = googleCloudStorageBucketForStorageFilePath(storage, storagePath);
2337
+ const file = bucket.file(storagePath.pathString);
2338
+ const folder = {
2339
+ reference: file,
2340
+ storagePath,
2341
+ exists: async () => folder.list({ maxResults: 1 }).then((x) => x.hasItems()),
2342
+ list: (options) => {
2343
+ const { maxResults, pageToken, includeNestedResults: listAll } = options ?? {};
2344
+ const listOptions = {
2345
+ maxResults,
2346
+ pageToken,
2347
+ autoPaginate: false,
2348
+ versions: false,
2349
+ ...(listAll
2350
+ ? {
2351
+ prefix: util.toRelativeSlashPathStartType(util.fixMultiSlashesInSlashPath(storagePath.pathString + '/'))
2352
+ }
2353
+ : {
2354
+ // includeTrailingDelimiter: true,
2355
+ delimiter: util.SLASH_PATH_SEPARATOR,
2356
+ prefix: util.toRelativeSlashPathStartType(util.fixMultiSlashesInSlashPath(storagePath.pathString + '/')) // make sure the folder always ends with a slash
2357
+ })
2358
+ };
2359
+ return bucket.getFiles(listOptions).then((x) => {
2360
+ const files = x[0];
2361
+ const nextQuery = x[1];
2362
+ const apiResponse = x[2];
2363
+ const result = {
2364
+ files: files,
2365
+ nextQuery,
2366
+ apiResponse: apiResponse
2367
+ };
2368
+ return googleCloudStorageListFilesResultFactory(storage, folder, options, result);
2369
+ });
2370
+ }
2371
+ };
2372
+ return folder;
2373
+ }
2374
+ function googleCloudStorageFirebaseStorageAccessorDriver() {
2375
+ return {
2376
+ type: 'server',
2377
+ file: (storage, path) => googleCloudStorageAccessorFile(storage, path),
2378
+ folder: (storage, path) => googleCloudStorageAccessorFolder(storage, path)
2379
+ };
2380
+ }
2381
+
2382
+ function googleCloudFirebaseStorageDrivers() {
2383
+ return {
2384
+ storageDriverIdentifier: '@google-cloud/storage',
2385
+ storageDriverType: 'production',
2386
+ storageAccessorDriver: googleCloudStorageFirebaseStorageAccessorDriver()
2387
+ };
2388
+ }
2389
+
2390
+ /**
2391
+ * Basic service that implements FirebaseStorageAccessor and provides a FirebaseStorageContext.
2392
+ */
2393
+ class FirebaseServerStorageService {
2394
+ _storageContext;
2395
+ constructor(storageContext) {
2396
+ this._storageContext = storageContext;
2397
+ }
2398
+ get storageContext() {
2399
+ return this._storageContext;
2400
+ }
2401
+ defaultBucket() {
2402
+ return this.storageContext.defaultBucket();
2403
+ }
2404
+ file(path) {
2405
+ return this.storageContext.file(path);
2406
+ }
2407
+ folder(path) {
2408
+ return this.storageContext.folder(path);
2409
+ }
2410
+ }
2411
+
2412
+ /**
2413
+ * Creates a FirestoreContextFactory that uses the @google-cloud/storage package.
2414
+ */
2415
+ const googleCloudFirebaseStorageContextFactory = firebase.firebaseStorageContextFactory(googleCloudFirebaseStorageDrivers());
2416
+ /**
2417
+ * Retrieves the GoogleCloudStorage object from the input FirebaseAdmin Storage type.
2418
+ *
2419
+ * @param storage
2420
+ * @returns
2421
+ */
2422
+ function googleCloudStorageFromFirebaseAdminStorage(storage) {
2423
+ return storage.storageClient;
2424
+ }
2425
+
2426
+ // MARK: Tokens
2427
+ /**
2428
+ * Token to access the Storage.
2429
+ */
2430
+ const FIREBASE_STORAGE_TOKEN = 'FIREBASE_STORAGE_TOKEN';
2431
+ /**
2432
+ * Token to access the root StorageContext for a server.
2433
+ */
2434
+ const FIREBASE_STORAGE_CONTEXT_TOKEN = 'FIREBASE_STORAGE_CONTEXT_TOKEN';
2435
+ /**
2436
+ * Token to the default bucket id string
2437
+ */
2438
+ const FIREBASE_STORAGE_CONTEXT_FACTORY_CONFIG_TOKEN = 'FIREBASE_STORAGE_CONTEXT_FACTORY_CONFIG_TOKEN';
2439
+ /**
2440
+ * Nest provider module for Firebase that provides a firestore, etc. from the firestore token.
2441
+ */
2442
+ exports.FirebaseServerStorageModule = class FirebaseServerStorageModule {
2443
+ };
2444
+ exports.FirebaseServerStorageModule = __decorate([
2445
+ common.Module({
2446
+ providers: [
2447
+ {
2448
+ provide: FIREBASE_STORAGE_TOKEN,
2449
+ useFactory: (app) => googleCloudStorageFromFirebaseAdminStorage(app.storage()),
2450
+ inject: [FIREBASE_APP_TOKEN]
2451
+ }
2452
+ ],
2453
+ exports: [FIREBASE_STORAGE_TOKEN]
2454
+ })
2455
+ ], exports.FirebaseServerStorageModule);
2456
+ /**
2457
+ * Nest provider module for firebase that includes the FirebaseServerStorageModule and provides a value for STORAGE_CONTEXT_TOKEN using the googleCloudStorageContextFactory.
2458
+ */
2459
+ exports.FirebaseServerStorageContextModule = class FirebaseServerStorageContextModule {
2460
+ };
2461
+ exports.FirebaseServerStorageContextModule = __decorate([
2462
+ common.Module({
2463
+ imports: [exports.FirebaseServerStorageModule],
2464
+ providers: [
2465
+ {
2466
+ provide: FIREBASE_STORAGE_CONTEXT_TOKEN,
2467
+ useFactory: googleCloudFirebaseStorageContextFactory,
2468
+ inject: [FIREBASE_STORAGE_TOKEN, FIREBASE_STORAGE_CONTEXT_FACTORY_CONFIG_TOKEN]
2469
+ }
2470
+ ],
2471
+ exports: [exports.FirebaseServerStorageModule, FIREBASE_STORAGE_CONTEXT_TOKEN]
2472
+ })
2473
+ ], exports.FirebaseServerStorageContextModule);
2474
+ // MARK: Token Configuration
2475
+ function firebaseServerStorageDefaultBucketIdTokenProvider(input) {
2476
+ const config = typeof input === 'string' ? { defaultBucketId: input } : input;
2477
+ if (!config.defaultBucketId) {
2478
+ throw new Error('Non-empty defaultBucketId is required.');
2479
+ }
2480
+ return {
2481
+ provide: FIREBASE_STORAGE_CONTEXT_FACTORY_CONFIG_TOKEN,
2482
+ useValue: config
2483
+ };
2484
+ }
2485
+ function defaultProvideFirebaseServerStorageServiceSimple() {
2486
+ return {
2487
+ provide: FirebaseServerStorageService,
2488
+ useFactory: (context) => new FirebaseServerStorageService(context)
2489
+ };
2490
+ }
2491
+ function provideFirebaseServerStorageService(provider) {
2492
+ const providers = [
2493
+ {
2494
+ ...provider,
2495
+ inject: provider.inject ?? [FIREBASE_STORAGE_CONTEXT_TOKEN]
2496
+ }
2497
+ ];
2498
+ if (provider.provide !== FirebaseServerStorageService) {
2499
+ providers.push({
2500
+ provide: FirebaseServerStorageService,
2501
+ useExisting: provider.provide
2502
+ });
2503
+ }
2504
+ return providers;
2505
+ }
2506
+ /**
2507
+ * Convenience function used to generate ModuleMetadata for an app's Auth related modules and FirebaseServerStorageService provider.
2508
+ *
2509
+ * @param provide
2510
+ * @param useFactory
2511
+ * @returns
2512
+ */
2513
+ function firebaseServerStorageModuleMetadata(config) {
2514
+ const serviceProvider = config && config.serviceProvider ? config.serviceProvider : defaultProvideFirebaseServerStorageServiceSimple();
2515
+ const providers = provideFirebaseServerStorageService(serviceProvider);
2516
+ const tokensToExport = nestjs.injectionTokensFromProviders(providers);
2517
+ return nestjs.mergeModuleMetadata({
2518
+ imports: [exports.FirebaseServerStorageContextModule],
2519
+ exports: [exports.FirebaseServerStorageContextModule, ...tokensToExport],
2520
+ providers
2521
+ }, config);
2522
+ }
2523
+
2524
+ class FirebaseNestServerRootModule {
2525
+ }
2526
+ function nestServerInstance(config) {
2527
+ const { moduleClass, providers: additionalProviders, defaultStorageBucket: inputDefaultStorageBucket, forceStorageBucket, globalApiRoutePrefix, configureNestServerInstance } = config;
2528
+ const serversCache = new Map();
2529
+ const initNestServer = (firebaseApp, env) => {
2530
+ const appName = firebaseApp.name;
2531
+ const defaultStorageBucket = inputDefaultStorageBucket ?? firebaseApp.options.storageBucket;
2532
+ let nestServer = serversCache.get(appName);
2533
+ if (!nestServer) {
2534
+ const server = express();
2535
+ const createNestServer = async (expressInstance) => {
2536
+ const providers = [firebaseServerAppTokenProvider(util.asGetter(firebaseApp))];
2537
+ // configure environment providers
2538
+ if (env?.environment != null) {
2539
+ providers.push(nestjs.serverEnvTokenProvider(env.environment));
2540
+ if (config.configureEnvService !== false) {
2541
+ providers.push({
2542
+ provide: FirebaseServerEnvService,
2543
+ useClass: exports.DefaultFirebaseServerEnvService
2544
+ }, {
2545
+ provide: nestjs.ServerEnvironmentService,
2546
+ useExisting: FirebaseServerEnvService
2547
+ });
2548
+ }
2549
+ }
2550
+ if (additionalProviders) {
2551
+ util.pushItemOrArrayItemsIntoArray(providers, additionalProviders);
2552
+ }
2553
+ const imports = [moduleClass];
2554
+ // NOTE: https://cloud.google.com/functions/docs/writing/http#parsing_http_requests
2555
+ const options = { bodyParser: false }; // firebase already parses the requests
2556
+ if (config.configureWebhooks) {
2557
+ imports.push(exports.ConfigureFirebaseWebhookMiddlewareModule);
2558
+ }
2559
+ if (config.appCheckEnabled != false) {
2560
+ imports.push(exports.ConfigureFirebaseAppCheckMiddlewareModule);
2561
+ }
2562
+ if (defaultStorageBucket) {
2563
+ providers.push(firebaseServerStorageDefaultBucketIdTokenProvider({
2564
+ defaultBucketId: defaultStorageBucket,
2565
+ forceBucket: forceStorageBucket
2566
+ }));
2567
+ }
2568
+ // provide the global prefix config to the app
2569
+ providers.push({
2570
+ provide: GlobalRoutePrefixConfig,
2571
+ useValue: {
2572
+ globalApiRoutePrefix
2573
+ }
2574
+ });
2575
+ const providersModule = {
2576
+ module: FirebaseNestServerRootModule,
2577
+ imports,
2578
+ providers,
2579
+ exports: providers,
2580
+ global: true
2581
+ };
2582
+ let nestApp = await core.NestFactory.create(providersModule, new platformExpress.ExpressAdapter(expressInstance), options);
2583
+ if (globalApiRoutePrefix) {
2584
+ nestApp = nestApp.setGlobalPrefix(globalApiRoutePrefix);
2585
+ }
2586
+ if (configureNestServerInstance) {
2587
+ nestApp = configureNestServerInstance(nestApp) || nestApp;
2588
+ }
2589
+ return nestApp.init();
2590
+ };
2591
+ const nest = createNestServer(server).catch((err) => {
2592
+ console.error('Nest failed startup.', err);
2593
+ throw err;
2594
+ });
2595
+ nestServer = { server, nest: util.makeGetter(nest) };
2596
+ serversCache.set(appName, nestServer);
2597
+ }
2598
+ return nestServer;
2599
+ };
2600
+ const removeNestServer = async (firebaseApp) => {
2601
+ const appName = firebaseApp.name;
2602
+ const nestServer = serversCache.get(appName);
2603
+ let removed;
2604
+ if (nestServer) {
2605
+ removed = nestServer.nest().then((x) => {
2606
+ serversCache.delete(appName);
2607
+ return x.close().then(() => true);
2608
+ });
2609
+ }
2610
+ else {
2611
+ removed = Promise.resolve(false);
2612
+ }
2613
+ return removed;
2614
+ };
2615
+ return {
2616
+ moduleClass,
2617
+ initNestServer,
2618
+ removeNestServer
2619
+ };
2620
+ }
2621
+
2622
+ /**
2623
+ * Abstract class that wraps an INestApplicationContext value.
2624
+ */
2625
+ class AbstractNestContext {
2626
+ _nest;
2627
+ constructor(nest) {
2628
+ this._nest = nest;
2629
+ }
2630
+ get nest() {
2631
+ return this._nest;
2632
+ }
2633
+ }
2634
+ class AbstractFirebaseNestContext extends AbstractNestContext {
2635
+ /**
2636
+ * FirebasePermissionErrorContextErrorFunction to use with makeModelContext().
2637
+ *
2638
+ * Defaults to nestFirebaseForbiddenPermissionError().
2639
+ */
2640
+ makePermissionError = nestFirebaseForbiddenPermissionError;
2641
+ /**
2642
+ * FirebaseDoesNotExistErrorContextErrorFunction to use with makeModelContext().
2643
+ *
2644
+ * Defaults to nestFirebaseDoesNotExistError().
2645
+ *
2646
+ * Some configurations may prefer to use nestFirebaseForbiddenPermissionError instead, which returns a forbidden error instead.
2647
+ * This prevents the leaking of information about the existence of an object.
2648
+ */
2649
+ makeDoesNotExistError = nestFirebaseDoesNotExistError;
2650
+ get envService() {
2651
+ return this.nest.get(FirebaseServerEnvService);
2652
+ }
2653
+ get storageService() {
2654
+ return this.nest.get(FirebaseServerStorageService);
2655
+ }
2656
+ /**
2657
+ * Creates a FirebaseAppModelContext instance.
2658
+ *
2659
+ * @param auth
2660
+ * @param buildFn
2661
+ * @returns
2662
+ */
2663
+ makeModelContext(auth, buildFn) {
2664
+ const base = {
2665
+ auth: this.authService.authContextInfo(auth),
2666
+ app: this.app,
2667
+ makePermissionError: this.makePermissionError,
2668
+ makeDoesNotExistError: this.makeDoesNotExistError
2669
+ };
2670
+ return buildFn
2671
+ ? util.build({
2672
+ base,
2673
+ build: buildFn
2674
+ })
2675
+ : base;
2676
+ }
2677
+ /**
2678
+ * Creates a InContextFirebaseModelsService given the input context and parameters.
2679
+ *
2680
+ * @param context
2681
+ * @param buildFn
2682
+ * @returns
2683
+ */
2684
+ model(context, buildFn) {
2685
+ const firebaseModelContext = this.makeModelContext(context, buildFn);
2686
+ return firebase.inContextFirebaseModelsServiceFactory(this.firebaseModelsService)(firebaseModelContext);
2687
+ }
2688
+ async useModel(type, select) {
2689
+ const context = this.makeModelContext(select.request, select.buildFn);
2690
+ const usePromise = firebase.useFirebaseModelsService(this.firebaseModelsService, type, {
2691
+ context,
2692
+ key: select.key,
2693
+ roles: select.roles,
2694
+ rolesSetIncludes: select.rolesSetIncludes
2695
+ });
2696
+ const use = select.use ?? ((x) => x);
2697
+ return usePromise(use);
2698
+ }
2699
+ }
2700
+
2701
+ exports.ALREADY_EXISTS_ERROR_CODE = ALREADY_EXISTS_ERROR_CODE;
2702
+ exports.AbstractFirebaseNestContext = AbstractFirebaseNestContext;
2703
+ exports.AbstractFirebaseServerActionsContext = AbstractFirebaseServerActionsContext;
2704
+ exports.AbstractFirebaseServerAuthContext = AbstractFirebaseServerAuthContext;
2705
+ exports.AbstractFirebaseServerAuthService = AbstractFirebaseServerAuthService;
2706
+ exports.AbstractFirebaseServerAuthUserContext = AbstractFirebaseServerAuthUserContext;
2707
+ exports.AbstractFirebaseServerNewUserService = AbstractFirebaseServerNewUserService;
2708
+ exports.AbstractNestContext = AbstractNestContext;
2709
+ exports.BAD_REQUEST_ERROR_CODE = BAD_REQUEST_ERROR_CODE;
2710
+ exports.CONFLICT_ERROR_CODE = CONFLICT_ERROR_CODE;
2711
+ exports.DEFAULT_FIREBASE_PASSWORD_NUMBER_GENERATOR = DEFAULT_FIREBASE_PASSWORD_NUMBER_GENERATOR;
2712
+ exports.DEFAULT_SETUP_COM_THROTTLE_TIME = DEFAULT_SETUP_COM_THROTTLE_TIME;
2713
+ exports.FIREBASE_APP_TOKEN = FIREBASE_APP_TOKEN;
2714
+ exports.FIREBASE_AUTH_TOKEN = FIREBASE_AUTH_TOKEN;
2715
+ exports.FIREBASE_FIRESTORE_CONTEXT_TOKEN = FIREBASE_FIRESTORE_CONTEXT_TOKEN;
2716
+ exports.FIREBASE_FIRESTORE_TOKEN = FIREBASE_FIRESTORE_TOKEN;
2717
+ exports.FIREBASE_SERVER_VALIDATION_ERROR_CODE = FIREBASE_SERVER_VALIDATION_ERROR_CODE;
2718
+ exports.FIREBASE_STORAGE_CONTEXT_FACTORY_CONFIG_TOKEN = FIREBASE_STORAGE_CONTEXT_FACTORY_CONFIG_TOKEN;
2719
+ exports.FIREBASE_STORAGE_CONTEXT_TOKEN = FIREBASE_STORAGE_CONTEXT_TOKEN;
2720
+ exports.FIREBASE_STORAGE_TOKEN = FIREBASE_STORAGE_TOKEN;
2721
+ exports.FIRESTORE_CLIENT_QUERY_CONSTRAINT_HANDLER_MAPPING = FIRESTORE_CLIENT_QUERY_CONSTRAINT_HANDLER_MAPPING;
2722
+ exports.FORBIDDEN_ERROR_CODE = FORBIDDEN_ERROR_CODE;
2723
+ exports.FirebaseNestServerRootModule = FirebaseNestServerRootModule;
2724
+ exports.FirebaseServerAuthNewUserSendSetupDetailsNoSetupConfigError = FirebaseServerAuthNewUserSendSetupDetailsNoSetupConfigError;
2725
+ exports.FirebaseServerAuthNewUserSendSetupDetailsSendOnceError = FirebaseServerAuthNewUserSendSetupDetailsSendOnceError;
2726
+ exports.FirebaseServerAuthNewUserSendSetupDetailsThrottleError = FirebaseServerAuthNewUserSendSetupDetailsThrottleError;
2727
+ exports.FirebaseServerAuthService = FirebaseServerAuthService;
2728
+ exports.FirebaseServerEnvService = FirebaseServerEnvService;
2729
+ exports.FirebaseServerStorageService = FirebaseServerStorageService;
2730
+ exports.INTERNAL_SERVER_ERROR_CODE = INTERNAL_SERVER_ERROR_CODE;
2731
+ exports.MODEL_NOT_AVAILABLE_ERROR_CODE = MODEL_NOT_AVAILABLE_ERROR_CODE;
2732
+ exports.NOT_FOUND_ERROR_CODE = NOT_FOUND_ERROR_CODE;
2733
+ exports.NO_RUN_NAME_SPECIFIED_FOR_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_CODE = NO_RUN_NAME_SPECIFIED_FOR_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_CODE;
2734
+ exports.NoSetupContentFirebaseServerNewUserService = NoSetupContentFirebaseServerNewUserService;
2735
+ exports.PERMISSION_DENIED_ERROR_CODE = PERMISSION_DENIED_ERROR_CODE;
2736
+ exports.PHONE_NUMBER_ALREADY_EXISTS_ERROR_CODE = PHONE_NUMBER_ALREADY_EXISTS_ERROR_CODE;
2737
+ exports.SkipAppCheck = SkipAppCheck;
2738
+ exports.UNAUTHENTICATED_ERROR_CODE = UNAUTHENTICATED_ERROR_CODE;
2739
+ exports.UNAVAILABLE_ERROR_CODE = UNAVAILABLE_ERROR_CODE;
2740
+ exports.UNAVAILABLE_OR_DEACTIVATED_FUNCTION_ERROR_CODE = UNAVAILABLE_OR_DEACTIVATED_FUNCTION_ERROR_CODE;
2741
+ exports.UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_NAME_CODE = UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_NAME_CODE;
2742
+ exports.UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_TYPE_CODE = UNKNOWN_SCHEDULED_FUNCTION_DEVELOPMENT_FUNCTION_TYPE_CODE;
2743
+ exports._onCallWithCallTypeFunction = _onCallWithCallTypeFunction;
2744
+ exports.alreadyExistsError = alreadyExistsError;
2745
+ exports.appFirestoreModuleMetadata = appFirestoreModuleMetadata;
2746
+ exports.assertContextHasAuth = assertContextHasAuth;
2747
+ exports.assertDocumentExists = assertDocumentExists;
2748
+ exports.assertHasRolesInRequest = assertHasRolesInRequest;
2749
+ exports.assertHasSignedTosInRequest = assertHasSignedTosInRequest;
2750
+ exports.assertIsAdminInRequest = assertIsAdminInRequest;
2751
+ exports.assertIsAdminOrTargetUserInRequestData = assertIsAdminOrTargetUserInRequestData;
2752
+ exports.assertIsContextWithAuthData = assertIsContextWithAuthData;
2753
+ exports.assertRequestRequiresAuthForFunction = assertRequestRequiresAuthForFunction;
2754
+ exports.assertSnapshotData = assertSnapshotData;
2755
+ exports.assertSnapshotDataWithKey = assertSnapshotDataWithKey;
2756
+ exports.badRequestError = badRequestError;
2757
+ exports.blockingFunctionHandlerWithNestContextFactory = blockingFunctionHandlerWithNestContextFactory;
2758
+ exports.cloudEventHandlerWithNestContextFactory = cloudEventHandlerWithNestContextFactory;
2759
+ exports.collectionRefForPath = collectionRefForPath;
2760
+ exports.createModelUnknownModelTypeError = createModelUnknownModelTypeError;
2761
+ exports.defaultFirebaseServerActionsTransformFactoryLogErrorFunction = defaultFirebaseServerActionsTransformFactoryLogErrorFunction;
2762
+ exports.defaultProvideFirebaseServerStorageServiceSimple = defaultProvideFirebaseServerStorageServiceSimple;
2763
+ exports.deleteModelUnknownModelTypeError = deleteModelUnknownModelTypeError;
2764
+ exports.developmentUnknownSpecifierError = developmentUnknownSpecifierError;
2765
+ exports.docRefForPath = docRefForPath;
2766
+ exports.documentModelNotAvailableError = documentModelNotAvailableError;
2767
+ exports.firebaseAuthTokenFromDecodedIdToken = firebaseAuthTokenFromDecodedIdToken;
2768
+ exports.firebaseServerActionsContext = firebaseServerActionsContext;
2769
+ exports.firebaseServerActionsTransformContext = firebaseServerActionsTransformContext;
2770
+ exports.firebaseServerActionsTransformFactory = firebaseServerActionsTransformFactory;
2771
+ exports.firebaseServerAppTokenProvider = firebaseServerAppTokenProvider;
2772
+ exports.firebaseServerAuthModuleMetadata = firebaseServerAuthModuleMetadata;
2773
+ exports.firebaseServerDevFunctions = firebaseServerDevFunctions;
2774
+ exports.firebaseServerErrorInfo = firebaseServerErrorInfo;
2775
+ exports.firebaseServerErrorInfoCodePair = firebaseServerErrorInfoCodePair;
2776
+ exports.firebaseServerErrorInfoServerErrorCodePair = firebaseServerErrorInfoServerErrorCodePair;
2777
+ exports.firebaseServerErrorInfoServerErrorPair = firebaseServerErrorInfoServerErrorPair;
2778
+ exports.firebaseServerStorageDefaultBucketIdTokenProvider = firebaseServerStorageDefaultBucketIdTokenProvider;
2779
+ exports.firebaseServerStorageModuleMetadata = firebaseServerStorageModuleMetadata;
2780
+ exports.firebaseServerValidationError = firebaseServerValidationError;
2781
+ exports.firebaseServerValidationServerError = firebaseServerValidationServerError;
2782
+ exports.firestoreClientQueryConstraintFunctionsDriver = firestoreClientQueryConstraintFunctionsDriver;
2783
+ exports.firestoreServerIncrementUpdateToUpdateData = firestoreServerIncrementUpdateToUpdateData;
2784
+ exports.forbiddenError = forbiddenError;
2785
+ exports.getAuthUserOrUndefined = getAuthUserOrUndefined;
2786
+ exports.googleCloudFileMetadataToStorageMetadata = googleCloudFileMetadataToStorageMetadata;
2787
+ exports.googleCloudFirebaseStorageContextFactory = googleCloudFirebaseStorageContextFactory;
2788
+ exports.googleCloudFirebaseStorageDrivers = googleCloudFirebaseStorageDrivers;
2789
+ exports.googleCloudFirestoreAccessorDriver = googleCloudFirestoreAccessorDriver;
2790
+ exports.googleCloudFirestoreContextFactory = googleCloudFirestoreContextFactory;
2791
+ exports.googleCloudFirestoreDrivers = googleCloudFirestoreDrivers;
2792
+ exports.googleCloudFirestoreQueryDriver = googleCloudFirestoreQueryDriver;
2793
+ exports.googleCloudStorageAccessorFile = googleCloudStorageAccessorFile;
2794
+ exports.googleCloudStorageAccessorFolder = googleCloudStorageAccessorFolder;
2795
+ exports.googleCloudStorageBucketForStorageFilePath = googleCloudStorageBucketForStorageFilePath;
2796
+ exports.googleCloudStorageFileForStorageFilePath = googleCloudStorageFileForStorageFilePath;
2797
+ exports.googleCloudStorageFirebaseStorageAccessorDriver = googleCloudStorageFirebaseStorageAccessorDriver;
2798
+ exports.googleCloudStorageFromFirebaseAdminStorage = googleCloudStorageFromFirebaseAdminStorage;
2799
+ exports.googleCloudStorageListFilesResultFactory = googleCloudStorageListFilesResultFactory;
2800
+ exports.handleFirebaseAuthError = handleFirebaseAuthError;
2801
+ exports.handleFirebaseError = handleFirebaseError;
2802
+ exports.hasAuthRolesInRequest = hasAuthRolesInRequest;
2803
+ exports.hasNewUserSetupPasswordInRequest = hasNewUserSetupPasswordInRequest;
2804
+ exports.hasSignedTosInRequest = hasSignedTosInRequest;
2805
+ exports.inAuthContext = inAuthContext;
2806
+ exports.injectNestApplicationContextIntoRequest = injectNestApplicationContextIntoRequest;
2807
+ exports.injectNestIntoRequest = injectNestIntoRequest;
2808
+ exports.internalServerError = internalServerError;
2809
+ exports.isAdminInRequest = isAdminInRequest;
2810
+ exports.isAdminOrTargetUserInRequestData = isAdminOrTargetUserInRequestData;
2811
+ exports.isContextWithAuthData = isContextWithAuthData;
2812
+ exports.isFirebaseError = isFirebaseError;
2813
+ exports.isFirebaseHttpsError = isFirebaseHttpsError;
2814
+ exports.makeBlockingFunctionWithHandler = makeBlockingFunctionWithHandler;
2815
+ exports.makeOnScheduleHandlerWithNestApplicationRequest = makeOnScheduleHandlerWithNestApplicationRequest;
2816
+ exports.makeScheduledFunctionDevelopmentFunction = makeScheduledFunctionDevelopmentFunction;
2817
+ exports.modelNotAvailableError = modelNotAvailableError;
2818
+ exports.nestAppHasDevelopmentSchedulerEnabled = nestAppHasDevelopmentSchedulerEnabled;
2819
+ exports.nestAppIsProductionEnvironment = nestAppIsProductionEnvironment;
2820
+ exports.nestFirebaseDoesNotExistError = nestFirebaseDoesNotExistError;
2821
+ exports.nestFirebaseForbiddenPermissionError = nestFirebaseForbiddenPermissionError;
2822
+ exports.nestServerInstance = nestServerInstance;
2823
+ exports.noRunNameSpecifiedForScheduledFunctionDevelopmentFunction = noRunNameSpecifiedForScheduledFunctionDevelopmentFunction;
2824
+ exports.notFoundError = notFoundError;
2825
+ exports.onCallCreateModel = onCallCreateModel;
2826
+ exports.onCallDeleteModel = onCallDeleteModel;
2827
+ exports.onCallDevelopmentFunction = onCallDevelopmentFunction;
2828
+ exports.onCallHandlerWithNestApplicationFactory = onCallHandlerWithNestApplicationFactory;
2829
+ exports.onCallHandlerWithNestContextFactory = onCallHandlerWithNestContextFactory;
2830
+ exports.onCallModel = onCallModel;
2831
+ exports.onCallModelMissingCallTypeError = onCallModelMissingCallTypeError;
2832
+ exports.onCallModelUnknownCallTypeError = onCallModelUnknownCallTypeError;
2833
+ exports.onCallReadModel = onCallReadModel;
2834
+ exports.onCallSpecifierHandler = onCallSpecifierHandler;
2835
+ exports.onCallUpdateModel = onCallUpdateModel;
2836
+ exports.onScheduleHandlerWithNestApplicationFactory = onScheduleHandlerWithNestApplicationFactory;
2837
+ exports.onScheduleHandlerWithNestContextFactory = onScheduleHandlerWithNestContextFactory;
2838
+ exports.optionalAuthContext = optionalAuthContext;
2839
+ exports.permissionDeniedError = permissionDeniedError;
2840
+ exports.phoneNumberAlreadyExistsError = phoneNumberAlreadyExistsError;
2841
+ exports.preconditionConflictError = preconditionConflictError;
2842
+ exports.provideAppFirestoreCollections = provideAppFirestoreCollections;
2843
+ exports.provideFirebaseServerAuthService = provideFirebaseServerAuthService;
2844
+ exports.provideFirebaseServerStorageService = provideFirebaseServerStorageService;
2845
+ exports.readModelUnknownModelTypeError = readModelUnknownModelTypeError;
2846
+ exports.setNestContextOnRequest = setNestContextOnRequest;
2847
+ exports.setNestContextOnScheduleRequest = setNestContextOnScheduleRequest;
2848
+ exports.taskQueueFunctionHandlerWithNestContextFactory = taskQueueFunctionHandlerWithNestContextFactory;
2849
+ exports.unauthenticatedContextHasNoAuthData = unauthenticatedContextHasNoAuthData;
2850
+ exports.unauthenticatedContextHasNoUidError = unauthenticatedContextHasNoUidError;
2851
+ exports.unauthenticatedError = unauthenticatedError;
2852
+ exports.unavailableError = unavailableError;
2853
+ exports.unavailableOrDeactivatedFunctionError = unavailableOrDeactivatedFunctionError;
2854
+ exports.unknownModelCrudFunctionSpecifierError = unknownModelCrudFunctionSpecifierError;
2855
+ exports.unknownScheduledFunctionDevelopmentFunctionName = unknownScheduledFunctionDevelopmentFunctionName;
2856
+ exports.unknownScheduledFunctionDevelopmentFunctionType = unknownScheduledFunctionDevelopmentFunctionType;
2857
+ exports.updateModelUnknownModelTypeError = updateModelUnknownModelTypeError;
2858
+ exports.userContextFromUid = userContextFromUid;
2859
+ exports.verifyAppCheckInRequest = verifyAppCheckInRequest;