commandkit 0.1.11-dev.20250128160021 → 0.1.11-dev.20250128162628

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 (188) hide show
  1. package/bin/index.mjs +2 -50
  2. package/dist/CommandKit.js +6 -6
  3. package/dist/CommandKit.js.map +1 -1
  4. package/dist/CommandKit.mjs +1 -1
  5. package/dist/cache/CacheProvider.js +1 -1
  6. package/dist/cache/CacheProvider.js.map +1 -1
  7. package/dist/cache/CacheProvider.mjs +1 -1
  8. package/dist/cache/MemoryCache.js +1 -1
  9. package/dist/cache/MemoryCache.js.map +1 -1
  10. package/dist/cache/MemoryCache.mjs +1 -1
  11. package/dist/cache/cache.js +6 -6
  12. package/dist/cache/cache.js.map +1 -1
  13. package/dist/cache/cache.mjs +1 -1
  14. package/dist/cache/index.js +6 -6
  15. package/dist/cache/index.js.map +1 -1
  16. package/dist/cache/index.mjs +1 -1
  17. package/dist/chunk-35OSBS47.mjs +2 -0
  18. package/dist/chunk-6ZU6MOKA.mjs +2 -0
  19. package/dist/chunk-73NFQRKA.mjs +7 -0
  20. package/dist/{chunk-XJCWZEWC.mjs.map → chunk-73NFQRKA.mjs.map} +1 -1
  21. package/dist/chunk-B5T552SB.mjs +2 -0
  22. package/dist/{chunk-4OV4GE7B.mjs.map → chunk-B5T552SB.mjs.map} +1 -1
  23. package/dist/{chunk-6AX5YJEO.mjs → chunk-BNTMQC76.mjs} +2 -2
  24. package/dist/{chunk-DW5KRS5H.mjs → chunk-DTKEXOZL.mjs} +3 -3
  25. package/dist/{chunk-DW5KRS5H.mjs.map → chunk-DTKEXOZL.mjs.map} +1 -1
  26. package/dist/chunk-FC5WQLBI.mjs +3 -0
  27. package/dist/chunk-FC5WQLBI.mjs.map +1 -0
  28. package/dist/{chunk-4CG7S6RY.mjs → chunk-ICJ4BBWI.mjs} +2 -2
  29. package/dist/chunk-IRBJOQ7G.mjs +2 -0
  30. package/dist/{chunk-CO2EZ53K.mjs.map → chunk-IRBJOQ7G.mjs.map} +1 -1
  31. package/dist/chunk-JYUG7HAX.mjs +2 -0
  32. package/dist/{chunk-Z4FBPRS6.mjs.map → chunk-JYUG7HAX.mjs.map} +1 -1
  33. package/dist/chunk-KAJRRZVI.mjs +2 -0
  34. package/dist/{chunk-5KRNT4BG.mjs.map → chunk-KAJRRZVI.mjs.map} +1 -1
  35. package/dist/chunk-LQPVE73I.mjs +2 -0
  36. package/dist/{chunk-RGQOLRR6.mjs.map → chunk-LQPVE73I.mjs.map} +1 -1
  37. package/dist/{chunk-6W2KY7FK.mjs → chunk-PTP2L33V.mjs} +2 -2
  38. package/dist/{chunk-C6WU57FQ.mjs → chunk-QXMWKQIO.mjs} +2 -2
  39. package/dist/{chunk-CKNUFVNV.mjs → chunk-R4SWJR4N.mjs} +2 -2
  40. package/dist/chunk-RQ3ABUE3.mjs +2 -0
  41. package/dist/chunk-RQ3ABUE3.mjs.map +1 -0
  42. package/dist/{chunk-6BSP7AD3.mjs → chunk-RVGLG66X.mjs} +2 -2
  43. package/dist/chunk-SI3L34FF.mjs +2 -0
  44. package/dist/{chunk-UPJYI5Q6.mjs.map → chunk-SI3L34FF.mjs.map} +1 -1
  45. package/dist/chunk-TEL2J6LT.mjs +2 -0
  46. package/dist/{chunk-WNEBLBID.mjs.map → chunk-TEL2J6LT.mjs.map} +1 -1
  47. package/dist/chunk-ULPF2QCW.mjs +2 -0
  48. package/dist/chunk-ULPF2QCW.mjs.map +1 -0
  49. package/dist/{chunk-J7CCGFUZ.mjs → chunk-UP6ACDGE.mjs} +2 -2
  50. package/dist/{chunk-J7CCGFUZ.mjs.map → chunk-UP6ACDGE.mjs.map} +1 -1
  51. package/dist/chunk-UYDZJJZT.mjs +4 -0
  52. package/dist/{chunk-K43A7OIY.mjs.map → chunk-UYDZJJZT.mjs.map} +1 -1
  53. package/dist/chunk-WZU7OSUV.mjs +13 -0
  54. package/dist/chunk-WZU7OSUV.mjs.map +1 -0
  55. package/dist/chunk-Y522NY4J.mjs +2 -0
  56. package/dist/chunk-Y522NY4J.mjs.map +1 -0
  57. package/dist/chunk-ZCUZ5ENB.mjs +2 -0
  58. package/dist/chunk-ZCUZ5ENB.mjs.map +1 -0
  59. package/dist/cli/build.d.mts +4 -0
  60. package/dist/cli/build.d.ts +4 -0
  61. package/dist/cli/build.js +14 -0
  62. package/dist/cli/build.js.map +1 -0
  63. package/dist/cli/build.mjs +2 -0
  64. package/dist/cli/build.mjs.map +1 -0
  65. package/dist/cli/common.d.mts +35 -0
  66. package/dist/cli/common.d.ts +35 -0
  67. package/dist/cli/common.js +3 -0
  68. package/dist/cli/common.js.map +1 -0
  69. package/dist/cli/common.mjs +2 -0
  70. package/dist/cli/common.mjs.map +1 -0
  71. package/dist/cli/development.d.mts +3 -0
  72. package/dist/cli/development.d.ts +3 -0
  73. package/dist/cli/development.js +17 -0
  74. package/dist/cli/development.js.map +1 -0
  75. package/dist/cli/development.mjs +7 -0
  76. package/dist/cli/development.mjs.map +1 -0
  77. package/dist/cli/esbuild-plugins/plugin.d.mts +10 -0
  78. package/dist/cli/esbuild-plugins/plugin.d.ts +10 -0
  79. package/dist/cli/esbuild-plugins/plugin.js +2 -0
  80. package/dist/cli/esbuild-plugins/plugin.js.map +1 -0
  81. package/dist/cli/esbuild-plugins/plugin.mjs +2 -0
  82. package/dist/cli/esbuild-plugins/plugin.mjs.map +1 -0
  83. package/dist/cli/esbuild-plugins/use-cache.d.mts +6 -0
  84. package/dist/cli/esbuild-plugins/use-cache.d.ts +6 -0
  85. package/dist/cli/esbuild-plugins/use-cache.js +2 -0
  86. package/dist/cli/esbuild-plugins/use-cache.js.map +1 -0
  87. package/dist/cli/esbuild-plugins/use-cache.mjs +2 -0
  88. package/dist/cli/esbuild-plugins/use-cache.mjs.map +1 -0
  89. package/dist/cli/init.d.mts +10 -0
  90. package/dist/cli/init.d.ts +10 -0
  91. package/dist/cli/init.js +20 -0
  92. package/dist/cli/init.js.map +1 -0
  93. package/dist/cli/init.mjs +2 -0
  94. package/dist/cli/init.mjs.map +1 -0
  95. package/dist/cli/parse-env.d.mts +3 -0
  96. package/dist/cli/parse-env.d.ts +3 -0
  97. package/dist/cli/parse-env.js +2 -0
  98. package/dist/cli/parse-env.js.map +1 -0
  99. package/dist/cli/parse-env.mjs +2 -0
  100. package/dist/cli/parse-env.mjs.map +1 -0
  101. package/dist/cli/production.d.mts +3 -0
  102. package/dist/cli/production.d.ts +3 -0
  103. package/dist/cli/production.js +4 -0
  104. package/dist/cli/production.js.map +1 -0
  105. package/dist/cli/production.mjs +3 -0
  106. package/dist/cli/production.mjs.map +1 -0
  107. package/dist/components/ButtonKit.js +1 -1
  108. package/dist/components/ButtonKit.js.map +1 -1
  109. package/dist/components/ButtonKit.mjs +1 -1
  110. package/dist/components/index.js +1 -1
  111. package/dist/components/index.js.map +1 -1
  112. package/dist/components/index.mjs +1 -1
  113. package/dist/config.mjs +1 -1
  114. package/dist/context/async-context.js +6 -6
  115. package/dist/context/async-context.js.map +1 -1
  116. package/dist/context/async-context.mjs +1 -1
  117. package/dist/context/environment.js +1 -1
  118. package/dist/context/environment.js.map +1 -1
  119. package/dist/context/environment.mjs +1 -1
  120. package/dist/handlers/command-handler/CommandHandler.js +6 -6
  121. package/dist/handlers/command-handler/CommandHandler.js.map +1 -1
  122. package/dist/handlers/command-handler/CommandHandler.mjs +1 -1
  123. package/dist/handlers/command-handler/functions/loadCommandsWithRest.js +2 -2
  124. package/dist/handlers/command-handler/functions/loadCommandsWithRest.js.map +1 -1
  125. package/dist/handlers/command-handler/functions/loadCommandsWithRest.mjs +1 -1
  126. package/dist/handlers/command-handler/functions/registerCommands.js +2 -2
  127. package/dist/handlers/command-handler/functions/registerCommands.js.map +1 -1
  128. package/dist/handlers/command-handler/functions/registerCommands.mjs +1 -1
  129. package/dist/handlers/command-handler/utils/areSlashCommandsDifferent.mjs +1 -1
  130. package/dist/handlers/command-handler/validations/devOnly.js +1 -1
  131. package/dist/handlers/command-handler/validations/devOnly.js.map +1 -1
  132. package/dist/handlers/command-handler/validations/devOnly.mjs +1 -1
  133. package/dist/handlers/command-handler/validations/index.js +1 -1
  134. package/dist/handlers/command-handler/validations/index.js.map +1 -1
  135. package/dist/handlers/command-handler/validations/index.mjs +1 -1
  136. package/dist/handlers/command-handler/validations/permissions.js +1 -1
  137. package/dist/handlers/command-handler/validations/permissions.js.map +1 -1
  138. package/dist/handlers/command-handler/validations/permissions.mjs +1 -1
  139. package/dist/handlers/event-handler/EventHandler.js +1 -1
  140. package/dist/handlers/event-handler/EventHandler.js.map +1 -1
  141. package/dist/handlers/event-handler/EventHandler.mjs +1 -1
  142. package/dist/handlers/index.js +6 -6
  143. package/dist/handlers/index.js.map +1 -1
  144. package/dist/handlers/index.mjs +1 -1
  145. package/dist/handlers/validation-handler/ValidationHandler.js +1 -1
  146. package/dist/handlers/validation-handler/ValidationHandler.js.map +1 -1
  147. package/dist/handlers/validation-handler/ValidationHandler.mjs +1 -1
  148. package/dist/index.d.mts +2 -0
  149. package/dist/index.d.ts +2 -0
  150. package/dist/index.js +24 -6
  151. package/dist/index.js.map +1 -1
  152. package/dist/index.mjs +1 -1
  153. package/dist/index.mjs.map +1 -1
  154. package/dist/types.mjs +1 -1
  155. package/dist/utils/clone.mjs +1 -1
  156. package/dist/utils/colors.mjs +1 -1
  157. package/dist/utils/constants.mjs +1 -1
  158. package/dist/utils/error-codes.mjs +1 -1
  159. package/dist/utils/get-paths.mjs +1 -1
  160. package/dist/utils/resolve-file-url.mjs +1 -1
  161. package/dist/utils/warn-unstable.mjs +1 -1
  162. package/package.json +3 -13
  163. package/bin/build.mjs +0 -129
  164. package/bin/common.mjs +0 -125
  165. package/bin/development.mjs +0 -187
  166. package/bin/esbuild-plugins/plugin.mjs +0 -74
  167. package/bin/esbuild-plugins/use-cache.mjs +0 -160
  168. package/bin/parse-env.mjs +0 -65
  169. package/bin/production.mjs +0 -86
  170. package/dist/chunk-4OV4GE7B.mjs +0 -2
  171. package/dist/chunk-5KRNT4BG.mjs +0 -2
  172. package/dist/chunk-6TIBWNPX.mjs +0 -2
  173. package/dist/chunk-6TIGKCSX.mjs +0 -2
  174. package/dist/chunk-CO2EZ53K.mjs +0 -2
  175. package/dist/chunk-K43A7OIY.mjs +0 -4
  176. package/dist/chunk-RGQOLRR6.mjs +0 -2
  177. package/dist/chunk-UPJYI5Q6.mjs +0 -2
  178. package/dist/chunk-WNEBLBID.mjs +0 -2
  179. package/dist/chunk-XJCWZEWC.mjs +0 -7
  180. package/dist/chunk-Z4FBPRS6.mjs +0 -2
  181. /package/dist/{chunk-6TIBWNPX.mjs.map → chunk-35OSBS47.mjs.map} +0 -0
  182. /package/dist/{chunk-6TIGKCSX.mjs.map → chunk-6ZU6MOKA.mjs.map} +0 -0
  183. /package/dist/{chunk-6AX5YJEO.mjs.map → chunk-BNTMQC76.mjs.map} +0 -0
  184. /package/dist/{chunk-4CG7S6RY.mjs.map → chunk-ICJ4BBWI.mjs.map} +0 -0
  185. /package/dist/{chunk-6W2KY7FK.mjs.map → chunk-PTP2L33V.mjs.map} +0 -0
  186. /package/dist/{chunk-C6WU57FQ.mjs.map → chunk-QXMWKQIO.mjs.map} +0 -0
  187. /package/dist/{chunk-CKNUFVNV.mjs.map → chunk-R4SWJR4N.mjs.map} +0 -0
  188. /package/dist/{chunk-6BSP7AD3.mjs.map → chunk-RVGLG66X.mjs.map} +0 -0
@@ -0,0 +1,4 @@
1
+ import{__name}from"./chunk-35OSBS47.mjs";import{EmbedBuilder}from"discord.js";function permissions_default({interaction,targetCommand}){var _a,_b,_c,_d;if(interaction.isAutocomplete())return;let userPermissions=interaction.memberPermissions,userPermissionsRequired=(_a=targetCommand.options)==null?void 0:_a.userPermissions,missingUserPermissions=[];typeof userPermissionsRequired=="string"&&(userPermissionsRequired=[userPermissionsRequired]);let botPermissions=(_c=(_b=interaction.guild)==null?void 0:_b.members.me)==null?void 0:_c.permissions,botPermissionsRequired=(_d=targetCommand.options)==null?void 0:_d.botPermissions,missingBotPermissions=[];if(typeof botPermissionsRequired=="string"&&(botPermissionsRequired=[botPermissionsRequired]),!(userPermissionsRequired!=null&&userPermissionsRequired.length)&&!(botPermissionsRequired!=null&&botPermissionsRequired.length))return;if(userPermissions&&userPermissionsRequired)for(let permission of userPermissionsRequired)userPermissions.has(permission)||missingUserPermissions.push(permission);if(botPermissions&&botPermissionsRequired)for(let permission of botPermissionsRequired)botPermissions.has(permission)||missingBotPermissions.push(permission);if(!missingUserPermissions.length&&!missingBotPermissions.length)return;let pattern=/([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;missingUserPermissions=missingUserPermissions.map(str=>str.replace(pattern,"$1$3 $2$4")),missingBotPermissions=missingBotPermissions.map(str=>str.replace(pattern,"$1$3 $2$4"));let embedDescription="",formatter=new Intl.ListFormat("en",{style:"long",type:"conjunction"}),getPermissionWord=__name(permissions=>permissions.length===1?"permission":"permissions","getPermissionWord");if(missingUserPermissions.length){let formattedPermissions=missingUserPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- You must have the ${permissionsString} ${getPermissionWord(missingUserPermissions)} to be able to run this command.
2
+ `}if(missingBotPermissions.length){let formattedPermissions=missingBotPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- I must have the ${permissionsString} ${getPermissionWord(missingBotPermissions)} to be able to execute this command.
3
+ `}let embed=new EmbedBuilder().setTitle(":x: Missing permissions!").setDescription(embedDescription).setColor("Red");return interaction.reply({embeds:[embed],ephemeral:!0}),!0}__name(permissions_default,"default");export{permissions_default};
4
+ //# sourceMappingURL=chunk-UYDZJJZT.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/handlers/command-handler/validations/permissions.ts"],"sourcesContent":["import type { BuiltInValidationParams } from '../typings';\nimport { EmbedBuilder } from 'discord.js';\n\nexport default function ({\n interaction,\n targetCommand\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n const userPermissions = interaction.memberPermissions;\n let userPermissionsRequired = targetCommand.options?.userPermissions;\n let missingUserPermissions: string[] = [];\n\n if (typeof userPermissionsRequired === 'string') {\n userPermissionsRequired = [userPermissionsRequired];\n }\n\n const botPermissions = interaction.guild?.members.me?.permissions;\n let botPermissionsRequired = targetCommand.options?.botPermissions;\n let missingBotPermissions: string[] = [];\n\n if (typeof botPermissionsRequired === 'string') {\n botPermissionsRequired = [botPermissionsRequired];\n }\n\n if (!userPermissionsRequired?.length && !botPermissionsRequired?.length) {\n return;\n }\n\n if (userPermissions && userPermissionsRequired) {\n for (const permission of userPermissionsRequired) {\n const hasPermission = userPermissions.has(permission);\n\n if (!hasPermission) {\n missingUserPermissions.push(permission);\n }\n }\n }\n\n if (botPermissions && botPermissionsRequired) {\n for (const permission of botPermissionsRequired) {\n const hasPermission = botPermissions.has(permission);\n\n if (!hasPermission) {\n missingBotPermissions.push(permission);\n }\n }\n }\n\n if (!missingUserPermissions.length && !missingBotPermissions.length) {\n return;\n }\n\n // Fix casing. e.g. KickMembers -> Kick Members\n const pattern = /([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;\n\n missingUserPermissions = missingUserPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n missingBotPermissions = missingBotPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n\n let embedDescription = '';\n\n const formatter = new Intl.ListFormat('en', {\n style: 'long',\n type: 'conjunction'\n });\n\n const getPermissionWord = (permissions: string[]) =>\n permissions.length === 1 ? 'permission' : 'permissions';\n\n if (missingUserPermissions.length) {\n const formattedPermissions = missingUserPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- You must have the ${permissionsString} ${getPermissionWord(\n missingUserPermissions\n )} to be able to run this command.\\n`;\n }\n\n if (missingBotPermissions.length) {\n const formattedPermissions = missingBotPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- I must have the ${permissionsString} ${getPermissionWord(\n missingBotPermissions\n )} to be able to execute this command.\\n`;\n }\n\n const embed = new EmbedBuilder().\n setTitle(`:x: Missing permissions!`).\n setDescription(embedDescription).\n setColor('Red');\n\n interaction.reply({ embeds: [embed], ephemeral: true });\n return true;\n}"],"mappings":"yCACA,OAAS,iBAAoB,aAEd,SAAR,oBAAkB,CACvB,YACA,aACF,EAA4B,CAC1B,GAAI,YAAY,eAAe,EAAG,OAClC,IAAM,gBAAkB,YAAY,kBAChC,wBAA0B,cAAc,SAAS,gBACjD,uBAAmC,CAAC,EAEpC,OAAO,yBAA4B,WACrC,wBAA0B,CAAC,uBAAuB,GAGpD,IAAM,eAAiB,YAAY,OAAO,QAAQ,IAAI,YAClD,uBAAyB,cAAc,SAAS,eAChD,sBAAkC,CAAC,EAMvC,GAJI,OAAO,wBAA2B,WACpC,uBAAyB,CAAC,sBAAsB,GAG9C,CAAC,yBAAyB,QAAU,CAAC,wBAAwB,OAC/D,OAGF,GAAI,iBAAmB,wBACrB,QAAW,cAAc,wBACD,gBAAgB,IAAI,UAAU,GAGlD,uBAAuB,KAAK,UAAU,EAK5C,GAAI,gBAAkB,uBACpB,QAAW,cAAc,uBACD,eAAe,IAAI,UAAU,GAGjD,sBAAsB,KAAK,UAAU,EAK3C,GAAI,CAAC,uBAAuB,QAAU,CAAC,sBAAsB,OAC3D,OAIF,IAAM,QAAU,uCAEhB,uBAAyB,uBAAuB,IAAK,KACrD,IAAI,QAAQ,QAAS,WAAW,CAChC,EACA,sBAAwB,sBAAsB,IAAK,KACnD,IAAI,QAAQ,QAAS,WAAW,CAChC,EAEA,IAAI,iBAAmB,GAEjB,UAAY,IAAI,KAAK,WAAW,KAAM,CAC1C,MAAO,OACP,KAAM,aACR,CAAC,EAEK,kBAAoB,OAAC,aAC3B,YAAY,SAAW,EAAI,aAAe,cADhB,qBAG1B,GAAI,uBAAuB,OAAQ,CACjC,IAAM,qBAAuB,uBAAuB,IAAK,GAAM,KAAK,CAAC,IAAI,EACnE,kBAAoB,UAAU,OAAO,oBAAoB,EAE/D,kBAAoB,uBAAuB,iBAAiB,IAAI,kBAC9D,sBACF,CAAC;AAAA,CACH,CAEA,GAAI,sBAAsB,OAAQ,CAChC,IAAM,qBAAuB,sBAAsB,IAAK,GAAM,KAAK,CAAC,IAAI,EAClE,kBAAoB,UAAU,OAAO,oBAAoB,EAE/D,kBAAoB,qBAAqB,iBAAiB,IAAI,kBAC5D,qBACF,CAAC;AAAA,CACH,CAEA,IAAM,MAAQ,IAAI,aAAa,EAC/B,SAAS,0BAA0B,EACnC,eAAe,gBAAgB,EAC/B,SAAS,KAAK,EAEd,mBAAY,MAAM,CAAE,OAAQ,CAAC,KAAK,EAAG,UAAW,EAAK,CAAC,EAC/C,EACT,CA9FO","names":[]}
1
+ {"version":3,"sources":["../src/handlers/command-handler/validations/permissions.ts"],"sourcesContent":["import type { BuiltInValidationParams } from '../typings';\nimport { EmbedBuilder } from 'discord.js';\n\nexport default function ({\n interaction,\n targetCommand\n}: BuiltInValidationParams) {\n if (interaction.isAutocomplete()) return;\n const userPermissions = interaction.memberPermissions;\n let userPermissionsRequired = targetCommand.options?.userPermissions;\n let missingUserPermissions: string[] = [];\n\n if (typeof userPermissionsRequired === 'string') {\n userPermissionsRequired = [userPermissionsRequired];\n }\n\n const botPermissions = interaction.guild?.members.me?.permissions;\n let botPermissionsRequired = targetCommand.options?.botPermissions;\n let missingBotPermissions: string[] = [];\n\n if (typeof botPermissionsRequired === 'string') {\n botPermissionsRequired = [botPermissionsRequired];\n }\n\n if (!userPermissionsRequired?.length && !botPermissionsRequired?.length) {\n return;\n }\n\n if (userPermissions && userPermissionsRequired) {\n for (const permission of userPermissionsRequired) {\n const hasPermission = userPermissions.has(permission);\n\n if (!hasPermission) {\n missingUserPermissions.push(permission);\n }\n }\n }\n\n if (botPermissions && botPermissionsRequired) {\n for (const permission of botPermissionsRequired) {\n const hasPermission = botPermissions.has(permission);\n\n if (!hasPermission) {\n missingBotPermissions.push(permission);\n }\n }\n }\n\n if (!missingUserPermissions.length && !missingBotPermissions.length) {\n return;\n }\n\n // Fix casing. e.g. KickMembers -> Kick Members\n const pattern = /([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;\n\n missingUserPermissions = missingUserPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n missingBotPermissions = missingBotPermissions.map((str) =>\n str.replace(pattern, '$1$3 $2$4')\n );\n\n let embedDescription = '';\n\n const formatter = new Intl.ListFormat('en', {\n style: 'long',\n type: 'conjunction'\n });\n\n const getPermissionWord = (permissions: string[]) =>\n permissions.length === 1 ? 'permission' : 'permissions';\n\n if (missingUserPermissions.length) {\n const formattedPermissions = missingUserPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- You must have the ${permissionsString} ${getPermissionWord(\n missingUserPermissions\n )} to be able to run this command.\\n`;\n }\n\n if (missingBotPermissions.length) {\n const formattedPermissions = missingBotPermissions.map((p) => `\\`${p}\\``);\n const permissionsString = formatter.format(formattedPermissions);\n\n embedDescription += `- I must have the ${permissionsString} ${getPermissionWord(\n missingBotPermissions\n )} to be able to execute this command.\\n`;\n }\n\n const embed = new EmbedBuilder().\n setTitle(`:x: Missing permissions!`).\n setDescription(embedDescription).\n setColor('Red');\n\n interaction.reply({ embeds: [embed], ephemeral: true });\n return true;\n}"],"mappings":"yCACA,OAAS,iBAAoB,aAEd,SAAR,oBAAkB,CACvB,YACA,aACF,EAA4B,CAN5B,gBAOE,GAAI,YAAY,eAAe,EAAG,OAClC,IAAM,gBAAkB,YAAY,kBAChC,yBAA0B,iBAAc,UAAd,eAAuB,gBACjD,uBAAmC,CAAC,EAEpC,OAAO,yBAA4B,WACrC,wBAA0B,CAAC,uBAAuB,GAGpD,IAAM,gBAAiB,mBAAY,QAAZ,eAAmB,QAAQ,KAA3B,eAA+B,YAClD,wBAAyB,iBAAc,UAAd,eAAuB,eAChD,sBAAkC,CAAC,EAMvC,GAJI,OAAO,wBAA2B,W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"./chunk-ZCUZ5ENB.mjs";import{Colors,erase,findCommandKitConfig,panic,write}from"./chunk-FC5WQLBI.mjs";import{__name}from"./chunk-35OSBS47.mjs";import{readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{build}from"tsup";import ora from"ora";async function bootstrapProductionBuild(config){let{sourcemap=!1,minify=!1,outDir="dist",antiCrash=!0,src,main,requirePolyfill:polyfillRequire}=await findCommandKitConfig(config),status=ora(`Creating optimized production build...
2
+ `).start(),start=performance.now();erase(outDir);try{await build({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify,shims:!0,banner:{js:"/* Optimized production build generated by CommandKit */"},sourcemap,keepNames:!0,outDir,silent:!0,watch:!1,cjsInterop:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`],esbuildPlugins:[commandkitPlugin()]}),await injectShims(outDir,main,antiCrash,polyfillRequire),status.succeed(Colors.green(`Build completed in ${(performance.now()-start).toFixed(2)}ms!`)),write(Colors.green(`
3
+ Run ${Colors.magenta("commandkit start")} ${Colors.green("to start your bot.")}`))}catch(e){status.fail(`Build failed after ${(performance.now()-start).toFixed(2)}ms!`),panic(e)}}__name(bootstrapProductionBuild,"bootstrapProductionBuild");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=join(process.cwd(),outDir,main),head=[`
4
+
5
+ ;await (async()=>{`," 'use strict';"].join(`
6
+ `),tail=`
7
+ })();`,requireScript=polyfillRequire?["// --- CommandKit require() polyfill ---",' if (typeof require === "undefined") {',' const { createRequire } = await import("node:module");'," const __require = createRequire(import.meta.url);",' Object.defineProperty(globalThis, "require", {'," value: (id) => {"," return __require(id);"," },"," configurable: true,"," enumerable: false,"," writable: true,"," });"," }","// --- CommandKit require() polyfill ---"].join(`
8
+ `):"",antiCrashScript=antiCrash?["// --- CommandKit Anti-Crash Monitor ---"," // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process"," // instead of using it as a means to resume operation."," // But it exists here due to compatibility reasons with discord bot ecosystem."," const p = (t) => `\\x1b[33m${t}\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';"," if (!process.eventNames().includes(e1)) // skip if it is already handled"," process.on(e1, (e) => {"," l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));"," })"," if (!process.eventNames().includes(e2)) // skip if it is already handled"," process.on(e2, (r) => {"," l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));"," });","// --- CommandKit Anti-Crash Monitor ---"].join(`
9
+ `):"",contents=await readFile(path,"utf-8"),finalScript=[head,requireScript,antiCrashScript,tail,`
10
+
11
+ `,contents].join(`
12
+ `);return writeFile(path,finalScript)}__name(injectShims,"injectShims");export{bootstrapProductionBuild,injectShims};
13
+ //# sourceMappingURL=chunk-WZU7OSUV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/build.ts"],"sourcesContent":["// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './common.js';\nimport ora from 'ora';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nexport async function bootstrapProductionBuild(config: any) {\n const {\n sourcemap = false,\n minify = false,\n outDir = 'dist',\n antiCrash = true,\n src,\n main,\n requirePolyfill: polyfillRequire\n } = await findCommandKitConfig(config);\n\n const status = ora('Creating optimized production build...\\n').start();\n const start = performance.now();\n\n erase(outDir);\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify,\n shims: true,\n banner: {\n js: '/* Optimized production build generated by CommandKit */'\n },\n sourcemap,\n keepNames: true,\n outDir,\n silent: true,\n watch: false,\n cjsInterop: true,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()]\n });\n\n await injectShims(outDir, main, antiCrash, polyfillRequire);\n\n status.succeed(\n Colors.green(\n `Build completed in ${(performance.now() - start).toFixed(2)}ms!`\n )\n );\n write(\n Colors.green(\n `\\nRun ${Colors.magenta(`commandkit start`)} ${Colors.green(\n 'to start your bot.'\n )}`\n )\n );\n } catch (e) {\n status.fail(\n `Build failed after ${(performance.now() - start).toFixed(2)}ms!`\n );\n panic(e);\n }\n}\n\nexport async function injectShims(\noutDir: string,\nmain: string,\nantiCrash: boolean,\npolyfillRequire: boolean)\n{\n const path = join(process.cwd(), outDir, main);\n\n const head = ['\\n\\n;await (async()=>{', \" 'use strict';\"].join('\\n');\n const tail = '\\n})();';\n const requireScript = polyfillRequire ?\n [\n '// --- CommandKit require() polyfill ---',\n ' if (typeof require === \"undefined\") {',\n ' const { createRequire } = await import(\"node:module\");',\n ' const __require = createRequire(import.meta.url);',\n ' Object.defineProperty(globalThis, \"require\", {',\n ' value: (id) => {',\n ' return __require(id);',\n ' },',\n ' configurable: true,',\n ' enumerable: false,',\n ' writable: true,',\n ' });',\n ' }',\n '// --- CommandKit require() polyfill ---'].\n join('\\n') :\n '';\n\n const antiCrashScript = antiCrash ?\n [\n '// --- CommandKit Anti-Crash Monitor ---',\n \" // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process\",\n ' // instead of using it as a means to resume operation.',\n ' // But it exists here due to compatibility reasons with discord bot ecosystem.',\n \" const p = (t) => `\\\\x1b[33m${t}\\\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';\",\n ' if (!process.eventNames().includes(e1)) // skip if it is already handled',\n ' process.on(e1, (e) => {',\n ' l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));',\n ' })',\n ' if (!process.eventNames().includes(e2)) // skip if it is already handled',\n ' process.on(e2, (r) => {',\n ' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',\n ' });',\n '// --- CommandKit Anti-Crash Monitor ---'].\n join('\\n') :\n '';\n\n const contents = await readFile(path, 'utf-8');\n const finalScript = [\n head,\n requireScript,\n antiCrashScript,\n tail,\n '\\n\\n',\n contents].\n join('\\n');\n\n return writeFile(path, finalScript);\n}"],"mappings":"4KAEA,OAAS,SAAU,cAAiB,mBACpC,OAAS,SAAY,YACrB,OAAS,UAAa,OAEtB,OAAO,QAAS,MAGhB,eAAsB,yBAAyB,OAAa,CAC1D,GAAM,CACJ,UAAY,GACZ,OAAS,GACT,OAAS,OACT,UAAY,GACZ,IACA,KACA,gBAAiB,eACnB,EAAI,MAAM,qBAAqB,MAAM,EAE/B,OAAS,IAAI;AAAA,CAA0C,EAAE,MAAM,EAC/D,MAAQ,YAAY,IAAI,EAE9B,MAAM,MAAM,EAEZ,GAAI,CACF,MAAM,MAAM,CACV,MAAO,GACP,OAAQ,CAAC,KAAK,EACd,IAAK,GACL,sBAAuB,GACvB,OACA,MAAO,GACP,OAAQ,CACN,GAAI,0DACN,EACA,UACA,UAAW,GACX,OACA,OAAQ,GACR,MAAO,GACP,WAAY,GACZ,MAAO,CAAC,IAAK,QAAS,eAAgB,IAAI,MAAM,EAAE,EAClD,eAAgB,CAAC,iBAAiB,CAAC,CACrC,CAAC,EAED,MAAM,YAAY,OAAQ,KAAM,UAAW,eAAe,EAE1D,OAAO,QACL,OAAO,MACL,uBAAuB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC,KAC9D,CACF,EACA,MACE,OAAO,MACL;AAAA,MAAS,OAAO,QAAQ,kBAAkB,CAAC,IAAI,OAAO,MACpD,oBACF,CAAC,EACH,CACF,CACF,OAAS,EAAG,CACV,OAAO,KACL,uBAAuB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC,KAC9D,EACA,MAAM,CAAC,CACT,CACF,CAzDsB,4DA2DtB,eAAsB,YACtB,OACA,KACA,UACA,gBACA,CACE,IAAM,KAAO,KAAK,QAAQ,IAAI,EAAG,OAAQ,IAAI,EAEvC,KAAO,CAAC;AAAA;AAAA,oBAA0B,iBAAiB,EAAE,KAAK;AAAA,CAAI,EAC9D,KAAO;AAAA,OACP,cAAgB,gBACtB,CACA,2CACA,0CACA,6DACA,wDACA,qDACA,yBACA,gCACA,WACA,4BACA,2BACA,wBACA,UACA,MACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,gBAAkB,UACxB,CACA,2CACA,wHACA,2DACA,mFACA,2JACA,6EACA,8BACA,mEACA,SACA,6EACA,8BACA,gFACA,UACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,SAAW,MAAM,SAAS,KAAM,OAAO,EACvC,YAAc,CACpB,KACA,cACA,gBACA,KACA;AAAA;AAAA,EACA,QAAQ,EACR,KAAK;AAAA,CAAI,EAET,OAAO,UAAU,KAAM,WAAW,CACpC,CA3DsB","names":[]}
@@ -0,0 +1,2 @@
1
+ import{__name}from"./chunk-35OSBS47.mjs";import*as parser from"@babel/parser";import _traverse from"@babel/traverse";import _generate from"@babel/generator";import*as t from"@babel/types";var traverse=_traverse.default||_traverse,generate=_generate.default||_generate,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");export{cacheDirectivePlugin};
2
+ //# sourceMappingURL=chunk-Y522NY4J.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/esbuild-plugins/use-cache.ts"],"sourcesContent":["import * as parser from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport _generate from '@babel/generator';\nimport * as t from '@babel/types';\n\n// @ts-ignore\nconst traverse = _traverse.default || _traverse;\n// @ts-ignore\nconst generate = _generate.default || _generate;\n\nconst IMPORT_PATH = 'commandkit';\nconst DIRECTIVE = 'use cache';\nconst CACHE_IDENTIFIER =\n'super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai';\n\nconst generateRandomString = (length = 6) => {\n const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n return Array.from(\n { length },\n () => chars[Math.floor(Math.random() * chars.length)]\n ).join('');\n};\n\nexport const cacheDirectivePlugin = async (source: string, args: any) => {\n const ast = parser.parse(source, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx']\n });\n\n let state = {\n needsImport: false,\n hasExistingImport: false,\n cacheIdentifierName: CACHE_IDENTIFIER,\n modifications: []\n };\n\n // First pass: check for naming collisions and collect modifications\n traverse(ast, {\n Program: {\n enter(path: any) {\n const binding = path.scope.getBinding(CACHE_IDENTIFIER);\n if (binding) {\n state.cacheIdentifierName = `${CACHE_IDENTIFIER}_${generateRandomString()}`;\n }\n }\n },\n\n ImportDeclaration(path: any) {\n if (\n path.node.source.value === IMPORT_PATH &&\n path.node.specifiers.some(\n (spec: any) =>\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER\n ))\n {\n state.hasExistingImport = true;\n if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {\n // @ts-ignore\n state.modifications.push(() => {\n path.node.specifiers.forEach((spec: any) => {\n if (\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER)\n {\n spec.local.name = state.cacheIdentifierName;\n }\n });\n });\n }\n }\n },\n\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(\n path: any)\n {\n const body = t.isBlockStatement(path.node.body) ? path.node.body : null;\n const hasUseCache = body?.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n );\n\n if (!hasUseCache && !t.isBlockStatement(path.node.body)) {\n const parentFunction = path.findParent(\n (p: any) =>\n (p.isFunction() || p.isProgram()) && 'directives' in p.node\n );\n if (\n !parentFunction?.node.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n ))\n {\n return;\n }\n }\n\n if (hasUseCache || !t.isBlockStatement(path.node.body)) {\n // Check if the function is async\n if (!path.node.async) {\n throw new Error(\n `\"${DIRECTIVE}\" directive may only be used in async functions at ${args.path}`\n );\n }\n\n state.needsImport = true;\n const isDeclaration = t.isFunctionDeclaration(path.node);\n const name = isDeclaration ? path.node.id?.name : undefined;\n\n // Create a new body without the 'use cache' directive\n const newBody = t.isBlockStatement(path.node.body) ?\n t.blockStatement(\n path.node.body.body,\n path.node.body.directives.filter(\n (d: any) => d.value.value !== DIRECTIVE\n )\n ) :\n path.node.body;\n\n const wrapped = t.callExpression(\n t.identifier(state.cacheIdentifierName),\n [t.arrowFunctionExpression(path.node.params, newBody, true)]\n );\n\n // @ts-ignore\n state.modifications.push(() => {\n if (name) {\n path.replaceWith(\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(name), wrapped)]\n )\n );\n } else if (!t.isVariableDeclarator(path.parent)) {\n path.replaceWith(wrapped);\n } else {\n path.parent.init = wrapped;\n }\n });\n }\n }\n });\n\n // Apply all collected modifications\n if (state.modifications.length > 0) {\n // Add import if needed\n if (state.needsImport && !state.hasExistingImport) {\n ast.program.body.unshift(\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier(state.cacheIdentifierName),\n t.identifier(CACHE_IDENTIFIER)\n )],\n\n t.stringLiteral(IMPORT_PATH)\n )\n );\n }\n\n // Apply collected modifications\n // @ts-ignore\n state.modifications.forEach((modify) => modify());\n }\n\n const { code } = generate(ast);\n return {\n contents: code,\n loader: args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GlD,GAAM,CAAE,IAAK,EAAI,SAAS,GAAG,EAC7B,MAAO,CACL,SAAU,KACV,OAAQ,KAAK,KAAK,MAAM,GAAG,EAAE,IAAI,CACnC,CACF,EAlJoC","names":[]}
@@ -0,0 +1,2 @@
1
+ import{cacheDirectivePlugin}from"./chunk-Y522NY4J.mjs";import{__name}from"./chunk-35OSBS47.mjs";import{MacroTransformer}from"use-macro";import{readFile}from"node:fs/promises";var defaultConfig={"use-macro":!0,"use-cache":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build.onLoad({filter:fileFilter},async args=>{let source=await readFile(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");export{commandkitPlugin};
2
+ //# sourceMappingURL=chunk-ZCUZ5ENB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/esbuild-plugins/plugin.ts"],"sourcesContent":["import { MacroTransformer } from 'use-macro';\nimport { cacheDirectivePlugin } from './use-cache';\nimport { readFile } from 'node:fs/promises';\n\nconst defaultConfig = {\n 'use-macro': true,\n 'use-cache': true\n};\n\ninterface CommandKitEsbuildPluginConfig {\n 'use-macro'?: boolean;\n 'use-cache'?: boolean;\n}\n\nexport const commandkitPlugin = (config?: CommandKitEsbuildPluginConfig) => {\n config = Object.assign({}, defaultConfig, config);\n\n const plugins = [\n {\n name: 'use-macro',\n plugin: async (content: string, args: any) => {\n const transformer = new MacroTransformer();\n const { contents } = await transformer.transform(content, args.path);\n return contents;\n }\n },\n {\n name: 'use-cache',\n plugin: async (content: string, args: any) => {\n const { contents } = await cacheDirectivePlugin(content, args);\n return contents;\n }\n }].\n filter((p) => {\n return !!config[p.name as keyof CommandKitEsbuildPluginConfig];\n });\n\n return {\n name: 'commandkit-transformer-plugin',\n setup(build: any) {\n if (!plugins.length) return;\n\n const fileFilter = /\\.(c|m)?(t|j)sx?$/;\n\n build.onLoad({ filter: fileFilter }, async (args: any) => {\n const source = await readFile(args.path, 'utf8');\n const loader = args.path.split('.').pop();\n\n let contents = source;\n\n for (const _plugin of plugins) {\n const { plugin, name } = _plugin;\n try {\n contents = await plugin(contents, args);\n } catch (e) {\n const err = new Error(`Plugin ${name} failed with ${e}`);\n err.stack = e instanceof Error ? e.stack : '';\n\n throw err;\n }\n }\n\n return {\n contents,\n loader\n };\n });\n }\n };\n};"],"mappings":"gGAAA,OAAS,qBAAwB,YAEjC,OAAS,aAAgB,mBAEzB,IAAM,cAAgB,CACpB,YAAa,GACb,YAAa,EACf,EAOa,iBAAmB,OAAC,QAA2C,CAC1E,OAAS,OAAO,OAAO,CAAC,EAAG,cAAe,MAAM,EAEhD,IAAM,QAAU,CAChB,CACE,KAAM,YACN,OAAQ,aAAO,QAAiB,OAAc,CAC5C,IAAM,YAAc,IAAI,iBAClB,CAAE,QAAS,EAAI,MAAM,YAAY,UAAU,QAAS,KAAK,IAAI,EACnE,OAAO,QACT,EAJQ,SAKV,EACA,CACE,KAAM,YACN,OAAQ,aAAO,QAAiB,OAAc,CAC5C,GAAM,CAAE,QAAS,EAAI,MAAM,qBAAqB,QAAS,IAAI,EAC7D,OAAO,QACT,EAHQ,SAIV,CAAC,EACD,OAAQ,GACC,CAAC,CAAC,OAAO,EAAE,IAA2C,CAC9D,EAED,MAAO,CACL,KAAM,gCACN,MAAM,MAAY,CAChB,GAAI,CAAC,QAAQ,OAAQ,OAErB,IAAM,WAAa,oBAEnB,MAAM,OAAO,CAAE,OAAQ,UAAW,EAAG,MAAO,MAAc,CACxD,IAAM,OAAS,MAAM,SAAS,KAAK,KAAM,MAAM,EACzC,OAAS,KAAK,KAAK,MAAM,GAAG,EAAE,IAAI,EAEpC,SAAW,OAEf,QAAW,WAAW,QAAS,CAC7B,GAAM,CAAE,OAAQ,IAAK,EAAI,QACzB,GAAI,CACF,SAAW,MAAM,OAAO,SAAU,IAAI,CACxC,OAAS,EAAG,CACV,IAAM,IAAM,IAAI,MAAM,UAAU,IAAI,gBAAgB,CAAC,EAAE,EACvD,UAAI,MAAQ,aAAa,MAAQ,EAAE,MAAQ,GAErC,GACR,CACF,CAEA,MAAO,CACL,SACA,MACF,CACF,CAAC,CACH,CACF,CACF,EAvDgC","names":[]}
@@ -0,0 +1,4 @@
1
+ declare function bootstrapProductionBuild(config: any): Promise<void>;
2
+ declare function injectShims(outDir: string, main: string, antiCrash: boolean, polyfillRequire: boolean): Promise<void>;
3
+
4
+ export { bootstrapProductionBuild, injectShims };
@@ -0,0 +1,4 @@
1
+ declare function bootstrapProductionBuild(config: any): Promise<void>;
2
+ declare function injectShims(outDir: string, main: string, antiCrash: boolean, polyfillRequire: boolean): Promise<void>;
3
+
4
+ export { bootstrapProductionBuild, injectShims };
@@ -0,0 +1,14 @@
1
+ "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var build_exports={};__export(build_exports,{bootstrapProductionBuild:()=>bootstrapProductionBuild,injectShims:()=>injectShims});module.exports=__toCommonJS(build_exports);var import_promises2=require("fs/promises"),import_node_path2=require("path"),import_tsup=require("tsup");var import_rimraf=require("rimraf"),import_node_path=require("path"),import_node_fs=__toESM(require("fs"));var resetColor="\x1B[0m",Colors={reset:__name(text=>`${text}${resetColor}`,"reset"),bright:__name(text=>`\x1B[1m${text}${resetColor}`,"bright"),dim:__name(text=>`\x1B[2m${text}${resetColor}`,"dim"),underscore:__name(text=>`\x1B[4m${text}${resetColor}`,"underscore"),blink:__name(text=>`\x1B[5m${text}${resetColor}`,"blink"),reverse:__name(text=>`\x1B[7m${text}${resetColor}`,"reverse"),hidden:__name(text=>`\x1B[8m${text}${resetColor}`,"hidden"),black:__name(text=>`\x1B[30m${text}${resetColor}`,"black"),red:__name(text=>`\x1B[31m${text}${resetColor}`,"red"),green:__name(text=>`\x1B[32m${text}${resetColor}`,"green"),yellow:__name(text=>`\x1B[33m${text}${resetColor}`,"yellow"),blue:__name(text=>`\x1B[34m${text}${resetColor}`,"blue"),magenta:__name(text=>`\x1B[35m${text}${resetColor}`,"magenta"),cyan:__name(text=>`\x1B[36m${text}${resetColor}`,"cyan"),white:__name(text=>`\x1B[37m${text}${resetColor}`,"white"),bgBlack:__name(text=>`\x1B[40m${text}${resetColor}`,"bgBlack"),bgRed:__name(text=>`\x1B[41m${text}${resetColor}`,"bgRed"),bgGreen:__name(text=>`\x1B[42m${text}${resetColor}`,"bgGreen"),bgYellow:__name(text=>`\x1B[43m${text}${resetColor}`,"bgYellow"),bgBlue:__name(text=>`\x1B[44m${text}${resetColor}`,"bgBlue"),bgMagenta:__name(text=>`\x1B[45m${text}${resetColor}`,"bgMagenta"),bgCyan:__name(text=>`\x1B[46m${text}${resetColor}`,"bgCyan"),bgWhite:__name(text=>`\x1B[47m${text}${resetColor}`,"bgWhite")};function write(message){process.stdout.write(message),process.stdout.write(`
2
+ `)}__name(write,"write");function panic(message){write(Colors.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");var possibleFileNames=["commandkit.json","commandkit.config.json","commandkit.js","commandkit.config.js","commandkit.mjs","commandkit.config.mjs","commandkit.cjs","commandkit.config.cjs","commandkit.ts","commandkit.mts","commandkit.cts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[(0,import_node_path.join)(cwd,src)]:possibleFileNames.map(name=>(0,import_node_path.join)(cwd,name));for(let location of locations)try{return await loadConfigInner(location)}catch{continue}panic(`Could not locate commandkit config from ${cwd}`)}__name(findCommandKitConfig,"findCommandKitConfig");function ensureTypeScript(target){/\.(c|m)tsx?$/.test(target)&&!process.features.typescript&&panic("You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.")}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){let isJSON=target.endsWith(".json");return await ensureExists(target),ensureTypeScript(target),await import(`file://${target}`).then(conf=>conf.default||conf)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){await import_node_fs.default.promises.access(loc,import_node_fs.default.constants.F_OK)}__name(ensureExists,"ensureExists");function erase(dir){(0,import_rimraf.rimrafSync)(dir)}__name(erase,"erase");var import_ora=__toESM(require("ora"));var import_use_macro=require("use-macro");var parser=__toESM(require("@babel/parser")),import_traverse=__toESM(require("@babel/traverse")),import_generator=__toESM(require("@babel/generator")),t=__toESM(require("@babel/types"));var traverse=import_traverse.default.default||import_traverse.default,generate=import_generator.default.default||import_generator.default,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");var import_promises=require("fs/promises");var defaultConfig={"use-macro":!0,"use-cache":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new import_use_macro.MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build2){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build2.onLoad({filter:fileFilter},async args=>{let source=await(0,import_promises.readFile)(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");async function bootstrapProductionBuild(config){let{sourcemap=!1,minify=!1,outDir="dist",antiCrash=!0,src,main,requirePolyfill:polyfillRequire}=await findCommandKitConfig(config),status=(0,import_ora.default)(`Creating optimized production build...
3
+ `).start(),start=performance.now();erase(outDir);try{await(0,import_tsup.build)({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify,shims:!0,banner:{js:"/* Optimized production build generated by CommandKit */"},sourcemap,keepNames:!0,outDir,silent:!0,watch:!1,cjsInterop:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`],esbuildPlugins:[commandkitPlugin()]}),await injectShims(outDir,main,antiCrash,polyfillRequire),status.succeed(Colors.green(`Build completed in ${(performance.now()-start).toFixed(2)}ms!`)),write(Colors.green(`
4
+ Run ${Colors.magenta("commandkit start")} ${Colors.green("to start your bot.")}`))}catch(e){status.fail(`Build failed after ${(performance.now()-start).toFixed(2)}ms!`),panic(e)}}__name(bootstrapProductionBuild,"bootstrapProductionBuild");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=(0,import_node_path2.join)(process.cwd(),outDir,main),head=[`
5
+
6
+ ;await (async()=>{`," 'use strict';"].join(`
7
+ `),tail=`
8
+ })();`,requireScript=polyfillRequire?["// --- CommandKit require() polyfill ---",' if (typeof require === "undefined") {',' const { createRequire } = await import("node:module");'," const __require = createRequire(import.meta.url);",' Object.defineProperty(globalThis, "require", {'," value: (id) => {"," return __require(id);"," },"," configurable: true,"," enumerable: false,"," writable: true,"," });"," }","// --- CommandKit require() polyfill ---"].join(`
9
+ `):"",antiCrashScript=antiCrash?["// --- CommandKit Anti-Crash Monitor ---"," // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process"," // instead of using it as a means to resume operation."," // But it exists here due to compatibility reasons with discord bot ecosystem."," const p = (t) => `\\x1b[33m${t}\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';"," if (!process.eventNames().includes(e1)) // skip if it is already handled"," process.on(e1, (e) => {"," l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));"," })"," if (!process.eventNames().includes(e2)) // skip if it is already handled"," process.on(e2, (r) => {"," l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));"," });","// --- CommandKit Anti-Crash Monitor ---"].join(`
10
+ `):"",contents=await(0,import_promises2.readFile)(path,"utf-8"),finalScript=[head,requireScript,antiCrashScript,tail,`
11
+
12
+ `,contents].join(`
13
+ `);return(0,import_promises2.writeFile)(path,finalScript)}__name(injectShims,"injectShims");0&&(module.exports={bootstrapProductionBuild,injectShims});
14
+ //# sourceMappingURL=build.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cli/build.ts","../../src/cli/common.ts","../../src/cli/esbuild-plugins/plugin.ts","../../src/cli/esbuild-plugins/use-cache.ts"],"sourcesContent":["// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './common.js';\nimport ora from 'ora';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nexport async function bootstrapProductionBuild(config: any) {\n const {\n sourcemap = false,\n minify = false,\n outDir = 'dist',\n antiCrash = true,\n src,\n main,\n requirePolyfill: polyfillRequire\n } = await findCommandKitConfig(config);\n\n const status = ora('Creating optimized production build...\\n').start();\n const start = performance.now();\n\n erase(outDir);\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify,\n shims: true,\n banner: {\n js: '/* Optimized production build generated by CommandKit */'\n },\n sourcemap,\n keepNames: true,\n outDir,\n silent: true,\n watch: false,\n cjsInterop: true,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()]\n });\n\n await injectShims(outDir, main, antiCrash, polyfillRequire);\n\n status.succeed(\n Colors.green(\n `Build completed in ${(performance.now() - start).toFixed(2)}ms!`\n )\n );\n write(\n Colors.green(\n `\\nRun ${Colors.magenta(`commandkit start`)} ${Colors.green(\n 'to start your bot.'\n )}`\n )\n );\n } catch (e) {\n status.fail(\n `Build failed after ${(performance.now() - start).toFixed(2)}ms!`\n );\n panic(e);\n }\n}\n\nexport async function injectShims(\noutDir: string,\nmain: string,\nantiCrash: boolean,\npolyfillRequire: boolean)\n{\n const path = join(process.cwd(), outDir, main);\n\n const head = ['\\n\\n;await (async()=>{', \" 'use strict';\"].join('\\n');\n const tail = '\\n})();';\n const requireScript = polyfillRequire ?\n [\n '// --- CommandKit require() polyfill ---',\n ' if (typeof require === \"undefined\") {',\n ' const { createRequire } = await import(\"node:module\");',\n ' const __require = createRequire(import.meta.url);',\n ' Object.defineProperty(globalThis, \"require\", {',\n ' value: (id) => {',\n ' return __require(id);',\n ' },',\n ' configurable: true,',\n ' enumerable: false,',\n ' writable: true,',\n ' });',\n ' }',\n '// --- CommandKit require() polyfill ---'].\n join('\\n') :\n '';\n\n const antiCrashScript = antiCrash ?\n [\n '// --- CommandKit Anti-Crash Monitor ---',\n \" // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process\",\n ' // instead of using it as a means to resume operation.',\n ' // But it exists here due to compatibility reasons with discord bot ecosystem.',\n \" const p = (t) => `\\\\x1b[33m${t}\\\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';\",\n ' if (!process.eventNames().includes(e1)) // skip if it is already handled',\n ' process.on(e1, (e) => {',\n ' l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));',\n ' })',\n ' if (!process.eventNames().includes(e2)) // skip if it is already handled',\n ' process.on(e2, (r) => {',\n ' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',\n ' });',\n '// --- CommandKit Anti-Crash Monitor ---'].\n join('\\n') :\n '';\n\n const contents = await readFile(path, 'utf-8');\n const finalScript = [\n head,\n requireScript,\n antiCrashScript,\n tail,\n '\\n\\n',\n contents].\n join('\\n');\n\n return writeFile(path, finalScript);\n}","// @ts-check\n\nimport { rimrafSync } from 'rimraf';\nimport { join } from 'node:path';\nimport fs from 'node:fs';\n\nconst resetColor = '\\x1b[0m';\n\nexport const Colors = {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`\n};\n\nexport function write(message: any) {\n process.stdout.write(message);\n process.stdout.write('\\n');\n}\n\n/**\n * @returns {never}\n */\nexport function panic(message: any) {\n write(Colors.red(`Error: ${message}`));\n process.exit(1);\n}\n\nexport function findPackageJSON() {\n const cwd = process.cwd();\n const target = join(cwd, 'package.json');\n\n if (!fs.existsSync(target)) {\n panic('Could not find package.json in current directory.');\n }\n\n return JSON.parse(fs.readFileSync(target, 'utf8'));\n}\n\nconst possibleFileNames = [\n'commandkit.json',\n'commandkit.config.json',\n'commandkit.js',\n'commandkit.config.js',\n'commandkit.mjs',\n'commandkit.config.mjs',\n'commandkit.cjs',\n'commandkit.config.cjs',\n'commandkit.ts',\n'commandkit.mts',\n'commandkit.cts'];\n\n\nexport async function findCommandKitConfig(src: string) {\n const cwd = process.cwd();\n const locations = src ?\n [join(cwd, src)] :\n possibleFileNames.map((name) => join(cwd, name));\n\n for (const location of locations) {\n try {\n return await loadConfigInner(location);\n } catch (e) {\n continue;\n }\n }\n\n panic(`Could not locate commandkit config from ${cwd}`);\n}\n\nfunction ensureTypeScript(target: string) {\n const isTypeScript = /\\.(c|m)tsx?$/.test(target);\n\n if (isTypeScript && !process.features.typescript) {\n panic(\n 'You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.'\n );\n }\n}\n\nasync function loadConfigInner(target: string) {\n const isJSON = target.endsWith('.json');\n\n await ensureExists(target);\n\n ensureTypeScript(target);\n\n /**\n * @type {import('..').CommandKitConfig}\n */\n // @ts-ignore\n const config = await import(`file://${target}`, {\n assert: isJSON ? { type: 'json' } : undefined\n }).then((conf) => conf.default || conf);\n\n return config;\n}\n\nasync function ensureExists(loc: string) {\n await fs.promises.access(loc, fs.constants.F_OK);\n}\n\nexport function erase(dir: string) {\n rimrafSync(dir);\n}","import { MacroTransformer } from 'use-macro';\nimport { cacheDirectivePlugin } from './use-cache';\nimport { readFile } from 'node:fs/promises';\n\nconst defaultConfig = {\n 'use-macro': true,\n 'use-cache': true\n};\n\ninterface CommandKitEsbuildPluginConfig {\n 'use-macro'?: boolean;\n 'use-cache'?: boolean;\n}\n\nexport const commandkitPlugin = (config?: CommandKitEsbuildPluginConfig) => {\n config = Object.assign({}, defaultConfig, config);\n\n const plugins = [\n {\n name: 'use-macro',\n plugin: async (content: string, args: any) => {\n const transformer = new MacroTransformer();\n const { contents } = await transformer.transform(content, args.path);\n return contents;\n }\n },\n {\n name: 'use-cache',\n plugin: async (content: string, args: any) => {\n const { contents } = await cacheDirectivePlugin(content, args);\n return contents;\n }\n }].\n filter((p) => {\n return !!config[p.name as keyof CommandKitEsbuildPluginConfig];\n });\n\n return {\n name: 'commandkit-transformer-plugin',\n setup(build: any) {\n if (!plugins.length) return;\n\n const fileFilter = /\\.(c|m)?(t|j)sx?$/;\n\n build.onLoad({ filter: fileFilter }, async (args: any) => {\n const source = await readFile(args.path, 'utf8');\n const loader = args.path.split('.').pop();\n\n let contents = source;\n\n for (const _plugin of plugins) {\n const { plugin, name } = _plugin;\n try {\n contents = await plugin(contents, args);\n } catch (e) {\n const err = new Error(`Plugin ${name} failed with ${e}`);\n err.stack = e instanceof Error ? e.stack : '';\n\n throw err;\n }\n }\n\n return {\n contents,\n loader\n };\n });\n }\n };\n};","import * as parser from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport _generate from '@babel/generator';\nimport * as t from '@babel/types';\n\n// @ts-ignore\nconst traverse = _traverse.default || _traverse;\n// @ts-ignore\nconst generate = _generate.default || _generate;\n\nconst IMPORT_PATH = 'commandkit';\nconst DIRECTIVE = 'use cache';\nconst CACHE_IDENTIFIER =\n'super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai';\n\nconst generateRandomString = (length = 6) => {\n const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n return Array.from(\n { length },\n () => chars[Math.floor(Math.random() * chars.length)]\n ).join('');\n};\n\nexport const cacheDirectivePlugin = async (source: string, args: any) => {\n const ast = parser.parse(source, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx']\n });\n\n let state = {\n needsImport: false,\n hasExistingImport: false,\n cacheIdentifierName: CACHE_IDENTIFIER,\n modifications: []\n };\n\n // First pass: check for naming collisions and collect modifications\n traverse(ast, {\n Program: {\n enter(path: any) {\n const binding = path.scope.getBinding(CACHE_IDENTIFIER);\n if (binding) {\n state.cacheIdentifierName = `${CACHE_IDENTIFIER}_${generateRandomString()}`;\n }\n }\n },\n\n ImportDeclaration(path: any) {\n if (\n path.node.source.value === IMPORT_PATH &&\n path.node.specifiers.some(\n (spec: any) =>\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER\n ))\n {\n state.hasExistingImport = true;\n if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {\n // @ts-ignore\n state.modifications.push(() => {\n path.node.specifiers.forEach((spec: any) => {\n if (\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER)\n {\n spec.local.name = state.cacheIdentifierName;\n }\n });\n });\n }\n }\n },\n\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(\n path: any)\n {\n const body = t.isBlockStatement(path.node.body) ? path.node.body : null;\n const hasUseCache = body?.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n );\n\n if (!hasUseCache && !t.isBlockStatement(path.node.body)) {\n const parentFunction = path.findParent(\n (p: any) =>\n (p.isFunction() || p.isProgram()) && 'directives' in p.node\n );\n if (\n !parentFunction?.node.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n ))\n {\n return;\n }\n }\n\n if (hasUseCache || !t.isBlockStatement(path.node.body)) {\n // Check if the function is async\n if (!path.node.async) {\n throw new Error(\n `\"${DIRECTIVE}\" directive may only be used in async functions at ${args.path}`\n );\n }\n\n state.needsImport = true;\n const isDeclaration = t.isFunctionDeclaration(path.node);\n const name = isDeclaration ? path.node.id?.name : undefined;\n\n // Create a new body without the 'use cache' directive\n const newBody = t.isBlockStatement(path.node.body) ?\n t.blockStatement(\n path.node.body.body,\n path.node.body.directives.filter(\n (d: any) => d.value.value !== DIRECTIVE\n )\n ) :\n path.node.body;\n\n const wrapped = t.callExpression(\n t.identifier(state.cacheIdentifierName),\n [t.arrowFunctionExpression(path.node.params, newBody, true)]\n );\n\n // @ts-ignore\n state.modifications.push(() => {\n if (name) {\n path.replaceWith(\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(name), wrapped)]\n )\n );\n } else if (!t.isVariableDeclarator(path.parent)) {\n path.replaceWith(wrapped);\n } else {\n path.parent.init = wrapped;\n }\n });\n }\n }\n });\n\n // Apply all collected modifications\n if (state.modifications.length > 0) {\n // Add import if needed\n if (state.needsImport && !state.hasExistingImport) {\n ast.program.body.unshift(\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier(state.cacheIdentifierName),\n t.identifier(CACHE_IDENTIFIER)\n )],\n\n t.stringLiteral(IMPORT_PATH)\n )\n );\n }\n\n // Apply collected modifications\n // @ts-ignore\n state.modifications.forEach((modify) => modify());\n }\n\n const { code } = generate(ast);\n return {\n contents: code,\n loader: args.path.split('.').pop()\n };\n};"],"mappings":"q+BAAA,4KAEA,IAAAA,iBAAoC,uBACpCC,kBAAqB,gBACrB,YAAsB,gBCFtB,kBAA2B,kBAC3B,iBAAqB,gBACrB,eAAe,uBAEf,IAAM,WAAa,UAEN,OAAS,CACpB,MAAO,OAAC,MAAiB,GAAG,IAAI,GAAG,UAAU,GAAtC,SACP,OAAQ,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,UACR,IAAK,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,OACL,WAAY,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,cACZ,MAAO,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,SACP,QAAS,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,WACT,OAAQ,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,UAER,MAAO,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,SACP,IAAK,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,OACL,MAAO,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,SACP,OAAQ,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,UACR,KAAM,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,QACN,QAAS,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,WACT,KAAM,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,QACN,MAAO,OAAC,MAAiB,WAAW,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,CAzDsB,4DA2DtB,eAAsB,YACtB,OACA,KACA,UACA,gBACA,CACE,IAAM,QAAO,wBAAK,QAAQ,IAAI,EAAG,OAAQ,IAAI,EAEvC,KAAO,CAAC;AAAA;AAAA,oBAA0B,iBAAiB,EAAE,KAAK;AAAA,CAAI,EAC9D,KAAO;AAAA,OACP,cAAgB,gBACtB,CACA,2CACA,0CACA,6DACA,wDACA,qDACA,yBACA,gCACA,WACA,4BACA,2BACA,wBACA,UACA,MACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,gBAAkB,UACxB,CACA,2CACA,wHACA,2DACA,mFACA,2JACA,6EACA,8BACA,mEACA,SACA,6EACA,8BACA,gFACA,UACA,0CAA0C,EAC1C,KAAK;AAAA,CAAI,EACT,GAEM,SAAW,QAAM,2BAAS,KAAM,OAAO,EACvC,YAAc,CACpB,KACA,cACA,gBACA,KACA;AAAA;AAAA,EACA,QAAQ,EACR,KAAK;AAAA,CAAI,EAET,SAAO,4BAAU,KAAM,WAAW,CACpC,CA3DsB","names":["import_promises","import_node_path","fs","_traverse","_generate","build","ora"]}
@@ -0,0 +1,2 @@
1
+ import{bootstrapProductionBuild,injectShims}from"../chunk-WZU7OSUV.mjs";import"../chunk-ZCUZ5ENB.mjs";import"../chunk-Y522NY4J.mjs";import"../chunk-FC5WQLBI.mjs";import"../chunk-35OSBS47.mjs";export{bootstrapProductionBuild,injectShims};
2
+ //# sourceMappingURL=build.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,35 @@
1
+ declare const Colors: {
2
+ reset: (text: string) => string;
3
+ bright: (text: string) => string;
4
+ dim: (text: string) => string;
5
+ underscore: (text: string) => string;
6
+ blink: (text: string) => string;
7
+ reverse: (text: string) => string;
8
+ hidden: (text: string) => string;
9
+ black: (text: string) => string;
10
+ red: (text: string) => string;
11
+ green: (text: string) => string;
12
+ yellow: (text: string) => string;
13
+ blue: (text: string) => string;
14
+ magenta: (text: string) => string;
15
+ cyan: (text: string) => string;
16
+ white: (text: string) => string;
17
+ bgBlack: (text: string) => string;
18
+ bgRed: (text: string) => string;
19
+ bgGreen: (text: string) => string;
20
+ bgYellow: (text: string) => string;
21
+ bgBlue: (text: string) => string;
22
+ bgMagenta: (text: string) => string;
23
+ bgCyan: (text: string) => string;
24
+ bgWhite: (text: string) => string;
25
+ };
26
+ declare function write(message: any): void;
27
+ /**
28
+ * @returns {never}
29
+ */
30
+ declare function panic(message: any): void;
31
+ declare function findPackageJSON(): any;
32
+ declare function findCommandKitConfig(src: string): Promise<any>;
33
+ declare function erase(dir: string): void;
34
+
35
+ export { Colors, erase, findCommandKitConfig, findPackageJSON, panic, write };
@@ -0,0 +1,35 @@
1
+ declare const Colors: {
2
+ reset: (text: string) => string;
3
+ bright: (text: string) => string;
4
+ dim: (text: string) => string;
5
+ underscore: (text: string) => string;
6
+ blink: (text: string) => string;
7
+ reverse: (text: string) => string;
8
+ hidden: (text: string) => string;
9
+ black: (text: string) => string;
10
+ red: (text: string) => string;
11
+ green: (text: string) => string;
12
+ yellow: (text: string) => string;
13
+ blue: (text: string) => string;
14
+ magenta: (text: string) => string;
15
+ cyan: (text: string) => string;
16
+ white: (text: string) => string;
17
+ bgBlack: (text: string) => string;
18
+ bgRed: (text: string) => string;
19
+ bgGreen: (text: string) => string;
20
+ bgYellow: (text: string) => string;
21
+ bgBlue: (text: string) => string;
22
+ bgMagenta: (text: string) => string;
23
+ bgCyan: (text: string) => string;
24
+ bgWhite: (text: string) => string;
25
+ };
26
+ declare function write(message: any): void;
27
+ /**
28
+ * @returns {never}
29
+ */
30
+ declare function panic(message: any): void;
31
+ declare function findPackageJSON(): any;
32
+ declare function findCommandKitConfig(src: string): Promise<any>;
33
+ declare function erase(dir: string): void;
34
+
35
+ export { Colors, erase, findCommandKitConfig, findPackageJSON, panic, write };
@@ -0,0 +1,3 @@
1
+ "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var common_exports={};__export(common_exports,{Colors:()=>Colors,erase:()=>erase,findCommandKitConfig:()=>findCommandKitConfig,findPackageJSON:()=>findPackageJSON,panic:()=>panic,write:()=>write});module.exports=__toCommonJS(common_exports);var import_rimraf=require("rimraf"),import_node_path=require("path"),import_node_fs=__toESM(require("fs"));var resetColor="\x1B[0m",Colors={reset:__name(text=>`${text}${resetColor}`,"reset"),bright:__name(text=>`\x1B[1m${text}${resetColor}`,"bright"),dim:__name(text=>`\x1B[2m${text}${resetColor}`,"dim"),underscore:__name(text=>`\x1B[4m${text}${resetColor}`,"underscore"),blink:__name(text=>`\x1B[5m${text}${resetColor}`,"blink"),reverse:__name(text=>`\x1B[7m${text}${resetColor}`,"reverse"),hidden:__name(text=>`\x1B[8m${text}${resetColor}`,"hidden"),black:__name(text=>`\x1B[30m${text}${resetColor}`,"black"),red:__name(text=>`\x1B[31m${text}${resetColor}`,"red"),green:__name(text=>`\x1B[32m${text}${resetColor}`,"green"),yellow:__name(text=>`\x1B[33m${text}${resetColor}`,"yellow"),blue:__name(text=>`\x1B[34m${text}${resetColor}`,"blue"),magenta:__name(text=>`\x1B[35m${text}${resetColor}`,"magenta"),cyan:__name(text=>`\x1B[36m${text}${resetColor}`,"cyan"),white:__name(text=>`\x1B[37m${text}${resetColor}`,"white"),bgBlack:__name(text=>`\x1B[40m${text}${resetColor}`,"bgBlack"),bgRed:__name(text=>`\x1B[41m${text}${resetColor}`,"bgRed"),bgGreen:__name(text=>`\x1B[42m${text}${resetColor}`,"bgGreen"),bgYellow:__name(text=>`\x1B[43m${text}${resetColor}`,"bgYellow"),bgBlue:__name(text=>`\x1B[44m${text}${resetColor}`,"bgBlue"),bgMagenta:__name(text=>`\x1B[45m${text}${resetColor}`,"bgMagenta"),bgCyan:__name(text=>`\x1B[46m${text}${resetColor}`,"bgCyan"),bgWhite:__name(text=>`\x1B[47m${text}${resetColor}`,"bgWhite")};function write(message){process.stdout.write(message),process.stdout.write(`
2
+ `)}__name(write,"write");function panic(message){write(Colors.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");function findPackageJSON(){let cwd=process.cwd(),target=(0,import_node_path.join)(cwd,"package.json");return import_node_fs.default.existsSync(target)||panic("Could not find package.json in current directory."),JSON.parse(import_node_fs.default.readFileSync(target,"utf8"))}__name(findPackageJSON,"findPackageJSON");var possibleFileNames=["commandkit.json","commandkit.config.json","commandkit.js","commandkit.config.js","commandkit.mjs","commandkit.config.mjs","commandkit.cjs","commandkit.config.cjs","commandkit.ts","commandkit.mts","commandkit.cts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[(0,import_node_path.join)(cwd,src)]:possibleFileNames.map(name=>(0,import_node_path.join)(cwd,name));for(let location of locations)try{return await loadConfigInner(location)}catch{continue}panic(`Could not locate commandkit config from ${cwd}`)}__name(findCommandKitConfig,"findCommandKitConfig");function ensureTypeScript(target){/\.(c|m)tsx?$/.test(target)&&!process.features.typescript&&panic("You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.")}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){let isJSON=target.endsWith(".json");return await ensureExists(target),ensureTypeScript(target),await import(`file://${target}`).then(conf=>conf.default||conf)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){await import_node_fs.default.promises.access(loc,import_node_fs.default.constants.F_OK)}__name(ensureExists,"ensureExists");function erase(dir){(0,import_rimraf.rimrafSync)(dir)}__name(erase,"erase");0&&(module.exports={Colors,erase,findCommandKitConfig,findPackageJSON,panic,write});
3
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cli/common.ts"],"sourcesContent":["// @ts-check\n\nimport { rimrafSync } from 'rimraf';\nimport { join } from 'node:path';\nimport fs from 'node:fs';\n\nconst resetColor = '\\x1b[0m';\n\nexport const Colors = {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`\n};\n\nexport function write(message: any) {\n process.stdout.write(message);\n process.stdout.write('\\n');\n}\n\n/**\n * @returns {never}\n */\nexport function panic(message: any) {\n write(Colors.red(`Error: ${message}`));\n process.exit(1);\n}\n\nexport function findPackageJSON() {\n const cwd = process.cwd();\n const target = join(cwd, 'package.json');\n\n if (!fs.existsSync(target)) {\n panic('Could not find package.json in current directory.');\n }\n\n return JSON.parse(fs.readFileSync(target, 'utf8'));\n}\n\nconst possibleFileNames = [\n'commandkit.json',\n'commandkit.config.json',\n'commandkit.js',\n'commandkit.config.js',\n'commandkit.mjs',\n'commandkit.config.mjs',\n'commandkit.cjs',\n'commandkit.config.cjs',\n'commandkit.ts',\n'commandkit.mts',\n'commandkit.cts'];\n\n\nexport async function findCommandKitConfig(src: string) {\n const cwd = process.cwd();\n const locations = src ?\n [join(cwd, src)] :\n possibleFileNames.map((name) => join(cwd, name));\n\n for (const location of locations) {\n try {\n return await loadConfigInner(location);\n } catch (e) {\n continue;\n }\n }\n\n panic(`Could not locate commandkit config from ${cwd}`);\n}\n\nfunction ensureTypeScript(target: string) {\n const isTypeScript = /\\.(c|m)tsx?$/.test(target);\n\n if (isTypeScript && !process.features.typescript) {\n panic(\n 'You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.'\n );\n }\n}\n\nasync function loadConfigInner(target: string) {\n const isJSON = target.endsWith('.json');\n\n await ensureExists(target);\n\n ensureTypeScript(target);\n\n /**\n * @type {import('..').CommandKitConfig}\n */\n // @ts-ignore\n const config = await import(`file://${target}`, {\n assert: isJSON ? { type: 'json' } : undefined\n }).then((conf) => conf.default || conf);\n\n return config;\n}\n\nasync function ensureExists(loc: string) {\n await fs.promises.access(loc, fs.constants.F_OK);\n}\n\nexport function erase(dir: string) {\n rimrafSync(dir);\n}"],"mappings":"q+BAAA,iPAEA,kB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AAI,CAGxC,CAhBe,0CAkBf,eAAe,aAAa,IAAa,CACvC,MAAM,eAAAA,QAAG,SAAS,OAAO,IAAK,eAAAA,QAAG,UAAU,IAAI,CACjD,CAFe,oCAIR,SAAS,MAAM,IAAa,IACjC,0BAAW,GAAG,CAChB,CAFgB","names":["fs"]}
@@ -0,0 +1,2 @@
1
+ import{Colors,erase,findCommandKitConfig,findPackageJSON,panic,write}from"../chunk-FC5WQLBI.mjs";import"../chunk-35OSBS47.mjs";export{Colors,erase,findCommandKitConfig,findPackageJSON,panic,write};
2
+ //# sourceMappingURL=common.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,3 @@
1
+ declare function bootstrapDevelopmentServer(opts: any): Promise<void>;
2
+
3
+ export { bootstrapDevelopmentServer };
@@ -0,0 +1,3 @@
1
+ declare function bootstrapDevelopmentServer(opts: any): Promise<void>;
2
+
3
+ export { bootstrapDevelopmentServer };
@@ -0,0 +1,17 @@
1
+ "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var development_exports={};__export(development_exports,{bootstrapDevelopmentServer:()=>bootstrapDevelopmentServer});module.exports=__toCommonJS(development_exports);var import_dotenv=require("dotenv"),import_node_path3=require("path"),import_tsup2=require("tsup");var import_rimraf=require("rimraf"),import_node_path=require("path"),import_node_fs=__toESM(require("fs"));var resetColor="\x1B[0m",Colors={reset:__name(text=>`${text}${resetColor}`,"reset"),bright:__name(text=>`\x1B[1m${text}${resetColor}`,"bright"),dim:__name(text=>`\x1B[2m${text}${resetColor}`,"dim"),underscore:__name(text=>`\x1B[4m${text}${resetColor}`,"underscore"),blink:__name(text=>`\x1B[5m${text}${resetColor}`,"blink"),reverse:__name(text=>`\x1B[7m${text}${resetColor}`,"reverse"),hidden:__name(text=>`\x1B[8m${text}${resetColor}`,"hidden"),black:__name(text=>`\x1B[30m${text}${resetColor}`,"black"),red:__name(text=>`\x1B[31m${text}${resetColor}`,"red"),green:__name(text=>`\x1B[32m${text}${resetColor}`,"green"),yellow:__name(text=>`\x1B[33m${text}${resetColor}`,"yellow"),blue:__name(text=>`\x1B[34m${text}${resetColor}`,"blue"),magenta:__name(text=>`\x1B[35m${text}${resetColor}`,"magenta"),cyan:__name(text=>`\x1B[36m${text}${resetColor}`,"cyan"),white:__name(text=>`\x1B[37m${text}${resetColor}`,"white"),bgBlack:__name(text=>`\x1B[40m${text}${resetColor}`,"bgBlack"),bgRed:__name(text=>`\x1B[41m${text}${resetColor}`,"bgRed"),bgGreen:__name(text=>`\x1B[42m${text}${resetColor}`,"bgGreen"),bgYellow:__name(text=>`\x1B[43m${text}${resetColor}`,"bgYellow"),bgBlue:__name(text=>`\x1B[44m${text}${resetColor}`,"bgBlue"),bgMagenta:__name(text=>`\x1B[45m${text}${resetColor}`,"bgMagenta"),bgCyan:__name(text=>`\x1B[46m${text}${resetColor}`,"bgCyan"),bgWhite:__name(text=>`\x1B[47m${text}${resetColor}`,"bgWhite")};function write(message){process.stdout.write(message),process.stdout.write(`
2
+ `)}__name(write,"write");function panic(message){write(Colors.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");var possibleFileNames=["commandkit.json","commandkit.config.json","commandkit.js","commandkit.config.js","commandkit.mjs","commandkit.config.mjs","commandkit.cjs","commandkit.config.cjs","commandkit.ts","commandkit.mts","commandkit.cts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[(0,import_node_path.join)(cwd,src)]:possibleFileNames.map(name=>(0,import_node_path.join)(cwd,name));for(let location of locations)try{return await loadConfigInner(location)}catch{continue}panic(`Could not locate commandkit config from ${cwd}`)}__name(findCommandKitConfig,"findCommandKitConfig");function ensureTypeScript(target){/\.(c|m)tsx?$/.test(target)&&!process.features.typescript&&panic("You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.")}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){let isJSON=target.endsWith(".json");return await ensureExists(target),ensureTypeScript(target),await import(`file://${target}`).then(conf=>conf.default||conf)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){await import_node_fs.default.promises.access(loc,import_node_fs.default.constants.F_OK)}__name(ensureExists,"ensureExists");function erase(dir){(0,import_rimraf.rimrafSync)(dir)}__name(erase,"erase");var import_node_crypto=require("crypto");var valuesMap={true:!0,false:!1,null:null,undefined:void 0,__UUIDv4__:__name(()=>(0,import_node_crypto.randomUUID)(),"__UUIDv4__")},VALUE_PREFIXES={JSON:"JSON::",DATE:"DATE::"};function catcher(fn){try{return fn(),!0}catch{return!1}}__name(catcher,"catcher");function parseEnv(src){for(let key in src){let value=src[key];if(typeof value=="string"){if(value.startsWith(VALUE_PREFIXES.JSON)){catcher(()=>src[key]=JSON.parse(value.replace(VALUE_PREFIXES.JSON,"")));continue}if(value.startsWith(VALUE_PREFIXES.DATE)){src[key]=new Date(value.replace(VALUE_PREFIXES.DATE,""));continue}if(value.includes(",")){src[key]=value.split(",").map(v=>v.trim());continue}if(/^[0-9]+n$/.test(value)){src[key]=BigInt(value);continue}if(value in valuesMap){src[key]=typeof valuesMap[value]=="function"?valuesMap[value]():valuesMap[value];continue}}}return src}__name(parseEnv,"parseEnv");var import_node_child_process=__toESM(require("child_process")),import_ora2=__toESM(require("ora"));var import_promises2=require("fs/promises"),import_node_path2=require("path"),import_tsup=require("tsup");var import_ora=__toESM(require("ora"));var import_use_macro=require("use-macro");var parser=__toESM(require("@babel/parser")),import_traverse=__toESM(require("@babel/traverse")),import_generator=__toESM(require("@babel/generator")),t=__toESM(require("@babel/types"));var traverse=import_traverse.default.default||import_traverse.default,generate=import_generator.default.default||import_generator.default,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");var import_promises=require("fs/promises");var defaultConfig={"use-macro":!0,"use-cache":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new import_use_macro.MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build3){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build3.onLoad({filter:fileFilter},async args=>{let source=await(0,import_promises.readFile)(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=(0,import_node_path2.join)(process.cwd(),outDir,main),head=[`
3
+
4
+ ;await (async()=>{`," 'use strict';"].join(`
5
+ `),tail=`
6
+ })();`,requireScript=polyfillRequire?["// --- CommandKit require() polyfill ---",' if (typeof require === "undefined") {',' const { createRequire } = await import("node:module");'," const __require = createRequire(import.meta.url);",' Object.defineProperty(globalThis, "require", {'," value: (id) => {"," return __require(id);"," },"," configurable: true,"," enumerable: false,"," writable: true,"," });"," }","// --- CommandKit require() polyfill ---"].join(`
7
+ `):"",antiCrashScript=antiCrash?["// --- CommandKit Anti-Crash Monitor ---"," // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process"," // instead of using it as a means to resume operation."," // But it exists here due to compatibility reasons with discord bot ecosystem."," const p = (t) => `\\x1b[33m${t}\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';"," if (!process.eventNames().includes(e1)) // skip if it is already handled"," process.on(e1, (e) => {"," l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));"," })"," if (!process.eventNames().includes(e2)) // skip if it is already handled"," process.on(e2, (r) => {"," l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));"," });","// --- CommandKit Anti-Crash Monitor ---"].join(`
8
+ `):"",contents=await(0,import_promises2.readFile)(path,"utf-8"),finalScript=[head,requireScript,antiCrashScript,tail,`
9
+
10
+ `,contents].join(`
11
+ `);return(0,import_promises2.writeFile)(path,finalScript)}__name(injectShims,"injectShims");var RESTARTING_MSG_PATTERN=/^Restarting '|".+'|"\n?$/,FAILED_RUNNING_PATTERN=/^Failed running '.+'|"\n?$/;async function bootstrapDevelopmentServer(opts){let{src,main,watch=!!opts.noWatch,nodeOptions=[],envExtra=!0,clearRestartLogs=!0,outDir,requirePolyfill}=await findCommandKitConfig(opts.config);src||panic("Could not find src in commandkit.json"),main||panic("Could not find main in commandkit.json");let watchMode=watch,status=(0,import_ora2.default)(Colors.green(`Starting a development server...
12
+ `)).start(),start=performance.now();watchMode&&!nodeOptions.includes("--watch")?nodeOptions.push("--watch"):!watchMode&&nodeOptions.includes("--watch")&&nodeOptions.splice(nodeOptions.indexOf("--watch"),1),nodeOptions.includes("--enable-source-maps")||nodeOptions.push("--enable-source-maps"),erase(".commandkit");try{await(0,import_tsup2.build)({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify:!1,shims:!0,sourcemap:"inline",keepNames:!0,outDir:".commandkit",silent:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`].filter(Boolean),watch:watchMode,cjsInterop:!0,async onSuccess(){return await injectShims(".commandkit",main,!1,requirePolyfill)},esbuildPlugins:[commandkitPlugin({"use-macro":!1})]}),status.succeed(Colors.green(`Dev server started in ${(performance.now()-start).toFixed(2)}ms!
13
+ `)),watchMode&&write(Colors.cyan(`Watching for file changes...
14
+ `));let processEnv={},env=(0,import_dotenv.config)({path:(0,import_node_path3.join)(process.cwd(),".env"),processEnv});envExtra&&parseEnv(processEnv),env.error&&write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`)),env.parsed&&write(Colors.blue("[DOTENV] Loaded .env file!"));let ps=import_node_child_process.default.spawn("node",[...nodeOptions,(0,import_node_path3.join)(process.cwd(),".commandkit",main)],{env:{...process.env,...processEnv,NODE_ENV:"development",COMMANDKIT_DEV:!0,COMMANDKIT_PRODUCTION:!1},cwd:process.cwd()}),isLastLogRestarting=!1,hasStarted=!1;ps.stdout.on("data",data=>{let message=data.toString();if(FAILED_RUNNING_PATTERN.test(message)){write(Colors.cyan("Failed running the bot, waiting for changes...")),isLastLogRestarting=!1,hasStarted||(hasStarted=!0);return}if(clearRestartLogs&&!RESTARTING_MSG_PATTERN.test(message))write(message),isLastLogRestarting=!1;else{if(isLastLogRestarting||!hasStarted){hasStarted||(hasStarted=!0);return}write(Colors.cyan("\u2300 Restarting the bot...")),isLastLogRestarting=!0}hasStarted||(hasStarted=!0)}),ps.stderr.on("data",data=>{let message=data.toString();message.includes("ExperimentalWarning: Watch mode is an experimental feature and might change at any time")||write(Colors.red(message))}),ps.on("close",code=>{write(`
15
+ `),process.exit(code??0)}),ps.on("error",err=>{panic(err)})}catch(e){status.fail(`Error occurred after ${(performance.now()-start).toFixed(2)}ms!
16
+ `),panic(e instanceof Error?e.stack:e)}}__name(bootstrapDevelopmentServer,"bootstrapDevelopmentServer");0&&(module.exports={bootstrapDevelopmentServer});
17
+ //# sourceMappingURL=development.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cli/development.ts","../../src/cli/common.ts","../../src/cli/parse-env.ts","../../src/cli/build.ts","../../src/cli/esbuild-plugins/plugin.ts","../../src/cli/esbuild-plugins/use-cache.ts"],"sourcesContent":["// @ts-check\nimport { config as dotenv } from 'dotenv';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './common';\nimport { parseEnv } from './parse-env';\nimport child_process from 'node:child_process';\nimport ora from 'ora';\nimport { injectShims } from './build';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nconst RESTARTING_MSG_PATTERN = /^Restarting '|\".+'|\"\\n?$/;\nconst FAILED_RUNNING_PATTERN = /^Failed running '.+'|\"\\n?$/;\n\nexport async function bootstrapDevelopmentServer(opts: any) {\n const {\n src,\n main,\n watch = Boolean(opts.noWatch),\n nodeOptions = [],\n envExtra = true,\n clearRestartLogs = true,\n outDir,\n requirePolyfill\n } = await findCommandKitConfig(opts.config);\n\n if (!src) {\n panic('Could not find src in commandkit.json');\n }\n\n if (!main) {\n panic('Could not find main in commandkit.json');\n }\n\n const watchMode = watch;\n const status = ora(\n Colors.green('Starting a development server...\\n')\n ).start();\n const start = performance.now();\n\n if (watchMode && !nodeOptions.includes('--watch')) {\n nodeOptions.push('--watch');\n } else if (!watchMode && nodeOptions.includes('--watch')) {\n nodeOptions.splice(nodeOptions.indexOf('--watch'), 1);\n }\n\n if (!nodeOptions.includes('--enable-source-maps')) {\n nodeOptions.push('--enable-source-maps');\n }\n\n erase('.commandkit');\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify: false,\n shims: true,\n sourcemap: 'inline',\n keepNames: true,\n outDir: '.commandkit',\n silent: true,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`].filter(Boolean),\n watch: watchMode,\n cjsInterop: true,\n async onSuccess() {\n return await injectShims('.commandkit', main, false, requirePolyfill);\n },\n esbuildPlugins: [\n commandkitPlugin({\n 'use-macro': false\n })]\n\n });\n\n status.succeed(\n Colors.green(\n `Dev server started in ${(performance.now() - start).toFixed(2)}ms!\\n`\n )\n );\n\n if (watchMode) write(Colors.cyan('Watching for file changes...\\n'));\n\n const processEnv = {};\n\n const env = dotenv({\n path: join(process.cwd(), '.env'),\n processEnv\n });\n\n if (envExtra) {\n parseEnv(processEnv);\n }\n\n if (env.error) {\n write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));\n }\n\n if (env.parsed) {\n write(Colors.blue('[DOTENV] Loaded .env file!'));\n }\n\n const ps: child_process.ChildProcessWithoutNullStreams =\n child_process.spawn(\n 'node',\n [...nodeOptions, join(process.cwd(), '.commandkit', main)],\n {\n env: {\n ...process.env,\n ...processEnv,\n NODE_ENV: 'development',\n // @ts-expect-error\n COMMANDKIT_DEV: true,\n // @ts-expect-error\n COMMANDKIT_PRODUCTION: false\n },\n cwd: process.cwd()\n }\n );\n\n let isLastLogRestarting = false,\n hasStarted = false;\n\n ps.stdout.on('data', (data) => {\n const message = data.toString();\n\n if (FAILED_RUNNING_PATTERN.test(message)) {\n write(Colors.cyan('Failed running the bot, waiting for changes...'));\n isLastLogRestarting = false;\n if (!hasStarted) hasStarted = true;\n return;\n }\n\n if (clearRestartLogs && !RESTARTING_MSG_PATTERN.test(message)) {\n write(message);\n isLastLogRestarting = false;\n } else {\n if (isLastLogRestarting || !hasStarted) {\n if (!hasStarted) hasStarted = true;\n return;\n }\n write(Colors.cyan('⌀ Restarting the bot...'));\n isLastLogRestarting = true;\n }\n\n if (!hasStarted) hasStarted = true;\n });\n\n ps.stderr.on('data', (data) => {\n const message = data.toString();\n\n if (\n message.includes(\n 'ExperimentalWarning: Watch mode is an experimental feature and might change at any time'\n ))\n\n return;\n\n write(Colors.red(message));\n });\n\n ps.on('close', (code) => {\n write('\\n');\n process.exit(code ?? 0);\n });\n\n ps.on('error', (err) => {\n panic(err);\n });\n } catch (e) {\n status.fail(\n `Error occurred after ${(performance.now() - start).toFixed(2)}ms!\\n`\n );\n panic(e instanceof Error ? e.stack : e);\n }\n}","// @ts-check\n\nimport { rimrafSync } from 'rimraf';\nimport { join } from 'node:path';\nimport fs from 'node:fs';\n\nconst resetColor = '\\x1b[0m';\n\nexport const Colors = {\n reset: (text: string) => `${text}${resetColor}`,\n bright: (text: string) => `\\x1b[1m${text}${resetColor}`,\n dim: (text: string) => `\\x1b[2m${text}${resetColor}`,\n underscore: (text: string) => `\\x1b[4m${text}${resetColor}`,\n blink: (text: string) => `\\x1b[5m${text}${resetColor}`,\n reverse: (text: string) => `\\x1b[7m${text}${resetColor}`,\n hidden: (text: string) => `\\x1b[8m${text}${resetColor}`,\n\n black: (text: string) => `\\x1b[30m${text}${resetColor}`,\n red: (text: string) => `\\x1b[31m${text}${resetColor}`,\n green: (text: string) => `\\x1b[32m${text}${resetColor}`,\n yellow: (text: string) => `\\x1b[33m${text}${resetColor}`,\n blue: (text: string) => `\\x1b[34m${text}${resetColor}`,\n magenta: (text: string) => `\\x1b[35m${text}${resetColor}`,\n cyan: (text: string) => `\\x1b[36m${text}${resetColor}`,\n white: (text: string) => `\\x1b[37m${text}${resetColor}`,\n\n bgBlack: (text: string) => `\\x1b[40m${text}${resetColor}`,\n bgRed: (text: string) => `\\x1b[41m${text}${resetColor}`,\n bgGreen: (text: string) => `\\x1b[42m${text}${resetColor}`,\n bgYellow: (text: string) => `\\x1b[43m${text}${resetColor}`,\n bgBlue: (text: string) => `\\x1b[44m${text}${resetColor}`,\n bgMagenta: (text: string) => `\\x1b[45m${text}${resetColor}`,\n bgCyan: (text: string) => `\\x1b[46m${text}${resetColor}`,\n bgWhite: (text: string) => `\\x1b[47m${text}${resetColor}`\n};\n\nexport function write(message: any) {\n process.stdout.write(message);\n process.stdout.write('\\n');\n}\n\n/**\n * @returns {never}\n */\nexport function panic(message: any) {\n write(Colors.red(`Error: ${message}`));\n process.exit(1);\n}\n\nexport function findPackageJSON() {\n const cwd = process.cwd();\n const target = join(cwd, 'package.json');\n\n if (!fs.existsSync(target)) {\n panic('Could not find package.json in current directory.');\n }\n\n return JSON.parse(fs.readFileSync(target, 'utf8'));\n}\n\nconst possibleFileNames = [\n'commandkit.json',\n'commandkit.config.json',\n'commandkit.js',\n'commandkit.config.js',\n'commandkit.mjs',\n'commandkit.config.mjs',\n'commandkit.cjs',\n'commandkit.config.cjs',\n'commandkit.ts',\n'commandkit.mts',\n'commandkit.cts'];\n\n\nexport async function findCommandKitConfig(src: string) {\n const cwd = process.cwd();\n const locations = src ?\n [join(cwd, src)] :\n possibleFileNames.map((name) => join(cwd, name));\n\n for (const location of locations) {\n try {\n return await loadConfigInner(location);\n } catch (e) {\n continue;\n }\n }\n\n panic(`Could not locate commandkit config from ${cwd}`);\n}\n\nfunction ensureTypeScript(target: string) {\n const isTypeScript = /\\.(c|m)tsx?$/.test(target);\n\n if (isTypeScript && !process.features.typescript) {\n panic(\n 'You are trying to load commandkit config file that is written in typescript. The current Node.js version does not have TypeScript feature enabled.'\n );\n }\n}\n\nasync function loadConfigInner(target: string) {\n const isJSON = target.endsWith('.json');\n\n await ensureExists(target);\n\n ensureTypeScript(target);\n\n /**\n * @type {import('..').CommandKitConfig}\n */\n // @ts-ignore\n const config = await import(`file://${target}`, {\n assert: isJSON ? { type: 'json' } : undefined\n }).then((conf) => conf.default || conf);\n\n return config;\n}\n\nasync function ensureExists(loc: string) {\n await fs.promises.access(loc, fs.constants.F_OK);\n}\n\nexport function erase(dir: string) {\n rimrafSync(dir);\n}","// @ts-check\n\nimport { randomUUID } from 'node:crypto';\n\nconst valuesMap = {\n true: true,\n false: false,\n null: null,\n undefined: undefined,\n __UUIDv4__: () => randomUUID()\n};\n\nconst VALUE_PREFIXES = {\n JSON: 'JSON::',\n DATE: 'DATE::'\n};\n\nfunction catcher(fn: Function) {\n try {\n fn();\n return true;\n } catch {\n return false;\n }\n}\n\nexport function parseEnv(src: any) {\n for (const key in src) {\n const value = src[key];\n\n if (typeof value !== 'string') continue;\n\n if (value.startsWith(VALUE_PREFIXES.JSON)) {\n catcher(\n () => src[key] = JSON.parse(value.replace(VALUE_PREFIXES.JSON, ''))\n );\n continue;\n }\n\n if (value.startsWith(VALUE_PREFIXES.DATE)) {\n src[key] = new Date(value.replace(VALUE_PREFIXES.DATE, ''));\n continue;\n }\n\n if (value.includes(',')) {\n src[key] = value.split(',').map((v) => v.trim());\n continue;\n }\n\n if (/^[0-9]+n$/.test(value)) {\n src[key] = BigInt(value);\n continue;\n }\n\n if (value in valuesMap) {\n src[key] =\n // @ts-ignore\n typeof valuesMap[value] === 'function' ?\n // @ts-ignore\n valuesMap[value]() :\n // @ts-ignore\n valuesMap[value];\n continue;\n }\n }\n\n return src;\n}","// @ts-check\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './common.js';\nimport ora from 'ora';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nexport async function bootstrapProductionBuild(config: any) {\n const {\n sourcemap = false,\n minify = false,\n outDir = 'dist',\n antiCrash = true,\n src,\n main,\n requirePolyfill: polyfillRequire\n } = await findCommandKitConfig(config);\n\n const status = ora('Creating optimized production build...\\n').start();\n const start = performance.now();\n\n erase(outDir);\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify,\n shims: true,\n banner: {\n js: '/* Optimized production build generated by CommandKit */'\n },\n sourcemap,\n keepNames: true,\n outDir,\n silent: true,\n watch: false,\n cjsInterop: true,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [commandkitPlugin()]\n });\n\n await injectShims(outDir, main, antiCrash, polyfillRequire);\n\n status.succeed(\n Colors.green(\n `Build completed in ${(performance.now() - start).toFixed(2)}ms!`\n )\n );\n write(\n Colors.green(\n `\\nRun ${Colors.magenta(`commandkit start`)} ${Colors.green(\n 'to start your bot.'\n )}`\n )\n );\n } catch (e) {\n status.fail(\n `Build failed after ${(performance.now() - start).toFixed(2)}ms!`\n );\n panic(e);\n }\n}\n\nexport async function injectShims(\noutDir: string,\nmain: string,\nantiCrash: boolean,\npolyfillRequire: boolean)\n{\n const path = join(process.cwd(), outDir, main);\n\n const head = ['\\n\\n;await (async()=>{', \" 'use strict';\"].join('\\n');\n const tail = '\\n})();';\n const requireScript = polyfillRequire ?\n [\n '// --- CommandKit require() polyfill ---',\n ' if (typeof require === \"undefined\") {',\n ' const { createRequire } = await import(\"node:module\");',\n ' const __require = createRequire(import.meta.url);',\n ' Object.defineProperty(globalThis, \"require\", {',\n ' value: (id) => {',\n ' return __require(id);',\n ' },',\n ' configurable: true,',\n ' enumerable: false,',\n ' writable: true,',\n ' });',\n ' }',\n '// --- CommandKit require() polyfill ---'].\n join('\\n') :\n '';\n\n const antiCrashScript = antiCrash ?\n [\n '// --- CommandKit Anti-Crash Monitor ---',\n \" // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process\",\n ' // instead of using it as a means to resume operation.',\n ' // But it exists here due to compatibility reasons with discord bot ecosystem.',\n \" const p = (t) => `\\\\x1b[33m${t}\\\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';\",\n ' if (!process.eventNames().includes(e1)) // skip if it is already handled',\n ' process.on(e1, (e) => {',\n ' l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));',\n ' })',\n ' if (!process.eventNames().includes(e2)) // skip if it is already handled',\n ' process.on(e2, (r) => {',\n ' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',\n ' });',\n '// --- CommandKit Anti-Crash Monitor ---'].\n join('\\n') :\n '';\n\n const contents = await readFile(path, 'utf-8');\n const finalScript = [\n head,\n requireScript,\n antiCrashScript,\n tail,\n '\\n\\n',\n contents].\n join('\\n');\n\n return writeFile(path, finalScript);\n}","import { MacroTransformer } from 'use-macro';\nimport { cacheDirectivePlugin } from './use-cache';\nimport { readFile } from 'node:fs/promises';\n\nconst defaultConfig = {\n 'use-macro': true,\n 'use-cache': true\n};\n\ninterface CommandKitEsbuildPluginConfig {\n 'use-macro'?: boolean;\n 'use-cache'?: boolean;\n}\n\nexport const commandkitPlugin = (config?: CommandKitEsbuildPluginConfig) => {\n config = Object.assign({}, defaultConfig, config);\n\n const plugins = [\n {\n name: 'use-macro',\n plugin: async (content: string, args: any) => {\n const transformer = new MacroTransformer();\n const { contents } = await transformer.transform(content, args.path);\n return contents;\n }\n },\n {\n name: 'use-cache',\n plugin: async (content: string, args: any) => {\n const { contents } = await cacheDirectivePlugin(content, args);\n return contents;\n }\n }].\n filter((p) => {\n return !!config[p.name as keyof CommandKitEsbuildPluginConfig];\n });\n\n return {\n name: 'commandkit-transformer-plugin',\n setup(build: any) {\n if (!plugins.length) return;\n\n const fileFilter = /\\.(c|m)?(t|j)sx?$/;\n\n build.onLoad({ filter: fileFilter }, async (args: any) => {\n const source = await readFile(args.path, 'utf8');\n const loader = args.path.split('.').pop();\n\n let contents = source;\n\n for (const _plugin of plugins) {\n const { plugin, name } = _plugin;\n try {\n contents = await plugin(contents, args);\n } catch (e) {\n const err = new Error(`Plugin ${name} failed with ${e}`);\n err.stack = e instanceof Error ? e.stack : '';\n\n throw err;\n }\n }\n\n return {\n contents,\n loader\n };\n });\n }\n };\n};","import * as parser from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport _generate from '@babel/generator';\nimport * as t from '@babel/types';\n\n// @ts-ignore\nconst traverse = _traverse.default || _traverse;\n// @ts-ignore\nconst generate = _generate.default || _generate;\n\nconst IMPORT_PATH = 'commandkit';\nconst DIRECTIVE = 'use cache';\nconst CACHE_IDENTIFIER =\n'super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai';\n\nconst generateRandomString = (length = 6) => {\n const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n return Array.from(\n { length },\n () => chars[Math.floor(Math.random() * chars.length)]\n ).join('');\n};\n\nexport const cacheDirectivePlugin = async (source: string, args: any) => {\n const ast = parser.parse(source, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx']\n });\n\n let state = {\n needsImport: false,\n hasExistingImport: false,\n cacheIdentifierName: CACHE_IDENTIFIER,\n modifications: []\n };\n\n // First pass: check for naming collisions and collect modifications\n traverse(ast, {\n Program: {\n enter(path: any) {\n const binding = path.scope.getBinding(CACHE_IDENTIFIER);\n if (binding) {\n state.cacheIdentifierName = `${CACHE_IDENTIFIER}_${generateRandomString()}`;\n }\n }\n },\n\n ImportDeclaration(path: any) {\n if (\n path.node.source.value === IMPORT_PATH &&\n path.node.specifiers.some(\n (spec: any) =>\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER\n ))\n {\n state.hasExistingImport = true;\n if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {\n // @ts-ignore\n state.modifications.push(() => {\n path.node.specifiers.forEach((spec: any) => {\n if (\n t.isImportSpecifier(spec) &&\n // @ts-ignore\n spec.imported.name === CACHE_IDENTIFIER)\n {\n spec.local.name = state.cacheIdentifierName;\n }\n });\n });\n }\n }\n },\n\n 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(\n path: any)\n {\n const body = t.isBlockStatement(path.node.body) ? path.node.body : null;\n const hasUseCache = body?.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n );\n\n if (!hasUseCache && !t.isBlockStatement(path.node.body)) {\n const parentFunction = path.findParent(\n (p: any) =>\n (p.isFunction() || p.isProgram()) && 'directives' in p.node\n );\n if (\n !parentFunction?.node.directives?.some(\n (d: any) => d.value.value === DIRECTIVE\n ))\n {\n return;\n }\n }\n\n if (hasUseCache || !t.isBlockStatement(path.node.body)) {\n // Check if the function is async\n if (!path.node.async) {\n throw new Error(\n `\"${DIRECTIVE}\" directive may only be used in async functions at ${args.path}`\n );\n }\n\n state.needsImport = true;\n const isDeclaration = t.isFunctionDeclaration(path.node);\n const name = isDeclaration ? path.node.id?.name : undefined;\n\n // Create a new body without the 'use cache' directive\n const newBody = t.isBlockStatement(path.node.body) ?\n t.blockStatement(\n path.node.body.body,\n path.node.body.directives.filter(\n (d: any) => d.value.value !== DIRECTIVE\n )\n ) :\n path.node.body;\n\n const wrapped = t.callExpression(\n t.identifier(state.cacheIdentifierName),\n [t.arrowFunctionExpression(path.node.params, newBody, true)]\n );\n\n // @ts-ignore\n state.modifications.push(() => {\n if (name) {\n path.replaceWith(\n t.variableDeclaration('const', [\n t.variableDeclarator(t.identifier(name), wrapped)]\n )\n );\n } else if (!t.isVariableDeclarator(path.parent)) {\n path.replaceWith(wrapped);\n } else {\n path.parent.init = wrapped;\n }\n });\n }\n }\n });\n\n // Apply all collected modifications\n if (state.modifications.length > 0) {\n // Add import if needed\n if (state.needsImport && !state.hasExistingImport) {\n ast.program.body.unshift(\n t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier(state.cacheIdentifierName),\n t.identifier(CACHE_IDENTIFIER)\n )],\n\n t.stringLiteral(IMPORT_PATH)\n )\n );\n }\n\n // Apply collected modifications\n // @ts-ignore\n state.modifications.forEach((modify) => modify());\n }\n\n const { code } = generate(ast);\n return {\n contents: code,\n loader: args.path.split('.').pop()\n };\n};"],"mappings":"q+BAAA,sKACA,kBAAiC,kBACjCA,kBAAqB,gBACrBC,aAAsB,gBCDtB,kBAA2B,kBAC3B,iBAAqB,gBACrB,eAAe,uBAEf,IAAM,WAAa,UAEN,OAAS,CACpB,MAAO,OAAC,MAAiB,GAAG,IAAI,GAAG,UAAU,GAAtC,SACP,OAAQ,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,UACR,IAAK,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,OACL,WAAY,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,cACZ,MAAO,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,SACP,QAAS,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,WACT,OAAQ,OAAC,MAAiB,UAAU,IAAI,GAAG,UAAU,GAA7C,UAER,MAAO,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,SACP,IAAK,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,OACL,MAAO,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,SACP,OAAQ,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,UACR,KAAM,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,QACN,QAAS,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,WACT,KAAM,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,QACN,MAAO,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,SAEP,QAAS,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,WACT,MAAO,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9C,SACP,QAAS,OAAC,MAAiB,WAAW,IAAI,GAAG,UAAU,GAA9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,WAAa,IAC9B,MACF,CAEA,GAAI,kBAAoB,CAAC,uBAAuB,KAAK,OAAO,EAC1D,MAAM,OAAO,EACb,oBAAsB,OACjB,CACL,GAAI,qBAAuB,CAAC,WAAY,CACjC,aAAY,WAAa,IAC9B,MACF,CACA,MAAM,OAAO,KAAK,8BAAyB,CAAC,EAC5C,oBAAsB,EACxB,CAEK,aAAY,WAAa,GAChC,CAAC,EAED,GAAG,OAAO,GAAG,OAAS,MAAS,CAC7B,IAAM,QAAU,KAAK,SAAS,EAG9B,QAAQ,SACN,yFACF,GAIA,MAAM,OAAO,IAAI,OAAO,CAAC,CAC3B,CAAC,EAED,GAAG,GAAG,QAAU,MAAS,CACvB,MAAM;AAAA,CAAI,EACV,QAAQ,KAAK,MAAQ,CAAC,CACxB,CAAC,EAED,GAAG,GAAG,QAAU,KAAQ,CACtB,MAAM,GAAG,CACX,CAAC,CACH,OAAS,EAAG,CACV,OAAO,KACL,yBAAyB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC;AAAA,CAChE,EACA,MAAM,aAAa,MAAQ,EAAE,MAAQ,CAAC,CACxC,CACF,CAnKsB","names":["import_node_path","import_tsup","fs","import_ora","import_promises","import_node_path","_traverse","_generate","build","ora","dotenv","child_process"]}
@@ -0,0 +1,7 @@
1
+ import{injectShims}from"../chunk-WZU7OSUV.mjs";import{commandkitPlugin}from"../chunk-ZCUZ5ENB.mjs";import"../chunk-Y522NY4J.mjs";import{Colors,erase,findCommandKitConfig,panic,write}from"../chunk-FC5WQLBI.mjs";import{parseEnv}from"../chunk-RQ3ABUE3.mjs";import{__name}from"../chunk-35OSBS47.mjs";import{config as dotenv}from"dotenv";import{join}from"node:path";import{build}from"tsup";import child_process from"node:child_process";import ora from"ora";var RESTARTING_MSG_PATTERN=/^Restarting '|".+'|"\n?$/,FAILED_RUNNING_PATTERN=/^Failed running '.+'|"\n?$/;async function bootstrapDevelopmentServer(opts){let{src,main,watch=!!opts.noWatch,nodeOptions=[],envExtra=!0,clearRestartLogs=!0,outDir,requirePolyfill}=await findCommandKitConfig(opts.config);src||panic("Could not find src in commandkit.json"),main||panic("Could not find main in commandkit.json");let watchMode=watch,status=ora(Colors.green(`Starting a development server...
2
+ `)).start(),start=performance.now();watchMode&&!nodeOptions.includes("--watch")?nodeOptions.push("--watch"):!watchMode&&nodeOptions.includes("--watch")&&nodeOptions.splice(nodeOptions.indexOf("--watch"),1),nodeOptions.includes("--enable-source-maps")||nodeOptions.push("--enable-source-maps"),erase(".commandkit");try{await build({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify:!1,shims:!0,sourcemap:"inline",keepNames:!0,outDir:".commandkit",silent:!0,entry:[src,"!dist","!.commandkit",`!${outDir}`].filter(Boolean),watch:watchMode,cjsInterop:!0,async onSuccess(){return await injectShims(".commandkit",main,!1,requirePolyfill)},esbuildPlugins:[commandkitPlugin({"use-macro":!1})]}),status.succeed(Colors.green(`Dev server started in ${(performance.now()-start).toFixed(2)}ms!
3
+ `)),watchMode&&write(Colors.cyan(`Watching for file changes...
4
+ `));let processEnv={},env=dotenv({path:join(process.cwd(),".env"),processEnv});envExtra&&parseEnv(processEnv),env.error&&write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`)),env.parsed&&write(Colors.blue("[DOTENV] Loaded .env file!"));let ps=child_process.spawn("node",[...nodeOptions,join(process.cwd(),".commandkit",main)],{env:{...process.env,...processEnv,NODE_ENV:"development",COMMANDKIT_DEV:!0,COMMANDKIT_PRODUCTION:!1},cwd:process.cwd()}),isLastLogRestarting=!1,hasStarted=!1;ps.stdout.on("data",data=>{let message=data.toString();if(FAILED_RUNNING_PATTERN.test(message)){write(Colors.cyan("Failed running the bot, waiting for changes...")),isLastLogRestarting=!1,hasStarted||(hasStarted=!0);return}if(clearRestartLogs&&!RESTARTING_MSG_PATTERN.test(message))write(message),isLastLogRestarting=!1;else{if(isLastLogRestarting||!hasStarted){hasStarted||(hasStarted=!0);return}write(Colors.cyan("\u2300 Restarting the bot...")),isLastLogRestarting=!0}hasStarted||(hasStarted=!0)}),ps.stderr.on("data",data=>{let message=data.toString();message.includes("ExperimentalWarning: Watch mode is an experimental feature and might change at any time")||write(Colors.red(message))}),ps.on("close",code=>{write(`
5
+ `),process.exit(code??0)}),ps.on("error",err=>{panic(err)})}catch(e){status.fail(`Error occurred after ${(performance.now()-start).toFixed(2)}ms!
6
+ `),panic(e instanceof Error?e.stack:e)}}__name(bootstrapDevelopmentServer,"bootstrapDevelopmentServer");export{bootstrapDevelopmentServer};
7
+ //# sourceMappingURL=development.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cli/development.ts"],"sourcesContent":["// @ts-check\nimport { config as dotenv } from 'dotenv';\nimport { join } from 'node:path';\nimport { build } from 'tsup';\nimport { Colors, erase, findCommandKitConfig, panic, write } from './common';\nimport { parseEnv } from './parse-env';\nimport child_process from 'node:child_process';\nimport ora from 'ora';\nimport { injectShims } from './build';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\n\nconst RESTARTING_MSG_PATTERN = /^Restarting '|\".+'|\"\\n?$/;\nconst FAILED_RUNNING_PATTERN = /^Failed running '.+'|\"\\n?$/;\n\nexport async function bootstrapDevelopmentServer(opts: any) {\n const {\n src,\n main,\n watch = Boolean(opts.noWatch),\n nodeOptions = [],\n envExtra = true,\n clearRestartLogs = true,\n outDir,\n requirePolyfill\n } = await findCommandKitConfig(opts.config);\n\n if (!src) {\n panic('Could not find src in commandkit.json');\n }\n\n if (!main) {\n panic('Could not find main in commandkit.json');\n }\n\n const watchMode = watch;\n const status = ora(\n Colors.green('Starting a development server...\\n')\n ).start();\n const start = performance.now();\n\n if (watchMode && !nodeOptions.includes('--watch')) {\n nodeOptions.push('--watch');\n } else if (!watchMode && nodeOptions.includes('--watch')) {\n nodeOptions.splice(nodeOptions.indexOf('--watch'), 1);\n }\n\n if (!nodeOptions.includes('--enable-source-maps')) {\n nodeOptions.push('--enable-source-maps');\n }\n\n erase('.commandkit');\n\n try {\n await build({\n clean: true,\n format: ['esm'],\n dts: false,\n skipNodeModulesBundle: true,\n minify: false,\n shims: true,\n sourcemap: 'inline',\n keepNames: true,\n outDir: '.commandkit',\n silent: true,\n entry: [src, '!dist', '!.commandkit', `!${outDir}`].filter(Boolean),\n watch: watchMode,\n cjsInterop: true,\n async onSuccess() {\n return await injectShims('.commandkit', main, false, requirePolyfill);\n },\n esbuildPlugins: [\n commandkitPlugin({\n 'use-macro': false\n })]\n\n });\n\n status.succeed(\n Colors.green(\n `Dev server started in ${(performance.now() - start).toFixed(2)}ms!\\n`\n )\n );\n\n if (watchMode) write(Colors.cyan('Watching for file changes...\\n'));\n\n const processEnv = {};\n\n const env = dotenv({\n path: join(process.cwd(), '.env'),\n processEnv\n });\n\n if (envExtra) {\n parseEnv(processEnv);\n }\n\n if (env.error) {\n write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));\n }\n\n if (env.parsed) {\n write(Colors.blue('[DOTENV] Loaded .env file!'));\n }\n\n const ps: child_process.ChildProcessWithoutNullStreams =\n child_process.spawn(\n 'node',\n [...nodeOptions, join(process.cwd(), '.commandkit', main)],\n {\n env: {\n ...process.env,\n ...processEnv,\n NODE_ENV: 'development',\n // @ts-expect-error\n COMMANDKIT_DEV: true,\n // @ts-expect-error\n COMMANDKIT_PRODUCTION: false\n },\n cwd: process.cwd()\n }\n );\n\n let isLastLogRestarting = false,\n hasStarted = false;\n\n ps.stdout.on('data', (data) => {\n const message = data.toString();\n\n if (FAILED_RUNNING_PATTERN.test(message)) {\n write(Colors.cyan('Failed running the bot, waiting for changes...'));\n isLastLogRestarting = false;\n if (!hasStarted) hasStarted = true;\n return;\n }\n\n if (clearRestartLogs && !RESTARTING_MSG_PATTERN.test(message)) {\n write(message);\n isLastLogRestarting = false;\n } else {\n if (isLastLogRestarting || !hasStarted) {\n if (!hasStarted) hasStarted = true;\n return;\n }\n write(Colors.cyan('⌀ Restarting the bot...'));\n isLastLogRestarting = true;\n }\n\n if (!hasStarted) hasStarted = true;\n });\n\n ps.stderr.on('data', (data) => {\n const message = data.toString();\n\n if (\n message.includes(\n 'ExperimentalWarning: Watch mode is an experimental feature and might change at any time'\n ))\n\n return;\n\n write(Colors.red(message));\n });\n\n ps.on('close', (code) => {\n write('\\n');\n process.exit(code ?? 0);\n });\n\n ps.on('error', (err) => {\n panic(err);\n });\n } catch (e) {\n status.fail(\n `Error occurred after ${(performance.now() - start).toFixed(2)}ms!\\n`\n );\n panic(e instanceof Error ? e.stack : e);\n }\n}"],"mappings":"wSACA,OAAS,UAAU,WAAc,SACjC,OAAS,SAAY,YACrB,OAAS,UAAa,OAGtB,OAAO,kBAAmB,qBAC1B,OAAO,QAAS,MAIhB,IAAM,uBAAyB,2BACzB,uBAAyB,6BAE/B,eAAsB,2BAA2B,KAAW,CAC1D,GAAM,CACJ,IACA,KACA,MAAQ,EAAQ,KAAK,QACrB,YAAc,CAAC,EACf,SAAW,GACX,iBAAmB,GACnB,OACA,eACF,EAAI,MAAM,qBAAqB,KAAK,MAAM,EAErC,KACH,MAAM,uCAAuC,EAG1C,MACH,MAAM,wCAAwC,EAGhD,IAAM,UAAY,MACZ,OAAS,IACb,OAAO,MAAM;AAAA,CAAoC,CACnD,EAAE,MAAM,EACF,MAAQ,YAAY,IAAI,EAE1B,WAAa,CAAC,YAAY,SAAS,SAAS,EAC9C,YAAY,KAAK,SAAS,EACjB,CAAC,WAAa,YAAY,SAAS,SAAS,GACrD,YAAY,OAAO,YAAY,QAAQ,SAAS,EAAG,CAAC,EAGjD,YAAY,SAAS,sBAAsB,GAC9C,YAAY,KAAK,sBAAsB,EAGzC,MAAM,aAAa,EAEnB,GAAI,CACF,MAAM,MAAM,CACV,MAAO,GACP,OAAQ,CAAC,KAAK,EACd,IAAK,GACL,sBAAuB,GACvB,OAAQ,GACR,MAAO,GACP,UAAW,SACX,UAAW,GACX,OAAQ,cACR,OAAQ,GACR,MAAO,CAAC,IAAK,QAAS,eAAgB,IAAI,MAAM,EAAE,EAAE,OAA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C,CAAC,EAED,GAAG,OAAO,GAAG,OAAS,MAAS,CAC7B,IAAM,QAAU,KAAK,SAAS,EAG9B,QAAQ,SACN,yFACF,GAIA,MAAM,OAAO,IAAI,OAAO,CAAC,CAC3B,CAAC,EAED,GAAG,GAAG,QAAU,MAAS,CACvB,MAAM;AAAA,CAAI,EACV,QAAQ,KAAK,MAAQ,CAAC,CACxB,CAAC,EAED,GAAG,GAAG,QAAU,KAAQ,CACtB,MAAM,GAAG,CACX,CAAC,CACH,OAAS,EAAG,CACV,OAAO,KACL,yBAAyB,YAAY,IAAI,EAAI,OAAO,QAAQ,CAAC,CAAC;AAAA,CAChE,EACA,MAAM,aAAa,MAAQ,EAAE,MAAQ,CAAC,CACxC,CACF,CAnKsB","names":[]}
@@ -0,0 +1,10 @@
1
+ interface CommandKitEsbuildPluginConfig {
2
+ 'use-macro'?: boolean;
3
+ 'use-cache'?: boolean;
4
+ }
5
+ declare const commandkitPlugin: (config?: CommandKitEsbuildPluginConfig) => {
6
+ name: string;
7
+ setup(build: any): void;
8
+ };
9
+
10
+ export { commandkitPlugin };
@@ -0,0 +1,10 @@
1
+ interface CommandKitEsbuildPluginConfig {
2
+ 'use-macro'?: boolean;
3
+ 'use-cache'?: boolean;
4
+ }
5
+ declare const commandkitPlugin: (config?: CommandKitEsbuildPluginConfig) => {
6
+ name: string;
7
+ setup(build: any): void;
8
+ };
9
+
10
+ export { commandkitPlugin };
@@ -0,0 +1,2 @@
1
+ "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var plugin_exports={};__export(plugin_exports,{commandkitPlugin:()=>commandkitPlugin});module.exports=__toCommonJS(plugin_exports);var import_use_macro=require("use-macro");var parser=__toESM(require("@babel/parser")),import_traverse=__toESM(require("@babel/traverse")),import_generator=__toESM(require("@babel/generator")),t=__toESM(require("@babel/types"));var traverse=import_traverse.default.default||import_traverse.default,generate=import_generator.default.default||import_generator.default,IMPORT_PATH="commandkit",DIRECTIVE="use cache",CACHE_IDENTIFIER="super_duper_secret_internal_for_use_cache_directive_of_commandkit_cli_do_not_use_it_directly_or_you_will_be_fired_from_your_job_kthxbai",generateRandomString=__name((length=6)=>{let chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";return Array.from({length},()=>chars[Math.floor(Math.random()*chars.length)]).join("")},"generateRandomString"),cacheDirectivePlugin=__name(async(source,args)=>{let ast=parser.parse(source,{sourceType:"module",plugins:["typescript","jsx"]}),state={needsImport:!1,hasExistingImport:!1,cacheIdentifierName:CACHE_IDENTIFIER,modifications:[]};traverse(ast,{Program:{enter(path){path.scope.getBinding(CACHE_IDENTIFIER)&&(state.cacheIdentifierName=`${CACHE_IDENTIFIER}_${generateRandomString()}`)}},ImportDeclaration(path){path.node.source.value===IMPORT_PATH&&path.node.specifiers.some(spec=>t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER)&&(state.hasExistingImport=!0,state.cacheIdentifierName!==CACHE_IDENTIFIER&&state.modifications.push(()=>{path.node.specifiers.forEach(spec=>{t.isImportSpecifier(spec)&&spec.imported.name===CACHE_IDENTIFIER&&(spec.local.name=state.cacheIdentifierName)})}))},"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(path){var _a,_b,_c;let body=t.isBlockStatement(path.node.body)?path.node.body:null,hasUseCache=(_a=body==null?void 0:body.directives)==null?void 0:_a.some(d=>d.value.value===DIRECTIVE);if(!hasUseCache&&!t.isBlockStatement(path.node.body)){let parentFunction=path.findParent(p=>(p.isFunction()||p.isProgram())&&"directives"in p.node);if(!((_b=parentFunction==null?void 0:parentFunction.node.directives)!=null&&_b.some(d=>d.value.value===DIRECTIVE)))return}if(hasUseCache||!t.isBlockStatement(path.node.body)){if(!path.node.async)throw new Error(`"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`);state.needsImport=!0;let name=t.isFunctionDeclaration(path.node)?(_c=path.node.id)==null?void 0:_c.name:void 0,newBody=t.isBlockStatement(path.node.body)?t.blockStatement(path.node.body.body,path.node.body.directives.filter(d=>d.value.value!==DIRECTIVE)):path.node.body,wrapped=t.callExpression(t.identifier(state.cacheIdentifierName),[t.arrowFunctionExpression(path.node.params,newBody,!0)]);state.modifications.push(()=>{name?path.replaceWith(t.variableDeclaration("const",[t.variableDeclarator(t.identifier(name),wrapped)])):t.isVariableDeclarator(path.parent)?path.parent.init=wrapped:path.replaceWith(wrapped)})}}}),state.modifications.length>0&&(state.needsImport&&!state.hasExistingImport&&ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(state.cacheIdentifierName),t.identifier(CACHE_IDENTIFIER))],t.stringLiteral(IMPORT_PATH))),state.modifications.forEach(modify=>modify()));let{code}=generate(ast);return{contents:code,loader:args.path.split(".").pop()}},"cacheDirectivePlugin");var import_promises=require("fs/promises");var defaultConfig={"use-macro":!0,"use-cache":!0},commandkitPlugin=__name(config=>{config=Object.assign({},defaultConfig,config);let plugins=[{name:"use-macro",plugin:__name(async(content,args)=>{let transformer=new import_use_macro.MacroTransformer,{contents}=await transformer.transform(content,args.path);return contents},"plugin")},{name:"use-cache",plugin:__name(async(content,args)=>{let{contents}=await cacheDirectivePlugin(content,args);return contents},"plugin")}].filter(p=>!!config[p.name]);return{name:"commandkit-transformer-plugin",setup(build){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build.onLoad({filter:fileFilter},async args=>{let source=await(0,import_promises.readFile)(args.path,"utf8"),loader=args.path.split(".").pop(),contents=source;for(let _plugin of plugins){let{plugin,name}=_plugin;try{contents=await plugin(contents,args)}catch(e){let err=new Error(`Plugin ${name} failed with ${e}`);throw err.stack=e instanceof Error?e.stack:"",err}}return{contents,loader}})}}},"commandkitPlugin");0&&(module.exports={commandkitPlugin});
2
+ //# sourceMappingURL=plugin.js.map