### Nicola Core - HTTP Server Setup and Routing Source: https://context7.com/ericktiznado/nicola/llms.txt Demonstrates setting up the Nicola HTTP server, defining basic GET and POST routes, handling URL parameters, processing JSON request bodies, and managing file uploads. It also shows how to start the server with optional timeout configurations. ```javascript import Nicola from "nicola-framework"; const app = new Nicola(); // Basic route with JSON response app.get("/", (req, res) => { res.json({ message: "Hello from Nicola!", status: "ok" }); }); // Route with URL parameters app.get("/users/:id", (req, res) => { const userId = req.params.id; res.json({ userId, found: true }); }); // POST with automatic JSON body parsing app.post("/users", (req, res) => { const { name, email } = req.body; res.statusCode = 201; res.json({ created: true, user: { name, email } }); }); // File upload with multipart/form-data app.post("/upload", (req, res) => { if (!req.files || !req.files.avatar) { res.statusCode = 400; return res.end("No file uploaded"); } const file = req.files.avatar; res.json({ filename: file.filename, type: file.type, size: file.size }); }); // Start server with optional timeouts via environment variables // NICOLA_REQUEST_TIMEOUT, NICOLA_HEADERS_TIMEOUT, NICOLA_KEEP_ALIVE_TIMEOUT app.listen(3000, () => { console.log("Server running on http://localhost:3000"); }); ``` -------------------------------- ### Complete Nicola Framework Application Example (JavaScript) Source: https://context7.com/ericktiznado/nicola/llms.txt This JavaScript code demonstrates a complete application using the Nicola Framework. It includes setting up the server, defining a database model (User), implementing authentication middleware, creating API routes for registration, login, and profile retrieval, and starting the server. It utilizes various components of the framework like Remote, Regulator, Coherer, Dynamo, and Insulator. ```javascript import Nicola, { Remote, Regulator, Coherer, Dynamo, Insulator, EasyCors } from "nicola-framework"; // Load environment variables Regulator.load(); const app = new Nicola(); // Define User model class User extends Dynamo.Model { static tableName = "users"; static schema = { email: { type: "string", required: true }, password: { type: "string", required: true } }; } // Auth middleware const authenticate = (req, res, next) => { const token = req.headers.authorization?.split(" ")[1]; if (!token) { res.statusCode = 401; return res.json({ error: "No token provided" }); } try { req.user = Coherer.verify(token); next(); } catch (err) { res.statusCode = 401; res.json({ error: err.message }); } }; // API Router const api = new Remote(); // Public: Register api.post("/register", Insulator({ email: "string", password: "string" }), async (req, res) => { try { const user = await User.create(req.body); res.statusCode = 201; res.json({ id: user.id, email: user.email }); } catch (err) { res.statusCode = 500; res.json({ error: "Registration failed" }); } }); // Public: Login api.post("/login", async (req, res) => { const { email, password } = req.body; const users = await User.where("email", email).where("password", password).get(); if (users.length === 0) { res.statusCode = 401; return res.json({ error: "Invalid credentials" }); } const token = Coherer.sign({ userId: users[0].id }, { expiresIn: "7d" }); res.json({ token }); }); // Protected: Get profile api.get("/profile", authenticate, async (req, res) => { const users = await User.where("id", req.user.userId).get(); if (users.length === 0) { res.statusCode = 404; return res.json({ error: "User not found" }); } res.json({ email: users[0].email }); }); // Mount API router app.use("/api", api); // Health check app.get("/health", (req, res) => { res.json({ status: "ok", timestamp: Date.now() }); }); // Start server const start = async () => { await Dynamo.connect(); app.listen(3000, () => { console.log("Server running on http://localhost:3000"); }); }; start().catch(console.error); ``` -------------------------------- ### Nicola CLI Commands for Project Management Source: https://context7.com/ericktiznado/nicola/llms.txt The Nicola CLI provides commands for scaffolding new projects and managing the development server. Key commands include `init` for creating a new project with a starter template and `start` for launching the development server with hot-reloading capabilities. The generated project structure includes an entry point (`app.js`), configuration files, and example directories for controllers and routes. ```bash # Create new project with starter template npx nicola init my-api cd my-api npm install # Start development server with hot reload npm start # or npx nicola start # Generated project structure: # my-api/ # app.js # Entry point # package.json # With "type": "module" # src/ # controllers/ # user.controller.js # Example controller # routes/ # user.Routes.js # Example routes # Generated app.js example: # import Nicola, { Regulator } from "nicola-framework"; # import UserRoute from "./src/routes/user.Routes.js"; # # Regulator.load(); # const app = new Nicola(); # app.use("/user", UserRoute); # app.get("/", (req, res) => res.json({ message: "Welcome" })); # app.listen(3000); ``` -------------------------------- ### Nicola JWT Authentication with Coherer Source: https://context7.com/ericktiznado/nicola/llms.txt Shows how to implement JWT authentication using Nicola's `Coherer` module. It includes an example of a login endpoint to generate tokens and a protected route that uses an authentication middleware to verify tokens and attach user information to the request. ```javascript import Nicola, { Regulator, Coherer } from "nicola-framework"; // Load environment variables (requires .env with NICOLA_SECRET) Regulator.load(); const app = new Nicola(); // Login endpoint - generate JWT token app.post("/login", (req, res) => { const { username, password } = req.body; // Validate credentials (example) if (username !== "admin" || password !== "secret") { res.statusCode = 401; return res.json({ error: "Invalid credentials" }); } // Sign token with expiration (supported: s, m, h, d, y) const token = Coherer.sign( { userId: 1, username, role: "admin" }, { expiresIn: "24h" } ); res.json({ token }); }); // Authentication middleware const authMiddleware = (req, res, next) => { const authHeader = req.headers.authorization || ""; const [scheme, token] = authHeader.split(" "); if (scheme !== "Bearer" || !token) { res.statusCode = 401; return res.json({ error: "Missing token" }); } try { const payload = Coherer.verify(token); req.user = payload; next(); } catch (err) { res.statusCode = 401; // err.message: "Token Invalido" | "Token Expired" res.json({ error: err.message }); } }; // Protected route app.get("/profile", authMiddleware, (req, res) => { res.json({ user: req.user }); }); app.listen(3000); ``` -------------------------------- ### Nicola Core - HTTP Server API Source: https://context7.com/ericktiznado/nicola/llms.txt The main entry point for creating web applications. Extends the router with HTTP server capabilities, automatic body parsing, and response helpers. ```APIDOC ## Nicola Core - HTTP Server ### Description The main entry point for creating web applications. Extends the router with HTTP server capabilities, automatic body parsing, and response helpers. ### Method GET, POST ### Endpoint /, /users/:id, /users, /upload ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email of the user. - **avatar** (file) - Required - The avatar file to upload. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **message** (string) - A greeting message. - **status** (string) - The status of the response. - **userId** (string) - The ID of the user. - **found** (boolean) - Indicates if the user was found. - **created** (boolean) - Indicates if the user was created. - **user** (object) - The created user object. - **filename** (string) - The name of the uploaded file. - **type** (string) - The type of the uploaded file. - **size** (number) - The size of the uploaded file. #### Response Example ```json { "message": "Hello from Nicola!", "status": "ok" } ``` ```json { "userId": "123", "found": true } ``` ```json { "created": true, "user": { "name": "John Doe", "email": "john.doe@example.com" } } ``` ```json { "filename": "avatar.jpg", "type": "image/jpeg", "size": 10240 } ``` ``` -------------------------------- ### Load Environment Variables with Regulator Source: https://context7.com/ericktiznado/nicola/llms.txt Loads environment variables from a .env file in the current working directory using the Regulator module. It supports the KEY=value format, comments, and empty lines. Ensure this is called before accessing environment-dependent features. ```javascript import { Regulator } from "nicola-framework"; // Load .env file before using environment-dependent features Regulator.load(); // Environment variables are now available console.log(process.env.NICOLA_SECRET); console.log(process.env.DB_HOST); console.log(process.env.NODE_ENV); ``` -------------------------------- ### Nicola Router - Standalone Route Grouping Source: https://context7.com/ericktiznado/nicola/llms.txt Illustrates using the `Remote` class to create standalone routers for modular route organization. It shows how to define routes within sub-routers and mount them onto the main application with path prefixes, enabling nested routing structures. ```javascript import Nicola, { Remote } from "nicola-framework"; const app = new Nicola(); // Create a sub-router for API routes const apiRouter = new Remote(); apiRouter.get("/ping", (req, res) => { res.end("pong"); }); apiRouter.get("/status", (req, res) => { res.json({ status: "healthy", uptime: process.uptime() }); }); apiRouter.post("/echo", (req, res) => { res.json({ received: req.body }); }); // Create another sub-router for admin routes const adminRouter = new Remote(); adminRouter.get("/dashboard", (req, res) => { res.json({ admin: true, section: "dashboard" }); }); // Mount routers with path prefixes app.use("/api", apiRouter); // /api/ping, /api/status, /api/echo app.use("/admin", adminRouter); // /admin/dashboard // Middleware applies to all routes below app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); app.listen(3000); ``` -------------------------------- ### LiveCurrent Hot Reload Development Server for Nicola Source: https://context7.com/ericktiznado/nicola/llms.txt LiveCurrent is a development tool that provides a hot-reloading development server for Nicola applications. It watches specified entry point files and automatically restarts the Node.js process upon detecting changes in supported file types (.js, .json, .env). It includes features like debouncing, interactive shortcuts, and smart crash analysis. ```javascript import LiveCurrent from "nicola-framework/dev-tools/LiveCurrent"; // Create watcher for entry point const watcher = new LiveCurrent("app.js"); // Start watching and auto-reloading watcher.boot(); // Features: // - Watches .js, .json, .env files // - Ignores node_modules, .git, logs, coverage, test directories // - Debounces rapid changes (200ms delay) // - Interactive shortcuts: r=reload, c=clear, i=inspect, q=quit, h=help // - Smart crash analysis with code frame display // Typically used via CLI: // npx nicola start ``` -------------------------------- ### Configure CORS with EasyCors Middleware Source: https://context7.com/ericktiznado/nicola/llms.txt Provides Cross-Origin Resource Sharing middleware for the Nicola framework. It supports wildcard or whitelist origins and automatically handles OPTIONS preflight requests. CORS headers like `Access-Control-Allow-Origin` are set based on the configuration. ```javascript import Nicola, { EasyCors } from "nicola-framework"; const app = new Nicola(); // Allow all origins (default) app.use(EasyCors()); // Or whitelist specific origins app.use(EasyCors({ origin: ["https://myapp.com", "http://localhost:3000"] })); // CORS headers set: // Access-Control-Allow-Origin: * or specific origin // Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH // Access-Control-Allow-Headers: Content-Type, Authorization // OPTIONS requests automatically return 204 No Content app.get("/api/data", (req, res) => { res.json({ data: "accessible cross-origin" }); }); app.listen(3000); ``` -------------------------------- ### Add Security Headers with Teleforce Source: https://context7.com/ericktiznado/nicola/llms.txt A middleware for the Nicola framework that automatically adds basic security headers to all outgoing responses. It helps mitigate common web vulnerabilities by setting headers like `X-Content-Type-Options`, `X-Frame-Options`, and `X-XSS-Protection`. ```javascript import Nicola from "nicola-framework"; import Teleforce from "nicola-framework/middlewares/Teleforce"; const app = new Nicola(); // Add security headers to all responses app.use(Teleforce); // Headers added: // X-Content-Type-Options: nosniff // X-Frame-Options: Deny // X-XSS-Protection: 1 // X-Powered-By: (removed) app.get("/", (req, res) => { res.json({ secure: true }); }); app.listen(3000); ``` -------------------------------- ### PatternBuilder Fluent Regex API for JavaScript Source: https://context7.com/ericktiznado/nicola/llms.txt PatternBuilder offers a fluent API for constructing regular expressions in a readable, chainable syntax. It supports various methods for defining patterns, matching strings, extracting content, and replacing text. The `toRegex()` method compiles the pattern into a standard JavaScript RegExp object. ```javascript import { PatternBuilder } from "nicola-framework"; // Validate email format const emailPattern = new PatternBuilder() .startOfLine() .word().oneOrMore() .find("@") .word().oneOrMore() .find(".") .word().oneOrMore() .endOfLine(); console.log(emailPattern.matches("user@example.com")); // true console.log(emailPattern.matches("invalid-email")); // false // Validate phone number (555-123-4567) const phonePattern = new PatternBuilder() .startOfLine() .digit().exactly(3) .find("-") .digit().exactly(3) .find("-") .digit().exactly(4) .endOfLine(); console.log(phonePattern.matches("555-123-4567")); // true // Extract text between delimiters using cut() const quotePattern = new PatternBuilder().cut('"'); const result = quotePattern.get('name="Nicola Framework"'); console.log(result[1]); // "Nicola Framework" // Extract content between different delimiters const tagPattern = new PatternBuilder().cut('<', '>'); const tagResult = tagPattern.get('