### Initialize a Rune Application Source: https://ekkojs.com/docs/rune Basic setup for a Rune application, including importing the runtime, creating the app instance, defining a route, and starting the server. ```javascript import "@ekko/react/jsx-runtime"; import { createApp } from "ekko:rune"; const app = createApp({ port: 3000 }); app.page("/", () =>

Hello from Rune

, { title: "Home", page: "pages/index.tsx" }); app.start(); ``` -------------------------------- ### Basic Server Initialization Source: https://ekkojs.com/docs/api/web Minimal setup to start a web server on a specified port. ```typescript import { createServer } from "ekko:web"; const server = createServer({ port: 3000 }); server.get("/", (req, res) => res.json({ hello: "world" })); server.start(); console.log("listening on http://localhost:3000"); ``` -------------------------------- ### app.start() Source: https://ekkojs.com/docs/rune Starts the application server. ```APIDOC ## app.start() ### Description Begins listening for requests. Returns an object containing server, url, stop, invalidate, and cache methods. ``` -------------------------------- ### server.start() Source: https://ekkojs.com/docs/api/web Starts the server, begins listening for incoming requests, and returns the bound URL. ```APIDOC ## server.start() ### Description Begins listening for incoming requests on the configured port and returns the bound URL string. ### Returns - **url** (string) - The URL the server is bound to. ``` -------------------------------- ### Install Database Driver Source: https://ekkojs.com/docs/api/db/ekko-db/drivers Install the desired database driver package using the ekko CLI. ```bash ekko add @ekko/postgres # or @ekko/mysql · @ekko/mssql · @ekko/mongodb ``` -------------------------------- ### EkkoJS Command Examples Source: https://ekkojs.com/docs/guides/docker Common commands for interacting with the EkkoJS environment after setting up the wrapper. ```bash ekko --version ekko run main.ts --allow=fs,net ekko repl ``` -------------------------------- ### Run development server Source: https://ekkojs.com/docs/rune/build-and-deploy Starts the development server with file watching and hot reload. ```bash ekko dev server.tsx ``` ```bash ekko dev --port 4000 server.tsx ``` -------------------------------- ### Install EkkoJS on Windows Source: https://ekkojs.com/docs/getting-started Executes the installation script via PowerShell for Windows systems. ```powershell irm https://ekkojs.dev/install.ps1 | iex ``` -------------------------------- ### CLI help output examples Source: https://ekkojs.com/docs/apps/cli/building-a-cli Displays the auto-generated help screens for the root application and specific commands. ```text ⚡ deploy v2.0.0 · Ship a build to an environment USAGE deploy [options] COMMANDS push Deploy to an environment rollback Roll back the last deploy OPTIONS --help, -h Show help --version, -v Show version EXAMPLES $ deploy push staging --tag v2 Run deploy --help for detailed help. ``` ```text deploy push · Deploy to an environment USAGE deploy push [options] OPTIONS --help, -h Show help --version, -v Show version --force, -f Skip the confirmation prompt --tag, -t Version tag to deploy (default: latest) EXAMPLES $ deploy push prod --force ``` -------------------------------- ### Configuring a Queue Source: https://ekkojs.com/docs/api/job/queue Example of initializing a queue with specific concurrency, retry, and backoff settings. ```javascript import { createQueue } from "ekko:job/queue"; const resize = createQueue("image-resize", { concurrency: 4, // four images at once retries: 3, // retry a failed job up to 3 times backoff: "exponential", // backing off longer each attempt }); ``` -------------------------------- ### Configure Auth Instance Source: https://ekkojs.com/docs/api/auth Example of initializing an auth instance with custom production settings. ```typescript import { createAuth } from "ekko:auth"; const auth = createAuth({ secret: "a-long-random-secret", sessionTTL: 7200, // 2 hours secureCookies: true, // production }); ``` -------------------------------- ### CLI Execution Examples Source: https://ekkojs.com/docs/apps/cli Commands for executing the CLI script and accessing the auto-generated help documentation. ```bash ekko run greet.ts -- hello world # → "Hello, world!" ekko run greet.ts -- --help # auto-generated help ``` -------------------------------- ### Install EkkoJS on macOS or Linux Source: https://ekkojs.com/docs/getting-started Executes the installation script via curl for Unix-based systems. ```bash curl -fsSL https://ekkojs.dev/install.sh | sh ``` -------------------------------- ### Install the MySQL driver Source: https://ekkojs.com/docs/api/db/ekko-db/drivers/mysql Use the Ekko CLI to add the MySQL driver package to your project. ```bash ekko add @ekko/mysql ``` -------------------------------- ### Run store packages Source: https://ekkojs.com/docs/cli/run-eval-repl Execute an installed package directly from the store by name. ```bash ekko run @acme/site ``` -------------------------------- ### Create and start a web server Source: https://ekkojs.com/docs/apps/cli Initialize a server and database connection to handle API requests with parameterized queries. ```typescript // server.ts import { createServer } from "ekko:web"; import { connect } from "ekko:db/orm"; import { Users } from "./models/user"; const db = connect("./app.db"); const server = createServer({ port: 3000 }); server.get("/users/:id", (req, res) => { │ // The id is bound as a parameter, never concatenated into a query. │ const user = db.from(Users).where((u) => u.id.eq(req.params.id)).first(); │ if (!user) return res.status(404).json({ error: "not found" }); │ res.json(user); }); server.start(); ``` -------------------------------- ### Example manifest output Source: https://ekkojs.com/docs/getting-started/project-structure The manifest generated by the initialization command includes the project type and required entry fields. ```json { "name": "my-lib", "version": "1.0.0", "type": "lib", "exports": { ".": "src/index.ts" } } ``` -------------------------------- ### Basic Queue Usage Source: https://ekkojs.com/docs/api/job/queue Example of creating a queue, defining a processor, and adding a job. ```javascript import { createQueue } from "ekko:job/queue"; const emails = createQueue("emails", { concurrency: 2 }); emails.process(async (job) => { console.log("sending to", job.data.to); return { sent: true }; }); emails.add({ to: "alice@example.com" }); ``` -------------------------------- ### Start the REPL Source: https://ekkojs.com/docs/getting-started/first-program Commands to launch the interactive Read-Eval-Print Loop. ```bash ekko # starts the REPL (when not inside a runnable project) ekko repl # explicit, always opens the REPL ``` -------------------------------- ### Initialize and use MysqlClient Source: https://ekkojs.com/docs/api/db/ekko-db/drivers/mysql Example of connecting to a MySQL database, executing a command, and querying data. ```typescript import { MysqlClient } from "@ekko/mysql"; const client = new MysqlClient({ host: "localhost", port: 3306, database: "app", user: "root", password: "secret", }); client.exec("INSERT INTO users (name) VALUES (@p0)", { p0: "Alice" }); const res = client.query("SELECT id, name FROM users WHERE id = @p0", { p0: 1 }); console.log(res.columns, res.rows); client.close(); ``` -------------------------------- ### Install the PostgreSQL driver Source: https://ekkojs.com/docs/api/db/ekko-db/drivers/postgres Use the Ekko CLI to add the PostgreSQL driver package to your project. ```bash ekko add @ekko/postgres ``` -------------------------------- ### Initialize Auth and Verify Passwords Source: https://ekkojs.com/docs/api/auth Demonstrates basic setup of the auth instance and password verification workflow. ```typescript import { createAuth } from "ekko:auth"; const auth = createAuth({ secret: "change-me-in-production" }); const hash = auth.hashPassword("hunter2"); console.log(auth.verifyPassword("hunter2", hash)); // true console.log(auth.verifyPassword("wrong", hash)); // false ``` -------------------------------- ### spawn(command, args?, options?) Source: https://ekkojs.com/docs/api/process Starts a process and returns a ChildProcess handle for real-time interaction. ```APIDOC ## spawn(command: string, args?: string[], options?: SpawnOptions) ### Description Starts a process and returns immediately with a ChildProcess handle. This is ideal for long-running servers, interactive tools, or streaming output. ### Parameters - **command** (string) - Required - Program to run. Executed directly, not through a shell. - **args** (string[]) - Optional - Arguments passed to the command. - **options** (SpawnOptions) - Optional - Working directory and environment. ### SpawnOptions - **cwd** (string) - Optional - Working directory (default: inherit). - **env** (Record) - Optional - Extra environment variables. ### Returns - **ChildProcess** - An interactive handle to the running child. ### ChildProcess Members - **pid** (number) - The child's process id. - **write(data)** - Send data to the child's stdin (string or Uint8Array). - **closeStdin()** - Signal end-of-input. - **onStdout(cb)** - Register callback for stdout chunks. - **onStderr(cb)** - Register callback for stderr chunks. - **onExit(cb)** - Register callback for process exit code. - **kill()** - Forcibly terminate the process. ``` -------------------------------- ### Basic Image Operations Source: https://ekkojs.com/docs/cli/image Common usage examples for image conversion, compression, and resizing. ```bash ekko img info photo.jpg # 4032x3024 jpeg 3.1 MB ekko img convert logo.png logo.webp -q 90 # change format ekko img compress hero.jpg # shrink in place to hero.min.jpg ekko img resize hero.jpg hero@2x.jpg --width 1600 # resize, keep aspect ``` -------------------------------- ### Start Interactive REPL Source: https://ekkojs.com/docs/cli/run-eval-repl Launches an interactive read-eval-print loop, optionally with filesystem permissions. ```bash ekko repl ``` ```bash ekko repl --allow=fs # grant the REPL session permissions ``` -------------------------------- ### Implementing a progress bar Source: https://ekkojs.com/docs/apps/cli/prompts/progress Example of initializing a progress bar and updating it within a loop. ```javascript import { prompt } from "ekko:app/cli"; const bar = prompt.progress("Downloading", { total: 100 }); for (let i = 0; i <= 100; i += 20) bar.update(i); bar.done("Downloaded"); ``` -------------------------------- ### Install the MongoDB driver Source: https://ekkojs.com/docs/api/db/ekko-db/drivers/mongodb Use the Ekko CLI to add the MongoDB driver package to your project. ```bash ekko add @ekko/mongodb ``` -------------------------------- ### Initialize and Query Database Source: https://ekkojs.com/docs/api/db/ekko-db Basic setup for an in-memory database and executing standard SQL queries. ```typescript import { Database } from "ekko:db"; const db = new Database(":memory:"); db.exec("CREATE TABLE events (id INTEGER PRIMARY KEY, at TEXT DEFAULT CURRENT_TIMESTAMP)"); db.exec("INSERT INTO events DEFAULT VALUES"); console.log(db.query("SELECT date('now') AS today").rows); // [["2026-..."]] db.close(); ``` -------------------------------- ### Initialize and Use MssqlClient Source: https://ekkojs.com/docs/api/db/ekko-db/drivers/mssql Example of connecting to a SQL Server instance, executing an insert, and querying data. ```typescript import { MssqlClient } from "@ekko/mssql"; const client = new MssqlClient({ host: "localhost", port: 1433, database: "app", user: "sa", password: "Str0ng!Passw0rd", }); client.exec( "INSERT INTO [users] (name, email, age) VALUES (@p0, @p1, @p2)", { p0: "Alice", p1: "alice@example.com", p2: 30 }, ); const res = client.query("SELECT * FROM [users] WHERE age > @p0", { p0: 25 }); console.log(res.columns, res.rows); client.close(); ``` -------------------------------- ### Run and develop a Rune application Source: https://ekkojs.com/docs/getting-started/creating-a-project A complete workflow for initializing, installing dependencies, building, and running a Rune application. ```bash ekko init rune my-app -t asgard-minimal # explicit type + name + template (never prompts) cd my-app ekko add # install the declared deps (@ekko/react, @ekko/react-dom) + write ekko.lock ekko build --client # generate the client bundles (.ekko/build) ekko run server.tsx --allow=fs,net,env # or: ekko dev server.tsx (watch + HMR) ``` -------------------------------- ### Initialize Ekko Projects Source: https://ekkojs.com/docs/apps/tui Commands to scaffold new projects using documentation or demo templates, and to launch the resulting application. ```bash ekko init tui my-docs # the two-pane docs browser above ekko init tui my-demo -t demo # a showcase of every component ekko run # launch it (the type is read from ekko.json) ``` -------------------------------- ### Streaming Compression Example Source: https://ekkojs.com/docs/api/compress Demonstrates feeding data chunks into a gzip compression stream and finalizing the result. ```javascript import { gzip } from "ekko:compress"; import { utf8 } from "ekko:text/encoding"; const stream = gzip.createCompressStream({ level: "optimal" }); stream.write(utf8.encode("first chunk ")); stream.write(utf8.encode("second chunk ")); const compressed = stream.finish(); console.log("round-trips:", utf8.decode(gzip.decompress(compressed)) === "first chunk second chunk "); ``` -------------------------------- ### Runtime enforcement error messages Source: https://ekkojs.com/docs/guides/publishing Example output when a package installation is rejected due to runtime version mismatch. ```text package '@you/pkg@2.0.0' requires EkkoJS >= 0.8.5 (you have 0.8.4). Upgrade the runtime to install it. package '@you/pkg@2.0.0' requires EkkoJS <= 0.9.0 (you have 0.10.0). Install an older runtime, or a release of '@you/pkg' that supports 0.10.0. ``` -------------------------------- ### Build and run a website from an archive Source: https://ekkojs.com/docs/guides/packaging Commands to build a client, pack the project into an .ekl file, and execute it with network and filesystem access. ```bash cd my-site ekko build --client # produce .ekko/build/ (packed via the run-type preset) ekko pack # → my-site-1.0.0.any.any.ekl cp my-site-*.ekl /tmp/site.ekl cd /tmp ekko run --ekl site.ekl --allow=net,fs # SSR reads templates/assets from the VFS; # any runtime writes land in /tmp ``` -------------------------------- ### Verify EkkoJS Installation Source: https://ekkojs.com/docs/getting-started Checks the installed version of the EkkoJS CLI. ```bash ekko --version ``` -------------------------------- ### Resolve and connect to a host Source: https://ekkojs.com/docs/api/net/dns Example of resolving a hostname, filtering for an IPv4 address, and establishing a TCP connection. ```javascript import { dns, tcp } from "ekko:net"; // Resolve, prefer IPv4, then connect. const addresses = await dns.resolve("example.com"); const ipv4 = addresses.find((a) => !a.includes(":")) ?? addresses[0]; const conn = await tcp.connect(ipv4, 80); // ... tcp.close(conn); ``` -------------------------------- ### List installed dependencies Source: https://ekkojs.com/docs/cli/packages Display all currently installed package dependencies. ```bash ekko list ``` -------------------------------- ### Manage Web Server Lifecycle Source: https://ekkojs.com/docs/api/web Demonstrates initializing a server, setting a global error handler, starting the server, and stopping it. ```javascript import { createServer } from "ekko:web"; const server = createServer({ port: 3000 }); server.onError((err, req, res) => res.status(500).json({ error: "internal" })); const url = server.start(); console.log("listening on", url); // ... later ... server.stop(); ``` -------------------------------- ### Initialize a new Ekko project Source: https://ekkojs.com/docs/getting-started/creating-a-project Use the ekko init command to scaffold a new project. Always provide the type, name, and template to avoid interactive prompts in non-interactive environments. ```bash ekko init rune my-app -t asgard-minimal ekko init web my-site -t static ekko init cli my-tool # types with no templates take no -t ``` -------------------------------- ### Initialize a new project Source: https://ekkojs.com/docs/getting-started/project-structure Use the explicit, non-interactive form for scripting and automation. Avoid bare 'ekko init' in non-interactive environments. ```bash ekko init rune my-app -t asgard-minimal ``` ```bash ekko init run my-app # (type run) no templates ekko init lib my-lib # (type lib) ekko init cli my-tool # (type tool) ekko init test my-tests # (type test) ekko init rune my-app -t asgard-minimal # (type rune) -t: asgard-minimal (clean) | minimal | showcase, asgard (full demos) ekko init web my-site -t static # (type web) -t: static | api ekko init gui my-gui -t app # (type gui) -t: app | demo ekko init tui my-tui # (type tui) one template (docs) ``` -------------------------------- ### Aggregate Method Examples Source: https://ekkojs.com/docs/api/db/orm/aggregates-and-grouping Examples of using sum, avg, and min aggregate methods with filters. ```typescript orm.from(Posts).sum("likes"); // total likes orm.from(Users).where((u) => u.age.isNotNull()).avg("age"); // avg of non-null ages orm.from(Users).where((u) => u.age.isNotNull()).min("age"); // 25 ``` -------------------------------- ### Initialize and execute a GraphQL query Source: https://ekkojs.com/docs/api/web/graphql Basic setup of a GraphQL instance using createGraphQL and executing a simple query. ```typescript import { createGraphQL } from "ekko:web/graphql"; const gql = createGraphQL({ schema: `type Query { hello(name: String): String! }`, resolvers: { Query: { hello: (_p, args) => `Hello, ${args.name ?? "world"}!` }, }, }); const result = gql.execute(`{ hello(name: "Ekko") }`); console.log(result.data); // { hello: "Hello, Ekko!" } ``` -------------------------------- ### Start a TCP server Source: https://ekkojs.com/docs/api/net/tcp Starts a TCP server and defines the connection interface. The listener handle is required to stop the server later. ```typescript tcp.listen(host: string, port: number, onConnection: (conn: Connection) => void): number ``` ```typescript interface Connection { handle: number; // per-client handle for tcp.read/write/close address: string; // client IP address port: number; // client port } ``` -------------------------------- ### totp.setup Source: https://ekkojs.com/docs/api/auth Generates a new TOTP secret, backup codes, an otpauth URL, and a QR code for user setup. ```APIDOC ## totp.setup(options: TotpSetupOptions) ### Description Generates a new secret for a user, returning the secret, a set of backup codes, an otpauth URL, and a ready-to-display QR code. ### Parameters - **options** (TotpSetupOptions) - Required - The issuer (app name) and account (user identifier) shown in the authenticator. ### Returns - **TotpSetup** - Object containing secret, backupCodes, backupCodesHashed, otpauthUrl, and qrCode. ``` -------------------------------- ### Initialize a new workspace Source: https://ekkojs.com/docs/guides/workspaces Create a new directory and initialize it as an Ekko workspace. ```bash mkdir my-workspace && cd my-workspace ekko init workspace my-workspace ``` -------------------------------- ### PgClient.beginTransaction Source: https://ekkojs.com/docs/api/db/ekko-db/drivers/postgres Starts a new database transaction. ```APIDOC ## beginTransaction() ### Description Starts a transaction and returns a transaction handle. ### Returns - **PgClientTransaction** (object) - A transaction handle with the same exec and query methods, plus commit() and rollback() methods. ``` -------------------------------- ### Configure Network Permissions Source: https://ekkojs.com/docs/api/net Examples of CLI flags for granting network access, either globally or scoped to specific hosts. ```bash ekko run --allow=net app.ts # any host ekko run --allow=net:api.example.com app.ts # only this host ekko run --allow=net:127.0.0.1 app.ts # only loopback ``` -------------------------------- ### ekko list Source: https://ekkojs.com/docs/cli/packages Lists all installed package dependencies. ```APIDOC ## ekko list ### Description Displays the list of currently installed package dependencies for the project. ``` -------------------------------- ### Initialize Ekko Projects Source: https://ekkojs.com/docs/cli/project Commands to scaffold new projects or workspaces, supporting both interactive and non-interactive modes. ```bash ekko init # interactive picker (choose the type) ekko init lib # a specific type: run | lib | cli | test | rune | web | gui | tui ekko init cli my-tool # positional name (shorthand for --name) ekko init run --path apps/web --name web # into a directory, with a name ekko init workspace my-ws # a workspace root (members + map) in the current dir ``` ```bash ekko init rune # interactive: then choose showcase | minimal | asgard ekko init rune -t minimal # non-interactive: pick the template directly ekko init web -t api # web: static (default) or api ekko init gui --demo # gui: --demo is shorthand for --template demo ``` -------------------------------- ### start() & stop() Source: https://ekkojs.com/docs/api/job/cron Controls the lifecycle of the cron scheduler. ```APIDOC ## start() ### Description Begins the scheduler. Registering jobs does nothing until this is called. The first tick fires immediately. ## stop() ### Description Halts the scheduler without forgetting registered schedules. ``` -------------------------------- ### Implement a two-pane TUI application Source: https://ekkojs.com/docs/apps/tui/layout A complete example of a documentation browser layout using Box, Text, and CodeView components. ```typescript import { render, Box, Text, Spacer, CodeView, renderMarkdown, mdWrap, useState, useResize, } from "ekko:app/tui"; function App() { const { columns, rows } = useResize(); // fills the whole terminal, re-renders on resize const [scroll, setScroll] = useState(0); const contentW = columns - 30 - 2; const lines = mdWrap(renderMarkdown(page), contentW); return ( docs browser ↑↓ move ⏎ open q quit {/* Left: a fixed-width accordion nav inside a bordered box. */} ▾ Getting started Welcome Installation ▸ Reference {/* Right: a flexible content pane that renders markdown into a scrollable window. */} docs/getting-started/welcome.md ); } render(); ``` -------------------------------- ### cron.start() Source: https://ekkojs.com/docs/api/job/cron Starts the scheduler to begin executing registered jobs. ```APIDOC ## cron.start() ### Description Initializes and starts the scheduler. No scheduled jobs will execute until this method is called. ``` -------------------------------- ### cli(name, version?) Source: https://ekkojs.com/docs/apps/cli/reference Initializes a new CLI application instance. ```APIDOC ## cli(name: string, version?: string) ### Description Creates and returns an app object used to configure and run a CLI application. ### Signature `cli(name: string, version?: string)` ### Parameters - **name** (string) - Required - The name of the application. - **version** (string) - Optional - The version string of the application. ``` -------------------------------- ### MultiSelect UI Example Source: https://ekkojs.com/docs/apps/cli/prompts/multiselect Visual representation of the multi-select prompt interface. ```text Select features: (space toggle, enter confirm) ❯ [x] TypeScript [x] Linting [ ] Unit tests [ ] GitHub Actions ``` -------------------------------- ### Initialize and Configure RBAC Source: https://ekkojs.com/docs/api/auth/rbac Demonstrates the basic setup of the RBAC system, including role creation, permission definition, and checking access. ```javascript import { createRBAC } from "ekko:auth/rbac"; import { connect } from "ekko:db/orm"; const rbac = createRBAC({ db: connect(":memory:") }); rbac.initialize(); rbac.createRole("editor"); rbac.definePermission("posts", "publish"); rbac.grant("editor", "posts", "publish"); rbac.assignRole("alice", "editor"); console.log(rbac.can("alice", "posts", "publish")); // true console.log(rbac.can("alice", "posts", "delete")); // false ``` -------------------------------- ### server.onError(handler) Source: https://ekkojs.com/docs/api/web Installs a global catch-all error handler for the server instance. ```APIDOC ## server.onError(handler) ### Description Registers a callback function to handle errors that occur during the request-response lifecycle. ### Parameters - **handler** (function) - Required - A function with signature (err, req, res) to process errors. ``` -------------------------------- ### Initialize and run TUI projects Source: https://ekkojs.com/docs/apps/tui/layout Commands to scaffold new TUI applications and preview layouts without a live terminal. ```bash ekko init tui my-docs # this two-pane documentation browser, ready to run ekko init tui my-demo -t demo # a showcase of every component (Box, inputs, Table, code, Modal) ekko run --snapshot app.tsx # render the first frame to stdout to check a layout without a live terminal ``` -------------------------------- ### Example Markdown output Source: https://ekkojs.com/docs/apps/tui/rich-content Visual representation of rendered markdown content in the terminal. ```text ═══ RELEASE NOTES ═══ ═════════════════════ EkkoJS 0.8.9 adds: ● A terminal Markdown renderer ● Syntax-highlighted code blocks │ Built on the same pipeline as ekko doc. ``` -------------------------------- ### Initialize Realtime Server Source: https://ekkojs.com/docs/api/web/realtime Sets up a basic chat server using channels to broadcast messages to connected clients. ```javascript import { createServer } from "ekko:web"; import { createRealtime } from "ekko:web/realtime"; const rt = createRealtime(); rt.channel("chat", { message(socket, data) { socket.broadcast("chat", { from: socket.id, text: data }); }, }); const server = createServer({ port: 3000 }); server.ws("/chat", (ws) => rt.handleConnection(ws, "chat")); server.start(); ``` -------------------------------- ### Execute CLI commands Source: https://ekkojs.com/docs/apps/cli/building-a-cli Examples of running the CLI application via the terminal. ```bash ekko run store.ts -- remote add origin https://example.com/repo ekko run store.ts -- remote --help ``` -------------------------------- ### Initialize and Query ekko:db Source: https://ekkojs.com/docs/api/db/ekko-db Demonstrates opening a database file, creating a table, performing an insert, and executing a query. ```javascript import { Database } from "ekko:db"; const db = new Database("./app.db"); db.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)"); db.exec("INSERT INTO notes (body) VALUES (@body)", { body: "first note" }); const result = db.query("SELECT id, body FROM notes"); console.log(result.rows); // [[1, "first note"]] db.close(); ``` -------------------------------- ### Install the MSSQL Driver Source: https://ekkojs.com/docs/api/db/ekko-db/drivers/mssql Command to add the MSSQL driver package to your EkkoJS project. ```bash ekko add @ekko/mssql ``` -------------------------------- ### Deploy Rune application Source: https://ekkojs.com/docs/rune/build-and-deploy Builds the client bundles and runs the server with necessary permissions. ```bash ekko build --client ekko run --allow=net,fs:.ekko/build/** server.tsx ``` -------------------------------- ### View image tag format Source: https://ekkojs.com/docs/guides/docker Example of the versioned tag structure for the headless image. ```text emc2dev/ekkojs:v0.8.9-server # version 0.8.9, headless ``` -------------------------------- ### Basic Filtering Operators Source: https://ekkojs.com/docs/api/db/orm/querying Examples of using various comparison operators on user fields. ```javascript orm.from(Users).where((u) => u.age.between(25, 30)).toArray(); ``` ```javascript orm.from(Users).where((u) => u.name.isIn(["Alice", "Charlie"])).toArray(); ``` ```javascript orm.from(Users).where((u) => u.age.isNull()).toArray(); ``` ```javascript orm.from(Users).where((u) => u.name.notLike("A%")).toArray(); ``` -------------------------------- ### Run Ekko with database permissions Source: https://ekkojs.com/docs/api/db/ekko-db Examples of running an Ekko application with specific filesystem permissions for file-backed databases versus in-memory databases. ```bash ekko run --allow=fs:./data/** app.ts # file-backed database under ./data/ ekko run app.ts # :memory: only, no grant needed ``` -------------------------------- ### Initialize a Rune application Source: https://ekkojs.com/docs/rune Configures the server with port, manifest, and SSR settings using the createApp function. ```javascript import { createApp, readManifest } from "ekko:rune"; import NotFound from "./pages/not-found"; const app = createApp({ port: 3000, manifest: readManifest(), notFound: NotFound, ssr: "eager", }); ``` -------------------------------- ### Verify a Password Source: https://ekkojs.com/docs/api/auth Example of verifying a candidate password against a previously stored hash string. ```javascript import { createAuth } from "ekko:auth"; const auth = createAuth({ secret: "s" }); const stored = auth.hashPassword("hunter2"); console.log(auth.verifyPassword("hunter2", stored)); // true console.log(auth.verifyPassword("nope", stored)); // false ``` -------------------------------- ### Create Realtime Instance Source: https://ekkojs.com/docs/api/web/realtime Demonstrates the instantiation of a Realtime object and inspection of its initial state. ```javascript import { createRealtime } from "ekko:web/realtime"; const rt = createRealtime(); console.log(rt.channelCount(), rt.socketCount()); // 0 0 ``` -------------------------------- ### createApp(options) Source: https://ekkojs.com/docs/rune Initializes a new Rune application with the provided configuration options. ```APIDOC ## createApp(options) ### Description Builds your application and returns an app object used to register routes and start the server. ### Parameters - **options** (object) - Required - Configuration object containing: - **port** (number) - Optional - Listener port (default: 3000) - **host** (string) - Optional - Listener host (default: 0.0.0.0) - **manifest** (object) - Required - Build manifest from readManifest() - **ssr** (string) - Optional - SSR strategy: "eager", "lazy", or "background" - **layouts** (object) - Optional - Layout tree wrapping pages - **notFound** (component) - Optional - Component for 404 pages - **static** (string) - Optional - Directory for static assets - **staticPrefix** (string) - Optional - URL prefix for static assets - **tls** (object) - Optional - TLS configuration - **http2** (boolean) - Optional - Enable HTTP/2 ``` -------------------------------- ### Filesystem Access in Tools Source: https://ekkojs.com/docs/cli/run-eval-repl Demonstrates reading bundle-relative assets and writing to user-specified directories using absolute paths. ```javascript import { readText, writeText } from "ekko:fs"; import { cwd } from "ekko:process"; import { join } from "ekko:path"; const tpl = readText("./templates/Component.ts"); // bundle-relative, the tool's own asset writeText(join(cwd(), "src/Component.ts"), render(tpl)); // user file, gated by --allow=fs ``` -------------------------------- ### Initialize TOTP Setup Source: https://ekkojs.com/docs/api/auth Generates a new secret, backup codes, and a QR code for a user. Store the secret and hashed backup codes securely. ```javascript import { totp } from "ekko:auth"; const setup = totp.setup({ issuer: "MyApp", account: "alice@example.com" }); console.log(setup.secret.length > 0, setup.qrCode.startsWith("data:image/svg")); console.log(`${setup.backupCodes.length} backup codes`); ``` -------------------------------- ### Initialize and Run a CLI Application Source: https://ekkojs.com/docs/apps/cli Basic setup for a CLI application using the cli export to define commands and handle arguments. ```typescript import { cli } from "ekko:app/cli"; const app = cli("greet", "1.0.0"); app.command("hello ") .description("Greet someone") .action((args) => console.log(`Hello, ${args.name}!`)); app.run(); ``` -------------------------------- ### Defining Global Styles Source: https://ekkojs.com/docs/rune/styling Example of a global Sass file defining variables and base styles. ```scss // styles/global.scss $brand: #38bdf8; :root { --brand: #{$brand}; } body { margin: 0; font-family: system-ui; background: #0f172a; color: #e2e8f0; } a { color: var(--brand); } .app-shell { min-height: 100vh; } ``` -------------------------------- ### Basic usage of prompt.select Source: https://ekkojs.com/docs/apps/cli/prompts/select Demonstrates how to prompt a user to select a template from a list of options with descriptions. ```typescript import { prompt } from "ekko:app/cli"; const template = await prompt.select("Choose a template:", [ { label: "Minimal", value: "minimal", description: "An empty project, just the essentials." }, { label: "Web app", value: "web", description: "A Rune full-stack web app with routing." }, { label: "CLI tool", value: "cli", description: "A command-line app built on ekko:app/cli." }, ]); if (template !== null) console.log(`Scaffolding ${template}`); ``` -------------------------------- ### View coverage report output Source: https://ekkojs.com/docs/guides/workspaces Example output showing the location of generated coverage reports. ```text Coverage: /path/to/my-workspace/coverage/lcov.info HTML report: /path/to/my-workspace/coverage/html/index.html 30/79 lines (38.0%) across 5 files ``` -------------------------------- ### Read Files with Built-in Modules Source: https://ekkojs.com/docs/getting-started/first-program Example of importing and using the built-in file system module. ```typescript import { readText } from "ekko:fs"; const contents = readText("./main.ts"); console.log(contents); ``` -------------------------------- ### Initialize and query PostgreSQL client Source: https://ekkojs.com/docs/api/db/ekko-db Connects to a PostgreSQL instance and executes a parameterized query. Requires --allow=net and ffi permissions. ```javascript // Install: ekko add @ekko/postgres import { PgClient } from "@ekko/postgres"; const db = new PgClient({ host: "localhost", port: 5432, database: "app", user: "app", password: "secret", }); const res = db.query("SELECT id, name FROM users WHERE age > @p0", { p0: 25 }); db.close(); ``` -------------------------------- ### Initialize a GUI application window Source: https://ekkojs.com/docs/apps/gui Create a new native window with custom dimensions and inline HTML content. ```javascript import { createWindow, onMessage, send } from "ekko:app/gui"; const win = await createWindow({ title: "My App", width: 800, height: 600, html: `

Hello from EkkoJS

`, }); onMessage((msg) => { if (msg.click) send({ message: "got your click" }); }); ``` -------------------------------- ### Number Refinements Example Source: https://ekkojs.com/docs/api/web/validate Illustrates the use of number-specific refinements such as .int(), .positive(), and range constraints. ```typescript import { z } from "ekko:web/validate"; const Pagination = z.object({ page: z.number().int().positive(), pageSize: z.number().int().min(1).max(100), }); console.log(Pagination.parse({ page: 1, pageSize: 25 })); ``` -------------------------------- ### Define an asynchronous test Source: https://ekkojs.com/docs/api/test Example of testing asynchronous code using an async test function. ```typescript import { test, expect } from "ekko:test"; test("fetches a value", async () => { const value = await Promise.resolve(42); expect(value).toBe(42); }); ``` -------------------------------- ### Initialize a Database Connection Source: https://ekkojs.com/docs/api/db/ekko-db Create a new database handle using a file path or the :memory: identifier. Always use a static import for the ekko:db module. ```javascript import { Database } from "ekko:db"; const file = new Database("./data/app.db"); // persistent, created if missing const mem = new Database(":memory:"); // ephemeral, perfect for tests ``` -------------------------------- ### Initialize app with manifest Source: https://ekkojs.com/docs/rune/build-and-deploy Configures the server to use the generated manifest for hydration. ```javascript import { createApp, readManifest } from "ekko:rune"; const app = createApp({ port: 3000, manifest: readManifest() }); // manifest enables hydration ``` -------------------------------- ### Basic execution with exec Source: https://ekkojs.com/docs/api/process Simple example of executing a command and accessing its output and exit code. ```typescript import { exec } from "ekko:process"; const result = await exec("echo", ["hello"]); console.log(result.stdout.trim()); // "hello" console.log(result.exitCode); // 0 ``` -------------------------------- ### Terminal Query Methods Source: https://ekkojs.com/docs/api/db/orm/aggregates-and-grouping Examples of terminal methods used to execute queries and return results. ```typescript orm.from(Users).first(); // { id, name, age } | null orm.from(Users).where((u) => u.name.eq("Alice")).firstOrThrow(); // throws if absent orm.from(Users).where((u) => u.name.eq("Nobody")).exists(); // false orm.from(Users).where((u) => u.name.eq("Nobody")).toArray(); // [] ``` -------------------------------- ### Initialize SEO and generate head tags Source: https://ekkojs.com/docs/rune/seo Demonstrates basic initialization of the SEO helper and generation of HTML head tags. ```typescript import { createSEO } from "ekko:rune/seo"; const seo = createSEO({ site: { name: "My Blog", url: "https://myblog.com" }, meta: { description: "Thoughts on software." }, }); console.log(seo.headTags({ title: "Hello World" })); // Hello World... ``` -------------------------------- ### Streaming Decompression Example Source: https://ekkojs.com/docs/api/compress Demonstrates reconstructing a payload by feeding compressed chunks into a decompression stream. ```javascript import { gzip } from "ekko:compress"; import { utf8 } from "ekko:text/encoding"; // Pretend these two halves arrived separately over the network. const whole = gzip.compress(utf8.encode("streamed payload")); const a = whole.slice(0, 10), b = whole.slice(10); const d = gzip.createDecompressStream(); d.write(a); d.write(b); console.log(utf8.decode(d.finish())); // "streamed payload" ``` -------------------------------- ### Define a table with foreign keys Source: https://ekkojs.com/docs/api/db/orm/defining-tables Example of defining a posts table that references the users table. ```typescript const Posts = defineTable("posts", { id: col.int().primaryKey().autoIncrement(), title: col.text(), body: col.text().nullable(), authorId: col.int().references(Users, "id"), views: col.int().default(0), createdAt: col.timestamp(), }); orm.createTable(Posts); ``` -------------------------------- ### Initialize SEO Configuration Source: https://ekkojs.com/docs/rune/seo Use createSEO to define site-wide defaults for meta tags, Open Graph, and Twitter settings. ```javascript import { createSEO } from "ekko:rune/seo"; const seo = createSEO({ site: { name: "Acme", url: "https://acme.com", language: "en" }, meta: { description: "Acme makes things.", author: "Acme Inc." }, og: { type: "website", image: "https://acme.com/og.png" }, twitter: { card: "summary_large_image", site: "@acme" }, }); ``` -------------------------------- ### Define a basic table Source: https://ekkojs.com/docs/api/db/orm/defining-tables Example of defining a users table with various column types and constraints. ```typescript import { connect, defineTable, col } from "ekko:db/orm"; const orm = connect(":memory:"); const Users = defineTable("users", { id: col.int().primaryKey().autoIncrement(), email: col.text().unique(), name: col.text(), age: col.int().nullable(), active: col.bool().default(true), }); orm.createTable(Users); ``` -------------------------------- ### Create a web server with database integration Source: https://ekkojs.com/docs/api/ekko Initialize a server and query the database using the defined model with parameterized inputs. ```typescript // server.ts import { createServer } from "ekko:web"; import { connect } from "ekko:db/orm"; import { Users } from "./models/user"; const db = connect("./app.db"); const server = createServer({ port: 3000 }); server.get("/users/:id", (req, res) => { // The id is bound as a parameter, never concatenated into a query. const user = db.from(Users).where((u) => u.id.eq(req.params.id)).first(); if (!user) return res.status(404).json({ error: "not found" }); res.json(user); }); server.start(); ``` -------------------------------- ### tcp.listen Source: https://ekkojs.com/docs/api/net/tcp Starts a TCP server on the specified host and port, invoking a callback for each incoming connection. ```APIDOC ## tcp.listen(host: string, port: number, onConnection: (conn: Connection) => void): number ### Description Starts a TCP server and returns a listener handle. The provided callback is executed for every incoming client connection. ### Parameters - **host** (string) - Required - Address to bind: "localhost", "0.0.0.0", or a specific IP literal. - **port** (number) - Required - TCP port to listen on. - **onConnection** ((conn: Connection) => void) - Required - Callback function triggered for every incoming client connection. ### Returns - **number** - A listener handle used to stop the server. ``` -------------------------------- ### Manual package signing for debugging Source: https://ekkojs.com/docs/guides/publishing Demonstrates how to manually sign a package archive using the ecdsaSign primitive. ```javascript import { ecdsaSign, ecdsaVerify } from "ekko:crypto"; import { read, readText } from "ekko:fs"; import { base64 } from "ekko:text/encoding"; const priv = readText("~/.ekko/signing-key.pem"); const data = read("package.ekl"); const sig = ecdsaSign(priv, data); console.log("signature (base64):", base64.encode(sig)); ```