commandkit 0.1.11-dev.20250216075349 → 0.1.11-dev.20250216141351
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.
- package/dist/build-5WDRAFIL.mjs +2 -0
- package/dist/build-5WDRAFIL.mjs.map +1 -0
- package/dist/chunk-NAFN6ATB.mjs +3 -0
- package/dist/chunk-NAFN6ATB.mjs.map +1 -0
- package/dist/chunk-PSR46ODG.mjs +3 -0
- package/dist/chunk-PSR46ODG.mjs.map +1 -0
- package/dist/chunk-RPTZYNBM.mjs +2 -0
- package/dist/chunk-RPTZYNBM.mjs.map +1 -0
- package/dist/chunk-UCPCQQQH.mjs +15 -0
- package/dist/chunk-UCPCQQQH.mjs.map +1 -0
- package/dist/development-5QKAE4EE.mjs +4 -0
- package/dist/development-5QKAE4EE.mjs.map +1 -0
- package/dist/generators-OG3OGOCO.mjs +21 -0
- package/dist/generators-OG3OGOCO.mjs.map +1 -0
- package/dist/index.d.mts +1 -3
- package/dist/index.d.ts +1 -3
- package/dist/index.js +12 -11
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -42
- package/dist/index.mjs.map +1 -1
- package/dist/production-53LVW6PE.mjs +3 -0
- package/dist/production-53LVW6PE.mjs.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{bootstrapDevelopmentBuild,bootstrapProductionBuild,injectShims}from"./chunk-UCPCQQQH.mjs";import"./chunk-PSR46ODG.mjs";import"./chunk-NAFN6ATB.mjs";import"./chunk-RPTZYNBM.mjs";export{bootstrapDevelopmentBuild,bootstrapProductionBuild,injectShims};
|
|
2
|
+
//# sourceMappingURL=build-5WDRAFIL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{__name,colors_default}from"./chunk-RPTZYNBM.mjs";import{rimrafSync}from"rimraf";import{join}from"node:path";import fs from"node:fs";var ts;function write(message){process.stdout.write(message),process.stdout.write(`
|
|
2
|
+
`)}__name(write,"write");function panic(message){write(colors_default.red(`Error: ${message}`)),process.exit(1)}__name(panic,"panic");var possibleFileNames=["commandkit.js","commandkit.mjs","commandkit.cjs","commandkit.ts"];async function findCommandKitConfig(src){let cwd=process.cwd(),locations=src?[join(cwd,src)]:possibleFileNames.map(name=>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");async function ensureTypeScript(target){if(!/\.(c|m)?tsx?$/.test(target))return!1;if(process.features.typescript)return!0;if(!ts)try{ts=await import("typescript")}catch{panic("TypeScript must be installed to use TypeScript config files.")}return!0}__name(ensureTypeScript,"ensureTypeScript");async function loadConfigInner(target){if(await ensureExists(target),await ensureTypeScript(target)&&ts){let{transpileModule}=ts,src=fs.readFileSync(target,"utf8"),{outputText}=transpileModule(src,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ESNext,moduleResolution:ts.ModuleResolutionKind.NodeNext},fileName:target}),nodeModulesPath=join(process.cwd(),"node_modules",".commandkit_tmp");fs.mkdirSync(nodeModulesPath,{recursive:!0});let tmpFile=join(nodeModulesPath,"compiled-commandkit.config.mjs");fs.writeFileSync(tmpFile,outputText),target=tmpFile}return await import(`file://${target}`).then(conf=>conf.default||conf).catch(console.log)}__name(loadConfigInner,"loadConfigInner");async function ensureExists(loc){if(!fs.existsSync(loc))throw new Error(`File not found: ${loc}`)}__name(ensureExists,"ensureExists");function erase(dir){rimrafSync(dir)}__name(erase,"erase");async function copyLocaleFiles(_from,_to){let resolvedFrom=join(process.cwd(),_from),resolvedTo=join(process.cwd(),_to),localePaths=["app/locales"],srcLocalePaths=localePaths.map(path=>join(resolvedFrom,path)),destLocalePaths=localePaths.map(path=>join(resolvedTo,path));for(let localePath of srcLocalePaths){if(!fs.existsSync(localePath))continue;let destLocalePath=destLocalePaths[srcLocalePaths.indexOf(localePath)];fs.existsSync(destLocalePath)||fs.promises.mkdir(destLocalePath,{recursive:!0}),await fs.promises.cp(localePath,destLocalePath,{recursive:!0,force:!0})}}__name(copyLocaleFiles,"copyLocaleFiles");export{write,panic,findCommandKitConfig,erase,copyLocaleFiles};
|
|
3
|
+
//# sourceMappingURL=chunk-NAFN6ATB.mjs.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';\nimport colors from '../utils/colors';\n\nlet ts: typeof import('typescript') | undefined;\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): never {\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.js',\n'commandkit.mjs',\n'commandkit.cjs',\n'commandkit.ts'];\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\nasync function ensureTypeScript(target: string) {\n const isTypeScript = /\\.(c|m)?tsx?$/.test(target);\n\n if (!isTypeScript) return false;\n if (process.features.typescript) return true;\n\n if (!ts) {\n try {\n ts = await import('typescript');\n } catch {\n panic('TypeScript must be installed to use TypeScript config files.');\n }\n }\n\n return true;\n}\n\nasync function loadConfigInner(target: string) {\n await ensureExists(target);\n\n const isTs = await ensureTypeScript(target);\n\n if (isTs && ts) {\n const { transpileModule } = ts;\n const src = fs.readFileSync(target, 'utf8');\n const { outputText } = transpileModule(src, {\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ESNext,\n moduleResolution: ts.ModuleResolutionKind.NodeNext\n },\n fileName: target\n });\n\n const nodeModulesPath = join(\n process.cwd(),\n 'node_modules',\n '.commandkit_tmp'\n );\n\n fs.mkdirSync(nodeModulesPath, { recursive: true });\n\n const tmpFile = join(nodeModulesPath, 'compiled-commandkit.config.mjs');\n\n fs.writeFileSync(tmpFile, outputText);\n\n target = tmpFile;\n }\n\n /**\n * @type {import('..').CommandKitConfig}\n */\n const config = await import(`file://${target}`).\n then((conf) => conf.default || conf).\n catch(console.log);\n\n return config;\n}\n\nasync function ensureExists(loc: string) {\n const exists = fs.existsSync(loc);\n\n if (!exists) {\n throw new Error(`File not found: ${loc}`);\n }\n}\n\nexport function erase(dir: string) {\n rimrafSync(dir);\n}\n\nexport async function copyLocaleFiles(_from: string, _to: string) {\n const resolvedFrom = join(process.cwd(), _from);\n const resolvedTo = join(process.cwd(), _to);\n\n const localePaths = ['app/locales'];\n const srcLocalePaths = localePaths.map((path) => join(resolvedFrom, path));\n const destLocalePaths = localePaths.map((path) => join(resolvedTo, path));\n\n for (const localePath of srcLocalePaths) {\n if (!fs.existsSync(localePath)) {\n continue;\n }\n\n // copy localePath to destLocalePath\n const destLocalePath = destLocalePaths[srcLocalePaths.indexOf(localePath)];\n\n if (!fs.existsSync(destLocalePath)) {\n fs.promises.mkdir(destLocalePath, { recursive: true });\n }\n\n await fs.promises.cp(localePath, destLocalePath, {\n recursive: true,\n force: true\n });\n }\n}"],"mappings":"wDAEA,OAAS,eAAkB,SAC3B,OAAS,SAAY,YACrB,OAAO,OAAQ,UAGf,IAAI,GAEG,SAAS,MAAM,QAAc,CAClC,QAAQ,OAAO,MAAM,OAAO,EAC5B,QAAQ,OAAO,MAAM;AAAA,CAAI,CAC3B,CAHgB,sBAQT,SAA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AO,UAAU,MAAM,IAC5C,KAAM,MAAS,KAAK,SAAW,IAAI,EACnC,MAAM,QAAQ,GAAG,CAGnB,CAxCe,0CA0Cf,eAAe,aAAa,IAAa,CAGvC,GAAI,CAFW,GAAG,WAAW,GAAG,EAG9B,MAAM,IAAI,MAAM,mBAAmB,GAAG,EAAE,CAE5C,CANe,oCAQR,SAAS,MAAM,IAAa,CACjC,WAAW,GAAG,CAChB,CAFgB,sBAIhB,eAAsB,gBAAgB,MAAe,IAAa,CAChE,IAAM,aAAe,KAAK,QAAQ,IAAI,EAAG,KAAK,EACxC,WAAa,KAAK,QAAQ,IAAI,EAAG,GAAG,EAEpC,YAAc,CAAC,aAAa,EAC5B,eAAiB,YAAY,IAAK,MAAS,KAAK,aAAc,IAAI,CAAC,EACnE,gBAAkB,YAAY,IAAK,MAAS,KAAK,WAAY,IAAI,CAAC,EAExE,QAAW,cAAc,eAAgB,CACvC,GAAI,CAAC,GAAG,WAAW,UAAU,EAC3B,SAIF,IAAM,eAAiB,gBAAgB,eAAe,QAAQ,UAAU,CAAC,EAEpE,GAAG,WAAW,cAAc,GAC/B,GAAG,SAAS,MAAM,eAAgB,CAAE,UAAW,EAAK,CAAC,EAGvD,MAAM,GAAG,SAAS,GAAG,WAAY,eAAgB,CAC/C,UAAW,GACX,MAAO,EACT,CAAC,CACH,CACF,CAzBsB","names":[]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{__name,colors_default}from"./chunk-RPTZYNBM.mjs";import{randomUUID}from"node:crypto";var valuesMap={true:!0,false:!1,null:null,undefined:void 0,__UUIDv4__:__name(()=>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");import{config as dotenv}from"dotenv";import{join}from"node:path";import{spawn}from"node:child_process";var ora;function createNodeProcess(options){let{nodeOptions=[],main,outDir,env={}}=options,processEnv=loadEnvFiles(options);return spawn("node",[...nodeOptions,join(process.cwd(),outDir,main)].filter(Boolean),{env:{...process.env,...processEnv,...env},cwd:process.cwd()})}__name(createNodeProcess,"createNodeProcess");function loadEnvFiles(options){let{envExtra=!0}=options,processEnv={},env=dotenv({path:join(process.cwd(),".env"),processEnv});return envExtra&&parseEnv(processEnv),env.error&&write(colors_default.yellow(`[DOTENV] Warning: ${env.error.message}`)),env.parsed&&write(colors_default.blue("[DOTENV] Loaded .env file!")),processEnv}__name(loadEnvFiles,"loadEnvFiles");async function createSpinner(text){return ora||(ora=await import("ora")),(ora.default||ora)({text,color:"cyan"})}__name(createSpinner,"createSpinner");function write(message){process.stdout.write(message+`
|
|
2
|
+
`)}__name(write,"write");export{parseEnv,createNodeProcess,createSpinner};
|
|
3
|
+
//# sourceMappingURL=chunk-PSR46ODG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/parse-env.ts","../src/cli/utils.ts"],"sourcesContent":["// @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}","import { config as dotenv } from 'dotenv';\nimport { join } from 'node:path';\nimport { parseEnv } from './parse-env';\nimport { ChildProcessWithoutNullStreams, spawn } from 'node:child_process';\nimport colors from '../utils/colors';\nimport { CLIOptions } from './types';\nimport type { Ora } from 'ora';\n\nlet ora: typeof import('ora') | undefined;\n\nexport function createNodeProcess(\noptions: CLIOptions)\n: ChildProcessWithoutNullStreams {\n const { nodeOptions = [], main, outDir, env = {} } = options;\n const processEnv = loadEnvFiles(options);\n\n return spawn(\n 'node',\n [...nodeOptions, join(process.cwd(), outDir, main)].filter(Boolean),\n {\n env: {\n ...process.env,\n ...processEnv,\n ...env\n },\n cwd: process.cwd()\n }\n );\n}\n\nexport function loadEnvFiles(options: CLIOptions) {\n const { envExtra = true } = options;\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 return processEnv;\n}\n\nexport async function createSpinner(text: string): Promise<Ora> {\n if (!ora) ora = await import('ora');\n\n return (ora.default || ora)({\n text,\n color: 'cyan'\n });\n}\n\nexport function write(message: string): void {\n process.stdout.write(message + '\\n');\n}\n\nexport function panic(message: string): never {\n write(colors.red(`Error: ${message}`));\n process.exit(1);\n}"],"mappings":"wDAEA,OAAS,eAAkB,cAE3B,IAAM,UAAY,CAChB,KAAM,GACN,MAAO,GACP,KAAM,KACN,UAAW,OACX,WAAY,WAAM,WAAW,EAAjB,aACd,EAEM,eAAiB,CACrB,KAAM,SACN,KAAM,QACR,EAEA,SAAS,QAAQ,GAAc,CAC7B,GAAI,CACF,UAAG,EACI,EACT,MAAQ,CACN,MAAO,EACT,CACF,CAPS,0BASF,SAAS,SAAS,IAAU,CACjC,QAAW,OAAO,IAAK,CACrB,IAAM,MAAQ,IAAI,GAAG,EAErB,GAAI,OAAO,OAAU,SAErB,IAAI,MAAM,WAAW,eAAe,IAAI,EAAG,CACzC,QACE,IAAM,IAAI,GAAG,EAAI,KAAK,MAAM,MAAM,QAAQ,eAAe,KAAM,EAAE,CAAC,CACpE,EACA,QACF,CAEA,GAAI,MAAM,WAAW,eAAe,IAAI,EAAG,CACzC,IAAI,GAAG,EAAI,IAAI,KAAK,MAAM,QAAQ,eAAe,KAAM,EAAE,CAAC,EAC1D,QACF,CAEA,GAAI,MAAM,SAAS,GAAG,EAAG,CACvB,IAAI,GAAG,EAAI,MAAM,MAAM,GAAG,EAAE,IAAK,GAAM,EAAE,KAAK,CAAC,EAC/C,QACF,CAEA,GAAI,YAAY,KAAK,KAAK,EAAG,CAC3B,IAAI,GAAG,EAAI,OAAO,KAAK,EACvB,QACF,CAEA,GAAI,SAAS,UAAW,CACtB,IAAI,GAAG,EAEP,OAAO,UAAU,KAAK,GAAM,WAE5B,UAAU,KAAK,EAAE,EAEjB,UAAU,KAAK,EACf,QACF,EACF,CAEA,OAAO,GACT,CAzCgB,4BC1BhB,OAAS,UAAU,WAAc,SACjC,OAAS,SAAY,YAErB,OAAyC,UAAa,qBAKtD,IAAI,IAEG,SAAS,kBAChB,QACiC,CAC/B,GAAM,CAAE,YAAc,CAAC,EAAG,KAAM,OAAQ,IAAM,CAAC,CAAE,EAAI,QAC/C,WAAa,aAAa,OAAO,EAEvC,OAAO,MACL,OACA,CAAC,GAAG,YAAa,KAAK,QAAQ,IAAI,EAAG,OAAQ,IAAI,CAAC,EAAE,OAAO,OAAO,EAClE,CACE,IAAK,CACH,GAAG,QAAQ,IACX,GAAG,WACH,GAAG,GACL,EACA,IAAK,QAAQ,IAAI,CACnB,CACF,CACF,CAlBgB,8CAoBT,SAAS,aAAa,QAAqB,CAChD,GAAM,CAAE,SAAW,EAAK,EAAI,QACtB,WAAa,CAAC,EAEd,IAAM,OAAO,CACjB,KAAM,KAAK,QAAQ,IAAI,EAAG,MAAM,EAChC,UACF,CAAC,EAED,OAAI,UACF,SAAS,UAAU,EAGjB,IAAI,OACN,MAAM,eAAO,OAAO,qBAAqB,IAAI,MAAM,OAAO,EAAE,CAAC,EAG3D,IAAI,QACN,MAAM,eAAO,KAAK,4BAA4B,CAAC,EAG1C,UACT,CAtBgB,oCAwBhB,eAAsB,cAAc,KAA4B,CAC9D,OAAK,MAAK,IAAM,KAAM,QAAO,KAAK,IAE1B,IAAI,SAAW,KAAK,CAC1B,KACA,MAAO,MACT,CAAC,CACH,CAPsB,sCASf,SAAS,MAAM,QAAuB,CAC3C,QAAQ,OAAO,MAAM,QAAU;AAAA,CAAI,CACrC,CAFgB","names":[]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var __defProp=Object.defineProperty;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),__accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);import{createColors}from"picocolors";var colors_default=createColors(!0);export{__name,__require,__publicField,__privateGet,__privateAdd,__privateSet,__privateMethod,colors_default};
|
|
2
|
+
//# sourceMappingURL=chunk-RPTZYNBM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/colors.ts"],"sourcesContent":["import { createColors } from 'picocolors';\n\nexport default createColors(true);"],"mappings":"ovCAAA,OAAS,iBAAoB,aAE7B,IAAO,eAAQ,aAAa,EAAI","names":[]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{createSpinner}from"./chunk-PSR46ODG.mjs";import{copyLocaleFiles,erase,findCommandKitConfig,panic,write}from"./chunk-NAFN6ATB.mjs";import{__name,colors_default}from"./chunk-RPTZYNBM.mjs";import{readFile as readFile2,writeFile}from"node:fs/promises";import{join}from"node:path";import{build}from"tsup";import{MacroTransformer}from"use-macro";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|ObjectMethod"(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}
|
|
2
|
+
|
|
3
|
+
${path.toString()}
|
|
4
|
+
^^^^${"-".repeat(6)} This function must be async`);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(()=>{t.isObjectMethod(path.node)?path.replaceWith(t.objectProperty(t.identifier(path.node.key.name),wrapped)):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");import{readFile}from"node:fs/promises";var defaultConfig={"use-macro":!0,"use-cache":!0,"jsx-importsource":!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(build2){if(!plugins.length)return;let fileFilter=/\.(c|m)?(t|j)sx?$/;build2.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");async function bootstrapProductionBuild(configPath){let config=await findCommandKitConfig(configPath),spinner=await createSpinner("Creating optimized production build..."),start=performance.now();try{await buildProject(config),spinner.succeed(colors_default.green(`Build completed in ${(performance.now()-start).toFixed(2)}ms!`))}catch(e){spinner.fail("Build failed"),panic(e instanceof Error?e.stack:e)}}__name(bootstrapProductionBuild,"bootstrapProductionBuild");async function bootstrapDevelopmentBuild(configPath){let config=await findCommandKitConfig(configPath);try{await buildProject({...config,outDir:".commandkit",isDevelopment:!0})}catch(e){console.error(e instanceof Error?e.stack:e),console.error(colors_default.red("Failed to build the project. Waiting for changes..."))}}__name(bootstrapDevelopmentBuild,"bootstrapDevelopmentBuild");async function buildProject(options){let{sourcemap=!1,minify=!1,outDir="dist",antiCrash=!0,main,requirePolyfill:polyfillRequire}=options;erase(outDir);try{await build({clean:!0,format:["esm"],dts:!1,skipNodeModulesBundle:!0,minify,shims:!0,banner:options.isDevelopment?{}:{js:"/* Optimized production build generated by CommandKit */"},sourcemap,keepNames:!0,outDir,silent:!0,watch:!!options.isDevelopment&&!!options.watch,cjsInterop:!0,splitting:!0,entry:["src","!dist","!.commandkit",`!${outDir}`],esbuildPlugins:[commandkitPlugin({"jsx-importsource":!1,"use-cache":!0,"use-macro":!!options.isDevelopment})],jsxFactory:"CommandKit.createElement",jsxFragment:"CommandKit.Fragment",async onSuccess(){await copyLocaleFiles("src",outDir)}}),await injectShims(outDir,main,!options.isDevelopment&&antiCrash,!!polyfillRequire),options.isDevelopment||write(colors_default.green(`
|
|
5
|
+
Run ${colors_default.magenta("commandkit start")} ${colors_default.green("to start your bot.")}`))}catch(e){panic(e)}}__name(buildProject,"buildProject");async function injectShims(outDir,main,antiCrash,polyfillRequire){let path=join(process.cwd(),outDir,main),head=[`
|
|
6
|
+
|
|
7
|
+
;await (async()=>{`," 'use strict';"].join(`
|
|
8
|
+
`),tail=`
|
|
9
|
+
})();`,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(`
|
|
10
|
+
`):"",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(`
|
|
11
|
+
`):"",contents=await readFile2(path,"utf-8"),finalScript=[head,requireScript,antiCrashScript,tail,`
|
|
12
|
+
|
|
13
|
+
`,contents].join(`
|
|
14
|
+
`);return writeFile(path,finalScript)}__name(injectShims,"injectShims");export{bootstrapProductionBuild,bootstrapDevelopmentBuild,injectShims};
|
|
15
|
+
//# sourceMappingURL=chunk-UCPCQQQH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/build.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 {\n copyLocaleFiles,\n erase,\n findCommandKitConfig,\n panic,\n write } from\n'./common.js';\nimport { commandkitPlugin } from './esbuild-plugins/plugin';\nimport colors from '../utils/colors.js';\nimport { createSpinner } from './utils';\nimport { BuildOptions } from './types';\n\nexport async function bootstrapProductionBuild(configPath: string) {\n const config = await findCommandKitConfig(configPath);\n const spinner = await createSpinner('Creating optimized production build...');\n const start = performance.now();\n\n try {\n await buildProject(config);\n spinner.succeed(\n colors.green(\n `Build completed in ${(performance.now() - start).toFixed(2)}ms!`\n )\n );\n } catch (e) {\n spinner.fail('Build failed');\n panic(e instanceof Error ? e.stack : e);\n }\n}\n\nexport async function bootstrapDevelopmentBuild(configPath: string) {\n const config = await findCommandKitConfig(configPath);\n\n try {\n await buildProject({\n ...config,\n outDir: '.commandkit',\n isDevelopment: true\n });\n } catch (e) {\n console.error(e instanceof Error ? e.stack : e);\n console.error(\n colors.red('Failed to build the project. Waiting for changes...')\n );\n }\n}\n\nasync function buildProject(options: BuildOptions) {\n const {\n sourcemap = false,\n minify = false,\n outDir = 'dist',\n antiCrash = true,\n main,\n requirePolyfill: polyfillRequire\n } = options;\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: options.isDevelopment ?\n {} :\n {\n js: '/* Optimized production build generated by CommandKit */'\n },\n sourcemap,\n keepNames: true,\n outDir,\n silent: true,\n watch: !!options.isDevelopment && !!options.watch,\n cjsInterop: true,\n splitting: true,\n entry: ['src', '!dist', '!.commandkit', `!${outDir}`],\n esbuildPlugins: [\n commandkitPlugin({\n 'jsx-importsource': false,\n 'use-cache': true,\n 'use-macro': !!options.isDevelopment\n })],\n\n jsxFactory: 'CommandKit.createElement',\n jsxFragment: 'CommandKit.Fragment',\n async onSuccess() {\n await copyLocaleFiles('src', outDir);\n }\n });\n\n await injectShims(\n outDir,\n main,\n !options.isDevelopment && antiCrash,\n !!polyfillRequire\n );\n\n if (!options.isDevelopment) {\n write(\n colors.green(\n `\\nRun ${colors.magenta(`commandkit start`)} ${colors.green(\n 'to start your bot.'\n )}`\n )\n );\n }\n } catch (e) {\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 'jsx-importsource': true\n};\n\ninterface CommandKitEsbuildPluginConfig {\n 'use-macro'?: boolean;\n 'jsx-importsource'?: 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|ObjectMethod'(\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${path.toString()}\\n^^^^${'-'.repeat(6)} This function must be async`\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 (t.isObjectMethod(path.node)) {\n path.replaceWith(\n t.objectProperty(t.identifier(path.node.key.name), wrapped)\n );\n } else 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":"iMAEA,OAAS,YAAAA,UAAU,cAAiB,mBACpC,OAAS,SAAY,YACrB,OAAS,UAAa,OCJtB,OAAS,qBAAwB,YCAjC,UAAY,WAAY,gBACxB,OAAO,cAAe,kBACtB,OAAO,cAAe,mBACtB,UAAY,MAAO,eAGnB,IAAM,SAAW,UAAU,SAAW,UAEhC,SAAW,UAAU,SAAW,UAEhC,YAAc,aACd,UAAY,YACZ,iBACN,0IAEM,qBAAuB,QAAC,OAAS,IAAM,CAC3C,IAAM,MAAQ,uDACd,OAAO,MAAM,KACX,CAAE,MAAO,EACT,IAAM,MAAM,KAAK,MAAM,KAAK,OAAO,EAAI,MAAM,MAAM,CAAC,CACtD,EAAE,KAAK,EAAE,CACX,EAN6B,wBAQhB,qBAAuB,aAAO,OAAgB,OAAc,CACvE,IAAM,IAAa,aAAM,OAAQ,CAC/B,WAAY,S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CAAC,CACT,CACF,CAlEe,oCAoEf,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,MAAMC,UAAS,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":["readFile","build","readFile"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{bootstrapDevelopmentBuild}from"./chunk-UCPCQQQH.mjs";import{createNodeProcess,createSpinner}from"./chunk-PSR46ODG.mjs";import{erase,findCommandKitConfig,panic,write}from"./chunk-NAFN6ATB.mjs";import{__name,colors_default}from"./chunk-RPTZYNBM.mjs";var RESTARTING_MSG_PATTERN=/^Restarting '|".+'|"\n?$/,FAILED_RUNNING_PATTERN=/^Failed running '.+'|"\n?$/;async function bootstrapDevelopmentServer(opts){var _a,_b;let config=await findCommandKitConfig(opts.config),{watch=!0,nodeOptions=[],clearRestartLogs=!0}=config,spinner=await createSpinner("Starting development server..."),start=performance.now();try{await erase(".commandkit"),await bootstrapDevelopmentBuild(opts.config);let ps=createNodeProcess({...config,outDir:".commandkit",nodeOptions:[...nodeOptions,watch?"--watch":"","--enable-source-maps"].filter(Boolean),env:{NODE_ENV:"development",COMMANDKIT_DEV:"true",COMMANDKIT_PRODUCTION:"false"}}),isLastLogRestarting=!1,hasStarted=!1;(_a=ps.stdout)==null||_a.on("data",data=>{let message=data.toString();if(FAILED_RUNNING_PATTERN.test(message)){write(colors_default.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_default.cyan("\u2300 Restarting the bot...")),isLastLogRestarting=!0}hasStarted||(hasStarted=!0)}),(_b=ps.stderr)==null||_b.on("data",data=>{let message=data.toString();message.includes("ExperimentalWarning: Watch mode is an experimental feature and might change at any time")||write(colors_default.red(message))}),ps.on("close",code=>{write(`
|
|
2
|
+
`),process.exit(code??0)}),ps.on("error",err=>{panic(err)}),spinner.succeed(colors_default.green(`Dev server started in ${(performance.now()-start).toFixed(2)}ms!
|
|
3
|
+
`))}catch(e){spinner.fail(colors_default.red(`Failed to start dev server: ${e}`)),panic(e instanceof Error?e.stack:e)}}__name(bootstrapDevelopmentServer,"bootstrapDevelopmentServer");export{bootstrapDevelopmentServer};
|
|
4
|
+
//# sourceMappingURL=development-5QKAE4EE.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/development.ts"],"sourcesContent":["import { erase, findCommandKitConfig, panic, write } from './common';\nimport colors from '../utils/colors';\nimport { createNodeProcess, createSpinner } from './utils';\nimport { bootstrapDevelopmentBuild } from './build';\n\nconst RESTARTING_MSG_PATTERN = /^Restarting '|\".+'|\"\\n?$/;\nconst FAILED_RUNNING_PATTERN = /^Failed running '.+'|\"\\n?$/;\n\nexport async function bootstrapDevelopmentServer(opts: any) {\n const config = await findCommandKitConfig(opts.config);\n const { watch = true, nodeOptions = [], clearRestartLogs = true } = config;\n\n const spinner = await createSpinner('Starting development server...');\n const start = performance.now();\n\n try {\n await erase('.commandkit');\n await bootstrapDevelopmentBuild(opts.config);\n\n const ps = createNodeProcess({\n ...config,\n outDir: '.commandkit',\n nodeOptions: [\n ...nodeOptions,\n watch ? '--watch' : '',\n '--enable-source-maps'].\n filter(Boolean),\n env: {\n NODE_ENV: 'development',\n COMMANDKIT_DEV: 'true',\n COMMANDKIT_PRODUCTION: 'false'\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\n spinner.succeed(\n colors.green(\n `Dev server started in ${(performance.now() - start).toFixed(2)}ms!\\n`\n )\n );\n } catch (e) {\n spinner.fail(colors.red(`Failed to start dev server: ${e}`));\n panic(e instanceof Error ? e.stack : e);\n }\n}"],"mappings":"+PAKA,IAAM,uBAAyB,2BACzB,uBAAyB,6BAE/B,eAAsB,2BAA2B,KAAW,CAR5D,UASE,IAAM,OAAS,MAAM,qBAAqB,KAAK,MAAM,EAC/C,CAAE,MAAQ,GAAM,YAAc,CAAC,EAAG,iBAAmB,EAAK,EAAI,OAE9D,QAAU,MAAM,cAAc,gCAAgC,EAC9D,MAAQ,YAAY,I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xC,CACF,CArFsB","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{panic}from"./chunk-NAFN6ATB.mjs";import{__name,colors_default}from"./chunk-RPTZYNBM.mjs";import{mkdir,writeFile,readdir}from"fs/promises";import{join}from"path";import{Locale}from"discord.js";import{existsSync}from"fs";var BASE_PATH=process.cwd(),COMMANDS_DIR=join(BASE_PATH,"src/app/commands"),EVENTS_DIR=join(BASE_PATH,"src/app/events"),LOCALES_DIR=join(BASE_PATH,"src/app/locales"),formatPath=__name(path=>path.replace(process.cwd(),".").replace(/\\/g,"/"),"formatPath");async function generateCommand(name,customPath){let cmdPath=join(customPath||COMMANDS_DIR,name);existsSync(cmdPath)||await mkdir(cmdPath,{recursive:!0}),existsSync(join(cmdPath,"command.ts"))&&panic(`Command ${name} already exists.`);let commandFile=`
|
|
2
|
+
import type { CommandData, SlashCommand, MessageCommand } from 'commandkit';
|
|
3
|
+
|
|
4
|
+
export const command: CommandData = {
|
|
5
|
+
name: '${name}',
|
|
6
|
+
description: '${name} command',
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export const chatInput: SlashCommand = async (ctx) => {
|
|
10
|
+
await ctx.interaction.reply('Hello from ${name}!');
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const message: MessageCommand = async (ctx) => {
|
|
14
|
+
await ctx.message.reply('Hello from ${name}!');
|
|
15
|
+
};
|
|
16
|
+
`.trim();await writeFile(join(cmdPath,"command.ts"),commandFile),console.log(colors_default.green(`Command ${colors_default.magenta(name)} created at ${colors_default.blue(formatPath(cmdPath))}/command.ts`))}__name(generateCommand,"generateCommand");async function generateEvent(name,customPath){let eventPath=join(customPath||EVENTS_DIR,name);existsSync(eventPath)||await mkdir(eventPath,{recursive:!0});let filename="event.ts";if(existsSync(join(eventPath,filename))){let count=(await readdir(eventPath)).length;filename=`${String(count).padStart(2,"0")}_${filename}`}let eventFile=`
|
|
17
|
+
export default async function on${name[0].toUpperCase()+name.slice(1)}() {
|
|
18
|
+
console.log('${name} event fired!');
|
|
19
|
+
};
|
|
20
|
+
`.trim();await writeFile(join(eventPath,filename),eventFile),console.log(colors_default.green(`Event ${colors_default.magenta(name)} created at ${colors_default.blue(formatPath(eventPath))}/${colors_default.magenta(filename)}`))}__name(generateEvent,"generateEvent");async function generateLocale(locale,commandName,customPath){Object.fromEntries(Object.entries(Locale).map(([k,v])=>[v,k]))[locale]||panic(`Invalid locale: ${locale}`),commandName||panic("Command name is required.");let localePath=join(customPath||LOCALES_DIR,locale);existsSync(localePath)||await mkdir(localePath,{recursive:!0}),existsSync(join(localePath,`${commandName}.json`))&&panic(`Locale file for ${commandName} already exists.`);let localeFile={command:{name:`${commandName}`,description:`${commandName} command`},translations:{}};await writeFile(join(localePath,`${commandName}.json`),JSON.stringify(localeFile,null,2)),console.log(colors_default.green(`Locale file for ${colors_default.magenta(commandName)} created at ${colors_default.blue(formatPath(localePath))}/${colors_default.magenta(`${commandName}.json`)}`))}__name(generateLocale,"generateLocale");export{generateCommand,generateEvent,generateLocale};
|
|
21
|
+
//# sourceMappingURL=generators-OG3OGOCO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/generators.ts"],"sourcesContent":["import { mkdir, writeFile, readdir } from 'fs/promises';\nimport { join } from 'path';\nimport { Locale } from 'discord.js';\nimport { panic } from './common';\nimport { existsSync } from 'fs';\nimport colors from '../utils/colors';\n\nconst BASE_PATH = process.cwd();\nconst COMMANDS_DIR = join(BASE_PATH, 'src/app/commands');\nconst EVENTS_DIR = join(BASE_PATH, 'src/app/events');\nconst LOCALES_DIR = join(BASE_PATH, 'src/app/locales');\n\nconst formatPath = (path: string) =>\npath.replace(process.cwd(), '.').replace(/\\\\/g, '/');\n\nexport async function generateCommand(name: string, customPath?: string) {\n const cmdPath = join(customPath || COMMANDS_DIR, name);\n if (!existsSync(cmdPath)) await mkdir(cmdPath, { recursive: true });\n\n if (existsSync(join(cmdPath, 'command.ts'))) {\n panic(`Command ${name} already exists.`);\n }\n\n const commandFile = `\nimport type { CommandData, SlashCommand, MessageCommand } from 'commandkit';\n\nexport const command: CommandData = {\n name: '${name}',\n description: '${name} command',\n};\n\nexport const chatInput: SlashCommand = async (ctx) => {\n await ctx.interaction.reply('Hello from ${name}!');\n};\n\nexport const message: MessageCommand = async (ctx) => {\n await ctx.message.reply('Hello from ${name}!');\n};\n`.trim();\n\n await writeFile(join(cmdPath, 'command.ts'), commandFile);\n\n console.log(\n colors.green(\n `Command ${colors.magenta(name)} created at ${colors.blue(formatPath(cmdPath))}/command.ts`\n )\n );\n}\n\nexport async function generateEvent(name: string, customPath?: string) {\n const eventPath = join(customPath || EVENTS_DIR, name);\n if (!existsSync(eventPath)) await mkdir(eventPath, { recursive: true });\n\n let filename = 'event.ts';\n if (existsSync(join(eventPath, filename))) {\n const count = (await readdir(eventPath)).length;\n filename = `${String(count).padStart(2, '0')}_${filename}`;\n }\n\n const eventFile = `\nexport default async function on${name[0].toUpperCase() + name.slice(1)}() {\n console.log('${name} event fired!');\n};\n`.trim();\n\n await writeFile(join(eventPath, filename), eventFile);\n\n console.log(\n colors.green(\n `Event ${colors.magenta(name)} created at ${colors.blue(formatPath(eventPath))}/${colors.magenta(filename)}`\n )\n );\n}\n\nexport async function generateLocale(\nlocale: keyof typeof Locale,\ncommandName: string,\ncustomPath?: string)\n{\n const localeNames = Object.fromEntries(\n Object.entries(Locale).map(([k, v]) => [v, k])\n );\n\n if (!localeNames[locale]) {\n panic(`Invalid locale: ${locale}`);\n }\n\n if (!commandName) {\n panic('Command name is required.');\n }\n\n const localePath = join(customPath || LOCALES_DIR, locale);\n\n if (!existsSync(localePath)) await mkdir(localePath, { recursive: true });\n\n if (existsSync(join(localePath, `${commandName}.json`))) {\n panic(`Locale file for ${commandName} already exists.`);\n }\n\n const localeFile = {\n command: {\n name: `${commandName}`,\n description: `${commandName} command`\n },\n translations: {}\n };\n\n await writeFile(\n join(localePath, `${commandName}.json`),\n JSON.stringify(localeFile, null, 2)\n );\n\n console.log(\n colors.green(\n `Locale file for ${colors.magenta(commandName)} created at ${colors.blue(\n formatPath(localePath)\n )}/${colors.magenta(`${commandName}.json`)}`\n )\n );\n}"],"mappings":"gGAAA,OAAS,MAAO,UAAW,YAAe,cAC1C,OAAS,SAAY,OACrB,OAAS,WAAc,aAEvB,OAAS,eAAkB,KAG3B,IAAM,UAAY,QAAQ,IAAI,EACxB,aAAe,KAAK,UAAW,kBAAkB,EACjD,WAAa,KAAK,UAAW,gBAAgB,EAC7C,YAAc,KAAK,UAAW,iBAAiB,EAE/C,WAAa,OAAC,MACpB,KAAK,QAAQ,QAAQ,IAAI,EAAG,GAAG,EAAE,QAAQ,MAAO,GAAG,EADhC,cAGnB,eAAsB,gBAAgB,KAAc,WAAqB,CACvE,IAAM,QAAU,KAAK,YAAc,aAAc,IAAI,EAChD,WAAW,OAAO,GAAG,MAAM,MAAM,QAAS,CAAE,UAAW,EAAK,CAAC,EAE9D,WAAW,KAAK,QAAS,YAAY,CAAC,GACxC,MAAM,WAAW,IAAI,kBAAkB,EAGzC,IAAM,YAAc;AAAA;AAAA;AAAA;AAAA,WAIX,IAAI;AAAA,kBACG,IAAI;AAAA;AAAA;AAAA;AAAA,4CAIsB,IAAI;AAAA;AAAA;AAAA;AAAA,wCAIR,IAAI;AAAA;AAAA,EAE1C,KAAK,EAEL,MAAM,UAAU,KAAK,QAAS,YAAY,EAAG,WAAW,EAExD,QAAQ,IACN,eAAO,MACL,WAAW,eAAO,QAAQ,IAAI,CAAC,eAAe,eAAO,KAAK,WAAW,OAAO,CAAC,CAAC,aAChF,CACF,CACF,CAhCsB,0CAkCtB,eAAsB,cAAc,KAAc,WAAqB,CACrE,IAAM,UAAY,KAAK,YAAc,WAAY,IAAI,EAChD,WAAW,SAAS,GAAG,MAAM,MAAM,UAAW,CAAE,UAAW,EAAK,CAAC,EAEtE,IAAI,SAAW,WACf,GAAI,WAAW,KAAK,UAAW,QAAQ,CAAC,EAAG,CACzC,IA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,CA7CsB","names":[]}
|
package/dist/index.d.mts
CHANGED
|
@@ -1061,12 +1061,10 @@ declare function getContext(): CommandKitEnvironment | undefined;
|
|
|
1061
1061
|
declare function useEnvironment(): CommandKitEnvironment;
|
|
1062
1062
|
/**
|
|
1063
1063
|
* Ensures the command is only available in guilds.
|
|
1064
|
-
* Note: do not wrap this function in a try/catch block.
|
|
1065
1064
|
*/
|
|
1066
1065
|
declare function guildOnly(): void;
|
|
1067
1066
|
/**
|
|
1068
1067
|
* Ensures the command is only available in DMs.
|
|
1069
|
-
* Note: do not wrap this function in a try/catch block.
|
|
1070
1068
|
*/
|
|
1071
1069
|
declare function dmOnly(): void;
|
|
1072
1070
|
|
|
@@ -1376,7 +1374,7 @@ declare class AppCommandHandler {
|
|
|
1376
1374
|
private loadedCommands;
|
|
1377
1375
|
private loadedMiddlewares;
|
|
1378
1376
|
constructor(commandkit: CommandKit);
|
|
1379
|
-
getCommandsArray():
|
|
1377
|
+
getCommandsArray(): LoadedCommand[];
|
|
1380
1378
|
prepareCommandRun(source: Interaction | Message): Promise<PreparedAppCommandExecution | null>;
|
|
1381
1379
|
loadCommands(): Promise<void>;
|
|
1382
1380
|
applyLocalizations(command: CommandBuilderLike): Promise<discord_js.RESTPostAPIContextMenuApplicationCommandsJSONBody | CommandBuilderLike>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1061,12 +1061,10 @@ declare function getContext(): CommandKitEnvironment | undefined;
|
|
|
1061
1061
|
declare function useEnvironment(): CommandKitEnvironment;
|
|
1062
1062
|
/**
|
|
1063
1063
|
* Ensures the command is only available in guilds.
|
|
1064
|
-
* Note: do not wrap this function in a try/catch block.
|
|
1065
1064
|
*/
|
|
1066
1065
|
declare function guildOnly(): void;
|
|
1067
1066
|
/**
|
|
1068
1067
|
* Ensures the command is only available in DMs.
|
|
1069
|
-
* Note: do not wrap this function in a try/catch block.
|
|
1070
1068
|
*/
|
|
1071
1069
|
declare function dmOnly(): void;
|
|
1072
1070
|
|
|
@@ -1376,7 +1374,7 @@ declare class AppCommandHandler {
|
|
|
1376
1374
|
private loadedCommands;
|
|
1377
1375
|
private loadedMiddlewares;
|
|
1378
1376
|
constructor(commandkit: CommandKit);
|
|
1379
|
-
getCommandsArray():
|
|
1377
|
+
getCommandsArray(): LoadedCommand[];
|
|
1380
1378
|
prepareCommandRun(source: Interaction | Message): Promise<PreparedAppCommandExecution | null>;
|
|
1381
1379
|
loadCommands(): Promise<void>;
|
|
1382
1380
|
applyLocalizations(command: CommandBuilderLike): Promise<discord_js.RESTPostAPIContextMenuApplicationCommandsJSONBody | CommandBuilderLike>;
|