@lunora/errors 0.0.1 → 1.0.0-alpha.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.
@@ -0,0 +1,220 @@
1
+ const ERROR_CATALOG = {
2
+ BAD_REQUEST: { status: 400, title: "Bad request" },
3
+ UNAUTHORIZED: { status: 401, title: "Unauthorized" },
4
+ FORBIDDEN: { status: 403, title: "Forbidden" },
5
+ NOT_FOUND: { status: 404, title: "Not found" },
6
+ CONFLICT: {
7
+ hint: [
8
+ "Another write changed this row while your mutation was running (optimistic concurrency conflict).",
9
+ "",
10
+ "Re-read the row and retry the mutation with the fresh value. Lunora serializes a DO's mutations, so a persistent conflict usually means the handler conflicts **with itself** (e.g. a trigger or cascade touching the same row) — split that work rather than adding a retry loop."
11
+ ],
12
+ status: 409,
13
+ title: "Conflict"
14
+ },
15
+ NOT_UNIQUE: {
16
+ hint: [
17
+ "`.unique()` matched more than one document — it expects the query to identify at most one row.",
18
+ "",
19
+ "- If several matches are legitimate, use `.first()` (take one) or `.collect()` (take all) instead.",
20
+ "- Otherwise tighten the query (e.g. filter on a unique/indexed field) so it can only match one row."
21
+ ],
22
+ status: 400,
23
+ title: "Query matched more than one document"
24
+ },
25
+ VALIDATION_ERROR: { status: 400, title: "Validation failed" },
26
+ TOO_MANY_REQUESTS: { status: 429, title: "Too many requests" },
27
+ UNPROCESSABLE: { status: 422, title: "Unprocessable" },
28
+ NOT_IMPLEMENTED: { status: 501, title: "Not implemented" },
29
+ /** RPC/REST dispatch codes emitted by the runtime + Durable Object router. */
30
+ FUNCTION_NOT_FOUND: { status: 404, title: "Function not found" },
31
+ METHOD_NOT_ALLOWED: { status: 405, title: "Method not allowed" },
32
+ PAYLOAD_TOO_LARGE: { status: 413, title: "Payload too large" },
33
+ /** Free-form internal failure — redacted to a generic message on the wire. */
34
+ INTERNAL: { internal: true, status: 500, title: "Internal error" },
35
+ /** Alias of {@link ERROR_CATALOG.INTERNAL} kept for `@lunora/server`'s historical code name. */
36
+ INTERNAL_SERVER_ERROR: { internal: true, status: 500, title: "Internal error" },
37
+ /** Non-mappable throw crossed the RPC boundary. */
38
+ RPC_FAILED: { internal: true, status: 500, title: "Internal error" },
39
+ COUNT_RLS_UNSUPPORTED: { status: 422, title: "count() is unsupported under an RLS policy" },
40
+ MASK_UNSUPPORTED: { status: 422, title: "Aggregation over a masked column is unsupported" },
41
+ RELATION_PREDICATE_UNSUPPORTED: { status: 422, title: "Relation predicate is unsupported in a write policy" },
42
+ RLS_REQUIRED: {
43
+ hint: [
44
+ "This table is secure-by-default: it has no `.public()` marker and no RLS policy resolved for the caller, so the read fails closed.",
45
+ "",
46
+ "Add a read policy with `.rls(...)`, or mark the table `.public()` if it is intentionally world-readable."
47
+ ],
48
+ status: 403,
49
+ title: "RLS policy required"
50
+ },
51
+ SHARD_ERROR: { status: 503, title: "Shard error" },
52
+ SHARD_UNAVAILABLE: { status: 503, title: "Shard unavailable" },
53
+ OFFLINE_IDENTITY_CHANGED: { status: 409, title: "Offline identity changed" },
54
+ /** Package-specific codes. Build-time-only — never cross the RPC wire, so deliberately not `internal`. */
55
+ CODEGEN_DIAGNOSTIC: { status: 500, title: "Codegen diagnostic" },
56
+ /** Build-time-only — never crosses the RPC wire, so deliberately not `internal`. */
57
+ SCHEMA_SNAPSHOT_PARSE: { status: 500, title: "Schema snapshot parse error" },
58
+ /** Runtime-reachable (env.ts): message enumerates failing env key names — redact on the wire. */
59
+ ENV_INVALID: { internal: true, status: 500, title: "Invalid environment" },
60
+ /** Runtime-reachable (auth/middleware.ts): message carries auth-wiring guidance — redact on the wire. */
61
+ AUTH_HEADERS_MISSING: { internal: true, status: 500, title: "Auth headers missing" },
62
+ /**
63
+ * Upstream Cloudflare API failures surfaced from an action. The message
64
+ * carries the upstream response body (Cloudflare's own error text — trusted
65
+ * infra, not user input), so it is echoed rather than redacted. `status`
66
+ * here is a fallback; each throw passes the actual upstream HTTP status.
67
+ */
68
+ ANALYTICS_SQL_ERROR: { status: 502, title: "Analytics Engine SQL API error" },
69
+ R2_SQL_ERROR: { status: 502, title: "R2 SQL API error" },
70
+ WORKFLOWS_REST_ERROR: { status: 502, title: "Cloudflare Workflows REST API error" }
71
+ };
72
+ const isInternalCode = (code) => ERROR_CATALOG[code]?.internal === true;
73
+ const MESSAGE_SOLUTIONS = [
74
+ {
75
+ body: [
76
+ "Lunora codegen couldn't find a schema to generate from.",
77
+ "",
78
+ "Create `lunora/schema.ts` exporting a `defineSchema(...)` call:",
79
+ "",
80
+ "```ts",
81
+ 'import { defineSchema, defineTable, v } from "@lunora/server";',
82
+ "",
83
+ "export default defineSchema({",
84
+ " messages: defineTable({ body: v.string() }),",
85
+ "});",
86
+ "```",
87
+ "",
88
+ "Or run `lunora init` to scaffold Lunora (a sample `lunora/schema.ts` included) into your app."
89
+ ].join("\n"),
90
+ header: "No Lunora schema found",
91
+ id: "lunora-schema-missing",
92
+ test: (message) => message.includes("defineSchema() not found") || message.includes("schema.ts not found at")
93
+ },
94
+ {
95
+ body: [
96
+ "`defineSchema(...)` must be called with an **inline object literal** mapping table names to `defineTable(...)`:",
97
+ "",
98
+ "```ts",
99
+ "export default defineSchema({",
100
+ " todos: defineTable({ title: v.string(), done: v.boolean() }),",
101
+ "});",
102
+ "```",
103
+ "",
104
+ "Codegen reads the schema statically, so it can't follow a variable or a spread — pass the object literal directly."
105
+ ].join("\n"),
106
+ header: "`defineSchema()` needs an inline object literal",
107
+ id: "lunora-schema-not-object-literal",
108
+ test: (message) => message.includes("defineSchema() expects an object literal")
109
+ },
110
+ {
111
+ body: [
112
+ "This table name collides with a built-in `ctx.db` member, so the generated client can't expose it.",
113
+ "",
114
+ "Rename the table to anything that isn't a reserved name (the error lists them) — e.g. `userAccounts` instead of `insert`."
115
+ ].join("\n"),
116
+ header: "Table name is reserved",
117
+ id: "lunora-table-reserved",
118
+ test: (message) => message.includes("is reserved") && message.includes("ctx.db")
119
+ },
120
+ {
121
+ body: [
122
+ "Two tables resolve to the same name — usually a base table and a schema **extension** both defining it.",
123
+ "",
124
+ "Rename one of them, or drop the duplicate from the extension. Each table name must be unique across `defineSchema(...)` and every `.extend(...)`."
125
+ ].join("\n"),
126
+ header: "Duplicate table name",
127
+ id: "lunora-table-duplicate",
128
+ // Anchor on `.extend(` — the only Lunora throw for this is
129
+ // `defineSchema(...).extend(...): table "x" already exists …`. Matching a
130
+ // bare "already exists"/"extension" pair would false-positive on
131
+ // unrelated forwarded errors (e.g. a "file already exists" + "extension").
132
+ test: (message) => message.includes("already exists") && message.includes(".extend(")
133
+ },
134
+ {
135
+ body: [
136
+ '`.jurisdiction(...)` accepts only a **string literal** of `"eu"`, `"us"`, or `"fedramp"`:',
137
+ "",
138
+ "```ts",
139
+ 'defineSchema({ /* … */ }).jurisdiction("eu");',
140
+ "```"
141
+ ].join("\n"),
142
+ header: "Invalid `.jurisdiction(...)` value",
143
+ id: "lunora-jurisdiction",
144
+ test: (message) => message.includes("unknown jurisdiction") || message.includes("jurisdiction") && message.includes('"eu", "us", or "fedramp"')
145
+ },
146
+ {
147
+ body: [
148
+ "The `unique` flag on an index must be a **literal** `true` or `false`, not a computed value — codegen needs to read it statically:",
149
+ "",
150
+ "```ts",
151
+ 'defineTable({ email: v.string() }).index("by_email", ["email"], { unique: true });',
152
+ "```"
153
+ ].join("\n"),
154
+ header: "`unique` must be a literal",
155
+ id: "lunora-unique-literal",
156
+ test: (message) => message.includes("must be a literal") && message.includes("unique")
157
+ },
158
+ {
159
+ body: [
160
+ "A declared container/workflow class isn't re-exported by your worker entry, so `wrangler deploy` would reject it.",
161
+ "",
162
+ "Add the generated re-export shown in the error to your worker entry (e.g. `src/index.ts`):",
163
+ "",
164
+ "```ts",
165
+ 'export * from "./lunora/_generated/containers";',
166
+ "```"
167
+ ].join("\n"),
168
+ header: "Binding not exported by your worker entry",
169
+ id: "lunora-worker-entry-export-gap",
170
+ test: (message) => message.includes("not exported by your worker entry")
171
+ },
172
+ {
173
+ // Deliberately NOT ERROR_CATALOG.NOT_UNIQUE.hint: that code (and hint)
174
+ // describes the read-side `.unique()` multi-match, while this matcher
175
+ // fires on the WRITE-path message ("unique constraint violation on
176
+ // <table>") thrown as a CONFLICT by an insert/patch breaching a
177
+ // `unique` index — a different error class needing insert remediation.
178
+ body: [
179
+ "A row with the same value already exists in a `unique` index.",
180
+ "",
181
+ "- If you meant to upsert, use `ctx.db.<table>().upsert(...)` (or `.patch(...)` an existing row) instead of `.insert(...)`.",
182
+ `- Otherwise pick a value that isn't already taken, and consider surfacing a friendly "already exists" message to the user.`
183
+ ].join("\n"),
184
+ header: "Unique constraint violation",
185
+ id: "lunora-runtime-unique",
186
+ test: (message) => message.includes("unique constraint violation on")
187
+ },
188
+ {
189
+ body: ERROR_CATALOG.CONFLICT.hint.join("\n"),
190
+ header: "Optimistic concurrency conflict",
191
+ id: "lunora-runtime-occ",
192
+ test: (message) => message.includes("optimistic concurrency conflict")
193
+ }
194
+ ];
195
+ const flattenHint = (hint) => (Array.isArray(hint) ? hint.join("\n") : hint).split("\n").filter((line) => !line.startsWith("```")).join("\n").replaceAll(/\*\*(.+?)\*\*/gu, "$1").replaceAll(/`([^`]+)`/gu, "$1");
196
+ const findSolutionByMessage = (message) => {
197
+ for (const rule of MESSAGE_SOLUTIONS) {
198
+ if (rule.test(message)) {
199
+ return { body: rule.body, header: rule.header, id: rule.id };
200
+ }
201
+ }
202
+ return void 0;
203
+ };
204
+ const resolveHint = (input) => {
205
+ if (typeof input === "string") {
206
+ return findSolutionByMessage(input)?.body;
207
+ }
208
+ if (input.hint !== void 0) {
209
+ return input.hint;
210
+ }
211
+ if (input.code !== void 0) {
212
+ const entry = ERROR_CATALOG[input.code];
213
+ if (entry?.hint !== void 0) {
214
+ return entry.hint;
215
+ }
216
+ }
217
+ return input.message === void 0 ? void 0 : findSolutionByMessage(input.message)?.body;
218
+ };
219
+
220
+ export { ERROR_CATALOG, MESSAGE_SOLUTIONS, findSolutionByMessage, flattenHint, isInternalCode, resolveHint };
@@ -0,0 +1,38 @@
1
+ import { ERROR_CATALOG } from './ERROR_CATALOG-DAg3Unhb.mjs';
2
+
3
+ class LunoraError extends Error {
4
+ /**
5
+ * Discriminator recognised by `@visulima/error`'s `renderError`/`isVisulimaError`
6
+ * (`error.type === "VisulimaError"`), so a `LunoraError` renders like a native
7
+ * `VisulimaError` — hint and all.
8
+ */
9
+ type = "VisulimaError";
10
+ /** Actionable fix (Markdown), rendered by the CLI/overlay/Studio. */
11
+ hint;
12
+ /** Short, human-readable summary (separate from `message`). */
13
+ title;
14
+ /** Source location, when known (mirrors `VisulimaError.loc`). */
15
+ loc;
16
+ /** Machine-readable reason, keyed into {@link ERROR_CATALOG}. */
17
+ code;
18
+ /** HTTP/RPC status for the transport mappers. */
19
+ status;
20
+ /** Optional link to deeper docs. */
21
+ docsUrl;
22
+ /** Optional structured payload propagated verbatim to the client. */
23
+ data;
24
+ constructor(code, message, options = {}) {
25
+ const entry = ERROR_CATALOG[code];
26
+ super(message ?? code, { cause: options.cause });
27
+ this.name = options.name ?? "LunoraError";
28
+ this.hint = options.hint ?? entry?.hint;
29
+ this.title = options.title ?? entry?.title;
30
+ this.loc = options.location;
31
+ this.code = code;
32
+ this.status = options.status ?? entry?.status ?? 500;
33
+ this.docsUrl = options.docsUrl ?? entry?.docsUrl;
34
+ this.data = options.data;
35
+ }
36
+ }
37
+
38
+ export { LunoraError };
@@ -0,0 +1,12 @@
1
+ import { LunoraError } from './LunoraError-Dg03M4uC.mjs';
2
+
3
+ const invariant = (condition, message) => {
4
+ if (!condition) {
5
+ throw new LunoraError("INTERNAL", message, { name: "InvariantError" });
6
+ }
7
+ };
8
+ const unreachable = (message) => {
9
+ throw new LunoraError("INTERNAL", message, { name: "InvariantError" });
10
+ };
11
+
12
+ export { invariant, unreachable };
@@ -0,0 +1,9 @@
1
+ const isLunoraError = (error) => {
2
+ if (!(error instanceof Error)) {
3
+ return false;
4
+ }
5
+ const candidate = error;
6
+ return typeof candidate.code === "string" && typeof candidate.status === "number";
7
+ };
8
+
9
+ export { isLunoraError };
@@ -0,0 +1,26 @@
1
+ import { isInternalCode, resolveHint } from './ERROR_CATALOG-DAg3Unhb.mjs';
2
+ import { isLunoraError } from './isLunoraError-BvsoKcWE.mjs';
3
+
4
+ const toErrorBody = (error, options = {}) => {
5
+ const redactedMessage = options.redactedMessage ?? "Internal error";
6
+ if (isLunoraError(error)) {
7
+ if (isInternalCode(error.code)) {
8
+ return { body: { code: error.code, message: redactedMessage }, redacted: true, status: error.status };
9
+ }
10
+ const body = { code: error.code, message: error.message };
11
+ if (error.data !== void 0 && options.encodeData !== void 0) {
12
+ body.data = options.encodeData(error.data);
13
+ }
14
+ const hint = resolveHint({ code: error.code, hint: error.hint, message: error.message });
15
+ if (hint !== void 0) {
16
+ body.hint = hint;
17
+ }
18
+ if (error.docsUrl !== void 0) {
19
+ body.docsUrl = error.docsUrl;
20
+ }
21
+ return { body, redacted: false, status: error.status };
22
+ }
23
+ return { body: { code: options.fallbackCode ?? "INTERNAL", message: redactedMessage }, redacted: true, status: 500 };
24
+ };
25
+
26
+ export { toErrorBody };
package/package.json CHANGED
@@ -1,10 +1,50 @@
1
1
  {
2
2
  "name": "@lunora/errors",
3
- "version": "0.0.1",
4
- "description": "OIDC trusted publishing setup package for @lunora/errors",
3
+ "version": "1.0.0-alpha.2",
4
+ "description": "Unified error layer for Lunora: one LunoraError base + a central catalog of codes, statuses, and actionable hints, rendered across CLI, overlay, Studio, and the client",
5
5
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
6
+ "cloudflare",
7
+ "durable-objects",
8
+ "error",
9
+ "error-handling",
10
+ "hints",
11
+ "lunora",
12
+ "workers"
13
+ ],
14
+ "homepage": "https://lunora.sh",
15
+ "bugs": "https://github.com/anolilab/lunora/issues",
16
+ "license": "FSL-1.1-Apache-2.0",
17
+ "author": {
18
+ "name": "Daniel Bannert",
19
+ "email": "d.bannert@anolilab.de"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/anolilab/lunora.git",
24
+ "directory": "packages/errors"
25
+ },
26
+ "files": [
27
+ "./dist",
28
+ "README.md",
29
+ "LICENSE.md",
30
+ "__assets__"
31
+ ],
32
+ "type": "module",
33
+ "sideEffects": false,
34
+ "main": "./dist/index.mjs",
35
+ "module": "./dist/index.mjs",
36
+ "types": "./dist/index.d.ts",
37
+ "exports": {
38
+ ".": {
39
+ "types": "./dist/index.d.ts",
40
+ "import": "./dist/index.mjs"
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "engines": {
48
+ "node": "^22.15.0 || >=24.11.0"
49
+ }
50
+ }