@vritti/api-sdk 0.3.13 → 0.3.14

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.
@@ -21,10 +21,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  // src/catalog-resolver/index.ts
22
22
  var catalog_resolver_exports = {};
23
23
  __export(catalog_resolver_exports, {
24
+ API_BUCKETS: () => API_BUCKETS,
25
+ API_SURFACES: () => API_SURFACES,
26
+ BUCKET_BY_SURFACE: () => BUCKET_BY_SURFACE,
24
27
  PLATFORMS: () => PLATFORMS,
25
28
  SERVICE_CODES: () => SERVICE_CODES,
26
29
  SITE_TYPES: () => SITE_TYPES,
27
30
  SNAPSHOT_SCHEMA_VERSION: () => SNAPSHOT_SCHEMA_VERSION,
31
+ SURFACE_BY_BUCKET: () => SURFACE_BY_BUCKET,
32
+ UI_PLATFORMS: () => UI_PLATFORMS,
28
33
  buildDependsMap: () => buildDependsMap,
29
34
  buildPlanMatrix: () => buildPlanMatrix,
30
35
  buildSiteCatalog: () => buildSiteCatalog,
@@ -35,12 +40,15 @@ __export(catalog_resolver_exports, {
35
40
  featureAppliesAtNode: () => featureAppliesAtNode,
36
41
  filterGrantedByDeps: () => filterGrantedByDeps,
37
42
  findFeatureByCode: () => findFeatureByCode,
43
+ isApiBucket: () => isApiBucket,
38
44
  isPlanMember: () => isPlanMember,
39
45
  isSiteLockedOnPlatform: () => isSiteLockedOnPlatform,
46
+ normalizeApiBuckets: () => normalizeApiBuckets,
40
47
  pickRouteForPlatform: () => pickRouteForPlatform,
41
48
  prereqClosure: () => prereqClosure,
42
49
  resolveUserFeatures: () => resolveUserFeatures,
43
- snapshotFeatureKey: () => snapshotFeatureKey
50
+ snapshotFeatureKey: () => snapshotFeatureKey,
51
+ surfaceAllows: () => surfaceAllows
44
52
  });
45
53
  module.exports = __toCommonJS(catalog_resolver_exports);
46
54
 
@@ -118,12 +126,33 @@ __name(filterGrantedByDeps, "filterGrantedByDeps");
118
126
  var PLATFORMS = [
119
127
  "web",
120
128
  "mobile",
121
- "app"
129
+ "graphql",
130
+ "http"
122
131
  ];
123
132
  var UI_PLATFORMS = [
124
133
  "web",
125
134
  "mobile"
126
135
  ];
136
+ var API_SURFACES = [
137
+ "GRAPHQL",
138
+ "HTTP"
139
+ ];
140
+ var API_BUCKETS = [
141
+ "graphql",
142
+ "http"
143
+ ];
144
+ var SURFACE_BY_BUCKET = {
145
+ graphql: "GRAPHQL",
146
+ http: "HTTP"
147
+ };
148
+ var BUCKET_BY_SURFACE = {
149
+ GRAPHQL: "graphql",
150
+ HTTP: "http"
151
+ };
152
+ function isApiBucket(bucket) {
153
+ return bucket === "graphql" || bucket === "http";
154
+ }
155
+ __name(isApiBucket, "isApiBucket");
127
156
  var SITE_TYPES = [
128
157
  "OUTLET",
129
158
  "WAREHOUSE",
@@ -136,9 +165,47 @@ function snapshotFeatureKey(code, scope) {
136
165
  return `${scope}.${code}`;
137
166
  }
138
167
  __name(snapshotFeatureKey, "snapshotFeatureKey");
139
- var SNAPSHOT_SCHEMA_VERSION = 2;
168
+ var SNAPSHOT_SCHEMA_VERSION = 4;
140
169
 
141
170
  // src/catalog-resolver/catalog.builder.ts
171
+ function normalizeApiBuckets(doc) {
172
+ if (!doc) return doc;
173
+ let changed = false;
174
+ const next = {};
175
+ for (const [code, entry] of Object.entries(doc)) {
176
+ const legacy = entry.app;
177
+ if (legacy === void 0 || entry.graphql !== void 0 && entry.http !== void 0) {
178
+ next[code] = entry;
179
+ continue;
180
+ }
181
+ changed = true;
182
+ next[code] = {
183
+ ...entry,
184
+ ...entry.graphql === void 0 ? {
185
+ graphql: legacy
186
+ } : {},
187
+ ...entry.http === void 0 ? {
188
+ http: legacy
189
+ } : {}
190
+ };
191
+ }
192
+ return changed ? next : doc;
193
+ }
194
+ __name(normalizeApiBuckets, "normalizeApiBuckets");
195
+ function normalizePlans(plans) {
196
+ let changed = false;
197
+ const next = {};
198
+ for (const [code, plan] of Object.entries(plans)) {
199
+ const unlockedPermissions = normalizeApiBuckets(plan.unlockedPermissions) ?? {};
200
+ if (unlockedPermissions !== plan.unlockedPermissions) changed = true;
201
+ next[code] = unlockedPermissions === plan.unlockedPermissions ? plan : {
202
+ ...plan,
203
+ unlockedPermissions
204
+ };
205
+ }
206
+ return changed ? next : plans;
207
+ }
208
+ __name(normalizePlans, "normalizePlans");
142
209
  function featureAppliesAtNode(applicableSiteTypes, siteType) {
143
210
  return applicableSiteTypes.includes(siteType);
144
211
  }
@@ -154,26 +221,28 @@ function buildSiteCatalog(snapshot, businessCode, planCode, siteLocks, bucket, s
154
221
  if (!businessCode) return [];
155
222
  const business = snapshot.businesses?.[businessCode];
156
223
  if (!business) return [];
157
- const plan = planCode ? business.plans?.[planCode] : void 0;
158
- const plans = business.plans ?? {};
224
+ const plans = normalizePlans(business.plans ?? {});
225
+ const plan = planCode ? plans[planCode] : void 0;
226
+ const locks = normalizeApiBuckets(siteLocks);
159
227
  const catalog = [];
160
228
  const sortedApps = [
161
229
  ...business.apps
162
230
  ].sort((a, b) => a.name.localeCompare(b.name));
163
231
  for (const app of sortedApps) {
164
232
  const businessAppFeatures = app.features.filter((ref) => scope === void 0 || ref.scope === scope).map((ref) => snapshot.features?.[snapshotFeatureKey(ref.code, ref.scope)]).filter((f) => !!f && // A UI bucket needs something to render, so a feature shipping no microfrontend is dropped.
165
- // The `app` bucket renders nothing — dropping headless features there would make them
166
- // permanently ungrantable to an API client.
167
- (bucket === "app" || !!(f.microfrontends?.web || f.microfrontends?.mobile)) && (siteType === void 0 || featureAppliesAtNode(f.applicableSiteTypes, siteType)));
233
+ // An API bucket renders nothing — there a feature is admitted by the surfaces it declares
234
+ // instead, so a GRAPHQL credential never resolves an HTTP-only feature. A surface-excluded
235
+ // feature vanishes from the catalog entirely, which is what makes resolution fail closed.
236
+ (isApiBucket(bucket) ? surfaceAllows(f.apiSurfaces, SURFACE_BY_BUCKET[bucket]) : !!(f.microfrontends?.web || f.microfrontends?.mobile)) && (siteType === void 0 || featureAppliesAtNode(f.applicableSiteTypes, siteType)));
168
237
  if (businessAppFeatures.length === 0) continue;
169
238
  for (const feature of businessAppFeatures) {
170
239
  const membership = plan?.unlockedPermissions?.[feature.code];
171
240
  const web = feature.microfrontends?.web;
172
241
  const mobile = feature.microfrontends?.mobile;
173
242
  const memberOnBucket = membership?.[bucket] !== void 0;
174
- const sitePlatformLocked = siteLocks?.[feature.code]?.[bucket] === null;
243
+ const sitePlatformLocked = locks?.[feature.code]?.[bucket] === null;
175
244
  const missingServices = unmetServices(feature, availableServices);
176
- const permissions = buildPermissions(feature, businessCode, membership, siteLocks, plans, bucket, missingServices);
245
+ const permissions = buildPermissions(feature, businessCode, membership, locks, plans, bucket, missingServices);
177
246
  const lockReason = resolveLockReason(!memberOnBucket, sitePlatformLocked, missingServices);
178
247
  const locked = lockReason !== null;
179
248
  const unlockPlans = lockReason === "PLAN" ? plansIncludingFeature(plans, feature.code, bucket) : [];
@@ -210,9 +279,14 @@ function buildSiteCatalog(snapshot, businessCode, planCode, siteLocks, bucket, s
210
279
  }
211
280
  __name(buildSiteCatalog, "buildSiteCatalog");
212
281
  function isPlanMember(entry) {
213
- return !!entry && (entry.web !== void 0 || entry.mobile !== void 0);
282
+ if (!entry) return false;
283
+ return PLATFORMS.some((platform) => entry[platform] !== void 0) || entry.app !== void 0;
214
284
  }
215
285
  __name(isPlanMember, "isPlanMember");
286
+ function surfaceAllows(surfaces, surface) {
287
+ return surface === void 0 || surfaces === void 0 || surfaces.includes(surface);
288
+ }
289
+ __name(surfaceAllows, "surfaceAllows");
216
290
  function resolveLockReason(planLocked, siteLocked, missingServices) {
217
291
  if (planLocked) return "PLAN";
218
292
  if (siteLocked) return "SITE";
@@ -322,7 +396,7 @@ function composeRoleGrants(params) {
322
396
  if (revoke === null) continue;
323
397
  composed[bucket] = revoke === void 0 ? merged : merged.filter((c) => !revoke.includes(c));
324
398
  }
325
- if (composed.web === void 0 && composed.mobile === void 0) continue;
399
+ if (PLATFORMS.every((bucket) => composed[bucket] === void 0)) continue;
326
400
  result[code] = composed;
327
401
  }
328
402
  return result;
@@ -330,21 +404,35 @@ function composeRoleGrants(params) {
330
404
  __name(composeRoleGrants, "composeRoleGrants");
331
405
 
332
406
  // src/catalog-resolver/resolve-user-features.ts
407
+ var BUCKET_BY_CLIENT = {
408
+ web: "web",
409
+ ios: "mobile",
410
+ android: "mobile",
411
+ graphql: "graphql",
412
+ http: "http"
413
+ };
333
414
  var EMPTY_ROUTE = {
334
415
  remoteEntry: "",
335
416
  exposedModule: "",
336
417
  routePrefix: ""
337
418
  };
338
419
  function resolveUserFeatures(params) {
339
- const { snapshot, businessCode, planCode, siteLocks, roleFeatures, platform, siteType, scope, availableServices } = params;
340
- const bucket = platform === "web" ? "web" : platform === "app" ? "app" : "mobile";
420
+ const { snapshot, businessCode, planCode, siteLocks, platform, siteType, scope, availableServices } = params;
421
+ const bucket = BUCKET_BY_CLIENT[platform];
422
+ const roleFeatures = normalizeApiBuckets(params.roleFeatures) ?? {};
341
423
  const featureByCode = /* @__PURE__ */ __name((code) => scope ? snapshot.features?.[snapshotFeatureKey(code, scope)] : findFeatureByCode(snapshot, code), "featureByCode");
342
424
  const catalog = buildSiteCatalog(snapshot, businessCode, planCode, siteLocks, bucket, siteType, scope, availableServices);
343
425
  const catalogMap = new Map(catalog.map((f) => [
344
426
  f.code,
345
427
  f
346
428
  ]));
347
- const businessPlans = snapshot.businesses[businessCode]?.plans ?? {};
429
+ const businessPlans = Object.fromEntries(Object.entries(snapshot.businesses[businessCode]?.plans ?? {}).map(([code, plan]) => [
430
+ code,
431
+ {
432
+ ...plan,
433
+ unlockedPermissions: normalizeApiBuckets(plan.unlockedPermissions) ?? {}
434
+ }
435
+ ]));
348
436
  const currentUnlockedCodes = /* @__PURE__ */ new Set();
349
437
  if (planCode && businessPlans[planCode]) {
350
438
  for (const [featureCode, platforms] of Object.entries(businessPlans[planCode].unlockedPermissions ?? {})) {
@@ -376,7 +464,7 @@ function resolveUserFeatures(params) {
376
464
  for (const [code, permsSet] of grantedFeatures) {
377
465
  const catalogEntry = catalogMap.get(code);
378
466
  if (!catalogEntry) continue;
379
- const route = bucket === "app" ? EMPTY_ROUTE : pickRouteForPlatform(catalogEntry, platform);
467
+ const route = isApiBucket(bucket) ? EMPTY_ROUTE : pickRouteForPlatform(catalogEntry, platform);
380
468
  if (!route) continue;
381
469
  const featureDeps = buildDependsMap(featureByCode(code)?.permissions ?? []);
382
470
  const permByCode = new Map((catalogEntry.permissions ?? []).map((p) => [
@@ -421,6 +509,7 @@ function resolveUserFeatures(params) {
421
509
  }
422
510
  __name(resolveUserFeatures, "resolveUserFeatures");
423
511
  function pickRouteForPlatform(entry, platform) {
512
+ if (platform === "graphql" || platform === "http") return null;
424
513
  if (platform === "ios" || platform === "android") {
425
514
  if (!entry.mobile) return null;
426
515
  return {
@@ -449,13 +538,20 @@ function buildPlanMatrix(snapshot, businessCode, planCode, siteLocks) {
449
538
  __name(buildPlanMatrix, "buildPlanMatrix");
450
539
  function buildMatrix(snapshot, businessCode, planCode, siteLocks, allScopes, siteType) {
451
540
  const business = businessCode ? snapshot.businesses?.[businessCode] : void 0;
452
- const plans = business?.plans ?? {};
541
+ const plans = Object.fromEntries(Object.entries(business?.plans ?? {}).map(([code, p]) => [
542
+ code,
543
+ {
544
+ ...p,
545
+ unlockedPermissions: normalizeApiBuckets(p.unlockedPermissions) ?? {}
546
+ }
547
+ ]));
453
548
  const plan = planCode ? plans[planCode] : void 0;
454
549
  const planMeta = {
455
550
  code: planCode ?? "",
456
551
  name: plan?.name ?? planCode ?? ""
457
552
  };
458
- const locks = siteLocks ?? {};
553
+ const normalizedLocks = normalizeApiBuckets(siteLocks);
554
+ const locks = normalizedLocks ?? {};
459
555
  if (!business || !plan) return {
460
556
  plan: planMeta,
461
557
  apps: [],
@@ -474,11 +570,11 @@ function buildMatrix(snapshot, businessCode, planCode, siteLocks, allScopes, sit
474
570
  if (siteType !== void 0 && !featureAppliesAtNode(feature.applicableSiteTypes, siteType)) continue;
475
571
  const platforms = [
476
572
  ...UI_PLATFORMS.filter((p) => !!feature.microfrontends?.[p]),
477
- "app"
573
+ ...API_BUCKETS.filter((b) => feature.apiSurfaces === void 0 || feature.apiSurfaces.includes(SURFACE_BY_BUCKET[b]))
478
574
  ];
479
575
  const membership = plan.unlockedPermissions?.[code];
480
576
  const featureInPlan = isPlanMember(membership);
481
- const siteEntry = siteLocks?.[code];
577
+ const siteEntry = normalizedLocks?.[code];
482
578
  const permissions = (feature.permissions ?? []).filter((p) => p.isGlobal || p.businesses.includes(businessCode ?? "")).map((p) => {
483
579
  const cell = /* @__PURE__ */ __name((plat) => {
484
580
  if (!platforms.includes(plat)) return null;
@@ -500,7 +596,8 @@ function buildMatrix(snapshot, businessCode, planCode, siteLocks, allScopes, sit
500
596
  dependsOn: p.dependsOn ?? [],
501
597
  web: cell("web"),
502
598
  mobile: cell("mobile"),
503
- app: cell("app")
599
+ graphql: cell("graphql"),
600
+ http: cell("http")
504
601
  };
505
602
  });
506
603
  features.push({
@@ -512,6 +609,7 @@ function buildMatrix(snapshot, businessCode, planCode, siteLocks, allScopes, sit
512
609
  platforms,
513
610
  inPlan: featureInPlan,
514
611
  availableIn: featureInPlan ? [] : plansIncludingFeature2(plans, code, planCode),
612
+ apiSurfaces: feature.apiSurfaces,
515
613
  permissions
516
614
  });
517
615
  }
@@ -553,10 +651,15 @@ function plansIncludingFeature2(plans, featureCode, excludeCode) {
553
651
  __name(plansIncludingFeature2, "plansIncludingFeature");
554
652
  // Annotate the CommonJS export names for ESM import in node:
555
653
  0 && (module.exports = {
654
+ API_BUCKETS,
655
+ API_SURFACES,
656
+ BUCKET_BY_SURFACE,
556
657
  PLATFORMS,
557
658
  SERVICE_CODES,
558
659
  SITE_TYPES,
559
660
  SNAPSHOT_SCHEMA_VERSION,
661
+ SURFACE_BY_BUCKET,
662
+ UI_PLATFORMS,
560
663
  buildDependsMap,
561
664
  buildPlanMatrix,
562
665
  buildSiteCatalog,
@@ -567,11 +670,14 @@ __name(plansIncludingFeature2, "plansIncludingFeature");
567
670
  featureAppliesAtNode,
568
671
  filterGrantedByDeps,
569
672
  findFeatureByCode,
673
+ isApiBucket,
570
674
  isPlanMember,
571
675
  isSiteLockedOnPlatform,
676
+ normalizeApiBuckets,
572
677
  pickRouteForPlatform,
573
678
  prereqClosure,
574
679
  resolveUserFeatures,
575
- snapshotFeatureKey
680
+ snapshotFeatureKey,
681
+ surfaceAllows
576
682
  });
577
683
  //# sourceMappingURL=catalog-resolver.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/catalog-resolver/index.ts","../src/catalog-resolver/permission-deps.ts","../src/catalog-resolver/types.ts","../src/catalog-resolver/catalog.builder.ts","../src/catalog-resolver/compose-role-grants.ts","../src/catalog-resolver/resolve-user-features.ts","../src/catalog-resolver/site-matrix.builder.ts"],"sourcesContent":["// Catalog resolver — the single shared implementation of snapshot resolution (BU catalog, BU matrix, user features)\n\nexport {\n buildSiteCatalog,\n buildSiteRoles,\n featureAppliesAtNode,\n findFeatureByCode,\n isPlanMember,\n isSiteLockedOnPlatform,\n} from './catalog.builder';\nexport { type ComposeRoleGrantsParams, composeRoleGrants, type RevokedGrants } from './compose-role-grants';\nexport {\n buildDependsMap,\n cascadeLocked,\n type DependsMap,\n filterGrantedByDeps,\n prereqClosure,\n} from './permission-deps';\nexport {\n type ClientPlatform,\n type LockedPermission,\n type PermissionFeature,\n pickRouteForPlatform,\n type ResolveUserFeaturesParams,\n resolveUserFeatures,\n} from './resolve-user-features';\nexport {\n buildPlanMatrix,\n buildSiteMatrix,\n type SiteMatrix,\n type SiteMatrixApp,\n type SiteMatrixCell,\n type SiteMatrixFeature,\n type SiteMatrixPermission,\n} from './site-matrix.builder';\nexport {\n type BusinessVocabulary,\n type CatalogPermission,\n type FeatureCatalogEntry,\n type FeatureLocks,\n type FeatureUnlocks,\n type LockReason,\n PLATFORMS,\n type PlatformBucket,\n type PlatformCodes,\n type PlatformDenyCodes,\n type RoleItem,\n type ScopeType,\n SERVICE_CODES,\n type ServiceCode,\n SITE_TYPES,\n type SiteFeatureLocks,\n type SiteType,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotApp,\n type SnapshotAppFeatureRef,\n type SnapshotBusiness,\n type SnapshotFeature,\n type SnapshotMicrofrontendMobile,\n type SnapshotMicrofrontends,\n type SnapshotMicrofrontendWeb,\n type SnapshotPermission,\n type SnapshotPlan,\n type SnapshotRoleTemplate,\n snapshotFeatureKey,\n type VersionSnapshot,\n type VocabularyEntry,\n} from './types';\n","// Intra-feature permission prerequisites — only DIRECT edges are declared; the transitive closure is computed by recursion, cycle-guarded\n\nexport type DependsMap = Map<string, string[]>;\n\n// Builds a dependency map from a feature's permissions, keeping only edges to codes present in the set\nexport function buildDependsMap(permissions: Array<{ code: string; dependsOn?: string[] }>): DependsMap {\n const present = new Set(permissions.map((p) => p.code));\n const map: DependsMap = new Map();\n for (const p of permissions) {\n map.set(\n p.code,\n (p.dependsOn ?? []).filter((dep) => dep !== p.code && present.has(dep)),\n );\n }\n return map;\n}\n\n// Transitive prerequisite closure of a code (excludes the code itself), cycle-safe\nexport function prereqClosure(code: string, deps: DependsMap): string[] {\n const out = new Set<string>();\n const seen = new Set<string>([code]);\n const stack = [code];\n while (stack.length > 0) {\n const current = stack.pop() as string;\n for (const dep of deps.get(current) ?? []) {\n if (seen.has(dep)) continue;\n seen.add(dep);\n out.add(dep);\n stack.push(dep);\n }\n }\n return [...out];\n}\n\n// Codes locked after cascade: a code is locked if directly locked or any transitive prerequisite is (cycle-safe)\nexport function cascadeLocked(codes: string[], directlyLocked: Set<string>, deps: DependsMap): Set<string> {\n const locked = new Set<string>();\n const visiting = new Set<string>();\n const check = (code: string): boolean => {\n if (locked.has(code)) return true;\n if (directlyLocked.has(code)) {\n locked.add(code);\n return true;\n }\n if (visiting.has(code)) return false;\n visiting.add(code);\n const viaDep = (deps.get(code) ?? []).some(check);\n visiting.delete(code);\n if (viaDep) locked.add(code);\n return viaDep;\n };\n for (const code of codes) check(code);\n return locked;\n}\n\n// Keeps only codes whose FULL prerequisite closure is also present — drops a dependent missing any prerequisite (cycle-safe)\nexport function filterGrantedByDeps(granted: Set<string>, deps: DependsMap): Set<string> {\n const ok = new Set<string>();\n const visiting = new Set<string>();\n const check = (code: string): boolean => {\n if (ok.has(code)) return true;\n if (!granted.has(code)) return false;\n if (visiting.has(code)) return true;\n visiting.add(code);\n const satisfied = (deps.get(code) ?? []).every(check);\n visiting.delete(code);\n if (satisfied) ok.add(code);\n return satisfied;\n };\n for (const code of granted) check(code);\n return ok;\n}\n","// ——— Platform algebra — plan unlocks, role grants, and BU locks are all stored per platform bucket ———\n\n/**\n * The surfaces a permission can be granted on.\n *\n * `web` and `mobile` are UI buckets: a feature reaches them through a microfrontend, and a grant\n * there means a person can operate it on that surface. `app` is not a UI at all — it is an API\n * client signing its own requests, so it has no microfrontend and no route, and a feature needs\n * neither to be reachable by one.\n *\n * Keeping `app` in the same algebra rather than beside it is what lets plan entitlement, node\n * feature locks and permission prerequisites bind an API client exactly as they bind a person.\n */\nexport type PlatformBucket = 'web' | 'mobile' | 'app';\n\nexport const PLATFORMS: PlatformBucket[] = ['web', 'mobile', 'app'];\n\n/** Buckets that reach their feature through a microfrontend, and so require one to resolve. */\nexport type UiPlatformBucket = Exclude<PlatformBucket, 'app'>;\n\nexport const UI_PLATFORMS: UiPlatformBucket[] = ['web', 'mobile'];\n\nexport interface PlatformCodes {\n web?: string[];\n mobile?: string[];\n app?: string[];\n}\n\nexport interface PlatformDenyCodes {\n web?: string[] | null;\n mobile?: string[] | null;\n app?: string[] | null;\n}\n\nexport type FeatureUnlocks = Record<string, PlatformCodes>;\n\nexport type FeatureLocks = Record<string, PlatformDenyCodes>;\nexport type SiteFeatureLocks = FeatureLocks;\n\n// ——— Snapshot document shape — what gets stored in versions.snapshot and signed into the catalog license ———\n\nexport interface SnapshotPermission {\n code: string;\n label: string;\n isGlobal: boolean;\n businesses: string[];\n dependsOn: string[];\n}\nexport interface SnapshotMicrofrontendWeb {\n code: string;\n name: string;\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n}\nexport interface SnapshotMicrofrontendMobile {\n code: string;\n name: string;\n remoteEntryAndroid: string;\n remoteEntryIos: string;\n exposedModule: string;\n routePrefix: string;\n}\nexport interface SnapshotMicrofrontends {\n web?: SnapshotMicrofrontendWeb;\n mobile?: SnapshotMicrofrontendMobile;\n}\nexport type ScopeType = 'ORG' | 'LE' | 'SITE_GROUP' | 'SITE';\nexport type SiteType = 'OUTLET' | 'WAREHOUSE' | 'PRODUCTION';\nexport const SITE_TYPES: SiteType[] = ['OUTLET', 'WAREHOUSE', 'PRODUCTION'];\n// External services a feature can depend on — the org must have the service provisioned before the feature\n// unlocks. Add new services here and nowhere else in this package; every lock path is service-agnostic.\nexport const SERVICE_CODES = ['GITEA'] as const;\nexport type ServiceCode = (typeof SERVICE_CODES)[number];\nexport interface SnapshotFeature {\n code: string;\n name: string;\n lucideIcon: string;\n sfSymbol: string;\n materialSymbol: string;\n scope: ScopeType;\n applicableSiteTypes: SiteType[];\n permissions: SnapshotPermission[];\n microfrontends: SnapshotMicrofrontends;\n // Optional: snapshots built before service gating existed carry no services, which reads as \"requires none\"\n requiredServices?: ServiceCode[];\n}\nexport interface SnapshotAppFeatureRef {\n code: string;\n scope: ScopeType;\n}\nexport interface SnapshotApp {\n code: string;\n name: string;\n icon: string;\n sortOrder: number;\n features: SnapshotAppFeatureRef[];\n}\nexport interface SnapshotRoleTemplate {\n name: string;\n code: string;\n scope: ScopeType;\n siteType: SiteType;\n features: FeatureUnlocks;\n}\nexport interface SnapshotPlan {\n code: string;\n name: string;\n isCustom: boolean;\n maxSites: number | null;\n unlockedPermissions: FeatureUnlocks;\n}\nexport interface VocabularyEntry {\n singular: string;\n plural: string;\n}\nexport interface BusinessVocabulary {\n site?: VocabularyEntry;\n siteGroup?: VocabularyEntry;\n outlet?: VocabularyEntry;\n warehouse?: VocabularyEntry;\n production?: VocabularyEntry;\n}\nexport interface SnapshotBusiness {\n name: string;\n vocabulary?: BusinessVocabulary;\n apps: SnapshotApp[];\n roleTemplates: Record<string, SnapshotRoleTemplate>;\n plans: Record<string, SnapshotPlan>;\n}\nexport interface VersionSnapshot {\n schemaVersion?: number;\n // Flat feature dictionary keyed by `${scope}.${code}` (see snapshotFeatureKey) — same-code features at different scopes stay distinct\n features: Record<string, SnapshotFeature>;\n businesses: Record<string, SnapshotBusiness>;\n}\n\n// Composite key for the snapshot feature dictionary — feature identity is (scope, code)\nexport function snapshotFeatureKey(code: string, scope: ScopeType): string {\n return `${scope}.${code}`;\n}\n\nexport const SNAPSHOT_SCHEMA_VERSION = 2;\n\n// SERVICE = the org has not provisioned an external service the feature declares; the specific services are\n// reported alongside in `missingServices` so callers never branch on a service code baked into this union\nexport type LockReason = 'PLAN' | 'SITE' | 'SERVICE';\n\nexport interface CatalogPermission {\n code: string;\n locked: boolean;\n lockReason: LockReason | null;\n unlockPlans: string[];\n missingServices: ServiceCode[];\n}\n\nexport interface FeatureCatalogEntry {\n code: string;\n name: string;\n lucideIcon: string | null;\n sfSymbol: string;\n materialSymbol: string;\n web: {\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n mobile: {\n remoteEntryAndroid: string;\n remoteEntryIos: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n appCode: string;\n appName: string;\n appIcon: string | null;\n appSortOrder: number;\n locked: boolean;\n lockReason: LockReason | null;\n unlockPlans: string[];\n missingServices: ServiceCode[];\n permissions: CatalogPermission[];\n}\n\nexport type RoleItem = SnapshotRoleTemplate;\n","import { buildDependsMap, cascadeLocked, prereqClosure } from './permission-deps';\nimport type {\n CatalogPermission,\n FeatureCatalogEntry,\n LockReason,\n PlatformBucket,\n PlatformCodes,\n RoleItem,\n ScopeType,\n ServiceCode,\n SiteFeatureLocks,\n SiteType,\n SnapshotFeature,\n SnapshotPlan,\n VersionSnapshot,\n} from './types';\nimport { snapshotFeatureKey } from './types';\n\n// Whether a feature with the given site-type applicability is exposed at this site type\nexport function featureAppliesAtNode(applicableSiteTypes: SiteType[], siteType: SiteType): boolean {\n return applicableSiteTypes.includes(siteType);\n}\n\n// Scope-agnostic lookup of a feature by bare code — grants/locks key features by code alone, so the first scope-variant's shared metadata (permission graph) answers\nexport function findFeatureByCode(snapshot: VersionSnapshot, code: string): SnapshotFeature | undefined {\n for (const feature of Object.values(snapshot.features ?? {})) {\n if (feature?.code === code) return feature;\n }\n return undefined;\n}\n\n// Builds the per-site catalog for ONE platform bucket — plan is the ceiling, siteLocks is a deny-list within it; each permission carries locked + lockReason + unlockPlans\n// availableServices defaults to none, so a caller that doesn't know the org's provisioned services locks every service-dependent feature rather than leaking it\nexport function buildSiteCatalog(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n bucket: PlatformBucket,\n siteType?: SiteType,\n scope?: ScopeType,\n availableServices: ServiceCode[] = [],\n): FeatureCatalogEntry[] {\n if (!businessCode) return [];\n const business = snapshot.businesses?.[businessCode];\n if (!business) return [];\n const plan = planCode ? business.plans?.[planCode] : undefined;\n const plans = business.plans ?? {};\n\n const catalog: FeatureCatalogEntry[] = [];\n // Iterate apps alphabetically by name so the resolved feature list (→ core-web sidebar) is app-alphabetical without any frontend re-sort\n const sortedApps = [...business.apps].sort((a, b) => a.name.localeCompare(b.name));\n for (const app of sortedApps) {\n // The app's renderable features (each ref pins scope+code to one app), dropped when they don't belong to this workspace scope or node type (outlet vs container)\n const businessAppFeatures = app.features\n .filter((ref) => scope === undefined || ref.scope === scope)\n .map((ref) => snapshot.features?.[snapshotFeatureKey(ref.code, ref.scope)])\n .filter(\n (f): f is SnapshotFeature =>\n !!f &&\n // A UI bucket needs something to render, so a feature shipping no microfrontend is dropped.\n // The `app` bucket renders nothing — dropping headless features there would make them\n // permanently ungrantable to an API client.\n (bucket === 'app' || !!(f.microfrontends?.web || f.microfrontends?.mobile)) &&\n (siteType === undefined || featureAppliesAtNode(f.applicableSiteTypes, siteType)),\n );\n\n if (businessAppFeatures.length === 0) continue;\n\n // Emit EVERY business feature so a role's grant on a plan-omitted feature still resolves as a locked tile instead of vanishing\n for (const feature of businessAppFeatures) {\n const membership = plan?.unlockedPermissions?.[feature.code];\n // Routes are exposed wherever the feature SHIPS — membership never hides them\n const web = feature.microfrontends?.web;\n const mobile = feature.microfrontends?.mobile;\n\n // Feature-level lock is EXPLICIT: plan must include the feature on this bucket, the site must not null-lock\n // the platform, and every external service the feature declares must be provisioned for the org\n const memberOnBucket = membership?.[bucket] !== undefined;\n const sitePlatformLocked = siteLocks?.[feature.code]?.[bucket] === null;\n const missingServices = unmetServices(feature, availableServices);\n // Unmet services lock every permission too — otherwise the feature reads locked while its actions still\n // report as available, which is not how plan and site locks behave\n const permissions = buildPermissions(\n feature,\n businessCode,\n membership,\n siteLocks,\n plans,\n bucket,\n missingServices,\n );\n const lockReason = resolveLockReason(!memberOnBucket, sitePlatformLocked, missingServices);\n const locked = lockReason !== null;\n const unlockPlans = lockReason === 'PLAN' ? plansIncludingFeature(plans, feature.code, bucket) : [];\n\n catalog.push({\n code: feature.code,\n name: feature.name,\n lucideIcon: feature.lucideIcon ?? null,\n sfSymbol: feature.sfSymbol ?? 'square',\n materialSymbol: feature.materialSymbol ?? 'square',\n web: web\n ? {\n remoteEntry: web.remoteEntry ?? '',\n exposedModule: web.exposedModule ?? '',\n routePrefix: web.routePrefix ?? '',\n }\n : null,\n mobile: mobile\n ? {\n remoteEntryAndroid: mobile.remoteEntryAndroid ?? '',\n remoteEntryIos: mobile.remoteEntryIos ?? '',\n exposedModule: mobile.exposedModule ?? '',\n routePrefix: mobile.routePrefix ?? '',\n }\n : null,\n appCode: app.code,\n appName: app.name,\n appIcon: app.icon ?? null,\n appSortOrder: app.sortOrder ?? 0,\n locked,\n lockReason,\n unlockPlans,\n missingServices,\n permissions,\n });\n }\n }\n return catalog;\n}\n\n// A feature is a plan member when its unlock entry exists on at least one platform (even with zero actions)\nexport function isPlanMember(entry: PlatformCodes | undefined): boolean {\n return !!entry && (entry.web !== undefined || entry.mobile !== undefined);\n}\n\n// The one place lock precedence is decided, for features and permissions alike; null means nothing locks.\n// Plan is the ceiling (an unentitled feature must upsell, not send the user to provision something they still\n// couldn't use), then the site deny-list, then any unprovisioned service.\nfunction resolveLockReason(\n planLocked: boolean,\n siteLocked: boolean,\n missingServices: ServiceCode[],\n): LockReason | null {\n if (planLocked) return 'PLAN';\n if (siteLocked) return 'SITE';\n if (missingServices.length > 0) return 'SERVICE';\n return null;\n}\n\n// The services a feature declares that this org has not provisioned\nfunction unmetServices(feature: SnapshotFeature, availableServices: ServiceCode[]): ServiceCode[] {\n return (feature.requiredServices ?? []).filter((service) => !availableServices.includes(service));\n}\n\n// Per-platform site-lock primitive: null locks the whole feature, string[] locks those codes, absent = not locked\nexport function isSiteLockedOnPlatform(\n entry: SiteFeatureLocks[string] | undefined,\n platform: PlatformBucket,\n code: string,\n): boolean {\n const locks = entry?.[platform];\n return locks === null || (locks?.includes(code) ?? false);\n}\n\n// A feature's business-scoped permissions, each tagged with locked + reason against the plan and site deny-list\n// (bucket-scoped). Unmet services lock the whole set — an unprovisioned service blocks every action on the feature.\nfunction buildPermissions(\n feature: SnapshotFeature,\n businessCode: string,\n planMembership: PlatformCodes | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n plans: Record<string, SnapshotPlan>,\n bucket: PlatformBucket,\n missingServices: ServiceCode[] = [],\n): CatalogPermission[] {\n const planUnlocked = new Set(planMembership?.[bucket] ?? []);\n const lockEntry = siteLocks?.[feature.code];\n\n const perms = (feature.permissions ?? []).filter((p) => p.isGlobal || p.businesses.includes(businessCode));\n const deps = buildDependsMap(perms);\n const codes = perms.map((p) => p.code);\n\n // Direct plan/site locks, then cascade so a locked prerequisite (e.g. view) locks its dependents (add/edit/delete)\n const directlyPlanLocked = new Set<string>();\n const directlySiteLocked = new Set<string>();\n for (const p of perms) {\n if (!planUnlocked.has(p.code)) directlyPlanLocked.add(p.code);\n if (isSiteLockedOnPlatform(lockEntry, bucket, p.code)) directlySiteLocked.add(p.code);\n }\n const directlyLocked = new Set<string>([...directlyPlanLocked, ...directlySiteLocked]);\n const lockedSet = cascadeLocked(codes, directlyLocked, deps);\n\n return perms.map((p) => {\n // A permission is enabled only if it AND its whole prerequisite closure are unlocked — reason/upsell reflect that\n const closure = [p.code, ...prereqClosure(p.code, deps)];\n const cascaded = lockedSet.has(p.code);\n const planReason = cascaded && closure.some((c) => directlyPlanLocked.has(c));\n const siteReason = cascaded && closure.some((c) => directlySiteLocked.has(c));\n const lockReason = resolveLockReason(planReason, siteReason, missingServices);\n const locked = lockReason !== null;\n const unlockPlans = lockReason === 'PLAN' ? plansUnlockingClosure(plans, feature.code, closure, bucket) : [];\n return { code: p.code, locked, lockReason, unlockPlans, missingServices };\n });\n}\n\n// Plan codes (in the business) whose unlocked set includes the permission AND its whole prerequisite closure — upsell targets\nfunction plansUnlockingClosure(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n closure: string[],\n bucket: PlatformBucket,\n): string[] {\n const result: string[] = [];\n for (const [code, plan] of Object.entries(plans)) {\n const unlocked = plan.unlockedPermissions?.[featureCode]?.[bucket];\n if (unlocked && closure.every((c) => unlocked.includes(c))) result.push(code);\n }\n return result;\n}\n\n// Plan codes (in the business) that include this feature on the bucket — the feature-level upsell targets\nfunction plansIncludingFeature(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n bucket: PlatformBucket,\n): string[] {\n const result: string[] = [];\n for (const [code, plan] of Object.entries(plans)) {\n if (plan.unlockedPermissions?.[featureCode]?.[bucket] !== undefined) result.push(code);\n }\n return result;\n}\n\n// The business's role templates as provisionable role items for core (identical shapes)\nexport function buildSiteRoles(snapshot: VersionSnapshot, businessCode: string | undefined): RoleItem[] {\n if (!businessCode) return [];\n const business = snapshot.businesses?.[businessCode];\n if (!business) return [];\n return Object.values(business.roleTemplates ?? {});\n}\n","import { type FeatureUnlocks, PLATFORMS, type PlatformCodes, type PlatformDenyCodes } from './types';\n\nexport type RevokedGrants = Record<string, PlatformDenyCodes>;\n\nexport interface ComposeRoleGrantsParams {\n baseFeatures: FeatureUnlocks | undefined;\n additions: FeatureUnlocks;\n revoked: RevokedGrants | undefined;\n}\n\n// Deduped union of two optional code lists — undefined on both sides means no platform membership\nfunction unionBucket(base: string[] | undefined, add: string[] | undefined): string[] | undefined {\n if (base === undefined && add === undefined) return undefined;\n return [...new Set([...(base ?? []), ...(add ?? [])])];\n}\n\n// Composes a custom role's effective grants: merge(base ∪ additions) − revoked (design doc §10); inputs are never mutated\nexport function composeRoleGrants(params: ComposeRoleGrantsParams): FeatureUnlocks {\n const { baseFeatures, additions, revoked } = params;\n\n const result: FeatureUnlocks = {};\n const featureCodes = new Set([...Object.keys(baseFeatures ?? {}), ...Object.keys(additions ?? {})]);\n\n for (const code of featureCodes) {\n const base = baseFeatures?.[code] ?? {};\n const add = additions?.[code] ?? {};\n const revokes = revoked?.[code];\n\n const composed: PlatformCodes = {};\n for (const bucket of PLATFORMS) {\n const merged = unionBucket(base[bucket], add[bucket]);\n if (merged === undefined) continue;\n const revoke = revokes?.[bucket];\n // null revokes the whole platform (membership + all codes); string[] subtracts codes but keeps membership\n if (revoke === null) continue;\n composed[bucket] = revoke === undefined ? merged : merged.filter((c) => !revoke.includes(c));\n }\n\n // A feature with no surviving platform membership disappears from the effective set\n if (composed.web === undefined && composed.mobile === undefined) continue;\n result[code] = composed;\n }\n\n return result;\n}\n","import { buildSiteCatalog, findFeatureByCode } from './catalog.builder';\nimport { buildDependsMap, filterGrantedByDeps } from './permission-deps';\nimport type {\n FeatureUnlocks,\n LockReason,\n PlatformBucket,\n ScopeType,\n ServiceCode,\n SiteFeatureLocks,\n SiteType,\n VersionSnapshot,\n} from './types';\nimport { snapshotFeatureKey } from './types';\n\n/**\n * The caller's surface, as the caller reports it.\n *\n * Finer than `PlatformBucket` on the mobile side — `ios` and `android` load different remote\n * entries but share one grant bucket. `app` is one-to-one with its bucket: an API client has no\n * variants because it has no UI.\n */\nexport type ClientPlatform = 'web' | 'ios' | 'android' | 'app';\n\n/**\n * Stands in for the microfrontend an API client does not load.\n *\n * `PermissionFeature.route` is non-optional and read by the web sidebar and the mobile host to\n * mount a remote. Nothing on the app path reads it — the permission interceptor uses `code`,\n * `permissions` and `locked` — so an empty route keeps one shape for every bucket instead of\n * widening the field to null across every consumer.\n */\nconst EMPTY_ROUTE = { remoteEntry: '', exposedModule: '', routePrefix: '' };\n\nexport interface LockedPermission {\n code: string;\n reason: LockReason | null;\n unlockPlans: string[];\n missingServices: ServiceCode[];\n}\n\nexport interface PlanUpsell {\n plan: string;\n features: string[];\n}\n\nexport interface PermissionFeature {\n code: string;\n name: string;\n lucideIcon: string | null;\n sfSymbol: string;\n materialSymbol: string;\n permissions: string[];\n locked: boolean;\n lockReason: LockReason | null;\n unlockPlans: string[];\n // Which declared services the org has not provisioned — empty unless lockReason is 'SERVICE'\n missingServices: ServiceCode[];\n lockedPermissions: LockedPermission[];\n upsell: PlanUpsell[];\n route: {\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n };\n appCode: string;\n appName: string;\n appIcon: string | null;\n appSortOrder: number;\n}\n\nexport interface ResolveUserFeaturesParams {\n snapshot: VersionSnapshot;\n businessCode: string;\n planCode: string | undefined;\n siteLocks: SiteFeatureLocks | undefined;\n roleFeatures: FeatureUnlocks;\n platform: ClientPlatform;\n siteType?: SiteType;\n scope?: ScopeType;\n // External services the org has provisioned; omitting it locks every service-dependent feature\n availableServices?: ServiceCode[];\n}\n\n// Resolves the features + MF config a user sees at a BU: plan ∧ BU catalog intersected with the role's grants, filtered to the requested platform\nexport function resolveUserFeatures(params: ResolveUserFeaturesParams): PermissionFeature[] {\n const { snapshot, businessCode, planCode, siteLocks, roleFeatures, platform, siteType, scope, availableServices } =\n params;\n\n // Plan unlocks, BU locks, and role grants are stored per platform; resolve only the requesting\n // surface's bucket (web → 'web'; ios/android → 'mobile'; app → 'app')\n const bucket: PlatformBucket = platform === 'web' ? 'web' : platform === 'app' ? 'app' : 'mobile';\n\n // Grants/plans/locks key features by bare code; resolve to the workspace scope's variant (or any variant when unscoped)\n const featureByCode = (code: string) =>\n scope ? snapshot.features?.[snapshotFeatureKey(code, scope)] : findFeatureByCode(snapshot, code);\n\n // Plan ∧ BU overlay for this bucket, filtered to features that apply to this workspace scope and node type — emits EVERY applicable business feature (plan non-members come out fully locked)\n const catalog = buildSiteCatalog(\n snapshot,\n businessCode,\n planCode,\n siteLocks,\n bucket,\n siteType,\n scope,\n availableServices,\n );\n const catalogMap = new Map(catalog.map((f) => [f.code, f]));\n\n // Per-plan feature-name delta vs the current plan — feeds the plan-locked upsell screen\n const businessPlans = snapshot.businesses[businessCode]?.plans ?? {};\n const currentUnlockedCodes = new Set<string>();\n if (planCode && businessPlans[planCode]) {\n for (const [featureCode, platforms] of Object.entries(businessPlans[planCode].unlockedPermissions ?? {})) {\n if (platforms?.[bucket] !== undefined) currentUnlockedCodes.add(featureCode);\n }\n }\n const planAdds = new Map<string, Array<{ code: string; name: string }>>();\n for (const [planKey, plan] of Object.entries(businessPlans)) {\n if (planKey === planCode) continue;\n const adds: Array<{ code: string; name: string }> = [];\n for (const [featureCode, platforms] of Object.entries(plan.unlockedPermissions ?? {})) {\n if (platforms?.[bucket] === undefined || currentUnlockedCodes.has(featureCode)) continue;\n const name = featureByCode(featureCode)?.name;\n if (name) adds.push({ code: featureCode, name });\n }\n planAdds.set(planKey, adds);\n }\n\n // Granted permission set per feature, taking only this platform's grants\n const grantedFeatures = new Map<string, Set<string>>();\n for (const [code, grant] of Object.entries(roleFeatures ?? {})) {\n // Membership is the gate: undefined = not a member on this platform; [] = member with no actions (view-only)\n const granted = grant?.[bucket];\n if (granted === undefined) continue;\n if (!grantedFeatures.has(code)) grantedFeatures.set(code, new Set());\n for (const perm of granted) grantedFeatures.get(code)?.add(perm);\n }\n\n // Cross-reference the granted features with the catalog to build the response\n const features: PermissionFeature[] = [];\n for (const [code, permsSet] of grantedFeatures) {\n const catalogEntry = catalogMap.get(code);\n if (!catalogEntry) continue;\n\n // A UI bucket reaches its feature by loading a microfrontend, so a feature not published to\n // this platform is omitted rather than handed over as an unloadable tile. An API client loads\n // nothing — requiring a route there would make every headless feature permanently ungrantable.\n const route = bucket === 'app' ? EMPTY_ROUTE : pickRouteForPlatform(catalogEntry, platform);\n if (!route) continue;\n\n // Drop granted permissions whose intra-feature prerequisites aren't also granted (e.g. add needs view)\n const featureDeps = buildDependsMap(featureByCode(code)?.permissions ?? []);\n // Plan/BU lock a subset of permissions; surface which GRANTED ones are locked + why + how to unlock (upsell)\n const permByCode = new Map((catalogEntry.permissions ?? []).map((p) => [p.code, p]));\n const grantedPerms = [...filterGrantedByDeps(permsSet, featureDeps)];\n const lockedPermissions: LockedPermission[] = grantedPerms\n .map((c) => permByCode.get(c))\n .filter((p): p is NonNullable<typeof p> => !!p?.locked)\n .map((p) => ({\n code: p.code,\n reason: p.lockReason ?? null,\n unlockPlans: p.unlockPlans ?? [],\n missingServices: p.missingServices ?? [],\n }));\n\n // For a plan-locked feature, list the extra features each unlocking plan would add (excluding this feature)\n const upsell: PlanUpsell[] =\n catalogEntry.locked && catalogEntry.lockReason === 'PLAN'\n ? (catalogEntry.unlockPlans ?? [])\n .map((plan) => ({\n plan,\n features: (planAdds.get(plan) ?? []).filter((f) => f.code !== code).map((f) => f.name),\n }))\n .filter((group) => group.features.length > 0)\n : [];\n\n features.push({\n code,\n name: catalogEntry.name,\n lucideIcon: catalogEntry.lucideIcon,\n sfSymbol: catalogEntry.sfSymbol,\n materialSymbol: catalogEntry.materialSymbol,\n permissions: grantedPerms,\n locked: catalogEntry.locked ?? false,\n lockReason: catalogEntry.lockReason ?? null,\n unlockPlans: catalogEntry.unlockPlans ?? [],\n missingServices: catalogEntry.missingServices ?? [],\n lockedPermissions,\n upsell,\n route,\n appCode: catalogEntry.appCode,\n appName: catalogEntry.appName,\n appIcon: catalogEntry.appIcon,\n appSortOrder: catalogEntry.appSortOrder,\n });\n }\n\n // Order app-alphabetically so the core-web sidebar (groups by app) renders apps sorted without any frontend re-sort;\n // stable sort keeps each app's features in their existing relative order\n features.sort((a, b) => a.appName.localeCompare(b.appName));\n\n return features;\n}\n\n// Selects the route block from a catalog entry for the requested platform, or null when it doesn't publish there\nexport function pickRouteForPlatform(\n entry: {\n web: {\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n mobile: {\n remoteEntryAndroid: string;\n remoteEntryIos: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n },\n platform: ClientPlatform,\n): { remoteEntry: string; exposedModule: string; routePrefix: string } | null {\n if (platform === 'ios' || platform === 'android') {\n if (!entry.mobile) return null;\n return {\n remoteEntry: platform === 'ios' ? entry.mobile.remoteEntryIos : entry.mobile.remoteEntryAndroid,\n exposedModule: entry.mobile.exposedModule,\n routePrefix: entry.mobile.routePrefix,\n };\n }\n // Web\n if (!entry.web) return null;\n return {\n remoteEntry: entry.web.remoteEntry,\n exposedModule: entry.web.exposedModule,\n routePrefix: entry.web.routePrefix,\n };\n}\n","import { featureAppliesAtNode, isPlanMember, isSiteLockedOnPlatform } from './catalog.builder';\nimport {\n PLATFORMS,\n UI_PLATFORMS,\n type PlatformBucket,\n type ScopeType,\n type SiteFeatureLocks,\n type SiteType,\n type SnapshotPlan,\n snapshotFeatureKey,\n type VersionSnapshot,\n} from './types';\n\nexport interface SiteMatrixCell {\n inPlan: boolean;\n selected: boolean;\n availableIn: string[];\n}\n\nexport interface SiteMatrixPermission {\n code: string;\n label: string;\n dependsOn: string[];\n web: SiteMatrixCell | null;\n mobile: SiteMatrixCell | null;\n app: SiteMatrixCell | null;\n}\n\nexport interface SiteMatrixFeature {\n code: string;\n name: string;\n icon: string | null;\n scope: ScopeType;\n applicableSiteTypes: SiteType[];\n platforms: PlatformBucket[];\n inPlan: boolean;\n availableIn: string[];\n permissions: SiteMatrixPermission[];\n}\n\nexport interface SiteMatrixApp {\n code: string;\n name: string;\n icon: string | null;\n unlockedCount: number;\n totalCount: number;\n features: SiteMatrixFeature[];\n}\n\nexport interface SiteMatrix {\n plan: { code: string; name: string };\n apps: SiteMatrixApp[];\n locks: SiteFeatureLocks;\n}\n\n// Builds the SITE-only apps/features/permissions matrix — not filtered to plan members; plan-locked items carry inPlan=false + availableIn\nexport function buildSiteMatrix(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n siteType?: SiteType,\n): SiteMatrix {\n return buildMatrix(snapshot, businessCode, planCode, siteLocks, false, siteType);\n}\n\n// Builds the all-scopes apps/features/permissions matrix — every scope's features included, each carrying its real scope; powers the Plan Overview + Create Custom Role picker\nexport function buildPlanMatrix(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks?: SiteFeatureLocks,\n): SiteMatrix {\n return buildMatrix(snapshot, businessCode, planCode, siteLocks, true);\n}\n\n// Shared matrix builder — allScopes=false keeps only SITE refs; allScopes=true includes every scope and emits each feature's real scope\nfunction buildMatrix(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n allScopes: boolean,\n siteType?: SiteType,\n): SiteMatrix {\n const business = businessCode ? snapshot.businesses?.[businessCode] : undefined;\n const plans = business?.plans ?? {};\n const plan = planCode ? plans[planCode] : undefined;\n const planMeta = { code: planCode ?? '', name: plan?.name ?? planCode ?? '' };\n const locks = siteLocks ?? {};\n if (!business || !plan) return { plan: planMeta, apps: [], locks };\n\n const apps: SiteMatrixApp[] = [];\n for (const app of business.apps) {\n let unlockedCount = 0;\n let totalCount = 0;\n const features: SiteMatrixFeature[] = [];\n\n for (const ref of app.features) {\n if (!allScopes && ref.scope !== 'SITE') continue;\n const code = ref.code;\n const feature = snapshot.features?.[snapshotFeatureKey(code, ref.scope)];\n if (!feature) continue;\n if (siteType !== undefined && !featureAppliesAtNode(feature.applicableSiteTypes, siteType)) continue;\n // A UI bucket is offered only where the feature publishes a microfrontend; `app` is offered\n // always, because an API client has nothing to load. So a headless feature still yields one\n // platform and must not be skipped.\n const platforms: PlatformBucket[] = [\n ...UI_PLATFORMS.filter((p) => !!feature.microfrontends?.[p]),\n 'app',\n ];\n\n const membership = plan.unlockedPermissions?.[code];\n const featureInPlan = isPlanMember(membership);\n const siteEntry = siteLocks?.[code];\n\n const permissions: SiteMatrixPermission[] = (feature.permissions ?? [])\n .filter((p) => p.isGlobal || p.businesses.includes(businessCode ?? ''))\n .map((p) => {\n const cell = (plat: PlatformBucket): SiteMatrixCell | null => {\n if (!platforms.includes(plat)) return null;\n const planCodes = membership?.[plat];\n const inPlan = featureInPlan && planCodes !== undefined && planCodes.includes(p.code);\n // Deny-list: an in-plan cell is selected unless the site locks it on this platform\n const selected = inPlan && !isSiteLockedOnPlatform(siteEntry, plat, p.code);\n const availableIn = inPlan ? [] : plansUnlockingPerm(plans, code, p.code, plat, planCode);\n totalCount += 1;\n if (inPlan) unlockedCount += 1;\n return { inPlan, selected, availableIn };\n };\n return {\n code: p.code,\n label: p.label,\n dependsOn: p.dependsOn ?? [],\n web: cell('web'),\n mobile: cell('mobile'),\n app: cell('app'),\n };\n });\n\n features.push({\n code: feature.code,\n name: feature.name,\n icon: feature.lucideIcon ?? null,\n scope: feature.scope,\n applicableSiteTypes: feature.applicableSiteTypes,\n platforms,\n inPlan: featureInPlan,\n availableIn: featureInPlan ? [] : plansIncludingFeature(plans, code, planCode),\n permissions,\n });\n }\n\n if (features.length === 0) continue;\n apps.push({ code: app.code, name: app.name, icon: app.icon ?? null, unlockedCount, totalCount, features });\n }\n\n // Emit apps alphabetically by name so every consumer (Plan Overview, Role picker, all Locks screens) renders them sorted\n apps.sort((a, b) => a.name.localeCompare(b.name));\n\n return { plan: planMeta, apps, locks };\n}\n\n// Names of other plans (excluding the org's own) that unlock this feature+permission on the given platform\nfunction plansUnlockingPerm(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n permCode: string,\n platform: PlatformBucket,\n excludeCode: string | undefined,\n): string[] {\n const names: string[] = [];\n for (const [code, p] of Object.entries(plans)) {\n if (code === excludeCode) continue;\n if ((p.unlockedPermissions?.[featureCode]?.[platform] ?? []).includes(permCode)) names.push(p.name);\n }\n return names;\n}\n\n// Names of other plans (excluding the org's own) that include this feature at all (membership) — feature-level upsell\nfunction plansIncludingFeature(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n excludeCode: string | undefined,\n): string[] {\n const names: string[] = [];\n for (const [code, p] of Object.entries(plans)) {\n if (code === excludeCode) continue;\n if (isPlanMember(p.unlockedPermissions?.[featureCode])) names.push(p.name);\n }\n return names;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;ACKO,SAASA,gBAAgBC,aAA0D;AACxF,QAAMC,UAAU,IAAIC,IAAIF,YAAYG,IAAI,CAACC,MAAMA,EAAEC,IAAI,CAAA;AACrD,QAAMF,MAAkB,oBAAIG,IAAAA;AAC5B,aAAWF,KAAKJ,aAAa;AAC3BG,QAAII,IACFH,EAAEC,OACDD,EAAEI,aAAa,CAAA,GAAIC,OAAO,CAACC,QAAQA,QAAQN,EAAEC,QAAQJ,QAAQU,IAAID,GAAAA,CAAAA,CAAAA;EAEtE;AACA,SAAOP;AACT;AAVgBJ;AAaT,SAASa,cAAcP,MAAcQ,MAAgB;AAC1D,QAAMC,MAAM,oBAAIZ,IAAAA;AAChB,QAAMa,OAAO,oBAAIb,IAAY;IAACG;GAAK;AACnC,QAAMW,QAAQ;IAACX;;AACf,SAAOW,MAAMC,SAAS,GAAG;AACvB,UAAMC,UAAUF,MAAMG,IAAG;AACzB,eAAWT,OAAOG,KAAKO,IAAIF,OAAAA,KAAY,CAAA,GAAI;AACzC,UAAIH,KAAKJ,IAAID,GAAAA,EAAM;AACnBK,WAAKM,IAAIX,GAAAA;AACTI,UAAIO,IAAIX,GAAAA;AACRM,YAAMM,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1D,KAAAA,GAAQ;AAC7C,QAAIG,SAASoD,YAAa;AAC1B,QAAI9B,aAAaL,EAAEG,sBAAsB6B,WAAAA,CAAY,EAAGI,OAAMb,KAAKvB,EAAEhB,IAAI;EAC3E;AACA,SAAOoD;AACT;AAXSV,OAAAA,wBAAAA;","names":["buildDependsMap","permissions","present","Set","map","p","code","Map","set","dependsOn","filter","dep","has","prereqClosure","deps","out","seen","stack","length","current","pop","get","add","push","cascadeLocked","codes","directlyLocked","locked","visiting","check","viaDep","some","delete","filterGrantedByDeps","granted","ok","satisfied","every","PLATFORMS","UI_PLATFORMS","SITE_TYPES","SERVICE_CODES","snapshotFeatureKey","code","scope","SNAPSHOT_SCHEMA_VERSION","featureAppliesAtNode","applicableSiteTypes","siteType","includes","findFeatureByCode","snapshot","code","feature","Object","values","features","undefined","buildSiteCatalog","businessCode","planCode","siteLocks","bucket","scope","availableServices","business","businesses","plan","plans","catalog","sortedApps","apps","sort","a","b","name","localeCompare","app","businessAppFeatures","filter","ref","map","snapshotFeatureKey","f","microfrontends","web","mobile","length","membership","unlockedPermissions","memberOnBucket","sitePlatformLocked","missingServices","unmetServices","permissions","buildPermissions","lockReason","resolveLockReason","locked","unlockPlans","plansIncludingFeature","push","lucideIcon","sfSymbol","materialSymbol","remoteEntry","exposedModule","routePrefix","remoteEntryAndroid","remoteEntryIos","appCode","appName","appIcon","icon","appSortOrder","sortOrder","isPlanMember","entry","planLocked","siteLocked","requiredServices","service","isSiteLockedOnPlatform","platform","locks","planMembership","planUnlocked","Set","lockEntry","perms","p","isGlobal","deps","buildDependsMap","codes","directlyPlanLocked","directlySiteLocked","has","add","directlyLocked","lockedSet","cascadeLocked","closure","prereqClosure","cascaded","planReason","some","c","siteReason","plansUnlockingClosure","featureCode","result","entries","unlocked","every","buildSiteRoles","roleTemplates","unionBucket","base","add","undefined","Set","composeRoleGrants","params","baseFeatures","additions","revoked","result","featureCodes","Object","keys","code","revokes","composed","bucket","PLATFORMS","merged","revoke","filter","c","includes","web","mobile","EMPTY_ROUTE","remoteEntry","exposedModule","routePrefix","resolveUserFeatures","params","snapshot","businessCode","planCode","siteLocks","roleFeatures","platform","siteType","scope","availableServices","bucket","featureByCode","code","features","snapshotFeatureKey","findFeatureByCode","catalog","buildSiteCatalog","catalogMap","Map","map","f","businessPlans","businesses","plans","currentUnlockedCodes","Set","featureCode","platforms","Object","entries","unlockedPermissions","undefined","add","planAdds","planKey","plan","adds","has","name","push","set","grantedFeatures","grant","granted","perm","get","permsSet","catalogEntry","route","pickRouteForPlatform","featureDeps","buildDependsMap","permissions","permByCode","p","grantedPerms","filterGrantedByDeps","lockedPermissions","c","filter","locked","reason","lockReason","unlockPlans","missingServices","upsell","group","length","lucideIcon","sfSymbol","materialSymbol","appCode","appName","appIcon","appSortOrder","sort","a","b","localeCompare","entry","mobile","remoteEntryIos","remoteEntryAndroid","web","buildSiteMatrix","snapshot","businessCode","planCode","siteLocks","siteType","buildMatrix","buildPlanMatrix","allScopes","business","businesses","undefined","plans","plan","planMeta","code","name","locks","apps","app","unlockedCount","totalCount","features","ref","scope","feature","snapshotFeatureKey","featureAppliesAtNode","applicableSiteTypes","platforms","UI_PLATFORMS","filter","p","microfrontends","membership","unlockedPermissions","featureInPlan","isPlanMember","siteEntry","permissions","isGlobal","includes","map","cell","plat","planCodes","inPlan","selected","isSiteLockedOnPlatform","availableIn","plansUnlockingPerm","label","dependsOn","web","mobile","push","icon","lucideIcon","plansIncludingFeature","length","sort","a","b","localeCompare","featureCode","permCode","platform","excludeCode","names","Object","entries"]}
1
+ {"version":3,"sources":["../src/catalog-resolver/index.ts","../src/catalog-resolver/permission-deps.ts","../src/catalog-resolver/types.ts","../src/catalog-resolver/catalog.builder.ts","../src/catalog-resolver/compose-role-grants.ts","../src/catalog-resolver/resolve-user-features.ts","../src/catalog-resolver/site-matrix.builder.ts"],"sourcesContent":["// Catalog resolver — the single shared implementation of snapshot resolution (BU catalog, BU matrix, user features)\n\nexport {\n buildSiteCatalog,\n buildSiteRoles,\n featureAppliesAtNode,\n findFeatureByCode,\n isPlanMember,\n isSiteLockedOnPlatform,\n normalizeApiBuckets,\n surfaceAllows,\n} from './catalog.builder';\nexport { type ComposeRoleGrantsParams, composeRoleGrants, type RevokedGrants } from './compose-role-grants';\nexport {\n buildDependsMap,\n cascadeLocked,\n type DependsMap,\n filterGrantedByDeps,\n prereqClosure,\n} from './permission-deps';\nexport {\n type ClientPlatform,\n type LockedPermission,\n type PermissionFeature,\n pickRouteForPlatform,\n type ResolveUserFeaturesParams,\n resolveUserFeatures,\n} from './resolve-user-features';\nexport {\n buildPlanMatrix,\n buildSiteMatrix,\n type SiteMatrix,\n type SiteMatrixApp,\n type SiteMatrixCell,\n type SiteMatrixFeature,\n type SiteMatrixPermission,\n} from './site-matrix.builder';\nexport {\n API_BUCKETS,\n API_SURFACES,\n type ApiBucket,\n type ApiSurface,\n BUCKET_BY_SURFACE,\n type BusinessVocabulary,\n type CatalogPermission,\n type FeatureCatalogEntry,\n type FeatureLocks,\n type FeatureUnlocks,\n isApiBucket,\n type LockReason,\n PLATFORMS,\n type PlatformBucket,\n type PlatformCodes,\n type PlatformDenyCodes,\n type RoleItem,\n type ScopeType,\n SERVICE_CODES,\n type ServiceCode,\n SITE_TYPES,\n type SiteFeatureLocks,\n type SiteType,\n SNAPSHOT_SCHEMA_VERSION,\n type SnapshotApp,\n type SnapshotAppFeatureRef,\n type SnapshotBusiness,\n type SnapshotFeature,\n type SnapshotMicrofrontendMobile,\n type SnapshotMicrofrontends,\n type SnapshotMicrofrontendWeb,\n type SnapshotPermission,\n type SnapshotPlan,\n type SnapshotRoleTemplate,\n SURFACE_BY_BUCKET,\n snapshotFeatureKey,\n UI_PLATFORMS,\n type UiPlatformBucket,\n type VersionSnapshot,\n type VocabularyEntry,\n} from './types';\n","// Intra-feature permission prerequisites — only DIRECT edges are declared; the transitive closure is computed by recursion, cycle-guarded\n\nexport type DependsMap = Map<string, string[]>;\n\n// Builds a dependency map from a feature's permissions, keeping only edges to codes present in the set\nexport function buildDependsMap(permissions: Array<{ code: string; dependsOn?: string[] }>): DependsMap {\n const present = new Set(permissions.map((p) => p.code));\n const map: DependsMap = new Map();\n for (const p of permissions) {\n map.set(\n p.code,\n (p.dependsOn ?? []).filter((dep) => dep !== p.code && present.has(dep)),\n );\n }\n return map;\n}\n\n// Transitive prerequisite closure of a code (excludes the code itself), cycle-safe\nexport function prereqClosure(code: string, deps: DependsMap): string[] {\n const out = new Set<string>();\n const seen = new Set<string>([code]);\n const stack = [code];\n while (stack.length > 0) {\n const current = stack.pop() as string;\n for (const dep of deps.get(current) ?? []) {\n if (seen.has(dep)) continue;\n seen.add(dep);\n out.add(dep);\n stack.push(dep);\n }\n }\n return [...out];\n}\n\n// Codes locked after cascade: a code is locked if directly locked or any transitive prerequisite is (cycle-safe)\nexport function cascadeLocked(codes: string[], directlyLocked: Set<string>, deps: DependsMap): Set<string> {\n const locked = new Set<string>();\n const visiting = new Set<string>();\n const check = (code: string): boolean => {\n if (locked.has(code)) return true;\n if (directlyLocked.has(code)) {\n locked.add(code);\n return true;\n }\n if (visiting.has(code)) return false;\n visiting.add(code);\n const viaDep = (deps.get(code) ?? []).some(check);\n visiting.delete(code);\n if (viaDep) locked.add(code);\n return viaDep;\n };\n for (const code of codes) check(code);\n return locked;\n}\n\n// Keeps only codes whose FULL prerequisite closure is also present — drops a dependent missing any prerequisite (cycle-safe)\nexport function filterGrantedByDeps(granted: Set<string>, deps: DependsMap): Set<string> {\n const ok = new Set<string>();\n const visiting = new Set<string>();\n const check = (code: string): boolean => {\n if (ok.has(code)) return true;\n if (!granted.has(code)) return false;\n if (visiting.has(code)) return true;\n visiting.add(code);\n const satisfied = (deps.get(code) ?? []).every(check);\n visiting.delete(code);\n if (satisfied) ok.add(code);\n return satisfied;\n };\n for (const code of granted) check(code);\n return ok;\n}\n","// ——— Platform algebra — plan unlocks, role grants, and BU locks are all stored per platform bucket ———\n\n/**\n * The surfaces a permission can be granted on.\n *\n * `web` and `mobile` are UI buckets: a feature reaches them through a microfrontend, and a grant\n * there means a person can operate it on that surface. `graphql` and `http` are not UIs at all —\n * each is an API surface a credential signs its own requests against, so they have no\n * microfrontend and no route, and a feature needs neither to be reachable on one.\n *\n * Keeping the API buckets in the same algebra rather than beside it is what lets plan entitlement,\n * node feature locks and permission prerequisites bind an API client exactly as they bind a person.\n * One bucket per surface is what lets a plan entitle GraphQL and HTTP access independently.\n */\nexport type PlatformBucket = 'web' | 'mobile' | 'graphql' | 'http';\n\nexport const PLATFORMS: PlatformBucket[] = ['web', 'mobile', 'graphql', 'http'];\n\n/** Buckets that reach their feature through a microfrontend, and so require one to resolve. */\nexport type UiPlatformBucket = 'web' | 'mobile';\n\nexport const UI_PLATFORMS: UiPlatformBucket[] = ['web', 'mobile'];\n\n// The API surfaces an app credential can present — literally the values of core's `app_type` enum, so\n// enforcement is a plain lookup with no mapping. A feature declares which surfaces expose it.\nexport const API_SURFACES = ['GRAPHQL', 'HTTP'] as const;\nexport type ApiSurface = (typeof API_SURFACES)[number];\n\n/** Buckets that admit an API credential rather than a person — exactly one per surface. */\nexport type ApiBucket = Exclude<PlatformBucket, UiPlatformBucket>;\n\nexport const API_BUCKETS: ApiBucket[] = ['graphql', 'http'];\n\nexport const SURFACE_BY_BUCKET: Record<ApiBucket, ApiSurface> = { graphql: 'GRAPHQL', http: 'HTTP' };\nexport const BUCKET_BY_SURFACE: Record<ApiSurface, ApiBucket> = { GRAPHQL: 'graphql', HTTP: 'http' };\n\nexport function isApiBucket(bucket: PlatformBucket): bucket is ApiBucket {\n return bucket === 'graphql' || bucket === 'http';\n}\n\n// Documents written before GraphQL and HTTP were entitled separately may still carry a single legacy\n// `app` bucket meaning \"any API surface\". It is deliberately NOT part of these shapes — nothing may\n// write it — and is honoured only inside `normalizeApiBuckets`, which copies it into graphql/http.\nexport interface PlatformCodes {\n web?: string[];\n mobile?: string[];\n graphql?: string[];\n http?: string[];\n}\n\nexport interface PlatformDenyCodes {\n web?: string[] | null;\n mobile?: string[] | null;\n graphql?: string[] | null;\n http?: string[] | null;\n}\n\nexport type FeatureUnlocks = Record<string, PlatformCodes>;\n\nexport type FeatureLocks = Record<string, PlatformDenyCodes>;\nexport type SiteFeatureLocks = FeatureLocks;\n\n// ——— Snapshot document shape — what gets stored in versions.snapshot and signed into the catalog license ———\n\nexport interface SnapshotPermission {\n code: string;\n label: string;\n isGlobal: boolean;\n businesses: string[];\n dependsOn: string[];\n}\nexport interface SnapshotMicrofrontendWeb {\n code: string;\n name: string;\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n}\nexport interface SnapshotMicrofrontendMobile {\n code: string;\n name: string;\n remoteEntryAndroid: string;\n remoteEntryIos: string;\n exposedModule: string;\n routePrefix: string;\n}\nexport interface SnapshotMicrofrontends {\n web?: SnapshotMicrofrontendWeb;\n mobile?: SnapshotMicrofrontendMobile;\n}\nexport type ScopeType = 'ORG' | 'LE' | 'SITE_GROUP' | 'SITE';\nexport type SiteType = 'OUTLET' | 'WAREHOUSE' | 'PRODUCTION';\nexport const SITE_TYPES: SiteType[] = ['OUTLET', 'WAREHOUSE', 'PRODUCTION'];\n// External services a feature can depend on — the org must have the service provisioned before the feature\n// unlocks. Add new services here and nowhere else in this package; every lock path is service-agnostic.\nexport const SERVICE_CODES = ['GITEA'] as const;\nexport type ServiceCode = (typeof SERVICE_CODES)[number];\nexport interface SnapshotFeature {\n code: string;\n name: string;\n lucideIcon: string;\n sfSymbol: string;\n materialSymbol: string;\n scope: ScopeType;\n applicableSiteTypes: SiteType[];\n permissions: SnapshotPermission[];\n microfrontends: SnapshotMicrofrontends;\n // Optional: snapshots built before service gating existed carry no services, which reads as \"requires none\"\n requiredServices?: ServiceCode[];\n // Optional: snapshots built before surface gating existed carry no list, which reads as \"reachable by any\n // app credential\". A present list is strict — it decides which of the `graphql`/`http` buckets the feature\n // offers at all, and `[]` offers neither. The builder always emits it, so only pre-flag snapshots are lenient.\n apiSurfaces?: ApiSurface[];\n}\nexport interface SnapshotAppFeatureRef {\n code: string;\n scope: ScopeType;\n}\nexport interface SnapshotApp {\n code: string;\n name: string;\n icon: string;\n sortOrder: number;\n features: SnapshotAppFeatureRef[];\n}\nexport interface SnapshotRoleTemplate {\n name: string;\n code: string;\n scope: ScopeType;\n siteType: SiteType;\n features: FeatureUnlocks;\n}\nexport interface SnapshotPlan {\n code: string;\n name: string;\n isCustom: boolean;\n maxSites: number | null;\n unlockedPermissions: FeatureUnlocks;\n}\nexport interface VocabularyEntry {\n singular: string;\n plural: string;\n}\nexport interface BusinessVocabulary {\n site?: VocabularyEntry;\n siteGroup?: VocabularyEntry;\n outlet?: VocabularyEntry;\n warehouse?: VocabularyEntry;\n production?: VocabularyEntry;\n}\nexport interface SnapshotBusiness {\n name: string;\n vocabulary?: BusinessVocabulary;\n apps: SnapshotApp[];\n roleTemplates: Record<string, SnapshotRoleTemplate>;\n plans: Record<string, SnapshotPlan>;\n}\nexport interface VersionSnapshot {\n schemaVersion?: number;\n // Flat feature dictionary keyed by `${scope}.${code}` (see snapshotFeatureKey) — same-code features at different scopes stay distinct\n features: Record<string, SnapshotFeature>;\n businesses: Record<string, SnapshotBusiness>;\n}\n\n// Composite key for the snapshot feature dictionary — feature identity is (scope, code)\nexport function snapshotFeatureKey(code: string, scope: ScopeType): string {\n return `${scope}.${code}`;\n}\n\nexport const SNAPSHOT_SCHEMA_VERSION = 4;\n\n// SERVICE = the org has not provisioned an external service the feature declares; the specific services are\n// reported alongside in `missingServices` so callers never branch on a service code baked into this union\nexport type LockReason = 'PLAN' | 'SITE' | 'SERVICE';\n\nexport interface CatalogPermission {\n code: string;\n locked: boolean;\n lockReason: LockReason | null;\n unlockPlans: string[];\n missingServices: ServiceCode[];\n}\n\nexport interface FeatureCatalogEntry {\n code: string;\n name: string;\n lucideIcon: string | null;\n sfSymbol: string;\n materialSymbol: string;\n web: {\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n mobile: {\n remoteEntryAndroid: string;\n remoteEntryIos: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n appCode: string;\n appName: string;\n appIcon: string | null;\n appSortOrder: number;\n locked: boolean;\n lockReason: LockReason | null;\n unlockPlans: string[];\n missingServices: ServiceCode[];\n permissions: CatalogPermission[];\n}\n\nexport type RoleItem = SnapshotRoleTemplate;\n","import { buildDependsMap, cascadeLocked, prereqClosure } from './permission-deps';\nimport type {\n ApiSurface,\n CatalogPermission,\n FeatureCatalogEntry,\n LockReason,\n PlatformBucket,\n PlatformCodes,\n PlatformDenyCodes,\n RoleItem,\n ScopeType,\n ServiceCode,\n SiteFeatureLocks,\n SiteType,\n SnapshotFeature,\n SnapshotPlan,\n VersionSnapshot,\n} from './types';\nimport { isApiBucket, PLATFORMS, SURFACE_BY_BUCKET, snapshotFeatureKey } from './types';\n\n/**\n * Copies a legacy `app` bucket into whichever of `graphql`/`http` an entry lacks.\n *\n * Documents written before the API surfaces were entitled separately — old snapshots, old\n * credential grants, old deny-lists — carry one `app` bucket that meant \"any API surface\".\n * Normalising at read time is what lets those documents keep working without a re-key: an\n * `app` grant admits both surfaces, and an `app` lock fails closed on both. Entries already\n * carrying a surface bucket keep it — the legacy value only fills gaps.\n */\nexport function normalizeApiBuckets<T extends PlatformCodes | PlatformDenyCodes>(\n doc: Record<string, T> | undefined,\n): Record<string, T> | undefined {\n if (!doc) return doc;\n let changed = false;\n const next: Record<string, T> = {};\n for (const [code, entry] of Object.entries(doc)) {\n // The legacy key is deliberately absent from the public shapes so nothing can write it;\n // stored documents predating the split are the only place it still occurs.\n const legacy = (entry as T & LegacyApiBucket).app;\n if (legacy === undefined || (entry.graphql !== undefined && entry.http !== undefined)) {\n next[code] = entry;\n continue;\n }\n changed = true;\n next[code] = {\n ...entry,\n ...(entry.graphql === undefined ? { graphql: legacy } : {}),\n ...(entry.http === undefined ? { http: legacy } : {}),\n };\n }\n return changed ? next : doc;\n}\n\n// The pre-split single API bucket, as old persisted jsonb still carries it\ntype LegacyApiBucket = { app?: string[] | null };\n\n// Normalizes every plan's unlock document in one pass, so per-plan upsell lookups read legacy docs correctly too\nfunction normalizePlans(plans: Record<string, SnapshotPlan>): Record<string, SnapshotPlan> {\n let changed = false;\n const next: Record<string, SnapshotPlan> = {};\n for (const [code, plan] of Object.entries(plans)) {\n const unlockedPermissions = normalizeApiBuckets(plan.unlockedPermissions) ?? {};\n if (unlockedPermissions !== plan.unlockedPermissions) changed = true;\n next[code] = unlockedPermissions === plan.unlockedPermissions ? plan : { ...plan, unlockedPermissions };\n }\n return changed ? next : plans;\n}\n\n// Whether a feature with the given site-type applicability is exposed at this site type\nexport function featureAppliesAtNode(applicableSiteTypes: SiteType[], siteType: SiteType): boolean {\n return applicableSiteTypes.includes(siteType);\n}\n\n// Scope-agnostic lookup of a feature by bare code — grants/locks key features by code alone, so the first scope-variant's shared metadata (permission graph) answers\nexport function findFeatureByCode(snapshot: VersionSnapshot, code: string): SnapshotFeature | undefined {\n for (const feature of Object.values(snapshot.features ?? {})) {\n if (feature?.code === code) return feature;\n }\n return undefined;\n}\n\n// Builds the per-site catalog for ONE platform bucket — plan is the ceiling, siteLocks is a deny-list within it; each permission carries locked + lockReason + unlockPlans\n// availableServices defaults to none, so a caller that doesn't know the org's provisioned services locks every service-dependent feature rather than leaking it\nexport function buildSiteCatalog(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n bucket: PlatformBucket,\n siteType?: SiteType,\n scope?: ScopeType,\n availableServices: ServiceCode[] = [],\n): FeatureCatalogEntry[] {\n if (!businessCode) return [];\n const business = snapshot.businesses?.[businessCode];\n if (!business) return [];\n // Legacy `app` buckets in stored documents read as both API surfaces — see normalizeApiBuckets\n const plans = normalizePlans(business.plans ?? {});\n const plan = planCode ? plans[planCode] : undefined;\n const locks = normalizeApiBuckets(siteLocks);\n\n const catalog: FeatureCatalogEntry[] = [];\n // Iterate apps alphabetically by name so the resolved feature list (→ core-web sidebar) is app-alphabetical without any frontend re-sort\n const sortedApps = [...business.apps].sort((a, b) => a.name.localeCompare(b.name));\n for (const app of sortedApps) {\n // The app's renderable features (each ref pins scope+code to one app), dropped when they don't belong to this workspace scope or node type (outlet vs container)\n const businessAppFeatures = app.features\n .filter((ref) => scope === undefined || ref.scope === scope)\n .map((ref) => snapshot.features?.[snapshotFeatureKey(ref.code, ref.scope)])\n .filter(\n (f): f is SnapshotFeature =>\n !!f &&\n // A UI bucket needs something to render, so a feature shipping no microfrontend is dropped.\n // An API bucket renders nothing — there a feature is admitted by the surfaces it declares\n // instead, so a GRAPHQL credential never resolves an HTTP-only feature. A surface-excluded\n // feature vanishes from the catalog entirely, which is what makes resolution fail closed.\n (isApiBucket(bucket)\n ? surfaceAllows(f.apiSurfaces, SURFACE_BY_BUCKET[bucket])\n : !!(f.microfrontends?.web || f.microfrontends?.mobile)) &&\n (siteType === undefined || featureAppliesAtNode(f.applicableSiteTypes, siteType)),\n );\n\n if (businessAppFeatures.length === 0) continue;\n\n // Emit EVERY business feature so a role's grant on a plan-omitted feature still resolves as a locked tile instead of vanishing\n for (const feature of businessAppFeatures) {\n const membership = plan?.unlockedPermissions?.[feature.code];\n // Routes are exposed wherever the feature SHIPS — membership never hides them\n const web = feature.microfrontends?.web;\n const mobile = feature.microfrontends?.mobile;\n\n // Feature-level lock is EXPLICIT: plan must include the feature on this bucket, the site must not null-lock\n // the platform, and every external service the feature declares must be provisioned for the org\n const memberOnBucket = membership?.[bucket] !== undefined;\n const sitePlatformLocked = locks?.[feature.code]?.[bucket] === null;\n const missingServices = unmetServices(feature, availableServices);\n // Unmet services lock every permission too — otherwise the feature reads locked while its actions still\n // report as available, which is not how plan and site locks behave\n const permissions = buildPermissions(feature, businessCode, membership, locks, plans, bucket, missingServices);\n const lockReason = resolveLockReason(!memberOnBucket, sitePlatformLocked, missingServices);\n const locked = lockReason !== null;\n const unlockPlans = lockReason === 'PLAN' ? plansIncludingFeature(plans, feature.code, bucket) : [];\n\n catalog.push({\n code: feature.code,\n name: feature.name,\n lucideIcon: feature.lucideIcon ?? null,\n sfSymbol: feature.sfSymbol ?? 'square',\n materialSymbol: feature.materialSymbol ?? 'square',\n web: web\n ? {\n remoteEntry: web.remoteEntry ?? '',\n exposedModule: web.exposedModule ?? '',\n routePrefix: web.routePrefix ?? '',\n }\n : null,\n mobile: mobile\n ? {\n remoteEntryAndroid: mobile.remoteEntryAndroid ?? '',\n remoteEntryIos: mobile.remoteEntryIos ?? '',\n exposedModule: mobile.exposedModule ?? '',\n routePrefix: mobile.routePrefix ?? '',\n }\n : null,\n appCode: app.code,\n appName: app.name,\n appIcon: app.icon ?? null,\n appSortOrder: app.sortOrder ?? 0,\n locked,\n lockReason,\n unlockPlans,\n missingServices,\n permissions,\n });\n }\n }\n return catalog;\n}\n\n// A feature is a plan member when its unlock entry exists on at least one platform (even with zero actions).\n// Iterates PLATFORMS plus the legacy `app` key, so a caller handing over an un-normalized document\n// still reads a legacy API entitlement as membership.\nexport function isPlanMember(entry: PlatformCodes | undefined): boolean {\n if (!entry) return false;\n return PLATFORMS.some((platform) => entry[platform] !== undefined) || (entry as LegacyApiBucket).app !== undefined;\n}\n\n/**\n * Whether a feature's declared API surfaces admit a caller's surface.\n *\n * Lenient on either side being unknown: a pre-flag snapshot declares nothing (`undefined`), and a\n * caller resolving without a surface (cloud's matrix builders, UI buckets) filters nothing. Strictness\n * comes from both sides being present — including a declared `[]`, which admits no surface at all.\n */\nexport function surfaceAllows(surfaces: ApiSurface[] | undefined, surface: ApiSurface | undefined): boolean {\n return surface === undefined || surfaces === undefined || surfaces.includes(surface);\n}\n\n// The one place lock precedence is decided, for features and permissions alike; null means nothing locks.\n// Plan is the ceiling (an unentitled feature must upsell, not send the user to provision something they still\n// couldn't use), then the site deny-list, then any unprovisioned service.\nfunction resolveLockReason(\n planLocked: boolean,\n siteLocked: boolean,\n missingServices: ServiceCode[],\n): LockReason | null {\n if (planLocked) return 'PLAN';\n if (siteLocked) return 'SITE';\n if (missingServices.length > 0) return 'SERVICE';\n return null;\n}\n\n// The services a feature declares that this org has not provisioned\nfunction unmetServices(feature: SnapshotFeature, availableServices: ServiceCode[]): ServiceCode[] {\n return (feature.requiredServices ?? []).filter((service) => !availableServices.includes(service));\n}\n\n// Per-platform site-lock primitive: null locks the whole feature, string[] locks those codes, absent = not locked\nexport function isSiteLockedOnPlatform(\n entry: SiteFeatureLocks[string] | undefined,\n platform: PlatformBucket,\n code: string,\n): boolean {\n const locks = entry?.[platform];\n return locks === null || (locks?.includes(code) ?? false);\n}\n\n// A feature's business-scoped permissions, each tagged with locked + reason against the plan and site deny-list\n// (bucket-scoped). Unmet services lock the whole set — an unprovisioned service blocks every action on the feature.\nfunction buildPermissions(\n feature: SnapshotFeature,\n businessCode: string,\n planMembership: PlatformCodes | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n plans: Record<string, SnapshotPlan>,\n bucket: PlatformBucket,\n missingServices: ServiceCode[] = [],\n): CatalogPermission[] {\n const planUnlocked = new Set(planMembership?.[bucket] ?? []);\n const lockEntry = siteLocks?.[feature.code];\n\n const perms = (feature.permissions ?? []).filter((p) => p.isGlobal || p.businesses.includes(businessCode));\n const deps = buildDependsMap(perms);\n const codes = perms.map((p) => p.code);\n\n // Direct plan/site locks, then cascade so a locked prerequisite (e.g. view) locks its dependents (add/edit/delete)\n const directlyPlanLocked = new Set<string>();\n const directlySiteLocked = new Set<string>();\n for (const p of perms) {\n if (!planUnlocked.has(p.code)) directlyPlanLocked.add(p.code);\n if (isSiteLockedOnPlatform(lockEntry, bucket, p.code)) directlySiteLocked.add(p.code);\n }\n const directlyLocked = new Set<string>([...directlyPlanLocked, ...directlySiteLocked]);\n const lockedSet = cascadeLocked(codes, directlyLocked, deps);\n\n return perms.map((p) => {\n // A permission is enabled only if it AND its whole prerequisite closure are unlocked — reason/upsell reflect that\n const closure = [p.code, ...prereqClosure(p.code, deps)];\n const cascaded = lockedSet.has(p.code);\n const planReason = cascaded && closure.some((c) => directlyPlanLocked.has(c));\n const siteReason = cascaded && closure.some((c) => directlySiteLocked.has(c));\n const lockReason = resolveLockReason(planReason, siteReason, missingServices);\n const locked = lockReason !== null;\n const unlockPlans = lockReason === 'PLAN' ? plansUnlockingClosure(plans, feature.code, closure, bucket) : [];\n return { code: p.code, locked, lockReason, unlockPlans, missingServices };\n });\n}\n\n// Plan codes (in the business) whose unlocked set includes the permission AND its whole prerequisite closure — upsell targets\nfunction plansUnlockingClosure(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n closure: string[],\n bucket: PlatformBucket,\n): string[] {\n const result: string[] = [];\n for (const [code, plan] of Object.entries(plans)) {\n const unlocked = plan.unlockedPermissions?.[featureCode]?.[bucket];\n if (unlocked && closure.every((c) => unlocked.includes(c))) result.push(code);\n }\n return result;\n}\n\n// Plan codes (in the business) that include this feature on the bucket — the feature-level upsell targets\nfunction plansIncludingFeature(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n bucket: PlatformBucket,\n): string[] {\n const result: string[] = [];\n for (const [code, plan] of Object.entries(plans)) {\n if (plan.unlockedPermissions?.[featureCode]?.[bucket] !== undefined) result.push(code);\n }\n return result;\n}\n\n// The business's role templates as provisionable role items for core (identical shapes)\nexport function buildSiteRoles(snapshot: VersionSnapshot, businessCode: string | undefined): RoleItem[] {\n if (!businessCode) return [];\n const business = snapshot.businesses?.[businessCode];\n if (!business) return [];\n return Object.values(business.roleTemplates ?? {});\n}\n","import { type FeatureUnlocks, PLATFORMS, type PlatformCodes, type PlatformDenyCodes } from './types';\n\nexport type RevokedGrants = Record<string, PlatformDenyCodes>;\n\nexport interface ComposeRoleGrantsParams {\n baseFeatures: FeatureUnlocks | undefined;\n additions: FeatureUnlocks;\n revoked: RevokedGrants | undefined;\n}\n\n// Deduped union of two optional code lists — undefined on both sides means no platform membership\nfunction unionBucket(base: string[] | undefined, add: string[] | undefined): string[] | undefined {\n if (base === undefined && add === undefined) return undefined;\n return [...new Set([...(base ?? []), ...(add ?? [])])];\n}\n\n// Composes a custom role's effective grants: merge(base ∪ additions) − revoked (design doc §10); inputs are never mutated\nexport function composeRoleGrants(params: ComposeRoleGrantsParams): FeatureUnlocks {\n const { baseFeatures, additions, revoked } = params;\n\n const result: FeatureUnlocks = {};\n const featureCodes = new Set([...Object.keys(baseFeatures ?? {}), ...Object.keys(additions ?? {})]);\n\n for (const code of featureCodes) {\n const base = baseFeatures?.[code] ?? {};\n const add = additions?.[code] ?? {};\n const revokes = revoked?.[code];\n\n const composed: PlatformCodes = {};\n for (const bucket of PLATFORMS) {\n const merged = unionBucket(base[bucket], add[bucket]);\n if (merged === undefined) continue;\n const revoke = revokes?.[bucket];\n // null revokes the whole platform (membership + all codes); string[] subtracts codes but keeps membership\n if (revoke === null) continue;\n composed[bucket] = revoke === undefined ? merged : merged.filter((c) => !revoke.includes(c));\n }\n\n // A feature with no surviving platform membership disappears from the effective set.\n // Iterates PLATFORMS rather than naming buckets — the web/mobile-only version silently\n // dropped a grant surviving only on an API bucket.\n if (PLATFORMS.every((bucket) => composed[bucket] === undefined)) continue;\n result[code] = composed;\n }\n\n return result;\n}\n","import { buildSiteCatalog, findFeatureByCode, normalizeApiBuckets } from './catalog.builder';\nimport { buildDependsMap, filterGrantedByDeps } from './permission-deps';\nimport type {\n FeatureUnlocks,\n LockReason,\n PlatformBucket,\n ScopeType,\n ServiceCode,\n SiteFeatureLocks,\n SiteType,\n VersionSnapshot,\n} from './types';\nimport { isApiBucket, snapshotFeatureKey } from './types';\n\n/**\n * The caller's surface, as the caller reports it.\n *\n * Finer than `PlatformBucket` on the mobile side — `ios` and `android` load different remote\n * entries but share one grant bucket. The API platforms are one-to-one with their buckets: an\n * API client has no variants because it has no UI.\n */\nexport type ClientPlatform = 'web' | 'ios' | 'android' | 'graphql' | 'http';\n\n// Exhaustive by type, so adding a ClientPlatform without deciding its bucket fails the build instead\n// of silently falling through to mobile — which is how an API caller would end up resolving a UI bucket.\nconst BUCKET_BY_CLIENT: Record<ClientPlatform, PlatformBucket> = {\n web: 'web',\n ios: 'mobile',\n android: 'mobile',\n graphql: 'graphql',\n http: 'http',\n};\n\n/**\n * Stands in for the microfrontend an API client does not load.\n *\n * `PermissionFeature.route` is non-optional and read by the web sidebar and the mobile host to\n * mount a remote. Nothing on the API paths reads it — the permission interceptor uses `code`,\n * `permissions` and `locked` — so an empty route keeps one shape for every bucket instead of\n * widening the field to null across every consumer.\n */\nconst EMPTY_ROUTE = { remoteEntry: '', exposedModule: '', routePrefix: '' };\n\nexport interface LockedPermission {\n code: string;\n reason: LockReason | null;\n unlockPlans: string[];\n missingServices: ServiceCode[];\n}\n\nexport interface PlanUpsell {\n plan: string;\n features: string[];\n}\n\nexport interface PermissionFeature {\n code: string;\n name: string;\n lucideIcon: string | null;\n sfSymbol: string;\n materialSymbol: string;\n permissions: string[];\n locked: boolean;\n lockReason: LockReason | null;\n unlockPlans: string[];\n // Which declared services the org has not provisioned — empty unless lockReason is 'SERVICE'\n missingServices: ServiceCode[];\n lockedPermissions: LockedPermission[];\n upsell: PlanUpsell[];\n route: {\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n };\n appCode: string;\n appName: string;\n appIcon: string | null;\n appSortOrder: number;\n}\n\nexport interface ResolveUserFeaturesParams {\n snapshot: VersionSnapshot;\n businessCode: string;\n planCode: string | undefined;\n siteLocks: SiteFeatureLocks | undefined;\n roleFeatures: FeatureUnlocks;\n platform: ClientPlatform;\n siteType?: SiteType;\n scope?: ScopeType;\n // External services the org has provisioned; omitting it locks every service-dependent feature\n availableServices?: ServiceCode[];\n}\n\n// Resolves the features + MF config a user sees at a BU: plan ∧ BU catalog intersected with the role's grants, filtered to the requested platform\nexport function resolveUserFeatures(params: ResolveUserFeaturesParams): PermissionFeature[] {\n const { snapshot, businessCode, planCode, siteLocks, platform, siteType, scope, availableServices } = params;\n\n // Plan unlocks, BU locks, and role grants are stored per platform; resolve only the requesting\n // surface's bucket (web → web; ios/android → mobile; graphql/http → themselves)\n const bucket: PlatformBucket = BUCKET_BY_CLIENT[platform];\n\n // Legacy `app` buckets in stored grants read as both API surfaces — see normalizeApiBuckets\n const roleFeatures = normalizeApiBuckets(params.roleFeatures) ?? {};\n\n // Grants/plans/locks key features by bare code; resolve to the workspace scope's variant (or any variant when unscoped)\n const featureByCode = (code: string) =>\n scope ? snapshot.features?.[snapshotFeatureKey(code, scope)] : findFeatureByCode(snapshot, code);\n\n // Plan ∧ BU overlay for this bucket, filtered to features that apply to this workspace scope and node type — emits EVERY applicable business feature (plan non-members come out fully locked)\n const catalog = buildSiteCatalog(\n snapshot,\n businessCode,\n planCode,\n siteLocks,\n bucket,\n siteType,\n scope,\n availableServices,\n );\n const catalogMap = new Map(catalog.map((f) => [f.code, f]));\n\n // Per-plan feature-name delta vs the current plan — feeds the plan-locked upsell screen.\n // Normalized so a legacy plan document's `app` entitlement still counts for either API bucket.\n const businessPlans = Object.fromEntries(\n Object.entries(snapshot.businesses[businessCode]?.plans ?? {}).map(([code, plan]) => [\n code,\n { ...plan, unlockedPermissions: normalizeApiBuckets(plan.unlockedPermissions) ?? {} },\n ]),\n );\n const currentUnlockedCodes = new Set<string>();\n if (planCode && businessPlans[planCode]) {\n for (const [featureCode, platforms] of Object.entries(businessPlans[planCode].unlockedPermissions ?? {})) {\n if (platforms?.[bucket] !== undefined) currentUnlockedCodes.add(featureCode);\n }\n }\n const planAdds = new Map<string, Array<{ code: string; name: string }>>();\n for (const [planKey, plan] of Object.entries(businessPlans)) {\n if (planKey === planCode) continue;\n const adds: Array<{ code: string; name: string }> = [];\n for (const [featureCode, platforms] of Object.entries(plan.unlockedPermissions ?? {})) {\n if (platforms?.[bucket] === undefined || currentUnlockedCodes.has(featureCode)) continue;\n const name = featureByCode(featureCode)?.name;\n if (name) adds.push({ code: featureCode, name });\n }\n planAdds.set(planKey, adds);\n }\n\n // Granted permission set per feature, taking only this platform's grants\n const grantedFeatures = new Map<string, Set<string>>();\n for (const [code, grant] of Object.entries(roleFeatures ?? {})) {\n // Membership is the gate: undefined = not a member on this platform; [] = member with no actions (view-only)\n const granted = grant?.[bucket];\n if (granted === undefined) continue;\n if (!grantedFeatures.has(code)) grantedFeatures.set(code, new Set());\n for (const perm of granted) grantedFeatures.get(code)?.add(perm);\n }\n\n // Cross-reference the granted features with the catalog to build the response\n const features: PermissionFeature[] = [];\n for (const [code, permsSet] of grantedFeatures) {\n const catalogEntry = catalogMap.get(code);\n if (!catalogEntry) continue;\n\n // A UI bucket reaches its feature by loading a microfrontend, so a feature not published to\n // this platform is omitted rather than handed over as an unloadable tile. An API client loads\n // nothing — requiring a route there would make every headless feature permanently ungrantable.\n const route = isApiBucket(bucket) ? EMPTY_ROUTE : pickRouteForPlatform(catalogEntry, platform);\n if (!route) continue;\n\n // Drop granted permissions whose intra-feature prerequisites aren't also granted (e.g. add needs view)\n const featureDeps = buildDependsMap(featureByCode(code)?.permissions ?? []);\n // Plan/BU lock a subset of permissions; surface which GRANTED ones are locked + why + how to unlock (upsell)\n const permByCode = new Map((catalogEntry.permissions ?? []).map((p) => [p.code, p]));\n const grantedPerms = [...filterGrantedByDeps(permsSet, featureDeps)];\n const lockedPermissions: LockedPermission[] = grantedPerms\n .map((c) => permByCode.get(c))\n .filter((p): p is NonNullable<typeof p> => !!p?.locked)\n .map((p) => ({\n code: p.code,\n reason: p.lockReason ?? null,\n unlockPlans: p.unlockPlans ?? [],\n missingServices: p.missingServices ?? [],\n }));\n\n // For a plan-locked feature, list the extra features each unlocking plan would add (excluding this feature)\n const upsell: PlanUpsell[] =\n catalogEntry.locked && catalogEntry.lockReason === 'PLAN'\n ? (catalogEntry.unlockPlans ?? [])\n .map((plan) => ({\n plan,\n features: (planAdds.get(plan) ?? []).filter((f) => f.code !== code).map((f) => f.name),\n }))\n .filter((group) => group.features.length > 0)\n : [];\n\n features.push({\n code,\n name: catalogEntry.name,\n lucideIcon: catalogEntry.lucideIcon,\n sfSymbol: catalogEntry.sfSymbol,\n materialSymbol: catalogEntry.materialSymbol,\n permissions: grantedPerms,\n locked: catalogEntry.locked ?? false,\n lockReason: catalogEntry.lockReason ?? null,\n unlockPlans: catalogEntry.unlockPlans ?? [],\n missingServices: catalogEntry.missingServices ?? [],\n lockedPermissions,\n upsell,\n route,\n appCode: catalogEntry.appCode,\n appName: catalogEntry.appName,\n appIcon: catalogEntry.appIcon,\n appSortOrder: catalogEntry.appSortOrder,\n });\n }\n\n // Order app-alphabetically so the core-web sidebar (groups by app) renders apps sorted without any frontend re-sort;\n // stable sort keeps each app's features in their existing relative order\n features.sort((a, b) => a.appName.localeCompare(b.appName));\n\n return features;\n}\n\n// Selects the route block from a catalog entry for the requested platform, or null when it doesn't publish there\nexport function pickRouteForPlatform(\n entry: {\n web: {\n remoteEntry: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n mobile: {\n remoteEntryAndroid: string;\n remoteEntryIos: string;\n exposedModule: string;\n routePrefix: string;\n } | null;\n },\n platform: ClientPlatform,\n): { remoteEntry: string; exposedModule: string; routePrefix: string } | null {\n // API platforms load nothing — resolveUserFeatures never routes them here, and answering with the\n // web block for an unhandled value would hand an API caller a remote it cannot mount\n if (platform === 'graphql' || platform === 'http') return null;\n if (platform === 'ios' || platform === 'android') {\n if (!entry.mobile) return null;\n return {\n remoteEntry: platform === 'ios' ? entry.mobile.remoteEntryIos : entry.mobile.remoteEntryAndroid,\n exposedModule: entry.mobile.exposedModule,\n routePrefix: entry.mobile.routePrefix,\n };\n }\n // Web\n if (!entry.web) return null;\n return {\n remoteEntry: entry.web.remoteEntry,\n exposedModule: entry.web.exposedModule,\n routePrefix: entry.web.routePrefix,\n };\n}\n","import { featureAppliesAtNode, isPlanMember, isSiteLockedOnPlatform, normalizeApiBuckets } from './catalog.builder';\nimport {\n API_BUCKETS,\n type ApiSurface,\n type PlatformBucket,\n type ScopeType,\n type SiteFeatureLocks,\n type SiteType,\n type SnapshotPlan,\n SURFACE_BY_BUCKET,\n snapshotFeatureKey,\n UI_PLATFORMS,\n type VersionSnapshot,\n} from './types';\n\nexport interface SiteMatrixCell {\n inPlan: boolean;\n selected: boolean;\n availableIn: string[];\n}\n\nexport interface SiteMatrixPermission {\n code: string;\n label: string;\n dependsOn: string[];\n web: SiteMatrixCell | null;\n mobile: SiteMatrixCell | null;\n graphql: SiteMatrixCell | null;\n http: SiteMatrixCell | null;\n}\n\nexport interface SiteMatrixFeature {\n code: string;\n name: string;\n icon: string | null;\n scope: ScopeType;\n applicableSiteTypes: SiteType[];\n platforms: PlatformBucket[];\n inPlan: boolean;\n availableIn: string[];\n // The API surfaces the feature declares — what lets the app-credential editor filter by the\n // credential's type. Absent on pre-flag snapshots, which reads as \"any surface\".\n apiSurfaces?: ApiSurface[];\n permissions: SiteMatrixPermission[];\n}\n\nexport interface SiteMatrixApp {\n code: string;\n name: string;\n icon: string | null;\n unlockedCount: number;\n totalCount: number;\n features: SiteMatrixFeature[];\n}\n\nexport interface SiteMatrix {\n plan: { code: string; name: string };\n apps: SiteMatrixApp[];\n locks: SiteFeatureLocks;\n}\n\n// Builds the SITE-only apps/features/permissions matrix — not filtered to plan members; plan-locked items carry inPlan=false + availableIn\nexport function buildSiteMatrix(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n siteType?: SiteType,\n): SiteMatrix {\n return buildMatrix(snapshot, businessCode, planCode, siteLocks, false, siteType);\n}\n\n// Builds the all-scopes apps/features/permissions matrix — every scope's features included, each carrying its real scope; powers the Plan Overview + Create Custom Role picker\nexport function buildPlanMatrix(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks?: SiteFeatureLocks,\n): SiteMatrix {\n return buildMatrix(snapshot, businessCode, planCode, siteLocks, true);\n}\n\n// Shared matrix builder — allScopes=false keeps only SITE refs; allScopes=true includes every scope and emits each feature's real scope\nfunction buildMatrix(\n snapshot: VersionSnapshot,\n businessCode: string | undefined,\n planCode: string | undefined,\n siteLocks: SiteFeatureLocks | undefined,\n allScopes: boolean,\n siteType?: SiteType,\n): SiteMatrix {\n const business = businessCode ? snapshot.businesses?.[businessCode] : undefined;\n // Legacy `app` buckets in stored documents read as both API surfaces — see normalizeApiBuckets\n const plans = Object.fromEntries(\n Object.entries(business?.plans ?? {}).map(([code, p]) => [\n code,\n { ...p, unlockedPermissions: normalizeApiBuckets(p.unlockedPermissions) ?? {} },\n ]),\n );\n const plan = planCode ? plans[planCode] : undefined;\n const planMeta = { code: planCode ?? '', name: plan?.name ?? planCode ?? '' };\n const normalizedLocks = normalizeApiBuckets(siteLocks);\n const locks = normalizedLocks ?? {};\n if (!business || !plan) return { plan: planMeta, apps: [], locks };\n\n const apps: SiteMatrixApp[] = [];\n for (const app of business.apps) {\n let unlockedCount = 0;\n let totalCount = 0;\n const features: SiteMatrixFeature[] = [];\n\n for (const ref of app.features) {\n if (!allScopes && ref.scope !== 'SITE') continue;\n const code = ref.code;\n const feature = snapshot.features?.[snapshotFeatureKey(code, ref.scope)];\n if (!feature) continue;\n if (siteType !== undefined && !featureAppliesAtNode(feature.applicableSiteTypes, siteType)) continue;\n // A UI bucket is offered only where the feature publishes a microfrontend; each API bucket is\n // offered where the feature declares its surface. An undeclared list (pre-flag snapshot) keeps\n // the old always-offered behaviour on both; an undeclared surface shows an em dash like a\n // missing microfrontend does.\n const platforms: PlatformBucket[] = [\n ...UI_PLATFORMS.filter((p) => !!feature.microfrontends?.[p]),\n ...API_BUCKETS.filter(\n (b) => feature.apiSurfaces === undefined || feature.apiSurfaces.includes(SURFACE_BY_BUCKET[b]),\n ),\n ];\n\n const membership = plan.unlockedPermissions?.[code];\n const featureInPlan = isPlanMember(membership);\n const siteEntry = normalizedLocks?.[code];\n\n const permissions: SiteMatrixPermission[] = (feature.permissions ?? [])\n .filter((p) => p.isGlobal || p.businesses.includes(businessCode ?? ''))\n .map((p) => {\n const cell = (plat: PlatformBucket): SiteMatrixCell | null => {\n if (!platforms.includes(plat)) return null;\n const planCodes = membership?.[plat];\n const inPlan = featureInPlan && planCodes !== undefined && planCodes.includes(p.code);\n // Deny-list: an in-plan cell is selected unless the site locks it on this platform\n const selected = inPlan && !isSiteLockedOnPlatform(siteEntry, plat, p.code);\n const availableIn = inPlan ? [] : plansUnlockingPerm(plans, code, p.code, plat, planCode);\n totalCount += 1;\n if (inPlan) unlockedCount += 1;\n return { inPlan, selected, availableIn };\n };\n return {\n code: p.code,\n label: p.label,\n dependsOn: p.dependsOn ?? [],\n web: cell('web'),\n mobile: cell('mobile'),\n graphql: cell('graphql'),\n http: cell('http'),\n };\n });\n\n features.push({\n code: feature.code,\n name: feature.name,\n icon: feature.lucideIcon ?? null,\n scope: feature.scope,\n applicableSiteTypes: feature.applicableSiteTypes,\n platforms,\n inPlan: featureInPlan,\n availableIn: featureInPlan ? [] : plansIncludingFeature(plans, code, planCode),\n apiSurfaces: feature.apiSurfaces,\n permissions,\n });\n }\n\n if (features.length === 0) continue;\n apps.push({ code: app.code, name: app.name, icon: app.icon ?? null, unlockedCount, totalCount, features });\n }\n\n // Emit apps alphabetically by name so every consumer (Plan Overview, Role picker, all Locks screens) renders them sorted\n apps.sort((a, b) => a.name.localeCompare(b.name));\n\n return { plan: planMeta, apps, locks };\n}\n\n// Names of other plans (excluding the org's own) that unlock this feature+permission on the given platform\nfunction plansUnlockingPerm(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n permCode: string,\n platform: PlatformBucket,\n excludeCode: string | undefined,\n): string[] {\n const names: string[] = [];\n for (const [code, p] of Object.entries(plans)) {\n if (code === excludeCode) continue;\n if ((p.unlockedPermissions?.[featureCode]?.[platform] ?? []).includes(permCode)) names.push(p.name);\n }\n return names;\n}\n\n// Names of other plans (excluding the org's own) that include this feature at all (membership) — feature-level upsell\nfunction plansIncludingFeature(\n plans: Record<string, SnapshotPlan>,\n featureCode: string,\n excludeCode: string | undefined,\n): string[] {\n const names: string[] = [];\n for (const [code, p] of Object.entries(plans)) {\n if (code === excludeCode) continue;\n if (isPlanMember(p.unlockedPermissions?.[featureCode])) names.push(p.name);\n }\n return names;\n}\n"],"mappings":";;;;;;;;;;;;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AK,CAACC,GAAG9B,MAAM8B,EAAEjD,KAAKkD,cAAc/B,EAAEnB,IAAI,CAAA;AAE/C,SAAO;IAAEF,MAAMC;IAAUI;IAAMD;EAAM;AACvC;AAhGSnB;AAmGT,SAASqD,mBACP/C,OACA8D,aACAC,UACAC,UACAC,aAA+B;AAE/B,QAAMC,QAAkB,CAAA;AACxB,aAAW,CAAC7D,MAAMC,CAAAA,KAAML,OAAOE,QAAQH,KAAAA,GAAQ;AAC7C,QAAIK,SAAS4D,YAAa;AAC1B,SAAK3D,EAAEC,sBAAsBuD,WAAAA,IAAeE,QAAAA,KAAa,CAAA,GAAIhC,SAAS+B,QAAAA,EAAWG,OAAMZ,KAAKhD,EAAEK,IAAI;EACpG;AACA,SAAOuD;AACT;AAbSnB;AAgBT,SAASU,uBACPzD,OACA8D,aACAG,aAA+B;AAE/B,QAAMC,QAAkB,CAAA;AACxB,aAAW,CAAC7D,MAAMC,CAAAA,KAAML,OAAOE,QAAQH,KAAAA,GAAQ;AAC7C,QAAIK,SAAS4D,YAAa;AAC1B,QAAI7B,aAAa9B,EAAEC,sBAAsBuD,WAAAA,CAAY,EAAGI,OAAMZ,KAAKhD,EAAEK,IAAI;EAC3E;AACA,SAAOuD;AACT;AAXST,OAAAA,wBAAAA;","names":["buildDependsMap","permissions","present","Set","map","p","code","Map","set","dependsOn","filter","dep","has","prereqClosure","deps","out","seen","stack","length","current","pop","get","add","push","cascadeLocked","codes","directlyLocked","locked","visiting","check","viaDep","some","delete","filterGrantedByDeps","granted","ok","satisfied","every","PLATFORMS","UI_PLATFORMS","API_SURFACES","API_BUCKETS","SURFACE_BY_BUCKET","graphql","http","BUCKET_BY_SURFACE","GRAPHQL","HTTP","isApiBucket","bucket","SITE_TYPES","SERVICE_CODES","snapshotFeatureKey","code","scope","SNAPSHOT_SCHEMA_VERSION","normalizeApiBuckets","doc","changed","next","code","entry","Object","entries","legacy","app","undefined","graphql","http","normalizePlans","plans","plan","unlockedPermissions","featureAppliesAtNode","applicableSiteTypes","siteType","includes","findFeatureByCode","snapshot","feature","values","features","buildSiteCatalog","businessCode","planCode","siteLocks","bucket","scope","availableServices","business","businesses","locks","catalog","sortedApps","apps","sort","a","b","name","localeCompare","businessAppFeatures","filter","ref","map","snapshotFeatureKey","f","isApiBucket","surfaceAllows","apiSurfaces","SURFACE_BY_BUCKET","microfrontends","web","mobile","length","membership","memberOnBucket","sitePlatformLocked","missingServices","unmetServices","permissions","buildPermissions","lockReason","resolveLockReason","locked","unlockPlans","plansIncludingFeature","push","lucideIcon","sfSymbol","materialSymbol","remoteEntry","exposedModule","routePrefix","remoteEntryAndroid","remoteEntryIos","appCode","appName","appIcon","icon","appSortOrder","sortOrder","isPlanMember","PLATFORMS","some","platform","surfaces","surface","planLocked","siteLocked","requiredServices","service","isSiteLockedOnPlatform","planMembership","planUnlocked","Set","lockEntry","perms","p","isGlobal","deps","buildDependsMap","codes","directlyPlanLocked","directlySiteLocked","has","add","directlyLocked","lockedSet","cascadeLocked","closure","prereqClosure","cascaded","planReason","c","siteReason","plansUnlockingClosure","featureCode","result","unlocked","every","buildSiteRoles","roleTemplates","unionBucket","base","add","undefined","Set","composeRoleGrants","params","baseFeatures","additions","revoked","result","featureCodes","Object","keys","code","revokes","composed","bucket","PLATFORMS","merged","revoke","filter","c","includes","every","BUCKET_BY_CLIENT","web","ios","android","graphql","http","EMPTY_ROUTE","remoteEntry","exposedModule","routePrefix","resolveUserFeatures","params","snapshot","businessCode","planCode","siteLocks","platform","siteType","scope","availableServices","bucket","roleFeatures","normalizeApiBuckets","featureByCode","code","features","snapshotFeatureKey","findFeatureByCode","catalog","buildSiteCatalog","catalogMap","Map","map","f","businessPlans","Object","fromEntries","entries","businesses","plans","plan","unlockedPermissions","currentUnlockedCodes","Set","featureCode","platforms","undefined","add","planAdds","planKey","adds","has","name","push","set","grantedFeatures","grant","granted","perm","get","permsSet","catalogEntry","route","isApiBucket","pickRouteForPlatform","featureDeps","buildDependsMap","permissions","permByCode","p","grantedPerms","filterGrantedByDeps","lockedPermissions","c","filter","locked","reason","lockReason","unlockPlans","missingServices","upsell","group","length","lucideIcon","sfSymbol","materialSymbol","appCode","appName","appIcon","appSortOrder","sort","a","b","localeCompare","entry","mobile","remoteEntryIos","remoteEntryAndroid","buildSiteMatrix","snapshot","businessCode","planCode","siteLocks","siteType","buildMatrix","buildPlanMatrix","allScopes","business","businesses","undefined","plans","Object","fromEntries","entries","map","code","p","unlockedPermissions","normalizeApiBuckets","plan","planMeta","name","normalizedLocks","locks","apps","app","unlockedCount","totalCount","features","ref","scope","feature","snapshotFeatureKey","featureAppliesAtNode","applicableSiteTypes","platforms","UI_PLATFORMS","filter","microfrontends","API_BUCKETS","b","apiSurfaces","includes","SURFACE_BY_BUCKET","membership","featureInPlan","isPlanMember","siteEntry","permissions","isGlobal","cell","plat","planCodes","inPlan","selected","isSiteLockedOnPlatform","availableIn","plansUnlockingPerm","label","dependsOn","web","mobile","graphql","http","push","icon","lucideIcon","plansIncludingFeature","length","sort","a","localeCompare","featureCode","permCode","platform","excludeCode","names"]}