@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.6 → 3.5.0-ultramodern.76

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 (179) 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/mfCache.js +2 -2
  10. package/dist/cjs/module-federation-css/collector.js +79 -0
  11. package/dist/cjs/module-federation-css/index.js +55 -0
  12. package/dist/cjs/module-federation-css/manifest.js +129 -0
  13. package/dist/cjs/module-federation-css/plugin.js +71 -0
  14. package/dist/cjs/module-federation-css/remote.js +133 -0
  15. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  16. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  17. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  18. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  19. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  20. package/dist/cjs/telemetry/canary.js +180 -0
  21. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  22. package/dist/cjs/telemetry/canarySetup.js +107 -0
  23. package/dist/cjs/telemetry/envelope.js +223 -0
  24. package/dist/cjs/telemetry/exporters.js +148 -0
  25. package/dist/cjs/telemetry/lifecycle.js +98 -0
  26. package/dist/cjs/telemetry/metrics.js +115 -0
  27. package/dist/cjs/telemetry/plugin.js +185 -0
  28. package/dist/cjs/telemetry/registry.js +296 -0
  29. package/dist/cjs/telemetry/registryTypes.js +46 -0
  30. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  31. package/dist/cjs/telemetry.js +32 -343
  32. package/dist/cjs/telemetryCore.js +14 -767
  33. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  34. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  35. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  36. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  37. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  38. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  39. package/dist/esm/contractGateAutopilot.mjs +21 -69
  40. package/dist/esm/index.mjs +1 -2
  41. package/dist/esm/mfCache.mjs +2 -2
  42. package/dist/esm/module-federation-css/collector.mjs +38 -0
  43. package/dist/esm/module-federation-css/index.mjs +4 -0
  44. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  45. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  46. package/dist/esm/module-federation-css/remote.mjs +92 -0
  47. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  48. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  49. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  50. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  51. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  52. package/dist/esm/telemetry/canary.mjs +142 -0
  53. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  54. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  55. package/dist/esm/telemetry/envelope.mjs +164 -0
  56. package/dist/esm/telemetry/exporters.mjs +104 -0
  57. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  58. package/dist/esm/telemetry/metrics.mjs +77 -0
  59. package/dist/esm/telemetry/plugin.mjs +87 -0
  60. package/dist/esm/telemetry/registry.mjs +258 -0
  61. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  62. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  63. package/dist/esm/telemetry.mjs +1 -275
  64. package/dist/esm/telemetryCore.mjs +6 -759
  65. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  69. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  70. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  71. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  72. package/dist/esm-node/index.mjs +1 -2
  73. package/dist/esm-node/mfCache.mjs +2 -2
  74. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  75. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  76. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  77. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  78. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  79. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  80. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  81. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  82. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  83. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  84. package/dist/esm-node/telemetry/canary.mjs +143 -0
  85. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  86. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  87. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  88. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  89. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  90. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  91. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  92. package/dist/esm-node/telemetry/registry.mjs +259 -0
  93. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  94. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  95. package/dist/esm-node/telemetry.mjs +1 -275
  96. package/dist/esm-node/telemetryCore.mjs +6 -759
  97. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  98. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  99. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  100. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  101. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  102. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  103. package/dist/types/contractGateAutopilot.d.ts +3 -6
  104. package/dist/types/index.d.ts +1 -2
  105. package/dist/types/module-federation-css/collector.d.ts +25 -0
  106. package/dist/types/module-federation-css/index.d.ts +8 -0
  107. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  108. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  109. package/dist/types/module-federation-css/remote.d.ts +20 -0
  110. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  111. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  112. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  113. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  114. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  115. package/dist/types/telemetry/canary.d.ts +85 -0
  116. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  117. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  118. package/dist/types/telemetry/envelope.d.ts +55 -0
  119. package/dist/types/telemetry/exporters.d.ts +12 -0
  120. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  121. package/dist/types/telemetry/metrics.d.ts +3 -0
  122. package/dist/types/telemetry/plugin.d.ts +12 -0
  123. package/dist/types/telemetry/registry.d.ts +69 -0
  124. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  125. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  126. package/dist/types/telemetry.d.ts +1 -12
  127. package/dist/types/telemetryCore.d.ts +6 -257
  128. package/package.json +11 -13
  129. package/src/contract-gate-snapshot-normalization.ts +155 -0
  130. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  131. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  132. package/src/contract-gate-snapshot-store/index.ts +20 -0
  133. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  134. package/src/contract-gate-snapshot-store/types.ts +64 -0
  135. package/src/contractGateAutopilot.ts +39 -131
  136. package/src/index.ts +1 -17
  137. package/src/mfCache.ts +3 -1
  138. package/src/module-federation-css/collector.ts +82 -0
  139. package/src/module-federation-css/index.ts +14 -0
  140. package/src/module-federation-css/manifest.ts +163 -0
  141. package/src/module-federation-css/plugin.ts +86 -0
  142. package/src/module-federation-css/remote.ts +165 -0
  143. package/src/runtime-fallback-signal/index.ts +34 -0
  144. package/src/runtime-fallback-signal/model.ts +230 -0
  145. package/src/runtime-fallback-signal/resolver.ts +304 -0
  146. package/src/runtime-fallback-signal/store.ts +78 -0
  147. package/src/runtimeFallbackSignal.ts +1 -584
  148. package/src/telemetry/canary.ts +291 -0
  149. package/src/telemetry/canaryEvaluation.ts +83 -0
  150. package/src/telemetry/canarySetup.ts +160 -0
  151. package/src/telemetry/envelope.ts +277 -0
  152. package/src/telemetry/exporters.ts +165 -0
  153. package/src/telemetry/lifecycle.ts +138 -0
  154. package/src/telemetry/metrics.ts +141 -0
  155. package/src/telemetry/plugin.ts +197 -0
  156. package/src/telemetry/registry.ts +424 -0
  157. package/src/telemetry/registryTypes.ts +63 -0
  158. package/src/telemetry/runtimeEndpoints.ts +172 -0
  159. package/src/telemetry.ts +1 -554
  160. package/src/telemetryCore.ts +34 -1332
  161. package/tests/contractGateAutopilot.test.ts +205 -0
  162. package/tests/contractGateSnapshotStore.test.ts +54 -1
  163. package/tests/helpers.ts +1 -0
  164. package/tests/moduleFederationCss.test.ts +1 -1
  165. package/tests/registration.test.ts +1 -1
  166. package/tests/telemetry.test.ts +51 -0
  167. package/tests/telemetryAutopilot.test.ts +141 -0
  168. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  169. package/tests/telemetryLifecycle.test.ts +253 -2
  170. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  171. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  172. package/dist/cjs/moduleFederationCss.js +0 -285
  173. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  174. package/dist/esm/moduleFederationCss.mjs +0 -225
  175. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  176. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  177. package/dist/types/moduleFederationCss.d.ts +0 -87
  178. package/src/contractGateSnapshotStore.ts +0 -420
  179. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,83 @@
1
+ import { promises as nodeFs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fs } from '@modern-js/utils';
4
+
5
+ import { parseServerRuntimeExtensionsEnv } from '../env';
6
+
7
+ import { normalizeSnapshot } from './resolve';
8
+
9
+ import type { ContractGateSnapshotStore } from './types';
10
+
11
+ import {
12
+ CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
13
+ DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
14
+ } from './types';
15
+
16
+ export const resolveContractGateSnapshotPath = (
17
+ appDirectory: string,
18
+ configuredPath: string | undefined,
19
+ ) => {
20
+ const rawPath =
21
+ configuredPath ||
22
+ parseServerRuntimeExtensionsEnv().contractGatesFile ||
23
+ DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH;
24
+ if (path.isAbsolute(rawPath)) {
25
+ return rawPath;
26
+ }
27
+ return path.resolve(appDirectory, rawPath);
28
+ };
29
+
30
+ const writeSnapshotFileAtomically = async (
31
+ resolvedPath: string,
32
+ contents: string,
33
+ ) => {
34
+ const directory = path.dirname(resolvedPath);
35
+ await nodeFs.mkdir(directory, { recursive: true });
36
+
37
+ const temporaryPath = path.join(
38
+ directory,
39
+ `.${path.basename(resolvedPath)}.${process.pid}.${Date.now()}.${Math.random()
40
+ .toString(36)
41
+ .slice(2)}.tmp`,
42
+ );
43
+
44
+ try {
45
+ await nodeFs.writeFile(temporaryPath, contents);
46
+ await nodeFs.rename(temporaryPath, resolvedPath);
47
+ } catch (error) {
48
+ await nodeFs.rm(temporaryPath, { force: true }).catch(() => {});
49
+ throw error;
50
+ }
51
+ };
52
+
53
+ export const createFileContractGateSnapshotStore = (
54
+ gateSnapshotPath: string,
55
+ ): ContractGateSnapshotStore => {
56
+ const resolvedPath = path.resolve(gateSnapshotPath);
57
+ return {
58
+ name: `file:${resolvedPath}`,
59
+ async readSnapshot() {
60
+ if (!(await fs.pathExists(resolvedPath))) {
61
+ return undefined;
62
+ }
63
+
64
+ try {
65
+ const raw = await nodeFs.readFile(resolvedPath, 'utf8');
66
+ return normalizeSnapshot(JSON.parse(raw));
67
+ } catch (_error) {
68
+ return undefined;
69
+ }
70
+ },
71
+ async writeSnapshot(snapshot) {
72
+ const normalized = normalizeSnapshot(snapshot) || {
73
+ schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
74
+ updatedAt: Date.now(),
75
+ gates: {},
76
+ };
77
+ await writeSnapshotFileAtomically(
78
+ resolvedPath,
79
+ `${JSON.stringify(normalized, null, 2)}\n`,
80
+ );
81
+ },
82
+ };
83
+ };
@@ -0,0 +1,159 @@
1
+ import { normalizeSnapshot } from './resolve';
2
+ import type {
3
+ ContractGateSnapshotHttpStoreOptions,
4
+ ContractGateSnapshotStore,
5
+ ContractGateSnapshotStoreUserConfig,
6
+ } from './types';
7
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from './types';
8
+
9
+ const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5_000;
10
+
11
+ const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
12
+ 'http',
13
+ // historical aliases kept for config compatibility with the era when these
14
+ // modules lived inside @modern-js/server-core.
15
+ '@modern-js/server-core/http',
16
+ '@modern-js/server-core/contract-gate-http-store',
17
+ '@modern-js/server-runtime-extensions/http',
18
+ '@modern-js/server-runtime-extensions/contract-gate-http-store',
19
+ ]);
20
+
21
+ const normalizeHttpStoreOptions = (
22
+ options: Record<string, unknown> | undefined,
23
+ ): ContractGateSnapshotHttpStoreOptions => {
24
+ const endpoint =
25
+ typeof options?.endpoint === 'string' ? options.endpoint.trim() : '';
26
+ if (!endpoint) {
27
+ throw new Error(
28
+ '[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint',
29
+ );
30
+ }
31
+
32
+ const readMethod =
33
+ typeof options?.readMethod === 'string' && options.readMethod.trim()
34
+ ? options.readMethod.trim().toUpperCase()
35
+ : 'GET';
36
+ const writeMethod =
37
+ typeof options?.writeMethod === 'string' && options.writeMethod.trim()
38
+ ? options.writeMethod.trim().toUpperCase()
39
+ : 'PUT';
40
+
41
+ const timeoutMsRaw = Number(options?.timeoutMs);
42
+ const timeoutMs =
43
+ Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0
44
+ ? Math.floor(timeoutMsRaw)
45
+ : DEFAULT_HTTP_STORE_TIMEOUT_MS;
46
+
47
+ const headersRaw = options?.headers;
48
+ const headers: Record<string, string> = {};
49
+ if (
50
+ headersRaw &&
51
+ typeof headersRaw === 'object' &&
52
+ !Array.isArray(headersRaw)
53
+ ) {
54
+ Object.entries(headersRaw).forEach(([key, value]) => {
55
+ if (typeof key === 'string' && key.trim().length > 0 && value != null) {
56
+ headers[key] = String(value);
57
+ }
58
+ });
59
+ }
60
+
61
+ return {
62
+ endpoint,
63
+ readMethod,
64
+ writeMethod,
65
+ headers,
66
+ timeoutMs,
67
+ };
68
+ };
69
+
70
+ const withTimeoutAbort = (timeoutMs: number) => {
71
+ const controller = new AbortController();
72
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
73
+ return {
74
+ signal: controller.signal,
75
+ clear: () => clearTimeout(timer),
76
+ };
77
+ };
78
+
79
+ export const createHttpContractGateSnapshotStore = (
80
+ options: ContractGateSnapshotHttpStoreOptions,
81
+ ): ContractGateSnapshotStore => {
82
+ const normalized = normalizeHttpStoreOptions(
83
+ options as unknown as Record<string, unknown>,
84
+ );
85
+ const endpoint = normalized.endpoint;
86
+
87
+ return {
88
+ name: `http:${endpoint}`,
89
+ async readSnapshot() {
90
+ const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5_000);
91
+ try {
92
+ const response = await fetch(endpoint, {
93
+ method: normalized.readMethod || 'GET',
94
+ headers: {
95
+ accept: 'application/json',
96
+ ...(normalized.headers || {}),
97
+ },
98
+ signal,
99
+ });
100
+
101
+ if (response.status === 404) {
102
+ return undefined;
103
+ }
104
+
105
+ if (!response.ok) {
106
+ throw new Error(
107
+ `HTTP stateStore read failed with status ${String(response.status)}`,
108
+ );
109
+ }
110
+
111
+ const payload = await response.json();
112
+ return normalizeSnapshot(payload);
113
+ } finally {
114
+ clear();
115
+ }
116
+ },
117
+ async writeSnapshot(snapshot) {
118
+ const body = JSON.stringify(
119
+ normalizeSnapshot(snapshot) || {
120
+ schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
121
+ updatedAt: Date.now(),
122
+ gates: {},
123
+ },
124
+ );
125
+ const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5_000);
126
+ try {
127
+ const response = await fetch(endpoint, {
128
+ method: normalized.writeMethod || 'PUT',
129
+ headers: {
130
+ 'content-type': 'application/json',
131
+ ...(normalized.headers || {}),
132
+ },
133
+ body,
134
+ signal,
135
+ });
136
+ if (!response.ok) {
137
+ throw new Error(
138
+ `HTTP stateStore write failed with status ${String(response.status)}`,
139
+ );
140
+ }
141
+ } finally {
142
+ clear();
143
+ }
144
+ },
145
+ };
146
+ };
147
+
148
+ export const tryResolveBuiltinSnapshotStore = (input: {
149
+ stateStore: ContractGateSnapshotStoreUserConfig;
150
+ }): ContractGateSnapshotStore | undefined => {
151
+ const moduleName = input.stateStore.module.trim();
152
+ if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) {
153
+ return undefined;
154
+ }
155
+
156
+ return createHttpContractGateSnapshotStore(
157
+ (input.stateStore.options || {}) as ContractGateSnapshotHttpStoreOptions,
158
+ );
159
+ };
@@ -0,0 +1,20 @@
1
+ export {
2
+ createFileContractGateSnapshotStore,
3
+ resolveContractGateSnapshotPath,
4
+ } from './file-store';
5
+ export { createHttpContractGateSnapshotStore } from './http-store';
6
+ export { resolveContractGateSnapshotStore } from './resolve';
7
+ export type {
8
+ ContractGateSnapshotHttpStoreOptions,
9
+ ContractGateSnapshotStore,
10
+ ContractGateSnapshotStoreFactory,
11
+ ContractGateSnapshotStoreFactoryContext,
12
+ ContractGateSnapshotStoreModule,
13
+ ContractGateSnapshotStoreUserConfig,
14
+ GateSnapshot,
15
+ GateSnapshotGateValue,
16
+ } from './types';
17
+ export {
18
+ CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
19
+ DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
20
+ } from './types';
@@ -0,0 +1,179 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ import { createFileContractGateSnapshotStore } from './file-store';
6
+
7
+ import { tryResolveBuiltinSnapshotStore } from './http-store';
8
+
9
+ import type {
10
+ ContractGateSnapshotStore,
11
+ ContractGateSnapshotStoreFactory,
12
+ ContractGateSnapshotStoreFactoryContext,
13
+ ContractGateSnapshotStoreModule,
14
+ ContractGateSnapshotStoreUserConfig,
15
+ GateSnapshot,
16
+ GateSnapshotGateValue,
17
+ LoggerLike,
18
+ } from './types';
19
+
20
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from './types';
21
+
22
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
23
+ typeof value === 'object' && value !== null && !Array.isArray(value);
24
+
25
+ export const normalizeSnapshot = (
26
+ snapshot: unknown,
27
+ ): GateSnapshot | undefined => {
28
+ if (!isRecord(snapshot)) {
29
+ return undefined;
30
+ }
31
+
32
+ const schemaVersion =
33
+ typeof snapshot.schemaVersion === 'number'
34
+ ? snapshot.schemaVersion
35
+ : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
36
+ const updatedAt =
37
+ typeof snapshot.updatedAt === 'number' ? snapshot.updatedAt : Date.now();
38
+ const gates = isRecord(snapshot.gates)
39
+ ? (snapshot.gates as Record<string, GateSnapshotGateValue>)
40
+ : {};
41
+
42
+ return {
43
+ schemaVersion,
44
+ updatedAt,
45
+ gates,
46
+ };
47
+ };
48
+
49
+ const pickStoreFactory = (
50
+ mod: ContractGateSnapshotStoreModule,
51
+ ): ContractGateSnapshotStoreFactory | undefined => {
52
+ if (typeof mod === 'function') {
53
+ return mod as unknown as ContractGateSnapshotStoreFactory;
54
+ }
55
+
56
+ if (typeof mod.createContractGateSnapshotStore === 'function') {
57
+ return mod.createContractGateSnapshotStore;
58
+ }
59
+
60
+ if (typeof mod.default === 'function') {
61
+ return mod.default;
62
+ }
63
+
64
+ if (
65
+ mod.default &&
66
+ typeof mod.default === 'object' &&
67
+ typeof mod.default.createContractGateSnapshotStore === 'function'
68
+ ) {
69
+ return mod.default.createContractGateSnapshotStore;
70
+ }
71
+
72
+ return undefined;
73
+ };
74
+
75
+ const ensureStoreShape = (
76
+ store: ContractGateSnapshotStore,
77
+ modulePath: string,
78
+ ) => {
79
+ if (
80
+ !store ||
81
+ typeof store !== 'object' ||
82
+ typeof store.readSnapshot !== 'function' ||
83
+ typeof store.writeSnapshot !== 'function'
84
+ ) {
85
+ throw new Error(
86
+ `Invalid contract gate snapshot store from "${modulePath}". Expected { readSnapshot(), writeSnapshot() }.`,
87
+ );
88
+ }
89
+ };
90
+
91
+ /**
92
+ * Resolves a user-configured stateStore module specifier from the app, not
93
+ * from this framework package: relative paths resolve against appDirectory,
94
+ * and bare package specifiers resolve through the app's own module graph
95
+ * (`createRequire` anchored at the app package.json). Resolving from the
96
+ * framework package breaks app-installed stores under pnpm's strict
97
+ * node_modules layout. Bare specifiers fall back to framework-local
98
+ * resolution for stores installed alongside the framework.
99
+ */
100
+ const resolveStoreModulePath = (appDirectory: string, modulePath: string) => {
101
+ const normalized = modulePath.trim();
102
+ if (!normalized) {
103
+ throw new Error(
104
+ 'Contract gate snapshot stateStore.module must be non-empty',
105
+ );
106
+ }
107
+
108
+ if (path.isAbsolute(normalized)) {
109
+ return normalized;
110
+ }
111
+
112
+ if (normalized.startsWith('.')) {
113
+ return path.resolve(appDirectory, normalized);
114
+ }
115
+
116
+ const appRequire = createRequire(path.join(appDirectory, 'package.json'));
117
+ try {
118
+ return appRequire.resolve(normalized);
119
+ } catch (_error) {
120
+ // Fall back to this package's own resolution so stores installed next to
121
+ // the framework keep working.
122
+ return normalized;
123
+ }
124
+ };
125
+
126
+ const toStoreModuleImportSpecifier = (modulePath: string) =>
127
+ path.isAbsolute(modulePath) ? pathToFileURL(modulePath).href : modulePath;
128
+
129
+ export const resolveContractGateSnapshotStore = async (input: {
130
+ appDirectory: string;
131
+ gateSnapshotPath: string;
132
+ stateStore?: ContractGateSnapshotStoreUserConfig;
133
+ logger?: LoggerLike;
134
+ }): Promise<ContractGateSnapshotStore> => {
135
+ const { appDirectory, gateSnapshotPath, stateStore, logger } = input;
136
+
137
+ if (!stateStore?.module) {
138
+ return createFileContractGateSnapshotStore(gateSnapshotPath);
139
+ }
140
+
141
+ const builtinStore = tryResolveBuiltinSnapshotStore({ stateStore });
142
+ if (builtinStore) {
143
+ logger?.info?.(
144
+ `[telemetry.canary.autopilot] using built-in contract gate snapshot store "${builtinStore.name}"`,
145
+ );
146
+ return builtinStore;
147
+ }
148
+
149
+ const modulePath = resolveStoreModulePath(appDirectory, stateStore.module);
150
+ let mod: ContractGateSnapshotStoreModule;
151
+ try {
152
+ mod = (await import(
153
+ toStoreModuleImportSpecifier(modulePath)
154
+ )) as ContractGateSnapshotStoreModule;
155
+ } catch (error) {
156
+ throw new Error(
157
+ `[telemetry.canary.autopilot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`,
158
+ );
159
+ }
160
+
161
+ const factory = pickStoreFactory(mod);
162
+ if (!factory) {
163
+ throw new Error(
164
+ `[telemetry.canary.autopilot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`,
165
+ );
166
+ }
167
+
168
+ const store = await factory({
169
+ appDirectory,
170
+ gateSnapshotPath,
171
+ options: stateStore.options,
172
+ logger,
173
+ });
174
+ ensureStoreShape(store, modulePath);
175
+ logger?.info?.(
176
+ `[telemetry.canary.autopilot] using contract gate snapshot store "${store.name || modulePath}"`,
177
+ );
178
+ return store;
179
+ };
@@ -0,0 +1,64 @@
1
+ export const CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = 1;
2
+
3
+ export const DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH =
4
+ '.modern/contract-gates.json';
5
+
6
+ export type GateSnapshotGateValue =
7
+ | boolean
8
+ | {
9
+ passed?: boolean;
10
+ reason?: string;
11
+ updatedAt?: number;
12
+ expiresAt?: number;
13
+ [key: string]: unknown;
14
+ };
15
+
16
+ export type GateSnapshot = {
17
+ schemaVersion?: number;
18
+ updatedAt?: number;
19
+ gates?: Record<string, GateSnapshotGateValue>;
20
+ };
21
+
22
+ export type LoggerLike = {
23
+ info?: (message: string) => void;
24
+ warn?: (message: string) => void;
25
+ };
26
+
27
+ export type ContractGateSnapshotStore = {
28
+ name: string;
29
+ readSnapshot: () => Promise<GateSnapshot | undefined>;
30
+ writeSnapshot: (snapshot: GateSnapshot) => Promise<void>;
31
+ };
32
+
33
+ export type ContractGateSnapshotStoreFactoryContext = {
34
+ appDirectory: string;
35
+ gateSnapshotPath: string;
36
+ options?: Record<string, unknown>;
37
+ logger?: LoggerLike;
38
+ };
39
+
40
+ export type ContractGateSnapshotStoreFactory = (
41
+ context: ContractGateSnapshotStoreFactoryContext,
42
+ ) => Promise<ContractGateSnapshotStore> | ContractGateSnapshotStore;
43
+
44
+ export type ContractGateSnapshotStoreModule = {
45
+ createContractGateSnapshotStore?: ContractGateSnapshotStoreFactory;
46
+ default?:
47
+ | ContractGateSnapshotStoreFactory
48
+ | {
49
+ createContractGateSnapshotStore?: ContractGateSnapshotStoreFactory;
50
+ };
51
+ };
52
+
53
+ export type ContractGateSnapshotStoreUserConfig = {
54
+ module: string;
55
+ options?: Record<string, unknown>;
56
+ };
57
+
58
+ export type ContractGateSnapshotHttpStoreOptions = {
59
+ endpoint: string;
60
+ readMethod?: string;
61
+ writeMethod?: string;
62
+ headers?: Record<string, string>;
63
+ timeoutMs?: number;
64
+ };