@arbol-ai/maximus 8.8.0 → 8.9.0

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 (45) hide show
  1. package/config/oxfmt.mjs +2 -0
  2. package/config/oxlint.mjs +3 -0
  3. package/dist/analytics/analytics.d.ts +1 -1
  4. package/dist/body.d.ts +1 -1
  5. package/dist/capture/index.d.ts +1 -1
  6. package/dist/chunks/{define-app-Bd6sRVHj.js → define-app-IhSbBWTD.js} +1 -1
  7. package/dist/chunks/{http-layout-DqE7LBsS.js → http-layout-B-9NbM5M.js} +1 -1
  8. package/dist/chunks/{meter-dTMGs_lr.js → meter-BpzCC7J3.js} +1 -1
  9. package/dist/chunks/{openapi-BX_eqRLX.js → openapi-Ye_Ypx-d.js} +1 -1
  10. package/dist/chunks/{openapi-file-BV-f_Wij.js → openapi-file-2fUP4JLw.js} +2 -2
  11. package/dist/chunks/{pages-DVORVVEZ.js → pages-BJKV04-G.js} +1 -1
  12. package/dist/chunks/{prepare-configured-Cithjf80.js → prepare-configured-DjCFAqdH.js} +6 -2
  13. package/dist/chunks/{prepare-configured-BmRJLg6J.js → prepare-configured-Dw3-u-b3.js} +1 -1
  14. package/dist/chunks/{runtime-CWORw_TD.js → runtime-Bg729nOQ.js} +3 -3
  15. package/dist/chunks/{server-DCwV3d2Y.js → server-ZGiWOeAp.js} +1 -1
  16. package/dist/chunks/{src-Bcl6xrV7.js → src-8mwPVI5H.js} +10 -6
  17. package/dist/chunks/{tokens-D0OMoQWV.js → tokens-CBQO5lc0.js} +35 -1
  18. package/dist/chunks/{types-t_09KY-x.d.ts → types-Dmw37bhl.d.ts} +27 -0
  19. package/dist/chunks/{workers-types-DyQBrA49.d.ts → workers-types-CYOvun0Q.d.ts} +1 -1
  20. package/dist/client.d.ts +1 -1
  21. package/dist/diagnostics.d.ts +1 -1
  22. package/dist/errors.d.ts +1 -1
  23. package/dist/http-paths.d.ts +1 -1
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +3 -3
  26. package/dist/internals.d.ts +1 -1
  27. package/dist/internals.js +2 -2
  28. package/dist/mcp/index.d.ts +1 -1
  29. package/dist/mcp/index.js +1 -1
  30. package/dist/mcp/tasks.d.ts +1 -1
  31. package/dist/project/config.d.ts +1 -1
  32. package/dist/project/index.d.ts +2 -2
  33. package/dist/project/index.js +2 -2
  34. package/dist/schemas.d.ts +1 -1
  35. package/dist/standard-failures.d.ts +1 -1
  36. package/dist/tooling/cli.js +3 -4
  37. package/dist/vite/index.d.ts +85 -7
  38. package/dist/vite/index.js +279 -34
  39. package/dist/webhooks.d.ts +1 -1
  40. package/dist/workers/runtime.d.ts +1 -1
  41. package/dist/workers/runtime.js +1 -1
  42. package/package.json +1 -1
  43. package/skills/maximus/SKILL.md +4 -0
  44. package/skills/maximus/references/deploying.md +9 -0
  45. package/skills/maximus/references/project.md +46 -3
@@ -1,12 +1,19 @@
1
- import { Mn as RoleDefinitions, dr as TokenAlgorithm, hr as TokenPolicy, pr as TokenDevelopment } from "../chunks/types-t_09KY-x.js";
2
- import { WorkerConfig } from "cf/config";
1
+ import { Mn as RoleDefinitions, dr as TokenAlgorithm, hr as TokenPolicy, pr as TokenDevelopment } from "../chunks/types-Dmw37bhl.js";
2
+ import { WorkerConfig, bindings } from "cf/config";
3
3
  import { Plugin } from "vite";
4
4
  /** Where the Worker runs: `development` under `vp dev`, `production` in every build. */
5
5
  type Phase = 'development' | 'production';
6
6
  /** How tokens are verified, as configuration states it; the code that verifies them itself is `auth.ts`. */
7
- type TokenOptions = Omit<TokenPolicy, 'resolve' | 'challenge' | 'resources' | 'resourceMetadataUrl' | 'audience' | 'development'> & {
7
+ type TokenOptions = Omit<TokenPolicy, 'resolve' | 'challenge' | 'resources' | 'resourceMetadataUrl' | 'audience' | 'development' | 'clients'> & {
8
8
  /** The audience tokens must carry, or several any one of which they may carry; by default, the origin. */
9
9
  audience?: TokenPolicy['audience'];
10
+ /**
11
+ * The OAuth clients whose access tokens the application admits: a list every environment admits, or each
12
+ * environment's own by its name, `{ production: 'notes-web', preview: 'notes-preview' }`, so a preview's
13
+ * tokens never open production. Under `vp dev`, a record without `development` gives production's; a build
14
+ * of an environment the record does not name is refused.
15
+ */
16
+ clients?: readonly string[] | Readonly<Record<string, string | readonly string[]>>;
10
17
  /**
11
18
  * The token `vp dev` accepts from localhost: its binding, `DEVELOPMENT_TOKEN` by default, which only
12
19
  * `vp dev` declares. `false` accepts none.
@@ -30,6 +37,14 @@ interface WebAppOptions {
30
37
  * runs inline scripts over plain HTTP.
31
38
  */
32
39
  headers?: Readonly<Record<string, string | false>>;
40
+ /**
41
+ * The pages of an app whose own router declares them, such as TanStack Router's, in place of `app/routes/`:
42
+ * each path the Worker answers with `index.html`, fixed (`/patients`) or with parameter segments
43
+ * (`/patients/:patientId`, or `$patientId` as TanStack Router writes it). Every other path that is no
44
+ * operation, page or file of the build answers `NOT_FOUND`. Without it or `app/routes/`, the app's one page
45
+ * is `/`.
46
+ */
47
+ pages?: readonly string[];
33
48
  }
34
49
  /**
35
50
  * What `vite.config.ts` states: the application's configuration, and the Worker's settings as Cloudflare
@@ -108,9 +123,39 @@ interface MaximusOptions extends Omit<WorkerConfig, 'name' | 'entrypoint' | 'env
108
123
  };
109
124
  /** The Worker's bindings, from `cf/config`'s `bindings`; the generated `Env` is inferred from them. */
110
125
  env?: WorkerConfig['env'];
111
- /** What a web app answers with besides its build: its response headers. */
126
+ /** What a web app answers with besides its build: its response headers, and the pages its own router declares. */
112
127
  webApp?: WebAppOptions;
128
+ /**
129
+ * The account's Secrets Store, by its id: the store `storeSecret()` bindings read their secrets from.
130
+ */
131
+ secretsStore?: string;
132
+ /**
133
+ * What each environment changes over these options, by its name, which is the Vite mode that builds it:
134
+ * `vp build --mode preview` builds `preview`. An environment states only what differs: `env` and `tokens`
135
+ * key by key, any other option whole. `production` and `development` (`vp dev`) only override.
136
+ *
137
+ * Any other environment is apart from production. It is served at addresses of its own: never the shared
138
+ * `domains`, but its own `origin` when it states one, and otherwise the Worker's preview URLs (`preview`) or
139
+ * its `workers.dev` subdomain. `preview` is the Worker's previews (`cf previews deploy`); every other one is
140
+ * a Worker of its own, named `<name>-<environment>`. It runs the `triggers` it states and no other: no shared
141
+ * route, cron schedule or queue consumer. And it shares no store with production by accident: a shared R2
142
+ * bucket becomes `<bucket>-<environment>`, and a shared D1, KV or Hyperdrive bound by its id, or a shared
143
+ * queue, is refused until the environment declares its own.
144
+ */
145
+ environments?: Readonly<Record<string, EnvironmentOptions>>;
113
146
  }
147
+ /** What an environment states over the shared options: any of them but the service's name and namespace. */
148
+ type EnvironmentOptions = Partial<Omit<MaximusOptions, 'name' | 'namespace' | 'environments'>>;
149
+ /**
150
+ * A secret of the account's Secrets Store that names no store of its own: read from `secretsStore`, under
151
+ * its binding's name unless it names another. `storeSecret()` writes such a binding.
152
+ */
153
+ export declare function storeSecret(secretName?: string): ReturnType<typeof bindings.secretsStoreSecret>;
154
+ /**
155
+ * What `auth0()` and `cloudflareAccess()` state: token options without clients by environment, so the same
156
+ * value also configures a Worker composed by hand, whose policy lists its clients.
157
+ */
158
+ type PresetTokens = Omit<TokenOptions, 'clients'>;
114
159
  /** The algorithms Auth0 signs an API's access tokens with that a JWKS publishes the keys of. */
115
160
  type Auth0Algorithm = Extract<TokenAlgorithm, 'RS256' | 'RS512' | 'PS256'>;
116
161
  /** What `auth0()` takes: the tenant's domain, the API's audience and its signing algorithms. */
@@ -125,6 +170,27 @@ interface Auth0Options {
125
170
  /** The algorithms the API signs its access tokens with, as its settings name them; `['RS256']` by default. */
126
171
  algorithms?: readonly Auth0Algorithm[];
127
172
  }
173
+ /** What `arbolIdentity()` takes: the API's audience, the clients it admits and what their people may do. */
174
+ interface ArbolIdentityOptions {
175
+ /**
176
+ * The API's audience, which Identity's access tokens for it carry, such as `https://notes.example.com`, or
177
+ * several; by default, the service's origin.
178
+ */
179
+ audience?: string | readonly string[];
180
+ /** Identity's origin, which its tokens name as `iss`; `https://id.getarbol.com` by default. */
181
+ issuer?: string;
182
+ /**
183
+ * The clients whose tokens the service admits, registered at Identity: a list every environment admits, or
184
+ * each environment's own, `{ production: '…', preview: '…' }`. Any client by default.
185
+ */
186
+ clients?: TokenOptions['clients'];
187
+ /**
188
+ * What a person signed in through one of `clients` may do: `all`, every public operation of the service,
189
+ * for one whose members Identity admits without granting its scopes; `token`, the default, what the token's
190
+ * scopes and permissions grant.
191
+ */
192
+ people?: TokenOptions['people'];
193
+ }
128
194
  /** What `cloudflareAccess()` takes: the team, the Access application and what its callers hold. */
129
195
  interface CloudflareAccessOptions {
130
196
  /** The Zero Trust team name: `acme` for `acme.cloudflareaccess.com`. */
@@ -153,7 +219,19 @@ interface CloudflareAccessOptions {
153
219
  * such as one with a scheme or a path, and for an algorithm other than RS256, RS512 and PS256: HS256 tokens
154
220
  * are signed with a secret, which no JWKS publishes.
155
221
  */
156
- export declare function auth0({ domain, audience, algorithms }: Auth0Options): TokenOptions;
222
+ export declare function auth0({ domain, audience, algorithms }: Auth0Options): PresetTokens;
223
+ /**
224
+ * The token options of a service whose access tokens Arbol's Identity issues, as its OpenID metadata publishes
225
+ * it: the issuer, its JWKS (`/api/auth/jwks`), its authorization and token endpoints (`/api/auth/oauth2/…`),
226
+ * access tokens that say so (`typ: at+jwt`), and machines whose subject is their client id. With `clients`, it
227
+ * admits only the tokens of those clients, each environment's own when they are named by environment; with
228
+ * `people: 'all'`, their people may call every public operation:
229
+ *
230
+ * tokens: arbolIdentity({ clients: { production: '…', preview: '…' }, people: 'all' })
231
+ *
232
+ * Throws a TypeError for an issuer that is not an HTTPS origin.
233
+ */
234
+ export declare function arbolIdentity({ audience, issuer, clients, people }?: ArbolIdentityOptions): TokenOptions;
157
235
  /**
158
236
  * The token options of an application behind Cloudflare Access: the application token Access sets in
159
237
  * `Cf-Access-Jwt-Assertion`, read from there alone and verified against the team's keys (RS256, issued by
@@ -162,11 +240,11 @@ export declare function auth0({ domain, audience, algorithms }: Auth0Options): T
162
240
  * for a team that is not a team name, such as the team's domain, and an AUD tag that is not 64 lowercase
163
241
  * hexadecimal characters.
164
242
  */
165
- export declare function cloudflareAccess({ team, aud, managedOAuth, organizationId, scopes }: CloudflareAccessOptions): TokenOptions;
243
+ export declare function cloudflareAccess({ team, aud, managedOAuth, organizationId, scopes }: CloudflareAccessOptions): PresetTokens;
166
244
  /**
167
245
  * Maximus in Vite+: prepares the project from its files before every build and source change, brings the
168
246
  * Maximus lint and format presets, and builds, runs and deploys the Worker these options describe through
169
247
  * Cloudflare's Vite plugin.
170
248
  */
171
249
  export declare function maximus(options: MaximusOptions): Plugin[];
172
- export type { Auth0Algorithm, Auth0Options, CloudflareAccessOptions, MaximusOptions, Phase, ServiceOptions, TokenOptions, WebAppOptions };
250
+ export type { ArbolIdentityOptions, Auth0Algorithm, Auth0Options, CloudflareAccessOptions, EnvironmentOptions, MaximusOptions, Phase, ServiceOptions, TokenOptions, WebAppOptions };
@@ -1,9 +1,9 @@
1
1
  import { a as operationPathParameters } from "../chunks/http-paths-D043DkJv.js";
2
- import { a as ownsPrefix, t as VERSIONED_PATH } from "../chunks/http-layout-DqE7LBsS.js";
2
+ import { a as ownsPrefix, t as VERSIONED_PATH } from "../chunks/http-layout-B-9NbM5M.js";
3
3
  import { t as routeName } from "../chunks/names-ncD7A3DV.js";
4
- import { t as checkPagePaths } from "../chunks/pages-DVORVVEZ.js";
4
+ import { t as checkPagePaths } from "../chunks/pages-BJKV04-G.js";
5
5
  import { a as projectPath, i as projectFiles, o as publicFiles, r as compareNames, s as routeShape, t as PROJECT_DIRECTORIES } from "../chunks/project-files-C0OX7MQQ.js";
6
- import { t as checkMcpResourceNames } from "../chunks/define-app-Bd6sRVHj.js";
6
+ import { t as checkMcpResourceNames } from "../chunks/define-app-IhSbBWTD.js";
7
7
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { dirname, join, posix, relative, resolve, sep } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
@@ -11,6 +11,120 @@ import { cloudflare } from "@cloudflare/vite-plugin";
11
11
  import { bindings, triggers } from "cf/config";
12
12
  import { parseSync } from "vite";
13
13
 
14
+ // src/vite/environments.ts
15
+ /** An environment's name: lowercase letters, digits and single hyphens, 2 to 24 characters. */
16
+ const ENVIRONMENT_NAME = /^(?=.{2,24}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
17
+ /** What an environment never states: they are the service's own, the same wherever it runs. */
18
+ const SHARED_ALONE = [
19
+ "name",
20
+ "namespace",
21
+ "environments"
22
+ ];
23
+ /** The stores a binding names by the id of one existing store: sharing one shares its data. */
24
+ const STORES_BY_ID = /* @__PURE__ */ new Set([
25
+ "d1",
26
+ "kv",
27
+ "hyperdrive"
28
+ ]);
29
+ /** Why an environment apart may not inherit a shared binding, or undefined when it may. */
30
+ function productionOwns(binding) {
31
+ const kind = bindingKind(binding);
32
+ if (kind !== void 0 && STORES_BY_ID.has(kind) && "id" in binding) return `the shared ${kind} store, which holds production's data`;
33
+ if (kind === "queue") return "the shared queue, whose messages production's Worker consumes";
34
+ }
35
+ /**
36
+ * The environment a command builds: `development` under `vp dev`, whatever its mode, and otherwise the Vite
37
+ * mode, which is `production` unless the build names another (`vp build --mode preview`).
38
+ */
39
+ function environmentName(phase, mode) {
40
+ return phase === "development" ? "development" : mode || "production";
41
+ }
42
+ /** A binding as `cf/config` states it: a plain object whose `type` names its kind. */
43
+ function bindingKind(binding) {
44
+ if (typeof binding !== "object" || binding === null || !("type" in binding)) return;
45
+ return typeof binding.type === "string" ? binding.type : void 0;
46
+ }
47
+ /**
48
+ * The bindings of an environment apart: its own, and of the shared ones it leaves alone, an R2 bucket under
49
+ * the environment's name (`notes-documents-preview`) and every other binding as it is. A shared store named
50
+ * by its id (D1, KV, Hyperdrive) and a shared queue are refused: the environment declares its own, so nothing
51
+ * it runs reads or writes production's data, or sends production's Worker a message, unless the configuration
52
+ * says so.
53
+ */
54
+ function bindingsApart(shared, own, environment) {
55
+ const kept = Object.entries(shared ?? {}).filter(([key]) => !Object.hasOwn(own ?? {}, key)).map(([key, binding]) => {
56
+ const owned = productionOwns(binding);
57
+ if (owned !== void 0) throw new TypeError(`environments.${environment}: ${key} is ${owned}. Declare the environment's own ${key} in environments.${environment}.env.`);
58
+ if (bindingKind(binding) === "r2" && "name" in binding && typeof binding.name === "string") return [key, {
59
+ ...binding,
60
+ name: `${binding.name}-${environment}`
61
+ }];
62
+ return [key, binding];
63
+ });
64
+ return {
65
+ ...Object.fromEntries(kept),
66
+ ...own
67
+ };
68
+ }
69
+ /**
70
+ * The options a build of `name` follows. An environment the configuration does not declare builds the shared
71
+ * options as they are. A declared one states its own over them: `env` and `tokens` key by key, every other
72
+ * option whole. An environment apart from production also leaves the shared `domains`, `workersDev`,
73
+ * `previewUrls` and `triggers` behind, and takes its stores as `bindingsApart` says.
74
+ *
75
+ * Throws a TypeError for an environment name that is not lowercase words, and for an environment that states
76
+ * the service's `name`, its `namespace` or environments of its own.
77
+ */
78
+ function resolveEnvironment(options, name) {
79
+ const { environments, ...shared } = options;
80
+ for (const declared of Object.keys(environments ?? {})) if (!ENVIRONMENT_NAME.test(declared)) throw new TypeError(`environments.${declared}: name an environment in lowercase letters, digits and single hyphens, such as preview or staging.`);
81
+ const own = environments && Object.hasOwn(environments, name) ? environments[name] : void 0;
82
+ if (own === void 0) return {
83
+ name,
84
+ options: shared,
85
+ apart: false,
86
+ ownOrigin: false
87
+ };
88
+ if (typeof own !== "object" || own === null) throw new TypeError(`environments.${name} states what the environment changes: an object of options.`);
89
+ for (const fixed of SHARED_ALONE) if (fixed in own) throw new TypeError(`environments.${name}.${fixed}: the service keeps its name and its namespace in every environment.`);
90
+ const apart = name !== "production" && name !== "development";
91
+ const { domains: _domains, workersDev: _workersDev, previewUrls: _previewUrls, triggers: _triggers, ...settings } = shared;
92
+ const base = apart ? settings : shared;
93
+ const env = apart ? bindingsApart(shared.env, own.env, name) : {
94
+ ...shared.env,
95
+ ...own.env
96
+ };
97
+ const tokens = shared.tokens || own.tokens ? {
98
+ ...shared.tokens,
99
+ ...own.tokens
100
+ } : void 0;
101
+ return {
102
+ name,
103
+ options: {
104
+ ...base,
105
+ ...own,
106
+ env,
107
+ ...tokens ? { tokens } : {}
108
+ },
109
+ apart,
110
+ ownOrigin: apart && own.origin !== void 0
111
+ };
112
+ }
113
+ /**
114
+ * The clients an environment admits, from `tokens.clients`: the list as it is, or from a record by
115
+ * environment, that environment's client or clients. Under `vp dev`, a record without `development` gives
116
+ * production's. Throws a TypeError for a record that names none for the environment.
117
+ */
118
+ function environmentClients(clients, environment) {
119
+ if (clients === void 0 || Array.isArray(clients)) return clients;
120
+ if (typeof clients !== "object" || clients === null) throw new TypeError("tokens.clients lists client ids, or names each environment’s: { production, preview }.");
121
+ const byEnvironment = clients;
122
+ const named = [environment, ...environment === "development" ? ["production"] : []].find((key) => Object.hasOwn(byEnvironment, key));
123
+ if (named === void 0) throw new TypeError(`tokens.clients names no client for the environment ${environment}: add ${environment} to it, or list the clients every environment admits.`);
124
+ const chosen = byEnvironment[named];
125
+ return typeof chosen === "string" ? [chosen] : chosen;
126
+ }
127
+
14
128
  // src/vite/options.ts
15
129
  /**
16
130
  * What `vite.config.ts` states and what follows from it: the application the generated modules carry and
@@ -44,7 +158,7 @@ const SERVICE_NAME = /^(?=.{2,63}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
44
158
  /** The application's options and the Worker's settings, apart. `assets` is maximus()'s own. */
45
159
  function split(options) {
46
160
  if ("assets" in options) throw new TypeError("maximus() configures the assets: index.html at the root makes the project a web app.");
47
- const { name, namespace, title, description, groups, roles, version, origin, tokens, rpc, http, maxBodyBytes, maxOutputBytes, rateLimit, meter, env, services, webApp, ...worker } = options;
161
+ const { name, namespace, title, description, groups, roles, version, origin, tokens, rpc, http, maxBodyBytes, maxOutputBytes, rateLimit, meter, env, services, webApp, secretsStore: _secretsStore, environments: _environments, ...worker } = options;
48
162
  return {
49
163
  application: {
50
164
  name,
@@ -71,6 +185,17 @@ function split(options) {
71
185
  }
72
186
  /** The binding a web app's build is served through. */
73
187
  const ASSETS = "ASSETS";
188
+ /** The environment that is the Worker's previews: it keeps the Worker's name and answers at preview URLs. */
189
+ const PREVIEWS = "preview";
190
+ /** How the Worker serves a web app's build: its binding, its headers and the pages its own router declares. */
191
+ function webAppAssets(options, phase) {
192
+ const pages = options.webApp?.pages;
193
+ return {
194
+ binding: ASSETS,
195
+ headers: webAppHeaders(options, phase),
196
+ ...pages === void 0 ? {} : { pages: [...pages] }
197
+ };
198
+ }
74
199
  /** Whether the project is a web app: `index.html` at its root, which Vite builds for the browser. */
75
200
  function servesWebApp(root) {
76
201
  return existsSync(join(root, "index.html"));
@@ -125,12 +250,33 @@ function serviceBindings(root, options) {
125
250
  }));
126
251
  }
127
252
  /**
253
+ * A secret of the account's Secrets Store that names no store of its own: read from `secretsStore`, under
254
+ * its binding's name unless it names another. `storeSecret()` writes such a binding.
255
+ */
256
+ function storeSecret(secretName) {
257
+ return bindings.secretsStoreSecret({
258
+ storeId: "",
259
+ secretName: secretName ?? ""
260
+ });
261
+ }
262
+ /** A `storeSecret()` binding with the store and the name it left out; any other binding as it is. */
263
+ function storeSecretBinding(key, binding, secretsStore) {
264
+ if (typeof binding !== "object" || binding === null || !("type" in binding) || binding.type !== "secrets-store-secret" || !("storeId" in binding) || binding.storeId !== "") return binding;
265
+ if (typeof secretsStore !== "string" || !secretsStore) throw new TypeError(`${key}: storeSecret() reads the Secrets Store maximus({ secretsStore }) names by its id.`);
266
+ const named = "secretName" in binding && typeof binding.secretName === "string" ? binding.secretName : "";
267
+ return {
268
+ ...binding,
269
+ storeId: secretsStore,
270
+ secretName: named || key
271
+ };
272
+ }
273
+ /**
128
274
  * The Worker's bindings in a phase: the declared ones and each service's, a web app's assets and, under
129
275
  * `vp dev` alone, the development token. A declared binding cannot take the name of either of those.
130
276
  */
131
277
  function workerEnv(root, options, phase) {
132
278
  const declared = {
133
- ...Object.fromEntries(Object.entries(options.env ?? {}).filter(([, binding]) => binding)),
279
+ ...Object.fromEntries(Object.entries(options.env ?? {}).filter(([, binding]) => binding).map(([key, binding]) => [key, storeSecretBinding(key, binding, options.secretsStore)])),
134
280
  ...serviceBindings(root, options)
135
281
  };
136
282
  const development = developmentToken(options);
@@ -196,10 +342,17 @@ function webAppHeaders(options, phase) {
196
342
  * token's policy under `vp dev` alone, the Worker's HTTP paths, pinned to the origin in production behind
197
343
  * Cloudflare Access, and a web app's binding and headers.
198
344
  */
199
- function projectOptions(root, options, phase = "production") {
345
+ function projectOptions(root, stated, phase = "production", environment = phase) {
346
+ const { options } = resolveEnvironment(stated, environment);
200
347
  const { application } = split(options);
348
+ if (options.webApp?.pages !== void 0 && !servesWebApp(root)) throw new TypeError("webApp.pages lists the pages of a web app: add its index.html at the project root.");
201
349
  const { name, version } = identity(root, options);
202
- const { audience = application.origin, development: _declared, ...tokens } = application.tokens ?? {};
350
+ const { audience = application.origin, development: _declared, clients: declaredClients, ...admission } = application.tokens ?? {};
351
+ const clients = environmentClients(declaredClients, environment);
352
+ const tokens = {
353
+ ...admission,
354
+ ...clients === void 0 ? {} : { clients }
355
+ };
203
356
  const development = developmentToken(options);
204
357
  const pinned = phase === "production" && tokens.source === "cloudflare-access";
205
358
  return {
@@ -229,10 +382,7 @@ function projectOptions(root, options, phase = "production") {
229
382
  healthPath: application.http?.healthPath ?? "/health",
230
383
  ...pinned ? { origins: [new URL(application.origin).origin] } : {}
231
384
  },
232
- ...servesWebApp(root) ? { assets: {
233
- binding: ASSETS,
234
- headers: webAppHeaders(options, phase)
235
- } } : {}
385
+ ...servesWebApp(root) ? { assets: webAppAssets(options, phase) } : {}
236
386
  },
237
387
  ...options.services ? { services: options.services } : {},
238
388
  env: {
@@ -243,9 +393,18 @@ function projectOptions(root, options, phase = "production") {
243
393
  }
244
394
  /**
245
395
  * Where a deployment serves the Worker unless the options route it themselves: at its `workers.dev`
246
- * subdomain when the origin is one, and otherwise at the origin's host, as its custom domain alone.
396
+ * subdomain when the origin is one, and otherwise at the origin's host, as its custom domain alone. An
397
+ * environment apart from production without an origin of its own is never served at the shared one: the
398
+ * Worker's previews answer at their preview URLs, and a Worker of its own at its `workers.dev` subdomain.
247
399
  */
248
- function hosting(options, worker) {
400
+ function hosting(options, worker, environment) {
401
+ if (environment.apart && !environment.ownOrigin) {
402
+ const previews = environment.name === PREVIEWS;
403
+ return {
404
+ workersDev: !previews,
405
+ previewUrls: previews
406
+ };
407
+ }
249
408
  const { hostname } = new URL(options.origin);
250
409
  const onWorkersDev = hostname.endsWith(".workers.dev");
251
410
  const routed = worker.domains !== void 0 || worker.triggers?.some(({ type }) => type === "fetch");
@@ -255,28 +414,43 @@ function hosting(options, worker) {
255
414
  };
256
415
  }
257
416
  /**
417
+ * The Worker an environment deploys to: the service's own, whose previews are the `preview` environment, and
418
+ * for any other environment apart from production a Worker of its own, `<name>-<environment>`, so deploying it
419
+ * never replaces production's.
420
+ */
421
+ function workerName(root, options, environment) {
422
+ const { name } = identity(root, options);
423
+ if (!environment.apart || environment.name === PREVIEWS) return name;
424
+ const own = `${name}-${environment.name}`;
425
+ if (!SERVICE_NAME.test(own)) throw new TypeError(`environments.${environment.name}: its Worker would be ${own}, longer than the 63 characters a Worker's name takes.`);
426
+ return own;
427
+ }
428
+ /**
258
429
  * The Worker Cloudflare's plugin builds: the options' settings, the generated entry, `nodejs_compat`, which
259
430
  * Maximus needs for its diagnostics, the bindings of the phase, where it is served, its observability, a cron
260
431
  * trigger for each schedule the cron modules state, a consumer trigger for each queue module the options do not
261
432
  * subscribe themselves and, for a web app, its build as assets every request reaches through the Worker,
262
- * which decides what they answer.
433
+ * which decides what they answer. A build of an environment follows that environment's options, and one apart
434
+ * from production takes its own name, addresses and triggers.
263
435
  */
264
- function workerConfig(root, phase, options, { crons, queues }) {
436
+ function workerConfig(root, phase, stated, { crons, queues }, environmentName = phase) {
437
+ const environment = resolveEnvironment(stated, environmentName);
438
+ const { options } = environment;
265
439
  const { worker } = split(options);
266
440
  const subscribed = new Set((worker.triggers ?? []).flatMap((trigger) => trigger.type === "queue" ? [trigger.name] : []));
267
- const consumers = queues.filter((queue) => !subscribed.has(queue)).map((queue) => triggers.queue({ name: queue }));
441
+ const consumers = environment.apart ? [] : queues.filter((queue) => !subscribed.has(queue)).map((queue) => triggers.queue({ name: queue }));
268
442
  const declared = new Set((worker.triggers ?? []).flatMap((trigger) => trigger.type === "scheduled" ? [trigger.schedule] : []));
269
443
  const schedules = crons.map(({ file, cron }) => {
270
444
  if (cron === void 0) throw new TypeError(`${file}: export the schedule as a string literal, export const cron = '0 8 * * *'.`);
271
445
  return cron;
272
446
  });
273
- const scheduled = [...new Set(schedules)].filter((schedule) => !declared.has(schedule)).map((schedule) => triggers.scheduled({ schedule }));
447
+ const scheduled = environment.apart ? [] : [...new Set(schedules)].filter((schedule) => !declared.has(schedule)).map((schedule) => triggers.scheduled({ schedule }));
274
448
  return {
275
- ...hosting(options, worker),
276
449
  previewUrls: false,
450
+ ...hosting(options, worker, environment),
277
451
  ...worker,
278
452
  observability: observability(worker.observability),
279
- name: identity(root, options).name,
453
+ name: workerName(root, options, environment),
280
454
  compatibilityFlags: [.../* @__PURE__ */ new Set(["nodejs_compat", ...worker.compatibilityFlags ?? []])],
281
455
  entrypoint: "./.maximus/entry.ts",
282
456
  ...servesWebApp(root) ? { assets: {
@@ -945,9 +1119,29 @@ function discoverDurableObjects(files, imports) {
945
1119
  return `export const ${className} = worker.durableObject(${imports.add(`durable_object_${index}`, file)});`;
946
1120
  });
947
1121
  }
1122
+ /** A declared page's segment: a fixed name, or a parameter as React Router (`:id`) or TanStack Router (`$id`) writes it. */
1123
+ const PAGE_SEGMENT = /^(?:[a-zA-Z0-9._~-]+|[:$][a-zA-Z][a-zA-Z0-9_]*)$/;
948
1124
  /**
949
- * A web app: `index.html` at the root, which the plugin found, and the pages `app/routes/` declares. The same
950
- * files make React Router's routes and the paths the Worker answers with the app's shell.
1125
+ * The pages `webApp.pages` declares, as paths with `:parameter` segments: `/` or absolute paths of fixed and
1126
+ * parameter segments, no trailing slash, each shape once.
1127
+ */
1128
+ function declaredPages(declared) {
1129
+ if (!Array.isArray(declared) || !declared.length) throw new TypeError("webApp.pages lists one or more page paths, such as /patients/:patientId, or is absent.");
1130
+ const shapes = /* @__PURE__ */ new Set();
1131
+ return declared.map((path) => {
1132
+ const segments = typeof path === "string" && path.startsWith("/") ? path.slice(1).split("/") : [];
1133
+ if (!(path === "/" || segments.length > 0 && segments.every((segment) => PAGE_SEGMENT.test(segment) && segment !== "." && segment !== ".."))) throw new TypeError(`webApp.pages takes absolute paths of fixed and :parameter or $parameter segments, such as /patients/:patientId: ${String(path)}`);
1134
+ const route = path === "/" ? "/" : `/${segments.map((segment) => segment.replace(/^\$/, ":")).join("/")}`;
1135
+ const shape = route.replaceAll(/:[^/]+/g, ":");
1136
+ if (shapes.has(shape)) throw new TypeError(`webApp.pages lists the same page twice: ${path}`);
1137
+ shapes.add(shape);
1138
+ return route;
1139
+ });
1140
+ }
1141
+ /**
1142
+ * A web app: `index.html` at the root, which the plugin found, and the pages `app/routes/` declares, or those
1143
+ * its own router declares in `webApp.pages`. The same files make React Router's routes and the paths the
1144
+ * Worker answers with the app's shell.
951
1145
  */
952
1146
  function discoverWebApp(root, output, mode, project, pagePaths) {
953
1147
  const web = project.worker.assets;
@@ -965,10 +1159,18 @@ function discoverWebApp(root, output, mode, project, pagePaths) {
965
1159
  "js"
966
1160
  ]);
967
1161
  const pages = projectFiles(root, "app/routes", mode);
1162
+ const declared = web.pages === void 0 ? [] : declaredPages(web.pages);
1163
+ if (declared.length && pages.length) throw new TypeError("Declare a web app's pages once: in app/routes/ or in webApp.pages, not both.");
968
1164
  const shell = {
969
- paths: pages.length ? [] : ["/"],
1165
+ paths: pages.length || declared.length ? [] : ["/"],
970
1166
  patterns: []
971
1167
  };
1168
+ /** Answers a page's path with the shell: exactly, or by a pattern when it carries a parameter. */
1169
+ const servePage = (route) => {
1170
+ if (route.includes(":")) shell.patterns.push(`/^${route.replaceAll(/:[^/]+/g, "[^/]+").replaceAll("/", String.raw`\/`).replaceAll(".", String.raw`\.`)}$/`);
1171
+ else shell.paths.push(route);
1172
+ };
1173
+ for (const route of declared) servePage(route);
972
1174
  const claimed = /* @__PURE__ */ new Map();
973
1175
  const imports = new Imports(output);
974
1176
  const routes = pages.map(({ name, file }) => {
@@ -977,16 +1179,19 @@ function discoverWebApp(root, output, mode, project, pagePaths) {
977
1179
  const owner = claimed.get(shape);
978
1180
  if (owner) throw new TypeError(`Multiple page files claim ${route}: ${relative(root, owner)} and ${relative(root, file)}.`);
979
1181
  claimed.set(shape, file);
980
- if (route.includes(":")) shell.patterns.push(`/^${route.replaceAll(/:[^/]+/g, "[^/]+").replaceAll("/", String.raw`\/`)}$/`);
981
- else shell.paths.push(route);
1182
+ servePage(route);
982
1183
  return `{ path: ${JSON.stringify(route)}, caseSensitive: true, lazy: () => import(${imports.source(file)}).then(page) }`;
983
1184
  });
984
- for (const route of [...shell.paths, ...pages.map(({ name }) => projectPath(name, "app"))]) if ([
1185
+ for (const route of [
1186
+ ...shell.paths,
1187
+ ...declared,
1188
+ ...pages.map(({ name }) => projectPath(name, "app"))
1189
+ ]) if ([
985
1190
  basePath,
986
1191
  "/.well-known",
987
1192
  "/mcp",
988
1193
  "/assets"
989
- ].some((prefix) => ownsPrefix(prefix, route)) || route === healthPath || VERSIONED_PATH.test(route) || pagePaths.has(route)) throw new TypeError(`The page ${route} claims a path the API, discovery, MCP, the build's assets or pages/ answer: move it in app/routes/.`);
1194
+ ].some((prefix) => ownsPrefix(prefix, route)) || route === healthPath || VERSIONED_PATH.test(route) || pagePaths.has(route)) throw new TypeError(`The page ${route} claims a path the API, discovery, MCP, the build's assets or pages/ answer: move it in ${declared.length ? "webApp.pages" : "app/routes/"}.`);
990
1195
  const source = pages.length ? generatedModule(mode, [
991
1196
  "import type { ComponentType } from 'react';",
992
1197
  "import type { RouteObject } from 'react-router';",
@@ -1296,13 +1501,14 @@ function workerShape({ webApp, durableObjects, crons, queues }) {
1296
1501
  * trigger its cron and queue modules state. The project is prepared for `development` under `vp dev` alone;
1297
1502
  * every build is `production`.
1298
1503
  */
1299
- function maximusProject(project) {
1504
+ function maximusProject(project, environments = []) {
1300
1505
  let root = process.cwd();
1301
1506
  let mode = "production";
1507
+ let building;
1302
1508
  let previous;
1303
- const prepare = (directory, preparing) => prepareProject(directory, preparing, project(resolve(directory), preparing));
1509
+ const prepare = (directory, preparing, environment) => prepareProject(directory, preparing, project(resolve(directory), preparing, environment));
1304
1510
  const reconcile = () => {
1305
- const current = prepare(root, mode);
1511
+ const current = prepare(root, mode, building);
1306
1512
  const restart = previous !== void 0 && workerShape(previous) !== workerShape(current);
1307
1513
  previous = current;
1308
1514
  return {
@@ -1317,10 +1523,14 @@ function maximusProject(project) {
1317
1523
  return {
1318
1524
  name: "maximus-project",
1319
1525
  enforce: "pre",
1320
- api: { prepare },
1526
+ api: {
1527
+ prepare,
1528
+ environments
1529
+ },
1321
1530
  config(config, environment) {
1322
1531
  root = resolve(config.root ?? root);
1323
1532
  mode = environment.command === "serve" && !environment.isPreview ? "development" : "production";
1533
+ building = environmentName(mode, environment.mode);
1324
1534
  reconcile();
1325
1535
  },
1326
1536
  buildStart() {
@@ -1376,6 +1586,40 @@ function auth0({ domain, audience, algorithms = ["RS256"] }) {
1376
1586
  algorithms
1377
1587
  };
1378
1588
  }
1589
+ /** Arbol's Identity in production. */
1590
+ const ARBOL_IDENTITY = "https://id.getarbol.com";
1591
+ /**
1592
+ * The token options of a service whose access tokens Arbol's Identity issues, as its OpenID metadata publishes
1593
+ * it: the issuer, its JWKS (`/api/auth/jwks`), its authorization and token endpoints (`/api/auth/oauth2/…`),
1594
+ * access tokens that say so (`typ: at+jwt`), and machines whose subject is their client id. With `clients`, it
1595
+ * admits only the tokens of those clients, each environment's own when they are named by environment; with
1596
+ * `people: 'all'`, their people may call every public operation:
1597
+ *
1598
+ * tokens: arbolIdentity({ clients: { production: '…', preview: '…' }, people: 'all' })
1599
+ *
1600
+ * Throws a TypeError for an issuer that is not an HTTPS origin.
1601
+ */
1602
+ function arbolIdentity({ audience, issuer = ARBOL_IDENTITY, clients, people } = {}) {
1603
+ let origin;
1604
+ try {
1605
+ const url = new URL(issuer);
1606
+ origin = url.protocol === "https:" && url.origin === issuer ? url.origin : void 0;
1607
+ } catch {
1608
+ origin = void 0;
1609
+ }
1610
+ if (origin === void 0) throw new TypeError("arbolIdentity() takes Identity's issuer as an HTTPS origin, such as https://id.getarbol.com.");
1611
+ return {
1612
+ issuer: origin,
1613
+ ...audience === void 0 ? {} : { audience },
1614
+ jwksUri: "/api/auth/jwks",
1615
+ authorizationEndpoint: "/api/auth/oauth2/authorize",
1616
+ tokenEndpoint: "/api/auth/oauth2/token",
1617
+ requireType: "at+jwt",
1618
+ claims: { machineSubject: "{client}" },
1619
+ ...clients === void 0 ? {} : { clients },
1620
+ ...people === void 0 ? {} : { people }
1621
+ };
1622
+ }
1379
1623
  /**
1380
1624
  * The token options of an application behind Cloudflare Access: the application token Access sets in
1381
1625
  * `Cf-Access-Jwt-Assertion`, read from there alone and verified against the team's keys (RS256, issued by
@@ -1438,17 +1682,18 @@ async function presets(config) {
1438
1682
  * Cloudflare's Vite plugin.
1439
1683
  */
1440
1684
  function maximus(options) {
1441
- const project = maximusProject((root, phase) => projectOptions(root, options, phase));
1685
+ const project = maximusProject((root, phase, environment) => projectOptions(root, options, phase, environment), Object.keys(options.environments ?? {}));
1442
1686
  let worker;
1443
1687
  const configure = {
1444
1688
  name: "maximus",
1445
1689
  enforce: "pre",
1446
- async config(config, { command, isPreview }) {
1690
+ async config(config, { command, isPreview, mode }) {
1447
1691
  const root = resolve(config.root ?? process.cwd());
1448
1692
  const phase = command === "serve" && !isPreview ? "development" : "production";
1693
+ const environment = environmentName(phase, mode);
1449
1694
  for (const [file, subject] of [["cloudflare.config.ts", "the Worker"], ["maximus.config.ts", "the application"]]) if (existsSync(join(root, file))) throw new TypeError(`maximus() configures ${subject}: move ${file} into maximus()'s options.`);
1450
1695
  checkWebAppBuild(root, config);
1451
- worker = workerConfig(root, phase, options, project.api.prepare(root, phase));
1696
+ worker = workerConfig(root, phase, options, project.api.prepare(root, phase, environment), environment);
1452
1697
  return await presets(config);
1453
1698
  },
1454
1699
  configEnvironment(name, config) {
@@ -1492,4 +1737,4 @@ function testing() {
1492
1737
  };
1493
1738
  }
1494
1739
 
1495
- export { auth0, cloudflareAccess, maximus };
1740
+ export { arbolIdentity, auth0, cloudflareAccess, maximus, storeSecret };
@@ -1,4 +1,4 @@
1
- import { Fr as Result, qr as Failure } from "./chunks/types-t_09KY-x.js";
1
+ import { Fr as Result, qr as Failure } from "./chunks/types-Dmw37bhl.js";
2
2
  /** Why a webhook signature was refused: absent, malformed, outside the time tolerance, or not matching. */
3
3
  export declare const WEBHOOK_SIGNATURE_FAILURES: readonly ['missing', 'malformed', 'expired', 'mismatch'];
4
4
  /** Why a webhook signature was refused. */
@@ -1,2 +1,2 @@
1
- import { a as credentials, i as createWorker, n as WorkerOptions, o as WorkerAssetsOptions, r as WorkerRuntime, t as RpcMethods } from "../chunks/workers-types-DyQBrA49.js";
1
+ import { a as credentials, i as createWorker, n as WorkerOptions, o as WorkerAssetsOptions, r as WorkerRuntime, t as RpcMethods } from "../chunks/workers-types-CYOvun0Q.js";
2
2
  export { RpcMethods, type WorkerAssetsOptions, WorkerOptions, WorkerRuntime, createWorker, credentials };
@@ -1,3 +1,3 @@
1
- import { n as credentials, t as createWorker } from "../chunks/runtime-CWORw_TD.js";
1
+ import { n as credentials, t as createWorker } from "../chunks/runtime-Bg729nOQ.js";
2
2
 
3
3
  export { createWorker, credentials };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arbol-ai/maximus",
3
- "version": "8.8.0",
3
+ "version": "8.9.0",
4
4
  "description": "Maximus: define a service once and serve it over HTTP, MCP and Worker RPC on Cloudflare Workers, configured in vite.config.ts, with its OpenAPI and CLI.",
5
5
  "keywords": [
6
6
  "api",