@plitzi/sdk-server 0.38.13 → 0.38.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +255 -0
- package/README.md +81 -7
- package/dist/core/auth/createAuth.d.ts +5 -0
- package/dist/core/auth/createAuth.js +5 -0
- package/dist/core/auth/csrf.d.ts +25 -0
- package/dist/core/auth/csrf.js +34 -32
- package/dist/core/auth/session.d.ts +10 -2
- package/dist/core/auth/session.js +31 -6
- package/dist/core/createServer.js +4 -0
- package/dist/core/http/stages/authRoutes.js +3 -0
- package/dist/core/http/stages/crossSiteWrites.d.ts +23 -0
- package/dist/core/http/stages/crossSiteWrites.js +44 -0
- package/dist/core/http/stages/crossSiteWrites.test.d.ts +1 -0
- package/dist/core/http/stages/exchangeRoute.js +2 -0
- package/dist/core/http/stages/sessionRenewal.js +2 -1
- package/dist/core/http/stages/signInRoute.js +1 -1
- package/dist/core/http/stages/static.js +1 -1
- package/dist/core/mimeTypes.d.ts +10 -1
- package/dist/core/mimeTypes.js +2 -1
- package/dist/core/oauth/authorize.js +2 -1
- package/dist/core/requestParser.d.ts +6 -0
- package/dist/core/requestParser.js +8 -2
- package/dist/core/requestParser.test.d.ts +1 -0
- package/dist/core/server/fleet/link.d.ts +1 -1
- package/dist/core/server/fleet/stores.js +1 -1
- package/dist/core/services/action.js +1 -1
- package/dist/core/services/realtime.js +1 -1
- package/dist/core/services/registry.js +2 -0
- package/dist/core/staticFiles.d.ts +2 -1
- package/dist/core/staticFiles.js +5 -5
- package/dist/functions-api.d.ts +5 -2
- package/dist/helpers/cache/keys.d.ts +1 -0
- package/dist/helpers/cache/keys.js +4 -3
- package/dist/helpers/flagOverrides.d.ts +2 -0
- package/dist/helpers/flagOverrides.js +2 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -1
- package/dist/modules/actions/tasks/realtime.js +1 -1
- package/dist/modules/authoringHost/index.d.ts +49 -0
- package/dist/modules/authoringHost/index.js +113 -0
- package/dist/modules/authoringHost/index.test.d.ts +1 -0
- package/dist/modules/functions/contract.d.ts +5 -2
- package/dist/modules/project/serveProject.d.ts +3 -2
- package/dist/modules/project/serveProject.js +85 -15
- package/dist/modules/realtime/hub.d.ts +7 -2
- package/dist/modules/realtime/hub.js +8 -4
- package/dist/modules/realtime/index.js +14 -7
- package/dist/modules/realtime/message.d.ts +3 -0
- package/dist/modules/realtime/message.js +5 -0
- package/dist/modules/realtime/retained.d.ts +24 -0
- package/dist/modules/realtime/retained.js +47 -0
- package/dist/modules/realtime/retained.test.d.ts +1 -0
- package/dist/modules/realtime/socket.js +1 -1
- package/dist/modules/rsc/handler.js +2 -1
- package/dist/modules/runtime/elsewhere.test.d.ts +1 -0
- package/dist/modules/runtime/inside.d.ts +21 -0
- package/dist/modules/runtime/inside.js +51 -3
- package/dist/modules/runtime/ownServer.test.d.ts +1 -0
- package/dist/modules/runtime/stages.d.ts +4 -1
- package/dist/modules/ssr/prepareRender.js +3 -2
- package/dist/modules/ssr/spaceDocument.js +5 -1
- package/dist/plugins/manager.d.ts +9 -0
- package/dist/plugins/manager.js +43 -1
- package/dist/runtime.d.ts +2 -1
- package/dist/runtime.js +2 -2
- package/package.json +3 -3
- package/skills/plitzi-authoring/SKILL.md +1 -1
- package/skills/plitzi-authoring/reference/index.md +3 -2
- package/skills/plitzi-authoring/reference/layouts.md +10 -0
- package/skills/plitzi-authoring/reference/plugin-reach.md +91 -0
- package/skills/plitzi-authoring/reference/plugins.md +19 -35
- package/skills/plitzi-authoring/reference/realtime.md +11 -0
- package/skills/plitzi-authoring/reference/testing.md +3 -1
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { X509Certificate } from "node:crypto";
|
|
1
2
|
import net from "node:net";
|
|
3
|
+
import tls from "node:tls";
|
|
2
4
|
//#region src/modules/runtime/inside.ts
|
|
3
5
|
/** Headers as a dispatch carries them — a record, name/value pairs flattened into one list, or pairs — plus one more. */
|
|
4
6
|
var withHeader = (headers, name, value) => {
|
|
@@ -12,6 +14,12 @@ var withHeader = (headers, name, value) => {
|
|
|
12
14
|
};
|
|
13
15
|
};
|
|
14
16
|
/**
|
|
17
|
+
* How every OTHER host is reached once one of these dispatchers is the process's: as Node's own `fetch` reaches it,
|
|
18
|
+
* over HTTP/1.1. An undici connector offers HTTP/2 by default, and an answer that came back over h2 reached Node's
|
|
19
|
+
* `fetch` without its `content-encoding` — so nothing decoded it, and every API that compresses read as Brotli bytes.
|
|
20
|
+
*/
|
|
21
|
+
var elsewhere = (undici) => undici.buildConnector({ allowH2: false });
|
|
22
|
+
/**
|
|
15
23
|
* The space's own public address, reached from inside the network this runtime runs in: every request this process
|
|
16
24
|
* makes to the space's host — `fetch` and `WebSocket` alike, which share Node's dispatcher — connects to `insideUrl`
|
|
17
25
|
* instead, over plain HTTP, the space's host and the public protocol kept (`X-Forwarded-Proto`). It is the path a
|
|
@@ -26,10 +34,11 @@ var reachSpaceInside = async ({ publicUrl, insideUrl }) => {
|
|
|
26
34
|
const outside = new URL(publicUrl);
|
|
27
35
|
const inside = new URL(insideUrl);
|
|
28
36
|
if (inside.protocol !== "http:") throw new Error(`A space is reached from inside over plain HTTP, not ${inside.protocol} (${insideUrl})`);
|
|
29
|
-
const
|
|
37
|
+
const undici = await import("undici");
|
|
38
|
+
const { Agent, setGlobalDispatcher } = undici;
|
|
30
39
|
const port = Number(inside.port || 80);
|
|
31
40
|
const protocol = outside.protocol.replace(":", "");
|
|
32
|
-
const connect =
|
|
41
|
+
const connect = elsewhere(undici);
|
|
33
42
|
setGlobalDispatcher(new Agent({ connect: (options, callback) => {
|
|
34
43
|
if (options.hostname !== outside.hostname) {
|
|
35
44
|
connect(options, callback);
|
|
@@ -43,5 +52,44 @@ var reachSpaceInside = async ({ publicUrl, insideUrl }) => {
|
|
|
43
52
|
headers: withHeader(options.headers, "x-forwarded-proto", protocol)
|
|
44
53
|
} : options, handler)));
|
|
45
54
|
};
|
|
55
|
+
/**
|
|
56
|
+
* A self-hosted server serving TLS itself, reached from its own process — the runtime calling its own MCP, a function
|
|
57
|
+
* calling a route of its own space: every request to its public address connects to its listener on this machine.
|
|
58
|
+
*
|
|
59
|
+
* Its certificate is usually a local one (mkcert, for a tablet on the Wi-Fi), which the browsers on that network were
|
|
60
|
+
* told to trust and Node was not, so these requests failed whatever the address said. They are taken when the peer
|
|
61
|
+
* presents exactly this server's certificate — its fingerprint, not a chain — and refused otherwise; nothing else the
|
|
62
|
+
* process reaches is verified any less.
|
|
63
|
+
*/
|
|
64
|
+
var reachOwnServer = async ({ publicUrl, listener, cert }) => {
|
|
65
|
+
const outside = new URL(publicUrl);
|
|
66
|
+
const outsidePort = outside.port || (outside.protocol === "https:" ? "443" : "80");
|
|
67
|
+
const own = new X509Certificate(cert).fingerprint256;
|
|
68
|
+
const undici = await import("undici");
|
|
69
|
+
const { Agent, setGlobalDispatcher } = undici;
|
|
70
|
+
const connect = elsewhere(undici);
|
|
71
|
+
setGlobalDispatcher(new Agent({ connect: (options, callback) => {
|
|
72
|
+
if (options.hostname !== outside.hostname || (options.port || outsidePort) !== outsidePort) {
|
|
73
|
+
connect(options, callback);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const socket = tls.connect({
|
|
77
|
+
host: listener.host,
|
|
78
|
+
port: listener.port,
|
|
79
|
+
...net.isIP(outside.hostname) ? {} : { servername: outside.hostname },
|
|
80
|
+
ALPNProtocols: ["http/1.1"],
|
|
81
|
+
rejectUnauthorized: false
|
|
82
|
+
});
|
|
83
|
+
socket.once("secureConnect", () => {
|
|
84
|
+
if (socket.getPeerX509Certificate()?.fingerprint256 !== own) {
|
|
85
|
+
socket.destroy();
|
|
86
|
+
callback(/* @__PURE__ */ new Error(`${outside.host} answered with a certificate that is not this server's`), null);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
callback(null, socket);
|
|
90
|
+
});
|
|
91
|
+
socket.once("error", (error) => callback(error, null));
|
|
92
|
+
} }));
|
|
93
|
+
};
|
|
46
94
|
//#endregion
|
|
47
|
-
export { reachSpaceInside };
|
|
95
|
+
export { reachOwnServer, reachSpaceInside };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -7,7 +7,10 @@ export declare const runtimeEndpointsStage: (endpoints: Record<string, SpaceRunt
|
|
|
7
7
|
export type ServedRuntime = {
|
|
8
8
|
/** Its tasks and routes, for `functions.native`. */
|
|
9
9
|
native: FunctionsDefinition[];
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* Its endpoints, for `data` — where the platform forwards a space's: behind the auth chain and the cross-site guard,
|
|
12
|
+
* gating who may call them themselves.
|
|
13
|
+
*/
|
|
11
14
|
stage: Stage<SSRContext>;
|
|
12
15
|
close: () => Promise<void>;
|
|
13
16
|
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { requestAuthority } from "../../core/requestParser.js";
|
|
1
2
|
import { requestFlagOverrides } from "../../helpers/flagOverrides.js";
|
|
2
3
|
import { authorizesDebugging } from "../../helpers/debugAuthorization.js";
|
|
3
4
|
import { SPACE_TOKEN_PARAM } from "../../core/auth/credentials.js";
|
|
@@ -119,7 +120,7 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
|
|
|
119
120
|
* so does the space itself (`settings.debugMode`) — an owner inspecting their own published site. The space is read
|
|
120
121
|
* from what this server loaded, never from the request, so a visitor has no say in it.
|
|
121
122
|
*/
|
|
122
|
-
const debugRendered = resolveDebugMode(debugAuthorized, readCookie(req.headers.cookie, debugCookieName(req
|
|
123
|
+
const debugRendered = resolveDebugMode(debugAuthorized, readCookie(req.headers.cookie, debugCookieName(requestAuthority(req))));
|
|
123
124
|
/**
|
|
124
125
|
* The runs this render's server elements started, handed to a page that may debug them — and to no other.
|
|
125
126
|
*
|
|
@@ -159,7 +160,7 @@ var prepareRender = async (req, config, spaceId, environment, revision, pluginMa
|
|
|
159
160
|
* travels as the SDK's `state`, the starting `runtime.state`, in the render and in the payload alike, or the client
|
|
160
161
|
* would hydrate other markup. Only the keys the space declares, and only with `keepState` on.
|
|
161
162
|
*/
|
|
162
|
-
const paintedState = schema?.settings.keepState ? paintedStateFor(req.headers.cookie, ssrPaintedCookieName(req
|
|
163
|
+
const paintedState = schema?.settings.keepState ? paintedStateFor(req.headers.cookie, ssrPaintedCookieName(requestAuthority(req)), paintedKeys(schema.settings)) : void 0;
|
|
163
164
|
/**
|
|
164
165
|
* The two layers of the space's flags this server answers for. Its own (`config.flags`), asked per space when it
|
|
165
166
|
* serves several; and the ones a tester forced from the dev tools, read from their cookie — only for a page allowed
|
|
@@ -56,7 +56,11 @@ var handleSpaceDocument = async (req, res, config, offlineDataCache) => {
|
|
|
56
56
|
const offlineData = cached ? JSON.parse(cached) : await config.adapters.getOfflineData(spaceId, environment, revision);
|
|
57
57
|
if (!offlineData) {
|
|
58
58
|
res.setStatus(404);
|
|
59
|
-
res.
|
|
59
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
60
|
+
res.send(JSON.stringify({
|
|
61
|
+
error: `This request resolves to space ${String(spaceId)} (${environment}), which has no data: getSpaceDeployment chose it from what this request carries — its host and credentials, never the page’s path or query`,
|
|
62
|
+
reason: "not_found"
|
|
63
|
+
}));
|
|
60
64
|
return;
|
|
61
65
|
}
|
|
62
66
|
const document = spaceDocument(offlineData);
|
|
@@ -12,6 +12,8 @@ export declare class PluginManager {
|
|
|
12
12
|
private readonly devMode;
|
|
13
13
|
/** Who is told what each built plugin was built from — a dev server's watcher (`watchPluginSources`). */
|
|
14
14
|
private readonly sourceListeners;
|
|
15
|
+
/** The bundles being built again because they vanished from disk under this server — see `restore`. */
|
|
16
|
+
private restoring?;
|
|
15
17
|
constructor(plugins: Record<string, PluginSource>, cacheDir?: string, ttlMs?: number, devMode?: boolean);
|
|
16
18
|
/**
|
|
17
19
|
* Tells `listener` the files every built plugin was built from — those built so far, at once, and each one built or
|
|
@@ -108,6 +110,13 @@ export declare class PluginManager {
|
|
|
108
110
|
*/
|
|
109
111
|
prepareAll(): Promise<void>;
|
|
110
112
|
prepare(name: string): Promise<PluginEntry | null>;
|
|
113
|
+
/**
|
|
114
|
+
* Bundles that vanished from disk under a running server are built again as one episode: said once when the first
|
|
115
|
+
* is noticed and once when the last is built — how many, how long, which failed — at the level it was noticed at.
|
|
116
|
+
* Said per plugin, it was a warning for each and a "ready" for each at a level a project's terminal does not show,
|
|
117
|
+
* so the rebuild never said it had finished.
|
|
118
|
+
*/
|
|
119
|
+
private restore;
|
|
111
120
|
private build;
|
|
112
121
|
getEntries(names: string[]): Promise<PluginEntry[]>;
|
|
113
122
|
getComponents(): Record<string, unknown>;
|
package/dist/plugins/manager.js
CHANGED
|
@@ -11,6 +11,8 @@ import path from "node:path";
|
|
|
11
11
|
var META_FILE = "meta.json";
|
|
12
12
|
var DEFAULT_TTL_MS = 6048e5;
|
|
13
13
|
var DEFAULT_CACHE_DIR = "tmp/.sdk-plugins";
|
|
14
|
+
/** How long a rebuild of vanished bundles waits, once none is pending, for another of the same render to be noticed. */
|
|
15
|
+
var RESTORE_SETTLE_MS = 100;
|
|
14
16
|
/** One hash over every input's path and content — a file gone counts as changed, like a file edited. */
|
|
15
17
|
var digestOf = async (files) => {
|
|
16
18
|
const hash = createHash("sha256");
|
|
@@ -49,6 +51,8 @@ var PluginManager = class {
|
|
|
49
51
|
devMode = false;
|
|
50
52
|
/** Who is told what each built plugin was built from — a dev server's watcher (`watchPluginSources`). */
|
|
51
53
|
sourceListeners = /* @__PURE__ */ new Set();
|
|
54
|
+
/** The bundles being built again because they vanished from disk under this server — see `restore`. */
|
|
55
|
+
restoring;
|
|
52
56
|
constructor(plugins, cacheDir, ttlMs, devMode = false) {
|
|
53
57
|
assertPluginSources(plugins);
|
|
54
58
|
this.plugins = plugins;
|
|
@@ -262,6 +266,7 @@ var PluginManager = class {
|
|
|
262
266
|
if (isComponentSource(source) && !source.js) return this.toEntry(key, false, void 0, source.props);
|
|
263
267
|
if (!isComponentSource(source) && source.action === "cdn") return this.toRemoteEntry(key, source);
|
|
264
268
|
const cached = this.mem.get(key);
|
|
269
|
+
let missing = false;
|
|
265
270
|
if (cached && !this.isExpired(cached.compiledAt)) {
|
|
266
271
|
if (await this.fileExists(path.join(this.pluginDir(key), "index.js"))) {
|
|
267
272
|
/**
|
|
@@ -278,8 +283,9 @@ var PluginManager = class {
|
|
|
278
283
|
force: true
|
|
279
284
|
});
|
|
280
285
|
} else {
|
|
281
|
-
serverLog.
|
|
286
|
+
serverLog.info("SSR", `Plugin "${key}" output missing, rebuilding…`);
|
|
282
287
|
this.mem.delete(key);
|
|
288
|
+
missing = true;
|
|
283
289
|
}
|
|
284
290
|
}
|
|
285
291
|
const meta = await this.readMeta(key);
|
|
@@ -315,8 +321,44 @@ var PluginManager = class {
|
|
|
315
321
|
}
|
|
316
322
|
const promise = this.build(key, source).finally(() => this.inflight.delete(key));
|
|
317
323
|
this.inflight.set(key, promise);
|
|
324
|
+
if (missing) this.restore(key, promise);
|
|
318
325
|
return promise;
|
|
319
326
|
}
|
|
327
|
+
/**
|
|
328
|
+
* Bundles that vanished from disk under a running server are built again as one episode: said once when the first
|
|
329
|
+
* is noticed and once when the last is built — how many, how long, which failed — at the level it was noticed at.
|
|
330
|
+
* Said per plugin, it was a warning for each and a "ready" for each at a level a project's terminal does not show,
|
|
331
|
+
* so the rebuild never said it had finished.
|
|
332
|
+
*/
|
|
333
|
+
restore(key, build) {
|
|
334
|
+
if (!this.restoring) {
|
|
335
|
+
this.restoring = {
|
|
336
|
+
started: Date.now(),
|
|
337
|
+
pending: /* @__PURE__ */ new Set(),
|
|
338
|
+
rebuilt: 0,
|
|
339
|
+
failed: []
|
|
340
|
+
};
|
|
341
|
+
const where = path.relative(process.cwd(), this.outputDir) || this.outputDir;
|
|
342
|
+
serverLog.warn("SSR", `Plugin bundles missing from ${where}: building them again…`);
|
|
343
|
+
}
|
|
344
|
+
const episode = this.restoring;
|
|
345
|
+
clearTimeout(episode.closing);
|
|
346
|
+
episode.pending.add(key);
|
|
347
|
+
build.then((entry) => {
|
|
348
|
+
episode.pending.delete(key);
|
|
349
|
+
if (entry) episode.rebuilt += 1;
|
|
350
|
+
else episode.failed.push(key);
|
|
351
|
+
if (episode.pending.size > 0) return;
|
|
352
|
+
episode.closing = setTimeout(() => {
|
|
353
|
+
if (this.restoring !== episode || episode.pending.size > 0) return;
|
|
354
|
+
this.restoring = void 0;
|
|
355
|
+
const seconds = ((Date.now() - episode.started) / 1e3).toFixed(1);
|
|
356
|
+
const failed = episode.failed.length > 0 ? ` — ${String(episode.failed.length)} failed (${episode.failed.join(", ")}), said above` : "";
|
|
357
|
+
serverLog.warn("SSR", `Plugin bundles built again: ${String(episode.rebuilt)} in ${seconds}s${failed}`);
|
|
358
|
+
}, RESTORE_SETTLE_MS);
|
|
359
|
+
episode.closing.unref();
|
|
360
|
+
});
|
|
361
|
+
}
|
|
320
362
|
async build(name, source) {
|
|
321
363
|
const dir = this.pluginDir(name);
|
|
322
364
|
await fs.mkdir(dir, { recursive: true });
|
package/dist/runtime.d.ts
CHANGED
|
@@ -9,7 +9,8 @@ export type { SpaceRuntime, SpaceRuntimeContext, SpaceRuntimeEndpoint, SpaceRunt
|
|
|
9
9
|
export { RUNTIME_DESCRIBE_PATH, startSpaceRuntime } from './modules/runtime/host';
|
|
10
10
|
export type { SpaceRuntimeDescription, SpaceRuntimeHost, SpaceRuntimeHostOptions } from './modules/runtime/host';
|
|
11
11
|
export { inspectRuntime, loadRuntime, loadRuntimeModule, MAX_RUNTIME_BUNDLE_BYTES, packRuntime, runtimeBundleId } from './modules/runtime/bundle';
|
|
12
|
-
export { reachSpaceInside } from './modules/runtime/inside';
|
|
12
|
+
export { reachOwnServer, reachSpaceInside } from './modules/runtime/inside';
|
|
13
|
+
export type { OwnServer } from './modules/runtime/inside';
|
|
13
14
|
export { createRuntimeRunner } from './modules/runtime/runner';
|
|
14
15
|
export { createRuntimeProxyStage, runtimeEndpointsStage, serveRuntime } from './modules/runtime/stages';
|
|
15
16
|
export type { RuntimeProxyConfig, RuntimeTarget, ServedRuntime } from './modules/runtime/stages';
|
package/dist/runtime.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { defineRuntime, endpointFor, endpointProblem } from "./modules/runtime/contract.js";
|
|
2
|
-
import { reachSpaceInside } from "./modules/runtime/inside.js";
|
|
2
|
+
import { reachOwnServer, reachSpaceInside } from "./modules/runtime/inside.js";
|
|
3
3
|
import { createRuntimeRunner } from "./modules/runtime/runner.js";
|
|
4
4
|
import { RUNTIME_DESCRIBE_PATH, startSpaceRuntime } from "./modules/runtime/host.js";
|
|
5
5
|
import { MAX_RUNTIME_BUNDLE_BYTES, inspectRuntime, loadRuntime, loadRuntimeModule, packRuntime, runtimeBundleId } from "./modules/runtime/bundle.js";
|
|
6
6
|
import { createRuntimeProxyStage, runtimeEndpointsStage, serveRuntime } from "./modules/runtime/stages.js";
|
|
7
|
-
export { MAX_RUNTIME_BUNDLE_BYTES, RUNTIME_DESCRIBE_PATH, createRuntimeProxyStage, createRuntimeRunner, defineRuntime, endpointFor, endpointProblem, inspectRuntime, loadRuntime, loadRuntimeModule, packRuntime, reachSpaceInside, runtimeBundleId, runtimeEndpointsStage, serveRuntime, startSpaceRuntime };
|
|
7
|
+
export { MAX_RUNTIME_BUNDLE_BYTES, RUNTIME_DESCRIBE_PATH, createRuntimeProxyStage, createRuntimeRunner, defineRuntime, endpointFor, endpointProblem, inspectRuntime, loadRuntime, loadRuntimeModule, packRuntime, reachOwnServer, reachSpaceInside, runtimeBundleId, runtimeEndpointsStage, serveRuntime, startSpaceRuntime };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plitzi/sdk-server",
|
|
3
|
-
"version": "0.38.
|
|
3
|
+
"version": "0.38.15",
|
|
4
4
|
"license": "AGPL-3.0",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -96,8 +96,8 @@
|
|
|
96
96
|
"./dist/env.js"
|
|
97
97
|
],
|
|
98
98
|
"dependencies": {
|
|
99
|
-
"@plitzi/plitzi-sdk": "0.38.
|
|
100
|
-
"@plitzi/sdk-shared": "0.38.
|
|
99
|
+
"@plitzi/plitzi-sdk": "0.38.15",
|
|
100
|
+
"@plitzi/sdk-shared": "0.38.15",
|
|
101
101
|
"ejs": "^6.0.1",
|
|
102
102
|
"esbuild": "^0.28.2",
|
|
103
103
|
"jsonwebtoken": "^9.0.3",
|
|
@@ -36,7 +36,7 @@ A space on Plitzi — edited in the builder — is edited through the Plitzi MCP
|
|
|
36
36
|
when the text is not enough.
|
|
37
37
|
4. **Before saying done:** `npm run lint:space` clean, and the [review checklist](reference/review-checklist.md).
|
|
38
38
|
|
|
39
|
-
What a name means — an element, a step, a trigger, a code, any export (`pageFamily`, `
|
|
39
|
+
What a name means — an element, a step, a trigger, a code, any `@plitzi` export (`pageFamily`, `createServer`): `npx plitzi explain
|
|
40
40
|
<name>`, in a few lines. Never read the `.d.ts`.
|
|
41
41
|
|
|
42
42
|
## Five rules authoring cannot check for you
|
|
@@ -22,8 +22,9 @@ Read one only when the task names its subject.
|
|
|
22
22
|
| [authoring-errors.md](authoring-errors.md) | What `authorSpace` refuses or warns about, and what to write instead |
|
|
23
23
|
| [templates.md](templates.md) | Any `{{ … }}` or `{% … %}`: where it runs, naming sources, filters, tests, dates |
|
|
24
24
|
| [flows.md](flows.md) | Clicks, submits, page loads, every few seconds, server actions, modals, state |
|
|
25
|
-
| [realtime.md](realtime.md) | Pages that see each other: channels, presence, cursors, a shared board, who may hear a topic |
|
|
26
|
-
| [plugins.md](plugins.md) | A component of your own: props, binding them, writing state,
|
|
25
|
+
| [realtime.md](realtime.md) | Pages that see each other: channels, presence, cursors, a shared board, state every screen shares, who may hear a topic |
|
|
26
|
+
| [plugins.md](plugins.md) | A component of your own: props, binding them, writing state, registering, behaving in the builder |
|
|
27
|
+
| [plugin-reach.md](plugin-reach.md) | What a plugin says and to whom: a notification, another element, a server action, shared state, other pages |
|
|
27
28
|
| [drawing.md](drawing.md) | A plugin that draws or animates: a canvas sized to the device, WebGL, a loop that stops when unseen |
|
|
28
29
|
| [structure.md](structure.md) | A space bigger than one screen: files, helpers, naming, keeping it short |
|
|
29
30
|
| [testing.md](testing.md) | Any test: `inspectPage`, handles, fixtures, catching a flash from the first frame, shortcuts, counting renders |
|
|
@@ -145,6 +145,16 @@ Every page is now its content and nothing else, and every page is guaranteed the
|
|
|
145
145
|
by name — `"{{ not (apiContainer_feed.products|find('slug', navigation.routeParams.slug)) }}"`. The page renders as
|
|
146
146
|
written: show its "not found" part with `visible`.
|
|
147
147
|
|
|
148
|
+
## A screen that fills the window
|
|
149
|
+
|
|
150
|
+
A dashboard or a board — one screen whose panels scroll on their own — says so on its page: `documentScroll:
|
|
151
|
+
'locked'` holds the document still, so a finger dragged on a tablet no longer pulls the whole page and bounces it
|
|
152
|
+
back. Give the shell the window's height (`height: '100dvh'`) and `overflow: 'auto'` to each part that scrolls; what
|
|
153
|
+
does not fit is cut off, with nothing a visitor can scroll to reach it. `'noBounce'` keeps a page scrolling without
|
|
154
|
+
the rubber band or pull-to-refresh. Either is written onto the document only while that page is on it, and only when
|
|
155
|
+
the document is the space's own — never the site a widget sits on, nor a space drawn inside another. Not an
|
|
156
|
+
`html, body` rule in `customCss`, which holds every page and the site the space is a widget on.
|
|
157
|
+
|
|
148
158
|
## Styles follow the same rule
|
|
149
159
|
|
|
150
160
|
- A role used on several pages is ONE class (`panelCard`, `pageTitle`), declared in the module that owns the area and
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# What a plugin says, and to whom
|
|
2
|
+
|
|
3
|
+
A plugin reaches the person, the space's other elements, the server and the other screens each one way. All of it is
|
|
4
|
+
imported from `@plitzi/plitzi-sdk` — the page's copy, which every plugin shares — never from `window` events or a
|
|
5
|
+
module of the project's (each plugin is a bundle of its own: a module two of them import is two).
|
|
6
|
+
|
|
7
|
+
## To the person: `useNotify`
|
|
8
|
+
|
|
9
|
+
```tsx
|
|
10
|
+
import { useNotify } from '@plitzi/plitzi-sdk';
|
|
11
|
+
|
|
12
|
+
const notify = useNotify();
|
|
13
|
+
notify('Deleted 79 recordings'); // what an `addNotification` step shows
|
|
14
|
+
notify('Training failed', { appearance: 'danger', autoDismiss: false });
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The page's own toasts, in the space's theme and with the look its `notifications` give them. For what only the plugin
|
|
18
|
+
knows; what the PAGE decides to say stays a flow (`on(…)` → `addNotification`).
|
|
19
|
+
|
|
20
|
+
## To another element: an event, and the space's flow
|
|
21
|
+
|
|
22
|
+
A plugin never calls another one. It fires what happened, and the space's flow decides who acts — visible in the
|
|
23
|
+
space, and the same flow a button can start:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// the assistant's declaration: triggers: { onOpenResult: { action: 'onOpenResult', preview: { index: 0 } } }
|
|
27
|
+
assistant({ id: 'jarvis', flows: [[
|
|
28
|
+
named('asked', declaredTrigger(assistantDeclaration, 'onOpenResult')),
|
|
29
|
+
declaredCallback(browserDeclaration, 'openResult', { on: 'browser', params: { index: '{{ asked.index }}' } })
|
|
30
|
+
]] })
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The receiver declares the action (`callbacks`) and registers it from its declaration; a name either side does not
|
|
34
|
+
declare is refused when the space is authored.
|
|
35
|
+
|
|
36
|
+
## To the server: `useServerAction`
|
|
37
|
+
|
|
38
|
+
One operation is one server action — `taskAction(tasks.done, …)` or `defineAction(…)` — whose input the server checks
|
|
39
|
+
before any code runs, never a `case` in one route. A plugin runs it awaited, typed by the action:
|
|
40
|
+
|
|
41
|
+
```tsx
|
|
42
|
+
import { useServerAction } from '@plitzi/plitzi-sdk';
|
|
43
|
+
import type { habitDone } from '../../space/actions';
|
|
44
|
+
|
|
45
|
+
const done = useServerAction<typeof habitDone>('habits-done');
|
|
46
|
+
const result = await done({ id }); // the input its `call` way in declares
|
|
47
|
+
if (result.ok) { show(result.output.streak); } else { say(result.error ?? result.reason); }
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The same run a flow's `runServerAction` makes: its `access`, its refusals, its entry in the dev tools; a completed run
|
|
51
|
+
refreshes the page's cached requests (`{ invalidateQueries: 'none' }` for one that only reads).
|
|
52
|
+
|
|
53
|
+
## State every screen shares: a channel that retains
|
|
54
|
+
|
|
55
|
+
What the server keeps and every page shows — a dashboard's lists, a board's settings — is a channel declared
|
|
56
|
+
`retain: true` (with `publish: 'server'`): the server keeps the latest message of each type and hands them to every
|
|
57
|
+
page that joins.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
channels: { desk: { access: { mode: 'session' }, publish: 'server', retain: true } }
|
|
61
|
+
|
|
62
|
+
// the server, in a task, a route or a flow's `realtime.publish`: kept, and said to every page on it
|
|
63
|
+
await ctx.publish('desk', 'lists', lists);
|
|
64
|
+
await ctx.publish('desk', 'lists', null); // forgotten
|
|
65
|
+
|
|
66
|
+
channel({ id: 'desk', topic: 'desk', children: [lists({ id: 'lists', bind: { lists: 'desk.retained.lists' } })] })
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`useChannel('desk').retained.lists` is the same value in a plugin, re-rendering when it changes; what the page is
|
|
70
|
+
handed on joining reaches `onMessage` too, as if just said. A page changes it by
|
|
71
|
+
asking the server (an action), which keeps it and says it. A topic keeps at most 64 types and 512 KB.
|
|
72
|
+
|
|
73
|
+
## To other pages, at the speed of a cursor: `useChannel`
|
|
74
|
+
|
|
75
|
+
```tsx
|
|
76
|
+
const room = useChannel(roomTopic, { onMessage: message => move(message.from, message.data) });
|
|
77
|
+
room.publish('pointer', { x, y }); // throttle it: ~20 a second, the latest position each time
|
|
78
|
+
room.publish('react', { emoji }, { echo: true }); // and heard here too
|
|
79
|
+
room.members; // who is here, with the state each announced
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Messages arrive through the callback and re-render nothing. Take the topic as a prop
|
|
83
|
+
(`bindTemplate('roomTopic', 'board.id', 'room:{{ source }}')`) so the space names its channels, and trust a message
|
|
84
|
+
you act on only when `message.from === 'server'`. The page has one connection and is one member per topic, however
|
|
85
|
+
many elements and plugins listen.
|
|
86
|
+
|
|
87
|
+
## Its own server code
|
|
88
|
+
|
|
89
|
+
`plitzi plugin add board --server` writes `functions/index.ts` in its folder. Its routes answer under
|
|
90
|
+
`/fn/plugins/board/`, named with `usePluginRoute('board')('/layout')` (`undefined` where no server runs code, as on the
|
|
91
|
+
canvas). Its `ctx.kv` is the plugin's own; the space's credentials, channels and data are not.
|
|
@@ -55,8 +55,14 @@ const NebulaRun = ({ shipColor = 'amber', best = 0, className }: NebulaRunProps)
|
|
|
55
55
|
|
|
56
56
|
- **Render `RootElement`**, not a `div`: it carries the element's id, classes and `data-plitzi-el`, so the CSS
|
|
57
57
|
authored on the element applies, the builder can select it and a test can find it.
|
|
58
|
-
- **Render the same thing on the server and on the first client pass
|
|
59
|
-
`window` belongs in an effect; a hydration mismatch discards the whole
|
|
58
|
+
- **Render the same thing on the server and on the first client pass** — a plugin is drawn on the server first. A
|
|
59
|
+
clock, a random number or anything read from `window` belongs in an effect; a hydration mismatch discards the whole
|
|
60
|
+
tree, not the plugin. A preference per device (a tab, muted) is never read from `localStorage` while rendering: write
|
|
61
|
+
it to `runtime.state` with `keepState` — and `paintedState` when it changes the first paint ([kept state](kept-state.md))
|
|
62
|
+
— and take it as a bound prop.
|
|
63
|
+
- **`@plitzi/plitzi-ui` is not the page's.** The build keeps out only React and the SDK: a plugin importing it carries
|
|
64
|
+
its own copy, whose contexts (its toasts) are not the page's and whose look is not the space's. Draw controls with the
|
|
65
|
+
space's tokens; tabs over the space's elements are a plugin that lays them out (below).
|
|
60
66
|
- **Borrow colours.** `currentColor` and the space's `var(--…)` tokens follow the theme; a hard-coded colour is
|
|
61
67
|
invisible in one of them. A canvas reads them with `getComputedStyle(element).getPropertyValue('--accent')` and
|
|
62
68
|
again when `theme.resolved` changes (bind it as a prop).
|
|
@@ -64,19 +70,19 @@ const NebulaRun = ({ shipColor = 'amber', best = 0, className }: NebulaRunProps)
|
|
|
64
70
|
## Writing to the space
|
|
65
71
|
|
|
66
72
|
A plugin that produces something the page shows — a score, a selection — writes it to `runtime.state`, where every
|
|
67
|
-
binding reads it:
|
|
73
|
+
binding reads it — and where two plugins share it, each being a bundle of its own (a module both import is two):
|
|
68
74
|
|
|
69
75
|
```ts
|
|
70
76
|
import { getStateManager } from '@plitzi/plitzi-sdk';
|
|
71
77
|
|
|
72
78
|
const state = getStateManager();
|
|
73
79
|
state.setStateByKey('arcadeBest', Math.max(score, Number(state.state.arcadeBest ?? 0)));
|
|
74
|
-
const stop = state.subscribe(next => save(next)); //
|
|
80
|
+
const stop = state.subscribe(next => save(next)); // after every change; `stop()` to leave
|
|
75
81
|
```
|
|
76
82
|
|
|
77
83
|
`state` is the current value, `setState` replaces it (or takes an updater), `setStateByKey` writes one key,
|
|
78
|
-
`clearState` empties it, `subscribe` listens. Bindings on `state.*` re-render at once. With
|
|
79
|
-
|
|
84
|
+
`clearState` empties it, `subscribe` listens. Bindings on `state.*` re-render at once. With `keepState` on
|
|
85
|
+
([kept state](kept-state.md)), what a plugin writes there is back after a reload.
|
|
80
86
|
|
|
81
87
|
## Laying out the space's elements
|
|
82
88
|
|
|
@@ -90,39 +96,17 @@ import { elementChildren } from '@plitzi/plitzi-sdk';
|
|
|
90
96
|
{elementChildren(children).map(({ id, node }) => <section key={id} style={placed[id]}>{node}</section>)}
|
|
91
97
|
```
|
|
92
98
|
|
|
93
|
-
|
|
99
|
+
One that shows only some of them — a dashboard's panels, a wizard's step — says `choosesChildren: true` in its
|
|
100
|
+
declaration: the page checks then owe none at rest, and check the ones it draws. Never write `style` onto an element
|
|
101
|
+
the plugin does not render: nothing promises to keep it. Its boxes share one
|
|
94
102
|
stacking context, the plugin's. `useDisplayMode()` names the breakpoint showing (`desktop`, `tablet`, `mobile`) at the
|
|
95
103
|
space's widths; `useElementSize(ref)`, its own box (`undefined` until measured).
|
|
96
104
|
|
|
97
|
-
##
|
|
105
|
+
## What it says, and to whom
|
|
98
106
|
|
|
99
|
-
`
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
```tsx
|
|
103
|
-
const route = usePluginRoute('board'); // from '@plitzi/plitzi-sdk'
|
|
104
|
-
const url = route('/layout'); // undefined where no server runs code (the canvas)
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
Its `ctx.kv` is the plugin's own; the space's credentials, channels and data are not.
|
|
108
|
-
|
|
109
|
-
## Talking to other pages
|
|
110
|
-
|
|
111
|
-
A plugin that moves at the speed of a cursor reads a realtime channel through `useChannel` rather than through flows —
|
|
112
|
-
messages arrive through a callback and re-render nothing:
|
|
113
|
-
|
|
114
|
-
```tsx
|
|
115
|
-
import { useChannel } from '@plitzi/plitzi-sdk';
|
|
116
|
-
|
|
117
|
-
const room = useChannel(roomTopic, { onMessage: message => move(message.from, message.data) });
|
|
118
|
-
room.publish('pointer', { x, y }); // throttle it: ~20 a second, the latest position each time
|
|
119
|
-
room.publish('react', { emoji }, { echo: true }); // and heard here too
|
|
120
|
-
room.members; // who is here, with the state each announced
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
Take the topic as a prop (`bindTemplate('roomTopic', 'board.id', 'room:{{ source }}')`) so the space names its
|
|
124
|
-
channels, and trust a message you act on only when `message.from === 'server'`. The page has one connection and is one
|
|
125
|
-
member per topic, however many elements and plugins listen.
|
|
107
|
+
The person (`useNotify`), another element (an event and the space's flow — never a `window` event), the server
|
|
108
|
+
(`useServerAction`, typed by the action), state every screen shares (a channel that retains), other pages
|
|
109
|
+
(`useChannel`) and its own server code: [plugin-reach](plugin-reach.md).
|
|
126
110
|
|
|
127
111
|
## Feature flags
|
|
128
112
|
|
|
@@ -33,6 +33,17 @@ channels: { 'order:{id}': { access: { mode: 'session' }, grant: true } }
|
|
|
33
33
|
channel({ id: 'order', topic: 'order:{{ id }}', bind: { grant: 'state.follow.grant' }, children: [...] })
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
+
State every screen shows and the server keeps — a dashboard's lists, a board's settings — goes on a channel declared
|
|
37
|
+
`retain: true` (and `publish: 'server'`): the server keeps the latest message of each type, sends it as it is said and
|
|
38
|
+
again to every page that joins — and to its `onMessage` flows, as if just said — which reads it as
|
|
39
|
+
`desk.retained.lists` (a plugin, `useChannel('desk').retained`).
|
|
40
|
+
Publishing `null` forgets the type; a topic keeps at most 64 types and 512 KB. No read of its own, no copy in `state`:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
channels: { desk: { access: { mode: 'session' }, publish: 'server', retain: true } }
|
|
44
|
+
// a flow: { task: 'realtime.publish', params: { topic: 'desk', type: 'lists', data: '{{ saved.lists }}' } }
|
|
45
|
+
```
|
|
46
|
+
|
|
36
47
|
Two people writing the same thing at once: `kv.setIf` writes only if the value is still the one the flow read (empty
|
|
37
48
|
`expected` = only if nothing is there yet — claim a seat, a username), `list.put`/`list.range` keep an ordered list
|
|
38
49
|
(latest first, a leaderboard), and `flow.rateLimit` first in a public action that writes.
|
|
@@ -44,7 +44,9 @@ the list `inspectPage` holds a page to.
|
|
|
44
44
|
Three flags say what a bare visit cannot promise, and `onScreen` leaves out:
|
|
45
45
|
|
|
46
46
|
- `conditional` — on screen only under a condition of its own or of an ancestor, or with every child conditional (a
|
|
47
|
-
list of flyouts at rest)
|
|
47
|
+
list of flyouts at rest). Under a plugin that chooses its children (`choosesChildren`), each child — and what is
|
|
48
|
+
inside it under no condition of its own — also carries `shownWith`, the child it comes with: once that child is
|
|
49
|
+
drawn it is owed like the rest (`onScreenIfChosen` lists them, and `inspectPage` checks them);
|
|
48
50
|
- `repeated` — inside a list row, so rendered once per row: several copies, or none while the list is empty. Address
|
|
49
51
|
one with `.first()` / `.nth(i)`, in a test that knows the data;
|
|
50
52
|
- `boxless` — a provider with no tag, which renders its children and no element of its own; or a plugin whose
|