@elysiumjs/styx 0.9.1 → 0.9.2
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/CHANGELOG.md +6 -0
- package/dist/cli.js +3 -3
- package/dist/cloudflare-stubs.d.ts +3 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @elysiumjs/styx
|
|
2
2
|
|
|
3
|
+
## 0.9.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#36](https://github.com/na2axl/elysiumjs/pull/36) [`0f64f52`](https://github.com/na2axl/elysiumjs/commit/0f64f5209dd0a6f094b3336b0ca2831e28099861) Thanks [@na2axl](https://github.com/na2axl)! - Styx commands load apps that import `cloudflare:workers` (to export a Durable Object, such as the flow store of `@elysiumjs/ariadne-workers`): stand-ins of the `cloudflare:*` modules are registered while Styx reads the app's code.
|
|
8
|
+
|
|
3
9
|
## 0.9.1
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:!0}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __legacyDecorateClassTS=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};var __legacyMetadataTS=(k,v)=>{if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(k,v)};var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __require=import.meta.require;var require_package=__commonJS(function(exports,module){module.exports={name:"@elysiumjs/styx",version:"0.9.
|
|
3
|
+
var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:!0}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __legacyDecorateClassTS=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};var __legacyMetadataTS=(k,v)=>{if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(k,v)};var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __require=import.meta.require;var require_package=__commonJS(function(exports,module){module.exports={name:"@elysiumjs/styx",version:"0.9.2",license:"Apache-2.0",description:"The command line tool of the Elysium.js framework: creates projects, generates code and runs app commands.",private:!1,author:"Workbud Technologies Inc.",repository:{type:"git",url:"git+https://github.com/na2axl/elysiumjs.git",directory:"@elysiumjs/styx"},homepage:"https://github.com/na2axl/elysiumjs/tree/main/@elysiumjs/styx#readme",bugs:{url:"https://github.com/na2axl/elysiumjs/issues"},scripts:{format:'prettier --write "./src/**/*.ts"',clean:"rimraf dist","build:js":"bun build ./src/cli.ts ./src/index.ts --outdir ./dist --target bun -e @elysiumjs/* --root ./src --minify-syntax --minify-whitespace","build:ts":"tsc",build:"bun run clean && bun run build:js && bun run build:ts",typecheck:"tsc --noEmit",prepublishOnly:"bun run build",test:"bun test","test:coverage":"bun test --coverage","build:bin":"bun scripts/build-bin.ts"},keywords:["elysium","framework","web","api","typescript","cli"],type:"module",sideEffects:!1,bin:{styx:"dist/cli.js"},module:"dist/index.js",types:"dist/index.d.ts",files:["dist","stubs","templates","CHANGELOG.md"],devDependencies:{"@elysiumjs/core":"workspace:*","@elysiumjs/hephaestus":"workspace:*","@elysiumjs/runtime-bun":"workspace:*","@types/prompts":"^2.4.9","@types/string-template":"^1.0.7",prompts:"^2.4.2",radash:"catalog:","string-template":"^1.0.0"},dependencies:{"@elysiumjs/core":"workspace:^","@elysiumjs/runtime-bun":"workspace:^"}}});class ToolingStub{}var CLOUDFLARE_STUBS,stubCloudflareModules=()=>{Bun.plugin({name:"styx-cloudflare-stubs",setup(build){for(let[specifier,exports]of Object.entries(CLOUDFLARE_STUBS))build.module(specifier,()=>({exports,loader:"object"}))}})};var init_cloudflare_stubs=__esm(()=>{CLOUDFLARE_STUBS={"cloudflare:workers":{DurableObject:ToolingStub,WorkerEntrypoint:ToolingStub,WorkflowEntrypoint:ToolingStub,RpcTarget:ToolingStub,RpcStub:ToolingStub,env:{},waitUntil:()=>{}},"cloudflare:email":{EmailMessage:ToolingStub},"cloudflare:sockets":{connect:()=>({})}}});import{Command}from"@elysiumjs/core";var BaseCommand;var init_base_command=__esm(()=>{BaseCommand=class BaseCommand extends Command{static dev=!0}});var require_kleur=__commonJS(function(exports,module){var{FORCE_COLOR,NODE_DISABLE_COLORS,TERM}=process.env,$={enabled:!NODE_DISABLE_COLORS&&TERM!=="dumb"&&FORCE_COLOR!=="0",reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(arr,str){let i=0,tmp,beg="",end="";for(;i<arr.length;i++)if(tmp=arr[i],beg+=tmp.open,end+=tmp.close,str.includes(tmp.close))str=str.replace(tmp.rgx,tmp.close+tmp.open);return beg+str+end}function chain(has,keys){let ctx={has,keys};return ctx.reset=$.reset.bind(ctx),ctx.bold=$.bold.bind(ctx),ctx.dim=$.dim.bind(ctx),ctx.italic=$.italic.bind(ctx),ctx.underline=$.underline.bind(ctx),ctx.inverse=$.inverse.bind(ctx),ctx.hidden=$.hidden.bind(ctx),ctx.strikethrough=$.strikethrough.bind(ctx),ctx.black=$.black.bind(ctx),ctx.red=$.red.bind(ctx),ctx.green=$.green.bind(ctx),ctx.yellow=$.yellow.bind(ctx),ctx.blue=$.blue.bind(ctx),ctx.magenta=$.magenta.bind(ctx),ctx.cyan=$.cyan.bind(ctx),ctx.white=$.white.bind(ctx),ctx.gray=$.gray.bind(ctx),ctx.grey=$.grey.bind(ctx),ctx.bgBlack=$.bgBlack.bind(ctx),ctx.bgRed=$.bgRed.bind(ctx),ctx.bgGreen=$.bgGreen.bind(ctx),ctx.bgYellow=$.bgYellow.bind(ctx),ctx.bgBlue=$.bgBlue.bind(ctx),ctx.bgMagenta=$.bgMagenta.bind(ctx),ctx.bgCyan=$.bgCyan.bind(ctx),ctx.bgWhite=$.bgWhite.bind(ctx),ctx}function init(open,close){let blk={open:`\x1B[${open}m`,close:`\x1B[${close}m`,rgx:new RegExp(`\\x1b\\[${close}m`,"g")};return function(txt){if(this!==void 0&&this.has!==void 0)return this.has.includes(open)||(this.has.push(open),this.keys.push(blk)),txt===void 0?this:$.enabled?run(this.keys,txt+""):txt+"";return txt===void 0?chain([open],[blk]):$.enabled?run([blk],txt+""):txt+""}}module.exports=$});var require_action=__commonJS(function(exports,module){module.exports=(key,isSelect)=>{if(key.meta&&key.name!=="escape")return;if(key.ctrl){if(key.name==="a")return"first";if(key.name==="c")return"abort";if(key.name==="d")return"abort";if(key.name==="e")return"last";if(key.name==="g")return"reset"}if(isSelect){if(key.name==="j")return"down";if(key.name==="k")return"up"}if(key.name==="return")return"submit";if(key.name==="enter")return"submit";if(key.name==="backspace")return"delete";if(key.name==="delete")return"deleteForward";if(key.name==="abort")return"abort";if(key.name==="escape")return"exit";if(key.name==="tab")return"next";if(key.name==="pagedown")return"nextPage";if(key.name==="pageup")return"prevPage";if(key.name==="home")return"home";if(key.name==="end")return"end";if(key.name==="up")return"up";if(key.name==="down")return"down";if(key.name==="right")return"right";if(key.name==="left")return"left";return!1}});var require_strip=__commonJS(function(exports,module){module.exports=(str)=>{let pattern=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),RGX=new RegExp(pattern,"g");return typeof str==="string"?str.replace(RGX,""):str}});var require_src=__commonJS(function(exports,module){var cursor={to(x,y){if(!y)return`\x1B[${x+1}G`;return`\x1B[${y+1};${x+1}H`},move(x,y){let ret="";if(x<0)ret+=`\x1B[${-x}D`;else if(x>0)ret+=`\x1B[${x}C`;if(y<0)ret+=`\x1B[${-y}A`;else if(y>0)ret+=`\x1B[${y}B`;return ret},up:(count=1)=>`\x1B[${count}A`,down:(count=1)=>`\x1B[${count}B`,forward:(count=1)=>`\x1B[${count}C`,backward:(count=1)=>`\x1B[${count}D`,nextLine:(count=1)=>"\x1B[E".repeat(count),prevLine:(count=1)=>"\x1B[F".repeat(count),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},scroll={up:(count=1)=>"\x1B[S".repeat(count),down:(count=1)=>"\x1B[T".repeat(count)},erase={screen:"\x1B[2J",up:(count=1)=>"\x1B[1J".repeat(count),down:(count=1)=>"\x1B[J".repeat(count),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");if(count)clear+=cursor.left;return clear}};module.exports={cursor,scroll,erase,beep:"\x07"}});var require_clear=__commonJS(function(exports,module){function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0,F=function(){};return{s:F,n:function(){if(i>=o.length)return{done:!0};return{done:!1,value:o[i++]}},e:function(_e){throw _e},f:F}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
4
4
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var normalCompletion=!0,didErr=!1,err;return{s:function(){it=it.call(o)},n:function(){var step=it.next();return normalCompletion=step.done,step},e:function(_e2){didErr=!0,err=_e2},f:function(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}var strip=require_strip(),_require=require_src(),erase=_require.erase,cursor=_require.cursor,width=(str)=>[...strip(str)].length;module.exports=function(prompt,perLine){if(!perLine)return erase.line+cursor.to(0);let rows=0,lines=prompt.split(/\r?\n/);var _iterator=_createForOfIteratorHelper(lines),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){let line=_step.value;rows+=1+Math.floor(Math.max(width(line)-1,0)/perLine)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return erase.lines(rows)}});var require_figures=__commonJS(function(exports,module){var main={arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",radioOn:"\u25C9",radioOff:"\u25EF",tick:"\u2714",cross:"\u2716",ellipsis:"\u2026",pointerSmall:"\u203A",line:"\u2500",pointer:"\u276F"},win={arrowUp:main.arrowUp,arrowDown:main.arrowDown,arrowLeft:main.arrowLeft,arrowRight:main.arrowRight,radioOn:"(*)",radioOff:"( )",tick:"\u221A",cross:"\xD7",ellipsis:"...",pointerSmall:"\xBB",line:"\u2500",pointer:">"},figures=process.platform==="win32"?win:main;module.exports=figures});var require_style=__commonJS(function(exports,module){var c=require_kleur(),figures=require_figures(),styles=Object.freeze({password:{scale:1,render:(input)=>"*".repeat(input.length)},emoji:{scale:2,render:(input)=>"\uD83D\uDE03".repeat(input.length)},invisible:{scale:0,render:(input)=>""},default:{scale:1,render:(input)=>`${input}`}}),render=(type)=>styles[type]||styles.default,symbols=Object.freeze({aborted:c.red(figures.cross),done:c.green(figures.tick),exited:c.yellow(figures.cross),default:c.cyan("?")}),symbol=(done,aborted,exited)=>aborted?symbols.aborted:exited?symbols.exited:done?symbols.done:symbols.default,delimiter=(completing)=>c.gray(completing?figures.ellipsis:figures.pointerSmall),item=(expandable,expanded)=>c.gray(expandable?expanded?figures.pointerSmall:"+":figures.line);module.exports={styles,render,symbols,symbol,delimiter,item}});var require_lines=__commonJS(function(exports,module){var strip=require_strip();module.exports=function(msg,perLine){let lines=String(strip(msg)||"").split(/\r?\n/);if(!perLine)return lines.length;return lines.map((l)=>Math.ceil(l.length/perLine)).reduce((a,b)=>a+b)}});var require_wrap=__commonJS(function(exports,module){module.exports=(msg,opts={})=>{let tab=Number.isSafeInteger(parseInt(opts.margin))?Array(parseInt(opts.margin)).fill(" ").join(""):opts.margin||"",width=opts.width;return(msg||"").split(/\r?\n/g).map((line)=>line.split(/\s+/g).reduce((arr,w)=>{if(w.length+tab.length>=width||arr[arr.length-1].length+w.length+1<width)arr[arr.length-1]+=` ${w}`;else arr.push(`${tab}${w}`);return arr},[tab]).join(`
|
|
5
5
|
`)).join(`
|
|
6
6
|
`)}});var require_entriesToDisplay=__commonJS(function(exports,module){module.exports=(cursor,total,maxVisible)=>{maxVisible=maxVisible||total;let startIndex=Math.min(total-maxVisible,cursor-Math.floor(maxVisible/2));if(startIndex<0)startIndex=0;let endIndex=Math.min(startIndex+maxVisible,total);return{startIndex,endIndex}}});var require_util=__commonJS(function(exports,module){module.exports={action:require_action(),clear:require_clear(),style:require_style(),strip:require_strip(),figures:require_figures(),lines:require_lines(),wrap:require_wrap(),entriesToDisplay:require_entriesToDisplay()}});var require_prompt=__commonJS(function(exports,module){var readline=__require("readline"),_require=require_util(),action=_require.action,EventEmitter=__require("events"),_require2=require_src(),beep=_require2.beep,cursor=_require2.cursor,color=require_kleur();class Prompt extends EventEmitter{constructor(opts={}){super();this.firstRender=!0,this.in=opts.stdin||process.stdin,this.out=opts.stdout||process.stdout,this.onRender=(opts.onRender||(()=>{return})).bind(this);let rl=readline.createInterface({input:this.in,escapeCodeTimeout:50});if(readline.emitKeypressEvents(this.in,rl),this.in.isTTY)this.in.setRawMode(!0);let isSelect=["SelectPrompt","MultiselectPrompt"].indexOf(this.constructor.name)>-1,keypress=(str,key)=>{let a=action(key,isSelect);if(a===!1)this._&&this._(str,key);else if(typeof this[a]==="function")this[a](key);else this.bell()};this.close=()=>{if(this.out.write(cursor.show),this.in.removeListener("keypress",keypress),this.in.isTTY)this.in.setRawMode(!1);rl.close(),this.emit(this.aborted?"abort":this.exited?"exit":"submit",this.value),this.closed=!0},this.in.on("keypress",keypress)}fire(){this.emit("state",{value:this.value,aborted:!!this.aborted,exited:!!this.exited})}bell(){this.out.write(beep)}render(){if(this.onRender(color),this.firstRender)this.firstRender=!1}}module.exports=Prompt});var require_text=__commonJS(function(exports,module){function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){reject(error);return}if(info.done)resolve(value);else Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}var color=require_kleur(),Prompt=require_prompt(),_require=require_src(),erase=_require.erase,cursor=_require.cursor,_require2=require_util(),style=_require2.style,clear=_require2.clear,lines=_require2.lines,figures=_require2.figures;class TextPrompt extends Prompt{constructor(opts={}){super(opts);this.transform=style.render(opts.style),this.scale=this.transform.scale,this.msg=opts.message,this.initial=opts.initial||"",this.validator=opts.validate||(()=>!0),this.value="",this.errorMsg=opts.error||"Please Enter A Valid Value",this.cursor=Number(!!this.initial),this.cursorOffset=0,this.clear=clear("",this.out.columns),this.render()}set value(v){if(!v&&this.initial)this.placeholder=!0,this.rendered=color.gray(this.transform.render(this.initial));else this.placeholder=!1,this.rendered=this.transform.render(v);this._value=v,this.fire()}get value(){return this._value}reset(){this.value="",this.cursor=Number(!!this.initial),this.cursorOffset=0,this.fire(),this.render()}exit(){this.abort()}abort(){this.value=this.value||this.initial,this.done=this.aborted=!0,this.error=!1,this.red=!1,this.fire(),this.render(),this.out.write(`
|
|
@@ -110,7 +110,7 @@ export class ${className} extends Module {}
|
|
|
110
110
|
routes(${quote(controller.path)})${chain}
|
|
111
111
|
)`}),prefix=module.prefix?quote(module.prefix):"";lines.push(`/** The routes of the module ${module.id}. */`),lines.push(`const ${name} = () =>
|
|
112
112
|
routes(${prefix})${controllers.join("")};`,"")}let uses=moduleNames.map((name)=>`.use(${name}())`).join("");return lines.push(`const app = () => routes()${uses};`,""),lines.push("/** The routes of the app, for typed clients: `treaty<AppRoutes>(url)`. */"),lines.push("export type AppRoutes = ReturnType<typeof app>;",""),lines.join(`
|
|
113
|
-
`)};var init_render=__esm(()=>{METHODS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"])});import{join as join6,relative as relative2}from"path";import{Command as Command12,CommandArgumentType as CommandArgumentType11,ConsoleFormat}from"@elysiumjs/core";var RoutesGenerateCommand;var init_routes_generate_command=__esm(()=>{init_config();init_collect();init_render();init_utils();init_base_command();RoutesGenerateCommand=class RoutesGenerateCommand extends BaseCommand{static command="routes:generate";static description="Writes the route types of the app (AppRoutes) for typed clients.";async run(){let projectPath=getProjectPath(),config=await parseProjectConfig(),outFile=join6(projectPath,this.out??config.routes??"src/routes.gen.ts"),app=await resolveAppEntry(projectPath),{modules,missing}=await collectRoutes(projectPath,app,outFile);await Bun.write(outFile,renderRoutes(modules));for(let name of missing)this.warning(`${name} is not declared in the project sources, so its routes are not in AppRoutes.`);let count=modules.reduce((total,module)=>total+module.controllers.reduce((sum,controller)=>sum+controller.routes.length,0),0);this.success(`Wrote ${count} routes to ${this.format(relative2(projectPath,outFile),ConsoleFormat.BOLD)}.`)}};__legacyDecorateClassTS([Command12.arg({description:"The file to write, relative to the project (default: src/routes.gen.ts)",type:CommandArgumentType11.STRING}),__legacyMetadataTS("design:type",String)],RoutesGenerateCommand.prototype,"out",void 0),RoutesGenerateCommand=__legacyDecorateClassTS([Command12.register()],RoutesGenerateCommand)});var init_commands=__esm(()=>{init_base_command();init_make_command_command();init_make_controller_command();init_make_job_command();init_make_middleware_command();init_make_model_command();init_make_repository_command();init_make_service_command();init_make_validator_command();init_module_new_command();init_module_rename_command();init_routes_generate_command()});var TOOL_VERSIONS,versionFor=(name)=>{let elysium={"@elysiumjs/moirai-drizzle":"0.1.2","@elysiumjs/ariadne-redis":"0.1.0","@elysiumjs/runtime-bun":"0.1.1","@elysiumjs/cerberus":"0.3.4","@elysiumjs/ariadne":"0.1.1","@elysiumjs/moirai":"0.2.1","@elysiumjs/themis":"0.
|
|
113
|
+
`)};var init_render=__esm(()=>{METHODS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"])});import{join as join6,relative as relative2}from"path";import{Command as Command12,CommandArgumentType as CommandArgumentType11,ConsoleFormat}from"@elysiumjs/core";var RoutesGenerateCommand;var init_routes_generate_command=__esm(()=>{init_config();init_collect();init_render();init_utils();init_base_command();RoutesGenerateCommand=class RoutesGenerateCommand extends BaseCommand{static command="routes:generate";static description="Writes the route types of the app (AppRoutes) for typed clients.";async run(){let projectPath=getProjectPath(),config=await parseProjectConfig(),outFile=join6(projectPath,this.out??config.routes??"src/routes.gen.ts"),app=await resolveAppEntry(projectPath),{modules,missing}=await collectRoutes(projectPath,app,outFile);await Bun.write(outFile,renderRoutes(modules));for(let name of missing)this.warning(`${name} is not declared in the project sources, so its routes are not in AppRoutes.`);let count=modules.reduce((total,module)=>total+module.controllers.reduce((sum,controller)=>sum+controller.routes.length,0),0);this.success(`Wrote ${count} routes to ${this.format(relative2(projectPath,outFile),ConsoleFormat.BOLD)}.`)}};__legacyDecorateClassTS([Command12.arg({description:"The file to write, relative to the project (default: src/routes.gen.ts)",type:CommandArgumentType11.STRING}),__legacyMetadataTS("design:type",String)],RoutesGenerateCommand.prototype,"out",void 0),RoutesGenerateCommand=__legacyDecorateClassTS([Command12.register()],RoutesGenerateCommand)});var init_commands=__esm(()=>{init_base_command();init_make_command_command();init_make_controller_command();init_make_job_command();init_make_middleware_command();init_make_model_command();init_make_repository_command();init_make_service_command();init_make_validator_command();init_module_new_command();init_module_rename_command();init_routes_generate_command()});var TOOL_VERSIONS,versionFor=(name)=>{let elysium={"@elysiumjs/moirai-drizzle":"0.1.2","@elysiumjs/ariadne-redis":"0.1.0","@elysiumjs/runtime-bun":"0.1.1","@elysiumjs/cerberus":"0.3.4","@elysiumjs/ariadne":"0.1.1","@elysiumjs/moirai":"0.2.1","@elysiumjs/themis":"0.2.0","@elysiumjs/themis-redis":"0.0.2","@elysiumjs/heracles":"0.8.1","@elysiumjs/argus":"0.3.1","@elysiumjs/mnemosyne-drizzle":"0.4.2","@elysiumjs/mnemosyne":"0.5.1","@elysiumjs/runtime-node":"0.1.1","@elysiumjs/hermes":"0.5.1","@elysiumjs/themis-workers":"0.0.2","@elysiumjs/hephaestus":"0.5.0","@elysiumjs/ariadne-workers":"0.1.0","@elysiumjs/redis":"0.1.1","@elysiumjs/heracles-workers":"0.1.1","@elysiumjs/plugin-sentry":"0.3.1","@elysiumjs/core":"0.12.0","@elysiumjs/styx":"0.9.2","@elysiumjs/runtime-workers":"0.1.1"}[name];if(elysium)return`^${elysium}`;let range=TOOL_VERSIONS[name];if(!range)throw Error(`No version is known for ${name}.`);return range},getModuleCode=(module)=>`import { Module } from '@elysiumjs/core';
|
|
114
114
|
|
|
115
115
|
@Module.register({
|
|
116
116
|
controllers: []
|
|
@@ -197,4 +197,4 @@ export const app = worker.app;
|
|
|
197
197
|
export default worker;
|
|
198
198
|
`,getWranglerConfig=(projectName,parts)=>{let config={$schema:"node_modules/wrangler/config-schema.json",name:projectName.replace(/^@[^/]+\//,""),main:"dist/worker.js",compatibility_date:"2026-10-01",compatibility_flags:["nodejs_compat"],observability:{enabled:!0}};if(parts.database)config.hyperdrive=[{binding:"HYPERDRIVE",id:"<your-hyperdrive-id>",localConnectionString:`postgres://postgres:postgres@localhost:5432/${config.name}`}];return JSON.stringify(config,null,"\t")+`
|
|
199
199
|
`};var init_code=__esm(()=>{init_esm();TOOL_VERSIONS={prettier:"^3.9.10","@ianvs/prettier-plugin-sort-imports":"^4.7.1",typescript:"^7.0.2","drizzle-kit":"^1.0.0-rc.5",postgres:"^3.4.7",ioredis:"^5.8.2","@types/bun":"^1.3.1","@types/node":"^24.10.0","@cloudflare/workers-types":"^4.20251101.0",wrangler:"^4.158.0"},RUNTIMES={bun:{title:"Bun",description:"Run with Bun (https://bun.sh)",package:"@elysiumjs/runtime-bun",alias:"bunRuntime",types:["bun"],devPackages:["@types/bun"]},node:{title:"Node.js",description:"Run with Node.js (https://nodejs.org), built with styx build --target node",package:"@elysiumjs/runtime-node",alias:"nodeRuntime",types:["node"],devPackages:["@types/node"]},workers:{title:"Cloudflare Workers",description:"Deploy to Cloudflare Workers (https://workers.cloudflare.com)",package:"@elysiumjs/runtime-workers",alias:"workersRuntime",types:["@cloudflare/workers-types","node"],devPackages:["@cloudflare/workers-types","@types/node","wrangler"]}}});import{relative as relative3,resolve as resolve2,sep}from"path";import{ElysiumError as ElysiumError2}from"@elysiumjs/core";var PACKAGE_NAME,MODULE_NAME,InvalidNameError,validateProjectName=(name)=>{let match=PACKAGE_NAME.exec(name);if(!match)throw new InvalidNameError("project",name,'use lower-case letters, digits, "-", "_", "." or "~", optionally under an @scope/');let[,,directory]=match;return directory},validateModuleName=(name)=>{if(!MODULE_NAME.test(name))throw new InvalidNameError("module",name,'start with a lower-case letter, then use lower-case letters, digits or "-"');return name},resolveProjectPath=(base,directory)=>{let path=resolve2(base,directory),inside=relative3(resolve2(base),path);if(inside===""||inside===".."||inside.startsWith(`..${sep}`)||resolve2(inside)===inside)throw new InvalidNameError("project",directory,`it must be a folder inside ${resolve2(base)}`);return path};var init_names=__esm(()=>{PACKAGE_NAME=/^(?:@([a-z0-9-~][a-z0-9-._~]*)\/)?([a-z0-9-~][a-z0-9-._~]*)$/,MODULE_NAME=/^[a-z][a-z0-9-]*$/;InvalidNameError=class InvalidNameError extends ElysiumError2{kind;value;reason;constructor(kind,value,reason){super(`Invalid ${kind} name "${value}": ${reason}`);this.kind=kind;this.value=value;this.reason=reason}}});import{existsSync as existsSync3}from"fs";import{mkdir as mkdir2,readdir as readdir2,rm as rm2}from"fs/promises";import{dirname as dirname4,join as join7,relative as relative4}from"path";import{Command as Command13,CommandArgumentType as CommandArgumentType12,ConsoleFormat as ConsoleFormat2}from"@elysiumjs/core";var import_prompts11,PACKAGE_MANAGERS,runWith=(manager)=>`${manager} run`,list2=(value)=>typeof value==="string"?value.split(",").map((item)=>item.trim()).filter(Boolean):void 0,copyAssets=async(folder,to,projectName,skip=[])=>{for(let path of await listAssets(folder)){let target=join7(to,path);await mkdir2(dirname4(target),{recursive:!0});let file=path.split("/").at(-1);if(file===".gitkeep"||skip.includes(file))continue;let text=await readAsset(`${folder}/${path}`),renamed=file==="gitignore"?join7(dirname4(target),".gitignore"):target;await Bun.write(renamed,text.replaceAll("{PROJECT_NAME}",projectName))}},createProject=async(options,exec,progress=()=>{})=>{let directory=validateProjectName(options.name),projectPath=resolveProjectPath(options.path,directory),modules=options.template==="single"?["main"]:options.modules.map(validateModuleName);if(!RUNTIMES[options.runtime])throw Error(`Unknown runtime ${options.runtime}.`);if(!PACKAGE_MANAGERS.includes(options.packageManager))throw Error(`Unknown package manager ${options.packageManager}.`);let parts={database:options.database,cache:options.cache};if((await listAssets(`templates/template-${options.template}`)).length===0)throw Error(`Unknown template ${options.template}.`);if(progress("Creating project directory..."),existsSync3(projectPath)&&(await readdir2(projectPath)).length>0){if(!options.force)throw Error(`${projectPath} already exists and is not empty.`);await rm2(projectPath,{recursive:!0,force:!0})}await mkdir2(projectPath,{recursive:!0}),progress("Copying template files..."),await copyAssets(`templates/template-${options.template}`,projectPath,options.name),await writeRuntimeFiles(projectPath,options),await Bun.write(join7(projectPath,".elysiumrc"),JSON.stringify({projectName:options.name,mono:options.template!=="multi",modules:options.template==="multi"?objectify(modules,(m)=>m,(m)=>`src/modules/${m}`):void 0},null,2));for(let module of modules){let modulePath=options.template==="multi"?join7(projectPath,"src","modules",module):join7(projectPath,"src");await copyAssets("templates/shared-module",modulePath,options.name),await Bun.write(join7(modulePath,`${snake(module)}.module.ts`),getModuleCode(pascal(module)))}let packageFile=join7(projectPath,"package.json"),packageJson=assign(await Bun.file(packageFile).json(),{scripts:getScripts(options.runtime),imports:options.template==="multi"?objectify(modules,(m)=>`#${m}/*`,(m)=>`./src/modules/${m}/*.ts`):{"#root/*":"./src/*.ts"}}),base=appPackages(options.runtime,parts),devPackages=[...base.dev],packages=[...base.prod],enabledModules=[];for(let[kind,names]of[["plugin",options.plugins],["feature",options.features]])for(let name of names){let folder=`templates/${kind}-${name}`;if((await listAssets(folder)).length===0)throw Error(`Unknown ${kind} ${name}.`);await copyAssets(folder,projectPath,options.name,[".specs"]);let specs=JSON.parse(await readAsset(`${folder}/.specs`));if(devPackages.push(...specs.packages?.dev??[]),packages.push(...specs.packages?.prod??[]),specs.patch)packageJson=assign(packageJson,specs.patch);if(specs.module)enabledModules.push(specs.module)}let declare=(names)=>objectify(names,(n)=>n,versionFor);if(packageJson=assign(packageJson,{dependencies:{...packageJson.dependencies,...declare(packages)},devDependencies:{...packageJson.devDependencies,...declare(devPackages)}}),await Bun.write(packageFile,JSON.stringify(packageJson,null,2)+`
|
|
200
|
-
`),await Bun.write(join7(projectPath,"src","app.ts"),getAppCode(options.name,objectify(modules,(m)=>m,(m)=>options.template==="multi"?`#${m}/${snake(m)}.module`:`#root/${snake(m)}.module`),enabledModules,options.runtime,parts)),options.install){if(progress("Installing dependencies..."),await exec(projectPath,[options.packageManager,"install"]),options.features.includes("prettier"))progress("Formatting code using Prettier..."),await exec(projectPath,[options.packageManager,"run","format"])}if(options.git)progress("Initializing Git repository..."),await exec(projectPath,["git","init"]);return projectPath},writeRuntimeFiles=async(projectPath,options)=>{let tsconfigFile=join7(projectPath,"tsconfig.json"),tsconfig=await Bun.file(tsconfigFile).text(),types=JSON.stringify(RUNTIMES[options.runtime].types);await Bun.write(tsconfigFile,tsconfig.replace(/"types":\s*\[[^\]]*\]/,`"types": ${types}`));let readmeFile=join7(projectPath,"README.md"),readme=await Bun.file(readmeFile).text();if(await Bun.write(readmeFile,readme.replaceAll("{INSTALL}",`${options.packageManager} install`).replaceAll("{RUN}",runWith(options.packageManager))),options.runtime==="workers")await rm2(join7(projectPath,"index.ts"),{force:!0}),await mkdir2(join7(projectPath,"src"),{recursive:!0}),await Bun.write(join7(projectPath,"src","worker.ts"),getWorkerCode()),await Bun.write(join7(projectPath,"wrangler.jsonc"),getWranglerConfig(options.name,{database:options.database,cache:options.cache}))},execIn=async(cwd,command)=>{let proc=Bun.spawn(command,{cwd,stdout:"pipe",stderr:"pipe"});if(await proc.exited!==0)throw Error(`${command.join(" ")} failed: ${await new Response(proc.stderr).text()}`)},CreateCommand;var init_create_command=__esm(()=>{init_esm();init_assets();init_code();init_names();import_prompts11=__toESM(require_prompts3(),1),PACKAGE_MANAGERS=["bun","npm","pnpm"];CreateCommand=class CreateCommand extends Command13{static command="create";static description="Creates a new Elysium project.";static dev=!1;async run(){this.write(`Welcome to ${this.format("Elysium",ConsoleFormat2.MAGENTA,ConsoleFormat2.UNDERLINE)}`),this.newLine();let options=await this.ask(),s=process.stdout.isTTY?this.spinner("Creating project..."):{update:(step)=>this.info(step),complete:(message)=>this.success(message),fail:(message)=>this.error(message)};try{let projectPath=await createProject(options,execIn,(step)=>s.update(step));s.complete(`Project ${options.name} created successfully`);let dev=`${runWith(options.packageManager)} dev`;this.info(`Open it with ${this.format(`cd ${relative4(process.cwd(),projectPath)}`,ConsoleFormat2.BLUE,ConsoleFormat2.BOLD)}, then run ${this.format(dev,ConsoleFormat2.BLUE,ConsoleFormat2.BOLD)}`)}catch(error){s.fail(error instanceof Error?error.message:String(error)),process.exitCode=1}}async ask(){let interactive=!this.yes&&process.stdin.isTTY===!0,given={name:this.name,path:this.path,template:this.template,runtime:this.runtime,database:this.database,cache:this.cache,packageManager:this.packageManager,modules:list2(this.modules),plugins:list2(this.plugins),features:list2(this.features),git:this.git},questions=[{type:given.name?null:"text",name:"name",message:"What is the name of the project?",initial:"elysium-app",validate:(value)=>{try{return validateProjectName(value),!0}catch(error){return error.message}}},{type:given.template?null:"select",name:"template",message:"Which template would you like to use?",choices:[{title:"Single Module",value:"single",description:"A single module project"},{title:"Multi Module",value:"multi",description:"A project with several modules (monolith)"}]},{type:given.runtime?null:"select",name:"runtime",message:"Which runtime will the app run on?",choices:Object.entries(RUNTIMES).map(([value,runtime])=>({title:runtime.title,value,description:runtime.description}))},{type:given.database===void 0?"confirm":null,name:"database",message:"Set up a PostgreSQL database?",initial:!0},{type:given.cache===void 0?"confirm":null,name:"cache",message:"Set up a Redis cache?",initial:!1},{type:given.packageManager?null:"select",name:"packageManager",message:"Which package manager will install the dependencies?",choices:PACKAGE_MANAGERS.map((manager)=>({title:manager,value:manager})),initial:(_,values)=>(given.runtime??values.runtime??"bun")==="bun"?0:1},{type:(_,values)=>given.modules||(given.template??values.template)!=="multi"?null:"list",name:"modules",message:"Which modules would you like to include? (separate by commas)",initial:"main",separator:","},{type:given.plugins?null:"multiselect",name:"plugins",message:"Which plugins would you like to include?",choices:[{title:"Sentry",value:"sentry",description:"Error reporting (https://sentry.io)"}]},{type:given.features?null:"multiselect",name:"features",message:"Select features:",choices:[{title:"Prettier",value:"prettier",description:"Format code with Prettier"},{title:"Hephaestus",value:"hephaestus",description:"Build standalone executables and Docker images"}]},{type:given.git===void 0?"confirm":null,name:"git",message:"Initialize a Git repository?",initial:!0}],answers=interactive?await import_prompts11.default(questions,{onCancel:()=>{this.error("Project creation cancelled."),process.exit(1)}}):{},runtime=given.runtime??answers.runtime??"bun",name=given.name??answers.name;if(!name)throw Error("Give the project a name: styx create my-app");return validateProjectName(name),{name,path:given.path??".",template:given.template??answers.template??"single",runtime,database:given.database??answers.database??!0,cache:given.cache??answers.cache??!1,packageManager:given.packageManager??answers.packageManager??(runtime==="bun"?"bun":"npm"),modules:given.modules??answers.modules??["main"],plugins:given.plugins??answers.plugins??[],features:given.features??answers.features??[],git:given.git??answers.git??!1,install:this.install??!0,force:this.force??!1}}};__legacyDecorateClassTS([Command13.arg({description:"The name of the project",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command13.arg({description:"Where to create the project",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"path",void 0),__legacyDecorateClassTS([Command13.arg({description:"The template: single or multi",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"template",void 0),__legacyDecorateClassTS([Command13.arg({description:"The runtime: bun, node or workers",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"runtime",void 0),__legacyDecorateClassTS([Command13.arg({description:"Set up a PostgreSQL connection",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"database",void 0),__legacyDecorateClassTS([Command13.arg({description:"Set up a Redis connection",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"cache",void 0),__legacyDecorateClassTS([Command13.arg({name:"package-manager",description:"The package manager: bun, npm or pnpm",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"packageManager",void 0),__legacyDecorateClassTS([Command13.arg({description:"The modules of a multi template, comma separated",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"modules",void 0),__legacyDecorateClassTS([Command13.arg({description:"The plugins to add, comma separated (sentry)",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"plugins",void 0),__legacyDecorateClassTS([Command13.arg({description:"The features to add, comma separated (prettier, hephaestus)",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"features",void 0),__legacyDecorateClassTS([Command13.arg({description:"Initialize a Git repository",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"git",void 0),__legacyDecorateClassTS([Command13.arg({description:"Install the dependencies",type:CommandArgumentType12.BOOLEAN,default:!0}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"install",void 0),__legacyDecorateClassTS([Command13.arg({description:"Replace a folder that is not empty",type:CommandArgumentType12.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"force",void 0),__legacyDecorateClassTS([Command13.arg({description:"Use the defaults instead of asking",type:CommandArgumentType12.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"yes",void 0),CreateCommand=__legacyDecorateClassTS([Command13.register()],CreateCommand)});import{Application as Application2,Module}from"@elysiumjs/core";import{runtime as bunRuntime}from"@elysiumjs/runtime-bun";var StyxCliModule,runCli=async(argv,tools=[])=>{class StyxCli extends Application2{}StyxCli=__legacyDecorateClassTS([Application2.register({runtime:bunRuntime,modules:[StyxCliModule,...tools],openapi:!1})],StyxCli),await new StyxCli().run(argv)};var init_app=__esm(()=>{init_commands();init_create_command();StyxCliModule=class StyxCliModule extends Module{};StyxCliModule=__legacyDecorateClassTS([Module.register({commands:[CreateCommand,MakeCommandCommand,MakeControllerCommand,MakeJobCommand,MakeMiddlewareCommand,MakeModelCommand,MakeRepositoryCommand,MakeServiceCommand,MakeValidatorCommand,ModuleNewCommand,ModuleRenameCommand,RoutesGenerateCommand]})],StyxCliModule)});import{existsSync as existsSync4,realpathSync}from"fs";import{dirname as dirname5,join as join8}from"path";var GLOBAL_COMMANDS=new Set(["create","new"]),isGenerator=(command)=>command!==void 0&&/^(make|module):/.test(command),isAppTool=(command)=>command!==void 0&&(command==="build"||/^(routes|hephaestus):/.test(command)),isCliCommand=(command)=>isGenerator(command)||isAppTool(command),withPositionalName=(argv)=>{let[,name,...rest]=argv;if(name===void 0||name.startsWith("--"))return["create",...argv.slice(1)];return["create","--name",name,...rest]},route=(argv,context)=>{let[command]=argv;if(command==="--version"||command==="-v"||command==="version")return{kind:"version"};if(command!==void 0&&GLOBAL_COMMANDS.has(command))return{kind:"cli",argv:withPositionalName(argv)};if(!context.project){if(command===void 0||command==="list"||command==="help"||isCliCommand(command))return isCliCommand(command)?{kind:"error",message:`Run ${command} inside an Elysium project (a folder with an .elysiumrc file).`}:{kind:"cli",argv};return{kind:"error",message:"Not inside an Elysium project (no .elysiumrc found). Create one with: styx create my-app"}}if(context.projectCli&&context.projectCli!==context.self)return{kind:"handoff",cli:context.projectCli,argv};if(isGenerator(command))return{kind:"cli",argv};if(!context.projectCli)return{kind:"error",message:"This project does not install @elysiumjs/styx. Add it with: bun add -D @elysiumjs/styx"};if(command==="build")return{kind:"cli",argv:["hephaestus:build",...argv.slice(1)]};if(isAppTool(command))return{kind:"cli",argv};return{kind:"app",project:context.project,argv}};var findProject=(from)=>{for(let dir=from;;dir=dirname5(dir)){if(existsSync4(join8(dir,".elysiumrc")))return dir;if(dirname5(dir)===dir)return}},resolveFrom=(project,specifier)=>{try{return Bun.resolveSync(specifier,project)}catch{return}},real=(path)=>{try{return realpathSync(path)}catch{return path}},findProjectCli=(project)=>{let cli=resolveFrom(project,"@elysiumjs/styx/dist/cli.js");return cli?real(cli):void 0},loadTools=async(project,isProjectCli)=>{if(!project||!isProjectCli)return[];let entry=resolveFrom(project,"@elysiumjs/hephaestus");if(!entry)return[];let hephaestus=await import(entry);return hephaestus.HephaestusModule?[hephaestus.HephaestusModule]:[]},argv=process.argv.slice(2),project=findProject(process.cwd()),projectCli=project?findProjectCli(project):void 0,self=real(Bun.main),decision=route(argv,{project,projectCli,self});switch(decision.kind){case"version":{let{version}=await Promise.resolve().then(() => __toESM(require_package(),1));console.log(version);break}case"error":console.error(decision.message),process.exit(1);case"handoff":{let bun=Bun.which("bun");if(!bun)console.error("Bun is needed to run the Styx installed in this project: https://bun.sh"),process.exit(1);let proc=Bun.spawn([bun,decision.cli,...decision.argv],{stdio:["inherit","inherit","inherit"]});process.exit(await proc.exited)}case"cli":{await Promise.resolve().then(() => init_app());await runCli(decision.argv,await loadTools(project,projectCli===self));break}case"app":{await Promise.resolve().then(() => init_utils());let{ElysiumError}=await import("@elysiumjs/core");try{await new(await resolveAppEntry(decision.project))().run(decision.argv)}catch(error){if(!(error instanceof ElysiumError))throw error;console.error(error.message),process.exit(1)}break}}
|
|
200
|
+
`),await Bun.write(join7(projectPath,"src","app.ts"),getAppCode(options.name,objectify(modules,(m)=>m,(m)=>options.template==="multi"?`#${m}/${snake(m)}.module`:`#root/${snake(m)}.module`),enabledModules,options.runtime,parts)),options.install){if(progress("Installing dependencies..."),await exec(projectPath,[options.packageManager,"install"]),options.features.includes("prettier"))progress("Formatting code using Prettier..."),await exec(projectPath,[options.packageManager,"run","format"])}if(options.git)progress("Initializing Git repository..."),await exec(projectPath,["git","init"]);return projectPath},writeRuntimeFiles=async(projectPath,options)=>{let tsconfigFile=join7(projectPath,"tsconfig.json"),tsconfig=await Bun.file(tsconfigFile).text(),types=JSON.stringify(RUNTIMES[options.runtime].types);await Bun.write(tsconfigFile,tsconfig.replace(/"types":\s*\[[^\]]*\]/,`"types": ${types}`));let readmeFile=join7(projectPath,"README.md"),readme=await Bun.file(readmeFile).text();if(await Bun.write(readmeFile,readme.replaceAll("{INSTALL}",`${options.packageManager} install`).replaceAll("{RUN}",runWith(options.packageManager))),options.runtime==="workers")await rm2(join7(projectPath,"index.ts"),{force:!0}),await mkdir2(join7(projectPath,"src"),{recursive:!0}),await Bun.write(join7(projectPath,"src","worker.ts"),getWorkerCode()),await Bun.write(join7(projectPath,"wrangler.jsonc"),getWranglerConfig(options.name,{database:options.database,cache:options.cache}))},execIn=async(cwd,command)=>{let proc=Bun.spawn(command,{cwd,stdout:"pipe",stderr:"pipe"});if(await proc.exited!==0)throw Error(`${command.join(" ")} failed: ${await new Response(proc.stderr).text()}`)},CreateCommand;var init_create_command=__esm(()=>{init_esm();init_assets();init_code();init_names();import_prompts11=__toESM(require_prompts3(),1),PACKAGE_MANAGERS=["bun","npm","pnpm"];CreateCommand=class CreateCommand extends Command13{static command="create";static description="Creates a new Elysium project.";static dev=!1;async run(){this.write(`Welcome to ${this.format("Elysium",ConsoleFormat2.MAGENTA,ConsoleFormat2.UNDERLINE)}`),this.newLine();let options=await this.ask(),s=process.stdout.isTTY?this.spinner("Creating project..."):{update:(step)=>this.info(step),complete:(message)=>this.success(message),fail:(message)=>this.error(message)};try{let projectPath=await createProject(options,execIn,(step)=>s.update(step));s.complete(`Project ${options.name} created successfully`);let dev=`${runWith(options.packageManager)} dev`;this.info(`Open it with ${this.format(`cd ${relative4(process.cwd(),projectPath)}`,ConsoleFormat2.BLUE,ConsoleFormat2.BOLD)}, then run ${this.format(dev,ConsoleFormat2.BLUE,ConsoleFormat2.BOLD)}`)}catch(error){s.fail(error instanceof Error?error.message:String(error)),process.exitCode=1}}async ask(){let interactive=!this.yes&&process.stdin.isTTY===!0,given={name:this.name,path:this.path,template:this.template,runtime:this.runtime,database:this.database,cache:this.cache,packageManager:this.packageManager,modules:list2(this.modules),plugins:list2(this.plugins),features:list2(this.features),git:this.git},questions=[{type:given.name?null:"text",name:"name",message:"What is the name of the project?",initial:"elysium-app",validate:(value)=>{try{return validateProjectName(value),!0}catch(error){return error.message}}},{type:given.template?null:"select",name:"template",message:"Which template would you like to use?",choices:[{title:"Single Module",value:"single",description:"A single module project"},{title:"Multi Module",value:"multi",description:"A project with several modules (monolith)"}]},{type:given.runtime?null:"select",name:"runtime",message:"Which runtime will the app run on?",choices:Object.entries(RUNTIMES).map(([value,runtime])=>({title:runtime.title,value,description:runtime.description}))},{type:given.database===void 0?"confirm":null,name:"database",message:"Set up a PostgreSQL database?",initial:!0},{type:given.cache===void 0?"confirm":null,name:"cache",message:"Set up a Redis cache?",initial:!1},{type:given.packageManager?null:"select",name:"packageManager",message:"Which package manager will install the dependencies?",choices:PACKAGE_MANAGERS.map((manager)=>({title:manager,value:manager})),initial:(_,values)=>(given.runtime??values.runtime??"bun")==="bun"?0:1},{type:(_,values)=>given.modules||(given.template??values.template)!=="multi"?null:"list",name:"modules",message:"Which modules would you like to include? (separate by commas)",initial:"main",separator:","},{type:given.plugins?null:"multiselect",name:"plugins",message:"Which plugins would you like to include?",choices:[{title:"Sentry",value:"sentry",description:"Error reporting (https://sentry.io)"}]},{type:given.features?null:"multiselect",name:"features",message:"Select features:",choices:[{title:"Prettier",value:"prettier",description:"Format code with Prettier"},{title:"Hephaestus",value:"hephaestus",description:"Build standalone executables and Docker images"}]},{type:given.git===void 0?"confirm":null,name:"git",message:"Initialize a Git repository?",initial:!0}],answers=interactive?await import_prompts11.default(questions,{onCancel:()=>{this.error("Project creation cancelled."),process.exit(1)}}):{},runtime=given.runtime??answers.runtime??"bun",name=given.name??answers.name;if(!name)throw Error("Give the project a name: styx create my-app");return validateProjectName(name),{name,path:given.path??".",template:given.template??answers.template??"single",runtime,database:given.database??answers.database??!0,cache:given.cache??answers.cache??!1,packageManager:given.packageManager??answers.packageManager??(runtime==="bun"?"bun":"npm"),modules:given.modules??answers.modules??["main"],plugins:given.plugins??answers.plugins??[],features:given.features??answers.features??[],git:given.git??answers.git??!1,install:this.install??!0,force:this.force??!1}}};__legacyDecorateClassTS([Command13.arg({description:"The name of the project",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command13.arg({description:"Where to create the project",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"path",void 0),__legacyDecorateClassTS([Command13.arg({description:"The template: single or multi",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"template",void 0),__legacyDecorateClassTS([Command13.arg({description:"The runtime: bun, node or workers",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"runtime",void 0),__legacyDecorateClassTS([Command13.arg({description:"Set up a PostgreSQL connection",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"database",void 0),__legacyDecorateClassTS([Command13.arg({description:"Set up a Redis connection",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"cache",void 0),__legacyDecorateClassTS([Command13.arg({name:"package-manager",description:"The package manager: bun, npm or pnpm",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"packageManager",void 0),__legacyDecorateClassTS([Command13.arg({description:"The modules of a multi template, comma separated",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"modules",void 0),__legacyDecorateClassTS([Command13.arg({description:"The plugins to add, comma separated (sentry)",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"plugins",void 0),__legacyDecorateClassTS([Command13.arg({description:"The features to add, comma separated (prettier, hephaestus)",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"features",void 0),__legacyDecorateClassTS([Command13.arg({description:"Initialize a Git repository",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"git",void 0),__legacyDecorateClassTS([Command13.arg({description:"Install the dependencies",type:CommandArgumentType12.BOOLEAN,default:!0}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"install",void 0),__legacyDecorateClassTS([Command13.arg({description:"Replace a folder that is not empty",type:CommandArgumentType12.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"force",void 0),__legacyDecorateClassTS([Command13.arg({description:"Use the defaults instead of asking",type:CommandArgumentType12.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"yes",void 0),CreateCommand=__legacyDecorateClassTS([Command13.register()],CreateCommand)});import{Application as Application2,Module}from"@elysiumjs/core";import{runtime as bunRuntime}from"@elysiumjs/runtime-bun";var StyxCliModule,runCli=async(argv,tools=[])=>{class StyxCli extends Application2{}StyxCli=__legacyDecorateClassTS([Application2.register({runtime:bunRuntime,modules:[StyxCliModule,...tools],openapi:!1})],StyxCli),await new StyxCli().run(argv)};var init_app=__esm(()=>{init_commands();init_create_command();StyxCliModule=class StyxCliModule extends Module{};StyxCliModule=__legacyDecorateClassTS([Module.register({commands:[CreateCommand,MakeCommandCommand,MakeControllerCommand,MakeJobCommand,MakeMiddlewareCommand,MakeModelCommand,MakeRepositoryCommand,MakeServiceCommand,MakeValidatorCommand,ModuleNewCommand,ModuleRenameCommand,RoutesGenerateCommand]})],StyxCliModule)});import{existsSync as existsSync4,realpathSync}from"fs";import{dirname as dirname5,join as join8}from"path";var GLOBAL_COMMANDS=new Set(["create","new"]),isGenerator=(command)=>command!==void 0&&/^(make|module):/.test(command),isAppTool=(command)=>command!==void 0&&(command==="build"||/^(routes|hephaestus):/.test(command)),isCliCommand=(command)=>isGenerator(command)||isAppTool(command),withPositionalName=(argv)=>{let[,name,...rest]=argv;if(name===void 0||name.startsWith("--"))return["create",...argv.slice(1)];return["create","--name",name,...rest]},route=(argv,context)=>{let[command]=argv;if(command==="--version"||command==="-v"||command==="version")return{kind:"version"};if(command!==void 0&&GLOBAL_COMMANDS.has(command))return{kind:"cli",argv:withPositionalName(argv)};if(!context.project){if(command===void 0||command==="list"||command==="help"||isCliCommand(command))return isCliCommand(command)?{kind:"error",message:`Run ${command} inside an Elysium project (a folder with an .elysiumrc file).`}:{kind:"cli",argv};return{kind:"error",message:"Not inside an Elysium project (no .elysiumrc found). Create one with: styx create my-app"}}if(context.projectCli&&context.projectCli!==context.self)return{kind:"handoff",cli:context.projectCli,argv};if(isGenerator(command))return{kind:"cli",argv};if(!context.projectCli)return{kind:"error",message:"This project does not install @elysiumjs/styx. Add it with: bun add -D @elysiumjs/styx"};if(command==="build")return{kind:"cli",argv:["hephaestus:build",...argv.slice(1)]};if(isAppTool(command))return{kind:"cli",argv};return{kind:"app",project:context.project,argv}};var findProject=(from)=>{for(let dir=from;;dir=dirname5(dir)){if(existsSync4(join8(dir,".elysiumrc")))return dir;if(dirname5(dir)===dir)return}},resolveFrom=(project,specifier)=>{try{return Bun.resolveSync(specifier,project)}catch{return}},real=(path)=>{try{return realpathSync(path)}catch{return path}},findProjectCli=(project)=>{let cli=resolveFrom(project,"@elysiumjs/styx/dist/cli.js");return cli?real(cli):void 0},loadTools=async(project,isProjectCli)=>{if(!project||!isProjectCli)return[];let entry=resolveFrom(project,"@elysiumjs/hephaestus");if(!entry)return[];let hephaestus=await import(entry);return hephaestus.HephaestusModule?[hephaestus.HephaestusModule]:[]},argv=process.argv.slice(2),project=findProject(process.cwd()),projectCli=project?findProjectCli(project):void 0,self=real(Bun.main),decision=route(argv,{project,projectCli,self});switch(decision.kind){case"version":{let{version}=await Promise.resolve().then(() => __toESM(require_package(),1));console.log(version);break}case"error":console.error(decision.message),process.exit(1);case"handoff":{let bun=Bun.which("bun");if(!bun)console.error("Bun is needed to run the Styx installed in this project: https://bun.sh"),process.exit(1);let proc=Bun.spawn([bun,decision.cli,...decision.argv],{stdio:["inherit","inherit","inherit"]});process.exit(await proc.exited)}case"cli":{await Promise.resolve().then(() => init_cloudflare_stubs());stubCloudflareModules();await Promise.resolve().then(() => init_app());await runCli(decision.argv,await loadTools(project,projectCli===self));break}case"app":{await Promise.resolve().then(() => init_utils());let{ElysiumError}=await import("@elysiumjs/core");try{await new(await resolveAppEntry(decision.project))().run(decision.argv)}catch(error){if(!(error instanceof ElysiumError))throw error;console.error(error.message),process.exit(1)}break}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elysiumjs/styx",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.2",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "The command line tool of the Elysium.js framework: creates projects, generates code and runs app commands.",
|
|
6
6
|
"private": false,
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
],
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@elysiumjs/core": "0.12.0",
|
|
52
|
-
"@elysiumjs/hephaestus": "0.
|
|
52
|
+
"@elysiumjs/hephaestus": "0.5.0",
|
|
53
53
|
"@elysiumjs/runtime-bun": "0.1.1",
|
|
54
54
|
"@types/prompts": "^2.4.9",
|
|
55
55
|
"@types/string-template": "^1.0.7",
|