@gadgetinc/ggt 2.3.0 → 3.0.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 (224) hide show
  1. package/README.md +387 -327
  2. package/dist/action-CF6zatIh.js +64 -0
  3. package/dist/action-CF6zatIh.js.map +1 -0
  4. package/dist/action-CrDCeX3F.js +8 -0
  5. package/dist/action-CrDCeX3F.js.map +1 -0
  6. package/dist/add-Basu3Gyf.js +1 -0
  7. package/dist/agent-plugin-CqgwTOk-.js +15 -0
  8. package/dist/agent-plugin-CqgwTOk-.js.map +1 -0
  9. package/dist/agent-plugin-DU9G5B1d.js +9 -0
  10. package/dist/agent-plugin-DU9G5B1d.js.map +1 -0
  11. package/dist/assert-Bu1E126Z.js +2 -0
  12. package/dist/assert-Bu1E126Z.js.map +1 -0
  13. package/dist/chunk-BjEoQXZ0.js +1 -0
  14. package/dist/collection-C2TCeYqY.js +2 -0
  15. package/dist/collection-C2TCeYqY.js.map +1 -0
  16. package/dist/collection-aM0fpch0.js +1 -0
  17. package/dist/command-2iNTc5dV.js +118 -0
  18. package/dist/command-2iNTc5dV.js.map +1 -0
  19. package/dist/completion-D96nxD5n.js +37 -0
  20. package/dist/completion-D96nxD5n.js.map +1 -0
  21. package/dist/configure-C8ge-2cK.js +15 -0
  22. package/dist/configure-C8ge-2cK.js.map +1 -0
  23. package/dist/debugger-BkYgApKn.js +22 -0
  24. package/dist/debugger-BkYgApKn.js.map +1 -0
  25. package/dist/defaults-B_eD7Pia.js +2 -0
  26. package/dist/defaults-B_eD7Pia.js.map +1 -0
  27. package/dist/deploy-Da6P2HXS.js +15 -0
  28. package/dist/deploy-Da6P2HXS.js.map +1 -0
  29. package/dist/dev-DWMSNcLl.js +32 -0
  30. package/dist/dev-DWMSNcLl.js.map +1 -0
  31. package/dist/dev-lock-BFanZSu1.js +10 -0
  32. package/dist/dev-lock-BFanZSu1.js.map +1 -0
  33. package/dist/directory-CNL03L6c.js +9 -0
  34. package/dist/directory-CNL03L6c.js.map +1 -0
  35. package/dist/env-DoWNvHzW.js +62 -0
  36. package/dist/env-DoWNvHzW.js.map +1 -0
  37. package/dist/esm-B25i6Etq.js +12 -0
  38. package/dist/esm-B25i6Etq.js.map +1 -0
  39. package/dist/esm-CJocZrdd.js +2 -0
  40. package/dist/esm-CJocZrdd.js.map +1 -0
  41. package/dist/eval-BceZMSd5.js +27 -0
  42. package/dist/eval-BceZMSd5.js.map +1 -0
  43. package/dist/execAsync-DrhcEHLd.js +2 -0
  44. package/dist/execAsync-DrhcEHLd.js.map +1 -0
  45. package/dist/filesync-De6asZeR.js +61 -0
  46. package/dist/filesync-De6asZeR.js.map +1 -0
  47. package/dist/getMachineId-bsd-Cch8Z6pV.js +2 -0
  48. package/dist/getMachineId-bsd-Cch8Z6pV.js.map +1 -0
  49. package/dist/getMachineId-darwin-kbQWK54o.js +3 -0
  50. package/dist/getMachineId-darwin-kbQWK54o.js.map +1 -0
  51. package/dist/getMachineId-linux-DdIel6zr.js +2 -0
  52. package/dist/getMachineId-linux-DdIel6zr.js.map +1 -0
  53. package/dist/getMachineId-unsupported-Bvmsh30k.js +2 -0
  54. package/dist/getMachineId-unsupported-Bvmsh30k.js.map +1 -0
  55. package/dist/getMachineId-win-BteHZe8j.js +2 -0
  56. package/dist/getMachineId-win-BteHZe8j.js.map +1 -0
  57. package/dist/ggt-B3HQjQRM.js +3 -0
  58. package/dist/ggt-B3HQjQRM.js.map +1 -0
  59. package/dist/handler-DZyG8Sel.js +4 -0
  60. package/dist/handler-DZyG8Sel.js.map +1 -0
  61. package/dist/http-CY3lPMkt.js +320 -0
  62. package/dist/http-CY3lPMkt.js.map +1 -0
  63. package/dist/indent-string-BVm-4tyL.js +2 -0
  64. package/dist/indent-string-BVm-4tyL.js.map +1 -0
  65. package/dist/list-lQKWZ6ZI.js +10 -0
  66. package/dist/list-lQKWZ6ZI.js.map +1 -0
  67. package/dist/login-Ce0tByNd.js +1 -0
  68. package/dist/logout-_sTWeaiQ.js +5 -0
  69. package/dist/logout-_sTWeaiQ.js.map +1 -0
  70. package/dist/logs-DbhJzz4M.js +9 -0
  71. package/dist/logs-DbhJzz4M.js.map +1 -0
  72. package/dist/main.js +2 -2
  73. package/dist/main.js.map +1 -7
  74. package/dist/model-CBiMKY0P.js +11 -0
  75. package/dist/model-CBiMKY0P.js.map +1 -0
  76. package/dist/ms-B7sMc0pR.js +2 -0
  77. package/dist/ms-B7sMc0pR.js.map +1 -0
  78. package/dist/open-CSsA4B-l.js +38 -0
  79. package/dist/open-CSsA4B-l.js.map +1 -0
  80. package/dist/p-map-DE0acmRv.js +2 -0
  81. package/dist/p-map-DE0acmRv.js.map +1 -0
  82. package/dist/problems-BMLsmxd4.js +11 -0
  83. package/dist/problems-BMLsmxd4.js.map +1 -0
  84. package/dist/prompt-C9nwJW0G.js +2 -0
  85. package/dist/prompt-C9nwJW0G.js.map +1 -0
  86. package/dist/pull-DpizmJGk.js +12 -0
  87. package/dist/pull-DpizmJGk.js.map +1 -0
  88. package/dist/push-67KBCw6c.js +12 -0
  89. package/dist/push-67KBCw6c.js.map +1 -0
  90. package/dist/root-D_UnUsp7.js +28 -0
  91. package/dist/root-D_UnUsp7.js.map +1 -0
  92. package/dist/select-Dey_sjjd.js +4 -0
  93. package/dist/select-Dey_sjjd.js.map +1 -0
  94. package/dist/session-BmzGF1t7.js +2 -0
  95. package/dist/session-BmzGF1t7.js.map +1 -0
  96. package/dist/spinner-BVmbgIil.js +8 -0
  97. package/dist/spinner-BVmbgIil.js.map +1 -0
  98. package/dist/src-DxCC1MV4.js +6 -0
  99. package/dist/src-DxCC1MV4.js.map +1 -0
  100. package/dist/status-P_RFQ7J0.js +13 -0
  101. package/dist/status-P_RFQ7J0.js.map +1 -0
  102. package/dist/subscribeToEnvironmentLogs-CUicaiw_.js +2 -0
  103. package/dist/subscribeToEnvironmentLogs-CUicaiw_.js.map +1 -0
  104. package/dist/sync-json-V52OzeCz.js +112 -0
  105. package/dist/sync-json-V52OzeCz.js.map +1 -0
  106. package/dist/table-MrBbxMay.js +11 -0
  107. package/dist/table-MrBbxMay.js.map +1 -0
  108. package/dist/update-CfxiL08e.js +12 -0
  109. package/dist/update-CfxiL08e.js.map +1 -0
  110. package/dist/update-iyhnL9-M.js +1 -0
  111. package/dist/var-ByWcufFt.js +59 -0
  112. package/dist/var-ByWcufFt.js.map +1 -0
  113. package/dist/version-B_9GB4u3.js +9 -0
  114. package/dist/version-B_9GB4u3.js.map +1 -0
  115. package/dist/whoami-BNcXIfz7.js +5 -0
  116. package/dist/whoami-BNcXIfz7.js.map +1 -0
  117. package/package.json +18 -22
  118. package/assets/favicon-128@4x.png +0 -0
  119. package/dist/add-7MLI3TCY.js +0 -82
  120. package/dist/add-7MLI3TCY.js.map +0 -7
  121. package/dist/agent-plugin-543K6WBH.js +0 -11
  122. package/dist/agent-plugin-543K6WBH.js.map +0 -7
  123. package/dist/chunk-2HJS3KFB.js +0 -2
  124. package/dist/chunk-2HJS3KFB.js.map +0 -7
  125. package/dist/chunk-3WKH3DJL.js +0 -2
  126. package/dist/chunk-3WKH3DJL.js.map +0 -7
  127. package/dist/chunk-577KP32Z.js +0 -8
  128. package/dist/chunk-577KP32Z.js.map +0 -7
  129. package/dist/chunk-6FVHOLT7.js +0 -28
  130. package/dist/chunk-6FVHOLT7.js.map +0 -7
  131. package/dist/chunk-72J7X5LR.js +0 -2
  132. package/dist/chunk-72J7X5LR.js.map +0 -7
  133. package/dist/chunk-7DYQUG5M.js +0 -2
  134. package/dist/chunk-7DYQUG5M.js.map +0 -7
  135. package/dist/chunk-ALSXPCRD.js +0 -118
  136. package/dist/chunk-ALSXPCRD.js.map +0 -7
  137. package/dist/chunk-CNNOPE5K.js +0 -69
  138. package/dist/chunk-CNNOPE5K.js.map +0 -7
  139. package/dist/chunk-ETKWDO4V.js +0 -2
  140. package/dist/chunk-ETKWDO4V.js.map +0 -7
  141. package/dist/chunk-F6BGQ4LG.js +0 -11
  142. package/dist/chunk-F6BGQ4LG.js.map +0 -7
  143. package/dist/chunk-FE5O5VX4.js +0 -2
  144. package/dist/chunk-FE5O5VX4.js.map +0 -7
  145. package/dist/chunk-GFQYFEEH.js +0 -2
  146. package/dist/chunk-GFQYFEEH.js.map +0 -7
  147. package/dist/chunk-GJGBTM5Y.js +0 -2
  148. package/dist/chunk-GJGBTM5Y.js.map +0 -7
  149. package/dist/chunk-GZTHIOXS.js +0 -2
  150. package/dist/chunk-GZTHIOXS.js.map +0 -7
  151. package/dist/chunk-IQSZEOYY.js +0 -283
  152. package/dist/chunk-IQSZEOYY.js.map +0 -7
  153. package/dist/chunk-J232VCIM.js +0 -2
  154. package/dist/chunk-J232VCIM.js.map +0 -7
  155. package/dist/chunk-KKIL22RY.js +0 -2
  156. package/dist/chunk-KKIL22RY.js.map +0 -7
  157. package/dist/chunk-L2XBSR7G.js +0 -2
  158. package/dist/chunk-L2XBSR7G.js.map +0 -7
  159. package/dist/chunk-N5FFICAP.js +0 -9
  160. package/dist/chunk-N5FFICAP.js.map +0 -7
  161. package/dist/chunk-TGCJ6TMW.js +0 -10
  162. package/dist/chunk-TGCJ6TMW.js.map +0 -7
  163. package/dist/chunk-ULJYEUQG.js +0 -113
  164. package/dist/chunk-ULJYEUQG.js.map +0 -7
  165. package/dist/chunk-UVVKKUYG.js +0 -10
  166. package/dist/chunk-UVVKKUYG.js.map +0 -7
  167. package/dist/chunk-WZ2PO6H2.js +0 -11
  168. package/dist/chunk-WZ2PO6H2.js.map +0 -7
  169. package/dist/chunk-X4XSYLCE.js +0 -12
  170. package/dist/chunk-X4XSYLCE.js.map +0 -7
  171. package/dist/chunk-ZYDMXS5R.js +0 -6
  172. package/dist/chunk-ZYDMXS5R.js.map +0 -7
  173. package/dist/configure-PYRXYNGZ.js +0 -12
  174. package/dist/configure-PYRXYNGZ.js.map +0 -7
  175. package/dist/debugger-VKLUEWIN.js +0 -41
  176. package/dist/debugger-VKLUEWIN.js.map +0 -7
  177. package/dist/deploy-JCREEGBA.js +0 -25
  178. package/dist/deploy-JCREEGBA.js.map +0 -7
  179. package/dist/dev-Y2GLI7EH.js +0 -59
  180. package/dist/dev-Y2GLI7EH.js.map +0 -7
  181. package/dist/env-5OPHX3MC.js +0 -135
  182. package/dist/env-5OPHX3MC.js.map +0 -7
  183. package/dist/esm-3JVXH7DT.js +0 -37
  184. package/dist/esm-3JVXH7DT.js.map +0 -7
  185. package/dist/eval-LZPZ6PBQ.js +0 -54
  186. package/dist/eval-LZPZ6PBQ.js.map +0 -7
  187. package/dist/getMachineId-bsd-QUXN4NKS.js +0 -2
  188. package/dist/getMachineId-bsd-QUXN4NKS.js.map +0 -7
  189. package/dist/getMachineId-darwin-TCXBAX22.js +0 -3
  190. package/dist/getMachineId-darwin-TCXBAX22.js.map +0 -7
  191. package/dist/getMachineId-linux-IJ3LYIOX.js +0 -2
  192. package/dist/getMachineId-linux-IJ3LYIOX.js.map +0 -7
  193. package/dist/getMachineId-unsupported-IKXBUCYY.js +0 -2
  194. package/dist/getMachineId-unsupported-IKXBUCYY.js.map +0 -7
  195. package/dist/getMachineId-win-6CX7VSFF.js +0 -2
  196. package/dist/getMachineId-win-6CX7VSFF.js.map +0 -7
  197. package/dist/ggt-KUAF6WUA.js +0 -45
  198. package/dist/ggt-KUAF6WUA.js.map +0 -7
  199. package/dist/list-IANT7SNF.js +0 -11
  200. package/dist/list-IANT7SNF.js.map +0 -7
  201. package/dist/login-TYRZLN5S.js +0 -2
  202. package/dist/login-TYRZLN5S.js.map +0 -7
  203. package/dist/logout-P75XYYZ6.js +0 -7
  204. package/dist/logout-P75XYYZ6.js.map +0 -7
  205. package/dist/logs-SBMD6JSR.js +0 -28
  206. package/dist/logs-SBMD6JSR.js.map +0 -7
  207. package/dist/open-JPAMII4K.js +0 -74
  208. package/dist/open-JPAMII4K.js.map +0 -7
  209. package/dist/problems-EZRSHLZT.js +0 -14
  210. package/dist/problems-EZRSHLZT.js.map +0 -7
  211. package/dist/pull-R3PMBVOT.js +0 -28
  212. package/dist/pull-R3PMBVOT.js.map +0 -7
  213. package/dist/push-5XEEESQQ.js +0 -2
  214. package/dist/push-5XEEESQQ.js.map +0 -7
  215. package/dist/status-RJN5ES6S.js +0 -14
  216. package/dist/status-RJN5ES6S.js.map +0 -7
  217. package/dist/update-X7YS3MNH.js +0 -2
  218. package/dist/update-X7YS3MNH.js.map +0 -7
  219. package/dist/var-PC6KQUPF.js +0 -159
  220. package/dist/var-PC6KQUPF.js.map +0 -7
  221. package/dist/version-GZJOU2CV.js +0 -11
  222. package/dist/version-GZJOU2CV.js.map +0 -7
  223. package/dist/whoami-GKPGPZ3B.js +0 -7
  224. package/dist/whoami-GKPGPZ3B.js.map +0 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-DWMSNcLl.js","names":["process","RetryfyQueue","readdir","sfs","readdir","EventEmitter","posix","sep","join","colors"],"sources":["../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/constants.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/enums.js","../node_modules/.pnpm/dettle@1.0.5/node_modules/dettle/dist/debounce.js","../node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/attemptify.js","../node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/constants.js","../node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/handlers.js","../node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/retryify_queue.js","../node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/retryify.js","../node_modules/.pnpm/stubborn-fs@1.2.5/node_modules/stubborn-fs/dist/index.js","../node_modules/.pnpm/promise-make-naked@3.0.2/node_modules/promise-make-naked/dist/utils.js","../node_modules/.pnpm/promise-make-naked@3.0.2/node_modules/promise-make-naked/dist/index.js","../node_modules/.pnpm/promise-make-counter@1.0.2/node_modules/promise-make-counter/dist/index.js","../node_modules/.pnpm/tiny-readdir@2.7.4_patch_hash=3dce4e110ba2c24db565b9002cc31dd2dc4034f4db553ad7855e07872f737b39/node_modules/tiny-readdir/dist/constants.js","../node_modules/.pnpm/tiny-readdir@2.7.4_patch_hash=3dce4e110ba2c24db565b9002cc31dd2dc4034f4db553ad7855e07872f737b39/node_modules/tiny-readdir/dist/utils.js","../node_modules/.pnpm/tiny-readdir@2.7.4_patch_hash=3dce4e110ba2c24db565b9002cc31dd2dc4034f4db553ad7855e07872f737b39/node_modules/tiny-readdir/dist/index.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/utils.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/watcher_handler.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/watcher_locks_resolver.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/watcher_locker.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/lazy_map_set.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/watcher_stats.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/watcher_poller.js","../node_modules/.pnpm/watcher@2.3.1_patch_hash=13bfcfa6ba91e30ec5d967b9dd42986b47c554ad2ab4fce1c31087e3da3c3b63/node_modules/watcher/dist/watcher.js","../node_modules/.pnpm/isexe@4.0.0/node_modules/isexe/dist/commonjs/index.min.js","../node_modules/.pnpm/which@6.0.1/node_modules/which/lib/index.js","../src/services/output/footer.ts","../src/services/output/notify.ts","../src/commands/dev.ts"],"sourcesContent":["/* IMPORT */\nimport os from 'node:os';\n/* MAIN */\nconst DEBOUNCE = 300;\nconst DEPTH = 20;\nconst LIMIT = 10000000;\nconst PLATFORM = os.platform();\nconst IS_LINUX = (PLATFORM === 'linux');\nconst IS_MAC = (PLATFORM === 'darwin');\nconst IS_WINDOWS = (PLATFORM === 'win32');\nconst HAS_NATIVE_RECURSION = IS_MAC || IS_WINDOWS;\nconst POLLING_INTERVAL = 3000;\nconst POLLING_TIMEOUT = 20000;\nconst RENAME_TIMEOUT = 1250;\n/* EXPORT */\nexport { DEBOUNCE, DEPTH, LIMIT, HAS_NATIVE_RECURSION, IS_LINUX, IS_MAC, IS_WINDOWS, PLATFORM, POLLING_INTERVAL, POLLING_TIMEOUT, RENAME_TIMEOUT };\n","/* MAIN */\nvar FileType;\n(function (FileType) {\n FileType[FileType[\"DIR\"] = 1] = \"DIR\";\n FileType[FileType[\"FILE\"] = 2] = \"FILE\";\n})(FileType || (FileType = {}));\nvar FSTargetEvent;\n(function (FSTargetEvent) {\n FSTargetEvent[\"CHANGE\"] = \"change\";\n FSTargetEvent[\"RENAME\"] = \"rename\";\n})(FSTargetEvent || (FSTargetEvent = {}));\nvar FSWatcherEvent;\n(function (FSWatcherEvent) {\n FSWatcherEvent[\"CHANGE\"] = \"change\";\n FSWatcherEvent[\"ERROR\"] = \"error\";\n})(FSWatcherEvent || (FSWatcherEvent = {}));\nvar TargetEvent;\n(function (TargetEvent) {\n TargetEvent[\"ADD\"] = \"add\";\n TargetEvent[\"ADD_DIR\"] = \"addDir\";\n TargetEvent[\"CHANGE\"] = \"change\";\n TargetEvent[\"RENAME\"] = \"rename\";\n TargetEvent[\"RENAME_DIR\"] = \"renameDir\";\n TargetEvent[\"UNLINK\"] = \"unlink\";\n TargetEvent[\"UNLINK_DIR\"] = \"unlinkDir\";\n})(TargetEvent || (TargetEvent = {}));\nvar WatcherEvent;\n(function (WatcherEvent) {\n WatcherEvent[\"ALL\"] = \"all\";\n WatcherEvent[\"CLOSE\"] = \"close\";\n WatcherEvent[\"ERROR\"] = \"error\";\n WatcherEvent[\"READY\"] = \"ready\";\n})(WatcherEvent || (WatcherEvent = {}));\n/* EXPORT */\nexport { FileType, FSTargetEvent, FSWatcherEvent, TargetEvent, WatcherEvent };\n","/* IMPORT */\n/* MAIN */\nconst debounce = (fn, wait = 1, options) => {\n /* VARIABLES */\n wait = Math.max(1, wait);\n const leading = options?.leading ?? false;\n const trailing = options?.trailing ?? true;\n const maxWait = Math.max(options?.maxWait ?? Infinity, wait);\n let args;\n let timeout;\n let timestampCall = 0;\n let timestampInvoke = 0;\n /* HELPERS */\n const getInstantData = () => {\n const timestamp = Date.now();\n const elapsedCall = timestamp - timestampCall;\n const elapsedInvoke = timestamp - timestampInvoke;\n const isInvoke = (elapsedCall >= wait || elapsedInvoke >= maxWait);\n return [timestamp, isInvoke];\n };\n const invoke = (timestamp) => {\n timestampInvoke = timestamp;\n if (!args)\n return; // This should never happen\n const _args = args;\n args = undefined;\n fn.apply(undefined, _args);\n };\n const onCancel = () => {\n resetTimeout(0);\n };\n const onFlush = () => {\n if (!timeout)\n return;\n onCancel();\n invoke(Date.now());\n };\n const onLeading = (timestamp) => {\n timestampInvoke = timestamp;\n if (leading)\n return invoke(timestamp);\n };\n const onTrailing = (timestamp) => {\n if (trailing && args)\n return invoke(timestamp);\n args = undefined;\n };\n const onTimeout = () => {\n timeout = undefined;\n const [timestamp, isInvoking] = getInstantData();\n if (isInvoking)\n return onTrailing(timestamp);\n return updateTimeout(timestamp);\n };\n const updateTimeout = (timestamp) => {\n const elapsedCall = timestamp - timestampCall;\n const elapsedInvoke = timestamp - timestampInvoke;\n const remainingCall = wait - elapsedCall;\n const remainingInvoke = maxWait - elapsedInvoke;\n const ms = Math.min(remainingCall, remainingInvoke);\n return resetTimeout(ms);\n };\n const resetTimeout = (ms) => {\n if (timeout)\n clearTimeout(timeout);\n if (ms <= 0)\n return;\n timeout = setTimeout(onTimeout, ms);\n };\n /* DEBOUNCED */\n const debounced = (...argsLatest) => {\n const [timestamp, isInvoking] = getInstantData();\n const hadTimeout = !!timeout;\n args = argsLatest;\n timestampCall = timestamp;\n if (isInvoking || !timeout)\n resetTimeout(wait);\n if (isInvoking) {\n if (!hadTimeout)\n return onLeading(timestamp);\n return invoke(timestamp);\n }\n };\n /* DEBOUNCED UTILITIES */\n debounced.cancel = onCancel;\n debounced.flush = onFlush;\n /* RETURN */\n return debounced;\n};\n/* EXPORT */\nexport default debounce;\n","/* MAIN */\n//FIXME: The return type of these functions is wrong, it doesn't account for returning \"undefined\", but a correct type cannot be written because generics cannot be extended properly, it seems\nconst attemptifyAsync = (fn, onError) => {\n return function attemptified(...args) {\n return fn.apply(undefined, args).catch(onError);\n };\n};\nconst attemptifySync = (fn, onError) => {\n return function attemptified(...args) {\n try {\n return fn.apply(undefined, args);\n }\n catch (error) {\n return onError(error);\n }\n };\n};\n/* EXPORT */\nexport { attemptifyAsync, attemptifySync };\n","/* IMPORT */\nimport process from 'node:process';\n/* MAIN */\nconst IS_USER_ROOT = process.getuid ? !process.getuid() : false;\nconst LIMIT_FILES_DESCRIPTORS = 10000; //TODO: Fetch the real limit from the filesystem, somehow\nconst NOOP = () => undefined;\n/* EXPORT */\nexport { IS_USER_ROOT, LIMIT_FILES_DESCRIPTORS, NOOP };\n","/* IMPORT */\nimport { IS_USER_ROOT } from './constants.js';\n/* MAIN */\nconst Handlers = {\n /* API */\n isChangeErrorOk: (error) => {\n if (!Handlers.isNodeError(error))\n return false;\n const { code } = error;\n if (code === 'ENOSYS')\n return true;\n if (!IS_USER_ROOT && (code === 'EINVAL' || code === 'EPERM'))\n return true;\n return false;\n },\n isNodeError: (error) => {\n return (error instanceof Error);\n },\n isRetriableError: (error) => {\n if (!Handlers.isNodeError(error))\n return false;\n const { code } = error;\n if (code === 'EMFILE' || code === 'ENFILE' || code === 'EAGAIN' || code === 'EBUSY' || code === 'EACCESS' || code === 'EACCES' || code === 'EACCS' || code === 'EPERM')\n return true;\n return false;\n },\n onChangeError: (error) => {\n if (!Handlers.isNodeError(error))\n throw error;\n if (Handlers.isChangeErrorOk(error))\n return;\n throw error;\n }\n};\n/* EXPORT */\nexport default Handlers;\n","/* IMPORT */\nimport { LIMIT_FILES_DESCRIPTORS } from './constants.js';\n/* MAIN */\nclass RetryfyQueue {\n constructor() {\n /* VARIABLES */\n this.interval = 25;\n this.intervalId = undefined;\n this.limit = LIMIT_FILES_DESCRIPTORS;\n this.queueActive = new Set();\n this.queueWaiting = new Set();\n /* LIFECYCLE API */\n this.init = () => {\n if (this.intervalId)\n return;\n this.intervalId = setInterval(this.tick, this.interval);\n };\n this.reset = () => {\n if (!this.intervalId)\n return;\n clearInterval(this.intervalId);\n delete this.intervalId;\n };\n /* API */\n this.add = (fn) => {\n this.queueWaiting.add(fn);\n if (this.queueActive.size < (this.limit / 2)) { // Active queue not under preassure, executing immediately\n this.tick();\n }\n else {\n this.init();\n }\n };\n this.remove = (fn) => {\n this.queueWaiting.delete(fn);\n this.queueActive.delete(fn);\n };\n this.schedule = () => {\n return new Promise(resolve => {\n const cleanup = () => this.remove(resolver);\n const resolver = () => resolve(cleanup);\n this.add(resolver);\n });\n };\n this.tick = () => {\n if (this.queueActive.size >= this.limit)\n return;\n if (!this.queueWaiting.size)\n return this.reset();\n for (const fn of this.queueWaiting) {\n if (this.queueActive.size >= this.limit)\n break;\n this.queueWaiting.delete(fn);\n this.queueActive.add(fn);\n fn();\n }\n };\n }\n}\n;\n/* EXPORT */\nexport default new RetryfyQueue();\n","/* IMPORT */\nimport RetryfyQueue from './retryify_queue.js';\n/* MAIN */\n//FIXME: There are a boatload of anys here, but apparently generics cannot be extended properly, so...\nconst retryifyAsync = (fn, isRetriableError) => {\n return function retrified(timestamp) {\n return function attempt(...args) {\n return RetryfyQueue.schedule().then(cleanup => {\n const onResolve = (result) => {\n cleanup();\n return result;\n };\n const onReject = (error) => {\n cleanup();\n if (Date.now() >= timestamp)\n throw error;\n if (isRetriableError(error)) {\n const delay = Math.round(100 * Math.random());\n const delayPromise = new Promise(resolve => setTimeout(resolve, delay));\n return delayPromise.then(() => attempt.apply(undefined, args));\n }\n throw error;\n };\n return fn.apply(undefined, args).then(onResolve, onReject);\n });\n };\n };\n};\nconst retryifySync = (fn, isRetriableError) => {\n return function retrified(timestamp) {\n return function attempt(...args) {\n try {\n return fn.apply(undefined, args);\n }\n catch (error) {\n if (Date.now() > timestamp)\n throw error;\n if (isRetriableError(error))\n return attempt.apply(undefined, args);\n throw error;\n }\n };\n };\n};\n/* EXPORT */\nexport { retryifyAsync, retryifySync };\n","/* IMPORT */\nimport fs from 'node:fs';\nimport { promisify } from 'node:util';\nimport { attemptifyAsync, attemptifySync } from './attemptify.js';\nimport { NOOP } from './constants.js';\nimport Handlers from './handlers.js';\nimport { retryifyAsync, retryifySync } from './retryify.js';\n/* MAIN */\nconst FS = {\n attempt: {\n /* ASYNC */\n chmod: attemptifyAsync(promisify(fs.chmod), Handlers.onChangeError),\n chown: attemptifyAsync(promisify(fs.chown), Handlers.onChangeError),\n close: attemptifyAsync(promisify(fs.close), NOOP),\n fsync: attemptifyAsync(promisify(fs.fsync), NOOP),\n mkdir: attemptifyAsync(promisify(fs.mkdir), NOOP),\n realpath: attemptifyAsync(promisify(fs.realpath), NOOP),\n stat: attemptifyAsync(promisify(fs.stat), NOOP),\n unlink: attemptifyAsync(promisify(fs.unlink), NOOP),\n /* SYNC */\n chmodSync: attemptifySync(fs.chmodSync, Handlers.onChangeError),\n chownSync: attemptifySync(fs.chownSync, Handlers.onChangeError),\n closeSync: attemptifySync(fs.closeSync, NOOP),\n existsSync: attemptifySync(fs.existsSync, NOOP),\n fsyncSync: attemptifySync(fs.fsync, NOOP),\n mkdirSync: attemptifySync(fs.mkdirSync, NOOP),\n realpathSync: attemptifySync(fs.realpathSync, NOOP),\n statSync: attemptifySync(fs.statSync, NOOP),\n unlinkSync: attemptifySync(fs.unlinkSync, NOOP)\n },\n retry: {\n /* ASYNC */\n close: retryifyAsync(promisify(fs.close), Handlers.isRetriableError),\n fsync: retryifyAsync(promisify(fs.fsync), Handlers.isRetriableError),\n open: retryifyAsync(promisify(fs.open), Handlers.isRetriableError),\n readFile: retryifyAsync(promisify(fs.readFile), Handlers.isRetriableError),\n rename: retryifyAsync(promisify(fs.rename), Handlers.isRetriableError),\n stat: retryifyAsync(promisify(fs.stat), Handlers.isRetriableError),\n write: retryifyAsync(promisify(fs.write), Handlers.isRetriableError),\n writeFile: retryifyAsync(promisify(fs.writeFile), Handlers.isRetriableError),\n /* SYNC */\n closeSync: retryifySync(fs.closeSync, Handlers.isRetriableError),\n fsyncSync: retryifySync(fs.fsyncSync, Handlers.isRetriableError),\n openSync: retryifySync(fs.openSync, Handlers.isRetriableError),\n readFileSync: retryifySync(fs.readFileSync, Handlers.isRetriableError),\n renameSync: retryifySync(fs.renameSync, Handlers.isRetriableError),\n statSync: retryifySync(fs.statSync, Handlers.isRetriableError),\n writeSync: retryifySync(fs.writeSync, Handlers.isRetriableError),\n writeFileSync: retryifySync(fs.writeFileSync, Handlers.isRetriableError)\n }\n};\n/* EXPORT */\nexport default FS;\n","/* MAIN */\nconst noop = () => { };\n/* EXPORT */\nexport { noop };\n","/* IMPORT */\nimport { noop } from './utils.js';\n/* MAIN */\nconst makeNakedPromise = () => {\n let resolve = noop;\n let reject = noop;\n let resolved = false;\n let rejected = false;\n const promise = new Promise((res, rej) => {\n resolve = value => {\n resolved = true;\n return res(value);\n };\n reject = value => {\n rejected = true;\n return rej(value);\n };\n });\n const isPending = () => !resolved && !rejected;\n const isResolved = () => resolved;\n const isRejected = () => rejected;\n return { promise, resolve, reject, isPending, isResolved, isRejected };\n};\n/* EXPORT */\nexport default makeNakedPromise;\n","/* IMPORT */\nimport makeNakedPromise from 'promise-make-naked';\n/* MAIN */\nconst makeCounterPromise = () => {\n const { promise, resolve, isPending } = makeNakedPromise();\n let counter = 0;\n const increment = () => {\n counter += 1;\n };\n const decrement = () => {\n counter -= 1;\n if (counter)\n return;\n resolve();\n };\n const init = () => {\n increment();\n queueMicrotask(decrement);\n };\n init();\n return { promise, isPending, increment, decrement };\n};\n/* EXPORT */\nexport default makeCounterPromise;\n","/* IMPORT */\n/* MAIN */\nconst NOOP_PROMISE_LIKE = {\n then: (fn) => {\n fn();\n }\n};\n/* EXPORT */\nexport { NOOP_PROMISE_LIKE };\n","/* MAIN */\nconst castArray = (value) => {\n return Array.isArray(value) ? value : [value];\n};\nconst isFunction = (value) => {\n return (typeof value === 'function');\n};\n/* EXPORT */\nexport { castArray, isFunction };\n","/* IMPORT */\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport makeCounterPromise from 'promise-make-counter';\nimport { NOOP_PROMISE_LIKE } from './constants.js';\nimport { castArray, isFunction } from './utils.js';\n/* MAIN */\n//TODO: Streamline the type of dirmaps\nconst readdir = (rootPath, options) => {\n const followSymlinks = options?.followSymlinks ?? false;\n const maxDepth = options?.depth ?? Infinity;\n const maxPaths = options?.limit ?? Infinity;\n const ignore = options?.ignore ?? [];\n const ignores = castArray(ignore).map(ignore => isFunction(ignore) ? ignore : (targetPath) => ignore.test(targetPath));\n const isIgnored = (targetPath, isDirectory) => ignores.some(ignore => ignore(targetPath, isDirectory));\n const signal = options?.signal ?? { aborted: false };\n const onDirents = options?.onDirents || (() => { });\n const directories = [];\n const directoriesNames = new Set();\n const directoriesNamesToPaths = {};\n const files = [];\n const filesNames = new Set();\n const filesNamesToPaths = {};\n const symlinks = [];\n const symlinksNames = new Set();\n const symlinksNamesToPaths = {};\n const map = {};\n const visited = new Set();\n const resultEmpty = { directories: [], directoriesNames: new Set(), directoriesNamesToPaths: {}, files: [], filesNames: new Set(), filesNamesToPaths: {}, symlinks: [], symlinksNames: new Set(), symlinksNamesToPaths: {}, map: {} };\n const result = { directories, directoriesNames, directoriesNamesToPaths, files, filesNames, filesNamesToPaths, symlinks, symlinksNames, symlinksNamesToPaths, map };\n const { promise, increment, decrement } = makeCounterPromise();\n let foundPaths = 0;\n const handleDirectory = (dirmap, subPath, name, depth) => {\n if (visited.has(subPath))\n return;\n if (foundPaths >= maxPaths)\n return;\n foundPaths += 1;\n dirmap.directories.push(subPath);\n dirmap.directoriesNames.add(name);\n // dirmap.directoriesNamesToPaths.propertyIsEnumerable(name) || ( dirmap.directoriesNamesToPaths[name] = [] );\n // dirmap.directoriesNamesToPaths[name].push ( subPath );\n directories.push(subPath);\n directoriesNames.add(name);\n directoriesNamesToPaths.propertyIsEnumerable(name) || (directoriesNamesToPaths[name] = []);\n directoriesNamesToPaths[name].push(subPath);\n visited.add(subPath);\n if (depth >= maxDepth)\n return;\n if (foundPaths >= maxPaths)\n return;\n populateResultFromPath(subPath, depth + 1);\n };\n const handleFile = (dirmap, subPath, name) => {\n if (visited.has(subPath))\n return;\n if (foundPaths >= maxPaths)\n return;\n foundPaths += 1;\n dirmap.files.push(subPath);\n dirmap.filesNames.add(name);\n // dirmap.filesNamesToPaths.propertyIsEnumerable(name) || ( dirmap.filesNamesToPaths[name] = [] );\n // dirmap.filesNamesToPaths[name].push ( subPath );\n files.push(subPath);\n filesNames.add(name);\n filesNamesToPaths.propertyIsEnumerable(name) || (filesNamesToPaths[name] = []);\n filesNamesToPaths[name].push(subPath);\n visited.add(subPath);\n };\n const handleSymlink = (dirmap, subPath, name, depth) => {\n if (visited.has(subPath))\n return;\n if (foundPaths >= maxPaths)\n return;\n foundPaths += 1;\n dirmap.symlinks.push(subPath);\n dirmap.symlinksNames.add(name);\n // dirmap.symlinksNamesToPaths.propertyIsEnumerable(name) || ( dirmap.symlinksNamesToPaths[name] = [] );\n // dirmap.symlinksNamesToPaths[name].push ( subPath );\n symlinks.push(subPath);\n symlinksNames.add(name);\n symlinksNamesToPaths.propertyIsEnumerable(name) || (symlinksNamesToPaths[name] = []);\n symlinksNamesToPaths[name].push(subPath);\n visited.add(subPath);\n if (!followSymlinks)\n return;\n if (depth >= maxDepth)\n return;\n if (foundPaths >= maxPaths)\n return;\n populateResultFromSymlink(subPath, depth + 1);\n };\n const handleStat = (dirmap, rootPath, name, stat, depth) => {\n if (signal.aborted)\n return;\n if (isIgnored(rootPath, stat.isDirectory()))\n return;\n if (stat.isDirectory()) {\n handleDirectory(dirmap, rootPath, name, depth);\n }\n else if (stat.isFile()) {\n handleFile(dirmap, rootPath, name);\n }\n else if (stat.isSymbolicLink()) {\n handleSymlink(dirmap, rootPath, name, depth);\n }\n };\n const handleDirent = (dirmap, rootPath, dirent, depth) => {\n if (signal.aborted)\n return;\n const separator = (rootPath === path.sep) ? '' : path.sep;\n const name = dirent.name;\n const subPath = `${rootPath}${separator}${name}`;\n if (isIgnored(subPath, dirent.isDirectory()))\n return;\n if (dirent.isDirectory()) {\n handleDirectory(dirmap, subPath, name, depth);\n }\n else if (dirent.isFile()) {\n handleFile(dirmap, subPath, name);\n }\n else if (dirent.isSymbolicLink()) {\n handleSymlink(dirmap, subPath, name, depth);\n }\n };\n const handleDirents = (dirmap, rootPath, dirents, depth) => {\n for (let i = 0, l = dirents.length; i < l; i++) {\n handleDirent(dirmap, rootPath, dirents[i], depth);\n }\n };\n const populateResultFromPath = (rootPath, depth) => {\n if (signal.aborted)\n return;\n if (depth > maxDepth)\n return;\n if (foundPaths >= maxPaths)\n return;\n increment();\n fs.readdir(rootPath, { withFileTypes: true }, (error, dirents) => {\n if (error)\n return decrement();\n if (signal.aborted)\n return decrement();\n if (!dirents.length)\n return decrement();\n const promise = onDirents(dirents) || NOOP_PROMISE_LIKE;\n promise.then(() => {\n const dirmap = map[rootPath] = { directories: [], directoriesNames: new Set(), directoriesNamesToPaths: {}, files: [], filesNames: new Set(), filesNamesToPaths: {}, symlinks: [], symlinksNames: new Set(), symlinksNamesToPaths: {} };\n handleDirents(dirmap, rootPath, dirents, depth);\n decrement();\n });\n });\n };\n const populateResultFromSymlink = (rootPath, depth) => {\n increment();\n fs.realpath(rootPath, (error, realPath) => {\n if (error)\n return decrement();\n if (signal.aborted)\n return decrement();\n fs.stat(realPath, (error, stat) => {\n if (error)\n return decrement();\n if (signal.aborted)\n return decrement();\n const name = path.basename(realPath);\n const dirmap = map[rootPath] = { directories: [], directoriesNames: new Set(), directoriesNamesToPaths: {}, files: [], filesNames: new Set(), filesNamesToPaths: {}, symlinks: [], symlinksNames: new Set(), symlinksNamesToPaths: {} };\n handleStat(dirmap, realPath, name, stat, depth);\n decrement();\n });\n });\n };\n const populateResultFromRoot = async (rootPath, depth = 1) => {\n rootPath = path.normalize(rootPath);\n visited.add(rootPath);\n populateResultFromPath(rootPath, depth);\n await promise;\n if (signal.aborted)\n return resultEmpty;\n return result;\n };\n return populateResultFromRoot(rootPath);\n};\n/* EXPORT */\nexport default readdir;\n","/* IMPORT */\nimport { debounce } from 'dettle';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport sfs from 'stubborn-fs';\nimport readdir from 'tiny-readdir';\nimport { POLLING_TIMEOUT } from './constants.js';\n/* MAIN */\nconst Utils = {\n /* LANG API */\n lang: {\n debounce,\n attempt: (fn) => {\n try {\n return fn();\n }\n catch (error) {\n return Utils.lang.castError(error);\n }\n },\n castArray: (x) => {\n return Utils.lang.isArray(x) ? x : [x];\n },\n castError: (exception) => {\n if (Utils.lang.isError(exception))\n return exception;\n if (Utils.lang.isString(exception))\n return new Error(exception);\n return new Error('Unknown error');\n },\n defer: (callback) => {\n return setTimeout(callback, 0);\n },\n isArray: (value) => {\n return Array.isArray(value);\n },\n isError: (value) => {\n return value instanceof Error;\n },\n isFunction: (value) => {\n return typeof value === 'function';\n },\n isNaN: (value) => {\n return Number.isNaN(value);\n },\n isNumber: (value) => {\n return typeof value === 'number';\n },\n isPrimitive: (value) => {\n if (value === null)\n return true;\n const type = typeof value;\n return type !== 'object' && type !== 'function';\n },\n isShallowEqual: (x, y) => {\n if (x === y)\n return true;\n if (Utils.lang.isNaN(x))\n return Utils.lang.isNaN(y);\n if (Utils.lang.isPrimitive(x) || Utils.lang.isPrimitive(y))\n return x === y;\n for (const i in x)\n if (!(i in y))\n return false;\n for (const i in y)\n if (x[i] !== y[i])\n return false;\n return true;\n },\n isSet: (value) => {\n return value instanceof Set;\n },\n isString: (value) => {\n return typeof value === 'string';\n },\n isUndefined: (value) => {\n return value === undefined;\n },\n noop: () => {\n return;\n },\n uniq: (arr) => {\n if (arr.length < 2)\n return arr;\n return Array.from(new Set(arr));\n }\n },\n /* FS API */\n fs: {\n getDepth: (targetPath) => {\n return Math.max(0, targetPath.split(path.sep).length - 1);\n },\n getRealPath: (targetPath, native) => {\n try {\n return native ? fs.realpathSync.native(targetPath) : fs.realpathSync(targetPath);\n }\n catch {\n return;\n }\n },\n isSubPath: (targetPath, subPath) => {\n return (subPath.startsWith(targetPath) && subPath[targetPath.length] === path.sep && (subPath.length - targetPath.length) > path.sep.length);\n },\n poll: (targetPath, timeout = POLLING_TIMEOUT) => {\n return sfs.retry.stat(timeout)(targetPath, { bigint: true }).catch(Utils.lang.noop);\n },\n readdir: async (rootPath, ignore, depth = Infinity, limit = Infinity, signal, readdirMap) => {\n if (readdirMap && depth === 1 && rootPath in readdirMap) { // Reusing cached data\n const result = readdirMap[rootPath];\n return [result.directories, result.files];\n }\n else { // Retrieving fresh data\n const result = await readdir(rootPath, { depth, limit, ignore, signal });\n return [result.directories, result.files];\n }\n }\n }\n};\n/* EXPORT */\nexport default Utils;\n","/* IMPORT */\nimport path from 'node:path';\nimport { DEBOUNCE, DEPTH, LIMIT, HAS_NATIVE_RECURSION, IS_WINDOWS } from './constants.js';\nimport { FSTargetEvent, FSWatcherEvent, TargetEvent } from './enums.js';\nimport Utils from './utils.js';\n/* MAIN */\nclass WatcherHandler {\n /* CONSTRUCTOR */\n constructor(watcher, config, base) {\n this.base = base;\n this.watcher = watcher;\n this.handler = config.handler;\n this.fswatcher = config.watcher;\n this.options = config.options;\n this.folderPath = config.folderPath;\n this.filePath = config.filePath;\n this.handlerBatched = this.base ? this.base.onWatcherEvent.bind(this.base) : this._makeHandlerBatched(this.options.debounce); //UGLY\n }\n /* HELPERS */\n _isSubRoot(targetPath) {\n if (this.filePath) {\n return targetPath === this.filePath;\n }\n else {\n return targetPath === this.folderPath || Utils.fs.isSubPath(this.folderPath, targetPath);\n }\n }\n _makeHandlerBatched(delay = DEBOUNCE) {\n return (() => {\n let lock = this.watcher._readyWait; // ~Ensuring no two flushes are active in parallel, or before the watcher is ready\n let initials = [];\n let regulars = new Set();\n const flush = async (initials, regulars) => {\n const initialEvents = this.options.ignoreInitial ? [] : initials;\n const regularEvents = await this.eventsPopulate([...regulars]);\n const events = this.eventsDeduplicate([...initialEvents, ...regularEvents]);\n this.onTargetEvents(events);\n };\n const flushDebounced = Utils.lang.debounce(() => {\n if (this.watcher.isClosed())\n return;\n lock = flush(initials, regulars);\n initials = [];\n regulars = new Set();\n }, delay);\n return async (event, targetPath = '', isInitial = false) => {\n if (isInitial) { // Poll immediately\n await this.eventsPopulate([targetPath], initials, true);\n }\n else { // Poll later\n regulars.add(targetPath);\n }\n lock.then(flushDebounced);\n };\n })();\n }\n /* EVENT HELPERS */\n eventsDeduplicate(events) {\n if (events.length < 2)\n return events;\n const targetsEventPrev = {};\n return events.reduce((acc, event) => {\n const [targetEvent, targetPath] = event;\n const targetEventPrev = targetsEventPrev[targetPath];\n if (targetEvent === targetEventPrev)\n return acc; // Same event, ignoring\n if (targetEvent === TargetEvent.CHANGE && targetEventPrev === TargetEvent.ADD)\n return acc; // \"change\" after \"add\", ignoring\n targetsEventPrev[targetPath] = targetEvent;\n acc.push(event);\n return acc;\n }, []);\n }\n async eventsPopulate(targetPaths, events = [], isInitial = false) {\n await Promise.all(targetPaths.map(async (targetPath) => {\n const targetEvents = await this.watcher._poller.update(targetPath, this.options.pollingTimeout);\n await Promise.all(targetEvents.map(async (event) => {\n events.push([event, targetPath]);\n if (event === TargetEvent.ADD_DIR) {\n await this.eventsPopulateAddDir(targetPaths, targetPath, events, isInitial);\n }\n else if (event === TargetEvent.UNLINK_DIR) {\n await this.eventsPopulateUnlinkDir(targetPaths, targetPath, events, isInitial);\n }\n }));\n }));\n return events;\n }\n ;\n async eventsPopulateAddDir(targetPaths, targetPath, events = [], isInitial = false) {\n if (isInitial)\n return events;\n const depth = this.options.recursive ? this.options.depth ?? DEPTH : Math.min(1, this.options.depth ?? DEPTH);\n const limit = this.options.limit ?? LIMIT;\n const [directories, files] = await Utils.fs.readdir(targetPath, this.options.ignore, depth, limit, this.watcher._closeSignal);\n const dirSet = new Set(directories);\n const targetSubPaths = [...directories, ...files];\n await Promise.all(targetSubPaths.map(targetSubPath => {\n if (this.watcher.isIgnored(targetSubPath, this.options.ignore, dirSet.has(targetSubPath)))\n return;\n if (targetPaths.includes(targetSubPath))\n return;\n return this.eventsPopulate([targetSubPath], events, true);\n }));\n return events;\n }\n async eventsPopulateUnlinkDir(targetPaths, targetPath, events = [], isInitial = false) {\n if (isInitial)\n return events;\n for (const folderPathOther of this.watcher._poller.stats.keys()) {\n if (!Utils.fs.isSubPath(targetPath, folderPathOther))\n continue;\n if (targetPaths.includes(folderPathOther))\n continue;\n await this.eventsPopulate([folderPathOther], events, true);\n }\n return events;\n }\n /* EVENT HANDLERS */\n onTargetAdd(targetPath) {\n if (this._isSubRoot(targetPath)) {\n if (this.options.renameDetection) {\n this.watcher._locker.getLockTargetAdd(targetPath, this.options.renameTimeout);\n }\n else {\n this.watcher.event(TargetEvent.ADD, targetPath);\n }\n }\n }\n onTargetAddDir(targetPath) {\n if (targetPath !== this.folderPath && this.options.recursive && (!HAS_NATIVE_RECURSION && this.options.native !== false)) {\n this.watcher.watchDirectory(targetPath, this.options, this.handler, undefined, this.base || this);\n }\n if (this._isSubRoot(targetPath)) {\n if (this.options.renameDetection) {\n this.watcher._locker.getLockTargetAddDir(targetPath, this.options.renameTimeout);\n }\n else {\n this.watcher.event(TargetEvent.ADD_DIR, targetPath);\n }\n }\n }\n onTargetChange(targetPath) {\n if (this._isSubRoot(targetPath)) {\n this.watcher.event(TargetEvent.CHANGE, targetPath);\n }\n }\n onTargetUnlink(targetPath) {\n this.watcher.watchersClose(path.dirname(targetPath), targetPath, false);\n if (this._isSubRoot(targetPath)) {\n if (this.options.renameDetection) {\n this.watcher._locker.getLockTargetUnlink(targetPath, this.options.renameTimeout);\n }\n else {\n this.watcher.event(TargetEvent.UNLINK, targetPath);\n }\n }\n }\n onTargetUnlinkDir(targetPath) {\n this.watcher.watchersClose(path.dirname(targetPath), targetPath, false);\n this.watcher.watchersClose(targetPath);\n if (this._isSubRoot(targetPath)) {\n if (this.options.renameDetection) {\n this.watcher._locker.getLockTargetUnlinkDir(targetPath, this.options.renameTimeout);\n }\n else {\n this.watcher.event(TargetEvent.UNLINK_DIR, targetPath);\n }\n }\n }\n onTargetEvent(event) {\n const [targetEvent, targetPath] = event;\n if (targetEvent === TargetEvent.ADD) {\n this.onTargetAdd(targetPath);\n }\n else if (targetEvent === TargetEvent.ADD_DIR) {\n this.onTargetAddDir(targetPath);\n }\n else if (targetEvent === TargetEvent.CHANGE) {\n this.onTargetChange(targetPath);\n }\n else if (targetEvent === TargetEvent.UNLINK) {\n this.onTargetUnlink(targetPath);\n }\n else if (targetEvent === TargetEvent.UNLINK_DIR) {\n this.onTargetUnlinkDir(targetPath);\n }\n }\n onTargetEvents(events) {\n for (const event of events) {\n this.onTargetEvent(event);\n }\n }\n onWatcherEvent(event, targetPath, isInitial = false) {\n return this.handlerBatched(event, targetPath, isInitial);\n }\n onWatcherChange(event = FSTargetEvent.CHANGE, targetName) {\n if (this.watcher.isClosed())\n return;\n const targetPath = path.resolve(this.folderPath, targetName || '');\n if (this.filePath && targetPath !== this.folderPath && targetPath !== this.filePath)\n return;\n if (this.watcher.isIgnored(targetPath, this.options.ignore))\n return;\n this.onWatcherEvent(event, targetPath);\n }\n onWatcherError(error) {\n if (IS_WINDOWS && error.code === 'EPERM') { // This may happen when a folder is deleted\n this.onWatcherChange(FSTargetEvent.CHANGE, '');\n }\n else {\n this.watcher.error(error);\n }\n }\n /* API */\n async init() {\n await this.initWatcherEvents();\n await this.initInitialEvents();\n }\n async initWatcherEvents() {\n const onChange = this.onWatcherChange.bind(this);\n this.fswatcher.on(FSWatcherEvent.CHANGE, onChange);\n const onError = this.onWatcherError.bind(this);\n this.fswatcher.on(FSWatcherEvent.ERROR, onError);\n }\n async initInitialEvents() {\n const isInitial = !this.watcher.isReady(); // \"isInitial\" => is ignorable via the \"ignoreInitial\" option\n if (this.filePath) { // Single initial path\n if (this.watcher._poller.stats.has(this.filePath))\n return; // Already polled\n await this.onWatcherEvent(FSTargetEvent.CHANGE, this.filePath, isInitial);\n }\n else { // Multiple initial paths\n const depth = this.options.recursive && (HAS_NATIVE_RECURSION && this.options.native !== false) ? this.options.depth ?? DEPTH : Math.min(1, this.options.depth ?? DEPTH);\n const limit = this.options.limit ?? LIMIT;\n const [directories, files] = await Utils.fs.readdir(this.folderPath, this.options.ignore, depth, limit, this.watcher._closeSignal, this.options.readdirMap);\n const dirSet = new Set(directories);\n dirSet.add(this.folderPath);\n const targetPaths = [this.folderPath, ...directories, ...files];\n await Promise.all(targetPaths.map(targetPath => {\n if (this.watcher._poller.stats.has(targetPath))\n return; // Already polled\n if (this.watcher.isIgnored(targetPath, this.options.ignore, dirSet.has(targetPath)))\n return;\n return this.onWatcherEvent(FSTargetEvent.CHANGE, targetPath, isInitial);\n }));\n }\n }\n}\n/* EXPORT */\nexport default WatcherHandler;\n","/* MAIN */\n// Registering a single interval scales much better than registering N timeouts\n// Timeouts are respected within the interval margin\nconst WatcherLocksResolver = {\n /* VARIABLES */\n interval: 100,\n intervalId: undefined,\n fns: new Map(),\n /* LIFECYCLE API */\n init: () => {\n if (WatcherLocksResolver.intervalId)\n return;\n WatcherLocksResolver.intervalId = setInterval(WatcherLocksResolver.resolve, WatcherLocksResolver.interval);\n },\n reset: () => {\n if (!WatcherLocksResolver.intervalId)\n return;\n clearInterval(WatcherLocksResolver.intervalId);\n delete WatcherLocksResolver.intervalId;\n },\n /* API */\n add: (fn, timeout) => {\n WatcherLocksResolver.fns.set(fn, Date.now() + timeout);\n WatcherLocksResolver.init();\n },\n remove: (fn) => {\n WatcherLocksResolver.fns.delete(fn);\n },\n resolve: () => {\n if (!WatcherLocksResolver.fns.size)\n return WatcherLocksResolver.reset();\n const now = Date.now();\n for (const [fn, timestamp] of WatcherLocksResolver.fns) {\n if (timestamp >= now)\n continue; // We should still wait some more for this\n WatcherLocksResolver.remove(fn);\n fn();\n }\n }\n};\n/* EXPORT */\nexport default WatcherLocksResolver;\n","/* IMPORT */\nimport { RENAME_TIMEOUT } from './constants.js';\nimport { FileType, TargetEvent } from './enums.js';\nimport Utils from './utils.js';\nimport WatcherLocksResolver from './watcher_locks_resolver.js';\n/* MAIN */\n//TODO: Use a better name for this thing, maybe \"RenameDetector\"\nclass WatcherLocker {\n /* CONSTRUCTOR */\n constructor(watcher) {\n this._watcher = watcher;\n this.reset();\n }\n /* API */\n getLockAdd(config, timeout = RENAME_TIMEOUT) {\n const { ino, targetPath, events, locks } = config;\n const emit = () => {\n const otherPath = this._watcher._poller.paths.find(ino || -1, path => path !== targetPath); // Maybe this is actually a rename in a case-insensitive filesystem\n if (otherPath && otherPath !== targetPath) {\n if (Utils.fs.getRealPath(targetPath, true) === otherPath)\n return; //TODO: This seems a little too special-casey\n this._watcher.event(events.rename, otherPath, targetPath);\n }\n else {\n this._watcher.event(events.add, targetPath);\n }\n };\n if (!ino)\n return emit();\n const cleanup = () => {\n locks.add.delete(ino);\n WatcherLocksResolver.remove(free);\n };\n const free = () => {\n cleanup();\n emit();\n };\n WatcherLocksResolver.add(free, timeout);\n const resolve = () => {\n const unlink = locks.unlink.get(ino);\n if (!unlink)\n return; // No matching \"unlink\" lock found, skipping\n cleanup();\n const targetPathPrev = unlink();\n if (targetPath === targetPathPrev) {\n if (events.change) {\n if (this._watcher._poller.stats.has(targetPath)) {\n this._watcher.event(events.change, targetPath);\n }\n }\n }\n else {\n this._watcher.event(events.rename, targetPathPrev, targetPath);\n }\n };\n locks.add.set(ino, resolve);\n resolve();\n }\n getLockUnlink(config, timeout = RENAME_TIMEOUT) {\n const { ino, targetPath, events, locks } = config;\n const emit = () => {\n this._watcher.event(events.unlink, targetPath);\n };\n if (!ino)\n return emit();\n const cleanup = () => {\n locks.unlink.delete(ino);\n WatcherLocksResolver.remove(free);\n };\n const free = () => {\n cleanup();\n emit();\n };\n WatcherLocksResolver.add(free, timeout);\n const overridden = () => {\n cleanup();\n return targetPath;\n };\n locks.unlink.set(ino, overridden);\n locks.add.get(ino)?.();\n }\n getLockTargetAdd(targetPath, timeout) {\n const ino = this._watcher._poller.getIno(targetPath, TargetEvent.ADD, FileType.FILE);\n return this.getLockAdd({\n ino,\n targetPath,\n events: WatcherLocker.FILE_EVENTS,\n locks: this._locksFile\n }, timeout);\n }\n getLockTargetAddDir(targetPath, timeout) {\n const ino = this._watcher._poller.getIno(targetPath, TargetEvent.ADD_DIR, FileType.DIR);\n return this.getLockAdd({\n ino,\n targetPath,\n events: WatcherLocker.DIR_EVENTS,\n locks: this._locksDir\n }, timeout);\n }\n getLockTargetUnlink(targetPath, timeout) {\n const ino = this._watcher._poller.getIno(targetPath, TargetEvent.UNLINK, FileType.FILE);\n return this.getLockUnlink({\n ino,\n targetPath,\n events: WatcherLocker.FILE_EVENTS,\n locks: this._locksFile\n }, timeout);\n }\n getLockTargetUnlinkDir(targetPath, timeout) {\n const ino = this._watcher._poller.getIno(targetPath, TargetEvent.UNLINK_DIR, FileType.DIR);\n return this.getLockUnlink({\n ino,\n targetPath,\n events: WatcherLocker.DIR_EVENTS,\n locks: this._locksDir\n }, timeout);\n }\n reset() {\n this._locksAdd = new Map();\n this._locksAddDir = new Map();\n this._locksUnlink = new Map();\n this._locksUnlinkDir = new Map();\n this._locksDir = { add: this._locksAddDir, unlink: this._locksUnlinkDir };\n this._locksFile = { add: this._locksAdd, unlink: this._locksUnlink };\n }\n}\nWatcherLocker.DIR_EVENTS = {\n add: TargetEvent.ADD_DIR,\n rename: TargetEvent.RENAME_DIR,\n unlink: TargetEvent.UNLINK_DIR\n};\nWatcherLocker.FILE_EVENTS = {\n add: TargetEvent.ADD,\n change: TargetEvent.CHANGE,\n rename: TargetEvent.RENAME,\n unlink: TargetEvent.UNLINK\n};\n/* EXPORT */\nexport default WatcherLocker;\n","/* IMPORT */\nimport Utils from './utils.js';\n/* MAIN */\n//TODO: Maybe publish this as a standalone module\nclass LazyMapSet {\n constructor() {\n /* VARIABLES */\n this.map = new Map();\n }\n /* API */\n clear() {\n this.map.clear();\n }\n delete(key, value) {\n if (Utils.lang.isUndefined(value)) {\n return this.map.delete(key);\n }\n else if (this.map.has(key)) {\n const values = this.map.get(key);\n if (Utils.lang.isSet(values)) {\n const deleted = values.delete(value);\n if (!values.size) {\n this.map.delete(key);\n }\n return deleted;\n }\n else if (values === value) {\n this.map.delete(key);\n return true;\n }\n }\n return false;\n }\n find(key, iterator) {\n if (this.map.has(key)) {\n const values = this.map.get(key);\n if (Utils.lang.isSet(values)) {\n return Array.from(values).find(iterator);\n }\n else if (iterator(values)) { //TSC\n return values;\n }\n }\n return undefined;\n }\n get(key) {\n return this.map.get(key);\n }\n has(key, value) {\n if (Utils.lang.isUndefined(value)) {\n return this.map.has(key);\n }\n else if (this.map.has(key)) {\n const values = this.map.get(key);\n if (Utils.lang.isSet(values)) {\n return values.has(value);\n }\n else {\n return (values === value);\n }\n }\n return false;\n }\n set(key, value) {\n if (this.map.has(key)) {\n const values = this.map.get(key);\n if (Utils.lang.isSet(values)) {\n values.add(value);\n }\n else if (values !== value) {\n this.map.set(key, new Set([values, value])); //TSC\n }\n }\n else {\n this.map.set(key, value);\n }\n return this;\n }\n}\n/* EXPORT */\nexport default LazyMapSet;\n","/* IMPORT */\n/* MAIN */\n// An more memory-efficient representation of the useful subset of stats objects\nclass WatcherStats {\n /* CONSTRUCTOR */\n constructor(stats) {\n this.ino = (stats.ino <= Number.MAX_SAFE_INTEGER) ? Number(stats.ino) : stats.ino;\n this.size = Number(stats.size);\n this.atimeMs = Number(stats.atimeMs);\n this.mtimeMs = Number(stats.mtimeMs);\n this.ctimeMs = Number(stats.ctimeMs);\n this.birthtimeMs = Number(stats.birthtimeMs);\n this._isFile = stats.isFile();\n this._isDirectory = stats.isDirectory();\n this._isSymbolicLink = stats.isSymbolicLink();\n }\n /* API */\n isFile() {\n return this._isFile;\n }\n isDirectory() {\n return this._isDirectory;\n }\n isSymbolicLink() {\n return this._isSymbolicLink;\n }\n}\n/* EXPORT */\nexport default WatcherStats;\n","/* IMPORT */\nimport { FileType, TargetEvent } from './enums.js';\nimport LazyMapSet from './lazy_map_set.js';\nimport Utils from './utils.js';\nimport WatcherStats from './watcher_stats.js';\n/* MAIN */\nclass WatcherPoller {\n constructor() {\n /* VARIABLES */\n this.inos = {};\n this.paths = new LazyMapSet();\n this.stats = new Map();\n }\n /* API */\n getIno(targetPath, event, type) {\n const inos = this.inos[event];\n if (!inos)\n return;\n const ino = inos[targetPath];\n if (!ino)\n return;\n if (type && ino[1] !== type)\n return;\n return ino[0];\n }\n getStats(targetPath) {\n return this.stats.get(targetPath);\n }\n async poll(targetPath, timeout) {\n const stats = await Utils.fs.poll(targetPath, timeout);\n if (!stats)\n return;\n const isSupported = stats.isFile() || stats.isDirectory();\n if (!isSupported)\n return;\n return new WatcherStats(stats);\n }\n reset() {\n this.inos = {};\n this.paths = new LazyMapSet();\n this.stats = new Map();\n }\n async update(targetPath, timeout) {\n const prev = this.getStats(targetPath);\n const next = await this.poll(targetPath, timeout);\n this.updateStats(targetPath, next);\n if (!prev && next) {\n if (next.isFile()) {\n this.updateIno(targetPath, TargetEvent.ADD, next);\n return [TargetEvent.ADD];\n }\n if (next.isDirectory()) {\n this.updateIno(targetPath, TargetEvent.ADD_DIR, next);\n return [TargetEvent.ADD_DIR];\n }\n }\n else if (prev && !next) {\n if (prev.isFile()) {\n this.updateIno(targetPath, TargetEvent.UNLINK, prev);\n return [TargetEvent.UNLINK];\n }\n if (prev.isDirectory()) {\n this.updateIno(targetPath, TargetEvent.UNLINK_DIR, prev);\n return [TargetEvent.UNLINK_DIR];\n }\n }\n else if (prev && next) {\n if (prev.isFile()) {\n if (next.isFile()) {\n if (prev.ino === next.ino && !prev.size && !next.size)\n return []; // Same path, same content and same file, nothing actually changed\n this.updateIno(targetPath, TargetEvent.CHANGE, next);\n return [TargetEvent.CHANGE];\n }\n if (next.isDirectory()) {\n this.updateIno(targetPath, TargetEvent.UNLINK, prev);\n this.updateIno(targetPath, TargetEvent.ADD_DIR, next);\n return [TargetEvent.UNLINK, TargetEvent.ADD_DIR];\n }\n }\n else if (prev.isDirectory()) {\n if (next.isFile()) {\n this.updateIno(targetPath, TargetEvent.UNLINK_DIR, prev);\n this.updateIno(targetPath, TargetEvent.ADD, next);\n return [TargetEvent.UNLINK_DIR, TargetEvent.ADD];\n }\n if (next.isDirectory()) {\n if (prev.ino === next.ino)\n return []; // Same path and same directory, nothing actually changed\n this.updateIno(targetPath, TargetEvent.UNLINK_DIR, prev);\n this.updateIno(targetPath, TargetEvent.ADD_DIR, next);\n return [TargetEvent.UNLINK_DIR, TargetEvent.ADD_DIR];\n }\n }\n }\n return [];\n }\n updateIno(targetPath, event, stats) {\n const inos = this.inos[event] = this.inos[event] || (this.inos[event] = {});\n const type = stats.isFile() ? FileType.FILE : FileType.DIR;\n inos[targetPath] = [stats.ino, type];\n }\n updateStats(targetPath, stats) {\n if (stats) {\n this.paths.set(stats.ino, targetPath);\n this.stats.set(targetPath, stats);\n }\n else {\n const ino = this.stats.get(targetPath)?.ino || -1;\n this.paths.delete(ino, targetPath);\n this.stats.delete(targetPath);\n }\n }\n}\n/* EXPORT */\nexport default WatcherPoller;\n","/* IMPORT */\nimport { EventEmitter } from 'node:events';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { DEPTH, LIMIT, HAS_NATIVE_RECURSION, POLLING_INTERVAL } from './constants.js';\nimport { TargetEvent, WatcherEvent } from './enums.js';\nimport Utils from './utils.js';\nimport WatcherHandler from './watcher_handler.js';\nimport WatcherLocker from './watcher_locker.js';\nimport WatcherPoller from './watcher_poller.js';\n/* MAIN */\nclass Watcher extends EventEmitter {\n /* CONSTRUCTOR */\n constructor(target, options, handler) {\n super();\n this._closed = false;\n this._ready = false;\n this._closeAborter = new AbortController();\n this._closeSignal = this._closeAborter.signal;\n this.on(WatcherEvent.CLOSE, () => this._closeAborter.abort());\n this._closeWait = new Promise(resolve => this.on(WatcherEvent.CLOSE, resolve));\n this._readyWait = new Promise(resolve => this.on(WatcherEvent.READY, resolve));\n this._locker = new WatcherLocker(this);\n this._roots = new Set();\n this._poller = new WatcherPoller();\n this._pollers = new Set();\n this._subwatchers = new Set();\n this._watchers = {};\n this._watchersLock = Promise.resolve();\n this._watchersRestorable = {};\n this.watch(target, options, handler);\n }\n /* API */\n isClosed() {\n return this._closed;\n }\n isIgnored(targetPath, ignore, isDirectory) {\n return !!ignore && (Utils.lang.isFunction(ignore) ? !!ignore(targetPath, isDirectory) : ignore.test(targetPath));\n }\n isReady() {\n return this._ready;\n }\n close() {\n this._locker.reset();\n this._poller.reset();\n this._roots.clear();\n this.watchersClose();\n if (this.isClosed())\n return false;\n this._closed = true;\n return this.emit(WatcherEvent.CLOSE);\n }\n error(exception) {\n if (this.isClosed())\n return false;\n const error = Utils.lang.castError(exception);\n return this.emit(WatcherEvent.ERROR, error);\n }\n event(event, targetPath, targetPathNext) {\n if (this.isClosed())\n return false;\n this.emit(WatcherEvent.ALL, event, targetPath, targetPathNext);\n return this.emit(event, targetPath, targetPathNext);\n }\n ready() {\n if (this.isClosed() || this.isReady())\n return false;\n this._ready = true;\n return this.emit(WatcherEvent.READY);\n }\n pollerExists(targetPath, options) {\n for (const poller of this._pollers) {\n if (poller.targetPath !== targetPath)\n continue;\n if (!Utils.lang.isShallowEqual(poller.options, options))\n continue;\n return true;\n }\n return false;\n }\n subwatcherExists(targetPath, options) {\n for (const subwatcher of this._subwatchers) {\n if (subwatcher.targetPath !== targetPath)\n continue;\n if (!Utils.lang.isShallowEqual(subwatcher.options, options))\n continue;\n return true;\n }\n return false;\n }\n watchersClose(folderPath, filePath, recursive = true) {\n if (!folderPath) {\n for (const folderPath in this._watchers) {\n this.watchersClose(folderPath, filePath, false);\n }\n }\n else {\n const configs = this._watchers[folderPath];\n if (configs) {\n for (const config of [...configs]) { // It's important to clone the array, as items will be deleted from it also\n if (filePath && config.filePath !== filePath)\n continue;\n this.watcherClose(config);\n }\n }\n if (recursive) {\n for (const folderPathOther in this._watchers) {\n if (!Utils.fs.isSubPath(folderPath, folderPathOther))\n continue;\n this.watchersClose(folderPathOther, filePath, false);\n }\n }\n }\n }\n watchersLock(callback) {\n return this._watchersLock.then(() => {\n return this._watchersLock = new Promise(async (resolve) => {\n await callback();\n resolve();\n });\n });\n }\n watchersRestore() {\n delete this._watchersRestoreTimeout;\n const watchers = Object.entries(this._watchersRestorable);\n this._watchersRestorable = {};\n for (const [targetPath, config] of watchers) {\n this.watchPath(targetPath, config.options, config.handler);\n }\n }\n async watcherAdd(config, baseWatcherHandler) {\n const { folderPath } = config;\n const configs = this._watchers[folderPath] = (this._watchers[folderPath] || []);\n configs.push(config);\n const watcherHandler = new WatcherHandler(this, config, baseWatcherHandler);\n await watcherHandler.init();\n return watcherHandler;\n }\n watcherClose(config) {\n config.watcher.close();\n const configs = this._watchers[config.folderPath];\n if (configs) {\n const index = configs.indexOf(config);\n configs.splice(index, 1);\n if (!configs.length) {\n delete this._watchers[config.folderPath];\n }\n }\n const rootPath = config.filePath || config.folderPath;\n const isRoot = this._roots.has(rootPath);\n if (isRoot) {\n this._watchersRestorable[rootPath] = config;\n if (!this._watchersRestoreTimeout) {\n this._watchersRestoreTimeout = Utils.lang.defer(() => this.watchersRestore());\n }\n }\n }\n watcherExists(folderPath, options, handler, filePath) {\n const configsSibling = this._watchers[folderPath];\n if (!!configsSibling?.find(config => config.handler === handler && (!config.filePath || config.filePath === filePath) && config.options.ignore === options.ignore && !!config.options.native === !!options.native && (!options.recursive || config.options.recursive)))\n return true;\n let folderAncestorPath = path.dirname(folderPath);\n for (let depth = 1; depth < Infinity; depth++) {\n const configsAncestor = this._watchers[folderAncestorPath];\n if (!!configsAncestor?.find(config => (depth === 1 || (config.options.recursive && depth <= (config.options.depth ?? DEPTH))) && config.handler === handler && (!config.filePath || config.filePath === filePath) && config.options.ignore === options.ignore && !!config.options.native === !!options.native && (!options.recursive || (config.options.recursive && (HAS_NATIVE_RECURSION && config.options.native !== false)))))\n return true;\n if (!HAS_NATIVE_RECURSION)\n break; // No other ancestor will possibly be found\n const folderAncestorPathNext = path.dirname(folderPath);\n if (folderAncestorPath === folderAncestorPathNext)\n break;\n folderAncestorPath = folderAncestorPathNext;\n }\n return false;\n }\n async watchDirectories(foldersPaths, options, handler, filePath, baseWatcherHandler) {\n if (this.isClosed())\n return;\n foldersPaths = Utils.lang.uniq(foldersPaths).sort();\n let watcherHandlerLast;\n for (const folderPath of foldersPaths) {\n if (this.isIgnored(folderPath, options.ignore, true))\n continue;\n if (this.watcherExists(folderPath, options, handler, filePath))\n continue;\n try {\n const watcherOptions = (!options.recursive || (HAS_NATIVE_RECURSION && options.native !== false)) ? options : { ...options, recursive: false }; // Ensuring recursion is explicitly disabled if not available\n const watcher = fs.watch(folderPath, watcherOptions);\n const watcherConfig = { watcher, handler, options, folderPath, filePath };\n const watcherHandler = watcherHandlerLast = await this.watcherAdd(watcherConfig, baseWatcherHandler);\n const isRoot = this._roots.has(filePath || folderPath);\n if (isRoot) {\n const parentOptions = { ...options, ignoreInitial: true, recursive: false }; // Ensuring only the parent folder is being watched\n const parentFolderPath = path.dirname(folderPath);\n const parentFilePath = folderPath;\n await this.watchDirectories([parentFolderPath], parentOptions, handler, parentFilePath, watcherHandler);\n //TODO: Watch parents recursively with the following code, which requires other things to be changed too though\n // while ( true ) {\n // await this.watchDirectories ( [parentFolderPath], parentOptions, handler, parentFilePath, watcherHandler );\n // const parentFolderPathNext = path.dirname ( parentFolderPath );\n // if ( parentFolderPath === parentFolderPathNext ) break;\n // parentFilePath = parentFolderPath;\n // parentFolderPath = parentFolderPathNext;\n // }\n }\n }\n catch (error) {\n this.error(error);\n }\n }\n return watcherHandlerLast;\n }\n async watchDirectory(folderPath, options, handler, filePath, baseWatcherHandler) {\n if (this.isClosed())\n return;\n if (this.isIgnored(folderPath, options.ignore, true))\n return;\n if (!options.recursive || (HAS_NATIVE_RECURSION && options.native !== false)) {\n return this.watchersLock(() => {\n return this.watchDirectories([folderPath], options, handler, filePath, baseWatcherHandler);\n });\n }\n else {\n options = { ...options, recursive: true }; // Ensuring recursion is explicitly enabled\n const depth = options.depth ?? DEPTH;\n const limit = options.limit ?? LIMIT;\n const [folderSubPaths] = await Utils.fs.readdir(folderPath, options.ignore, depth, limit, this._closeSignal, options.readdirMap);\n return this.watchersLock(async () => {\n const watcherHandler = await this.watchDirectories([folderPath], options, handler, filePath, baseWatcherHandler);\n if (folderSubPaths.length) {\n const folderPathDepth = Utils.fs.getDepth(folderPath);\n for (const folderSubPath of folderSubPaths) {\n const folderSubPathDepth = Utils.fs.getDepth(folderSubPath);\n const subDepth = Math.max(0, depth - (folderSubPathDepth - folderPathDepth));\n const subOptions = { ...options, depth: subDepth }; // Updating the maximum depth to account for depth of the sub path\n await this.watchDirectories([folderSubPath], subOptions, handler, filePath, baseWatcherHandler || watcherHandler);\n }\n }\n });\n }\n }\n async watchFileOnce(filePath, options, callback) {\n if (this.isClosed())\n return;\n options = { ...options, ignoreInitial: false }; // Ensuring initial events are detected too\n if (this.subwatcherExists(filePath, options))\n return;\n const config = { targetPath: filePath, options };\n const handler = (event, targetPath) => {\n if (targetPath !== filePath)\n return;\n stop();\n callback();\n };\n const watcher = new Watcher(handler);\n const start = () => {\n this._subwatchers.add(config);\n this.on(WatcherEvent.CLOSE, stop); // Ensuring the subwatcher is stopped on close\n watcher.watchFile(filePath, options, handler);\n };\n const stop = () => {\n this._subwatchers.delete(config);\n this.removeListener(WatcherEvent.CLOSE, stop); // Ensuring there are no leftover listeners\n watcher.close();\n };\n return start();\n }\n async watchFile(filePath, options, handler) {\n if (this.isClosed())\n return;\n if (this.isIgnored(filePath, options.ignore, false))\n return;\n options = { ...options, recursive: false }; // Ensuring recursion is explicitly disabled\n const folderPath = path.dirname(filePath);\n return this.watchDirectory(folderPath, options, handler, filePath);\n }\n async watchPollingOnce(targetPath, options, callback) {\n if (this.isClosed())\n return;\n let isDone = false;\n const poller = new WatcherPoller();\n const disposer = await this.watchPolling(targetPath, options, async () => {\n if (isDone)\n return;\n const events = await poller.update(targetPath, options.pollingTimeout);\n if (!events.length)\n return; // Nothing actually changed, skipping\n if (isDone)\n return; // Another async callback has done the work already, skipping\n isDone = true;\n disposer();\n callback();\n });\n }\n async watchPolling(targetPath, options, callback) {\n if (this.isClosed())\n return Utils.lang.noop;\n if (this.pollerExists(targetPath, options))\n return Utils.lang.noop;\n const watcherOptions = { ...options, interval: options.pollingInterval ?? POLLING_INTERVAL }; // Ensuring a default interval is set\n const config = { targetPath, options };\n const start = () => {\n this._pollers.add(config);\n this.on(WatcherEvent.CLOSE, stop); // Ensuring polling is stopped on close\n fs.watchFile(targetPath, watcherOptions, callback);\n };\n const stop = () => {\n this._pollers.delete(config);\n this.removeListener(WatcherEvent.CLOSE, stop); // Ensuring there are no leftover listeners\n fs.unwatchFile(targetPath, callback);\n };\n Utils.lang.attempt(start);\n return () => Utils.lang.attempt(stop);\n }\n async watchUnknownChild(targetPath, options, handler) {\n if (this.isClosed())\n return;\n const watch = () => this.watchPath(targetPath, options, handler);\n return this.watchFileOnce(targetPath, options, watch);\n }\n async watchUnknownTarget(targetPath, options, handler) {\n if (this.isClosed())\n return;\n const watch = () => this.watchPath(targetPath, options, handler);\n return this.watchPollingOnce(targetPath, options, watch);\n }\n async watchPaths(targetPaths, options, handler) {\n if (this.isClosed())\n return;\n targetPaths = Utils.lang.uniq(targetPaths).sort();\n const isParallelizable = targetPaths.every((targetPath, index) => targetPaths.every((t, i) => i === index || !Utils.fs.isSubPath(targetPath, t))); // All paths are about separate subtrees, so we can start watching in parallel safely //TODO: Find parallelizable chunks rather than using an all or nothing approach\n if (isParallelizable) { // Watching in parallel\n await Promise.all(targetPaths.map(targetPath => {\n return this.watchPath(targetPath, options, handler);\n }));\n }\n else { // Watching serially\n for (const targetPath of targetPaths) {\n await this.watchPath(targetPath, options, handler);\n }\n }\n }\n async watchPath(targetPath, options, handler) {\n if (this.isClosed())\n return;\n targetPath = path.resolve(targetPath);\n if (this.isIgnored(targetPath, options.ignore))\n return;\n const stats = await Utils.fs.poll(targetPath, options.pollingTimeout);\n if (!stats) {\n const parentPath = path.dirname(targetPath);\n const parentStats = await Utils.fs.poll(parentPath, options.pollingTimeout);\n if (parentStats?.isDirectory()) {\n return this.watchUnknownChild(targetPath, options, handler);\n }\n else {\n return this.watchUnknownTarget(targetPath, options, handler);\n }\n }\n else if (stats.isFile()) {\n return this.watchFile(targetPath, options, handler);\n }\n else if (stats.isDirectory()) {\n return this.watchDirectory(targetPath, options, handler);\n }\n else {\n this.error(`\"${targetPath}\" is not supported`);\n }\n }\n async watch(target, options, handler = Utils.lang.noop) {\n if (Utils.lang.isFunction(target))\n return this.watch([], {}, target);\n if (Utils.lang.isUndefined(target))\n return this.watch([], options, handler);\n if (Utils.lang.isFunction(options))\n return this.watch(target, {}, options);\n if (Utils.lang.isUndefined(options))\n return this.watch(target, {}, handler);\n if (this.isClosed())\n return;\n if (this.isReady())\n options.readdirMap = undefined; // Only usable before initialization\n const targetPaths = Utils.lang.castArray(target);\n targetPaths.forEach(targetPath => this._roots.add(targetPath));\n await this.watchPaths(targetPaths, options, handler);\n if (this.isClosed())\n return;\n if (handler !== Utils.lang.noop) {\n this.on(WatcherEvent.ALL, handler);\n }\n options.readdirMap = undefined; // Only usable before initialization\n this.ready();\n }\n}\n/* EXPORT */\nexport default Watcher;\n","\"use strict\";var a=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var _=a(i=>{\"use strict\";Object.defineProperty(i,\"__esModule\",{value:!0});i.sync=i.isexe=void 0;var M=require(\"node:fs\"),x=require(\"node:fs/promises\"),q=async(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return d(await(0,x.stat)(t),e)}catch(s){let n=s;if(r||n.code===\"EACCES\")return!1;throw n}};i.isexe=q;var m=(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return d((0,M.statSync)(t),e)}catch(s){let n=s;if(r||n.code===\"EACCES\")return!1;throw n}};i.sync=m;var d=(t,e)=>t.isFile()&&A(t,e),A=(t,e)=>{let r=e.uid??process.getuid?.(),s=e.groups??process.getgroups?.()??[],n=e.gid??process.getgid?.()??s[0];if(r===void 0||n===void 0)throw new Error(\"cannot get uid or gid\");let u=new Set([n,...s]),c=t.mode,S=t.uid,P=t.gid,f=parseInt(\"100\",8),l=parseInt(\"010\",8),j=parseInt(\"001\",8),C=f|l;return!!(c&j||c&l&&u.has(P)||c&f&&S===r||c&C&&r===0)}});var g=a(o=>{\"use strict\";Object.defineProperty(o,\"__esModule\",{value:!0});o.sync=o.isexe=void 0;var T=require(\"node:fs\"),I=require(\"node:fs/promises\"),D=require(\"node:path\"),F=async(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return y(await(0,I.stat)(t),t,e)}catch(s){let n=s;if(r||n.code===\"EACCES\")return!1;throw n}};o.isexe=F;var L=(t,e={})=>{let{ignoreErrors:r=!1}=e;try{return y((0,T.statSync)(t),t,e)}catch(s){let n=s;if(r||n.code===\"EACCES\")return!1;throw n}};o.sync=L;var B=(t,e)=>{let{pathExt:r=process.env.PATHEXT||\"\"}=e,s=r.split(D.delimiter);if(s.indexOf(\"\")!==-1)return!0;for(let n of s){let u=n.toLowerCase(),c=t.substring(t.length-u.length).toLowerCase();if(u&&c===u)return!0}return!1},y=(t,e,r)=>t.isFile()&&B(e,r)});var p=a(h=>{\"use strict\";Object.defineProperty(h,\"__esModule\",{value:!0})});var v=exports&&exports.__createBinding||(Object.create?(function(t,e,r,s){s===void 0&&(s=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||(\"get\"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,s,n)}):(function(t,e,r,s){s===void 0&&(s=r),t[s]=e[r]})),G=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}):function(t,e){t.default=e}),w=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var s=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[s.length]=n);return s},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var s=t(e),n=0;n<s.length;n++)s[n]!==\"default\"&&v(r,e,s[n]);return G(r,e),r}})(),X=exports&&exports.__exportStar||function(t,e){for(var r in t)r!==\"default\"&&!Object.prototype.hasOwnProperty.call(e,r)&&v(e,t,r)};Object.defineProperty(exports,\"__esModule\",{value:!0});exports.sync=exports.isexe=exports.posix=exports.win32=void 0;var E=w(_());exports.posix=E;var O=w(g());exports.win32=O;X(p(),exports);var H=process.env._ISEXE_TEST_PLATFORM_||process.platform,b=H===\"win32\"?O:E;exports.isexe=b.isexe;exports.sync=b.sync;\n//# sourceMappingURL=index.min.js.map\n","const { isexe, sync: isexeSync } = require('isexe')\nconst { join, delimiter, sep, posix } = require('path')\n\nconst isWindows = process.platform === 'win32'\n\n// used to check for slashed in commands passed in. always checks for the posix\n// seperator on all platforms, and checks for the current separator when not on\n// a posix platform. don't use the isWindows check for this since that is mocked\n// in tests but we still need the code to actually work when called. that is also\n// why it is ignored from coverage.\n/* istanbul ignore next */\nconst rSlash = new RegExp(`[${posix.sep}${sep === posix.sep ? '' : sep}]`.replace(/(\\\\)/g, '\\\\$1'))\nconst rRel = new RegExp(`^\\\\.${rSlash.source}`)\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, {\n path: optPath = process.env.PATH,\n pathExt: optPathExt = process.env.PATHEXT,\n delimiter: optDelimiter = delimiter,\n}) => {\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(rSlash) ? [''] : [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(optPath || /* istanbul ignore next: very unusual */ '').split(optDelimiter),\n ]\n\n if (isWindows) {\n const pathExtExe = optPathExt ||\n ['.EXE', '.CMD', '.BAT', '.COM'].join(optDelimiter)\n const pathExt = pathExtExe.split(optDelimiter).flatMap((item) => [item, item.toLowerCase()])\n if (cmd.includes('.') && pathExt[0] !== '') {\n pathExt.unshift('')\n }\n return { pathEnv, pathExt, pathExtExe }\n }\n\n return { pathEnv, pathExt: [''] }\n}\n\nconst getPathPart = (raw, cmd) => {\n const pathPart = /^\".*\"$/.test(raw) ? raw.slice(1, -1) : raw\n const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : ''\n return prefix + join(pathPart, cmd)\n}\n\nconst which = async (cmd, opt = {}) => {\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (const envPart of pathEnv) {\n const p = getPathPart(envPart, cmd)\n\n for (const ext of pathExt) {\n const withExt = p + ext\n const is = await isexe(withExt, { pathExt: pathExtExe, ignoreErrors: true })\n if (is) {\n if (!opt.all) {\n return withExt\n }\n found.push(withExt)\n }\n }\n }\n\n if (opt.all && found.length) {\n return found\n }\n\n if (opt.nothrow) {\n return null\n }\n\n throw getNotFoundError(cmd)\n}\n\nconst whichSync = (cmd, opt = {}) => {\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (const pathEnvPart of pathEnv) {\n const p = getPathPart(pathEnvPart, cmd)\n\n for (const ext of pathExt) {\n const withExt = p + ext\n const is = isexeSync(withExt, { pathExt: pathExtExe, ignoreErrors: true })\n if (is) {\n if (!opt.all) {\n return withExt\n }\n found.push(withExt)\n }\n }\n }\n\n if (opt.all && found.length) {\n return found\n }\n\n if (opt.nothrow) {\n return null\n }\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","import { output } from \"./output.ts\";\nimport { sprintln, type SprintOptionsWithContent } from \"./sprint.ts\";\n\nexport type footer = {\n (str: string | SprintOptionsWithContent): void;\n (template: TemplateStringsArray, ...values: unknown[]): void;\n};\n\nexport const footer = ((optionsOrString: SprintOptionsWithContent | string | TemplateStringsArray, ...values: unknown[]): void => {\n const str = sprintln(optionsOrString as TemplateStringsArray, ...values);\n if (output.isInteractive) {\n output.updateFooter(str);\n } else {\n output.writeStdout(str);\n }\n}) as footer;\n","import type { Context } from \"../command/context.ts\";\n\nexport type NotifyOptions = {\n subtitle?: string;\n message: string;\n};\n\n/**\n * Alerts the user by writing a terminal bell character (BEL) to stderr.\n *\n * This triggers the terminal's native attention mechanism — dock bounce on\n * macOS, taskbar flash on Linux/Windows — without any platform-specific\n * code or external dependencies.\n */\nexport const notify = (ctx: Context, notification: NotifyOptions): void => {\n ctx.log.info(\"notifying user\", { subtitle: notification.subtitle, message: notification.message });\n process.stderr.write(\"\\x07\");\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport dayjs from \"dayjs\";\nimport ms from \"ms\";\nimport Watcher from \"watcher\";\nimport which from \"which\";\n\nimport type { EditSubscription } from \"../services/app/edit/edit.ts\";\nimport type { ENVIRONMENT_LOGS_SUBSCRIPTION } from \"../services/app/edit/operation.ts\";\nimport { defineCommand } from \"../services/command/command.ts\";\nimport { Changes } from \"../services/filesync/changes.ts\";\nimport { acquireDevLock, releaseDevLock } from \"../services/filesync/dev-lock.ts\";\nimport { YarnNotFoundError } from \"../services/filesync/error.ts\";\nimport { FileSync } from \"../services/filesync/filesync.ts\";\nimport { FileSyncStrategy, MergeConflictPreferenceArg, MergeConflictPreferenceValues } from \"../services/filesync/strategy.ts\";\nimport { SyncJson, SyncJsonFlags, loadSyncJsonDirectory } from \"../services/filesync/sync-json.ts\";\nimport { subscribeToEnvironmentLogs } from \"../services/logs/subscribeToEnvironmentLogs.ts\";\nimport { maybePromptAgentsMd, maybePromptGadgetSkills } from \"../services/output/agent-plugin.ts\";\nimport colors from \"../services/output/colors.ts\";\nimport { footer } from \"../services/output/footer.ts\";\nimport { LoggingFlags } from \"../services/output/log/structured.ts\";\nimport { notify } from \"../services/output/notify.ts\";\nimport { println } from \"../services/output/print.ts\";\nimport { reportErrorAndExit } from \"../services/output/report.ts\";\nimport { select } from \"../services/output/select.ts\";\nimport { spin } from \"../services/output/spinner.ts\";\nimport { sprint } from \"../services/output/sprint.ts\";\nimport { symbol } from \"../services/output/symbols.ts\";\nimport { unreachable } from \"../services/util/assert.ts\";\nimport { debounceAsync } from \"../services/util/function.ts\";\nimport { isAbortError } from \"../services/util/is.ts\";\nimport { delay } from \"../services/util/promise.ts\";\n\nexport default defineCommand({\n name: \"dev\",\n description: \"Sync files and stream logs locally\",\n details: sprint`\n Watches your local files and your Gadget environment for changes, syncing them\n bidirectionally in real time. This lets you develop with your preferred editor while\n keeping your environment up to date.\n\n On first run, or when files have diverged since the last sync, an initial reconciliation\n is performed. You must resolve any conflicts before continuous syncing begins.\n\n While running, application logs are streamed to the terminal unless --no-logs is passed.\n `,\n sections: [\n {\n title: \"Ignoring files\",\n content: sprint`\n Add a .ignore file (uses .gitignore syntax) to exclude files and folders from syncing.\n These paths are always excluded:\n\n • .DS_Store\n • .gadget\n • .git\n • .shopify\n • node_modules\n `,\n },\n {\n title: \"Limitations\",\n content: sprint`\n • Only syncs with development environments.\n • Only supports yarn v1 for installing dependencies.\n • Do not delete or move all files at once while syncing.\n `,\n },\n ],\n examples: [\n \"ggt dev\",\n \"ggt dev ~/gadget/my-app\",\n \"ggt dev --prefer local\",\n \"ggt dev ~/gadget/my-app --app my-app --env development --prefer local\",\n ],\n positionals: [\n {\n name: \"directory\",\n description: \"Directory to sync files to\",\n details: \"If the directory does not exist, it will be created. Defaults to the current working directory when omitted.\",\n },\n ],\n flags: {\n ...SyncJsonFlags,\n ...LoggingFlags,\n \"--prefer\": {\n type: MergeConflictPreferenceArg,\n description: \"Auto-resolve conflicts using the given source\",\n details:\n \"Use 'local' to keep your local file contents or 'environment' to keep the environment's version. Without this flag, you are prompted to choose for each conflict.\",\n valueName: \"source\",\n complete: async (_ctx, partial, _argv) => {\n const { filterByPrefix } = await import(\"../services/util/collection.ts\");\n return filterByPrefix([...MergeConflictPreferenceValues], partial);\n },\n },\n \"--file-push-delay\": {\n type: Number,\n default: ms(\"100ms\"),\n description: \"Delay in ms before pushing file changes\",\n details:\n \"Batches rapid file changes into a single push by waiting this long after the last change before sending. Increase if you see excessive network requests during bulk edits. Defaults to 100ms.\",\n valueName: \"ms\",\n brief: false,\n },\n \"--file-watch-debounce\": {\n type: Number,\n default: ms(\"300ms\"),\n description: \"Debounce in ms for file watch events\",\n details:\n \"How long the file watcher waits after the last filesystem event before emitting a change. Helps avoid duplicate events from editors that write files in multiple steps. Defaults to 300ms.\",\n valueName: \"ms\",\n brief: false,\n },\n \"--file-watch-poll-interval\": {\n type: Number,\n default: ms(\"3s\"),\n description: \"Interval in ms for polling file changes\",\n details:\n \"How often the file watcher polls for changes on filesystems that don't support native events (e.g. network drives). Defaults to 3s (3000ms).\",\n valueName: \"ms\",\n brief: false,\n },\n \"--file-watch-poll-timeout\": {\n type: Number,\n default: ms(\"20s\"),\n description: \"Timeout in ms for file watch polling\",\n details:\n \"How long to wait for a poll cycle to complete before timing out. Increase for very large directories where polling is slow. Defaults to 20s (20000ms).\",\n valueName: \"ms\",\n brief: false,\n },\n \"--file-watch-rename-timeout\": {\n type: Number,\n default: ms(\"1.25s\"),\n description: \"Timeout in ms for detecting file renames\",\n details:\n \"How long to wait for an add event to be followed by an unlink event (or vice versa) before treating them as separate operations instead of a rename. Defaults to 1.25s (1250ms).\",\n valueName: \"ms\",\n brief: false,\n },\n \"--no-logs\": {\n type: Boolean,\n description: \"Don't stream logs while syncing\",\n details:\n \"Useful when you only need file sync without log output, for example when running alongside a separate ggt logs session or in a background terminal.\",\n },\n },\n run: async (ctx, flags) => {\n if (!(await which(\"yarn\", { nothrow: true }))) {\n throw new YarnNotFoundError();\n }\n\n const directory = await loadSyncJsonDirectory(flags._[0] ?? process.cwd());\n const syncJson = await SyncJson.loadOrAskAndInit(ctx, { command: \"dev\", flags, directory });\n await acquireDevLock(directory);\n ctx.onAbort(async () => {\n await releaseDevLock(directory);\n });\n await maybePromptAgentsMd({ ctx, directory: syncJson.directory });\n await maybePromptGadgetSkills({ ctx, directory: syncJson.directory });\n footer({ ensureEmptyLineAbove: true, content: syncJson.sprint() });\n\n const filesync = new FileSync(syncJson);\n const hashes = await filesync.hashes(ctx);\n\n if (!hashes.inSync) {\n // our local files don't match our environment's files\n if (!syncJson.previousEnvironment || (hashes.localChangesToPush.size === 0 && hashes.onlyDotGadgetFilesChanged)) {\n // one of the following is true:\n // - we're developing on this environment for the first time\n // - we're developing on the same environment as last time\n // - we're developing on a different environment, but only .gadget/ files have changed\n // merge the changes (if any) and continue\n await filesync.merge(ctx, {\n hashes,\n printLocalChangesOptions: {\n limit: 5,\n },\n printEnvironmentChangesOptions: {\n limit: 5,\n },\n });\n } else {\n // we're switching environment's and files outside of .gadget/\n // have changed, so ask the user what to do\n await filesync.print(ctx, { hashes });\n const choices = Object.values(FileSyncStrategy);\n\n const strategy = await select({\n ensureEmptyLineAbove: true,\n choices: hashes.bothChanged ? choices : choices.filter((choice) => choice !== FileSyncStrategy.MERGE),\n content: colors.header(\"What do you want to do?\"),\n formatChoice: (choice) => {\n switch (choice) {\n case FileSyncStrategy.CANCEL:\n return sprint`Cancel (Ctrl+C)`;\n case FileSyncStrategy.MERGE:\n return sprint`Merge local and environment's changes`;\n case FileSyncStrategy.PUSH:\n switch (true) {\n case hashes.bothChanged:\n return sprint`Push local changes and ${colors.emphasis(\"discard environment's\")} changes`;\n case hashes.localChanges.size > 0:\n return sprint`Push local changes`;\n case hashes.environmentChanges.size > 0:\n return sprint`Discard environment's changes`;\n default:\n return unreachable(\"no changes to push or discard\");\n }\n case FileSyncStrategy.PULL:\n switch (true) {\n case hashes.bothChanged:\n return sprint`Pull environment's changes and ${colors.emphasis(\"discard local\")} changes`;\n case hashes.localChanges.size > 0:\n return sprint`Discard local changes`;\n case hashes.environmentChanges.size > 0:\n return sprint`Pull environment's changes`;\n default:\n return unreachable(\"no changes to pull or discard\");\n }\n }\n },\n });\n\n switch (strategy) {\n case FileSyncStrategy.CANCEL:\n process.exit(0);\n break;\n case FileSyncStrategy.MERGE:\n await filesync.merge(ctx, { hashes });\n break;\n case FileSyncStrategy.PUSH:\n await filesync.push(ctx, { command: \"dev\", hashes });\n break;\n case FileSyncStrategy.PULL:\n await filesync.pull(ctx, { hashes, force: true });\n break;\n }\n }\n }\n\n /**\n * A list of filepaths that have changed because we (this ggt process)\n * modified them. This is used to avoid reacting to filesystem events\n * that we caused, which would cause an infinite loop.\n */\n const recentWritesToLocalFilesystem = new Map<string, number>();\n\n const clearRecentWritesInterval = setInterval(() => {\n for (const [path, timestamp] of recentWritesToLocalFilesystem) {\n if (dayjs().isAfter(timestamp + ms(\"5s\"))) {\n // this change should have been seen by now\n recentWritesToLocalFilesystem.delete(path);\n }\n }\n }, ms(\"1s\")).unref();\n\n /**\n * Subscribe to file changes on Gadget and apply them to the local\n * filesystem.\n */\n const filesyncSubscription = filesync.subscribeToEnvironmentChanges(ctx, {\n onError: (error) => ctx.abort(error),\n beforeChanges: ({ changed, deleted }) => {\n // add all the files and directories we're about to touch to\n // recentWritesToLocalFilesystem so that we don't send them back\n // to Gadget\n for (const filepath of [...changed, ...deleted]) {\n recentWritesToLocalFilesystem.set(filepath, Date.now());\n\n let dir = path.dirname(filepath);\n while (dir !== \".\") {\n recentWritesToLocalFilesystem.set(dir + \"/\", Date.now());\n dir = path.dirname(dir);\n }\n }\n },\n });\n\n let logsSubscription: EditSubscription<ENVIRONMENT_LOGS_SUBSCRIPTION> | undefined;\n\n if (!flags[\"--no-logs\"]) {\n logsSubscription = subscribeToEnvironmentLogs(syncJson.edit, flags, {\n onError: (error) => {\n ctx.abort(error);\n },\n });\n }\n\n /**\n * A buffer of local file changes to send to Gadget.\n */\n const localChangesBuffer = new Changes();\n\n /**\n * A debounced function that sends the local file changes to Gadget.\n */\n const mergeChangesWithEnvironment = debounceAsync(flags[\"--file-push-delay\"], async (): Promise<void> => {\n try {\n const lastGitBranch = syncJson.gitBranch;\n await syncJson.loadGitBranch();\n\n if (lastGitBranch !== syncJson.gitBranch) {\n println({\n ensureEmptyLineAbove: true,\n content: sprint`\n Your git branch changed.\n\n ${lastGitBranch} → ${syncJson.gitBranch}\n `,\n });\n\n // we need all the changes to be sent in a single batch, so wait\n // a bit in case there are changes the watcher hasn't seen yet\n const spinner = spin({ ensureEmptyLineAbove: true, content: \"Waiting for file changes to settle.\" });\n await delay(\"3s\"); // this time was chosen arbitrarily\n spinner.succeed();\n }\n\n const changes = new Changes(localChangesBuffer.entries());\n localChangesBuffer.clear();\n\n await filesync.mergeChangesWithEnvironment(ctx, { changes });\n } catch (error) {\n ctx.log.error(\"error sending changes to gadget\", { error });\n ctx.abort(error);\n }\n });\n\n ctx.log.debug(\"watching\", { path: syncJson.directory.path });\n\n /**\n * Watches the local filesystem for changes.\n */\n const fileWatcher = new Watcher(\n syncJson.directory.path,\n {\n // don't emit an event for every watched file when we start watching\n ignoreInitial: true,\n // watch everything\n recursive: true,\n // don't emit changes to .gadget/ files because they're readonly (Gadget manages them)\n ignore: (filePath: string, isDirectory?: boolean) => {\n const relative = syncJson.directory.relative(filePath);\n if (relative.startsWith(\".gadget\")) return true;\n if (isDirectory === undefined) {\n try {\n isDirectory = fs.statSync(filePath).isDirectory();\n } catch {\n isDirectory = false;\n }\n }\n return syncJson.directory.ignores(filePath, isDirectory);\n },\n // emit rename/renameDir events\n renameDetection: true,\n // how long to wait for an add event to be followed by an unlink\n // event, and vice versa (i.e. a rename event)\n renameTimeout: flags[\"--file-watch-rename-timeout\"],\n // how long to wait before emitting a change event (helps avoid duplicate events)\n debounce: flags[\"--file-watch-debounce\"],\n },\n (event: string, absolutePath: string, renamedPath: string) => {\n const filepath = event === \"rename\" || event === \"renameDir\" ? renamedPath : absolutePath;\n const isDirectory = event === \"renameDir\" || event === \"addDir\" || event === \"unlinkDir\";\n const normalizedPath = syncJson.directory.normalize(filepath, isDirectory);\n\n ctx.log.trace(\"file event\", { event, isDirectory, path: normalizedPath });\n\n if (recentWritesToLocalFilesystem.delete(normalizedPath)) {\n ctx.log.trace(\"ignoring event because we caused it\", { event, path: normalizedPath });\n return;\n }\n\n if (filepath === syncJson.directory.absolute(\".ignore\")) {\n if (!syncJson.directory.ignoreFileLoadedWithin(ms(\"2s\"))) {\n syncJson.directory.loadIgnoreFile().catch((error: unknown) => ctx.abort(error));\n }\n } else if (syncJson.directory.ignores(filepath, isDirectory)) {\n return;\n }\n\n switch (event) {\n case \"add\":\n case \"addDir\":\n localChangesBuffer.set(normalizedPath, { type: \"create\" });\n break;\n case \"rename\":\n case \"renameDir\": {\n const oldNormalizedPath = syncJson.directory.normalize(absolutePath, isDirectory);\n localChangesBuffer.set(normalizedPath, { type: \"create\", oldPath: oldNormalizedPath });\n break;\n }\n case \"change\": {\n localChangesBuffer.set(normalizedPath, { type: \"update\" });\n break;\n }\n case \"unlink\":\n case \"unlinkDir\": {\n localChangesBuffer.set(normalizedPath, { type: \"delete\" });\n break;\n }\n }\n\n mergeChangesWithEnvironment();\n },\n ).once(\"error\", (error) => ctx.abort(error));\n\n ctx.onAbort(async (reason) => {\n ctx.log.info(\"stopping\", { reason });\n\n logsSubscription?.unsubscribe();\n filesyncSubscription.unsubscribe();\n fileWatcher.close();\n clearInterval(clearRecentWritesInterval);\n await mergeChangesWithEnvironment.flush();\n\n try {\n await filesync.idle();\n } catch (error) {\n ctx.log.error(\"error while waiting for idle\", { error });\n }\n\n if (isAbortError(reason)) {\n return;\n }\n\n notify(ctx, { subtitle: \"Uh oh!\", message: \"An error occurred while syncing files\" });\n await reportErrorAndExit(ctx, reason);\n });\n\n footer({\n ensureEmptyLineAbove: true,\n content: sprint`\n ${syncJson.sprint()}\n\n Waiting for file changes${symbol.ellipsis} ${colors.hint(\"Press Ctrl+C to stop\")}\n `,\n });\n },\n});\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],"mappings":"6iCAMA,MAAA,EAAA,GAAA,UAAA,CAEA,GAAA,IAAA,SACA,EAAA,IAAA,QACA,EAAA,IAAA,EAGA,GAAA,KCZA,IAAI,GACH,SAAU,EAAU,CACjB,EAAS,EAAS,IAAS,GAAK,MAChC,EAAS,EAAS,KAAU,GAAK,SAClC,AAAa,IAAW,EAAE,CAAE,CAC/B,IAAI,GACH,SAAU,EAAe,CACtB,EAAc,OAAY,SAC1B,EAAc,OAAY,WAC3B,AAAkB,IAAgB,EAAE,CAAE,CACzC,IAAI,GACH,SAAU,EAAgB,CACvB,EAAe,OAAY,SAC3B,EAAe,MAAW,UAC3B,AAAmB,IAAiB,EAAE,CAAE,CAC3C,IAAI,GACH,SAAU,EAAa,CACpB,EAAY,IAAS,MACrB,EAAY,QAAa,SACzB,EAAY,OAAY,SACxB,EAAY,OAAY,SACxB,EAAY,WAAgB,YAC5B,EAAY,OAAY,SACxB,EAAY,WAAgB,cAC7B,AAAgB,IAAc,EAAE,CAAE,CACrC,IAAI,GACH,SAAU,EAAc,CACrB,EAAa,IAAS,MACtB,EAAa,MAAW,QACxB,EAAa,MAAW,QACxB,EAAa,MAAW,UACzB,AAAiB,IAAe,EAAE,CAAE,CC9BvC,MAAM,IAAY,EAAI,EAAO,EAAG,IAAY,CAExC,EAAO,KAAK,IAAI,EAAG,EAAK,CACxB,IAAM,EAAU,GAAS,SAAW,GAC9B,EAAW,GAAS,UAAY,GACh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AK,SACL,IAAK,YAAa,CAChB,IAAM,EAAoB,EAAS,UAAU,UAAU,EAAc,EAAY,CACjF,EAAmB,IAAI,EAAgB,CAAE,KAAM,SAAU,QAAS,EAAmB,CAAC,CACtF,MAEF,IAAK,SACH,EAAmB,IAAI,EAAgB,CAAE,KAAM,SAAU,CAAC,CAC1D,MAEF,IAAK,SACL,IAAK,YACH,EAAmB,IAAI,EAAgB,CAAE,KAAM,SAAU,CAAC,CAC1D,MAIJ,GAA6B,EAEhC,CAAC,KAAK,QAAU,GAAU,EAAI,MAAM,EAAM,CAAC,CAE5C,EAAI,QAAQ,KAAO,IAAW,CAC5B,EAAI,IAAI,KAAK,WAAY,CAAE,SAAQ,CAAC,CAEpC,GAAkB,aAAa,CAC/B,EAAqB,aAAa,CAClC,GAAY,OAAO,CACnB,cAAc,EAA0B,CACxC,MAAM,EAA4B,OAAO,CAEzC,GAAI,CACF,MAAM,EAAS,MAAM,OACd,EAAO,CACd,EAAI,IAAI,MAAM,+BAAgC,CAAE,QAAO,CAAC,CAGtD,EAAa,EAAO,GAIxB,GAAO,EAAK,CAAE,SAAU,SAAU,QAAS,wCAAyC,CAAC,CACrF,MAAM,EAAmB,EAAK,EAAO,GACrC,CAEF,GAAO,CACL,qBAAsB,GACtB,QAAS,CAAM;UACX,EAAS,QAAQ,CAAC;;kCAEM,EAAO,SAAS,GAAGA,EAAO,KAAK,uBAAuB,CAAC;QAEpF,CAAC,EAEL,CAAC"}
@@ -0,0 +1,10 @@
1
+ import{o as e}from"./chunk-BjEoQXZ0.js";import{U as t,W as n}from"./http-CY3lPMkt.js";import{At as r,E as i,Mt as a,V as o,kt as s}from"./command-2iNTc5dV.js";var c=e(o(),1);const l=r({pid:s(),startedAt:a()});var u=class extends t{isBug=n.NO;details;constructor(e){super(`Another ggt dev process is already running (PID ${e.pid})`),this.details=e}render(){return i`
2
+ Another "ggt dev" process is already running in this directory:
3
+
4
+ ${this.details.directory}
5
+
6
+ The existing process has PID ${String(this.details.pid)}.
7
+
8
+ Stop the other process first, or use a different directory.
9
+ `}};const d=e=>e.absolute(`.gadget/dev-lock.json`),f=e=>{try{return process.kill(e,0),!0}catch{return!1}},p=async e=>{try{let t=await c.default.readJSON(d(e)),n=l.safeParse(t);return n.success?n.data:void 0}catch{return}},m=async e=>{let t=d(e),n={pid:process.pid,startedAt:new Date().toISOString()},r=JSON.stringify(n,null,2);await c.default.ensureDir(e.absolute(`.gadget`));try{await c.default.writeFile(t,r,{flag:`wx`})}catch(n){if(n.code!==`EEXIST`)throw n;let i=await p(e);if(i&&f(i.pid))throw new u({pid:i.pid,directory:e.path});await c.default.remove(t),await c.default.writeFile(t,r,{flag:`wx`})}},h=async e=>{try{await c.default.remove(d(e))}catch{}},g=async e=>{let t=await p(e);return t?f(t.pid)?{running:!0,pid:t.pid,startedAt:t.startedAt}:(await h(e),{running:!1}):{running:!1}};export{g as n,h as r,m as t};
10
+ //# sourceMappingURL=dev-lock-BFanZSu1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-lock-BFanZSu1.js","names":["z.object","z.number","z.string","fs"],"sources":["../src/services/filesync/dev-lock.ts"],"sourcesContent":["import fs from \"fs-extra\";\nimport { z } from \"zod\";\n\nimport { GGTError, IsBug } from \"../output/report.ts\";\nimport { sprint } from \"../output/sprint.ts\";\nimport type { Directory } from \"./directory.ts\";\n\n/**\n * The data stored in the dev lock file.\n */\nexport const DevLockData = z.object({\n pid: z.number(),\n startedAt: z.string(),\n});\n\nexport type DevLockData = z.infer<typeof DevLockData>;\n\n/**\n * Error thrown when another `ggt dev` process is already running in the same directory.\n */\nexport class DevAlreadyRunningError extends GGTError {\n isBug = IsBug.NO;\n\n readonly details: { pid: number; directory: string };\n\n constructor(details: { pid: number; directory: string }) {\n super(`Another ggt dev process is already running (PID ${details.pid})`);\n this.details = details;\n }\n\n protected render(): string {\n return sprint`\n Another \"ggt dev\" process is already running in this directory:\n\n ${this.details.directory}\n\n The existing process has PID ${String(this.details.pid)}.\n\n Stop the other process first, or use a different directory.\n `;\n }\n}\n\n/**\n * Returns the path to the dev lock file for the given directory.\n */\nexport const devLockPath = (directory: Directory): string => {\n return directory.absolute(\".gadget/dev-lock.json\");\n};\n\n/**\n * Checks whether a process with the given PID is alive.\n */\nexport const isProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n};\n\n/**\n * Reads and parses the dev lock file. Returns undefined if missing or malformed.\n */\nexport const readDevLock = async (directory: Directory): Promise<DevLockData | undefined> => {\n try {\n const data: unknown = await fs.readJSON(devLockPath(directory));\n const result = DevLockData.safeParse(data);\n return result.success ? result.data : undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Atomically acquires the dev lock for the given directory.\n *\n * Uses `wx` flag for exclusive creation to prevent race conditions.\n * If a stale lock (dead PID) is found, it is removed and re-acquired.\n *\n * @throws {DevAlreadyRunningError} if another live process holds the lock.\n */\nexport const acquireDevLock = async (directory: Directory): Promise<void> => {\n const lockPath = devLockPath(directory);\n const lockData: DevLockData = {\n pid: process.pid,\n startedAt: new Date().toISOString(),\n };\n const content = JSON.stringify(lockData, null, 2);\n\n await fs.ensureDir(directory.absolute(\".gadget\"));\n\n try {\n await fs.writeFile(lockPath, content, { flag: \"wx\" });\n } catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw error;\n }\n\n // Lock file already exists - check if the holding process is still alive\n const existing = await readDevLock(directory);\n if (existing && isProcessAlive(existing.pid)) {\n throw new DevAlreadyRunningError({ pid: existing.pid, directory: directory.path });\n }\n\n // Stale or malformed lock - remove and retry\n await fs.remove(lockPath);\n await fs.writeFile(lockPath, content, { flag: \"wx\" });\n }\n};\n\n/**\n * Releases the dev lock for the given directory. Ignores errors.\n */\nexport const releaseDevLock = async (directory: Directory): Promise<void> => {\n try {\n await fs.remove(devLockPath(directory));\n } catch {\n // ignore errors during cleanup\n }\n};\n\n/**\n * Returns the current dev status for the given directory.\n * Cleans up stale locks as a side effect.\n */\nexport const getDevStatus = async (\n directory: Directory,\n): Promise<{ running: false } | { running: true; pid: number; startedAt: string }> => {\n const lock = await readDevLock(directory);\n if (!lock) {\n return { running: false };\n }\n\n if (!isProcessAlive(lock.pid)) {\n // Stale lock - clean it up\n await releaseDevLock(directory);\n return { running: false };\n }\n\n return { running: true, pid: lock.pid, startedAt: lock.startedAt };\n};\n"],"mappings":"8KAUA,MAAa,EAAcA,EAAS,CAClC,IAAKC,GAAU,CACf,UAAWC,GAAU,CACtB,CAAC,CAOF,IAAa,EAAb,cAA4C,CAAS,CACnD,MAAQ,EAAM,GAEd,QAEA,YAAY,EAA6C,CACvD,MAAM,mDAAmD,EAAQ,IAAI,GAAG,CACxE,KAAK,QAAU,EAGjB,QAA2B,CACzB,MAAO,EAAM;;;UAGP,KAAK,QAAQ,UAAU;;qCAEI,OAAO,KAAK,QAAQ,IAAI,CAAC;;;QAU9D,MAAa,EAAe,GACnB,EAAU,SAAS,wBAAwB,CAMvC,EAAkB,GAAyB,CACtD,GAAI,CAEF,OADA,QAAQ,KAAK,EAAK,EAAE,CACb,QACD,CACN,MAAO,KAOE,EAAc,KAAO,IAA2D,CAC3F,GAAI,CACF,IAAM,EAAgB,MAAMC,EAAAA,QAAG,SAAS,EAAY,EAAU,CAAC,CACzD,EAAS,EAAY,UAAU,EAAK,CAC1C,OAAO,EAAO,QAAU,EAAO,KAAO,IAAA,QAChC,CACN,SAYS,EAAiB,KAAO,IAAwC,CAC3E,IAAM,EAAW,EAAY,EAAU,CACjC,EAAwB,CAC5B,IAAK,QAAQ,IACb,UAAW,IAAI,MAAM,CAAC,aAAa,CACpC,CACK,EAAU,KAAK,UAAU,EAAU,KAAM,EAAE,CAEjD,MAAMA,EAAAA,QAAG,UAAU,EAAU,SAAS,UAAU,CAAC,CAEjD,GAAI,CACF,MAAMA,EAAAA,QAAG,UAAU,EAAU,EAAS,CAAE,KAAM,KAAM,CAAC,OAC9C,EAAgB,CACvB,GAAK,EAAgC,OAAS,SAC5C,MAAM,EAIR,IAAM,EAAW,MAAM,EAAY,EAAU,CAC7C,GAAI,GAAY,EAAe,EAAS,IAAI,CAC1C,MAAM,IAAI,EAAuB,CAAE,IAAK,EAAS,IAAK,UAAW,EAAU,KAAM,CAAC,CAIpF,MAAMA,EAAAA,QAAG,OAAO,EAAS,CACzB,MAAMA,EAAAA,QAAG,UAAU,EAAU,EAAS,CAAE,KAAM,KAAM,CAAC,GAO5C,EAAiB,KAAO,IAAwC,CAC3E,GAAI,CACF,MAAMA,EAAAA,QAAG,OAAO,EAAY,EAAU,CAAC,MACjC,IASG,EAAe,KAC1B,IACoF,CACpF,IAAM,EAAO,MAAM,EAAY,EAAU,CAWzC,OAVK,EAIA,EAAe,EAAK,IAAI,CAMtB,CAAE,QAAS,GAAM,IAAK,EAAK,IAAK,UAAW,EAAK,UAAW,EAJhE,MAAM,EAAe,EAAU,CACxB,CAAE,QAAS,GAAO,EANlB,CAAE,QAAS,GAAO"}
@@ -0,0 +1,9 @@
1
+ import{o as e,t}from"./chunk-BjEoQXZ0.js";import{V as n}from"./command-2iNTc5dV.js";import r from"node:path";import{Transform as i}from"node:stream";import{createHash as a}from"node:crypto";import{pipeline as o}from"node:stream/promises";import s from"node:assert";var c=t(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.{0,2}\/|^\.{1,2}$/,l=/\/$/,u=`node-ignore`;typeof Symbol<`u`&&(u=Symbol.for(`node-ignore`));let d=u,f=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),p=/([0-z])-([0-z])/g,m=()=>!1,h=e=>e.replace(p,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),g=e=>{let{length:t}=e;return e.slice(0,t-t%2)},_=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${g(r)}${i}`:i===`]`&&r.length%2==0?`[${h(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],v=/(^|\\\/)?\\\*$/,y=`regex`,b=`checkRegex`,x={[y](e,t){return`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`},[b](e,t){return`${t?`${t}[^/]*`:`[^/]*`}(?=$|\\/$)`}},S=e=>_.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),C=e=>typeof e==`string`,w=e=>e&&C(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(s).filter(Boolean);var E=class{constructor(e,t,n,r,i,a){this.pattern=e,this.mark=t,this.negative=i,f(this,`body`,n),f(this,`ignoreCase`,r),f(this,`regexPrefix`,a)}get regex(){let e=`_`+y;return this[e]?this[e]:this._make(y,e)}get checkRegex(){let e=`_`+b;return this[e]?this[e]:this._make(b,e)}_make(e,t){let n=this.regexPrefix.replace(v,x[e]),r=this.ignoreCase?new RegExp(n,`i`):new RegExp(n);return f(this,t,r)}};let D=({pattern:e,mark:t},n)=>{let r=!1,i=e;i.indexOf(`!`)===0&&(r=!0,i=i.substr(1)),i=i.replace(a,`!`).replace(o,`#`);let s=S(i);return new E(e,t,i,n,r,s)};var O=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[d]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(C(e)&&(e={pattern:e}),w(e.pattern)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._add,this),this._added}test(e,t,n){let r=!1,i=!1,a;this._rules.forEach(o=>{let{negative:s}=o;i===s&&r!==i||s&&!r&&!i&&!t||o[n].test(e)&&(r=!s,i=s,a=s?void 0:o)});let o={ignored:r,unignored:i};return a&&(o.rule=a),o}};let k=(e,t)=>{throw new t(e)},A=(e,t,n)=>C(e)?e?A.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),j=e=>c.test(e);A.isNotRelative=j,A.convert=e=>e;var M=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){f(this,d,!0),this._rules=new O(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,r){let i=e&&A.convert(e);return A(i,e,this._strictPathCheck?k:m),this._t(i,t,n,r)}checkIgnore(e){if(!l.test(e))return this.test(e);let t=e.split(`/`).filter(Boolean);if(t.pop(),t.length){let e=this._t(t.join(`/`)+`/`,this._testCache,!0,t);if(e.ignored)return e}return this._rules.test(e,!1,b)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`).filter(Boolean),r.pop(),!r.length)return t[e]=this._rules.test(e,n,y);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._rules.test(e,n,y)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let N=e=>new M(e),P=e=>A(e&&A.convert(e),e,m),F=()=>{A.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;A.isNotRelative=t=>e.test(t)||j(t)};typeof process<`u`&&process.platform===`win32`&&F(),t.exports=N,N.default=N,t.exports.isPathValid=P,f(t.exports,Symbol.for(`setupWindows`),F)})),l=t(((e,t)=>{
2
+ /*!
3
+ * normalize-path <https://github.com/jonschlinkert/normalize-path>
4
+ *
5
+ * Copyright (c) 2014-2018, Jon Schlinkert.
6
+ * Released under the MIT License.
7
+ */
8
+ t.exports=function(e,t){if(typeof e!=`string`)throw TypeError(`expected path to be a string`);if(e===`\\`||e===`/`)return`/`;var n=e.length;if(n<=1)return e;var r=``;if(n>4&&e[3]===`\\`){var i=e[2];(i===`?`||i===`.`)&&e.slice(0,2)===`\\\\`&&(e=e.slice(2),r=`//`)}var a=e.split(/[/\\]+/);return t!==!1&&a[a.length-1]===``&&a.pop(),r+a.join(`/`)}})),u=e(n(),1),d=e(c(),1),f=e(l(),1);const p=[`.gadget/`],m=[`.DS_Store`,`node_modules`,`.git`,`.shopify`],h=[`.gadget/sync.json`,`.gadget/dev-lock.json`,`.gadget/backup`,`yarn-error.log`];var g=class e{_ignorer;_isHashing=!1;_lastIgnoreFileLoadTime=0;path;constructor(e){this.path=e}static async init(t){let n=new e(t);return await n.loadIgnoreFile(),n._lastIgnoreFileLoadTime=0,n}relative(e){return r.isAbsolute(e)?r.relative(this.path,e):e}absolute(...e){let t=r.resolve(this.path,...e);return s(t.startsWith(this.path),`expected ${t} to be within ${this.path}`),t}normalize(e,t){return r.isAbsolute(e)&&(e=this.relative(e)),e=(0,f.default)(e,!0),t&&(e+=`/`),e}async loadIgnoreFile(){this._lastIgnoreFileLoadTime=Date.now(),this._ignorer=(0,d.default)(),this._ignorer.add(m);try{let e=await u.default.readFile(this.absolute(`.ignore`),`utf8`);this._ignorer.add(e)}catch(e){if(y(e)||b(e))return;throw e}}ignoreFileLoadedWithin(e){return Date.now()-this._lastIgnoreFileLoadTime<e}ignores(e,t){return e=this.relative(e),e===``?!1:e.startsWith(`..`)||(e=(0,f.default)(e,!1),t&&!e.endsWith(`/`)&&(e+=`/`),this._isHashing&&h.some(t=>e.startsWith(t)))?!0:p.some(t=>e.startsWith(t))?!1:this._ignorer.ignores(e)}async*walk({dir:e=this.path}={}){e!==this.path&&(yield this.normalize(e,!0));for await(let t of await u.default.opendir(e)){let n=r.join(e,t.name);this.ignores(n,t.isDirectory())||(t.isDirectory()?yield*this.walk({dir:n}):t.isFile()&&(yield this.normalize(n,!1)))}}async hashes(){try{this._isHashing=!0;let e={};for await(let t of this.walk())e[t]=await v(this.absolute(t));return e}finally{this._isHashing=!1}}async hasFiles(){return!await this.isEmptyOrNonExistent()}async isEmptyOrNonExistent(){let e=!0;try{for await(let t of this.walk()){e=!1;break}}catch(e){x(e)}return e}};const _=process.platform===`linux`||process.platform===`darwin`,v=async e=>{let t=a(`sha1`);t.update(r.basename(e));let n=await u.default.stat(e),s;if(_&&(s=n.mode&511),n.isDirectory())return{sha1:t.digest(`hex`),permissions:s};let c=new i({transform(e,t,n){if(!e.includes(13)){n(void 0,e);return}let r=Buffer.alloc(e.length),i=0;for(let t of e)t!==13&&(r[i++]=t);n(void 0,r.subarray(0,i))}});return await o(u.default.createReadStream(e),c,t),{sha1:t.digest(`hex`),permissions:s}};function y(e){return!!e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`}function b(e){return!!e&&typeof e==`object`&&`code`in e&&e.code===`EISDIR`}const x=e=>{if(!y(e))throw e};export{_ as n,x as r,g as t};
9
+ //# sourceMappingURL=directory-CNL03L6c.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directory-CNL03L6c.js","names":["fs"],"sources":["../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js","../node_modules/.pnpm/normalize-path@3.0.0/node_modules/normalize-path/index.js","../src/services/filesync/directory.ts"],"sourcesContent":["// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\nconst REGEX_TEST_BLANK_LINE = /^\\s+$/\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst REGEX_TEST_INVALID_PATH = /^\\.{0,2}\\/|^\\.{1,2}$/\n\nconst REGEX_TEST_TRAILING_SLASH = /\\/$/\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g\n\nconst RETURN_FALSE = () => false\n\n// Sanitize the range of a regular expression\n// The cases are complicated, see test cases for details\nconst sanitizeRange = range => range.replace(\n REGEX_REGEXP_RANGE,\n (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)\n ? match\n // Invalid range (out of order) which is ok for gitignore rules but\n // fatal for JavaScript regular expression, so eliminate it.\n : EMPTY\n)\n\n// See fixtures #59\nconst cleanRangeBackSlash = slashes => {\n const {length} = slashes\n return slashes.slice(0, length - length % 2)\n}\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\nconst REPLACERS = [\n\n [\n // Remove BOM\n // TODO:\n // Other similar zero-width characters?\n /^\\uFEFF/,\n () => EMPTY\n ],\n\n // > Trailing spaces are ignored unless they are quoted with backslash (\"\\\")\n [\n // (a\\ ) -> (a )\n // (a ) -> (a)\n // (a ) -> (a)\n // (a \\ ) -> (a )\n /((?:\\\\\\\\)*?)(\\\\?\\s+)$/,\n (_, m1, m2) => m1 + (\n m2.indexOf('\\\\') === 0\n ? SPACE\n : EMPTY\n )\n ],\n\n // Replace (\\ ) with ' '\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n /(\\\\+?)\\s/g,\n (_, m1) => {\n const {length} = m1\n return m1.slice(0, length - length % 2) + SPACE\n }\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^'\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/'\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*\\\\\\*\\\\\\*\\\\\\//,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n /^(?=[^^])/,\n function startingReplacer () {\n // If has a slash `/` at the beginning or middle\n return !/\\/(?!$)/.test(this)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n ? '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder\n : '\\\\/.+'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n }\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE\n ],\n\n [\n // > The range notation, e.g. [a-zA-Z],\n // > can be used to match one of the characters in a range.\n\n // `\\` is escaped by step 3\n /(\\\\)?\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE\n // '\\\\[bar]' -> '\\\\\\\\[bar\\\\]'\n ? `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}`\n : close === ']'\n ? endEscape.length % 2 === 0\n // A normal case, and it is a range notation\n // '[bar]'\n // '[bar\\\\\\\\]'\n ? `[${sanitizeRange(range)}${endEscape}]`\n // Invalid range notaton\n // '[bar\\\\]' -> '[bar\\\\\\\\]'\n : '[]'\n : '[]'\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n /(?:[^*])$/,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n match => /\\/$/.test(match)\n // foo/ will not match 'foo'\n ? `${match}$`\n // foo matches 'foo' and 'foo/'\n : `${match}(?=$|\\\\/$)`\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\\\\\*$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst TRAILING_WILD_CARD_REPLACERS = {\n [MODE_IGNORE] (_, p1) {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n },\n\n [MODE_CHECK_IGNORE] (_, p1) {\n // When doing `git check-ignore`\n const prefix = p1\n // '\\\\\\/':\n // 'abc/*' DOES match 'abc/' !\n ? `${p1}[^/]*`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n }\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => REPLACERS.reduce(\n (prev, [matcher, replacer]) =>\n prev.replace(matcher, replacer.bind(pattern)),\n pattern\n)\n\nconst isString = subject => typeof subject === 'string'\n\n// > A blank line matches no files, so it can serve as a separator for readability.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_TEST_BLANK_LINE.test(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\n // > A line starting with # serves as a comment.\n && pattern.indexOf('#') !== 0\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = this.regexPrefix.replace(\n REGEX_REPLACE_TRAILING_WILDCARD,\n\n // It does not need to bind pattern\n TRAILING_WILD_CARD_REPLACERS[mode]\n )\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n let negative = false\n let body = pattern\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body.indexOf('!') === 0) {\n negative = true\n body = body.substr(1)\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n if (checkPattern(pattern.pattern)) {\n const rule = createRule(pattern, this._ignoreCase)\n this._added = true\n this._rules.push(rule)\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n return this._added\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - checkUnignored `boolean` whether should check if the path is unignored,\n // setting `checkUnignored` to `false` could reduce additional\n // path matching.\n // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult} true if a file is ignored\n test (path, checkUnignored, mode) {\n let ignored = false\n let unignored = false\n let matchedRule\n\n this._rules.forEach(rule => {\n const {negative} = rule\n\n // | ignored : unignored\n // -------- | ---------------------------------------\n // negative | 0:0 | 0:1 | 1:0 | 1:1\n // -------- | ------- | ------- | ------- | --------\n // 0 | TEST | TEST | SKIP | X\n // 1 | TESTIF | SKIP | TEST | X\n\n // - SKIP: always skip\n // - TEST: always test\n // - TESTIF: only test if checkUnignored\n // - X: that never happen\n if (\n unignored === negative && ignored !== unignored\n || negative && !ignored && !unignored && !checkUnignored\n ) {\n return\n }\n\n const matched = rule[mode].test(path)\n\n if (!matched) {\n return\n }\n\n ignored = !negative\n unignored = negative\n\n matchedRule = negative\n ? UNDEFINED\n : rule\n })\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\nconst isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path)\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache, checkUnignored, slices) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache, checkUnignored, slices)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (!REGEX_TEST_TRAILING_SLASH.test(path)) {\n return this.test(path)\n }\n\n const slices = path.split(SLASH).filter(Boolean)\n slices.pop()\n\n if (slices.length) {\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n this._testCache,\n true,\n slices\n )\n\n if (parent.ignored) {\n return parent\n }\n }\n\n return this._rules.test(path, false, MODE_CHECK_IGNORE)\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache,\n\n // Whether should check if the path is unignored\n checkUnignored,\n\n // The path slices\n slices\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n if (!slices) {\n // path/to/a.js\n // ['path', 'to', 'a.js']\n slices = path.split(SLASH).filter(Boolean)\n }\n\n slices.pop()\n\n // If the path has no parent directory, just test it\n if (!slices.length) {\n return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n cache,\n checkUnignored,\n slices\n )\n\n // If the path contains a parent directory, check the parent first\n return cache[path] = parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache, false).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache, true)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","/*!\n * normalize-path <https://github.com/jonschlinkert/normalize-path>\n *\n * Copyright (c) 2014-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nmodule.exports = function(path, stripTrailing) {\n if (typeof path !== 'string') {\n throw new TypeError('expected path to be a string');\n }\n\n if (path === '\\\\' || path === '/') return '/';\n\n var len = path.length;\n if (len <= 1) return path;\n\n // ensure that win32 namespaces has two leading slashes, so that the path is\n // handled properly by the win32 version of path.parse() after being normalized\n // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces\n var prefix = '';\n if (len > 4 && path[3] === '\\\\') {\n var ch = path[2];\n if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\\\\\') {\n path = path.slice(2);\n prefix = '//';\n }\n }\n\n var segs = path.split(/[/\\\\]+/);\n if (stripTrailing !== false && segs[segs.length - 1] === '') {\n segs.pop();\n }\n return prefix + segs.join('/');\n};\n","import assert from \"node:assert\";\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\n\n/* eslint-disable func-style */\n/**\n * DO NOT MODIFY\n *\n * Everything in this file also exists in gadget to ensure that this logic\n * is the same between the two projects.\n */\nimport fs from \"fs-extra\";\nimport type { Ignore } from \"ignore\";\nimport ignore from \"ignore\";\nimport normalizePath from \"normalize-path\";\n\n/**\n * Paths that are never ignored, regardless of the contents of the `.ignore` file.\n */\nexport const NEVER_IGNORE_PATHS = [\".gadget/\"] as const;\n\n/**\n * Paths that are always ignored, regardless of the contents of the `.ignore` file.\n */\nexport const ALWAYS_IGNORE_PATHS = [\".DS_Store\", \"node_modules\", \".git\", \".shopify\"] as const;\n\n/**\n * Paths that are ignored when hashing the directory.\n *\n * NOTE: This is the _only_ thing that is allowed to be different between gadget and ggt.\n */\nexport const HASHING_IGNORE_PATHS = [\".gadget/sync.json\", \".gadget/dev-lock.json\", \".gadget/backup\", \"yarn-error.log\"] as const;\n\n/**\n * Represents a directory that is being synced.\n */\nexport class Directory {\n /**\n * A gitignore-style file parser used to determine which files to\n * ignore while syncing.\n *\n * @see https://www.npmjs.com/package/ignore\n */\n private _ignorer!: Ignore;\n\n /**\n * Whether the directory is currently being hashed.\n */\n private _isHashing = false;\n\n /**\n * Timestamp of the last {@linkcode loadIgnoreFile} call, used to\n * deduplicate redundant reloads from duplicate FSEvents.\n */\n private _lastIgnoreFileLoadTime = 0;\n\n /**\n * An absolute path to the directory that is being synced.\n */\n readonly path: string;\n\n private constructor(path: string) {\n this.path = path;\n }\n\n /**\n * Initializes a directory to be synced.\n *\n * If the directory does not exist, it is created.\n *\n * @param dir - The directory to initialize.\n * @returns A Promise that resolves to a Directory instance.\n */\n static async init(dir: string): Promise<Directory> {\n const directory = new Directory(dir);\n await directory.loadIgnoreFile();\n // don't count the init call as a recent load — the timestamp is\n // only meaningful once the file watcher is running\n directory._lastIgnoreFileLoadTime = 0;\n return directory;\n }\n\n /**\n * Returns the relative path from this directory to the specified path.\n *\n * @param to - The path to which the relative path is calculated.\n * @returns The relative path from this directory to the specified path.\n */\n relative(to: string): string {\n if (!path.isAbsolute(to)) {\n // the filepath is already relative\n return to;\n }\n\n return path.relative(this.path, to);\n }\n\n /**\n * Returns the absolute path by resolving the given path segments\n * relative to the directory path.\n *\n * @param pathSegments - The path segments to resolve.\n * @returns The absolute path.\n */\n absolute(...pathSegments: string[]): string {\n const result = path.resolve(this.path, ...pathSegments);\n assert(result.startsWith(this.path), `expected ${result} to be within ${this.path}`);\n return result;\n }\n\n /**\n * Similar to {@linkcode relative} in that it converts an absolute\n * path into a relative one from {@linkcode path}. However, it also\n * changes any slashes to be posix/unix-like forward slashes,\n * condenses repeated slashes into a single slash, and adds a trailing\n * slash if the path is a directory.\n *\n * This is used when sending files to Gadget to ensure that the paths\n * are consistent across platforms.\n *\n * @see https://www.npmjs.com/package/normalize-path\n */\n normalize(filepath: string, isDirectory: boolean): string {\n if (path.isAbsolute(filepath)) {\n filepath = this.relative(filepath);\n }\n\n // true = trim trailing slashes\n filepath = normalizePath(filepath, true);\n\n if (isDirectory) {\n filepath += \"/\";\n }\n\n return filepath;\n }\n\n /**\n * Loads the `.ignore` file in the directory. If the file does not\n * exist, it is silently ignored.\n */\n async loadIgnoreFile(): Promise<void> {\n this._lastIgnoreFileLoadTime = Date.now();\n this._ignorer = ignore();\n this._ignorer.add(ALWAYS_IGNORE_PATHS);\n\n try {\n const content = await fs.readFile(this.absolute(\".ignore\"), \"utf8\");\n this._ignorer.add(content);\n } catch (error) {\n if (isEnoentError(error) || isEisdirError(error)) {\n // ignore missing or is-directory errors\n return;\n }\n throw error;\n }\n }\n\n /**\n * Returns true if {@linkcode loadIgnoreFile} was called within the\n * given duration. Used to skip redundant watcher-triggered reloads\n * when a remote write already loaded the ignore file.\n */\n ignoreFileLoadedWithin(duration: number): boolean {\n return Date.now() - this._lastIgnoreFileLoadTime < duration;\n }\n\n /**\n * Determines if a file should be ignored based on its filepath.\n *\n * @param filepath - The filepath of the file to check.\n * @returns True if the file should be ignored, false otherwise.\n */\n ignores(filepath: string, isDirectory: boolean): boolean {\n filepath = this.relative(filepath);\n if (filepath === \"\") {\n // don't ignore the root dir\n return false;\n }\n\n if (filepath.startsWith(\"..\")) {\n // anything above the root dir is ignored\n return true;\n }\n\n // false = don't trim trailing slashes\n filepath = normalizePath(filepath, false);\n\n if (isDirectory && !filepath.endsWith(\"/\")) {\n filepath += \"/\";\n }\n\n if (this._isHashing && HASHING_IGNORE_PATHS.some((ignored) => filepath.startsWith(ignored))) {\n // special case for hashing\n return true;\n }\n\n if (NEVER_IGNORE_PATHS.some((neverIgnored) => filepath.startsWith(neverIgnored))) {\n // special case for never ignored paths\n return false;\n }\n\n return this._ignorer.ignores(filepath);\n }\n\n /**\n * Recursively walks through the directory and yields all non-ignored\n * files and directories within it.\n *\n * @yields - The normalized path of each file and directory.\n */\n async *walk({ dir = this.path } = {}): AsyncGenerator<string> {\n // don't yield the root directory\n if (dir !== this.path) {\n yield this.normalize(dir, true);\n }\n\n for await (const entry of await fs.opendir(dir)) {\n const filepath = path.join(dir, entry.name);\n if (this.ignores(filepath, entry.isDirectory())) {\n continue;\n }\n\n if (entry.isDirectory()) {\n yield* this.walk({ dir: filepath });\n } else if (entry.isFile()) {\n yield this.normalize(filepath, false);\n }\n }\n }\n\n /**\n * Calculates the hash of each file and directory and returns an\n * object containing the hashes keyed by the normalized file path.\n *\n * @returns A Promise that resolves to an object containing the hashes\n * of each file.\n */\n async hashes(): Promise<Hashes> {\n try {\n this._isHashing = true;\n const files = {} as Hashes;\n\n for await (const normalizedPath of this.walk()) {\n const absolutePath = this.absolute(normalizedPath);\n files[normalizedPath] = await hash(absolutePath);\n }\n\n return files;\n } finally {\n this._isHashing = false;\n }\n }\n\n async hasFiles(): Promise<boolean> {\n return !(await this.isEmptyOrNonExistent());\n }\n\n async isEmptyOrNonExistent(): Promise<boolean> {\n let isEmptyOrNonExistent = true;\n try {\n for await (const _ of this.walk()) {\n isEmptyOrNonExistent = false;\n break;\n }\n } catch (error) {\n swallowEnoent(error);\n }\n return isEmptyOrNonExistent;\n }\n}\n\n/**\n * Key/value pairs where the key is the normalized path and the value is\n * the result of {@linkcode hash} for that path.\n */\nexport type Hashes = Record<string, Hash>;\n\nexport type Hash = {\n /**\n * The SHA-1 hash of the file or directory.\n *\n * If the path points to a directory, the hash is calculated based on\n * the directory's basename. If the path points to a file, the hash is\n * calculated based on the file's basename and contents.\n */\n sha1: string;\n\n /**\n * The Unix-style file permissions of the file or directory, or\n * undefined if the platform that generated this hash doesn't support\n * them.\n *\n * @example 0o644\n * @see supportsPermissions\n */\n permissions?: number;\n};\n\n/**\n * Whether the current platform supports Unix-style file permissions.\n *\n * Windows doesn't support Unix-style file permissions and all file\n * permissions retrieved via `node:fs` on Windows are translated to 666\n * or 444.\n */\nexport const supportsPermissions = process.platform === \"linux\" || process.platform === \"darwin\";\n\n/**\n * Calculates the {@linkcode Hash} of the file or directory at the\n * specified absolute path.\n *\n * @param absolutePath - The absolute path to the file or directory.\n * @returns A Promise that resolves to the {@linkcode Hash} of the file\n * or directory.\n */\nconst hash = async (absolutePath: string): Promise<Hash> => {\n const sha1 = createHash(\"sha1\");\n sha1.update(path.basename(absolutePath));\n\n const stats = await fs.stat(absolutePath);\n\n let permissions;\n if (supportsPermissions) {\n // strip everything but the permissions\n permissions = stats.mode & 0o777;\n }\n\n if (stats.isDirectory()) {\n return { sha1: sha1.digest(\"hex\"), permissions };\n }\n\n // windows uses CRLF line endings whereas unix uses LF line endings so\n // we always strip out CR bytes (0x0d) when hashing files. this does\n // make us blind to files that only differ by CR bytes, but that's a\n // tradeoff we're willing to make.\n const removeCR = new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n if (!chunk.includes(0x0d)) {\n callback(undefined, chunk);\n return;\n }\n\n const filteredChunk = Buffer.alloc(chunk.length);\n let i = 0;\n for (const byte of chunk) {\n if (byte !== 0x0d) {\n filteredChunk[i++] = byte;\n }\n }\n\n callback(undefined, filteredChunk.subarray(0, i));\n },\n });\n\n await pipeline(fs.createReadStream(absolutePath), removeCR, sha1);\n\n return { sha1: sha1.digest(\"hex\"), permissions };\n};\n\nfunction isEnoentError(error: unknown): error is { code: \"ENOENT\" } {\n return !!error && typeof error === \"object\" && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction isEisdirError(error: unknown): error is { code: \"EISDIR\" } {\n return !!error && typeof error === \"object\" && \"code\" in error && error.code === \"EISDIR\";\n}\n\n/**\n * Swallows ENOENT errors and throws any other errors.\n *\n * @param error - The error to handle.\n * @throws The original error if it is not an ENOENT error.\n */\nexport const swallowEnoent = (error: unknown): void => {\n if (isEnoentError(error)) {\n return;\n }\n throw error;\n};\n"],"x_google_ignoreList":[0,1],"mappings":"0RACA,SAAS,EAAW,EAAS,CAC3B,OAAO,MAAM,QAAQ,EAAQ,CACzB,EACA,CAAC,EAAQ,CAGf,IAIM,EAAwB,QACx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6C,CAClE,MAAO,CAAC,CAAC,GAAS,OAAO,GAAU,UAAY,SAAU,GAAS,EAAM,OAAS,SASnF,MAAa,EAAiB,GAAyB,CACjD,MAAc,EAAM,CAGxB,MAAM"}
@@ -0,0 +1,62 @@
1
+ import{o as e}from"./chunk-BjEoQXZ0.js";import"./ms-B7sMc0pR.js";import"./src-DxCC1MV4.js";import{r as t}from"./prompt-C9nwJW0G.js";import{Q as n,c as r,g as i,h as a,j as o,k as s,l as c,mt as l,nt as u,s as d}from"./http-CY3lPMkt.js";import{E as f,V as p,c as m,n as h,s as g}from"./command-2iNTc5dV.js";import{i as _}from"./collection-C2TCeYqY.js";import"./directory-CNL03L6c.js";import"./session-BmzGF1t7.js";import{a as v,o as y,r as b,u as x,y as S}from"./sync-json-V52OzeCz.js";import"./select-Dey_sjjd.js";import{t as C}from"./table-MrBbxMay.js";import w from"node:path";var T=e(p(),1);const E={"--application":v[`--application`]},D=async(e,t)=>{let n=await a(e,`env`),r=await c(e);if(r.length===0)throw new o(f`
2
+ You (${n.email}) don't have any Gadget applications.
3
+
4
+ Visit https://gadget.new to create one!
5
+ `,{usageHint:!1});let i;try{let e=await b(process.cwd()),t=await T.default.readFile(e.absolute(`.gadget/sync.json`),`utf8`);i=s.parse(JSON.parse(t))}catch{}return{application:await y({flags:t,availableApps:r,state:i,selectPrompt:`Which application do you want to manage environments for?`}),state:i}},O=(e,t)=>{let n=e.environments.find(e=>e.name===t.toLowerCase());if(n)return{...n,application:e};throw e.environments.length===0?new o(f`
6
+ No environments found for ${e.slug}.
7
+ `,{usageHint:!1}):new o(f`
8
+ Unknown environment: ${t}
9
+
10
+ Did you mean one of these?
11
+
12
+ ${_(t,e.environments.map(e=>e.name)).slice(0,5).map(e=>`• ${e}`).join(`
13
+ `)}
14
+ `,{usageHint:!1})},k=(e,t,n)=>{let i=n??t.environments.find(e=>e.type===r.Development);if(!i)throw new o(`No development environment found for ${t.slug}.`,{usageHint:!1});return new S(e,{...i,application:t})},A=async(e,n)=>{let r;try{r=await b(process.cwd())}catch(e){if(!(e instanceof x))throw e}if(r){let i=r.absolute(`.gadget/sync.json`),a;try{a=await T.default.readFile(i,`utf8`)}catch{}if(a){let r=s.parse(JSON.parse(a));if(r.application!==e.slug)throw new o(f`
15
+ This directory is synced to ${g.warning(r.application)}, but you specified ${g.warning(e.slug)}.
16
+
17
+ Either run this command from a directory synced to ${e.slug}, or omit the ${g.subdued(`--app`)} flag.
18
+ `,{usageHint:!1});if(r.environment===n){m(`Already on environment ${n}.`);return}let c=r.environment;r.environment=n,r.environments[n]||(r.environments[n]={filesVersion:`0`}),await T.default.outputJSON(i,r,{spaces:2}),m(`${t.tick} Switched environment: ${c} → ${n}`);return}}let i=r?r.absolute(`.gadget/sync.json`):w.join(process.cwd(),`.gadget`,`sync.json`),a={application:e.slug,environment:n,environments:{[n]:{filesVersion:`0`}}};await T.default.outputJSON(i,a,{spaces:2}),m(`${t.tick} Activated environment ${n}`)};var j=h({name:`env`,aliases:[`envs`],description:`Manage your app's environments`,details:f`
19
+ Environments are isolated copies of your app for development, staging, and testing. Each
20
+ environment has its own database, file tree, and environment variables. The production
21
+ environment cannot be deleted or used directly with ggt dev.
22
+ `,examples:[`ggt env list`,`ggt env create staging`,`ggt env create staging --from development`,`ggt env delete staging --force`,`ggt env unpause staging`,`ggt env use staging`],flags:E,subcommands:e=>({list:e({aliases:[`ls`],description:`List all environments`,details:f`
23
+ Displays a table of all environments with their names and types. Returns
24
+ a "no environments found" message if the app has none.
25
+ `,examples:[`ggt env list`,`ggt env list --app myapp`],run:async(e,t)=>{let{application:n}=await D(e,t),r=n.environments;if(r.length===0){m(`No environments found.`);return}C({headers:[`Name`,`Type`],rows:r.map(e=>[e.name,e.type])})}}),create:e({description:`Create a new environment`,details:f`
26
+ The environment name is lowercased automatically. Use ${g.subdued(`--from`)} to clone an
27
+ existing environment's data and schema; if omitted, the current environment
28
+ is used as the source. Use ${g.subdued(`--use`)} to switch your local directory to the
29
+ new environment immediately after creation.
30
+
31
+ See also: ${g.subdued(`ggt add environment`)} for a simpler shorthand that clones
32
+ the current environment and auto-switches.
33
+ `,examples:[`ggt env create staging`,`ggt env create staging --from development`,`ggt env create my-feature --use`],positionals:[{name:`name`,required:!0,description:`New environment name`,details:`The name is lowercased automatically. Must be unique within the app.`}],flags:{"--from":{...d,alias:[],description:`Clone from an existing environment`,details:`Clones the source environment's data and schema. If omitted, the current environment is used as the source.`},"--use":{type:Boolean,alias:`-u`,description:`Switch to the new environment after creation`,details:`Updates .gadget/sync.json to point at the new environment so subsequent commands target it.`}},run:async(e,r)=>{let{application:i,state:a}=await D(e,r),s=r._[0],c=(r[`--from`]??(a?.application===i.slug?a.environment:void 0))?.toLowerCase(),l=r[`--use`]??!1,u=s.toLowerCase();if(l&&a?.application&&a.application!==i.slug)throw new o(f`
34
+ Cannot use ${g.subdued(`--use`)}: this directory is synced to ${g.warning(a.application)}, but you specified ${g.warning(i.slug)}.
35
+
36
+ Either run this command from a directory synced to ${i.slug}, or omit the ${g.subdued(`--app`)} flag.
37
+ `,{usageHint:!1});let d=k(e,i);try{await d.mutate({mutation:n,variables:{environment:{slug:u,...c&&{sourceSlug:c}}}}),m(`${t.tick} Created environment ${u}`)}finally{await d.dispose()}l&&await A(i,u)}}),delete:e({description:`Delete an environment`,details:f`
38
+ Prompts for confirmation before deleting unless ${g.subdued(`--force`)} is passed. The
39
+ production environment cannot be deleted. If your sync directory was using
40
+ the deleted environment, you'll need to switch to another with
41
+ ${g.identifier(`ggt env use`)}.
42
+ `,examples:[`ggt env delete staging`,`ggt env delete staging --force`],positionals:[{name:`name`,required:!0,description:`Environment name`,details:`The production environment cannot be deleted.`}],flags:{"--force":{type:Boolean,alias:`-f`,description:`Skip confirmation`,details:`Deletes the environment immediately without a confirmation prompt.`}},run:async(e,n)=>{let{application:a,state:s}=await D(e,n),c=n._[0],l=O(a,c);if(l.type===r.Production)throw new o(f`
43
+ Cannot delete the ${g.identifier(`production`)} environment.
44
+ `,{usageHint:!1});n[`--force`]||await i(`Are you sure you want to delete the ${l.name} environment?`);let d=k(e,a);try{await d.mutate({mutation:u,variables:{slug:l.name}}),m(`${t.tick} Deleted environment ${l.name}`)}finally{await d.dispose()}s?.application===a.slug&&s.environment===l.name&&m(f`
45
+ ${g.warning(`Warning:`)} your sync directory was using the ${l.name} environment.
46
+
47
+ Run ${g.subdued(`ggt env use <environment>`)} to switch to another environment.
48
+ `)}}),unpause:e({description:`Unpause a paused environment`,details:f`
49
+ Environments are paused automatically after a period of inactivity.
50
+ This command resumes a paused environment so it can serve requests and
51
+ run actions again. Prints a message if the environment is already
52
+ active.
53
+ `,examples:[`ggt env unpause staging`,`ggt env unpause development --app myapp`],positionals:[{name:`name`,required:!0,description:`Environment name`,details:`Must match an existing environment in the app.`}],run:async(e,n)=>{let{application:r}=await D(e,n),i=n._[0],a=k(e,r,O(r,i));try{(await a.mutate({mutation:l})).unpauseEnvironment.alreadyActive?m(`Environment ${i} is already active.`):m(`${t.tick} Unpaused environment ${i}`)}finally{await a.dispose()}}}),use:e({description:`Switch the active environment for this directory`,details:f`
54
+ Updates ${g.subdued(`.gadget/sync.json`)} to point at the given environment. The
55
+ production environment cannot be set as the active sync target — use
56
+ ${g.identifier(`ggt pull --env production`)} to pull production files instead.
57
+ `,examples:[`ggt env use staging`,`ggt env use development`],positionals:[{name:`name`,required:!0,description:`Environment name`,details:`The production environment cannot be set as the active sync target.`}],run:async(e,t)=>{let{application:n}=await D(e,t),i=t._[0],a=O(n,i);if(a.type===r.Production)throw new o(f`
58
+ Cannot use the ${g.identifier(`production`)} environment.
59
+
60
+ Use ${g.subdued(`ggt pull --env production`)} to pull from production instead.
61
+ `,{usageHint:!1});await A(n,a.name)}})})});export{j as default};
62
+ //# sourceMappingURL=env-DoWNvHzW.js.map