Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,19 @@
{
"name": "@toolctrl/entitlements",
"version": "0.0.0",
"private": true,
"type": "module",
"sideEffects": false,
"exports": {
".": "./src/index.ts"
},
"scripts": {
"test": "vitest run src",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"devDependencies": {
"@types/node": "^25.6.0",
"typescript": "^5.3.2",
"vitest": "^3.2.4"
}
}
@@ -0,0 +1,82 @@
import { featureKeys, type FeatureKey } from "./features.js";
export const productBlueprintIds = Object.freeze({
crmSaas: "crm-saas",
} as const);
export type ProductBlueprintId = (typeof productBlueprintIds)[keyof typeof productBlueprintIds];
export interface ProductBlueprintFeatureDefinition {
readonly featureKey: FeatureKey;
readonly defaultEnabled: boolean;
readonly tenantToggleable: boolean;
readonly requiresTenantRolePermission?: string;
}
export interface ProductBlueprintDefinition {
readonly id: ProductBlueprintId;
readonly version: string;
readonly title: string;
readonly description: string;
readonly defaultShowcase: boolean;
readonly features: readonly ProductBlueprintFeatureDefinition[];
}
function blueprintFeature(
featureKey: FeatureKey,
defaultEnabled: boolean,
tenantToggleable: boolean,
requiresTenantRolePermission?: string
): ProductBlueprintFeatureDefinition {
return Object.freeze({
featureKey,
defaultEnabled,
tenantToggleable,
...(requiresTenantRolePermission ? { requiresTenantRolePermission } : {}),
});
}
export const productBlueprints = Object.freeze([
Object.freeze({
id: productBlueprintIds.crmSaas,
version: "2026.05.15",
title: "CRM SaaS",
description: "Default CRM SaaS product core with support, knowledge base, marketing, API, AI credits, workflow automation, and optional tenant MCP.",
defaultShowcase: true,
features: Object.freeze([
blueprintFeature(featureKeys.crmBasic, true, false, "app.dashboard.view"),
blueprintFeature(featureKeys.files, true, true, "files.read_own"),
blueprintFeature(featureKeys.tasks, true, true, "tasks.read_own"),
blueprintFeature(featureKeys.supportTickets, true, true, "app.dashboard.view"),
blueprintFeature(featureKeys.knowledgeBaseRead, true, true, "app.dashboard.view"),
blueprintFeature(featureKeys.knowledgeBaseTenant, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.emailMarketing, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.importedLists, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.crmBasedLists, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.onboarding, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.api, true, true, "app.settings.apiKeys.create"),
blueprintFeature(featureKeys.workflowEngine, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.mcp, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.advancedBuilder, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.importExport, true, true, "app.dashboard.view"),
blueprintFeature(featureKeys.credits, true, false, "app.dashboard.view"),
blueprintFeature(featureKeys.users, true, false, "app.settings.members.view"),
]),
}),
] as const satisfies readonly ProductBlueprintDefinition[]);
const blueprintById = new Map<ProductBlueprintId, ProductBlueprintDefinition>(productBlueprints.map((blueprint) => [blueprint.id, blueprint]));
export function getProductBlueprint(blueprintId: ProductBlueprintId): ProductBlueprintDefinition;
export function getProductBlueprint(blueprintId: string): ProductBlueprintDefinition | undefined;
export function getProductBlueprint(blueprintId: string): ProductBlueprintDefinition | undefined {
return blueprintById.get(blueprintId as ProductBlueprintId);
}
export function getDefaultProductBlueprint(): ProductBlueprintDefinition {
const blueprint = productBlueprints.find((item) => item.defaultShowcase);
if (!blueprint) {
throw new Error("No default product blueprint is configured.");
}
return blueprint;
}
@@ -0,0 +1,65 @@
import { readdir, readFile } from "node:fs/promises";
import { dirname, extname, join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const sourceRoot = dirname(fileURLToPath(import.meta.url));
const forbiddenImportPattern = /(?:from\s+["']|import\s*\(\s*["'])(~\/|app\/|@toolctrl\/(?:db|config)(?:\/|$)|react(?:\/|$)|react-router(?:\/|$)|stripe(?:\/|$)|@prisma\/client(?:\/|$)|\.prisma\/client(?:\/|$)|prisma(?:\/|$))/;
const diagnosticTemplatePattern = /(?:message\s*[:=]|new\s+\w*Error\s*\()[^;\n]*/g;
const unsafeDiagnosticPattern = /tenant|customer|user|api[-_\s]?key|subscription[-_\s]?id|secret|sk_[a-z0-9]/i;
async function collectSourceFiles(directory: string): Promise<readonly string[]> {
const entries = await readdir(directory, { withFileTypes: true });
const files = await Promise.all(
entries.map(async (entry) => {
const entryPath = join(directory, entry.name);
if (entry.isDirectory()) {
return collectSourceFiles(entryPath);
}
const isSourceFile = extname(entryPath) === ".ts" && !entryPath.endsWith(".test.ts");
return isSourceFile ? [entryPath] : [];
}),
);
return files.flat();
}
function toPackageRelativePath(absolutePath: string): string {
return relative(sourceRoot, absolutePath).split(sep).join("/");
}
describe("entitlements package boundary", () => {
it("keeps runtime source files free of app and framework imports", async () => {
const sourceFiles = await collectSourceFiles(sourceRoot);
expect(sourceFiles.map(toPackageRelativePath).sort()).toEqual([
"blueprints.ts",
"evaluate.ts",
"features.ts",
"index.ts",
"plans.ts",
"product-access.ts",
]);
for (const sourceFile of sourceFiles) {
const source = await readFile(sourceFile, "utf8");
expect(source, toPackageRelativePath(sourceFile)).not.toMatch(forbiddenImportPattern);
}
});
it("keeps exported diagnostic templates free of identifiers and secrets", async () => {
const exportedSourceFiles = [join(sourceRoot, "features.ts"), join(sourceRoot, "evaluate.ts")];
for (const sourceFile of exportedSourceFiles) {
const source = await readFile(sourceFile, "utf8");
const diagnosticTemplates = source.match(diagnosticTemplatePattern) ?? [];
expect(diagnosticTemplates.join("\n"), toPackageRelativePath(sourceFile)).not.toMatch(unsafeDiagnosticPattern);
}
});
});
@@ -0,0 +1,259 @@
import { describe, expect, it } from "vitest";
import { entitlementLimitTypes, evaluateEntitlement, type EntitlementDecisionReason } from "./index.js";
const stableReasonCodes = [
"included",
"not-included",
"max-remaining",
"max-exhausted",
"monthly-remaining",
"monthly-exhausted",
"unlimited",
"trial-active",
"trial-expired",
"missing-subscription",
"unknown-feature",
] as const satisfies readonly EntitlementDecisionReason[];
describe("evaluateEntitlement", () => {
it("allows included features", () => {
expect(
evaluateEntitlement({
featureKey: "api",
hasSubscription: true,
limitType: entitlementLimitTypes.included,
}),
).toEqual({
allowed: true,
reason: "included",
featureKey: "api",
limitType: 1,
period: undefined,
message: undefined,
});
});
it("denies not-included features", () => {
expect(
evaluateEntitlement({
featureKey: "priority-support",
hasSubscription: true,
limitType: entitlementLimitTypes.notIncluded,
message: "Upgrade required",
}),
).toMatchObject({
allowed: false,
reason: "not-included",
featureKey: "priority-support",
limitType: 0,
message: "Upgrade required",
});
});
it("allows max-limited features with remaining usage", () => {
expect(
evaluateEntitlement({
featureKey: "users",
hasSubscription: true,
limitType: entitlementLimitTypes.max,
limit: 5,
used: 3,
}),
).toMatchObject({
allowed: true,
reason: "max-remaining",
featureKey: "users",
limitType: 3,
limit: 5,
used: 3,
remaining: 2,
});
});
it("denies max-limited features with exhausted usage", () => {
expect(
evaluateEntitlement({
featureKey: "users",
hasSubscription: true,
limitType: entitlementLimitTypes.max,
limit: 5,
used: 5,
}),
).toMatchObject({
allowed: false,
reason: "max-exhausted",
limit: 5,
used: 5,
remaining: 0,
});
});
it("allows monthly-limited features with remaining usage and period diagnostics", () => {
expect(
evaluateEntitlement({
featureKey: "ai-credits",
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 25,
period: "2026-05",
}),
).toMatchObject({
allowed: true,
reason: "monthly-remaining",
featureKey: "ai-credits",
limitType: 2,
limit: 100,
used: 25,
remaining: 75,
period: "2026-05",
});
});
it("denies monthly-limited features with exhausted usage", () => {
expect(
evaluateEntitlement({
featureKey: "ai-credits",
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 125,
period: "2026-05",
}),
).toMatchObject({
allowed: false,
reason: "monthly-exhausted",
limit: 100,
used: 125,
remaining: 0,
period: "2026-05",
});
});
it("allows unlimited features", () => {
expect(
evaluateEntitlement({
featureKey: "private-generations",
hasSubscription: true,
limitType: entitlementLimitTypes.unlimited,
}),
).toMatchObject({
allowed: true,
reason: "unlimited",
featureKey: "private-generations",
limitType: 4,
});
});
it("denies known features when subscription state is missing", () => {
expect(
evaluateEntitlement({
featureKey: "api",
limitType: entitlementLimitTypes.included,
}),
).toMatchObject({
allowed: false,
reason: "missing-subscription",
featureKey: "api",
limitType: 1,
});
});
it("allows known features during an active trial without a subscription", () => {
expect(
evaluateEntitlement({
featureKey: "api",
trialActive: true,
trialPeriod: "trial-day-7",
trialMessage: "Trial access",
limitType: entitlementLimitTypes.included,
}),
).toEqual({
allowed: true,
reason: "trial-active",
featureKey: "api",
limitType: 1,
period: undefined,
trialPeriod: "trial-day-7",
message: "Trial access",
});
});
it("denies known features when the trial is expired and no subscription exists", () => {
expect(
evaluateEntitlement({
featureKey: "api",
trialActive: false,
trialPeriod: "trial-ended",
limitType: entitlementLimitTypes.included,
}),
).toMatchObject({
allowed: false,
reason: "trial-expired",
featureKey: "api",
limitType: 1,
trialPeriod: "trial-ended",
});
});
it("denies unknown features before evaluating trial state", () => {
expect(
evaluateEntitlement({
featureKey: "unknown-feature",
trialActive: true,
limitType: entitlementLimitTypes.unlimited,
}),
).toMatchObject({
allowed: false,
reason: "unknown-feature",
featureKey: "unknown-feature",
limitType: 4,
});
});
it("denies unknown features before evaluating subscription state", () => {
expect(
evaluateEntitlement({
featureKey: "unknown-feature",
hasSubscription: true,
limitType: entitlementLimitTypes.unlimited,
}),
).toMatchObject({
allowed: false,
reason: "unknown-feature",
featureKey: "unknown-feature",
limitType: 4,
});
});
it("keeps denied diagnostics free of obvious identifiers and secrets", () => {
const decisions = [
evaluateEntitlement({ featureKey: "api", limitType: entitlementLimitTypes.included }),
evaluateEntitlement({ featureKey: "api", trialActive: false, trialPeriod: "trial-ended" }),
evaluateEntitlement({ featureKey: "ai-credits", hasSubscription: true, limitType: entitlementLimitTypes.monthly, limit: 1, used: 1 }),
evaluateEntitlement({ featureKey: "unknown-feature", hasSubscription: true, trialActive: true }),
];
const unsafeDiagnosticPattern = /tenant|customer|subscription id|user id|api key|secret|sk_[a-z0-9]/i;
for (const decision of decisions) {
expect(JSON.stringify(decision)).not.toMatch(unsafeDiagnosticPattern);
}
});
it("keeps reason codes stable for package-boundary consumers", () => {
expect(stableReasonCodes).toEqual([
"included",
"not-included",
"max-remaining",
"max-exhausted",
"monthly-remaining",
"monthly-exhausted",
"unlimited",
"trial-active",
"trial-expired",
"missing-subscription",
"unknown-feature",
]);
});
});
@@ -0,0 +1,177 @@
import { isFeatureKey, type FeatureKey } from "./features.js";
export const entitlementLimitTypes = Object.freeze({
notIncluded: 0,
included: 1,
monthly: 2,
max: 3,
unlimited: 4,
} as const);
export type EntitlementLimitType = (typeof entitlementLimitTypes)[keyof typeof entitlementLimitTypes];
export type EntitlementDecisionReason =
| "included"
| "not-included"
| "max-remaining"
| "max-exhausted"
| "monthly-remaining"
| "monthly-exhausted"
| "unlimited"
| "trial-active"
| "trial-expired"
| "missing-subscription"
| "unknown-feature";
export interface EvaluateEntitlementInput {
readonly featureKey: string;
readonly hasSubscription?: boolean;
readonly trialActive?: boolean;
readonly trialPeriod?: string;
readonly trialMessage?: string;
readonly limitType?: EntitlementLimitType;
readonly limit?: number | null;
readonly used?: number | null;
readonly period?: string;
readonly message?: string;
}
export interface EntitlementDecision {
readonly allowed: boolean;
readonly reason: EntitlementDecisionReason;
readonly featureKey: FeatureKey | string;
readonly limitType?: EntitlementLimitType;
readonly limit?: number;
readonly used?: number;
readonly remaining?: number;
readonly period?: string;
readonly trialPeriod?: string;
readonly message?: string;
}
function normalizeCount(value: number | null | undefined): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : undefined;
}
function usageDecision({
featureKey,
limitType,
limit,
used,
period,
message,
allowedReason,
deniedReason,
}: {
readonly featureKey: FeatureKey;
readonly limitType: EntitlementLimitType;
readonly limit: number | null | undefined;
readonly used: number | null | undefined;
readonly period?: string;
readonly message?: string;
readonly allowedReason: EntitlementDecisionReason;
readonly deniedReason: EntitlementDecisionReason;
}): EntitlementDecision {
const normalizedLimit = normalizeCount(limit) ?? 0;
const normalizedUsed = normalizeCount(used) ?? 0;
const remaining = Math.max(0, normalizedLimit - normalizedUsed);
const allowed = remaining > 0;
return {
allowed,
reason: allowed ? allowedReason : deniedReason,
featureKey,
limitType,
limit: normalizedLimit,
used: normalizedUsed,
remaining,
period,
message,
};
}
export function evaluateEntitlement(input: EvaluateEntitlementInput): EntitlementDecision {
const { featureKey, limitType, limit, used, period, message, trialActive, trialPeriod, trialMessage } = input;
if (!isFeatureKey(featureKey)) {
return {
allowed: false,
reason: "unknown-feature",
featureKey,
limitType,
limit: normalizeCount(limit),
used: normalizeCount(used),
period,
trialPeriod,
message,
};
}
if (input.hasSubscription !== true) {
if (trialActive === true) {
return {
allowed: true,
reason: "trial-active",
featureKey,
limitType,
period,
trialPeriod,
message: trialMessage ?? message,
};
}
return {
allowed: false,
reason: trialActive === false ? "trial-expired" : "missing-subscription",
featureKey,
limitType,
limit: normalizeCount(limit),
used: normalizeCount(used),
period,
trialPeriod,
message: trialActive === false ? (trialMessage ?? message) : message,
};
}
switch (limitType) {
case entitlementLimitTypes.included:
return { allowed: true, reason: "included", featureKey, limitType, period, message };
case entitlementLimitTypes.notIncluded:
return { allowed: false, reason: "not-included", featureKey, limitType, period, message };
case entitlementLimitTypes.max:
return usageDecision({
featureKey,
limitType,
limit,
used,
period,
message,
allowedReason: "max-remaining",
deniedReason: "max-exhausted",
});
case entitlementLimitTypes.monthly:
return usageDecision({
featureKey,
limitType,
limit,
used,
period,
message,
allowedReason: "monthly-remaining",
deniedReason: "monthly-exhausted",
});
case entitlementLimitTypes.unlimited:
return { allowed: true, reason: "unlimited", featureKey, limitType, period, message };
default:
return {
allowed: false,
reason: "not-included",
featureKey,
limitType,
limit: normalizeCount(limit),
used: normalizeCount(used),
period,
message,
};
}
}
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import { assertKnownFeatureKey, featureGateRegistry, featureKeys, getFeatureGate, isFeatureKey, type FeatureKey } from "./index.js";
const currentDefaultFeatureKeys = [
"crm-basic",
"support-tickets",
"knowledge-base-read",
"knowledge-base-tenant",
"files",
"users",
"tasks",
"api",
"email-marketing",
"imported-lists",
"crm-based-lists",
"onboarding",
"workflow-engine",
"mcp",
"advanced-builder",
"import-export",
"rate-limit-per-minute",
"rate-limit-per-second",
"priority-support",
"ai-credits",
"private-generations",
] as const satisfies readonly FeatureKey[];
describe("featureGateRegistry", () => {
it("covers every current default billing feature key", () => {
expect(featureGateRegistry.map((feature) => feature.key)).toEqual(currentDefaultFeatureKeys);
expect(Object.values(featureKeys).sort()).toEqual([...currentDefaultFeatureKeys].sort());
});
it("uses unique feature keys and default ordering", () => {
const keys = featureGateRegistry.map((feature) => feature.key);
const orders = featureGateRegistry.map((feature) => feature.defaultOrder);
expect(new Set(keys).size).toBe(keys.length);
expect(new Set(orders).size).toBe(orders.length);
expect([...orders].sort((left, right) => left - right)).toEqual(orders);
});
it("keeps registry items diagnostic-safe", () => {
const unsafeDiagnosticPattern = /customer|subscription id|user id|api key|secret|sk_[a-z0-9]/i;
for (const feature of featureGateRegistry) {
expect(feature.description).not.toMatch(unsafeDiagnosticPattern);
expect(feature.title).not.toMatch(unsafeDiagnosticPattern);
}
});
it("returns immutable lookup results", () => {
const usersFeature = getFeatureGate("users");
expect(Object.isFrozen(featureGateRegistry)).toBe(true);
expect(usersFeature).toBeDefined();
expect(Object.isFrozen(usersFeature)).toBe(true);
expect(() => {
(usersFeature as { title: string }).title = "Changed";
}).toThrow(TypeError);
expect(getFeatureGate("users")?.title).toBe("Users");
});
it("narrows and asserts known feature keys", () => {
const maybeFeature = "ai-credits";
expect(isFeatureKey(maybeFeature)).toBe(true);
assertKnownFeatureKey(maybeFeature);
expect(getFeatureGate(maybeFeature)?.key).toBe("ai-credits");
});
it("returns undefined and throws for unknown feature keys", () => {
expect(isFeatureKey("unknown-feature")).toBe(false);
expect(getFeatureGate("unknown-feature")).toBeUndefined();
expect(() => assertKnownFeatureKey("unknown-feature")).toThrow(RangeError);
});
});
@@ -0,0 +1,231 @@
export const featureKeys = {
crmBasic: "crm-basic",
files: "files",
tasks: "tasks",
supportTickets: "support-tickets",
knowledgeBaseRead: "knowledge-base-read",
knowledgeBaseTenant: "knowledge-base-tenant",
users: "users",
emailMarketing: "email-marketing",
importedLists: "imported-lists",
crmBasedLists: "crm-based-lists",
onboarding: "onboarding",
api: "api",
workflowEngine: "workflow-engine",
mcp: "mcp",
advancedBuilder: "advanced-builder",
importExport: "import-export",
rateLimitPerMinute: "rate-limit-per-minute",
rateLimitPerSecond: "rate-limit-per-second",
prioritySupport: "priority-support",
credits: "ai-credits",
privateGenerations: "private-generations",
} as const;
export type FeatureKey = (typeof featureKeys)[keyof typeof featureKeys];
export type FeatureCategory = "access" | "usage" | "support" | "generation" | "crm" | "marketing" | "automation" | "customization";
export type FeatureLimitType = "not-included" | "included" | "monthly" | "max" | "unlimited";
export interface FeatureGateRegistryItem {
readonly key: FeatureKey;
readonly title: string;
readonly category: FeatureCategory;
readonly supportedLimitTypes: readonly FeatureLimitType[];
readonly defaultOrder: number;
readonly description: string;
}
const accessLimitTypes = ["not-included", "included", "unlimited"] as const satisfies readonly FeatureLimitType[];
const quotaLimitTypes = ["not-included", "monthly", "max", "unlimited"] as const satisfies readonly FeatureLimitType[];
const rateLimitTypes = ["not-included", "max", "unlimited"] as const satisfies readonly FeatureLimitType[];
export const featureGateRegistry = Object.freeze([
Object.freeze({
key: featureKeys.crmBasic,
title: "CRM basics",
category: "crm",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 5,
description: "Controls access to the default CRM account, contact, and opportunity surfaces.",
}),
Object.freeze({
key: featureKeys.supportTickets,
title: "Support tickets",
category: "support",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 6,
description: "Controls support ticket creation and ticket volume.",
}),
Object.freeze({
key: featureKeys.knowledgeBaseRead,
title: "Knowledge base read",
category: "support",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 7,
description: "Controls read access to the global and product knowledge bases.",
}),
Object.freeze({
key: featureKeys.knowledgeBaseTenant,
title: "Tenant knowledge base",
category: "support",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 8,
description: "Controls tenant-owned knowledge base authoring and publishing.",
}),
Object.freeze({
key: featureKeys.files,
title: "Files",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 9,
description: "Controls access to the central file storage (chunked upload, preview, sharing).",
}),
Object.freeze({
key: featureKeys.users,
title: "Users",
category: "access",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 10,
description: "Controls the number of workspace members available to an account.",
}),
Object.freeze({
key: featureKeys.tasks,
title: "Tasks",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 11,
description: "Controls access to the cross-cutting task module (assignment, reminders, entity links).",
}),
Object.freeze({
key: featureKeys.api,
title: "API Access",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 20,
description: "Controls whether programmatic API access is available.",
}),
Object.freeze({
key: featureKeys.emailMarketing,
title: "Email marketing",
category: "marketing",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 21,
description: "Controls email campaign creation and monthly campaign sends.",
}),
Object.freeze({
key: featureKeys.importedLists,
title: "Imported lists",
category: "marketing",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 22,
description: "Controls whether imported audience lists can be used.",
}),
Object.freeze({
key: featureKeys.crmBasedLists,
title: "CRM based lists",
category: "marketing",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 23,
description: "Controls whether CRM segments can be used as audiences.",
}),
Object.freeze({
key: featureKeys.onboarding,
title: "Onboarding",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 24,
description: "Controls tenant onboarding builder access.",
}),
Object.freeze({
key: featureKeys.workflowEngine,
title: "Workflow engine",
category: "automation",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 25,
description: "Controls tenant workflow builder and workflow run volume.",
}),
Object.freeze({
key: featureKeys.mcp,
title: "Tenant MCP",
category: "automation",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 26,
description: "Controls tenant MCP access when the active product blueprint enables MCP.",
}),
Object.freeze({
key: featureKeys.advancedBuilder,
title: "Advanced builder",
category: "customization",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 27,
description: "Controls advanced entity, UI, and product customization tools.",
}),
Object.freeze({
key: featureKeys.importExport,
title: "Import and export",
category: "usage",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 28,
description: "Controls import/export heavy workflows and monthly operation volume.",
}),
Object.freeze({
key: featureKeys.rateLimitPerMinute,
title: "Rate limit per minute",
category: "usage",
supportedLimitTypes: rateLimitTypes,
defaultOrder: 30,
description: "Controls the maximum permitted requests in a one minute window.",
}),
Object.freeze({
key: featureKeys.rateLimitPerSecond,
title: "Rate limit per second",
category: "usage",
supportedLimitTypes: rateLimitTypes,
defaultOrder: 40,
description: "Controls the maximum permitted requests in a one second window.",
}),
Object.freeze({
key: featureKeys.prioritySupport,
title: "Priority support",
category: "support",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 50,
description: "Controls whether priority support handling is available.",
}),
Object.freeze({
key: featureKeys.credits,
title: "Credits",
category: "usage",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 60,
description: "Controls the amount of metered product credits available in a billing period.",
}),
Object.freeze({
key: featureKeys.privateGenerations,
title: "Private generations",
category: "generation",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 70,
description: "Controls whether generated outputs are handled with private visibility.",
}),
] as const satisfies readonly FeatureGateRegistryItem[]);
const featureGateRegistryByKey = new Map<FeatureKey, FeatureGateRegistryItem>(featureGateRegistry.map((feature) => [feature.key, feature]));
export function isFeatureKey(value: string): value is FeatureKey {
return featureGateRegistryByKey.has(value as FeatureKey);
}
export function getFeatureGate(featureKey: FeatureKey): FeatureGateRegistryItem;
export function getFeatureGate(featureKey: string): FeatureGateRegistryItem | undefined;
export function getFeatureGate(featureKey: string): FeatureGateRegistryItem | undefined {
return isFeatureKey(featureKey) ? featureGateRegistryByKey.get(featureKey) : undefined;
}
export function assertKnownFeatureKey(value: string): asserts value is FeatureKey {
if (!isFeatureKey(value)) {
throw new RangeError(`Unknown feature key: ${value}`);
}
}
@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import {
entitlementLimitTypes,
entitlementPlanIds,
entitlementsPackageName,
evaluateProductAccess,
featureKeys,
getDefaultProductBlueprint,
getStandardEntitlementPlan,
productBlueprintIds,
} from "./index.js";
describe("entitlements package shell", () => {
it("exports the package identity placeholder", () => {
expect(entitlementsPackageName).toBe("@toolctrl/entitlements");
});
it("defines the CRM SaaS product core blueprint as the default showcase", () => {
const blueprint = getDefaultProductBlueprint();
expect(blueprint).toMatchObject({
id: productBlueprintIds.crmSaas,
version: "2026.05.15",
defaultShowcase: true,
});
expect(blueprint.features.map((feature) => feature.featureKey)).toEqual(
expect.arrayContaining([featureKeys.crmBasic, featureKeys.supportTickets, featureKeys.workflowEngine, featureKeys.mcp])
);
});
it("keeps Starter, Pro, and Business realistically strict", () => {
expect(getStandardEntitlementPlan(entitlementPlanIds.starter)?.features).toEqual(
expect.arrayContaining([
expect.objectContaining({ featureKey: featureKeys.crmBasic, limitType: entitlementLimitTypes.included }),
expect.objectContaining({ featureKey: featureKeys.api, limitType: entitlementLimitTypes.notIncluded }),
expect.objectContaining({ featureKey: featureKeys.workflowEngine, limitType: entitlementLimitTypes.notIncluded }),
])
);
expect(getStandardEntitlementPlan(entitlementPlanIds.pro)?.features).toEqual(
expect.arrayContaining([
expect.objectContaining({ featureKey: featureKeys.emailMarketing, limitType: entitlementLimitTypes.monthly }),
expect.objectContaining({ featureKey: featureKeys.api, limitType: entitlementLimitTypes.included }),
expect.objectContaining({ featureKey: featureKeys.workflowEngine, limitType: entitlementLimitTypes.notIncluded }),
])
);
expect(getStandardEntitlementPlan(entitlementPlanIds.business)?.features).toEqual(
expect.arrayContaining([
expect.objectContaining({ featureKey: featureKeys.workflowEngine, limitType: entitlementLimitTypes.monthly }),
expect.objectContaining({ featureKey: featureKeys.mcp, limitType: entitlementLimitTypes.included }),
expect.objectContaining({ featureKey: featureKeys.advancedBuilder, limitType: entitlementLimitTypes.included }),
])
);
});
it("evaluates product access through blueprint, plan, tenant override, and tenant-owned role permission", () => {
expect(
evaluateProductAccess({
blueprintId: productBlueprintIds.crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.notIncluded,
tenantRolePermissionNames: ["app.settings.roles.set"],
})
).toMatchObject({ allowed: false, reason: "not-included" });
expect(
evaluateProductAccess({
blueprintId: productBlueprintIds.crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 10,
tenantOverride: "disabled",
tenantRolePermissionNames: ["app.settings.roles.set"],
})
).toMatchObject({ allowed: false, reason: "tenant-override-disabled" });
expect(
evaluateProductAccess({
blueprintId: productBlueprintIds.crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 10,
tenantRolePermissionNames: [],
})
).toMatchObject({ allowed: false, reason: "tenant-role-missing", requiredTenantRolePermission: "app.settings.roles.set" });
expect(
evaluateProductAccess({
blueprintId: productBlueprintIds.crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 10,
tenantRolePermissionNames: ["app.settings.roles.set"],
})
).toMatchObject({ allowed: true, reason: "monthly-remaining", remaining: 90 });
expect(
evaluateProductAccess({
blueprintId: productBlueprintIds.crmSaas,
featureKey: featureKeys.crmBasic,
hasSubscription: true,
limitType: entitlementLimitTypes.notIncluded,
tenantOverride: "enabled",
tenantRolePermissionNames: ["app.dashboard.view"],
})
).toMatchObject({ allowed: false, reason: "tenant-override-not-toggleable" });
});
});
@@ -0,0 +1,36 @@
export const entitlementsPackageName = "@toolctrl/entitlements";
export {
assertKnownFeatureKey,
featureGateRegistry,
featureKeys,
getFeatureGate,
isFeatureKey,
} from "./features.js";
export { entitlementLimitTypes, evaluateEntitlement } from "./evaluate.js";
export {
entitlementPlanIds,
getStandardEntitlementPlan,
getStripePricePlaceholder,
getStripeProductPlaceholder,
listStandardEntitlementPlanIds,
standardEntitlementPlans,
} from "./plans.js";
export { getDefaultProductBlueprint, getProductBlueprint, productBlueprintIds, productBlueprints } from "./blueprints.js";
export { evaluateProductAccess } from "./product-access.js";
export type { FeatureCategory, FeatureGateRegistryItem, FeatureKey, FeatureLimitType } from "./features.js";
export type { ProductBlueprintDefinition, ProductBlueprintFeatureDefinition, ProductBlueprintId } from "./blueprints.js";
export type {
EntitlementPlanFeatureAssignment,
EntitlementPlanId,
EntitlementPlanMetadata,
EntitlementPlanStub,
} from "./plans.js";
export type {
EntitlementDecision,
EntitlementDecisionReason,
EntitlementLimitType,
EvaluateEntitlementInput,
} from "./evaluate.js";
export type { ProductAccessDecision, ProductAccessDecisionReason, ProductAccessInput, TenantFeatureOverride } from "./product-access.js";
@@ -0,0 +1,143 @@
import { describe, expect, it } from "vitest";
import {
entitlementLimitTypes,
featureGateRegistry,
getFeatureGate,
getStandardEntitlementPlan,
getStripePricePlaceholder,
getStripeProductPlaceholder,
listStandardEntitlementPlanIds,
standardEntitlementPlans,
type EntitlementPlanFeatureAssignment,
type FeatureKey,
} from "./index.js";
const expectedPlanIds = ["starter", "pro", "business"] as const;
const expectedFeatureKeys = [
"crm-basic",
"support-tickets",
"knowledge-base-read",
"knowledge-base-tenant",
"files",
"users",
"tasks",
"api",
"email-marketing",
"imported-lists",
"crm-based-lists",
"onboarding",
"workflow-engine",
"mcp",
"advanced-builder",
"import-export",
"rate-limit-per-minute",
"rate-limit-per-second",
"priority-support",
"ai-credits",
"private-generations",
] as const satisfies readonly FeatureKey[];
const unsafeFixturePattern =
/(?:prod_[a-z0-9]|price_[a-z0-9]|sk_(?:live|test)|pk_(?:live|test)|api[_ -]?key|secret|password|token|tenant[_ -]?id|customer[_ -]?id|subscription[_ -]?id|acct_[a-z0-9]|cus_[a-z0-9]|sub_[a-z0-9])/i;
function limitTypeName(limitType: number): string | undefined {
return Object.entries(entitlementLimitTypes).find(([, value]) => value === limitType)?.[0];
}
function assignmentStrings(assignment: EntitlementPlanFeatureAssignment): readonly string[] {
return [assignment.featureKey, assignment.label, String(assignment.limit ?? ""), String(assignment.order), String(assignment.limitType)];
}
describe("standardEntitlementPlans", () => {
it("exports public standard plans in deterministic order", () => {
expect(listStandardEntitlementPlanIds()).toEqual(expectedPlanIds);
expect(standardEntitlementPlans.map((plan) => plan.metadata.sortOrder)).toEqual([10, 20, 30]);
expect(standardEntitlementPlans.map((plan) => plan.metadata.slug)).toEqual(expectedPlanIds);
expect(standardEntitlementPlans.every((plan) => plan.metadata.isPublic)).toBe(true);
});
it("uses unique plan IDs and immutable plan fixtures", () => {
const planIds = listStandardEntitlementPlanIds();
expect(new Set(planIds).size).toBe(planIds.length);
expect(Object.isFrozen(standardEntitlementPlans)).toBe(true);
for (const plan of standardEntitlementPlans) {
expect(Object.isFrozen(plan)).toBe(true);
expect(Object.isFrozen(plan.metadata)).toBe(true);
expect(Object.isFrozen(plan.features)).toBe(true);
}
});
it("covers every registered standard feature in every public plan", () => {
for (const plan of standardEntitlementPlans) {
expect(
plan.features.map((feature) => feature.featureKey),
`${plan.id} feature coverage`
).toEqual(expectedFeatureKeys);
expect(
plan.features.map((feature) => feature.featureKey),
`${plan.id} registry coverage`
).toEqual(featureGateRegistry.map((feature) => feature.key));
}
});
it("keeps plan feature assignments in registry order", () => {
const expectedOrders = featureGateRegistry.map((feature) => feature.defaultOrder);
for (const plan of standardEntitlementPlans) {
expect(
plan.features.map((feature) => feature.order),
`${plan.id} feature order`
).toEqual(expectedOrders);
}
});
it("references only known feature keys and supported limit types", () => {
for (const plan of standardEntitlementPlans) {
for (const assignment of plan.features) {
const featureGate = getFeatureGate(assignment.featureKey);
const registryLimitType = limitTypeName(assignment.limitType);
expect(featureGate, `${plan.id}.${assignment.featureKey} known feature`).toBeDefined();
expect(registryLimitType, `${plan.id}.${assignment.featureKey} limit type name`).toBeDefined();
expect(featureGate?.supportedLimitTypes, `${plan.id}.${assignment.featureKey} supported limit type`).toContain(
registryLimitType?.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)
);
}
}
});
it("exposes lookup helpers without mutating fixture order", () => {
expect(getStandardEntitlementPlan("pro")?.metadata.publicName).toBe("Pro");
expect(getStandardEntitlementPlan("pro")?.metadata.stripeProductId).toBe(getStripeProductPlaceholder("pro"));
expect(getStandardEntitlementPlan("pro")?.metadata.stripePriceId).toBe(getStripePricePlaceholder("pro"));
expect(getStandardEntitlementPlan("unknown-plan")).toBeUndefined();
expect(listStandardEntitlementPlanIds()).toEqual(expectedPlanIds);
});
it("uses deterministic safe Stripe placeholders and no secret-looking fixture strings", () => {
for (const plan of standardEntitlementPlans) {
expect(plan.metadata.stripeProductId, `${plan.id} product id placeholder`).toBe(getStripeProductPlaceholder(plan.id));
expect(plan.metadata.stripePriceId, `${plan.id} price id placeholder`).toBe(getStripePricePlaceholder(plan.id));
expect(plan.metadata.stripeProductId, `${plan.id} non-empty product placeholder`).not.toBe("");
expect(plan.metadata.stripePriceId, `${plan.id} non-empty price placeholder`).not.toBe("");
expect(getStandardEntitlementPlan(plan.id)?.metadata.stripeProductId, `${plan.id} lookup product placeholder`).toBe(plan.metadata.stripeProductId);
expect(getStandardEntitlementPlan(plan.id)?.metadata.stripePriceId, `${plan.id} lookup price placeholder`).toBe(plan.metadata.stripePriceId);
const strings = [
plan.id,
plan.metadata.slug,
plan.metadata.publicName,
plan.metadata.description,
plan.metadata.stripeProductId,
plan.metadata.stripePriceId,
...plan.features.flatMap(assignmentStrings),
];
for (const value of strings) {
expect(value, `${plan.id} safe fixture value`).not.toMatch(unsafeFixturePattern);
}
}
});
});
@@ -0,0 +1,185 @@
import { entitlementLimitTypes, type EntitlementLimitType } from "./evaluate.js";
import { featureGateRegistry, featureKeys, type FeatureKey } from "./features.js";
export const entitlementPlanIds = Object.freeze({
starter: "starter",
pro: "pro",
business: "business",
} as const);
export type EntitlementPlanId = (typeof entitlementPlanIds)[keyof typeof entitlementPlanIds];
export const stripePlaceholderPrefixes = Object.freeze({
product: "fixture-stripe-product",
price: "fixture-stripe-price",
} as const);
export function getStripeProductPlaceholder(planId: EntitlementPlanId): string {
return `${stripePlaceholderPrefixes.product}-${planId}`;
}
export function getStripePricePlaceholder(planId: EntitlementPlanId): string {
return `${stripePlaceholderPrefixes.price}-${planId}`;
}
export interface EntitlementPlanMetadata {
readonly slug: EntitlementPlanId;
readonly publicName: string;
readonly description: string;
readonly stripeProductId: string;
readonly stripePriceId: string;
readonly sortOrder: number;
readonly isPublic: boolean;
}
export interface EntitlementPlanFeatureAssignment {
readonly featureKey: FeatureKey;
readonly limitType: EntitlementLimitType;
readonly limit: number | null;
readonly order: number;
readonly label: string;
}
export interface EntitlementPlanStub {
readonly id: EntitlementPlanId;
readonly metadata: EntitlementPlanMetadata;
readonly features: readonly EntitlementPlanFeatureAssignment[];
}
const featureOrderByKey = new Map<FeatureKey, number>(featureGateRegistry.map((feature) => [feature.key, feature.defaultOrder]));
function assignment(featureKey: FeatureKey, limitType: EntitlementLimitType, limit: number | null, label: string): EntitlementPlanFeatureAssignment {
return Object.freeze({
featureKey,
limitType,
limit,
order: featureOrderByKey.get(featureKey) ?? 0,
label,
});
}
function planStub(
id: EntitlementPlanId,
metadata: Omit<EntitlementPlanMetadata, "slug" | "stripeProductId" | "stripePriceId" | "isPublic">,
features: readonly EntitlementPlanFeatureAssignment[]
): EntitlementPlanStub {
return Object.freeze({
id,
metadata: Object.freeze({
slug: id,
stripeProductId: getStripeProductPlaceholder(id),
stripePriceId: getStripePricePlaceholder(id),
isPublic: true,
...metadata,
}),
features: Object.freeze([...features].sort((left, right) => left.order - right.order || left.featureKey.localeCompare(right.featureKey))),
});
}
export const standardEntitlementPlans = Object.freeze([
planStub(
entitlementPlanIds.starter,
{
publicName: "Starter",
description: "CRM basics, support tickets, knowledge base reading, and small team limits.",
sortOrder: 10,
},
[
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.monthly, 50, "50 support tickets per month"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.notIncluded, null, "Tenant knowledge base authoring not included"),
assignment(featureKeys.users, entitlementLimitTypes.max, 3, "Up to 3 users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.notIncluded, null, "Email marketing not included"),
assignment(featureKeys.importedLists, entitlementLimitTypes.notIncluded, null, "Imported lists not included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.notIncluded, null, "CRM based lists not included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.notIncluded, null, "Onboarding builder not included"),
assignment(featureKeys.api, entitlementLimitTypes.notIncluded, null, "API access not included"),
assignment(featureKeys.workflowEngine, entitlementLimitTypes.notIncluded, null, "Workflow engine not included"),
assignment(featureKeys.mcp, entitlementLimitTypes.notIncluded, null, "Tenant MCP not included"),
assignment(featureKeys.advancedBuilder, entitlementLimitTypes.notIncluded, null, "Advanced builder not included"),
assignment(featureKeys.importExport, entitlementLimitTypes.monthly, 25, "25 import/export operations per month"),
assignment(featureKeys.rateLimitPerMinute, entitlementLimitTypes.max, 60, "60 requests per minute"),
assignment(featureKeys.rateLimitPerSecond, entitlementLimitTypes.max, 2, "2 requests per second"),
assignment(featureKeys.prioritySupport, entitlementLimitTypes.notIncluded, null, "Community support"),
assignment(featureKeys.credits, entitlementLimitTypes.monthly, 250, "250 AI credits per month"),
assignment(featureKeys.privateGenerations, entitlementLimitTypes.notIncluded, null, "Shared generation visibility"),
]
),
planStub(
entitlementPlanIds.pro,
{
publicName: "Pro",
description: "Production CRM SaaS plan with marketing, onboarding, API, and AI credits.",
sortOrder: 20,
},
[
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.monthly, 500, "500 support tickets per month"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.included, null, "Tenant knowledge base authoring included"),
assignment(featureKeys.users, entitlementLimitTypes.max, 10, "Up to 10 users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.monthly, 5000, "5,000 marketing sends per month"),
assignment(featureKeys.importedLists, entitlementLimitTypes.included, null, "Imported lists included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.included, null, "CRM based lists included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.included, null, "Onboarding builder included"),
assignment(featureKeys.api, entitlementLimitTypes.included, null, "API access included"),
assignment(featureKeys.workflowEngine, entitlementLimitTypes.notIncluded, null, "Workflow engine not included"),
assignment(featureKeys.mcp, entitlementLimitTypes.notIncluded, null, "Tenant MCP not included"),
assignment(featureKeys.advancedBuilder, entitlementLimitTypes.notIncluded, null, "Advanced builder not included"),
assignment(featureKeys.importExport, entitlementLimitTypes.monthly, 500, "500 import/export operations per month"),
assignment(featureKeys.rateLimitPerMinute, entitlementLimitTypes.max, 600, "600 requests per minute"),
assignment(featureKeys.rateLimitPerSecond, entitlementLimitTypes.max, 10, "10 requests per second"),
assignment(featureKeys.prioritySupport, entitlementLimitTypes.included, null, "Priority support included"),
assignment(featureKeys.credits, entitlementLimitTypes.monthly, 5000, "5,000 credits per month"),
assignment(featureKeys.privateGenerations, entitlementLimitTypes.included, null, "Private generation visibility"),
]
),
planStub(
entitlementPlanIds.business,
{
publicName: "Business",
description: "Advanced CRM SaaS plan with workflow automation, MCP, customization, and high limits.",
sortOrder: 30,
},
[
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.unlimited, null, "Unlimited support tickets"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.included, null, "Tenant knowledge base authoring included"),
assignment(featureKeys.users, entitlementLimitTypes.unlimited, null, "Unlimited users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.monthly, 50000, "50,000 marketing sends per month"),
assignment(featureKeys.importedLists, entitlementLimitTypes.included, null, "Imported lists included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.included, null, "CRM based lists included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.included, null, "Onboarding builder included"),
assignment(featureKeys.api, entitlementLimitTypes.included, null, "API access included"),
assignment(featureKeys.workflowEngine, entitlementLimitTypes.monthly, 10000, "10,000 workflow runs per month"),
assignment(featureKeys.mcp, entitlementLimitTypes.included, null, "Tenant MCP included when the blueprint enables it"),
assignment(featureKeys.advancedBuilder, entitlementLimitTypes.included, null, "Advanced builder included"),
assignment(featureKeys.importExport, entitlementLimitTypes.monthly, 10000, "10,000 import/export operations per month"),
assignment(featureKeys.rateLimitPerMinute, entitlementLimitTypes.max, 3000, "3,000 requests per minute"),
assignment(featureKeys.rateLimitPerSecond, entitlementLimitTypes.max, 50, "50 requests per second"),
assignment(featureKeys.prioritySupport, entitlementLimitTypes.included, null, "Priority support included"),
assignment(featureKeys.credits, entitlementLimitTypes.monthly, 50000, "50,000 credits per month"),
assignment(featureKeys.privateGenerations, entitlementLimitTypes.included, null, "Private generation visibility"),
]
),
] as const satisfies readonly EntitlementPlanStub[]);
const standardEntitlementPlanById = new Map<EntitlementPlanId, EntitlementPlanStub>(standardEntitlementPlans.map((plan) => [plan.id, plan]));
export function getStandardEntitlementPlan(planId: EntitlementPlanId): EntitlementPlanStub;
export function getStandardEntitlementPlan(planId: string): EntitlementPlanStub | undefined;
export function getStandardEntitlementPlan(planId: string): EntitlementPlanStub | undefined {
return standardEntitlementPlanById.get(planId as EntitlementPlanId);
}
export function listStandardEntitlementPlanIds(): readonly EntitlementPlanId[] {
return standardEntitlementPlans.map((plan) => plan.id);
}
@@ -0,0 +1,104 @@
import { evaluateEntitlement, type EntitlementDecision, type EntitlementLimitType } from "./evaluate.js";
import { type FeatureKey } from "./features.js";
import { getProductBlueprint, type ProductBlueprintId } from "./blueprints.js";
export type TenantFeatureOverride = "enabled" | "disabled" | "inherit";
export interface ProductAccessInput {
readonly blueprintId: ProductBlueprintId | string;
readonly featureKey: FeatureKey | string;
readonly hasSubscription: boolean;
readonly limitType?: EntitlementLimitType;
readonly limit?: number | null;
readonly used?: number | null;
readonly tenantOverride?: TenantFeatureOverride;
readonly tenantRolePermissionNames?: readonly string[];
readonly period?: string;
}
export type ProductAccessDecisionReason =
| EntitlementDecision["reason"]
| "blueprint-disabled"
| "tenant-override-disabled"
| "tenant-override-not-toggleable"
| "tenant-role-missing";
export interface ProductAccessDecision extends Omit<EntitlementDecision, "reason"> {
readonly reason: ProductAccessDecisionReason;
readonly blueprintId: string;
readonly tenantOverride: TenantFeatureOverride;
readonly requiredTenantRolePermission?: string;
}
export function evaluateProductAccess(input: ProductAccessInput): ProductAccessDecision {
const blueprint = getProductBlueprint(input.blueprintId);
const blueprintFeature = blueprint?.features.find((feature) => feature.featureKey === input.featureKey);
const tenantOverride = input.tenantOverride ?? "inherit";
const base = {
blueprintId: input.blueprintId,
featureKey: input.featureKey,
tenantOverride,
};
if (!blueprint || !blueprintFeature?.defaultEnabled) {
return {
...base,
allowed: false,
reason: "blueprint-disabled",
period: input.period,
};
}
if (tenantOverride === "disabled") {
return {
...base,
allowed: false,
reason: "tenant-override-disabled",
period: input.period,
};
}
if (tenantOverride === "enabled" && !blueprintFeature.tenantToggleable) {
return {
...base,
allowed: false,
reason: "tenant-override-not-toggleable",
period: input.period,
};
}
const entitlement = evaluateEntitlement({
featureKey: input.featureKey,
hasSubscription: input.hasSubscription,
limitType: input.limitType,
limit: input.limit,
used: input.used,
period: input.period,
});
if (!entitlement.allowed && tenantOverride !== "enabled") {
return { ...entitlement, blueprintId: input.blueprintId, tenantOverride };
}
const requiredPermission = blueprintFeature.requiresTenantRolePermission;
const hasRolePermission = !requiredPermission || input.tenantRolePermissionNames?.includes(requiredPermission);
if (!hasRolePermission) {
return {
...entitlement,
blueprintId: input.blueprintId,
tenantOverride,
allowed: false,
reason: "tenant-role-missing",
requiredTenantRolePermission: requiredPermission,
};
}
return {
...entitlement,
blueprintId: input.blueprintId,
tenantOverride,
allowed: true,
reason: tenantOverride === "enabled" && !entitlement.allowed ? "included" : entitlement.reason,
requiredTenantRolePermission: requiredPermission,
};
}
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"allowJs": false,
"allowImportingTsExtensions": false,
"lib": ["ES2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noEmit": true,
"types": ["node", "vitest/globals"]
},
"include": ["src/**/*.ts"]
}