@tylix/core 0.6.0 → 1.0.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.
@@ -0,0 +1,31 @@
1
+ export interface Store {
2
+ readonly driver: 'memory' | 'database' | 'redis'
3
+ /** True when other processes see the same values and messages. */
4
+ readonly shared: boolean
5
+ get<T = unknown>(key: string): Promise<T | null>
6
+ set(key: string, value: unknown, options?: { ttlMs?: number }): Promise<void>
7
+ delete(key: string): Promise<void>
8
+ /** Deletes every key starting with prefix; resolves to how many. */
9
+ deletePrefix(prefix: string): Promise<number>
10
+ /** Adds `by` (default 1) atomically and returns the new count; ttlMs applies when the key is new. */
11
+ increment(key: string, options?: { by?: number; ttlMs?: number }): Promise<number>
12
+ publish(channel: string, message: unknown): Promise<void>
13
+ /** Resolves to a function that unsubscribes. */
14
+ subscribe(channel: string, listener: (message: any) => void): Promise<() => Promise<void>>
15
+ close(): Promise<void>
16
+ }
17
+
18
+ export interface StoreOptions {
19
+ driver?: 'memory' | 'database' | 'redis'
20
+ /** For redis. */
21
+ redisUrl?: string
22
+ /** Put in front of every key and channel. */
23
+ prefix?: string
24
+ /** How often the database driver checks for messages. Default 250ms. */
25
+ pollMs?: number
26
+ }
27
+
28
+ export declare function createStore(options?: StoreOptions): Promise<Store>
29
+ /** The app's store ("tylix dev" and "tylix start" set it from STORE_DRIVER). */
30
+ export declare function getStore(): Store
31
+ export declare function setStore(store: Store): void
@@ -0,0 +1,52 @@
1
+ import { createMemoryStore } from './memory.js'
2
+ import { createDatabaseStore } from './database.js'
3
+ import { createRedisStore } from './redis.js'
4
+
5
+ // A key-value store with expiry, atomic counters and messages, shared by
6
+ // every process of the app (except the memory driver). Rate limits, the
7
+ // cache and channel broadcasts use it, so running several workers or
8
+ // servers behaves like one.
9
+ //
10
+ // STORE_DRIVER=memory this process only (fastest; one process)
11
+ // STORE_DRIVER=database the app's database (default; nothing new to run)
12
+ // STORE_DRIVER=redis Redis at REDIS_URL (npm install redis)
13
+ //
14
+ // Keys are prefixed (STORE_PREFIX, default the app name), so apps can
15
+ // share a Redis.
16
+
17
+ export async function createStore({ driver = 'database', redisUrl, prefix = '', adapter, client, pollMs } = {}) {
18
+ let inner
19
+ if (driver === 'memory') inner = createMemoryStore()
20
+ else if (driver === 'database') inner = createDatabaseStore({ adapter, pollMs })
21
+ else if (driver === 'redis') inner = await createRedisStore({ url: redisUrl, client })
22
+ else throw new Error(`Unknown store driver "${driver}": use memory, database or redis.`)
23
+ return withPrefix(inner, prefix)
24
+ }
25
+
26
+ function withPrefix(store, prefix) {
27
+ if (!prefix) return store
28
+ const k = (key) => `${prefix}${key}`
29
+ return {
30
+ ...store,
31
+ get: (key) => store.get(k(key)),
32
+ set: (key, value, options) => store.set(k(key), value, options),
33
+ delete: (key) => store.delete(k(key)),
34
+ deletePrefix: (start) => store.deletePrefix(k(start)),
35
+ increment: (key, options) => store.increment(k(key), options),
36
+ publish: (channel, message) => store.publish(k(channel), message),
37
+ subscribe: (channel, listener) => store.subscribe(k(channel), listener),
38
+ }
39
+ }
40
+
41
+ // The app's store, set by "tylix dev" / "tylix start" (and the workers)
42
+ // from the settings. Until then: a memory store.
43
+ let current = null
44
+
45
+ export function setStore(store) {
46
+ current = store
47
+ }
48
+
49
+ export function getStore() {
50
+ current ??= createMemoryStore()
51
+ return current
52
+ }
@@ -0,0 +1,72 @@
1
+ import { EventEmitter } from 'node:events'
2
+
3
+ // One process only: the fastest driver, but other processes (workers,
4
+ // "tylix channels:work") neither see its values nor its messages.
5
+ export function createMemoryStore() {
6
+ const values = new Map()
7
+ const events = new EventEmitter()
8
+ events.setMaxListeners(0)
9
+
10
+ const live = (key) => {
11
+ const entry = values.get(key)
12
+ if (!entry) return null
13
+ if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
14
+ values.delete(key)
15
+ return null
16
+ }
17
+ return entry
18
+ }
19
+
20
+ // Expired entries nobody reads again are swept once a minute.
21
+ const sweep = setInterval(() => {
22
+ const now = Date.now()
23
+ for (const [key, entry] of values) if (entry.expiresAt !== null && entry.expiresAt <= now) values.delete(key)
24
+ }, 60_000)
25
+ sweep.unref()
26
+
27
+ return {
28
+ driver: 'memory',
29
+ shared: false,
30
+ async get(key) {
31
+ return live(key)?.value ?? null
32
+ },
33
+ async set(key, value, { ttlMs } = {}) {
34
+ values.set(key, { value, expiresAt: ttlMs ? Date.now() + ttlMs : null })
35
+ },
36
+ async delete(key) {
37
+ values.delete(key)
38
+ },
39
+ async deletePrefix(prefix) {
40
+ let count = 0
41
+ for (const key of [...values.keys()]) {
42
+ if (key.startsWith(prefix)) {
43
+ values.delete(key)
44
+ count++
45
+ }
46
+ }
47
+ return count
48
+ },
49
+ async increment(key, { by = 1, ttlMs } = {}) {
50
+ const entry = live(key)
51
+ if (entry) {
52
+ entry.value = Number(entry.value) + by
53
+ return entry.value
54
+ }
55
+ values.set(key, { value: by, expiresAt: ttlMs ? Date.now() + ttlMs : null })
56
+ return by
57
+ },
58
+ async publish(channel, message) {
59
+ // Asynchronous, like the shared drivers, so code doesn't come to rely
60
+ // on a subscriber running before publish() returns.
61
+ setImmediate(() => events.emit(channel, message))
62
+ },
63
+ async subscribe(channel, listener) {
64
+ events.on(channel, listener)
65
+ return async () => events.off(channel, listener)
66
+ },
67
+ async close() {
68
+ clearInterval(sweep)
69
+ events.removeAllListeners()
70
+ },
71
+ }
72
+ }
@@ -0,0 +1,77 @@
1
+ import { createRequire } from 'node:module'
2
+ import path from 'node:path'
3
+
4
+ // Redis: the fastest shared driver, for many servers and heavy traffic.
5
+ // Needs the "redis" package in the app (npm install redis) and REDIS_URL.
6
+
7
+ // INCRBY, and set the expiry only when the key has none yet, atomically.
8
+ const INCREMENT = `
9
+ local value = redis.call('INCRBY', KEYS[1], ARGV[1])
10
+ if tonumber(ARGV[2]) > 0 and redis.call('PTTL', KEYS[1]) < 0 then
11
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
12
+ end
13
+ return value`
14
+
15
+ async function loadRedis() {
16
+ try {
17
+ const require = createRequire(path.join(process.cwd(), 'package.json'))
18
+ return await import(require.resolve('redis'))
19
+ } catch {
20
+ throw new Error('STORE_DRIVER=redis needs the "redis" package: run npm install redis')
21
+ }
22
+ }
23
+
24
+ // `client` is for tests: anything with node-redis's methods.
25
+ export async function createRedisStore({ url, client: given } = {}) {
26
+ let client = given
27
+ if (!client) {
28
+ const { createClient } = await loadRedis()
29
+ client = createClient({ url })
30
+ client.on('error', (err) => console.error('[tylix] Redis:', err.message))
31
+ await client.connect()
32
+ }
33
+ let subscriber = null
34
+
35
+ return {
36
+ driver: 'redis',
37
+ shared: true,
38
+ client,
39
+ async get(key) {
40
+ const raw = await client.get(key)
41
+ return raw === null ? null : JSON.parse(raw)
42
+ },
43
+ async set(key, value, { ttlMs } = {}) {
44
+ await client.set(key, JSON.stringify(value), ttlMs ? { PX: ttlMs } : undefined)
45
+ },
46
+ async delete(key) {
47
+ await client.del(key)
48
+ },
49
+ async deletePrefix(prefix) {
50
+ let count = 0
51
+ for await (const keys of client.scanIterator({ MATCH: `${prefix.replace(/[*?[\]\\]/g, '\\$&')}*`, COUNT: 500 })) {
52
+ const batch = Array.isArray(keys) ? keys : [keys]
53
+ if (batch.length) count += await client.del(batch)
54
+ }
55
+ return count
56
+ },
57
+ async increment(key, { by = 1, ttlMs } = {}) {
58
+ return Number(await client.eval(INCREMENT, { keys: [key], arguments: [String(by), String(ttlMs ?? 0)] }))
59
+ },
60
+ async publish(channel, message) {
61
+ await client.publish(channel, JSON.stringify(message))
62
+ },
63
+ async subscribe(channel, listener) {
64
+ if (!subscriber) {
65
+ subscriber = client.duplicate()
66
+ await subscriber.connect()
67
+ }
68
+ const handler = (raw) => listener(JSON.parse(raw))
69
+ await subscriber.subscribe(channel, handler)
70
+ return async () => subscriber.unsubscribe(channel, handler)
71
+ },
72
+ async close() {
73
+ await subscriber?.quit()
74
+ if (!given) await client.quit()
75
+ },
76
+ }
77
+ }
@@ -1,99 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { Router } from "../router/Router.js";
4
- import { Server } from "./Server.js";
5
-
6
- test("handles a matched GET route", async () => {
7
- const router = new Router();
8
- router.get("/api/ping", (req, res) => res.json({ pong: true }));
9
-
10
- const server = new Server(router);
11
- const httpServer = server.listen(0);
12
- const { port } = httpServer.address();
13
-
14
- const response = await fetch(`http://localhost:${port}/api/ping`);
15
- const body = await response.json();
16
-
17
- assert.equal(response.status, 200);
18
- assert.deepEqual(body, { pong: true });
19
-
20
- httpServer.close();
21
- });
22
-
23
- test("returns 404 for unmatched routes", async () => {
24
- const router = new Router();
25
- const server = new Server(router);
26
- const httpServer = server.listen(0);
27
- const { port } = httpServer.address();
28
-
29
- const response = await fetch(`http://localhost:${port}/nonexistent`);
30
- assert.equal(response.status, 404);
31
-
32
- httpServer.close();
33
- });
34
-
35
- test("parses JSON body and passes params to handler", async () => {
36
- const router = new Router();
37
- router.post("/api/echo/:id", (req, res) => {
38
- res.json({ id: req.params.id, body: req.body });
39
- });
40
-
41
- const server = new Server(router);
42
- const httpServer = server.listen(0);
43
- const { port } = httpServer.address();
44
-
45
- const response = await fetch(`http://localhost:${port}/api/echo/42`, {
46
- method: "POST",
47
- headers: { "Content-Type": "application/json" },
48
- body: JSON.stringify({ title: "Hello" }),
49
- });
50
- const body = await response.json();
51
-
52
- assert.deepEqual(body, { id: "42", body: { title: "Hello" } });
53
-
54
- httpServer.close();
55
- });
56
-
57
- test("parses query string into req.query", async () => {
58
- const router = new Router();
59
- router.get("/api/comments/:id", (req, res) => {
60
- res.json({ id: req.params.id, include: req.query.include ?? null });
61
- });
62
-
63
- const server = new Server(router);
64
- const httpServer = server.listen(0);
65
- const { port } = httpServer.address();
66
-
67
- const response = await fetch(`http://localhost:${port}/api/comments/1?include=post`);
68
- const body = await response.json();
69
-
70
- assert.deepEqual(body, { id: "1", include: "post" });
71
-
72
- httpServer.close();
73
- });
74
-
75
- test("calls notFoundHandler when no route matches, and skips 404 if it handles the request", async () => {
76
- const router = new Router();
77
- const server = new Server(router, {
78
- notFoundHandler: async (req, res) => {
79
- if (req.url === "/static-file.txt") {
80
- res.setHeader("Content-Type", "text/plain");
81
- res.end("served by fallback");
82
- return true;
83
- }
84
- return false;
85
- },
86
- });
87
-
88
- const httpServer = server.listen(0);
89
- const { port } = httpServer.address();
90
-
91
- const handled = await fetch(`http://localhost:${port}/static-file.txt`);
92
- const handledBody = await handled.text();
93
- assert.equal(handledBody, "served by fallback");
94
-
95
- const unhandled = await fetch(`http://localhost:${port}/nonexistent`);
96
- assert.equal(unhandled.status, 404);
97
-
98
- httpServer.close();
99
- });
@@ -1,45 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { enhanceResponse } from "./enhanceResponse.js";
4
-
5
- function createMockResponse() {
6
- return {
7
- statusCode: 200,
8
- headers: {},
9
- body: null,
10
- setHeader(key, value) {
11
- this.headers[key] = value;
12
- },
13
- end(data) {
14
- this.body = data;
15
- },
16
- };
17
- }
18
-
19
- test("status() sets statusCode and returns res for chaining", () => {
20
- const res = enhanceResponse(createMockResponse());
21
- const result = res.status(404);
22
- assert.equal(res.statusCode, 404);
23
- assert.equal(result, res);
24
- });
25
-
26
- test("json() sets content-type and serializes body", () => {
27
- const res = enhanceResponse(createMockResponse());
28
- res.json({ hello: "world" });
29
- assert.equal(res.headers["Content-Type"], "application/json");
30
- assert.equal(res.body, JSON.stringify({ hello: "world" }));
31
- });
32
-
33
- test("status().json() chains correctly", () => {
34
- const res = enhanceResponse(createMockResponse());
35
- res.status(201).json({ id: 1 });
36
- assert.equal(res.statusCode, 201);
37
- assert.equal(res.body, JSON.stringify({ id: 1 }));
38
- });
39
-
40
- test("send() with no args ends the response with no body", () => {
41
- const res = enhanceResponse(createMockResponse());
42
- res.status(204).send();
43
- assert.equal(res.statusCode, 204);
44
- assert.equal(res.body, undefined);
45
- });
@@ -1,33 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { Readable } from "node:stream";
4
- import { parseBody } from "./parseBody.js";
5
-
6
- function createMockRequest(bodyString, contentType = "application/json") {
7
- const req = Readable.from([bodyString]);
8
- req.headers = { "content-type": contentType };
9
- return req;
10
- }
11
-
12
- test("parses a valid JSON body", async () => {
13
- const req = createMockRequest(JSON.stringify({ title: "Hello" }));
14
- const body = await parseBody(req);
15
- assert.deepEqual(body, { title: "Hello" });
16
- });
17
-
18
- test("returns empty object for empty body", async () => {
19
- const req = createMockRequest("");
20
- const body = await parseBody(req);
21
- assert.deepEqual(body, {});
22
- });
23
-
24
- test("returns empty object when content-type is not JSON", async () => {
25
- const req = createMockRequest("plain text", "text/plain");
26
- const body = await parseBody(req);
27
- assert.deepEqual(body, {});
28
- });
29
-
30
- test("rejects on malformed JSON", async () => {
31
- const req = createMockRequest("{not valid json");
32
- await assert.rejects(() => parseBody(req), /Invalid JSON body/);
33
- });
@@ -1,15 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { parseQuery } from "./parseQuery.js";
4
-
5
- test("returns empty object when there is no query string", () => {
6
- assert.deepEqual(parseQuery("/api/posts"), {});
7
- });
8
-
9
- test("parses a single query param", () => {
10
- assert.deepEqual(parseQuery("/api/comments/1?include=post"), { include: "post" });
11
- });
12
-
13
- test("parses multiple query params", () => {
14
- assert.deepEqual(parseQuery("/api/posts?page=2&limit=10"), { page: "2", limit: "10" });
15
- });
@@ -1,76 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { signToken } from "@tylix/auth";
4
- import { requireAuth } from "./requireAuth.js";
5
-
6
- function createMockRes() {
7
- return {
8
- statusCode: 200,
9
- body: null,
10
- status(code) {
11
- this.statusCode = code;
12
- return this;
13
- },
14
- json(data) {
15
- this.body = data;
16
- return this;
17
- },
18
- };
19
- }
20
-
21
- test("calls the handler and sets req.user when the token is valid", async () => {
22
- const token = signToken({ userId: 7 }, "test-secret");
23
- const req = { headers: { authorization: `Bearer ${token}` } };
24
- const res = createMockRes();
25
-
26
- let calledWith = null;
27
- const handler = requireAuth((req, res) => {
28
- calledWith = req.user;
29
- res.json({ ok: true });
30
- }, "test-secret");
31
-
32
- await handler(req, res);
33
-
34
- assert.deepEqual(calledWith, { userId: 7 });
35
- assert.deepEqual(res.body, { ok: true });
36
- });
37
-
38
- test("responds 401 when Authorization header is missing", async () => {
39
- const req = { headers: {} };
40
- const res = createMockRes();
41
-
42
- const handler = requireAuth(() => {
43
- throw new Error("should not be called");
44
- }, "test-secret");
45
-
46
- await handler(req, res);
47
-
48
- assert.equal(res.statusCode, 401);
49
- });
50
-
51
- test("responds 401 when the token is signed with a different secret", async () => {
52
- const token = signToken({ userId: 1 }, "wrong-secret");
53
- const req = { headers: { authorization: `Bearer ${token}` } };
54
- const res = createMockRes();
55
-
56
- const handler = requireAuth(() => {
57
- throw new Error("should not be called");
58
- }, "test-secret");
59
-
60
- await handler(req, res);
61
-
62
- assert.equal(res.statusCode, 401);
63
- });
64
-
65
- test("responds 401 when the Authorization header has no Bearer scheme", async () => {
66
- const req = { headers: { authorization: "Basic abc123" } };
67
- const res = createMockRes();
68
-
69
- const handler = requireAuth(() => {
70
- throw new Error("should not be called");
71
- }, "test-secret");
72
-
73
- await handler(req, res);
74
-
75
- assert.equal(res.statusCode, 401);
76
- });
@@ -1,16 +0,0 @@
1
- import { reactive } from '@tylix/compiler'
2
-
3
- export function createProvider(setup) {
4
- const state = reactive(setup.state ? setup.state() : {})
5
- let inflight = null
6
-
7
- async function load(...args) {
8
- if (inflight) return inflight
9
- inflight = setup.fetch(state, ...args).finally(() => {
10
- inflight = null
11
- })
12
- return inflight
13
- }
14
-
15
- return { state, load, ...(setup.actions ? setup.actions(state) : {}) }
16
- }
@@ -1,128 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { Router } from "./Router.js";
4
-
5
- // match() returns a composed chain (global middleware, route
6
- // middleware, then the final handler), so tests run the chain and
7
- // check what the original handler saw.
8
- async function run(match) {
9
- const req = {};
10
- const res = {};
11
- await match.handler(req, res);
12
- return { req, res };
13
- }
14
-
15
- test("matches an exact static route", async () => {
16
- const router = new Router();
17
- let calls = 0;
18
- router.get("/api/posts", () => {
19
- calls++;
20
- });
21
-
22
- const match = router.match("GET", "/api/posts");
23
- assert.ok(match);
24
- assert.deepEqual(match.params, {});
25
-
26
- await run(match);
27
- assert.equal(calls, 1);
28
- });
29
-
30
- test("matches a dynamic route and extracts params", async () => {
31
- const router = new Router();
32
- let calls = 0;
33
- router.get("/api/posts/:id", () => {
34
- calls++;
35
- });
36
-
37
- const match = router.match("GET", "/api/posts/42");
38
- assert.ok(match);
39
- assert.deepEqual(match.params, { id: "42" });
40
-
41
- await run(match);
42
- assert.equal(calls, 1);
43
- });
44
-
45
- test("differentiates by HTTP method", async () => {
46
- const router = new Router();
47
- const seen = [];
48
- router.get("/api/posts", () => seen.push("get"));
49
- router.post("/api/posts", () => seen.push("post"));
50
-
51
- await run(router.match("GET", "/api/posts"));
52
- await run(router.match("POST", "/api/posts"));
53
-
54
- assert.deepEqual(seen, ["get", "post"]);
55
- });
56
-
57
- test("returns null when no route matches", () => {
58
- const router = new Router();
59
- router.get("/api/posts", () => {});
60
- assert.equal(router.match("GET", "/api/nonexistent"), null);
61
- });
62
-
63
- test("ignores query string when matching", async () => {
64
- const router = new Router();
65
- let calls = 0;
66
- router.get("/api/posts", () => {
67
- calls++;
68
- });
69
-
70
- const match = router.match("GET", "/api/posts?page=2");
71
- assert.ok(match);
72
-
73
- await run(match);
74
- assert.equal(calls, 1);
75
- });
76
-
77
- test("runs global middleware, then route middleware, then the handler, in order", async () => {
78
- const router = new Router();
79
- const order = [];
80
-
81
- router.use(async (req, res, next) => {
82
- order.push("global");
83
- await next();
84
- });
85
- router.get(
86
- "/api/posts",
87
- async (req, res, next) => {
88
- order.push("route");
89
- await next();
90
- },
91
- () => {
92
- order.push("handler");
93
- },
94
- );
95
-
96
- await run(router.match("GET", "/api/posts"));
97
- assert.deepEqual(order, ["global", "route", "handler"]);
98
- });
99
-
100
- test("a middleware that does not call next() stops the chain", async () => {
101
- const router = new Router();
102
- let handlerCalled = false;
103
-
104
- router.use(() => {
105
- // deliberately never calls next()
106
- });
107
- router.get("/api/posts", () => {
108
- handlerCalled = true;
109
- });
110
-
111
- await run(router.match("GET", "/api/posts"));
112
- assert.equal(handlerCalled, false);
113
- });
114
-
115
- test("calling next() twice in one middleware rejects", async () => {
116
- const router = new Router();
117
-
118
- router.use(async (req, res, next) => {
119
- await next();
120
- await next();
121
- });
122
- router.get("/api/posts", () => {});
123
-
124
- await assert.rejects(
125
- () => run(router.match("GET", "/api/posts")),
126
- /next\(\) called multiple times/,
127
- );
128
- });