Deno

From j4flmao/agent-skills · View interactive version

Deno is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about Deno 2, deno.json, deno task, Deno.serve, Deno KV, JSR imports, deno compile or permission flags. Produces Deno projects with least-privilege permissions, tests and deployment. Not for the Oak framework specifically (use oak-backend).

How to use this skill

Skill file

Deno

Purpose

Build TypeScript services on Deno 2 with least-privilege permissions, JSR-first dependencies, built-in tooling (fmt, lint, test, check, compile) and a choice of bare Deno.serve, Hono, Oak or Fresh.

Agent Protocol

Trigger

Exact user phrases: "deno", "deno 2", "deno.json", "deno task", "deno compile", "deno test", "Deno.serve", "Deno KV", "JSR", "deno permissions", "Fresh framework".

Input Context

Output Artifact

deno.json, server code, tests and run/deploy commands with explicit permissions. No files unless requested.

Response Format

Deno: 2.x   Framework: {bare|Hono|Oak|Fresh}
Permissions: --allow-net={hosts} --allow-env={vars} --allow-read={paths}
Deps: {jsr:/npm: specifiers in deno.json imports}
Files: {deno.json, src/main.ts, tests}
Run: deno task {dev|start|test}

Decisions

Framework

| Need | Choice |

|---|---|

| Small API, no deps | Deno.serve + URLPattern |

| Typed REST API with middleware ecosystem, multi-runtime | Hono (jsr:@hono/hono) |

| Koa-style middleware, existing Oak codebase | Oak (jsr:@oak/oak) |

| Server-rendered pages with interactive islands | Fresh 2 (jsr:@fresh/core, built on Vite) |

Dependencies

Permissions

Grant the narrowest scope: --allow-net=api.example.com:443,0.0.0.0:8000, --allow-env=DATABASE_URL,PORT, --allow-read=./static. Avoid -A outside local scripts. Deno 2 also offers --deny-* flags to carve exceptions out of broader grants.

Workflow

Step 1: deno.json

{
  "tasks": {
    "dev": "deno run --watch --allow-net --allow-env=PORT,DATABASE_URL src/main.ts",
    "start": "deno run --allow-net --allow-env=PORT,DATABASE_URL src/main.ts",
    "test": "deno test --allow-net --allow-env",
    "check": "deno check src/main.ts && deno lint && deno fmt --check",
    "compile": "deno compile --allow-net --allow-env=PORT,DATABASE_URL --output dist/api src/main.ts"
  },
  "imports": {
    "@hono/hono": "jsr:@hono/hono@^4",
    "@std/assert": "jsr:@std/assert@^1",
    "zod": "npm:zod@^3"
  },
  "compilerOptions": { "strict": true },
  "fmt": { "lineWidth": 100, "singleQuote": true }
}

Step 2: Hono API on Deno.serve

// src/app.ts
import { Hono } from '@hono/hono';
import { cors } from '@hono/hono/cors';
import { logger } from '@hono/hono/logger';
import { HTTPException } from '@hono/hono/http-exception';
import { z } from 'zod';

const kv = await Deno.openKv(Deno.env.get('KV_PATH')); // undefined -> default local store

const UserInput = z.object({ name: z.string().min(2), email: z.string().email() });
type User = z.infer<typeof UserInput> & { id: string };

export const app = new Hono();
app.use('*', logger());
app.use('/api/*', cors({ origin: Deno.env.get('CORS_ORIGIN') ?? 'http://localhost:5173' }));

app.get('/health', (c) => c.json({ status: 'ok' }));

app.get('/api/v1/users', async (c) => {
  const users: User[] = [];
  for await (const entry of kv.list<User>({ prefix: ['users'] }, { limit: 100 })) {
    users.push(entry.value);
  }
  return c.json({ data: users });
});

app.post('/api/v1/users', async (c) => {
  const parsed = UserInput.safeParse(await c.req.json());
  if (!parsed.success) return c.json({ error: parsed.error.flatten() }, 400);
  const user: User = { id: crypto.randomUUID(), ...parsed.data };
  // atomic check prevents overwriting an existing key
  const res = await kv.atomic()
    .check({ key: ['users', user.id], versionstamp: null })
    .set(['users', user.id], user)
    .commit();
  if (!res.ok) throw new HTTPException(409, { message: 'user exists' });
  return c.json({ data: user }, 201);
});

app.get('/api/v1/users/:id', async (c) => {
  const { value } = await kv.get<User>(['users', c.req.param('id')]);
  return value ? c.json({ data: value }) : c.json({ error: 'not found' }, 404);
});

app.onError((err, c) => {
  if (err instanceof HTTPException) return err.getResponse();
  console.error('unhandled error', err);
  return c.json({ error: 'internal error' }, 500);
});
// src/main.ts
import { app } from './app.ts';

Deno.serve({ port: Number(Deno.env.get('PORT') ?? 8000) }, app.fetch);

For validation middleware, @hono/zod-validator (npm:@hono/zod-validator) provides zValidator('json', schema).

Step 3: Bare Deno.serve (no framework)

const userRoute = new URLPattern({ pathname: '/api/v1/users/:id' });

Deno.serve({ port: 8000 }, (req) => {
  const match = userRoute.exec(req.url);
  if (match && req.method === 'GET') {
    return Response.json({ id: match.pathname.groups.id });
  }
  return new Response('not found', { status: 404 });
});

Deno.serve returns an HttpServer with shutdown() and a finished promise for graceful shutdown.

Step 4: Tests

// tests/app_test.ts  (run: deno test --allow-env --unstable-kv if your Deno version requires it)
import { assertEquals } from '@std/assert';
import { app } from '../src/app.ts';

Deno.test('GET /health returns ok', async () => {
  const res = await app.request('/health');   // no network listener needed
  assertEquals(res.status, 200);
  assertEquals(await res.json(), { status: 'ok' });
});

Deno.test('POST /users rejects invalid input', async () => {
  const res = await app.request('/api/v1/users', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ name: '' }),
  });
  assertEquals(res.status, 400);
});

Set KV_PATH=:memory: for tests to use an isolated in-memory KV. Deno KV is still marked unstable in the CLI, so local runs need --unstable-kv (or "unstable": ["kv"] in deno.json).

Step 5: Fresh 2 (SSR + islands)

deno run -Ar jsr:@fresh/init my-app
cd my-app && deno task dev

Fresh 2 renders Preact on the server and hydrates only components in islands/. Routes live in routes/; API handlers can share the same app. Use it when you need server-rendered pages; for pure APIs Hono or bare Deno.serve are simpler.

Step 6: Deployment

FROM denoland/deno:2.5.0
WORKDIR /app
COPY deno.json deno.lock ./
COPY src/ src/
RUN deno install --entrypoint src/main.ts   # cache deps at build time
USER deno
EXPOSE 8000
CMD ["deno", "run", "--allow-net", "--allow-env=PORT,DATABASE_URL", "--cached-only", "src/main.ts"]

Pin the image tag to the Deno version you test with. Alternatives: deno compile for a single binary (permissions are baked in at compile time), or Deno Deploy, where permissions are managed by the platform and Deno KV is available as a hosted database.

Production Considerations

Security Considerations

Anti-Patterns

| Anti-pattern | Fix |

|---|---|

| https://deno.land/std@0.x imports in new code | jsr:@std/* via deno.json imports |

| deno cache --lock-write (Deno 1) | Deno 2 writes deno.lock automatically; use --frozen in CI |

| -A in production | Scoped --allow-* flags |

| Starting a real listener in unit tests | app.request() (Hono) or call the handler function directly |

| Raw kv.set for create-if-absent | kv.atomic().check({ versionstamp: null }) |

Rules

References

Note: some reference files predate Deno 2 and use deno.land/std URLs; translate them to jsr:@std/*.

Handoff

Oak applications: skills/backend/deno/oak/SKILL.md. API response formats: skills/backend/universal/api-response/SKILL.md.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.