@bleedingdev/modern-js-surface-resolution 0.0.0 → 3.9.0-ultramodern.6

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 (28) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/surface-resolution/env-static-provider.js +318 -0
  3. package/dist/cjs/surface-resolution/index.js +69 -0
  4. package/dist/cjs/surface-resolution/surface-ref.js +132 -0
  5. package/dist/cjs/surface-resolution/types.js +18 -0
  6. package/dist/cjs/surface-resolution/validation.js +202 -0
  7. package/dist/esm/surface-resolution/env-static-provider.mjs +274 -0
  8. package/dist/esm/surface-resolution/index.mjs +3 -0
  9. package/dist/esm/surface-resolution/surface-ref.mjs +88 -0
  10. package/dist/esm/surface-resolution/types.mjs +0 -0
  11. package/dist/esm/surface-resolution/validation.mjs +155 -0
  12. package/dist/esm-node/surface-resolution/env-static-provider.mjs +275 -0
  13. package/dist/esm-node/surface-resolution/index.mjs +4 -0
  14. package/dist/esm-node/surface-resolution/surface-ref.mjs +89 -0
  15. package/dist/esm-node/surface-resolution/types.mjs +1 -0
  16. package/dist/esm-node/surface-resolution/validation.mjs +156 -0
  17. package/dist/types/surface-resolution/env-static-provider.d.ts +107 -0
  18. package/dist/types/surface-resolution/index.d.ts +4 -0
  19. package/dist/types/surface-resolution/surface-ref.d.ts +72 -0
  20. package/dist/types/surface-resolution/types.d.ts +102 -0
  21. package/dist/types/surface-resolution/validation.d.ts +53 -0
  22. package/package.json +40 -4
  23. package/src/surface-resolution/env-static-provider.ts +596 -0
  24. package/src/surface-resolution/index.ts +43 -0
  25. package/src/surface-resolution/surface-ref.ts +145 -0
  26. package/src/surface-resolution/types.ts +136 -0
  27. package/src/surface-resolution/validation.ts +337 -0
  28. package/README.md +0 -3
@@ -0,0 +1,155 @@
1
+ import { formatSurfaceRef } from "./surface-ref.mjs";
2
+ const SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
3
+ function createDiscoveryError(code, ref, message, details) {
4
+ const refString = 'string' == typeof ref ? ref : formatSurfaceRef(ref);
5
+ return void 0 === details ? {
6
+ code,
7
+ ref: refString,
8
+ message
9
+ } : {
10
+ code,
11
+ ref: refString,
12
+ message,
13
+ details
14
+ };
15
+ }
16
+ function isNonEmptyString(value) {
17
+ return 'string' == typeof value && value.length > 0;
18
+ }
19
+ function isValidUnitId(unitId) {
20
+ return unitId.split('/').every((segment)=>SEGMENT_PATTERN.test(segment));
21
+ }
22
+ function isRecord(value) {
23
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
24
+ }
25
+ const COMPATIBILITY_STATUSES = [
26
+ 'compatible',
27
+ 'incompatible',
28
+ 'degraded'
29
+ ];
30
+ const SURFACE_KINDS = [
31
+ 'component',
32
+ 'route',
33
+ 'api',
34
+ 'backend'
35
+ ];
36
+ const LOCATION_PLATFORMS = [
37
+ 'browser-mf-manifest',
38
+ 'node-mf-manifest',
39
+ 'http-api',
40
+ 'cloudflare-service-binding'
41
+ ];
42
+ const LOCATION_REQUIRED_FIELDS = {
43
+ 'browser-mf-manifest': [
44
+ 'manifestUrl'
45
+ ],
46
+ 'node-mf-manifest': [
47
+ 'manifestRef'
48
+ ],
49
+ 'http-api': [
50
+ 'baseUrl',
51
+ 'prefix'
52
+ ],
53
+ 'cloudflare-service-binding': [
54
+ 'serviceBinding'
55
+ ]
56
+ };
57
+ function validateLocation(location, path, seenPlatforms, push) {
58
+ if (!isRecord(location)) return void push(path, 'must be an object');
59
+ const platform = location.platform;
60
+ if ('string' != typeof platform || !LOCATION_PLATFORMS.includes(platform)) return void push(`${path}.platform`, `must be one of ${LOCATION_PLATFORMS.join(', ')}`);
61
+ if (seenPlatforms.has(platform)) push(`${path}.platform`, `duplicate platform ${platform} within one surface`);
62
+ seenPlatforms.add(platform);
63
+ for (const field of LOCATION_REQUIRED_FIELDS[platform] ?? [])if (!isNonEmptyString(location[field])) push(`${path}.${field}`, 'must be a non-empty string');
64
+ if ('cloudflare-service-binding' === platform && void 0 !== location.dispatchNamespace && !isNonEmptyString(location.dispatchNamespace)) push(`${path}.dispatchNamespace`, 'must be a non-empty string when present');
65
+ }
66
+ function validateSurface(surface, path, seenSurfaceIds, push) {
67
+ if (!isRecord(surface)) return void push(path, 'must be an object');
68
+ if (isNonEmptyString(surface.surfaceId)) if (SEGMENT_PATTERN.test(surface.surfaceId)) if (seenSurfaceIds.has(surface.surfaceId)) push(`${path}.surfaceId`, 'must be unique within the record');
69
+ else seenSurfaceIds.add(surface.surfaceId);
70
+ else push(`${path}.surfaceId`, 'must match the SurfaceRef SurfaceId grammar');
71
+ else push(`${path}.surfaceId`, 'must be a non-empty string');
72
+ if ('string' != typeof surface.kind || !SURFACE_KINDS.includes(surface.kind)) push(`${path}.kind`, `must be one of ${SURFACE_KINDS.join(', ')}`);
73
+ if (void 0 !== surface.servedMajor && (!Number.isSafeInteger(surface.servedMajor) || surface.servedMajor < 1)) push(`${path}.servedMajor`, 'must be a positive safe integer when present');
74
+ if (!Array.isArray(surface.locations)) return void push(`${path}.locations`, 'must be an array of locations');
75
+ if (0 === surface.locations.length) push(`${path}.locations`, 'must contain at least one location (no partial records)');
76
+ const seenPlatforms = new Set();
77
+ surface.locations.forEach((location, locationIndex)=>{
78
+ validateLocation(location, `${path}.locations[${locationIndex}]`, seenPlatforms, push);
79
+ });
80
+ }
81
+ function validateResolvedDeliveryUnit(unit) {
82
+ const issues = [];
83
+ const push = (path, message)=>{
84
+ issues.push({
85
+ path,
86
+ message
87
+ });
88
+ };
89
+ if (!isRecord(unit)) {
90
+ push('', 'must be an object');
91
+ return {
92
+ ok: false,
93
+ issues
94
+ };
95
+ }
96
+ const raw = unit;
97
+ if (isNonEmptyString(raw.unitId)) {
98
+ if (!isValidUnitId(raw.unitId)) push('unitId', 'must match the SurfaceRef UnitId grammar');
99
+ } else push('unitId', 'must be a non-empty string');
100
+ if (!isNonEmptyString(raw.buildMarker)) push('buildMarker', 'must be a non-empty string');
101
+ if (!isNonEmptyString(raw.sourceRevision)) push('sourceRevision', 'must be a non-empty string');
102
+ if (!isNonEmptyString(raw.baselineCohortId)) push('baselineCohortId', 'must be a non-empty string');
103
+ const compatibility = raw.compatibility;
104
+ if (isRecord(compatibility)) {
105
+ if ('string' != typeof compatibility.status || !COMPATIBILITY_STATUSES.includes(compatibility.status)) push('compatibility.status', `must be one of ${COMPATIBILITY_STATUSES.join(', ')}`);
106
+ if (compatibility.baselineCohortId !== raw.baselineCohortId) push('compatibility.baselineCohortId', 'must equal the record-level baselineCohortId (one verdict per record)');
107
+ if (void 0 !== compatibility.reason && !isNonEmptyString(compatibility.reason)) push('compatibility.reason', 'must be a non-empty string when present');
108
+ } else push('compatibility', 'must be an object');
109
+ if (!Array.isArray(raw.surfaces)) {
110
+ push('surfaces', 'must be an array of surfaces');
111
+ return {
112
+ ok: false,
113
+ issues
114
+ };
115
+ }
116
+ if (0 === raw.surfaces.length) push('surfaces', 'must contain at least one surface');
117
+ const seenSurfaceIds = new Set();
118
+ raw.surfaces.forEach((surface, surfaceIndex)=>{
119
+ validateSurface(surface, `surfaces[${surfaceIndex}]`, seenSurfaceIds, push);
120
+ });
121
+ return {
122
+ ok: 0 === issues.length,
123
+ issues
124
+ };
125
+ }
126
+ function selectResolvedSurface(unit, ref) {
127
+ if (unit.unitId !== ref.unitId) return {
128
+ ok: false,
129
+ error: createDiscoveryError('unknown-unit', ref, `Resolved record is for unit ${unit.unitId}, not ${ref.unitId}.`, {
130
+ recordUnitId: unit.unitId
131
+ })
132
+ };
133
+ const surface = unit.surfaces.find((candidate)=>candidate.surfaceId === ref.surfaceId);
134
+ if (void 0 === surface) return {
135
+ ok: false,
136
+ error: createDiscoveryError('unknown-surface', ref, `Unit ${unit.unitId} (buildMarker ${unit.buildMarker}) does not publish surface ${ref.surfaceId}.`, {
137
+ availableSurfaces: unit.surfaces.map((entry)=>entry.surfaceId)
138
+ })
139
+ };
140
+ return {
141
+ ok: true,
142
+ surface
143
+ };
144
+ }
145
+ function matchDeliveryUnitIdentity(expected, unit, ref) {
146
+ if (expected.unitId === unit.unitId && expected.buildMarker === unit.buildMarker) return;
147
+ return createDiscoveryError('identity-mismatch', ref, `Delivery-unit identity mismatch: expected ${expected.unitId}@${expected.buildMarker}, resolved ${unit.unitId}@${unit.buildMarker}.`, {
148
+ expected,
149
+ resolved: {
150
+ unitId: unit.unitId,
151
+ buildMarker: unit.buildMarker
152
+ }
153
+ });
154
+ }
155
+ export { createDiscoveryError, matchDeliveryUnitIdentity, selectResolvedSurface, validateResolvedDeliveryUnit };
@@ -0,0 +1,275 @@
1
+ import "node:module";
2
+ import { formatSurfaceRef } from "./surface-ref.mjs";
3
+ import { createDiscoveryError, validateResolvedDeliveryUnit } from "./validation.mjs";
4
+ const DEFAULT_LOCAL_ENVIRONMENTS = [
5
+ 'development',
6
+ 'local'
7
+ ];
8
+ const ENV_STATIC_PROVIDER_NAME = 'env-static';
9
+ function trimTrailingSlashes(value) {
10
+ return value.replace(/\/+$/u, '');
11
+ }
12
+ function envValue(env, name) {
13
+ const value = env[name]?.trim();
14
+ return void 0 !== value && value.length > 0 ? value : void 0;
15
+ }
16
+ function stripMfNamePrefix(value, mfName) {
17
+ return value.startsWith(`${mfName}@`) ? value.slice(mfName.length + 1) : value;
18
+ }
19
+ function createEnvContext(env, allowLocalFallback) {
20
+ return {
21
+ env,
22
+ allowLocalFallback,
23
+ cloudflareDeployEnabled: 'cloudflare' === env.MODERNJS_DEPLOY,
24
+ workersDevSubdomain: envValue(env, 'ULTRAMODERN_CLOUDFLARE_WORKERS_DEV_SUBDOMAIN'),
25
+ requireCloudflarePublicUrls: 'true' === env.ULTRAMODERN_CLOUDFLARE_REQUIRE_PUBLIC_URLS
26
+ };
27
+ }
28
+ function resolveBaseUrl(context, unit) {
29
+ const publicUrlEnv = `ULTRAMODERN_PUBLIC_URL_${unit.envSegment}`;
30
+ const configuredPublicUrl = envValue(context.env, publicUrlEnv);
31
+ if (void 0 !== configuredPublicUrl) return {
32
+ ok: true,
33
+ baseUrl: trimTrailingSlashes(configuredPublicUrl)
34
+ };
35
+ if (context.cloudflareDeployEnabled && void 0 !== context.workersDevSubdomain && void 0 !== unit.workerName) return {
36
+ ok: true,
37
+ baseUrl: `https://${unit.workerName}.${context.workersDevSubdomain}.workers.dev`
38
+ };
39
+ if (context.cloudflareDeployEnabled && context.requireCloudflarePublicUrls) return {
40
+ ok: false,
41
+ reason: `Cloudflare deploy requires ${publicUrlEnv} (or a configured manifest env / ULTRAMODERN_CLOUDFLARE_WORKERS_DEV_SUBDOMAIN with a worker name)`,
42
+ details: {
43
+ publicUrlEnv
44
+ }
45
+ };
46
+ if (void 0 !== unit.port && context.allowLocalFallback) return {
47
+ ok: true,
48
+ baseUrl: `http://localhost:${unit.port}`
49
+ };
50
+ if (void 0 !== unit.port) return {
51
+ ok: false,
52
+ reason: `No base URL available: set ${publicUrlEnv} (localhost fallback is disabled outside designated local environments)`,
53
+ details: {
54
+ publicUrlEnv
55
+ }
56
+ };
57
+ return {
58
+ ok: false,
59
+ reason: `No base URL available: set ${publicUrlEnv} or configure a localhost port`,
60
+ details: {
61
+ publicUrlEnv
62
+ }
63
+ };
64
+ }
65
+ function resolveBrowserMfManifest(context, unit) {
66
+ const manifestEnv = `VERTICAL_${unit.envSegment}_MF_MANIFEST`;
67
+ const configuredManifest = envValue(context.env, manifestEnv);
68
+ if (void 0 !== configuredManifest) return {
69
+ ok: true,
70
+ location: {
71
+ platform: 'browser-mf-manifest',
72
+ manifestUrl: stripMfNamePrefix(configuredManifest, unit.mfName)
73
+ }
74
+ };
75
+ const base = resolveBaseUrl(context, unit);
76
+ if (!base.ok) return {
77
+ ok: false,
78
+ reason: `browser-mf-manifest unavailable (${manifestEnv} unset; ${base.reason})`,
79
+ details: {
80
+ manifestEnv,
81
+ ...base.details
82
+ }
83
+ };
84
+ return {
85
+ ok: true,
86
+ location: {
87
+ platform: 'browser-mf-manifest',
88
+ manifestUrl: `${base.baseUrl}/mf-manifest.json`
89
+ }
90
+ };
91
+ }
92
+ function resolveNodeMfManifest(context, unit) {
93
+ const manifestEnv = `VERTICAL_${unit.envSegment}_BACKEND_MF_MANIFEST`;
94
+ const configuredManifest = envValue(context.env, manifestEnv);
95
+ if (void 0 !== configuredManifest) return {
96
+ ok: true,
97
+ location: {
98
+ platform: 'node-mf-manifest',
99
+ manifestRef: configuredManifest
100
+ }
101
+ };
102
+ if (void 0 !== unit.port && context.allowLocalFallback) return {
103
+ ok: true,
104
+ location: {
105
+ platform: 'node-mf-manifest',
106
+ manifestRef: `http://localhost:${unit.port}/backend-mf-manifest.json`
107
+ }
108
+ };
109
+ if (void 0 !== unit.port) return {
110
+ ok: false,
111
+ reason: `node-mf-manifest unavailable: set ${manifestEnv} (localhost fallback is disabled outside designated local environments)`,
112
+ details: {
113
+ manifestEnv
114
+ }
115
+ };
116
+ return {
117
+ ok: false,
118
+ reason: `node-mf-manifest unavailable: set ${manifestEnv} or configure a localhost port`,
119
+ details: {
120
+ manifestEnv
121
+ }
122
+ };
123
+ }
124
+ function resolveHttpApi(context, unit, config) {
125
+ const base = resolveBaseUrl(context, unit);
126
+ if (!base.ok) return {
127
+ ok: false,
128
+ reason: `http-api unavailable (${base.reason})`,
129
+ details: base.details
130
+ };
131
+ return {
132
+ ok: true,
133
+ location: {
134
+ platform: 'http-api',
135
+ baseUrl: base.baseUrl,
136
+ prefix: config.prefix
137
+ }
138
+ };
139
+ }
140
+ function resolveCloudflareServiceBinding(config) {
141
+ if (0 === config.serviceBinding.length) return {
142
+ ok: false,
143
+ reason: 'cloudflare-service-binding unavailable: empty serviceBinding'
144
+ };
145
+ return {
146
+ ok: true,
147
+ location: {
148
+ platform: 'cloudflare-service-binding',
149
+ serviceBinding: config.serviceBinding,
150
+ ...void 0 === config.dispatchNamespace ? {} : {
151
+ dispatchNamespace: config.dispatchNamespace
152
+ }
153
+ }
154
+ };
155
+ }
156
+ function resolveSurfaceLocations(context, unit, surface) {
157
+ const outcomes = [];
158
+ if (surface.platforms.browserMfManifest) outcomes.push(resolveBrowserMfManifest(context, unit));
159
+ if (surface.platforms.nodeMfManifest) outcomes.push(resolveNodeMfManifest(context, unit));
160
+ if (void 0 !== surface.platforms.httpApi) outcomes.push(resolveHttpApi(context, unit, surface.platforms.httpApi));
161
+ if (void 0 !== surface.platforms.cloudflareServiceBinding) outcomes.push(resolveCloudflareServiceBinding(surface.platforms.cloudflareServiceBinding));
162
+ const failure = outcomes.find((outcome)=>!outcome.ok);
163
+ if (void 0 !== failure && !failure.ok) return {
164
+ ok: false,
165
+ reason: `surface ${surface.surfaceId}: ${failure.reason}`,
166
+ details: failure.details
167
+ };
168
+ const locations = outcomes.flatMap((outcome)=>outcome.ok ? [
169
+ outcome.location
170
+ ] : []);
171
+ if (0 === locations.length) return {
172
+ ok: false,
173
+ reason: `surface ${surface.surfaceId} declares no platform locations`
174
+ };
175
+ return {
176
+ ok: true,
177
+ surface: {
178
+ surfaceId: surface.surfaceId,
179
+ kind: surface.kind,
180
+ locations
181
+ }
182
+ };
183
+ }
184
+ function createEnvStaticSurfaceResolutionProvider(options) {
185
+ const env = options.env ?? {};
186
+ const localEnvironments = new Set(options.localEnvironments ?? DEFAULT_LOCAL_ENVIRONMENTS);
187
+ const identityVerification = options.identityVerification ?? 'static-trust';
188
+ const unitsById = new Map(options.units.map((unit)=>[
189
+ unit.unitId,
190
+ unit
191
+ ]));
192
+ return {
193
+ name: ENV_STATIC_PROVIDER_NAME,
194
+ resolve (ref, environment) {
195
+ const refString = formatSurfaceRef(ref);
196
+ const unit = unitsById.get(ref.unitId);
197
+ if (void 0 === unit) return {
198
+ ok: false,
199
+ error: createDiscoveryError('unknown-unit', refString, `No statically configured delivery unit ${ref.unitId}.`, {
200
+ environment,
201
+ knownUnits: [
202
+ ...unitsById.keys()
203
+ ]
204
+ })
205
+ };
206
+ if (!unit.surfaces.some((surface)=>surface.surfaceId === ref.surfaceId)) return {
207
+ ok: false,
208
+ error: createDiscoveryError('unknown-surface', refString, `Unit ${unit.unitId} does not declare surface ${ref.surfaceId}.`, {
209
+ environment,
210
+ availableSurfaces: unit.surfaces.map((surface)=>surface.surfaceId)
211
+ })
212
+ };
213
+ let effectiveUnit = unit;
214
+ if (void 0 !== ref.major) {
215
+ const majorConfig = (unit.majors ?? []).find((candidate)=>candidate.major === ref.major);
216
+ if (void 0 === majorConfig) return {
217
+ ok: false,
218
+ error: createDiscoveryError('major-not-published', refString, `Unit ${unit.unitId} has no materialization for external major v${ref.major}.`, {
219
+ environment,
220
+ publishedMajors: (unit.majors ?? []).map((candidate)=>candidate.major)
221
+ })
222
+ };
223
+ effectiveUnit = {
224
+ ...unit,
225
+ envSegment: majorConfig.envSegment ?? `${unit.envSegment}_V${majorConfig.major}`,
226
+ port: majorConfig.port,
227
+ workerName: majorConfig.workerName
228
+ };
229
+ }
230
+ const context = createEnvContext(env, localEnvironments.has(environment));
231
+ const surfaces = [];
232
+ for (const surfaceConfig of unit.surfaces){
233
+ const resolved = resolveSurfaceLocations(context, effectiveUnit, surfaceConfig);
234
+ if (!resolved.ok) return {
235
+ ok: false,
236
+ error: createDiscoveryError('provider-unavailable', refString, `env-static provider cannot assemble a complete record for ${unit.unitId}: ${resolved.reason}.`, {
237
+ environment,
238
+ ...resolved.details
239
+ })
240
+ };
241
+ surfaces.push(void 0 === ref.major ? resolved.surface : {
242
+ ...resolved.surface,
243
+ servedMajor: ref.major
244
+ });
245
+ }
246
+ const record = {
247
+ unitId: unit.unitId,
248
+ buildMarker: unit.buildMarker,
249
+ sourceRevision: unit.sourceRevision,
250
+ baselineCohortId: unit.baselineCohortId,
251
+ surfaces,
252
+ compatibility: {
253
+ status: 'compatible',
254
+ baselineCohortId: unit.baselineCohortId,
255
+ ...'static-trust' === identityVerification ? {
256
+ reason: 'static-identity-unverified'
257
+ } : {}
258
+ }
259
+ };
260
+ const validation = validateResolvedDeliveryUnit(record);
261
+ if (!validation.ok) return {
262
+ ok: false,
263
+ error: createDiscoveryError('provider-unavailable', refString, `env-static provider assembled an invalid record for ${unit.unitId}.`, {
264
+ environment,
265
+ issues: validation.issues
266
+ })
267
+ };
268
+ return {
269
+ ok: true,
270
+ unit: record
271
+ };
272
+ }
273
+ };
274
+ }
275
+ export { DEFAULT_LOCAL_ENVIRONMENTS, ENV_STATIC_PROVIDER_NAME, createEnvStaticSurfaceResolutionProvider };
@@ -0,0 +1,4 @@
1
+ import "node:module";
2
+ export { DEFAULT_LOCAL_ENVIRONMENTS, ENV_STATIC_PROVIDER_NAME, createEnvStaticSurfaceResolutionProvider } from "./env-static-provider.mjs";
3
+ export { formatSurfaceRef, parseSurfaceRef, validateSurfaceRef } from "./surface-ref.mjs";
4
+ export { createDiscoveryError, matchDeliveryUnitIdentity, selectResolvedSurface, validateResolvedDeliveryUnit } from "./validation.mjs";
@@ -0,0 +1,89 @@
1
+ import "node:module";
2
+ const SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
3
+ const MAJOR_PATTERN = /^v[1-9][0-9]*$/;
4
+ function parseSurfaceRef(input) {
5
+ if ('' === input) return {
6
+ ok: false,
7
+ error: {
8
+ code: 'empty'
9
+ }
10
+ };
11
+ const hashCount = countChar(input, '#');
12
+ if (0 === hashCount) return {
13
+ ok: false,
14
+ error: {
15
+ code: 'missing-surface-separator'
16
+ }
17
+ };
18
+ if (hashCount > 1) return {
19
+ ok: false,
20
+ error: {
21
+ code: 'multiple-surface-separators'
22
+ }
23
+ };
24
+ const hashIndex = input.indexOf('#');
25
+ const unitPart = input.slice(0, hashIndex);
26
+ const rest = input.slice(hashIndex + 1);
27
+ const atIndex = rest.indexOf('@');
28
+ const surfaceId = -1 === atIndex ? rest : rest.slice(0, atIndex);
29
+ const ref = {
30
+ unitId: unitPart,
31
+ surfaceId
32
+ };
33
+ if (-1 !== atIndex) {
34
+ const majorPart = rest.slice(atIndex + 1);
35
+ if ('' === majorPart) return {
36
+ ok: false,
37
+ error: {
38
+ code: 'empty-major'
39
+ }
40
+ };
41
+ if (!MAJOR_PATTERN.test(majorPart)) return {
42
+ ok: false,
43
+ error: {
44
+ code: 'invalid-major',
45
+ value: majorPart
46
+ }
47
+ };
48
+ ref.major = Number(majorPart.slice(1));
49
+ }
50
+ const error = validateSurfaceRef(ref);
51
+ return void 0 === error ? {
52
+ ok: true,
53
+ ref
54
+ } : {
55
+ ok: false,
56
+ error
57
+ };
58
+ }
59
+ function formatSurfaceRef(ref) {
60
+ const error = validateSurfaceRef(ref);
61
+ if (void 0 !== error) throw new TypeError(`Cannot format invalid SurfaceRef: ${error.code}.`);
62
+ const base = `${ref.unitId}#${ref.surfaceId}`;
63
+ return void 0 === ref.major ? base : `${base}@v${ref.major}`;
64
+ }
65
+ function validateSurfaceRef(ref) {
66
+ if ('' === ref.unitId) return {
67
+ code: 'empty-unit-id'
68
+ };
69
+ for (const segment of ref.unitId.split('/'))if (!SEGMENT_PATTERN.test(segment)) return {
70
+ code: 'invalid-unit-id',
71
+ segment
72
+ };
73
+ if ('' === ref.surfaceId) return {
74
+ code: 'empty-surface-id'
75
+ };
76
+ if (!SEGMENT_PATTERN.test(ref.surfaceId)) return {
77
+ code: 'invalid-surface-id'
78
+ };
79
+ if (void 0 !== ref.major && (!Number.isSafeInteger(ref.major) || ref.major < 1)) return {
80
+ code: 'invalid-major',
81
+ value: String(ref.major)
82
+ };
83
+ }
84
+ function countChar(input, char) {
85
+ let count = 0;
86
+ for (const current of input)if (current === char) count += 1;
87
+ return count;
88
+ }
89
+ export { formatSurfaceRef, parseSurfaceRef, validateSurfaceRef };
@@ -0,0 +1 @@
1
+ import "node:module";
@@ -0,0 +1,156 @@
1
+ import "node:module";
2
+ import { formatSurfaceRef } from "./surface-ref.mjs";
3
+ const SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
4
+ function createDiscoveryError(code, ref, message, details) {
5
+ const refString = 'string' == typeof ref ? ref : formatSurfaceRef(ref);
6
+ return void 0 === details ? {
7
+ code,
8
+ ref: refString,
9
+ message
10
+ } : {
11
+ code,
12
+ ref: refString,
13
+ message,
14
+ details
15
+ };
16
+ }
17
+ function isNonEmptyString(value) {
18
+ return 'string' == typeof value && value.length > 0;
19
+ }
20
+ function isValidUnitId(unitId) {
21
+ return unitId.split('/').every((segment)=>SEGMENT_PATTERN.test(segment));
22
+ }
23
+ function isRecord(value) {
24
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
25
+ }
26
+ const COMPATIBILITY_STATUSES = [
27
+ 'compatible',
28
+ 'incompatible',
29
+ 'degraded'
30
+ ];
31
+ const SURFACE_KINDS = [
32
+ 'component',
33
+ 'route',
34
+ 'api',
35
+ 'backend'
36
+ ];
37
+ const LOCATION_PLATFORMS = [
38
+ 'browser-mf-manifest',
39
+ 'node-mf-manifest',
40
+ 'http-api',
41
+ 'cloudflare-service-binding'
42
+ ];
43
+ const LOCATION_REQUIRED_FIELDS = {
44
+ 'browser-mf-manifest': [
45
+ 'manifestUrl'
46
+ ],
47
+ 'node-mf-manifest': [
48
+ 'manifestRef'
49
+ ],
50
+ 'http-api': [
51
+ 'baseUrl',
52
+ 'prefix'
53
+ ],
54
+ 'cloudflare-service-binding': [
55
+ 'serviceBinding'
56
+ ]
57
+ };
58
+ function validateLocation(location, path, seenPlatforms, push) {
59
+ if (!isRecord(location)) return void push(path, 'must be an object');
60
+ const platform = location.platform;
61
+ if ('string' != typeof platform || !LOCATION_PLATFORMS.includes(platform)) return void push(`${path}.platform`, `must be one of ${LOCATION_PLATFORMS.join(', ')}`);
62
+ if (seenPlatforms.has(platform)) push(`${path}.platform`, `duplicate platform ${platform} within one surface`);
63
+ seenPlatforms.add(platform);
64
+ for (const field of LOCATION_REQUIRED_FIELDS[platform] ?? [])if (!isNonEmptyString(location[field])) push(`${path}.${field}`, 'must be a non-empty string');
65
+ if ('cloudflare-service-binding' === platform && void 0 !== location.dispatchNamespace && !isNonEmptyString(location.dispatchNamespace)) push(`${path}.dispatchNamespace`, 'must be a non-empty string when present');
66
+ }
67
+ function validateSurface(surface, path, seenSurfaceIds, push) {
68
+ if (!isRecord(surface)) return void push(path, 'must be an object');
69
+ if (isNonEmptyString(surface.surfaceId)) if (SEGMENT_PATTERN.test(surface.surfaceId)) if (seenSurfaceIds.has(surface.surfaceId)) push(`${path}.surfaceId`, 'must be unique within the record');
70
+ else seenSurfaceIds.add(surface.surfaceId);
71
+ else push(`${path}.surfaceId`, 'must match the SurfaceRef SurfaceId grammar');
72
+ else push(`${path}.surfaceId`, 'must be a non-empty string');
73
+ if ('string' != typeof surface.kind || !SURFACE_KINDS.includes(surface.kind)) push(`${path}.kind`, `must be one of ${SURFACE_KINDS.join(', ')}`);
74
+ if (void 0 !== surface.servedMajor && (!Number.isSafeInteger(surface.servedMajor) || surface.servedMajor < 1)) push(`${path}.servedMajor`, 'must be a positive safe integer when present');
75
+ if (!Array.isArray(surface.locations)) return void push(`${path}.locations`, 'must be an array of locations');
76
+ if (0 === surface.locations.length) push(`${path}.locations`, 'must contain at least one location (no partial records)');
77
+ const seenPlatforms = new Set();
78
+ surface.locations.forEach((location, locationIndex)=>{
79
+ validateLocation(location, `${path}.locations[${locationIndex}]`, seenPlatforms, push);
80
+ });
81
+ }
82
+ function validateResolvedDeliveryUnit(unit) {
83
+ const issues = [];
84
+ const push = (path, message)=>{
85
+ issues.push({
86
+ path,
87
+ message
88
+ });
89
+ };
90
+ if (!isRecord(unit)) {
91
+ push('', 'must be an object');
92
+ return {
93
+ ok: false,
94
+ issues
95
+ };
96
+ }
97
+ const raw = unit;
98
+ if (isNonEmptyString(raw.unitId)) {
99
+ if (!isValidUnitId(raw.unitId)) push('unitId', 'must match the SurfaceRef UnitId grammar');
100
+ } else push('unitId', 'must be a non-empty string');
101
+ if (!isNonEmptyString(raw.buildMarker)) push('buildMarker', 'must be a non-empty string');
102
+ if (!isNonEmptyString(raw.sourceRevision)) push('sourceRevision', 'must be a non-empty string');
103
+ if (!isNonEmptyString(raw.baselineCohortId)) push('baselineCohortId', 'must be a non-empty string');
104
+ const compatibility = raw.compatibility;
105
+ if (isRecord(compatibility)) {
106
+ if ('string' != typeof compatibility.status || !COMPATIBILITY_STATUSES.includes(compatibility.status)) push('compatibility.status', `must be one of ${COMPATIBILITY_STATUSES.join(', ')}`);
107
+ if (compatibility.baselineCohortId !== raw.baselineCohortId) push('compatibility.baselineCohortId', 'must equal the record-level baselineCohortId (one verdict per record)');
108
+ if (void 0 !== compatibility.reason && !isNonEmptyString(compatibility.reason)) push('compatibility.reason', 'must be a non-empty string when present');
109
+ } else push('compatibility', 'must be an object');
110
+ if (!Array.isArray(raw.surfaces)) {
111
+ push('surfaces', 'must be an array of surfaces');
112
+ return {
113
+ ok: false,
114
+ issues
115
+ };
116
+ }
117
+ if (0 === raw.surfaces.length) push('surfaces', 'must contain at least one surface');
118
+ const seenSurfaceIds = new Set();
119
+ raw.surfaces.forEach((surface, surfaceIndex)=>{
120
+ validateSurface(surface, `surfaces[${surfaceIndex}]`, seenSurfaceIds, push);
121
+ });
122
+ return {
123
+ ok: 0 === issues.length,
124
+ issues
125
+ };
126
+ }
127
+ function selectResolvedSurface(unit, ref) {
128
+ if (unit.unitId !== ref.unitId) return {
129
+ ok: false,
130
+ error: createDiscoveryError('unknown-unit', ref, `Resolved record is for unit ${unit.unitId}, not ${ref.unitId}.`, {
131
+ recordUnitId: unit.unitId
132
+ })
133
+ };
134
+ const surface = unit.surfaces.find((candidate)=>candidate.surfaceId === ref.surfaceId);
135
+ if (void 0 === surface) return {
136
+ ok: false,
137
+ error: createDiscoveryError('unknown-surface', ref, `Unit ${unit.unitId} (buildMarker ${unit.buildMarker}) does not publish surface ${ref.surfaceId}.`, {
138
+ availableSurfaces: unit.surfaces.map((entry)=>entry.surfaceId)
139
+ })
140
+ };
141
+ return {
142
+ ok: true,
143
+ surface
144
+ };
145
+ }
146
+ function matchDeliveryUnitIdentity(expected, unit, ref) {
147
+ if (expected.unitId === unit.unitId && expected.buildMarker === unit.buildMarker) return;
148
+ return createDiscoveryError('identity-mismatch', ref, `Delivery-unit identity mismatch: expected ${expected.unitId}@${expected.buildMarker}, resolved ${unit.unitId}@${unit.buildMarker}.`, {
149
+ expected,
150
+ resolved: {
151
+ unitId: unit.unitId,
152
+ buildMarker: unit.buildMarker
153
+ }
154
+ });
155
+ }
156
+ export { createDiscoveryError, matchDeliveryUnitIdentity, selectResolvedSurface, validateResolvedDeliveryUnit };