chirag-appwrite-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (491) hide show
  1. package/.github/workflows/npm-publish.yml +49 -0
  2. package/CHANGELOG.md +1 -0
  3. package/Formula/appwrite.rb +19 -0
  4. package/LICENSE.md +1 -0
  5. package/README.md +104 -0
  6. package/appwrite.json +164 -0
  7. package/docs/examples/account/create-anonymous-session.md +1 -0
  8. package/docs/examples/account/create-email-password-session.md +3 -0
  9. package/docs/examples/account/create-email-token.md +4 -0
  10. package/docs/examples/account/create-j-w-t.md +1 -0
  11. package/docs/examples/account/create-magic-u-r-l-token.md +5 -0
  12. package/docs/examples/account/create-mfa-authenticator.md +2 -0
  13. package/docs/examples/account/create-mfa-challenge.md +2 -0
  14. package/docs/examples/account/create-mfa-recovery-codes.md +1 -0
  15. package/docs/examples/account/create-o-auth2session.md +5 -0
  16. package/docs/examples/account/create-o-auth2token.md +5 -0
  17. package/docs/examples/account/create-phone-token.md +3 -0
  18. package/docs/examples/account/create-phone-verification.md +1 -0
  19. package/docs/examples/account/create-push-target.md +4 -0
  20. package/docs/examples/account/create-recovery.md +3 -0
  21. package/docs/examples/account/create-session.md +3 -0
  22. package/docs/examples/account/create-verification.md +2 -0
  23. package/docs/examples/account/create.md +5 -0
  24. package/docs/examples/account/delete-identity.md +2 -0
  25. package/docs/examples/account/delete-mfa-authenticator.md +2 -0
  26. package/docs/examples/account/delete-push-target.md +2 -0
  27. package/docs/examples/account/delete-session.md +2 -0
  28. package/docs/examples/account/delete-sessions.md +1 -0
  29. package/docs/examples/account/delete.md +1 -0
  30. package/docs/examples/account/get-mfa-recovery-codes.md +1 -0
  31. package/docs/examples/account/get-prefs.md +1 -0
  32. package/docs/examples/account/get-session.md +2 -0
  33. package/docs/examples/account/get.md +1 -0
  34. package/docs/examples/account/list-identities.md +2 -0
  35. package/docs/examples/account/list-logs.md +2 -0
  36. package/docs/examples/account/list-mfa-factors.md +1 -0
  37. package/docs/examples/account/list-sessions.md +1 -0
  38. package/docs/examples/account/update-email.md +3 -0
  39. package/docs/examples/account/update-m-f-a.md +2 -0
  40. package/docs/examples/account/update-magic-u-r-l-session.md +3 -0
  41. package/docs/examples/account/update-mfa-authenticator.md +3 -0
  42. package/docs/examples/account/update-mfa-challenge.md +3 -0
  43. package/docs/examples/account/update-mfa-recovery-codes.md +1 -0
  44. package/docs/examples/account/update-name.md +2 -0
  45. package/docs/examples/account/update-password.md +3 -0
  46. package/docs/examples/account/update-phone-session.md +3 -0
  47. package/docs/examples/account/update-phone-verification.md +3 -0
  48. package/docs/examples/account/update-phone.md +3 -0
  49. package/docs/examples/account/update-prefs.md +2 -0
  50. package/docs/examples/account/update-push-target.md +3 -0
  51. package/docs/examples/account/update-recovery.md +4 -0
  52. package/docs/examples/account/update-session.md +2 -0
  53. package/docs/examples/account/update-status.md +1 -0
  54. package/docs/examples/account/update-verification.md +3 -0
  55. package/docs/examples/avatars/get-browser.md +5 -0
  56. package/docs/examples/avatars/get-credit-card.md +5 -0
  57. package/docs/examples/avatars/get-favicon.md +2 -0
  58. package/docs/examples/avatars/get-flag.md +5 -0
  59. package/docs/examples/avatars/get-image.md +4 -0
  60. package/docs/examples/avatars/get-initials.md +5 -0
  61. package/docs/examples/avatars/get-q-r.md +5 -0
  62. package/docs/examples/console/get-resource.md +3 -0
  63. package/docs/examples/console/variables.md +1 -0
  64. package/docs/examples/databases/create-boolean-attribute.md +7 -0
  65. package/docs/examples/databases/create-collection.md +7 -0
  66. package/docs/examples/databases/create-datetime-attribute.md +7 -0
  67. package/docs/examples/databases/create-document.md +6 -0
  68. package/docs/examples/databases/create-documents.md +4 -0
  69. package/docs/examples/databases/create-email-attribute.md +7 -0
  70. package/docs/examples/databases/create-enum-attribute.md +8 -0
  71. package/docs/examples/databases/create-float-attribute.md +9 -0
  72. package/docs/examples/databases/create-index.md +8 -0
  73. package/docs/examples/databases/create-integer-attribute.md +9 -0
  74. package/docs/examples/databases/create-ip-attribute.md +7 -0
  75. package/docs/examples/databases/create-relationship-attribute.md +9 -0
  76. package/docs/examples/databases/create-string-attribute.md +9 -0
  77. package/docs/examples/databases/create-url-attribute.md +7 -0
  78. package/docs/examples/databases/create.md +4 -0
  79. package/docs/examples/databases/decrement-document-attribute.md +7 -0
  80. package/docs/examples/databases/delete-attribute.md +4 -0
  81. package/docs/examples/databases/delete-collection.md +3 -0
  82. package/docs/examples/databases/delete-document.md +4 -0
  83. package/docs/examples/databases/delete-documents.md +4 -0
  84. package/docs/examples/databases/delete-index.md +4 -0
  85. package/docs/examples/databases/delete.md +2 -0
  86. package/docs/examples/databases/get-attribute.md +4 -0
  87. package/docs/examples/databases/get-collection-usage.md +4 -0
  88. package/docs/examples/databases/get-collection.md +3 -0
  89. package/docs/examples/databases/get-database-usage.md +3 -0
  90. package/docs/examples/databases/get-document.md +5 -0
  91. package/docs/examples/databases/get-index.md +4 -0
  92. package/docs/examples/databases/get-usage.md +2 -0
  93. package/docs/examples/databases/get.md +2 -0
  94. package/docs/examples/databases/increment-document-attribute.md +7 -0
  95. package/docs/examples/databases/list-attributes.md +4 -0
  96. package/docs/examples/databases/list-collection-logs.md +4 -0
  97. package/docs/examples/databases/list-collections.md +4 -0
  98. package/docs/examples/databases/list-document-logs.md +5 -0
  99. package/docs/examples/databases/list-documents.md +4 -0
  100. package/docs/examples/databases/list-indexes.md +4 -0
  101. package/docs/examples/databases/list-logs.md +3 -0
  102. package/docs/examples/databases/list.md +3 -0
  103. package/docs/examples/databases/update-boolean-attribute.md +7 -0
  104. package/docs/examples/databases/update-collection.md +7 -0
  105. package/docs/examples/databases/update-datetime-attribute.md +7 -0
  106. package/docs/examples/databases/update-document.md +6 -0
  107. package/docs/examples/databases/update-documents.md +5 -0
  108. package/docs/examples/databases/update-email-attribute.md +7 -0
  109. package/docs/examples/databases/update-enum-attribute.md +8 -0
  110. package/docs/examples/databases/update-float-attribute.md +9 -0
  111. package/docs/examples/databases/update-integer-attribute.md +9 -0
  112. package/docs/examples/databases/update-ip-attribute.md +7 -0
  113. package/docs/examples/databases/update-relationship-attribute.md +6 -0
  114. package/docs/examples/databases/update-string-attribute.md +8 -0
  115. package/docs/examples/databases/update-url-attribute.md +7 -0
  116. package/docs/examples/databases/update.md +4 -0
  117. package/docs/examples/databases/upsert-document.md +6 -0
  118. package/docs/examples/databases/upsert-documents.md +4 -0
  119. package/docs/examples/functions/create-deployment.md +6 -0
  120. package/docs/examples/functions/create-duplicate-deployment.md +4 -0
  121. package/docs/examples/functions/create-execution.md +8 -0
  122. package/docs/examples/functions/create-template-deployment.md +7 -0
  123. package/docs/examples/functions/create-variable.md +5 -0
  124. package/docs/examples/functions/create-vcs-deployment.md +5 -0
  125. package/docs/examples/functions/create.md +19 -0
  126. package/docs/examples/functions/delete-deployment.md +3 -0
  127. package/docs/examples/functions/delete-execution.md +3 -0
  128. package/docs/examples/functions/delete-variable.md +3 -0
  129. package/docs/examples/functions/delete.md +2 -0
  130. package/docs/examples/functions/get-deployment-download.md +4 -0
  131. package/docs/examples/functions/get-deployment.md +3 -0
  132. package/docs/examples/functions/get-execution.md +3 -0
  133. package/docs/examples/functions/get-template.md +2 -0
  134. package/docs/examples/functions/get-usage.md +3 -0
  135. package/docs/examples/functions/get-variable.md +3 -0
  136. package/docs/examples/functions/get.md +2 -0
  137. package/docs/examples/functions/list-deployments.md +4 -0
  138. package/docs/examples/functions/list-executions.md +3 -0
  139. package/docs/examples/functions/list-runtimes.md +1 -0
  140. package/docs/examples/functions/list-specifications.md +1 -0
  141. package/docs/examples/functions/list-templates.md +5 -0
  142. package/docs/examples/functions/list-usage.md +2 -0
  143. package/docs/examples/functions/list-variables.md +2 -0
  144. package/docs/examples/functions/list.md +3 -0
  145. package/docs/examples/functions/update-deployment-status.md +3 -0
  146. package/docs/examples/functions/update-function-deployment.md +3 -0
  147. package/docs/examples/functions/update-variable.md +6 -0
  148. package/docs/examples/functions/update.md +19 -0
  149. package/docs/examples/graphql/mutation.md +2 -0
  150. package/docs/examples/graphql/query.md +2 -0
  151. package/docs/examples/health/get-antivirus.md +1 -0
  152. package/docs/examples/health/get-cache.md +1 -0
  153. package/docs/examples/health/get-certificate.md +2 -0
  154. package/docs/examples/health/get-d-b.md +1 -0
  155. package/docs/examples/health/get-failed-jobs.md +3 -0
  156. package/docs/examples/health/get-pub-sub.md +1 -0
  157. package/docs/examples/health/get-queue-builds.md +2 -0
  158. package/docs/examples/health/get-queue-certificates.md +2 -0
  159. package/docs/examples/health/get-queue-databases.md +3 -0
  160. package/docs/examples/health/get-queue-deletes.md +2 -0
  161. package/docs/examples/health/get-queue-functions.md +2 -0
  162. package/docs/examples/health/get-queue-logs.md +2 -0
  163. package/docs/examples/health/get-queue-mails.md +2 -0
  164. package/docs/examples/health/get-queue-messaging.md +2 -0
  165. package/docs/examples/health/get-queue-migrations.md +2 -0
  166. package/docs/examples/health/get-queue-stats-resources.md +2 -0
  167. package/docs/examples/health/get-queue-usage.md +2 -0
  168. package/docs/examples/health/get-queue-webhooks.md +2 -0
  169. package/docs/examples/health/get-storage-local.md +1 -0
  170. package/docs/examples/health/get-storage.md +1 -0
  171. package/docs/examples/health/get-time.md +1 -0
  172. package/docs/examples/health/get.md +1 -0
  173. package/docs/examples/locale/get.md +1 -0
  174. package/docs/examples/locale/list-codes.md +1 -0
  175. package/docs/examples/locale/list-continents.md +1 -0
  176. package/docs/examples/locale/list-countries-e-u.md +1 -0
  177. package/docs/examples/locale/list-countries-phones.md +1 -0
  178. package/docs/examples/locale/list-countries.md +1 -0
  179. package/docs/examples/locale/list-currencies.md +1 -0
  180. package/docs/examples/locale/list-languages.md +1 -0
  181. package/docs/examples/messaging/create-apns-provider.md +9 -0
  182. package/docs/examples/messaging/create-email.md +13 -0
  183. package/docs/examples/messaging/create-fcm-provider.md +5 -0
  184. package/docs/examples/messaging/create-mailgun-provider.md +11 -0
  185. package/docs/examples/messaging/create-msg91provider.md +7 -0
  186. package/docs/examples/messaging/create-push.md +20 -0
  187. package/docs/examples/messaging/create-sendgrid-provider.md +9 -0
  188. package/docs/examples/messaging/create-sms.md +8 -0
  189. package/docs/examples/messaging/create-smtp-provider.md +15 -0
  190. package/docs/examples/messaging/create-subscriber.md +4 -0
  191. package/docs/examples/messaging/create-telesign-provider.md +7 -0
  192. package/docs/examples/messaging/create-textmagic-provider.md +7 -0
  193. package/docs/examples/messaging/create-topic.md +4 -0
  194. package/docs/examples/messaging/create-twilio-provider.md +7 -0
  195. package/docs/examples/messaging/create-vonage-provider.md +7 -0
  196. package/docs/examples/messaging/delete-provider.md +2 -0
  197. package/docs/examples/messaging/delete-subscriber.md +3 -0
  198. package/docs/examples/messaging/delete-topic.md +2 -0
  199. package/docs/examples/messaging/delete.md +2 -0
  200. package/docs/examples/messaging/get-message.md +2 -0
  201. package/docs/examples/messaging/get-provider.md +2 -0
  202. package/docs/examples/messaging/get-subscriber.md +3 -0
  203. package/docs/examples/messaging/get-topic.md +2 -0
  204. package/docs/examples/messaging/list-message-logs.md +3 -0
  205. package/docs/examples/messaging/list-messages.md +3 -0
  206. package/docs/examples/messaging/list-provider-logs.md +3 -0
  207. package/docs/examples/messaging/list-providers.md +3 -0
  208. package/docs/examples/messaging/list-subscriber-logs.md +3 -0
  209. package/docs/examples/messaging/list-subscribers.md +4 -0
  210. package/docs/examples/messaging/list-targets.md +3 -0
  211. package/docs/examples/messaging/list-topic-logs.md +3 -0
  212. package/docs/examples/messaging/list-topics.md +3 -0
  213. package/docs/examples/messaging/update-apns-provider.md +9 -0
  214. package/docs/examples/messaging/update-email.md +13 -0
  215. package/docs/examples/messaging/update-fcm-provider.md +5 -0
  216. package/docs/examples/messaging/update-mailgun-provider.md +11 -0
  217. package/docs/examples/messaging/update-msg91provider.md +7 -0
  218. package/docs/examples/messaging/update-push.md +20 -0
  219. package/docs/examples/messaging/update-sendgrid-provider.md +9 -0
  220. package/docs/examples/messaging/update-sms.md +8 -0
  221. package/docs/examples/messaging/update-smtp-provider.md +15 -0
  222. package/docs/examples/messaging/update-telesign-provider.md +7 -0
  223. package/docs/examples/messaging/update-textmagic-provider.md +7 -0
  224. package/docs/examples/messaging/update-topic.md +4 -0
  225. package/docs/examples/messaging/update-twilio-provider.md +7 -0
  226. package/docs/examples/messaging/update-vonage-provider.md +7 -0
  227. package/docs/examples/migrations/create-appwrite-migration.md +5 -0
  228. package/docs/examples/migrations/create-csv-migration.md +4 -0
  229. package/docs/examples/migrations/create-firebase-migration.md +3 -0
  230. package/docs/examples/migrations/create-n-host-migration.md +9 -0
  231. package/docs/examples/migrations/create-supabase-migration.md +8 -0
  232. package/docs/examples/migrations/delete.md +2 -0
  233. package/docs/examples/migrations/get-appwrite-report.md +5 -0
  234. package/docs/examples/migrations/get-firebase-report.md +3 -0
  235. package/docs/examples/migrations/get-n-host-report.md +9 -0
  236. package/docs/examples/migrations/get-supabase-report.md +8 -0
  237. package/docs/examples/migrations/get.md +2 -0
  238. package/docs/examples/migrations/list.md +3 -0
  239. package/docs/examples/migrations/retry.md +2 -0
  240. package/docs/examples/project/create-variable.md +4 -0
  241. package/docs/examples/project/delete-variable.md +2 -0
  242. package/docs/examples/project/get-usage.md +4 -0
  243. package/docs/examples/project/get-variable.md +2 -0
  244. package/docs/examples/project/list-variables.md +1 -0
  245. package/docs/examples/project/update-variable.md +5 -0
  246. package/docs/examples/projects/create-dev-key.md +4 -0
  247. package/docs/examples/projects/create-j-w-t.md +4 -0
  248. package/docs/examples/projects/create-key.md +5 -0
  249. package/docs/examples/projects/create-platform.md +7 -0
  250. package/docs/examples/projects/create-smtp-test.md +11 -0
  251. package/docs/examples/projects/create-webhook.md +9 -0
  252. package/docs/examples/projects/create.md +14 -0
  253. package/docs/examples/projects/delete-dev-key.md +3 -0
  254. package/docs/examples/projects/delete-email-template.md +4 -0
  255. package/docs/examples/projects/delete-key.md +3 -0
  256. package/docs/examples/projects/delete-platform.md +3 -0
  257. package/docs/examples/projects/delete-sms-template.md +4 -0
  258. package/docs/examples/projects/delete-webhook.md +3 -0
  259. package/docs/examples/projects/delete.md +2 -0
  260. package/docs/examples/projects/get-dev-key.md +3 -0
  261. package/docs/examples/projects/get-email-template.md +4 -0
  262. package/docs/examples/projects/get-key.md +3 -0
  263. package/docs/examples/projects/get-platform.md +3 -0
  264. package/docs/examples/projects/get-sms-template.md +4 -0
  265. package/docs/examples/projects/get-webhook.md +3 -0
  266. package/docs/examples/projects/get.md +2 -0
  267. package/docs/examples/projects/list-dev-keys.md +3 -0
  268. package/docs/examples/projects/list-keys.md +2 -0
  269. package/docs/examples/projects/list-platforms.md +2 -0
  270. package/docs/examples/projects/list-webhooks.md +2 -0
  271. package/docs/examples/projects/list.md +3 -0
  272. package/docs/examples/projects/update-api-status-all.md +3 -0
  273. package/docs/examples/projects/update-api-status.md +4 -0
  274. package/docs/examples/projects/update-auth-duration.md +3 -0
  275. package/docs/examples/projects/update-auth-limit.md +3 -0
  276. package/docs/examples/projects/update-auth-password-dictionary.md +3 -0
  277. package/docs/examples/projects/update-auth-password-history.md +3 -0
  278. package/docs/examples/projects/update-auth-sessions-limit.md +3 -0
  279. package/docs/examples/projects/update-auth-status.md +4 -0
  280. package/docs/examples/projects/update-dev-key.md +5 -0
  281. package/docs/examples/projects/update-email-template.md +9 -0
  282. package/docs/examples/projects/update-key.md +6 -0
  283. package/docs/examples/projects/update-memberships-privacy.md +5 -0
  284. package/docs/examples/projects/update-mock-numbers.md +3 -0
  285. package/docs/examples/projects/update-o-auth2.md +6 -0
  286. package/docs/examples/projects/update-personal-data-check.md +3 -0
  287. package/docs/examples/projects/update-platform.md +7 -0
  288. package/docs/examples/projects/update-service-status-all.md +3 -0
  289. package/docs/examples/projects/update-service-status.md +4 -0
  290. package/docs/examples/projects/update-session-alerts.md +3 -0
  291. package/docs/examples/projects/update-sms-template.md +5 -0
  292. package/docs/examples/projects/update-smtp.md +11 -0
  293. package/docs/examples/projects/update-team.md +3 -0
  294. package/docs/examples/projects/update-webhook-signature.md +3 -0
  295. package/docs/examples/projects/update-webhook.md +10 -0
  296. package/docs/examples/projects/update.md +12 -0
  297. package/docs/examples/proxy/create-a-p-i-rule.md +2 -0
  298. package/docs/examples/proxy/create-function-rule.md +4 -0
  299. package/docs/examples/proxy/create-redirect-rule.md +6 -0
  300. package/docs/examples/proxy/create-site-rule.md +4 -0
  301. package/docs/examples/proxy/delete-rule.md +2 -0
  302. package/docs/examples/proxy/get-rule.md +2 -0
  303. package/docs/examples/proxy/list-rules.md +3 -0
  304. package/docs/examples/proxy/update-rule-verification.md +2 -0
  305. package/docs/examples/sites/create-deployment.md +7 -0
  306. package/docs/examples/sites/create-duplicate-deployment.md +3 -0
  307. package/docs/examples/sites/create-template-deployment.md +7 -0
  308. package/docs/examples/sites/create-variable.md +5 -0
  309. package/docs/examples/sites/create-vcs-deployment.md +5 -0
  310. package/docs/examples/sites/create.md +19 -0
  311. package/docs/examples/sites/delete-deployment.md +3 -0
  312. package/docs/examples/sites/delete-log.md +3 -0
  313. package/docs/examples/sites/delete-variable.md +3 -0
  314. package/docs/examples/sites/delete.md +2 -0
  315. package/docs/examples/sites/get-deployment-download.md +4 -0
  316. package/docs/examples/sites/get-deployment.md +3 -0
  317. package/docs/examples/sites/get-log.md +3 -0
  318. package/docs/examples/sites/get-template.md +2 -0
  319. package/docs/examples/sites/get-usage.md +3 -0
  320. package/docs/examples/sites/get-variable.md +3 -0
  321. package/docs/examples/sites/get.md +2 -0
  322. package/docs/examples/sites/list-deployments.md +4 -0
  323. package/docs/examples/sites/list-frameworks.md +1 -0
  324. package/docs/examples/sites/list-logs.md +3 -0
  325. package/docs/examples/sites/list-specifications.md +1 -0
  326. package/docs/examples/sites/list-templates.md +5 -0
  327. package/docs/examples/sites/list-usage.md +2 -0
  328. package/docs/examples/sites/list-variables.md +2 -0
  329. package/docs/examples/sites/list.md +3 -0
  330. package/docs/examples/sites/update-deployment-status.md +3 -0
  331. package/docs/examples/sites/update-site-deployment.md +3 -0
  332. package/docs/examples/sites/update-variable.md +6 -0
  333. package/docs/examples/sites/update.md +19 -0
  334. package/docs/examples/storage/create-bucket.md +11 -0
  335. package/docs/examples/storage/create-file.md +5 -0
  336. package/docs/examples/storage/delete-bucket.md +2 -0
  337. package/docs/examples/storage/delete-file.md +3 -0
  338. package/docs/examples/storage/get-bucket-usage.md +3 -0
  339. package/docs/examples/storage/get-bucket.md +2 -0
  340. package/docs/examples/storage/get-file-download.md +4 -0
  341. package/docs/examples/storage/get-file-preview.md +15 -0
  342. package/docs/examples/storage/get-file-view.md +4 -0
  343. package/docs/examples/storage/get-file.md +3 -0
  344. package/docs/examples/storage/get-usage.md +2 -0
  345. package/docs/examples/storage/list-buckets.md +3 -0
  346. package/docs/examples/storage/list-files.md +4 -0
  347. package/docs/examples/storage/update-bucket.md +11 -0
  348. package/docs/examples/storage/update-file.md +5 -0
  349. package/docs/examples/teams/create-membership.md +8 -0
  350. package/docs/examples/teams/create.md +4 -0
  351. package/docs/examples/teams/delete-membership.md +3 -0
  352. package/docs/examples/teams/delete.md +2 -0
  353. package/docs/examples/teams/get-membership.md +3 -0
  354. package/docs/examples/teams/get-prefs.md +2 -0
  355. package/docs/examples/teams/get.md +2 -0
  356. package/docs/examples/teams/list-logs.md +3 -0
  357. package/docs/examples/teams/list-memberships.md +4 -0
  358. package/docs/examples/teams/list.md +3 -0
  359. package/docs/examples/teams/update-membership-status.md +5 -0
  360. package/docs/examples/teams/update-membership.md +4 -0
  361. package/docs/examples/teams/update-name.md +3 -0
  362. package/docs/examples/teams/update-prefs.md +3 -0
  363. package/docs/examples/tokens/create-file-token.md +4 -0
  364. package/docs/examples/tokens/delete.md +2 -0
  365. package/docs/examples/tokens/get.md +2 -0
  366. package/docs/examples/tokens/list.md +4 -0
  367. package/docs/examples/tokens/update.md +3 -0
  368. package/docs/examples/users/create-argon2user.md +5 -0
  369. package/docs/examples/users/create-bcrypt-user.md +5 -0
  370. package/docs/examples/users/create-j-w-t.md +4 -0
  371. package/docs/examples/users/create-m-d5user.md +5 -0
  372. package/docs/examples/users/create-mfa-recovery-codes.md +2 -0
  373. package/docs/examples/users/create-p-h-pass-user.md +5 -0
  374. package/docs/examples/users/create-s-h-a-user.md +6 -0
  375. package/docs/examples/users/create-scrypt-modified-user.md +8 -0
  376. package/docs/examples/users/create-scrypt-user.md +10 -0
  377. package/docs/examples/users/create-session.md +2 -0
  378. package/docs/examples/users/create-target.md +7 -0
  379. package/docs/examples/users/create-token.md +4 -0
  380. package/docs/examples/users/create.md +6 -0
  381. package/docs/examples/users/delete-identity.md +2 -0
  382. package/docs/examples/users/delete-mfa-authenticator.md +3 -0
  383. package/docs/examples/users/delete-session.md +3 -0
  384. package/docs/examples/users/delete-sessions.md +2 -0
  385. package/docs/examples/users/delete-target.md +3 -0
  386. package/docs/examples/users/delete.md +2 -0
  387. package/docs/examples/users/get-mfa-recovery-codes.md +2 -0
  388. package/docs/examples/users/get-prefs.md +2 -0
  389. package/docs/examples/users/get-target.md +3 -0
  390. package/docs/examples/users/get-usage.md +2 -0
  391. package/docs/examples/users/get.md +2 -0
  392. package/docs/examples/users/list-identities.md +3 -0
  393. package/docs/examples/users/list-logs.md +3 -0
  394. package/docs/examples/users/list-memberships.md +4 -0
  395. package/docs/examples/users/list-mfa-factors.md +2 -0
  396. package/docs/examples/users/list-sessions.md +2 -0
  397. package/docs/examples/users/list-targets.md +3 -0
  398. package/docs/examples/users/list.md +3 -0
  399. package/docs/examples/users/update-email-verification.md +3 -0
  400. package/docs/examples/users/update-email.md +3 -0
  401. package/docs/examples/users/update-labels.md +3 -0
  402. package/docs/examples/users/update-mfa-recovery-codes.md +2 -0
  403. package/docs/examples/users/update-mfa.md +3 -0
  404. package/docs/examples/users/update-name.md +3 -0
  405. package/docs/examples/users/update-password.md +3 -0
  406. package/docs/examples/users/update-phone-verification.md +3 -0
  407. package/docs/examples/users/update-phone.md +3 -0
  408. package/docs/examples/users/update-prefs.md +3 -0
  409. package/docs/examples/users/update-status.md +3 -0
  410. package/docs/examples/users/update-target.md +6 -0
  411. package/docs/examples/vcs/create-repository-detection.md +5 -0
  412. package/docs/examples/vcs/create-repository.md +4 -0
  413. package/docs/examples/vcs/delete-installation.md +2 -0
  414. package/docs/examples/vcs/get-installation.md +2 -0
  415. package/docs/examples/vcs/get-repository-contents.md +5 -0
  416. package/docs/examples/vcs/get-repository.md +3 -0
  417. package/docs/examples/vcs/list-installations.md +3 -0
  418. package/docs/examples/vcs/list-repositories.md +4 -0
  419. package/docs/examples/vcs/list-repository-branches.md +3 -0
  420. package/docs/examples/vcs/update-external-deployments.md +4 -0
  421. package/functions/Starter function/.prettierrc.json +6 -0
  422. package/functions/Starter function/README.md +48 -0
  423. package/functions/Starter function/package-lock.json +60 -0
  424. package/functions/Starter function/package.json +16 -0
  425. package/functions/Starter function/src/main.js +35 -0
  426. package/generate/appwrite.d.ts +18 -0
  427. package/index.js +109 -0
  428. package/install.ps1 +98 -0
  429. package/install.sh +157 -0
  430. package/lib/client.js +259 -0
  431. package/lib/commands/account.js +2074 -0
  432. package/lib/commands/avatars.js +491 -0
  433. package/lib/commands/console.js +129 -0
  434. package/lib/commands/databases.js +2972 -0
  435. package/lib/commands/functions.js +1737 -0
  436. package/lib/commands/generic.js +328 -0
  437. package/lib/commands/graphql.js +128 -0
  438. package/lib/commands/health.js +891 -0
  439. package/lib/commands/init.js +566 -0
  440. package/lib/commands/locale.js +324 -0
  441. package/lib/commands/messaging.js +2970 -0
  442. package/lib/commands/migrations.js +751 -0
  443. package/lib/commands/organizations.js +48 -0
  444. package/lib/commands/project.js +308 -0
  445. package/lib/commands/projects.js +2615 -0
  446. package/lib/commands/proxy.js +406 -0
  447. package/lib/commands/pull.js +474 -0
  448. package/lib/commands/push.js +2117 -0
  449. package/lib/commands/run.js +330 -0
  450. package/lib/commands/sites.js +1663 -0
  451. package/lib/commands/storage.js +990 -0
  452. package/lib/commands/teams.js +682 -0
  453. package/lib/commands/tokens.js +261 -0
  454. package/lib/commands/types.js +156 -0
  455. package/lib/commands/users.js +2035 -0
  456. package/lib/commands/vcs.js +484 -0
  457. package/lib/config.js +705 -0
  458. package/lib/emulation/docker.js +264 -0
  459. package/lib/emulation/utils.js +186 -0
  460. package/lib/exception.js +9 -0
  461. package/lib/id.js +30 -0
  462. package/lib/paginate.js +52 -0
  463. package/lib/parser.js +246 -0
  464. package/lib/questions.js +1006 -0
  465. package/lib/sdks.js +60 -0
  466. package/lib/spinner.js +104 -0
  467. package/lib/type-generation/attribute.js +16 -0
  468. package/lib/type-generation/languages/dart.js +196 -0
  469. package/lib/type-generation/languages/java.js +130 -0
  470. package/lib/type-generation/languages/javascript.js +102 -0
  471. package/lib/type-generation/languages/kotlin.js +84 -0
  472. package/lib/type-generation/languages/language.js +125 -0
  473. package/lib/type-generation/languages/php.js +109 -0
  474. package/lib/type-generation/languages/swift.js +169 -0
  475. package/lib/type-generation/languages/typescript.js +102 -0
  476. package/lib/utils.js +289 -0
  477. package/lib/validations.js +17 -0
  478. package/package.json +50 -0
  479. package/scoop/appwrite.json +30 -0
  480. package/sites/JavaScript starter/.env.example +3 -0
  481. package/sites/JavaScript starter/LICENSE +21 -0
  482. package/sites/JavaScript starter/images/appwrite.svg +8 -0
  483. package/sites/JavaScript starter/images/javascript.svg +5 -0
  484. package/sites/JavaScript starter/index.html +250 -0
  485. package/sites/JavaScript starter/lib/appwrite.js +10 -0
  486. package/sites/JavaScript starter/package-lock.json +1431 -0
  487. package/sites/JavaScript starter/package.json +21 -0
  488. package/sites/JavaScript starter/readme.md +26 -0
  489. package/sites/JavaScript starter/src/javascript.svg +1 -0
  490. package/sites/JavaScript starter/style/app.css +20 -0
  491. package/sites/JavaScript starter/vite.config.js +7 -0
@@ -0,0 +1,2117 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { parse: parseDotenv } = require('dotenv');
4
+ const chalk = require('chalk');
5
+ const inquirer = require("inquirer");
6
+ const JSONbig = require("json-bigint")({ storeAsString: false });
7
+ const { Command } = require("commander");
8
+ const ID = require("../id");
9
+ const { localConfig, globalConfig, KeysAttributes, KeysFunction, KeysSite, whitelistKeys, KeysTopics, KeysStorage, KeysTeams, KeysCollection } = require("../config");
10
+ const { Spinner, SPINNER_ARC, SPINNER_DOTS } = require('../spinner');
11
+ const { paginate } = require('../paginate');
12
+ const { questionsPushBuckets, questionsPushTeams, questionsPushFunctions, questionsPushSites, questionsGetEntrypoint, questionsPushCollections, questionPushChanges, questionPushChangesConfirmation, questionsPushMessagingTopics, questionsPushResources } = require("../questions");
13
+ const { cliConfig, actionRunner, success, warn, log, hint, error, commandDescriptions, drawTable } = require("../parser");
14
+ const { proxyCreateFunctionRule, proxyCreateSiteRule, proxyListRules } = require('./proxy');
15
+ const { consoleVariables } = require('./console');
16
+ const { sdkForConsole } = require('../sdks')
17
+ const { functionsGet, functionsCreate, functionsUpdate, functionsCreateDeployment, functionsGetDeployment, functionsListVariables, functionsDeleteVariable, functionsCreateVariable } = require('./functions');
18
+ const { sitesGet, sitesCreate, sitesUpdate, sitesCreateDeployment, sitesGetDeployment, sitesCreateVariable, sitesListVariables, sitesDeleteVariable } = require('./sites');
19
+ const {
20
+ databasesGet,
21
+ databasesCreate,
22
+ databasesUpdate,
23
+ databasesCreateBooleanAttribute,
24
+ databasesGetCollection,
25
+ databasesCreateCollection,
26
+ databasesCreateStringAttribute,
27
+ databasesCreateIntegerAttribute,
28
+ databasesCreateFloatAttribute,
29
+ databasesCreateEmailAttribute,
30
+ databasesCreateDatetimeAttribute,
31
+ databasesCreateIndex,
32
+ databasesCreateUrlAttribute,
33
+ databasesCreateIpAttribute,
34
+ databasesCreateEnumAttribute,
35
+ databasesUpdateBooleanAttribute,
36
+ databasesUpdateStringAttribute,
37
+ databasesUpdateIntegerAttribute,
38
+ databasesUpdateFloatAttribute,
39
+ databasesUpdateEmailAttribute,
40
+ databasesUpdateDatetimeAttribute,
41
+ databasesUpdateUrlAttribute,
42
+ databasesUpdateIpAttribute,
43
+ databasesUpdateEnumAttribute,
44
+ databasesUpdateRelationshipAttribute,
45
+ databasesCreateRelationshipAttribute,
46
+ databasesDeleteAttribute,
47
+ databasesDeleteIndex,
48
+ databasesListAttributes,
49
+ databasesListIndexes,
50
+ databasesUpdateCollection
51
+ } = require("./databases");
52
+ const {
53
+ storageGetBucket, storageUpdateBucket, storageCreateBucket
54
+ } = require("./storage");
55
+ const {
56
+ messagingGetTopic, messagingUpdateTopic, messagingCreateTopic
57
+ } = require("./messaging");
58
+ const {
59
+ teamsGet,
60
+ teamsUpdateName,
61
+ teamsCreate
62
+ } = require("./teams");
63
+ const {
64
+ projectsGet,
65
+ projectsUpdate,
66
+ projectsUpdateServiceStatus,
67
+ projectsUpdateAuthStatus,
68
+ projectsUpdateAuthDuration,
69
+ projectsUpdateAuthLimit,
70
+ projectsUpdateAuthSessionsLimit,
71
+ projectsUpdateAuthPasswordDictionary,
72
+ projectsUpdateAuthPasswordHistory,
73
+ projectsUpdatePersonalDataCheck,
74
+ projectsUpdateSessionAlerts,
75
+ projectsUpdateMockNumbers,
76
+ } = require("./projects");
77
+ const { checkDeployConditions } = require('../utils');
78
+
79
+ const STEP_SIZE = 100; // Resources
80
+ const POLL_DEBOUNCE = 2000; // Milliseconds
81
+ const POLL_MAX_DEBOUNCE = 1800; // Times of POLL_DEBOUNCE (1 hour)
82
+ const POLL_DEFAULT_VALUE = 30;
83
+
84
+ let pollMaxDebounces = POLL_DEFAULT_VALUE;
85
+
86
+ const changeableKeys = ['status', 'required', 'xdefault', 'elements', 'min', 'max', 'default', 'error'];
87
+
88
+ const awaitPools = {
89
+ wipeAttributes: async (databaseId, collectionId, iteration = 1) => {
90
+ if (iteration > pollMaxDebounces) {
91
+ return false;
92
+ }
93
+
94
+ const { total } = await databasesListAttributes({
95
+ databaseId,
96
+ collectionId,
97
+ queries: [JSON.stringify({ method: 'limit', values: [1] })],
98
+ parseOutput: false
99
+ });
100
+
101
+ if (total === 0) {
102
+ return true;
103
+ }
104
+
105
+ if (pollMaxDebounces === POLL_DEFAULT_VALUE) {
106
+ let steps = Math.max(1, Math.ceil(total / STEP_SIZE));
107
+ if (steps > 1 && iteration === 1) {
108
+ pollMaxDebounces *= steps;
109
+
110
+ log('Found a large number of attributes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes')
111
+ }
112
+ }
113
+
114
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE));
115
+
116
+ return await awaitPools.wipeAttributes(
117
+ databaseId,
118
+ collectionId,
119
+ iteration + 1
120
+ );
121
+ },
122
+ wipeIndexes: async (databaseId, collectionId, iteration = 1) => {
123
+ if (iteration > pollMaxDebounces) {
124
+ return false;
125
+ }
126
+
127
+ const { total } = await databasesListIndexes({
128
+ databaseId,
129
+ collectionId,
130
+ queries: [JSON.stringify({ method: 'limit', values: [1] })],
131
+ parseOutput: false
132
+ });
133
+
134
+ if (total === 0) {
135
+ return true;
136
+ }
137
+
138
+ if (pollMaxDebounces === POLL_DEFAULT_VALUE) {
139
+ let steps = Math.max(1, Math.ceil(total / STEP_SIZE));
140
+ if (steps > 1 && iteration === 1) {
141
+ pollMaxDebounces *= steps;
142
+
143
+ log('Found a large number of indexes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes')
144
+ }
145
+ }
146
+
147
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE));
148
+
149
+ return await awaitPools.wipeIndexes(
150
+ databaseId,
151
+ collectionId,
152
+ iteration + 1
153
+ );
154
+ },
155
+ deleteAttributes: async (databaseId, collectionId, attributeKeys, iteration = 1) => {
156
+ if (iteration > pollMaxDebounces) {
157
+ return false;
158
+ }
159
+
160
+ if (pollMaxDebounces === POLL_DEFAULT_VALUE) {
161
+ let steps = Math.max(1, Math.ceil(attributeKeys.length / STEP_SIZE));
162
+ if (steps > 1 && iteration === 1) {
163
+ pollMaxDebounces *= steps;
164
+
165
+ log('Found a large number of attributes to be deleted. Increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes')
166
+ }
167
+ }
168
+
169
+ const { attributes } = await paginate(databasesListAttributes, {
170
+ databaseId,
171
+ collectionId,
172
+ parseOutput: false
173
+ }, 100, 'attributes');
174
+
175
+ const ready = attributeKeys.filter(attribute => attributes.includes(attribute.key));
176
+
177
+ if (ready.length === 0) {
178
+ return true;
179
+ }
180
+
181
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE));
182
+
183
+ return await awaitPools.expectAttributes(
184
+ databaseId,
185
+ collectionId,
186
+ attributeKeys,
187
+ iteration + 1
188
+ );
189
+ },
190
+ expectAttributes: async (databaseId, collectionId, attributeKeys, iteration = 1) => {
191
+ if (iteration > pollMaxDebounces) {
192
+ return false;
193
+ }
194
+
195
+ if (pollMaxDebounces === POLL_DEFAULT_VALUE) {
196
+ let steps = Math.max(1, Math.ceil(attributeKeys.length / STEP_SIZE));
197
+ if (steps > 1 && iteration === 1) {
198
+ pollMaxDebounces *= steps;
199
+
200
+ log('Creating a large number of attributes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes')
201
+ }
202
+ }
203
+
204
+ const { attributes } = await paginate(databasesListAttributes, {
205
+ databaseId,
206
+ collectionId,
207
+ parseOutput: false
208
+ }, 100, 'attributes');
209
+
210
+ const ready = attributes
211
+ .filter(attribute => {
212
+ if (attributeKeys.includes(attribute.key)) {
213
+ if (['stuck', 'failed'].includes(attribute.status)) {
214
+ throw new Error(`Attribute '${attribute.key}' failed!`);
215
+ }
216
+
217
+ return attribute.status === 'available';
218
+ }
219
+
220
+ return false;
221
+ })
222
+ .map(attribute => attribute.key);
223
+
224
+ if (ready.length === attributeKeys.length) {
225
+ return true;
226
+ }
227
+
228
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE));
229
+
230
+ return await awaitPools.expectAttributes(
231
+ databaseId,
232
+ collectionId,
233
+ attributeKeys,
234
+ iteration + 1
235
+ );
236
+ },
237
+ deleteIndexes: async (databaseId, collectionId, indexesKeys, iteration = 1) => {
238
+ if (iteration > pollMaxDebounces) {
239
+ return false;
240
+ }
241
+
242
+ if (pollMaxDebounces === POLL_DEFAULT_VALUE) {
243
+ let steps = Math.max(1, Math.ceil(attributeKeys.length / STEP_SIZE));
244
+ if (steps > 1 && iteration === 1) {
245
+ pollMaxDebounces *= steps;
246
+
247
+ log('Found a large number of indexes to be deleted. Increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes')
248
+ }
249
+ }
250
+
251
+ const { indexes } = await paginate(databasesListIndexes, {
252
+ databaseId,
253
+ collectionId,
254
+ parseOutput: false
255
+ }, 100, 'indexes');
256
+
257
+ const ready = indexesKeys.filter(index => indexes.includes(index.key));
258
+
259
+ if (ready.length === 0) {
260
+ return true;
261
+ }
262
+
263
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE));
264
+
265
+ return await awaitPools.expectIndexes(
266
+ databaseId,
267
+ collectionId,
268
+ indexesKeys,
269
+ iteration + 1
270
+ );
271
+ },
272
+ expectIndexes: async (databaseId, collectionId, indexKeys, iteration = 1) => {
273
+ if (iteration > pollMaxDebounces) {
274
+ return false;
275
+ }
276
+
277
+ if (pollMaxDebounces === POLL_DEFAULT_VALUE) {
278
+ let steps = Math.max(1, Math.ceil(indexKeys.length / STEP_SIZE));
279
+ if (steps > 1 && iteration === 1) {
280
+ pollMaxDebounces *= steps;
281
+
282
+ log('Creating a large number of indexes, increasing timeout to ' + (pollMaxDebounces * POLL_DEBOUNCE / 1000 / 60) + ' minutes')
283
+ }
284
+ }
285
+
286
+ const { indexes } = await paginate(databasesListIndexes, {
287
+ databaseId,
288
+ collectionId,
289
+ parseOutput: false
290
+ }, 100, 'indexes');
291
+
292
+ const ready = indexes
293
+ .filter((index) => {
294
+ if (indexKeys.includes(index.key)) {
295
+ if (['stuck', 'failed'].includes(index.status)) {
296
+ throw new Error(`Index '${index.key}' failed!`);
297
+ }
298
+
299
+ return index.status === 'available';
300
+ }
301
+
302
+ return false;
303
+ })
304
+ .map(index => index.key);
305
+
306
+ if (ready.length >= indexKeys.length) {
307
+ return true;
308
+ }
309
+
310
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE));
311
+
312
+ return await awaitPools.expectIndexes(
313
+ databaseId,
314
+ collectionId,
315
+ indexKeys,
316
+ iteration + 1
317
+ );
318
+ },
319
+ }
320
+
321
+ const getConfirmation = async () => {
322
+ if (cliConfig.force) {
323
+ return true;
324
+ }
325
+
326
+ async function fixConfirmation() {
327
+ const answers = await inquirer.prompt(questionPushChangesConfirmation);
328
+ if (answers.changes !== 'YES' && answers.changes !== 'NO') {
329
+ return await fixConfirmation();
330
+ }
331
+
332
+ return answers.changes;
333
+ }
334
+
335
+ let answers = await inquirer.prompt(questionPushChanges);
336
+
337
+ if (answers.changes !== 'YES' && answers.changes !== 'NO') {
338
+ answers.changes = await fixConfirmation();
339
+ }
340
+
341
+ if (answers.changes === 'YES') {
342
+ return true;
343
+ }
344
+
345
+ warn('Skipping push action. Changes were not applied.');
346
+ return false;
347
+
348
+ };
349
+ const isEmpty = (value) => (value === null || value === undefined || (typeof value === "string" && value.trim().length === 0) || (Array.isArray(value) && value.length === 0));
350
+
351
+ const approveChanges = async (resource, resourceGetFunction, keys, resourceName, resourcePlural, skipKeys = [], secondId = '', secondResourceName = '') => {
352
+ log('Checking for changes ...');
353
+ const changes = [];
354
+
355
+ await Promise.all(resource.map(async (localResource) => {
356
+ try {
357
+ const options = {
358
+ [resourceName]: localResource['$id'],
359
+ parseOutput: false,
360
+ };
361
+
362
+ if (secondId !== '' && secondResourceName !== '') {
363
+ options[secondResourceName] = localResource[secondId]
364
+ }
365
+
366
+ const remoteResource = await resourceGetFunction(options);
367
+
368
+ for (let [key, value] of Object.entries(whitelistKeys(remoteResource, keys))) {
369
+ if (skipKeys.includes(key)) {
370
+ continue;
371
+ }
372
+
373
+ if (isEmpty(value) && isEmpty(localResource[key])) {
374
+ continue;
375
+ }
376
+
377
+ if (Array.isArray(value) && Array.isArray(localResource[key])) {
378
+ if (JSON.stringify(value) !== JSON.stringify(localResource[key])) {
379
+ changes.push({
380
+ id: localResource['$id'],
381
+ key,
382
+ remote: chalk.red(value.join('\n')),
383
+ local: chalk.green(localResource[key].join('\n'))
384
+ })
385
+ }
386
+ } else if (value !== localResource[key]) {
387
+ changes.push({
388
+ id: localResource['$id'],
389
+ key,
390
+ remote: chalk.red(value),
391
+ local: chalk.green(localResource[key])
392
+ })
393
+ }
394
+ }
395
+ } catch (e) {
396
+ if (Number(e.code) !== 404) {
397
+ throw e;
398
+ }
399
+ }
400
+ }));
401
+
402
+ if (changes.length === 0) {
403
+ return true;
404
+ }
405
+
406
+ drawTable(changes);
407
+ if ((await getConfirmation()) === true) {
408
+ return true;
409
+ }
410
+
411
+ success(`Successfully pushed 0 ${resourcePlural}.`);
412
+ return false;
413
+ }
414
+
415
+ const getObjectChanges = (remote, local, index, what) => {
416
+ const changes = [];
417
+
418
+ if (remote[index] && local[index]) {
419
+ for (let [service, status] of Object.entries(remote[index])) {
420
+ const localValue = local[index][service];
421
+ let valuesEqual = false;
422
+
423
+ if (Array.isArray(status) && Array.isArray(localValue)) {
424
+ valuesEqual = JSON.stringify(status) === JSON.stringify(localValue);
425
+ } else {
426
+ valuesEqual = status === localValue;
427
+ }
428
+
429
+ if (!valuesEqual) {
430
+ changes.push({ group: what, setting: service, remote: chalk.red(status), local: chalk.green(localValue) })
431
+ }
432
+ }
433
+ }
434
+
435
+ return changes;
436
+ }
437
+
438
+ const createAttribute = (databaseId, collectionId, attribute) => {
439
+ switch (attribute.type) {
440
+ case 'string':
441
+ switch (attribute.format) {
442
+ case 'email':
443
+ return databasesCreateEmailAttribute({
444
+ databaseId,
445
+ collectionId,
446
+ key: attribute.key,
447
+ required: attribute.required,
448
+ xdefault: attribute.default,
449
+ array: attribute.array,
450
+ parseOutput: false
451
+ })
452
+ case 'url':
453
+ return databasesCreateUrlAttribute({
454
+ databaseId,
455
+ collectionId,
456
+ key: attribute.key,
457
+ required: attribute.required,
458
+ xdefault: attribute.default,
459
+ array: attribute.array,
460
+ parseOutput: false
461
+ })
462
+ case 'ip':
463
+ return databasesCreateIpAttribute({
464
+ databaseId,
465
+ collectionId,
466
+ key: attribute.key,
467
+ required: attribute.required,
468
+ xdefault: attribute.default,
469
+ array: attribute.array,
470
+ parseOutput: false
471
+ })
472
+ case 'enum':
473
+ return databasesCreateEnumAttribute({
474
+ databaseId,
475
+ collectionId,
476
+ key: attribute.key,
477
+ elements: attribute.elements,
478
+ required: attribute.required,
479
+ xdefault: attribute.default,
480
+ array: attribute.array,
481
+ parseOutput: false
482
+ })
483
+ default:
484
+ return databasesCreateStringAttribute({
485
+ databaseId,
486
+ collectionId,
487
+ key: attribute.key,
488
+ size: attribute.size,
489
+ required: attribute.required,
490
+ xdefault: attribute.default,
491
+ array: attribute.array,
492
+ encrypt: attribute.encrypt,
493
+ parseOutput: false
494
+ })
495
+
496
+ }
497
+ case 'integer':
498
+ return databasesCreateIntegerAttribute({
499
+ databaseId,
500
+ collectionId,
501
+ key: attribute.key,
502
+ required: attribute.required,
503
+ min: attribute.min,
504
+ max: attribute.max,
505
+ xdefault: attribute.default,
506
+ array: attribute.array,
507
+ parseOutput: false
508
+ })
509
+ case 'double':
510
+ return databasesCreateFloatAttribute({
511
+ databaseId,
512
+ collectionId,
513
+ key: attribute.key,
514
+ required: attribute.required,
515
+ min: attribute.min,
516
+ max: attribute.max,
517
+ xdefault: attribute.default,
518
+ array: attribute.array,
519
+ parseOutput: false
520
+ })
521
+ case 'boolean':
522
+ return databasesCreateBooleanAttribute({
523
+ databaseId,
524
+ collectionId,
525
+ key: attribute.key,
526
+ required: attribute.required,
527
+ xdefault: attribute.default,
528
+ array: attribute.array,
529
+ parseOutput: false
530
+ })
531
+ case 'datetime':
532
+ return databasesCreateDatetimeAttribute({
533
+ databaseId,
534
+ collectionId,
535
+ key: attribute.key,
536
+ required: attribute.required,
537
+ xdefault: attribute.default,
538
+ array: attribute.array,
539
+ parseOutput: false
540
+ })
541
+ case 'relationship':
542
+ return databasesCreateRelationshipAttribute({
543
+ databaseId,
544
+ collectionId,
545
+ relatedCollectionId: attribute.relatedCollection,
546
+ type: attribute.relationType,
547
+ twoWay: attribute.twoWay,
548
+ key: attribute.key,
549
+ twoWayKey: attribute.twoWayKey,
550
+ onDelete: attribute.onDelete,
551
+ parseOutput: false
552
+ })
553
+ default:
554
+ throw new Error(`Unsupported attribute type: ${attribute.type}`);
555
+ }
556
+ }
557
+
558
+ const updateAttribute = (databaseId, collectionId, attribute) => {
559
+ switch (attribute.type) {
560
+ case 'string':
561
+ switch (attribute.format) {
562
+ case 'email':
563
+ return databasesUpdateEmailAttribute({
564
+ databaseId,
565
+ collectionId,
566
+ key: attribute.key,
567
+ required: attribute.required,
568
+ xdefault: attribute.default,
569
+ array: attribute.array,
570
+ parseOutput: false
571
+ })
572
+ case 'url':
573
+ return databasesUpdateUrlAttribute({
574
+ databaseId,
575
+ collectionId,
576
+ key: attribute.key,
577
+ required: attribute.required,
578
+ xdefault: attribute.default,
579
+ array: attribute.array,
580
+ parseOutput: false
581
+ })
582
+ case 'ip':
583
+ return databasesUpdateIpAttribute({
584
+ databaseId,
585
+ collectionId,
586
+ key: attribute.key,
587
+ required: attribute.required,
588
+ xdefault: attribute.default,
589
+ array: attribute.array,
590
+ parseOutput: false
591
+ })
592
+ case 'enum':
593
+ return databasesUpdateEnumAttribute({
594
+ databaseId,
595
+ collectionId,
596
+ key: attribute.key,
597
+ elements: attribute.elements,
598
+ required: attribute.required,
599
+ xdefault: attribute.default,
600
+ array: attribute.array,
601
+ parseOutput: false
602
+ })
603
+ default:
604
+ return databasesUpdateStringAttribute({
605
+ databaseId,
606
+ collectionId,
607
+ key: attribute.key,
608
+ size: attribute.size,
609
+ required: attribute.required,
610
+ xdefault: attribute.default,
611
+ array: attribute.array,
612
+ parseOutput: false
613
+ })
614
+
615
+ }
616
+ case 'integer':
617
+ return databasesUpdateIntegerAttribute({
618
+ databaseId,
619
+ collectionId,
620
+ key: attribute.key,
621
+ required: attribute.required,
622
+ min: attribute.min,
623
+ max: attribute.max,
624
+ xdefault: attribute.default,
625
+ array: attribute.array,
626
+ parseOutput: false
627
+ })
628
+ case 'double':
629
+ return databasesUpdateFloatAttribute({
630
+ databaseId,
631
+ collectionId,
632
+ key: attribute.key,
633
+ required: attribute.required,
634
+ min: attribute.min,
635
+ max: attribute.max,
636
+ xdefault: attribute.default,
637
+ array: attribute.array,
638
+ parseOutput: false
639
+ })
640
+ case 'boolean':
641
+ return databasesUpdateBooleanAttribute({
642
+ databaseId,
643
+ collectionId,
644
+ key: attribute.key,
645
+ required: attribute.required,
646
+ xdefault: attribute.default,
647
+ array: attribute.array,
648
+ parseOutput: false
649
+ })
650
+ case 'datetime':
651
+ return databasesUpdateDatetimeAttribute({
652
+ databaseId,
653
+ collectionId,
654
+ key: attribute.key,
655
+ required: attribute.required,
656
+ xdefault: attribute.default,
657
+ array: attribute.array,
658
+ parseOutput: false
659
+ })
660
+ case 'relationship':
661
+ return databasesUpdateRelationshipAttribute({
662
+ databaseId,
663
+ collectionId,
664
+ relatedCollectionId: attribute.relatedCollection,
665
+ type: attribute.relationType,
666
+ twoWay: attribute.twoWay,
667
+ key: attribute.key,
668
+ twoWayKey: attribute.twoWayKey,
669
+ onDelete: attribute.onDelete,
670
+ parseOutput: false
671
+ })
672
+ default:
673
+ throw new Error(`Unsupported attribute type: ${attribute.type}`);
674
+ }
675
+ }
676
+ const deleteAttribute = async (collection, attribute, isIndex = false) => {
677
+ log(`Deleting ${isIndex ? 'index' : 'attribute'} ${attribute.key} of ${collection.name} ( ${collection['$id']} )`);
678
+
679
+ if (isIndex) {
680
+ await databasesDeleteIndex({
681
+ databaseId: collection['databaseId'],
682
+ collectionId: collection['$id'],
683
+ key: attribute.key,
684
+ parseOutput: false
685
+ });
686
+ return;
687
+ }
688
+
689
+ await databasesDeleteAttribute({
690
+ databaseId: collection['databaseId'],
691
+ collectionId: collection['$id'],
692
+ key: attribute.key,
693
+ parseOutput: false
694
+ });
695
+ }
696
+
697
+ const isEqual = (a, b) => {
698
+ if (a === b) return true;
699
+
700
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
701
+ if (a.constructor && a.constructor.name === 'BigNumber' &&
702
+ b.constructor && b.constructor.name === 'BigNumber') {
703
+ return a.eq(b);
704
+ }
705
+
706
+ if (typeof a.equals === 'function') {
707
+ return a.equals(b);
708
+ }
709
+
710
+ if (typeof a.eq === 'function') {
711
+ return a.eq(b);
712
+ }
713
+ }
714
+
715
+ if (typeof a === 'number' && typeof b === 'number') {
716
+ if (isNaN(a) && isNaN(b)) return true;
717
+ if (!isFinite(a) && !isFinite(b)) return a === b;
718
+ return Math.abs(a - b) < Number.EPSILON;
719
+ }
720
+
721
+ return false;
722
+ };
723
+
724
+ const compareAttribute = (remote, local, reason, key) => {
725
+ if (isEmpty(remote) && isEmpty(local)) {
726
+ return reason;
727
+ }
728
+
729
+ if (Array.isArray(remote) && Array.isArray(local)) {
730
+ if (JSON.stringify(remote) !== JSON.stringify(local)) {
731
+ const bol = reason === '' ? '' : '\n';
732
+ reason += `${bol}${key} changed from ${chalk.red(remote)} to ${chalk.green(local)}`;
733
+ }
734
+ } else if (!isEqual(remote, local)) {
735
+ const bol = reason === '' ? '' : '\n';
736
+ reason += `${bol}${key} changed from ${chalk.red(remote)} to ${chalk.green(local)}`;
737
+ }
738
+
739
+ return reason
740
+ }
741
+
742
+
743
+ /**
744
+ * Check if attribute non-changeable fields has been changed
745
+ * If so return the differences as an object.
746
+ * @param remote
747
+ * @param local
748
+ * @param collection
749
+ * @param recreating when true will check only non-changeable keys
750
+ * @returns {undefined|{reason: string, action: *, attribute, key: string}}
751
+ */
752
+ const checkAttributeChanges = (remote, local, collection, recreating = true) => {
753
+ if (local === undefined) {
754
+ return undefined;
755
+ }
756
+
757
+ const keyName = `${chalk.yellow(local.key)} in ${collection.name} (${collection['$id']})`;
758
+ const action = chalk.cyan(recreating ? 'recreating' : 'changing');
759
+ let reason = '';
760
+ let attribute = remote;
761
+
762
+ for (let key of Object.keys(remote)) {
763
+ if (!KeysAttributes.has(key)) {
764
+ continue;
765
+ }
766
+
767
+ if (changeableKeys.includes(key)) {
768
+ if (!recreating) {
769
+ reason = compareAttribute(remote[key], local[key], reason, key)
770
+ }
771
+ continue;
772
+ }
773
+
774
+ if (!recreating) {
775
+ continue;
776
+ }
777
+
778
+ reason = compareAttribute(remote[key], local[key], reason, key)
779
+ }
780
+
781
+ return reason === '' ? undefined : { key: keyName, attribute, reason, action };
782
+ }
783
+
784
+ /**
785
+ * Check if attributes contain the given attribute
786
+ * @param attribute
787
+ * @param attributes
788
+ * @returns {*}
789
+ */
790
+ const attributesContains = (attribute, attributes) => attributes.find((attr) => attr.key === attribute.key);
791
+ const generateChangesObject = (attribute, collection, isAdding) => {
792
+ return {
793
+ key: `${chalk.yellow(attribute.key)} in ${collection.name} (${collection['$id']})`,
794
+ attribute: attribute,
795
+ reason: isAdding ? 'Field isn\'t present on the remote server' : 'Field isn\'t present on the appwrite.json file',
796
+ action: isAdding ? chalk.green('adding') : chalk.red('deleting')
797
+ };
798
+
799
+ };
800
+
801
+ /**
802
+ * Filter deleted and recreated attributes,
803
+ * return list of attributes to create
804
+ * @returns {Promise<*|*[]>}
805
+ */
806
+ const attributesToCreate = async (remoteAttributes, localAttributes, collection, isIndex = false) => {
807
+
808
+ const deleting = remoteAttributes.filter((attribute) => !attributesContains(attribute, localAttributes)).map((attr) => generateChangesObject(attr, collection, false));
809
+ const adding = localAttributes.filter((attribute) => !attributesContains(attribute, remoteAttributes)).map((attr) => generateChangesObject(attr, collection, true));
810
+ const conflicts = remoteAttributes.map((attribute) => checkAttributeChanges(attribute, attributesContains(attribute, localAttributes), collection)).filter(attribute => attribute !== undefined);
811
+ const changes = remoteAttributes.map((attribute) => checkAttributeChanges(attribute, attributesContains(attribute, localAttributes), collection, false))
812
+ .filter(attribute => attribute !== undefined)
813
+ .filter(attribute => conflicts.filter(attr => attribute.key === attr.key).length !== 1);
814
+
815
+ let changedAttributes = [];
816
+ const changing = [...deleting, ...adding, ...conflicts, ...changes]
817
+ if (changing.length === 0) {
818
+ return changedAttributes;
819
+ }
820
+
821
+ log(!cliConfig.force ? 'There are pending changes in your collection deployment' : 'List of applied changes');
822
+
823
+ drawTable(changing.map((change) => {
824
+ return { Key: change.key, Action: change.action, Reason: change.reason, };
825
+ }));
826
+
827
+ if (!cliConfig.force) {
828
+ if (deleting.length > 0 && !isIndex) {
829
+ console.log(`${chalk.red('-------------------------------------------------------')}`);
830
+ console.log(`${chalk.red('| WARNING: Attribute deletion may cause loss of data |')}`);
831
+ console.log(`${chalk.red('-------------------------------------------------------')}`);
832
+ }
833
+ if (conflicts.length > 0 && !isIndex) {
834
+ console.log(`${chalk.red('---------------------------------------------------------')}`);
835
+ console.log(`${chalk.red('| WARNING: Attribute recreation may cause loss of data |')}`);
836
+ console.log(`${chalk.red('---------------------------------------------------------')}`);
837
+ }
838
+
839
+ if ((await getConfirmation()) !== true) {
840
+ return changedAttributes;
841
+ }
842
+ }
843
+
844
+ if (conflicts.length > 0) {
845
+ changedAttributes = conflicts.map((change) => change.attribute);
846
+ await Promise.all(changedAttributes.map((changed) => deleteAttribute(collection, changed, isIndex)));
847
+ remoteAttributes = remoteAttributes.filter((attribute) => !attributesContains(attribute, changedAttributes))
848
+ }
849
+
850
+ if (changes.length > 0) {
851
+ changedAttributes = changes.map((change) => change.attribute);
852
+ await Promise.all(changedAttributes.map((changed) => updateAttribute(collection['databaseId'], collection['$id'], changed)));
853
+ }
854
+
855
+ const deletingAttributes = deleting.map((change) => change.attribute);
856
+ await Promise.all(deletingAttributes.map((attribute) => deleteAttribute(collection, attribute, isIndex)));
857
+ const attributeKeys = [...remoteAttributes.map(attribute => attribute.key), ...deletingAttributes.map(attribute => attribute.key)]
858
+
859
+ if (attributeKeys.length) {
860
+ const deleteAttributesPoolStatus = await awaitPools.deleteAttributes(collection['databaseId'], collection['$id'], attributeKeys);
861
+
862
+ if (!deleteAttributesPoolStatus) {
863
+ throw new Error("Attribute deletion timed out.");
864
+ }
865
+ }
866
+
867
+ return localAttributes.filter((attribute) => !attributesContains(attribute, remoteAttributes));
868
+ }
869
+ const createIndexes = async (indexes, collection) => {
870
+ log(`Creating indexes ...`)
871
+
872
+ for (let index of indexes) {
873
+ await databasesCreateIndex({
874
+ databaseId: collection['databaseId'],
875
+ collectionId: collection['$id'],
876
+ key: index.key,
877
+ type: index.type,
878
+ attributes: index.attributes,
879
+ orders: index.orders,
880
+ parseOutput: false
881
+ });
882
+ }
883
+
884
+ const result = await awaitPools.expectIndexes(
885
+ collection['databaseId'],
886
+ collection['$id'],
887
+ indexes.map(index => index.key)
888
+ );
889
+
890
+ if (!result) {
891
+ throw new Error("Index creation timed out.");
892
+ }
893
+
894
+ success(`Created ${indexes.length} indexes`);
895
+ }
896
+ const createAttributes = async (attributes, collection) => {
897
+ for (let attribute of attributes) {
898
+ if (attribute.side !== 'child') {
899
+ await createAttribute(collection['databaseId'], collection['$id'], attribute);
900
+ }
901
+ }
902
+
903
+ const result = await awaitPools.expectAttributes(
904
+ collection['databaseId'],
905
+ collection['$id'],
906
+ collection.attributes.filter(attribute => attribute.side !== 'child').map(attribute => attribute.key)
907
+ );
908
+
909
+ if (!result) {
910
+ throw new Error(`Attribute creation timed out.`);
911
+ }
912
+
913
+ success(`Created ${attributes.length} attributes`);
914
+ }
915
+
916
+ const pushResources = async () => {
917
+ const actions = {
918
+ settings: pushSettings,
919
+ functions: pushFunction,
920
+ sites: pushSite,
921
+ collections: pushCollection,
922
+ buckets: pushBucket,
923
+ teams: pushTeam,
924
+ messages: pushMessagingTopic
925
+ }
926
+
927
+ if (cliConfig.all) {
928
+ for (let action of Object.values(actions)) {
929
+ await action({ returnOnZero: true });
930
+ }
931
+ } else {
932
+ const answers = await inquirer.prompt(questionsPushResources[0]);
933
+
934
+ const action = actions[answers.resource];
935
+ if (action !== undefined) {
936
+ await action({ returnOnZero: true });
937
+ }
938
+ }
939
+ };
940
+
941
+ const pushSettings = async () => {
942
+ checkDeployConditions(localConfig);
943
+
944
+ try {
945
+ let response = await projectsGet({
946
+ parseOutput: false,
947
+ projectId: localConfig.getProject().projectId
948
+ });
949
+
950
+ const remoteSettings = localConfig.createSettingsObject(response ?? {});
951
+ const localSettings = localConfig.getProject().projectSettings ?? {};
952
+
953
+ log('Checking for changes ...');
954
+ const changes = [];
955
+
956
+ changes.push(...(getObjectChanges(remoteSettings, localSettings, 'services', 'Service')));
957
+ changes.push(...(getObjectChanges(remoteSettings['auth'] ?? {}, localSettings['auth'] ?? {}, 'methods', 'Auth method')));
958
+ changes.push(...(getObjectChanges(remoteSettings['auth'] ?? {}, localSettings['auth'] ?? {}, 'security', 'Auth security')));
959
+
960
+ if (changes.length > 0) {
961
+ drawTable(changes);
962
+ if ((await getConfirmation()) !== true) {
963
+ success(`Successfully pushed 0 project settings.`);
964
+ return;
965
+ }
966
+ }
967
+ } catch (e) {
968
+ }
969
+
970
+ try {
971
+ log("Pushing project settings ...");
972
+
973
+ const projectId = localConfig.getProject().projectId;
974
+ const projectName = localConfig.getProject().projectName;
975
+ const settings = localConfig.getProject().projectSettings ?? {};
976
+
977
+ if (projectName) {
978
+ log("Applying project name ...");
979
+ await projectsUpdate({
980
+ projectId,
981
+ name: projectName,
982
+ parseOutput: false
983
+ });
984
+ }
985
+
986
+ if (settings.services) {
987
+ log("Applying service statuses ...");
988
+ for (let [service, status] of Object.entries(settings.services)) {
989
+ await projectsUpdateServiceStatus({
990
+ projectId,
991
+ service,
992
+ status,
993
+ parseOutput: false
994
+ });
995
+ }
996
+ }
997
+
998
+ if (settings.auth) {
999
+ if (settings.auth.security) {
1000
+ log("Applying auth security settings ...");
1001
+ await projectsUpdateAuthDuration({ projectId, duration: settings.auth.security.duration, parseOutput: false });
1002
+ await projectsUpdateAuthLimit({ projectId, limit: settings.auth.security.limit, parseOutput: false });
1003
+ await projectsUpdateAuthSessionsLimit({ projectId, limit: settings.auth.security.sessionsLimit, parseOutput: false });
1004
+ await projectsUpdateAuthPasswordDictionary({ projectId, enabled: settings.auth.security.passwordDictionary, parseOutput: false });
1005
+ await projectsUpdateAuthPasswordHistory({ projectId, limit: settings.auth.security.passwordHistory, parseOutput: false });
1006
+ await projectsUpdatePersonalDataCheck({ projectId, enabled: settings.auth.security.personalDataCheck, parseOutput: false });
1007
+ await projectsUpdateSessionAlerts({ projectId, alerts: settings.auth.security.sessionAlerts, parseOutput: false });
1008
+ await projectsUpdateMockNumbers({ projectId, numbers: settings.auth.security.mockNumbers, parseOutput: false });
1009
+ }
1010
+
1011
+ if (settings.auth.methods) {
1012
+ log("Applying auth methods statuses ...");
1013
+
1014
+ for (let [method, status] of Object.entries(settings.auth.methods)) {
1015
+ await projectsUpdateAuthStatus({
1016
+ projectId,
1017
+ method,
1018
+ status,
1019
+ parseOutput: false
1020
+ });
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+ success(`Successfully pushed ${chalk.bold('all')} project settings.`);
1026
+ } catch (e) {
1027
+ throw e;
1028
+ }
1029
+ }
1030
+
1031
+ const pushSite = async({ siteId, async, code, withVariables } = { returnOnZero: false }) => {
1032
+ process.chdir(localConfig.configDirectoryPath)
1033
+
1034
+ const siteIds = [];
1035
+
1036
+ if(siteId) {
1037
+ siteIds.push(siteId);
1038
+ } else if (cliConfig.all) {
1039
+ checkDeployConditions(localConfig);
1040
+ const sites = localConfig.getSites();
1041
+ siteIds.push(...sites.map((site) => {
1042
+ return site.$id;
1043
+ }));
1044
+ }
1045
+
1046
+ if (siteIds.length <= 0) {
1047
+ const answers = await inquirer.prompt(questionsPushSites[0]);
1048
+ if (answers.sites) {
1049
+ siteIds.push(...answers.sites);
1050
+ }
1051
+ }
1052
+
1053
+ if (siteIds.length === 0) {
1054
+ log("No sites found.");
1055
+ hint("Use 'appwrite pull sites' to synchronize existing one, or use 'appwrite init site' to create a new one.");
1056
+ return;
1057
+ }
1058
+
1059
+ let sites = siteIds.map((id) => {
1060
+ const sites = localConfig.getSites();
1061
+ const site = sites.find((s) => s.$id === id);
1062
+
1063
+ if (!site) {
1064
+ throw new Error("Site '" + id + "' not found.")
1065
+ }
1066
+
1067
+ return site;
1068
+ });
1069
+
1070
+ log('Validating sites ...');
1071
+ // Validation is done BEFORE pushing so the deployment process can be run in async with progress update
1072
+ for (let site of sites) {
1073
+
1074
+ if (!site.buildCommand) {
1075
+ log(`Site ${site.name} is missing build command.`);
1076
+ const answers = await inquirer.prompt(questionsGetBuildCommand)
1077
+ site.buildCommand = answers.buildCommand;
1078
+ localConfig.addSite(site);
1079
+ }
1080
+ }
1081
+
1082
+ if (!(await approveChanges(sites, sitesGet, KeysSite, 'siteId', 'sites', ['vars']))) {
1083
+ return;
1084
+ }
1085
+
1086
+ log('Pushing sites ...');
1087
+
1088
+ Spinner.start(false);
1089
+ let successfullyPushed = 0;
1090
+ let successfullyDeployed = 0;
1091
+ const failedDeployments = [];
1092
+ const errors = [];
1093
+
1094
+ await Promise.all(sites.map(async (site) => {
1095
+ let response = {};
1096
+
1097
+ const ignore = site.ignore ? 'appwrite.json' : '.gitignore';
1098
+ let siteExists = false;
1099
+ let deploymentCreated = false;
1100
+
1101
+ const updaterRow = new Spinner({ status: '', resource: site.name, id: site['$id'], end: `Ignoring using: ${ignore}` });
1102
+
1103
+ updaterRow.update({ status: 'Getting' }).startSpinner(SPINNER_DOTS);
1104
+
1105
+ try {
1106
+ response = await sitesGet({
1107
+ siteId: site['$id'],
1108
+ parseOutput: false,
1109
+ });
1110
+ siteExists = true;
1111
+ if (response.framework !== site.framework) {
1112
+ updaterRow.fail({ errorMessage: `Framework mismatch! (local=${site.framework},remote=${response.framework}) Please delete remote site or update your appwrite.json` })
1113
+ return;
1114
+ }
1115
+
1116
+ updaterRow.update({ status: 'Updating' }).replaceSpinner(SPINNER_ARC);
1117
+
1118
+ response = await sitesUpdate({
1119
+ siteId: site['$id'],
1120
+ name: site.name,
1121
+ framework: site.framework,
1122
+ buildRuntime: site.buildRuntime,
1123
+ specification: site.specification,
1124
+ timeout: site.timeout,
1125
+ enabled: site.enabled,
1126
+ logging: site.logging,
1127
+ adapter: site.adapter,
1128
+ buildCommand: site.buildCommand,
1129
+ installCommand: site.installCommand,
1130
+ outputDirectory: site.outputDirectory,
1131
+ fallbackFile: site.fallbackFile,
1132
+ vars: JSON.stringify(response.vars),
1133
+ parseOutput: false
1134
+ });
1135
+ } catch (e) {
1136
+
1137
+ if (Number(e.code) === 404) {
1138
+ siteExists = false;
1139
+ } else {
1140
+ errors.push(e);
1141
+ updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' });
1142
+ return;
1143
+ }
1144
+ }
1145
+
1146
+ if (!siteExists) {
1147
+ updaterRow.update({ status: 'Creating' }).replaceSpinner(SPINNER_DOTS);
1148
+
1149
+ try {
1150
+ response = await sitesCreate({
1151
+ siteId: site.$id,
1152
+ name: site.name,
1153
+ framework: site.framework,
1154
+ specification: site.specification,
1155
+ buildRuntime: site.buildRuntime,
1156
+ buildCommand: site.buildCommand,
1157
+ installCommand: site.installCommand,
1158
+ outputDirectory: site.outputDirectory,
1159
+ fallbackFile: site.fallbackFile,
1160
+ adapter: site.adapter,
1161
+ timeout: site.timeout,
1162
+ enabled: site.enabled,
1163
+ logging: site.logging,
1164
+ parseOutput: false
1165
+ });
1166
+
1167
+ let domain = '';
1168
+ try {
1169
+ const variables = await consoleVariables({ parseOutput: false, sdk: await sdkForConsole() });
1170
+ domain = ID.unique() + '.' + variables['_APP_DOMAIN_SITES'];
1171
+ } catch (error) {
1172
+ console.error('Error fetching console variables.');
1173
+ throw error;
1174
+ }
1175
+
1176
+ try {
1177
+ const rule = await proxyCreateSiteRule(
1178
+ {
1179
+ domain: domain,
1180
+ siteId: site.$id
1181
+ }
1182
+ );
1183
+ } catch (error) {
1184
+ console.error('Error creating site rule.');
1185
+ throw error;
1186
+ }
1187
+
1188
+ updaterRow.update({ status: 'Created' });
1189
+ } catch (e) {
1190
+ errors.push(e)
1191
+ updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' });
1192
+ return;
1193
+ }
1194
+ }
1195
+
1196
+ if (withVariables) {
1197
+ updaterRow.update({ status: 'Creating variables' }).replaceSpinner(SPINNER_ARC);
1198
+
1199
+ const { variables } = await paginate(sitesListVariables, {
1200
+ siteId: site['$id'],
1201
+ parseOutput: false
1202
+ }, 100, 'variables');
1203
+
1204
+ await Promise.all(variables.map(async variable => {
1205
+ await sitesDeleteVariable({
1206
+ siteId: site['$id'],
1207
+ variableId: variable['$id'],
1208
+ parseOutput: false
1209
+ });
1210
+ }));
1211
+
1212
+ const envFileLocation = `${site['path']}/.env`;
1213
+ let envVariables = [];
1214
+ try {
1215
+ if (fs.existsSync(envFileLocation)) {
1216
+ const envObject = parseDotenv(fs.readFileSync(envFileLocation, 'utf8'));
1217
+ envVariables = Object.entries(envObject || {}).map(([key, value]) => ({ key, value }));
1218
+ }
1219
+ } catch (error) {
1220
+ // Handle parsing errors gracefully
1221
+ envVariables = [];
1222
+ }
1223
+ await Promise.all(envVariables.map(async variable => {
1224
+ await sitesCreateVariable({
1225
+ siteId: site['$id'],
1226
+ key: variable.key,
1227
+ value: variable.value,
1228
+ parseOutput: false,
1229
+ secret: false
1230
+ });
1231
+ }));
1232
+ }
1233
+
1234
+ if (code === false) {
1235
+ successfullyPushed++;
1236
+ successfullyDeployed++;
1237
+ updaterRow.update({ status: 'Pushed' });
1238
+ updaterRow.stopSpinner();
1239
+ return;
1240
+ }
1241
+
1242
+ try {
1243
+ updaterRow.update({ status: 'Pushing' }).replaceSpinner(SPINNER_ARC);
1244
+ response = await sitesCreateDeployment({
1245
+ siteId: site['$id'],
1246
+ buildCommand: site.buildCommand,
1247
+ installCommand: site.installCommand,
1248
+ outputDirectory: site.outputDirectory,
1249
+ fallbackFile: site.fallbackFile,
1250
+ code: site.path,
1251
+ activate: true,
1252
+ parseOutput: false
1253
+ })
1254
+
1255
+ updaterRow.update({ status: 'Pushed' });
1256
+ deploymentCreated = true;
1257
+ successfullyPushed++;
1258
+ } catch (e) {
1259
+ errors.push(e);
1260
+
1261
+ switch (e.code) {
1262
+ case 'ENOENT':
1263
+ updaterRow.fail({ errorMessage: 'Not found in the current directory. Skipping...' })
1264
+ break;
1265
+ default:
1266
+ updaterRow.fail({ errorMessage: e.message ?? 'An unknown error occurred. Please try again.' })
1267
+ }
1268
+ }
1269
+
1270
+ if (deploymentCreated && !async) {
1271
+ try {
1272
+ const deploymentId = response['$id'];
1273
+ updaterRow.update({ status: 'Deploying', end: 'Checking deployment status...' })
1274
+ let pollChecks = 0;
1275
+
1276
+ while (true) {
1277
+ response = await sitesGetDeployment({
1278
+ siteId: site['$id'],
1279
+ deploymentId: deploymentId,
1280
+ parseOutput: false
1281
+ });
1282
+
1283
+ const status = response['status'];
1284
+ if (status === 'ready') {
1285
+ successfullyDeployed++;
1286
+
1287
+ let url = '';
1288
+ const res = await proxyListRules({
1289
+ parseOutput: false,
1290
+ queries: [
1291
+ JSON.stringify({ method: 'limit', values: [1] }),
1292
+ JSON.stringify({ method: 'equal', "attribute": "deploymentResourceType", "values": ["site"] }),
1293
+ JSON.stringify({ method: 'equal', "attribute": "deploymentResourceId", "values": [site['$id']] }),
1294
+ JSON.stringify({ method: 'equal', "attribute": "trigger", "values": ["manual"] }),
1295
+ ],
1296
+ });
1297
+
1298
+ if (Number(res.total) === 1) {
1299
+ url = res.rules[0].domain;
1300
+ }
1301
+
1302
+ updaterRow.update({ status: 'Deployed', end: url });
1303
+
1304
+ break;
1305
+ } else if (status === 'failed') {
1306
+ failedDeployments.push({ name: site['name'], $id: site['$id'], deployment: response['$id'] });
1307
+ updaterRow.fail({ errorMessage: `Failed to deploy` });
1308
+
1309
+ break;
1310
+ } else {
1311
+ updaterRow.update({ status: 'Deploying', end: `Current status: ${status}` })
1312
+ }
1313
+
1314
+ pollChecks++;
1315
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE * 1.5));
1316
+ }
1317
+ } catch (e) {
1318
+ errors.push(e);
1319
+ updaterRow.fail({ errorMessage: e.message ?? 'Unknown error occurred. Please try again' })
1320
+ }
1321
+ }
1322
+
1323
+ updaterRow.stopSpinner();
1324
+ }));
1325
+
1326
+ Spinner.stop();
1327
+
1328
+ failedDeployments.forEach((failed) => {
1329
+ const { name, deployment, $id } = failed;
1330
+ const failUrl = `${globalConfig.getEndpoint().slice(0, -3)}/console/project-${localConfig.getProject().projectId}/sites/site-${$id}/deployments/deployment-${deployment}`;
1331
+
1332
+ error(`Deployment of ${name} has failed. Check at ${failUrl} for more details\n`);
1333
+ });
1334
+
1335
+ if (!async) {
1336
+ if (successfullyPushed === 0) {
1337
+ error('No sites were pushed.');
1338
+ } else if (successfullyDeployed !== successfullyPushed) {
1339
+ warn(`Successfully pushed ${successfullyDeployed} of ${successfullyPushed} sites`)
1340
+ } else {
1341
+ success(`Successfully pushed ${successfullyPushed} sites.`);
1342
+ }
1343
+ } else {
1344
+ success(`Successfully pushed ${successfullyPushed} sites.`);
1345
+ }
1346
+
1347
+ if (cliConfig.verbose) {
1348
+ errors.forEach(e => {
1349
+ console.error(e);
1350
+ })
1351
+ }
1352
+ }
1353
+
1354
+ const pushFunction = async ({ functionId, async, code, withVariables } = { returnOnZero: false }) => {
1355
+ process.chdir(localConfig.configDirectoryPath)
1356
+
1357
+ const functionIds = [];
1358
+
1359
+ if (functionId) {
1360
+ functionIds.push(functionId);
1361
+ } else if (cliConfig.all) {
1362
+ checkDeployConditions(localConfig);
1363
+ const functions = localConfig.getFunctions();
1364
+ functionIds.push(...functions.map((func) => {
1365
+ return func.$id;
1366
+ }));
1367
+ }
1368
+
1369
+ if (functionIds.length <= 0) {
1370
+ const answers = await inquirer.prompt(questionsPushFunctions[0]);
1371
+ if (answers.functions) {
1372
+ functionIds.push(...answers.functions);
1373
+ }
1374
+ }
1375
+
1376
+ if (functionIds.length === 0) {
1377
+ log("No functions found.");
1378
+ hint("Use 'appwrite pull functions' to synchronize existing one, or use 'appwrite init function' to create a new one.");
1379
+ return;
1380
+ }
1381
+
1382
+ let functions = functionIds.map((id) => {
1383
+ const functions = localConfig.getFunctions();
1384
+ const func = functions.find((f) => f.$id === id);
1385
+
1386
+ if (!func) {
1387
+ throw new Error("Function '" + id + "' not found.")
1388
+ }
1389
+
1390
+ return func;
1391
+ });
1392
+
1393
+ log('Validating functions ...');
1394
+ // Validation is done BEFORE pushing so the deployment process can be run in async with progress update
1395
+ for (let func of functions) {
1396
+
1397
+ if (!func.entrypoint) {
1398
+ log(`Function ${func.name} is missing an entrypoint.`);
1399
+ const answers = await inquirer.prompt(questionsGetEntrypoint)
1400
+ func.entrypoint = answers.entrypoint;
1401
+ localConfig.addFunction(func);
1402
+ }
1403
+ }
1404
+
1405
+ if (!(await approveChanges(functions, functionsGet, KeysFunction, 'functionId', 'functions', ['vars']))) {
1406
+ return;
1407
+ }
1408
+
1409
+ log('Pushing functions ...');
1410
+
1411
+ Spinner.start(false);
1412
+ let successfullyPushed = 0;
1413
+ let successfullyDeployed = 0;
1414
+ const failedDeployments = [];
1415
+ const errors = [];
1416
+
1417
+ await Promise.all(functions.map(async (func) => {
1418
+ let response = {};
1419
+
1420
+ const ignore = func.ignore ? 'appwrite.json' : '.gitignore';
1421
+ let functionExists = false;
1422
+ let deploymentCreated = false;
1423
+
1424
+ const updaterRow = new Spinner({ status: '', resource: func.name, id: func['$id'], end: `Ignoring using: ${ignore}` });
1425
+
1426
+ updaterRow.update({ status: 'Getting' }).startSpinner(SPINNER_DOTS);
1427
+ try {
1428
+ response = await functionsGet({
1429
+ functionId: func['$id'],
1430
+ parseOutput: false,
1431
+ });
1432
+ functionExists = true;
1433
+ if (response.runtime !== func.runtime) {
1434
+ updaterRow.fail({ errorMessage: `Runtime mismatch! (local=${func.runtime},remote=${response.runtime}) Please delete remote function or update your appwrite.json` })
1435
+ return;
1436
+ }
1437
+
1438
+ updaterRow.update({ status: 'Updating' }).replaceSpinner(SPINNER_ARC);
1439
+
1440
+ response = await functionsUpdate({
1441
+ functionId: func['$id'],
1442
+ name: func.name,
1443
+ specification: func.specification,
1444
+ execute: func.execute,
1445
+ events: func.events,
1446
+ schedule: func.schedule,
1447
+ timeout: func.timeout,
1448
+ enabled: func.enabled,
1449
+ logging: func.logging,
1450
+ entrypoint: func.entrypoint,
1451
+ commands: func.commands,
1452
+ scopes: func.scopes,
1453
+ vars: JSON.stringify(response.vars),
1454
+ parseOutput: false
1455
+ });
1456
+ } catch (e) {
1457
+
1458
+ if (Number(e.code) === 404) {
1459
+ functionExists = false;
1460
+ } else {
1461
+ errors.push(e);
1462
+ updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' });
1463
+ return;
1464
+ }
1465
+ }
1466
+
1467
+ if (!functionExists) {
1468
+ updaterRow.update({ status: 'Creating' }).replaceSpinner(SPINNER_DOTS);
1469
+
1470
+ try {
1471
+ response = await functionsCreate({
1472
+ functionId: func.$id,
1473
+ name: func.name,
1474
+ runtime: func.runtime,
1475
+ specification: func.specification,
1476
+ execute: func.execute,
1477
+ events: func.events,
1478
+ schedule: func.schedule,
1479
+ timeout: func.timeout,
1480
+ enabled: func.enabled,
1481
+ logging: func.logging,
1482
+ entrypoint: func.entrypoint,
1483
+ commands: func.commands,
1484
+ scopes: func.scopes,
1485
+ parseOutput: false
1486
+ });
1487
+
1488
+ let domain = '';
1489
+ try {
1490
+ const variables = await consoleVariables({ parseOutput: false, sdk: await sdkForConsole() });
1491
+ domain = ID.unique() + '.' + variables['_APP_DOMAIN_FUNCTIONS'];
1492
+ } catch (error) {
1493
+ console.error('Error fetching console variables.');
1494
+ throw error;
1495
+ }
1496
+
1497
+ try {
1498
+ const rule = await proxyCreateFunctionRule(
1499
+ {
1500
+ domain: domain,
1501
+ functionId: func.$id
1502
+ }
1503
+ );
1504
+ } catch (error) {
1505
+ console.error('Error creating function rule.');
1506
+ throw error;
1507
+ }
1508
+
1509
+ updaterRow.update({ status: 'Created' });
1510
+ } catch (e) {
1511
+ errors.push(e)
1512
+ updaterRow.fail({ errorMessage: e.message ?? 'General error occurs please try again' });
1513
+ return;
1514
+ }
1515
+ }
1516
+
1517
+ if (withVariables) {
1518
+ updaterRow.update({ status: 'Updating variables' }).replaceSpinner(SPINNER_ARC);
1519
+
1520
+ const { variables } = await paginate(functionsListVariables, {
1521
+ functionId: func['$id'],
1522
+ parseOutput: false
1523
+ }, 100, 'variables');
1524
+
1525
+ await Promise.all(variables.map(async variable => {
1526
+ await functionsDeleteVariable({
1527
+ functionId: func['$id'],
1528
+ variableId: variable['$id'],
1529
+ parseOutput: false
1530
+ });
1531
+ }));
1532
+
1533
+ const envFileLocation = `${func['path']}/.env`;
1534
+ let envVariables = [];
1535
+ try {
1536
+ if (fs.existsSync(envFileLocation)) {
1537
+ const envObject = parseDotenv(fs.readFileSync(envFileLocation, 'utf8'));
1538
+ envVariables = Object.entries(envObject || {}).map(([key, value]) => ({ key, value }));
1539
+ }
1540
+ } catch (error) {
1541
+ // Handle parsing errors gracefully
1542
+ envVariables = [];
1543
+ }
1544
+ await Promise.all(envVariables.map(async variable => {
1545
+ await functionsCreateVariable({
1546
+ functionId: func['$id'],
1547
+ variableId: ID.unique(),
1548
+ key: variable.key,
1549
+ value: variable.value,
1550
+ parseOutput: false,
1551
+ secret: false
1552
+ });
1553
+ }));
1554
+ }
1555
+
1556
+ if (code === false) {
1557
+ successfullyPushed++;
1558
+ successfullyDeployed++;
1559
+ updaterRow.update({ status: 'Pushed' });
1560
+ updaterRow.stopSpinner();
1561
+ return;
1562
+ }
1563
+
1564
+ try {
1565
+ updaterRow.update({ status: 'Pushing' }).replaceSpinner(SPINNER_ARC);
1566
+ response = await functionsCreateDeployment({
1567
+ functionId: func['$id'],
1568
+ entrypoint: func.entrypoint,
1569
+ commands: func.commands,
1570
+ code: func.path,
1571
+ activate: true,
1572
+ parseOutput: false
1573
+ })
1574
+
1575
+ updaterRow.update({ status: 'Pushed' });
1576
+ deploymentCreated = true;
1577
+ successfullyPushed++;
1578
+ } catch (e) {
1579
+ errors.push(e);
1580
+
1581
+ switch (e.code) {
1582
+ case 'ENOENT':
1583
+ updaterRow.fail({ errorMessage: 'Not found in the current directory. Skipping...' })
1584
+ break;
1585
+ default:
1586
+ updaterRow.fail({ errorMessage: e.message ?? 'An unknown error occurred. Please try again.' })
1587
+ }
1588
+ }
1589
+
1590
+ if (deploymentCreated && !async) {
1591
+ try {
1592
+ const deploymentId = response['$id'];
1593
+ updaterRow.update({ status: 'Deploying', end: 'Checking deployment status...' })
1594
+ let pollChecks = 0;
1595
+
1596
+ while (true) {
1597
+ response = await functionsGetDeployment({
1598
+ functionId: func['$id'],
1599
+ deploymentId: deploymentId,
1600
+ parseOutput: false
1601
+ });
1602
+
1603
+
1604
+ const status = response['status'];
1605
+ if (status === 'ready') {
1606
+ successfullyDeployed++;
1607
+
1608
+ let url = '';
1609
+ const res = await proxyListRules({
1610
+ parseOutput: false,
1611
+ queries: [
1612
+ JSON.stringify({ method: 'limit', values: [1] }),
1613
+ JSON.stringify({ method: 'equal', "attribute": "deploymentResourceType", "values": ["function"] }),
1614
+ JSON.stringify({ method: 'equal', "attribute": "deploymentResourceId", "values": [func['$id']] }),
1615
+ JSON.stringify({ method: 'equal', "attribute": "trigger", "values": ["manual"] }),
1616
+ ],
1617
+ });
1618
+
1619
+ if (Number(res.total) === 1) {
1620
+ url = res.rules[0].domain;
1621
+ }
1622
+
1623
+ updaterRow.update({ status: 'Deployed', end: url });
1624
+
1625
+ break;
1626
+ } else if (status === 'failed') {
1627
+ failedDeployments.push({ name: func['name'], $id: func['$id'], deployment: response['$id'] });
1628
+ updaterRow.fail({ errorMessage: `Failed to deploy` });
1629
+
1630
+ break;
1631
+ } else {
1632
+ updaterRow.update({ status: 'Deploying', end: `Current status: ${status}` })
1633
+ }
1634
+
1635
+ pollChecks++;
1636
+ await new Promise(resolve => setTimeout(resolve, POLL_DEBOUNCE * 1.5));
1637
+ }
1638
+ } catch (e) {
1639
+ errors.push(e);
1640
+ updaterRow.fail({ errorMessage: e.message ?? 'Unknown error occurred. Please try again' })
1641
+ }
1642
+ }
1643
+
1644
+ updaterRow.stopSpinner();
1645
+ }));
1646
+
1647
+ Spinner.stop();
1648
+
1649
+ failedDeployments.forEach((failed) => {
1650
+ const { name, deployment, $id } = failed;
1651
+ const failUrl = `${globalConfig.getEndpoint().slice(0, -3)}/console/project-${localConfig.getProject().projectId}/functions/function-${$id}/deployment-${deployment}`;
1652
+
1653
+ error(`Deployment of ${name} has failed. Check at ${failUrl} for more details\n`);
1654
+ });
1655
+
1656
+ if (!async) {
1657
+ if (successfullyPushed === 0) {
1658
+ error('No functions were pushed.');
1659
+ } else if (successfullyDeployed !== successfullyPushed) {
1660
+ warn(`Successfully pushed ${successfullyDeployed} of ${successfullyPushed} functions`)
1661
+ } else {
1662
+ success(`Successfully pushed ${successfullyPushed} functions.`);
1663
+ }
1664
+ } else {
1665
+ success(`Successfully pushed ${successfullyPushed} functions.`);
1666
+ }
1667
+
1668
+ if (cliConfig.verbose) {
1669
+ errors.forEach(e => {
1670
+ console.error(e);
1671
+ })
1672
+ }
1673
+ }
1674
+
1675
+ const pushCollection = async ({ returnOnZero, attempts } = { returnOnZero: false }) => {
1676
+ const collections = [];
1677
+
1678
+ if (attempts) {
1679
+ pollMaxDebounces = attempts;
1680
+ }
1681
+
1682
+ if (cliConfig.all) {
1683
+ checkDeployConditions(localConfig);
1684
+ collections.push(...localConfig.getCollections());
1685
+ } else {
1686
+ const answers = await inquirer.prompt(questionsPushCollections)
1687
+ if (answers.collections) {
1688
+ const configCollections = new Map();
1689
+ localConfig.getCollections().forEach((c) => {
1690
+ configCollections.set(`${c['databaseId']}|${c['$id']}`, c);
1691
+ });
1692
+ answers.collections.forEach((a) => {
1693
+ const collection = configCollections.get(a);
1694
+ collections.push(collection);
1695
+ })
1696
+ }
1697
+ }
1698
+
1699
+ if (collections.length === 0) {
1700
+ log("No collections found.");
1701
+ hint("Use 'appwrite pull collections' to synchronize existing one, or use 'appwrite init collection' to create a new one.");
1702
+ return;
1703
+ }
1704
+
1705
+ const databases = Array.from(new Set(collections.map(collection => collection['databaseId'])));
1706
+
1707
+ // Parallel db actions
1708
+ await Promise.all(databases.map(async (databaseId) => {
1709
+ const localDatabase = localConfig.getDatabase(databaseId);
1710
+
1711
+ try {
1712
+ const database = await databasesGet({
1713
+ databaseId: databaseId,
1714
+ parseOutput: false,
1715
+ });
1716
+
1717
+ if (database.name !== (localDatabase.name ?? databaseId)) {
1718
+ await databasesUpdate({
1719
+ databaseId: databaseId,
1720
+ name: localDatabase.name ?? databaseId,
1721
+ parseOutput: false
1722
+ })
1723
+
1724
+ success(`Updated ${localDatabase.name} ( ${databaseId} ) name`);
1725
+ }
1726
+ } catch (err) {
1727
+ log(`Database ${databaseId} not found. Creating it now ...`);
1728
+
1729
+ await databasesCreate({
1730
+ databaseId: databaseId,
1731
+ name: localDatabase.name ?? databaseId,
1732
+ parseOutput: false,
1733
+ });
1734
+ }
1735
+ }));
1736
+
1737
+
1738
+ if (!(await approveChanges(collections, databasesGetCollection, KeysCollection, 'collectionId', 'collections', ['attributes', 'indexes'], 'databaseId', 'databaseId',))) {
1739
+ return;
1740
+ }
1741
+ // Parallel collection actions
1742
+ await Promise.all(collections.map(async (collection) => {
1743
+ try {
1744
+ const remoteCollection = await databasesGetCollection({
1745
+ databaseId: collection['databaseId'],
1746
+ collectionId: collection['$id'],
1747
+ parseOutput: false,
1748
+ });
1749
+
1750
+ if (remoteCollection.name !== collection.name) {
1751
+ await databasesUpdateCollection({
1752
+ databaseId: collection['databaseId'],
1753
+ collectionId: collection['$id'],
1754
+ name: collection.name,
1755
+ name: collection.name,
1756
+ parseOutput: false
1757
+ })
1758
+
1759
+ success(`Updated ${collection.name} ( ${collection['$id']} ) name`);
1760
+ }
1761
+ collection.remoteVersion = remoteCollection;
1762
+
1763
+ collection.isExisted = true;
1764
+ } catch
1765
+ (e) {
1766
+ if (Number(e.code) === 404) {
1767
+ log(`Collection ${collection.name} does not exist in the project. Creating ... `);
1768
+ await databasesCreateCollection({
1769
+ databaseId: collection['databaseId'],
1770
+ collectionId: collection['$id'],
1771
+ name: collection.name,
1772
+ documentSecurity: collection.documentSecurity,
1773
+ permissions: collection['$permissions'],
1774
+ parseOutput: false
1775
+ })
1776
+ } else {
1777
+ throw e;
1778
+ }
1779
+ }
1780
+ }))
1781
+ let numberOfCollections = 0;
1782
+ // Serialize attribute actions
1783
+ for (let collection of collections) {
1784
+ let attributes = collection.attributes;
1785
+ let indexes = collection.indexes;
1786
+
1787
+ if (collection.isExisted) {
1788
+ attributes = await attributesToCreate(collection.remoteVersion.attributes, collection.attributes, collection);
1789
+ indexes = await attributesToCreate(collection.remoteVersion.indexes, collection.indexes, collection, true);
1790
+
1791
+ if ((Array.isArray(attributes) && attributes.length <= 0) && (Array.isArray(indexes) && indexes.length <= 0)) {
1792
+ continue;
1793
+ }
1794
+
1795
+ }
1796
+
1797
+ log(`Pushing collection ${collection.name} ( ${collection['databaseId']} - ${collection['$id']} ) attributes`)
1798
+
1799
+ try {
1800
+ await createAttributes(attributes, collection)
1801
+ } catch (e) {
1802
+ throw e;
1803
+ }
1804
+
1805
+ try {
1806
+ await createIndexes(indexes, collection);
1807
+ } catch (e) {
1808
+ throw e;
1809
+ }
1810
+ numberOfCollections++;
1811
+ success(`Successfully pushed ${collection.name} ( ${collection['$id']} )`);
1812
+ }
1813
+
1814
+ success(`Successfully pushed ${numberOfCollections} collections`);
1815
+ }
1816
+
1817
+ const pushBucket = async ({ returnOnZero } = { returnOnZero: false }) => {
1818
+ let response = {};
1819
+
1820
+ let bucketIds = [];
1821
+ const configBuckets = localConfig.getBuckets();
1822
+
1823
+ if (cliConfig.all) {
1824
+ checkDeployConditions(localConfig);
1825
+ bucketIds.push(...configBuckets.map((b) => b.$id));
1826
+ }
1827
+
1828
+ if (bucketIds.length === 0) {
1829
+ const answers = await inquirer.prompt(questionsPushBuckets[0])
1830
+ if (answers.buckets) {
1831
+ bucketIds.push(...answers.buckets);
1832
+ }
1833
+ }
1834
+
1835
+ if (bucketIds.length === 0) {
1836
+ log("No buckets found.");
1837
+ hint("Use 'appwrite pull buckets' to synchronize existing one, or use 'appwrite init bucket' to create a new one.");
1838
+ return;
1839
+ }
1840
+
1841
+ let buckets = [];
1842
+
1843
+ for (const bucketId of bucketIds) {
1844
+ const idBuckets = configBuckets.filter((b) => b.$id === bucketId);
1845
+ buckets.push(...idBuckets);
1846
+ }
1847
+
1848
+ if (!(await approveChanges(buckets, storageGetBucket, KeysStorage, 'bucketId', 'buckets'))) {
1849
+ return;
1850
+ }
1851
+
1852
+ log('Pushing buckets ...');
1853
+
1854
+ for (let bucket of buckets) {
1855
+ log(`Pushing bucket ${chalk.bold(bucket['name'])} ...`);
1856
+
1857
+ try {
1858
+ response = await storageGetBucket({
1859
+ bucketId: bucket['$id'],
1860
+ parseOutput: false,
1861
+ })
1862
+
1863
+ await storageUpdateBucket({
1864
+ bucketId: bucket['$id'],
1865
+ name: bucket.name,
1866
+ permissions: bucket['$permissions'],
1867
+ fileSecurity: bucket.fileSecurity,
1868
+ enabled: bucket.enabled,
1869
+ maximumFileSize: bucket.maximumFileSize,
1870
+ allowedFileExtensions: bucket.allowedFileExtensions,
1871
+ encryption: bucket.encryption,
1872
+ antivirus: bucket.antivirus,
1873
+ compression: bucket.compression,
1874
+ parseOutput: false
1875
+ });
1876
+ } catch (e) {
1877
+ if (Number(e.code) === 404) {
1878
+ log(`Bucket ${bucket.name} does not exist in the project. Creating ... `);
1879
+
1880
+ response = await storageCreateBucket({
1881
+ bucketId: bucket['$id'],
1882
+ name: bucket.name,
1883
+ permissions: bucket['$permissions'],
1884
+ fileSecurity: bucket.fileSecurity,
1885
+ enabled: bucket.enabled,
1886
+ maximumFileSize: bucket.maximumFileSize,
1887
+ allowedFileExtensions: bucket.allowedFileExtensions,
1888
+ compression: bucket.compression,
1889
+ encryption: bucket.encryption,
1890
+ antivirus: bucket.antivirus,
1891
+ parseOutput: false
1892
+ })
1893
+ } else {
1894
+ throw e;
1895
+ }
1896
+ }
1897
+ }
1898
+
1899
+ success(`Successfully pushed ${buckets.length} buckets.`);
1900
+ }
1901
+
1902
+ const pushTeam = async ({ returnOnZero } = { returnOnZero: false }) => {
1903
+ let response = {};
1904
+
1905
+ let teamIds = [];
1906
+ const configTeams = localConfig.getTeams();
1907
+
1908
+ if (cliConfig.all) {
1909
+ checkDeployConditions(localConfig);
1910
+ teamIds.push(...configTeams.map((t) => t.$id));
1911
+ }
1912
+
1913
+ if (teamIds.length === 0) {
1914
+ const answers = await inquirer.prompt(questionsPushTeams[0])
1915
+ if (answers.teams) {
1916
+ teamIds.push(...answers.teams);
1917
+ }
1918
+ }
1919
+
1920
+ if (teamIds.length === 0) {
1921
+ log("No teams found.");
1922
+ hint("Use 'appwrite pull teams' to synchronize existing one, or use 'appwrite init team' to create a new one.");
1923
+ return;
1924
+ }
1925
+
1926
+ let teams = [];
1927
+
1928
+ for (const teamId of teamIds) {
1929
+ const idTeams = configTeams.filter((t) => t.$id === teamId);
1930
+ teams.push(...idTeams);
1931
+ }
1932
+
1933
+ if (!(await approveChanges(teams, teamsGet, KeysTeams, 'teamId', 'teams'))) {
1934
+ return;
1935
+ }
1936
+
1937
+
1938
+ log('Pushing teams ...');
1939
+
1940
+ for (let team of teams) {
1941
+ log(`Pushing team ${chalk.bold(team['name'])} ...`);
1942
+
1943
+ try {
1944
+ response = await teamsGet({
1945
+ teamId: team['$id'],
1946
+ parseOutput: false,
1947
+ })
1948
+
1949
+ await teamsUpdateName({
1950
+ teamId: team['$id'],
1951
+ name: team.name,
1952
+ parseOutput: false
1953
+ });
1954
+ } catch (e) {
1955
+ if (Number(e.code) === 404) {
1956
+ log(`Team ${team.name} does not exist in the project. Creating ... `);
1957
+
1958
+ response = await teamsCreate({
1959
+ teamId: team['$id'],
1960
+ name: team.name,
1961
+ parseOutput: false
1962
+ })
1963
+ } else {
1964
+ throw e;
1965
+ }
1966
+ }
1967
+ }
1968
+
1969
+ success(`Successfully pushed ${teams.length} teams.`);
1970
+ }
1971
+
1972
+ const pushMessagingTopic = async ({ returnOnZero } = { returnOnZero: false }) => {
1973
+ let response = {};
1974
+
1975
+ let topicsIds = [];
1976
+ const configTopics = localConfig.getMessagingTopics();
1977
+
1978
+ if (cliConfig.all) {
1979
+ checkDeployConditions(localConfig);
1980
+ topicsIds.push(...configTopics.map((b) => b.$id));
1981
+ }
1982
+
1983
+ if (topicsIds.length === 0) {
1984
+ const answers = await inquirer.prompt(questionsPushMessagingTopics[0])
1985
+ if (answers.topics) {
1986
+ topicsIds.push(...answers.topics);
1987
+ }
1988
+ }
1989
+
1990
+ if (topicsIds.length === 0) {
1991
+ log("No topics found.");
1992
+ hint("Use 'appwrite pull topics' to synchronize existing one, or use 'appwrite init topic' to create a new one.");
1993
+ return;
1994
+ }
1995
+
1996
+ let topics = [];
1997
+
1998
+ for (const topicId of topicsIds) {
1999
+ const idTopic = configTopics.filter((b) => b.$id === topicId);
2000
+ topics.push(...idTopic);
2001
+ }
2002
+
2003
+ if (!(await approveChanges(topics, messagingGetTopic, KeysTopics, 'topicId', 'topics'))) {
2004
+ return;
2005
+ }
2006
+
2007
+ log('Pushing topics ...');
2008
+
2009
+ for (let topic of topics) {
2010
+ log(`Pushing topic ${chalk.bold(topic['name'])} ...`);
2011
+
2012
+ try {
2013
+ response = await messagingGetTopic({
2014
+ topicId: topic['$id'],
2015
+ parseOutput: false
2016
+ })
2017
+ log(`Topic ${topic.name} ( ${topic['$id']} ) already exists.`);
2018
+
2019
+ await messagingUpdateTopic({
2020
+ topicId: topic['$id'],
2021
+ name: topic.name,
2022
+ subscribe: topic.subscribe,
2023
+ parseOutput: false
2024
+ });
2025
+ } catch (e) {
2026
+ if (Number(e.code) === 404) {
2027
+ log(`Topic ${topic.name} does not exist in the project. Creating ... `);
2028
+
2029
+ response = await messagingCreateTopic({
2030
+ topicId: topic['$id'],
2031
+ name: topic.name,
2032
+ subscribe: topic.subscribe,
2033
+ parseOutput: false
2034
+ })
2035
+
2036
+ success(`Created ${topic.name} ( ${topic['$id']} )`);
2037
+ } else {
2038
+ throw e;
2039
+ }
2040
+ }
2041
+ }
2042
+
2043
+ success(`Successfully pushed ${topics.length} topics.`);
2044
+ }
2045
+
2046
+ const push = new Command("push")
2047
+ .description(commandDescriptions['push'])
2048
+ .action(actionRunner(pushResources));
2049
+
2050
+ push
2051
+ .command("all")
2052
+ .description("Push all resource.")
2053
+ .action(actionRunner(() => {
2054
+ cliConfig.all = true;
2055
+ return pushResources();
2056
+ }));
2057
+
2058
+ push
2059
+ .command("settings")
2060
+ .description("Push project name, services and auth settings")
2061
+ .action(actionRunner(pushSettings));
2062
+
2063
+ push
2064
+ .command("function")
2065
+ .alias("functions")
2066
+ .description("Push functions in the current directory.")
2067
+ .option(`-f, --function-id <function-id>`, `ID of function to run`)
2068
+ .option(`-A, --async`, `Don't wait for functions deployments status`)
2069
+ .option("--no-code", "Don't push the function's code")
2070
+ .option("--with-variables", `Push function variables.`)
2071
+ .action(actionRunner(pushFunction));
2072
+
2073
+ push
2074
+ .command("site")
2075
+ .alias("sites")
2076
+ .description("Push sites in the current directory.")
2077
+ .option(`-f, --site-id <site-id>`, `ID of site to run`)
2078
+ .option(`-A, --async`, `Don't wait for sites deployments status`)
2079
+ .option("--no-code", "Don't push the site's code")
2080
+ .option("--with-variables", `Push site variables.`)
2081
+ .action(actionRunner(pushSite));
2082
+
2083
+ push
2084
+ .command("collection")
2085
+ .alias("collections")
2086
+ .description("Push collections in the current project.")
2087
+ .option(`-a, --attempts <numberOfAttempts>`, `Max number of attempts before timing out. default: 30.`)
2088
+ .action(actionRunner(pushCollection));
2089
+
2090
+ push
2091
+ .command("bucket")
2092
+ .alias("buckets")
2093
+ .description("Push buckets in the current project.")
2094
+ .action(actionRunner(pushBucket));
2095
+
2096
+ push
2097
+ .command("team")
2098
+ .alias("teams")
2099
+ .description("Push teams in the current project.")
2100
+ .action(actionRunner(pushTeam));
2101
+
2102
+ push
2103
+ .command("topic")
2104
+ .alias("topics")
2105
+ .description("Push messaging topics in the current project.")
2106
+ .action(actionRunner(pushMessagingTopic));
2107
+
2108
+ const deploy = new Command("deploy")
2109
+ .description('Removed. Use appwrite push instead')
2110
+ .action(actionRunner(async () => {
2111
+ warn("appwrite deploy has been removed. Please use 'appwrite push' instead");
2112
+ }));
2113
+
2114
+ module.exports = {
2115
+ push,
2116
+ deploy
2117
+ }