---
title: defineLuna
description: Every option of defineLuna for a keyed or a stateless luna type, its hooks and crons, and the luna type it returns.
related:
  - /lunas/define-a-luna
  - /concepts/the-life-of-a-luna
  - /lunas/write-stateless-lunas
---

`defineLuna` turns a spec into a luna type, which you export from your lunas module so that it deploys.

```ts luna/lunas/list.ts
import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  visibility: "public",
  key: { id: t.string() },
  schema: {
    items: table({ id: t.id(), text: t.string() }),
  },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      ctx.db.items.insert({ text });
    }),
    all: h({ query: true }, (ctx) => ctx.db.items.find({ orderBy: "id" })),
  }),
});
```

## Reference

### defineLuna(spec)

```ts
import { defineLuna } from "luna";
```

Takes a `LunaSpec`, or a `StatelessSpec` for a stateless type, and returns a `Luna`. It throws at once for a bad name, a bad key field or an option a stateless type cannot have.

### LunaSpec

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The luna type's name, used in every URL and call. |
| `handlers` | `(h: HandlerFactory) => Record<string, Handler>` | - | Returns the handlers, each made with h(spec, run). See Handler spec. |
| `key?` | `Record<string, Ty>` | `{}` | The key fields that pick one luna. With none, the type has exactly one luna. |
| `visibility?` | `"private" \| "public"` | `"private"` | Public types can be called with a publishable key. Private ones need a secret token. |
| `schema?` | `Record<string, TableDef>` | `{}` | Each luna's tables, made with table(). |
| `hooks?` | `object` | - | Functions that run at points in a luna's life and on connections. See Hooks. |
| `crons?` | `Record<string, CronSpec>` | `{}` | Handlers that run on a schedule in every luna of the type that has stored data. See CronSpec. |
| `idleTimeout?` | `number \| string` | `"30s"` | How long a luna stays awake without calls, in milliseconds or as a duration such as "5m". |
| `limits?` | `{ memory?: string; cpu?: number; reserve?: boolean }` | - | The most memory and CPU one luna may use. See Limits. |
| `internet?` | `boolean` | `true` | Set false to refuse outbound requests from handlers and from this type's sandboxes. |
| `on?` | `(listen) => ListenDef[]` | - | The events and table changes this type listens to. See defineEvent. |
| `pushes?` | `Record<string, Ty>` | - | The typed messages a luna sends its connected apps, with conn.push and ctx.broadcast. |
| `streams?` | `Record<string, StreamDef>` | - | Append-only logs made with stream(), used as ctx.streams.<name>. |
| `blobs?` | `Record<string, BucketDef>` | - | Buckets of files made with bucket(), used as ctx.blobs.<name>. |
| `sandboxes?` | `Record<string, SandboxDef>` | - | Linux machines made with sandbox(), used as ctx.sandboxes.<name>. |
| `isolates?` | `Record<string, IsolateDef>` | - | Templates for running JavaScript you did not write, made with isolate(), used as ctx.isolates.<name>. |
| `stateless?` | `false` | `false` | Leave it out for a keyed type. A stateless type sets true and takes StatelessSpec instead. |

### Hooks

Each hook gets the same `ctx` as a handler.

| Prop | Type | Default | Description |
| - | - | - | - |
| `onMigrate?` | `(ctx, change: { from: number; to: number }) => void \| Promise<void>` | - | Runs once as a luna with stored data moves to a new version, before anything else, in one transaction with the schema change. |
| `onCreate?` | `(ctx) => void \| Promise<void>` | - | Runs when a luna with no stored data wakes, before onWake. |
| `onWake?` | `(ctx) => void \| Promise<void>` | - | Runs each time a luna wakes. |
| `onSleep?` | `(ctx) => void \| Promise<void>` | - | Runs before a luna goes to sleep. |
| `onDestroy?` | `(ctx) => void \| Promise<void>` | - | Runs when the luna is destroyed. |
| `onBeforeConnect?` | `(ctx, request: ConnectRequest) => unknown` | - | Runs before every call from outside. What it returns becomes ctx.caller.external, and ctx.fail(code) refuses the call. |
| `onConnect?` | `(ctx, conn: Connection) => void \| Promise<void>` | - | Runs when an app opens a connection, after onBeforeConnect. Throwing refuses the connection. |
| `onDisconnect?` | `(ctx, conn: Connection) => void \| Promise<void>` | - | Runs at least once when an app's connection closes, never when the luna closed it. |
| `onMessage?` | `(ctx, conn: Connection, data: unknown) => void \| Promise<void>` | - | Runs for each raw message an app sends over its connection. |
| `onSshConnect?` | `(ctx, request: SshConnectRequest) => boolean \| { user?: string } \| void \| Promise<…>` | - | Decides whether an SSH connection to one of the luna's sandboxes may open. Return true, or { user } to pick the account its programs run as, root by default. |

### ConnectRequest

What `onBeforeConnect` sees of a request from outside.

| Prop | Type | Default | Description |
| - | - | - | - |
| `method` | `string` | - | The HTTP method. |
| `path` | `string` | - | The request's path. |
| `headers` | `Record<string, string>` | - | The request's headers, with lower-case names. |
| `query` | `Record<string, string>` | - | The query parameters. |
| `handler` | `string` | - | The handler the request calls. |
| `apiToken` | `boolean` | - | True when the request carried a secret API token. |

### SshConnectRequest

What `onSshConnect` sees of an SSH connection.

| Prop | Type | Default | Description |
| - | - | - | - |
| `sandbox` | `string` | - | The sandbox, by the name the luna type gives it. |
| `instance` | `string \| null` | - | Which instance of the sandbox, or null for the first. |
| `publicKey` | `string` | - | The key the connection proved it holds, as ssh-ed25519 AAAA…. |
| `fingerprint` | `string` | - | The key's fingerprint, as ssh-keygen -l prints it. |
| `address` | `string` | - | Where the connection comes from. |

### CronSpec

| Prop | Type | Default | Description |
| - | - | - | - |
| `schedule` | `string` | - | Five cron fields, such as "0 3 * * *", or an interval such as "every 10m". |
| `handler` | `string` | - | The handler to run, one of this type's. |
| `args?` | `Record<string, unknown>` | `{}` | The arguments the handler gets. |
| `tz?` | `string` | `"UTC"` | The time zone the cron fields are read in. |
| `onMissed?` | `"once" \| "skip" \| "all"` | `"once"` | Runs it missed: once runs one, skip runs one only if it is under a minute late, all runs each. |
| `overlap?` | `"skip" \| "queue" \| "allow"` | `"skip"` | When a run is due while the last still runs: skip it, run it after, or run both at once. |

### Limits

| Prop | Type | Default | Description |
| - | - | - | - |
| `memory?` | `string` | - | The most memory one luna may use, such as "512MB" or "16GB". At least "64MB". |
| `cpu?` | `number` | - | The most cores one luna may use, from 0.05 to 1024. |
| `reserve?` | `boolean` | `false` | Holds all of memory and cpu from when the luna opens until it closes. Needs both. |

### StatelessSpec

A stateless type has no key, no tables and no transaction. Its handlers run many at once.

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The luna type's name. |
| `stateless` | `true` | - | Makes the type stateless. |
| `handlers` | `(h: HandlerFactory<StatelessCtx>) => Record<string, Handler>` | - | The handlers. Each gets a StatelessCtx. |
| `visibility?` | `"private" \| "public"` | `"private"` | As for a keyed type. |
| `internet?` | `boolean` | `true` | Set false to refuse outbound requests. |
| `limits?` | `{ memory?: string; cpu?: number }` | - | As for a keyed type, without reserve. |
| `isolates?` | `Record<string, IsolateDef>` | - | Isolate templates, used as ctx.isolates.<name>. |

### Luna

What `defineLuna` returns.

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The luna type's name. |
| `kind` | `"luna"` | - | Marks the value as a luna type. |
| `spec` | `LunaSpec` | - | The spec it was made from, without handlers. |
| `handlers` | `Record<string, Handler>` | - | The handlers, by name. |
| `changes` | `Record<string, TableChanges>` | - | Each table's changes, to listen to or index, such as List.changes.items. |
| `package?` | `string` | - | The package the type came from, when definePackage marked it. |
| `extras` | `Luna[]` | - | Luna types made for this one, deployed with it. |
| `manifest()` | `() => Record<string, unknown>` | - | The type as Luna reads it on deploy. |

## Good to know

- A luna type's name starts with a capital letter and holds letters, digits and `_`, up to 64 characters.
- A key field is a required `t.string()`, `t.int()`, `t.uuid()`, `t.bytes()` or `t.enum()`. A handler argument cannot share a key field's name.
- `onSleep` and `onDestroy` may run for 10 seconds, and `onMigrate` for 60 seconds. A hook that runs longer fails.
- If `onMigrate` throws, nothing it did is kept and the luna stays on its old version until a newer one is deployed.
- `onBeforeConnect` runs for calls from outside Luna only. Calls between lunas skip it. Without `onSshConnect`, every SSH connection is refused.
- `internet: false` on any luna type turns off outbound requests from handlers of every luna type deployed with it, because their handlers share one runtime. See [Reach the internet](/files-and-code/reach-the-internet). A deploy that sets it on some types and not others asks you to confirm first.
- With `reserve: true`, a luna that opens waits for a machine with that much free, and fails with [`NoRoom`](/errors/no-room) if none has it.
- A stateless type given any other option, such as `key` or `schema`, throws when it is defined. Its handlers cannot use `query`, `shared`, `exclusive`, `durable` or `requires`.

## Examples

### Set up a new luna

`onCreate` runs before the first call to a luna with no stored data. Its writes create the luna.

```ts luna/lunas/board.ts
import { defineLuna, t, table } from "luna";

export const Board = defineLuna({
  name: "Board",
  key: { id: t.string() },
  schema: {
    settings: table({ title: t.string(), created: t.timestamp() }, { singleRow: true }),
    cards: table({ id: t.id(), text: t.string(), archived: t.bool().default(false) }),
  },
  hooks: {
    onCreate(ctx) {
      ctx.db.settings.set({ title: `Board ${ctx.key.id}`, created: ctx.now() });
    },
  },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => ctx.db.cards.insert({ text })),
  }),
});
```

### Fix data on a new version

`change.from` is the version the luna ran before.

```ts luna/lunas/board.ts
hooks: {
  onMigrate(ctx, { from }) {
    if (from < 3) ctx.exec("UPDATE cards SET text = trim(text)");
  },
},
```

### Run a handler every night

```ts luna/lunas/board.ts
handlers: (h) => ({
  tidy: h({}, (ctx) => {
    ctx.db.cards.delete({ where: { archived: true } });
  }),
}),
crons: {
  nightly: { schedule: "0 3 * * *", handler: "tidy", tz: "Europe/Paris" },
},
```

### Give each luna more room

```ts luna/lunas/report.ts
import { defineLuna, t, table } from "luna";

export const Report = defineLuna({
  name: "Report",
  key: { id: t.string() },
  limits: { memory: "4GB", cpu: 2 },
  idleTimeout: "5m",
  schema: { rows: table({ id: t.id(), value: t.float() }) },
  handlers: (h) => ({
    total: h({ query: true }, (ctx) => ctx.db.rows.find().reduce((sum, r) => sum + r.value, 0)),
  }),
});
```

### Define a stateless type

```ts luna/lunas/stats.ts
import { defineLuna, t } from "luna";
import { List } from "./list.ts";

export const Stats = defineLuna({
  name: "Stats",
  stateless: true,
  visibility: "public",
  handlers: (h) => ({
    count: h({ args: { lists: t.array(t.string()) } }, async (ctx, { lists }) => {
      const all = await Promise.all(lists.map((id) => ctx.call(List, { id }).all({})));
      return all.reduce((n, items) => n + items.length, 0);
    }),
  }),
});
```
