arcanajs 5.0.0 → 5.0.1

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/cli/index.js CHANGED
@@ -1,2 +1,3 @@
1
- (()=>{"use strict";var __webpack_modules__={14:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{dynamicRequire:()=>dynamicRequire});const dynamicRequire=id=>{try{var _global$process;const e=global,t=null===(_global$process=e.process)||void 0===_global$process||null===(_global$process=_global$process.mainModule)||void 0===_global$process?void 0:_global$process.require;if(t)return t(id)}catch(e){}return eval("require")(id)}},896:e=>{e.exports=require("fs")},916:e=>{e.exports=require("ts-node")},928:e=>{e.exports=require("path")}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var s=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](s,s.exports,__webpack_require__),s.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var s=Object.create(null);__webpack_require__.r(s);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var a=2&t&&e;("object"==typeof a||"function"==typeof a)&&!~leafPrototypes.indexOf(a);a=getProto(a))Object.getOwnPropertyNames(a).forEach(t=>n[t]=()=>e[t]);return n.default=()=>e,__webpack_require__.d(s,n),s},__webpack_require__.d=(e,t)=>{for(var s in t)__webpack_require__.o(t,s)&&!__webpack_require__.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};const external_child_process_namespaceObject=require("child_process"),external_dotenv_namespaceObject=require("dotenv");var external_dotenv_default=__webpack_require__.n(external_dotenv_namespaceObject),external_fs_=__webpack_require__(896),external_fs_default=__webpack_require__.n(external_fs_),external_path_=__webpack_require__(928),external_path_default=__webpack_require__.n(external_path_);const external_webpack_namespaceObject=require("webpack");var external_webpack_default=__webpack_require__.n(external_webpack_namespaceObject);const external_clean_webpack_plugin_namespaceObject=require("clean-webpack-plugin"),external_html_webpack_plugin_namespaceObject=require("html-webpack-plugin");var external_html_webpack_plugin_default=__webpack_require__.n(external_html_webpack_plugin_namespaceObject);const external_mini_css_extract_plugin_namespaceObject=require("mini-css-extract-plugin");var external_mini_css_extract_plugin_default=__webpack_require__.n(external_mini_css_extract_plugin_namespaceObject);const external_webpack_node_externals_namespaceObject=require("webpack-node-externals");var external_webpack_node_externals_default=__webpack_require__.n(external_webpack_node_externals_namespaceObject);const cwd=process.cwd(),resolveLoader=e=>require.resolve(e),findEntry=e=>{const t=[".ts",".tsx",".js",".jsx"];for(const s of e)for(const e of t){const t=external_path_default().resolve(cwd,s+e);if(external_fs_default().existsSync(t))return t;const n=external_path_default().resolve(cwd,s,"index"+e);if(external_fs_default().existsSync(n))return n}const s=external_path_default().resolve(cwd,"src/example/client/index.tsx"),n=external_path_default().resolve(cwd,"src/example/server/index.ts");if(e.some(e=>e.includes("client"))&&external_fs_default().existsSync(s))return s;if(e.some(e=>e.includes("server"))&&external_fs_default().existsSync(n))return n;throw new Error(`Could not find entry point. Searched in: ${e.join(", ")}`)},getViewsLoaderPath=()=>{const e=external_path_default().resolve(cwd,"src/resources/views"),t=external_fs_default().existsSync(e),s=external_path_default().resolve(__dirname,"../../node_modules/.cache/arcanajs/views-loader.js"),n=external_path_default().dirname(s);external_fs_default().existsSync(n)||external_fs_default().mkdirSync(n,{recursive:!0});const a=t?`module.exports = require.context('${e}', true, /\\.(tsx|jsx)$/);`:"module.exports = null;";return external_fs_default().writeFileSync(s,a),s},createClientConfig=()=>{const e="production"===process.env.NODE_ENV,t=getViewsLoaderPath();return{mode:e?"production":"development",target:"web",entry:{client:findEntry(["src/bootstrap/client"])},output:{path:external_path_default().resolve(cwd,"dist/public"),filename:e?"[name].[contenthash].bundle.js":"[name].bundle.js",publicPath:"/",assetModuleFilename:"assets/[hash][ext][query]"},resolve:{extensions:[".ts",".tsx",".js",".jsx"],alias:{"arcana-views":t,"@":external_path_default().resolve(cwd,"src")}},resolveLoader:{modules:["node_modules",external_path_default().resolve(__dirname,"../../node_modules")]},module:{rules:[{test:/\.(ts|tsx|js|jsx)$/,exclude:/node_modules/,use:{loader:resolveLoader("babel-loader"),options:{presets:[resolveLoader("@babel/preset-env"),[resolveLoader("@babel/preset-react"),{runtime:"automatic"}],resolveLoader("@babel/preset-typescript")]}}},{test:/\.module\.css$/,use:[e?external_mini_css_extract_plugin_default().loader:resolveLoader("style-loader"),{loader:resolveLoader("css-loader"),options:{importLoaders:1,modules:{localIdentName:e?"[hash:base64:8]":"[path][name]__[local]--[hash:base64:5]",exportLocalsConvention:"camelCaseOnly"}}},{loader:resolveLoader("postcss-loader"),options:{postcssOptions:{config:external_path_default().resolve(cwd,"postcss.config.js")}}}]},{test:/\.css$/,exclude:/\.module\.css$/,use:[e?external_mini_css_extract_plugin_default().loader:resolveLoader("style-loader"),{loader:resolveLoader("css-loader"),options:{importLoaders:1}},{loader:resolveLoader("postcss-loader"),options:{postcssOptions:{config:external_path_default().resolve(cwd,"postcss.config.js")}}}]},{test:/\.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf|otf)$/i,type:"asset/resource"}]},plugins:[new external_clean_webpack_plugin_namespaceObject.CleanWebpackPlugin,new(external_html_webpack_plugin_default())({templateContent:'<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n \x3c!--HEAD_CONTENT--\x3e\n </head>\n <body>\n <div id="root">\x3c!--APP_CONTENT--\x3e</div>\n \x3c!--ARCANAJS_DATA_SCRIPT--\x3e\n </body>\n</html>',filename:"index.html",inject:"body",minify:!!e&&{removeComments:!1,collapseWhitespace:!0,removeRedundantAttributes:!0,useShortDoctype:!0,removeEmptyAttributes:!0,removeStyleLinkTypeAttributes:!0,keepClosingSlash:!0,minifyJS:!0,minifyCSS:!0,minifyURLs:!0}}),new(external_mini_css_extract_plugin_default())({filename:e?"[name].[contenthash].css":"[name].css"})],optimization:{splitChunks:{chunks:"all",cacheGroups:{defaultVendors:{test:/[\\/]node_modules[\\/]/,priority:-10,reuseExistingChunk:!0},default:{minChunks:2,priority:-20,reuseExistingChunk:!0},react:{test:/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,name:"react-vendor",chunks:"all",priority:10}}}},performance:{maxEntrypointSize:512e3,maxAssetSize:512e3,hints:!!e&&"warning"},devtool:e?"source-map":"eval-source-map"}},createServerConfig=()=>{const e="production"===process.env.NODE_ENV,t=findEntry(["src/bootstrap/server"]),s=getViewsLoaderPath();return{mode:e?"production":"development",target:"node",entry:t,output:{path:external_path_default().resolve(cwd,"dist"),filename:"server.js"},externals:[external_webpack_node_externals_default()({allowlist:[/^arcanajs/]})],resolve:{extensions:[".ts",".tsx",".js",".jsx"],alias:{"arcana-views":s,"@":external_path_default().resolve(cwd,"src")}},resolveLoader:{modules:["node_modules",external_path_default().resolve(__dirname,"../../node_modules")]},module:{rules:[{test:/\.(ts|tsx|js|jsx)$/,exclude:/node_modules/,use:{loader:resolveLoader("babel-loader"),options:{presets:[resolveLoader("@babel/preset-env"),[resolveLoader("@babel/preset-react"),{runtime:"automatic"}],resolveLoader("@babel/preset-typescript")]}}},{test:/\.module\.css$/,use:{loader:resolveLoader("css-loader"),options:{modules:{localIdentName:e?"[hash:base64:8]":"[path][name]__[local]--[hash:base64:5]",exportLocalsConvention:"camelCaseOnly",exportOnlyLocals:!0}}}},{test:/\.css$/,exclude:/\.module\.css$/,use:resolveLoader("null-loader")},{test:/\.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf|otf)$/i,type:"asset/resource",generator:{emit:!1}}]},devtool:e?"source-map":"eval-source-map"}},external_ws_namespaceObject=require("ws");var dynamicRequire=__webpack_require__(14);class MongoAdapter{client=null;db=null;async connect(e){const{MongoClient:t}=(0,dynamicRequire.dynamicRequire)("mongodb"),s=`mongodb://${e.host}:${e.port}`;return this.client=new t(s,{auth:e.username&&e.password?{username:e.username,password:e.password}:void 0}),await this.client.connect(),this.db=this.client.db(e.database),{query:async(e,t)=>{throw new Error("Raw SQL queries are not supported in MongoDB adapter")},execute:async(e,t)=>{throw new Error("Raw SQL execution is not supported in MongoDB adapter")},close:async()=>{await this.disconnect()}}}async disconnect(){this.client&&(await this.client.close(),this.client=null,this.db=null)}async createTable(e,t){if(!this.db)throw new Error("Database not connected");await this.db.createCollection(e)}async dropTable(e){if(!this.db)throw new Error("Database not connected");await this.db.collection(e).drop()}async hasTable(e){if(!this.db)throw new Error("Database not connected");return(await this.db.listCollections({name:e}).toArray()).length>0}async hasColumn(e,t){return!0}async select(e,t){if(!this.db)throw new Error("Database not connected");const s=this.db.collection(e),n=this.buildFilter(t.where||[]),a=this.buildProjection(t.columns);let r=s.find(n);if(a&&(r=r.project(a)),t.orderBy){const e={};t.orderBy.forEach(t=>{e[t.column]="ASC"===t.direction?1:-1}),r=r.sort(e)}return t.offset&&(r=r.skip(t.offset)),t.limit&&(r=r.limit(t.limit)),(await r.toArray()).map(e=>{const{_id:t,...s}=e;return{id:t,_id:t,...s}})}async insert(e,t){if(!this.db)throw new Error("Database not connected");const s=this.db.collection(e),n={...t};n.id&&(n._id=n.id,delete n.id);const a=await s.insertOne(n);return{id:a.insertedId,_id:a.insertedId,...t}}async update(e,t,s){if(!this.db)throw new Error("Database not connected");const n=this.db.collection(e),a={_id:this.normalizeId(t)},r={$set:s};await n.updateOne(a,r);const o=await n.findOne(a);if(o){const{_id:e,...t}=o;return{id:e,_id:e,...t}}return null}async delete(e,t){if(!this.db)throw new Error("Database not connected");const s=this.db.collection(e);return 1===(await s.deleteOne({_id:this.normalizeId(t)})).deletedCount}async beginTransaction(){}async raw(e,t=[]){if(!this.db)throw new Error("Database not connected");return"db"===e?this.db:await this.db.command(JSON.parse(e))}async commit(){}async rollback(){}buildFilter(e){const t={};return e.forEach(e=>{const s="id"===e.column?"_id":e.column;let n=e.value;switch("_id"===s&&(n=this.normalizeId(n)),e.operator){case"=":t[s]=n;break;case"!=":t[s]={$ne:n};break;case">":t[s]={$gt:n};break;case"<":t[s]={$lt:n};break;case">=":t[s]={$gte:n};break;case"<=":t[s]={$lte:n};break;case"IN":t[s]={$in:Array.isArray(n)?n:[n]};break;case"NOT IN":t[s]={$nin:Array.isArray(n)?n:[n]};break;case"LIKE":t[s]={$regex:new RegExp(n.replace(/%/g,".*"),"i")};break;case"IS NULL":t[s]=null;break;case"IS NOT NULL":t[s]={$ne:null}}}),t}buildProjection(e){if(!e||0===e.length||e.includes("*"))return null;const t={};return e.forEach(e=>{"id"===e||(t[e]=1)}),t}normalizeId(e){const{ObjectId:t}=(0,dynamicRequire.dynamicRequire)("mongodb");return e instanceof t?e:"string"==typeof e&&t.isValid(e)?new t(e):e}}class MySQLAdapter{pool=null;connection=null;async connect(e){var t;const s=(0,dynamicRequire.dynamicRequire)("mysql2/promise");return this.pool=s.createPool({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,waitForConnections:!0,connectionLimit:(null===(t=e.pool)||void 0===t?void 0:t.max)||10,queueLimit:0}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){if(!this.pool)throw new Error("Database not connected");const[s]=await this.pool.query(e,t);return s}async execute(e,t){if(!this.pool)throw new Error("Database not connected");const[s]=await this.pool.execute(e,t);return s}async createTable(e,t){const s=`CREATE TABLE IF NOT EXISTS \`${e}\` (${t.map(e=>{let t=`\`${e.name}\` ${this.mapType(e.type,e.length)}`;return e.unsigned&&(t+=" UNSIGNED"),e.autoIncrement&&(t+=" AUTO_INCREMENT"),e.nullable||(t+=" NOT NULL"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),e.primary&&(t+=" PRIMARY KEY"),e.unique&&(t+=" UNIQUE"),t}).join(", ")}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;await this.execute(s)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS \`${e}\``)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT COUNT(*) as count FROM information_schema.tables \n WHERE table_schema = DATABASE() AND table_name = ?",[e]))[0])||void 0===t?void 0:t.count)>0}async hasColumn(e,t){var s;return(null===(s=(await this.query("SELECT COUNT(*) as count FROM information_schema.columns \n WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",[e,t]))[0])||void 0===s?void 0:s.count)>0}async select(e,t){var s;let n=`SELECT ${(null===(s=t.columns)||void 0===s?void 0:s.join(", "))||"*"} FROM \`${e}\``;const a=[];if(t.joins&&t.joins.length>0)for(const e of t.joins)n+=` ${e.type} JOIN \`${e.table}\` ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(n+=" "+t.where.map((e,t)=>`${0===t?"WHERE":e.boolean} ${this.buildWhereCondition(e,a)}`).join(" ")),t.orderBy&&t.orderBy.length>0&&(n+=` ORDER BY ${t.orderBy.map(e=>`\`${e.column}\` ${e.direction}`).join(", ")}`),t.limit&&(n+=" LIMIT ?",a.push(t.limit)),t.offset&&(n+=" OFFSET ?",a.push(t.offset)),await this.query(n,a)}async insert(e,t){const s=Object.keys(t),n=Object.values(t),a=n.map(()=>"?").join(", "),r=`INSERT INTO \`${e}\` (${s.map(e=>`\`${e}\``).join(", ")}) VALUES (${a})`;return{id:(await this.execute(r,n)).insertId,...t}}async update(e,t,s){const n=Object.keys(s),a=Object.values(s),r=`UPDATE \`${e}\` SET ${n.map(e=>`\`${e}\` = ?`).join(", ")} WHERE id = ?`;return await this.execute(r,[...a,t]),{id:t,...s}}async delete(e,t){const s=`DELETE FROM \`${e}\` WHERE id = ?`;return(await this.execute(s,[t])).affectedRows>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.connection=await this.pool.getConnection(),await this.connection.beginTransaction()}async commit(){if(!this.connection)throw new Error("No active transaction");await this.connection.commit(),this.connection.release(),this.connection=null}async rollback(){if(!this.connection)throw new Error("No active transaction");await this.connection.rollback(),this.connection.release(),this.connection=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");const[s]=await this.pool.execute(e,t);return s}buildWhereCondition(e,t){const s=`\`${e.column}\``;switch(e.operator){case"IN":const n=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${s} IN (${n})`;case"NOT IN":const a=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${s} NOT IN (${a})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${s} BETWEEN ? AND ?`;case"IS NULL":return`${s} IS NULL`;case"IS NOT NULL":return`${s} IS NOT NULL`;default:return t.push(e.value),`${s} ${e.operator} ?`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INT",bigInteger:"BIGINT",float:"FLOAT",double:"DOUBLE",decimal:"DECIMAL(10,2)",boolean:"TINYINT(1)",date:"DATE",datetime:"DATETIME",timestamp:"TIMESTAMP",json:"JSON",uuid:"CHAR(36)"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"1":"0":e instanceof Date?`'${e.toISOString().slice(0,19).replace("T"," ")}'`:String(e)}}class PostgresAdapter{pool=null;client=null;async connect(e){var t,s;const{Pool:n}=(0,dynamicRequire.dynamicRequire)("pg");return this.pool=new n({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,ssl:e.ssl,min:(null===(t=e.pool)||void 0===t?void 0:t.min)||2,max:(null===(s=e.pool)||void 0===s?void 0:s.max)||10}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}async execute(e,t){if(!this.pool)throw new Error("Database not connected");return await this.pool.query(e,t)}async createTable(e,t){const s=`CREATE TABLE IF NOT EXISTS "${e}" (${t.map(e=>{let t=`"${e.name}" ${this.mapType(e.type,e.length)}`;return e.primary&&(t+=" PRIMARY KEY"),e.autoIncrement&&(t+=" GENERATED ALWAYS AS IDENTITY"),e.nullable||(t+=" NOT NULL"),e.unique&&(t+=" UNIQUE"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),t}).join(", ")})`;await this.execute(s)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS "${e}"`)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.tables \n WHERE table_schema = 'public' \n AND table_name = $1\n )",[e]))[0])||void 0===t?void 0:t.exists)||!1}async hasColumn(e,t){var s;return(null===(s=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.columns \n WHERE table_schema = 'public' \n AND table_name = $1 \n AND column_name = $2\n )",[e,t]))[0])||void 0===s?void 0:s.exists)||!1}async select(e,t){var s;let n=`SELECT ${(null===(s=t.columns)||void 0===s?void 0:s.join(", "))||"*"} FROM "${e}"`;const a=[];let r=1;if(t.joins&&t.joins.length>0)for(const e of t.joins)n+=` ${e.type} JOIN "${e.table}" ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(n+=" "+t.where.map((e,t)=>{const s=0===t?"WHERE":e.boolean,n=this.buildWhereCondition(e,a,r);return r=a.length+1,`${s} ${n}`}).join(" ")),t.orderBy&&t.orderBy.length>0&&(n+=` ORDER BY ${t.orderBy.map(e=>`"${e.column}" ${e.direction}`).join(", ")}`),t.limit&&(n+=" LIMIT $"+r++,a.push(t.limit)),t.offset&&(n+=" OFFSET $"+r++,a.push(t.offset)),await this.query(n,a)}async insert(e,t){const s=Object.keys(t),n=Object.values(t),a=n.map((e,t)=>`$${t+1}`).join(", "),r=`INSERT INTO "${e}" (${s.map(e=>`"${e}"`).join(", ")}) \n VALUES (${a}) \n RETURNING *`;return(await this.query(r,n))[0]}async update(e,t,s){const n=Object.keys(s),a=Object.values(s),r=`UPDATE "${e}" SET ${n.map((e,t)=>`"${e}" = $${t+1}`).join(", ")} WHERE id = $${n.length+1} RETURNING *`;return(await this.query(r,[...a,t]))[0]}async delete(e,t){const s=`DELETE FROM "${e}" WHERE id = $1`;return(await this.execute(s,[t])).rowCount>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.client=await this.pool.connect(),await this.client.query("BEGIN")}async commit(){if(!this.client)throw new Error("No active transaction");await this.client.query("COMMIT"),this.client.release(),this.client=null}async rollback(){if(!this.client)throw new Error("No active transaction");await this.client.query("ROLLBACK"),this.client.release(),this.client=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}buildWhereCondition(e,t,s){const n=`"${e.column}"`;switch(e.operator){case"IN":const a=e.value.map((e,t)=>`$${s+t}`).join(", ");return t.push(...e.value),`${n} IN (${a})`;case"NOT IN":const r=e.value.map((e,t)=>`$${s+t}`).join(", ");return t.push(...e.value),`${n} NOT IN (${r})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${n} BETWEEN $${s} AND $${s+1}`;case"IS NULL":return`${n} IS NULL`;case"IS NOT NULL":return`${n} IS NOT NULL`;default:return t.push(e.value),`${n} ${e.operator} $${s}`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INTEGER",bigInteger:"BIGINT",float:"REAL",double:"DOUBLE PRECISION",decimal:"DECIMAL",boolean:"BOOLEAN",date:"DATE",datetime:"TIMESTAMP",timestamp:"TIMESTAMP",json:"JSONB",uuid:"UUID"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"TRUE":"FALSE":e instanceof Date?`'${e.toISOString()}'`:String(e)}}class Macroable{static macros={};static macro(e,t){this.macros[e]=t,this.prototype[e]=t}static mixin(e){Object.keys(e).forEach(t=>{this.macro(t,e[t])})}static hasMacro(e){return!!this.macros[e]}}class QueryBuilder extends Macroable{selectColumns=["*"];whereClauses=[];orderByClauses=[];joinClauses=[];constructor(e,t){super(),this.tableName=e,this.adapter=t}select(...e){return this.selectColumns=e,this}where(e,t,s){return void 0===s&&(s=t,t="="),this.whereClauses.push({column:e,operator:t,value:s,boolean:"AND"}),this}orWhere(e,t,s){return void 0===s&&(s=t,t="="),this.whereClauses.push({column:e,operator:t,value:s,boolean:"OR"}),this}whereIn(e,t){return this.whereClauses.push({column:e,operator:"IN",value:t,boolean:"AND"}),this}whereNotIn(e,t){return this.whereClauses.push({column:e,operator:"NOT IN",value:t,boolean:"AND"}),this}whereBetween(e,t){return this.whereClauses.push({column:e,operator:"BETWEEN",value:t,boolean:"AND"}),this}whereNull(e){return this.whereClauses.push({column:e,operator:"IS NULL",value:null,boolean:"AND"}),this}whereNotNull(e){return this.whereClauses.push({column:e,operator:"IS NOT NULL",value:null,boolean:"AND"}),this}orderBy(e,t="ASC"){return this.orderByClauses.push({column:e,direction:t.toUpperCase()}),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}join(e,t,s,n,a="INNER"){return this.joinClauses.push({type:a,table:e,first:t,operator:s,second:n}),this}leftJoin(e,t,s,n){return this.join(e,t,s,n,"LEFT")}rightJoin(e,t,s,n){return this.join(e,t,s,n,"RIGHT")}eagerLoads=[];setModel(e){return this.model=e,this}with(e){return Array.isArray(e)?this.eagerLoads.push(...e):this.eagerLoads.push(e),this}async get(){const e={columns:this.selectColumns,where:this.whereClauses,orderBy:this.orderByClauses,limit:this.limitValue,offset:this.offsetValue,joins:this.joinClauses},t=await this.adapter.select(this.tableName,e);return this.eagerLoads.length>0&&this.model?await this.eagerLoadRelations(t):t}async eagerLoadRelations(e){if(0===e.length)return e;const t=e.map(e=>this.model.hydrate(e));for(const e of this.eagerLoads){const s=new this.model;if("function"!=typeof s[e])throw new Error(`Relation ${e} does not exist on ${this.model.name}`);const n=s[e]();n.addEagerConstraints(t);const a=await n.get();n.match(t,a,e)}return t}async first(){return this.limit(1),(await this.get())[0]||null}async find(e){return this.where("id",e).first()}async count(){this.selectColumns=["COUNT(*) as count"];const e=await this.first();return e?e.count:0}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async sum(e){this.selectColumns=[`SUM(${e}) as sum`];const t=await this.first();return t&&t.sum||0}async avg(e){this.selectColumns=[`AVG(${e}) as avg`];const t=await this.first();return t&&t.avg||0}async min(e){this.selectColumns=[`MIN(${e}) as min`];const t=await this.first();return t?t.min:null}async max(e){this.selectColumns=[`MAX(${e}) as max`];const t=await this.first();return t?t.max:null}async exists(){return await this.count()>0}async paginate(e=1,t=15){const s=await this.count(),n=(e-1)*t;return this.limit(t).offset(n),{data:await this.get(),total:s,perPage:t,currentPage:e,lastPage:Math.ceil(s/t)}}clone(){const e=new QueryBuilder(this.tableName,this.adapter);return e.selectColumns=[...this.selectColumns],e.whereClauses=[...this.whereClauses],e.orderByClauses=[...this.orderByClauses],e.joinClauses=[...this.joinClauses],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e}}class Relation{constructor(e,t){this.query=e,this.parent=t,this.related=e.model,this.addConstraints()}getQuery(){return this.query}async get(){return this.query.get()}async first(){return this.query.first()}}class BelongsTo extends Relation{constructor(e,t,s,n){super(e,t),this.foreignKey=s,this.ownerKey=n}addConstraints(){const e=this.parent.getAttribute(this.foreignKey);this.query.where(this.ownerKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.foreignKey)).filter(e=>null!==e);this.query.whereIn(this.ownerKey,t)}match(e,t,s){const n={};return t.forEach(e=>{const t=e.getAttribute(this.ownerKey);n[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.foreignKey);n[t]&&e.setRelation(s,n[t])}),e}}class BelongsToMany extends Relation{constructor(e,t,s,n,a,r,o){super(e,t),this.table=s,this.foreignPivotKey=n,this.relatedPivotKey=a,this.parentKey=r,this.relatedKey=o}addConstraints(){this.performJoin(),this.query.where(`${this.table}.${this.foreignPivotKey}`,"=",this.parent.getAttribute(this.parentKey))}performJoin(e){const t=e||this.query,s=this.related.prototype.getTable();return t.join(this.table,`${s}.${this.relatedKey}`,"=",`${this.table}.${this.relatedPivotKey}`),this}addEagerConstraints(e){this.performJoin();const t=e.map(e=>e.getAttribute(this.parentKey)).filter(e=>null!==e);this.query.whereIn(`${this.table}.${this.foreignPivotKey}`,t)}match(e,t,s){return e}}class HasMany extends Relation{constructor(e,t,s,n){super(e,t),this.foreignKey=s,this.localKey=n}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,s){const n={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);n[t]||(n[t]=[]),n[t].push(e)}),e.forEach(e=>{const t=e.getAttribute(this.localKey);n[t]?e.setRelation(s,n[t]):e.setRelation(s,[])}),e}}class HasOne extends Relation{constructor(e,t,s,n){super(e,t),this.foreignKey=s,this.localKey=n}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,s){const n={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);n[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.localKey);n[t]&&e.setRelation(s,n[t])}),e}}class Model extends Macroable{static primaryKey="id";static connection="default";attributes={};original={};relations={};exists=!1;fillable=[];guarded=["id"];hidden=[];visible=[];casts={};dates=[];timestamps=!0;createdAt="created_at";updatedAt="updated_at";softDeletes=!1;deletedAt="deleted_at";static setAdapter(e){this.adapter=e}static getTable(){if(this.tableName)return this.tableName;const e=this.name;return this.pluralize(this.snakeCase(e))}static query(){return new QueryBuilder(this.getTable(),this.adapter)}static async all(){return(await this.query().get()).map(e=>this.hydrate(e))}static async find(e){const t=await this.query().where(this.primaryKey,e).first();return t?this.hydrate(t):null}static async findOrFail(e){const t=await this.find(e);if(!t)throw new Error(`Model not found with ${this.primaryKey}: ${e}`);return t}static where(e,t,s){return this.query().where(e,t,s)}static async create(e){const t=new this;if(t.fill(e),t.timestamps){const e=new Date;t.attributes[t.createdAt]=e,t.attributes[t.updatedAt]=e}const s=await this.adapter.insert(this.getTable(),t.attributes),n=s[this.primaryKey]||s.id||s.insertId;return t.attributes[this.primaryKey]=n,"id"!==this.primaryKey&&(t.attributes.id=n),t.exists=!0,t.syncOriginal(),t}static async update(e,t){const s=await this.findOrFail(e);return await s.update(t),s}static async destroy(e){const t=await this.find(e);return!!t&&await t.delete()}static async firstOrCreate(e,t={}){const s=this.query();for(const[t,n]of Object.entries(e))s.where(t,n);const n=await s.first();return n?this.hydrate(n):await this.create({...e,...t})}static async updateOrCreate(e,t={}){const s=this.query();for(const[t,n]of Object.entries(e))s.where(t,n);const n=await s.first();if(n){const e=this.hydrate(n);return await e.update(t),e}return await this.create({...e,...t})}static hydrate(e){const t=new this;return t.attributes={...e},t.original={...e},t.exists=!0,t}fill(e){for(const[t,s]of Object.entries(e))this.isFillable(t)&&this.setAttribute(t,s);return this}isFillable(e){return this.fillable.length>0?this.fillable.includes(e):!this.guarded.includes(e)}setAttribute(e,t){const s=`set${this.studly(e)}Attribute`;"function"==typeof this[s]&&(t=this[s](t)),this.attributes[e]=this.castAttribute(e,t)}getAttribute(e){const t=`get${this.studly(e)}Attribute`;if("function"==typeof this[t])return this[t]();const s=this.attributes[e];return this.castAttribute(e,s,!0)}castAttribute(e,t,s=!1){if(null==t)return t;const n=this.casts[e];if(!n)return t;if(s)switch(n){case"int":case"integer":return parseInt(t);case"float":case"double":return parseFloat(t);case"string":return String(t);case"bool":case"boolean":return Boolean(t);case"array":case"json":return"string"==typeof t?JSON.parse(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}else switch(n){case"array":case"json":return"object"==typeof t?JSON.stringify(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}}async save(){const e=this.constructor;if(this.timestamps){const e=new Date;this.exists||(this.attributes[this.createdAt]=e),this.attributes[this.updatedAt]=e}if(this.exists){const t=this.attributes[e.primaryKey];await e.adapter.update(e.getTable(),t,this.attributes)}else{const t=await e.adapter.insert(e.getTable(),this.attributes),s=t[e.primaryKey]||t.id||t.insertId;this.attributes[e.primaryKey]=s,"id"!==e.primaryKey&&(this.attributes.id=s),this.exists=!0}return this.syncOriginal(),this}async update(e){return this.fill(e),await this.save()}async delete(){const e=this.constructor;if(this.softDeletes)return this.attributes[this.deletedAt]=new Date,await this.save(),!0;const t=this.attributes[e.primaryKey];return await e.adapter.delete(e.getTable(),t)}async forceDelete(){const e=this.constructor,t=this.attributes[e.primaryKey];return await e.adapter.delete(e.getTable(),t)}async restore(){return this.softDeletes&&(this.attributes[this.deletedAt]=null,await this.save()),this}syncOriginal(){this.original={...this.attributes}}getDirty(){const e={};for(const[t,s]of Object.entries(this.attributes))this.original[t]!==s&&(e[t]=s);return e}isDirty(){return Object.keys(this.getDirty()).length>0}constructor(e={}){super(),this.fill(e)}toJSON(){const e={};for(const[t,s]of Object.entries(this.attributes))this.hidden.includes(t)||this.visible.length>0&&!this.visible.includes(t)||(e[t]=this.getAttribute(t));for(const[t,s]of Object.entries(this.relations))e[t]=s;return e}hasOne(e,t,s){const n=new e,a=t||`${this.constructor.name.toLowerCase()}_id`,r=s||"id";return new HasOne(n.newQuery(),this,a,r)}hasMany(e,t,s){const n=new e,a=t||`${this.constructor.name.toLowerCase()}_id`,r=s||"id";return new HasMany(n.newQuery(),this,a,r)}belongsTo(e,t,s){const n=new e,a=t||`${n.constructor.name.toLowerCase()}_id`,r=s||"id";return new BelongsTo(n.newQuery(),this,a,r)}belongsToMany(e,t,s,n,a,r){const o=new e,i=t||this.guessPivotTable(o),l=s||`${this.constructor.name.toLowerCase()}_id`,c=n||`${o.constructor.name.toLowerCase()}_id`,u=a||"id",d=r||"id";return new BelongsToMany(o.newQuery(),this,i,l,c,u,d)}guessPivotTable(e){const t=[this.constructor.name.toLowerCase(),e.constructor.name.toLowerCase()];return t.sort(),t.join("_")}static with(e){return this.query().with(e)}setRelation(e,t){return this.relations[e]=t,this}getRelation(e){return this.relations[e]}relationLoaded(e){return void 0!==this.relations[e]}newQuery(){return this.constructor.query()}static snakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}static pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")?e+"es":e+"s"}studly(e){return e.replace(/(^|_)(\w)/g,(e,t,s)=>s.toUpperCase())}}const handleDb=async e=>{const t=e[0];"db:seed"!==t&&(console.error(`Unknown db command: ${t}`),process.exit(1));const s=external_path_default().resolve(process.cwd(),"src/config/database");try{__webpack_require__(916).register({transpileOnly:!0,compilerOptions:{module:"commonjs"}})}catch(e){}const{dynamicRequire:n}=__webpack_require__(14);let a,r;try{const e=n(s);a=e.default||e.databaseConfig||e}catch(e){console.error("Failed to load database config:",e),process.exit(1)}"postgres"===a.type?r=new PostgresAdapter:"mongodb"===a.type?r=new MongoAdapter:"mysql"===a.type?r=new MySQLAdapter:(console.error(`Unsupported database type: ${a.type}`),process.exit(1));try{await r.connect(a),Model.setAdapter(r);const e=n(external_path_default().resolve(process.cwd(),"database/seeders/DatabaseSeeder.ts")),t=e.default||e.DatabaseSeeder;if(!t)throw new Error("DatabaseSeeder not found");console.log("Seeding database...");const s=new t;await s.run(),console.log("Database seeded successfully")}catch(e){console.error("Seeding failed:",e),process.exit(1)}finally{await r.disconnect()}},detectPackageManager=()=>{const e=process.cwd();return external_fs_default().existsSync(external_path_default().join(e,"bun.lockb"))?"bun":external_fs_default().existsSync(external_path_default().join(e,"pnpm-lock.yaml"))?"pnpm":external_fs_default().existsSync(external_path_default().join(e,"yarn.lock"))?"yarn":"npm"},getInstallCommand=(e,t)=>{const s=t.join(" ");switch(e){case"npm":return`npm install ${s}`;case"yarn":return`yarn add ${s}`;case"pnpm":return`pnpm add ${s}`;case"bun":return`bun add ${s}`}},installDependencies=(e,t=[])=>{const s=detectPackageManager();if(console.log(`\nšŸ“¦ Detected package manager: ${s}\n`),e.length>0){console.log(`Installing dependencies: ${e.join(", ")}`);const t=getInstallCommand(s,e);try{(0,external_child_process_namespaceObject.execSync)(t,{stdio:"inherit"}),console.log("āœ… Dependencies installed successfully!\n")}catch(e){console.error("āŒ Failed to install dependencies"),process.exit(1)}}if(t.length>0){let e;switch(console.log(`Installing dev dependencies: ${t.join(", ")}`),s){case"npm":e=`npm install --save-dev ${t.join(" ")}`;break;case"yarn":e=`yarn add --dev ${t.join(" ")}`;break;case"pnpm":e=`pnpm add -D ${t.join(" ")}`;break;case"bun":e=`bun add -d ${t.join(" ")}`}try{(0,external_child_process_namespaceObject.execSync)(e,{stdio:"inherit"}),console.log("āœ… Dev dependencies installed successfully!\n")}catch(e){console.error("āŒ Failed to install dev dependencies"),process.exit(1)}}},installAuthDependencies=()=>{console.log("šŸ” Installing Auth Provider dependencies...\n"),installDependencies(["jsonwebtoken","bcryptjs","redis","connect-redis","express-session"],["@types/jsonwebtoken","@types/bcryptjs","@types/express-session"]),console.log("✨ Auth Provider dependencies installed!"),console.log("You can now use AuthProvider in your application.\n")},installMailDependencies=()=>{console.log("šŸ“§ Installing Mail Provider dependencies...\n"),installDependencies(["nodemailer","ejs","handlebars","ioredis","@aws-sdk/client-ses","@aws-sdk/credential-provider-node","nodemailer-mailgun-transport"],["@types/nodemailer","@types/ejs"]),console.log("✨ Mail Provider dependencies installed!"),console.log("You can now use MailProvider in your application.\n")},installDatabaseDependencies=e=>{console.log(`šŸ—„ļø Installing Database Provider dependencies for ${e}...\n`);let t=[],s=[];switch(e.toLowerCase()){case"mongo":case"mongodb":t=["mongodb"],console.log("Installing MongoDB dependencies...");break;case"postgres":case"postgresql":case"pg":t=["pg"],s=["@types/pg"],console.log("Installing PostgreSQL dependencies...");break;case"mysql":t=["mysql2"],console.log("Installing MySQL dependencies...");break;default:console.error(`āŒ Unknown database type: ${e}. Supported types: mongo, postgres, mysql`),process.exit(1)}const n=["@faker-js/faker","reflect-metadata",...t];installDependencies(n,s),console.log("✨ Database Provider dependencies installed!"),console.log("You can now use DatabaseProvider in your application.\n")},handleDependency=e=>{const t=e[0].split(":")[1];switch(t||(console.error("Please specify a dependency type: auth, mail, or database"),console.log("\nUsage:"),console.log(" npx arcanajs dependency:auth"),console.log(" npx arcanajs dependency:mail"),console.log(" npx arcanajs dependency:database [mongo|postgres|mysql]"),process.exit(1)),t){case"auth":installAuthDependencies();break;case"mail":installMailDependencies();break;case"database":const s=e[1];s||(console.error("Please specify a database type: mongo, postgres, or mysql"),console.log("\nUsage:"),console.log(" npx arcanajs dependency:database mongo"),console.log(" npx arcanajs dependency:database postgres"),console.log(" npx arcanajs dependency:database mysql"),process.exit(1)),installDatabaseDependencies(s);break;default:console.error(`Unknown dependency type: ${t}`),console.log("\nAvailable types:"),console.log(" - auth"),console.log(" - mail"),console.log(" - database"),process.exit(1)}},toPascalCase=e=>e.replace(/(^|_)(\w)/g,(e,t,s)=>s.toUpperCase()),writeFile=async(e,t,s)=>{const n=external_path_default().resolve(process.cwd(),`src/${e}`),a=external_path_default().join(n,t);external_fs_default().existsSync(n)||external_fs_default().mkdirSync(n,{recursive:!0}),external_fs_default().existsSync(a)&&(console.error(`File already exists: ${a}`),process.exit(1)),external_fs_default().writeFileSync(a,s),console.log(`Created: ${external_path_default().join(e,t)}`)},makeController=async(e,t="normal")=>{let s="";s="resource"===t?"\n async index(req: Request, res: Response) {\n //\n }\n\n async create(req: Request, res: Response) {\n //\n }\n\n async store(req: Request, res: Response) {\n //\n }\n\n async show(req: Request, res: Response) {\n //\n }\n\n async edit(req: Request, res: Response) {\n //\n }\n\n async update(req: Request, res: Response) {\n //\n }\n\n async destroy(req: Request, res: Response) {\n //\n }\n":"api"===t?"\n async index(req: Request, res: Response) {\n //\n }\n\n async store(req: Request, res: Response) {\n //\n }\n\n async show(req: Request, res: Response) {\n //\n }\n\n async update(req: Request, res: Response) {\n //\n }\n\n async destroy(req: Request, res: Response) {\n //\n }\n":"\n //\n";const n=`import { Request, Response } from 'arcanajs/server'\n\nclass ${toPascalCase(e)} {${s}}\n\nexport default ${toPascalCase(e)}\n`;await writeFile("app/Http/Controllers",`${toPascalCase(e)}.ts`,n)},Controller=makeController,makeFactory=async e=>{const t=e.replace("Factory",""),s=`import { Factory } from 'arcanajs/arcanox'\nimport { ${t} } from '@/app/Models/${t}'\n\nclass ${toPascalCase(e)} extends Factory<${t}> {\n protected model = ${t}\n\n definition() {\n return {\n //\n }\n }\n}\n\nexport default ${toPascalCase(e)}\n`;await writeFile("database/factories",`${toPascalCase(e)}.ts`,s)},Factory=makeFactory;async function makeMiddleware(e){const t=`import { Middleware, NextFunction, Request, Response } from "arcanajs/server";\n\nclass ${toPascalCase(e)} implements Middleware {\n public handle(req: Request, res: Response, next: NextFunction): void {\n // Middleware logic here\n next();\n }\n}\n\nexport default ${toPascalCase(e)}\n`;await writeFile("app/Http/Middleware",`${toPascalCase(e)}.ts`,t)}const makeMigration=async e=>{const t=new Date,s=e=>e.toString().padStart(2,"0"),n=`${t.getFullYear()}_${s(t.getMonth()+1)}_${s(t.getDate())}_${s(t.getHours())}${s(t.getMinutes())}${s(t.getSeconds())}_${e}.ts`,a=`import { Migration, Schema } from 'arcanajs/arcanox'\n\nclass ${toPascalCase(e)} extends Migration {\n async up() {\n // await Schema.create('${e}', (table) => {\n // table.id()\n // table.timestamps()\n // })\n }\n\n async down() {\n // await Schema.dropIfExists('${e}')\n }\n}\n\nexport default ${toPascalCase(e)}\n`;await writeFile("database/migrations",n,a)},Migration=makeMigration,makeModel=async e=>{const t=`import { Model } from 'arcanajs/arcanox'\n\nclass ${toPascalCase(e)} extends Model {\n // protected table = '${e.toLowerCase()}s'\n protected fillable = []\n}\n\nexport default ${toPascalCase(e)}\n`;await writeFile("app/Models",`${toPascalCase(e)}.ts`,t)},make_Model=makeModel;async function makeProvider(e){const t=`import { ServiceProvider } from "arcanajs/server";\n\nclass ${toPascalCase(e)} extends ServiceProvider {\n /**\n * Register any application services.\n */\n public register(): void {\n // Bind services to the container\n }\n\n /**\n * Bootstrap any application services.\n */\n public boot(): void {\n // Run code on application startup\n }\n}\n\nexport default ${toPascalCase(e)}`;await writeFile("app/Providers",`${toPascalCase(e)}.ts`,t)}async function makeRequest(e){const t=`import { FormRequest } from "arcanajs/validator";\n\nclass ${toPascalCase(e)} extends FormRequest {\n /**\n * Determine if the user is authorized to make this request.\n */\n public authorize(): boolean {\n return true;\n }\n\n /**\n * Get the validation rules that apply to the request.\n */\n public rules(): Record<string, string> {\n return {\n // 'field': 'required|string',\n };\n }\n}\n\nexport default ${toPascalCase(e)}`;await writeFile("app/Http/Requests",`${toPascalCase(e)}.ts`,t)}const makeSeeder=async e=>{const t=`import { Seeder } from 'arcanajs/arcanox'\n\nclass ${toPascalCase(e)} extends Seeder {\n async run() {\n //\n }\n}\n\nexport default ${toPascalCase(e)}\n`;await writeFile("database/seeders",`${toPascalCase(e)}.ts`,t)},Seeder=makeSeeder,handleMake=async e=>{const t=e[0].split(":")[1],s=e[1];switch(s||(console.error(`Please specify a name for the ${t}`),process.exit(1)),t){case"model":await make_Model(s),(e.includes("--all")||e.includes("-a"))&&(await Migration(`create_${s.toLowerCase()}s_table`),await Factory(`${s}Factory`),await Seeder(`${s}Seeder`),await Controller(`${s}Controller`,"resource"));break;case"controller":let n="normal";e.includes("--resource")||e.includes("-r")?n="resource":e.includes("--api")&&(n="api"),await Controller(s,n);break;case"migration":await Migration(s);break;case"seeder":await Seeder(s);break;case"factory":await Factory(s);break;case"request":await makeRequest(s);break;case"middleware":await makeMiddleware(s);break;case"provider":await makeProvider(s);break;default:console.error(`Unknown make command: make:${t}`),process.exit(1)}};class ColumnBuilder{constructor(e,t,s){this.definition={name:e,type:t,length:s,nullable:!1}}nullable(){return this.definition.nullable=!0,this}default(e){return this.definition.default=e,this}unique(){return this.definition.unique=!0,this}primary(){return this.definition.primary=!0,this}autoIncrement(){return this.definition.autoIncrement=!0,this}unsigned(){return this.definition.unsigned=!0,this}getDefinition(){return this.definition}}class ForeignKeyBuilder{constructor(e){this.column=e}references(e){return this.referencedColumn=e,this}on(e){return this.referencedTable=e,this}onDelete(e){return this.onDeleteAction=e,this}onUpdate(e){return this.onUpdateAction=e,this}toSQL(){if(!this.referencedTable||!this.referencedColumn)throw new Error("Foreign key must reference a table and column");let e=`FOREIGN KEY (${this.column}) REFERENCES ${this.referencedTable}(${this.referencedColumn})`;return this.onDeleteAction&&(e+=` ON DELETE ${this.onDeleteAction}`),this.onUpdateAction&&(e+=` ON UPDATE ${this.onUpdateAction}`),e}}class Blueprint{columns=[];indexes=[];foreignKeys=[];primaryKeys=[];constructor(e){this.tableName=e}id(e="id"){const t=new ColumnBuilder(e,"bigInteger");return t.primary().autoIncrement().unsigned(),this.columns.push(t.getDefinition()),t}uuid(e="id"){const t=new ColumnBuilder(e,"uuid");return this.columns.push(t.getDefinition()),t}string(e,t=255){const s=new ColumnBuilder(e,"string",t);return this.columns.push(s.getDefinition()),s}text(e){const t=new ColumnBuilder(e,"text");return this.columns.push(t.getDefinition()),t}integer(e){const t=new ColumnBuilder(e,"integer");return this.columns.push(t.getDefinition()),t}bigInteger(e){const t=new ColumnBuilder(e,"bigInteger");return this.columns.push(t.getDefinition()),t}decimal(e,t=10,s=2){const n=new ColumnBuilder(e,"decimal");return this.columns.push(n.getDefinition()),n}float(e){const t=new ColumnBuilder(e,"float");return this.columns.push(t.getDefinition()),t}double(e){const t=new ColumnBuilder(e,"double");return this.columns.push(t.getDefinition()),t}boolean(e){const t=new ColumnBuilder(e,"boolean");return this.columns.push(t.getDefinition()),t}date(e){const t=new ColumnBuilder(e,"date");return this.columns.push(t.getDefinition()),t}datetime(e){const t=new ColumnBuilder(e,"datetime");return this.columns.push(t.getDefinition()),t}timestamp(e){const t=new ColumnBuilder(e,"timestamp");return this.columns.push(t.getDefinition()),t}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}softDeletes(e="deleted_at"){return this.timestamp(e).nullable()}json(e){const t=new ColumnBuilder(e,"json");return this.columns.push(t.getDefinition()),t}enum(e,t){const s=new ColumnBuilder(e,"enum");return this.columns.push(s.getDefinition()),s}foreign(e){const t=new ForeignKeyBuilder(e);return this.foreignKeys.push(t),t}index(e,t){const s=Array.isArray(e)?e:[e];this.indexes.push({columns:s,unique:!1,name:t})}unique(e,t){const s=Array.isArray(e)?e:[e];this.indexes.push({columns:s,unique:!0,name:t})}primary(e){this.primaryKeys=Array.isArray(e)?e:[e]}getColumns(){return this.columns}getTableName(){return this.tableName}getIndexes(){return this.indexes}getForeignKeys(){return this.foreignKeys}}class Schema{static setAdapter(e){this.adapter=e}static async create(e,t){const s=new Blueprint(e);t(s),await this.adapter.createTable(e,s.getColumns())}static async table(e,t){t(new Blueprint(e)),console.warn("Schema.table() is not fully implemented yet. Use migrations for complex alterations.")}static async drop(e){await this.adapter.dropTable(e)}static async dropIfExists(e){await this.hasTable(e)&&await this.drop(e)}static async rename(e,t){throw new Error("Schema.rename() not yet implemented")}static async hasTable(e){return await this.adapter.hasTable(e)}static async hasColumn(e,t){return await this.adapter.hasColumn(e,t)}static async getTables(){throw new Error("Schema.getTables() not yet implemented")}static async getColumns(e){throw new Error("Schema.getColumns() not yet implemented")}}class Migration_Migration{}class MigrationRunner{migrationsTable="migrations";constructor(e,t){this.adapter=e,this.migrationsPath=t}async ensureMigrationsTable(){await Schema.hasTable(this.migrationsTable)||await Schema.create(this.migrationsTable,e=>{e.id(),e.string("migration"),e.integer("batch"),e.timestamp("created_at").nullable()})}async getRanMigrations(){return await this.ensureMigrationsTable(),await this.adapter.select(this.migrationsTable,{orderBy:[{column:"batch",direction:"ASC"}]})}async getPendingMigrations(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,896,23)),t=(await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),(await this.getRanMigrations()).map(e=>e.migration));return e.readdirSync(this.migrationsPath).filter(e=>e.endsWith(".ts")||e.endsWith(".js")).filter(e=>!t.includes(e.replace(/\.(ts|js)$/,""))).sort()}async run(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),t=await this.getPendingMigrations();if(0===t.length)return void console.log("No pending migrations");const s=await this.getRanMigrations(),n=s.length>0?Math.max(...s.map(e=>e.batch))+1:1;console.log(`Running ${t.length} migration(s)...`);for(const s of t){const t=e.resolve(this.migrationsPath,s),a=s.replace(/\.(ts|js)$/,"");try{const e=new(await this.loadMigration(t));console.log(`Migrating: ${a}`),await e.up(),await this.adapter.insert(this.migrationsTable,{migration:a,batch:n,created_at:new Date}),console.log(`Migrated: ${a}`)}catch(e){throw console.error(`Failed to migrate ${a}:`,e),e}}console.log("Migrations completed successfully")}async rollback(e=1){const t=await this.getRanMigrations();if(0===t.length)return void console.log("No migrations to rollback");const s=Math.max(...t.map(e=>e.batch)),n=s-e+1,a=t.filter(e=>e.batch>=n&&e.batch<=s).reverse();console.log(`Rolling back ${a.length} migration(s)...`);const r=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23));for(const e of a){const t=r.resolve(this.migrationsPath,`${e.migration}.ts`);try{const s=new(await this.loadMigration(t));console.log(`Rolling back: ${e.migration}`),await s.down(),await this.adapter.delete(this.migrationsTable,e.id),console.log(`Rolled back: ${e.migration}`)}catch(t){throw console.error(`Failed to rollback ${e.migration}:`,t),t}}console.log("Rollback completed successfully")}async reset(){const e=await this.getRanMigrations(),t=Math.max(...e.map(e=>e.batch));await this.rollback(t)}async fresh(){await this.reset(),await this.run()}async status(){return(await this.getRanMigrations()).map(e=>({name:e.migration,batch:e.batch,ranAt:e.created_at||new Date}))}async loadMigration(e){const t=(0,dynamicRequire.dynamicRequire)(e),s=t.default||t;if(!s||"function"!=typeof s)throw new Error(`Migration file ${e} does not export a valid migration class`);const n=new s;if("function"!=typeof n.up||"function"!=typeof n.down)throw new Error(`Migration class in ${e} must implement up() and down() methods`);return s}}const handleMigrate=async e=>{const t=e[0],s=external_path_default().resolve(process.cwd(),"src/config/database"),{dynamicRequire:n}=__webpack_require__(14);try{n("ts-node").register({transpileOnly:!0,compilerOptions:{module:"commonjs"}})}catch(e){}let a,r;try{const e=n(s);a=e.default||e.databaseConfig||e}catch(e){console.error("Failed to load database config:",e),process.exit(1)}"postgres"===a.type?r=new PostgresAdapter:"mysql"===a.type?r=new MySQLAdapter:(console.error(`Unsupported database type: ${a.type}`),process.exit(1));try{await r.connect(a);const e=external_path_default().resolve(process.cwd(),"src/database/migrations"),s=new MigrationRunner(r,e);switch(t){case"migrate":await s.run();break;case"migrate:rollback":await s.rollback();break;case"migrate:reset":await s.reset();break;case"migrate:fresh":await s.fresh();break;case"migrate:status":const e=await s.status();console.table(e);break;default:console.error(`Unknown migrate command: ${t}`),process.exit(1)}}catch(e){console.error("Migration failed:",e),process.exit(1)}finally{await r.disconnect()}},args=process.argv.slice(2),envFileArg=args.find(e=>e.startsWith("--env-file=")),customEnvFile=envFileArg?envFileArg.split("=")[1]:null;if(customEnvFile){const e=external_path_default().resolve(process.cwd(),customEnvFile);external_fs_default().existsSync(e)?(external_dotenv_default().config({path:e}),console.log(`Loaded environment from ${customEnvFile}`)):console.warn(`Warning: Environment file ${customEnvFile} not found.`)}else external_dotenv_default().config();const command=args[0];command||(console.error("Please specify a command: init, dev, build, start"),process.exit(1));const runCompiler=e=>new Promise((t,s)=>{e.run((e,n)=>e?(console.error(e),s(e)):n&&n.hasErrors()?(console.error(n.toString({colors:!0})),s(new Error("Webpack build failed"))):(console.log(null==n?void 0:n.toString({colors:!0})),void t()))});let serverProcess=null;const startDevServer=e=>new Promise(t=>{var s;serverProcess&&serverProcess.kill();const n=external_path_default().resolve(process.cwd(),"dist/server.js");serverProcess=(0,external_child_process_namespaceObject.spawn)("node",[n],{stdio:["inherit","pipe","inherit"],env:{...process.env,ARCANA_HMR_PORT:e.toString()}}),null===(s=serverProcess.stdout)||void 0===s||s.on("data",e=>{process.stdout.write(e),e.toString().includes("Server is running")&&t()}),serverProcess.on("close",e=>{0!==e&&null!==e&&console.error(`Dev server exited with code ${e}`)})}),watchCompiler=(e,t)=>{e.watch({},(e,s)=>{e?console.error(e):(console.log(null==s?void 0:s.toString({colors:!0})),s&&!s.hasErrors()&&t&&t())})},build=async()=>{process.env.NODE_ENV="production",console.log("Building for production...");const e=createClientConfig(),t=createServerConfig();try{await runCompiler(external_webpack_default()(e)),await runCompiler(external_webpack_default()(t)),console.log("Build complete.")}catch(e){console.error("Build failed:",e),process.exit(1)}},dev=async()=>{let e,t;process.env.NODE_ENV="development",console.log("Starting development server...");const s=e=>new Promise((t,s)=>{const n=new external_ws_namespaceObject.WebSocketServer({port:e});n.on("listening",()=>{t(n)}),n.on("error",e=>{s(e)})});for(let n=0;n<10;n++)try{const a=3001+n;e=await s(a),t=a,console.log(`HMR Server running on port ${t}`);break}catch(e){if("EADDRINUSE"!==e.code)throw e;if(console.warn(`Port ${3001+n} is in use, trying next port...`),9===n)throw new Error("Could not start HMR server after 10 attempts.")}if(!e||!t)throw new Error("Failed to start HMR server.");const n=()=>{console.log("\nShutting down development server..."),e&&e.close(()=>{console.log("HMR server closed.")}),serverProcess&&(serverProcess.kill(),serverProcess=null),process.exit(0)};process.on("SIGINT",n),process.on("SIGTERM",n);const a=()=>{e.clients.forEach(e=>{1===e.readyState&&e.send(JSON.stringify({type:"reload"}))})},r=createClientConfig(),o=createServerConfig();let i=!1,l=!1;const c=external_webpack_default()(o);c.hooks.invalid.tap("ArcanaJS",()=>{i=!0}),watchCompiler(external_webpack_default()(r),()=>{console.log("Client build complete."),i?(console.log("Server is building. Waiting to reload..."),l=!0):(console.log("Reloading browsers..."),a())}),watchCompiler(c,async()=>{console.log("Server build complete. Restarting server..."),await startDevServer(t),i=!1,l&&(console.log("Pending reload found. Reloading browsers..."),a(),l=!1)})},start=()=>{process.env.NODE_ENV="production";const e=external_path_default().resolve(process.cwd(),"dist/server.js");console.log(`Starting server at ${e}...`),(0,external_child_process_namespaceObject.spawn)("node",[e],{stdio:"inherit"}).on("close",e=>{process.exit(e||0)})};switch(command){case"build":build();break;case"dev":dev();break;case"start":start();break;default:command.startsWith("make:")?handleMake(args):command.startsWith("migrate")?handleMigrate(args):command.startsWith("db:")?handleDb(args):command.startsWith("dependency:")?handleDependency(args):(console.error(`Unknown command: ${command}`),process.exit(1))}var __webpack_export_target__=exports;for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__]=__webpack_exports__[__webpack_i__];__webpack_exports__.__esModule&&Object.defineProperty(__webpack_export_target__,"__esModule",{value:!0})})();
1
+ /*! For license information please see index.js.LICENSE.txt */
2
+ (()=>{var __webpack_modules__={14:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{dynamicRequire:()=>dynamicRequire});const dynamicRequire=id=>{try{var _global$process;const e=global,t=null===(_global$process=e.process)||void 0===_global$process||null===(_global$process=_global$process.mainModule)||void 0===_global$process?void 0:_global$process.require;if(t)return t(id)}catch(e){}return eval("require")(id)}},590:(e,t,n)=>{"use strict";n.d(t,{PostgresAdapter:()=>s});var r=n(14);class s{pool=null;client=null;async connect(e){var t,n;const{Pool:s}=(0,r.dynamicRequire)("pg");return this.pool=new s({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,ssl:e.ssl,min:(null===(t=e.pool)||void 0===t?void 0:t.min)||2,max:(null===(n=e.pool)||void 0===n?void 0:n.max)||10}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){const n=this.client||this.pool;if(!n)throw new Error("Database not connected");return(await n.query(e,t)).rows}async execute(e,t){const n=this.client||this.pool;if(!n)throw new Error("Database not connected");return await n.query(e,t)}async createTable(e,t){const n=`CREATE TABLE IF NOT EXISTS "${e}" (${t.map(e=>{let t=`"${e.name}" ${this.mapType(e.type,e.length)}`;return e.primary&&(t+=" PRIMARY KEY"),e.autoIncrement&&(t+=" GENERATED ALWAYS AS IDENTITY"),e.nullable||(t+=" NOT NULL"),e.unique&&(t+=" UNIQUE"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),t}).join(", ")})`;await this.execute(n)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS "${e}"`)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.tables \n WHERE table_schema = 'public' \n AND table_name = $1\n )",[e]))[0])||void 0===t?void 0:t.exists)||!1}async hasColumn(e,t){var n;return(null===(n=(await this.query("SELECT EXISTS (\n SELECT FROM information_schema.columns \n WHERE table_schema = 'public' \n AND table_name = $1 \n AND column_name = $2\n )",[e,t]))[0])||void 0===n?void 0:n.exists)||!1}async select(e,t){var n;let r=`SELECT ${(null===(n=t.columns)||void 0===n?void 0:n.join(", "))||"*"} FROM "${e}"`;const s=[];let o=1;if(t.joins&&t.joins.length>0)for(const e of t.joins)r+=` ${e.type} JOIN "${e.table}" ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(r+=" "+t.where.map((e,t)=>{const n=0===t?"WHERE":e.boolean,r=this.buildWhereCondition(e,s,o);return o=s.length+1,`${n} ${r}`}).join(" ")),t.orderBy&&t.orderBy.length>0&&(r+=` ORDER BY ${t.orderBy.map(e=>`"${e.column}" ${e.direction}`).join(", ")}`),t.limit&&(r+=" LIMIT $"+o++,s.push(t.limit)),t.offset&&(r+=" OFFSET $"+o++,s.push(t.offset)),await this.query(r,s)}async insert(e,t){const n=Object.keys(t),r=Object.values(t),s=r.map((e,t)=>`$${t+1}`).join(", "),o=`INSERT INTO "${e}" (${n.map(e=>`"${e}"`).join(", ")}) \n VALUES (${s}) \n RETURNING *`;return(await this.query(o,r))[0]}async update(e,t,n){const r=Object.keys(n),s=Object.values(n),o=`UPDATE "${e}" SET ${r.map((e,t)=>`"${e}" = $${t+1}`).join(", ")} WHERE id = $${r.length+1} RETURNING *`;return(await this.query(o,[...s,t]))[0]}async delete(e,t){const n=`DELETE FROM "${e}" WHERE id = $1`;return(await this.execute(n,[t])).rowCount>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.client=await this.pool.connect(),await this.client.query("BEGIN")}async commit(){if(!this.client)throw new Error("No active transaction");await this.client.query("COMMIT"),this.client.release(),this.client=null}async rollback(){if(!this.client)throw new Error("No active transaction");await this.client.query("ROLLBACK"),this.client.release(),this.client=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");return(await this.pool.query(e,t)).rows}buildWhereCondition(e,t,n){const r=`"${e.column}"`;switch(e.operator){case"IN":const s=e.value.map((e,t)=>`$${n+t}`).join(", ");return t.push(...e.value),`${r} IN (${s})`;case"NOT IN":const o=e.value.map((e,t)=>`$${n+t}`).join(", ");return t.push(...e.value),`${r} NOT IN (${o})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${r} BETWEEN $${n} AND $${n+1}`;case"IS NULL":return`${r} IS NULL`;case"IS NOT NULL":return`${r} IS NOT NULL`;default:return t.push(e.value),`${r} ${e.operator} $${n}`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INTEGER",bigInteger:"BIGINT",float:"REAL",double:"DOUBLE PRECISION",decimal:"DECIMAL",boolean:"BOOLEAN",date:"DATE",datetime:"TIMESTAMP",timestamp:"TIMESTAMP",json:"JSONB",uuid:"UUID"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"TRUE":"FALSE":e instanceof Date?`'${e.toISOString()}'`:String(e)}}},630:()=>{var e;!function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof global?global:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),n=r(e);function r(e,t){return function(n,r){Object.defineProperty(e,n,{configurable:!0,writable:!0,value:r}),t&&t(n,r)}}void 0!==t.Reflect&&(n=r(t.Reflect,n)),function(e,t){var n=Object.prototype.hasOwnProperty,r="function"==typeof Symbol,s=r&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",o=r&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",a="function"==typeof Object.create,i={__proto__:[]}instanceof Array,c=!a&&!i,l={create:a?function(){return F(Object.create(null))}:i?function(){return F({__proto__:null})}:function(){return F({})},has:c?function(e,t){return n.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return n.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),d="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},t=[],n=function(){function e(e,t,n){this._index=0,this._keys=e,this._values=t,this._selector=n}return e.prototype["@@iterator"]=function(){return this},e.prototype[o]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var n=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:n,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();return function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var n=this._find(e,!0);return this._values[n]=t,this},t.prototype.delete=function(t){var n=this._find(t,!1);if(n>=0){for(var r=this._keys.length,s=n+1;s<r;s++)this._keys[s-1]=this._keys[s],this._values[s-1]=this._values[s];return this._keys.length--,this._values.length--,N(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new n(this._keys,this._values,r)},t.prototype.values=function(){return new n(this._keys,this._values,s)},t.prototype.entries=function(){return new n(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[o]=function(){return this.entries()},t.prototype._find=function(e,t){if(!N(this._cacheKey,e)){this._cacheIndex=-1;for(var n=0;n<this._keys.length;n++)if(N(this._keys[n],e)){this._cacheIndex=n;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();function r(e,t){return e}function s(e,t){return t}function a(e,t){return[e,t]}}(),h="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[o]=function(){return this.keys()},e}(),p="function"==typeof WeakMap?WeakMap:function(){var e=l.create(),t=r();return function(){function e(){this._key=r()}return e.prototype.has=function(e){var t=s(e,!1);return void 0!==t&&l.has(t,this._key)},e.prototype.get=function(e){var t=s(e,!1);return void 0!==t?l.get(t,this._key):void 0},e.prototype.set=function(e,t){return s(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=s(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=r()},e}();function r(){var t;do{t="@@WeakMap@@"+a()}while(l.has(e,t));return e[t]=!0,t}function s(e,r){if(!n.call(e,t)){if(!r)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function o(e,t){for(var n=0;n<t;++n)e[n]=255*Math.random()|0;return e}function a(){var e=function(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):o(t,e),t}return o(new Array(e),e)}(16);e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var t="",n=0;n<16;++n){var r=e[n];4!==n&&6!==n&&8!==n||(t+="-"),r<16&&(t+="0"),t+=r.toString(16).toLowerCase()}return t}}(),f=r?Symbol.for("@reflect-metadata:registry"):void 0,y=function(){var e;return!k(f)&&T(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),k(e)&&(e=function(){var e,n,r,s;k(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=function(e){var t=e.defineMetadata,n=e.hasOwnMetadata,r=e.getOwnMetadata,s=e.getOwnMetadataKeys,o=e.deleteMetadata,a=new p;return{isProviderFor:function(e,t){var n=a.get(e);return!(k(n)||!n.has(t))||!!s(e,t).length&&(k(n)&&(n=new h,a.set(e,n)),n.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:n,OrdinaryGetOwnMetadata:r,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:o}}(t.Reflect));var o=new p,a={registerProvider:i,getProvider:l,setProvider:y};return a;function i(t){if(!Object.isExtensible(a))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case k(n):n=t;break;case n===t:break;case k(r):r=t;break;case r===t:break;default:void 0===s&&(s=new h),s.add(t)}}function c(t,o){if(!k(n)){if(n.isProviderFor(t,o))return n;if(!k(r)){if(r.isProviderFor(t,o))return n;if(!k(s))for(var a=I(s);;){var i=P(a);if(!i)return;var c=M(i);if(c.isProviderFor(t,o))return L(a),c}}}if(!k(e)&&e.isProviderFor(t,o))return e}function l(e,t){var n,r=o.get(e);return k(r)||(n=r.get(t)),k(n)?(k(n=c(e,t))||(k(r)&&(r=new d,o.set(e,r)),r.set(t,n)),n):n}function u(e){if(k(e))throw new TypeError;return n===e||r===e||!k(s)&&s.has(e)}function y(e,t,n){if(!u(n))throw new Error("Metadata provider not registered.");var r=l(e,t);if(r!==n){if(!k(r))return!1;var s=o.get(e);k(s)&&(s=new d,o.set(e,s)),s.set(t,n)}return!0}}()),!k(f)&&T(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),w=function(e){var t=new p,n={isProviderFor:function(e,n){var r=t.get(e);return!k(r)&&r.has(n)},OrdinaryDefineOwnMetadata:function(e,t,n,s){r(n,s,!0).set(e,t)},OrdinaryHasOwnMetadata:function(e,t,n){var s=r(t,n,!1);return!k(s)&&S(s.has(e))},OrdinaryGetOwnMetadata:function(e,t,n){var s=r(t,n,!1);if(!k(s))return s.get(e)},OrdinaryOwnMetadataKeys:function(e,t){var n=[],s=r(e,t,!1);if(k(s))return n;for(var o=I(s.keys()),a=0;;){var i=P(o);if(!i)return n.length=a,n;var c=M(i);try{n[a]=c}catch(e){try{L(o)}finally{throw e}}a++}},OrdinaryDeleteMetadata:function(e,n,s){var o=r(n,s,!1);if(k(o))return!1;if(!o.delete(e))return!1;if(0===o.size){var a=t.get(n);k(a)||(a.delete(s),0===a.size&&t.delete(a))}return!0}};return y.registerProvider(n),n;function r(r,s,o){var a=t.get(r),i=!1;if(k(a)){if(!o)return;a=new d,t.set(r,a),i=!0}var c=a.get(s);if(k(c)){if(!o)return;if(c=new d,a.set(s,c),!e.setProvider(r,s,n))throw a.delete(s),i&&t.delete(r),new Error("Wrong provider for target.")}return c}}(y);function m(e,t,n){if(b(e,t,n))return!0;var r=K(t);return!A(r)&&m(e,r,n)}function b(e,t,n){var r=U(t,n,!1);return!k(r)&&S(r.OrdinaryHasOwnMetadata(e,t,n))}function g(e,t,n){if(b(e,t,n))return _(e,t,n);var r=K(t);return A(r)?void 0:g(e,r,n)}function _(e,t,n){var r=U(t,n,!1);if(!k(r))return r.OrdinaryGetOwnMetadata(e,t,n)}function v(e,t,n,r){U(n,r,!0).OrdinaryDefineOwnMetadata(e,t,n,r)}function E(e,t){var n=$(e,t),r=K(e);if(null===r)return n;var s=E(r,t);if(s.length<=0)return n;if(n.length<=0)return s;for(var o=new h,a=[],i=0,c=n;i<c.length;i++){var l=c[i];o.has(l)||(o.add(l),a.push(l))}for(var u=0,d=s;u<d.length;u++)l=d[u],o.has(l)||(o.add(l),a.push(l));return a}function $(e,t){var n=U(e,t,!1);return n?n.OrdinaryOwnMetadataKeys(e,t):[]}function x(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function k(e){return void 0===e}function A(e){return null===e}function T(e){return"object"==typeof e?null!==e:"function"==typeof e}function O(e,t){switch(x(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var n=3===t?"string":5===t?"number":"default",r=D(e,s);if(void 0!==r){var o=r.call(e,n);if(T(o))throw new TypeError;return o}return function(e,t){if("string"===t){var n=e.toString;if(j(n)&&!T(s=n.call(e)))return s;if(j(r=e.valueOf)&&!T(s=r.call(e)))return s}else{var r;if(j(r=e.valueOf)&&!T(s=r.call(e)))return s;var s,o=e.toString;if(j(o)&&!T(s=o.call(e)))return s}throw new TypeError}(e,"default"===n?"number":n)}function S(e){return!!e}function q(e){var t=O(e,3);return"symbol"==typeof t?t:function(e){return""+e}(t)}function R(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function j(e){return"function"==typeof e}function C(e){return"function"==typeof e}function N(e,t){return e===t||e!=e&&t!=t}function D(e,t){var n=e[t];if(null!=n){if(!j(n))throw new TypeError;return n}}function I(e){var t=D(e,o);if(!j(t))throw new TypeError;var n=t.call(e);if(!T(n))throw new TypeError;return n}function M(e){return e.value}function P(e){var t=e.next();return!t.done&&t}function L(e){var t=e.return;t&&t.call(e)}function K(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===u)return t;if(t!==u)return t;var n=e.prototype,r=n&&Object.getPrototypeOf(n);if(null==r||r===Object.prototype)return t;var s=r.constructor;return"function"!=typeof s||s===e?t:s}function U(e,t,n){var r=y.getProvider(e,t);if(!k(r))return r;if(n){if(y.setProvider(e,t,w))return w;throw new Error("Illegal state.")}}function F(e){return e.__=void 0,delete e.__,e}e("decorate",function(e,t,n,r){if(k(n)){if(!R(e))throw new TypeError;if(!C(t))throw new TypeError;return function(e,t){for(var n=e.length-1;n>=0;--n){var r=(0,e[n])(t);if(!k(r)&&!A(r)){if(!C(r))throw new TypeError;t=r}}return t}(e,t)}if(!R(e))throw new TypeError;if(!T(t))throw new TypeError;if(!T(r)&&!k(r)&&!A(r))throw new TypeError;return A(r)&&(r=void 0),function(e,t,n,r){for(var s=e.length-1;s>=0;--s){var o=(0,e[s])(t,n,r);if(!k(o)&&!A(o)){if(!T(o))throw new TypeError;r=o}}return r}(e,t,n=q(n),r)}),e("metadata",function(e,t){return function(n,r){if(!T(n))throw new TypeError;if(!k(r)&&!function(e){switch(x(e)){case 3:case 4:return!0;default:return!1}}(r))throw new TypeError;v(e,t,n,r)}}),e("defineMetadata",function(e,t,n,r){if(!T(n))throw new TypeError;return k(r)||(r=q(r)),v(e,t,n,r)}),e("hasMetadata",function(e,t,n){if(!T(t))throw new TypeError;return k(n)||(n=q(n)),m(e,t,n)}),e("hasOwnMetadata",function(e,t,n){if(!T(t))throw new TypeError;return k(n)||(n=q(n)),b(e,t,n)}),e("getMetadata",function(e,t,n){if(!T(t))throw new TypeError;return k(n)||(n=q(n)),g(e,t,n)}),e("getOwnMetadata",function(e,t,n){if(!T(t))throw new TypeError;return k(n)||(n=q(n)),_(e,t,n)}),e("getMetadataKeys",function(e,t){if(!T(e))throw new TypeError;return k(t)||(t=q(t)),E(e,t)}),e("getOwnMetadataKeys",function(e,t){if(!T(e))throw new TypeError;return k(t)||(t=q(t)),$(e,t)}),e("deleteMetadata",function(e,t,n){if(!T(t))throw new TypeError;if(k(n)||(n=q(n)),!T(t))throw new TypeError;k(n)||(n=q(n));var r=U(t,n,!1);return!k(r)&&r.OrdinaryDeleteMetadata(e,t,n)})}(n,t),void 0===t.Reflect&&(t.Reflect=e)}()}(e||(e={}))},697:(e,t,n)=>{"use strict";n.d(t,{MongoAdapter:()=>s});var r=n(14);class s{client=null;db=null;async connect(e){const{MongoClient:t}=(0,r.dynamicRequire)("mongodb"),n=e.url||e.uri||`mongodb://${e.host}:${e.port}`,s={};return!e.url&&!e.uri&&e.username&&e.password&&(s.auth={username:e.username,password:e.password}),this.client=new t(n,s),await this.client.connect(),this.db=this.client.db(e.database),{query:async(e,t)=>{throw new Error("Raw SQL queries are not supported in MongoDB adapter")},execute:async(e,t)=>{throw new Error("Raw SQL execution is not supported in MongoDB adapter")},close:async()=>{await this.disconnect()}}}async disconnect(){this.client&&(await this.client.close(),this.client=null,this.db=null)}async createTable(e,t){if(!this.db)throw new Error("Database not connected");await this.db.createCollection(e)}async dropTable(e){if(!this.db)throw new Error("Database not connected");await this.db.collection(e).drop()}async hasTable(e){if(!this.db)throw new Error("Database not connected");return(await this.db.listCollections({name:e}).toArray()).length>0}async hasColumn(e,t){return!0}async select(e,t){if(!this.db)throw new Error("Database not connected");const n=this.db.collection(e),r=this.buildFilter(t.where||[]),s=this.buildProjection(t.columns);let o=n.find(r);if(s&&(o=o.project(s)),t.orderBy){const e={};t.orderBy.forEach(t=>{e[t.column]="ASC"===t.direction?1:-1}),o=o.sort(e)}return t.offset&&(o=o.skip(t.offset)),t.limit&&(o=o.limit(t.limit)),(await o.toArray()).map(e=>{const{_id:t,...n}=e;return{id:t,_id:t,...n}})}async insert(e,t){if(!this.db)throw new Error("Database not connected");const n=this.db.collection(e),r={...t};r.id&&(r._id=r.id,delete r.id);const s=await n.insertOne(r);return{id:s.insertedId,_id:s.insertedId,...t}}async update(e,t,n){if(!this.db)throw new Error("Database not connected");const r=this.db.collection(e),s={_id:this.normalizeId(t)},o={$set:n},a=await r.findOneAndUpdate(s,o,{returnDocument:"after"});if(a){const{_id:e,...t}=a;return{id:e,_id:e,...t}}return null}async delete(e,t){if(!this.db)throw new Error("Database not connected");const n=this.db.collection(e);return 1===(await n.deleteOne({_id:this.normalizeId(t)})).deletedCount}async beginTransaction(){}async raw(e,t=[]){if(!this.db)throw new Error("Database not connected");return"db"===e?this.db:await this.db.command(JSON.parse(e))}async commit(){}async rollback(){}buildFilter(e){const t={};return e.forEach(e=>{const n="id"===e.column?"_id":e.column;let r=e.value;switch("_id"===n&&(r=this.normalizeId(r)),e.operator){case"=":t[n]=r;break;case"!=":t[n]={$ne:r};break;case">":t[n]={$gt:r};break;case"<":t[n]={$lt:r};break;case">=":t[n]={$gte:r};break;case"<=":t[n]={$lte:r};break;case"IN":t[n]={$in:Array.isArray(r)?r:[r]};break;case"NOT IN":t[n]={$nin:Array.isArray(r)?r:[r]};break;case"LIKE":t[n]={$regex:new RegExp(r.replace(/%/g,".*"),"i")};break;case"IS NULL":t[n]=null;break;case"IS NOT NULL":t[n]={$ne:null}}}),t}buildProjection(e){if(!e||0===e.length||e.includes("*"))return null;const t={};return e.forEach(e=>{"id"===e||(t[e]=1)}),t}normalizeId(e){const{ObjectId:t}=(0,r.dynamicRequire)("mongodb");return e instanceof t?e:"string"==typeof e&&t.isValid(e)?new t(e):e}}},707:(e,t,n)=>{"use strict";n.d(t,{MySQLAdapter:()=>s});var r=n(14);class s{pool=null;connection=null;async connect(e){var t;const n=(0,r.dynamicRequire)("mysql2/promise");return this.pool=n.createPool({host:e.host,port:e.port,database:e.database,user:e.username,password:e.password,waitForConnections:!0,connectionLimit:(null===(t=e.pool)||void 0===t?void 0:t.max)||10,queueLimit:0}),{query:this.query.bind(this),execute:this.execute.bind(this),close:this.disconnect.bind(this)}}async disconnect(){this.pool&&(await this.pool.end(),this.pool=null)}async query(e,t){const n=this.connection||this.pool;if(!n)throw new Error("Database not connected");const[r]=await n.query(e,t);return r}async execute(e,t){const n=this.connection||this.pool;if(!n)throw new Error("Database not connected");const[r]=await n.execute(e,t);return r}async createTable(e,t){const n=`CREATE TABLE IF NOT EXISTS \`${e}\` (${t.map(e=>{let t=`\`${e.name}\` ${this.mapType(e.type,e.length)}`;return e.unsigned&&(t+=" UNSIGNED"),e.autoIncrement&&(t+=" AUTO_INCREMENT"),e.nullable||(t+=" NOT NULL"),void 0!==e.default&&(t+=` DEFAULT ${this.formatValue(e.default)}`),e.primary&&(t+=" PRIMARY KEY"),e.unique&&(t+=" UNIQUE"),t}).join(", ")}) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;await this.execute(n)}async dropTable(e){await this.execute(`DROP TABLE IF EXISTS \`${e}\``)}async hasTable(e){var t;return(null===(t=(await this.query("SELECT COUNT(*) as count FROM information_schema.tables \n WHERE table_schema = DATABASE() AND table_name = ?",[e]))[0])||void 0===t?void 0:t.count)>0}async hasColumn(e,t){var n;return(null===(n=(await this.query("SELECT COUNT(*) as count FROM information_schema.columns \n WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",[e,t]))[0])||void 0===n?void 0:n.count)>0}async select(e,t){var n;let r=`SELECT ${(null===(n=t.columns)||void 0===n?void 0:n.join(", "))||"*"} FROM \`${e}\``;const s=[];if(t.joins&&t.joins.length>0)for(const e of t.joins)r+=` ${e.type} JOIN \`${e.table}\` ON ${e.first} ${e.operator} ${e.second}`;return t.where&&t.where.length>0&&(r+=" "+t.where.map((e,t)=>`${0===t?"WHERE":e.boolean} ${this.buildWhereCondition(e,s)}`).join(" ")),t.orderBy&&t.orderBy.length>0&&(r+=` ORDER BY ${t.orderBy.map(e=>`\`${e.column}\` ${e.direction}`).join(", ")}`),t.limit&&(r+=" LIMIT ?",s.push(t.limit)),t.offset&&(r+=" OFFSET ?",s.push(t.offset)),await this.query(r,s)}async insert(e,t){const n=Object.keys(t),r=Object.values(t),s=r.map(()=>"?").join(", "),o=`INSERT INTO \`${e}\` (${n.map(e=>`\`${e}\``).join(", ")}) VALUES (${s})`;return{id:(await this.execute(o,r)).insertId,...t}}async update(e,t,n){const r=Object.keys(n),s=Object.values(n),o=`UPDATE \`${e}\` SET ${r.map(e=>`\`${e}\` = ?`).join(", ")} WHERE id = ?`;return await this.execute(o,[...s,t]),{id:t,...n}}async delete(e,t){const n=`DELETE FROM \`${e}\` WHERE id = ?`;return(await this.execute(n,[t])).affectedRows>0}async beginTransaction(){if(!this.pool)throw new Error("Database not connected");this.connection=await this.pool.getConnection(),await this.connection.beginTransaction()}async commit(){if(!this.connection)throw new Error("No active transaction");await this.connection.commit(),this.connection.release(),this.connection=null}async rollback(){if(!this.connection)throw new Error("No active transaction");await this.connection.rollback(),this.connection.release(),this.connection=null}async raw(e,t=[]){if(!this.pool)throw new Error("Database not connected");const[n]=await this.pool.execute(e,t);return n}buildWhereCondition(e,t){const n=`\`${e.column}\``;switch(e.operator){case"IN":const r=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${n} IN (${r})`;case"NOT IN":const s=e.value.map(()=>"?").join(", ");return t.push(...e.value),`${n} NOT IN (${s})`;case"BETWEEN":return t.push(e.value[0],e.value[1]),`${n} BETWEEN ? AND ?`;case"IS NULL":return`${n} IS NULL`;case"IS NOT NULL":return`${n} IS NOT NULL`;default:return t.push(e.value),`${n} ${e.operator} ?`}}mapType(e,t){return{string:t?`VARCHAR(${t})`:"VARCHAR(255)",text:"TEXT",integer:"INT",bigInteger:"BIGINT",float:"FLOAT",double:"DOUBLE",decimal:"DECIMAL(10,2)",boolean:"TINYINT(1)",date:"DATE",datetime:"DATETIME",timestamp:"TIMESTAMP",json:"JSON",uuid:"CHAR(36)"}[e]||e.toUpperCase()}formatValue(e){return null===e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"1":"0":e instanceof Date?`'${e.toISOString().slice(0,19).replace("T"," ")}'`:String(e)}}},896:e=>{"use strict";e.exports=require("fs")},916:e=>{"use strict";e.exports=require("ts-node")},928:e=>{"use strict";e.exports=require("path")}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var n=Object.create(null);__webpack_require__.r(n);var r={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;("object"==typeof s||"function"==typeof s)&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach(t=>r[t]=()=>e[t]);return r.default=()=>e,__webpack_require__.d(n,r),n},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";const e=require("child_process"),t=require("dotenv");var n=__webpack_require__.n(t),r=__webpack_require__(896),s=__webpack_require__.n(r),o=__webpack_require__(928),a=__webpack_require__.n(o);const i=require("webpack");var c=__webpack_require__.n(i);const l=require("clean-webpack-plugin"),u=require("html-webpack-plugin");var d=__webpack_require__.n(u);const h=require("mini-css-extract-plugin");var p=__webpack_require__.n(h);const f=require("webpack-node-externals");var y=__webpack_require__.n(f);const w=process.cwd(),m=e=>require.resolve(e),b=e=>{const t=[".ts",".tsx",".js",".jsx"];for(const n of e)for(const e of t){const t=a().resolve(w,n+e);if(s().existsSync(t))return t;const r=a().resolve(w,n,"index"+e);if(s().existsSync(r))return r}const n=a().resolve(w,"src/example/client/index.tsx"),r=a().resolve(w,"src/example/server/index.ts");if(e.some(e=>e.includes("client"))&&s().existsSync(n))return n;if(e.some(e=>e.includes("server"))&&s().existsSync(r))return r;throw new Error(`Could not find entry point. Searched in: ${e.join(", ")}`)},g=()=>{const e=a().resolve(w,"src/resources/views"),t=s().existsSync(e),n=a().resolve(__dirname,"../../node_modules/.cache/arcanajs/views-loader.js"),r=a().dirname(n);s().existsSync(r)||s().mkdirSync(r,{recursive:!0});const o=t?`module.exports = require.context('${e}', true, /\\.(tsx|jsx)$/);`:"module.exports = null;";return s().writeFileSync(n,o),n},_=()=>{const e="production"===process.env.NODE_ENV,t=g();return{mode:e?"production":"development",target:"web",entry:{client:b(["src/bootstrap/client"])},output:{path:a().resolve(w,"dist/public"),filename:e?"[name].[contenthash].bundle.js":"[name].bundle.js",publicPath:"/",assetModuleFilename:"assets/[hash][ext][query]"},resolve:{extensions:[".ts",".tsx",".js",".jsx"],alias:{"arcana-views":t,"@":a().resolve(w,"src")}},resolveLoader:{modules:["node_modules",a().resolve(__dirname,"../../node_modules")]},module:{rules:[{test:/\.(ts|tsx|js|jsx)$/,exclude:/node_modules/,use:{loader:m("babel-loader"),options:{presets:[m("@babel/preset-env"),[m("@babel/preset-react"),{runtime:"automatic"}],m("@babel/preset-typescript")]}}},{test:/\.module\.css$/,use:[e?p().loader:m("style-loader"),{loader:m("css-loader"),options:{importLoaders:1,modules:{localIdentName:e?"[hash:base64:8]":"[path][name]__[local]--[hash:base64:5]",exportLocalsConvention:"camelCaseOnly"}}},{loader:m("postcss-loader"),options:{postcssOptions:{config:a().resolve(w,"postcss.config.js")}}}]},{test:/\.css$/,exclude:/\.module\.css$/,use:[e?p().loader:m("style-loader"),{loader:m("css-loader"),options:{importLoaders:1}},{loader:m("postcss-loader"),options:{postcssOptions:{config:a().resolve(w,"postcss.config.js")}}}]},{test:/\.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf|otf)$/i,type:"asset/resource"}]},plugins:[new l.CleanWebpackPlugin,new(d())({templateContent:'<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n \x3c!--HEAD_CONTENT--\x3e\n </head>\n <body>\n <div id="root">\x3c!--APP_CONTENT--\x3e</div>\n \x3c!--ARCANAJS_DATA_SCRIPT--\x3e\n </body>\n</html>',filename:"index.html",inject:"body",minify:!!e&&{removeComments:!1,collapseWhitespace:!0,removeRedundantAttributes:!0,useShortDoctype:!0,removeEmptyAttributes:!0,removeStyleLinkTypeAttributes:!0,keepClosingSlash:!0,minifyJS:!0,minifyCSS:!0,minifyURLs:!0}}),new(p())({filename:e?"[name].[contenthash].css":"[name].css"})],optimization:{splitChunks:{chunks:"all",cacheGroups:{defaultVendors:{test:/[\\/]node_modules[\\/]/,priority:-10,reuseExistingChunk:!0},default:{minChunks:2,priority:-20,reuseExistingChunk:!0},react:{test:/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,name:"react-vendor",chunks:"all",priority:10}}}},performance:{maxEntrypointSize:512e3,maxAssetSize:512e3,hints:!!e&&"warning"},devtool:e?"source-map":"eval-source-map"}},v=()=>{const e="production"===process.env.NODE_ENV,t=b(["src/bootstrap/server"]),n=g();return{mode:e?"production":"development",target:"node",entry:t,output:{path:a().resolve(w,"dist"),filename:"server.js"},externals:[y()({allowlist:[/^arcanajs/]})],resolve:{extensions:[".ts",".tsx",".js",".jsx"],alias:{"arcana-views":n,"@":a().resolve(w,"src")}},resolveLoader:{modules:["node_modules",a().resolve(__dirname,"../../node_modules")]},module:{rules:[{test:/\.(ts|tsx|js|jsx)$/,exclude:/node_modules/,use:{loader:m("babel-loader"),options:{presets:[m("@babel/preset-env"),[m("@babel/preset-react"),{runtime:"automatic"}],m("@babel/preset-typescript")]}}},{test:/\.module\.css$/,use:{loader:m("css-loader"),options:{modules:{localIdentName:e?"[hash:base64:8]":"[path][name]__[local]--[hash:base64:5]",exportLocalsConvention:"camelCaseOnly",exportOnlyLocals:!0}}}},{test:/\.css$/,exclude:/\.module\.css$/,use:m("null-loader")},{test:/\.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf|otf)$/i,type:"asset/resource",generator:{emit:!1}}]},devtool:e?"source-map":"eval-source-map"}},E=require("ws");var $=__webpack_require__(697),x=__webpack_require__(707),k=__webpack_require__(590);class A{static macros={};static macro(e,t){this.macros[e]=t,this.prototype[e]=t}static mixin(e){Object.keys(e).forEach(t=>{this.macro(t,e[t])})}static hasMacro(e){return!!this.macros[e]}}class T extends A{selectColumns=["*"];whereClauses=[];orderByClauses=[];joinClauses=[];constructor(e,t){super(),this.tableName=e,this.adapter=t}select(...e){return this.selectColumns=e,this}where(e,t,n){return void 0===n&&(n=t,t="="),this.whereClauses.push({column:e,operator:t,value:n,boolean:"AND"}),this}orWhere(e,t,n){return void 0===n&&(n=t,t="="),this.whereClauses.push({column:e,operator:t,value:n,boolean:"OR"}),this}whereIn(e,t){return this.whereClauses.push({column:e,operator:"IN",value:t,boolean:"AND"}),this}whereNotIn(e,t){return this.whereClauses.push({column:e,operator:"NOT IN",value:t,boolean:"AND"}),this}whereBetween(e,t){return this.whereClauses.push({column:e,operator:"BETWEEN",value:t,boolean:"AND"}),this}whereNull(e){return this.whereClauses.push({column:e,operator:"IS NULL",value:null,boolean:"AND"}),this}whereNotNull(e){return this.whereClauses.push({column:e,operator:"IS NOT NULL",value:null,boolean:"AND"}),this}orderBy(e,t="ASC"){return this.orderByClauses.push({column:e,direction:t.toUpperCase()}),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}join(e,t,n,r,s="INNER"){return this.joinClauses.push({type:s,table:e,first:t,operator:n,second:r}),this}leftJoin(e,t,n,r){return this.join(e,t,n,r,"LEFT")}rightJoin(e,t,n,r){return this.join(e,t,n,r,"RIGHT")}eagerLoads=[];setModel(e){return this.model=e,this}with(e){return Array.isArray(e)?this.eagerLoads.push(...e):this.eagerLoads.push(e),this}async get(){const e={columns:this.selectColumns,where:this.whereClauses,orderBy:this.orderByClauses,limit:this.limitValue,offset:this.offsetValue,joins:this.joinClauses},t=await this.adapter.select(this.tableName,e);return this.eagerLoads.length>0&&this.model?await this.eagerLoadRelations(t):t}async eagerLoadRelations(e){if(0===e.length)return e;const t=e.map(e=>this.model.hydrate(e));for(const e of this.eagerLoads){const n=new this.model;if("function"!=typeof n[e])throw new Error(`Relation ${e} does not exist on ${this.model.name}`);const r=n[e]();r.addEagerConstraints(t);const s=await r.get();r.match(t,s,e)}return t}async first(){return this.limit(1),(await this.get())[0]||null}async find(e){return this.where("id",e).first()}async count(){this.selectColumns=["COUNT(*) as count"];const e=await this.first();return e?e.count:0}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async sum(e){this.selectColumns=[`SUM(${e}) as sum`];const t=await this.first();return t&&t.sum||0}async avg(e){this.selectColumns=[`AVG(${e}) as avg`];const t=await this.first();return t&&t.avg||0}async min(e){this.selectColumns=[`MIN(${e}) as min`];const t=await this.first();return t?t.min:null}async max(e){this.selectColumns=[`MAX(${e}) as max`];const t=await this.first();return t?t.max:null}async exists(){return await this.count()>0}async paginate(e=1,t=15){const n=await this.count(),r=(e-1)*t;return this.limit(t).offset(r),{data:await this.get(),total:n,perPage:t,currentPage:e,lastPage:Math.ceil(n/t)}}clone(){const e=new T(this.tableName,this.adapter);return e.selectColumns=[...this.selectColumns],e.whereClauses=[...this.whereClauses],e.orderByClauses=[...this.orderByClauses],e.joinClauses=[...this.joinClauses],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e}}class O{constructor(e,t){this.query=e,this.parent=t,this.related=e.model,this.addConstraints()}getQuery(){return this.query}async get(){return this.query.get()}async first(){return this.query.first()}}class S extends O{constructor(e,t,n,r){super(e,t),this.foreignKey=n,this.ownerKey=r}addConstraints(){const e=this.parent.getAttribute(this.foreignKey);this.query.where(this.ownerKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.foreignKey)).filter(e=>null!==e);this.query.whereIn(this.ownerKey,t)}match(e,t,n){const r={};return t.forEach(e=>{const t=e.getAttribute(this.ownerKey);r[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]&&e.setRelation(n,r[t])}),e}}class q extends O{constructor(e,t,n,r,s,o,a){super(e,t),this.table=n,this.foreignPivotKey=r,this.relatedPivotKey=s,this.parentKey=o,this.relatedKey=a}addConstraints(){this.performJoin(),this.query.where(`${this.table}.${this.foreignPivotKey}`,"=",this.parent.getAttribute(this.parentKey))}performJoin(e){const t=e||this.query,n=this.related.prototype.getTable();return t.join(this.table,`${n}.${this.relatedKey}`,"=",`${this.table}.${this.relatedPivotKey}`),this}addEagerConstraints(e){this.performJoin();const t=e.map(e=>e.getAttribute(this.parentKey)).filter(e=>null!==e);this.query.whereIn(`${this.table}.${this.foreignPivotKey}`,t)}match(e,t,n){return e}}class R extends O{constructor(e,t,n,r){super(e,t),this.foreignKey=n,this.localKey=r}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,n){const r={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]||(r[t]=[]),r[t].push(e)}),e.forEach(e=>{const t=e.getAttribute(this.localKey);r[t]?e.setRelation(n,r[t]):e.setRelation(n,[])}),e}}class j extends O{constructor(e,t,n,r){super(e,t),this.foreignKey=n,this.localKey=r}addConstraints(){const e=this.parent.getAttribute(this.localKey);this.query.where(this.foreignKey,"=",e)}addEagerConstraints(e){const t=e.map(e=>e.getAttribute(this.localKey)).filter(e=>null!==e);this.query.whereIn(this.foreignKey,t)}match(e,t,n){const r={};return t.forEach(e=>{const t=e.getAttribute(this.foreignKey);r[t]=e}),e.forEach(e=>{const t=e.getAttribute(this.localKey);r[t]&&e.setRelation(n,r[t])}),e}}class C extends A{static primaryKey="id";static connection="default";attributes={};original={};relations={};exists=!1;fillable=[];guarded=["id"];hidden=[];visible=[];casts={};dates=[];timestamps=!0;createdAt="created_at";updatedAt="updated_at";softDeletes=!1;deletedAt="deleted_at";static setAdapter(e){this.adapter=e}static getAdapter(){const e=this.adapter||global.ArcanaDatabaseAdapter;if(!e)throw new Error("Database adapter not set. Call Model.setAdapter() or ensure global.ArcanaDatabaseAdapter is set.");return e}static getTable(){if(this.tableName)return this.tableName;const e=this.name;return this.pluralize(this.snakeCase(e))}static query(){return new T(this.getTable(),this.getAdapter()).setModel(this)}static async all(){return(await this.query().get()).map(e=>this.hydrate(e))}static async find(e){const t=await this.query().where(this.primaryKey,e).first();return t?this.hydrate(t):null}static async findOrFail(e){const t=await this.find(e);if(!t)throw new Error(`Model not found with ${this.primaryKey}: ${e}`);return t}static where(e,t,n){return this.query().where(e,t,n)}static async create(e){const t=new this;if(t.fill(e),t.timestamps){const e=new Date;t.attributes[t.createdAt]=e,t.attributes[t.updatedAt]=e}const n=await this.getAdapter().insert(this.getTable(),t.attributes),r=n[this.primaryKey]||n.id||n.insertId;return t.attributes[this.primaryKey]=r,"id"!==this.primaryKey&&(t.attributes.id=r),t.exists=!0,t.syncOriginal(),t}static async update(e,t){const n=await this.findOrFail(e);return await n.update(t),n}static async destroy(e){const t=await this.find(e);return!!t&&await t.delete()}static async firstOrCreate(e,t={}){const n=this.query();for(const[t,r]of Object.entries(e))n.where(t,r);const r=await n.first();return r?this.hydrate(r):await this.create({...e,...t})}static async updateOrCreate(e,t={}){const n=this.query();for(const[t,r]of Object.entries(e))n.where(t,r);const r=await n.first();if(r){const e=this.hydrate(r);return await e.update(t),e}return await this.create({...e,...t})}static hydrate(e){const t=new this;return t.attributes={...e},t.original={...e},t.exists=!0,t}fill(e){for(const[t,n]of Object.entries(e))this.isFillable(t)&&this.setAttribute(t,n);return this}isFillable(e){return this.fillable.length>0?this.fillable.includes(e):!this.guarded.includes(e)}setAttribute(e,t){const n=`set${this.studly(e)}Attribute`;"function"==typeof this[n]&&(t=this[n](t)),this.attributes[e]=this.castAttribute(e,t)}getAttribute(e){const t=`get${this.studly(e)}Attribute`;if("function"==typeof this[t])return this[t]();const n=this.attributes[e];return this.castAttribute(e,n,!0)}castAttribute(e,t,n=!1){if(null==t)return t;const r=this.casts[e];if(!r)return t;if(n)switch(r){case"int":case"integer":return parseInt(t);case"float":case"double":return parseFloat(t);case"string":return String(t);case"bool":case"boolean":return Boolean(t);case"array":case"json":return"string"==typeof t?JSON.parse(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}else switch(r){case"array":case"json":return"object"==typeof t?JSON.stringify(t):t;case"date":case"datetime":return t instanceof Date?t:new Date(t);default:return t}}async save(){const e=this.constructor;if(this.timestamps){const e=new Date;this.exists||(this.attributes[this.createdAt]=e),this.attributes[this.updatedAt]=e}if(this.exists){const t=this.attributes[e.primaryKey];await e.getAdapter().update(e.getTable(),t,this.attributes)}else{const t=await e.getAdapter().insert(e.getTable(),this.attributes),n=t[e.primaryKey]||t.id||t.insertId;this.attributes[e.primaryKey]=n,"id"!==e.primaryKey&&(this.attributes.id=n),this.exists=!0}return this.syncOriginal(),this}async update(e){return this.fill(e),await this.save()}async delete(){const e=this.constructor;if(this.softDeletes)return this.attributes[this.deletedAt]=new Date,await this.save(),!0;const t=this.attributes[e.primaryKey];return await e.getAdapter().delete(e.getTable(),t)}async forceDelete(){const e=this.constructor,t=this.attributes[e.primaryKey];return await e.getAdapter().delete(e.getTable(),t)}async restore(){return this.softDeletes&&(this.attributes[this.deletedAt]=null,await this.save()),this}syncOriginal(){this.original={...this.attributes}}getDirty(){const e={};for(const[t,n]of Object.entries(this.attributes))this.original[t]!==n&&(e[t]=n);return e}isDirty(){return Object.keys(this.getDirty()).length>0}constructor(e={}){super(),this.fill(e)}toJSON(){const e={};for(const[t,n]of Object.entries(this.attributes))this.hidden.includes(t)||this.visible.length>0&&!this.visible.includes(t)||(e[t]=this.getAttribute(t));for(const[t,n]of Object.entries(this.relations))e[t]=n;return e}hasOne(e,t,n){const r=new e,s=t||`${this.constructor.name.toLowerCase()}_id`,o=n||"id";return new j(r.newQuery(),this,s,o)}hasMany(e,t,n){const r=new e,s=t||`${this.constructor.name.toLowerCase()}_id`,o=n||"id";return new R(r.newQuery(),this,s,o)}belongsTo(e,t,n){const r=new e,s=t||`${r.constructor.name.toLowerCase()}_id`,o=n||"id";return new S(r.newQuery(),this,s,o)}belongsToMany(e,t,n,r,s,o){const a=new e,i=t||this.guessPivotTable(a),c=n||`${this.constructor.name.toLowerCase()}_id`,l=r||`${a.constructor.name.toLowerCase()}_id`,u=s||"id",d=o||"id";return new q(a.newQuery(),this,i,c,l,u,d)}guessPivotTable(e){const t=[this.constructor.name.toLowerCase(),e.constructor.name.toLowerCase()];return t.sort(),t.join("_")}static with(e){return this.query().with(e)}setRelation(e,t){return this.relations[e]=t,this}getRelation(e){return this.relations[e]}relationLoaded(e){return void 0!==this.relations[e]}newQuery(){return this.constructor.query()}static snakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}static pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")?e+"es":e+"s"}studly(e){return e.replace(/(^|_)(\w)/g,(e,t,n)=>n.toUpperCase())}}const N=(t,n=[])=>{const r=(()=>{const e=process.cwd();return s().existsSync(a().join(e,"bun.lockb"))?"bun":s().existsSync(a().join(e,"pnpm-lock.yaml"))?"pnpm":s().existsSync(a().join(e,"yarn.lock"))?"yarn":"npm"})();if(console.log(`\nšŸ“¦ Detected package manager: ${r}\n`),t.length>0){console.log(`Installing dependencies: ${t.join(", ")}`);const n=((e,t)=>{const n=t.join(" ");switch(e){case"npm":return`npm install ${n}`;case"yarn":return`yarn add ${n}`;case"pnpm":return`pnpm add ${n}`;case"bun":return`bun add ${n}`}})(r,t);try{(0,e.execSync)(n,{stdio:"inherit"}),console.log("āœ… Dependencies installed successfully!\n")}catch(e){console.error("āŒ Failed to install dependencies"),process.exit(1)}}if(n.length>0){let t;switch(console.log(`Installing dev dependencies: ${n.join(", ")}`),r){case"npm":t=`npm install --save-dev ${n.join(" ")}`;break;case"yarn":t=`yarn add --dev ${n.join(" ")}`;break;case"pnpm":t=`pnpm add -D ${n.join(" ")}`;break;case"bun":t=`bun add -d ${n.join(" ")}`}try{(0,e.execSync)(t,{stdio:"inherit"}),console.log("āœ… Dev dependencies installed successfully!\n")}catch(e){console.error("āŒ Failed to install dev dependencies"),process.exit(1)}}},D=e=>e.replace(/(^|_)(\w)/g,(e,t,n)=>n.toUpperCase()),I=async(e,t,n)=>{const r=a().resolve(process.cwd(),`src/${e}`),o=a().join(r,t);s().existsSync(r)||s().mkdirSync(r,{recursive:!0}),s().existsSync(o)&&(console.error(`File already exists: ${o}`),process.exit(1)),s().writeFileSync(o,n),console.log(`Created: ${a().join(e,t)}`)},M=async(e,t="normal")=>{let n="";n="resource"===t?"\n async index(req: Request, res: Response) {\n //\n }\n\n async create(req: Request, res: Response) {\n //\n }\n\n async store(req: Request, res: Response) {\n //\n }\n\n async show(req: Request, res: Response) {\n //\n }\n\n async edit(req: Request, res: Response) {\n //\n }\n\n async update(req: Request, res: Response) {\n //\n }\n\n async destroy(req: Request, res: Response) {\n //\n }\n":"api"===t?"\n async index(req: Request, res: Response) {\n //\n }\n\n async store(req: Request, res: Response) {\n //\n }\n\n async show(req: Request, res: Response) {\n //\n }\n\n async update(req: Request, res: Response) {\n //\n }\n\n async destroy(req: Request, res: Response) {\n //\n }\n":"\n //\n";const r=`import { Request, Response } from 'arcanajs/server'\n\nclass ${D(e)} {${n}}\n\nexport default ${D(e)}\n`;await I("app/Http/Controllers",`${D(e)}.ts`,r)},P=async e=>{const t=e.replace("Factory",""),n=`import { Factory } from 'arcanajs/arcanox'\nimport { ${t} } from '@/app/Models/${D(t)}'\n\nclass ${D(e)} extends Factory<${t}> {\n protected model = ${t}\n\n definition() {\n return {\n //\n }\n }\n}\n\nexport default ${D(e)}\n`;await I("database/factories",`${D(e)}.ts`,n)},L=async e=>{const t=new Date,n=e=>e.toString().padStart(2,"0"),r=`${t.getFullYear()}_${n(t.getMonth()+1)}_${n(t.getDate())}_${n(t.getHours())}${n(t.getMinutes())}${n(t.getSeconds())}_${e}.ts`,s=`import { Migration, Schema } from 'arcanajs/arcanox'\n\nclass ${D(e)} extends Migration {\n async up() {\n // await Schema.create('${e.toLowerCase()}', (table) => {\n // table.id()\n // table.timestamps()\n // })\n }\n\n async down() {\n // await Schema.dropIfExists('${e.toLowerCase()}')\n }\n}\n\nexport default ${D(e)}\n`;await I("database/migrations",r,s)},K=async e=>{const t=`import { Seeder } from 'arcanajs/arcanox'\n\nclass ${D(e)} extends Seeder {\n async run() {\n //\n }\n}\n\nexport default ${D(e)}\n`;await I("database/seeders",`${D(e)}.ts`,t)},U=async e=>{const t=e[0].split(":")[1],n=e[1];switch(n||(console.error(`Please specify a name for the ${t}`),process.exit(1)),t){case"model":await(async e=>{const t=`import { Model } from 'arcanajs/arcanox'\n\nclass ${D(e)} extends Model {\n // protected table = '${e.toLowerCase()}s'\n protected fillable = []\n}\n\nexport default ${D(e)}\n`;await I("app/Models",`${D(e)}.ts`,t)})(n),(e.includes("--all")||e.includes("-a"))&&(await L(`create_${n.toLowerCase()}s_table`),await P(`${n}Factory`),await K(`${n}Seeder`),await M(`${n}Controller`,"resource"));break;case"controller":let r="normal";e.includes("--resource")||e.includes("-r")?r="resource":e.includes("--api")&&(r="api"),await M(n,r);break;case"migration":await L(n);break;case"seeder":await K(n);break;case"factory":await P(n);break;case"request":await async function(e){const t=`import { FormRequest } from "arcanajs/validator";\n\nclass ${D(e)} extends FormRequest {\n /**\n * Determine if the user is authorized to make this request.\n */\n public authorize(): boolean {\n return true;\n }\n\n /**\n * Get the validation rules that apply to the request.\n */\n public rules(): Record<string, string> {\n return {\n // 'field': 'required|string',\n };\n }\n}\n\nexport default ${D(e)}`;await I("app/Http/Requests",`${D(e)}.ts`,t)}(n);break;case"middleware":await async function(e){const t=`import { Middleware, NextFunction, Request, Response } from "arcanajs/server";\n\nclass ${D(e)} implements Middleware {\n public handle(req: Request, res: Response, next: NextFunction): void {\n // Middleware logic here\n next();\n }\n}\n\nexport default ${D(e)}\n`;await I("app/Http/Middleware",`${D(e)}.ts`,t)}(n);break;case"provider":await async function(e){const t=`import { ServiceProvider } from "arcanajs/server";\n\nclass ${D(e)} extends ServiceProvider {\n /**\n * Register any application services.\n */\n public register(): void {\n // Bind services to the container\n }\n\n /**\n * Bootstrap any application services.\n */\n public boot(): void {\n // Run code on application startup\n }\n}\n\nexport default ${D(e)}`;await I("app/Providers",`${D(e)}.ts`,t)}(n);break;default:console.error(`Unknown make command: make:${t}`),process.exit(1)}};class F{constructor(e,t,n){this.definition={name:e,type:t,length:n,nullable:!1}}nullable(){return this.definition.nullable=!0,this}default(e){return this.definition.default=e,this}unique(){return this.definition.unique=!0,this}primary(){return this.definition.primary=!0,this}autoIncrement(){return this.definition.autoIncrement=!0,this}unsigned(){return this.definition.unsigned=!0,this}getDefinition(){return this.definition}}class B{constructor(e){this.column=e}references(e){return this.referencedColumn=e,this}on(e){return this.referencedTable=e,this}onDelete(e){return this.onDeleteAction=e,this}onUpdate(e){return this.onUpdateAction=e,this}toSQL(){if(!this.referencedTable||!this.referencedColumn)throw new Error("Foreign key must reference a table and column");let e=`FOREIGN KEY (${this.column}) REFERENCES ${this.referencedTable}(${this.referencedColumn})`;return this.onDeleteAction&&(e+=` ON DELETE ${this.onDeleteAction}`),this.onUpdateAction&&(e+=` ON UPDATE ${this.onUpdateAction}`),e}}class W{columns=[];indexes=[];foreignKeys=[];primaryKeys=[];constructor(e){this.tableName=e}id(e="id"){const t=new F(e,"bigInteger");return t.primary().autoIncrement().unsigned(),this.columns.push(t.getDefinition()),t}uuid(e="id"){const t=new F(e,"uuid");return this.columns.push(t.getDefinition()),t}string(e,t=255){const n=new F(e,"string",t);return this.columns.push(n.getDefinition()),n}text(e){const t=new F(e,"text");return this.columns.push(t.getDefinition()),t}integer(e){const t=new F(e,"integer");return this.columns.push(t.getDefinition()),t}bigInteger(e){const t=new F(e,"bigInteger");return this.columns.push(t.getDefinition()),t}decimal(e,t=10,n=2){const r=new F(e,"decimal");return this.columns.push(r.getDefinition()),r}float(e){const t=new F(e,"float");return this.columns.push(t.getDefinition()),t}double(e){const t=new F(e,"double");return this.columns.push(t.getDefinition()),t}boolean(e){const t=new F(e,"boolean");return this.columns.push(t.getDefinition()),t}date(e){const t=new F(e,"date");return this.columns.push(t.getDefinition()),t}datetime(e){const t=new F(e,"datetime");return this.columns.push(t.getDefinition()),t}timestamp(e){const t=new F(e,"timestamp");return this.columns.push(t.getDefinition()),t}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}softDeletes(e="deleted_at"){return this.timestamp(e).nullable()}json(e){const t=new F(e,"json");return this.columns.push(t.getDefinition()),t}enum(e,t){const n=new F(e,"enum");return this.columns.push(n.getDefinition()),n}foreign(e){const t=new B(e);return this.foreignKeys.push(t),t}index(e,t){const n=Array.isArray(e)?e:[e];this.indexes.push({columns:n,unique:!1,name:t})}unique(e,t){const n=Array.isArray(e)?e:[e];this.indexes.push({columns:n,unique:!0,name:t})}primary(e){this.primaryKeys=Array.isArray(e)?e:[e]}getColumns(){return this.columns}getTableName(){return this.tableName}getIndexes(){return this.indexes}getForeignKeys(){return this.foreignKeys}}class H{static getAdapter(){const e=this.adapter||global.ArcanaDatabaseAdapter;if(!e)throw new Error("Database adapter not set. Call Schema.setAdapter() or ensure global.ArcanaDatabaseAdapter is set.");return e}static setAdapter(e){this.adapter=e}static async create(e,t){const n=new W(e);t(n),await this.getAdapter().createTable(e,n.getColumns())}static async table(e,t){t(new W(e)),console.warn("Schema.table() is not fully implemented yet. Use migrations for complex alterations.")}static async drop(e){await this.getAdapter().dropTable(e)}static async dropIfExists(e){await this.hasTable(e)&&await this.drop(e)}static async rename(e,t){throw new Error("Schema.rename() not yet implemented")}static async hasTable(e){return await this.getAdapter().hasTable(e)}static async hasColumn(e,t){return await this.getAdapter().hasColumn(e,t)}static async getTables(){throw new Error("Schema.getTables() not yet implemented")}static async getColumns(e){throw new Error("Schema.getColumns() not yet implemented")}}var V=__webpack_require__(14);class G{migrationsTable="migrations";constructor(e,t){this.adapter=e,this.migrationsPath=t}async ensureMigrationsTable(){await H.hasTable(this.migrationsTable)||await H.create(this.migrationsTable,e=>{e.id(),e.string("migration"),e.integer("batch"),e.timestamp("created_at").nullable()})}async getRanMigrations(){return await this.ensureMigrationsTable(),await this.adapter.select(this.migrationsTable,{orderBy:[{column:"batch",direction:"ASC"}]})}async getPendingMigrations(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,896,23)),t=(await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),(await this.getRanMigrations()).map(e=>e.migration));return e.readdirSync(this.migrationsPath).filter(e=>e.endsWith(".ts")||e.endsWith(".js")).filter(e=>!t.includes(e.replace(/\.(ts|js)$/,""))).sort()}async run(){const e=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23)),t=await this.getPendingMigrations();if(0===t.length)return void console.log("No pending migrations");const n=await this.getRanMigrations(),r=n.length>0?Math.max(...n.map(e=>e.batch))+1:1;console.log(`Running ${t.length} migration(s)...`);for(const n of t){const t=e.resolve(this.migrationsPath,n),s=n.replace(/\.(ts|js)$/,"");try{const e=new(await this.loadMigration(t));console.log(`Migrating: ${s}`),await e.up(),await this.adapter.insert(this.migrationsTable,{migration:s,batch:r,created_at:new Date}),console.log(`Migrated: ${s}`)}catch(e){throw console.error(`Failed to migrate ${s}:`,e),e}}console.log("Migrations completed successfully")}async rollback(e=1){const t=await this.getRanMigrations();if(0===t.length)return void console.log("No migrations to rollback");const n=Math.max(...t.map(e=>e.batch)),r=n-e+1,s=t.filter(e=>e.batch>=r&&e.batch<=n).reverse();console.log(`Rolling back ${s.length} migration(s)...`);const o=await Promise.resolve().then(__webpack_require__.t.bind(__webpack_require__,928,23));for(const e of s){const t=o.resolve(this.migrationsPath,`${e.migration}.ts`);try{const n=new(await this.loadMigration(t));console.log(`Rolling back: ${e.migration}`),await n.down(),await this.adapter.delete(this.migrationsTable,e.id),console.log(`Rolled back: ${e.migration}`)}catch(t){throw console.error(`Failed to rollback ${e.migration}:`,t),t}}console.log("Rollback completed successfully")}async reset(){const e=await this.getRanMigrations(),t=Math.max(...e.map(e=>e.batch));await this.rollback(t)}async fresh(){await this.reset(),await this.run()}async status(){return(await this.getRanMigrations()).map(e=>({name:e.migration,batch:e.batch,ranAt:e.created_at||new Date}))}async loadMigration(e){const t=(0,V.dynamicRequire)(e),n=t.default||t;if(!n||"function"!=typeof n)throw new Error(`Migration file ${e} does not export a valid migration class`);const r=new n;if("function"!=typeof r.up||"function"!=typeof r.down)throw new Error(`Migration class in ${e} must implement up() and down() methods`);return n}}__webpack_require__(630);class z{bindings=new Map;singletons=new Map;constructor(){z.instance||(z.instance=this)}static getInstance(){return z.instance||(z.instance=new z),z.instance}bind(e,t){this.isConstructor(t)?this.bindings.set(e,()=>this.build(t)):this.bindings.set(e,t)}singleton(e,t){const n=this.isConstructor(t)?()=>this.build(t):t;this.bindings.set(e,()=>(this.singletons.has(e)||this.singletons.set(e,n(this)),this.singletons.get(e)))}make(e){if(this.bindings.has(e))return this.bindings.get(e)(this);if(this.isConstructor(e))return this.build(e);throw new Error(`Service not found: ${e.toString()}`)}has(e){return this.bindings.has(e)}resolve(e){return this.make(e)}build(e){return new e(...(Reflect.getMetadata("design:paramtypes",e)||[]).map(e=>this.make(e)))}isConstructor(e){return!!e.prototype&&!!e.prototype.constructor.name}}z.getInstance();const J=process.argv.slice(2),Q=J.find(e=>e.startsWith("--env-file=")),Y=Q?Q.split("=")[1]:null;if(Y){const e=a().resolve(process.cwd(),Y);s().existsSync(e)?(n().config({path:e}),console.log(`Loaded environment from ${Y}`)):console.warn(`Warning: Environment file ${Y} not found.`)}else n().config();const X=J[0];X||(console.error("Please specify a command: init, dev, build, start"),process.exit(1));const Z=e=>new Promise((t,n)=>{e.run((e,r)=>e?(console.error(e),n(e)):r&&r.hasErrors()?(console.error(r.toString({colors:!0})),n(new Error("Webpack build failed"))):(console.log(null==r?void 0:r.toString({colors:!0})),void t()))});let ee=null;const te=(e,t)=>{e.watch({},(e,n)=>{e?console.error(e):(console.log(null==n?void 0:n.toString({colors:!0})),n&&!n.hasErrors()&&t&&t())})};switch(X){case"build":(async()=>{process.env.NODE_ENV="production",console.log("Building for production...");const e=_(),t=v();try{await Z(c()(e)),await Z(c()(t)),console.log("Build complete.")}catch(e){console.error("Build failed:",e),process.exit(1)}})();break;case"dev":(async()=>{let t,n;process.env.NODE_ENV="development",console.log("Starting development server...");const r=e=>new Promise((t,n)=>{const r=new E.WebSocketServer({port:e});r.on("listening",()=>{t(r)}),r.on("error",e=>{n(e)})});for(let e=0;e<10;e++)try{const s=3001+e;t=await r(s),n=s,console.log(`HMR Server running on port ${n}`);break}catch(t){if("EADDRINUSE"!==t.code)throw t;if(console.warn(`Port ${3001+e} is in use, trying next port...`),9===e)throw new Error("Could not start HMR server after 10 attempts.")}if(!t||!n)throw new Error("Failed to start HMR server.");const s=()=>{console.log("\nShutting down development server..."),t&&t.close(()=>{console.log("HMR server closed.")}),ee&&(ee.kill(),ee=null),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);const o=()=>{t.clients.forEach(e=>{1===e.readyState&&e.send(JSON.stringify({type:"reload"}))})},i=_(),l=v();let u=!1,d=!1;const h=c()(l);h.hooks.invalid.tap("ArcanaJS",()=>{u=!0}),te(c()(i),()=>{console.log("Client build complete."),u?(console.log("Server is building. Waiting to reload..."),d=!0):(console.log("Reloading browsers..."),o())}),te(h,async()=>{var t;console.log("Server build complete. Restarting server..."),await(t=n,new Promise(n=>{var r;ee&&ee.kill();const s=a().resolve(process.cwd(),"dist/server.js");ee=(0,e.spawn)("node",[s],{stdio:["inherit","pipe","inherit"],env:{...process.env,ARCANA_HMR_PORT:t.toString()}}),null===(r=ee.stdout)||void 0===r||r.on("data",e=>{process.stdout.write(e),e.toString().includes("Server is running")&&n()}),ee.on("close",e=>{0!==e&&null!==e&&console.error(`Dev server exited with code ${e}`)})})),u=!1,d&&(console.log("Pending reload found. Reloading browsers..."),o(),d=!1)})})();break;case"start":(()=>{process.env.NODE_ENV="production";const t=a().resolve(process.cwd(),"dist/server.js");console.log(`Starting server at ${t}...`),(0,e.spawn)("node",[t],{stdio:"inherit"}).on("close",e=>{process.exit(e||0)})})();break;default:X.startsWith("make:")?U(J):X.startsWith("migrate")?(async e=>{const t=e[0],n=a().resolve(process.cwd(),"src/config/database.ts");try{(0,V.dynamicRequire)("ts-node").register({transpileOnly:!0,compilerOptions:{module:"commonjs",moduleResolution:"node"}})}catch(e){}let r;try{const e=(0,V.dynamicRequire)(n);r=e.default||e.databaseConfig||e}catch(e){console.error("Failed to load database config:",e),process.exit(1)}const s=z.getInstance();let o,i;s.singleton("DatabaseConfig",()=>r);try{o=s.resolve("DatabaseConfig"),console.log("āœ“ Migration: Configuration loaded successfully")}catch(e){console.warn("⚠ Migration: No configuration found - Skipping setup"),process.exit(1)}try{switch(o.type){case"mysql":const{MySQLAdapter:e}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,707));i=new e;break;case"mongodb":const{MongoAdapter:t}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,697));i=new t;break;case"postgres":const{PostgresAdapter:n}=await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,590));i=new n;break;default:throw new Error(`Unsupported database type: ${o.type}`)}}catch(e){console.error("Failed to load database adapter:",e),process.exit(1)}try{await i.connect(o),C.setAdapter(i),H.setAdapter(i),global.ArcanaDatabaseAdapter=i;const e=a().resolve(process.cwd(),"src/database/migrations"),n=new G(i,e);switch(t){case"migrate":await n.run();break;case"migrate:rollback":await n.rollback();break;case"migrate:reset":await n.reset();break;case"migrate:fresh":await n.fresh();break;case"migrate:status":const e=await n.status();console.table(e);break;default:console.error(`Unknown migrate command: ${t}`),process.exit(1)}}catch(e){console.error("Migration failed:",e),process.exit(1)}finally{await i.disconnect()}})(J):X.startsWith("db:")?(async e=>{const t=e[0];"db:seed"!==t&&(console.error(`Unknown db command: ${t}`),process.exit(1));const n=a().resolve(process.cwd(),"src/config/database");try{__webpack_require__(916).register({transpileOnly:!0,compilerOptions:{module:"commonjs"}})}catch(e){}const{dynamicRequire:r}=__webpack_require__(14);let s,o;try{const e=r(n);s=e.default||e.databaseConfig||e}catch(e){console.error("Failed to load database config:",e),process.exit(1)}"postgres"===s.type?o=new k.PostgresAdapter:"mongodb"===s.type?o=new $.MongoAdapter:"mysql"===s.type?o=new x.MySQLAdapter:(console.error(`Unsupported database type: ${s.type}`),process.exit(1));try{await o.connect(s),C.setAdapter(o);const e=r(a().resolve(process.cwd(),"database/seeders/DatabaseSeeder.ts")),t=e.default||e.DatabaseSeeder;if(!t)throw new Error("DatabaseSeeder not found");console.log("Seeding database...");const n=new t;await n.run(),console.log("Database seeded successfully")}catch(e){console.error("Seeding failed:",e),process.exit(1)}finally{await o.disconnect()}})(J):X.startsWith("dependency:")?(e=>{const t=e[0].split(":")[1];switch(t||(console.error("Please specify a dependency type: auth, mail, or database"),console.log("\nUsage:"),console.log(" npx arcanajs dependency:auth"),console.log(" npx arcanajs dependency:mail"),console.log(" npx arcanajs dependency:database [mongo|postgres|mysql]"),process.exit(1)),t){case"auth":console.log("šŸ” Installing Auth Provider dependencies...\n"),N(["jsonwebtoken","bcryptjs","redis","connect-redis","express-session"],["@types/jsonwebtoken","@types/bcryptjs","@types/express-session"]),console.log("✨ Auth Provider dependencies installed!"),console.log("You can now use AuthProvider in your application.\n");break;case"mail":console.log("šŸ“§ Installing Mail Provider dependencies...\n"),N(["nodemailer","ejs","handlebars","ioredis","@aws-sdk/client-ses","@aws-sdk/credential-provider-node","nodemailer-mailgun-transport"],["@types/nodemailer","@types/ejs"]),console.log("✨ Mail Provider dependencies installed!"),console.log("You can now use MailProvider in your application.\n");break;case"database":const n=e[1];n||(console.error("Please specify a database type: mongo, postgres, or mysql"),console.log("\nUsage:"),console.log(" npx arcanajs dependency:database mongo"),console.log(" npx arcanajs dependency:database postgres"),console.log(" npx arcanajs dependency:database mysql"),process.exit(1)),(e=>{console.log(`šŸ—„ļø Installing Database Provider dependencies for ${e}...\n`);let t=[],n=[];switch(e.toLowerCase()){case"mongo":case"mongodb":t=["mongodb"],console.log("Installing MongoDB dependencies...");break;case"postgres":case"postgresql":case"pg":t=["pg"],n=["@types/pg"],console.log("Installing PostgreSQL dependencies...");break;case"mysql":t=["mysql2"],console.log("Installing MySQL dependencies...");break;default:console.error(`āŒ Unknown database type: ${e}. Supported types: mongo, postgres, mysql`),process.exit(1)}const r=["@faker-js/faker","reflect-metadata",...t];N(r,n),console.log("✨ Database Provider dependencies installed!"),console.log("You can now use DatabaseProvider in your application.\n")})(n);break;default:console.error(`Unknown dependency type: ${t}`),console.log("\nAvailable types:"),console.log(" - auth"),console.log(" - mail"),console.log(" - database"),process.exit(1)}})(J):(console.error(`Unknown command: ${X}`),process.exit(1))}})();var __webpack_export_target__=exports;for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__]=__webpack_exports__[__webpack_i__];__webpack_exports__.__esModule&&Object.defineProperty(__webpack_export_target__,"__esModule",{value:!0})})();
2
3
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ /*! *****************************************************************************
2
+ Copyright (C) Microsoft. All rights reserved.
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4
+ this file except in compliance with the License. You may obtain a copy of the
5
+ License at http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10
+ MERCHANTABLITY OR NON-INFRINGEMENT.
11
+
12
+ See the Apache Version 2.0 License for specific language governing permissions
13
+ and limitations under the License.
14
+ ***************************************************************************** */