@jimhoyd/urlcode 0.4.0-alpha.1 → 0.4.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/.claude/skills/urlcode-authoring/SKILL.md +24 -8
  2. package/.claude/skills/urlcode-operations/SKILL.md +10 -16
  3. package/.claude-plugin/marketplace.json +1 -1
  4. package/README.md +75 -62
  5. package/ROADMAP.md +61 -16
  6. package/SECURITY.md +23 -8
  7. package/dist/BUILD-MANIFEST.json +38 -43
  8. package/dist/agents-guide.js +18 -18
  9. package/dist/build-static.js +134 -0
  10. package/dist/capabilities.js +85 -31
  11. package/dist/capability-query.js +0 -1
  12. package/dist/cli.js +23 -31
  13. package/dist/compliance-rules/baseline.js +2 -10
  14. package/dist/compliance-rules/privacy.js +5 -16
  15. package/dist/compliance-rules/shared.js +0 -2
  16. package/dist/compliance.js +6 -8
  17. package/dist/config.js +15 -8
  18. package/dist/context.js +9 -10
  19. package/dist/examples.js +2 -2
  20. package/dist/explain-cli.js +3 -3
  21. package/dist/explain.js +5 -6
  22. package/dist/extensions.js +61 -2
  23. package/dist/function-sources.js +34 -2
  24. package/dist/function-worker.js +3 -1
  25. package/dist/functions.js +84 -13
  26. package/dist/guest-api.js +29 -3
  27. package/dist/index.js +3 -6
  28. package/dist/manifest.js +5 -7
  29. package/dist/mcp.js +1 -1
  30. package/dist/observability.js +1 -21
  31. package/dist/policies/cache.js +8 -3
  32. package/dist/policy.js +28 -9
  33. package/dist/project-tests.js +3 -3
  34. package/dist/readiness.js +32 -9
  35. package/dist/router.js +5 -7
  36. package/dist/runtime.js +77 -58
  37. package/dist/sandbox.js +48 -0
  38. package/dist/scaffold.js +0 -0
  39. package/dist/scripts/operational-drills.js +12 -54
  40. package/dist/server.js +3 -29
  41. package/dist/tooling.js +1 -1
  42. package/dist/trusted-functions.js +210 -0
  43. package/dist/types/build-static.d.ts +43 -0
  44. package/dist/types/capabilities.d.ts +14 -5
  45. package/dist/types/compliance-rules/shared.d.ts +0 -2
  46. package/dist/types/compliance.d.ts +0 -3
  47. package/dist/types/config.d.ts +2 -1
  48. package/dist/types/context.d.ts +2 -1
  49. package/dist/types/examples.d.ts +1 -1
  50. package/dist/types/extensions.d.ts +55 -0
  51. package/dist/types/function-sources.d.ts +4 -0
  52. package/dist/types/functions.d.ts +48 -5
  53. package/dist/types/guest-api.d.ts +1 -0
  54. package/dist/types/index.d.ts +3 -6
  55. package/dist/types/manifest.d.ts +1 -3
  56. package/dist/types/observability.d.ts +1 -14
  57. package/dist/types/project-tests.d.ts +1 -2
  58. package/dist/types/readiness.d.ts +10 -3
  59. package/dist/types/router.d.ts +2 -1
  60. package/dist/types/runtime.d.ts +0 -27
  61. package/dist/types/sandbox.d.ts +12 -0
  62. package/dist/types/scaffold.d.ts +0 -2
  63. package/dist/types/server.d.ts +1 -4
  64. package/dist/types/tooling.d.ts +3 -3
  65. package/dist/types/trusted-functions.d.ts +29 -0
  66. package/dist/types/types.d.ts +14 -7
  67. package/dist/types/verify-deployment.d.ts +2 -2
  68. package/dist/types.js +17 -4
  69. package/dist/typescript-authoring.js +55 -17
  70. package/dist/verify-deployment.js +3 -3
  71. package/docs/AI-AUTHORING.md +104 -9
  72. package/docs/AWS.md +4 -4
  73. package/docs/BEST-PRACTICES.md +3 -2
  74. package/docs/CAPABILITIES.md +29 -16
  75. package/docs/CAPACITY.md +128 -31
  76. package/docs/CLOUDFLARE.md +1 -2
  77. package/docs/COMPLIANCE.md +6 -9
  78. package/docs/DEPLOYMENT-CHECKS.md +1 -1
  79. package/docs/EXTENSIONS.md +183 -11
  80. package/docs/FRAMEWORK.md +35 -19
  81. package/docs/FUNCTION-SECURITY.md +129 -32
  82. package/docs/INSTALL.md +0 -5
  83. package/docs/LOAD-TESTING.md +4 -4
  84. package/docs/MIDDLEWARE.md +27 -16
  85. package/docs/MONITORING.md +2 -19
  86. package/docs/NEXT-PHASE-PLAN.md +12 -4
  87. package/docs/NEXT-STEPS.md +259 -40
  88. package/docs/OBSERVABILITY.md +7 -16
  89. package/docs/OPEN-DECISIONS.md +212 -0
  90. package/docs/OPERATIONAL-PROOF.md +26 -30
  91. package/docs/OPERATIONS.md +23 -32
  92. package/docs/POLICIES.md +15 -4
  93. package/docs/PRERENDER.md +2 -2
  94. package/docs/PROJECT-DIRECTION.md +34 -9
  95. package/docs/README.md +13 -11
  96. package/docs/RELEASE-READINESS.md +49 -29
  97. package/docs/RELEASE-SECURITY.md +89 -3
  98. package/docs/RESILIENCE.md +16 -15
  99. package/docs/ROUTING.md +8 -10
  100. package/docs/SANDBOX-REVIEW.md +19 -6
  101. package/docs/SCAFFOLDING.md +0 -2
  102. package/docs/SECURITY-AUDIT.md +40 -0
  103. package/docs/SPECIFICATION.md +60 -26
  104. package/docs/SPIKE-AI-FRAMEWORK-BENCHMARK.md +287 -0
  105. package/docs/SPIKE-BUSINESS-SUITE.md +8 -0
  106. package/docs/SPIKE-CORE-LAYERING.md +337 -0
  107. package/docs/SPIKE-DEFAULT-TRUST-MODEL.md +209 -0
  108. package/docs/SPIKE-EXTENSION-MODEL.md +2 -2
  109. package/docs/SPIKE-EXTENSIONS.md +5 -0
  110. package/docs/SPIKE-LAMBDA-COMPILE.md +4 -2
  111. package/docs/SPIKE-MONOREPO.md +322 -0
  112. package/docs/STARTERS.md +1 -1
  113. package/docs/STATIC.md +94 -0
  114. package/docs/TOOLING.md +13 -9
  115. package/docs/TUNNELS.md +0 -3
  116. package/docs/TYPESCRIPT-AUTHORING.md +27 -12
  117. package/docs/TYPESCRIPT.md +25 -4
  118. package/docs/USABILITY-REVIEW.md +7 -1
  119. package/docs/VERCEL.md +4 -5
  120. package/docs/VERSION-ALIGNMENT.md +205 -0
  121. package/docs/YAML-GUIDE.md +0 -3
  122. package/docs/YAML-REFERENCE.md +16 -6
  123. package/docs/policies/cache.md +13 -0
  124. package/examples/assets/example.yaml +1 -1
  125. package/examples/aws/example.yaml +1 -1
  126. package/examples/cloudflare/example.yaml +1 -1
  127. package/examples/conditions/example.yaml +1 -1
  128. package/examples/cookbook/example.yaml +1 -1
  129. package/examples/cookbook/middleware/bucket.mjs +12 -2
  130. package/examples/cookbook/middleware/locale.mjs +7 -3
  131. package/examples/egress/example.yaml +1 -1
  132. package/examples/extensions/example.yaml +1 -1
  133. package/examples/prerender/README.md +2 -2
  134. package/examples/prerender/example.yaml +1 -1
  135. package/examples/provider-conformance/example.yaml +1 -1
  136. package/examples/vercel/example.yaml +1 -1
  137. package/llms-full.txt +594 -219
  138. package/llms.txt +23 -12
  139. package/package.json +10 -3
  140. package/packaging/claude-plugin/.claude-plugin/plugin.json +1 -1
  141. package/packaging/claude-plugin/skills/urlcode-authoring/SKILL.md +24 -8
  142. package/packaging/claude-plugin/skills/urlcode-operations/SKILL.md +10 -16
  143. package/recipes/authenticated-json-api/recipe.yaml +1 -1
  144. package/recipes/contact-form/recipe.yaml +1 -1
  145. package/recipes/cors-api/recipe.yaml +1 -1
  146. package/recipes/health-page/recipe.yaml +1 -1
  147. package/recipes/json-api/recipe.yaml +1 -1
  148. package/recipes/middleware/middleware/bucket.mjs +12 -2
  149. package/recipes/middleware/middleware/locale.mjs +7 -3
  150. package/recipes/middleware/recipe.yaml +1 -1
  151. package/recipes/protected-download/recipe.yaml +1 -1
  152. package/recipes/redirect/recipe.yaml +1 -1
  153. package/recipes/static-plus-api/recipe.yaml +1 -1
  154. package/recipes/typescript/README.md +2 -1
  155. package/recipes/typescript/recipe.yaml +1 -1
  156. package/recipes/webhook-receiver/README.md +5 -1
  157. package/recipes/webhook-receiver/recipe.yaml +2 -1
  158. package/recipes/webhook-receiver/urlcode.yaml +7 -0
  159. package/schemas/recipe.schema.json +4 -3
  160. package/schemas/urlcode.schema.json +14 -41
  161. package/skills/urlcode/SKILL.md +29 -8
  162. package/starters/default/AGENTS.md +18 -18
  163. package/starters/default/urlcode.yaml +0 -1
  164. package/dist/link-api.js +0 -136
  165. package/dist/link-cli.js +0 -141
  166. package/dist/link-events.js +0 -76
  167. package/dist/link-records.js +0 -31
  168. package/dist/link-store-worker.js +0 -150
  169. package/dist/link-store.js +0 -250
  170. package/dist/management-policy.js +0 -40
  171. package/dist/sqlite-version.js +0 -6
  172. package/dist/types/link-api.d.ts +0 -30
  173. package/dist/types/link-cli.d.ts +0 -37
  174. package/dist/types/link-events.d.ts +0 -27
  175. package/dist/types/link-records.d.ts +0 -11
  176. package/dist/types/link-store-worker.d.ts +0 -1
  177. package/dist/types/link-store.d.ts +0 -130
  178. package/dist/types/management-policy.d.ts +0 -8
  179. package/dist/types/sqlite-version.d.ts +0 -1
  180. package/docs/DYNAMIC-LINKS.md +0 -61
  181. package/docs/MANAGEMENT-SECURITY.md +0 -82
  182. package/docs/links/cli.md +0 -110
  183. package/docs/links/limits.md +0 -175
  184. package/docs/links/management-api.md +0 -80
  185. package/docs/links/pools.md +0 -75
  186. package/docs/links/setup.md +0 -135
  187. package/docs/yaml/links.md +0 -30
  188. package/examples/live-links/README.md +0 -11
  189. package/examples/live-links/example.yaml +0 -21
  190. package/examples/live-links/tests/requests.json +0 -6
  191. package/examples/live-links/urlcode.yaml +0 -16
package/dist/server.js CHANGED
@@ -7,8 +7,6 @@ import { join } from 'node:path';
7
7
  import { createRuntime } from './runtime.js';
8
8
 
9
9
  import { createJsonLogger } from './logging.js';
10
- import { createLinkObserver } from './link-events.js';
11
-
12
10
  import { createObserverSink, renderPrometheus } from './observability.js';
13
11
 
14
12
  import { assert, HttpError } from './errors.js';
@@ -19,12 +17,12 @@ import { compileTrustedProxies, resolveClient } from './client-address.js';
19
17
 
20
18
 
21
19
 
22
-
20
+
23
21
 
24
22
 
25
23
 
26
24
 
27
-
25
+
28
26
 
29
27
 
30
28
 
@@ -83,7 +81,7 @@ function originForm(target ) {
83
81
  export async function startServer({ project = '.', host = '127.0.0.1', port = 3000, watch = false,
84
82
  local = false, log = createJsonLogger(),
85
83
  maxBodyBytes = 1048576, maxInFlightRequests = 64, maxInFlightHealthRequests = 16,
86
- requestLog = 'minimal', trustRequestId = false, origin, linkEvents, trustedProxies = [],
84
+ requestLog = 'minimal', trustRequestId = false, origin, trustedProxies = [],
87
85
  observers = [], metrics = false, metricsIntervalMs = 0, ...runtimeOptions } = {}) {
88
86
  // Which peers may set X-Forwarded-For. Empty means the socket peer is the
89
87
  // client for every policy; a forwarded header from anyone else is ignored.
@@ -105,9 +103,6 @@ export async function startServer({ project = '.', host = '127.0.0.1', port = 30
105
103
  const sink = createObserverSink(observers, log);
106
104
  const counters = sink.metrics;
107
105
  const emit = (event , context ) => { try { sink(event, context); } catch { /* Logging cannot fail requests. */ } };
108
- // Operator-supplied and explicitly enabled; route YAML cannot reach it and no
109
- // callback is ever loaded from the project. Undefined leaves it off.
110
- const observer = createLinkObserver(linkEvents, emit);
111
106
  let current = await createRuntime(project, { local, log: emit, origin, ...runtimeOptions });
112
107
  let shuttingDown = false, reloading = false, watching = false, interval , lastFingerprint , inFlight = 0, healthInFlight = 0;
113
108
  const retired = new Set ();
@@ -128,24 +123,6 @@ export async function startServer({ project = '.', host = '127.0.0.1', port = 30
128
123
  let status = 500;
129
124
  res.on('error', () => {});
130
125
  req.on('error', () => {});
131
- {
132
- // Enqueued after the response is over, so an observer can neither delay a
133
- // redirect nor turn its own failure into one. A response that never
134
- // finished is reported as aborted rather than counted as a click. The
135
- // outcome is counted whether or not an operator collects link events.
136
- let observed = false;
137
- const settle = () => {
138
- if (observed || !trace.link) return;
139
- observed = true;
140
- const event = { event: 'link_request', requestId, collection: trace.link.collection, route: trace.route ?? null,
141
- code: trace.link.code, method, status,
142
- outcome: trace.link.result === 'redirect' ? (res.writableFinished ? 'completed' : 'aborted') : trace.link.result,
143
- durationMs: Math.round((performance.now() - started) * 100) / 100 };
144
- counters.record(event);
145
- if (observer) observer.emit(event);
146
- };
147
- res.once('finish', settle); res.once('close', settle);
148
- }
149
126
  try {
150
127
  if (shuttingDown) throw new HttpError(503, 'Runtime shutting down');
151
128
  let result ;
@@ -246,7 +223,6 @@ export async function startServer({ project = '.', host = '127.0.0.1', port = 30
246
223
  }
247
224
  return {
248
225
  server, reload, address, root: current.root, testPlan: () => current.testPlan(),
249
- linkEventStats: () => observer?.stats(),
250
226
  metrics: snapshot,
251
227
  get observers() { return observers.map(observer => ({ name: observer.name, version: observer.version })); },
252
228
  // What a request sees as its own origin: behind a tunnel or proxy this is
@@ -260,8 +236,6 @@ export async function startServer({ project = '.', host = '127.0.0.1', port = 30
260
236
  clearTimeout(deadline);
261
237
  while (reloading) await new Promise(resolve => setTimeout(resolve,10));
262
238
  await current.close(); await Promise.all(retired);
263
- // Observers drain after the connections they describe are gone.
264
- if (observer) emit({ event: 'link_observer', status: 'closed', ...await observer.close() });
265
239
  // A final snapshot, then observers release in reverse order.
266
240
  sink.publish(snapshot());
267
241
  await sink.close();
package/dist/tooling.js CHANGED
@@ -44,7 +44,7 @@ export async function inspectProject(project ,options ={}) {
44
44
  const offset=options.offset??0,limit=options.limit??100;
45
45
  if(!Number.isSafeInteger(offset)||offset<0||!Number.isSafeInteger(limit)||limit<1||limit>1000)throw new Error('Invalid inspection page');
46
46
  const {loaded,compiled,routes,projectSha256}=await prepare(project,options);
47
- const report=analyzeCompiledCapabilities(loaded.document,compiled,options.target??'self-hosted');
47
+ const report=analyzeCompiledCapabilities(loaded.document,compiled,options.target??'self-hosted',options.extensions);
48
48
  return {format:1,projectSha256,routeCount:compiled.count,offset,limit,routes:routes.slice(offset,offset+limit).map(route=>({path:route.pattern,methods:route.methods,enabled:route.enabled!==false,capabilities:routeCapabilities(route,loaded.document)})),compatibility:{...compatibilitySummary(report),offset,limit,hasMore:offset+limit<report.issues.length,issues:report.issues.slice(offset,offset+limit)}};
49
49
  }
50
50
  export async function validateProject(project ,options ={}) {
@@ -0,0 +1,210 @@
1
+ // Trusted (unsandboxed) execution for `function`/`middleware` routes that do
2
+ // not declare `sandbox: true` (docs/SPIKE-DEFAULT-TRUST-MODEL.md). This is the
3
+ // new default: an ordinary dynamic `import()` of the project's own module,
4
+ // called in the host process with full Node access — no worker thread, no
5
+ // QuickJS/WASM, no fresh-heap-per-call, no module-graph allowlist. The
6
+ // sandboxed path (FunctionPool, function-worker.ts) is untouched by this file
7
+ // and keeps its own guarantees exactly as before for any route that opts in
8
+ // with `sandbox: true`.
9
+ //
10
+ // The request/response contract mirrors the sandboxed path (guest-api.ts) as
11
+ // closely as an in-process call can: a `Request` and a `context` in, a
12
+ // `Response` out, the same middleware `(request, context, next)` chain with
13
+ // `next()` callable at most once and no arguments, and the same native-reply
14
+ // passthrough (a middleware chain wrapping a native reply — redirect, asset,
15
+ // static reply — can return that exact Response unchanged to avoid
16
+ // re-encoding its body). Node's own `Request`/`Response`/`Headers` are used
17
+ // instead of guest-api.ts's restricted classes, so a trusted function can
18
+ // return richer bodies (e.g. binary) than a sandboxed one can; that is a
19
+ // documented, intentional capability difference, not a contract violation.
20
+ //
21
+ // Deadline: unlike the sandboxed path, there is no interrupt mechanism that
22
+ // can stop trusted code running in the host's own event loop. `timeoutMs`
23
+ // here is an advisory race against the handler's promise settling — it
24
+ // rejects the *call* once the deadline passes, but cannot preempt trusted
25
+ // code that is blocking the event loop synchronously (a WASM interrupt has no
26
+ // equivalent in-process). This is a documented difference from the
27
+ // sandboxed path's forced worker termination; see docs/CAPACITY.md.
28
+ import { randomUUID } from 'node:crypto';
29
+ import { pathToFileURL } from 'node:url';
30
+ import { ConfigError, HttpError } from './errors.js';
31
+ import { routeFunctions } from './function-sources.js';
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+ export class TrustedFunctions {
45
+ timeoutMs ; maxBytes ; log ;
46
+ // Node's ESM loader caches a resolved module forever by URL, unlike a
47
+ // sandboxed worker, which gets a genuinely fresh module registry on every
48
+ // reload/restart. A snapshot reload constructs a brand-new TrustedFunctions
49
+ // (createRuntime runs again), so each instance gets its own cache-busting
50
+ // query string: reloaded code is re-imported and re-executed, matching the
51
+ // sandboxed pool's "new workers, new snapshot" reload contract, while a
52
+ // single instance still only imports each module once per process.
53
+ epoch = randomUUID();
54
+ constructor({ timeoutMs = 5000, maxBytes = 1048576, log = () => {} } = {}) {
55
+ this.timeoutMs = timeoutMs; this.maxBytes = maxBytes; this.log = log;
56
+ }
57
+ // Eagerly imports and validates every declared export exists as a function,
58
+ // the same guarantee FunctionPool.start() gives the sandboxed path: a
59
+ // broken function/middleware module fails runtime activation up front
60
+ // rather than the first request that happens to hit it.
61
+ async start(routes ) {
62
+ try { await Promise.all(routes.flatMap(routeFunctions).map(definition => this.loadExport(definition))); }
63
+ catch { throw new ConfigError('Function initialization failed (check module syntax, imports and exports)'); }
64
+ return this;
65
+ }
66
+ // No dependency allowlist, no relative-static-import-only rule and no
67
+ // per-module byte budget apply here — those are sandbox-snapshot
68
+ // constraints (function-sources.ts), not trusted-path ones. A trusted
69
+ // module may use bare specifiers, Node builtins, npm packages and dynamic
70
+ // import exactly like any other project code.
71
+ async loadExport(definition ) {
72
+ let mod ;
73
+ try { mod = await import(pathToFileURL(definition.source).href + '?urlcode-trusted-epoch=' + this.epoch) ; }
74
+ catch { throw new HttpError(502, 'Function execution failed'); }
75
+ const value = mod[definition.export];
76
+ if (typeof value !== 'function') throw new HttpError(502, 'Function execution failed');
77
+ return value;
78
+ }
79
+ async execute(route , request , context , native ) {
80
+ // The timer backing the deadline race must be cleared on every path —
81
+ // success or failure — or a completed call leaves a live Timeout behind
82
+ // for the full timeoutMs (see #138: 100 sequential calls, 100 leaked
83
+ // timers). `finally` covers both outcomes of the race in one place.
84
+ // The AbortController lets a fired deadline reach into `invoke`'s body
85
+ // read and cancel it immediately (#137), instead of letting a losing
86
+ // racer keep consuming an oversized or slow stream after this call has
87
+ // already rejected with 504.
88
+ const controller = new AbortController();
89
+ let timer ;
90
+ const timeout = new Promise ((_, reject) => {
91
+ timer = setTimeout(() => { controller.abort(); reject(new HttpError(504, 'Function deadline exceeded')); }, this.timeoutMs);
92
+ timer.unref?.();
93
+ });
94
+ const invocation = this.invoke(route, request, context, native, controller.signal);
95
+ try { return await Promise.race([invocation, timeout]); }
96
+ catch (error) { throw error instanceof HttpError ? error : new HttpError(502, 'Function execution failed'); }
97
+ finally {
98
+ clearTimeout(timer);
99
+ // `invocation` may still be running (e.g. blocked on a cancelled
100
+ // reader settling) after the race above has already returned; a later
101
+ // rejection from it must not surface as an unhandled rejection.
102
+ invocation.catch(() => {});
103
+ }
104
+ }
105
+ // Reads a Response body incrementally, rejecting/cancelling as soon as
106
+ // `maxBytes` is exceeded instead of buffering the whole stream first
107
+ // (#137: a single `.arrayBuffer()` call reads everything unconditionally,
108
+ // so a configured limit only ever rejects *after* the oversized body has
109
+ // already been fully read into memory). Also cancels the reader as soon as
110
+ // `signal` aborts (the call's deadline firing), rather than letting a slow
111
+ // stream keep being pulled after the request has already timed out.
112
+ // Applies on every path that has a real body to measure, GET or HEAD alike
113
+ // (#139): the caller decides whether to transmit the bytes, this only
114
+ // decides how many there are, matching the convention the native/asset
115
+ // path already uses (the full body and its length are always determined
116
+ // up front; only `prepareResponse` in http-response.ts drops the body for
117
+ // HEAD at write time).
118
+ async readBody(response , signal ) {
119
+ if (response.body === null) return Buffer.alloc(0);
120
+ const reader = response.body.getReader();
121
+ const cancel = () => { reader.cancel().catch(() => {}); };
122
+ if (signal.aborted) { cancel(); throw new HttpError(504, 'Function deadline exceeded'); }
123
+ signal.addEventListener('abort', cancel, { once: true });
124
+ try {
125
+ const chunks = [];
126
+ let total = 0;
127
+ for (;;) {
128
+ const { done, value } = await reader.read();
129
+ if (done) break;
130
+ total += value.byteLength;
131
+ if (total > this.maxBytes) { cancel(); throw new HttpError(502, 'Function execution failed'); }
132
+ chunks.push(Buffer.from(value));
133
+ }
134
+ return Buffer.concat(chunks, total);
135
+ } catch (error) {
136
+ if (signal.aborted) throw new HttpError(504, 'Function deadline exceeded');
137
+ throw error instanceof HttpError ? error : new HttpError(502, 'Function execution failed');
138
+ } finally { signal.removeEventListener('abort', cancel); }
139
+ }
140
+ async invoke(route , request , requestContext , native , signal ) {
141
+ // Matches guest-api.ts's __invokePipeline/__invoke: a fresh `state` object
142
+ // per invocation, shared across the whole middleware+handler chain for
143
+ // this one call only, never carried between requests.
144
+ const context = requestContext ;
145
+ context.state = {};
146
+ const hasBody = request.body !== undefined && request.body.length > 0 && !['GET','HEAD'].includes(request.method);
147
+ const req = new Request(request.url, {
148
+ method: request.method, headers: request.headers,
149
+ ...(hasBody ? { body: request.body , duplex: 'half' } : {}),
150
+ });
151
+ let nativeResponse ;
152
+ if (native) {
153
+ const nativeBytes = native.body ;
154
+ const bodyless = [204,205,304].includes(native.status) || !nativeBytes || nativeBytes.length === 0;
155
+ nativeResponse = new Response(bodyless ? null : nativeBytes, { status: native.status, headers: native.headers });
156
+ }
157
+ const middleware = route.middleware || [];
158
+ const handlers = await Promise.all(middleware.map(definition => this.loadExport(definition))) ;
159
+ const entry = route.function ? (await this.loadExport(route.function) ) : undefined;
160
+ const dispatch = async (index ) => {
161
+ if (index === handlers.length) {
162
+ if (entry) return await entry(req, context);
163
+ if (nativeResponse) return nativeResponse;
164
+ throw new HttpError(502, 'Function execution failed');
165
+ }
166
+ let called = false, open = true, pending ;
167
+ const next = async (...args ) => {
168
+ if (args.length || called || !open) throw new TypeError('next may be called once during middleware');
169
+ called = true; pending = dispatch(index + 1); return pending;
170
+ };
171
+ let response ;
172
+ try { response = await handlers[index] (req, context, next); if (pending) await pending.catch(() => {}); }
173
+ finally { open = false; }
174
+ if (!(response instanceof Response)) throw new HttpError(502, 'Function execution failed');
175
+ return response;
176
+ };
177
+ const response = await dispatch(0);
178
+ if (!(response instanceof Response) || !Number.isInteger(response.status) || response.status < 200 || response.status > 599) throw new HttpError(502, 'Function execution failed');
179
+ const nativeBody = response === nativeResponse;
180
+ const headers = [...response.headers.entries()];
181
+ if (nativeBody && native) {
182
+ // The route returned the untouched native reply (possibly with extra
183
+ // headers a middleware added, e.g. `x-seen` above `location`): reject
184
+ // only if native's *own* metadata was changed, the same contract the
185
+ // sandboxed path enforces (function-worker.ts's "Native metadata
186
+ // changed" check) — an added header is fine, a changed one is not.
187
+ for (const key of new Set(native.headers.map(([k]) => k.toLowerCase()))) {
188
+ const originals = native.headers.filter(([k]) => k.toLowerCase() === key).map(([,v]) => v);
189
+ const current = headers.filter(([k]) => k.toLowerCase() === key).map(([,v]) => v);
190
+ if (JSON.stringify(originals) !== JSON.stringify(current)) throw new HttpError(502, 'Function execution failed');
191
+ }
192
+ }
193
+ // Header count/byte limits apply either way, matching function-worker.ts.
194
+ { let bytes = 0; for (const [k,v] of headers) bytes += Buffer.byteLength(k) + Buffer.byteLength(v) + 4;
195
+ if (headers.length > 256 || bytes > 16384) throw new HttpError(502, 'Function execution failed'); }
196
+ // Measured on HEAD too, not skipped: prepareResponse (http-response.ts)
197
+ // is what decides not to put the bytes on the wire for HEAD, but it
198
+ // still needs the real length rather than the 0 a skipped read leaves it
199
+ // to assume (#139).
200
+ const body = nativeBody && native
201
+ ? ((native.body ) ?? Buffer.alloc(0))
202
+ : await this.readBody(response, signal);
203
+ return { status: response.status, headers, body, nativeBody,
204
+ ...(nativeBody && native?.contentLength !== undefined ? { contentLength: native.contentLength } : {}) };
205
+ }
206
+ // Symmetry with FunctionPool.close(): nothing to release for the trusted
207
+ // path (no workers, no pending requests it owns), but the runtime can call
208
+ // either executor's close() uniformly during shutdown.
209
+ async close() { /* no owned resources */ }
210
+ }
@@ -0,0 +1,43 @@
1
+ import type { LogFn } from './types.ts';
2
+ export interface BuildOptions {
3
+ out?: string | undefined;
4
+ origin?: string | undefined;
5
+ log?: LogFn | undefined;
6
+ }
7
+ export interface BuildReport {
8
+ out: string;
9
+ format: number;
10
+ version: string;
11
+ routes: number;
12
+ redirects: number;
13
+ files: number;
14
+ manifest: string;
15
+ }
16
+ /** One S3 per-object website redirect: a zero-byte object at `key` carrying
17
+ * `x-amz-website-redirect-location: location`, which S3 always answers with a
18
+ * 301 regardless of the object's own metadata. */
19
+ export interface StaticRedirect {
20
+ key: string;
21
+ location: string;
22
+ status: 301;
23
+ }
24
+ /** One served file: the bytes are written under `out/objects/<key>`; the
25
+ * metadata here is what a deploy step sets as the S3 object's own headers. */
26
+ export interface StaticObject {
27
+ key: string;
28
+ contentType: string;
29
+ cacheControl?: string;
30
+ contentDisposition?: string;
31
+ }
32
+ export interface RedirectManifest {
33
+ format: number;
34
+ redirects: StaticRedirect[];
35
+ }
36
+ export interface ObjectManifest {
37
+ format: number;
38
+ objects: StaticObject[];
39
+ }
40
+ declare function objectKey(pattern: string): string;
41
+ export declare function buildStatic(project: string, { out, origin, log }?: BuildOptions): Promise<BuildReport>;
42
+ export declare const staticObjectKey: typeof objectKey;
43
+ export {};
@@ -1,9 +1,12 @@
1
+ import type { RuntimeExtension } from './extensions.ts';
1
2
  import type { CompiledRoute, CompiledRouteTable, LoadedDocument, PolicySupport, ProjectDocument, RouteConfig } from './types.ts';
2
- export declare const capabilityTargets: readonly ["self-hosted", "cloudflare", "aws", "vercel"];
3
+ export declare const capabilityTargets: readonly ["self-hosted", "cloudflare", "aws", "vercel", "static"];
3
4
  export type CapabilityTarget = typeof capabilityTargets[number];
4
5
  export type CapabilitySupport = PolicySupport | 'conditional' | 'unknown';
5
- export declare const capabilityNames: readonly ["extension", "policies.extensions", "proxy", "signals", "conditional", "conditions", "redirect", "respond", "page", "static", "download", "function", "middleware", "link", "dynamicLinks", "parameters", "methods", "enabled", "expires", "request.body", "response.headers", "bindings", "policies.agents", "policies.security", "policies.cache", "policies.compression", "policies.throttle"];
6
+ export declare const capabilityNames: readonly ["extension", "policies.extensions", "proxy", "signals", "conditional", "conditions", "redirect", "respond", "page", "static", "download", "function", "middleware", "parameters", "methods", "enabled", "expires", "request.body", "response.headers", "bindings", "policies.agents", "policies.security", "policies.cache", "policies.compression", "policies.throttle"];
6
7
  export type CapabilityName = typeof capabilityNames[number];
8
+ /** The resolved operator registration set, when known (loaded via --host-file, same as `inspectExtensions`). Keyed by extension name. */
9
+ export type ExtensionRegistry = ReadonlyMap<string, RuntimeExtension>;
7
10
  export interface CapabilityDecision {
8
11
  support: CapabilitySupport;
9
12
  reason: string;
@@ -35,10 +38,16 @@ export declare function normalizeCapabilityTarget(target: string): CapabilityTar
35
38
  export declare function getCapabilities(target?: string): CapabilityCatalog;
36
39
  /** A safe projection shared by declaration preflight and the existing compiled IR. No values escape. */
37
40
  export declare function routeCapabilities(route: RouteConfig | CompiledRoute, document: ProjectDocument): CapabilityName[];
38
- /** Preflight only: call after schema validation/site expansion, before resolving bindings. */
39
- export declare function analyzeProjectCapabilities(loaded: LoadedDocument, target: string): CompatibilityReport;
41
+ /**
42
+ * Preflight only: call after schema validation/site expansion, before resolving bindings.
43
+ * `registrations` is the resolved operator extension set, when known (the same
44
+ * shape --host-file loads for `inspectExtensions`); without it, `extension`/
45
+ * `policies.extensions` requirements report `conditional`/`unknown` rather
46
+ * than a blanket `native` that ignores the specific extension's own targets.
47
+ */
48
+ export declare function analyzeProjectCapabilities(loaded: LoadedDocument, target: string, registrations?: readonly RuntimeExtension[]): CompatibilityReport;
40
49
  /** Analyze normalized route semantics without exporting validators, resources or resolved secrets. */
41
- export declare function analyzeCompiledCapabilities(document: ProjectDocument, compiled: CompiledRouteTable, target: string): CompatibilityReport;
50
+ export declare function analyzeCompiledCapabilities(document: ProjectDocument, compiled: CompiledRouteTable, target: string, registrations?: readonly RuntimeExtension[]): CompatibilityReport;
42
51
  export declare function assertTargetCompatibility(report: CompatibilityReport): void;
43
52
  export declare function formatCapabilities(catalog: CapabilityCatalog): string;
44
53
  export type CapabilityKind = 'handler' | 'policy' | 'routing' | 'request' | 'binding' | 'egress' | 'middleware' | 'project';
@@ -7,8 +7,6 @@ export declare const rfc6585: Standard;
7
7
  export declare const rfc9309: Standard;
8
8
  export declare const breach: Standard;
9
9
  export declare const monitoring: Standard;
10
- export declare const linkChannel: Standard;
11
- export declare const management: Standard;
12
10
  export declare const agentLists: Standard;
13
11
  export declare const active: (route: PlanInventoryEntry) => boolean;
14
12
  export declare const functionLike: (route: PlanInventoryEntry) => boolean;
@@ -27,8 +27,6 @@ export type RuleResult = RawFinding[] | RawFinding | null | undefined | false;
27
27
  /** The host settings under review, null where the operator declared nothing. */
28
28
  export interface HostSettings {
29
29
  requestLog: 'minimal' | 'detailed' | null;
30
- linkEvents: boolean | null;
31
- includeCode: boolean | null;
32
30
  }
33
31
  export interface ProjectContext {
34
32
  document: ProjectDocument;
@@ -92,7 +90,6 @@ export interface ComplianceReport {
92
90
  evidence: {
93
91
  routes: number;
94
92
  active: number;
95
- dynamicLinks: boolean;
96
93
  policies: string[];
97
94
  files: string[];
98
95
  origin: string | null;
@@ -20,7 +20,8 @@ export declare const SHORT_FORM_PATH_SCHEMA: {
20
20
  /**
21
21
  * Expands the YAML short forms into the canonical long form. `function: functions/x.mjs`
22
22
  * becomes `{source, args}` with an argument per `{param}` in the path, declaring any
23
- * parameter the route does not declare itself; a string middleware entry becomes `{source}`.
23
+ * parameter the route does not declare itself; a string middleware entry becomes `{source}`;
24
+ * a route-level `cache` becomes `policies.cache` (refused alongside a direct `policies.cache`).
24
25
  * Everything downstream (routes, audit, the compiled table) sees only the long form.
25
26
  */
26
27
  export declare function normalizeRoute(pattern: string, route: AuthoredRouteConfig | RouteConfig): RouteConfig;
@@ -25,7 +25,6 @@ export interface ProjectContext {
25
25
  env: string[];
26
26
  secrets: string[];
27
27
  };
28
- dynamicLinks: boolean;
29
28
  site: string[];
30
29
  files?: {
31
30
  includes: string[];
@@ -41,6 +40,8 @@ export interface ProjectContext {
41
40
  path: string;
42
41
  methods: string[];
43
42
  handler: string;
43
+ sandbox: boolean;
44
+ sandboxReason?: string;
44
45
  }[];
45
46
  constraints: Record<string, boolean | string | {
46
47
  value: boolean | string;
@@ -31,7 +31,7 @@ export interface ExampleSearchResult {
31
31
  matchedRoutes: RouteIndexEntry[];
32
32
  })[];
33
33
  }
34
- export declare const exampleNames: readonly ["assets", "aws", "cloudflare", "compliance", "conditions", "cookbook", "egress", "extensions", "live-links", "monitoring", "prerender", "provider-conformance", "tunnel", "vercel"];
34
+ export declare const exampleNames: readonly ["assets", "aws", "cloudflare", "compliance", "conditions", "cookbook", "egress", "extensions", "monitoring", "prerender", "provider-conformance", "tunnel", "vercel"];
35
35
  export declare const routeIndexFile = "route-index.json";
36
36
  export declare function listExamples(): Promise<ExampleSummary[]>;
37
37
  /**
@@ -6,11 +6,23 @@ export interface ExtensionDeclaration {
6
6
  config: Record<string, unknown>;
7
7
  }
8
8
  export type ExtensionPolicies = Record<string, Record<string, unknown> | false>;
9
+ /**
10
+ * `root` is the project's resolved absolute directory (the same value
11
+ * `loadDocument()` computes and `functionFile()`/router.ts resolves
12
+ * `function`/`middleware` `source` entries against). It is not the process's
13
+ * `cwd()`: `--project`/`--host-file` are independent paths, a server can be
14
+ * started from any working directory, and the JS API can load a project
15
+ * programmatically with no relationship to `cwd()` at all. An extension that
16
+ * resolves project-relative paths of its own (for example, an alternative
17
+ * middleware source it loads by convention rather than through core's native
18
+ * `middleware:` array) must resolve them against this field, never `cwd()`.
19
+ */
9
20
  export interface ExtensionActivation {
10
21
  origin: string;
11
22
  target: TargetName;
12
23
  projectSha256: string;
13
24
  mounts: readonly string[];
25
+ root: string;
14
26
  }
15
27
  export interface ExtensionRequest {
16
28
  method: string;
@@ -28,6 +40,20 @@ export interface ExtensionRequest {
28
40
  export interface ExtensionInstance {
29
41
  handle(request: ExtensionRequest): HandlerResult | Promise<HandlerResult>;
30
42
  authorize?(requirement: Readonly<Record<string, unknown>>, request: ExtensionRequest): HandlerResult | undefined | Promise<HandlerResult | undefined>;
43
+ /**
44
+ * Wrap semantics, not gate semantics: attached the same way as `authorize`
45
+ * (policies.extensions.<name> on a route, `config` the same validated
46
+ * per-route value `authorize`'s `requirement` receives), but given `next`,
47
+ * a callable invoking the rest of the pipeline for this route (any other
48
+ * declared extension `middleware()` after this one, then the route's own
49
+ * native `middleware:` chain and handler) at most once. Calling it lets
50
+ * this hook run code before and after the rest of the pipeline, inspecting
51
+ * or mutating the `HandlerResult` it resolves to; skipping it short-circuits
52
+ * the rest of the pipeline entirely, the same way `authorize` can. Never
53
+ * touches the native `middleware:` array or its own sandboxed/trusted
54
+ * dispatch, and never runs before `authorize` on the same route.
55
+ */
56
+ middleware?(config: Readonly<Record<string, unknown>>, request: ExtensionRequest, next: () => Promise<HandlerResult>): HandlerResult | Promise<HandlerResult>;
31
57
  close?(): void | Promise<void>;
32
58
  }
33
59
  /** Trusted operator code only. YAML declares names/configuration, never modules. */
@@ -49,6 +75,23 @@ export interface RuntimeExtension {
49
75
  policySchema?: object;
50
76
  credentialHeaders?: string[];
51
77
  immutableAssets?: ExtensionImmutableAssets;
78
+ /**
79
+ * Reviewed, operator-declared cache sensitivity for `policies.extensions.<name>`
80
+ * routes (never for an `extension:` mount, which is always treated as
81
+ * sensitive). Omitted or `true`: the current, safe default — the runtime
82
+ * forces `Cache-Control: no-store`, disables compression and applies the
83
+ * extension response's header/size caps, exactly like `authorize`-gating
84
+ * auth/admin extensions. `false` is an explicit, reviewed opt-in a generic,
85
+ * cache-transparent extension (pure request/response middleware with no
86
+ * gating semantics of its own, like `urlcode-middleware`) makes to say its
87
+ * `middleware()` hook never depends on withholding the response from
88
+ * shared caches: the wrapped route's own declared cache headers pass
89
+ * through unchanged, exactly as the native `middleware:` array already
90
+ * does. A route naming more than one extension is treated as sensitive if
91
+ * any of them is (or leaves this unset) — this can only relax the no-store
92
+ * floor, never weaken it, and it never changes whether `authorize()` runs.
93
+ */
94
+ cacheSensitive?: boolean;
52
95
  activate(config: Readonly<Record<string, unknown>>, context: ExtensionActivation): ExtensionInstance | Promise<ExtensionInstance>;
53
96
  }
54
97
  /** `urlcode init --with <name>` contract: what core hands `@jimhoyd/urlcode-<name>`'s `scaffold` export. Nothing is written by `scaffold`. */
@@ -107,6 +150,18 @@ export declare const immutableCacheControl = "public, max-age=31536000, immutabl
107
150
  export declare function inspectExtensionRevision(project: string): Promise<string>;
108
151
  export declare function effectiveExtensionPolicies(document: ProjectDocument, route: Pick<RouteConfig, 'policies'>): Record<string, Record<string, unknown>>;
109
152
  export declare function hasExtensionPolicy(document: ProjectDocument, route: Pick<RouteConfig, 'policies'>): boolean;
153
+ /**
154
+ * Whether a route naming these `policies.extensions` names must be treated as
155
+ * confidential (forced no-store, no compression, extension response caps).
156
+ * `names` with no entries is never confidential. Without a `registrations`
157
+ * list to consult (a build path with no operator host loaded), every name is
158
+ * treated as sensitive: the safe default this can only relax, never weaken.
159
+ * A name whose registration is missing, or declares no `cacheSensitive` (or
160
+ * `true`), counts as sensitive; only an explicit `cacheSensitive: false`
161
+ * excuses it, and one sensitive name among several makes the whole route
162
+ * confidential.
163
+ */
164
+ export declare function isSensitiveExtensionPolicy(names: readonly string[], registrations?: readonly Pick<RuntimeExtension, 'name' | 'cacheSensitive'>[]): boolean;
110
165
  export declare function prepareExtensions(document: ProjectDocument, routes: Record<string, RouteConfig>, registrations: RuntimeExtension[] | undefined, context: Omit<ExtensionActivation, 'mounts'>): {
111
166
  activate(): Promise<ExtensionRegistry>;
112
167
  };
@@ -23,4 +23,8 @@ export declare const MODULE_LIMIT = 128;
23
23
  export declare const MODULE_BYTE_LIMIT = 1048576;
24
24
  export declare const TOTAL_BYTE_LIMIT = 4194304;
25
25
  export declare function routeFunctions<D>(route: FunctionRoute<D>): D[];
26
+ export declare function collectTrustedSources(routes: FunctionRoute[], root: string): Promise<Record<string, string>>;
27
+ export declare function collectSourcesFor(definitions: FunctionDefinition[], root: string): Promise<FunctionSources>;
28
+ /** Route-shaped convenience over `collectSourcesFor`: every existing caller (policy.ts,
29
+ * prerender.ts, typescript-authoring.ts) keeps working unchanged from `FunctionRoute[]`. */
26
30
  export declare function collectFunctionSources(routes: FunctionRoute[], root: string): Promise<FunctionSources>;