zawit 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kacalayar <kacalayar64@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,109 @@
1
- # Temporary Holding Version
1
+ ```text
2
+ __ _.--..--._ __
3
+ .-' _/ _/\_ \_'-.
4
+ |__ / _/\__/\_ \__|
5
+ |___/\_\__/ \___|
6
+ \__/
7
+ \__/
8
+ \__/
9
+ \__/
10
+ ____\__/____
11
+ . - ' ' -.
12
+ / \
13
+ ~~~~~~~~~~ Z A W I T ~~~~~~~~~~
14
+ ```
2
15
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
16
+ # 🌴 Zawit
17
+
18
+ A lightweight, **zero-dependency**, **security-hardened**, and **SEO-ready** JavaScript web & API framework built on Web Standards (`Request` / `Response`) and Node.js.
19
+
20
+ - **Zero Runtime Dependencies**: Pure modern ESM JavaScript (`Node.js >= 18.11.0`).
21
+ - **Next.js-style Setup & File Routing**: `npx zawit create my-app`, `zawit dev` (auto-reload), and optional `routes/` directory (`[id].js`, `[...slug].js`).
22
+ - **Seamless npm Integration**: Works natively with any npm package (`zod`, `prisma`, `drizzle-orm`, etc.) plus `adaptExpress()` for Express/Connect middlewares (`helmet`, `cors`, `morgan`).
23
+ - **SEO Built-in**: `ctx.html(body, { seo })` with Open Graph, Twitter Cards, canonical URLs, XSS-safe JSON-LD, `sitemap()`, and `robotsTxt()`.
24
+ - **Secure by Default**: Safe error responses (no stack trace leaks), strict static path-traversal & dotfile protection, hardened CORS, and `securityHeaders()`.
25
+ - **TypeScript IntelliSense**: Ships with `types/index.d.ts` out of the box.
26
+
27
+ ---
28
+
29
+ ## Quick Start (Next.js-style CLI)
30
+
31
+ ```bash
32
+ npx zawit create my-app
33
+ cd my-app
34
+ npm install
35
+ npm run dev
36
+ ```
37
+
38
+ Or install directly in an existing project:
39
+
40
+ ```bash
41
+ npm install zawit
42
+ ```
43
+
44
+ ### Minimal Example
45
+
46
+ ```js
47
+ import { Zawit, logger, securityHeaders } from 'zawit';
48
+
49
+ const app = new Zawit();
50
+
51
+ app.use(logger());
52
+ app.use(securityHeaders());
53
+
54
+ app.get('/', (ctx) =>
55
+ ctx.html('<h1>Hello Zawit</h1>', {
56
+ seo: {
57
+ title: 'Home — My App',
58
+ description: 'Fast, secure, and SEO-ready app built with Zawit.',
59
+ canonical: 'https://example.com/'
60
+ }
61
+ })
62
+ );
63
+
64
+ app.get('/api/users/:id', (ctx) => {
65
+ return ctx.json({ id: ctx.params.id, filter: ctx.query.filter ?? null });
66
+ });
67
+
68
+ app.listen(3000, () => console.log('Listening on http://localhost:3000'));
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Modular Architecture
74
+
75
+ Zawit exposes modular subpath imports so you only load what you need:
76
+
77
+ | Import Path | Contents |
78
+ |---|---|
79
+ | `zawit` | Full framework (`Zawit`, `Context`, `Router`, middlewares, SEO, adapters) |
80
+ | `zawit/router` | Standalone `Router` |
81
+ | `zawit/middleware` | `logger`, `cors`, `serveStatic`, `securityHeaders` |
82
+ | `zawit/seo` | `renderHead`, `renderDocument`, `sitemap`, `robotsTxt`, `escapeHtml` |
83
+ | `zawit/adapters/express` | `adaptExpress` for Express/Connect npm middlewares |
84
+ | `zawit/adapters/node` | `createNodeServer`, `toWebRequest`, `sendNodeResponse` |
85
+
86
+ ---
87
+
88
+ ## Documentation
89
+
90
+ - [Getting Started](docs/getting-started.md) — CLI setup, routes, request/response context
91
+ - [Routing & Middleware](docs/routing-and-middleware.md) — Programmatic routes, groups, file-based `routes/`, onion middleware
92
+ - [Integrating npm Packages](docs/npm-integration.md) — Using `zod`, `prisma`, `drizzle-orm`, and Express middlewares via `adaptExpress()`
93
+ - [SEO & Security](docs/seo-and-security.md) — Meta tags, JSON-LD, sitemaps, CORS, static serving, and error handling
94
+ - [LLM & Contributor Architecture Guide](LLM.md) — Map for AI coding agents and contributors
95
+
96
+ ## Examples
97
+
98
+ - [examples/basic-api/server.js](examples/basic-api/server.js) — In-memory REST API with route groups & validation
99
+ - [examples/express-adapter/server.js](examples/express-adapter/server.js) — Running Express-style `(req, res, next)` middleware inside Zawit
100
+
101
+ ## Running Tests
102
+
103
+ ```bash
104
+ npm test
105
+ ```
106
+
107
+ ## License
108
+
109
+ [MIT](LICENSE)
package/bin/zawit.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../src/cli/index.js';
3
+
4
+ runCli(process.argv.slice(2)).catch((err) => {
5
+ console.error(`zawit: ${err.message}`);
6
+ process.exit(1);
7
+ });
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "zawit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Lightweight, zero-dependency, security-hardened & SEO-ready JavaScript web framework with npm/Express compatibility and Next.js-style CLI.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./types/index.d.ts",
8
+ "bin": {
9
+ "zawit": "bin/zawit.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./types/index.d.ts",
14
+ "default": "./src/index.js"
15
+ },
16
+ "./router": "./src/core/router.js",
17
+ "./middleware": "./src/middleware/index.js",
18
+ "./seo": "./src/seo/index.js",
19
+ "./adapters/express": "./src/adapters/express.js",
20
+ "./adapters/node": "./src/adapters/node.js"
21
+ },
22
+ "files": [
23
+ "bin/",
24
+ "src/",
25
+ "types/",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=18.11.0"
31
+ },
32
+ "scripts": {
33
+ "test": "node --test"
34
+ },
35
+ "author": "kacalayar <kacalayar64@gmail.com>",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/kacalayar/Zawit-Framework.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/kacalayar/Zawit-Framework/issues"
42
+ },
43
+ "homepage": "https://github.com/kacalayar/Zawit-Framework#readme",
44
+ "keywords": [
45
+ "framework",
46
+ "web",
47
+ "api",
48
+ "http",
49
+ "router",
50
+ "middleware",
51
+ "seo",
52
+ "zero-dependency",
53
+ "esm"
54
+ ],
55
+ "license": "MIT"
56
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Adapt a classic Express/Connect `(req, res, next)` npm middleware to Zawit.
3
+ * Works both under Node HTTP (`app.listen`) and Web Standard (`app.fetch`).
4
+ *
5
+ * @param {(req: any, res: any, next: (err?: any) => void) => void} middleware
6
+ * @returns {(ctx: import('../core/context.js').Context, next: () => Promise<void>) => Promise<void>}
7
+ */
8
+ export function adaptExpress(middleware) {
9
+ return async (ctx, next) => {
10
+ const reqHeaders = Object.fromEntries(ctx.req.headers.entries());
11
+ const req = {
12
+ method: ctx.method,
13
+ url: ctx.url.pathname + ctx.url.search,
14
+ originalUrl: ctx.url.pathname + ctx.url.search,
15
+ path: ctx.path,
16
+ query: ctx.query,
17
+ params: ctx.params,
18
+ headers: reqHeaders,
19
+ get(name) {
20
+ return ctx.header(name) ?? undefined;
21
+ }
22
+ };
23
+
24
+ const resHeaders = new Headers();
25
+ let ended = false;
26
+ let statusCode = 200;
27
+ let endedBody = null;
28
+
29
+ const res = {
30
+ get statusCode() {
31
+ return statusCode;
32
+ },
33
+ set statusCode(code) {
34
+ statusCode = code;
35
+ },
36
+ status(code) {
37
+ statusCode = code;
38
+ return res;
39
+ },
40
+ setHeader(name, value) {
41
+ resHeaders.set(name, String(value));
42
+ },
43
+ getHeader(name) {
44
+ return resHeaders.get(name) ?? undefined;
45
+ },
46
+ removeHeader(name) {
47
+ resHeaders.delete(name);
48
+ },
49
+ set(name, value) {
50
+ resHeaders.set(name, String(value));
51
+ return res;
52
+ },
53
+ json(data) {
54
+ resHeaders.set('Content-Type', 'application/json; charset=utf-8');
55
+ ended = true;
56
+ endedBody = JSON.stringify(data);
57
+ return res;
58
+ },
59
+ send(body) {
60
+ if (typeof body === 'object' && body !== null && !(body instanceof Uint8Array)) {
61
+ return res.json(body);
62
+ }
63
+ ended = true;
64
+ endedBody = body ?? '';
65
+ return res;
66
+ },
67
+ end(body) {
68
+ ended = true;
69
+ endedBody = body ?? null;
70
+ }
71
+ };
72
+
73
+ await new Promise((resolve, reject) => {
74
+ let settled = false;
75
+ const done = (err) => {
76
+ if (settled) return;
77
+ settled = true;
78
+ if (err) reject(err);
79
+ else resolve(undefined);
80
+ };
81
+
82
+ // Intercept res.end / json / send when middleware short-circuits without calling next()
83
+ const origEnd = res.end;
84
+ res.end = (body) => {
85
+ origEnd(body);
86
+ done();
87
+ };
88
+ const origJson = res.json;
89
+ res.json = (data) => {
90
+ origJson(data);
91
+ done();
92
+ return res;
93
+ };
94
+ const origSend = res.send;
95
+ res.send = (body) => {
96
+ origSend(body);
97
+ done();
98
+ return res;
99
+ };
100
+
101
+ try {
102
+ middleware(req, res, done);
103
+ } catch (err) {
104
+ done(err);
105
+ }
106
+ });
107
+
108
+ if (ended) {
109
+ ctx.res = new Response(endedBody, { status: statusCode, headers: resHeaders });
110
+ return;
111
+ }
112
+
113
+ await next();
114
+
115
+ if (ctx.res) {
116
+ resHeaders.forEach((value, key) => {
117
+ if (!ctx.res.headers.has(key)) ctx.res.headers.set(key, value);
118
+ });
119
+ }
120
+ };
121
+ }
@@ -0,0 +1,81 @@
1
+ import http from 'node:http';
2
+ import { Readable } from 'node:stream';
3
+
4
+ /**
5
+ * Convert a Node.js IncomingMessage into a Web Standard Request.
6
+ * @param {http.IncomingMessage} req
7
+ * @returns {Request}
8
+ */
9
+ export function toWebRequest(req) {
10
+ const proto = req.socket?.encrypted ? 'https' : 'http';
11
+ const host = req.headers.host || 'localhost';
12
+ const url = new URL(req.url || '/', `${proto}://${host}`);
13
+
14
+ const headers = new Headers();
15
+ for (const [key, value] of Object.entries(req.headers)) {
16
+ if (value === undefined) continue;
17
+ if (Array.isArray(value)) {
18
+ for (const v of value) headers.append(key, v);
19
+ } else {
20
+ headers.set(key, value);
21
+ }
22
+ }
23
+
24
+ const method = (req.method || 'GET').toUpperCase();
25
+ const hasBody = method !== 'GET' && method !== 'HEAD';
26
+
27
+ /** @type {RequestInit} */
28
+ const init = {
29
+ method,
30
+ headers
31
+ };
32
+
33
+ if (hasBody) {
34
+ init.body = Readable.toWeb(req);
35
+ // @ts-ignore - required by Node fetch Request for streaming bodies
36
+ init.duplex = 'half';
37
+ }
38
+
39
+ return new Request(url, init);
40
+ }
41
+
42
+ /**
43
+ * Write a Web Standard Response back to a Node.js ServerResponse.
44
+ * @param {Response} response
45
+ * @param {http.ServerResponse} res
46
+ */
47
+ export async function sendNodeResponse(response, res) {
48
+ res.statusCode = response.status;
49
+ response.headers.forEach((value, key) => {
50
+ res.setHeader(key, value);
51
+ });
52
+
53
+ if (!response.body) {
54
+ res.end();
55
+ return;
56
+ }
57
+
58
+ const buf = Buffer.from(await response.arrayBuffer());
59
+ res.end(buf);
60
+ }
61
+
62
+ /**
63
+ * Create a Node.js http.Server bound to a Zawit app.
64
+ * @param {import('../core/app.js').Zawit} app
65
+ * @returns {http.Server}
66
+ */
67
+ export function createNodeServer(app) {
68
+ return http.createServer(async (req, res) => {
69
+ try {
70
+ const webReq = toWebRequest(req);
71
+ const webRes = await app.fetch(webReq, { rawReq: req, rawRes: res });
72
+ await sendNodeResponse(webRes, res);
73
+ } catch {
74
+ if (!res.headersSent) {
75
+ res.statusCode = 500;
76
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
77
+ res.end(JSON.stringify({ error: 'Internal Server Error' }));
78
+ }
79
+ }
80
+ });
81
+ }
@@ -0,0 +1,40 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { getStarterFiles } from '../templates/starter.js';
4
+
5
+ /**
6
+ * Scaffold a new Zawit project in targetDir.
7
+ * @param {string} targetArg
8
+ * @param {{ cwd?: string }} [options]
9
+ * @returns {Promise<{ targetDir: string, projectName: string }>}
10
+ */
11
+ export async function createCommand(targetArg, options = {}) {
12
+ const cwd = options.cwd ?? process.cwd();
13
+ const dirName = targetArg || 'zawit-app';
14
+ const targetDir = path.resolve(cwd, dirName);
15
+ const projectName = path.basename(targetDir).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'zawit-app';
16
+
17
+ try {
18
+ const existing = await fs.readdir(targetDir);
19
+ if (existing.length > 0) {
20
+ throw new Error(`Directory "${dirName}" already exists and is not empty.`);
21
+ }
22
+ } catch (err) {
23
+ if (err.code !== 'ENOENT') throw err;
24
+ }
25
+
26
+ const files = getStarterFiles(projectName);
27
+ for (const [relPath, content] of Object.entries(files)) {
28
+ const fullPath = path.join(targetDir, relPath);
29
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
30
+ await fs.writeFile(fullPath, content, 'utf8');
31
+ }
32
+
33
+ console.log(`\nCreated Zawit app in ${targetDir}\n`);
34
+ console.log('Next steps:');
35
+ console.log(` cd ${dirName}`);
36
+ console.log(' npm install');
37
+ console.log(' npm run dev\n');
38
+
39
+ return { targetDir, projectName };
40
+ }
@@ -0,0 +1,20 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+
5
+ export function resolveEntry(entryArg, cwd = process.cwd()) {
6
+ if (entryArg) return path.resolve(cwd, entryArg);
7
+ for (const candidate of ['server.js', 'src/index.js', 'index.js']) {
8
+ const full = path.resolve(cwd, candidate);
9
+ if (fs.existsSync(full)) return full;
10
+ }
11
+ throw new Error('No entry file found (tried server.js, src/index.js, index.js).');
12
+ }
13
+
14
+ export function runNodeEntry(entryArg, { watch = false } = {}) {
15
+ const entry = resolveEntry(entryArg);
16
+ const args = watch ? ['--watch', entry] : [entry];
17
+ const child = spawn(process.execPath, args, { stdio: 'inherit' });
18
+ child.on('exit', (code) => process.exit(code ?? 0));
19
+ return child;
20
+ }
@@ -0,0 +1,11 @@
1
+ import { runNodeEntry } from './dev.js';
2
+
3
+ export function devCommand(entryArg) {
4
+ console.log('Starting Zawit dev server (watch mode)...');
5
+ return runNodeEntry(entryArg, { watch: true });
6
+ }
7
+
8
+ export function startCommand(entryArg) {
9
+ console.log('Starting Zawit production server...');
10
+ return runNodeEntry(entryArg, { watch: false });
11
+ }
@@ -0,0 +1,56 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { createCommand } from './commands/create.js';
5
+ import { devCommand, startCommand } from './commands/start.js';
6
+
7
+ const HELP_TEXT = `Zawit CLI — Lightweight, secure & SEO-ready JS framework
8
+
9
+ Usage:
10
+ zawit create <dir> Create a new Zawit project
11
+ zawit dev [entry] Start development server with auto-reload
12
+ zawit start [entry] Start production server
13
+ zawit --version Show version
14
+ zawit --help Show this help message
15
+ `;
16
+
17
+ async function getVersion() {
18
+ const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../package.json');
19
+ const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
20
+ return pkg.version;
21
+ }
22
+
23
+ /**
24
+ * Dispatch CLI arguments.
25
+ * @param {string[]} argv
26
+ */
27
+ export async function runCli(argv) {
28
+ const [command, ...rest] = argv;
29
+
30
+ if (!command || command === '--help' || command === '-h') {
31
+ console.log(HELP_TEXT);
32
+ return;
33
+ }
34
+
35
+ if (command === '--version' || command === '-v') {
36
+ console.log(await getVersion());
37
+ return;
38
+ }
39
+
40
+ if (command === 'create') {
41
+ await createCommand(rest[0]);
42
+ return;
43
+ }
44
+
45
+ if (command === 'dev') {
46
+ devCommand(rest[0]);
47
+ return;
48
+ }
49
+
50
+ if (command === 'start') {
51
+ startCommand(rest[0]);
52
+ return;
53
+ }
54
+
55
+ throw new Error(`Unknown command "${command}". Run "zawit --help" for usage.`);
56
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Generate starter project files for `zawit create <name>`.
3
+ * @param {string} projectName
4
+ * @returns {Record<string, string>}
5
+ */
6
+ export function getStarterFiles(projectName) {
7
+ return {
8
+ 'package.json': JSON.stringify(
9
+ {
10
+ name: projectName,
11
+ version: '0.1.0',
12
+ private: true,
13
+ type: 'module',
14
+ scripts: {
15
+ dev: 'zawit dev',
16
+ start: 'zawit start'
17
+ },
18
+ dependencies: {
19
+ zawit: '^0.1.0'
20
+ }
21
+ },
22
+ null,
23
+ 2
24
+ ) + '\n',
25
+
26
+ '.gitignore': `node_modules/\n.env\n.env.*\n*.log\n`,
27
+
28
+ 'README.md': `# ${projectName}
29
+
30
+ Built with **Zawit** — zero-dependency, security-hardened & SEO-ready JavaScript framework.
31
+
32
+ ## Getting Started
33
+
34
+ \`\`\`bash
35
+ npm install
36
+ npm run dev
37
+ \`\`\`
38
+
39
+ Open http://localhost:3000
40
+ `,
41
+
42
+ 'server.js': `import { Zawit, logger, securityHeaders, sitemap, robotsTxt } from 'zawit';
43
+
44
+ const app = new Zawit();
45
+
46
+ app.use(logger());
47
+ app.use(securityHeaders());
48
+
49
+ // Auto-load Next.js-style routes from ./routes
50
+ await app.routesDir('./routes');
51
+
52
+ // Built-in SEO endpoints
53
+ app.get('/robots.txt', (ctx) =>
54
+ ctx.text(robotsTxt({ allow: ['/'], sitemap: 'http://localhost:3000/sitemap.xml' }))
55
+ );
56
+
57
+ app.get('/sitemap.xml', (ctx) =>
58
+ ctx
59
+ .set('Content-Type', 'application/xml; charset=utf-8')
60
+ .text(sitemap([{ url: 'http://localhost:3000/', changefreq: 'weekly', priority: 1.0 }]))
61
+ );
62
+
63
+ const port = Number(process.env.PORT) || 3000;
64
+ app.listen(port, () => {
65
+ console.log(\`Zawit server running at http://localhost:\${port}\`);
66
+ });
67
+ `,
68
+
69
+ 'routes/index.js': `export function GET(ctx) {
70
+ return ctx.html(
71
+ \`<main style="font-family:system-ui,sans-serif;max-width:640px;margin:4rem auto;padding:0 1rem">
72
+ <h1>Welcome to ${projectName}</h1>
73
+ <p>Powered by <strong>Zawit</strong> — pure JS, zero dependencies, SEO-ready.</p>
74
+ <p>Try <a href="/api/hello">/api/hello</a> or <a href="/sitemap.xml">/sitemap.xml</a>.</p>
75
+ </main>\`,
76
+ {
77
+ seo: {
78
+ title: '${projectName} — Powered by Zawit',
79
+ description: 'Fast, secure, and SEO-ready web app built with Zawit.',
80
+ canonical: 'http://localhost:3000/'
81
+ }
82
+ }
83
+ );
84
+ }
85
+ `,
86
+
87
+ 'routes/api/hello.js': `export function GET(ctx) {
88
+ const name = ctx.query.name || 'World';
89
+ return ctx.json({ message: \`Hello, \${name}!\`, framework: 'zawit' });
90
+ }
91
+
92
+ export async function POST(ctx) {
93
+ const data = await ctx.body();
94
+ return ctx.json({ received: data }, 201);
95
+ }
96
+ `
97
+ };
98
+ }