@quixotic_mnemonics/swastik 0.0.0-stage → 0.1.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 (66) hide show
  1. package/_template/README.md +34 -0
  2. package/_template/assets/.gitkeep +1 -0
  3. package/_template/commands/.gitkeep +1 -0
  4. package/_template/config/.gitkeep +1 -0
  5. package/_template/events/.gitkeep +1 -0
  6. package/_template/jobs/.gitkeep +1 -0
  7. package/_template/locales/.gitkeep +1 -0
  8. package/_template/manifest.ts +13 -0
  9. package/_template/migrations/.gitkeep +1 -0
  10. package/_template/repositories/.gitkeep +1 -0
  11. package/_template/services/.gitkeep +1 -0
  12. package/_template/tests/.gitkeep +1 -0
  13. package/_template/ui/.gitkeep +1 -0
  14. package/dist/capabilities.d.ts +110 -0
  15. package/dist/capabilities.js +107 -0
  16. package/dist/commands.d.ts +157 -0
  17. package/dist/commands.js +9 -0
  18. package/dist/components-v2.d.ts +252 -0
  19. package/dist/components-v2.js +263 -0
  20. package/dist/components.d.ts +142 -0
  21. package/dist/components.js +11 -0
  22. package/dist/context.d.ts +59 -0
  23. package/dist/context.js +29 -0
  24. package/dist/entrypoints/admin.d.ts +26 -0
  25. package/dist/entrypoints/admin.js +2 -0
  26. package/dist/entrypoints/core.d.ts +31 -0
  27. package/dist/entrypoints/core.js +2 -0
  28. package/dist/entrypoints/marketplace.d.ts +30 -0
  29. package/dist/entrypoints/marketplace.js +2 -0
  30. package/dist/entrypoints/standard.d.ts +36 -0
  31. package/dist/entrypoints/standard.js +2 -0
  32. package/dist/events.d.ts +15 -0
  33. package/dist/events.js +19 -0
  34. package/dist/index.d.ts +27 -0
  35. package/dist/index.js +21 -0
  36. package/dist/manifest-schema.d.ts +261 -0
  37. package/dist/manifest-schema.js +297 -0
  38. package/dist/manifest.d.ts +47 -0
  39. package/dist/manifest.js +6 -0
  40. package/dist/pages.d.ts +274 -0
  41. package/dist/pages.js +3 -0
  42. package/dist/paging.d.ts +32 -0
  43. package/dist/paging.js +59 -0
  44. package/dist/permits.d.ts +222 -0
  45. package/dist/permits.js +16 -0
  46. package/dist/validate.d.ts +21 -0
  47. package/dist/validate.js +33 -0
  48. package/package.json +78 -4
  49. package/src/capabilities.ts +196 -0
  50. package/src/commands.ts +181 -0
  51. package/src/components-v2.ts +533 -0
  52. package/src/components.ts +162 -0
  53. package/src/context.ts +83 -0
  54. package/src/entrypoints/admin.ts +36 -0
  55. package/src/entrypoints/core.ts +41 -0
  56. package/src/entrypoints/marketplace.ts +38 -0
  57. package/src/entrypoints/standard.ts +44 -0
  58. package/src/events.ts +34 -0
  59. package/src/index.ts +159 -0
  60. package/src/manifest-schema.ts +340 -0
  61. package/src/manifest.ts +68 -0
  62. package/src/pages.ts +282 -0
  63. package/src/paging.ts +72 -0
  64. package/src/permits.ts +250 -0
  65. package/src/validate.ts +42 -0
  66. package/README.md +0 -3
@@ -0,0 +1,297 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * The module manifest — the specified contract.
4
+ *
5
+ * Authority: `docs/spec/modules/module-anatomy-manifest.md` (SPEC-03-MODULES) and
6
+ * `docs/contracts/module-manifest.schema.json`. Where the two once disagreed with this file, this
7
+ * file was the gap; it now expresses the contract.
8
+ *
9
+ * The shape is a **discriminated union on `hardcoded`**: a `hardcoded: true` build is a private
10
+ * build pinned to one guild, so it carries `hardcodeGuildId` and admits only `releaseStatus:
11
+ * 'private'`; a `hardcoded: false` build forbids `hardcodeGuildId` and admits either release status.
12
+ * On top of the union the **visibility triad** runs as one `superRefine`, so a violating manifest
13
+ * fails with a single error naming the conflicting fields together rather than three independent
14
+ * ones.
15
+ */
16
+ export const moduleTierSchema = z.enum([
17
+ "admin",
18
+ "core",
19
+ "standard",
20
+ "marketplace",
21
+ ]);
22
+ export const moduleVisibilitySchema = z.enum(["public", "unlisted", "private"]);
23
+ /**
24
+ * UR-20261119-145 — DEPRECATED, and kept only because it is public API.
25
+ *
26
+ * `releaseStatus` left the manifest in UR-20261118-138: nothing read it, and the runtime gate it was meant
27
+ * to be is deferred in `ADR-017`. This schema and its `ModuleReleaseStatus` type are still exported from
28
+ * `@quixotic_mnemonics/swastik`, so deleting them is a breaking change for any module author who imported the name —
29
+ * and there are none yet, which is exactly why it should be done deliberately rather than as a tidy-up.
30
+ *
31
+ * Nothing in the framework references either one. When the gate in ADR-017 is built, this either returns as
32
+ * a real field or is removed in the same change; until then it is a name with no behaviour, and it says so.
33
+ */
34
+ export const moduleReleaseStatusSchema = z.enum(["private", "public"]);
35
+ export const marketplaceCategorySchema = z.enum([
36
+ "audio",
37
+ "community",
38
+ "security",
39
+ "integrations",
40
+ "utility",
41
+ ]);
42
+ /** Mirrors the DI container's `Lifetime` (src/di/container.ts). */
43
+ export const serviceLifetimeSchema = z.enum([
44
+ "singleton",
45
+ "transient",
46
+ "scoped",
47
+ ]);
48
+ export const commandManifestSchema = z.object({
49
+ name: z.string().min(1),
50
+ description: z.string().min(1),
51
+ guildOnly: z.boolean().default(true),
52
+ requiresDefer: z.boolean().default(false),
53
+ ephemeral: z.boolean().default(false),
54
+ nsfw: z.boolean().default(false),
55
+ permissions: z
56
+ .object({
57
+ discord: z.array(z.string()).default([]),
58
+ })
59
+ .default({ discord: [] }),
60
+ defaultMemberPermissions: z.string().nullable().optional(),
61
+ // UR-20261119-146 — `rbacRequirement` was DELETED from here. Nothing in the backend read it: the
62
+ // requirement that is enforced lives in the module's own `defineCommand({ permissions: { rbac } })`, which
63
+ // `toCommandDefinition` maps to `RBAC_TO_RANK` and the resolver consumes as `requiredRank`. Two
64
+ // declarations existed and only the code-level one worked, so the field a module author would naturally
65
+ // reach for was the dead one - the same defect class as `releaseStatus` (REC-058) and `buildId` (REC-049).
66
+ });
67
+ export const eventCatalogEntrySchema = z.object({
68
+ name: z
69
+ .string()
70
+ .regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*){2}$/, "event name must be {domain}.{entity}.{action}"),
71
+ description: z.string().min(1),
72
+ // §18 — every catalog entry declares a payload schema; a change to it is a breaking change.
73
+ payload: z.record(z.string(), z.unknown()),
74
+ });
75
+ export const crossModuleReadSchema = z.object({
76
+ targetModule: z.string().min(1),
77
+ accessor: z
78
+ .string()
79
+ .regex(/ForCrossModuleRead$/, 'accessor name must end with "ForCrossModuleRead"'),
80
+ });
81
+ /**
82
+ * `depends` entries are `{ token, version }` pins, never bare tokens: Stage 11 runs a
83
+ * range-satisfaction evaluator over them (see `topo-sort.ts`).
84
+ */
85
+ export const dependencyEntrySchema = z
86
+ .object({
87
+ token: z.string().min(1),
88
+ version: z.string().min(1),
89
+ })
90
+ .strict();
91
+ /** `provides` entries are `{ token, contract }` — the contract names a TS interface `tsc` checks. */
92
+ export const providedServiceSchema = z
93
+ .object({
94
+ token: z.string().min(1),
95
+ contract: z.string().min(1),
96
+ })
97
+ .strict();
98
+ /** `services` entries are `{ token, class, lifetime, deps }`. */
99
+ export const declaredServiceSchema = z
100
+ .object({
101
+ token: z.string().min(1),
102
+ class: z.string().min(1),
103
+ lifetime: serviceLifetimeSchema,
104
+ deps: z.array(z.string()).default([]),
105
+ })
106
+ .strict();
107
+ /** §1.3 / ADR-012 / ADR-013 — a module's declared UI identity: banner, accent, logo icon, name. */
108
+ export const moduleUiSchema = z
109
+ .object({
110
+ banner: z.string().min(1).optional(),
111
+ accent: z
112
+ .string()
113
+ .regex(/^#[0-9a-fA-F]{6}$/, "accent must be a #RRGGBB hex colour")
114
+ .optional(),
115
+ icon: z.string().min(1).optional(),
116
+ /**
117
+ * UR-20261012-066 — the module-relative path to the logo image the core registers as the emoji
118
+ * named by `icon`. Mirrors `banner`: a module-supplied asset, declared by the module that owns it.
119
+ */
120
+ iconAsset: z.string().min(1).optional(),
121
+ /**
122
+ * UR-20261029-112 — a module's OWN indicator set: emoji name -> module-relative image.
123
+ *
124
+ * The framework uploaded these from its own `assets/` before, so a module's indicator artwork
125
+ * lived in the host. The module now names each emoji it needs and points at its own file; the
126
+ * core resolves and registers them, and holds no copy.
127
+ */
128
+ icons: z.record(z.string().min(1), z.string().min(1)).optional(),
129
+ displayName: z.string().min(1).optional(),
130
+ // UR-20261119-139 - `devUsername` moved to the TOP LEVEL. It was under `ui`, which made the
131
+ // developer's identity a rendering detail; the maintainer's definition puts it in the manifest as the
132
+ // attribution the renderer grammar reads. One field, in one place, so the two cannot disagree.
133
+ })
134
+ .strict();
135
+ const commonManifestFields = {
136
+ name: z
137
+ .string()
138
+ .min(1)
139
+ .regex(/^[a-z][a-z0-9-]*$/, "module name must be lowercase-kebab-case"),
140
+ version: z
141
+ .string()
142
+ .regex(/^\d+\.\d+\.\d+$/, 'version must be semver, e.g. "1.0.0"'),
143
+ description: z.string().min(1).max(120),
144
+ tier: moduleTierSchema,
145
+ devGuildOnly: z.boolean().optional(),
146
+ /**
147
+ * UR-20261119-139 - THE MANIFEST NAMES THE DEVELOPER BY USERNAME, NEVER BY ID.
148
+ *
149
+ * The maintainer drew the line the corpus had blurred: a **developer username** is a Dumby account
150
+ * username, promoted to a developer account with friction, and it is what the renderer's attribution
151
+ * grammar and the manifest speak. A **developer id** is issued by application, is what the compliance
152
+ * and management team enforce against, and never appears in a manifest at all - it lives in the
153
+ * credential record and in the license subject.
154
+ *
155
+ * Optional, and ABSENT MEANS FIRST-PARTY: the seven core modules and hello-world ship inside the image
156
+ * and have no registered account to name. Absence is only reachable by a module built into the image,
157
+ * because the upload endpoint refuses a submission without it.
158
+ */
159
+ devUsername: z.string().min(1).optional(),
160
+ /**
161
+ * UR-20261119-139 - the ADMIN tier's guild binding.
162
+ *
163
+ * The tier was designed for "our own bot-owner modules on our development server"; the maintainer's
164
+ * adaptation is that any developer may have such a module, scoped to their own development guild -
165
+ * exactly as a persona is scoped to its bound guild. `devGuildOnly` is the catalogue-side claim;
166
+ * `devGuildId` is the BINDING, and it is required for `tier: admin` (tier-rules) and enforced by the
167
+ * loader and the dispatch path, so the claim can no longer be declared and ignored.
168
+ */
169
+ devGuildId: z.string().min(1).optional(),
170
+ /** The ONLY catalogue field with a consumer: `mdis.service.ts` filters `visibility !== 'private'`. */
171
+ visibility: moduleVisibilitySchema,
172
+ marketplaceCategory: marketplaceCategorySchema.optional(),
173
+ depends: z.array(dependencyEntrySchema).default([]),
174
+ provides: z.array(providedServiceSchema).default([]),
175
+ intents: z.array(z.string()).default([]),
176
+ partials: z.array(z.string()).default([]),
177
+ commands: z.array(commandManifestSchema).default([]),
178
+ events: z.array(z.string()).default([]),
179
+ services: z.array(declaredServiceSchema).default([]),
180
+ repositories: z.array(z.string()).default([]),
181
+ jobs: z.array(z.string()).default([]),
182
+ tasks: z.array(z.string()).default([]),
183
+ routes: z.array(z.string()).default([]),
184
+ middleware: z.array(z.string()).default([]),
185
+ // UR-20261116-132 — the customId prefixes this module ANSWERS, so a control a module owns is
186
+ // declared rather than hidden. The loader refuses a handler whose prefix is not listed here.
187
+ components: z.array(z.string().min(1)).default([]),
188
+ migrations: z.array(z.string()).default([]),
189
+ locales: z.array(z.string()).default(["en-US"]),
190
+ config: z.record(z.string(), z.unknown()).default({}),
191
+ eventsCatalog: z.array(eventCatalogEntrySchema).default([]),
192
+ dashboardSchema: z.record(z.string(), z.unknown()).optional(),
193
+ ui: moduleUiSchema.optional(),
194
+ /**
195
+ * UR-20261126-247 R3 — ADR-001 BAN 2, LAYER 2: THE MANIFEST DECLARES HOW IT RENDERS.
196
+ *
197
+ * Division 1 §1.8 has claimed since ADR-001 that load-time validation "refuses any module whose
198
+ * declared render contract requires classic embeds". It could not: there was no field to declare, so
199
+ * there was nothing to refuse. This is the field. It admits exactly one value — `blocks` — because the
200
+ * only conforming answer is the one the framework already assumes; a manifest that declares anything
201
+ * else fails validation at load, which is the layer-2 refusal the spec describes.
202
+ *
203
+ * Optional, and ABSENT MEANS `blocks`: every module that ships today returns blocks or data, and a
204
+ * required field would have been eight manifest edits that changed no behaviour. Declaring it is for
205
+ * a module author who wants the contract stated, and for the gate that checks the corpus's claim.
206
+ */
207
+ render: z
208
+ .object({
209
+ contract: z.enum(["blocks"]),
210
+ })
211
+ .strict()
212
+ .optional(),
213
+ crossModuleReads: z.array(crossModuleReadSchema).default([]),
214
+ };
215
+ /**
216
+ * UR-20261118-138 - the union is gone with `hardcoded`.
217
+ *
218
+ * The schema used to be a discriminated union on `hardcoded`, and `hardcoded`, `releaseStatus` and
219
+ * `visibility` were then validated against each other as a "triad". Tracing every consumer showed the
220
+ * shape of the problem: `hardcoded` was read by NOTHING, `releaseStatus` was read by NOTHING, and the
221
+ * triad rule was therefore three fields keeping each other consistent, two of which nothing consumed.
222
+ * It looked meaningful because it validated, and it meant nothing because nothing read it - the same
223
+ * defect class as `RenderDescriptor.buildId` (REC-049).
224
+ *
225
+ * `hardcodeGuildId` existed only to pair with `hardcoded` and had no consumer either, so it went too.
226
+ *
227
+ * What remains is what the code actually uses: `tier` (fatal-vs-degraded, privilege), `visibility` (the
228
+ * catalogue filter in mdis.service.ts), `devUsername` (the developer's account name, optional and absent
229
+ * for first-party) and `devGuildId` (the admin tier's guild binding). `required` is derived from `tier` at
230
+ * the loader rather than declared.
231
+ */
232
+ export const moduleManifestSchema = z
233
+ .object(commonManifestFields)
234
+ .strict()
235
+ .superRefine((manifest, ctx) => {
236
+ const problems = providesIsNamespacedAndFirstParty(manifest);
237
+ if (problems.length > 0) {
238
+ ctx.addIssue({
239
+ code: "custom",
240
+ message: `manifest "${manifest.name}" violates the service seam: ${problems.join("; ")}`,
241
+ });
242
+ }
243
+ });
244
+ /**
245
+ * 2026-11-16 — the service seam, closed at validation (`REC-052`).
246
+ *
247
+ * `provides` used to accept any non-empty token for any module, and the registry resolved it
248
+ * last-wins, so a licensed module could declare `core.PersonaRuntime` and take a core capability by
249
+ * loading later. Three rules now, all refused at validation rather than at load:
250
+ *
251
+ * 1. A `core.*` token is FIRST-PARTY ONLY. The discriminator is `devId: 'dev_first_party'`, which is
252
+ * safe to key on because the manifest's `devId` is checked against the authenticated principal at
253
+ * upload and at deploy — a licensed developer cannot claim it and have the claim survive the
254
+ * endpoint. It is not trusted here on its own; it is trusted because the endpoint already proved it.
255
+ * 2. A `core.*` token requires `tier: 'core'`. A first-party standard-tier module (hello-world) may
256
+ * not reach the core base through the service seam any more than through an import.
257
+ * 3. Every token is NAMESPACED — `core.*` or `module.<slug>.*` — and no manifest may declare the same
258
+ * token twice. The guard's `MODULE_TOKEN_PATTERN` already gave module-namespaced tokens their own
259
+ * namespace; this is the same rule, stated where the manifest is validated.
260
+ */
261
+ export const providesIsNamespacedAndFirstParty = (manifest) => {
262
+ const problems = [];
263
+ const seen = new Set();
264
+ for (const { token } of manifest.provides) {
265
+ if (seen.has(token))
266
+ problems.push(`token '${token}' is declared more than once`);
267
+ seen.add(token);
268
+ if (token.startsWith("core.")) {
269
+ if (manifest.devUsername !== undefined) {
270
+ problems.push(`token '${token}' is a core capability, and core capabilities are first-party only (declared by '${manifest.devUsername}')`);
271
+ }
272
+ if (manifest.tier !== "core") {
273
+ problems.push(`token '${token}' is a core capability, and only tier 'core' may provide one (tier is '${manifest.tier}')`);
274
+ }
275
+ continue;
276
+ }
277
+ if (!/^module\.[a-z0-9][a-z0-9-]*\.[A-Za-z0-9_.]+$/.test(token)) {
278
+ problems.push(`token '${token}' is not namespaced — use 'module.<slug>.<name>'`);
279
+ }
280
+ }
281
+ return problems;
282
+ };
283
+ /**
284
+ * UR-20261118-138 - `required` is DERIVED, not declared.
285
+ *
286
+ * It used to be a manifest field, and every manifest restated its own tier with it: all seven core
287
+ * modules said `required: true`, `hello-world` said `false`. The loader's only use for it was deciding
288
+ * fatal-versus-degraded on a load failure, and core/admin are already the tiers §13.2 makes permanent
289
+ * and un-disableable. So the field was a second way to say `tier`, and a manifest could say it WRONGLY -
290
+ * `tier: standard, required: true` was schema-valid and would have made a marketplace module fatal to
291
+ * the boot.
292
+ *
293
+ * One function, so there is one answer.
294
+ */
295
+ export function isRequiredTier(tier) {
296
+ return tier === "core" || tier === "admin";
297
+ }
@@ -0,0 +1,47 @@
1
+ export declare const moduleTiers: readonly ["admin", "core", "standard", "marketplace"];
2
+ export type ModuleTier = (typeof moduleTiers)[number];
3
+ import type { ModuleManifest } from './manifest-schema.js';
4
+ import type { z } from 'zod';
5
+ import { commandManifestSchema } from './manifest-schema.js';
6
+ export type { ModuleManifest } from './manifest-schema.js';
7
+ export type { DependencyEntry, ProvidedService, DeclaredService, ModuleVisibility, ModuleReleaseStatus, MarketplaceCategory, } from './manifest-schema.js';
8
+ export * from './manifest-schema.js';
9
+ /** The per-command entry of a manifest, derived from the shared schema. */
10
+ export type ModuleCommandManifest = z.infer<typeof commandManifestSchema>;
11
+ export interface ModuleLifecycle<Container = unknown> {
12
+ onLoad?: (container: Container) => Promise<void> | void;
13
+ onReady?: (container: Container) => Promise<void> | void;
14
+ /**
15
+ * UR-20261012-071 — §11.7: start active processes on the DISABLED → ENABLED transition (a polling
16
+ * loop, an external connection, a scheduled task). Optional; idempotent; ≤ 5 s.
17
+ *
18
+ * These are GLOBAL transitions — load, re-enable, shutdown — not per-guild ones. §13.7 is explicit
19
+ * that a per-guild toggle "never touches the module's loaded state, DI registrations, or event
20
+ * subscriptions", so disabling a module in ONE guild must not stop a process that other guilds are
21
+ * still served by. The per-guild case is handled by the execution gates (UR-20261012-069).
22
+ */
23
+ onEnable?: (container: Container) => Promise<void> | void;
24
+ /**
25
+ * UR-20261012-071 — §11.7: stop them on the ENABLED → DISABLED transition. Optional; idempotent;
26
+ * ≤ 5 s. A throw is logged and the module still transitions to DISABLED. Always runs BEFORE
27
+ * `onUnload`.
28
+ */
29
+ onDisable?: () => Promise<void> | void;
30
+ /**
31
+ * UR-20261012-072 — §11.7: "cleanup on an unrecoverable error". Called when the framework gives up
32
+ * on the module — a load or ready failure it cannot recover from. Idempotent; a throw here is
33
+ * logged and does not change the outcome.
34
+ */
35
+ onError?: (error: Error) => Promise<void> | void;
36
+ /**
37
+ * UR-20261012-072 — §11.7: "react to a per-guild config change without a reload". Called when THIS
38
+ * module's per-guild config is written, so a module can refresh cached values rather than recompute
39
+ * them on every read. Idempotent.
40
+ */
41
+ onConfigChange?: (guildId: string, config: Readonly<Record<string, unknown>>) => Promise<void> | void;
42
+ onUnload?: () => Promise<void> | void;
43
+ }
44
+ export interface SwastikModule<Container = unknown> extends ModuleLifecycle<Container> {
45
+ manifest: ModuleManifest;
46
+ }
47
+ export declare function defineModule<Container = unknown>(moduleDefinition: SwastikModule<Container>): SwastikModule<Container>;
@@ -0,0 +1,6 @@
1
+ export const moduleTiers = ['admin', 'core', 'standard', 'marketplace'];
2
+ import { commandManifestSchema } from './manifest-schema.js';
3
+ export * from './manifest-schema.js';
4
+ export function defineModule(moduleDefinition) {
5
+ return moduleDefinition;
6
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * UR-20261027-106 — a module OWNS its page.
3
+ *
4
+ * The doctrine says a module is a self-contained vertical slice owning commands, events, services,
5
+ * data and config. The tree did the opposite: every module declared a command that returned
6
+ * `{ page, data }` and the host built the page in `apps/main/src/rendering/page-data.ts`. That file is
7
+ * a core-base file serving seven modules, which makes "core module" a manifest label rather than a
8
+ * code boundary.
9
+ *
10
+ * This is the contract that lets a module build its own page without importing the core base:
11
+ *
12
+ * - the module declares the page and owns its composition (labels, sections, ordering);
13
+ * - the framework supplies the DATA through typed capability calls (operator decision, 2026-10-27):
14
+ * the module calls `read.installState(guildId)` and owns the page; the framework owns the query.
15
+ * A raw SQL handle was rejected — under the doctrine a module owns its own tables, and a
16
+ * framework read-model is the honest shape for a read that spans what the framework records.
17
+ *
18
+ * A page declared here wins over the host's built-in page of the same id, so a module can take over
19
+ * its own surface without the host changing.
20
+ */
21
+ export interface ModulePageContext {
22
+ /** The guild the page is being rendered for; null in a DM. */
23
+ readonly guildId: string | null;
24
+ /** The Discord application answering — the main profile's, or a persona's. */
25
+ readonly applicationId: string;
26
+ /** `'main'`, or the persona's id. */
27
+ readonly profileId: string;
28
+ /** 1-based page index within the module's own pager. */
29
+ readonly page: number;
30
+ /** The member who invoked the surface — a module binding its own control ids needs it. */
31
+ readonly invokerId: string;
32
+ /** The member's search text, when the surface has one — /browse's Discover query. */
33
+ readonly query?: string;
34
+ /**
35
+ * UR-20261029-113 — resolve an emoji NAME to the reference the rendering application owns, or
36
+ * `undefined` when that application has not uploaded it (the caller falls back to its own glyph).
37
+ *
38
+ * A module composes its own blocks, so it needs the marks it puts in them. Without this it would
39
+ * have to import the framework's emoji table — which is how a module's schema ended up living in the
40
+ * host in the first place. The module names the emoji; the framework owns the id.
41
+ */
42
+ readonly emoji: (name: string) => string | undefined;
43
+ /**
44
+ * UR-20261029-116 — whether the member who invoked the command administers this guild.
45
+ *
46
+ * A page that offers a control only an admin may use must know this, and the module cannot ask
47
+ * Discord. Without it the /persona setup control had to be assembled by the router, which is how
48
+ * that page's whole schema ended up in the framework.
49
+ */
50
+ readonly isAdmin: boolean;
51
+ /**
52
+ * The same emoji as PARTS, for a component that needs the object rather than the inline ref — a
53
+ * button's icon is `{ id, name }`, not `<:name:id>`. Both shapes are honest needs, so both are here
54
+ * rather than one being reconstructed from the other by string surgery in every module.
55
+ */
56
+ readonly emojiParts: (name: string) => {
57
+ readonly id: string;
58
+ readonly name: string;
59
+ } | undefined;
60
+ }
61
+ /** A module as the read-model reports it — manifest facts only, no database row. */
62
+ export interface ModuleSummary {
63
+ readonly slug: string;
64
+ readonly tier: string;
65
+ readonly description: string;
66
+ readonly displayName?: string;
67
+ readonly iconName?: string;
68
+ readonly accent?: string;
69
+ readonly commands: readonly {
70
+ readonly name: string;
71
+ readonly description: string;
72
+ }[]; /** The developer who published it — what the Discover search matches on. */
73
+ readonly devId?: string;
74
+ }
75
+ /**
76
+ * The typed read-model the framework provides. It carries no handle and no table name: a module asks
77
+ * for the fact it needs, and the framework decides how to answer it. Every method is scoped to the
78
+ * guild and profile the page is being rendered for, so a module cannot read another guild's state by
79
+ * passing a different id.
80
+ */
81
+ export interface ModulePageReadModel {
82
+ /** Every module the framework knows, in load order. */
83
+ list(): Promise<readonly ModuleSummary[]>;
84
+ /** Is this module enabled in the page's guild? Core and admin always are. */
85
+ installState(slug: string): Promise<boolean>;
86
+ /** When this module was installed in the page's guild, as epoch ms; `undefined` when it has no row. */
87
+ installedAt(slug: string): Promise<number | undefined>;
88
+ /** Does the page's profile hold this module in this guild? */
89
+ ownedByCaller(slug: string): Promise<boolean>;
90
+ /** The command names this guild actually resolves to, keyed by the declared name. */
91
+ commandNames(): Promise<ReadonlyMap<string, string>>;
92
+ /** The per-guild status of a declared command name. */
93
+ commandStatus(name: string): Promise<'enabled' | 'disabled'>;
94
+ /** The emoji name a module page uses as its command marker. */
95
+ markerIcon(): Promise<string>;
96
+ /**
97
+ * The rendered reference for a declared `ui.icon`, as the application serving this page owns it —
98
+ * `<:name:id>` — or the declared name itself when the application has not uploaded that emoji.
99
+ *
100
+ * A module names the icon; the framework resolves it. The emoji registry, the upload lifecycle and
101
+ * the per-application ownership of an emoji all stay behind this call, which is why a page can
102
+ * render an icon without touching the core base.
103
+ */
104
+ moduleIcon(iconName: string | undefined): Promise<string>;
105
+ /** Reachability of the two shared subsystems, as the framework measured them for this render. */
106
+ probe(): Promise<{
107
+ readonly database: SubsystemState;
108
+ readonly redis: SubsystemState;
109
+ }>;
110
+ /** The PROFILE this page reports for — her runtime, not the host's. */
111
+ actingProfile(): Promise<ActingProfileFacts>;
112
+ /** The modules this profile HOLDS in the page's guild — the ownership read, not what is loaded. */
113
+ heldModules(): Promise<readonly string[]>;
114
+ /**
115
+ * The configured shard count. A narrow read on purpose: a general `setting(key)` would hand a module
116
+ * the whole configuration surface, which is the boundary this contract exists to hold.
117
+ */
118
+ shardCount(): Promise<number>;
119
+ /**
120
+ * The guild and member counts this profile sees, and WHICH source answered. The Discord API is the
121
+ * authority on membership; the cache is a snapshot taken at login and can lag, which is how a bot in
122
+ * three guilds once reported four. A page must be able to say which it used.
123
+ */
124
+ guilds(): Promise<GuildCounts>;
125
+ /**
126
+ * The host process's own numbers. A module CANNOT read these itself: its tsconfig carries no Node
127
+ * types, because a module is environment-neutral — it declares surfaces, it does not touch the host
128
+ * runtime. So the framework reports them, and the page labels them as SHARED rather than the
129
+ * profile's.
130
+ */
131
+ hostProcess(): Promise<HostProcessFacts>;
132
+ /**
133
+ * The pending command-queue actions for the page's guild, oldest first. The queue is core
134
+ * infrastructure; a module asks what is pending, not how the table is shaped.
135
+ */
136
+ pendingQueue(): Promise<readonly PendingQueueEntry[]>;
137
+ /**
138
+ * WHO holds a module in this page's guild — `'main'`, a persona's id, or `undefined` when nobody
139
+ * does. `undefined` is NOT the main bot: the ownership read answers `'main'` explicitly when the
140
+ * resident bot holds it, and a page that conflated the two would name the bot as the holder of a
141
+ * module it never claimed.
142
+ */
143
+ holder(slug: string): Promise<string | undefined>;
144
+ /**
145
+ * Is this module enabled by DEFAULT for the acting profile? Not the same as the guild's state: a
146
+ * standard module is enabled by default only for the profile that got there first, so this answer
147
+ * depends on ownership. Core and Admin are shared and always on; marketplace never defaults on.
148
+ */
149
+ enabledByDefault(slug: string): Promise<boolean>;
150
+ /**
151
+ * How to NAME a profile on a surface: "Dumby Profile" for the internal one, or the persona's own
152
+ * registered name. A page must never invent a holder, and never show a raw id to a member.
153
+ */
154
+ profileLabel(profileId: string): Promise<string>;
155
+ /**
156
+ * The GUILD's own stored state for a module — the `guild_module_states` row — and `undefined` when
157
+ * there is no row. Lossless on purpose: `undefined` ("never touched here") and `false` ("the guild
158
+ * disabled it") are different facts, and a catalogue that conflated them would label a module
159
+ * disabled-by-choice as merely unavailable.
160
+ */
161
+ guildState(slug: string): Promise<boolean | undefined>;
162
+ /** The tier's default for the GUILD, when it has no row: core and admin on, marketplace off. */
163
+ tierDefault(slug: string): Promise<boolean>;
164
+ /**
165
+ * The guild's persona bindings: which module is bound to which persona here. A module bound to a
166
+ * persona is owned by that persona in this guild; every other module belongs to the resident bot.
167
+ */
168
+ personaBindings(): Promise<readonly PersonaBinding[]>;
169
+ /**
170
+ * The personas this guild knows — registered here, or named by a binding. `boundGuildId` is exactly
171
+ * "the personas this guild registered", which is not the same set as "personas bound to a module".
172
+ */
173
+ registeredPersonas(): Promise<readonly PersonaRecord[]>;
174
+ /**
175
+ * The identity this PROCESS runs as: a persona's id when it is a dedicated persona process, `'main'`
176
+ * otherwise. Not "the persona registered for this guild" — that was the bug that opened /persona on
177
+ * a persona's profile when the main bot ran it.
178
+ */
179
+ residentProfileId(): Promise<string>;
180
+ /** The resident bot's own identity: its name, its application id, and whether it is connected. */
181
+ botIdentity(): Promise<{
182
+ readonly name: string;
183
+ readonly applicationId: string;
184
+ readonly online: boolean;
185
+ }>;
186
+ /**
187
+ * Is this application present in the page's guild? A persona is ACTIVE only when its bot has been
188
+ * invited and is there; presence that cannot be resolved is reported as absent, never assumed.
189
+ */
190
+ isMember(applicationId: string): Promise<boolean>;
191
+ /** The invite URL for a persona's application, or `''` when there is no guild or no builder. */
192
+ inviteUrl(applicationId: string, withOAuth: boolean): Promise<string>;
193
+ }
194
+ export type SubsystemState = 'connected' | 'unavailable';
195
+ export interface PersonaBinding {
196
+ readonly moduleSlug: string;
197
+ readonly personaId: string;
198
+ }
199
+ export interface PersonaRecord {
200
+ readonly id: string;
201
+ readonly name: string;
202
+ readonly discordApplicationId: string;
203
+ readonly boundGuildId: string;
204
+ readonly dmBehavior: string;
205
+ readonly shardAllocation: number;
206
+ readonly status: string;
207
+ readonly hasOAuth: boolean;
208
+ /**
209
+ * Whether this persona's OAuth leg has EVER completed. Discord exposes no API to read an
210
+ * application's registered redirect URIs, so a successful exchange is the only honest proof the
211
+ * redirect URL is configured. The fact, not a presentation of it.
212
+ */
213
+ readonly oauthVerified: boolean;
214
+ }
215
+ export interface PendingQueueEntry {
216
+ /** The command this action will apply to. */
217
+ readonly commandKey: string;
218
+ /** `'rename'` when the payload carries no action — the queue's own default. */
219
+ readonly action: string;
220
+ readonly newName?: string;
221
+ readonly alias?: string;
222
+ readonly disable?: boolean;
223
+ }
224
+ export interface HostProcessFacts {
225
+ /** Seconds the process has been up. */
226
+ readonly uptimeSeconds: number;
227
+ /** e.g. `v20.20.2`. */
228
+ readonly nodeVersion: string;
229
+ readonly memory: {
230
+ readonly rss: number;
231
+ readonly heapUsed: number;
232
+ readonly heapTotal: number;
233
+ };
234
+ }
235
+ export interface GuildCounts {
236
+ /** Guilds this profile is in. */
237
+ readonly total: number;
238
+ /** Members across them; `undefined` when the cache has not filled — not zero. */
239
+ readonly members?: number;
240
+ /** `'live'` when the API answered, `'cache'` when the snapshot did. */
241
+ readonly source: 'live' | 'cache';
242
+ }
243
+ export interface ActingProfileFacts {
244
+ /** `'main'`, or the persona's id. */
245
+ readonly profileId: string;
246
+ /** When this profile's runtime started, epoch ms; absent for the internal profile, the host. */
247
+ readonly startedAt?: number;
248
+ /** Is this profile's gateway connected? */
249
+ readonly gatewayReady: boolean;
250
+ /** Gateway latency in ms, when the client reports one. */
251
+ readonly gatewayPingMs?: number;
252
+ /** The module slugs this profile's runtime has LOADED — a different fact from what it holds. */
253
+ readonly loadedModules: readonly string[];
254
+ }
255
+ /**
256
+ * UR-20261029-113 — what a page hands back.
257
+ *
258
+ * `data` is the shape the framework's own consumers read; `blocks` is the module's OWN renderer
259
+ * schema for its content. A module that returns blocks owns its surface end to end: the framework
260
+ * renders what it is given and contributes only its chrome — the navigation, the footer, the dial —
261
+ * which is what keeps the zone grammar enforceable. A module that returns data alone is shaped by the
262
+ * framework as before, so no existing page had to change.
263
+ */
264
+ export interface ModulePageResult {
265
+ readonly data: unknown;
266
+ readonly blocks?: readonly Record<string, unknown>[];
267
+ }
268
+ export interface ModulePage {
269
+ /** The page id the command returns. */
270
+ readonly id: string;
271
+ /** Build the page: its data, and optionally its own content blocks. */
272
+ render(context: ModulePageContext, read: ModulePageReadModel): Promise<unknown>;
273
+ }
274
+ export declare function definePage(page: ModulePage): ModulePage;
package/dist/pages.js ADDED
@@ -0,0 +1,3 @@
1
+ export function definePage(page) {
2
+ return page;
3
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Paging helpers a module page needs to build its own slides.
3
+ *
4
+ * These lived in `apps/main/src/rendering/page-data.ts`, which a module cannot import — so they are
5
+ * here, in the package a module already depends on, and the host re-exports them from where it used
6
+ * to declare them. One implementation, two callers.
7
+ */
8
+ /**
9
+ * 1 -> I, 4 -> IIII. Non-finite or non-positive values are printed as they are.
10
+ *
11
+ * ADDITIVE ONLY, and deliberately so: there is no subtractive pair, so 4 is `IIII` and not `IV`, 9 is
12
+ * `VIIII` and not `IX`, 40 is `XXXX` and not `XL`. The rationale lived only in the host's re-export
13
+ * (`apps/main/src/rendering/page-data.ts`), which said the form is used "throughout (IIII rather than
14
+ * IV) on purpose: it is unambiguous to read at a glance" — a slide dial is scanned, not read. It is
15
+ * recorded here, at the implementation, because this comment used to say "4 -> IV" and the function
16
+ * has never done that; a reader who trusted it would have "fixed" a deliberate choice.
17
+ */
18
+ export declare function romanNumeral(value: number): string;
19
+ export interface PageSlide {
20
+ readonly id: string;
21
+ readonly name: string;
22
+ readonly description: string;
23
+ readonly page: number;
24
+ }
25
+ /**
26
+ * The DIAL's entries for a surface that pages MODULES directly: one option per slide, naming the
27
+ * range it holds. An option per module would offer targets that do not exist.
28
+ *
29
+ * Page 0 is Home; the slides cover 1..pageTotal-1, numbered from I — numbering the first listing page
30
+ * as a slide made Home and "Slide I" the same destination with the same modules on it.
31
+ */
32
+ export declare function modulePageNavigation(pageTotal: number, total: number, pageSize: number): readonly PageSlide[];