@spfn/core 0.3.0-beta.2 → 0.3.0-beta.21

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 (94) hide show
  1. package/README.md +343 -16
  2. package/dist/app-config/index.d.ts +134 -0
  3. package/dist/app-config/index.js +58 -0
  4. package/dist/app-config/index.js.map +1 -0
  5. package/dist/authz/index.js +1 -381
  6. package/dist/authz/index.js.map +1 -1
  7. package/dist/{boss-D16fO2oG.d.ts → boss-BiDCbbAQ.d.ts} +60 -7
  8. package/dist/codegen/index.d.ts +93 -15
  9. package/dist/codegen/index.js +626 -165
  10. package/dist/codegen/index.js.map +1 -1
  11. package/dist/config/index.d.ts +0 -63
  12. package/dist/config/index.js +15 -15
  13. package/dist/config/index.js.map +1 -1
  14. package/dist/contract/index.d.ts +40 -17
  15. package/dist/contract/index.js +147 -23
  16. package/dist/contract/index.js.map +1 -1
  17. package/dist/db/index.d.ts +201 -34
  18. package/dist/db/index.js +294 -158
  19. package/dist/db/index.js.map +1 -1
  20. package/dist/{define-middleware-DfDP39Nq.d.ts → define-middleware-CVKgqo8S.d.ts} +1 -1
  21. package/dist/env/index.d.ts +6 -442
  22. package/dist/env/index.js +13 -16
  23. package/dist/env/index.js.map +1 -1
  24. package/dist/env/loader.js +24 -1
  25. package/dist/env/loader.js.map +1 -1
  26. package/dist/error-TsUIjp_x.d.ts +157 -0
  27. package/dist/errors/index.js +1 -381
  28. package/dist/errors/index.js.map +1 -1
  29. package/dist/event/index.d.ts +5 -5
  30. package/dist/event/index.js +32 -1
  31. package/dist/event/index.js.map +1 -1
  32. package/dist/event/sse/client.d.ts +18 -4
  33. package/dist/event/sse/client.js +38 -2
  34. package/dist/event/sse/client.js.map +1 -1
  35. package/dist/event/sse/index.d.ts +5 -4
  36. package/dist/event/ws/client.d.ts +3 -2
  37. package/dist/event/ws/index.d.ts +4 -3
  38. package/dist/job/index.d.ts +48 -3
  39. package/dist/job/index.js +131 -52
  40. package/dist/job/index.js.map +1 -1
  41. package/dist/logger/index.js +0 -12
  42. package/dist/logger/index.js.map +1 -1
  43. package/dist/middleware/index.d.ts +6 -2
  44. package/dist/middleware/index.js +7 -388
  45. package/dist/middleware/index.js.map +1 -1
  46. package/dist/nextjs/index.d.ts +88 -8
  47. package/dist/nextjs/index.js +138 -62
  48. package/dist/nextjs/index.js.map +1 -1
  49. package/dist/nextjs/server.d.ts +45 -7
  50. package/dist/nextjs/server.js +14 -0
  51. package/dist/nextjs/server.js.map +1 -1
  52. package/dist/ops/index.d.ts +62 -43
  53. package/dist/ops/index.js +638 -97
  54. package/dist/ops/index.js.map +1 -1
  55. package/dist/registry-C2KQCh0m.d.ts +473 -0
  56. package/dist/route/index.d.ts +6 -3
  57. package/dist/route/index.js +97 -28
  58. package/dist/route/index.js.map +1 -1
  59. package/dist/route/types.d.ts +7 -1
  60. package/dist/{router-Qbssr11H.d.ts → route-builder-DRW-MSCJ.d.ts} +52 -127
  61. package/dist/router-4YoIy5fN.d.ts +172 -0
  62. package/dist/{token-manager-BT5EnUAR.d.ts → router-CysBmgv3.d.ts} +81 -127
  63. package/dist/server/index.d.ts +185 -14
  64. package/dist/server/index.js +883 -78
  65. package/dist/server/index.js.map +1 -1
  66. package/dist/surface/index.d.ts +115 -0
  67. package/dist/surface/index.js +1003 -0
  68. package/dist/surface/index.js.map +1 -0
  69. package/dist/token-manager-Ckjt2-qq.d.ts +122 -0
  70. package/dist/{types-D1c57Ko-.d.ts → types-5Rl11_Nb.d.ts} +43 -4
  71. package/dist/{types-ZQODsBft.d.ts → types-B8zAxFsE.d.ts} +2 -1
  72. package/dist/types-CxhPH4s_.d.ts +375 -0
  73. package/dist/{types-2AbaW4Ie.d.ts → types-W4u_S0lF.d.ts} +4 -3
  74. package/docs/file-upload.md +195 -333
  75. package/package.json +20 -9
  76. package/src/cache/README.md +330 -0
  77. package/src/codegen/README.md +634 -0
  78. package/src/config/README.md +333 -0
  79. package/src/contract/README.md +440 -0
  80. package/src/db/README.md +589 -0
  81. package/src/db/manager/README.md +500 -0
  82. package/src/db/schema/README.md +354 -0
  83. package/src/db/transaction/README.md +822 -0
  84. package/src/env/README.md +787 -0
  85. package/src/errors/README.md +429 -0
  86. package/src/event/README.md +789 -0
  87. package/src/job/README.md +613 -0
  88. package/src/logger/README.md +321 -0
  89. package/src/middleware/README.md +634 -0
  90. package/src/nextjs/README.md +688 -0
  91. package/src/route/README.md +763 -0
  92. package/src/security/README.md +100 -0
  93. package/src/server/README.md +704 -0
  94. package/dist/types-9oszaJqp.d.ts +0 -250
package/README.md CHANGED
@@ -43,7 +43,7 @@ Next.js owns the frontend, Drizzle owns the SQL, and your services own the rules
43
43
 
44
44
  ```bash
45
45
  pnpm add @spfn/core@beta drizzle-orm@1.0.0-rc.4 postgres pg
46
- # optional peer: next ^16.2.11 (only for the Next.js bridge)
46
+ # optional peer: next ^16.3.3 (only for the Next.js bridge)
47
47
  ```
48
48
 
49
49
  Node `>=20.0.0`. ESM only.
@@ -122,8 +122,9 @@ the route map the RPC proxy needs — and nothing else.
122
122
  5. **Mount the RPC proxy** in Next.js as the `app/api/rpc/[routeName]/route.ts`
123
123
  catch-all. The browser only ever sends `GET` (no body) or `POST` (body or formData)
124
124
  to `/api/rpc/{routeName}`; the proxy looks up `routeMap[routeName]`, substitutes
125
- `:params`, and forwards with the real method. Package route maps (`authRouteMap`,
126
- `eventRouteMap`) merge into the same map.
125
+ `:params`, and forwards with the real method. The generated map already carries the
126
+ routes of the packages the app router mounts with `.packages()`; `eventRouteMap` is
127
+ merged by hand, being a constant rather than a mounted router.
127
128
  6. **Call it** through `createApi<AppRouter>()`. The client is a `Proxy` over the
128
129
  `AppRouter` type — typed in and out, with no runtime cost for the types. Errors
129
130
  arrive as `ApiError`, or as the original error class when that class is registered in
@@ -185,18 +186,144 @@ import type { AppRouter } from '@/server/router';
185
186
 
186
187
  export const api = createApi<AppRouter>();
187
188
 
188
- // anywhere — server component, client component, or server action:
189
+ // the same client in a Server Component, a Client Component or a Server Action:
189
190
  const user = await api.getUser.call({ params: { id: '123' } }); // typed { id, name }
190
191
  const made = await api.createUser.call({ body: { name: 'A' } });
191
192
  ```
192
193
 
194
+ That the client is isomorphic does not make the three callers interchangeable. **A page's
195
+ initial data is awaited in the Server Component**, where
196
+ `api.getUser.fetchOptions({ next: { revalidate, tags } }).call(…)` participates in
197
+ Next.js caching and reaches the backend without a browser round trip. Fetching that same
198
+ first paint from a `'use client'` component inside a `useEffect` is the anti-pattern: it
199
+ ships a loading state and a second network hop for data the server already had. Client
200
+ Components and Server Actions are for what happens after the first paint — interaction
201
+ and mutation. Cache tags, revalidation and SSR cookie forwarding are in
202
+ [the Next.js bridge docs](https://superfunction.xyz/docs/packages/core/nextjs).
203
+
204
+ ---
205
+
206
+ ## How does a repository talk to the database?
207
+
208
+ Through `BaseRepository`. Extending it gives a repository two transaction-aware
209
+ connections — `this.db` (write/primary) and `this.readDb` (the replica, when one is
210
+ configured) — plus the CRUD set as protected methods.
211
+
212
+ ```typescript
213
+ // server/repositories/order.ts
214
+ import { BaseRepository } from '@spfn/core/db';
215
+ import { desc } from 'drizzle-orm';
216
+ import { orders } from '../entities/order';
217
+
218
+ export class OrderRepository extends BaseRepository
219
+ {
220
+ findRecentFor(userId: string)
221
+ {
222
+ return this._findMany(orders, { where: { userId }, orderBy: desc(orders.createdAt) });
223
+ }
224
+
225
+ place(data: { userId: string; total: number })
226
+ {
227
+ return this._create(orders, data);
228
+ }
229
+ }
230
+
231
+ export const orderRepo = new OrderRepository();
232
+ ```
233
+
234
+ Handlers never import drizzle query builders; repositories do. `_findMany` reads through
235
+ `this.readDb`, `_create` writes through `this.db`, and both getters resolve to the active
236
+ transaction's connection when there is one — so the same method is correct inside a
237
+ transaction and outside it. When a helper cannot express a query, drop to
238
+ `this.readDb.select()…` inside the repository rather than in the handler. The full
239
+ protected CRUD set is in [src/db](./src/db/README.md).
240
+
241
+ ---
242
+
243
+ ## Where do transactions and their side effects go?
244
+
245
+ `Transactional()` covers the route case — commit on return, rollback on throw. Two rules
246
+ decide the rest.
247
+
248
+ **Nothing takes a `tx` parameter.** The transaction travels in AsyncLocalStorage, so
249
+ `this.db` inside a repository already resolves to it. A service that accepts `tx` and
250
+ threads it downward re-implements propagation that already happened, and the first caller
251
+ that forgets to pass it writes outside the transaction. For a service, script or job with
252
+ no route around it, open one with `runInTransaction(fn, options?)`;
253
+ `runWithTransaction(tx, txId, fn)` is the lower-level primitive that binds an existing
254
+ Drizzle transaction into the context.
255
+
256
+ **Side effects go on the commit hooks, not inline.** An event emitted or a mail sent from
257
+ inside the transaction still went out when the transaction later rolls back.
258
+
259
+ | Hook | When it runs | What it is for |
260
+ |---|---|---|
261
+ | `onBeforeCommit(fn)` | Inside the still-open transaction, just before commit — a throw aborts and rolls back | Last-moment invariant checks, and statements that must land in the same commit |
262
+ | `onAfterCommit(fn)` | After the root transaction commits, outside the transaction context; errors are logged, never thrown | Events, mail, cache invalidation — anything the outside world observes |
263
+ | `onAfterRollback(fn)` | After the root transaction rolls back, before the causing error propagates; errors are logged, never thrown | Undoing external work that cannot roll itself back, such as an object already uploaded |
264
+
265
+ All three import from `@spfn/core/db`, can be registered anywhere inside the transaction,
266
+ and bubble to the **root** transaction — a nested block's callbacks fire on the outermost
267
+ outcome, not on a savepoint's.
268
+
269
+ ```typescript
270
+ import { runInTransaction, onAfterCommit } from '@spfn/core/db';
271
+
272
+ export async function placeOrder(input: { userId: string; total: number })
273
+ {
274
+ return runInTransaction(async () =>
275
+ {
276
+ const order = await orderRepo.place(input); // no tx argument, at any depth
277
+ onAfterCommit(() => orderPlacedEvent.emit({ orderId: order.id }));
278
+
279
+ return order;
280
+ });
281
+ }
282
+ ```
283
+
284
+ ---
285
+
286
+ ## What else can defineServerConfig configure?
287
+
288
+ `.port()` and `.routes()` are the two every app calls. The rest of the builder is how an
289
+ app wires its infrastructure without touching the server's boot sequence. Every method
290
+ returns the builder; `.build()` ends the chain.
291
+
292
+ | Method | What it configures |
293
+ |---|---|
294
+ | `.port(n)` / `.host(s)` | Where the server listens |
295
+ | `.routes(router)` | The `defineRouter` router to mount, with its own `.use()` and `.packages()` |
296
+ | `.jobs(router, config?)` | Background jobs — a `defineJobRouter`, plus pg-boss options |
297
+ | `.events(router, config?)` | SSE streaming — a `defineEventRouter`, served at `GET /events/stream` |
298
+ | `.websockets(router, config?)` | Bidirectional WebSockets — a `defineWSRouter`, served at `WS /ws` |
299
+ | `.workflows(router, config?)` | `@spfn/workflow` orchestration; the engine starts once the database is ready |
300
+ | `.lifecycle(hooks)` | Boot and shutdown hooks. Callable more than once; hooks run in registration order |
301
+ | `.migrations(opts)` | The migration boot gate — `{ allowPending: true }` lets a server start behind its migrations |
302
+ | `.database(opts)` | Connection and pool settings |
303
+ | `.infrastructure(opts)` | Which infrastructure is initialized at boot |
304
+ | `.healthCheck(opts)` | The health endpoint |
305
+ | `.serverTime(clock)` | The clock behind `GET /_core/time`; normally left at the default |
306
+ | `.middleware(opts)` | The built-in middleware — `ErrorHandler`, `RequestLogger` |
307
+ | `.use(handlers)` | Additional global Hono middleware |
308
+ | `.middlewares(named)` | Global middleware under names, so a route can `.skip([...])` it |
309
+ | `.cors(opts)` | CORS |
310
+ | `.rateLimit(opts)` | A global default limiter plus the named policies routes resolve against |
311
+ | `.proxyGuard(opts)` | Trusted-proxy signature and origin verification, resolved to a `clientType` |
312
+ | `.outboundFetch(opts)` | The SSRF policy `safeFetch` applies to outbound calls |
313
+ | `.timeout(opts)` / `.shutdown(opts)` | Request timeouts and graceful shutdown |
314
+ | `.debug(bool)` | Debug logging |
315
+
316
+ The options each one takes are in [src/server](./src/server/README.md).
317
+
193
318
  ---
194
319
 
195
320
  ## Which import path do I use for what?
196
321
 
197
322
  There is **no root barrel**: `import … from '@spfn/core'` does not resolve. Every symbol
198
323
  comes from a subpath, and the table below is the complete public surface — one row per
199
- entry in `package.json` `exports`. Each module has its own README with the API detail.
324
+ entry in `package.json` `exports`, with a single exclusion: `./client` is still listed in
325
+ `exports` but the build no longer emits it, so it has no row (see [Pitfalls](#pitfalls)).
326
+ Each module has its own README with the API detail.
200
327
 
201
328
  | Import path | Purpose | Doc |
202
329
  |-------------|---------|-----|
@@ -207,16 +334,17 @@ entry in `package.json` `exports`. Each module has its own README with the API d
207
334
  | `@spfn/core/nextjs/server` | Server-only: `createRpcProxy({ routeMap })`, `registerInterceptors`. Uses `next/headers`. | [src/nextjs](./src/nextjs/README.md) |
208
335
  | `@spfn/core/db` | PostgreSQL through Drizzle: CRUD helpers, `BaseRepository`, schema helpers, transactions, Postgres error mapping. One entry point for all of it. | [src/db](./src/db/README.md) |
209
336
  | `@spfn/core/db` → manager | Connection lifecycle, pool, primary/replica, health check, reconnect (`initDatabase`, `getDatabase`). Re-exported from `@spfn/core/db`. | [src/db/manager](./src/db/manager/README.md) |
210
- | `@spfn/core/db` → migrations | Which migrations each installed function package ships, and which the database has applied (`collectMigrationStatus`, `discoverFunctionMigrations`). What `spfn db status`, the boot gate and health all read. Re-exported from `@spfn/core/db`. | [src/db/migrations](./src/db/migrations/index.ts) |
337
+ | `@spfn/core/db` → migrations | Which migrations each installed function package ships, and which the database has applied (`collectMigrationStatus`, `discoverFunctionMigrations`). What `spfn db status`, the boot gate and health all read. Re-exported from `@spfn/core/db`. | [src/db/migrations](https://github.com/fxylabs/spfn/blob/main/packages/core/src/db/migrations/index.ts) |
211
338
  | `@spfn/core/db` → schema | Drizzle column helpers (`id`, `uuid`, `timestamps`, `foreignKey`, `enumText`, `typedJsonb`, `softDelete`, …). Re-exported from `@spfn/core/db`. | [src/db/schema](./src/db/schema/README.md) |
212
339
  | `@spfn/core/db` → transaction | `Transactional()` middleware and `runInTransaction`; the transaction reaches every repository through AsyncLocalStorage. Re-exported from `@spfn/core/db`. | [src/db/transaction](./src/db/transaction/README.md) |
213
340
  | `@spfn/core/middleware` | Built-in Hono middleware: `ErrorHandler`, `RequestLogger` and its masking helper. | [src/middleware](./src/middleware/README.md) |
214
341
  | `@spfn/core/errors` | Serializable HTTP and database error classes, plus `ErrorRegistry` so an error survives the trip to the client as its own class. | [src/errors](./src/errors/README.md) |
215
342
  | `@spfn/core/security` | `safeFetch` — a drop-in `fetch` hardened against SSRF, including DNS rebinding, by pinning the connection to a validated IP. | [src/security](./src/security/README.md) |
216
- | `@spfn/core/authz` | Ownership guards. `requireOwner(resource, userId)` makes "load it, then check it belongs to the requester" one call, so a handler cannot forget it. | [src/authz/index.ts](./src/authz/index.ts) |
343
+ | `@spfn/core/authz` | Ownership guards. `requireOwner(resource, userId)` makes "load it, then check it belongs to the requester" one call, so a handler cannot forget it. | [src/authz/index.ts](https://github.com/fxylabs/spfn/blob/main/packages/core/src/authz/index.ts) |
217
344
  | `@spfn/core/env` | Schema-based environment validation, isomorphic. | [src/env](./src/env/README.md) |
218
345
  | `@spfn/core/env/loader` | The **server-only** `.env` file loader (uses `node:fs`). | [src/env](./src/env/README.md) |
219
346
  | `@spfn/core/config` | `@spfn/core`'s own validated env config (`env`, `envSchema`, `registry`), built on `@spfn/core/env`. | [src/config](./src/config/README.md) |
347
+ | `@spfn/core/app-config` | Reads `spfn.config.js` — the one committed place that says which ports and host the app is served on (`loadAppConfig`, `resolvePorts`, `resolveHost`, `PORT_DEFAULTS`), and where the app's env schema modules are (`env.schemas`, read by `spfn env` / `spfn secret`). Deliberately side-effect free, so the CLI can import it before an app's environment exists. | [src/app-config/index.ts](https://github.com/fxylabs/spfn/blob/main/packages/core/src/app-config/index.ts) |
220
348
  | `@spfn/core/logger` | Structured singleton `logger` with child loggers and level masking. No dependencies. | [src/logger](./src/logger/README.md) |
221
349
  | `@spfn/core/cache` | Valkey/Redis singleton over ioredis (`getCache`, `getCacheRead`). Degrades to disabled rather than throwing. | [src/cache](./src/cache/README.md) |
222
350
  | `@spfn/core/job` | Background jobs on pg-boss: a fluent `job()` builder, cron, run-once, event-driven, `defineJobRouter`. | [src/job](./src/job/README.md) |
@@ -227,6 +355,8 @@ entry in `package.json` `exports`. Each module has its own README with the API d
227
355
  | `@spfn/core/event/ws/client` | Browser WebSocket client. | [src/event](./src/event/README.md) |
228
356
  | `@spfn/core/codegen` | The codegen orchestrator and the built-in generators: `@spfn/core:route-map` for the proxy's route map, `@spfn/core:contract` for the client contract. | [src/codegen](./src/codegen/README.md) |
229
357
  | `@spfn/core/contract` | Route contracts for clients that ship separately: collect, snapshot, and the build gate that refuses a breaking change. | [src/contract](./src/contract/README.md) |
358
+ | `@spfn/core/ops` | The operations surface `spfn ops` drives: `opsRoute`, `createOpsRouter`, `defineOpsModule`, and the manifest the CLI discovers commands from. Structure only — the router is always authenticated, and token verification lives in `@spfn/auth`. | [How do I operate the app from the terminal?](#how-do-i-operate-the-app-from-the-terminal) |
359
+ | `@spfn/core/surface` | `defineSurface`: a command surface on any namespace — the same authenticated router, manifest and modules `@spfn/core/ops` is on `/_ops`, for a caller other than an operator. | [Can a second surface sit beside `/_ops`?](#can-a-second-surface-sit-beside-_ops) |
230
360
 
231
361
  `db/manager`, `db/schema` and `db/transaction` are **not** package subpaths of their own.
232
362
  They are internal modules re-exported by `@spfn/core/db` — import their symbols from
@@ -292,8 +422,8 @@ export default defineServerConfig()
292
422
 
293
423
  All three log the pending list as a warning rather than silently continuing.
294
424
 
295
- **A readiness probe sees the same thing.** When detailed health is on, `GET /health`
296
- carries a `migrations` object beside `services`:
425
+ **A readiness probe sees the same thing.** When detailed health is on,
426
+ `GET /_core/health` carries a `migrations` object beside `services`:
297
427
 
298
428
  ```json
299
429
  {
@@ -320,6 +450,78 @@ The serverless path (`createServerlessApp`) has no boot to gate — run
320
450
 
321
451
  ---
322
452
 
453
+ ## Which path does the health endpoint answer on?
454
+
455
+ `/_core/health`. That is the whole answer — `@spfn/core` registers nothing on `/health`.
456
+
457
+ `/_core/` belongs to `@spfn/core` the way `/_auth/` belongs to `@spfn/auth`: the endpoints
458
+ in it are registered before your routes, so no route you declare can take one. That is
459
+ what makes `/_core/health` the right target for a readiness probe, a Dockerfile
460
+ `HEALTHCHECK` or an uptime monitor — the answer does not depend on what your app defines.
461
+
462
+ ```typescript
463
+ // the endpoint answers at /_core/health, and nowhere else
464
+ export default defineServerConfig().build();
465
+
466
+ // an additional address, for a probe path you cannot change
467
+ export default defineServerConfig().healthCheck({ path: '/health' }).build();
468
+
469
+ // off → nothing answers anywhere
470
+ export default defineServerConfig().healthCheck({ enabled: false }).build();
471
+ ```
472
+
473
+ `healthCheck.path` adds a second address. It never moves `/_core/health`, and it is
474
+ registered before your routes like the canonical one — so an app route on the same path
475
+ will not run, and the server says so at boot.
476
+
477
+ **`/health` is yours now.** Declare `GET /health` and it behaves like any other route of
478
+ yours. Declare nothing there and, for one release, a `GET` answers **410** naming
479
+ `/_core/health`, and the server warns once the first time it is hit — a readiness probe
480
+ failure shows an operator neither a response body nor a status text, so a bare 404 would
481
+ leave them nothing to search for. Upgrading an existing deployment?
482
+ [docs/guides/migration/health-endpoint.md](../../docs/guides/migration/health-endpoint.md).
483
+
484
+ Every built-in health address is registered before the `lifecycle.beforeRoutes` hook, and
485
+ a Hono middleware only wraps handlers registered after it. So a global guard your app adds
486
+ in that hook — which is what the hook is documented for — cannot close the endpoint a
487
+ probe depends on, and a probe reaches it unauthenticated. An app with `src/server/app.ts`
488
+ (level 3) wires its own server and gets no health endpoint at all.
489
+
490
+ ---
491
+
492
+ ## How does a client synchronize with the server clock?
493
+
494
+ Call `GET /_core/time` before minting a timestamped proof. It is a built-in,
495
+ unauthenticated and session-free operation registered before application middleware and
496
+ routes:
497
+
498
+ ```json
499
+ { "serverTimeMillis": 1750000000123 }
500
+ ```
501
+
502
+ The response is a closed contract: `serverTimeMillis` is an integer Unix epoch in
503
+ milliseconds and no additional fields are declared. It always carries
504
+ `Cache-Control: no-store`; a cached clock reading is not a synchronization point.
505
+
506
+ The value is trustworthy only when the transport is trustworthy. Production clients must
507
+ call the endpoint over HTTPS and validate the server certificate. The endpoint does not
508
+ sign its response, compensate for network latency, choose an authentication skew margin,
509
+ or define client retry and persistence policy — those belong to the consuming protocol.
510
+
511
+ Tests can inject an exact clock without replacing global time:
512
+
513
+ ```typescript
514
+ const app = await createServer(defineServerConfig()
515
+ .serverTime({ clock: { now: () => 1750000000123 } })
516
+ .build());
517
+ ```
518
+
519
+ `CORE_TIME_ROUTE`, `CORE_TIME_PATH`, `ServerTimeResponseSchema` and the
520
+ `ServerTimeResponse` type are exported from `@spfn/core/server` for separately deployed
521
+ client-contract exporters to consume from the same wire definition.
522
+
523
+ ---
524
+
323
525
  ## Can I deploy this to Vercel?
324
526
 
325
527
  Yes, and it is a first-class target rather than a workaround. From your app:
@@ -444,11 +646,135 @@ spfn ops call listSignups --query limit=50 # invoke one
444
646
  spfn ops call listSignups --describe # print its usage (--json for raw schemas)
445
647
  ```
446
648
 
649
+ ### Can a package ship ops commands?
650
+
651
+ It can describe them. Whether they are reachable is your application's decision, made in
652
+ the `createOpsRouter` call — installing a package never adds anything to your ops surface.
653
+ Available from **0.3.0-beta.5**.
654
+
655
+ ```typescript
656
+ // in the package
657
+ export const ledgerOpsModule = defineOpsModule({
658
+ id: 'ledger',
659
+ source: '@acme/ledger',
660
+ contractVersion: '1.0.0',
661
+ summary: 'Ledger diagnostics',
662
+ commands: {
663
+ verify: {
664
+ summary: 'Verify ledger invariants',
665
+ effect: 'read', // read | write | destructive
666
+ scopes: ['ledger:read'],
667
+ route: opsRoute.get('/ledger/verify').handler(verifyLedger),
668
+ },
669
+ },
670
+ });
671
+
672
+ // in the application — nothing is mounted until this line names it
673
+ export const opsRouter = createOpsRouter({ listSignups }, {
674
+ auth: opsTokenAuth,
675
+ authorize: requireOpsScope,
676
+ modules: [ledgerOpsModule],
677
+ });
678
+ ```
679
+
680
+ A module command is named `<module>.<command>` (`ledger.verify`) and its route must live
681
+ under `/_ops/<module>/`. The scopes it declares become a server-side guard, run after
682
+ authentication — `authorize` is required as soon as any module is mounted, and it is passed
683
+ in rather than imported so core stays independent of `@spfn/auth`.
684
+
685
+ What is refused at definition time: a path that could decode its way out of the module's
686
+ namespace, two commands in one module that could answer the same URL, and an app route that
687
+ overlaps a mounted module's command. That last one matters because the alternative is a
688
+ surface where which command answers depends on route registration order.
689
+
690
+ The manifest gains a `modules` array and per-command `module`, `summary`, `effect` and
691
+ `scopes`. All of it is additive — an app that mounts no modules serves exactly the v1
692
+ manifest it served before.
693
+
694
+ An app's own ops routes may declare `.effect()` and `.summary()` too, and the manifest
695
+ carries both for that command. On `/_ops` they are optional: a route declaring neither is
696
+ announced exactly as before.
697
+
698
+ ```bash
699
+ spfn ops modules # what is mounted, and from where
700
+ spfn ops list --module ledger # just that module's commands
701
+ spfn ops call ledger.compact --yes # effect=destructive needs this
702
+ ```
703
+
447
704
  Authentication is an ops token from [`@spfn/auth`](../auth/README.md#ops-tokens-spfn-ops):
448
- scoped, revocable, hash-stored, issued with `spfn ops token issue` where database access
449
- already exists — a deployed app has no token-creation endpoint. On macOS the CLI keeps the
450
- token in the keychain (`spfn ops token store`), and resolution order is `--token` →
451
- `SPFN_OPS_TOKEN` → keychain.
705
+ scoped, revocable, hash-stored, issued with `spfn ops token issue` against the running app
706
+ — the CLI signs in as an administrator, so issuance needs no database access. On macOS the
707
+ CLI keeps the token in the keychain (`spfn ops token store`), and resolution order is
708
+ `--token` → `SPFN_OPS_TOKEN` → keychain. The `--app` URL must be https, since every command
709
+ carries a secret; `http` is accepted only against a loopback host.
710
+
711
+ ### Can a second surface sit beside `/_ops`?
712
+
713
+ Yes. `/_ops` is one command surface; `defineSurface` from `@spfn/core/surface` builds
714
+ another on a namespace of your choosing, for a caller that is not an operator — a service
715
+ holding a token some issuer signed, say. It is the same structure: a `route` with the
716
+ namespace applied, auth injected into every command, a manifest at `<namespace>/_manifest`
717
+ registered first, and modules mounted only when you name them. `createOpsRouter` is
718
+ `defineSurface({ namespace: '/_ops', ... }).router(...)`.
719
+
720
+ ```typescript
721
+ // src/server/app-surface.ts
722
+ import { Type } from '@sinclair/typebox';
723
+ import { defineSurface } from '@spfn/core/surface';
724
+ import { signedTokenAuth } from '@spfn/auth/server';
725
+
726
+ export const app = defineSurface({
727
+ namespace: '/_app', // required
728
+ auth: signedTokenAuth({ // required
729
+ keysUrl: 'https://issuer.example/.well-known/keys',
730
+ iss: 'https://issuer.example',
731
+ aud: 'my-app',
732
+ }),
733
+ manifest: 'public', // 'authenticated' (default) | 'public'
734
+ });
735
+
736
+ export const pageAdd = app.route.post('/pages') // POST /_app/pages
737
+ .input({ body: Type.Object({ title: Type.String() }) })
738
+ .effect('write') // required: read | write | destructive
739
+ .summary('Add a page to the blueprint') // optional, at most 500 characters
740
+ .handler(async (c) => pagesRepository.add((await c.data()).body.title));
741
+
742
+ // src/server/router.ts — both surfaces, side by side
743
+ export const appRouter = defineRouter({ ... }).packages([app.router({ pageAdd }), opsRouter]);
744
+ ```
745
+
746
+ - **Namespace.** An absolute path of `[A-Za-z0-9_-]` segments with no trailing slash —
747
+ `/_app`, `/machine/v1`. Anything else (`app`, `/_app/`, `/`, a `%`, a `:param`) is refused
748
+ at `defineSurface`.
749
+ - **Manifest.** Served at `<namespace>/_manifest` under the reserved route name
750
+ `get<Namespace>Manifest` — `getAppManifest` for `/_app`, `getOpsManifest` for `/_ops`,
751
+ `getappManifest` for `/app`. The namespace is encoded one-to-one (`_x` → `X`; any other
752
+ `_`, `-`, `/` or uppercase letter is escaped with `_`), so two surfaces never register one
753
+ name. Two surfaces on one namespace are refused by `.packages()`. `manifest: 'public'`
754
+ drops `auth` from that one route and skips a server-level `auth` middleware on it, so a
755
+ caller can discover commands before it holds a token; every command stays behind `auth`
756
+ regardless.
757
+ - **`authorize`.** Optional, `(command) => middleware | undefined`, called once per command
758
+ (module commands included) when the router is built. The middleware runs after `auth` and
759
+ before the command's own: `[auth, authorize?, ...group, ...own]`. Required as soon as a
760
+ module is mounted. A guard named like `auth` or like one of the command's group or own
761
+ middlewares is refused: registration keeps one middleware per name, so the other one would
762
+ never run.
763
+ - **Effect.** Every app command on a `defineSurface` surface declares `.effect()` on its
764
+ route; `router()` refuses one that does not, naming the command, so a client never
765
+ receives a command whose effect it cannot know. `/_ops` routes may declare it and need
766
+ not. The manifest announces `effect` and `summary` beside the command, and `authorize`
767
+ receives them on the command it is given. A module command's own declaration wins over its
768
+ route's: a route `.effect()` that disagrees with it is refused.
769
+ - **Modules.** A module is validated against the namespace of the surface that mounts it —
770
+ its commands must live under `<namespace>/<id>/`. Write one for a surface with
771
+ `defineSurfaceModule(module, '/_app')`; a module written for `/_ops` mounted on `/_app` is
772
+ refused, and the message names the namespace.
773
+ - **Errors.** Every refusal is a `SurfaceError`. `@spfn/core/ops` exports the same class as
774
+ `OpsRouterError`, so `instanceof` holds under either name.
775
+
776
+ The client for any surface is the CLI's library export,
777
+ [`spfn/surface`](../cli/README.md#can-i-call-a-surface-from-my-own-code).
452
778
 
453
779
  ---
454
780
 
@@ -539,9 +865,10 @@ way so the endpoint never reveals that someone else's record exists.
539
865
 
540
866
  Other SPFN packages build on `@spfn/core`:
541
867
 
542
- - [`@spfn/auth`](../auth/README.md) — sessions, social login and RBAC. Exports
543
- `authRouteMap` and registers proxy interceptors automatically; merge its route map into
544
- `createRpcProxy`.
868
+ - [`@spfn/auth`](../auth/README.md) — sessions, social login and RBAC. Mount `authRouter`
869
+ with `.packages()` and its routes are in the app's generated map; the package registers
870
+ proxy interceptors automatically. (`authRouteMap` is still exported, and merging it is
871
+ now a no-op.)
545
872
  - [`@spfn/mcp`](../mcp/README.md) — exposes your operations as MCP tools, so an agent can
546
873
  run them instead of you building an admin dashboard.
547
874
  - `@spfn/i18n`, `@spfn/storage`, `@spfn/notification`, `@spfn/cms`, `@spfn/monitor`,
@@ -0,0 +1,134 @@
1
+ /**
2
+ * `spfn.config.js` — the app's serving shape, read by both the CLI and the server.
3
+ *
4
+ * The file has existed since `spfn init` started writing it, and until now
5
+ * nothing read it back. It is the one committed place that describes how an app
6
+ * is served, which makes it the right home for the ports: an app that wants a
7
+ * different port says so once here instead of repeating the number across its
8
+ * `server.config.ts`, Dockerfile, compose file, `next.config.ts` and env
9
+ * example, where nothing checks that the copies still agree.
10
+ *
11
+ * This module is deliberately free of side effects. `@spfn/core/config`
12
+ * validates the whole environment schema the moment it is imported, which is
13
+ * fine inside a server and wrong inside a CLI that has not been handed an
14
+ * app's environment yet.
15
+ *
16
+ * @module app-config
17
+ */
18
+ /**
19
+ * Ports the app is served on.
20
+ *
21
+ * Two names because two processes are started. Next.js reads `PORT` as its own,
22
+ * so the SPFN server cannot claim that name without the two colliding whenever
23
+ * they run together.
24
+ */
25
+ interface SpfnPorts {
26
+ /** Next.js frontend. Passed to `next` as `-p`. */
27
+ next?: number;
28
+ /** SPFN API server. */
29
+ server?: number;
30
+ }
31
+ /**
32
+ * Where the app's own environment schema lives.
33
+ *
34
+ * Read by the CLI (`spfn env`, `spfn secret`), which cannot otherwise find an
35
+ * app's variables: a package's schema sits at `<package>/config`, an app's
36
+ * sits wherever the app put it.
37
+ */
38
+ interface SpfnEnvConfig {
39
+ /**
40
+ * Modules that export `envSchema`, as paths relative to the project root —
41
+ * e.g. `['src/server/config/env.config.ts']`. TypeScript and the
42
+ * tsconfig path aliases it imports through are supported.
43
+ */
44
+ schemas?: string[];
45
+ /** What `spfn env audit` scans. */
46
+ audit?: SpfnEnvAuditConfig;
47
+ }
48
+ /**
49
+ * The files `spfn env audit` reads, as globs relative to the project root.
50
+ *
51
+ * `node_modules`, build output, `*.d.ts` files and symbolic links are never
52
+ * scanned, whatever the globs say.
53
+ */
54
+ interface SpfnEnvAuditConfig {
55
+ /**
56
+ * Directories or globs to scan — e.g. `['src', 'scripts/*.ts']`.
57
+ *
58
+ * @default ['src']
59
+ */
60
+ include?: string[];
61
+ /**
62
+ * Directories or globs to leave out — e.g. `['src/legacy/**']`. A file left
63
+ * out may read `process.env` directly, and names it reads do not count as read.
64
+ */
65
+ ignore?: string[];
66
+ }
67
+ interface SpfnAppConfig {
68
+ ports?: SpfnPorts;
69
+ /** Host the SPFN API server binds. */
70
+ host?: string;
71
+ /** The app's environment schema modules, and what `spfn env audit` scans. */
72
+ env?: SpfnEnvConfig;
73
+ /** Deployment settings — untouched by this module, kept so the type is whole. */
74
+ [key: string]: unknown;
75
+ }
76
+ /**
77
+ * The single place each default exists.
78
+ *
79
+ * Defaults live at the bottom of the chain and nowhere else. A default declared
80
+ * at an input layer — a commander option, a generated entry file, an env schema
81
+ * — cannot be told apart from a value someone supplied, so it silently outranks
82
+ * whatever is below it. Three separate defects in this repository came from
83
+ * exactly that, including an env schema default that forced the environment to
84
+ * be consulted last and made an injected port unreachable.
85
+ */
86
+ declare const PORT_DEFAULTS: {
87
+ readonly next: 3790;
88
+ readonly server: 8790;
89
+ };
90
+ declare const HOST_DEFAULT = "localhost";
91
+ /**
92
+ * Read `spfn.config.js` from an app directory.
93
+ *
94
+ * Returns an empty object when there is no file, and also when the file cannot
95
+ * be imported — a malformed deployment config must not stop a server from
96
+ * booting. The caller decides whether the absence is worth reporting.
97
+ */
98
+ declare function loadAppConfig(cwd?: string): Promise<SpfnAppConfig>;
99
+ /**
100
+ * The port each process binds, given a loaded config and the environment.
101
+ *
102
+ * Three layers, in this order, and no more: environment variable, then
103
+ * `spfn.config.js`, then the default.
104
+ */
105
+ declare function resolvePorts(config: SpfnAppConfig, env?: NodeJS.ProcessEnv): {
106
+ next: number;
107
+ server: number;
108
+ };
109
+ /**
110
+ * The host the SPFN server binds, on the same three layers.
111
+ *
112
+ * `localhost` by default: a container states `SPFN_HOST=0.0.0.0` in its own
113
+ * files, where that decision belongs, rather than every developer machine
114
+ * publishing a dev server to its network.
115
+ */
116
+ declare function resolveHost(config: SpfnAppConfig, env?: NodeJS.ProcessEnv): string;
117
+ /**
118
+ * Where the SPFN server binds, including the address a server config may still
119
+ * carry through `.port()` / `.host()`.
120
+ *
121
+ * Those two are deprecated and sit between `spfn.config.js` and the default for
122
+ * one release, so an app that has not moved yet keeps the address it had. Once
123
+ * they are removed this collapses back to {@link resolvePorts} and
124
+ * {@link resolveHost}.
125
+ */
126
+ declare function resolveServerAddress(config: SpfnAppConfig, deprecated?: {
127
+ port?: number;
128
+ host?: string;
129
+ }, env?: NodeJS.ProcessEnv): {
130
+ port: number;
131
+ host: string;
132
+ };
133
+
134
+ export { HOST_DEFAULT, PORT_DEFAULTS, type SpfnAppConfig, type SpfnEnvAuditConfig, type SpfnEnvConfig, type SpfnPorts, loadAppConfig, resolveHost, resolvePorts, resolveServerAddress };
@@ -0,0 +1,58 @@
1
+ import { existsSync } from 'fs';
2
+ import { pathToFileURL } from 'url';
3
+ import { join } from 'path';
4
+
5
+ // src/app-config/index.ts
6
+ var PORT_DEFAULTS = {
7
+ next: 3790,
8
+ server: 8790
9
+ };
10
+ var HOST_DEFAULT = "localhost";
11
+ var CONFIG_FILE_NAMES = [
12
+ "spfn.config.js",
13
+ "spfn.config.mjs"
14
+ ];
15
+ async function loadAppConfig(cwd = process.cwd()) {
16
+ for (const fileName of CONFIG_FILE_NAMES) {
17
+ const fullPath = join(cwd, fileName);
18
+ if (!existsSync(fullPath)) {
19
+ continue;
20
+ }
21
+ try {
22
+ const module = await import(pathToFileURL(fullPath).href);
23
+ return module.default ?? {};
24
+ } catch (error) {
25
+ console.warn(
26
+ `\u26A0\uFE0F ${fileName} could not be imported \u2014 falling back to defaults for ports and host. ${error instanceof Error ? error.message : String(error)}`
27
+ );
28
+ return {};
29
+ }
30
+ }
31
+ return {};
32
+ }
33
+ function resolvePorts(config, env = process.env) {
34
+ return {
35
+ next: readPort(env.NEXT_PORT) ?? config.ports?.next ?? PORT_DEFAULTS.next,
36
+ server: readPort(env.SPFN_PORT) ?? config.ports?.server ?? PORT_DEFAULTS.server
37
+ };
38
+ }
39
+ function resolveHost(config, env = process.env) {
40
+ return env.SPFN_HOST || config.host || HOST_DEFAULT;
41
+ }
42
+ function resolveServerAddress(config, deprecated = {}, env = process.env) {
43
+ return {
44
+ port: readPort(env.SPFN_PORT) ?? config.ports?.server ?? deprecated.port ?? PORT_DEFAULTS.server,
45
+ host: env.SPFN_HOST || config.host || deprecated.host || HOST_DEFAULT
46
+ };
47
+ }
48
+ function readPort(value) {
49
+ if (!value) {
50
+ return void 0;
51
+ }
52
+ const port = Number(value);
53
+ return Number.isInteger(port) && port > 0 && port < 65536 ? port : void 0;
54
+ }
55
+
56
+ export { HOST_DEFAULT, PORT_DEFAULTS, loadAppConfig, resolveHost, resolvePorts, resolveServerAddress };
57
+ //# sourceMappingURL=index.js.map
58
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/app-config/index.ts"],"names":[],"mappings":";;;;;AAwGO,IAAM,aAAA,GAAgB;AAAA,EACzB,IAAA,EAAM,IAAA;AAAA,EACN,MAAA,EAAQ;AACZ;AAEO,IAAM,YAAA,GAAe;AAE5B,IAAM,iBAAA,GAAoB;AAAA,EACtB,gBAAA;AAAA,EACA;AACJ,CAAA;AASA,eAAsB,aAAA,CAAc,GAAA,GAAc,OAAA,CAAQ,GAAA,EAAI,EAC9D;AACI,EAAA,KAAA,MAAW,YAAY,iBAAA,EACvB;AACI,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,EAAK,QAAQ,CAAA;AAEnC,IAAA,IAAI,CAAC,UAAA,CAAW,QAAQ,CAAA,EACxB;AACI,MAAA;AAAA,IACJ;AAEA,IAAA,IACA;AAGI,MAAA,MAAM,MAAA,GAAS,MAAM,OAAO,aAAA,CAAc,QAAQ,CAAA,CAAE,IAAA,CAAA;AAEpD,MAAA,OAAQ,MAAA,CAAO,WAAW,EAAC;AAAA,IAC/B,SACO,KAAA,EACP;AAQI,MAAA,OAAA,CAAQ,IAAA;AAAA,QACJ,CAAA,cAAA,EAAO,QAAQ,CAAA,2EAAA,EACU,KAAA,YAAiB,QAAQ,KAAA,CAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,OACnF;AAEA,MAAA,OAAO,EAAC;AAAA,IACZ;AAAA,EACJ;AAEA,EAAA,OAAO,EAAC;AACZ;AAQO,SAAS,YAAA,CACZ,MAAA,EACA,GAAA,GAAyB,OAAA,CAAQ,GAAA,EAErC;AACI,EAAA,OAAO;AAAA,IACH,IAAA,EAAM,SAAS,GAAA,CAAI,SAAS,KAAK,MAAA,CAAO,KAAA,EAAO,QAAQ,aAAA,CAAc,IAAA;AAAA,IACrE,MAAA,EAAQ,SAAS,GAAA,CAAI,SAAS,KAAK,MAAA,CAAO,KAAA,EAAO,UAAU,aAAA,CAAc;AAAA,GAC7E;AACJ;AASO,SAAS,WAAA,CACZ,MAAA,EACA,GAAA,GAAyB,OAAA,CAAQ,GAAA,EAErC;AACI,EAAA,OAAO,GAAA,CAAI,SAAA,IAAa,MAAA,CAAO,IAAA,IAAQ,YAAA;AAC3C;AAWO,SAAS,qBACZ,MAAA,EACA,UAAA,GAA+C,EAAC,EAChD,GAAA,GAAyB,QAAQ,GAAA,EAErC;AACI,EAAA,OAAO;AAAA,IACH,IAAA,EAAM,QAAA,CAAS,GAAA,CAAI,SAAS,CAAA,IACrB,OAAO,KAAA,EAAO,MAAA,IACd,UAAA,CAAW,IAAA,IACX,aAAA,CAAc,MAAA;AAAA,IACrB,MAAM,GAAA,CAAI,SAAA,IACH,MAAA,CAAO,IAAA,IACP,WAAW,IAAA,IACX;AAAA,GACX;AACJ;AAEA,SAAS,SAAS,KAAA,EAClB;AACI,EAAA,IAAI,CAAC,KAAA,EACL;AACI,IAAA,OAAO,MAAA;AAAA,EACX;AAEA,EAAA,MAAM,IAAA,GAAO,OAAO,KAAK,CAAA;AAEzB,EAAA,OAAO,MAAA,CAAO,UAAU,IAAI,CAAA,IAAK,OAAO,CAAA,IAAK,IAAA,GAAO,QAAQ,IAAA,GAAO,MAAA;AACvE","file":"index.js","sourcesContent":["/**\n * `spfn.config.js` — the app's serving shape, read by both the CLI and the server.\n *\n * The file has existed since `spfn init` started writing it, and until now\n * nothing read it back. It is the one committed place that describes how an app\n * is served, which makes it the right home for the ports: an app that wants a\n * different port says so once here instead of repeating the number across its\n * `server.config.ts`, Dockerfile, compose file, `next.config.ts` and env\n * example, where nothing checks that the copies still agree.\n *\n * This module is deliberately free of side effects. `@spfn/core/config`\n * validates the whole environment schema the moment it is imported, which is\n * fine inside a server and wrong inside a CLI that has not been handed an\n * app's environment yet.\n *\n * @module app-config\n */\n\nimport { existsSync } from 'fs';\nimport { pathToFileURL } from 'url';\nimport { join } from 'path';\n\n/**\n * Ports the app is served on.\n *\n * Two names because two processes are started. Next.js reads `PORT` as its own,\n * so the SPFN server cannot claim that name without the two colliding whenever\n * they run together.\n */\nexport interface SpfnPorts\n{\n /** Next.js frontend. Passed to `next` as `-p`. */\n next?: number;\n\n /** SPFN API server. */\n server?: number;\n}\n\n/**\n * Where the app's own environment schema lives.\n *\n * Read by the CLI (`spfn env`, `spfn secret`), which cannot otherwise find an\n * app's variables: a package's schema sits at `<package>/config`, an app's\n * sits wherever the app put it.\n */\nexport interface SpfnEnvConfig\n{\n /**\n * Modules that export `envSchema`, as paths relative to the project root —\n * e.g. `['src/server/config/env.config.ts']`. TypeScript and the\n * tsconfig path aliases it imports through are supported.\n */\n schemas?: string[];\n\n /** What `spfn env audit` scans. */\n audit?: SpfnEnvAuditConfig;\n}\n\n/**\n * The files `spfn env audit` reads, as globs relative to the project root.\n *\n * `node_modules`, build output, `*.d.ts` files and symbolic links are never\n * scanned, whatever the globs say.\n */\nexport interface SpfnEnvAuditConfig\n{\n /**\n * Directories or globs to scan — e.g. `['src', 'scripts/*.ts']`.\n *\n * @default ['src']\n */\n include?: string[];\n\n /**\n * Directories or globs to leave out — e.g. `['src/legacy/**']`. A file left\n * out may read `process.env` directly, and names it reads do not count as read.\n */\n ignore?: string[];\n}\n\nexport interface SpfnAppConfig\n{\n ports?: SpfnPorts;\n\n /** Host the SPFN API server binds. */\n host?: string;\n\n /** The app's environment schema modules, and what `spfn env audit` scans. */\n env?: SpfnEnvConfig;\n\n /** Deployment settings — untouched by this module, kept so the type is whole. */\n [key: string]: unknown;\n}\n\n/**\n * The single place each default exists.\n *\n * Defaults live at the bottom of the chain and nowhere else. A default declared\n * at an input layer — a commander option, a generated entry file, an env schema\n * — cannot be told apart from a value someone supplied, so it silently outranks\n * whatever is below it. Three separate defects in this repository came from\n * exactly that, including an env schema default that forced the environment to\n * be consulted last and made an injected port unreachable.\n */\nexport const PORT_DEFAULTS = {\n next: 3790,\n server: 8790,\n} as const;\n\nexport const HOST_DEFAULT = 'localhost';\n\nconst CONFIG_FILE_NAMES = [\n 'spfn.config.js',\n 'spfn.config.mjs',\n] as const;\n\n/**\n * Read `spfn.config.js` from an app directory.\n *\n * Returns an empty object when there is no file, and also when the file cannot\n * be imported — a malformed deployment config must not stop a server from\n * booting. The caller decides whether the absence is worth reporting.\n */\nexport async function loadAppConfig(cwd: string = process.cwd()): Promise<SpfnAppConfig>\n{\n for (const fileName of CONFIG_FILE_NAMES)\n {\n const fullPath = join(cwd, fileName);\n\n if (!existsSync(fullPath))\n {\n continue;\n }\n\n try\n {\n // A file URL, not a path: on Windows an absolute path is not a\n // valid ESM specifier, and this file is imported at runtime.\n const module = await import(pathToFileURL(fullPath).href);\n\n return (module.default ?? {}) as SpfnAppConfig;\n }\n catch (error)\n {\n // Falling back to defaults, and saying so. A file that exists and\n // cannot be imported is a typo, not an absence — silence would send\n // the server to port 8790 while its own config named another, and\n // the only symptom would be a port nobody chose.\n //\n // console, not the server logger: this runs inside the CLI too,\n // before any logger is configured.\n console.warn(\n `⚠️ ${fileName} could not be imported — falling back to defaults `\n + `for ports and host. ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return {};\n }\n }\n\n return {};\n}\n\n/**\n * The port each process binds, given a loaded config and the environment.\n *\n * Three layers, in this order, and no more: environment variable, then\n * `spfn.config.js`, then the default.\n */\nexport function resolvePorts(\n config: SpfnAppConfig,\n env: NodeJS.ProcessEnv = process.env,\n): { next: number; server: number }\n{\n return {\n next: readPort(env.NEXT_PORT) ?? config.ports?.next ?? PORT_DEFAULTS.next,\n server: readPort(env.SPFN_PORT) ?? config.ports?.server ?? PORT_DEFAULTS.server,\n };\n}\n\n/**\n * The host the SPFN server binds, on the same three layers.\n *\n * `localhost` by default: a container states `SPFN_HOST=0.0.0.0` in its own\n * files, where that decision belongs, rather than every developer machine\n * publishing a dev server to its network.\n */\nexport function resolveHost(\n config: SpfnAppConfig,\n env: NodeJS.ProcessEnv = process.env,\n): string\n{\n return env.SPFN_HOST || config.host || HOST_DEFAULT;\n}\n\n/**\n * Where the SPFN server binds, including the address a server config may still\n * carry through `.port()` / `.host()`.\n *\n * Those two are deprecated and sit between `spfn.config.js` and the default for\n * one release, so an app that has not moved yet keeps the address it had. Once\n * they are removed this collapses back to {@link resolvePorts} and\n * {@link resolveHost}.\n */\nexport function resolveServerAddress(\n config: SpfnAppConfig,\n deprecated: { port?: number; host?: string } = {},\n env: NodeJS.ProcessEnv = process.env,\n): { port: number; host: string }\n{\n return {\n port: readPort(env.SPFN_PORT)\n ?? config.ports?.server\n ?? deprecated.port\n ?? PORT_DEFAULTS.server,\n host: env.SPFN_HOST\n || config.host\n || deprecated.host\n || HOST_DEFAULT,\n };\n}\n\nfunction readPort(value: string | undefined): number | undefined\n{\n if (!value)\n {\n return undefined;\n }\n\n const port = Number(value);\n\n return Number.isInteger(port) && port > 0 && port < 65536 ? port : undefined;\n}\n"]}