@marktiderman/genesis-features 0.4.1 → 0.5.0

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.
package/README.md CHANGED
@@ -157,6 +157,10 @@ import { FeatureGate, FeatureGateProvider, useFeature } from "@marktiderman/gene
157
157
  </FeatureGateProvider>;
158
158
  ```
159
159
 
160
+ A feature that `requires` other features in the registry (a module's parts) is off while any of them is off,
161
+ with `via` naming the one that said no, so switching a module off or not paying for it turns its parts off
162
+ too. Ids outside the registry don't gate.
163
+
160
164
  The gate doesn't check roles: "may this person" stays with roles and row security. Why it works this
161
165
  way: [ADR 0001](../../docs/adr/0001-one-feature-gate.md).
162
166
 
@@ -36,7 +36,8 @@ function prepare(registry, context) {
36
36
  off: toTest(context.off, "off")
37
37
  };
38
38
  }
39
- function answer({ registry, context, entitled, off }, id) {
39
+ function answer(prepared, id, seen = /* @__PURE__ */ new Set()) {
40
+ const { registry, context, entitled, off } = prepared;
40
41
  const def = Object.hasOwn(registry.features, id) ? registry.features[id] : void 0;
41
42
  if (!def) return { on: false, reason: "unknown" };
42
43
  if (!SHIPPED_STATUSES.includes(def.status))
@@ -44,6 +45,11 @@ function answer({ registry, context, entitled, off }, id) {
44
45
  const here = statusOn(def, context.platform);
45
46
  if (!here || !SHIPPED_STATUSES.includes(here))
46
47
  return { on: false, reason: "platform" };
48
+ for (const need of def.requires ?? []) {
49
+ if (need === id || seen.has(need) || !Object.hasOwn(registry.features, need)) continue;
50
+ const parent = answer(prepared, need, /* @__PURE__ */ new Set([...seen, id]));
51
+ if (!parent.on) return { ...parent, via: parent.via ?? need };
52
+ }
47
53
  if (off(id)) return { on: false, reason: "tenant" };
48
54
  for (const [name, flag] of Object.entries(registry.flags ?? {})) {
49
55
  if (flag.feature !== id || !GATING_KINDS.includes(flag.kind) || typeof flag.default !== "boolean")
@@ -87,14 +93,18 @@ var FeatureOff = class extends Error {
87
93
  feature;
88
94
  reason;
89
95
  unlock;
96
+ /** The required feature that turned it off, when one did. */
97
+ via;
90
98
  constructor(feature, answer2) {
99
+ const through = answer2.via ? ` (through ${answer2.via})` : "";
91
100
  super(
92
- answer2.reason === "entitlement" && answer2.unlock ? `${feature} needs the ${answer2.unlock.plan} plan` : `${feature} is off (${answer2.reason ?? "unknown"})`
101
+ answer2.reason === "entitlement" && answer2.unlock ? `${feature} needs the ${answer2.unlock.plan} plan${through}` : `${feature} is off (${answer2.reason ?? "unknown"}${answer2.via ? ` via ${answer2.via}` : ""})`
93
102
  );
94
103
  this.name = "FeatureOff";
95
104
  this.feature = feature;
96
105
  this.reason = answer2.reason ?? "unknown";
97
106
  if (answer2.unlock) this.unlock = answer2.unlock;
107
+ if (answer2.via) this.via = answer2.via;
98
108
  }
99
109
  /** The HTTP status for this refusal: 402 when a plan unlocks it, else 403. */
100
110
  get status() {
@@ -107,5 +117,5 @@ function requireFeature(registry, context, id) {
107
117
  }
108
118
 
109
119
  export { FeatureOff, SHIPPED_STATUSES, featureOn, fromSnapshot, gateSnapshot, isSnapshotStale, requireFeature };
110
- //# sourceMappingURL=chunk-LNVWVPWB.js.map
111
- //# sourceMappingURL=chunk-LNVWVPWB.js.map
120
+ //# sourceMappingURL=chunk-U2RFA7VK.js.map
121
+ //# sourceMappingURL=chunk-U2RFA7VK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gate.ts"],"names":["answer"],"mappings":";;;AA0CO,IAAM,gBAAA,GAA6C;AAAA,EACxD,MAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF;AAkFA,IAAM,YAAA,GAAoC,CAAC,SAAA,EAAW,YAAY,CAAA;AAIlE,SAAS,MAAA,CAAO,KAAwB,IAAA,EAAoB;AAC1D,EAAA,IAAI,GAAA,KAAQ,MAAA,EAAW,OAAO,MAAM,KAAA;AACpC,EAAA,IAAI,OAAO,GAAA,KAAQ,UAAA,EAAY,OAAO,GAAA;AACtC,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA;AACjB,IAAA,M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* code, agents and (for status and entitlement) the database.\n *\n * Checks run in a fixed order and the first \"no\" wins:\n *\n * 1. status the feature has shipped (beta, live or deprecated)\n * 2. platform it has shipped on this platform\n * 3. tenant the tenant has not switched it off\n * 4. flag each of its boolean release or permission flags is true\n * 5. entitlement a paid feature (`access: { plan }`) has an active entitlement\n *\n * A feature that `requires` other features in the registry (a module's parts\n * require the module) is also off while any of them is off: after its own\n * status and platform, each required feature is asked the same way, and the\n * first \"no\" comes back with `via` naming it. So switching a module off, or not\n * paying for it, turns off every part with it, and the upsell names the module's\n * plan.\n *\n * Entitlement is last on purpose: an \"upgrade to unlock\" answer is only given\n * when paying is the one thing missing, so an upsell never promises a feature\n * that a switch or a flag would still keep off.\n *\n * The registry comes from code (features.ts and flags.json). Everything that\n * changes at runtime (entitlements, switches, flag values) comes in through\n * {@link GateContext}, read once per request or session on the server. Role\n * and row rights are not the gate's business: \"may this person\" stays with\n * roles and row security.\n *\n * No zod, React, Node built-ins or DOM globals here: this file ships to\n * browsers, extension service workers, phones and edge functions.\n */\nimport type {\n FeatureAccess,\n FeatureStatus,\n FlagKind,\n FlagValue,\n} from \"./types\";\nimport { statusOn } from \"./status\";\nimport type { FeaturePlatform } from \"./platforms\";\n\n/** The statuses in which a feature is on. A deprecated feature still works until it is retired. @stability Beta */\nexport const SHIPPED_STATUSES: readonly FeatureStatus[] = [\n \"beta\",\n \"live\",\n \"deprecated\",\n];\n\n/**\n * Why a feature is off: the first check that said no. `unknown` is an id that\n * isn't in the registry (or not in a snapshot).\n *\n * @stability Beta\n */\nexport type GateReason =\n \"unknown\" | \"status\" | \"platform\" | \"tenant\" | \"flag\" | \"entitlement\";\n\n/**\n * The gate's answer for one feature. `unlock` is set when the reason is\n * `entitlement`: the plan that turns it on, so the UI can show an upgrade\n * instead of hiding the feature.\n *\n * @stability Beta\n */\nexport interface GateAnswer {\n on: boolean;\n reason?: GateReason;\n unlock?: { plan: string };\n /** The flag that turned it off, when the reason is `flag`. Server side only: snapshots leave it out. */\n flag?: string;\n /** The required feature that turned it off (a module its part needs), when the \"no\" came from one. */\n via?: string;\n}\n\n/** The fields of a feature the gate reads. A `FeatureDef` fits. @stability Beta */\nexport interface GateFeature {\n status: FeatureStatus;\n apps: readonly string[];\n platforms?: Partial<Record<FeaturePlatform, FeatureStatus>>;\n access?: FeatureAccess;\n /** Ids this feature needs; those in the registry must be on too. */\n requires?: readonly string[];\n}\n\n/** The fields of a flag the gate reads. A `FlagDef` fits. @stability Beta */\nexport interface GateFlag {\n feature: string;\n kind: FlagKind;\n default: FlagValue;\n}\n\n/** What the gate decides from: the registry, as code defines it. @stability Beta */\nexport interface GateRegistry {\n features: { readonly [id: string]: GateFeature };\n flags?: { readonly [name: string]: GateFlag };\n}\n\n/**\n * A set of ids: a list, a Set or a test. Not any iterable: an iterator would\n * be used up by the first feature asked, and a bare string would count as its\n * characters.\n *\n * @stability Beta\n */\nexport type IdSet =\n readonly string[] | ReadonlySet<string> | ((id: string) => boolean);\n\n/**\n * Where and for whom the gate is asked: the platform, plus the tenant's\n * runtime state. Leave out what the app doesn't have: no `entitlements` means\n * no paid feature is on, no `off` means no switch is off, no `flags` means\n * every flag has its default.\n *\n * @stability Beta\n */\nexport interface GateContext {\n platform: FeaturePlatform;\n /** Feature ids the tenant holds an active entitlement for. */\n entitlements?: IdSet;\n /** Feature ids the tenant switched off. */\n off?: IdSet;\n /** Flag values for this tenant, by flag name. A missing flag has its default. */\n flags?:\n | { readonly [name: string]: FlagValue | undefined }\n | ((name: string) => FlagValue | undefined);\n}\n\n/** Flag kinds that can turn a feature off. Experiments and ops flags pick a variant; they don't gate. */\nconst GATING_KINDS: readonly FlagKind[] = [\"release\", \"permission\"];\n\ntype Test = (id: string) => boolean;\n\nfunction toTest(set: IdSet | undefined, name: string): Test {\n if (set === undefined) return () => false;\n if (typeof set === \"function\") return set;\n if (typeof set === \"string\")\n throw new TypeError(\n `GateContext.${name} must be a list, a Set or a function, not a string`,\n );\n if (Array.isArray(set)) {\n const ids = new Set<string>(set);\n return (id) => ids.has(id);\n }\n if (set instanceof Set) return (id) => set.has(id);\n throw new TypeError(\n `GateContext.${name} must be a list, a Set or a function`,\n );\n}\n\nfunction flagValue(\n flags: GateContext[\"flags\"],\n name: string,\n): FlagValue | undefined {\n if (!flags) return undefined;\n if (typeof flags === \"function\") return flags(name);\n return Object.hasOwn(flags, name) ? flags[name] : undefined;\n}\n\ninterface Prepared {\n registry: GateRegistry;\n context: GateContext;\n entitled: Test;\n off: Test;\n}\n\nfunction prepare(registry: GateRegistry, context: GateContext): Prepared {\n return {\n registry,\n context,\n entitled: toTest(context.entitlements, \"entitlements\"),\n off: toTest(context.off, \"off\"),\n };\n}\n\nfunction answer(prepared: Prepared, id: string, seen: ReadonlySet<string> = new Set()): GateAnswer {\n const { registry, context, entitled, off } = prepared;\n const def = Object.hasOwn(registry.features, id)\n ? registry.features[id]\n : undefined;\n if (!def) return { on: false, reason: \"unknown\" };\n if (!SHIPPED_STATUSES.includes(def.status))\n return { on: false, reason: \"status\" };\n const here = statusOn(def, context.platform);\n if (!here || !SHIPPED_STATUSES.includes(here))\n return { on: false, reason: \"platform\" };\n // What it requires must be on too: a module's parts go off with the module.\n // Ids outside the registry (blocks, infrastructure) don't gate; a cycle is cut.\n for (const need of def.requires ?? []) {\n if (need === id || seen.has(need) || !Object.hasOwn(registry.features, need)) continue;\n const parent = answer(prepared, need, new Set([...seen, id]));\n if (!parent.on) return { ...parent, via: parent.via ?? need };\n }\n if (off(id)) return { on: false, reason: \"tenant\" };\n for (const [name, flag] of Object.entries(registry.flags ?? {})) {\n if (\n flag.feature !== id ||\n !GATING_KINDS.includes(flag.kind) ||\n typeof flag.default !== \"boolean\"\n )\n continue;\n // On only when exactly true: a malformed value (\"false\", 0, null) keeps the feature off.\n if ((flagValue(context.flags, name) ?? flag.default) !== true)\n return { on: false, reason: \"flag\", flag: name };\n }\n const access = def.access ?? \"all\";\n if (access !== \"all\" && !entitled(id))\n return { on: false, reason: \"entitlement\", unlock: { plan: access.plan } };\n return { on: true };\n}\n\n/**\n * Is feature `id` on for this context? Returns the first check that said no\n * as `reason`, and for a paid feature the plan that unlocks it. An unknown id\n * is off with reason `unknown`; it never throws for one.\n *\n * ```ts\n * const answer = featureOn({ features, flags }, { platform: \"web\", entitlements, off }, \"form-webhook-delivery\");\n * // { on: false, reason: \"entitlement\", unlock: { plan: \"pro\" } }\n * ```\n *\n * @stability Beta\n */\nexport function featureOn(\n registry: GateRegistry,\n context: GateContext,\n id: string,\n): GateAnswer {\n return answer(prepare(registry, context), id);\n}\n\n/**\n * Every shipped feature's answer for one context: what a server hands a\n * client, so the client never decides on its own. Plain JSON, safe to store\n * (an extension's session storage, a cache) and to compare by `version`.\n *\n * It lists only features that have shipped somewhere (beta, live or\n * deprecated) and leaves out flag names; anything missing reads as off.\n *\n * @stability Beta\n */\nexport interface GateSnapshot {\n /** The answers, by feature id. */\n readonly answers: { readonly [id: string]: GateAnswer };\n /** When the server made it (ISO 8601). Refresh after your own time limit. */\n readonly at: string;\n /** The registry version it was made from, when known (the build's version). */\n readonly version?: string | number;\n}\n\n/** @stability Beta */\nexport interface GateSnapshotOptions {\n /** Answer for these features only. */\n ids?: Iterable<string>;\n /** The registry version, carried into the snapshot. */\n version?: string | number;\n /** The time to stamp (default now). */\n at?: Date;\n}\n\n/** @stability Beta */\nexport function gateSnapshot(\n registry: GateRegistry,\n context: GateContext,\n options: GateSnapshotOptions = {},\n): GateSnapshot {\n const prepared = prepare(registry, context);\n const ids =\n options.ids === undefined\n ? Object.keys(registry.features).filter((id) =>\n SHIPPED_STATUSES.includes(registry.features[id]!.status),\n )\n : Array.from(options.ids);\n const answers: Record<string, GateAnswer> = {};\n for (const id of ids) {\n const { flag: _flag, ...rest } = answer(prepared, id);\n answers[id] = rest;\n }\n return {\n answers,\n at: (options.at ?? new Date()).toISOString(),\n ...(options.version === undefined ? {} : { version: options.version }),\n };\n}\n\n/**\n * Whether a snapshot is older than `maxAgeMs`: refresh it then. A client\n * (an extension worker, a tab left open) keeps a snapshot, replaces it when it\n * is stale, after sign-in or a tenant switch, and right after a refusal.\n *\n * @stability Beta\n */\nexport function isSnapshotStale(snapshot: GateSnapshot, maxAgeMs: number, now: Date = new Date()): boolean {\n const at = Date.parse(snapshot?.at);\n // Too old, unreadable, or dated in the future (a wrong clock or a forged copy): refresh.\n return Number.isNaN(at) || Math.abs(now.getTime() - at) > maxAgeMs;\n}\n\n/** One feature's answer from a snapshot. An id missing from it is off, as an unknown feature. @stability Beta */\nexport function fromSnapshot(snapshot: GateSnapshot, id: string): GateAnswer {\n // A stored snapshot may be from an older shape, or damaged: missing answers mean off.\n const answers: GateSnapshot[\"answers\"] | undefined = snapshot?.answers;\n return (answers && Object.hasOwn(answers, id) ? answers[id] : undefined) ?? { on: false, reason: \"unknown\" };\n}\n\n/**\n * Thrown by {@link requireFeature} when a feature is off. Servers map it to a\n * refusal that carries the reason (HTTP 403, or 402 for `entitlement`).\n *\n * @stability Beta\n */\nexport class FeatureOff extends Error {\n readonly feature: string;\n readonly reason: GateReason;\n readonly unlock?: { plan: string };\n /** The required feature that turned it off, when one did. */\n readonly via?: string;\n constructor(feature: string, answer: GateAnswer) {\n const through = answer.via ? ` (through ${answer.via})` : \"\";\n super(\n answer.reason === \"entitlement\" && answer.unlock\n ? `${feature} needs the ${answer.unlock.plan} plan${through}`\n : `${feature} is off (${answer.reason ?? \"unknown\"}${answer.via ? ` via ${answer.via}` : \"\"})`,\n );\n this.name = \"FeatureOff\";\n this.feature = feature;\n this.reason = answer.reason ?? \"unknown\";\n if (answer.unlock) this.unlock = answer.unlock;\n if (answer.via) this.via = answer.via;\n }\n\n /** The HTTP status for this refusal: 402 when a plan unlocks it, else 403. */\n get status(): 402 | 403 {\n return this.reason === \"entitlement\" ? 402 : 403;\n }\n}\n\n/**\n * Refuse unless the feature is on: call it at the top of every server\n * function and route that belongs to a feature.\n *\n * ```ts\n * requireFeature({ features, flags }, await gateContext(tenant), \"form-webhook-delivery\");\n * ```\n *\n * @stability Beta\n */\nexport function requireFeature(\n registry: GateRegistry,\n context: GateContext,\n id: string,\n): void {\n const result = featureOn(registry, context, id);\n if (!result.on) throw new FeatureOff(id, result);\n}\n"]}
@@ -13,6 +13,13 @@ import { F as FeaturePlatform } from './platforms-NR0liM8L.js';
13
13
  * 4. flag each of its boolean release or permission flags is true
14
14
  * 5. entitlement a paid feature (`access: { plan }`) has an active entitlement
15
15
  *
16
+ * A feature that `requires` other features in the registry (a module's parts
17
+ * require the module) is also off while any of them is off: after its own
18
+ * status and platform, each required feature is asked the same way, and the
19
+ * first "no" comes back with `via` naming it. So switching a module off, or not
20
+ * paying for it, turns off every part with it, and the upsell names the module's
21
+ * plan.
22
+ *
16
23
  * Entitlement is last on purpose: an "upgrade to unlock" answer is only given
17
24
  * when paying is the one thing missing, so an upsell never promises a feature
18
25
  * that a switch or a flag would still keep off.
@@ -51,6 +58,8 @@ interface GateAnswer {
51
58
  };
52
59
  /** The flag that turned it off, when the reason is `flag`. Server side only: snapshots leave it out. */
53
60
  flag?: string;
61
+ /** The required feature that turned it off (a module its part needs), when the "no" came from one. */
62
+ via?: string;
54
63
  }
55
64
  /** The fields of a feature the gate reads. A `FeatureDef` fits. @stability Beta */
56
65
  interface GateFeature {
@@ -58,6 +67,8 @@ interface GateFeature {
58
67
  apps: readonly string[];
59
68
  platforms?: Partial<Record<FeaturePlatform, FeatureStatus>>;
60
69
  access?: FeatureAccess;
70
+ /** Ids this feature needs; those in the registry must be on too. */
71
+ requires?: readonly string[];
61
72
  }
62
73
  /** The fields of a flag the gate reads. A `FlagDef` fits. @stability Beta */
63
74
  interface GateFlag {
@@ -167,6 +178,8 @@ declare class FeatureOff extends Error {
167
178
  readonly unlock?: {
168
179
  plan: string;
169
180
  };
181
+ /** The required feature that turned it off, when one did. */
182
+ readonly via?: string;
170
183
  constructor(feature: string, answer: GateAnswer);
171
184
  /** The HTTP status for this refusal: 402 when a plan unlocks it, else 403. */
172
185
  get status(): 402 | 403;
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { G as GateAnswer, a as GateSnapshot } from './gate-BY352cd0.js';
3
+ import { G as GateAnswer, a as GateSnapshot } from './gate-4OB4ddHv.js';
4
4
  import './types-Bd766VxF.js';
5
5
  import './platforms-NR0liM8L.js';
6
6
 
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { fromSnapshot } from './chunk-LNVWVPWB.js';
2
+ import { fromSnapshot } from './chunk-U2RFA7VK.js';
3
3
  import './chunk-OW46SL2G.js';
4
4
  import { createContext, useContext } from 'react';
5
5
  import { jsx, Fragment } from 'react/jsx-runtime';
package/dist/gate.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { F as FeatureOff, G as GateAnswer, b as GateContext, c as GateFeature, d as GateFlag, e as GateReason, f as GateRegistry, a as GateSnapshot, g as GateSnapshotOptions, I as IdSet, S as SHIPPED_STATUSES, h as featureOn, i as fromSnapshot, j as gateSnapshot, k as isSnapshotStale, r as requireFeature } from './gate-BY352cd0.js';
1
+ export { F as FeatureOff, G as GateAnswer, b as GateContext, c as GateFeature, d as GateFlag, e as GateReason, f as GateRegistry, a as GateSnapshot, g as GateSnapshotOptions, I as IdSet, S as SHIPPED_STATUSES, h as featureOn, i as fromSnapshot, j as gateSnapshot, k as isSnapshotStale, r as requireFeature } from './gate-4OB4ddHv.js';
2
2
  import { a as FeatureStatus } from './types-Bd766VxF.js';
3
3
  import { F as FeaturePlatform } from './platforms-NR0liM8L.js';
4
4
  export { a as FEATURE_PLATFORMS } from './platforms-NR0liM8L.js';
package/dist/gate.js CHANGED
@@ -1,4 +1,4 @@
1
- export { FeatureOff, SHIPPED_STATUSES, featureOn, fromSnapshot, gateSnapshot, isSnapshotStale, requireFeature } from './chunk-LNVWVPWB.js';
1
+ export { FeatureOff, SHIPPED_STATUSES, featureOn, fromSnapshot, gateSnapshot, isSnapshotStale, requireFeature } from './chunk-U2RFA7VK.js';
2
2
  export { FEATURE_PLATFORMS } from './chunk-B6WRD3WF.js';
3
3
  export { statusOn } from './chunk-OW46SL2G.js';
4
4
  //# sourceMappingURL=gate.js.map
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { F as Features, b as FeatureRecord, a as Flags } from './model-8dMGbgtM.js';
2
2
  export { c as FEATURE_HORIZONS, d as FEATURE_LAYERS, e as FeatureDef, f as FeatureHorizon, g as FeatureIdOf, h as FeatureLayer, i as FeatureLinks, j as FeatureMedia, k as FeatureRegistryError, l as FeatureVisibility, m as FindOptions, n as FlagDef, o as defineFeatures, p as defineFlags, q as expiredFlags, r as featureSchema, s as findFeatures, t as flagSchema, u as flagsForFeature, v as toRecords } from './model-8dMGbgtM.js';
3
3
  export { BlockContributions, BlockDataUse, BlockDef, BlockError, BlockMigration, BlockNavItem, BlockPrivacy, BlockRoute, BlockSettingsRow, Contributed, EnabledBlocks, ResolveBlocksOptions, ResolvedBlocks, defineBlock, resolveBlocks } from './blocks.js';
4
- export { F as FeatureOff, G as GateAnswer, b as GateContext, c as GateFeature, d as GateFlag, e as GateReason, f as GateRegistry, a as GateSnapshot, g as GateSnapshotOptions, I as IdSet, S as SHIPPED_STATUSES, h as featureOn, i as fromSnapshot, j as gateSnapshot, k as isSnapshotStale, r as requireFeature } from './gate-BY352cd0.js';
4
+ export { F as FeatureOff, G as GateAnswer, b as GateContext, c as GateFeature, d as GateFlag, e as GateReason, f as GateRegistry, a as GateSnapshot, g as GateSnapshotOptions, I as IdSet, S as SHIPPED_STATUSES, h as featureOn, i as fromSnapshot, j as gateSnapshot, k as isSnapshotStale, r as requireFeature } from './gate-4OB4ddHv.js';
5
5
  export { a as FEATURE_PLATFORMS, F as FeaturePlatform } from './platforms-NR0liM8L.js';
6
6
  export { d as FEATURE_STATUSES, e as FLAG_KINDS, b as FeatureAccess, a as FeatureStatus, c as FlagKind, F as FlagValue } from './types-Bd766VxF.js';
7
7
  export { statusOn } from './gate.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { BlockError, defineBlock, resolveBlocks } from './chunk-4Q356635.js';
2
- export { FeatureOff, SHIPPED_STATUSES, featureOn, fromSnapshot, gateSnapshot, isSnapshotStale, requireFeature } from './chunk-LNVWVPWB.js';
2
+ export { FeatureOff, SHIPPED_STATUSES, featureOn, fromSnapshot, gateSnapshot, isSnapshotStale, requireFeature } from './chunk-U2RFA7VK.js';
3
3
  export { AGENTS_BLOCK_END, AGENTS_BLOCK_START, BrokenBlockError, FEATURE_HORIZONS, FEATURE_LAYERS, FEATURE_STATUSES, FLAG_KINDS, FeatureRegistryError, MARKETING_BLOCK_END, MARKETING_BLOCK_START, OPENFEATURE_MANIFEST_SCHEMA, defineFeatures, defineFlags, expiredFlags, featureSchema, findFeatures, flagSchema, flagsForFeature, marketingRecords, readAgentsBlock, replaceAgentsBlock, toAgentsMarkdown, toJson, toMarketingMarkdown, toOpenFeatureManifest, toRecords, toSkillMarkdown } from './chunk-JMXJZT6O.js';
4
4
  export { cycleProblems, dependencyOrder, requirementProblem, requiresProblems } from './chunk-VYUX7VAX.js';
5
5
  export { FEATURE_PLATFORMS } from './chunk-B6WRD3WF.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-features",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -69,9 +69,9 @@
69
69
  }
70
70
  },
71
71
  "devDependencies": {
72
- "@marktiderman/genesis-core": "^1.10.0",
72
+ "@marktiderman/genesis-core": "^1.11.0",
73
73
  "@marktiderman/genesis-design-system": "^1.5.0",
74
- "@marktiderman/genesis-ui": "^2.16.0",
74
+ "@marktiderman/genesis-ui": "^2.17.1",
75
75
  "@testing-library/react": "^16.3.2",
76
76
  "@types/node": "^22.9.0",
77
77
  "@types/react": "^19.2.14",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/gate.ts"],"names":["answer"],"mappings":";;;AAmCO,IAAM,gBAA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A,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,MAAA,GAASA,QAAO,MAAA,IAAU,SAAA;AAC/B,IAAA,IAAIA,OAAAA,CAAO,MAAA,EAAQ,IAAA,CAAK,MAAA,GAASA,OAAAA,CAAO,MAAA;AAAA,EAC1C;AAAA;AAAA,EAGA,IAAI,MAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,MAAA,KAAW,aAAA,GAAgB,GAAA,GAAM,GAAA;AAAA,EAC/C;AACF;AAYO,SAAS,cAAA,CACd,QAAA,EACA,OAAA,EACA,EAAA,EACM;AACN,EAAA,MAAM,MAAA,GAAS,SAAA,CAAU,QAAA,EAAU,OAAA,EAAS,EAAE,CAAA;AAC9C,EAAA,IAAI,CAAC,MAAA,CAAO,EAAA,QAAU,IAAI,UAAA,CAAW,IAAI,MAAM,CAAA;AACjD","file":"chunk-LNVWVPWB.js","sourcesContent":["/**\n * The feature gate: one answer to \"is this feature on here?\" for UI, server\n * code, agents and (for status and entitlement) the database.\n *\n * Checks run in a fixed order and the first \"no\" wins:\n *\n * 1. status the feature has shipped (beta, live or deprecated)\n * 2. platform it has shipped on this platform\n * 3. tenant the tenant has not switched it off\n * 4. flag each of its boolean release or permission flags is true\n * 5. entitlement a paid feature (`access: { plan }`) has an active entitlement\n *\n * Entitlement is last on purpose: an \"upgrade to unlock\" answer is only given\n * when paying is the one thing missing, so an upsell never promises a feature\n * that a switch or a flag would still keep off.\n *\n * The registry comes from code (features.ts and flags.json). Everything that\n * changes at runtime (entitlements, switches, flag values) comes in through\n * {@link GateContext}, read once per request or session on the server. Role\n * and row rights are not the gate's business: \"may this person\" stays with\n * roles and row security.\n *\n * No zod, React, Node built-ins or DOM globals here: this file ships to\n * browsers, extension service workers, phones and edge functions.\n */\nimport type {\n FeatureAccess,\n FeatureStatus,\n FlagKind,\n FlagValue,\n} from \"./types\";\nimport { statusOn } from \"./status\";\nimport type { FeaturePlatform } from \"./platforms\";\n\n/** The statuses in which a feature is on. A deprecated feature still works until it is retired. @stability Beta */\nexport const SHIPPED_STATUSES: readonly FeatureStatus[] = [\n \"beta\",\n \"live\",\n \"deprecated\",\n];\n\n/**\n * Why a feature is off: the first check that said no. `unknown` is an id that\n * isn't in the registry (or not in a snapshot).\n *\n * @stability Beta\n */\nexport type GateReason =\n \"unknown\" | \"status\" | \"platform\" | \"tenant\" | \"flag\" | \"entitlement\";\n\n/**\n * The gate's answer for one feature. `unlock` is set when the reason is\n * `entitlement`: the plan that turns it on, so the UI can show an upgrade\n * instead of hiding the feature.\n *\n * @stability Beta\n */\nexport interface GateAnswer {\n on: boolean;\n reason?: GateReason;\n unlock?: { plan: string };\n /** The flag that turned it off, when the reason is `flag`. Server side only: snapshots leave it out. */\n flag?: string;\n}\n\n/** The fields of a feature the gate reads. A `FeatureDef` fits. @stability Beta */\nexport interface GateFeature {\n status: FeatureStatus;\n apps: readonly string[];\n platforms?: Partial<Record<FeaturePlatform, FeatureStatus>>;\n access?: FeatureAccess;\n}\n\n/** The fields of a flag the gate reads. A `FlagDef` fits. @stability Beta */\nexport interface GateFlag {\n feature: string;\n kind: FlagKind;\n default: FlagValue;\n}\n\n/** What the gate decides from: the registry, as code defines it. @stability Beta */\nexport interface GateRegistry {\n features: { readonly [id: string]: GateFeature };\n flags?: { readonly [name: string]: GateFlag };\n}\n\n/**\n * A set of ids: a list, a Set or a test. Not any iterable: an iterator would\n * be used up by the first feature asked, and a bare string would count as its\n * characters.\n *\n * @stability Beta\n */\nexport type IdSet =\n readonly string[] | ReadonlySet<string> | ((id: string) => boolean);\n\n/**\n * Where and for whom the gate is asked: the platform, plus the tenant's\n * runtime state. Leave out what the app doesn't have: no `entitlements` means\n * no paid feature is on, no `off` means no switch is off, no `flags` means\n * every flag has its default.\n *\n * @stability Beta\n */\nexport interface GateContext {\n platform: FeaturePlatform;\n /** Feature ids the tenant holds an active entitlement for. */\n entitlements?: IdSet;\n /** Feature ids the tenant switched off. */\n off?: IdSet;\n /** Flag values for this tenant, by flag name. A missing flag has its default. */\n flags?:\n | { readonly [name: string]: FlagValue | undefined }\n | ((name: string) => FlagValue | undefined);\n}\n\n/** Flag kinds that can turn a feature off. Experiments and ops flags pick a variant; they don't gate. */\nconst GATING_KINDS: readonly FlagKind[] = [\"release\", \"permission\"];\n\ntype Test = (id: string) => boolean;\n\nfunction toTest(set: IdSet | undefined, name: string): Test {\n if (set === undefined) return () => false;\n if (typeof set === \"function\") return set;\n if (typeof set === \"string\")\n throw new TypeError(\n `GateContext.${name} must be a list, a Set or a function, not a string`,\n );\n if (Array.isArray(set)) {\n const ids = new Set<string>(set);\n return (id) => ids.has(id);\n }\n if (set instanceof Set) return (id) => set.has(id);\n throw new TypeError(\n `GateContext.${name} must be a list, a Set or a function`,\n );\n}\n\nfunction flagValue(\n flags: GateContext[\"flags\"],\n name: string,\n): FlagValue | undefined {\n if (!flags) return undefined;\n if (typeof flags === \"function\") return flags(name);\n return Object.hasOwn(flags, name) ? flags[name] : undefined;\n}\n\ninterface Prepared {\n registry: GateRegistry;\n context: GateContext;\n entitled: Test;\n off: Test;\n}\n\nfunction prepare(registry: GateRegistry, context: GateContext): Prepared {\n return {\n registry,\n context,\n entitled: toTest(context.entitlements, \"entitlements\"),\n off: toTest(context.off, \"off\"),\n };\n}\n\nfunction answer(\n { registry, context, entitled, off }: Prepared,\n id: string,\n): GateAnswer {\n const def = Object.hasOwn(registry.features, id)\n ? registry.features[id]\n : undefined;\n if (!def) return { on: false, reason: \"unknown\" };\n if (!SHIPPED_STATUSES.includes(def.status))\n return { on: false, reason: \"status\" };\n const here = statusOn(def, context.platform);\n if (!here || !SHIPPED_STATUSES.includes(here))\n return { on: false, reason: \"platform\" };\n if (off(id)) return { on: false, reason: \"tenant\" };\n for (const [name, flag] of Object.entries(registry.flags ?? {})) {\n if (\n flag.feature !== id ||\n !GATING_KINDS.includes(flag.kind) ||\n typeof flag.default !== \"boolean\"\n )\n continue;\n // On only when exactly true: a malformed value (\"false\", 0, null) keeps the feature off.\n if ((flagValue(context.flags, name) ?? flag.default) !== true)\n return { on: false, reason: \"flag\", flag: name };\n }\n const access = def.access ?? \"all\";\n if (access !== \"all\" && !entitled(id))\n return { on: false, reason: \"entitlement\", unlock: { plan: access.plan } };\n return { on: true };\n}\n\n/**\n * Is feature `id` on for this context? Returns the first check that said no\n * as `reason`, and for a paid feature the plan that unlocks it. An unknown id\n * is off with reason `unknown`; it never throws for one.\n *\n * ```ts\n * const answer = featureOn({ features, flags }, { platform: \"web\", entitlements, off }, \"form-webhook-delivery\");\n * // { on: false, reason: \"entitlement\", unlock: { plan: \"pro\" } }\n * ```\n *\n * @stability Beta\n */\nexport function featureOn(\n registry: GateRegistry,\n context: GateContext,\n id: string,\n): GateAnswer {\n return answer(prepare(registry, context), id);\n}\n\n/**\n * Every shipped feature's answer for one context: what a server hands a\n * client, so the client never decides on its own. Plain JSON, safe to store\n * (an extension's session storage, a cache) and to compare by `version`.\n *\n * It lists only features that have shipped somewhere (beta, live or\n * deprecated) and leaves out flag names; anything missing reads as off.\n *\n * @stability Beta\n */\nexport interface GateSnapshot {\n /** The answers, by feature id. */\n readonly answers: { readonly [id: string]: GateAnswer };\n /** When the server made it (ISO 8601). Refresh after your own time limit. */\n readonly at: string;\n /** The registry version it was made from, when known (the build's version). */\n readonly version?: string | number;\n}\n\n/** @stability Beta */\nexport interface GateSnapshotOptions {\n /** Answer for these features only. */\n ids?: Iterable<string>;\n /** The registry version, carried into the snapshot. */\n version?: string | number;\n /** The time to stamp (default now). */\n at?: Date;\n}\n\n/** @stability Beta */\nexport function gateSnapshot(\n registry: GateRegistry,\n context: GateContext,\n options: GateSnapshotOptions = {},\n): GateSnapshot {\n const prepared = prepare(registry, context);\n const ids =\n options.ids === undefined\n ? Object.keys(registry.features).filter((id) =>\n SHIPPED_STATUSES.includes(registry.features[id]!.status),\n )\n : Array.from(options.ids);\n const answers: Record<string, GateAnswer> = {};\n for (const id of ids) {\n const { flag: _flag, ...rest } = answer(prepared, id);\n answers[id] = rest;\n }\n return {\n answers,\n at: (options.at ?? new Date()).toISOString(),\n ...(options.version === undefined ? {} : { version: options.version }),\n };\n}\n\n/**\n * Whether a snapshot is older than `maxAgeMs`: refresh it then. A client\n * (an extension worker, a tab left open) keeps a snapshot, replaces it when it\n * is stale, after sign-in or a tenant switch, and right after a refusal.\n *\n * @stability Beta\n */\nexport function isSnapshotStale(snapshot: GateSnapshot, maxAgeMs: number, now: Date = new Date()): boolean {\n const at = Date.parse(snapshot?.at);\n // Too old, unreadable, or dated in the future (a wrong clock or a forged copy): refresh.\n return Number.isNaN(at) || Math.abs(now.getTime() - at) > maxAgeMs;\n}\n\n/** One feature's answer from a snapshot. An id missing from it is off, as an unknown feature. @stability Beta */\nexport function fromSnapshot(snapshot: GateSnapshot, id: string): GateAnswer {\n // A stored snapshot may be from an older shape, or damaged: missing answers mean off.\n const answers: GateSnapshot[\"answers\"] | undefined = snapshot?.answers;\n return (answers && Object.hasOwn(answers, id) ? answers[id] : undefined) ?? { on: false, reason: \"unknown\" };\n}\n\n/**\n * Thrown by {@link requireFeature} when a feature is off. Servers map it to a\n * refusal that carries the reason (HTTP 403, or 402 for `entitlement`).\n *\n * @stability Beta\n */\nexport class FeatureOff extends Error {\n readonly feature: string;\n readonly reason: GateReason;\n readonly unlock?: { plan: string };\n constructor(feature: string, answer: GateAnswer) {\n super(\n answer.reason === \"entitlement\" && answer.unlock\n ? `${feature} needs the ${answer.unlock.plan} plan`\n : `${feature} is off (${answer.reason ?? \"unknown\"})`,\n );\n this.name = \"FeatureOff\";\n this.feature = feature;\n this.reason = answer.reason ?? \"unknown\";\n if (answer.unlock) this.unlock = answer.unlock;\n }\n\n /** The HTTP status for this refusal: 402 when a plan unlocks it, else 403. */\n get status(): 402 | 403 {\n return this.reason === \"entitlement\" ? 402 : 403;\n }\n}\n\n/**\n * Refuse unless the feature is on: call it at the top of every server\n * function and route that belongs to a feature.\n *\n * ```ts\n * requireFeature({ features, flags }, await gateContext(tenant), \"form-webhook-delivery\");\n * ```\n *\n * @stability Beta\n */\nexport function requireFeature(\n registry: GateRegistry,\n context: GateContext,\n id: string,\n): void {\n const result = featureOn(registry, context, id);\n if (!result.on) throw new FeatureOff(id, result);\n}\n"]}