@marktiderman/genesis-features 0.9.1 → 0.10.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.
Files changed (43) hide show
  1. package/README.md +14 -279
  2. package/dist/blocks.d.ts +4 -470
  3. package/dist/blocks.js +7 -5
  4. package/dist/gate-react.d.ts +4 -45
  5. package/dist/gate-react.js +7 -36
  6. package/dist/gate.d.ts +4 -15
  7. package/dist/gate.js +7 -5
  8. package/dist/index.d.ts +4 -124
  9. package/dist/index.js +7 -8
  10. package/dist/node.d.ts +4 -156
  11. package/dist/node.js +7 -486
  12. package/dist/react.d.ts +4 -57
  13. package/dist/react.js +7 -235
  14. package/dist/settings-protocol.d.ts +7 -0
  15. package/dist/settings-protocol.js +7 -0
  16. package/dist/settings-react.d.ts +7 -0
  17. package/dist/settings-react.js +8 -0
  18. package/dist/settings.d.ts +7 -0
  19. package/dist/settings.js +7 -0
  20. package/package.json +35 -51
  21. package/dist/blocks.js.map +0 -1
  22. package/dist/chunk-B6WRD3WF.js +0 -6
  23. package/dist/chunk-B6WRD3WF.js.map +0 -1
  24. package/dist/chunk-OW46SL2G.js +0 -10
  25. package/dist/chunk-OW46SL2G.js.map +0 -1
  26. package/dist/chunk-SEFG2QV6.js +0 -413
  27. package/dist/chunk-SEFG2QV6.js.map +0 -1
  28. package/dist/chunk-VYUX7VAX.js +0 -52
  29. package/dist/chunk-VYUX7VAX.js.map +0 -1
  30. package/dist/chunk-YTPGUU5F.js +0 -121
  31. package/dist/chunk-YTPGUU5F.js.map +0 -1
  32. package/dist/chunk-Z3TTDIVM.js +0 -494
  33. package/dist/chunk-Z3TTDIVM.js.map +0 -1
  34. package/dist/gate-oYFzQKyb.d.ts +0 -199
  35. package/dist/gate-react.js.map +0 -1
  36. package/dist/gate.js.map +0 -1
  37. package/dist/index.js.map +0 -1
  38. package/dist/model-sTRmrxz3.d.ts +0 -437
  39. package/dist/node.js.map +0 -1
  40. package/dist/packages-CWhdXtzS.d.ts +0 -203
  41. package/dist/platforms-NR0liM8L.d.ts +0 -10
  42. package/dist/react.js.map +0 -1
  43. package/dist/types-Bd766VxF.d.ts +0 -39
@@ -1,121 +0,0 @@
1
- import { statusOn } from './chunk-OW46SL2G.js';
2
-
3
- // src/gate.ts
4
- var SHIPPED_STATUSES = [
5
- "beta",
6
- "live",
7
- "deprecated"
8
- ];
9
- var GATING_KINDS = ["release", "permission"];
10
- function toTest(set, name) {
11
- if (set === void 0) return () => false;
12
- if (typeof set === "function") return set;
13
- if (typeof set === "string")
14
- throw new TypeError(
15
- `GateContext.${name} must be a list, a Set or a function, not a string`
16
- );
17
- if (Array.isArray(set)) {
18
- const ids = new Set(set);
19
- return (id) => ids.has(id);
20
- }
21
- if (set instanceof Set) return (id) => set.has(id);
22
- throw new TypeError(
23
- `GateContext.${name} must be a list, a Set or a function`
24
- );
25
- }
26
- function flagValue(flags, name) {
27
- if (!flags) return void 0;
28
- if (typeof flags === "function") return flags(name);
29
- return Object.hasOwn(flags, name) ? flags[name] : void 0;
30
- }
31
- function prepare(registry, context) {
32
- return {
33
- registry,
34
- context,
35
- entitled: toTest(context.entitlements, "entitlements"),
36
- off: toTest(context.off, "off")
37
- };
38
- }
39
- function answer(prepared, id, seen = /* @__PURE__ */ new Set()) {
40
- const { registry, context, entitled, off } = prepared;
41
- const def = Object.hasOwn(registry.features, id) ? registry.features[id] : void 0;
42
- if (!def) return { on: false, reason: "unknown" };
43
- if (!SHIPPED_STATUSES.includes(def.status))
44
- return { on: false, reason: "status" };
45
- const here = statusOn(def, context.platform);
46
- if (!here || !SHIPPED_STATUSES.includes(here))
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
- }
53
- if (off(id)) return { on: false, reason: "tenant" };
54
- for (const [name, flag] of Object.entries(registry.flags ?? {})) {
55
- if (flag.feature !== id || !GATING_KINDS.includes(flag.kind) || typeof flag.default !== "boolean")
56
- continue;
57
- if ((flagValue(context.flags, name) ?? flag.default) !== true)
58
- return { on: false, reason: "flag", flag: name };
59
- }
60
- const access = def.access ?? "all";
61
- if (access !== "all" && !entitled(id))
62
- return { on: false, reason: "entitlement", unlock: { plan: access.plan } };
63
- return { on: true };
64
- }
65
- function featureOn(registry, context, id) {
66
- return answer(prepare(registry, context), id);
67
- }
68
- function gateSnapshot(registry, context, options = {}) {
69
- const prepared = prepare(registry, context);
70
- const ids = options.ids === void 0 ? Object.keys(registry.features).filter(
71
- (id) => SHIPPED_STATUSES.includes(registry.features[id].status)
72
- ) : Array.from(options.ids);
73
- const answers = {};
74
- for (const id of ids) {
75
- const { flag: _flag, ...rest } = answer(prepared, id);
76
- answers[id] = rest;
77
- }
78
- return {
79
- answers,
80
- at: (options.at ?? /* @__PURE__ */ new Date()).toISOString(),
81
- ...options.version === void 0 ? {} : { version: options.version }
82
- };
83
- }
84
- function isSnapshotStale(snapshot, maxAgeMs, now = /* @__PURE__ */ new Date()) {
85
- const at = Date.parse(snapshot?.at);
86
- return Number.isNaN(at) || Math.abs(now.getTime() - at) > maxAgeMs;
87
- }
88
- function fromSnapshot(snapshot, id) {
89
- const answers = snapshot?.answers;
90
- return (answers && Object.hasOwn(answers, id) ? answers[id] : void 0) ?? { on: false, reason: "unknown" };
91
- }
92
- var FeatureOff = class extends Error {
93
- feature;
94
- reason;
95
- unlock;
96
- /** The required feature that turned it off, when one did. */
97
- via;
98
- constructor(feature, answer2) {
99
- const through = answer2.via ? ` (through ${answer2.via})` : "";
100
- super(
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}` : ""})`
102
- );
103
- this.name = "FeatureOff";
104
- this.feature = feature;
105
- this.reason = answer2.reason ?? "unknown";
106
- if (answer2.unlock) this.unlock = answer2.unlock;
107
- if (answer2.via) this.via = answer2.via;
108
- }
109
- /** The HTTP status for this refusal: 402 when a plan unlocks it, else 403. */
110
- get status() {
111
- return this.reason === "entitlement" ? 402 : 403;
112
- }
113
- };
114
- function requireFeature(registry, context, id) {
115
- const result = featureOn(registry, context, id);
116
- if (!result.on) throw new FeatureOff(id, result);
117
- }
118
-
119
- export { FeatureOff, SHIPPED_STATUSES, featureOn, fromSnapshot, gateSnapshot, isSnapshotStale, requireFeature };
120
- //# sourceMappingURL=chunk-YTPGUU5F.js.map
121
- //# sourceMappingURL=chunk-YTPGUU5F.js.map
@@ -1 +0,0 @@
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,MAAM,IAAI,SAAA;AAAA,MACR,eAAe,IAAI,CAAA,kDAAA;AAAA,KACrB;AACF,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,GAAG,CAAA,EAAG;AACtB,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAY,GAAG,CAAA;AAC/B,IAAA,OAAO,CAAC,EAAA,KAAO,GAAA,CAAI,GAAA,CAAI,EAAE,CAAA;AAAA,EAC3B;AACA,EAAA,IAAI,eAAe,GAAA,EAAK,OAAO,CAAC,EAAA,KAAO,GAAA,CAAI,IAAI,EAAE,CAAA;AACjD,EAAA,MAAM,IAAI,SAAA;AAAA,IACR,eAAe,I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AAA,CAAO,GAAG,CAAA,CAAA,GAAK,EAAE,CAAA,CAAA;AAAA,KAC/F;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AACZ,IAAA,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;AACxC,IAAA,IAAIA,OAAAA,CAAO,GAAA,EAAK,IAAA,CAAK,GAAA,GAAMA,OAAAA,CAAO,GAAA;AAAA,EACpC;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-YTPGUU5F.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 * 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 with an active entitlement: the tenant's, and the viewer's own (a person grant). */\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"]}
@@ -1,494 +0,0 @@
1
- import { requirementProblem, cycleProblems, dependencyOrder } from './chunk-VYUX7VAX.js';
2
- import { FEATURE_PLATFORMS } from './chunk-B6WRD3WF.js';
3
-
4
- // src/blocks.ts
5
- var BlockError = class extends Error {
6
- constructor(problems) {
7
- super(`Invalid blocks:
8
- ${problems.map((p) => ` - ${p}`).join("\n")}`);
9
- this.problems = problems;
10
- this.name = "BlockError";
11
- }
12
- problems;
13
- };
14
- var ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
15
- var CONTRIBUTION_KEYS = ["nav", "settings", "routes", "slots", "migrations", "skills", "privacy", "contentSection"];
16
- function duplicates(values) {
17
- const seen = /* @__PURE__ */ new Set();
18
- const dup = /* @__PURE__ */ new Set();
19
- for (const v of values) (seen.has(v) ? dup : seen).add(v);
20
- return [...dup];
21
- }
22
- function blockProblems(block) {
23
- const { id } = block;
24
- const problems = [];
25
- if (typeof id !== "string" || !ID.test(id)) problems.push(`${String(id)}: a block id is a feature id: lowercase letters and digits, joined by -, _ or .`);
26
- for (const req of block.requires ?? []) {
27
- if (req === id) problems.push(`${id}.requires: a block can't require itself`);
28
- else if (!ID.test(req)) problems.push(`${id}.requires: "${req}" is not a feature id`);
29
- }
30
- for (const p of block.platforms ?? []) {
31
- if (!FEATURE_PLATFORMS.includes(p)) problems.push(`${id}.platforms: "${p}" is not one of ${FEATURE_PLATFORMS.join(", ")}`);
32
- }
33
- if (block.platforms && block.platforms.length === 0) problems.push(`${id}.platforms: an empty list runs nowhere; leave it out for every platform`);
34
- const c = block.contributes ?? {};
35
- for (const key of Object.keys(c)) {
36
- if (!CONTRIBUTION_KEYS.includes(key)) problems.push(`${id}.contributes.${key}: not a contribution (${CONTRIBUTION_KEYS.join(", ")})`);
37
- }
38
- for (const d of duplicates((c.nav ?? []).map((n) => n.id))) problems.push(`${id}.contributes.nav: "${d}" appears twice`);
39
- for (const d of duplicates((c.settings ?? []).map((r) => r.id))) problems.push(`${id}.contributes.settings: "${d}" appears twice`);
40
- for (const d of duplicates((c.routes ?? []).map((r) => r.path))) problems.push(`${id}.contributes.routes: "${d}" appears twice`);
41
- for (const n of c.nav ?? []) if (!n.id || !n.label || !n.path) problems.push(`${id}.contributes.nav: every entry needs an id, a label and a path`);
42
- for (const n of c.nav ?? []) if (n.zone !== void 0 && (typeof n.zone !== "string" || !n.zone.trim())) problems.push(`${id}.contributes.nav: "${n.id}" zone must be a non-empty string`);
43
- for (const r of c.settings ?? []) if (!r.id || !r.section || !r.title) problems.push(`${id}.contributes.settings: every row needs an id, a section and a title`);
44
- for (const m of c.migrations ?? []) if (!m.package || !m.file) problems.push(`${id}.contributes.migrations: every migration needs a package and a file`);
45
- return problems;
46
- }
47
- function defineBlock(block) {
48
- const problems = blockProblems(block);
49
- if (problems.length) throw new BlockError(problems);
50
- return Object.freeze(block);
51
- }
52
- function enabledPredicate(enabled) {
53
- if (enabled === void 0) return void 0;
54
- if (typeof enabled === "function") return enabled;
55
- const set = new Set(enabled);
56
- return (id) => set.has(id);
57
- }
58
- var byOrder = (items) => items.sort((a, b) => (a.item.order ?? 0) - (b.item.order ?? 0) || a.at - b.at).map((x) => x.item);
59
- function resolveBlocks(blocks, enabled, options = {}) {
60
- const { platform, features, missing = "throw", slots: slotNames } = options;
61
- const problems = [];
62
- const byId = /* @__PURE__ */ new Map();
63
- for (const block of blocks) {
64
- problems.push(...blockProblems(block));
65
- if (byId.has(block.id)) problems.push(`${block.id}: two blocks have this id`);
66
- else byId.set(block.id, block);
67
- }
68
- const isFeature = features ? (id) => Object.hasOwn(features, id) : void 0;
69
- if (isFeature) {
70
- for (const id of byId.keys()) if (!isFeature(id)) problems.push(`${id}: not a feature in the registry`);
71
- }
72
- const graph = Object.fromEntries([...byId].map(([id, b]) => [id, { requires: b.requires }]));
73
- const known = { noun: "block", isKnown: (req) => byId.has(req) || !isFeature || isFeature(req) };
74
- for (const [id, node] of Object.entries(graph)) {
75
- for (const req of node.requires ?? []) {
76
- if (req !== id && requirementProblem(graph, id, req, known)) problems.push(`${id}.requires: "${req}" is neither a block nor a feature in the registry`);
77
- }
78
- }
79
- problems.push(...cycleProblems(graph));
80
- if (problems.length) throw new BlockError(problems);
81
- const isOn = enabledPredicate(enabled);
82
- const runsHere = (b) => !platform || !b.platforms || b.platforms.includes(platform);
83
- const active = /* @__PURE__ */ new Set();
84
- for (const [id, b] of byId) if ((!isOn || isOn(id)) && runsHere(b)) active.add(id);
85
- const order = dependencyOrder(graph);
86
- const dropped = [];
87
- for (const id of order) {
88
- if (!active.has(id)) continue;
89
- const off = (byId.get(id).requires ?? []).filter((req) => {
90
- if (byId.has(req)) return !active.has(req);
91
- return !isOn || !isOn(req);
92
- });
93
- if (!off.length) continue;
94
- if (missing === "drop") {
95
- active.delete(id);
96
- dropped.push({ id, missing: off });
97
- continue;
98
- }
99
- for (const req of off) {
100
- const why = !byId.has(req) ? isOn ? "is not enabled" : "is not one of the blocks given (pass it, or list the app feature in enabled)" : !runsHere(byId.get(req)) ? `doesn't run on ${platform}` : "is off";
101
- problems.push(`${id}.requires: "${req}" ${why}; turn it on or turn ${id} off`);
102
- }
103
- }
104
- if (problems.length) throw new BlockError(problems);
105
- const on = order.filter((id) => active.has(id)).map((id) => byId.get(id));
106
- const nav = [];
107
- const settings = [];
108
- const routes = [];
109
- const migrations = [];
110
- const skills = [];
111
- const privacy = [];
112
- const slots = {};
113
- const owner = { nav: /* @__PURE__ */ new Map(), settings: /* @__PURE__ */ new Map(), routes: /* @__PURE__ */ new Map(), slots: /* @__PURE__ */ new Map() };
114
- const claim = (kind, key, id, what) => {
115
- const first = owner[kind].get(key);
116
- if (first !== void 0) problems.push(`${id}.contributes.${kind}: ${what} "${key}" is already contributed by ${first}`);
117
- else owner[kind].set(key, id);
118
- return first === void 0;
119
- };
120
- on.forEach((block, at) => {
121
- const feature = block.id;
122
- const c = block.contributes ?? {};
123
- for (const n of c.nav ?? []) if (claim("nav", n.id, feature, "the nav entry")) nav.push({ item: { ...n, feature }, at });
124
- for (const r of c.settings ?? []) if (claim("settings", r.id, feature, "the settings row")) settings.push({ item: { ...r, feature }, at });
125
- for (const r of c.routes ?? []) if (claim("routes", r.path, feature, "the route")) routes.push({ ...r, feature });
126
- for (const [name, fill] of Object.entries(c.slots ?? {})) {
127
- if (slotNames && !slotNames.includes(name)) {
128
- problems.push(`${feature}.contributes.slots: "${name}" is not a slot here (${slotNames.join(", ")})`);
129
- continue;
130
- }
131
- if (claim("slots", name, feature, "the slot")) slots[name] = fill;
132
- }
133
- for (const m of c.migrations ?? []) migrations.push({ ...m, feature });
134
- for (const path of c.skills ?? []) skills.push({ path, feature });
135
- if (c.privacy) privacy.push({ ...c.privacy, feature });
136
- });
137
- if (problems.length) throw new BlockError(problems);
138
- const ids = new Set(on.map((b) => b.id));
139
- return Object.freeze({
140
- blocks: Object.freeze(on),
141
- ids,
142
- has: (id) => ids.has(id),
143
- contributionsOf: (id) => ids.has(id) ? byId.get(id).contributes ?? {} : void 0,
144
- nav: Object.freeze(byOrder(nav)),
145
- settings: Object.freeze(byOrder(settings)),
146
- routes: Object.freeze(routes),
147
- slots: Object.freeze(slots),
148
- migrations: Object.freeze(migrations),
149
- skills: Object.freeze(skills),
150
- privacy: Object.freeze(privacy),
151
- dropped: Object.freeze(dropped)
152
- });
153
- }
154
-
155
- // src/content-packs-legacy.ts
156
- var CONTENT_PACK_FIELD_TARGETS = {
157
- pursuits: "pursuits",
158
- work_items: "pursuits",
159
- metrics: "metrics",
160
- sessions: "sessions"
161
- };
162
- var SECTION_BLOCK = { sessionTypes: "sessions", metricTemplates: "metrics", forms: "forms", roadmapTemplates: "roadmap" };
163
- function legacyContentPackBlocks(pack) {
164
- const needed = [];
165
- for (const [section, block] of Object.entries(SECTION_BLOCK)) {
166
- const items = pack[section];
167
- if (items && items.length) needed.push(block);
168
- }
169
- for (const f of pack.fieldDefinitions ?? []) {
170
- const block = CONTENT_PACK_FIELD_TARGETS[f.target];
171
- if (block) needed.push(block);
172
- }
173
- return needed;
174
- }
175
- function legacyContentPackProblems(pack, at, keyProblems2) {
176
- const problems = [
177
- ...keyProblems2(`${at}.sessionTypes`, pack.sessionTypes),
178
- ...keyProblems2(`${at}.metricTemplates`, pack.metricTemplates),
179
- ...keyProblems2(`${at}.fieldDefinitions`, pack.fieldDefinitions),
180
- ...keyProblems2(`${at}.forms`, pack.forms),
181
- ...keyProblems2(`${at}.roadmapTemplates`, pack.roadmapTemplates)
182
- ];
183
- for (const s of pack.sessionTypes ?? []) {
184
- problems.push(...keyProblems2(`${at}.sessionTypes.${s.key}.agenda`, s.agenda));
185
- for (const item of s.agenda ?? []) {
186
- if (!(typeof item.minutes === "number" && item.minutes > 0)) problems.push(`${at}.sessionTypes.${s.key}.agenda.${item.key}: minutes must be more than 0`);
187
- }
188
- }
189
- for (const f of pack.fieldDefinitions ?? []) {
190
- if (!Object.hasOwn(CONTENT_PACK_FIELD_TARGETS, f.target)) problems.push(`${at}.fieldDefinitions.${f.key}: target "${String(f.target)}" isn't one of ${Object.keys(CONTENT_PACK_FIELD_TARGETS).join(", ")}`);
191
- if (typeof f.field?.type !== "string") problems.push(`${at}.fieldDefinitions.${f.key}: field needs a genesis-forms type`);
192
- if (!["tenant", "app", "private"].includes(f.visibility)) problems.push(`${at}.fieldDefinitions.${f.key}: visibility must be tenant, app or private`);
193
- }
194
- for (const r of pack.roadmapTemplates ?? []) {
195
- problems.push(...keyProblems2(`${at}.roadmapTemplates.${r.key}.items`, r.items));
196
- const keys = new Set((r.items ?? []).map((i) => i.key));
197
- for (const item of r.items ?? []) {
198
- if (item.ref !== void 0 && (!keys.has(item.ref) || item.ref === item.key)) {
199
- problems.push(`${at}.roadmapTemplates.${r.key}.items.${item.key}: ref "${item.ref}" isn't another item in this template`);
200
- }
201
- }
202
- }
203
- return problems;
204
- }
205
-
206
- // src/content-packs.ts
207
- var ContentPackError = class extends Error {
208
- constructor(problems) {
209
- super(`Invalid content pack:
210
- ${problems.map((p) => ` - ${p}`).join("\n")}`);
211
- this.problems = problems;
212
- this.name = "ContentPackError";
213
- }
214
- problems;
215
- };
216
- var KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
217
- var KEY = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
218
- var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
219
- function keyProblems(where, items) {
220
- const problems = [];
221
- const seen = /* @__PURE__ */ new Set();
222
- for (const [i, item] of (items ?? []).entries()) {
223
- const key = item?.key;
224
- if (typeof key !== "string" || !KEY.test(key)) problems.push(`${where}[${i}].key: "${String(key)}" is not a key (lowercase, dots, dashes or underscores)`);
225
- else if (seen.has(key)) problems.push(`${where}: the key "${key}" is used twice`);
226
- else seen.add(key);
227
- }
228
- return problems;
229
- }
230
- function contentPackBlocks(pack) {
231
- const needed = new Set(legacyContentPackBlocks(pack));
232
- const sections = pack.sections;
233
- const entries = sections && typeof sections === "object" && !Array.isArray(sections) ? Object.entries(sections) : [];
234
- for (const [block, items] of entries) {
235
- if (Array.isArray(items) && items.length) needed.add(block);
236
- }
237
- return [...needed].sort();
238
- }
239
- function test(blocks) {
240
- if (typeof blocks === "function") return blocks;
241
- const set = new Set(blocks);
242
- return (id) => set.has(id);
243
- }
244
- function checkOptions(value) {
245
- if (value === void 0) return {};
246
- if (typeof value === "function") return { installed: value };
247
- if (typeof value === "object" && value !== null) {
248
- if (Symbol.iterator in value) return { installed: value };
249
- return value;
250
- }
251
- throw new TypeError(`contentPackProblems: the second argument is the installed block ids (a list or a predicate) or options, not ${value === null ? "null" : typeof value}`);
252
- }
253
- function contentPackProblems(pack, installedOrOptions) {
254
- const options = checkOptions(installedOrOptions);
255
- const at = `content pack ${typeof pack?.id === "string" ? pack.id : "?"}`;
256
- const problems = [];
257
- if (typeof pack?.id !== "string" || !KEBAB.test(pack.id)) problems.push(`${at}: id must be kebab-case`);
258
- if (typeof pack?.name !== "string" || !pack.name.trim()) problems.push(`${at}: needs a name`);
259
- if (typeof pack?.version !== "string" || !SEMVER.test(pack.version)) problems.push(`${at}: version "${String(pack?.version)}" isn't semver`);
260
- if (typeof pack?.publisher !== "string" || !pack.publisher.trim()) problems.push(`${at}: needs a publisher (its package name)`);
261
- if (!Array.isArray(pack?.requires)) {
262
- problems.push(`${at}: requires must list the blocks it fills`);
263
- return problems;
264
- }
265
- for (const [label, text] of Object.entries(pack.labels ?? {})) {
266
- if (!KEY.test(label)) problems.push(`${at}: label key "${label}" is not a key`);
267
- if (typeof text !== "string" || !text.trim()) problems.push(`${at}: label "${label}" needs display text`);
268
- }
269
- const validators = /* @__PURE__ */ Object.create(null);
270
- for (const block of options.blocks ?? []) {
271
- const validate = block.contributes?.contentSection;
272
- if (typeof validate === "function") validators[block.id] = validate;
273
- }
274
- for (const [block, validate] of Object.entries(options.validators ?? {})) if (typeof validate === "function") validators[block] = validate;
275
- const sections = pack.sections;
276
- const sectionsOk = sections === void 0 || typeof sections === "object" && sections !== null && !Array.isArray(sections);
277
- if (!sectionsOk) problems.push(`${at}: sections must be an object keyed by block id`);
278
- for (const [block, items] of sectionsOk ? Object.entries(sections ?? {}) : []) {
279
- const where = `${at}.sections.${block}`;
280
- if (!KEY.test(block)) problems.push(`${where}: "${block}" is not a block id`);
281
- if (!Array.isArray(items)) {
282
- problems.push(`${where}: must be a list of items`);
283
- continue;
284
- }
285
- problems.push(...keyProblems(where, items));
286
- const validate = validators[block];
287
- if (!validate) continue;
288
- let found;
289
- try {
290
- found = validate(items);
291
- } catch (error) {
292
- problems.push(`${where}: the block's validator failed: ${error instanceof Error ? error.message : String(error)}`);
293
- continue;
294
- }
295
- for (const problem of Array.isArray(found) ? found : []) problems.push(`${where}: ${problem}`);
296
- }
297
- problems.push(...legacyContentPackProblems(pack, at, keyProblems));
298
- const declared = new Set(pack.requires);
299
- for (const block of contentPackBlocks(pack)) {
300
- if (!declared.has(block)) problems.push(`${at}: fills the ${block} block but doesn't list it in requires`);
301
- }
302
- if (options.installed !== void 0) {
303
- const has = test(options.installed);
304
- for (const block of pack.requires) if (!has(block)) problems.push(`${at}: needs the ${block} block, which isn't installed`);
305
- }
306
- return problems;
307
- }
308
- function defineContentPack(pack, options) {
309
- const problems = contentPackProblems(pack, { blocks: options?.blocks, validators: options?.validators });
310
- if (problems.length) throw new ContentPackError(problems);
311
- return pack;
312
- }
313
-
314
- // src/overlay.ts
315
- var OVERLAY_KEYS = /* @__PURE__ */ new Set(["upstream", "since", "owner", "reason", "$comment"]);
316
- var UPSTREAM = /^(@marktiderman\/genesis(?:-[a-z0-9-]+)?)@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/;
317
- var LOCAL_TAG = /(?:^|[.-])local(?:[.-]|$)/;
318
- var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
319
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
320
- var isText = (v) => typeof v === "string" && v.trim().length > 0;
321
- function isIsoDate(v) {
322
- if (typeof v !== "string") return false;
323
- const m = ISO_DATE.exec(v);
324
- if (!m) return false;
325
- const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
326
- return d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3]);
327
- }
328
- function readOverlayMarker(name, raw, problems = []) {
329
- const at = `${name} genesis.overlay`;
330
- if (!isObject(raw)) {
331
- problems.push(`${at}: must be an object { "upstream", "since", "owner", "reason" }`);
332
- return null;
333
- }
334
- const before = problems.length;
335
- for (const key of Object.keys(raw)) {
336
- if (!OVERLAY_KEYS.has(key)) problems.push(`${at}: unknown key "${key}" (known: upstream, since, owner, reason)`);
337
- }
338
- const m = typeof raw.upstream === "string" ? UPSTREAM.exec(raw.upstream) : null;
339
- if (!m) problems.push(`${at}.upstream: must be "@marktiderman/genesis-<name>@<version>", the package and release it was copied from, not ${JSON.stringify(raw.upstream)}`);
340
- else if (m[1] !== name) problems.push(`${at}.upstream: names ${m[1]}, but the package is ${name}; an overlay keeps the name it shadows`);
341
- else if (m[2].includes("-") && LOCAL_TAG.test(m[2].slice(m[2].indexOf("-") + 1))) problems.push(`${at}.upstream: ${m[2]} is a local build; name the release it was copied from`);
342
- if (!isIsoDate(raw.since)) problems.push(`${at}.since: must be the day it was made, as YYYY-MM-DD, not ${JSON.stringify(raw.since)}`);
343
- if (!isText(raw.owner)) problems.push(`${at}.owner: say who answers for the overlay`);
344
- if (!isText(raw.reason)) problems.push(`${at}.reason: say why the overlay exists`);
345
- return problems.length === before ? { upstream: raw.upstream, since: raw.since, owner: raw.owner, reason: raw.reason } : null;
346
- }
347
- function overlayUpstream(marker) {
348
- const at = marker.upstream.lastIndexOf("@");
349
- return { name: marker.upstream.slice(0, at), version: marker.upstream.slice(at + 1) };
350
- }
351
-
352
- // src/packages.ts
353
- var PACKAGE_LAYERS = ["foundation", "primitive", "module", "tooling"];
354
- var PACKAGE_GROUPS = ["core", "data", "ai", "forms", "collaboration", "shells", "modules"];
355
- var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
356
- var isText2 = (v) => typeof v === "string" && v.trim().length > 0;
357
- var isTextList = (v) => Array.isArray(v) && v.every(isText2);
358
- var PG_NAME = /^[a-z_][a-z0-9_]*$/;
359
- var MODULE_KEYS = /* @__PURE__ */ new Set(["name", "summary", "blocks", "requiresModules", "schema", "install", "docs", "skill"]);
360
- function readPackageMeta(name, genesis, problems = [], exportsKeys) {
361
- const at = `${name} genesis`;
362
- if (!isObject2(genesis)) {
363
- problems.push(`${at}: missing; every package declares "genesis": { "layer", "group" }`);
364
- return null;
365
- }
366
- const before = problems.length;
367
- const { layer, group, essential, module, toolingEntries, owner, overlay, optional } = genesis;
368
- if (overlay !== void 0) readOverlayMarker(name, overlay, problems);
369
- if (owner !== void 0 && (typeof owner !== "string" || !/^@[A-Za-z0-9-]+(\/[A-Za-z0-9._-]+)?$/.test(owner))) {
370
- problems.push(`${at}.owner: must be a GitHub handle or team, like "@octocat" or "@acme/web"`);
371
- }
372
- if (!PACKAGE_LAYERS.includes(layer)) problems.push(`${at}.layer: must be one of ${PACKAGE_LAYERS.join(", ")}, not ${JSON.stringify(layer)}`);
373
- if (!PACKAGE_GROUPS.includes(group)) problems.push(`${at}.group: must be one of ${PACKAGE_GROUPS.join(", ")}, not ${JSON.stringify(group)}`);
374
- if (essential !== void 0 && typeof essential !== "boolean") problems.push(`${at}.essential: must be true or false`);
375
- if (essential === true && layer !== "foundation" && layer !== "tooling") problems.push(`${at}.essential: only a foundation or tooling package is essential, not a ${String(layer)}`);
376
- if (optional !== void 0 && typeof optional !== "boolean") problems.push(`${at}.optional: must be true or false`);
377
- if (optional === true && (layer === "foundation" || layer === "tooling")) problems.push(`${at}.optional: a ${String(layer)} package can't be optional; only a primitive or module is an upgrade apps opt into`);
378
- if (optional === true && essential === true) problems.push(`${at}.optional: an essential package can't be optional`);
379
- if (layer === "module" !== (group === "modules")) problems.push(`${at}.group: a module is in the "modules" group, and only a module is`);
380
- if (layer === "module" && module === void 0) problems.push(`${at}.module: a module declares its card and install (name, summary, blocks, install, docs, skill)`);
381
- if (layer !== "module" && module !== void 0) problems.push(`${at}.module: only a package with layer "module" has one`);
382
- if (module !== void 0) moduleProblems(at, genesis, module, problems);
383
- if (toolingEntries !== void 0) {
384
- if (!isTextList(toolingEntries) || toolingEntries.some((e) => !e.startsWith("./"))) problems.push(`${at}.toolingEntries: must be a list of entry points like "./node"`);
385
- else if (exportsKeys) {
386
- for (const e of toolingEntries) if (!exportsKeys.includes(e)) problems.push(`${at}.toolingEntries: "${e}" is not in the package's exports`);
387
- }
388
- }
389
- return problems.length === before ? genesis : null;
390
- }
391
- function moduleProblems(at, genesis, module, problems) {
392
- const where = `${at}.module`;
393
- if (!isObject2(module)) {
394
- problems.push(`${where}: must be an object`);
395
- return;
396
- }
397
- for (const key of Object.keys(module)) if (!MODULE_KEYS.has(key)) problems.push(`${where}.${key}: unknown key (one of ${[...MODULE_KEYS].join(", ")})`);
398
- for (const key of ["name", "summary", "install", "docs", "skill"]) if (!isText2(module[key])) problems.push(`${where}.${key}: required text`);
399
- const declared = isObject2(genesis["blocks"]) ? Object.keys(genesis["blocks"]) : [];
400
- const blocks = module["blocks"];
401
- if (!isTextList(blocks) || blocks.length === 0) problems.push(`${where}.blocks: list at least one id from genesis.blocks`);
402
- else for (const id of blocks) if (!declared.includes(id)) problems.push(`${where}.blocks: "${id}" is not in genesis.blocks`);
403
- const requiresModules = module["requiresModules"];
404
- if (requiresModules !== void 0 && !isTextList(requiresModules)) problems.push(`${where}.requiresModules: must be a list of package names`);
405
- const schema = module["schema"];
406
- if (schema !== void 0 && !(typeof schema === "string" && PG_NAME.test(schema))) problems.push(`${where}.schema: must be a Postgres schema name`);
407
- const install = module["install"];
408
- if (isText2(install)) {
409
- const words = install.trim().split(/\s+/);
410
- if (words.length !== 3 || words[0] !== "genesis" || words[1] !== "add") problems.push(`${where}.install: must be "genesis add <block>", not ${JSON.stringify(install)}`);
411
- else if (isTextList(blocks) && !blocks.includes(words[2])) problems.push(`${where}.install: "${words[2]}" is not one of the module's blocks`);
412
- }
413
- const docs = module["docs"];
414
- if (isText2(docs) && !docs.startsWith("https://") && !isPackagePath(docs)) problems.push(`${where}.docs: a path in the package or an https URL, not ${JSON.stringify(docs)}`);
415
- const skill = module["skill"];
416
- if (isText2(skill) && !(isPackagePath(skill) && skill.endsWith("SKILL.md"))) problems.push(`${where}.skill: a SKILL.md path in the package, not ${JSON.stringify(skill)}`);
417
- }
418
- function isPackagePath(value) {
419
- if (/[\0\\:]/.test(value) || value.startsWith("/") || value.startsWith("~")) return false;
420
- return value.split("/").every((s) => s !== "" && s !== "." && s !== "..");
421
- }
422
- function packageOf(specifier) {
423
- const parts = specifier.split("/");
424
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
425
- }
426
- function packageLayerProblems(packages) {
427
- const problems = [];
428
- const metas = /* @__PURE__ */ new Map();
429
- for (const pkg of packages) {
430
- const meta = readPackageMeta(pkg.name, pkg.genesis, problems, pkg.exports);
431
- if (isObject2(pkg.genesis) && pkg.genesis["overlay"] !== void 0) problems.push(`${pkg.name} genesis.overlay: only an app's local copy of a Genesis package carries one, never the package itself`);
432
- if (meta) metas.set(pkg.name, meta);
433
- }
434
- for (const [name, meta] of metas) {
435
- for (const req of meta.module?.requiresModules ?? []) {
436
- if (req === name) problems.push(`${name} genesis.module.requiresModules: a module can't require itself`);
437
- else if (metas.get(req)?.layer !== "module") problems.push(`${name} genesis.module.requiresModules: "${req}" is not a module`);
438
- }
439
- }
440
- const graph = {};
441
- for (const pkg of packages) {
442
- const meta = metas.get(pkg.name);
443
- if (!meta) continue;
444
- const edges = /* @__PURE__ */ new Set();
445
- const optionalPeers = new Set(pkg.optionalPeers ?? []);
446
- const valueImported = new Set((pkg.valueImports ?? []).map(packageOf));
447
- for (const spec of new Set(pkg.uses)) {
448
- const target = packageOf(spec);
449
- if (target === pkg.name) continue;
450
- const to = metas.get(target);
451
- if (!to || meta.layer === "tooling") continue;
452
- const sub = spec.length > target.length ? `.${spec.slice(target.length)}` : ".";
453
- if (to.layer === "tooling") problems.push(`${pkg.name} (${meta.layer}) uses ${target}, which is tooling: no runtime package depends on tooling`);
454
- else if (to.toolingEntries?.includes(sub)) problems.push(`${pkg.name} (${meta.layer}) imports ${spec}, a tooling entry point of ${target}`);
455
- else if (!allowed(meta, to, target)) problems.push(`${pkg.name} (${meta.layer}) uses ${target} (${to.layer}): ${rule(meta)}`);
456
- else if (to.optional === true && (meta.layer === "foundation" || meta.layer === "primitive") && !optionalPeers.has(target)) {
457
- problems.push(`${pkg.name} (${meta.layer}) uses ${target}, which is optional: define a port in ${pkg.name} and let ${target} ship the adapter (or list it as an optional peer dependency)`);
458
- } else if (to.optional === true && (meta.layer === "foundation" || meta.layer === "primitive") && valueImported.has(target)) {
459
- problems.push(`${pkg.name} (${meta.layer}) imports ${target} statically, but it is an optional peer: import it for types only or with import(), so ${pkg.name} still loads without it`);
460
- } else if (!optionalPeers.has(target)) edges.add(target);
461
- }
462
- if (meta.layer !== "tooling") graph[pkg.name] = { requires: [...edges].sort() };
463
- }
464
- for (const cycle of cycleProblems(graph)) problems.push(`dependency cycle:${cycle.slice(cycle.indexOf(": a cycle:") + ": a cycle:".length)}`);
465
- return problems;
466
- }
467
- function allowed(from, to, target) {
468
- switch (from.layer) {
469
- case "foundation":
470
- return to.layer === "foundation";
471
- case "primitive":
472
- return to.layer === "foundation" || to.layer === "primitive";
473
- case "module":
474
- return to.layer !== "module" || (from.module?.requiresModules ?? []).includes(target);
475
- case "tooling":
476
- return true;
477
- }
478
- }
479
- function rule(from) {
480
- switch (from.layer) {
481
- case "foundation":
482
- return "a foundation package depends only on foundation packages";
483
- case "primitive":
484
- return "a primitive depends only on foundation packages and other primitives (never a module)";
485
- case "module":
486
- return "a module depends on another module only when genesis.module.requiresModules lists it";
487
- default:
488
- return "";
489
- }
490
- }
491
-
492
- export { BlockError, CONTENT_PACK_FIELD_TARGETS, ContentPackError, PACKAGE_GROUPS, PACKAGE_LAYERS, contentPackBlocks, contentPackProblems, defineBlock, defineContentPack, overlayUpstream, packageLayerProblems, readOverlayMarker, readPackageMeta, resolveBlocks };
493
- //# sourceMappingURL=chunk-Z3TTDIVM.js.map
494
- //# sourceMappingURL=chunk-Z3TTDIVM.js.map