@arbol-ai/maximus 7.4.0 → 8.0.1

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.
Files changed (137) hide show
  1. package/README.md +36 -38
  2. package/bin/maximus.js +4 -0
  3. package/config/oxfmt.mjs +1 -0
  4. package/config/oxlint.mjs +10 -0
  5. package/dist/analytics/analytics.d.ts +21 -9
  6. package/dist/analytics/analytics.js +19 -5
  7. package/dist/body.d.ts +1 -1
  8. package/dist/body.js +2 -2
  9. package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
  10. package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
  11. package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
  12. package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
  13. package/dist/chunks/define-app-x7uY70_1.js +341 -0
  14. package/dist/chunks/{errors-D7zG9kx9.js → errors-C5w9WY1l.js} +10 -5
  15. package/dist/chunks/{execution-kVUJPy1A.js → execution-rOiLo8VG.js} +28 -15
  16. package/dist/chunks/generate-C-9FKW0o.js +197 -0
  17. package/dist/chunks/handler-iebR-urt.js +141 -0
  18. package/dist/chunks/http-layout-DS8DnPyu.js +128 -0
  19. package/dist/chunks/{http-paths-yKD6TSNJ.js → http-paths-DMBxwpp6.js} +50 -31
  20. package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
  21. package/dist/chunks/names-ncD7A3DV.js +280 -0
  22. package/dist/chunks/openapi-CeolxIqa.js +1588 -0
  23. package/dist/chunks/openapi-file-Bz9FRaE6.js +83 -0
  24. package/dist/chunks/pages-iZTvFs5a.js +14 -0
  25. package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
  26. package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
  27. package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
  28. package/dist/chunks/query-kind-CWKAXEME.js +40 -0
  29. package/dist/chunks/record-DQUDTpEA.js +10 -0
  30. package/dist/chunks/result-CKgZHrnj.js +56 -0
  31. package/dist/chunks/{runtime-DlqA7J38.js → runtime-D94vx21X.js} +50 -26
  32. package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
  33. package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
  34. package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
  35. package/dist/chunks/server-Bzf1Q1_4.js +410 -0
  36. package/dist/chunks/src-CPrJpbOM.js +573 -0
  37. package/dist/chunks/{standard-failures-CLjxS2ea.js → standard-failures-Lh4mSfwG.js} +1 -1
  38. package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
  39. package/dist/chunks/{types-DQdfRF3f.d.ts → types-DTIuIEJ-.d.ts} +1000 -342
  40. package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
  41. package/dist/chunks/workers-types-BRk_Xa_5.d.ts +143 -0
  42. package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
  43. package/dist/diagnostics.d.ts +6 -4
  44. package/dist/diagnostics.js +2 -2
  45. package/dist/errors.d.ts +2 -2
  46. package/dist/errors.js +2 -2
  47. package/dist/http-paths.d.ts +1 -1
  48. package/dist/http-paths.js +1 -1
  49. package/dist/index.d.ts +2 -2
  50. package/dist/index.js +12 -11
  51. package/dist/internals.d.ts +1 -1
  52. package/dist/internals.js +5 -4
  53. package/dist/mcp/index.d.ts +3 -2
  54. package/dist/mcp/index.js +5 -387
  55. package/dist/postgres/index.d.ts +25 -8
  56. package/dist/postgres/index.js +17 -8
  57. package/dist/project/config.d.ts +110 -72
  58. package/dist/project/config.js +161 -45
  59. package/dist/project/index.d.ts +17 -4
  60. package/dist/project/index.js +44 -9
  61. package/dist/projection.d.ts +14 -13
  62. package/dist/projection.js +8 -32
  63. package/dist/schemas.d.ts +1 -1
  64. package/dist/schemas.js +2 -2
  65. package/dist/standard-failures.d.ts +2 -89
  66. package/dist/standard-failures.js +1 -1
  67. package/dist/tooling/cli.js +149 -105
  68. package/dist/tooling/testing.js +2 -2
  69. package/dist/vite/cloudflare-workers.js +25 -0
  70. package/dist/vite/index.d.ts +157 -0
  71. package/dist/vite/index.js +1477 -0
  72. package/dist/webhooks.d.ts +12 -10
  73. package/dist/webhooks.js +26 -12
  74. package/dist/workers/runtime.d.ts +1 -1
  75. package/dist/workers/runtime.js +1 -1
  76. package/package.json +26 -22
  77. package/skills/maximus/SKILL.md +165 -68
  78. package/skills/maximus/references/deploying.md +73 -0
  79. package/skills/maximus/references/errors-and-results.md +114 -55
  80. package/skills/maximus/references/project.md +202 -0
  81. package/skills/maximus/references/routes-and-tools.md +256 -0
  82. package/skills/maximus/references/testing.md +137 -50
  83. package/skills/maximus/references/transports.md +113 -100
  84. package/skills/maximus/references/writing-code.md +84 -0
  85. package/templates/mcp/mcp/instructions.md.template +2 -0
  86. package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
  87. package/templates/mcp/tests/mcp.test.ts.template +36 -0
  88. package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
  89. package/templates/project/.github/workflows/ci.yml.template +4 -1
  90. package/templates/project/CLAUDE.md.template +41 -25
  91. package/templates/project/README.md.template +54 -48
  92. package/templates/project/middleware/10-response.ts.template +5 -2
  93. package/templates/project/package.json.template +13 -9
  94. package/templates/project/pages/index.ts.template +2 -4
  95. package/templates/project/routes/v1/greeting.get.ts.template +10 -0
  96. package/templates/project/routes/v1/greeting.post.ts.template +12 -0
  97. package/templates/project/tests/greeting.test.ts.template +45 -0
  98. package/templates/project/tsconfig.json.template +8 -6
  99. package/templates/project/vite.config.ts.template +15 -7
  100. package/templates/web/app/main.tsx.template +16 -0
  101. package/templates/web/app/root.tsx.template +17 -0
  102. package/templates/web/app/routes/index.tsx.template +9 -0
  103. package/templates/web/index.html.template +12 -0
  104. package/templates/web/package.json.template +12 -0
  105. package/templates/web/tsconfig.json.template +7 -0
  106. package/templates/web/vite.config.ts.template +22 -0
  107. package/dist/chunks/builder-BiXv7d2v.js +0 -100
  108. package/dist/chunks/define-app-DvD_1jUE.js +0 -625
  109. package/dist/chunks/prepare-project-CMyGSEtI.js +0 -236
  110. package/dist/chunks/prepare-project-MtS0-W_n.js +0 -3
  111. package/dist/chunks/record-DY-lX9w1.js +0 -34
  112. package/dist/chunks/src-N3oyx5QF.js +0 -1091
  113. package/dist/client/client.d.ts +0 -129
  114. package/dist/client/client.js +0 -321
  115. package/dist/tooling/vite.d.ts +0 -3
  116. package/dist/tooling/vite.js +0 -57
  117. package/skills/maximus/references/adding-an-operation.md +0 -179
  118. package/skills/maximus/references/building-a-service.md +0 -167
  119. package/skills/maximus/references/migration-from-v2.md +0 -62
  120. package/skills/maximus/references/migration-to-v5.md +0 -37
  121. package/skills/maximus/references/publishing-and-verification.md +0 -42
  122. package/templates/project/cloudflare.config.ts.template +0 -24
  123. package/templates/project/maximus.config.ts.template +0 -20
  124. package/templates/project/routes/v1/greeting.ts.template +0 -38
  125. package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
  126. package/templates/service/.github/workflows/ci.yml.template +0 -21
  127. package/templates/service/.gitignore.template +0 -9
  128. package/templates/service/CLAUDE.md.template +0 -5
  129. package/templates/service/README.md.template +0 -45
  130. package/templates/service/cloudflare.config.ts.template +0 -30
  131. package/templates/service/package.json.template +0 -36
  132. package/templates/service/src/app.ts.template +0 -30
  133. package/templates/service/src/index.ts.template +0 -13
  134. package/templates/service/tests/contract.test.ts.template +0 -12
  135. package/templates/service/tsconfig.json.template +0 -16
  136. package/templates/service/vite.config.ts.template +0 -13
  137. package/templates/service/vitest.config.ts.template +0 -10
@@ -1,21 +1,15 @@
1
1
  # Errors and results
2
2
 
3
- ## Results
3
+ ## The catalog
4
4
 
5
- ```ts
6
- import { err, ok } from '@arbol-ai/maximus';
7
-
8
- return note ? ok(note) : err(errors.noteNotFound.create());
9
- ```
10
-
11
- A handler returns exactly `{ ok: true, value }` or `{ ok: false, error }`. Anything else, a throw, an
12
- output that fails its schema or exceeds its byte limit, or a failure outside the catalog becomes
13
- `INTERNAL_ERROR`, reported to diagnostics without its message.
14
-
15
- ## Catalog
5
+ `errors.ts` declares the service's own failures. Each has a fixed code, HTTP status and message; the catalog
6
+ also holds every standard failure.
16
7
 
17
8
  ```ts
18
- export const errors = defineErrors({
9
+ // errors.ts
10
+ import { defineErrors, t } from '@arbol-ai/maximus';
11
+
12
+ export default defineErrors({
19
13
  noteNotFound: { code: 'NOTE_NOT_FOUND', status: 404, message: 'The note does not exist.' },
20
14
  quotaExceeded: {
21
15
  code: 'QUOTA_EXCEEDED',
@@ -26,52 +20,117 @@ export const errors = defineErrors({
26
20
  dataSchema: t.Object({ limit: t.Integer() }, { additionalProperties: false }),
27
21
  },
28
22
  });
23
+ ```
24
+
25
+ - A code is uppercase words joined by underscores, unique among the catalog's codes, the standard ones
26
+ included. A status is from 400 to 599. A message is fixed and never holds a value.
27
+ - `retryable` says whether the same request may succeed later; `retryAfter` sends `Retry-After` seconds.
28
+ - `dataSchema` is a strict object: the `data` a failure of that code carries. Put codes, counts, positions
29
+ and field paths in it, never a submitted value, a credential or another service's answer.
30
+ - The standard failures' names (`invalidInput`, `unauthorized`, `forbidden`, `notFound`, `methodNotAllowed`,
31
+ `tooLarge`, `unsupportedMedia`, `rateLimited`, `internal`, `upstreamUnavailable`, `upstreamTimeout`,
32
+ `outcomeUnknown`) and the catalog's members (`schema`, `definitions`, `status`, `retryAfter`, `validate`) are
33
+ reserved keys.
29
34
 
30
- errors.quotaExceeded.create({ limit: 100 }); // data required when dataSchema has required fields
31
- errors.noteNotFound.is(value);
32
- errors.status('NOTE_NOT_FOUND'); // 404
35
+ `defineErrors` throws a `TypeError` for a rule it refuses.
36
+
37
+ ## Answer a failure
38
+
39
+ A handler, `context.ts` or a tool answers an expected failure with `fail(code)`:
40
+
41
+ ```ts
42
+ const note = await notes.find(input.noteId);
43
+ if (!note) {
44
+ return fail('NOTE_NOT_FOUND');
45
+ }
33
46
  ```
34
47
 
35
- - Codes `UPPER_SNAKE_CASE`, unique including standard codes; status 400–599; messages fixed and
36
- value-free; `dataSchema` strict.
37
- - Standard names are reserved keys: `invalidInput`, `unauthorized`, `forbidden`, `notFound`,
38
- `methodNotAllowed`, `tooLarge`, `unsupportedMedia`, `rateLimited`, `internal`,
39
- `upstreamUnavailable`, `upstreamTimeout`, `outcomeUnknown`. Every catalog contains them, so use
40
- `errors.forbidden.create()` etc. `standardErrors` is the catalog with nothing added.
41
- - The catalog's members are reserved keys too: `schema`, `definitions`, `status`, `retryAfter`,
42
- `validate`.
43
- - Return only failures from this application's catalog. A dependency's failure must be translated.
44
-
45
- ## Standard codes
46
-
47
- | Code | Status | Retryable | Typical cause |
48
- | --- | --- | --- | --- |
49
- | `INVALID_INPUT` | 400 | No | Schema refusal with `data.issues` (≤ 10 `{ path, message }`, JSON Pointers); repeated query key; bad JSON |
50
- | `UNAUTHORIZED` | 401 | No | Missing/invalid token, bad RPC props or principal, invalid proof |
51
- | `FORBIDDEN` | 403 | No | Missing scope, ineligible actor, absent authority for conditional scopes, proof not admitting the call |
52
- | `NOT_FOUND` | 404 | No | No route (before authentication), unpinned origin |
53
- | `HTTP_METHOD_NOT_ALLOWED` | 405 | No | Non-GET on health or a `tokens.resources` path, non-GET/HEAD on assets |
54
- | `REQUEST_TOO_LARGE` | 413 | No | Body over its limit |
55
- | `UNSUPPORTED_MEDIA_TYPE` | 415 | No | Non-JSON body; content-encoded byte upload |
56
- | `RATE_LIMITED` | 429 | Yes (60 s) | The configured rate limit |
57
- | `INTERNAL_ERROR` | 500 | No | Unexpected error or invalid result |
58
- | `OUTCOME_UNKNOWN` | 502 | No | Returned by handlers: a write may have happened |
59
- | `UPSTREAM_UNAVAILABLE` | 503 | Yes | Returned by handlers |
60
- | `UPSTREAM_TIMEOUT` | 504 | Yes | Returned by handlers |
61
-
62
- ## Presentation
63
-
64
- HTTP: the catalog status, the envelope, `Retry-After` for `retryAfter`. MCP: a tool result with
65
- `isError: true` and the failure JSON. RPC: the `Result` itself. The typed client returns the envelope,
66
- or with `response: 'data'` throws an `Error` whose `cause` is `{ status, failure, requestId }`.
48
+ A code that declares data takes it: `return fail('QUOTA_EXCEEDED', { limit: 100 });`.
49
+
50
+ A route lists the domain codes it may answer in `failures`: `failures: ['NOTE_NOT_FOUND']`. `fail` then
51
+ type-checks only those codes and the standard ones an operation answers itself, the OpenAPI document lists
52
+ them, and any other domain
53
+ failure, from the handler, `context.ts` or middleware, answers `INTERNAL_ERROR` and is reported. Without
54
+ `failures`, every code of the catalog is allowed and listed.
55
+
56
+ Throw only for what should never happen. A throw, an output its schema refuses or over its limit, or a code
57
+ outside the catalog answers `INTERNAL_ERROR`, never the error's text, and is reported as `maximus.unexpected`
58
+ by the error's name alone.
59
+
60
+ ## Standard failures
61
+
62
+ Every catalog holds these, and an operation answers them without listing them, except five. Routing and
63
+ admission alone answer `NOT_FOUND`, `HTTP_METHOD_NOT_ALLOWED` and `UNAUTHORIZED`. Admission answers
64
+ `REQUEST_TOO_LARGE` and `UNSUPPORTED_MEDIA_TYPE` for a JSON body, and a byte route returns them as
65
+ `body.read()` gives them. `fail` takes none of the five; an operation that answers one in any other way
66
+ answers `INTERNAL_ERROR` instead.
67
+
68
+ | Code | Status | Retryable | When |
69
+ | ------------------------- | ------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
70
+ | `INVALID_INPUT` | 400 | No | The input does not match its schema; `data.issues` lists up to ten `{ path, message }`. |
71
+ | `UNAUTHORIZED` | 401 | No | No valid token; RPC props or principal refused. |
72
+ | `FORBIDDEN` | 403 | No | The token lacks the scope, the actor kind is not admitted. |
73
+ | `NOT_FOUND` | 404 | No | No route answers the method and path, before any token is read. |
74
+ | `HTTP_METHOD_NOT_ALLOWED` | 405 | No | A method the health path, discovery, a page or a web app's file does not answer, such as `POST /health`; on an API route an unserved method is `NOT_FOUND`. |
75
+ | `REQUEST_TOO_LARGE` | 413 | No | The body exceeds its limit. |
76
+ | `UNSUPPORTED_MEDIA_TYPE` | 415 | No | A body that is not JSON, or a compressed byte upload. |
77
+ | `RATE_LIMITED` | 429 | Yes, 60 s | The rate limit refused the caller. |
78
+ | `INTERNAL_ERROR` | 500 | No | Anything unexpected. |
79
+ | `OUTCOME_UNKNOWN` | 502 | No | A write may have happened and its answer was lost. |
80
+ | `UPSTREAM_UNAVAILABLE` | 503 | Yes | A service this one depends on could not answer. |
81
+ | `UPSTREAM_TIMEOUT` | 504 | Yes | A service this one depends on did not answer in time. |
82
+
83
+ A handler answers the last three itself, with `fail('UPSTREAM_UNAVAILABLE')` for instance.
84
+
85
+ ## On each transport
86
+
87
+ - HTTP: the code's status and `{ success: false, data: null, error, metadata: { requestId } }`, with
88
+ `Retry-After` when the code has one.
89
+ - MCP: a tool result with `isError: true` whose text is the failure.
90
+ - RPC: the `Result` `{ ok: false, error }`.
91
+
92
+ The failure is `{ code, message, retryable, data }` on all three.
67
93
 
68
94
  ## Uncertain outcomes and retries
69
95
 
70
- - `retryable: true` only when the same call may succeed later (rate limit, outage, timeout).
71
- - When a write may have been applied and its answer was lost, return
72
- `errors.outcomeUnknown.create()`. Callers reconcile (read the resource, poll an operation) before
73
- repeating anything. Record intent before provider writes and use idempotency keys where possible.
74
- - Never retry uncertain writes or paid provider calls blindly; never turn an outage into an empty
96
+ - `retryable: true` only when the same call may succeed later: a rate limit, an outage, a timeout.
97
+ - When a write may have been applied and its answer was lost, answer `OUTCOME_UNKNOWN`. The caller reconciles
98
+ (reads the resource, looks for the id it chose) before repeating anything. Record intent before a provider
99
+ write and give writes stable keys, such as an id the caller chooses.
100
+ - Never retry an uncertain write or a paid provider call blindly, and never turn an outage into an empty
75
101
  success.
76
- - `data` holds finite codes, counts, positions and field paths. Never submitted values, credentials
77
- or provider bodies.
102
+
103
+ ## Failures of other services
104
+
105
+ A failure another service answers belongs to that service's catalog, not to this one. Translate it before
106
+ answering: a failure the caller can fix becomes one of this catalog's codes, one that may pass becomes
107
+ `UPSTREAM_UNAVAILABLE`, and the rest `INTERNAL_ERROR`. A code outside this catalog fails its check and
108
+ answers `INTERNAL_ERROR`. Catch a call that throws, such as an RPC call to a Worker that cannot be reached:
109
+
110
+ ```ts
111
+ import type { Quote, QuoteItemsFailure } from '#maximus/services/pricing';
112
+
113
+ let priced: Result<Quote, QuoteItemsFailure>;
114
+ try {
115
+ priced = await env.PRICING.quoteItems(principal, input);
116
+ } catch {
117
+ return fail('UPSTREAM_UNAVAILABLE');
118
+ }
119
+ if (priced.ok) {
120
+ return { currency: priced.value.currency, totalCents: priced.value.totalCents };
121
+ }
122
+ const failure = priced.error;
123
+ if (failure.code === 'UNKNOWN_SKU') {
124
+ return fail('UNKNOWN_ITEM', { index: failure.data.index });
125
+ }
126
+ if (failure.retryable) {
127
+ return fail('UPSTREAM_UNAVAILABLE');
128
+ }
129
+ return fail('INTERNAL_ERROR');
130
+ ```
131
+
132
+ The owner's failure types come from the RPC document it publishes, so the code narrows `data`. Answer only
133
+ what this catalog declares: never return the owner's value or failure as it is.
134
+
135
+ See [Errors and results](https://github.com/getarbol/maximus/blob/main/docs/guides/errors-and-results.md)
136
+ and [Standard failures](https://github.com/getarbol/maximus/blob/main/docs/reference/standard-failures.md).
@@ -0,0 +1,202 @@
1
+ # The project
2
+
3
+ ## vite.config.ts
4
+
5
+ The only configuration. `maximus()` states the application and the Worker that serves it, with Cloudflare's
6
+ own names for the Worker's settings:
7
+
8
+ ```ts
9
+ import { maximus } from '@arbol-ai/maximus/vite';
10
+ import { bindings } from 'cf/config';
11
+ import { defineConfig } from 'vite-plus';
12
+
13
+ export default defineConfig({
14
+ plugins: [
15
+ maximus({
16
+ origin: 'https://notes.example.com',
17
+ tokens: { issuer: 'https://auth.example.com/' },
18
+ compatibilityDate: '2026-10-27',
19
+ env: { NOTES: bindings.kv() },
20
+ }),
21
+ ],
22
+ });
23
+ ```
24
+
25
+ | Option | Meaning, and default |
26
+ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
+ | `origin` | Required. The public HTTPS URL that OpenAPI, MCP resources and OAuth discovery advertise, and the default token audience. A `workers.dev` origin is served there; any other host becomes the Worker's custom domain unless `domains` or a fetch trigger route it. |
28
+ | `tokens` | `issuer`, the OAuth authorization server; `audience`, the origin by default; `jwksUri`, `algorithms`, `claims`, `scheme`, `authorizationEndpoint`, `tokenEndpoint`; `source` and `access` behind Cloudflare Access; `development`, the development token's binding, `DEVELOPMENT_TOKEN` by default, `false` for none. See [Tokens](#tokens). |
29
+ | `name` | The Worker's name, the MCP server's and the scopes' prefix: lowercase letters, digits and single hyphens. By default, the package's name without its scope. |
30
+ | `namespace`, `title`, `version` | The scopes' prefix (the name), the human name (the name), the version `/health` reports (the package's). |
31
+ | `description`, `groups` | The OpenAPI document's description of the service, and of each group of routes by its name: `{ Notes: "The notes of the caller's organization." }`. |
32
+ | `rpc` | `{ callers: ['example-orders'] }`: the services allowed to call RPC methods, by the `caller` their binding's props name, which is the calling service's `name`. None by default. |
33
+ | `services` | `{ PRICING: { worker: 'example-pricing', openapi: '../pricing/openapi.rpc.json' } }`: other Maximus services this one calls over RPC, each bound to its Worker's `Service` entrypoint with this service as the caller, and typed from the RPC document it publishes. See [transports.md](transports.md#worker-rpc). |
34
+ | `http` | `{ basePath, healthPath }`: `/api` and `/health` by default. |
35
+ | `maxBodyBytes`, `maxOutputBytes` | The limits of every operation that sets none: 32 KiB and 256 KiB. |
36
+ | `rateLimit` | `{ binding, retryAfter }`: a rate limiting binding every HTTP and MCP call passes, per organization and actor. |
37
+ | `env` | The Worker's bindings, from `cf/config`'s `bindings`. |
38
+ | `webApp` | `{ headers }` for a web app's pages and files. |
39
+ | Any other key | A Worker setting as Cloudflare names it: `compatibilityDate`, `compatibilityFlags`, `triggers`, `exports`, `observability`, `placement`, `limits`, `domains`, `workersDev`, `previewUrls`. |
40
+
41
+ `maximus()` owns the Worker's entry (`.maximus/entry.ts`) and a web app's assets, always adds
42
+ `nodejs_compat`, turns preview URLs off unless the options turn them on, sets Workers Logs and traces on with
43
+ query strings redacted (the options' `observability` joins these defaults key by key), adds a trigger for each
44
+ cron and queue module, and declares the development token under `vp dev` alone. It refuses a
45
+ `cloudflare.config.ts` or `maximus.config.ts` beside it, an `assets` option and a `DEVELOPMENT_TOKEN` binding in
46
+ `env`. It also brings the lint and format presets when the configuration sets no `lint` or `fmt`.
47
+ `vite.config.ts` runs in Node, so it may read `process.env`, for a database's id for instance.
48
+
49
+ ## Tokens
50
+
51
+ `tokens` states which tokens the API admits: by default, OAuth access tokens of the `issuer` it names, for
52
+ the `origin` as their audience. `auth0()` and `cloudflareAccess()` from `@arbol-ai/maximus/vite` state the
53
+ options for those providers, as plain data:
54
+
55
+ ```ts
56
+ import { auth0, cloudflareAccess, maximus } from '@arbol-ai/maximus/vite';
57
+
58
+ // Access tokens that Auth0 issues for the API whose identifier is the audience.
59
+ tokens: auth0({ domain: 'acme.us.auth0.com', audience: 'https://notes.example.com' }),
60
+
61
+ // The application token Cloudflare Access adds to each request it lets through.
62
+ tokens: cloudflareAccess({
63
+ team: 'acme',
64
+ aud: '4714c1358e65fe4b408ad6d432a5f878f08194bdb4752441fd56faefa9b2b6f2',
65
+ organizationId: 'org_acme',
66
+ scopes: {
67
+ people: ['notes:notes:read', 'notes:notes:write'],
68
+ services: { '88bf3b6d86161464f6509f7219099e57.access': ['notes:notes:read'] },
69
+ },
70
+ }),
71
+ ```
72
+
73
+ - `auth0({ domain, audience, algorithms? })`: `domain` is the tenant's host name, or a list of its domains,
74
+ the canonical one first, when it has a custom domain; `audience` is the API's identifier in Auth0. It
75
+ answers the issuer `https://<domain>/`, the audience and `algorithms`: `['RS256']` by default, `RS512` or
76
+ `PS256`. It throws for `HS256` and for a domain with a scheme, port or path. Turn on **Enable RBAC** and
77
+ **Add Permissions in the Access Token** in the API's settings: a person holds only the granted scopes their
78
+ `permissions` also list. A token without `org_id` is refused.
79
+ - `cloudflareAccess({ team, aud, organizationId?, scopes })`: `team` is the Zero Trust team name, `acme` for
80
+ `acme.cloudflareaccess.com`, and `aud` the Access application's AUD tag. Access tokens carry no scope:
81
+ `scopes.people` is what every person Access lets through holds, and `scopes.services` what each service
82
+ token holds, by its client id; one it does not list holds none. Each scope belongs to the service's own
83
+ namespace. Every caller acts in `organizationId`; for several organizations, leave it out and name the claim
84
+ that holds each caller's in `claims.organization`, beside the spread preset. The Worker then reads the
85
+ token from `cf-access-jwt-assertion` alone and verifies it against the team's keys; a production build
86
+ answers `404` to any host but `origin`; a write another site's page sends answers `403`; `authority.token`
87
+ is absent; and the Worker serves no OAuth discovery and no MCP, so `prepare` refuses a route or a file of
88
+ `mcp/` that declares MCP. Under `vp dev` and in tests, the development token still signs in as a bearer
89
+ token.
90
+ - Spread a preset to add what it leaves out: `tokens: { ...auth0({ domain, audience }), development: false }`.
91
+
92
+ Tokens that no issuer signs, such as keys the service issues itself, are verified by `auth.ts`. See
93
+ [Authentication and scopes](https://github.com/getarbol/maximus/blob/main/docs/guides/authentication-and-scopes.md).
94
+
95
+ ## Root modules
96
+
97
+ Each is optional and default-exports one declaration:
98
+
99
+ - `errors.ts`: `defineErrors({ noteNotFound: { code: 'NOTE_NOT_FOUND', status: 404, message: '…' } })`, the
100
+ codes `fail` and `failures` accept. See [errors-and-results.md](errors-and-results.md).
101
+ - `context.ts`: `defineContext(({ env, principal, fail }) => ({ … }))`, what every handler receives besides
102
+ its input. It runs once per call, after admission; it may answer `fail(code)` instead.
103
+ - `auth.ts`: `defineAuth({ resolve, resourceMetadataUrl, resources })`, for tokens the configured issuer does
104
+ not issue. `resolve(token, context)` verifies cryptographically and answers a principal
105
+ `{ actorId, actorKind, organizationId, scopes, client? }`, or a failure: `FORBIDDEN` answers 403, anything
106
+ else 401. The issuer, the audience and every other token setting stay in `vite.config.ts`; `defineAuth`
107
+ refuses them.
108
+ - `telemetry.ts`: `defineTelemetry({ enabled, observers, traceId })`, whether Maximus's diagnostics run and
109
+ the observers of every call, such as `analytics({ record })` from `@arbol-ai/maximus/analytics`. Observers
110
+ receive safe metadata alone, never input, output or credentials. See
111
+ [Observability](https://github.com/getarbol/maximus/blob/main/docs/guides/observability.md).
112
+
113
+ Root modules never import a route or a generated module.
114
+
115
+ ## Bindings and Env
116
+
117
+ Declare each binding in `env`; `.maximus/env.d.ts` types the global `Env` from them with Cloudflare's own
118
+ inference:
119
+
120
+ ```ts
121
+ env: {
122
+ NOTES: bindings.kv(),
123
+ NOTES_DB: bindings.d1({ name: 'notes', id: '<the id cf d1 create printed>' }),
124
+ DOCUMENTS: bindings.r2({ name: 'notes-documents' }),
125
+ DIGESTS: bindings.queue({ name: 'note-digests' }),
126
+ COUNTERS: bindings.durableObject({ worker: 'notes', exportName: 'NoteCounter' }),
127
+ PARTNER_API_KEY: bindings.secret(),
128
+ },
129
+ ```
130
+
131
+ A binding to one of the Worker's own Durable Object classes is typed as `DurableObjectNamespace` of that
132
+ class, and another Maximus service of `services` by the RPC document it publishes. What inference cannot
133
+ know, such as a queue's message type, a module declares:
134
+
135
+ ```ts
136
+ declare global {
137
+ interface Env {
138
+ DIGESTS: Queue<DigestMessage>;
139
+ }
140
+ }
141
+ ```
142
+
143
+ Under `vp dev` every store is local, in `.cloudflare/state/`, and a secret's value comes from `.dev.vars`.
144
+ `bindings.text()` and `bindings.json()` hold readable configuration, never a credential.
145
+
146
+ ## The development token
147
+
148
+ `maximus init` writes `.dev.vars` with `DEVELOPMENT_TOKEN=<64 hexadecimal characters>`. Under `vp dev` and
149
+ `vp test`, a request to `localhost`, `127.0.0.1` or `[::1]` whose bearer token equals `DEVELOPMENT_TOKEN`
150
+ (which needs at least 32 characters) signs in the developer `local-developer` of the organization
151
+ `local-development` (or `tokens.development`'s `organizationId`), holding every scope the service defines. No build declares it, so a deployed Worker accepts
152
+ only the issuer's access tokens.
153
+
154
+ ```sh
155
+ curl -H "authorization: Bearer $(cut -d= -f2 .dev.vars)" http://localhost:5173/api/v1/greeting
156
+ ```
157
+
158
+ ## What prepare generates
159
+
160
+ `maximus prepare` writes `.maximus/` from `vite.config.ts` and the files, and `vp dev` (when it starts and on
161
+ every change), `vp build`, `vp test` and `bun run typecheck` run it. It parses modules and never runs them.
162
+
163
+ | Module | Holds |
164
+ | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
165
+ | `config.ts` | The application's configuration from `vite.config.ts`, as data. |
166
+ | `env.d.ts` | `Env`. |
167
+ | `middleware.ts` | The modules of `middleware/`, apart by phase. |
168
+ | `base.ts` | The application builder: configuration, `errors.ts`, `auth.ts`, `context.ts`, `telemetry.ts`, MCP Markdown, operation middleware. |
169
+ | `register.d.ts` | `MaximusRegister`: types every handler's context, failures and `Env`. |
170
+ | `app.ts` | `app`: every route and tool, built. |
171
+ | `worker.ts`, `entry.ts` | The Worker: `export default` its handler, `export const Service` its RPC entrypoint, and the Durable Object classes. |
172
+ | `http.ts` | `handler`: the API as the Worker serves it, for tests in Node. |
173
+ | `mcp.ts`, `app-routes.ts` | The MCP Markdown, and a web app's pages, when the project has them. |
174
+ | `services/<binding>.ts` | The RPC methods of each service of `services`, typed from its document: `#maximus/services/pricing`. |
175
+
176
+ The starter's `package.json` maps `#maximus/*` to `.maximus/*.ts`, so tests import `handler` from
177
+ `#maximus/http` and `app` from `#maximus/app`. A refusal of `prepare` names the file and keeps the previous
178
+ output. `.maximus/` is in `.gitignore`.
179
+
180
+ ## Modes
181
+
182
+ A project is prepared for `development` under `vp dev` and `vp test`, and for `production` in every build and
183
+ preview. A module named `<name>.dev.ts` exists in development alone, `<name>.prod.ts` in production alone.
184
+
185
+ ## The Worker's other parts
186
+
187
+ | Folder | A file |
188
+ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
189
+ | `pages/` | Default-exports an `HttpRoute<Env>`, a public answer at a fixed path outside the API: `pages/index.ts` answers `GET` and `HEAD /`, and `pages/webhooks/payments.post.ts` answers `POST /webhooks/payments`. Other methods answer `405`. A page verifies any data it receives itself, as a webhook verifies its signature. Never tenant data. |
190
+ | `crons/` | Exports `const cron = '*/15 * * * *'`, a string literal that becomes the Worker's trigger, and default-exports an `ExportedHandlerScheduledHandler<Env>`. |
191
+ | `queues/` | Is named after the queue it consumes and default-exports an `ExportedHandlerQueueHandler<Env, unknown>`. The Worker subscribes to the queue unless `triggers` declares its consumer, for batches, retries and a dead letter queue. |
192
+ | `email/` | Is named after a recipient, or `_default`, and default-exports the email handler. |
193
+ | `durable-objects/` | Default-exports a class that extends `DurableObject<Env>`, exported as the PascalCase of the file's name. Declare it in `exports` (`exports.durableObject({ storage: 'sqlite' })`) and bind it with `bindings.durableObject({ worker, exportName })`. Its name is its storage's: renaming or removing it is a migration in `exports`. |
194
+
195
+ A web app is `index.html` at the root, with its pages in `app/routes/` (React Router), its layout in
196
+ `app/root.tsx` and its static files in `public/`. The same Worker serves it, and the API stays below `/api`.
197
+
198
+ Each topic has a guide: [Project structure](https://github.com/getarbol/maximus/blob/main/docs/guides/project-structure.md),
199
+ [Bindings](https://github.com/getarbol/maximus/blob/main/docs/guides/bindings.md),
200
+ [Background work](https://github.com/getarbol/maximus/blob/main/docs/guides/background-work.md),
201
+ [Durable Objects](https://github.com/getarbol/maximus/blob/main/docs/guides/durable-objects.md) and
202
+ [Web apps](https://github.com/getarbol/maximus/blob/main/docs/guides/web-apps.md).