@plitzi/sdk-kernel 0.0.0-stage → 0.39.2

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 (142) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +80 -2
  3. package/dist/build/esbuild.d.ts +16 -0
  4. package/dist/build/index.d.ts +1 -0
  5. package/dist/build/index.mjs +35 -0
  6. package/dist/cache/CompressedFileCache.d.ts +18 -0
  7. package/dist/cache/TtlCache.d.ts +65 -0
  8. package/dist/cache/index.d.ts +3 -0
  9. package/dist/cache/index.mjs +1 -0
  10. package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
  11. package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
  12. package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
  13. package/dist/chunks/link-C9wyDS9H.mjs +124 -0
  14. package/dist/chunks/query-DGbrN3mN.mjs +20 -0
  15. package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
  16. package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
  17. package/dist/chunks/session-B-dTEjeG.mjs +253 -0
  18. package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
  19. package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
  20. package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
  21. package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
  22. package/dist/chunks/tail-D-USrZIR.mjs +55 -0
  23. package/dist/chunks/tokens-CBd5tXut.mjs +262 -0
  24. package/dist/data/index.d.ts +2 -0
  25. package/dist/data/index.mjs +68 -0
  26. package/dist/data/projectData.d.ts +21 -0
  27. package/dist/deployment/hostDeployment.d.ts +8 -0
  28. package/dist/deployment/index.d.ts +3 -0
  29. package/dist/deployment/index.mjs +19 -0
  30. package/dist/deployment/spaceDeployment.d.ts +11 -0
  31. package/dist/engine/index.d.ts +2 -0
  32. package/dist/engine/index.mjs +1 -0
  33. package/dist/engine/page.d.ts +49 -0
  34. package/dist/engine/rsc.d.ts +32 -0
  35. package/dist/files/atomicFile.d.ts +10 -0
  36. package/dist/files/index.d.ts +1 -0
  37. package/dist/files/index.mjs +32 -0
  38. package/dist/http/bearer.d.ts +5 -0
  39. package/dist/http/buildResponseHelpers.d.ts +23 -0
  40. package/dist/http/closeOnSignals.d.ts +28 -0
  41. package/dist/http/compress.d.ts +20 -0
  42. package/dist/http/dispatcher.d.ts +15 -0
  43. package/dist/http/drain.d.ts +18 -0
  44. package/dist/http/fleet/channel.d.ts +103 -0
  45. package/dist/http/fleet/link.d.ts +28 -0
  46. package/dist/http/fleet/role.d.ts +46 -0
  47. package/dist/http/fleet/supervisor.d.ts +29 -0
  48. package/dist/http/freePort.d.ts +24 -0
  49. package/dist/http/health.d.ts +21 -0
  50. package/dist/http/index.d.ts +48 -0
  51. package/dist/http/index.mjs +1313 -0
  52. package/dist/http/middlewares/auth.d.ts +2 -0
  53. package/dist/http/middlewares/basicAuth.d.ts +6 -0
  54. package/dist/http/mimeTypes.d.ts +13 -0
  55. package/dist/http/navigation.d.ts +14 -0
  56. package/dist/http/onAbort.d.ts +12 -0
  57. package/dist/http/probes.d.ts +4 -0
  58. package/dist/http/requestParser.d.ts +22 -0
  59. package/dist/http/runMiddlewares.d.ts +6 -0
  60. package/dist/http/securityHeaders.d.ts +18 -0
  61. package/dist/http/server.d.ts +39 -0
  62. package/dist/http/socketResponse.d.ts +18 -0
  63. package/dist/http/sse.d.ts +26 -0
  64. package/dist/http/stages/crossSiteWrites.d.ts +24 -0
  65. package/dist/http/stages/health.d.ts +11 -0
  66. package/dist/http/stages/middlewares.d.ts +3 -0
  67. package/dist/http/stages/static.d.ts +4 -0
  68. package/dist/http/staticFiles.d.ts +3 -0
  69. package/dist/http/stopping.d.ts +11 -0
  70. package/dist/http/transports.d.ts +31 -0
  71. package/dist/http/types.d.ts +29 -0
  72. package/dist/http/unusedPort.d.ts +10 -0
  73. package/dist/http/webExchange.d.ts +18 -0
  74. package/dist/http/wsFrame.d.ts +3 -0
  75. package/dist/identity/accounts.d.ts +278 -0
  76. package/dist/identity/authorize.d.ts +96 -0
  77. package/dist/identity/credentials.d.ts +40 -0
  78. package/dist/identity/csrf.d.ts +139 -0
  79. package/dist/identity/debugAuthorization.d.ts +24 -0
  80. package/dist/identity/domains.d.ts +41 -0
  81. package/dist/identity/identity.d.ts +119 -0
  82. package/dist/identity/index.d.ts +21 -0
  83. package/dist/identity/index.mjs +731 -0
  84. package/dist/identity/passwords.d.ts +15 -0
  85. package/dist/identity/previewToken.d.ts +21 -0
  86. package/dist/identity/requestIdentity.d.ts +14 -0
  87. package/dist/identity/scopes.d.ts +56 -0
  88. package/dist/identity/session.d.ts +185 -0
  89. package/dist/identity/sessionActivity.d.ts +11 -0
  90. package/dist/identity/spaceTokens.d.ts +174 -0
  91. package/dist/index.d.ts +17 -0
  92. package/dist/index.mjs +1 -0
  93. package/dist/log/index.d.ts +3 -0
  94. package/dist/log/index.mjs +3 -0
  95. package/dist/log/serverLog.d.ts +49 -0
  96. package/dist/log/tail.d.ts +43 -0
  97. package/dist/mysql/accounts.d.ts +4 -0
  98. package/dist/mysql/admin.d.ts +58 -0
  99. package/dist/mysql/config.d.ts +82 -0
  100. package/dist/mysql/identities.d.ts +35 -0
  101. package/dist/mysql/index.d.ts +7 -0
  102. package/dist/mysql/index.mjs +1203 -0
  103. package/dist/mysql/pool.d.ts +3 -0
  104. package/dist/mysql/query.d.ts +12 -0
  105. package/dist/mysql/schema.d.ts +43 -0
  106. package/dist/mysql/sessions.d.ts +23 -0
  107. package/dist/mysql/spaceTokens.d.ts +11 -0
  108. package/dist/mysql/store.d.ts +66 -0
  109. package/dist/outbound/index.d.ts +4 -0
  110. package/dist/outbound/index.mjs +314 -0
  111. package/dist/outbound/inside.d.ts +36 -0
  112. package/dist/outbound/outboundGuard.d.ts +69 -0
  113. package/dist/pubsub/index.d.ts +3 -0
  114. package/dist/pubsub/index.mjs +76 -0
  115. package/dist/pubsub/memoryPubSub.d.ts +10 -0
  116. package/dist/pubsub/redisPubSub.d.ts +24 -0
  117. package/dist/stats/index.d.ts +9 -0
  118. package/dist/stats/index.mjs +228 -0
  119. package/dist/stats/load.d.ts +31 -0
  120. package/dist/stats/memory.d.ts +20 -0
  121. package/dist/stats/pools.d.ts +15 -0
  122. package/dist/stats/recorder.d.ts +34 -0
  123. package/dist/stats/stage.d.ts +15 -0
  124. package/dist/stats/types.d.ts +309 -0
  125. package/dist/testing/certificates.d.ts +21 -0
  126. package/dist/testing/fleet.d.ts +28 -0
  127. package/dist/testing/goneRuns.d.ts +5 -0
  128. package/dist/testing/index.d.ts +5 -0
  129. package/dist/testing/index.mjs +270 -0
  130. package/dist/testing/keys.d.ts +2 -0
  131. package/dist/testing/runNames.d.ts +10 -0
  132. package/dist/tokens/index.d.ts +2 -0
  133. package/dist/tokens/index.mjs +1 -0
  134. package/dist/tokens/tokens.d.ts +190 -0
  135. package/dist/types/adapters.d.ts +388 -0
  136. package/dist/types/config.d.ts +240 -0
  137. package/dist/types/index.d.ts +5 -0
  138. package/dist/types/index.mjs +1 -0
  139. package/dist/types/log.d.ts +119 -0
  140. package/dist/types/oauth.d.ts +246 -0
  141. package/dist/types/pipeline.d.ts +239 -0
  142. package/package.json +67 -3
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Names of this run's own for what the integration tests make in a database they share with every other run on the
3
+ * machine — another session, the workspace's suite beside a package's — which emptied and dropped each other's tables
4
+ * when the names were fixed. A name carries the process that made it, `<base>_<pid>`, so what a run killed before its
5
+ * `afterAll` left behind is told apart from what a run still going holds, and dropped by the next.
6
+ */
7
+ /** `<base>_<pid>`, this process's. */
8
+ export declare const runName: (base: string) => string;
9
+ /** Whether `name` is one `runName(base)` gave a process that is no longer running — never this one's. */
10
+ export declare const leftByGoneRun: (name: string, base: string) => boolean;
@@ -0,0 +1,2 @@
1
+ export { DEFAULT_LIFETIMES, generateTokenKeys, createTokens, userIdOf } from './tokens';
2
+ export type { TokenLifetimes, TokenKeys, TokenConfig, UserTokenPayload, UserTokenOptions, RefreshTokenPayload, MfaChallengePayload, SpaceTokenPayload, WidgetTokenPayload, TokenPayload, VerifyResult, SpaceTokenOptions, Tokens } from './tokens';
@@ -0,0 +1 @@
1
+ export { t as DEFAULT_LIFETIMES, n as createTokens, r as generateTokenKeys, i as userIdOf } from "../chunks/tokens-CBd5tXut.mjs";
@@ -0,0 +1,190 @@
1
+ import { SCOPES, AuthFailure, SpaceScope, TokenScope } from '../identity/scopes';
2
+ /**
3
+ * How long each credential lives. One rule, applied by how much damage the credential can do and whether something
4
+ * can renew it:
5
+ *
6
+ * - The **public render token** is the only one that may live forever, and defaults to it: it is embedded in
7
+ * published sites, where an expiry is a scheduled outage. A space may still give it a date.
8
+ * - **Everything else expires**, 30 days being the baseline.
9
+ * - **The most dangerous one is the shortest.** A session access token rides on every request and is the credential
10
+ * an attacker most wants, so it lasts a day — which costs nobody anything, because the refresh token silently
11
+ * renews it. That pairing is the whole reason it can be this short.
12
+ */
13
+ export declare const DEFAULT_LIFETIMES: {
14
+ readonly access: 86400;
15
+ readonly refresh: number;
16
+ readonly agent: number;
17
+ readonly widget: number;
18
+ /**
19
+ * Long enough to fetch a code out of an app, short enough that a stolen one is worthless. It authorises nothing
20
+ * on its own — only finishing the sign-in it belongs to, which still needs the code.
21
+ */
22
+ readonly mfaChallenge: 300;
23
+ /**
24
+ * The longest a session may live no matter how often it renews, counted from when it began. `0` means no cap,
25
+ * which is the default and what most deployments want: the renewal window is already an idle timeout, since a
26
+ * session nobody refreshes dies with its refresh token. This is the other half — the one that ends a session
27
+ * that has been renewing quietly for a year.
28
+ */
29
+ readonly session: 0;
30
+ };
31
+ /**
32
+ * Seconds, per credential. Written as a record of `number` rather than `Partial<typeof DEFAULT_LIFETIMES>`: the
33
+ * defaults are `as const`, so that shape narrowed every field to the literal it happens to default to and made
34
+ * `{ access: 3600 }` a type error. The option existed and could not be used.
35
+ */
36
+ export type TokenLifetimes = Partial<Record<keyof typeof DEFAULT_LIFETIMES, number>>;
37
+ /**
38
+ * The keys a deployment's credentials are signed and checked with: ES256, so checking one needs only a public key.
39
+ *
40
+ * A process that signs people in holds `signing`; one that only checks who a request is — a worker on another machine
41
+ * — holds `verifying` alone, and then cannot mint a session even if it is compromised. `verifying` lists every key a
42
+ * live credential may carry (its `kid`): the current one, and the one before it while what it signed still lives, so a
43
+ * key rotates without signing everybody out.
44
+ */
45
+ export type TokenKeys = {
46
+ signing?: {
47
+ kid: string;
48
+ privateKey: string;
49
+ };
50
+ verifying: readonly {
51
+ kid: string;
52
+ publicKey: string;
53
+ }[];
54
+ };
55
+ /**
56
+ * A new key pair for the credentials, as PEM: what a deployment generates once and keeps (its private key as a secret),
57
+ * and what a development server or a test makes for itself. `kid` names it inside every credential it signs.
58
+ */
59
+ export declare const generateTokenKeys: (kid?: string) => Required<TokenKeys>;
60
+ export type TokenConfig = {
61
+ keys: TokenKeys;
62
+ /** What this deployment mints under. Also accepted on the way back in, along with `alsoAccept`. */
63
+ issuer: string;
64
+ /** Extra issuers to honour — a migration, or a sibling deployment whose credentials are meant to work here. */
65
+ alsoAccept?: string[];
66
+ /**
67
+ * The API audiences a credential is meant for. Defaults to the issuer, which is right for the common case of a
68
+ * deployment that is its own audience — and stops it being a required field that everyone fills in by copying
69
+ * `issuer` into it.
70
+ */
71
+ audience?: string[];
72
+ lifetimes?: TokenLifetimes;
73
+ };
74
+ interface BaseClaims {
75
+ iss: string;
76
+ aud: string[];
77
+ scope: TokenScope;
78
+ /** Absent on a credential that is revoked rather than expired — see `generateSpaceToken`. */
79
+ exp?: number;
80
+ iat: number;
81
+ nbf: number;
82
+ jti: string;
83
+ }
84
+ export interface UserTokenPayload extends BaseClaims {
85
+ scope: typeof SCOPES.user;
86
+ sub: string;
87
+ /**
88
+ * Who is really behind this credential, when it is not the subject: an administrator acting AS somebody. `act` is
89
+ * the registered claim for exactly that (RFC 8693 §4.1), so a log line, an audit trail or a downstream service can
90
+ * tell a session somebody was given from one they signed into — and nothing has to invent a claim to say it.
91
+ */
92
+ act?: {
93
+ sub: string;
94
+ };
95
+ }
96
+ /** What a session credential is, beyond who it is for. */
97
+ export interface UserTokenOptions {
98
+ /** The id of whoever obtained this session on the subject's behalf. Becomes the `act` claim. */
99
+ actingAs?: number | string;
100
+ /** Overrides `lifetimes.access`. A borrowed session is worth keeping short. */
101
+ ttlSeconds?: number;
102
+ }
103
+ export interface RefreshTokenPayload extends BaseClaims {
104
+ scope: typeof SCOPES.refresh;
105
+ sub: string;
106
+ }
107
+ /** Half a sign-in: the password is proven, the second factor is not. Authorises finishing that login and nothing else. */
108
+ export interface MfaChallengePayload extends BaseClaims {
109
+ scope: typeof SCOPES.mfa;
110
+ sub: string;
111
+ }
112
+ export interface SpaceTokenPayload extends BaseClaims {
113
+ scope: typeof SCOPES.spaceRender | typeof SCOPES.spaceAgent | typeof SCOPES.spaceHost;
114
+ sub: string;
115
+ /** Web origins the space may be embedded on. No registered claim covers this. */
116
+ origins: string[];
117
+ }
118
+ /** The grant that deliberately reaches no space, so it carries no subject either. */
119
+ export interface WidgetTokenPayload extends BaseClaims {
120
+ scope: typeof SCOPES.widget;
121
+ }
122
+ export type TokenPayload = UserTokenPayload | RefreshTokenPayload | SpaceTokenPayload | WidgetTokenPayload | MfaChallengePayload;
123
+ export type VerifyResult<T> = {
124
+ ok: true;
125
+ payload: T;
126
+ } | {
127
+ ok: false;
128
+ reason: AuthFailure;
129
+ };
130
+ export interface SpaceTokenOptions {
131
+ /**
132
+ * When the token should stop working, as a unix timestamp. `null`/omitted on a `render` token means never — the
133
+ * space's choice, not a rule. An `agent` grant always gets a lifetime; only the public token may forgo one.
134
+ */
135
+ expiresAt?: number | null;
136
+ }
137
+ /**
138
+ * The credential mint and its verifier, bound to one deployment's signing key and issuer.
139
+ *
140
+ * A factory rather than a module of functions because the configuration is the deployment's: its secret, the issuer
141
+ * that separates its universe of credentials from every other, and how long each kind lives. A customer running this
142
+ * server issues under their own and nothing they mint is worth anything here, or the other way round.
143
+ */
144
+ export declare const createTokens: (config: TokenConfig) => {
145
+ lifetimes: Record<"agent" | "refresh" | "widget" | "access" | "mfaChallenge" | "session", number>;
146
+ /** What this deployment mints under. Read by anything that has to name the deployment — an enrolment URI, say. */
147
+ issuer: string;
148
+ generateUserToken: (userId: number | string, { actingAs, ttlSeconds }?: UserTokenOptions) => string;
149
+ generateRefreshToken: (userId: number | string) => string;
150
+ generateWidgetToken: () => string;
151
+ /** Says "this person proved their password"; nothing more, and only for a few minutes. */
152
+ generateMfaChallenge: (userId: number | string) => string;
153
+ /**
154
+ * A `render` token may live forever, and defaults to it, because it is embedded in a published site — often a
155
+ * SPA deployed once and left alone — where an expiry is a scheduled outage: the site breaks weeks later with
156
+ * nobody having touched anything. The deadline also buys little there, since the token is public by
157
+ * construction. What limits it is what it may do (read published content), where it may be presented (its
158
+ * declared domains), and the row behind it, which the owner can rotate or delete at any moment — revocation,
159
+ * not expiry, is the control.
160
+ *
161
+ * An `agent` grant is the opposite default and always carries a lifetime: it writes, and it is held by a
162
+ * third-party host.
163
+ *
164
+ * A `host` grant follows `render`: it only reads, it is held by the space owner's own deployment, and an expiry
165
+ * there is the same scheduled outage — except the site goes quietly STALE rather than dark, because a
166
+ * self-hosted renderer keeps serving the last copy it fetched. Being secret, it is worth rotating; being
167
+ * revocable, it does not need a deadline to be withdrawn.
168
+ */
169
+ generateSpaceToken: (spaceId: number | string, origins: string[], scope?: SpaceScope, { expiresAt }?: SpaceTokenOptions) => string;
170
+ verifyUserToken: (token: string) => VerifyResult<UserTokenPayload>;
171
+ verifyRefreshToken: (token: string) => VerifyResult<RefreshTokenPayload>;
172
+ verifyMfaChallenge: (token: string) => VerifyResult<MfaChallengePayload>;
173
+ verifyWidgetToken: (token: string) => VerifyResult<WidgetTokenPayload>;
174
+ verifySpaceToken: (token: string) => VerifyResult<SpaceTokenPayload & {
175
+ spaceId: number;
176
+ spaceScope: SpaceScope;
177
+ }>;
178
+ /**
179
+ * A token that no longer verifies for any reason the issuer can fix by re-minting — expiry, a pre-registered-
180
+ * claims shape, or an issuer from a deployment this one is not. Used by the endpoints that hand tokens back
181
+ * out, so a caller never has to know why.
182
+ */
183
+ needsRotation: (token: string) => boolean;
184
+ /** Undefined for a credential that never expires, which is what a host should read as "no renewal needed". */
185
+ expiresInSeconds: (token: string) => number | undefined;
186
+ };
187
+ export type Tokens = ReturnType<typeof createTokens>;
188
+ /** The user id a session or refresh token is about. */
189
+ export declare const userIdOf: (payload: UserTokenPayload | RefreshTokenPayload) => number;
190
+ export {};
@@ -0,0 +1,388 @@
1
+ import { SSRChangePage, SSRChangeQuery, SSRCredential, SSRGrant, SSRRequest, SSRResponseHelpers, SSRSession, SSRTemplateProps, SSRWriteContext } from './pipeline';
2
+ import { BadgeLinks, ActionEntry, ActionRunReport, ActionTaskDescriptor, AnalyticsConfig, ConnectorEntry, DataDraft, DataSaveResult, Environment, FunctionsDraft, FunctionsSaveResult, OfflineDataRaw, PluginSource, SSRRscData, SSRUser, Schema, SessionScope, Style } from '@plitzi/sdk-shared';
3
+ import { ActivityReader, SpaceActivityPage, SpaceActivityQuery } from '@plitzi/sdk-shared/activity';
4
+ import { FlagOverrides } from '@plitzi/sdk-shared/flags';
5
+ import { TSpaceEntitlements } from '@plitzi/sdk-shared/network';
6
+ /**
7
+ * A domain's own security, where its owner chose it.
8
+ *
9
+ * - `hsts`: `'host'` — browsers keep to https on this host alone; `'subdomains'` — on every sub-domain of it too, which
10
+ * on a domain of the owner's own reaches hosts this server does not serve, so it is theirs to ask for; `'off'` —
11
+ * nothing.
12
+ * - `scriptPolicy`: the page's script policy here (`SSRServerConfig.scriptPolicy`), `'off'` for none.
13
+ * - `frameAncestors`: the sites that may put this domain's pages in an iframe (`https://shop.example`), beside those the
14
+ * space allows everywhere (`SSRSpaceDeployment.frameAncestors`). A domain with any writes its cookies
15
+ * `SameSite=None`, so a visitor signed in on it is signed in inside those sites' pages too.
16
+ */
17
+ export type SSRDeploymentSecurity = {
18
+ hsts?: 'off' | 'host' | 'subdomains';
19
+ scriptPolicy?: 'off' | 'report-only' | 'enforce';
20
+ frameAncestors?: string[];
21
+ };
22
+ export type SSRSpaceDeployment = {
23
+ /** Who may put this space in an iframe, as CSP `frame-ancestors` sources (e.g. `'self'`, `https://acme.com`,
24
+ * or `*`). Resolved per space by the consumer, because only it knows the domains that space declares — a
25
+ * published space must not be framable from a site its owner never allowed. Omitted → the server's own
26
+ * `frameOptions` default stands. */
27
+ frameAncestors?: string[];
28
+ /** What this host's pages are held to, for a deployment that lets each domain say: absent, the server's own. */
29
+ security?: SSRDeploymentSecurity;
30
+ environment?: Environment;
31
+ credential?: SSRCredential;
32
+ spaceId?: number | null;
33
+ revision?: number;
34
+ /**
35
+ * What this space's feature flags are at, for a deployment that keeps them apart from its revisions — a hash that
36
+ * changes exactly when they do. Part of every cache key a render is kept under (the page, its server data, the space
37
+ * read for it), so a flag turned in production reaches the next request while the revision stays the same. Absent,
38
+ * the flags change only with the revision, and the revision alone keys the caches.
39
+ */
40
+ flagsVersion?: string;
41
+ /**
42
+ * This render is an author looking at their own work — the builder's preview — rather than a visitor being
43
+ * served. Metering skips it: nobody should be billed for editing.
44
+ *
45
+ * It is a property of HOW the request resolved, not of the environment it renders. Those two look the same
46
+ * from the render's side and are not: a space's free preview sub-domain serves the live editing environment
47
+ * to the public, so "which environment" cannot tell an author apart from a visitor. Only the resolver knows,
48
+ * which is why it says so here.
49
+ */
50
+ authoring?: boolean;
51
+ /**
52
+ * The origins of the credential that chose this space — set only when one did rather than the host (`renderGrant`):
53
+ * a page of one of them renders the space itself and is answered its document across origins.
54
+ */
55
+ grantOrigins?: string[];
56
+ /**
57
+ * What the draft (`main`) is at, when the deployment can say: changed by every write that changes what a page of it
58
+ * draws — its schema, its style, its data, its server code. With it, a draft's pages are kept like a revision's,
59
+ * under it, so a write is never answered with the page before it; without it, a draft is never kept.
60
+ */
61
+ draftVersion?: string;
62
+ /**
63
+ * How many pages of this space one process renders at once, when the deployment says (its plan's) — the server's
64
+ * `renderLimit.perSpace` otherwise, and no limit without either. A kept page takes no turn; a page past it waits
65
+ * for one (`renderLimit.waitMs`) and is answered 503 when none comes.
66
+ */
67
+ renderLimit?: number;
68
+ templateProps?: SSRTemplateProps;
69
+ pluginNames?: string[];
70
+ pluginSources?: Record<string, PluginSource>;
71
+ error?: {
72
+ code: number;
73
+ message: string;
74
+ };
75
+ };
76
+ /** Semantic + machine-readable metadata for one element type, so the MCP can tell an agent what the type DOES
77
+ * (not just that it exists) AND validate against it. `category` groups it (e.g. provider, structure, media);
78
+ * `custom` marks a plugin-provided type. The MCP keys strict-vs-lenient validation off `custom`: a `custom:false`
79
+ * (default sdk-elements) type is authoritative — an unknown attribute/setState key on it is an error — while a
80
+ * `custom:true` (plugin) type is best-effort (warnings only), since its metadata is a manifest snapshot. */
81
+ export type ComponentCatalogEntry = {
82
+ label?: string;
83
+ description?: string;
84
+ category?: string;
85
+ custom?: boolean;
86
+ /** The type's attribute/prop keys — the authoritative set for a default type (setState `key` when
87
+ * category="attribute", and type-prop validation). Absent when unknown (e.g. a plugin with no manifest). */
88
+ attributes?: string[];
89
+ /** The type's `definition.styleSelectors` keys (slots) — setState `key` when category="state" is
90
+ * `visibility` or `styleSelectors.<selector>`. */
91
+ styleSelectors?: string[];
92
+ /** The type's intrinsic base default CSS (its `defaultStyle.style.base.default`) — the declarations the element
93
+ * renders with before any class is attached, e.g. `text` defaults to `{ display: 'inline' }`. The MCP surfaces
94
+ * it so an agent styles against the real starting point instead of assuming `display: block`. */
95
+ defaultStyle?: Record<string, string>;
96
+ /** Binding targets the type exposes, from the plugin manifest's `defaultStyle.bindingsAllowed`. */
97
+ bindingsAllowed?: {
98
+ attributes?: string[];
99
+ initialState?: string[];
100
+ };
101
+ /** The attributes a role that edits the content and not the design may change: its words, a link, a
102
+ * picture. Absent, none — an element of the type is the design's alone. */
103
+ contentAttributes?: string[];
104
+ };
105
+ /** Element type → its semantic metadata, keyed by the `type` string used in the schema. Covers BOTH the default
106
+ * sdk-elements types (custom:false, authoritative) and the plugin (custom:true) element types installed on a
107
+ * space, so the MCP can validate types/attributes dynamically per space instead of against a hand-mirror. */
108
+ export type ComponentCatalog = Record<string, ComponentCatalogEntry>;
109
+ export type SSRAdapters = {
110
+ /** The space's render payload. Optional HERE and required by a page server (see {@link SSRPageAdapters}): a
111
+ * dedicated MCP server renders nothing, reads schema and style through its own adapters, and had to hand this
112
+ * one over anyway for the type to be satisfied — an adapter it never called. */
113
+ getOfflineData?: (spaceId: number, environment: string, revision?: number) => Promise<OfflineDataRaw | undefined>;
114
+ /**
115
+ * Which space, environment and revision a request resolves to. Optional here for the same reason as
116
+ * `getOfflineData`: MCP resolves its space from the request token (`getGrant`), never from the host.
117
+ *
118
+ * Asked on EVERY request, not only a page's: what the page fetches after it — `/_plitzi/space/<hash>.json`, `/_action`,
119
+ * `/fn/…`, `/_realtime` — is resolved again, and carries nothing of the page's address but its host (and the
120
+ * visitor's credentials). So a space is chosen by the host — a domain, a sub-domain (`wildcardSubdomain`) — or by a
121
+ * credential (`authoringPreview`): one chosen by the page's path or query is lost on the requests that follow it.
122
+ */
123
+ getSpaceDeployment?: (req: SSRRequest) => Promise<SSRSpaceDeployment>;
124
+ /** Resolve the grant the MCP request operates under, from the verified `Authorization` bearer. The consumer
125
+ * owns the JWT secret and the authorization model, so it decides here; the MCP service stays stateless.
126
+ * Returns undefined when the token is missing or invalid. Required for the `mcp` service to serve any
127
+ * request. `canWrite` is what separates a read-only bearer from one that may change the space — the MCP
128
+ * refuses every write tool without it, and never infers the answer from the token itself. */
129
+ getGrant?: (req: SSRRequest) => Promise<SSRGrant | undefined>;
130
+ /**
131
+ * Whether the tool calls a request carries may run — asked once per request that makes any, with how many it makes.
132
+ * A refusal's `error` is what the agent reads as each call's result, so it says why and the way past it (a plan's
133
+ * daily ceiling, say). Omitted, every call runs.
134
+ */
135
+ admitToolCalls?: (req: SSRRequest, calls: number) => Promise<{
136
+ error: string;
137
+ } | undefined>;
138
+ /** Read the element schema for the MCP tools. Separate from `getOfflineData` (which is SSR/RSC shaped and
139
+ * strips `style.platform`); the MCP style resource needs the full documents, so schema and style split. */
140
+ getSchema?: (spaceId: number, environment: Environment) => Promise<Schema | undefined>;
141
+ /** Read the full style document (with `platform`/`mode`, which the MCP definitions resource requires). */
142
+ getStyle?: (spaceId: number, environment: Environment) => Promise<Style | undefined>;
143
+ /** Read the semantic catalog of the space's PLUGIN (custom) element types — label/description/category from
144
+ * each installed plugin's manifest — so the MCP `plitzi://types` resource can explain what custom elements do.
145
+ * The MCP already knows the built-in types. When omitted, custom types surface with their observed label only. */
146
+ getComponentCatalog?: (spaceId: number, environment: Environment) => Promise<ComponentCatalog | undefined>;
147
+ /** Read every connector configured for the space, so the MCP can list them and author provider elements against
148
+ * them. Connectors are space-level (not per environment) server-side state: the manifests name endpoints and an
149
+ * auth scheme, so this must never feed a browser payload. When omitted, the MCP's connector resource is empty
150
+ * and a provider element cannot be checked against the connector it names. */
151
+ getConnectors?: (spaceId: number) => Promise<ConnectorEntry[] | undefined>;
152
+ /** Create or replace one connector, keyed by `entry.id`. When omitted, connector ops apply in memory only and
153
+ * `apply` reports `persisted: false`. */
154
+ saveConnector?: (spaceId: number, entry: ConnectorEntry) => Promise<void>;
155
+ /** Remove one connector by its identifier. Omitted alongside `saveConnector` for a read-only deployment. */
156
+ deleteConnector?: (spaceId: number, connectorId: string) => Promise<void>;
157
+ /** Read every server action configured for the space, so the MCP can list them and author flows against them.
158
+ * Space-level server-side state like connectors: the documents name credentials, connectors and steps, so this
159
+ * must never feed a browser payload. When omitted, the MCP's action resource is empty. */
160
+ getActions?: (spaceId: number) => Promise<ActionEntry[] | undefined>;
161
+ /** The server tasks a flow can be built from — what THIS deployment can run, which is the SDK's built-ins plus
162
+ * whatever tasks it registered. Shaped as `ActionTaskDescriptor` in `@plitzi/sdk-actions`. Without it an
163
+ * agent authoring an action is guessing at the step vocabulary. */
164
+ getActionTasks?: (spaceId: number) => Promise<ActionTaskDescriptor[] | undefined>;
165
+ /** What the space's plan includes (`TSpaceEntitlements`), for the primer to say before an agent plans work the space
166
+ * cannot ship. Omitted — a self-hosted deployment — everything is included and the primer says nothing of a plan. */
167
+ getEntitlements?: (spaceId: number) => Promise<TSpaceEntitlements | undefined>;
168
+ /** Create or replace one action, keyed by `entry.id`. When omitted, action ops apply in memory only and `apply`
169
+ * reports `persisted: false`. */
170
+ saveAction?: (spaceId: number, entry: ActionEntry) => Promise<void>;
171
+ /** Remove one action by its identifier. Omitted alongside `saveAction` for a read-only deployment. */
172
+ deleteAction?: (spaceId: number, actionId: string) => Promise<void>;
173
+ /** The space's own functions: the draft's source files, which copy of them it is and what they declare.
174
+ * Server-side code like the actions it serves — never a browser payload. When omitted, the MCP offers no functions
175
+ * resource and refuses the function ops. */
176
+ getFunctions?: (spaceId: number) => Promise<FunctionsDraft | undefined>;
177
+ /** Save the draft's functions, whole. The deployment builds and checks them and answers what is wrong where it is;
178
+ * `base` is the version the agent read, and a draft that moved on since is refused rather than overwritten. */
179
+ saveFunctions?: (spaceId: number, files: Record<string, string>, base: string, write: SSRWriteContext) => Promise<FunctionsSaveResult>;
180
+ /** Run one task of the draft's functions in the sandbox for the person behind the agent — the builder's Try. */
181
+ tryFunction?: (spaceId: number, task: string, params: Record<string, unknown>, write: SSRWriteContext) => Promise<ActionRunReport>;
182
+ /**
183
+ * Play the space's e2e tests on its draft, in a browser of the deployment's — those named, or all: each
184
+ * test's result, or why none was run there. When omitted, an agent's e2e tests are said as not run.
185
+ */
186
+ runE2eTests?: (spaceId: number, ids: readonly string[]) => Promise<{
187
+ results: unknown[];
188
+ } | {
189
+ notRun: string;
190
+ }>;
191
+ /** The space's own data: the draft's JSON files its server providers read (`/data/<file>`), and which copy they are.
192
+ * When omitted, the MCP offers no data resource and refuses the data ops. */
193
+ getData?: (spaceId: number) => Promise<DataDraft | undefined>;
194
+ /** Save the draft's data, whole: every file JSON at a plain path. `base` is the version the agent read, and data that
195
+ * moved on since is refused rather than overwritten. */
196
+ saveData?: (spaceId: number, files: Record<string, string>, base: string, write: SSRWriteContext) => Promise<DataSaveResult>;
197
+ /** Persist the element schema mutated by the MCP `apply` tool. When omitted, `apply` reports `persisted: false`. */
198
+ saveSchema?: (spaceId: number, environment: Environment, schema: Schema, write: SSRWriteContext) => Promise<void>;
199
+ /** Persist the style document mutated by the MCP `apply` tool — store it as given. `style.cache` arrives already
200
+ * compiled: the renderer serves that string and nothing else, so recomputing it is not a detail to delegate, and
201
+ * asking every deployment to remember it was one bug each of them could write alone. When omitted, `apply`
202
+ * reports `persisted: false`. */
203
+ saveStyle?: (spaceId: number, environment: Environment, style: Style, write: SSRWriteContext) => Promise<void>;
204
+ /** The space's change history, read-only: what every writer saved, and for whom. When omitted, the MCP offers no
205
+ * history resource. */
206
+ getChanges?: (spaceId: number, environment: Environment, query: SSRChangeQuery) => Promise<SSRChangePage>;
207
+ /** What happened on the space after a cursor — the draft changed, a version went out, an action failed — waiting up
208
+ * to `query.wait` seconds when nothing has yet. `reader` is who asks, so their own writes can be left out; `signal`
209
+ * ends the wait when the client goes. When omitted, the MCP offers no `plitzi_activity`. */
210
+ getActivity?: (spaceId: number, query: SpaceActivityQuery, reader: ActivityReader, signal?: AbortSignal) => Promise<SpaceActivityPage>;
211
+ /**
212
+ * Who this request carries, if anyone. The adapter reads the credential and resolves it; the cookie it arrived in
213
+ * was written by the server, from {@link SSRAuthCookie}.
214
+ *
215
+ * `res` is the response this request is answered with, when there is one: a session cookie the identity finds over
216
+ * for good — revoked, ended, never a token at all — is cleared on it, the readable hint with it. Left in place, the
217
+ * hint tells the browser it still holds a session, the browser restores the token it kept, and a page for signed-out
218
+ * visitors sends it on to one that sends it straight back, for ever.
219
+ */
220
+ getUser?: (req: SSRRequest, res?: SSRResponseHelpers) => Promise<SSRUser | undefined>;
221
+ /**
222
+ * Verify credentials and mint a session — identity, and nothing else. The server writes the cookies, clears them,
223
+ * and keeps the readable hint in step, because those are properties of how sessions travel rather than of who
224
+ * anyone is. A deployment bringing its own user database implements this and gets the rest for free.
225
+ *
226
+ * Return undefined to refuse. Never throw for a wrong password.
227
+ */
228
+ authenticate?: (credentials: Record<string, string>, req: SSRRequest) => Promise<SSRSession | undefined>;
229
+ /** Revoke whatever session this request carries, at the source. The cookies are the server's to clear. */
230
+ endSession?: (req: SSRRequest) => Promise<void>;
231
+ /**
232
+ * Sign the person this request carries out on every device: `site`, of the sessions signed in on this request's host
233
+ * (a space's own — its visitors' sign-out everywhere); `all`, of every session of the account. Answers whether one was
234
+ * carried: nobody signed in has nothing to end. The cookies are the server's to clear.
235
+ */
236
+ endSessions?: (req: SSRRequest, scope: SessionScope) => Promise<boolean>;
237
+ /**
238
+ * Turn a credential the browser obtained from an identity provider into a session here — see the exchange stage.
239
+ * Everything that decides whether it is any good lives in this adapter, because only the deployment knows:
240
+ *
241
+ * - which providers it trusts, and which one the space in question actually signs people in with;
242
+ * - that the token was minted for **this** application. Anyone who has signed into any other site with the same
243
+ * provider holds a valid token for that user, so accepting one merely because the provider recognises it lets
244
+ * that site sign in here as them. A provider that cannot prove it must be refused outright.
245
+ */
246
+ exchangeCredential?: (provider: string, token: string, req: SSRRequest) => Promise<{
247
+ ok: true;
248
+ session: SSRSession;
249
+ user?: SSRUser;
250
+ } | {
251
+ ok: false;
252
+ error: string;
253
+ status?: number;
254
+ reason?: string;
255
+ }>;
256
+ /** Called by the RSC endpoint, and once per page render, to fetch server-side data for server components.
257
+ * See {@link SSRRscContext} for what it is given. */
258
+ getRscData?: (context: SSRRscContext) => Promise<SSRRscData>;
259
+ /**
260
+ * One billable server request. This is where a deployment meters usage, because these are the moments it
261
+ * actually spends bandwidth on a visitor and the ones a visitor cannot reach around: the browser is told
262
+ * what happened, never asked. Each runs before its cache is consulted, so a cached response still counts.
263
+ *
264
+ * What comes back shapes the response — degrade the free tier, hand the browser its reporting channel — and
265
+ * a deployment that meters nothing simply omits the adapter. Never throw from here: a metering outage must
266
+ * not take a site down, so failures should degrade to "served, uncounted".
267
+ */
268
+ meter?: (event: SSRMeterEvent) => Promise<SSRMeterDecision | undefined>;
269
+ /**
270
+ * What a page's script policy refused, or would have refused while it only reports — for the space the report's host
271
+ * serves, never one the report names (anyone may post one). Said once per space and violation in a while, not on
272
+ * every page a visitor opens (`cspReportStage`). Where a deployment keeps them to show the space's owner what turning
273
+ * the policy on would stop; it says nothing back, and a failure here loses that report alone.
274
+ */
275
+ recordScriptPolicyReport?: (report: SSRScriptPolicyReport) => Promise<void>;
276
+ };
277
+ /** One thing a page's script policy refused, or would refuse, as the browser reported it. */
278
+ export type SSRScriptPolicyReport = {
279
+ spaceId: number;
280
+ environment: Environment;
281
+ /** The page it was on, without its query. */
282
+ page: string;
283
+ /** What was refused: a URL, `inline`, `eval`, `trusted-types-sink`… as the browser names it. */
284
+ blocked: string;
285
+ /** The directive that refused it: `script-src-elem`, `require-trusted-types-for`… */
286
+ directive: string;
287
+ /** Where it was written, `file:line`, when the browser says. */
288
+ source: string;
289
+ /** The first characters of an inline script or a sink's value, when the browser says. */
290
+ sample: string;
291
+ /** `report` while the policy only reports; `enforce` once it refused it. */
292
+ disposition: 'report' | 'enforce';
293
+ };
294
+ /**
295
+ * Which area of server work is being metered. One name per area, because that is the unit a deployment prices
296
+ * — a full page render does not cost what a partial data refresh costs, and both are cheaper when a cache
297
+ * answered them than when the origin did.
298
+ */
299
+ export type MeteredKind = 'page_view' | 'rsc_query'
300
+ /** Reserved: nothing emits this yet. Server actions are not implemented — the area exists so wiring them
301
+ * later is a call site, not a schema change. */
302
+ | 'server_action';
303
+ /** The request being metered, for {@link SSRAdapters.meter}. */
304
+ export interface SSRMeterEvent {
305
+ kind: MeteredKind;
306
+ /**
307
+ * Whether a cache answered this instead of the origin. Reported rather than inferred: only the handler knows,
308
+ * it is the same fact the response puts on the wire as `X-Cache: HIT`, and what it is worth is the
309
+ * deployment's to decide — an area may price a hit lower, or not distinguish one at all.
310
+ */
311
+ cached: boolean;
312
+ req: SSRRequest;
313
+ spaceId: number;
314
+ environment: Environment;
315
+ revision: number;
316
+ }
317
+ /** What the deployment decided about this request. */
318
+ export type SSRMeterDecision = {
319
+ /** This space is over the quota its plan allows and the render should say so — the "Made with Plitzi" badge
320
+ * on the free tier. Paid plans accrue overage instead and never set this. */
321
+ degrade?: boolean;
322
+ /**
323
+ * The deployment's "Made with Plitzi" badge on this render — its attribution, on a plan that does not remove it —
324
+ * and where it leads: the deployment's own addresses, its report page naming the page reported.
325
+ */
326
+ badge?: BadgeLinks;
327
+ /**
328
+ * This space has nearly spent its plan's allowance and the render should say so, calmly — before `degrade` would. The
329
+ * deployment decides where: Plitzi says it on the shared domain, where the visitor is the one who might tell the owner.
330
+ */
331
+ quotaNear?: boolean;
332
+ /**
333
+ * This page is sent `X-Robots-Tag: noindex`: an address the deployment does not mean to host a site on — a free
334
+ * sub-domain — kept out of search results, where an abused one would do the most harm.
335
+ */
336
+ noindex?: boolean;
337
+ /**
338
+ * The deployment does not serve this page right now, and these are the words its visitor reads instead: the page is
339
+ * answered 503, never rendered, cached or indexed — an address the deployment holds back, as a free site whose
340
+ * owner has not confirmed their email.
341
+ */
342
+ unavailable?: string;
343
+ /** Client reporting channel, injected into the page bootstrap. Omitted → the page reports nothing. Only a
344
+ * page render has anywhere to put it; the other kinds answer data, not a document. */
345
+ analytics?: AnalyticsConfig;
346
+ };
347
+ /** What a server that RENDERS PAGES must answer: the two adapters every page request goes through, on top of the
348
+ * optional rest. Stated as its own type rather than by making them required for everyone, because "required" is
349
+ * a property of the surface being served and not of the adapter set — a dedicated MCP server has no page request
350
+ * to resolve, and the old shape made it hand over two adapters nothing would ever call. */
351
+ export type SSRPageAdapters = SSRAdapters & Required<Pick<SSRAdapters, 'getOfflineData' | 'getSpaceDeployment'>>;
352
+ /**
353
+ * Everything an RSC read is given: which space and revision, who is asking, and which elements want data.
354
+ *
355
+ * One object rather than six positional parameters, because the reason to add to it is exactly the reason the
356
+ * positional form failed — `loadOfflineData` is a seventh thing to know, and nobody should have to count commas to
357
+ * reach it, nor rewrite their adapter when an eighth arrives.
358
+ */
359
+ export interface SSRRscContext {
360
+ req: SSRRequest;
361
+ spaceId: number;
362
+ environment: Environment;
363
+ revision: number;
364
+ /** Whoever the request carries, already resolved. */
365
+ user?: SSRUser;
366
+ /** On a partial refresh, the only element ids that want data. Absent means every one — the initial render. */
367
+ ids?: string[];
368
+ /**
369
+ * The space itself, read at most once per request however many times this is called.
370
+ *
371
+ * It is here because an adapter almost always needs the schema (to know which elements are server-rendered, or
372
+ * whether RSC is on at all) and the server is already loading it for the page — in parallel with this very call.
373
+ * Without a shared handle every deployment fetched it a second time, or wrote its own in-flight dedup to avoid
374
+ * doing so. Awaiting this joins the read already under way; it never starts a second one.
375
+ */
376
+ loadOfflineData: () => Promise<OfflineDataRaw | undefined>;
377
+ /**
378
+ * What the layers above the space decide about its flags for this request: the server's own and, on a page allowed
379
+ * to debug, a tester's. An element gated off by a flag is not resolved — `resolveRscData` resolves the flags
380
+ * against the page it matched and skips it — so a feature that is off puts nothing in the payload.
381
+ */
382
+ flagOverrides?: FlagOverrides;
383
+ /**
384
+ * Aborted when whoever asked stops waiting — a browser that hung up, a refresh superseded by a newer one, a STOP — so
385
+ * what it asked for stops being worked on, here and in the runs it started.
386
+ */
387
+ signal?: AbortSignal;
388
+ }