@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.4 → 3.5.0-ultramodern.41

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 (175) hide show
  1. package/dist/cjs/contract-gate-snapshot-normalization.js +122 -0
  2. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +133 -0
  4. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  5. package/dist/cjs/contract-gate-snapshot-store/resolve.js +124 -0
  6. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  7. package/dist/cjs/contractGateAutopilot.js +22 -70
  8. package/dist/cjs/index.js +6 -25
  9. package/dist/cjs/module-federation-css/collector.js +79 -0
  10. package/dist/cjs/module-federation-css/index.js +55 -0
  11. package/dist/cjs/module-federation-css/manifest.js +129 -0
  12. package/dist/cjs/module-federation-css/plugin.js +71 -0
  13. package/dist/cjs/module-federation-css/remote.js +133 -0
  14. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  15. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  16. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  17. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  18. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  19. package/dist/cjs/telemetry/canary.js +180 -0
  20. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  21. package/dist/cjs/telemetry/canarySetup.js +107 -0
  22. package/dist/cjs/telemetry/envelope.js +223 -0
  23. package/dist/cjs/telemetry/exporters.js +148 -0
  24. package/dist/cjs/telemetry/lifecycle.js +98 -0
  25. package/dist/cjs/telemetry/metrics.js +115 -0
  26. package/dist/cjs/telemetry/plugin.js +185 -0
  27. package/dist/cjs/telemetry/registry.js +296 -0
  28. package/dist/cjs/telemetry/registryTypes.js +46 -0
  29. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  30. package/dist/cjs/telemetry.js +32 -343
  31. package/dist/cjs/telemetryCore.js +14 -767
  32. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  33. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  34. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  35. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  36. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  37. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  38. package/dist/esm/contractGateAutopilot.mjs +21 -69
  39. package/dist/esm/index.mjs +1 -2
  40. package/dist/esm/module-federation-css/collector.mjs +38 -0
  41. package/dist/esm/module-federation-css/index.mjs +4 -0
  42. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  43. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  44. package/dist/esm/module-federation-css/remote.mjs +92 -0
  45. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  46. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  47. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  48. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  49. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  50. package/dist/esm/telemetry/canary.mjs +142 -0
  51. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  52. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  53. package/dist/esm/telemetry/envelope.mjs +164 -0
  54. package/dist/esm/telemetry/exporters.mjs +104 -0
  55. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  56. package/dist/esm/telemetry/metrics.mjs +77 -0
  57. package/dist/esm/telemetry/plugin.mjs +87 -0
  58. package/dist/esm/telemetry/registry.mjs +258 -0
  59. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  60. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  61. package/dist/esm/telemetry.mjs +1 -275
  62. package/dist/esm/telemetryCore.mjs +6 -759
  63. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  64. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  65. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  69. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  70. package/dist/esm-node/index.mjs +1 -2
  71. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  72. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  73. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  74. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  75. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  76. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  77. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  78. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  79. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  80. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  81. package/dist/esm-node/telemetry/canary.mjs +143 -0
  82. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  83. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  84. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  85. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  86. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  87. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  88. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  89. package/dist/esm-node/telemetry/registry.mjs +259 -0
  90. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  91. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  92. package/dist/esm-node/telemetry.mjs +1 -275
  93. package/dist/esm-node/telemetryCore.mjs +6 -759
  94. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  95. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  96. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  97. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  98. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  99. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  100. package/dist/types/contractGateAutopilot.d.ts +3 -6
  101. package/dist/types/index.d.ts +1 -2
  102. package/dist/types/module-federation-css/collector.d.ts +25 -0
  103. package/dist/types/module-federation-css/index.d.ts +8 -0
  104. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  105. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  106. package/dist/types/module-federation-css/remote.d.ts +20 -0
  107. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  108. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  109. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  110. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  111. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  112. package/dist/types/telemetry/canary.d.ts +85 -0
  113. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  114. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  115. package/dist/types/telemetry/envelope.d.ts +55 -0
  116. package/dist/types/telemetry/exporters.d.ts +12 -0
  117. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  118. package/dist/types/telemetry/metrics.d.ts +3 -0
  119. package/dist/types/telemetry/plugin.d.ts +12 -0
  120. package/dist/types/telemetry/registry.d.ts +69 -0
  121. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  122. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  123. package/dist/types/telemetry.d.ts +1 -12
  124. package/dist/types/telemetryCore.d.ts +6 -257
  125. package/package.json +9 -9
  126. package/src/contract-gate-snapshot-normalization.ts +155 -0
  127. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  128. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  129. package/src/contract-gate-snapshot-store/index.ts +20 -0
  130. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  131. package/src/contract-gate-snapshot-store/types.ts +64 -0
  132. package/src/contractGateAutopilot.ts +39 -131
  133. package/src/index.ts +1 -17
  134. package/src/module-federation-css/collector.ts +82 -0
  135. package/src/module-federation-css/index.ts +14 -0
  136. package/src/module-federation-css/manifest.ts +163 -0
  137. package/src/module-federation-css/plugin.ts +86 -0
  138. package/src/module-federation-css/remote.ts +165 -0
  139. package/src/runtime-fallback-signal/index.ts +34 -0
  140. package/src/runtime-fallback-signal/model.ts +230 -0
  141. package/src/runtime-fallback-signal/resolver.ts +304 -0
  142. package/src/runtime-fallback-signal/store.ts +78 -0
  143. package/src/runtimeFallbackSignal.ts +1 -584
  144. package/src/telemetry/canary.ts +291 -0
  145. package/src/telemetry/canaryEvaluation.ts +83 -0
  146. package/src/telemetry/canarySetup.ts +160 -0
  147. package/src/telemetry/envelope.ts +277 -0
  148. package/src/telemetry/exporters.ts +165 -0
  149. package/src/telemetry/lifecycle.ts +138 -0
  150. package/src/telemetry/metrics.ts +141 -0
  151. package/src/telemetry/plugin.ts +197 -0
  152. package/src/telemetry/registry.ts +424 -0
  153. package/src/telemetry/registryTypes.ts +63 -0
  154. package/src/telemetry/runtimeEndpoints.ts +172 -0
  155. package/src/telemetry.ts +1 -554
  156. package/src/telemetryCore.ts +34 -1332
  157. package/tests/contractGateAutopilot.test.ts +205 -0
  158. package/tests/contractGateSnapshotStore.test.ts +54 -1
  159. package/tests/helpers.ts +1 -0
  160. package/tests/moduleFederationCss.test.ts +1 -1
  161. package/tests/registration.test.ts +1 -1
  162. package/tests/telemetry.test.ts +51 -0
  163. package/tests/telemetryAutopilot.test.ts +141 -0
  164. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  165. package/tests/telemetryLifecycle.test.ts +253 -2
  166. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  167. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  168. package/dist/cjs/moduleFederationCss.js +0 -285
  169. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  170. package/dist/esm/moduleFederationCss.mjs +0 -225
  171. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  172. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  173. package/dist/types/moduleFederationCss.d.ts +0 -87
  174. package/src/contractGateSnapshotStore.ts +0 -420
  175. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,165 @@
1
+ import type { Monitors } from '@modern-js/types';
2
+
3
+ import type { ModuleFederationManifest } from './manifest';
4
+
5
+ import {
6
+ collectModuleFederationManifestCss,
7
+ getHostManifest,
8
+ normalizeRemoteEntry,
9
+ warn,
10
+ } from './manifest';
11
+
12
+ const DEFAULT_REMOTE_MANIFEST_TIMEOUT = 1500;
13
+
14
+ type FetchLike = (
15
+ input: string,
16
+ init?: {
17
+ signal?: AbortSignal;
18
+ },
19
+ ) => Promise<Response>;
20
+
21
+ export type CollectDirectRemoteModuleFederationCssOptions = {
22
+ fetcher?: FetchLike;
23
+ monitors?: Monitors;
24
+ timeout?: number;
25
+ };
26
+
27
+ const fetchJsonWithTimeout = async (
28
+ url: string,
29
+ fetcher: FetchLike,
30
+ timeout: number,
31
+ ) => {
32
+ const controller = new AbortController();
33
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
34
+
35
+ try {
36
+ const response = await Promise.race([
37
+ fetcher(url, { signal: controller.signal }),
38
+ new Promise<Response>((_, reject) => {
39
+ timeoutId = setTimeout(() => {
40
+ controller.abort();
41
+ reject(new Error(`Request timed out after ${timeout}ms`));
42
+ }, timeout);
43
+ }),
44
+ ]);
45
+
46
+ if (!response.ok) {
47
+ throw new Error(`Unexpected status ${response.status}`);
48
+ }
49
+
50
+ return (await response.json()) as ModuleFederationManifest;
51
+ } finally {
52
+ if (timeoutId) {
53
+ clearTimeout(timeoutId);
54
+ }
55
+ }
56
+ };
57
+
58
+ export type RemoteModuleFederationCssCollection = {
59
+ assets: string[];
60
+ /**
61
+ * True when at least one remote manifest fetch failed, i.e. `assets` may be
62
+ * incomplete and should not be cached long-term.
63
+ */
64
+ errored: boolean;
65
+ };
66
+
67
+ export const collectDirectRemoteModuleFederationCssWithMeta = async (
68
+ pwd: string,
69
+ options: CollectDirectRemoteModuleFederationCssOptions = {},
70
+ ): Promise<RemoteModuleFederationCssCollection> => {
71
+ const hostManifest = await getHostManifest(pwd, options.monitors);
72
+
73
+ if (!hostManifest) {
74
+ return { assets: [], errored: false };
75
+ }
76
+
77
+ const fetcher = options.fetcher || globalThis.fetch?.bind(globalThis);
78
+ if (!fetcher) {
79
+ warn(
80
+ options.monitors,
81
+ 'Skip module federation remote CSS collection because fetch is unavailable.',
82
+ );
83
+ return { assets: [], errored: false };
84
+ }
85
+
86
+ const timeout = options.timeout ?? DEFAULT_REMOTE_MANIFEST_TIMEOUT;
87
+
88
+ // Fetch all remote manifests in parallel so SSR latency is bounded by the
89
+ // slowest remote rather than the sum of all remotes.
90
+ const remoteResults = await Promise.all(
91
+ (hostManifest.remotes || []).map(
92
+ async (remote): Promise<{ assets: string[]; errored: boolean }> => {
93
+ if (!remote.entry) {
94
+ return { assets: [], errored: false };
95
+ }
96
+
97
+ const remoteEntry = normalizeRemoteEntry(remote.entry);
98
+ if (!remoteEntry) {
99
+ return { assets: [], errored: false };
100
+ }
101
+
102
+ let remoteManifestUrl: string;
103
+ try {
104
+ remoteManifestUrl = new URL(remoteEntry).toString();
105
+ } catch {
106
+ warn(
107
+ options.monitors,
108
+ 'Skip module federation remote CSS collection for non-absolute manifest URL %s',
109
+ remoteEntry,
110
+ );
111
+ return { assets: [], errored: false };
112
+ }
113
+
114
+ try {
115
+ const remoteManifest = await fetchJsonWithTimeout(
116
+ remoteManifestUrl,
117
+ fetcher,
118
+ timeout,
119
+ );
120
+ return {
121
+ assets: collectModuleFederationManifestCss(
122
+ remoteManifest,
123
+ remoteManifestUrl,
124
+ ),
125
+ errored: false,
126
+ };
127
+ } catch (error) {
128
+ warn(
129
+ options.monitors,
130
+ 'Load module federation remote manifest %s failed, error = %s',
131
+ remoteManifestUrl,
132
+ error instanceof Error ? error.message : error,
133
+ );
134
+ return { assets: [], errored: true };
135
+ }
136
+ },
137
+ ),
138
+ );
139
+
140
+ const cssAssets: string[] = [];
141
+ const seen = new Set<string>();
142
+ let errored = false;
143
+ for (const result of remoteResults) {
144
+ errored = errored || result.errored;
145
+ for (const asset of result.assets) {
146
+ if (!seen.has(asset)) {
147
+ seen.add(asset);
148
+ cssAssets.push(asset);
149
+ }
150
+ }
151
+ }
152
+
153
+ return { assets: cssAssets, errored };
154
+ };
155
+
156
+ export const collectDirectRemoteModuleFederationCss = async (
157
+ pwd: string,
158
+ options: CollectDirectRemoteModuleFederationCssOptions = {},
159
+ ) => {
160
+ const { assets } = await collectDirectRemoteModuleFederationCssWithMeta(
161
+ pwd,
162
+ options,
163
+ );
164
+ return assets;
165
+ };
@@ -0,0 +1,34 @@
1
+ export type {
2
+ RuntimeFallbackSignalAuthConfig,
3
+ RuntimeFallbackSignalConfig,
4
+ RuntimeFallbackSignalRuntimeState,
5
+ RuntimeFallbackSignalSource,
6
+ RuntimeFallbackSignalTrustContext,
7
+ RuntimeFallbackSignalTrustPolicy,
8
+ RuntimeSignalError,
9
+ RuntimeSignalErrorCode,
10
+ } from './model';
11
+ export {
12
+ createRuntimeSignalError,
13
+ DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS,
14
+ DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
15
+ DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES,
16
+ DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT,
17
+ DEFAULT_RUNTIME_STATUS_ENDPOINT,
18
+ getRuntimeSignalErrorStatusCode,
19
+ parseRuntimeFallbackSignalPayload,
20
+ parseRuntimeFallbackSignalPayloadFromRawBody,
21
+ } from './model';
22
+ export {
23
+ enforceRuntimeFallbackSignalAuth,
24
+ enforceRuntimeFallbackSignalAuthToken,
25
+ enforceRuntimeFallbackSignalTrustPolicy,
26
+ normalizeRequiredRuntimeFallbackSignalAuthConfig,
27
+ normalizeRuntimeFallbackSignalAuthConfig,
28
+ normalizeRuntimeFallbackTrustPolicy,
29
+ resolveRuntimeFallbackSignalEndpoint,
30
+ } from './resolver';
31
+ export {
32
+ createRuntimeFallbackSignalRuntimeState,
33
+ persistRuntimeFallbackContractGate,
34
+ } from './store';
@@ -0,0 +1,230 @@
1
+ import type { Context, ServerEnv } from '@modern-js/server-core';
2
+ import type { ContractGateSnapshotStore } from '../contract-gate-snapshot-store';
3
+
4
+ export const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT =
5
+ '/_modern/contract-gates/runtime-fallback';
6
+ export const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
7
+ export const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
8
+ export const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 5 * 60_000;
9
+ export const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16 * 1024;
10
+ export const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER =
11
+ 'x-modernjs-runtime-signal-token';
12
+ export const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
13
+ export const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60_000;
14
+ export const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10_000;
15
+
16
+ export type RuntimeSignalErrorCode =
17
+ | 'PAYLOAD_TOO_LARGE'
18
+ | 'INVALID_PAYLOAD'
19
+ | 'RATE_LIMITED'
20
+ | 'UNAUTHORIZED'
21
+ | 'UNTRUSTED_SOURCE';
22
+
23
+ export type RuntimeSignalError = Error & {
24
+ code?: RuntimeSignalErrorCode;
25
+ };
26
+
27
+ export type RuntimeFallbackSignalTrustPolicy = {
28
+ allowedApps: string[];
29
+ allowedEntryOrigins: string[];
30
+ expectedRuntimeDigests: Record<string, string>;
31
+ enforceRuntimeDigest: boolean;
32
+ maxSignalsPerWindow: number;
33
+ windowMs: number;
34
+ dedupeWindowMs: number;
35
+ };
36
+
37
+ type RuntimeFallbackSignalRateLimitState = {
38
+ count: number;
39
+ windowStartedAt: number;
40
+ };
41
+
42
+ export type RuntimeFallbackSignalAuthConfig = {
43
+ enabled: boolean;
44
+ headerName: string;
45
+ expectedValue?: string;
46
+ };
47
+
48
+ export type RuntimeFallbackSignalRuntimeState = {
49
+ rateLimitBySource: Map<string, RuntimeFallbackSignalRateLimitState>;
50
+ dedupeByFingerprint: Map<string, number>;
51
+ };
52
+
53
+ export type RuntimeFallbackSignalTrustContext = {
54
+ trustPolicy: RuntimeFallbackSignalTrustPolicy;
55
+ runtimeState: RuntimeFallbackSignalRuntimeState;
56
+ };
57
+
58
+ export type RuntimeFallbackSignalConfig = {
59
+ endpoint: string;
60
+ gateName: string;
61
+ gateSnapshotStore: Promise<ContractGateSnapshotStore>;
62
+ failureHoldMs: number;
63
+ maxBodyBytes: number;
64
+ auth: RuntimeFallbackSignalAuthConfig;
65
+ trustPolicy: RuntimeFallbackSignalTrustPolicy;
66
+ runtimeState: RuntimeFallbackSignalRuntimeState;
67
+ };
68
+
69
+ export type RuntimeFallbackSignalSource = {
70
+ /**
71
+ * Server-trusted connection identity (socket remote address). Never derive
72
+ * request headers or payload: both are attacker-controlled and would let
73
+ * callers reset their own rate-limit budget.
74
+ */
75
+ remoteAddress?: string;
76
+ };
77
+
78
+ export function createRuntimeSignalError(
79
+ message: string,
80
+ code: RuntimeSignalError['code'],
81
+ ) {
82
+ const error = new Error(message) as RuntimeSignalError;
83
+ error.code = code;
84
+ return error;
85
+ }
86
+
87
+ export function getRuntimeSignalErrorStatusCode(
88
+ signalError: RuntimeSignalError,
89
+ ): 400 | 401 | 403 | 413 | 429 | 500 {
90
+ if (signalError.code === 'PAYLOAD_TOO_LARGE') {
91
+ return 413;
92
+ }
93
+ if (signalError.code === 'INVALID_PAYLOAD') {
94
+ return 400;
95
+ }
96
+ if (signalError.code === 'UNAUTHORIZED') {
97
+ return 401;
98
+ }
99
+ if (signalError.code === 'RATE_LIMITED') {
100
+ return 429;
101
+ }
102
+ if (signalError.code === 'UNTRUSTED_SOURCE') {
103
+ return 403;
104
+ }
105
+ return 500;
106
+ }
107
+
108
+ export function normalizeRuntimeSignalOrigin(value: unknown) {
109
+ if (typeof value !== 'string' || value.trim().length === 0) {
110
+ return undefined;
111
+ }
112
+
113
+ try {
114
+ return new URL(value).origin;
115
+ } catch (_error) {
116
+ return undefined;
117
+ }
118
+ }
119
+
120
+ export function normalizeRuntimeSignalAppName(
121
+ payload: Record<string, unknown>,
122
+ ) {
123
+ if (typeof payload.appName !== 'string') {
124
+ return 'unknown';
125
+ }
126
+
127
+ const normalized = payload.appName.trim();
128
+ return normalized.length > 0 ? normalized : 'unknown';
129
+ }
130
+
131
+ export function normalizeRuntimeSignalRuntimeDigest(
132
+ payload: Record<string, unknown>,
133
+ ) {
134
+ if (
135
+ typeof payload.runtimeDigest === 'string' &&
136
+ payload.runtimeDigest.trim()
137
+ ) {
138
+ return payload.runtimeDigest.trim();
139
+ }
140
+
141
+ const metadata = payload.metadata;
142
+ if (
143
+ metadata &&
144
+ typeof metadata === 'object' &&
145
+ !Array.isArray(metadata) &&
146
+ typeof (metadata as Record<string, unknown>).runtimeDigest === 'string'
147
+ ) {
148
+ const digest = String(
149
+ (metadata as Record<string, unknown>).runtimeDigest,
150
+ ).trim();
151
+ if (digest) {
152
+ return digest;
153
+ }
154
+ }
155
+
156
+ return undefined;
157
+ }
158
+
159
+ function getUtf8ByteLength(input: string) {
160
+ if (typeof Buffer !== 'undefined') {
161
+ return Buffer.byteLength(input);
162
+ }
163
+
164
+ return new TextEncoder().encode(input).length;
165
+ }
166
+
167
+ export async function parseRuntimeFallbackSignalPayload(
168
+ c: Context<ServerEnv>,
169
+ maxBodyBytes: number,
170
+ ) {
171
+ const contentLengthHeader = c.req.header('content-length');
172
+ if (contentLengthHeader) {
173
+ const contentLength = Number.parseInt(contentLengthHeader, 10);
174
+ if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) {
175
+ throw createRuntimeSignalError(
176
+ 'runtime fallback signal payload too large',
177
+ 'PAYLOAD_TOO_LARGE',
178
+ );
179
+ }
180
+ }
181
+
182
+ const rawBody = await c.req.raw.text();
183
+ const payload = parseRuntimeFallbackSignalPayloadFromRawBody(
184
+ rawBody,
185
+ maxBodyBytes,
186
+ );
187
+
188
+ return {
189
+ rawBody,
190
+ payload,
191
+ };
192
+ }
193
+
194
+ export function parseRuntimeFallbackSignalPayloadFromRawBody(
195
+ rawBody: string,
196
+ maxBodyBytes: number,
197
+ ) {
198
+ if (!rawBody || rawBody.trim().length === 0) {
199
+ throw createRuntimeSignalError(
200
+ 'runtime fallback signal body empty',
201
+ 'INVALID_PAYLOAD',
202
+ );
203
+ }
204
+
205
+ if (getUtf8ByteLength(rawBody) > maxBodyBytes) {
206
+ throw createRuntimeSignalError(
207
+ 'runtime fallback signal payload too large',
208
+ 'PAYLOAD_TOO_LARGE',
209
+ );
210
+ }
211
+
212
+ let payload: unknown;
213
+ try {
214
+ payload = JSON.parse(rawBody);
215
+ } catch (_error) {
216
+ throw createRuntimeSignalError(
217
+ 'runtime fallback signal body must be valid JSON',
218
+ 'INVALID_PAYLOAD',
219
+ );
220
+ }
221
+
222
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
223
+ throw createRuntimeSignalError(
224
+ 'runtime fallback signal body must be a JSON object',
225
+ 'INVALID_PAYLOAD',
226
+ );
227
+ }
228
+
229
+ return payload as Record<string, unknown>;
230
+ }