@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/dist/ops/index.js CHANGED
@@ -7,6 +7,8 @@ var RouteBuilder = class _RouteBuilder {
7
7
  _middlewares;
8
8
  _skipMiddlewares;
9
9
  _contract;
10
+ _effect;
11
+ _summary;
10
12
  /**
11
13
  * Create a new RouteBuilder with copied properties and optional overrides
12
14
  */
@@ -19,6 +21,8 @@ var RouteBuilder = class _RouteBuilder {
19
21
  builder._middlewares = overrides?.middlewares ?? this._middlewares;
20
22
  builder._skipMiddlewares = overrides?.skipMiddlewares ?? this._skipMiddlewares;
21
23
  builder._contract = overrides?.contract ?? this._contract;
24
+ builder._effect = overrides?.effect ?? this._effect;
25
+ builder._summary = overrides?.summary ?? this._summary;
22
26
  return builder;
23
27
  }
24
28
  /**
@@ -138,7 +142,7 @@ var RouteBuilder = class _RouteBuilder {
138
142
  * @example
139
143
  * ```ts
140
144
  * // Skip specific middlewares
141
- * route.get('/health')
145
+ * route.get('/status')
142
146
  * .skip(['auth', 'rateLimit'])
143
147
  * .handler(async (c) => c.json({ status: 'ok' }));
144
148
  *
@@ -189,6 +193,49 @@ var RouteBuilder = class _RouteBuilder {
189
193
  contract(contract) {
190
194
  return this.clone({ contract });
191
195
  }
196
+ /**
197
+ * Declare what invoking this route does
198
+ *
199
+ * Read by a command surface (`@spfn/core/surface`, `@spfn/core/ops`),
200
+ * which announces it in its manifest so a machine caller can tell a read
201
+ * from a write before it calls — `spfn ops call` asks for `--yes` before a
202
+ * `destructive` command. A surface built with `defineSurface` refuses an
203
+ * app command that does not declare one; on `/_ops` it is optional.
204
+ *
205
+ * Nothing else reads it: codegen, the route map, and the contract are
206
+ * unaffected, and a route outside any surface simply carries it.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * export const pageAdd = app.route.post('/pages')
211
+ * .input({ body: PageAddBody })
212
+ * .effect('write')
213
+ * .summary('Add a page to the blueprint')
214
+ * .handler(async (c) => { ... });
215
+ * ```
216
+ */
217
+ effect(effect) {
218
+ return this.clone({ effect });
219
+ }
220
+ /**
221
+ * Describe this route in one line for a command surface's manifest
222
+ *
223
+ * A surface announces it beside the command in `spfn ops list` and
224
+ * `--describe`, and refuses one that is empty or longer than 500
225
+ * characters. Codegen, the route map, and the contract ignore it. On a
226
+ * module command the module's own summary wins.
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * export const pageAdd = app.route.post('/pages')
231
+ * .effect('write')
232
+ * .summary('Add a page to the blueprint')
233
+ * .handler(async (c) => { ... });
234
+ * ```
235
+ */
236
+ summary(summary) {
237
+ return this.clone({ summary });
238
+ }
192
239
  /**
193
240
  * Define handler function
194
241
  *
@@ -244,6 +291,8 @@ var RouteBuilder = class _RouteBuilder {
244
291
  middlewares: this._middlewares,
245
292
  skipMiddlewares: this._skipMiddlewares,
246
293
  contract: this._contract,
294
+ ...this._effect !== void 0 ? { effect: this._effect } : {},
295
+ ...this._summary !== void 0 ? { summary: this._summary } : {},
247
296
  handler: fn,
248
297
  _input: {},
249
298
  _interceptor: {},
@@ -268,43 +317,33 @@ var route = {
268
317
  };
269
318
 
270
319
  // src/route/router.ts
271
- function createRouterInstance(routes, packageRouters = [], globalMiddlewares = [], contractVersion = null) {
320
+ function createRouterInstance(state) {
272
321
  return {
273
- routes,
274
- _routes: routes,
275
- _packageRouters: packageRouters,
276
- _globalMiddlewares: globalMiddlewares,
277
- _contractVersion: contractVersion,
322
+ routes: state.routes,
323
+ _routes: state.routes,
324
+ _packageRouters: state.packageRouters,
325
+ _globalMiddlewares: state.globalMiddlewares,
326
+ _contractVersion: state.contractVersion,
327
+ _publishesRouteMap: state.publishesRouteMap,
278
328
  packages(routers) {
279
- const newPackageRouters = [...this._packageRouters, ...routers];
329
+ const newPackageRouters = [...state.packageRouters, ...routers];
280
330
  for (const pkgRouter of routers) {
281
331
  if (pkgRouter._packageRouters?.length > 0) {
282
332
  newPackageRouters.push(...pkgRouter._packageRouters);
283
333
  }
284
334
  }
285
- return createRouterInstance(
286
- this.routes,
287
- newPackageRouters,
288
- this._globalMiddlewares,
289
- this._contractVersion
290
- );
335
+ assertDistinctSurfaces(newPackageRouters);
336
+ return createRouterInstance({ ...state, packageRouters: newPackageRouters });
291
337
  },
292
338
  use(middlewares) {
293
- return createRouterInstance(
294
- this.routes,
295
- this._packageRouters,
296
- [...this._globalMiddlewares, ...middlewares],
297
- this._contractVersion
298
- );
339
+ return createRouterInstance({
340
+ ...state,
341
+ globalMiddlewares: [...state.globalMiddlewares, ...middlewares]
342
+ });
299
343
  },
300
344
  contractVersion(version) {
301
345
  assertContractVersion(version);
302
- return createRouterInstance(
303
- this.routes,
304
- this._packageRouters,
305
- this._globalMiddlewares,
306
- version
307
- );
346
+ return createRouterInstance({ ...state, contractVersion: version });
308
347
  }
309
348
  };
310
349
  }
@@ -315,17 +354,50 @@ function assertContractVersion(version) {
315
354
  );
316
355
  }
317
356
  }
318
- function defineRouter(routes) {
319
- return createRouterInstance(routes);
357
+ function assertDistinctSurfaces(packageRouters) {
358
+ const namespaces = /* @__PURE__ */ new Set();
359
+ for (const router of packageRouters) {
360
+ const namespace = router._surfaceNamespace;
361
+ if (namespace === void 0) {
362
+ continue;
363
+ }
364
+ if (namespaces.has(namespace)) {
365
+ throw new Error(
366
+ `.packages() mounts two command surfaces on "${namespace}". Both serve ${namespace}/_manifest, so the second one's commands would answer while no manifest lists them. Mount one router per namespace.`
367
+ );
368
+ }
369
+ namespaces.add(namespace);
370
+ }
371
+ }
372
+ function defineUnmappedRouter(routes) {
373
+ return createRouterInstance({
374
+ routes,
375
+ packageRouters: [],
376
+ globalMiddlewares: [],
377
+ contractVersion: null,
378
+ publishesRouteMap: false
379
+ });
320
380
  }
321
381
 
322
- // src/ops/manifest.ts
323
- var OpsRouterError = class extends Error {
382
+ // src/surface/error.ts
383
+ var SurfaceError = class extends Error {
324
384
  constructor(message) {
325
385
  super(message);
326
- this.name = "OpsRouterError";
386
+ this.name = "SurfaceError";
327
387
  }
328
388
  };
389
+
390
+ // src/surface/wording.ts
391
+ var SURFACE_WORDING = {
392
+ noun: "surface",
393
+ builder: "`<surface>.route`",
394
+ factory: "defineSurface"
395
+ };
396
+ function capitalized(noun) {
397
+ return noun.charAt(0).toUpperCase() + noun.slice(1);
398
+ }
399
+
400
+ // src/surface/manifest.ts
329
401
  function isRouter(value) {
330
402
  return value !== null && typeof value === "object" && "routes" in value && "_routes" in value;
331
403
  }
@@ -349,152 +421,621 @@ function toCommandInput(input) {
349
421
  }
350
422
  return sections;
351
423
  }
352
- function collectOpsCommands(routes) {
424
+ function collectSurfaceCommands(routes, wording = SURFACE_WORDING) {
353
425
  const commands = [];
354
- visit(routes, commands, /* @__PURE__ */ new Map());
426
+ visit(routes, commands, /* @__PURE__ */ new Map(), wording);
355
427
  commands.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
356
428
  return commands;
357
429
  }
358
- function visit(routes, commands, claimed) {
430
+ function visit(routes, commands, claimed, wording) {
359
431
  for (const [name, entry] of Object.entries(routes)) {
360
432
  if (isRouter(entry)) {
361
- visit(entry.routes, commands, claimed);
433
+ visit(entry.routes, commands, claimed, wording);
362
434
  continue;
363
435
  }
364
436
  if (!isRouteDef(entry) || !entry.method || !entry.path) {
365
437
  continue;
366
438
  }
367
- assertUnclaimedName(name, entry.path, claimed);
439
+ assertUnclaimedName(name, entry.path, claimed, wording);
368
440
  commands.push({
369
441
  name,
370
442
  method: entry.method,
371
443
  path: entry.path,
444
+ ...entry.summary !== void 0 ? { summary: entry.summary } : {},
445
+ ...entry.effect !== void 0 ? { effect: entry.effect } : {},
372
446
  input: toCommandInput(entry.input)
373
447
  });
374
448
  }
375
449
  }
376
- function assertUnclaimedName(name, path, claimed) {
450
+ function assertUnclaimedName(name, path, claimed, wording) {
377
451
  const existing = claimed.get(name);
378
452
  if (existing !== void 0) {
379
- throw new OpsRouterError(
380
- `Two ops routes are named "${name}" ("${existing}" and "${path}"). Command names are flattened across nested routers, so each must be unique for the CLI to resolve the one an operator asked for.`
453
+ throw new SurfaceError(
454
+ `Two ${wording.noun} routes are named "${name}" ("${existing}" and "${path}"). Command names are flattened across nested routers, so each must be unique for a client to resolve the one its caller asked for.`
381
455
  );
382
456
  }
383
457
  claimed.set(name, path);
384
458
  }
385
459
 
386
- // src/ops/create-ops-router.ts
387
- var OPS_PATH_PREFIX = "/_ops/";
388
- var OPS_MANIFEST_PATH = "/_ops/_manifest";
389
- var OPS_MANIFEST_NAME = "getOpsManifest";
460
+ // src/surface/route-overlap.ts
461
+ function routeSegments(path) {
462
+ return path.split("/").slice(1).map((raw) => {
463
+ if (raw === "*" || raw.endsWith("*")) {
464
+ return { kind: "wildcard", value: raw, optional: true };
465
+ }
466
+ if (raw.startsWith(":")) {
467
+ return {
468
+ kind: "parameter",
469
+ value: raw.slice(1).replace(/\?$/, ""),
470
+ optional: raw.endsWith("?")
471
+ };
472
+ }
473
+ return { kind: "static", value: raw, optional: false };
474
+ });
475
+ }
476
+ function customPattern(parameter) {
477
+ const openingBrace = parameter.indexOf("{");
478
+ return openingBrace >= 0 && parameter.endsWith("}") ? parameter.slice(openingBrace + 1, -1) : null;
479
+ }
480
+ function parameterAccepts(parameter, value) {
481
+ const pattern = customPattern(parameter);
482
+ if (pattern === null) {
483
+ return value.length > 0 && !value.includes("/");
484
+ }
485
+ try {
486
+ return new RegExp(`^(?:${pattern})$`).test(value);
487
+ } catch {
488
+ return true;
489
+ }
490
+ }
491
+ function remainingStaticPath(segments, from) {
492
+ const remaining = segments.slice(from);
493
+ return remaining.every((segment) => segment.kind === "static") ? remaining.map((segment) => segment.value).join("/") : null;
494
+ }
495
+ function routePatternsOverlap(firstPath, secondPath) {
496
+ const first = routeSegments(firstPath);
497
+ const second = routeSegments(secondPath);
498
+ const length = Math.max(first.length, second.length);
499
+ for (let index = 0; index < length; index++) {
500
+ const left = first[index];
501
+ const right = second[index];
502
+ if (!left || !right) {
503
+ const remaining = left ? first.slice(index) : second.slice(index);
504
+ return remaining.every((segment) => segment.optional || segment.kind === "wildcard");
505
+ }
506
+ if (left.kind === "wildcard" || right.kind === "wildcard") {
507
+ return true;
508
+ }
509
+ if (left.kind === "static" && right.kind === "static") {
510
+ if (left.value !== right.value) {
511
+ return false;
512
+ }
513
+ continue;
514
+ }
515
+ if (left.kind === "parameter" && right.kind === "static") {
516
+ const remaining = remainingStaticPath(second, index);
517
+ if (customPattern(left.value) !== null && remaining !== null && parameterAccepts(left.value, remaining)) {
518
+ return true;
519
+ }
520
+ if (!parameterAccepts(left.value, right.value)) {
521
+ return customPattern(left.value) !== null && remaining === null;
522
+ }
523
+ if (customPattern(left.value) !== null && first.length !== second.length) {
524
+ return true;
525
+ }
526
+ continue;
527
+ }
528
+ if (left.kind === "static" && right.kind === "parameter") {
529
+ const remaining = remainingStaticPath(first, index);
530
+ if (customPattern(right.value) !== null && remaining !== null && parameterAccepts(right.value, remaining)) {
531
+ return true;
532
+ }
533
+ if (!parameterAccepts(right.value, left.value)) {
534
+ return customPattern(right.value) !== null && remaining === null;
535
+ }
536
+ if (customPattern(right.value) !== null && first.length !== second.length) {
537
+ return true;
538
+ }
539
+ continue;
540
+ }
541
+ return true;
542
+ }
543
+ return true;
544
+ }
545
+
546
+ // src/surface/module.ts
547
+ var MODULE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
548
+ var COMMAND_NAME = /^[A-Za-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)*$/;
549
+ var CONTRACT_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)*$/;
550
+ var EFFECTS = /* @__PURE__ */ new Set(["read", "write", "destructive"]);
551
+ var PATH_BASE = "https://spfn.invalid";
552
+ function isSurfaceEffect(value) {
553
+ return EFFECTS.has(value);
554
+ }
555
+ function assertText(label, value) {
556
+ if (typeof value !== "string" || value.trim().length === 0) {
557
+ throw new SurfaceError(`${label} must be a non-empty string.`);
558
+ }
559
+ }
560
+ function assertStableModulePath(at, moduleId, commandName, path) {
561
+ const label = `${at.label} command "${moduleId}.${commandName}" path "${path}"`;
562
+ const transportPath = path.replace(/[{}?#]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
563
+ let url;
564
+ try {
565
+ url = new URL(transportPath, PATH_BASE);
566
+ } catch {
567
+ throw new SurfaceError(`${label} is not a valid URL path.`);
568
+ }
569
+ if (url.origin !== PATH_BASE || url.search !== "" || url.hash !== "" || url.pathname !== transportPath) {
570
+ throw new SurfaceError(`${label} is not a stable plain absolute path.`);
571
+ }
572
+ const slashCount = (path.match(/\//g) ?? []).length;
573
+ let decoded = path;
574
+ for (let depth = 0; depth < 8; depth++) {
575
+ let next;
576
+ try {
577
+ next = decodeURIComponent(decoded);
578
+ } catch {
579
+ throw new SurfaceError(`${label} contains malformed percent encoding.`);
580
+ }
581
+ if (next.includes("\\") || (next.match(/\//g) ?? []).length !== slashCount || next.split("/").some((segment) => segment === "." || segment === "..")) {
582
+ throw new SurfaceError(`${label} contains encoded path separators or dot segments.`);
583
+ }
584
+ if (next === decoded) {
585
+ return;
586
+ }
587
+ decoded = next;
588
+ }
589
+ throw new SurfaceError(`${label} uses too many percent-encoding layers.`);
590
+ }
591
+ function assertCliCallableModulePath(at, moduleId, commandName, path) {
592
+ const unsupported = path.split("/").slice(1).find((segment) => segment === "*" || segment.includes("*") || (segment.startsWith(":") ? !/^:[A-Za-z0-9_]+$/.test(segment) : !/^[A-Za-z0-9._~-]+$/.test(segment)));
593
+ if (unsupported !== void 0) {
594
+ throw new SurfaceError(
595
+ `${at.label} command "${moduleId}.${commandName}" path segment "${unsupported}" is not CLI-callable. Module routes support URL-safe static segments and simple :name parameters only; optional, wildcard, and custom-regex parameters are not supported.`
596
+ );
597
+ }
598
+ }
599
+ function assertCommand(at, moduleId, name, command) {
600
+ if (!COMMAND_NAME.test(name)) {
601
+ throw new SurfaceError(
602
+ `${at.label} module "${moduleId}" has invalid command name "${name}". Use dot-separated alphanumeric names.`
603
+ );
604
+ }
605
+ assertText(`${at.label} command "${moduleId}.${name}" summary`, command?.summary);
606
+ if (!EFFECTS.has(command?.effect)) {
607
+ throw new SurfaceError(
608
+ `${at.label} command "${moduleId}.${name}" has invalid effect ${JSON.stringify(command?.effect)}.`
609
+ );
610
+ }
611
+ if (!Array.isArray(command?.scopes) || command.scopes.length === 0 || command.scopes.some((scope) => typeof scope !== "string" || scope.trim().length === 0)) {
612
+ throw new SurfaceError(`${at.label} command "${moduleId}.${name}" must declare at least one non-empty scope.`);
613
+ }
614
+ const route2 = command?.route;
615
+ if (!route2 || typeof route2.handler !== "function" || !route2.method || !route2.path) {
616
+ throw new SurfaceError(`${at.label} command "${moduleId}.${name}" must carry a complete route.`);
617
+ }
618
+ assertStableModulePath(at, moduleId, name, route2.path);
619
+ assertCliCallableModulePath(at, moduleId, name, route2.path);
620
+ const modulePath = `${at.namespace}/${moduleId}/`;
621
+ if (!route2.path.startsWith(modulePath)) {
622
+ throw new SurfaceError(
623
+ `${at.label} command "${moduleId}.${name}" is at "${route2.path}", outside "${modulePath}". A module mounted on "${at.namespace}" keeps every command under "${modulePath}".`
624
+ );
625
+ }
626
+ if (route2.path.split("/").includes("..")) {
627
+ throw new SurfaceError(`${at.label} command "${moduleId}.${name}" path climbs out of its module namespace.`);
628
+ }
629
+ }
630
+ function validateSurfaceModule(module, namespace, wording = SURFACE_WORDING) {
631
+ const at = { namespace, label: capitalized(wording.noun) };
632
+ if (!MODULE_ID.test(module?.id ?? "")) {
633
+ throw new SurfaceError(
634
+ `${at.label} module id ${JSON.stringify(module?.id)} is invalid. Use lower-kebab-case.`
635
+ );
636
+ }
637
+ assertText(`${at.label} module "${module.id}" source`, module.source);
638
+ assertText(`${at.label} module "${module.id}" summary`, module.summary);
639
+ if (!CONTRACT_VERSION.test(module.contractVersion)) {
640
+ throw new SurfaceError(
641
+ `${at.label} module "${module.id}" contractVersion must be a semantic version.`
642
+ );
643
+ }
644
+ if (!module.commands || typeof module.commands !== "object" || Array.isArray(module.commands)) {
645
+ throw new SurfaceError(`${at.label} module "${module.id}" commands must be an object.`);
646
+ }
647
+ const signatures = /* @__PURE__ */ new Map();
648
+ const claimedRoutes = [];
649
+ for (const [name, command] of Object.entries(module.commands)) {
650
+ assertCommand(at, module.id, name, command);
651
+ const signature = `${command.route.method} ${command.route.path}`;
652
+ const existing = signatures.get(signature);
653
+ if (existing) {
654
+ throw new SurfaceError(
655
+ `${at.label} module "${module.id}" commands "${existing}" and "${name}" both use ${signature}.`
656
+ );
657
+ }
658
+ signatures.set(signature, name);
659
+ const overlapping = claimedRoutes.find((claim) => claim.method === command.route.method && routePatternsOverlap(claim.path, command.route.path));
660
+ if (overlapping) {
661
+ throw new SurfaceError(
662
+ `${at.label} module "${module.id}" commands "${overlapping.name}" and "${name}" have overlapping ${command.route.method} routes ("${overlapping.path}" and "${command.route.path}").`
663
+ );
664
+ }
665
+ claimedRoutes.push({
666
+ name,
667
+ method: command.route.method,
668
+ path: command.route.path
669
+ });
670
+ }
671
+ return module;
672
+ }
673
+
674
+ // src/surface/namespace.ts
675
+ var NAMESPACE = /^(?:\/[A-Za-z0-9_-]+)+$/;
676
+ function assertNamespace(namespace) {
677
+ if (typeof namespace !== "string" || !NAMESPACE.test(namespace)) {
678
+ throw new SurfaceError(
679
+ `Surface namespace ${JSON.stringify(namespace)} is invalid. Use an absolute path of [A-Za-z0-9_-] segments without a trailing slash, such as "/_app".`
680
+ );
681
+ }
682
+ }
683
+ function manifestPathOf(namespace) {
684
+ return `${namespace}/_manifest`;
685
+ }
686
+ function manifestNameOf(namespace) {
687
+ return `get${namespace.slice(1).replace(/_[a-z]|[A-Z_/-]/g, encodedCharacter)}Manifest`;
688
+ }
689
+ var ESCAPES = { "_": "_", "-": "d", "/": "s" };
690
+ function encodedCharacter(match) {
691
+ if (match.length === 2) {
692
+ return match.charAt(1).toUpperCase();
693
+ }
694
+ return `_${ESCAPES[match] ?? match}`;
695
+ }
696
+ function toSurfacePath(namespace, path, wording) {
697
+ const label = capitalized(wording.noun);
698
+ if (!path.startsWith("/")) {
699
+ throw new SurfaceError(
700
+ `${label} route path "${path}" must start with "/". It is appended to "${namespace}", so "${path}" would read as "${namespace}${path}".`
701
+ );
702
+ }
703
+ if (path === "/") {
704
+ throw new SurfaceError(
705
+ `${label} route path "/" names no command \u2014 "${namespace}" itself is not a command.`
706
+ );
707
+ }
708
+ return namespace + path;
709
+ }
710
+ function surfaceRouteBuilder(namespace, wording) {
711
+ const method = (name) => (path) => route[name](toSurfacePath(namespace, path, wording));
712
+ return {
713
+ get: method("get"),
714
+ post: method("post"),
715
+ put: method("put"),
716
+ patch: method("patch"),
717
+ delete: method("delete")
718
+ };
719
+ }
720
+
721
+ // src/surface/define-surface.ts
722
+ var MAX_COMMAND_SUMMARY_LENGTH = 500;
723
+ var EFFECT_METHOD = ".effect('read' | 'write' | 'destructive')";
390
724
  function isRouter2(value) {
391
725
  return value !== null && typeof value === "object" && "routes" in value && "_routes" in value;
392
726
  }
393
727
  function isRouteDef2(value) {
394
728
  return value !== null && typeof value === "object" && "handler" in value;
395
729
  }
396
- function assertOpsRoute(name, def) {
730
+ function assertSurfaceRoute(plan, name, def) {
731
+ const label = capitalized(plan.wording.noun);
397
732
  if (!def.method || !def.path) {
398
- throw new OpsRouterError(
399
- `Ops route "${name}" has no method or path. An ops command is invoked on the wire, so both are required.`
733
+ throw new SurfaceError(
734
+ `${label} route "${name}" has no method or path. A command is invoked on the wire, so both are required.`
735
+ );
736
+ }
737
+ if (!def.path.startsWith(plan.prefix)) {
738
+ throw new SurfaceError(
739
+ `${label} route "${name}" is at "${def.path}", outside "${plan.prefix}". Build ${plan.wording.noun} routes with ${plan.wording.builder} rather than \`route\` \u2014 it applies the namespace, so the path a definition carries is only the part the app owns.`
740
+ );
741
+ }
742
+ if (def.path === plan.manifestPath) {
743
+ throw new SurfaceError(
744
+ `${label} route "${name}" claims "${plan.manifestPath}", which is reserved for the manifest. The manifest is registered first, so this route would never answer.`
745
+ );
746
+ }
747
+ }
748
+ function assertCommandMetadata(plan, name, def) {
749
+ const label = `${capitalized(plan.wording.noun)} command "${name}"`;
750
+ if (def.effect === void 0 && plan.requireEffect) {
751
+ throw new SurfaceError(
752
+ `${label} declares no effect. A client reads it to decide whether to call, retry, or ask for confirmation, so ${plan.wording.factory} refuses a command without one. Declare it on the route with ${EFFECT_METHOD}.`
753
+ );
754
+ }
755
+ if (def.effect !== void 0 && !isSurfaceEffect(def.effect)) {
756
+ throw new SurfaceError(
757
+ `${label} has invalid effect ${JSON.stringify(def.effect)}. A client knows no other, so declare it with ${EFFECT_METHOD}.`
758
+ );
759
+ }
760
+ assertCommandSummary(label, def.summary);
761
+ }
762
+ function assertCommandSummary(label, summary) {
763
+ if (summary === void 0) {
764
+ return;
765
+ }
766
+ if (typeof summary !== "string" || summary.trim().length === 0) {
767
+ throw new SurfaceError(
768
+ `${label} has an empty summary. A client would list it as a command described by nothing; give .summary() one line of text, or leave it out.`
400
769
  );
401
770
  }
402
- if (!def.path.startsWith(OPS_PATH_PREFIX)) {
403
- throw new OpsRouterError(
404
- `Ops route "${name}" is at "${def.path}", outside "${OPS_PATH_PREFIX}". Build ops routes with \`opsRoute\` rather than \`route\` \u2014 it applies the namespace, so the path a definition carries is only the part the app owns.`
771
+ if (summary.length > MAX_COMMAND_SUMMARY_LENGTH) {
772
+ throw new SurfaceError(
773
+ `${label} has a summary of ${summary.length} characters, over the ${MAX_COMMAND_SUMMARY_LENGTH} a client accepts \u2014 it would drop the command's metadata and treat it as destructive. Shorten it.`
405
774
  );
406
775
  }
407
- if (def.path === OPS_MANIFEST_PATH) {
408
- throw new OpsRouterError(
409
- `Ops route "${name}" claims "${OPS_MANIFEST_PATH}", which is reserved for the manifest. The manifest is registered first, so this route would never answer.`
776
+ }
777
+ function assertModuleRouteEffect(plan, name, definition) {
778
+ const routeEffect = definition.route.effect;
779
+ if (routeEffect !== void 0 && routeEffect !== definition.effect) {
780
+ throw new SurfaceError(
781
+ `${capitalized(plan.wording.noun)} command "${name}" is declared ${JSON.stringify(definition.effect)} by its module, but its route says .effect(${JSON.stringify(routeEffect)}). The manifest announces the module's declaration, so the two cannot disagree. Drop the route's .effect() or make it match.`
410
782
  );
411
783
  }
412
784
  }
413
- function assertOpsName(name) {
414
- if (name === OPS_MANIFEST_NAME) {
415
- throw new OpsRouterError(
416
- `Ops route name "${OPS_MANIFEST_NAME}" is reserved for the manifest route.`
785
+ function assertSurfaceName(plan, name) {
786
+ if (name === plan.manifestName) {
787
+ throw new SurfaceError(
788
+ `${capitalized(plan.wording.noun)} route name "${plan.manifestName}" is reserved for the manifest route.`
417
789
  );
418
790
  }
419
791
  }
420
- function rebuildNestedRouter(name, router, auth, inherited) {
792
+ function rebuildNestedRouter(plan, name, router, commandsByName, inherited) {
421
793
  if (router._packageRouters?.length > 0) {
422
- throw new OpsRouterError(
423
- `Ops router "${name}" mounts package routers with .packages(). Their routes bypass the prefix check and the auth injection, so an ops surface cannot carry them.`
794
+ throw new SurfaceError(
795
+ `${capitalized(plan.wording.noun)} router "${name}" mounts package routers with .packages(). Their routes bypass the prefix check and the auth injection, so a surface cannot carry them.`
424
796
  );
425
797
  }
426
798
  const handedDown = [...inherited, ...router._globalMiddlewares ?? []];
427
- let rebuilt = defineRouter(
428
- secureRoutes(router.routes, auth, handedDown)
799
+ let rebuilt = defineUnmappedRouter(
800
+ secureRoutes(plan, router.routes, commandsByName, handedDown)
429
801
  );
430
802
  if (router._contractVersion) {
431
803
  rebuilt = rebuilt.contractVersion(router._contractVersion);
432
804
  }
433
805
  return rebuilt;
434
806
  }
435
- function secureRoutes(routes, auth, inherited = []) {
807
+ function secureRoutes(plan, routes, commandsByName, inherited = []) {
436
808
  const secured = {};
437
809
  for (const [name, entry] of Object.entries(routes)) {
438
- assertOpsName(name);
810
+ assertSurfaceName(plan, name);
439
811
  if (isRouter2(entry)) {
440
- secured[name] = rebuildNestedRouter(name, entry, auth, inherited);
812
+ secured[name] = rebuildNestedRouter(plan, name, entry, commandsByName, inherited);
441
813
  continue;
442
814
  }
443
815
  if (!isRouteDef2(entry)) {
444
- throw new OpsRouterError(`Ops router entry "${name}" is neither a route nor a router.`);
816
+ throw new SurfaceError(
817
+ `${capitalized(plan.wording.noun)} router entry "${name}" is neither a route nor a router.`
818
+ );
445
819
  }
446
- assertOpsRoute(name, entry);
820
+ assertSurfaceRoute(plan, name, entry);
821
+ assertCommandMetadata(plan, name, entry);
822
+ const guard = plan.authorize?.(commandsByName.get(name));
447
823
  secured[name] = {
448
824
  ...entry,
449
- middlewares: [auth, ...inherited, ...entry.middlewares ?? []]
825
+ middlewares: commandChain(plan, name, guard, [...inherited, ...entry.middlewares ?? []])
450
826
  };
451
827
  }
452
828
  return secured;
453
829
  }
454
- function createOpsRouter(routes, options) {
455
- if (!options?.auth) {
456
- throw new OpsRouterError(
457
- "createOpsRouter requires an auth middleware ({ auth: ... }). An ops surface reachable without authentication cannot be created."
830
+ function commandChain(plan, name, guard, declared) {
831
+ if (guard === void 0) {
832
+ return [plan.auth, ...declared];
833
+ }
834
+ const guardName = middlewareNameOf(guard);
835
+ if (guardName !== void 0) {
836
+ refuseGuardCollision(plan, name, guardName, declared);
837
+ }
838
+ return [plan.auth, guard, ...declared];
839
+ }
840
+ function refuseGuardCollision(plan, name, guardName, declared) {
841
+ const noun = capitalized(plan.wording.noun);
842
+ if (middlewareNameOf(plan.auth) === guardName) {
843
+ throw new SurfaceError(
844
+ `${noun} command "${name}"'s guard shares the name "${guardName}" with the surface's auth middleware. Route registration keeps one middleware per name, so the command's guard would never run. Give one of the two a distinct name.`
845
+ );
846
+ }
847
+ if (declared.some((middleware) => middlewareNameOf(middleware) === guardName)) {
848
+ throw new SurfaceError(
849
+ `${noun} command "${name}" declares a middleware named "${guardName}", the name of the guard authorize gave it. Route registration keeps one middleware per name, so the command's own guard would never run. Give one of the two a distinct name.`
850
+ );
851
+ }
852
+ }
853
+ function middlewareNameOf(middleware) {
854
+ return typeof middleware === "function" ? void 0 : middleware.name;
855
+ }
856
+ function assertModuleCommandFree(plan, command, appCommands, claimed) {
857
+ const noun = plan.wording.noun;
858
+ if (claimed.names.has(command.name)) {
859
+ throw new SurfaceError(`Two ${noun} commands are named "${command.name}".`);
860
+ }
861
+ const signature = `${command.method} ${command.path}`;
862
+ const existing = claimed.signatures.get(signature);
863
+ if (existing) {
864
+ throw new SurfaceError(
865
+ `${capitalized(noun)} commands "${existing}" and "${command.name}" both use ${signature}.`
458
866
  );
459
867
  }
868
+ const overlapping = appCommands.find((app) => app.method === command.method && routePatternsOverlap(app.path, command.path));
869
+ if (overlapping) {
870
+ throw new SurfaceError(
871
+ `App ${noun} command "${overlapping.name}" at ${command.method} ${overlapping.path} overlaps module command "${command.name}" at ${command.method} ${command.path}. Which one answers cannot depend on route registration order.`
872
+ );
873
+ }
874
+ claimed.names.add(command.name);
875
+ claimed.signatures.set(signature, command.name);
876
+ }
877
+ function compileModules(plan, appCommands) {
878
+ const compiled = { descriptors: [], commands: [], routes: {} };
879
+ const moduleIds = /* @__PURE__ */ new Set();
880
+ const claimed = {
881
+ names: new Set(appCommands.map((command) => command.name)),
882
+ signatures: new Map(appCommands.map((command) => [`${command.method} ${command.path}`, command.name]))
883
+ };
884
+ for (const rawModule of plan.modules) {
885
+ const module = validateSurfaceModule(rawModule, plan.namespace, plan.wording);
886
+ if (moduleIds.has(module.id)) {
887
+ throw new SurfaceError(`Two ${plan.wording.noun} modules use id "${module.id}".`);
888
+ }
889
+ moduleIds.add(module.id);
890
+ compiled.descriptors.push({
891
+ id: module.id,
892
+ source: module.source,
893
+ contractVersion: module.contractVersion,
894
+ summary: module.summary
895
+ });
896
+ for (const [localName, definition] of Object.entries(module.commands)) {
897
+ const command = {
898
+ name: `${module.id}.${localName}`,
899
+ module: module.id,
900
+ summary: definition.summary,
901
+ effect: definition.effect,
902
+ scopes: [...definition.scopes],
903
+ method: definition.route.method,
904
+ path: definition.route.path,
905
+ input: collectSurfaceCommands({ [localName]: definition.route }, plan.wording)[0].input
906
+ };
907
+ assertModuleRouteEffect(plan, command.name, definition);
908
+ assertModuleCommandFree(plan, command, appCommands, claimed);
909
+ compiled.commands.push(command);
910
+ compiled.routes[command.name] = { route: definition.route, command };
911
+ }
912
+ }
913
+ compiled.descriptors.sort((a, b) => a.id.localeCompare(b.id));
914
+ compiled.commands.sort((a, b) => a.name.localeCompare(b.name));
915
+ return compiled;
916
+ }
917
+ function secureModuleRoutes(plan, routes) {
918
+ const secured = {};
919
+ for (const [name, definition] of Object.entries(routes)) {
920
+ assertSurfaceName(plan, name);
921
+ assertSurfaceRoute(plan, name, definition.route);
922
+ secured[name] = {
923
+ ...definition.route,
924
+ middlewares: commandChain(
925
+ plan,
926
+ name,
927
+ plan.authorize?.(definition.command),
928
+ definition.route.middlewares ?? []
929
+ )
930
+ };
931
+ }
932
+ return secured;
933
+ }
934
+ function manifestRoute(plan, manifest) {
935
+ const builder = route.get(plan.manifestPath);
936
+ return (plan.manifest === "public" ? builder.skip(["auth"]) : builder.use([plan.auth])).handler(async () => manifest);
937
+ }
938
+ function buildRouter(plan, routes) {
939
+ const appCommands = collectSurfaceCommands(routes, plan.wording);
940
+ const moduleSurface = compileModules(plan, appCommands);
941
+ const commands = [...appCommands, ...moduleSurface.commands].sort((a, b) => a.name.localeCompare(b.name));
460
942
  const manifest = {
461
943
  manifestVersion: 1,
462
- commands: collectOpsCommands(routes)
944
+ ...moduleSurface.descriptors.length > 0 ? { modules: moduleSurface.descriptors } : {},
945
+ commands
946
+ };
947
+ const commandsByName = new Map(appCommands.map((command) => [command.name, command]));
948
+ const secured = secureRoutes(plan, routes, commandsByName);
949
+ const securedModules = secureModuleRoutes(plan, moduleSurface.routes);
950
+ return Object.defineProperty(defineUnmappedRouter({
951
+ [plan.manifestName]: manifestRoute(plan, manifest),
952
+ ...secured,
953
+ ...securedModules
954
+ }), "_surfaceNamespace", { value: plan.namespace, enumerable: false });
955
+ }
956
+ function planOf(options, wording, rules) {
957
+ assertNamespace(options?.namespace);
958
+ if (!options.auth) {
959
+ throw new SurfaceError(
960
+ `${wording.factory} requires an auth middleware ({ auth: ... }). A surface reachable without authentication cannot be created.`
961
+ );
962
+ }
963
+ const modules = options.modules ?? [];
964
+ if (modules.length > 0 && !options.authorize) {
965
+ throw new SurfaceError(`${wording.factory} requires an authorize function when modules are mounted.`);
966
+ }
967
+ const manifest = options.manifest ?? "authenticated";
968
+ if (manifest !== "authenticated" && manifest !== "public") {
969
+ throw new SurfaceError(
970
+ `${wording.factory} manifest must be 'authenticated' or 'public', got ${JSON.stringify(manifest)}.`
971
+ );
972
+ }
973
+ return {
974
+ namespace: options.namespace,
975
+ prefix: `${options.namespace}/`,
976
+ manifestPath: manifestPathOf(options.namespace),
977
+ manifestName: manifestNameOf(options.namespace),
978
+ auth: options.auth,
979
+ authorize: options.authorize,
980
+ manifest,
981
+ modules,
982
+ wording,
983
+ requireEffect: rules.requireEffect
984
+ };
985
+ }
986
+ function createSurface(options, wording, rules) {
987
+ const plan = planOf(options, wording, rules);
988
+ return {
989
+ namespace: plan.namespace,
990
+ route: surfaceRouteBuilder(plan.namespace, wording),
991
+ router: (routes) => buildRouter(plan, routes)
463
992
  };
464
- const secured = secureRoutes(routes, options.auth);
465
- const manifestRoute = route.get(OPS_MANIFEST_PATH).use([options.auth]).handler(async () => manifest);
466
- return defineRouter({
467
- [OPS_MANIFEST_NAME]: manifestRoute,
468
- ...secured
469
- });
470
993
  }
471
994
 
995
+ // src/ops/wording.ts
996
+ var OPS_WORDING = {
997
+ noun: "ops",
998
+ builder: "`opsRoute`",
999
+ factory: "createOpsRouter"
1000
+ };
1001
+
472
1002
  // src/ops/ops-route.ts
473
1003
  var OPS_PATH_ROOT = "/_ops";
474
- function toOpsPath(path) {
475
- if (!path.startsWith("/")) {
476
- throw new OpsRouterError(
477
- `Ops route path "${path}" must start with "/". It is appended to "${OPS_PATH_ROOT}", so "${path}" would read as "${OPS_PATH_ROOT}${path}".`
478
- );
1004
+ var opsRoute = surfaceRouteBuilder(OPS_PATH_ROOT, OPS_WORDING);
1005
+
1006
+ // src/ops/create-ops-router.ts
1007
+ var OPS_PATH_PREFIX = "/_ops/";
1008
+ var OPS_MANIFEST_PATH = "/_ops/_manifest";
1009
+ function moduleScopeGuard(authorize) {
1010
+ if (!authorize) {
1011
+ return void 0;
479
1012
  }
480
- if (path === "/") {
481
- throw new OpsRouterError(
482
- `Ops route path "/" names no command \u2014 "${OPS_PATH_ROOT}" itself is not a command.`
1013
+ return (command) => command.module === void 0 ? void 0 : authorize(...command.scopes ?? []);
1014
+ }
1015
+ function createOpsRouter(routes, options) {
1016
+ if ((options?.modules ?? []).length > 0 && !options.authorize) {
1017
+ throw new SurfaceError(
1018
+ "createOpsRouter requires an authorize scope factory when modules are mounted."
483
1019
  );
484
1020
  }
485
- return OPS_PATH_ROOT + path;
1021
+ return createSurface({
1022
+ namespace: OPS_PATH_ROOT,
1023
+ auth: options?.auth,
1024
+ authorize: moduleScopeGuard(options?.authorize),
1025
+ modules: options?.modules
1026
+ }, OPS_WORDING, { requireEffect: false }).router(routes);
486
1027
  }
487
- function opsMethod(method) {
488
- return (path) => route[method](toOpsPath(path));
1028
+
1029
+ // src/ops/manifest.ts
1030
+ function collectOpsCommands(routes) {
1031
+ return collectSurfaceCommands(routes, OPS_WORDING);
1032
+ }
1033
+
1034
+ // src/ops/module.ts
1035
+ function defineOpsModule(module) {
1036
+ return validateSurfaceModule(module, OPS_PATH_ROOT, OPS_WORDING);
489
1037
  }
490
- var opsRoute = {
491
- get: opsMethod("get"),
492
- post: opsMethod("post"),
493
- put: opsMethod("put"),
494
- patch: opsMethod("patch"),
495
- delete: opsMethod("delete")
496
- };
497
1038
 
498
- export { OPS_MANIFEST_PATH, OPS_PATH_PREFIX, OPS_PATH_ROOT, OpsRouterError, collectOpsCommands, createOpsRouter, opsRoute };
1039
+ export { OPS_MANIFEST_PATH, OPS_PATH_PREFIX, OPS_PATH_ROOT, SurfaceError as OpsRouterError, collectOpsCommands, createOpsRouter, defineOpsModule, opsRoute };
499
1040
  //# sourceMappingURL=index.js.map
500
1041
  //# sourceMappingURL=index.js.map