@wervt/nitro 0.0.0 → 0.0.2

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/README.md CHANGED
@@ -1,3 +1,25 @@
1
1
  # @wervt/nitro
2
2
 
3
- Placeholder. Released from https://github.com/wervt-app/wervt.
3
+ [Nitro](https://nitro.build) 3 module for apps on [wervt](https://wervt.app).
4
+
5
+ ```ts [nitro.config.ts]
6
+ import { defineConfig } from 'nitro'
7
+ import { wervt } from '@wervt/nitro'
8
+
9
+ export default defineConfig({
10
+ preset: 'deno-server',
11
+ modules: [wervt({ timezone: 'Europe/Berlin' })],
12
+ })
13
+ ```
14
+
15
+ - Builds for wervt's runtime (Supabase Edge Runtime, Deno): `node:` built-ins, Node globals,
16
+ JSDoc import paths.
17
+ - Serves `/_wervt/tasks` (the app's `tasks/`), the boot check and `/_wervt/user`.
18
+ - Hands `scheduledTasks` to the control plane, which runs them while the app sleeps.
19
+ - `nitro dev` creates the app's role and schema in the local stack, runs `drizzle/` migrations
20
+ and sets `DATABASE_URL` and `ELECTRIC_URL`.
21
+ - Writes the bundle manifest (`framework: nitro`).
22
+
23
+ Use [`@wervt/core`](https://www.npmjs.com/package/@wervt/core) in routes: `getUser(event.req)`,
24
+ `proxyShape(event.req, …)`, `sendMail()`, `useDb()` from `@wervt/core/db`. Nuxt apps use
25
+ `@wervt/nuxt` instead.
@@ -0,0 +1,51 @@
1
+ /** Node globals Deno doesn't define, which postgres.js and others use. For unenv's `inject`. */
2
+ export declare const DENO_INJECT: {
3
+ Buffer: [string, string];
4
+ setImmediate: [string, string];
5
+ clearImmediate: [string, string];
6
+ };
7
+ /** The output plugins every build for the runtime needs. */
8
+ export declare function denoPlugins(): {
9
+ name: string;
10
+ renderChunk(code: string): {
11
+ code: string;
12
+ map: null;
13
+ } | null;
14
+ }[];
15
+ /** Rewrites `from 'os'` / `import('os')` to `node:os` in the output chunks. */
16
+ export declare function prefixNodeBuiltins(): {
17
+ name: string;
18
+ renderChunk(code: string): {
19
+ code: string;
20
+ map: null;
21
+ } | null;
22
+ };
23
+ /**
24
+ * srvx (Nitro 3's server layer) pins `waitUntil` on each request as a non-configurable property.
25
+ * Edge Runtime hands the app a Proxy whose `get` returns its own `waitUntil`, which breaks the
26
+ * proxy invariant for non-configurable properties: reading `req.waitUntil` throws. Nitro's
27
+ * error handler reads it, so every thrown error (404, 400, …) became a 500. Configurable, the
28
+ * proxy may answer with its own function, which works the same.
29
+ */
30
+ export declare function configurableWaitUntil(): {
31
+ name: string;
32
+ renderChunk(code: string): {
33
+ code: string;
34
+ map: null;
35
+ } | null;
36
+ };
37
+ /**
38
+ * Deno's module graph reads JSDoc type imports (`{@link import('../internal/headers').x}`) as
39
+ * real dependencies and refuses to boot when one can't be resolved. Packages ship such paths
40
+ * relative to their own source tree (@anthropic-ai/sdk does), so once Nitro bundles them into
41
+ * `server/_libs/…` the path points nowhere and the worker fails with "Module not found".
42
+ * Dropping the `import(` from JSDoc lines keeps the comment readable and out of the graph. Only
43
+ * lines that open a JSDoc block or continue one with `*` are touched, so code never changes.
44
+ */
45
+ export declare function stripJsdocImports(): {
46
+ name: string;
47
+ renderChunk(code: string): {
48
+ code: string;
49
+ map: null;
50
+ } | null;
51
+ };
package/dist/build.js ADDED
@@ -0,0 +1,81 @@
1
+ import { builtinModules } from "node:module";
2
+ // src/build.ts
3
+ /** Node globals Deno doesn't define, which postgres.js and others use. For unenv's `inject`. */
4
+ const DENO_INJECT = {
5
+ Buffer: ["node:buffer", "Buffer"],
6
+ setImmediate: ["node:timers", "setImmediate"],
7
+ clearImmediate: ["node:timers", "clearImmediate"]
8
+ };
9
+ /** The output plugins every build for the runtime needs. */
10
+ function denoPlugins() {
11
+ return [
12
+ prefixNodeBuiltins(),
13
+ configurableWaitUntil(),
14
+ stripJsdocImports()
15
+ ];
16
+ }
17
+ const BUILTINS = new Set(builtinModules.filter((name) => !name.startsWith("_")));
18
+ /** Rewrites `from 'os'` / `import('os')` to `node:os` in the output chunks. */
19
+ function prefixNodeBuiltins() {
20
+ const IMPORT_RE = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(['"])([a-z_/]+)\2/g;
21
+ return {
22
+ name: "wervt:prefix-node-builtins",
23
+ renderChunk(code) {
24
+ let changed = false;
25
+ const out = code.replace(IMPORT_RE, (match, lead, quote, id) => {
26
+ if (!BUILTINS.has(id)) return match;
27
+ changed = true;
28
+ return `${lead}${quote}node:${id}${quote}`;
29
+ });
30
+ return changed ? {
31
+ code: out,
32
+ map: null
33
+ } : null;
34
+ }
35
+ };
36
+ }
37
+ /**
38
+ * srvx (Nitro 3's server layer) pins `waitUntil` on each request as a non-configurable property.
39
+ * Edge Runtime hands the app a Proxy whose `get` returns its own `waitUntil`, which breaks the
40
+ * proxy invariant for non-configurable properties: reading `req.waitUntil` throws. Nitro's
41
+ * error handler reads it, so every thrown error (404, 400, …) became a 500. Configurable, the
42
+ * proxy may answer with its own function, which works the same.
43
+ */
44
+ function configurableWaitUntil() {
45
+ const PIN_RE = /waitUntil:\s*\{\s*value:\s*(this\.#wait\?\.waitUntil)\s*\}/g;
46
+ return {
47
+ name: "wervt:configurable-wait-until",
48
+ renderChunk(code) {
49
+ if (!code.includes("waitUntil")) return null;
50
+ const out = code.replace(PIN_RE, "waitUntil: { value: $1, configurable: true, writable: true }");
51
+ return out === code ? null : {
52
+ code: out,
53
+ map: null
54
+ };
55
+ }
56
+ };
57
+ }
58
+ /**
59
+ * Deno's module graph reads JSDoc type imports (`{@link import('../internal/headers').x}`) as
60
+ * real dependencies and refuses to boot when one can't be resolved. Packages ship such paths
61
+ * relative to their own source tree (@anthropic-ai/sdk does), so once Nitro bundles them into
62
+ * `server/_libs/…` the path points nowhere and the worker fails with "Module not found".
63
+ * Dropping the `import(` from JSDoc lines keeps the comment readable and out of the graph. Only
64
+ * lines that open a JSDoc block or continue one with `*` are touched, so code never changes.
65
+ */
66
+ function stripJsdocImports() {
67
+ const JSDOC_LINE_RE = /^[ \t]*(?:\/\*\*|\*(?!\/)).*$/gm;
68
+ const IMPORT_RE = /\bimport\(\s*(['"])/g;
69
+ return {
70
+ name: "wervt:strip-jsdoc-imports",
71
+ renderChunk(code) {
72
+ if (!code.includes("import(")) return null;
73
+ const out = code.replace(JSDOC_LINE_RE, (line) => line.replace(IMPORT_RE, "$1"));
74
+ return out === code ? null : {
75
+ code: out,
76
+ map: null
77
+ };
78
+ }
79
+ };
80
+ }
81
+ export { DENO_INJECT, configurableWaitUntil, denoPlugins, prefixNodeBuiltins, stripJsdocImports };
@@ -0,0 +1,20 @@
1
+ import { DevOptions } from "@wervt/platform/dev";
2
+ import { NitroModule } from "nitro/types";
3
+ export interface WervtNitroOptions {
4
+ /** App name. Defaults to WERVT_APP (set by `wervt deploy`), then package.json's name. */
5
+ app?: string;
6
+ /** IANA time zone of `scheduledTasks`, UTC by default. */
7
+ timezone?: string;
8
+ /** What the dashboard shows as the app's framework, `nitro` by default. */
9
+ framework?: string;
10
+ /** The local stack `nitro dev` provisions the app's database in. */
11
+ dev?: DevOptions;
12
+ }
13
+ /** The module, configured: `modules: [wervt({ timezone: 'Europe/Berlin' })]`. */
14
+ export declare function wervt(options?: WervtNitroOptions): NitroModule & {
15
+ nitro: NitroModule;
16
+ };
17
+ declare const _default: NitroModule & {
18
+ nitro: NitroModule;
19
+ };
20
+ export { _default as default };
package/dist/index.js ADDED
@@ -0,0 +1,106 @@
1
+ import { DENO_INJECT, denoPlugins } from "./build.js";
2
+ import { glob, mkdir, writeFile } from "node:fs/promises";
3
+ import { dirname, join, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { BUNDLE_MANIFEST } from "@wervt/core";
6
+ import { SEED_TASK, resolveAppName, setupDev, unscheduleSeed } from "@wervt/platform/dev";
7
+ // src/index.ts
8
+ const ext = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
9
+ const runtime = (name) => fileURLToPath(new URL(`./runtime/${name}${ext}`, import.meta.url));
10
+ /** The module, configured: `modules: [wervt({ timezone: 'Europe/Berlin' })]`. */
11
+ function wervt(options = {}) {
12
+ const module = {
13
+ name: "wervt",
14
+ setup: (nitro) => setup(nitro, options)
15
+ };
16
+ return {
17
+ ...module,
18
+ nitro: module
19
+ };
20
+ }
21
+ var src_default = wervt();
22
+ async function setup(nitro, options) {
23
+ const { rootDir, dev } = nitro.options;
24
+ const app = await resolveAppName(rootDir, options.app);
25
+ if (!nitro.options.experimental.tasks) {
26
+ nitro.options.experimental.tasks = true;
27
+ await scanTasks(nitro);
28
+ }
29
+ nitro.options.handlers.push({
30
+ route: "/_wervt/tasks",
31
+ handler: runtime("tasks")
32
+ }, {
33
+ route: "/_wervt/tasks/**",
34
+ handler: runtime("tasks")
35
+ }, {
36
+ route: "/_wervt/boot",
37
+ handler: runtime("boot")
38
+ }, {
39
+ route: "/_wervt/user",
40
+ method: "GET",
41
+ handler: runtime("user")
42
+ });
43
+ if (dev) {
44
+ if (!process.env.NITRO_PRERENDER) await setupDevServer(nitro, app, options.dev ?? {});
45
+ return;
46
+ }
47
+ if (!/deno/i.test(String(nitro.options.preset))) throw new Error(`@wervt/nitro: wervt runs apps on Deno. Set \`preset: 'deno-server'\` in nitro.config (now: ${nitro.options.preset}).`);
48
+ nitro.options.unenv.push({ inject: DENO_INJECT });
49
+ nitro.hooks.hook("rollup:before", (_nitro, config) => {
50
+ config.plugins = [...[config.plugins ?? []].flat(), ...denoPlugins()];
51
+ });
52
+ const { schedules, removed } = unscheduleSeed(nitro.options.scheduledTasks ?? {});
53
+ if (removed.length) nitro.logger.warn(`\`${SEED_TASK}\` is not scheduled (${removed.join(", ")}): seeding only runs on request.`);
54
+ nitro.options.scheduledTasks = {};
55
+ nitro.hooks.hook("compiled", async () => {
56
+ const serverDir = nitro.options.output.serverDir;
57
+ const tasks = {
58
+ tasks: Object.entries(nitro.options.tasks ?? {}).map(([name, task]) => ({
59
+ name,
60
+ description: task.description || void 0
61
+ })),
62
+ schedules: Object.entries(schedules).map(([cron, entry]) => ({
63
+ cron,
64
+ tasks: [entry].flat()
65
+ })),
66
+ timezone: options.timezone
67
+ };
68
+ await mkdir(serverDir, { recursive: true });
69
+ await writeFile(join(serverDir, "wervt-tasks.json"), `${JSON.stringify(tasks, null, 2)}\n`);
70
+ const bundle = {
71
+ version: 2,
72
+ framework: options.framework ?? "nitro"
73
+ };
74
+ await writeFile(join(dirname(serverDir), BUNDLE_MANIFEST), `${JSON.stringify(bundle, null, 2)}\n`);
75
+ });
76
+ }
77
+ /**
78
+ * Nitro scans `tasks/` before it installs modules, and only with `experimental.tasks` set in the
79
+ * app's config. Turned on here, the scan is done here too, naming tasks like Nitro does
80
+ * (`tasks/db/seed.ts` is `db:seed`), so apps don't have to set the flag themselves.
81
+ */
82
+ async function scanTasks(nitro) {
83
+ for (const dir of nitro.options.scanDirs) {
84
+ const tasksDir = join(dir, "tasks");
85
+ for await (const file of glob("**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}", { cwd: tasksDir })) {
86
+ const name = file.split(sep).join("/").replace(/\/index$/, "").replace(/\.[A-Za-z]+$/, "").replace(/\//g, ":");
87
+ nitro.options.tasks[name] ??= {
88
+ handler: join(tasksDir, file),
89
+ description: ""
90
+ };
91
+ }
92
+ }
93
+ }
94
+ async function setupDevServer(nitro, app, options) {
95
+ await setupDev({
96
+ rootDir: nitro.options.rootDir,
97
+ onClose: (fn) => nitro.hooks.hook("close", fn),
98
+ restart: () => void nitro.hooks.callHook("restart"),
99
+ logger: {
100
+ info: (message) => nitro.logger.info(message),
101
+ success: (message) => nitro.logger.success(message),
102
+ warn: (message, ...args) => nitro.logger.warn(message, ...args)
103
+ }
104
+ }, app, options);
105
+ }
106
+ export { src_default as default, wervt };
@@ -0,0 +1,4 @@
1
+ declare function _default(event: {
2
+ req: Request;
3
+ }): Response;
4
+ export { _default as default };
@@ -0,0 +1,4 @@
1
+ import { isTaskRequest } from "@wervt/core";
2
+ // src/runtime/boot.ts
3
+ var boot_default = (event) => isTaskRequest(event.req) ? Response.json({ ok: true }, { headers: { "cache-control": "no-store" } }) : Response.json({ error: "not found" }, { status: 404 });
4
+ export { boot_default as default };
@@ -0,0 +1,3 @@
1
+ export default function handler(event: {
2
+ req: Request;
3
+ }): Promise<Response>;
@@ -0,0 +1,33 @@
1
+ import { isTaskRequest, taskRunResponse } from "@wervt/core";
2
+ import { tasks } from "#nitro/virtual/tasks";
3
+ // src/runtime/tasks.ts
4
+ async function resolveTask(name) {
5
+ return await (Object.hasOwn(tasks, name) ? tasks[name] : void 0)?.resolve?.();
6
+ }
7
+ const notFound = () => Response.json({ error: "not found" }, { status: 404 });
8
+ async function handler(event) {
9
+ const request = event.req;
10
+ if (!isTaskRequest(request)) return notFound();
11
+ const { pathname } = new URL(request.url);
12
+ if (pathname === "/_wervt/tasks") {
13
+ if (request.method !== "GET") return notFound();
14
+ const list = await Promise.all(Object.entries(tasks).map(async ([name, entry]) => {
15
+ return {
16
+ name,
17
+ description: (await entry.resolve?.().catch(() => void 0))?.meta?.description ?? entry.meta?.description
18
+ };
19
+ }));
20
+ return Response.json(list, { headers: { "cache-control": "no-store" } });
21
+ }
22
+ if (request.method !== "POST") return notFound();
23
+ const name = decodeURIComponent(pathname.slice(14));
24
+ const body = await request.json().catch(() => ({}));
25
+ const task = await resolveTask(name);
26
+ if (!task) return Response.json({ error: `no task ${name}` }, { status: 404 });
27
+ return taskRunResponse(name, async () => task.run({
28
+ name,
29
+ payload: body.payload ?? {},
30
+ context: {}
31
+ }));
32
+ }
33
+ export { handler as default };
@@ -0,0 +1,4 @@
1
+ declare function _default(event: {
2
+ req: Request;
3
+ }): Response;
4
+ export { _default as default };
@@ -0,0 +1,4 @@
1
+ import { getUser } from "@wervt/core";
2
+ // src/runtime/user.ts
3
+ var user_default = (event) => Response.json({ user: getUser(event.req) ?? null }, { headers: { "cache-control": "no-store" } });
4
+ export { user_default as default };
package/package.json CHANGED
@@ -1 +1,51 @@
1
- {"name":"@wervt/nitro","version":"0.0.0","description":"Placeholder, the first release follows from CI.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/wervt-app/wervt.git","directory":"packages/nitro"}}
1
+ {
2
+ "name": "@wervt/nitro",
3
+ "version": "0.0.2",
4
+ "description": "Nitro module for apps hosted on wervt: Deno build for the runtime, tasks, local database and the bundle manifest.",
5
+ "keywords": [
6
+ "nitro",
7
+ "nitro-module",
8
+ "wervt"
9
+ ],
10
+ "homepage": "https://wervt.app",
11
+ "license": "MIT",
12
+ "author": "Niki2k1",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/wervt-app/wervt.git",
16
+ "directory": "packages/nitro"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./build": {
29
+ "types": "./dist/build.d.ts",
30
+ "default": "./dist/build.js"
31
+ }
32
+ },
33
+ "dependencies": {
34
+ "@wervt/core": "^0.0.2",
35
+ "@wervt/platform": "^0.0.2"
36
+ },
37
+ "devDependencies": {
38
+ "nitro": "3.0.260903-beta"
39
+ },
40
+ "peerDependencies": {
41
+ "nitro": ">=3.0.260903-beta"
42
+ },
43
+ "peerDependenciesMeta": {
44
+ "nitro": {
45
+ "optional": true
46
+ }
47
+ },
48
+ "scripts": {
49
+ "build": "vp pack"
50
+ }
51
+ }