@niscorp/moss 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +492 -0
- package/DESIGN.md +265 -49
- package/DOCS.md +1527 -344
- package/README.md +37 -20
- package/dist/app-CUnDcXQu.d.ts +143 -0
- package/dist/app-CdANzi2q.d.cts +143 -0
- package/dist/chunk-3RIWTXGI.cjs +174 -0
- package/dist/chunk-3RIWTXGI.cjs.map +1 -0
- package/dist/chunk-4ZGAFZGS.js +152 -0
- package/dist/chunk-4ZGAFZGS.js.map +1 -0
- package/dist/chunk-6QPTMKRE.cjs +53 -0
- package/dist/chunk-6QPTMKRE.cjs.map +1 -0
- package/dist/chunk-D3YZIAYV.cjs +137 -0
- package/dist/chunk-D3YZIAYV.cjs.map +1 -0
- package/dist/chunk-IUJ2TRNB.cjs +57 -0
- package/dist/chunk-IUJ2TRNB.cjs.map +1 -0
- package/dist/chunk-IW3A2YIC.js +49 -0
- package/dist/chunk-IW3A2YIC.js.map +1 -0
- package/dist/chunk-NRZ3Z2FF.js +61 -0
- package/dist/chunk-NRZ3Z2FF.js.map +1 -0
- package/dist/chunk-NSK7QSSG.js +26 -0
- package/dist/chunk-NSK7QSSG.js.map +1 -0
- package/dist/chunk-PWUO4RET.js +374 -0
- package/dist/chunk-PWUO4RET.js.map +1 -0
- package/dist/chunk-R2YPQHQH.cjs +383 -0
- package/dist/chunk-R2YPQHQH.cjs.map +1 -0
- package/dist/chunk-R66WUKGC.cjs +2716 -0
- package/dist/chunk-R66WUKGC.cjs.map +1 -0
- package/dist/chunk-T5BRTFKP.js +53 -0
- package/dist/chunk-T5BRTFKP.js.map +1 -0
- package/dist/chunk-TGKDS2T7.cjs +330 -0
- package/dist/chunk-TGKDS2T7.cjs.map +1 -0
- package/dist/chunk-TLNRFAQ6.js +326 -0
- package/dist/chunk-TLNRFAQ6.js.map +1 -0
- package/dist/chunk-V5YMJL7Z.js +2704 -0
- package/dist/chunk-V5YMJL7Z.js.map +1 -0
- package/dist/chunk-VBWNHF4H.cjs +30 -0
- package/dist/chunk-VBWNHF4H.cjs.map +1 -0
- package/dist/chunk-VKQPOZDJ.cjs +72 -0
- package/dist/chunk-VKQPOZDJ.cjs.map +1 -0
- package/dist/{chunk-U3UR5AOQ.js → chunk-WKBH3UMB.js} +43 -16
- package/dist/chunk-WKBH3UMB.js.map +1 -0
- package/dist/client/node.cjs.map +1 -1
- package/dist/client/node.d.cts +3 -1
- package/dist/client/node.d.ts +3 -1
- package/dist/client/node.js.map +1 -1
- package/dist/client.cjs +14 -302
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +9 -33
- package/dist/client.d.ts +9 -33
- package/dist/client.js +2 -2
- package/dist/document-D7nroBww.d.cts +169 -0
- package/dist/document-DeTPGBil.d.ts +169 -0
- package/dist/env-CY8EGWnD.d.cts +24 -0
- package/dist/env-DEPqqHEb.d.ts +24 -0
- package/dist/index-B411sK9M.d.cts +130 -0
- package/dist/index-B411sK9M.d.ts +130 -0
- package/dist/index.cjs +45 -3916
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +46 -100
- package/dist/index.d.ts +46 -100
- package/dist/index.js +4 -94
- package/dist/index.js.map +1 -1
- package/dist/integrations.cjs +975 -0
- package/dist/integrations.cjs.map +1 -0
- package/dist/integrations.d.cts +63 -0
- package/dist/integrations.d.ts +63 -0
- package/dist/integrations.js +972 -0
- package/dist/integrations.js.map +1 -0
- package/dist/messages-CSwCJgH3.d.cts +51 -0
- package/dist/messages-CSwCJgH3.d.ts +51 -0
- package/dist/node.cjs +17 -3455
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +13 -10
- package/dist/node.d.ts +13 -10
- package/dist/node.js +5 -3
- package/dist/protocol.cjs +24 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +11 -0
- package/dist/protocol.d.ts +11 -0
- package/dist/protocol.js +3 -0
- package/dist/protocol.js.map +1 -0
- package/dist/slots-96gNc9uH.d.cts +12 -0
- package/dist/slots-BX5N0Juv.d.ts +14 -0
- package/dist/slots-CU-AbnJg.d.cts +14 -0
- package/dist/slots-sLXDrlbG.d.ts +12 -0
- package/dist/socket-D90h1xSV.d.cts +24 -0
- package/dist/socket-D90h1xSV.d.ts +24 -0
- package/dist/targets-DInbLzff.d.cts +9 -0
- package/dist/targets-DInbLzff.d.ts +9 -0
- package/dist/terminal/dom/index.cjs +8 -3
- package/dist/terminal/dom/index.cjs.map +1 -1
- package/dist/terminal/dom/index.d.cts +3 -0
- package/dist/terminal/dom/index.d.ts +3 -0
- package/dist/terminal/dom/index.js +8 -3
- package/dist/terminal/dom/index.js.map +1 -1
- package/dist/terminal/dom/server.cjs +2 -7
- package/dist/terminal/dom/server.cjs.map +1 -1
- package/dist/terminal/dom/server.d.cts +3 -5
- package/dist/terminal/dom/server.d.ts +3 -5
- package/dist/terminal/dom/server.js +2 -7
- package/dist/terminal/dom/server.js.map +1 -1
- package/dist/terminal/index.cjs +22 -300
- package/dist/terminal/index.cjs.map +1 -1
- package/dist/terminal/index.d.cts +7 -2
- package/dist/terminal/index.d.ts +7 -2
- package/dist/terminal/index.js +21 -22
- package/dist/terminal/index.js.map +1 -1
- package/dist/terminal/ink/index.d.ts +3 -2
- package/dist/terminal/ink/index.js +149 -106
- package/dist/terminal/ink/index.js.map +1 -1
- package/dist/terminal/react/index.cjs +21 -71
- package/dist/terminal/react/index.cjs.map +1 -1
- package/dist/terminal/react/index.d.cts +5 -2
- package/dist/terminal/react/index.d.ts +5 -2
- package/dist/terminal/react/index.js +17 -20
- package/dist/terminal/react/index.js.map +1 -1
- package/dist/terminal/react/server.cjs +4 -68
- package/dist/terminal/react/server.cjs.map +1 -1
- package/dist/terminal/react/server.d.cts +9 -6
- package/dist/terminal/react/server.d.ts +9 -6
- package/dist/terminal/react/server.js +3 -18
- package/dist/terminal/react/server.js.map +1 -1
- package/dist/terminal/tty/index.cjs +147 -130
- package/dist/terminal/tty/index.cjs.map +1 -1
- package/dist/terminal/tty/index.d.cts +4 -2
- package/dist/terminal/tty/index.d.ts +4 -2
- package/dist/terminal/tty/index.js +147 -130
- package/dist/terminal/tty/index.js.map +1 -1
- package/dist/terminal/vue/index.cjs +20 -72
- package/dist/terminal/vue/index.cjs.map +1 -1
- package/dist/terminal/vue/index.d.cts +8 -12
- package/dist/terminal/vue/index.d.ts +8 -12
- package/dist/terminal/vue/index.js +45 -1
- package/dist/terminal/vue/index.js.map +1 -1
- package/dist/terminal/vue/server.cjs +4 -76
- package/dist/terminal/vue/server.cjs.map +1 -1
- package/dist/terminal/vue/server.d.cts +7 -6
- package/dist/terminal/vue/server.d.ts +7 -6
- package/dist/terminal/vue/server.js +3 -10
- package/dist/terminal/vue/server.js.map +1 -1
- package/dist/tide.cjs +41 -0
- package/dist/tide.cjs.map +1 -0
- package/dist/tide.d.cts +25 -0
- package/dist/tide.d.ts +25 -0
- package/dist/tide.js +39 -0
- package/dist/tide.js.map +1 -0
- package/dist/unverified.cjs +12 -0
- package/dist/unverified.cjs.map +1 -0
- package/dist/unverified.d.cts +7 -0
- package/dist/unverified.d.ts +7 -0
- package/dist/unverified.js +10 -0
- package/dist/unverified.js.map +1 -0
- package/dist/vite.cjs +96 -232
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +6 -8
- package/dist/vite.d.ts +6 -8
- package/dist/vite.js +97 -71
- package/dist/vite.js.map +1 -1
- package/package.json +52 -9
- package/dist/chunk-4T6KAXBP.js +0 -256
- package/dist/chunk-4T6KAXBP.js.map +0 -1
- package/dist/chunk-EMRDIZLY.js +0 -99
- package/dist/chunk-EMRDIZLY.js.map +0 -1
- package/dist/chunk-HOZID4EM.js +0 -366
- package/dist/chunk-HOZID4EM.js.map +0 -1
- package/dist/chunk-R3QMJ3JF.js +0 -3404
- package/dist/chunk-R3QMJ3JF.js.map +0 -1
- package/dist/chunk-SK4PDGEE.js +0 -55
- package/dist/chunk-SK4PDGEE.js.map +0 -1
- package/dist/chunk-U3UR5AOQ.js.map +0 -1
- package/dist/document-DhWxieUc.d.cts +0 -1024
- package/dist/document-DhWxieUc.d.ts +0 -1024
- package/dist/slots-Do9ScG7v.d.cts +0 -37
- package/dist/slots-Do9ScG7v.d.ts +0 -37
package/dist/index.cjs
CHANGED
|
@@ -1,3926 +1,55 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
var hono$1 = require('@niscorp/vex/hono');
|
|
8
|
-
var vex = require('@niscorp/vex');
|
|
9
|
-
var strata = require('@niscorp/strata');
|
|
10
|
-
var migrations = require('@niscorp/nova/migrations');
|
|
11
|
-
var prism = require('@niscorp/prism');
|
|
12
|
-
var migrations$1 = require('@niscorp/prism/migrations');
|
|
13
|
-
var charter = require('@niscorp/charter');
|
|
14
|
-
var nova = require('@niscorp/nova');
|
|
15
|
-
var zod = require('zod');
|
|
16
|
-
var reflect = require('@niscorp/nova/reflect');
|
|
17
|
-
var i18n = require('@niscorp/nova/i18n');
|
|
18
|
-
var tide = require('@niscorp/tide');
|
|
19
|
-
var document = require('@niscorp/nova/document');
|
|
3
|
+
var chunkR66WUKGC_cjs = require('./chunk-R66WUKGC.cjs');
|
|
4
|
+
require('./chunk-R2YPQHQH.cjs');
|
|
5
|
+
require('./chunk-VBWNHF4H.cjs');
|
|
6
|
+
require('./chunk-3RIWTXGI.cjs');
|
|
20
7
|
|
|
21
|
-
// src/app.ts
|
|
22
|
-
var defineApp = (app) => app;
|
|
23
8
|
|
|
24
|
-
// src/runtime.ts
|
|
25
|
-
var mintDevToken = (sub, claims = {}) => btoa(JSON.stringify({ sub, ...claims, iat: Date.now() })).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
26
|
-
var devSession = (token) => {
|
|
27
|
-
try {
|
|
28
|
-
const parsed = JSON.parse(atob(token.replace(/-/g, "+").replace(/_/g, "/")));
|
|
29
|
-
const sub = parsed?.["sub"];
|
|
30
|
-
return typeof sub === "string" ? sub : null;
|
|
31
|
-
} catch {
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
9
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
telemetry.emit(span);
|
|
40
|
-
} catch (err) {
|
|
41
|
-
console.error("[moss:telemetry]", err);
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
var elapsedClock = () => typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
45
|
-
var spanClock = () => {
|
|
46
|
-
const startUnixNano = Date.now() * 1e6;
|
|
47
|
-
const t0 = elapsedClock();
|
|
48
|
-
return { startUnixNano, endUnixNano: () => startUnixNano + (elapsedClock() - t0) * 1e6 };
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
// src/fabric.ts
|
|
52
|
-
var wireFabric = (fabric, origin, apply) => {
|
|
53
|
-
if (fabric === void 0) return () => {
|
|
54
|
-
};
|
|
55
|
-
fabric.subscribe((message) => {
|
|
56
|
-
if (message.origin === origin) return;
|
|
57
|
-
try {
|
|
58
|
-
switch (message.kind) {
|
|
59
|
-
case "invalidate-identity":
|
|
60
|
-
apply.invalidateIdentity(message.principal);
|
|
61
|
-
break;
|
|
62
|
-
case "invalidate-tenant":
|
|
63
|
-
apply.invalidateTenant(message.tag);
|
|
64
|
-
break;
|
|
65
|
-
case "nudge":
|
|
66
|
-
apply.nudge(message.principal, message.channel);
|
|
67
|
-
break;
|
|
68
|
-
}
|
|
69
|
-
} catch (err) {
|
|
70
|
-
console.error("[moss:fabric] a remote signal failed to apply", err);
|
|
71
|
-
}
|
|
72
|
-
});
|
|
73
|
-
return (signal) => {
|
|
74
|
-
try {
|
|
75
|
-
fabric.publish({ ...signal, origin });
|
|
76
|
-
} catch (err) {
|
|
77
|
-
console.error("[moss:fabric] publish failed", err);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
};
|
|
81
|
-
var hashSessionToken = (token) => crypto$1.createHash("sha256").update(token).digest("hex");
|
|
82
|
-
var SESSIONS_SEQUENCE = {
|
|
83
|
-
id: "nisc.moss.sessions",
|
|
84
|
-
migrations: [
|
|
85
|
-
{
|
|
86
|
-
description: "The sessions table: a token is stored only as its hash",
|
|
87
|
-
steps: [
|
|
88
|
-
{
|
|
89
|
-
kind: "sql",
|
|
90
|
-
// THE HASH, NEVER THE TOKEN (see the header, and assert.ts for the rule).
|
|
91
|
-
sql: `CREATE TABLE IF NOT EXISTS sessions (
|
|
92
|
-
token_hash text PRIMARY KEY,
|
|
93
|
-
principal text NOT NULL,
|
|
94
|
-
created_at timestamptz NOT NULL DEFAULT now(),
|
|
95
|
-
expires_at timestamptz NOT NULL
|
|
96
|
-
)`
|
|
97
|
-
}
|
|
98
|
-
]
|
|
99
|
-
}
|
|
100
|
-
]
|
|
101
|
-
};
|
|
102
|
-
var initSessions = async (pool) => {
|
|
103
|
-
await postgres.migrate(pool, [SESSIONS_SEQUENCE]);
|
|
104
|
-
};
|
|
105
|
-
var mintSession = async (pool, principal, ttlMs) => {
|
|
106
|
-
await pool.query("DELETE FROM sessions WHERE expires_at < now()");
|
|
107
|
-
const token = `st_${crypto$1.randomBytes(32).toString("base64url")}`;
|
|
108
|
-
await pool.query("INSERT INTO sessions (token_hash, principal, expires_at) VALUES ($1, $2, $3)", [
|
|
109
|
-
hashSessionToken(token),
|
|
110
|
-
principal,
|
|
111
|
-
new Date(Date.now() + ttlMs)
|
|
112
|
-
]);
|
|
113
|
-
return token;
|
|
114
|
-
};
|
|
115
|
-
var sessionOf = async (pool, token) => {
|
|
116
|
-
const res = await pool.query("SELECT principal FROM sessions WHERE token_hash = $1 AND expires_at > now()", [hashSessionToken(token)]);
|
|
117
|
-
const principal = res.rows[0]?.principal;
|
|
118
|
-
return typeof principal === "string" ? principal : null;
|
|
119
|
-
};
|
|
120
|
-
var sessionRemainingMs = async (pool, token) => {
|
|
121
|
-
const res = await pool.query("SELECT extract(epoch from expires_at - now()) * 1000 AS remaining FROM sessions WHERE token_hash = $1 AND expires_at > now()", [hashSessionToken(token)]);
|
|
122
|
-
const remaining = Number(res.rows[0]?.["remaining"]);
|
|
123
|
-
return res.rows.length > 0 && Number.isFinite(remaining) ? remaining : null;
|
|
124
|
-
};
|
|
125
|
-
var revokeSession = async (pool, token) => {
|
|
126
|
-
await pool.query("DELETE FROM sessions WHERE token_hash = $1", [hashSessionToken(token)]);
|
|
127
|
-
};
|
|
128
|
-
var revokeAllFor = async (pool, principal) => {
|
|
129
|
-
await pool.query("DELETE FROM sessions WHERE principal = $1", [principal]);
|
|
130
|
-
};
|
|
131
|
-
var sessionVerifierOf = (runtime) => {
|
|
132
|
-
const chosen = runtime.session;
|
|
133
|
-
if (chosen === void 0) {
|
|
134
|
-
throw new Error(
|
|
135
|
-
"moss: `runtime.session` is unset \u2014 authentication is the one door that must not default open. Choose: 'sessions' (moss's stored credential: mintSession/sessionOf/revokeSession), 'dev-open' (every token is trusted; development only), or your own verifier function."
|
|
136
|
-
);
|
|
137
|
-
}
|
|
138
|
-
if (chosen === "sessions") return (token) => sessionOf(runtime.pool, token);
|
|
139
|
-
if (chosen === "dev-open") {
|
|
140
|
-
console.error("[moss] session: dev-open \u2014 every well-formed token is trusted, and a forged principal walks in. Development only.");
|
|
141
|
-
return devSession;
|
|
142
|
-
}
|
|
143
|
-
return chosen;
|
|
144
|
-
};
|
|
145
|
-
|
|
146
|
-
// src/follow.ts
|
|
147
|
-
var createWireFollower = (callSignal) => {
|
|
148
|
-
const controller = new AbortController();
|
|
149
|
-
const end = () => {
|
|
150
|
-
controller.abort();
|
|
151
|
-
};
|
|
152
|
-
if (callSignal.aborted) end();
|
|
153
|
-
else callSignal.addEventListener("abort", end, { once: true });
|
|
154
|
-
const handlers = /* @__PURE__ */ new Set();
|
|
155
|
-
let missed;
|
|
156
|
-
const live = {
|
|
157
|
-
signal: controller.signal,
|
|
158
|
-
onChange: (response) => {
|
|
159
|
-
if (handlers.size === 0) {
|
|
160
|
-
missed = { body: response.result };
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
for (const handler of [...handlers]) handler(response.result);
|
|
164
|
-
}
|
|
165
|
-
};
|
|
166
|
-
const onChange = (handler) => {
|
|
167
|
-
if (controller.signal.aborted) return () => {
|
|
168
|
-
};
|
|
169
|
-
handlers.add(handler);
|
|
170
|
-
if (missed !== void 0) {
|
|
171
|
-
const { body } = missed;
|
|
172
|
-
missed = void 0;
|
|
173
|
-
handler(body);
|
|
174
|
-
}
|
|
175
|
-
return () => {
|
|
176
|
-
handlers.delete(handler);
|
|
177
|
-
if (handlers.size === 0) end();
|
|
178
|
-
};
|
|
179
|
-
};
|
|
180
|
-
const handedOver = () => {
|
|
181
|
-
setTimeout(() => {
|
|
182
|
-
if (handlers.size === 0) end();
|
|
183
|
-
}, 0);
|
|
184
|
-
};
|
|
185
|
-
return { live, onChange, handedOver, end };
|
|
186
|
-
};
|
|
187
|
-
var grammarsOf = (app) => [
|
|
188
|
-
migrations.NOVA_SEQUENCE,
|
|
189
|
-
migrations$1.PRISM_SEQUENCE,
|
|
190
|
-
...app.grammars ?? []
|
|
191
|
-
];
|
|
192
|
-
var createGrammarUpgrader = (app) => strata.createUpgrader(grammarsOf(app), { transform: prism.evaluate });
|
|
193
|
-
var auditClosure = (definitions, variants = {}) => {
|
|
194
|
-
return (grantedIds, layoutIds = []) => {
|
|
195
|
-
const bindings = /* @__PURE__ */ new Map();
|
|
196
|
-
for (const id of layoutIds) {
|
|
197
|
-
const variant = variants[id];
|
|
198
|
-
if (variant !== void 0) bindings.set(variant.action, variant.layout);
|
|
199
|
-
}
|
|
200
|
-
const granted = grantedIds.map((id) => {
|
|
201
|
-
const definition = definitions[id];
|
|
202
|
-
if (definition === void 0) return void 0;
|
|
203
|
-
const layout = bindings.get(id);
|
|
204
|
-
return layout === void 0 ? definition : { ...definition, layout };
|
|
205
|
-
}).filter((definition) => definition !== void 0);
|
|
206
|
-
const catalog = granted.map((definition) => ({ id: definition.id, input: definition.input ?? {} }));
|
|
207
|
-
const channels = [
|
|
208
|
-
...new Set(
|
|
209
|
-
granted.flatMap((definition) => {
|
|
210
|
-
const found = nova.collectChannels(definition);
|
|
211
|
-
return [...found.emits, ...found.listens];
|
|
212
|
-
})
|
|
213
|
-
)
|
|
214
|
-
];
|
|
215
|
-
const issues = [];
|
|
216
|
-
for (const definition of granted) {
|
|
217
|
-
const audit = nova.auditAction(definition, { catalog, channels });
|
|
218
|
-
if (audit.ok) continue;
|
|
219
|
-
for (const issue of audit.issues) {
|
|
220
|
-
if (issue.includes("which is not in the catalog") && !issue.includes("{{")) issues.push(`${definition.id}: ${issue}`);
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
return issues;
|
|
224
|
-
};
|
|
225
|
-
};
|
|
226
|
-
var createDataLayer = async (runtime, entries = []) => {
|
|
227
|
-
const adapter = vex.createPostgresAdapter({ pool: runtime.pool });
|
|
228
|
-
const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
|
|
229
|
-
await cache.init?.();
|
|
230
|
-
await vex.seedCache(cache, entries);
|
|
231
|
-
const engine = vex.createQueryEngine({ adapter, cache, ...runtime.vexConfig !== void 0 ? { config: runtime.vexConfig } : {} });
|
|
232
|
-
const schema = await engine.introspect();
|
|
233
|
-
return { engine, schema, grants: vex.scopeGrants(schema.entities.map((e) => e.name)) };
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
// src/generation.ts
|
|
237
|
-
var GENERATION_DDL = [
|
|
238
|
-
/* sql */
|
|
239
|
-
`CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
|
|
240
|
-
/* sql */
|
|
241
|
-
`INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
|
|
242
|
-
];
|
|
243
|
-
var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
|
|
244
|
-
var createGeneration = (pool, ctx) => {
|
|
245
|
-
const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
|
|
246
|
-
let seen = -1;
|
|
247
|
-
let checking = false;
|
|
248
|
-
const read = async () => {
|
|
249
|
-
if (checking) return;
|
|
250
|
-
checking = true;
|
|
251
|
-
try {
|
|
252
|
-
const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
|
|
253
|
-
const n = Number(result.rows[0]?.n ?? 0);
|
|
254
|
-
if (!Number.isFinite(n)) return;
|
|
255
|
-
const first = seen === -1;
|
|
256
|
-
const moved = !first && n !== seen;
|
|
257
|
-
seen = n;
|
|
258
|
-
if (moved) await ctx.onMoved();
|
|
259
|
-
} catch (err) {
|
|
260
|
-
console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
|
|
261
|
-
} finally {
|
|
262
|
-
checking = false;
|
|
263
|
-
}
|
|
264
|
-
};
|
|
265
|
-
void read();
|
|
266
|
-
const timer = everyMs > 0 ? setInterval(() => void read(), everyMs) : void 0;
|
|
267
|
-
timer?.unref?.();
|
|
268
|
-
return {
|
|
269
|
-
bump: () => {
|
|
270
|
-
void pool.query("UPDATE moss_generation SET n = n + 1 WHERE id = 1").then(async () => {
|
|
271
|
-
const result = await pool.query("SELECT n FROM moss_generation WHERE id = 1");
|
|
272
|
-
seen = Number(result.rows[0]?.n ?? seen);
|
|
273
|
-
}).catch((err) => console.error("[moss:generation] could not move the pointer", err));
|
|
274
|
-
},
|
|
275
|
-
current: () => seen,
|
|
276
|
-
stop: () => {
|
|
277
|
-
if (timer !== void 0) clearInterval(timer);
|
|
278
|
-
}
|
|
279
|
-
};
|
|
280
|
-
};
|
|
281
|
-
var b64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
282
|
-
var fromB64url = (text) => Buffer.from(text.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
283
|
-
var signerFromSeed = (seed) => {
|
|
284
|
-
const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed.subarray(0, 32)]);
|
|
285
|
-
const privateKey = crypto$1.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
|
|
286
|
-
const asInput = privateKey;
|
|
287
|
-
return { privateKey, publicKey: crypto$1.createPublicKey(asInput) };
|
|
288
|
-
};
|
|
289
|
-
var createAssertionSigner = (seedB64) => {
|
|
290
|
-
const seed = seedB64 !== void 0 && seedB64 !== "" ? Buffer.from(seedB64, "base64") : void 0;
|
|
291
|
-
const { publicKey, privateKey } = seed !== void 0 && seed.length >= 32 ? signerFromSeed(seed) : crypto$1.generateKeyPairSync("ed25519");
|
|
292
|
-
const verifyKey = publicKey.export({ type: "spki", format: "der" }).toString("base64");
|
|
293
|
-
return {
|
|
294
|
-
verifyKey,
|
|
295
|
-
mint: (claims, ttlMs = 3e4) => {
|
|
296
|
-
const iat = Date.now();
|
|
297
|
-
const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));
|
|
298
|
-
return `${b64url(body)}.${b64url(crypto$1.sign(null, body, privateKey))}`;
|
|
299
|
-
}
|
|
300
|
-
};
|
|
301
|
-
};
|
|
302
|
-
var verifyAssertion = (token, verifyKey, now = Date.now()) => {
|
|
303
|
-
const dot = token.indexOf(".");
|
|
304
|
-
if (dot <= 0) return void 0;
|
|
305
|
-
try {
|
|
306
|
-
const body = fromB64url(token.slice(0, dot));
|
|
307
|
-
const signature = fromB64url(token.slice(dot + 1));
|
|
308
|
-
const key = crypto$1.createPublicKey({ key: fromB64url(verifyKey), format: "der", type: "spki" });
|
|
309
|
-
if (!crypto$1.verify(null, body, key, signature)) return void 0;
|
|
310
|
-
const parsed = JSON.parse(body.toString());
|
|
311
|
-
if (typeof parsed.integration !== "string" || typeof parsed.principal !== "string") return void 0;
|
|
312
|
-
if (typeof parsed.exp !== "number" || parsed.exp <= now) return void 0;
|
|
313
|
-
return parsed;
|
|
314
|
-
} catch {
|
|
315
|
-
return void 0;
|
|
316
|
-
}
|
|
317
|
-
};
|
|
318
|
-
var mintIntegrationKey = () => `ik_${crypto$1.randomBytes(32).toString("hex")}`;
|
|
319
|
-
var hashIntegrationKey = (key) => crypto$1.createHash("sha256").update(key).digest("hex");
|
|
320
|
-
|
|
321
|
-
// src/integrations.ts
|
|
322
|
-
var configurationBase = {
|
|
323
|
-
key: zod.z.string().regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, "a configuration key is lowercase words joined by single hyphens"),
|
|
324
|
-
title: zod.z.string().min(1),
|
|
325
|
-
description: zod.z.string().default("")
|
|
326
|
-
};
|
|
327
|
-
var configurationSchema = zod.z.array(
|
|
328
|
-
zod.z.discriminatedUnion("kind", [
|
|
329
|
-
zod.z.object({ ...configurationBase, kind: zod.z.literal("toggle"), default: zod.z.boolean() }).strict(),
|
|
330
|
-
zod.z.object({ ...configurationBase, kind: zod.z.literal("number"), min: zod.z.number().int(), max: zod.z.number().int(), default: zod.z.number().int() }).strict(),
|
|
331
|
-
zod.z.object({
|
|
332
|
-
...configurationBase,
|
|
333
|
-
kind: zod.z.literal("pick"),
|
|
334
|
-
options: zod.z.array(zod.z.object({ value: zod.z.string().min(1), label: zod.z.string().min(1) }).strict()).min(2),
|
|
335
|
-
default: zod.z.string().min(1)
|
|
336
|
-
}).strict(),
|
|
337
|
-
zod.z.object({ ...configurationBase, kind: zod.z.literal("line"), maxLength: zod.z.number().int().positive().max(200), default: zod.z.string() }).strict()
|
|
338
|
-
])
|
|
339
|
-
).superRefine((fields, ctx) => {
|
|
340
|
-
const seen = /* @__PURE__ */ new Set();
|
|
341
|
-
fields.forEach((field, i) => {
|
|
342
|
-
if (seen.has(field.key)) ctx.addIssue({ code: "custom", path: [i, "key"], message: `configuration "${field.key}": declared twice` });
|
|
343
|
-
seen.add(field.key);
|
|
344
|
-
if (field.kind === "number") {
|
|
345
|
-
if (field.min >= field.max) ctx.addIssue({ code: "custom", path: [i], message: `configuration "${field.key}": min ${field.min} is not below max ${field.max}` });
|
|
346
|
-
if (field.default < field.min || field.default > field.max) {
|
|
347
|
-
ctx.addIssue({ code: "custom", path: [i, "default"], message: `configuration "${field.key}": default ${field.default} is outside [${field.min}, ${field.max}]` });
|
|
348
|
-
}
|
|
349
|
-
} else if (field.kind === "pick") {
|
|
350
|
-
const values = field.options.map((o) => o.value);
|
|
351
|
-
if (new Set(values).size !== values.length) ctx.addIssue({ code: "custom", path: [i, "options"], message: `configuration "${field.key}": option values repeat` });
|
|
352
|
-
if (!values.includes(field.default)) ctx.addIssue({ code: "custom", path: [i, "default"], message: `configuration "${field.key}": default "${field.default}" is not one of its options` });
|
|
353
|
-
} else if (field.kind === "line") {
|
|
354
|
-
if (field.default.length > field.maxLength) ctx.addIssue({ code: "custom", path: [i, "default"], message: `configuration "${field.key}": default is longer than maxLength ${field.maxLength}` });
|
|
355
|
-
}
|
|
356
|
-
});
|
|
357
|
-
}).default([]);
|
|
358
|
-
var FieldKind = zod.z.enum(["line", "long", "url", "pick", "asset", "color", "number", "toggle", "list"]);
|
|
359
|
-
var documentFieldSchema = zod.z.object({
|
|
360
|
-
// A data key, or a CSS custom property (`--color-brand`) for a theme token.
|
|
361
|
-
key: zod.z.string().regex(/^[a-z][a-z0-9-]*$|^--[a-z][a-z0-9-]*$/, "a field key is lowercase-hyphen, optionally a `--` custom property"),
|
|
362
|
-
label: zod.z.string().min(1),
|
|
363
|
-
kind: FieldKind,
|
|
364
|
-
hint: zod.z.string().default(""),
|
|
365
|
-
placeholder: zod.z.string().default(""),
|
|
366
|
-
group: zod.z.string().default(""),
|
|
367
|
-
advanced: zod.z.boolean().default(false),
|
|
368
|
-
// Only meaningful for `pick`; intake refuses a `pick` with fewer than two.
|
|
369
|
-
options: zod.z.array(zod.z.object({ value: zod.z.string().min(1), label: zod.z.string().min(1) }).strict()).default([]),
|
|
370
|
-
max: zod.z.number().int().positive().optional()
|
|
371
|
-
}).strict();
|
|
372
|
-
var sectionTypeSchema = zod.z.object({
|
|
373
|
-
type: zod.z.string().min(1),
|
|
374
|
-
label: zod.z.string().min(1),
|
|
375
|
-
fields: zod.z.array(documentFieldSchema).min(1),
|
|
376
|
-
// The default content a new section of this type starts with.
|
|
377
|
-
starter: zod.z.record(zod.z.string(), zod.z.unknown()).default({}),
|
|
378
|
-
// The nova layout that draws this section over `$.content`. Typed as the
|
|
379
|
-
// real layout schema (not `unknown`) so a malformed fragment is refused at
|
|
380
|
-
// intake by SHAPE, and then walked by `validateLayout` for component/prop
|
|
381
|
-
// existence — the exact rigor an action's own layout gets.
|
|
382
|
-
fragment: nova.LayoutNodeSchema
|
|
383
|
-
}).strict();
|
|
384
|
-
var sectionsSchema = zod.z.union([
|
|
385
|
-
zod.z.object({
|
|
386
|
-
fixed: zod.z.array(
|
|
387
|
-
zod.z.object({ id: zod.z.string().min(1), type: zod.z.string().min(1), label: zod.z.string().min(1), extends: zod.z.string().optional() }).strict()
|
|
388
|
-
).min(1)
|
|
389
|
-
}).strict(),
|
|
390
|
-
zod.z.object({ open: zod.z.object({ max: zod.z.number().int().positive().max(40) }).strict() }).strict()
|
|
391
|
-
]);
|
|
392
|
-
var documentDeclarationSchema = zod.z.object({
|
|
393
|
-
id: zod.z.string().regex(/^[a-z][a-z0-9-]*$/, "a document id is lowercase words joined by single hyphens"),
|
|
394
|
-
title: zod.z.string().min(1),
|
|
395
|
-
// The capability that opens the editor on this document — one of the
|
|
396
|
-
// bundle's own `capabilities`, so the host's charter can grant it.
|
|
397
|
-
capability: zod.z.string().min(1),
|
|
398
|
-
registry: zod.z.array(sectionTypeSchema).min(1),
|
|
399
|
-
sections: sectionsSchema,
|
|
400
|
-
// Region actions the editor wants when the host's defaults do not fit (a
|
|
401
|
-
// product's stage is a live shell, not fragments). Each is one of the
|
|
402
|
-
// bundle's own actions or a region the host offers.
|
|
403
|
-
regions: zod.z.object({ bar: zod.z.string().optional(), outline: zod.z.string().optional(), stage: zod.z.string().optional(), inspector: zod.z.string().optional() }).strict().default({}),
|
|
404
|
-
// Checks that run before publish (the theme's readability floors), each one
|
|
405
|
-
// the host holds.
|
|
406
|
-
checks: zod.z.array(zod.z.string().min(1)).default([]),
|
|
407
|
-
// Where a published document is delivered: a route under the integration's
|
|
408
|
-
// own prefix. The add-on owns the live rows and the public renderer; the
|
|
409
|
-
// host owns the draft and the revisions.
|
|
410
|
-
publish: zod.z.object({ path: zod.z.string().min(1) }).strict()
|
|
411
|
-
}).strict();
|
|
412
|
-
var blockTypeSchema = zod.z.object({
|
|
413
|
-
type: zod.z.string().min(1),
|
|
414
|
-
label: zod.z.string().min(1),
|
|
415
|
-
fields: zod.z.array(documentFieldSchema).default([]),
|
|
416
|
-
// Data keys the block reads — carried, the block's own contract with its
|
|
417
|
-
// fragment; moss does not resolve them.
|
|
418
|
-
refs: zod.z.array(zod.z.string().min(1)).default([]),
|
|
419
|
-
fragment: nova.LayoutNodeSchema
|
|
420
|
-
}).strict();
|
|
421
|
-
var assistantDeclarationSchema = zod.z.object({
|
|
422
|
-
id: zod.z.string().regex(/^[a-z][a-z0-9-]*$/, "an assistant id is lowercase words joined by single hyphens"),
|
|
423
|
-
title: zod.z.string().min(1),
|
|
424
|
-
intro: zod.z.string().default(""),
|
|
425
|
-
instructions: zod.z.string().min(1),
|
|
426
|
-
// The reads it may run — each a host vex fingerprint the session may already
|
|
427
|
-
// call, under a heading (`as`) the rows appear beneath. `upfront` fetches at
|
|
428
|
-
// thread start rather than on demand.
|
|
429
|
-
grounding: zod.z.array(
|
|
430
|
-
zod.z.object({ as: zod.z.string().min(1), fingerprint: zod.z.string().min(1), context: zod.z.record(zod.z.string(), zod.z.unknown()).default({}), upfront: zod.z.boolean().default(false) }).strict()
|
|
431
|
-
).default([]),
|
|
432
|
-
// Host tools it may call, from the host's closed set (`floors`, `derive`).
|
|
433
|
-
tools: zod.z.array(zod.z.string().min(1)).default([]),
|
|
434
|
-
blocks: zod.z.array(blockTypeSchema).default([]),
|
|
435
|
-
starters: zod.z.array(zod.z.string().min(1)).max(6).default([]),
|
|
436
|
-
// One of the bundle's own documents, or one of its own screens (actions),
|
|
437
|
-
// so the host can find the row from what is on screen. An add-on attaches an
|
|
438
|
-
// assistant to its own surfaces only.
|
|
439
|
-
applies: zod.z.object({ document: zod.z.string().optional(), screen: zod.z.string().optional() }).strict(),
|
|
440
|
-
modelRole: zod.z.string().optional(),
|
|
441
|
-
// Data keys of the screen the thread is keyed by, and the keys sent to the
|
|
442
|
-
// model (absent = all). Carried; the host's `say` is the consumer.
|
|
443
|
-
subject: zod.z.array(zod.z.string().min(1)).default([]),
|
|
444
|
-
describe: zod.z.array(zod.z.string().min(1)).optional()
|
|
445
|
-
}).strict();
|
|
446
|
-
var BundleSchema = zod.z.object({
|
|
447
|
-
integration: zod.z.string().min(1),
|
|
448
|
-
// The store card's words, and the listing page's long form. Title, a
|
|
449
|
-
// line, a paragraph — then the story (sections a page renders in order),
|
|
450
|
-
// the highlight lines, and the press images. Story and highlights are
|
|
451
|
-
// text, enforced as nothing more; press is the one field with teeth: each
|
|
452
|
-
// entry is a path under the integration's own prefix, fetched ONCE at
|
|
453
|
-
// intake and copied to the host (copyPress), never fetched at render
|
|
454
|
-
// time. Strict, unlike before: a typo'd key here used to strip silently,
|
|
455
|
-
// which is not what "intake refuses anything outside the vocabulary"
|
|
456
|
-
// means.
|
|
457
|
-
meta: zod.z.object({
|
|
458
|
-
title: zod.z.string().default(""),
|
|
459
|
-
tagline: zod.z.string().default(""),
|
|
460
|
-
description: zod.z.string().default(""),
|
|
461
|
-
story: zod.z.array(zod.z.object({ heading: zod.z.string(), prose: zod.z.string() }).strict()).default([]),
|
|
462
|
-
highlights: zod.z.array(zod.z.string()).default([]),
|
|
463
|
-
press: zod.z.array(zod.z.string()).default([])
|
|
464
|
-
}).strict().default({ title: "", tagline: "", description: "", story: [], highlights: [], press: [] }),
|
|
465
|
-
// What it needs, which an operator approves once at registration. A bundle
|
|
466
|
-
// asking for more than it was approved for goes back to pending rather than
|
|
467
|
-
// silently keeping the old grants and half-working.
|
|
468
|
-
grants: zod.z.object({
|
|
469
|
-
actions: zod.z.array(zod.z.string()).default([]),
|
|
470
|
-
data: zod.z.array(zod.z.string()).default([])
|
|
471
|
-
}).default({ actions: [], data: [] }),
|
|
472
|
-
// THE VERBS THIS INTEGRATION GATES ON — the other direction from `grants`.
|
|
473
|
-
// Grants are what it ASKS OF the host (surfaces it may call); a capability
|
|
474
|
-
// is what it OFFERS the host's role editor to grant to PEOPLE, and its own
|
|
475
|
-
// service is the code that checks the grant (`can(who, '<integration>.<id>')`).
|
|
476
|
-
// moss validates shape and carries them, nothing more: WHICH endpoints a
|
|
477
|
-
// capability gates is the integration's contract with its own service,
|
|
478
|
-
// exactly as a fact kind's meaning and `meta`'s words are checked against
|
|
479
|
-
// nothing here. The host composes the full grant string as `<integration>.
|
|
480
|
-
// <id>` — a bundle cannot claim another integration's namespace — which is
|
|
481
|
-
// why the id forbids a dot: it has to stay splittable, the same reason the
|
|
482
|
-
// action namespace does. A capability carries no statement about WHO should
|
|
483
|
-
// hold it: no face, no audience, no population marker. Every role grants it
|
|
484
|
-
// identically, and who holds one is authored data in the host (its role
|
|
485
|
-
// grants), never a declaration here. There is deliberately no gates list —
|
|
486
|
-
// moss could name-check one (it name-checks every other cross-reference
|
|
487
|
-
// below) but no consumer needs it; the field is additive if one appears.
|
|
488
|
-
capabilities: zod.z.array(
|
|
489
|
-
zod.z.object({
|
|
490
|
-
id: zod.z.string().regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, "a capability id is lowercase words joined by single hyphens, and never a dot"),
|
|
491
|
-
title: zod.z.string().min(1)
|
|
492
|
-
}).strict()
|
|
493
|
-
).default([]),
|
|
494
|
-
// WHAT IT TELLS AND WHAT IT HEARS — the fact kinds this integration
|
|
495
|
-
// publishes and the kinds it consumes. moss validates shape and carries
|
|
496
|
-
// them; what a kind MEANS is the host's contract vocabulary, exactly as
|
|
497
|
-
// `meta` is words validated against nothing. There is no optional flag
|
|
498
|
-
// to declare: the host's laws forbid a hard dependency between
|
|
499
|
-
// integrations, so every need is soft by construction — absence
|
|
500
|
-
// degrades, and the store says so in a sentence the HOST prints.
|
|
501
|
-
offers: zod.z.array(zod.z.string()).default([]),
|
|
502
|
-
needs: zod.z.array(zod.z.string()).default([]),
|
|
503
|
-
// THE GRAMMARS THE ADD-ON WAS BUILT ON — how far along each grammar sequence
|
|
504
|
-
// (nova's, Prism's, the host's kit) its documents are written. The host
|
|
505
|
-
// upgrades them from here before anything else reads them, and refuses a
|
|
506
|
-
// bundle written in a grammar newer than its own. Absent: before stamps.
|
|
507
|
-
grammar: zod.z.record(zod.z.string(), zod.z.number().int().nonnegative()).optional(),
|
|
508
|
-
actions: zod.z.record(zod.z.string(), nova.ActionDefinitionSchema),
|
|
509
|
-
// action id → HOST action it rides on (a panel on the member detail). The
|
|
510
|
-
// host must have declared itself attachable — see IntakeContext. The long
|
|
511
|
-
// form adds a `preview`: an endpoint under the integration's own prefix that the
|
|
512
|
-
// host calls with the offered identifiers while deriving its strip, and
|
|
513
|
-
// that answers with display atoms — `bands` (colors) and `hint` (a line) —
|
|
514
|
-
// so the rider's row can SHOW the belt, not the word for it, while the
|
|
515
|
-
// host still learns nothing about what a belt is.
|
|
516
|
-
attachments: zod.z.record(
|
|
517
|
-
zod.z.string(),
|
|
518
|
-
zod.z.union([zod.z.string(), zod.z.object({ to: zod.z.string(), preview: zod.z.string().default("") }).strict()])
|
|
519
|
-
).default({}),
|
|
520
|
-
// action id → the MENU HUB it lists under (a roster under People). The hub
|
|
521
|
-
// must be one the host offers to integrations.
|
|
522
|
-
placements: zod.z.record(zod.z.string(), zod.z.string()).default({}),
|
|
523
|
-
// PAGES THE INTEGRATION SERVES AND THE HOST FRAMES. Lyra validates every layout
|
|
524
|
-
// against a fixed component vocabulary, so an integration cannot ship UI — which is
|
|
525
|
-
// right until a vendor's own browser SDK is the only way to render
|
|
526
|
-
// something (a payment onboarding form). The answer is not to teach the
|
|
527
|
-
// host's kit about the vendor: it is for the integration to serve a page and the
|
|
528
|
-
// host to frame it, at its own origin, gated by exactly what every other
|
|
529
|
-
// integration call is gated by.
|
|
530
|
-
//
|
|
531
|
-
// Named lyra-side, like `preview`, and under the integration's own prefix. What is
|
|
532
|
-
// inside a frame the host does NOT validate — that is the real cost, and it
|
|
533
|
-
// is why this is a declaration rather than an iframe a layout can conjure.
|
|
534
|
-
//
|
|
535
|
-
// PATH → THE ACTION IT BELONGS TO, and the second half is not decoration.
|
|
536
|
-
// A grant is minted for whoever asks, so without an owner the only questions
|
|
537
|
-
// this door could ask were "signed in?" and "installed here?" — which a
|
|
538
|
-
// member of the gym passes. Naming the action makes the grant answerable
|
|
539
|
-
// against the charter: a page belonging to a desk screen is mintable by
|
|
540
|
-
// somebody who holds that desk screen, and by nobody else.
|
|
541
|
-
frames: zod.z.record(zod.z.string(), zod.z.string()).default({}),
|
|
542
|
-
// The ONE action allowed to surface in the store: this integration's own
|
|
543
|
-
// settings screen, reachable from its tile and from nowhere else. Add-ons
|
|
544
|
-
// is a store; nothing functional lives there.
|
|
545
|
-
settings: zod.z.string().default(""),
|
|
546
|
-
// THE INTEGRATION'S OWN WORDS, in the languages it speaks — the same
|
|
547
|
-
// `(language, source, text)` shape the host's book uses, keyed by
|
|
548
|
-
// LANGUAGE, never by full locale: Vienna and Hamburg read the same
|
|
549
|
-
// sentences, and region is money and dates, which never come from a
|
|
550
|
-
// book. A malformed key refuses the whole bundle at intake, exactly as a
|
|
551
|
-
// placement outside the vocabulary does. The host merges these under its
|
|
552
|
-
// own book, so an integration can never rename a host word.
|
|
553
|
-
phrasebook: zod.z.record(zod.z.string().regex(/^[a-z]{2}$/, "a phrasebook is keyed by LANGUAGE (`de`), never by locale (`de-AT`)"), zod.z.record(zod.z.string(), zod.z.string())).default({}),
|
|
554
|
-
// WHAT A BUILDER MAY SET per product — a closed vocabulary of settings the
|
|
555
|
-
// host renders a form from. Carried, never read: the value's meaning is the
|
|
556
|
-
// integration's contract with its own service. See `configurationSchema`.
|
|
557
|
-
configuration: configurationSchema,
|
|
558
|
-
// WHAT AN ADD-ON LETS A PERSON EDIT in the host's editor — section types,
|
|
559
|
-
// fields, fragments, and a section model. See `documentDeclarationSchema`.
|
|
560
|
-
documents: zod.z.array(documentDeclarationSchema).default([]),
|
|
561
|
-
// WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO — instructions, grounding,
|
|
562
|
-
// blocks, tools, and what it applies to. See `assistantDeclarationSchema`.
|
|
563
|
-
assistants: zod.z.array(assistantDeclarationSchema).default([])
|
|
564
|
-
}).strict();
|
|
565
|
-
var normalizeReach = (path) => (path.split("?")[0] ?? "").replace(/\/+$/, "");
|
|
566
|
-
var reachOf = (bundle, integrationId) => {
|
|
567
|
-
const own = `/integrations/${integrationId}/`;
|
|
568
|
-
const reach = {};
|
|
569
|
-
const admit = (url, actionId) => {
|
|
570
|
-
if (!url.startsWith(own)) return;
|
|
571
|
-
const key = normalizeReach(url);
|
|
572
|
-
const held = reach[key] ??= [];
|
|
573
|
-
if (!held.includes(actionId)) held.push(actionId);
|
|
574
|
-
};
|
|
575
|
-
for (const [actionId, raw] of Object.entries(bundle.actions)) {
|
|
576
|
-
for (const endpoint of Object.values(raw.endpoints ?? {})) {
|
|
577
|
-
admit(endpoint.url ?? "", actionId);
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
for (const [actionId, binding] of Object.entries(bundle.attachments)) {
|
|
581
|
-
if (typeof binding !== "string") admit(binding.preview, actionId);
|
|
582
|
-
}
|
|
583
|
-
return Object.fromEntries(Object.entries(reach).sort(([a], [b]) => a.localeCompare(b)));
|
|
584
|
-
};
|
|
585
|
-
var reachAdmits = (reach, path, held) => (reach[normalizeReach(path)] ?? []).some((actionId) => held.has(actionId));
|
|
586
|
-
var reachDeclares = (reach, path) => reach[normalizeReach(path)] !== void 0;
|
|
587
|
-
var frameAdmits = (frames, path, held) => {
|
|
588
|
-
const owner = frames[path];
|
|
589
|
-
return owner !== void 0 && held.has(owner);
|
|
590
|
-
};
|
|
591
|
-
var intakeContextOf = (app, integrationId, fingerprints, upgrader) => ({
|
|
592
|
-
integrationId,
|
|
593
|
-
...upgrader === void 0 ? {} : { upgrader },
|
|
594
|
-
components: new Map(Object.entries(app.shell?.components ?? {}).map(([name, def]) => [name, { propsSchema: def.meta?.propsSchema }])),
|
|
595
|
-
fingerprints,
|
|
596
|
-
attachable: new Set(Object.keys(app.attachable ?? {})),
|
|
597
|
-
menuSlots: new Set(app.menuSlots ?? []),
|
|
598
|
-
tools: new Set(app.assistantTools ?? []),
|
|
599
|
-
checks: new Set(app.publishChecks ?? []),
|
|
600
|
-
regions: new Set(app.editorRegions ?? []),
|
|
601
|
-
hostActions: app.actions
|
|
10
|
+
Object.defineProperty(exports, "MOSS_SEQUENCE", {
|
|
11
|
+
enumerable: true,
|
|
12
|
+
get: function () { return chunkR66WUKGC_cjs.MOSS_SEQUENCE; }
|
|
602
13
|
});
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
var isPlainRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
607
|
-
var upgradeBundle = (payload, upgrader) => {
|
|
608
|
-
if (upgrader === void 0 || !isPlainRecord(payload) || !isPlainRecord(payload["actions"])) return { ok: true, payload };
|
|
609
|
-
const declared = payload["grammar"];
|
|
610
|
-
const stamp = isPlainRecord(declared) ? Object.fromEntries(Object.entries(declared).map(([k, v]) => [k, Number(v)])) : {};
|
|
611
|
-
try {
|
|
612
|
-
const actions = Object.fromEntries(
|
|
613
|
-
Object.entries(payload["actions"]).map(([id, definition]) => [id, upgrader.upgrade(definition, { kind: "nisc.nova/action", stamp }).document])
|
|
614
|
-
);
|
|
615
|
-
return { ok: true, payload: { ...payload, actions, grammar: upgrader.stamp } };
|
|
616
|
-
} catch (error) {
|
|
617
|
-
if (!(error instanceof strata.StrataError)) throw error;
|
|
618
|
-
return {
|
|
619
|
-
ok: false,
|
|
620
|
-
reasons: error.code === "TOO_NEW" ? ["This integration was built on newer nisc grammars than this host runs \u2014 the host must be updated first.", ...error.details] : [error.message.split("\n")[0] ?? error.code, ...error.details]
|
|
621
|
-
};
|
|
622
|
-
}
|
|
623
|
-
};
|
|
624
|
-
var runIntake = (payload, ctx) => {
|
|
625
|
-
if (strata.exceedsDepth(payload)) return { ok: false, reasons: [strata.depthRefusal()] };
|
|
626
|
-
const upgraded = upgradeBundle(payload, ctx.upgrader);
|
|
627
|
-
if (!upgraded.ok) return upgraded;
|
|
628
|
-
const parsed = BundleSchema.safeParse(upgraded.payload);
|
|
629
|
-
if (!parsed.success) {
|
|
630
|
-
return { ok: false, reasons: parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`) };
|
|
631
|
-
}
|
|
632
|
-
const bundle = parsed.data;
|
|
633
|
-
const reasons = [];
|
|
634
|
-
const validateLayout = (node, label) => {
|
|
635
|
-
const found = /* @__PURE__ */ new Set();
|
|
636
|
-
reflect.walkNodes(node, (record) => {
|
|
637
|
-
const name = record["component"];
|
|
638
|
-
if (typeof name !== "string") return;
|
|
639
|
-
const spec = ctx.components.get(name);
|
|
640
|
-
if (spec === void 0) {
|
|
641
|
-
found.add(`${label}: layout uses "${name}", which this app has no component for`);
|
|
642
|
-
return;
|
|
643
|
-
}
|
|
644
|
-
const schema = spec.propsSchema;
|
|
645
|
-
const props = record["props"];
|
|
646
|
-
if (!(schema instanceof zod.z.ZodObject) || !reflect.isRecord(props)) return;
|
|
647
|
-
const shape = schema.shape;
|
|
648
|
-
for (const [key, value] of Object.entries(props)) {
|
|
649
|
-
if (!(key in shape)) {
|
|
650
|
-
found.add(`${label}: "${name}" has no prop "${key}"`);
|
|
651
|
-
continue;
|
|
652
|
-
}
|
|
653
|
-
if (isDeferred(value)) continue;
|
|
654
|
-
const check = shape[key]?.safeParse(value);
|
|
655
|
-
if (check !== void 0 && !check.success) {
|
|
656
|
-
found.add(`${label}: "${name}" prop "${key}" \u2014 ${check.error.issues[0]?.message ?? "invalid"}`);
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
});
|
|
660
|
-
for (const reason of found) reasons.push(reason);
|
|
661
|
-
};
|
|
662
|
-
if (bundle.integration !== ctx.integrationId) {
|
|
663
|
-
reasons.push(`bundle says it is "${bundle.integration}" but was fetched as "${ctx.integrationId}"`);
|
|
664
|
-
}
|
|
665
|
-
for (const [id, raw] of Object.entries(bundle.actions)) {
|
|
666
|
-
const action = raw;
|
|
667
|
-
const parts = id.split(".");
|
|
668
|
-
if (parts[0] !== "ext" || parts.length < 4 || !AUDIENCE.test(parts[1] ?? "")) {
|
|
669
|
-
reasons.push(`action ${id}: not namespaced ext.<audience>.<integration>.<name>`);
|
|
670
|
-
} else if (parts[2] !== ctx.integrationId) {
|
|
671
|
-
reasons.push(`action ${id}: claims the "${parts[2]}" namespace, which belongs to somebody else`);
|
|
672
|
-
}
|
|
673
|
-
if (action.id !== id) reasons.push(`action ${id}: its own id says "${action.id}"`);
|
|
674
|
-
validateLayout(action.layout, `action ${id}`);
|
|
675
|
-
for (const [name, endpoint] of Object.entries(action.endpoints ?? {})) {
|
|
676
|
-
const ep = endpoint;
|
|
677
|
-
if (ep.fn !== void 0) {
|
|
678
|
-
reasons.push(`action ${id}: endpoint "${name}" uses fn:, which runs in this app's process`);
|
|
679
|
-
continue;
|
|
680
|
-
}
|
|
681
|
-
const url = ep.url ?? "";
|
|
682
|
-
const own = `/integrations/${ctx.integrationId}/`;
|
|
683
|
-
if (url === FRAME_GRANT_URL) continue;
|
|
684
|
-
if (url.startsWith(own)) {
|
|
685
|
-
if (url.startsWith(`${own}hook/`)) {
|
|
686
|
-
reasons.push(`action ${id}: endpoint "${name}" is under /hook/, which is the unauthenticated webhook path`);
|
|
687
|
-
}
|
|
688
|
-
if (url.startsWith(`${own}frame/`)) {
|
|
689
|
-
reasons.push(`action ${id}: endpoint "${name}" is under /frame/, which redeems frame grants`);
|
|
690
|
-
}
|
|
691
|
-
continue;
|
|
692
|
-
}
|
|
693
|
-
if (!url.startsWith("/api/")) {
|
|
694
|
-
reasons.push(`action ${id}: endpoint "${name}" calls "${url}" \u2014 only ${own}* or /api/*/vex`);
|
|
695
|
-
continue;
|
|
696
|
-
}
|
|
697
|
-
const fingerprint = ep.request?.fingerprint;
|
|
698
|
-
if (typeof fingerprint !== "string") {
|
|
699
|
-
reasons.push(`action ${id}: endpoint "${name}" calls the app without naming a fingerprint`);
|
|
700
|
-
} else if (!ctx.fingerprints.has(fingerprint)) {
|
|
701
|
-
reasons.push(`action ${id}: endpoint "${name}" calls "${fingerprint}", which this app does not serve`);
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
for (const cycle of reflect.chainCycles({ ...ctx.hostActions ?? {}, ...bundle.actions })) {
|
|
706
|
-
if (cycle.steps.some((step) => bundle.actions[step.action] !== void 0)) {
|
|
707
|
-
reasons.push(`a chain of steps that never ends: ${cycle.path}`);
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
for (const [actionId, binding] of Object.entries(bundle.attachments)) {
|
|
711
|
-
const host = typeof binding === "string" ? binding : binding.to;
|
|
712
|
-
const preview = typeof binding === "string" ? "" : binding.preview;
|
|
713
|
-
if (bundle.actions[actionId] === void 0) reasons.push(`attachment ${actionId}: no such action in this bundle`);
|
|
714
|
-
if (!ctx.attachable.has(host)) reasons.push(`attachment ${actionId}: attaches to "${host}", which offers nothing`);
|
|
715
|
-
if (preview !== "" && !preview.startsWith(`/integrations/${ctx.integrationId}/`)) {
|
|
716
|
-
reasons.push(`attachment ${actionId}: preview "${preview}" is not under this integration's own prefix`);
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
for (const [actionId, hub] of Object.entries(bundle.placements)) {
|
|
720
|
-
if (bundle.actions[actionId] === void 0) reasons.push(`placement ${actionId}: no such action in this bundle`);
|
|
721
|
-
if (!ctx.menuSlots.has(hub)) reasons.push(`placement ${actionId}: targets "${hub}", which accepts no integrations`);
|
|
722
|
-
}
|
|
723
|
-
const ownPrefix = `/integrations/${ctx.integrationId}/`;
|
|
724
|
-
for (const [path, actionId] of Object.entries(bundle.frames)) {
|
|
725
|
-
if (!path.startsWith(ownPrefix)) {
|
|
726
|
-
reasons.push(`frame "${path}": not under this integration's own prefix`);
|
|
727
|
-
} else if (path.startsWith(`${ownPrefix}hook/`) || path.startsWith(`${ownPrefix}frame/`)) {
|
|
728
|
-
reasons.push(`frame "${path}": /hook/ and /frame/ are reserved`);
|
|
729
|
-
}
|
|
730
|
-
if (bundle.actions[actionId] === void 0) {
|
|
731
|
-
reasons.push(`frame "${path}": belongs to "${actionId}", which is not an action in this bundle`);
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
for (const path of bundle.meta.press) {
|
|
735
|
-
if (!path.startsWith(ownPrefix)) {
|
|
736
|
-
reasons.push(`press "${path}": not under this integration's own prefix`);
|
|
737
|
-
} else if (path.startsWith(`${ownPrefix}hook/`) || path.startsWith(`${ownPrefix}frame/`)) {
|
|
738
|
-
reasons.push(`press "${path}": /hook/ and /frame/ are reserved`);
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
const seenCapability = /* @__PURE__ */ new Set();
|
|
742
|
-
for (const capability of bundle.capabilities) {
|
|
743
|
-
if (seenCapability.has(capability.id)) {
|
|
744
|
-
reasons.push(`capability "${capability.id}": declared twice`);
|
|
745
|
-
}
|
|
746
|
-
seenCapability.add(capability.id);
|
|
747
|
-
}
|
|
748
|
-
if (bundle.settings !== "" && bundle.actions[bundle.settings] === void 0) {
|
|
749
|
-
reasons.push(`settings: "${bundle.settings}" is not an action in this bundle`);
|
|
750
|
-
}
|
|
751
|
-
const ownActions = new Set(Object.keys(bundle.actions));
|
|
752
|
-
const ownCapabilities = new Set(bundle.capabilities.map((c) => c.id));
|
|
753
|
-
const hostRegions = ctx.regions ?? /* @__PURE__ */ new Set();
|
|
754
|
-
const hostChecks = ctx.checks ?? /* @__PURE__ */ new Set();
|
|
755
|
-
const seenDocument = /* @__PURE__ */ new Set();
|
|
756
|
-
for (const doc of bundle.documents) {
|
|
757
|
-
if (seenDocument.has(doc.id)) reasons.push(`document "${doc.id}": declared twice`);
|
|
758
|
-
seenDocument.add(doc.id);
|
|
759
|
-
if (!ownCapabilities.has(doc.capability)) {
|
|
760
|
-
reasons.push(`document "${doc.id}": capability "${doc.capability}" is not one this bundle declares`);
|
|
761
|
-
}
|
|
762
|
-
if (!doc.publish.path.startsWith(ownPrefix)) {
|
|
763
|
-
reasons.push(`document "${doc.id}": publish path "${doc.publish.path}" is not under this integration's own prefix`);
|
|
764
|
-
}
|
|
765
|
-
for (const [region, actionId] of Object.entries(doc.regions)) {
|
|
766
|
-
if (actionId === void 0) continue;
|
|
767
|
-
if (!ownActions.has(actionId) && !hostRegions.has(actionId)) {
|
|
768
|
-
reasons.push(`document "${doc.id}": region "${region}" names "${actionId}", which is neither an action in this bundle nor a region the host offers`);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
for (const check of doc.checks) {
|
|
772
|
-
if (!hostChecks.has(check)) reasons.push(`document "${doc.id}": check "${check}" is not one the host offers`);
|
|
773
|
-
}
|
|
774
|
-
const registryTypes = new Set(doc.registry.map((s) => s.type));
|
|
775
|
-
const seenType = /* @__PURE__ */ new Set();
|
|
776
|
-
for (const section of doc.registry) {
|
|
777
|
-
if (seenType.has(section.type)) reasons.push(`document "${doc.id}": section type "${section.type}" declared twice`);
|
|
778
|
-
seenType.add(section.type);
|
|
779
|
-
const seenKey = /* @__PURE__ */ new Set();
|
|
780
|
-
for (const field of section.fields) {
|
|
781
|
-
if (seenKey.has(field.key)) reasons.push(`document "${doc.id}" section "${section.type}": field key "${field.key}" declared twice`);
|
|
782
|
-
seenKey.add(field.key);
|
|
783
|
-
if (field.kind === "pick" && field.options.length < 2) {
|
|
784
|
-
reasons.push(`document "${doc.id}" section "${section.type}": pick field "${field.key}" needs at least two options`);
|
|
785
|
-
}
|
|
786
|
-
if (field.kind === "list") {
|
|
787
|
-
reasons.push(`document "${doc.id}" section "${section.type}": a list field is only allowed inside an assistant block`);
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
validateLayout(section.fragment, `document "${doc.id}" section "${section.type}" fragment`);
|
|
791
|
-
}
|
|
792
|
-
if ("fixed" in doc.sections) {
|
|
793
|
-
const siblingIds = new Set(doc.sections.fixed.map((f) => f.id));
|
|
794
|
-
for (const f of doc.sections.fixed) {
|
|
795
|
-
if (!registryTypes.has(f.type)) reasons.push(`document "${doc.id}": fixed section "${f.id}" has type "${f.type}", which is not in the registry`);
|
|
796
|
-
if (f.extends !== void 0 && !siblingIds.has(f.extends)) {
|
|
797
|
-
reasons.push(`document "${doc.id}": fixed section "${f.id}" extends "${f.extends}", which is not a sibling`);
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
const documentIds = new Set(bundle.documents.map((d) => d.id));
|
|
803
|
-
const hostTools = ctx.tools ?? /* @__PURE__ */ new Set();
|
|
804
|
-
const seenAssistant = /* @__PURE__ */ new Set();
|
|
805
|
-
for (const assistant of bundle.assistants) {
|
|
806
|
-
if (seenAssistant.has(assistant.id)) reasons.push(`assistant "${assistant.id}": declared twice`);
|
|
807
|
-
seenAssistant.add(assistant.id);
|
|
808
|
-
if (assistant.applies.document === void 0 && assistant.applies.screen === void 0) {
|
|
809
|
-
reasons.push(`assistant "${assistant.id}": applies to neither a document nor a screen`);
|
|
810
|
-
}
|
|
811
|
-
if (assistant.applies.document !== void 0 && !documentIds.has(assistant.applies.document)) {
|
|
812
|
-
reasons.push(`assistant "${assistant.id}": applies to document "${assistant.applies.document}", which this bundle does not declare`);
|
|
813
|
-
}
|
|
814
|
-
if (assistant.applies.screen !== void 0 && !ownActions.has(assistant.applies.screen)) {
|
|
815
|
-
reasons.push(`assistant "${assistant.id}": applies to screen "${assistant.applies.screen}", which is not an action in this bundle`);
|
|
816
|
-
}
|
|
817
|
-
for (const read of assistant.grounding) {
|
|
818
|
-
if (!ctx.fingerprints.has(read.fingerprint)) {
|
|
819
|
-
reasons.push(`assistant "${assistant.id}": grounding "${read.as}" reads "${read.fingerprint}", which this app does not serve`);
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
for (const tool of assistant.tools) {
|
|
823
|
-
if (!hostTools.has(tool)) reasons.push(`assistant "${assistant.id}": tool "${tool}" is not one the host offers`);
|
|
824
|
-
}
|
|
825
|
-
const seenBlock = /* @__PURE__ */ new Set();
|
|
826
|
-
for (const block of assistant.blocks) {
|
|
827
|
-
if (seenBlock.has(block.type)) reasons.push(`assistant "${assistant.id}": block type "${block.type}" declared twice`);
|
|
828
|
-
seenBlock.add(block.type);
|
|
829
|
-
const seenKey = /* @__PURE__ */ new Set();
|
|
830
|
-
for (const field of block.fields) {
|
|
831
|
-
if (seenKey.has(field.key)) reasons.push(`assistant "${assistant.id}" block "${block.type}": field key "${field.key}" declared twice`);
|
|
832
|
-
seenKey.add(field.key);
|
|
833
|
-
if (field.kind === "pick" && field.options.length < 2) {
|
|
834
|
-
reasons.push(`assistant "${assistant.id}" block "${block.type}": pick field "${field.key}" needs at least two options`);
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
validateLayout(block.fragment, `assistant "${assistant.id}" block "${block.type}" fragment`);
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
return reasons.length > 0 ? { ok: false, reasons } : { ok: true, bundle };
|
|
841
|
-
};
|
|
842
|
-
var describePlacements = (bundle, names = {}) => {
|
|
843
|
-
const say = (id) => names[id] ?? id;
|
|
844
|
-
const parts = [];
|
|
845
|
-
for (const [actionId, binding] of Object.entries(bundle.attachments)) {
|
|
846
|
-
const host = typeof binding === "string" ? binding : binding.to;
|
|
847
|
-
parts.push(`a "${bundle.actions[actionId]?.title ?? actionId}" panel on ${say(host)}`);
|
|
848
|
-
}
|
|
849
|
-
for (const [actionId, hub] of Object.entries(bundle.placements)) {
|
|
850
|
-
parts.push(`"${bundle.actions[actionId]?.title ?? actionId}" under ${say(hub)}`);
|
|
851
|
-
}
|
|
852
|
-
if (bundle.settings !== "") parts.push("a settings screen on its store tile");
|
|
853
|
-
return parts.length === 0 ? "" : `Adds ${parts.join(" \xB7 ")}.`;
|
|
854
|
-
};
|
|
855
|
-
var copyPress = async (bundle, integrationId, serviceUrl, store, fetchImpl = fetch) => {
|
|
856
|
-
const declared = bundle.meta.press;
|
|
857
|
-
if (declared.length === 0) return { ok: true, urls: [] };
|
|
858
|
-
if (store === void 0) {
|
|
859
|
-
return { ok: false, reasons: [`press: the bundle declares ${declared.length} image(s), and this deployment has no storePress seam to hold them`] };
|
|
860
|
-
}
|
|
861
|
-
const own = `/integrations/${integrationId}/`;
|
|
862
|
-
const urls = [];
|
|
863
|
-
for (const path of declared) {
|
|
864
|
-
const rest = path.slice(own.length);
|
|
865
|
-
try {
|
|
866
|
-
const response = await fetchImpl(`${serviceUrl.replace(/\/$/, "")}/${rest}`);
|
|
867
|
-
if (!response.ok) return { ok: false, reasons: [`press "${path}": the service answered ${response.status}`] };
|
|
868
|
-
const contentType = (response.headers.get("content-type") ?? "").split(";")[0]?.trim() ?? "";
|
|
869
|
-
if (!contentType.startsWith("image/")) {
|
|
870
|
-
return { ok: false, reasons: [`press "${path}": answered "${contentType === "" ? "nothing" : contentType}", which is not an image`] };
|
|
871
|
-
}
|
|
872
|
-
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
873
|
-
urls.push(await store(integrationId, rest, bytes, contentType));
|
|
874
|
-
} catch (err) {
|
|
875
|
-
return { ok: false, reasons: [`press "${path}": ${String(err)}`] };
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
return { ok: true, urls };
|
|
879
|
-
};
|
|
880
|
-
var callIntegrationWith = (deps) => {
|
|
881
|
-
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
882
|
-
const emit = emitterOf(deps.telemetry);
|
|
883
|
-
return async (id, path, init) => {
|
|
884
|
-
const clock = emit === void 0 ? void 0 : spanClock();
|
|
885
|
-
const done = (status, httpStatus) => {
|
|
886
|
-
if (emit === void 0 || clock === void 0) return;
|
|
887
|
-
emit({
|
|
888
|
-
name: "integration.call",
|
|
889
|
-
startUnixNano: clock.startUnixNano,
|
|
890
|
-
endUnixNano: clock.endUnixNano(),
|
|
891
|
-
status,
|
|
892
|
-
attributes: { addon: id, path, ...httpStatus !== void 0 ? { httpStatus } : {} }
|
|
893
|
-
});
|
|
894
|
-
};
|
|
895
|
-
const row = await deps.pool.query("SELECT url, status FROM integrations WHERE id = $1", [id]);
|
|
896
|
-
const found = row.rows[0];
|
|
897
|
-
if (found === void 0) {
|
|
898
|
-
done("refused");
|
|
899
|
-
throw new Error(`moss: callIntegration("${id}"): no such integration.`);
|
|
900
|
-
}
|
|
901
|
-
if (found.status !== "approved") {
|
|
902
|
-
done("refused");
|
|
903
|
-
throw new Error(`moss: callIntegration("${id}"): not approved (status "${String(found.status)}").`);
|
|
904
|
-
}
|
|
905
|
-
const installed = await deps.installedFor(init.principal);
|
|
906
|
-
if (installed !== void 0 && !installed.includes(id)) {
|
|
907
|
-
done("refused");
|
|
908
|
-
throw new Error(`moss: callIntegration("${id}"): not installed for "${init.principal}".`);
|
|
909
|
-
}
|
|
910
|
-
const scope = { ...await deps.scopeValuesFor(init.principal), ...init.scope ?? {} };
|
|
911
|
-
const target = `${String(found.url).replace(/\/$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
912
|
-
let response;
|
|
913
|
-
try {
|
|
914
|
-
response = await fetchImpl(target, {
|
|
915
|
-
method: init.method ?? "POST",
|
|
916
|
-
headers: {
|
|
917
|
-
"content-type": "application/json",
|
|
918
|
-
authorization: `Bearer ${deps.mint({ integration: id, principal: init.principal, scope })}`
|
|
919
|
-
},
|
|
920
|
-
...init.body === void 0 ? {} : { body: JSON.stringify(init.body) }
|
|
921
|
-
});
|
|
922
|
-
} catch (err) {
|
|
923
|
-
done("error");
|
|
924
|
-
throw err;
|
|
925
|
-
}
|
|
926
|
-
done(response.ok ? "ok" : "error", response.status);
|
|
927
|
-
return response;
|
|
928
|
-
};
|
|
929
|
-
};
|
|
930
|
-
var MOSS_SEQUENCE = {
|
|
931
|
-
id: "nisc.moss",
|
|
932
|
-
migrations: [
|
|
933
|
-
{
|
|
934
|
-
description: "Integrations, their actions and the generation pointer, converged from any earlier shape",
|
|
935
|
-
steps: [
|
|
936
|
-
{ kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integrations (
|
|
937
|
-
id text PRIMARY KEY,
|
|
938
|
-
url text NOT NULL,
|
|
939
|
-
-- THE HASH, NEVER THE KEY. The integration key is minted at registration
|
|
940
|
-
-- (see assert.ts for the credential rule), returned once in that response,
|
|
941
|
-
-- and this is all that remains of it here. Presenting the key is the only
|
|
942
|
-
-- way to produce this value again, so a stolen database does not hold a
|
|
943
|
-
-- credential \u2014 and a lost key is re-registered, not recovered.
|
|
944
|
-
key_hash text,
|
|
945
|
-
status text NOT NULL DEFAULT 'pending',
|
|
946
|
-
-- The store card's words, straight from the bundle's meta. Columns
|
|
947
|
-
-- rather than jsonb so an app's vex read can select them like anything
|
|
948
|
-
-- else on this table.
|
|
949
|
-
title text NOT NULL DEFAULT '',
|
|
950
|
-
tagline text NOT NULL DEFAULT '',
|
|
951
|
-
description text NOT NULL DEFAULT '',
|
|
952
|
-
-- The listing page's long form, re-imported whole like everything else
|
|
953
|
-
-- about a bundle. press holds the URLS THE HOST ANSWERED WITH at
|
|
954
|
-
-- intake (copyPress), never the paths the bundle declared \u2014 the listing
|
|
955
|
-
-- composes from host ground alone.
|
|
956
|
-
story jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
957
|
-
highlights jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
958
|
-
press jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
959
|
-
-- WHAT APPEARS WHERE, as one derived sentence (describePlacements) \u2014
|
|
960
|
-
-- printed by the approval card and the store tile from this one place.
|
|
961
|
-
adds text NOT NULL DEFAULT '',
|
|
962
|
-
-- The one integration action the store may open: its settings screen.
|
|
963
|
-
settings_action text NOT NULL DEFAULT '',
|
|
964
|
-
requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
965
|
-
requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
966
|
-
approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
967
|
-
-- What it tells and hears (bundle offers/needs), beside the grants
|
|
968
|
-
-- because they are the same kind of thing: the integration's declared
|
|
969
|
-
-- statement, written at import, replaced on re-registration. moss
|
|
970
|
-
-- never reads them; the host's bus does.
|
|
971
|
-
offers jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
972
|
-
needs jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
973
|
-
-- The verbs the integration gates on ({id, title}), for the host's role
|
|
974
|
-
-- editor to grant. Beside offers/needs because it is the same kind of
|
|
975
|
-
-- thing: a declaration written at import, replaced on re-registration,
|
|
976
|
-
-- that moss never reads \u2014 the host does.
|
|
977
|
-
capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
978
|
-
-- WHAT A BUILDER MAY SET per product \u2014 the closed-set field declaration,
|
|
979
|
-
-- beside capabilities because it is the same kind of thing: a declaration
|
|
980
|
-
-- written at import, replaced on re-registration, that moss never reads.
|
|
981
|
-
-- The host renders a settings form from it and stores the values itself.
|
|
982
|
-
configuration jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
983
|
-
-- WHAT AN ADD-ON LETS A PERSON EDIT \u2014 section types, fields, fragments,
|
|
984
|
-
-- and a section model the host's editor renders. Beside configuration
|
|
985
|
-
-- because it is the same kind of thing: a declaration written at import,
|
|
986
|
-
-- replaced on re-registration, that moss never reads \u2014 the host does.
|
|
987
|
-
documents jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
988
|
-
-- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO \u2014 instructions, grounding,
|
|
989
|
-
-- blocks, tools, what it applies to. Same kind of thing, same lifecycle;
|
|
990
|
-
-- the host's assistant is the consumer.
|
|
991
|
-
assistants jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
992
|
-
-- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake
|
|
993
|
-
-- (reachOf). Beside the grants because it is one: a grant of reach, held
|
|
994
|
-
-- by the same row, revoked by the same delete.
|
|
995
|
-
reach jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
996
|
-
-- Pages this integration serves and the host frames. Kept apart from reach
|
|
997
|
-
-- because they are spent differently: reach is a screen's call carrying a
|
|
998
|
-
-- session, a frame is a document GET carrying a grant.
|
|
999
|
-
frames jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
1000
|
-
last_import_at timestamptz,
|
|
1001
|
-
last_error text
|
|
1002
|
-
)
|
|
1003
|
-
` },
|
|
1004
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1005
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1006
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },
|
|
1007
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1008
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1009
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1010
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1011
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1012
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1013
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1014
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1015
|
-
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
1016
|
-
{ kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integration_actions (
|
|
1017
|
-
integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,
|
|
1018
|
-
action_id text NOT NULL,
|
|
1019
|
-
definition jsonb NOT NULL,
|
|
1020
|
-
-- The bindings, beside the artifact and never inside it: which host
|
|
1021
|
-
-- action this one rides (a panel), or which menu hub lists it. Empty
|
|
1022
|
-
-- means neither \u2014 reachable only through whatever else names it.
|
|
1023
|
-
-- preview is the rider's display endpoint (own-prefix, validated at
|
|
1024
|
-
-- intake): the host calls it with the offered ids to paint the strip.
|
|
1025
|
-
attach_to text NOT NULL DEFAULT '',
|
|
1026
|
-
preview text NOT NULL DEFAULT '',
|
|
1027
|
-
place_in text NOT NULL DEFAULT '',
|
|
1028
|
-
PRIMARY KEY (integration_id, action_id)
|
|
1029
|
-
)
|
|
1030
|
-
` },
|
|
1031
|
-
...GENERATION_DDL.map((sql) => ({ kind: "sql", sql }))
|
|
1032
|
-
]
|
|
1033
|
-
},
|
|
1034
|
-
{
|
|
1035
|
-
description: "Stored integration actions carry the grammar stamp their definition is written in",
|
|
1036
|
-
steps: [{ kind: "sql", sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }]
|
|
1037
|
-
}
|
|
1038
|
-
]
|
|
1039
|
-
};
|
|
1040
|
-
var INTEGRATION_ACTIONS_STORE = {
|
|
1041
|
-
table: "integration_actions",
|
|
1042
|
-
column: "definition",
|
|
1043
|
-
stamp: "grammar",
|
|
1044
|
-
kind: "nisc.nova/action",
|
|
1045
|
-
key: ["integration_id", "action_id"]
|
|
1046
|
-
};
|
|
1047
|
-
var initIntegrations = async (pool) => {
|
|
1048
|
-
await postgres.migrate(pool, [MOSS_SEQUENCE]);
|
|
1049
|
-
};
|
|
1050
|
-
var listAttachments = async (pool, hostAction) => {
|
|
1051
|
-
const res = await pool.query(
|
|
1052
|
-
`SELECT a.action_id, a.preview FROM integration_actions a JOIN integrations i ON i.id = a.integration_id
|
|
1053
|
-
WHERE i.status = 'approved' AND a.attach_to = $1 ORDER BY a.action_id`,
|
|
1054
|
-
[hostAction]
|
|
1055
|
-
);
|
|
1056
|
-
return res.rows.map((r) => {
|
|
1057
|
-
const row = r;
|
|
1058
|
-
return { actionId: String(row.action_id), preview: String(row.preview ?? "") };
|
|
1059
|
-
});
|
|
1060
|
-
};
|
|
1061
|
-
var listPlacements = async (pool) => {
|
|
1062
|
-
const res = await pool.query(
|
|
1063
|
-
`SELECT a.action_id, a.place_in FROM integration_actions a JOIN integrations i ON i.id = a.integration_id
|
|
1064
|
-
WHERE i.status = 'approved' AND a.place_in <> ''`
|
|
1065
|
-
);
|
|
1066
|
-
const out = {};
|
|
1067
|
-
for (const r of res.rows) {
|
|
1068
|
-
const row = r;
|
|
1069
|
-
out[String(row.action_id)] = String(row.place_in);
|
|
1070
|
-
}
|
|
1071
|
-
return out;
|
|
1072
|
-
};
|
|
1073
|
-
var integrationByKey = async (pool, key) => {
|
|
1074
|
-
const res = await pool.query("SELECT id FROM integrations WHERE key_hash = $1 AND status = 'approved'", [hashIntegrationKey(key)]);
|
|
1075
|
-
const id = res.rows[0]?.id;
|
|
1076
|
-
return id === void 0 ? void 0 : String(id);
|
|
1077
|
-
};
|
|
1078
|
-
var listIntegrations = async (pool) => {
|
|
1079
|
-
const res = await pool.query(`
|
|
1080
|
-
SELECT i.id, i.url, i.status, i.title, i.tagline, i.adds, i.settings_action,
|
|
1081
|
-
i.requested_actions, i.requested_data, i.approved_data,
|
|
1082
|
-
i.offers, i.needs, i.capabilities, i.configuration, i.documents, i.assistants,
|
|
1083
|
-
i.last_import_at, i.last_error,
|
|
1084
|
-
(SELECT count(*) FROM integration_actions a WHERE a.integration_id = i.id) AS action_count
|
|
1085
|
-
FROM integrations i ORDER BY i.id
|
|
1086
|
-
`);
|
|
1087
|
-
return res.rows.map((r) => {
|
|
1088
|
-
const row = r;
|
|
1089
|
-
const at = row["last_import_at"];
|
|
1090
|
-
return {
|
|
1091
|
-
id: String(row["id"]),
|
|
1092
|
-
url: String(row["url"]),
|
|
1093
|
-
status: String(row["status"]),
|
|
1094
|
-
title: String(row["title"] ?? ""),
|
|
1095
|
-
tagline: String(row["tagline"] ?? ""),
|
|
1096
|
-
adds: String(row["adds"] ?? ""),
|
|
1097
|
-
settingsAction: String(row["settings_action"] ?? ""),
|
|
1098
|
-
requestedActions: row["requested_actions"] ?? [],
|
|
1099
|
-
requestedData: row["requested_data"] ?? [],
|
|
1100
|
-
approvedData: row["approved_data"] ?? [],
|
|
1101
|
-
offers: row["offers"] ?? [],
|
|
1102
|
-
needs: row["needs"] ?? [],
|
|
1103
|
-
capabilities: row["capabilities"] ?? [],
|
|
1104
|
-
configuration: row["configuration"] ?? [],
|
|
1105
|
-
documents: row["documents"] ?? [],
|
|
1106
|
-
assistants: row["assistants"] ?? [],
|
|
1107
|
-
lastImportAt: at instanceof Date ? at.getTime() : typeof at === "string" || typeof at === "number" ? new Date(at).getTime() : null,
|
|
1108
|
-
lastError: row["last_error"] ?? null,
|
|
1109
|
-
actionCount: Number(row["action_count"] ?? 0)
|
|
1110
|
-
};
|
|
1111
|
-
});
|
|
1112
|
-
};
|
|
1113
|
-
var loadIntegrationActions = async (pool, upgrader) => {
|
|
1114
|
-
const res = await pool.query(
|
|
1115
|
-
`SELECT a.action_id, a.definition, a.grammar FROM integration_actions a
|
|
1116
|
-
JOIN integrations i ON i.id = a.integration_id
|
|
1117
|
-
WHERE i.status = 'approved'`
|
|
1118
|
-
);
|
|
1119
|
-
const out = {};
|
|
1120
|
-
for (const r of res.rows) {
|
|
1121
|
-
const row = r;
|
|
1122
|
-
const id = String(row["action_id"]);
|
|
1123
|
-
if (upgrader === void 0) {
|
|
1124
|
-
out[id] = row["definition"];
|
|
1125
|
-
continue;
|
|
1126
|
-
}
|
|
1127
|
-
const stamp = isPlainRecord(row["grammar"]) ? Object.fromEntries(Object.entries(row["grammar"]).map(([k, v]) => [k, Number(v)])) : {};
|
|
1128
|
-
try {
|
|
1129
|
-
out[id] = upgrader.upgrade(row["definition"], { kind: "nisc.nova/action", stamp }).document;
|
|
1130
|
-
} catch (error) {
|
|
1131
|
-
if (!(error instanceof strata.StrataError)) throw error;
|
|
1132
|
-
console.error(`[moss] integration action "${id}" is not served: ${error.message.split("\n")[0] ?? error.code}`);
|
|
1133
|
-
}
|
|
1134
|
-
}
|
|
1135
|
-
return out;
|
|
1136
|
-
};
|
|
1137
|
-
var integrationOfAction = (id) => id.startsWith("ext.") ? id.split(".")[2] : void 0;
|
|
1138
|
-
var filterInstalled = (ids, installed) => {
|
|
1139
|
-
if (installed === void 0) return ids;
|
|
1140
|
-
return ids.filter((id) => {
|
|
1141
|
-
const owner = integrationOfAction(id);
|
|
1142
|
-
return owner === void 0 || installed.has(owner);
|
|
1143
|
-
});
|
|
1144
|
-
};
|
|
1145
|
-
var buildContract = (app, integrationId) => {
|
|
1146
|
-
const registered = app.shell?.components ?? {};
|
|
1147
|
-
const components = Object.keys(registered).sort().map((name) => nova.paletteEntryOf(name, registered[name]?.meta ?? {}));
|
|
1148
|
-
const audiences = /* @__PURE__ */ new Set();
|
|
1149
|
-
for (const def of Object.values(app.charter)) {
|
|
1150
|
-
if (def === void 0 || Array.isArray(def)) continue;
|
|
1151
|
-
const selection = def.actions;
|
|
1152
|
-
const list = Array.isArray(selection) ? selection : selection?.allow ?? [];
|
|
1153
|
-
for (const entry of list) {
|
|
1154
|
-
const parts = String(entry).split(".");
|
|
1155
|
-
if (parts[0] === "ext" && parts[1] !== void 0 && parts[1] !== "*") audiences.add(parts[1]);
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
const attachable = {};
|
|
1159
|
-
for (const [action, offers] of Object.entries(app.attachable ?? {})) attachable[action] = Object.keys(offers);
|
|
1160
|
-
return {
|
|
1161
|
-
components,
|
|
1162
|
-
audiences: [...audiences].sort(),
|
|
1163
|
-
namespace: `ext.<audience>.${integrationId}.<name>`,
|
|
1164
|
-
actionSchema: "nova ActionDefinition",
|
|
1165
|
-
attachable,
|
|
1166
|
-
menuSlots: [...app.menuSlots ?? []]
|
|
1167
|
-
};
|
|
1168
|
-
};
|
|
1169
|
-
var describeProp = (schema) => {
|
|
1170
|
-
const enumValues = schema["enum"];
|
|
1171
|
-
if (Array.isArray(enumValues)) return `one of: ${enumValues.map((v) => String(v)).join(", ")}`;
|
|
1172
|
-
const anyOf = schema["anyOf"];
|
|
1173
|
-
if (Array.isArray(anyOf)) {
|
|
1174
|
-
const consts = anyOf.map((s) => s["const"]).filter((v) => v !== void 0);
|
|
1175
|
-
if (consts.length === anyOf.length && consts.length > 0) return `one of: ${consts.map((v) => String(v)).join(", ")}`;
|
|
1176
|
-
}
|
|
1177
|
-
const type = schema["type"];
|
|
1178
|
-
const base = typeof type === "string" ? type : Array.isArray(type) ? type.map((t) => String(t)).join(" | ") : "value";
|
|
1179
|
-
const min = schema["minimum"];
|
|
1180
|
-
const max = schema["maximum"];
|
|
1181
|
-
if (typeof min === "number" || typeof max === "number") return `${base} (${typeof min === "number" ? min : "\u2026"}\u2013${typeof max === "number" ? max : "\u2026"})`;
|
|
1182
|
-
return base;
|
|
1183
|
-
};
|
|
1184
|
-
var componentAsMarkdown = (component) => {
|
|
1185
|
-
const head = component.description !== "" ? `**${component.name}** \u2014 ${component.description}` : `**${component.name}**`;
|
|
1186
|
-
const schema = component.propsSchema;
|
|
1187
|
-
const properties = schema?.properties;
|
|
1188
|
-
if (properties === void 0 || Object.keys(properties).length === 0) return head;
|
|
1189
|
-
const required = new Set(schema?.required ?? []);
|
|
1190
|
-
const rows = Object.entries(properties).map(
|
|
1191
|
-
([prop, spec]) => `| ${prop} | ${describeProp(spec)} | ${required.has(prop) ? "yes" : "no"} | ${String(spec["description"] ?? "")} |`
|
|
1192
|
-
);
|
|
1193
|
-
return [head, ``, `| prop | type | required | meaning |`, `| --- | --- | --- | --- |`, ...rows].join("\n");
|
|
1194
|
-
};
|
|
1195
|
-
var contractAsMarkdown = (contract, fingerprints) => [
|
|
1196
|
-
`# What you can build against`,
|
|
1197
|
-
``,
|
|
1198
|
-
`## Your namespace`,
|
|
1199
|
-
``,
|
|
1200
|
-
` ${contract.namespace}`,
|
|
1201
|
-
``,
|
|
1202
|
-
`Every action you ship must be named this way. Audiences available: ${contract.audiences.join(", ") || "(none)"}.`,
|
|
1203
|
-
``,
|
|
1204
|
-
`## Components your layouts may use`,
|
|
1205
|
-
``,
|
|
1206
|
-
contract.components.map(componentAsMarkdown).join("\n\n") || "(none)",
|
|
1207
|
-
``,
|
|
1208
|
-
`## Fingerprints you may call`,
|
|
1209
|
-
``,
|
|
1210
|
-
`Endpoints may target \`/api/<resource>/vex\` with one of these, or any URL under`,
|
|
1211
|
-
`\`/integrations/<your id>/\`. Nothing else.`,
|
|
1212
|
-
``,
|
|
1213
|
-
fingerprints.map((f) => `- ${f}`).join("\n") || "(none \u2014 your grants reach nothing yet)",
|
|
1214
|
-
``,
|
|
1215
|
-
`## Where your screens may appear`,
|
|
1216
|
-
``,
|
|
1217
|
-
`Declare \`attachments\` (action \u2192 host action) to ride a host screen, and`,
|
|
1218
|
-
`\`placements\` (action \u2192 hub) to list under a menu hub. \`settings\` names the one`,
|
|
1219
|
-
`action the store tile opens. Anything else is refused.`,
|
|
1220
|
-
``,
|
|
1221
|
-
`Attachable, with what each hands you as input:`,
|
|
1222
|
-
``,
|
|
1223
|
-
Object.entries(contract.attachable).map(([action, offers]) => `- ${action} \u2014 offers ${offers.join(", ") || "(nothing)"}`).join("\n") || "(none)",
|
|
1224
|
-
``,
|
|
1225
|
-
`Menu hubs accepting placements:`,
|
|
1226
|
-
``,
|
|
1227
|
-
contract.menuSlots.map((hub) => `- ${hub}`).join("\n") || "(none)",
|
|
1228
|
-
``,
|
|
1229
|
-
`## What you cannot ship`,
|
|
1230
|
-
``,
|
|
1231
|
-
`- vex entries or mutations. Call what is listed above; if you need a read that`,
|
|
1232
|
-
` does not exist, it is a change to the app.`,
|
|
1233
|
-
`- \`fn:\` endpoints. Those run in the app's process.`,
|
|
1234
|
-
`- components. Layouts compose what is listed above.`,
|
|
1235
|
-
`- tables. Bring your own storage; we hand you identifiers.`,
|
|
1236
|
-
``
|
|
1237
|
-
].join("\n");
|
|
1238
|
-
|
|
1239
|
-
// src/migrate.ts
|
|
1240
|
-
var tableSequencesOf = (runtime) => {
|
|
1241
|
-
const cacheSequence = (runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool })).sequence;
|
|
1242
|
-
return [
|
|
1243
|
-
MOSS_SEQUENCE,
|
|
1244
|
-
...runtime.session === "sessions" ? [SESSIONS_SEQUENCE] : [],
|
|
1245
|
-
...cacheSequence === void 0 ? [] : [cacheSequence],
|
|
1246
|
-
...runtime.tables ?? []
|
|
1247
|
-
];
|
|
1248
|
-
};
|
|
1249
|
-
var misfitOf = (entry, schema) => {
|
|
1250
|
-
if (!("mutation" in entry)) {
|
|
1251
|
-
try {
|
|
1252
|
-
vex.resolve(vex.pruneOptional(entry.dsl, "all"), schema);
|
|
1253
|
-
return void 0;
|
|
1254
|
-
} catch (error) {
|
|
1255
|
-
return error instanceof Error ? error.message : String(error);
|
|
1256
|
-
}
|
|
1257
|
-
}
|
|
1258
|
-
return vex.mutationMisfits(entry.mutation, schema)[0];
|
|
1259
|
-
};
|
|
1260
|
-
var misfitsOf = (entries, schema) => {
|
|
1261
|
-
const misfits = /* @__PURE__ */ new Map();
|
|
1262
|
-
for (const entry of entries) {
|
|
1263
|
-
const why = misfitOf(entry, schema);
|
|
1264
|
-
if (why !== void 0) misfits.set(entry.fingerprint, why);
|
|
1265
|
-
}
|
|
1266
|
-
return misfits;
|
|
1267
|
-
};
|
|
1268
|
-
var canonical = (value) => {
|
|
1269
|
-
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
1270
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1271
|
-
const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
|
|
1272
|
-
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
|
|
1273
|
-
};
|
|
1274
|
-
var isSeededAs = async (cache, entry) => {
|
|
1275
|
-
const held = await cache.get(entry.fingerprint);
|
|
1276
|
-
if (held === void 0 || held.protected !== true) return false;
|
|
1277
|
-
if ("mutation" in entry) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry.mutation);
|
|
1278
|
-
return held.kind === "ok" && canonical(held.dsl) === canonical(entry.dsl);
|
|
1279
|
-
};
|
|
1280
|
-
var changesBetween = (before, after) => {
|
|
1281
|
-
const removed = [];
|
|
1282
|
-
const retyped = [];
|
|
1283
|
-
for (const was of before.entities) {
|
|
1284
|
-
const now = after.entities.find((entity) => entity.table === was.table);
|
|
1285
|
-
if (now === void 0) {
|
|
1286
|
-
removed.push(was.table);
|
|
1287
|
-
continue;
|
|
1288
|
-
}
|
|
1289
|
-
for (const field of was.fields) {
|
|
1290
|
-
const kept = now.fields.find((f) => f.name === field.name);
|
|
1291
|
-
if (kept === void 0) removed.push(`${was.table}.${field.name}`);
|
|
1292
|
-
else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
return { removed, retyped };
|
|
1296
|
-
};
|
|
1297
|
-
var oneAtATime = (query) => {
|
|
1298
|
-
let last = Promise.resolve();
|
|
1299
|
-
return (text, values) => {
|
|
1300
|
-
const next = last.then(() => query(text, values));
|
|
1301
|
-
last = next.catch(() => void 0);
|
|
1302
|
-
return next;
|
|
1303
|
-
};
|
|
1304
|
-
};
|
|
1305
|
-
var migrateTables = async (runtime, app, options = {}) => {
|
|
1306
|
-
const entries = app.entries ?? [];
|
|
1307
|
-
const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
|
|
1308
|
-
const before = await vex.createPostgresAdapter({ pool: runtime.pool }).introspect();
|
|
1309
|
-
const misfitsBefore = misfitsOf(entries, before);
|
|
1310
|
-
const excused = /* @__PURE__ */ new Set();
|
|
1311
|
-
for (const entry of entries) {
|
|
1312
|
-
if (misfitsBefore.has(entry.fingerprint) && await isSeededAs(cache, entry).catch(() => false)) excused.add(entry.fingerprint);
|
|
1313
|
-
}
|
|
1314
|
-
let found = { removed: [], retyped: [], alreadyBroken: [] };
|
|
1315
|
-
const report = await postgres.migrate(runtime.pool, tableSequencesOf(runtime), {
|
|
1316
|
-
...options.dryRun === true ? { dryRun: true } : {},
|
|
1317
|
-
guard: async (tx) => {
|
|
1318
|
-
const after = await vex.createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
|
|
1319
|
-
const refused = [];
|
|
1320
|
-
const alreadyBroken = [];
|
|
1321
|
-
for (const [fingerprint, why] of misfitsOf(entries, after)) {
|
|
1322
|
-
if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
|
|
1323
|
-
else refused.push(`${fingerprint}: ${why}`);
|
|
1324
|
-
}
|
|
1325
|
-
found = { ...changesBetween(before, after), alreadyBroken };
|
|
1326
|
-
return refused;
|
|
1327
|
-
}
|
|
1328
|
-
});
|
|
1329
|
-
return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
|
|
1330
|
-
};
|
|
1331
|
-
var TIDE_TABLES = ["tide_fact", "tide_run", "tide_work", "tide_reflex_state"];
|
|
1332
|
-
var TIDE_DDL = `
|
|
1333
|
-
CREATE TABLE IF NOT EXISTS tide_fact (
|
|
1334
|
-
id text PRIMARY KEY,
|
|
1335
|
-
kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
|
|
1336
|
-
entity text,
|
|
1337
|
-
op text CHECK (op IN ('insert','update','delete')),
|
|
1338
|
-
row jsonb,
|
|
1339
|
-
name text,
|
|
1340
|
-
payload jsonb,
|
|
1341
|
-
reflex text,
|
|
1342
|
-
run_id text,
|
|
1343
|
-
occurrence text,
|
|
1344
|
-
stats jsonb,
|
|
1345
|
-
target text,
|
|
1346
|
-
by text,
|
|
1347
|
-
at bigint NOT NULL,
|
|
1348
|
-
not_before bigint,
|
|
1349
|
-
dedupe_key text,
|
|
1350
|
-
cause text,
|
|
1351
|
-
depth integer NOT NULL DEFAULT 0,
|
|
1352
|
-
delivered_at bigint,
|
|
1353
|
-
parked text,
|
|
1354
|
-
released boolean,
|
|
1355
|
-
-- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
|
|
1356
|
-
-- anything the host ingested. The matcher refuses to hand a fact minted
|
|
1357
|
-
-- under one identity to a reflex running under another, which is the only
|
|
1358
|
-
-- thing standing between a carried row and somebody else's effect \u2014 tide is
|
|
1359
|
-
-- the one place a row travels without being read, so no scope policy is
|
|
1360
|
-
-- consulted on the way.
|
|
1361
|
-
as_who text
|
|
1362
|
-
);
|
|
1363
|
-
|
|
1364
|
-
-- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
|
|
1365
|
-
-- unique: it is a distinct occurrence of something, not a repeat of it.
|
|
1366
|
-
-- entity is in the key: without it, two producers over different tables
|
|
1367
|
-
-- that agreed on a key value silently ate each other's rows.
|
|
1368
|
-
CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
|
|
1369
|
-
ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
|
|
1370
|
-
WHERE dedupe_key IS NOT NULL;
|
|
1371
|
-
|
|
1372
|
-
-- The matcher's query, every advance.
|
|
1373
|
-
CREATE INDEX IF NOT EXISTS tide_fact_due
|
|
1374
|
-
ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
|
|
1375
|
-
CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
|
|
1376
|
-
|
|
1377
|
-
CREATE TABLE IF NOT EXISTS tide_run (
|
|
1378
|
-
id text PRIMARY KEY,
|
|
1379
|
-
reflex_id text NOT NULL,
|
|
1380
|
-
version text NOT NULL,
|
|
1381
|
-
as_who text,
|
|
1382
|
-
cause text NOT NULL,
|
|
1383
|
-
occurrence text,
|
|
1384
|
-
fact_ids jsonb,
|
|
1385
|
-
state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
|
|
1386
|
-
depth integer NOT NULL DEFAULT 0,
|
|
1387
|
-
selected integer,
|
|
1388
|
-
total integer NOT NULL DEFAULT 0,
|
|
1389
|
-
done integer NOT NULL DEFAULT 0,
|
|
1390
|
-
failed integer NOT NULL DEFAULT 0,
|
|
1391
|
-
due_at bigint NOT NULL,
|
|
1392
|
-
created_at bigint NOT NULL,
|
|
1393
|
-
settled_at bigint,
|
|
1394
|
-
drained boolean,
|
|
1395
|
-
note text,
|
|
1396
|
-
-- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
|
|
1397
|
-
-- cannot open twice, a replayed fact cannot open twice, and two instances
|
|
1398
|
-
-- ticking at the same moment contend instead of duplicating.
|
|
1399
|
-
UNIQUE (reflex_id, cause)
|
|
1400
|
-
);
|
|
1401
|
-
|
|
1402
|
-
CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
|
|
1403
|
-
CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
|
|
1404
|
-
CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
|
|
1405
|
-
|
|
1406
|
-
CREATE TABLE IF NOT EXISTS tide_work (
|
|
1407
|
-
id text PRIMARY KEY,
|
|
1408
|
-
-- ON DELETE CASCADE, because a run and its work are one fact about the
|
|
1409
|
-
-- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
|
|
1410
|
-
-- row that IS the "this unit already ran" record \u2014 and a restore then
|
|
1411
|
-
-- re-charges the invoice.
|
|
1412
|
-
run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
|
|
1413
|
-
reflex_id text NOT NULL,
|
|
1414
|
-
unit text NOT NULL,
|
|
1415
|
-
cause text NOT NULL,
|
|
1416
|
-
env jsonb NOT NULL,
|
|
1417
|
-
depth integer NOT NULL DEFAULT 0,
|
|
1418
|
-
state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
|
|
1419
|
-
attempt integer NOT NULL DEFAULT 0,
|
|
1420
|
-
token text,
|
|
1421
|
-
-- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
|
|
1422
|
-
-- comparison rather than a disjunction.
|
|
1423
|
-
claimed_until bigint NOT NULL DEFAULT 0,
|
|
1424
|
-
not_before bigint NOT NULL,
|
|
1425
|
-
input jsonb,
|
|
1426
|
-
output jsonb,
|
|
1427
|
-
error text,
|
|
1428
|
-
created_at bigint NOT NULL,
|
|
1429
|
-
settled_at bigint,
|
|
1430
|
-
UNIQUE (run_id, unit)
|
|
1431
|
-
);
|
|
1432
|
-
|
|
1433
|
-
CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
|
|
1434
|
-
CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
|
|
1435
|
-
CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
|
|
1436
|
-
|
|
1437
|
-
CREATE TABLE IF NOT EXISTS tide_reflex_state (
|
|
1438
|
-
reflex_id text PRIMARY KEY,
|
|
1439
|
-
armed_at bigint NOT NULL DEFAULT 0,
|
|
1440
|
-
materialized_through bigint
|
|
1441
|
-
);
|
|
1442
|
-
|
|
1443
|
-
-- Polls are gone (the vex bridge pushes writes \u2014 a poll could only
|
|
1444
|
-
-- re-discover them late), and their cursor state goes with them. IF EXISTS,
|
|
1445
|
-
-- so a store created after the removal is not asked to drop what it never had.
|
|
1446
|
-
ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;
|
|
1447
|
-
ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;
|
|
1448
|
-
ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;
|
|
1449
|
-
`;
|
|
1450
|
-
var SQL_TABLE = {
|
|
1451
|
-
fact: "tide_fact",
|
|
1452
|
-
run: "tide_run",
|
|
1453
|
-
task: "tide_work",
|
|
1454
|
-
state: "tide_reflex_state"
|
|
1455
|
-
};
|
|
1456
|
-
var COLUMN_OVERRIDES = { as: "as_who" };
|
|
1457
|
-
var snake = (field) => COLUMN_OVERRIDES[field] ?? field.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
1458
|
-
var camel = (column) => {
|
|
1459
|
-
for (const [field, mapped] of Object.entries(COLUMN_OVERRIDES)) if (mapped === column) return field;
|
|
1460
|
-
return column.replace(/_([a-z])/g, (_all, c) => c.toUpperCase());
|
|
1461
|
-
};
|
|
1462
|
-
var JSON_COLUMNS = /* @__PURE__ */ new Set(["row", "payload", "stats", "fact_ids", "env", "input", "output"]);
|
|
1463
|
-
var BIGINT_COLUMNS = /* @__PURE__ */ new Set([
|
|
1464
|
-
"at",
|
|
1465
|
-
"not_before",
|
|
1466
|
-
"delivered_at",
|
|
1467
|
-
"depth",
|
|
1468
|
-
"descendants",
|
|
1469
|
-
"due_at",
|
|
1470
|
-
"created_at",
|
|
1471
|
-
"settled_at",
|
|
1472
|
-
"claimed_until",
|
|
1473
|
-
"armed_at",
|
|
1474
|
-
"materialized_through",
|
|
1475
|
-
"attempt",
|
|
1476
|
-
"selected",
|
|
1477
|
-
"total",
|
|
1478
|
-
"done",
|
|
1479
|
-
"failed"
|
|
1480
|
-
]);
|
|
1481
|
-
var toColumn = (column, value) => {
|
|
1482
|
-
if (value === void 0) return null;
|
|
1483
|
-
if (JSON_COLUMNS.has(column)) return JSON.stringify(value);
|
|
1484
|
-
return value;
|
|
1485
|
-
};
|
|
1486
|
-
var fromColumn = (column, value) => {
|
|
1487
|
-
if (value === null) return void 0;
|
|
1488
|
-
if (JSON_COLUMNS.has(column)) return typeof value === "string" ? JSON.parse(value) : value;
|
|
1489
|
-
if (BIGINT_COLUMNS.has(column)) return Number(value);
|
|
1490
|
-
return value;
|
|
1491
|
-
};
|
|
1492
|
-
var rowToEntity = (table, row) => {
|
|
1493
|
-
const entity = {};
|
|
1494
|
-
for (const [column, value] of Object.entries(row)) {
|
|
1495
|
-
const mapped = fromColumn(column, value);
|
|
1496
|
-
if (mapped !== void 0) entity[camel(column)] = mapped;
|
|
1497
|
-
}
|
|
1498
|
-
return entity;
|
|
1499
|
-
};
|
|
1500
|
-
var COMPARATORS = { eq: "=", ne: "<>", lt: "<", lte: "<=", gt: ">", gte: ">=" };
|
|
1501
|
-
var compileWhere = (where, start, alias = "") => {
|
|
1502
|
-
const clauses = [];
|
|
1503
|
-
const params = [];
|
|
1504
|
-
const prefix = alias === "" ? "" : `${alias}.`;
|
|
1505
|
-
const slot = (value) => {
|
|
1506
|
-
params.push(value);
|
|
1507
|
-
return `$${start + params.length - 1}`;
|
|
1508
|
-
};
|
|
1509
|
-
for (const [field, test] of Object.entries(where ?? {})) {
|
|
1510
|
-
const column = `${prefix}${snake(field)}`;
|
|
1511
|
-
const bare = snake(field);
|
|
1512
|
-
if (test === null || typeof test !== "object" || Array.isArray(test)) {
|
|
1513
|
-
clauses.push(test === void 0 ? `${column} IS NULL` : `${column} = ${slot(toColumn(bare, test))}`);
|
|
1514
|
-
continue;
|
|
1515
|
-
}
|
|
1516
|
-
const comparison = test;
|
|
1517
|
-
for (const [op, symbol] of Object.entries(COMPARATORS)) {
|
|
1518
|
-
const operand = comparison[op];
|
|
1519
|
-
if (operand === void 0) continue;
|
|
1520
|
-
clauses.push(op === "ne" ? `(${column} IS NULL OR ${column} <> ${slot(toColumn(bare, operand))})` : `${column} ${symbol} ${slot(toColumn(bare, operand))}`);
|
|
1521
|
-
}
|
|
1522
|
-
if (comparison.in !== void 0) clauses.push(`${column} = ANY(${slot(comparison.in.map((value) => toColumn(bare, value)))})`);
|
|
1523
|
-
if (comparison.notIn !== void 0) clauses.push(`NOT (${column} = ANY(${slot(comparison.notIn.map((value) => toColumn(bare, value)))}))`);
|
|
1524
|
-
if (comparison.isNull !== void 0) clauses.push(comparison.isNull ? `${column} IS NULL` : `${column} IS NOT NULL`);
|
|
1525
|
-
}
|
|
1526
|
-
return { sql: clauses.length === 0 ? "TRUE" : clauses.join(" AND "), params };
|
|
1527
|
-
};
|
|
1528
|
-
var compileOrder = (order, alias = "") => {
|
|
1529
|
-
if (order === void 0 || order.length === 0) return "";
|
|
1530
|
-
const prefix = alias === "" ? "" : `${alias}.`;
|
|
1531
|
-
return ` ORDER BY ${order.map((key) => `${prefix}${snake(String(key.by))} ${key.dir === "desc" ? "DESC" : "ASC"}`).join(", ")}`;
|
|
1532
|
-
};
|
|
1533
|
-
var sortRows = (rows, order) => {
|
|
1534
|
-
if (order === void 0 || order.length === 0) return [...rows];
|
|
1535
|
-
return [...rows].sort((left, right) => {
|
|
1536
|
-
for (const key of order) {
|
|
1537
|
-
const a = left[String(key.by)];
|
|
1538
|
-
const b = right[String(key.by)];
|
|
1539
|
-
const compared = typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
|
|
1540
|
-
if (compared !== 0) return compared * (key.dir === "desc" ? -1 : 1);
|
|
1541
|
-
}
|
|
1542
|
-
return 0;
|
|
1543
|
-
});
|
|
1544
|
-
};
|
|
1545
|
-
var compileSet = (set, start) => {
|
|
1546
|
-
const assignments = [];
|
|
1547
|
-
const params = [];
|
|
1548
|
-
for (const [field, value] of Object.entries(set)) {
|
|
1549
|
-
const column = snake(field);
|
|
1550
|
-
if (value !== null && typeof value === "object" && "inc" in value) {
|
|
1551
|
-
assignments.push(`${column} = coalesce(${column}, 0) + ${Number(value.inc)}`);
|
|
1552
|
-
continue;
|
|
1553
|
-
}
|
|
1554
|
-
params.push(toColumn(column, value));
|
|
1555
|
-
assignments.push(`${column} = $${start + params.length - 1}`);
|
|
1556
|
-
}
|
|
1557
|
-
return { sql: assignments.join(", "), params };
|
|
1558
|
-
};
|
|
1559
|
-
var mintId = /* @__PURE__ */ (() => {
|
|
1560
|
-
let sequence = 0;
|
|
1561
|
-
return (table) => {
|
|
1562
|
-
sequence += 1;
|
|
1563
|
-
return `${table}_${Date.now().toString(36)}_${sequence.toString(36)}`;
|
|
1564
|
-
};
|
|
1565
|
-
})();
|
|
1566
|
-
var statementsOf = (ddl) => ddl.split(";").map((chunk) => chunk.trim()).filter((chunk) => chunk.split("\n").some((line) => line.trim() !== "" && !line.trim().startsWith("--"))).map((sql) => ({ kind: "sql", sql }));
|
|
1567
|
-
var TIDE_SEQUENCE = {
|
|
1568
|
-
id: "nisc.moss.tide",
|
|
1569
|
-
migrations: [
|
|
1570
|
-
{ description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
|
|
1571
|
-
{
|
|
1572
|
-
// A fact's chain: the root it belongs to, and — on a root — how many facts
|
|
1573
|
-
// the chain has minted beneath it. Nullable: every existing fact is a
|
|
1574
|
-
// root nothing has been counted against yet.
|
|
1575
|
-
description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
|
|
1576
|
-
steps: [
|
|
1577
|
-
{ kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
|
|
1578
|
-
{ kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
|
|
1579
|
-
]
|
|
1580
|
-
}
|
|
1581
|
-
]
|
|
1582
|
-
};
|
|
1583
|
-
var createTideStore = (pool, options = {}) => {
|
|
1584
|
-
const ready = options.migrate === false ? Promise.resolve() : postgres.migrate(pool, [TIDE_SEQUENCE]).then(() => void 0);
|
|
1585
|
-
ready.catch(() => void 0);
|
|
1586
|
-
const build = (client) => {
|
|
1587
|
-
const store = {
|
|
1588
|
-
query: async (spec) => {
|
|
1589
|
-
await ready;
|
|
1590
|
-
const where = compileWhere(spec.where, 1);
|
|
1591
|
-
const limit = spec.limit === void 0 ? "" : ` LIMIT ${Math.max(0, Math.floor(spec.limit))}`;
|
|
1592
|
-
const result = await client.query(
|
|
1593
|
-
`SELECT * FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql}${compileOrder(spec.order)}${limit}`,
|
|
1594
|
-
where.params
|
|
1595
|
-
);
|
|
1596
|
-
return result.rows.map((row) => rowToEntity(spec.table, row));
|
|
1597
|
-
},
|
|
1598
|
-
// ON CONFLICT DO NOTHING, which is the whole point: the refusal is the
|
|
1599
|
-
// DATABASE's, decided under the constraint, not a read the caller races.
|
|
1600
|
-
appendIfAbsent: async (table, input) => {
|
|
1601
|
-
await ready;
|
|
1602
|
-
const withId = tide.PRIMARY_KEY[table] === "id" ? { ...input, id: input.id ?? mintId(table) } : { ...input };
|
|
1603
|
-
const entries = Object.entries(withId).filter(([, value]) => value !== void 0);
|
|
1604
|
-
const columns = entries.map(([field]) => snake(field));
|
|
1605
|
-
const params = entries.map(([field, value]) => toColumn(snake(field), value));
|
|
1606
|
-
const unique = tide.UNIQUE_BY[table];
|
|
1607
|
-
const target = unique.when === void 0 ? `(${unique.by.map((column) => snake(String(column))).join(", ")})` : `(${unique.by.map((column) => column === "entity" || column === "name" ? `coalesce(${snake(String(column))},'')` : snake(String(column))).join(", ")}) WHERE ${snake(String(unique.when))} IS NOT NULL`;
|
|
1608
|
-
const result = await client.query(
|
|
1609
|
-
`INSERT INTO ${SQL_TABLE[table]} (${columns.join(", ")}) VALUES (${params.map((_value, index) => `$${index + 1}`).join(", ")})
|
|
1610
|
-
ON CONFLICT ${target} DO NOTHING RETURNING *`,
|
|
1611
|
-
params
|
|
1612
|
-
);
|
|
1613
|
-
const row = result.rows[0];
|
|
1614
|
-
return row === void 0 ? void 0 : rowToEntity(table, row);
|
|
1615
|
-
},
|
|
1616
|
-
// Selection and mutation in ONE statement. `FOR UPDATE SKIP LOCKED`
|
|
1617
|
-
// makes N instances ticking at once ordinary contention rather than a
|
|
1618
|
-
// lock service — it is a throughput choice; the exactly-once promise is
|
|
1619
|
-
// the single statement.
|
|
1620
|
-
claim: async (spec) => {
|
|
1621
|
-
await ready;
|
|
1622
|
-
const table = SQL_TABLE[spec.table];
|
|
1623
|
-
const order = compileOrder(spec.order, "c");
|
|
1624
|
-
const take = async (extra, limit) => {
|
|
1625
|
-
if (limit <= 0) return [];
|
|
1626
|
-
const where = compileWhere({ ...spec.where, ...extra }, 1, "c");
|
|
1627
|
-
const set = compileSet(spec.set, where.params.length + 1);
|
|
1628
|
-
const result = await client.query(
|
|
1629
|
-
`UPDATE ${table} SET ${set.sql}
|
|
1630
|
-
WHERE ctid IN (
|
|
1631
|
-
SELECT c.ctid FROM ${table} c WHERE ${where.sql}${order}
|
|
1632
|
-
LIMIT ${Math.floor(limit)} FOR UPDATE SKIP LOCKED
|
|
1633
|
-
)
|
|
1634
|
-
RETURNING *`,
|
|
1635
|
-
[...where.params, ...set.params]
|
|
1636
|
-
);
|
|
1637
|
-
return sortRows(result.rows.map((row) => rowToEntity(spec.table, row)), spec.order);
|
|
1638
|
-
};
|
|
1639
|
-
if (spec.onePer === void 0) return take({}, spec.limit);
|
|
1640
|
-
const { column, held, only } = spec.onePer;
|
|
1641
|
-
const restricted = [...only];
|
|
1642
|
-
const claimed = await take({ [String(column)]: { notIn: restricted } }, spec.limit - restricted.length);
|
|
1643
|
-
for (const group of restricted) {
|
|
1644
|
-
if (claimed.length >= spec.limit) break;
|
|
1645
|
-
const busy = compileWhere({ ...held, [String(column)]: group }, 1, "c");
|
|
1646
|
-
const taken = await client.query(`SELECT c.id FROM ${table} c WHERE ${busy.sql} LIMIT 1`, busy.params);
|
|
1647
|
-
if (taken.rows.length > 0) continue;
|
|
1648
|
-
claimed.push(...await take({ [String(column)]: group }, 1));
|
|
1649
|
-
}
|
|
1650
|
-
return claimed;
|
|
1651
|
-
},
|
|
1652
|
-
cas: async (table, id, expect, set) => {
|
|
1653
|
-
await ready;
|
|
1654
|
-
const key = snake(String(tide.PRIMARY_KEY[table]));
|
|
1655
|
-
const where = compileWhere(expect, 2);
|
|
1656
|
-
const patch = compileSet(set, where.params.length + 2);
|
|
1657
|
-
const result = await client.query(
|
|
1658
|
-
`UPDATE ${SQL_TABLE[table]} SET ${patch.sql} WHERE ${key} = $1 AND ${where.sql} RETURNING ${key}`,
|
|
1659
|
-
[id, ...where.params, ...patch.params]
|
|
1660
|
-
);
|
|
1661
|
-
return result.rows.length > 0;
|
|
1662
|
-
},
|
|
1663
|
-
remove: async (spec) => {
|
|
1664
|
-
await ready;
|
|
1665
|
-
const where = compileWhere(spec.where, 1);
|
|
1666
|
-
const result = await client.query(`DELETE FROM ${SQL_TABLE[spec.table]} WHERE ${where.sql} RETURNING ${snake(String(tide.PRIMARY_KEY[spec.table]))}`, where.params);
|
|
1667
|
-
return result.rows.length;
|
|
1668
|
-
},
|
|
1669
|
-
transact: async (fn) => {
|
|
1670
|
-
await ready;
|
|
1671
|
-
if (client.transaction === void 0)
|
|
1672
|
-
throw new Error("tide store: this pool cannot transact \u2014 fan-out and attempt recording are transactions, not conventions");
|
|
1673
|
-
return client.transaction((tx) => fn(build({ ...client, query: (text, values) => tx.query(text, values) })));
|
|
1674
|
-
}
|
|
1675
|
-
};
|
|
1676
|
-
return store;
|
|
1677
|
-
};
|
|
1678
|
-
return { ...build(pool), ready };
|
|
1679
|
-
};
|
|
1680
|
-
var mintWrites = async (intake, event, as, at, chain) => {
|
|
1681
|
-
for (const write of event.writes) {
|
|
1682
|
-
for (const row of write.rows) {
|
|
1683
|
-
await intake.ingest(
|
|
1684
|
-
{ kind: "write", entity: write.table, op: write.op, row, at },
|
|
1685
|
-
{ as, ...chain !== void 0 ? { cause: chain.cause, depth: chain.depth + 1 } : {} }
|
|
1686
|
-
);
|
|
1687
|
-
}
|
|
1688
|
-
}
|
|
1689
|
-
};
|
|
1690
|
-
var resolveRoles = (app, principal) => principal === null ? ["public"] : app.assignments?.[principal] ?? ["public"];
|
|
1691
|
-
var wearableOf = (app) => {
|
|
1692
|
-
const declared = app.wearable;
|
|
1693
|
-
const source = declared ?? Object.values(app.assignments ?? {});
|
|
1694
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1695
|
-
for (const roles of source) {
|
|
1696
|
-
const key = [...roles].sort().join("\0");
|
|
1697
|
-
if (!seen.has(key)) seen.set(key, roles);
|
|
1698
|
-
}
|
|
1699
|
-
return [...seen.values()];
|
|
1700
|
-
};
|
|
1701
|
-
var memoKey = (roles, installed) => `${[...roles].sort().join("\0")}\0\0${installed === void 0 ? "*" : [...installed].sort().join("\0")}`;
|
|
1702
|
-
var memoKeyOf = (app, principal) => memoKey(resolveRoles(app, principal), void 0);
|
|
1703
|
-
var resolvePolicy = (app, grants, principal) => {
|
|
1704
|
-
return resolvePolicyForRoles(app, grants, resolveRoles(app, principal));
|
|
1705
|
-
};
|
|
1706
|
-
var resolvePolicyForRoles = (app, grants, roles) => {
|
|
1707
|
-
const behaviors = app.behaviors ?? {};
|
|
1708
|
-
return vex.mergeScopePolicies(
|
|
1709
|
-
roles.map(
|
|
1710
|
-
(role) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, [role], "data"), behaviors, charter.resolveScoping(app.charter, role))
|
|
1711
|
-
)
|
|
1712
|
-
);
|
|
1713
|
-
};
|
|
1714
|
-
var resolvePolicyAtReach = (app, grants, principal, reach) => resolvePolicyAtReachForRoles(app, grants, resolveRoles(app, principal), reach);
|
|
1715
|
-
var resolvePolicyAtReachForRoles = (app, grants, roles, reach) => vex.createScopePolicy(charter.resolvePrincipal(app.charter, grants, roles, "data"), app.behaviors ?? {}, reach);
|
|
1716
|
-
var resolveCatalogForRoles = (app, roles, installed) => {
|
|
1717
|
-
const granted = [...charter.resolvePrincipal(app.charter, Object.keys(app.actions), roles, "actions")].sort();
|
|
1718
|
-
const ids = [...filterInstalled(granted, installed === void 0 ? void 0 : new Set(installed))];
|
|
1719
|
-
return { ids, hash: versionToken(ids) };
|
|
1720
|
-
};
|
|
1721
|
-
var resolveVariantsForRoles = (app, roles) => {
|
|
1722
|
-
const variants = app.layouts ?? {};
|
|
1723
|
-
const granted = charter.resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts");
|
|
1724
|
-
const bindings = /* @__PURE__ */ new Map();
|
|
1725
|
-
for (const id of granted) {
|
|
1726
|
-
const variant = variants[id];
|
|
1727
|
-
if (variant !== void 0) bindings.set(variant.action, variant.layout);
|
|
1728
|
-
}
|
|
1729
|
-
return bindings;
|
|
1730
|
-
};
|
|
1731
|
-
var resolveCatalog = (app, principal) => resolveCatalogForRoles(app, resolveRoles(app, principal), void 0);
|
|
1732
|
-
var resolveVariants = (app, principal) => {
|
|
1733
|
-
const variants = app.layouts ?? {};
|
|
1734
|
-
const granted = charter.resolvePrincipal(app.charter, Object.keys(variants), resolveRoles(app, principal), "layouts");
|
|
1735
|
-
const bindings = /* @__PURE__ */ new Map();
|
|
1736
|
-
for (const id of granted) {
|
|
1737
|
-
const variant = variants[id];
|
|
1738
|
-
if (variant !== void 0) bindings.set(variant.action, variant.layout);
|
|
1739
|
-
}
|
|
1740
|
-
return bindings;
|
|
1741
|
-
};
|
|
1742
|
-
var verifyVariants = (app) => {
|
|
1743
|
-
const variants = app.layouts ?? {};
|
|
1744
|
-
const ids = Object.keys(variants);
|
|
1745
|
-
if (ids.length === 0) return [];
|
|
1746
|
-
const errors = [];
|
|
1747
|
-
for (const [id, variant] of Object.entries(variants)) {
|
|
1748
|
-
if (app.actions[variant.action] === void 0) {
|
|
1749
|
-
errors.push(`layout variant "${id}" reshapes unknown action "${variant.action}"`);
|
|
1750
|
-
}
|
|
1751
|
-
}
|
|
1752
|
-
const wearers = /* @__PURE__ */ new Map();
|
|
1753
|
-
for (const role of Object.keys(app.charter)) wearers.set(`role "${role}"`, [role]);
|
|
1754
|
-
for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(", ")}]`, roles);
|
|
1755
|
-
wearers.set("the anonymous principal", ["public"]);
|
|
1756
|
-
for (const [who, roles] of wearers) {
|
|
1757
|
-
let granted;
|
|
1758
|
-
try {
|
|
1759
|
-
granted = charter.resolvePrincipal(app.charter, ids, roles, "layouts");
|
|
1760
|
-
} catch {
|
|
1761
|
-
continue;
|
|
1762
|
-
}
|
|
1763
|
-
const byAction = /* @__PURE__ */ new Map();
|
|
1764
|
-
for (const id of granted) {
|
|
1765
|
-
const variant = variants[id];
|
|
1766
|
-
if (variant !== void 0) byAction.set(variant.action, [...byAction.get(variant.action) ?? [], id]);
|
|
1767
|
-
}
|
|
1768
|
-
for (const [action, held] of byAction) {
|
|
1769
|
-
if (held.length > 1) {
|
|
1770
|
-
errors.push(`${who} holds ${held.length} variants of "${action}" (${held.sort().join(", ")}) \u2014 one variant per action per principal`);
|
|
1771
|
-
}
|
|
1772
|
-
}
|
|
1773
|
-
}
|
|
1774
|
-
return errors;
|
|
1775
|
-
};
|
|
1776
|
-
var versionToken = (ids) => {
|
|
1777
|
-
const s = ids.join("\n");
|
|
1778
|
-
let h = 2166136261;
|
|
1779
|
-
for (let i = 0; i < s.length; i += 1) {
|
|
1780
|
-
h ^= s.charCodeAt(i);
|
|
1781
|
-
h = Math.imul(h, 16777619) >>> 0;
|
|
1782
|
-
}
|
|
1783
|
-
return h.toString(16).padStart(8, "0");
|
|
1784
|
-
};
|
|
1785
|
-
|
|
1786
|
-
// src/session-cookie.ts
|
|
1787
|
-
var DEFAULT_TOKEN_KEY = "nisc.token";
|
|
1788
|
-
var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
|
|
1789
|
-
if (header === void 0 || header === null) return null;
|
|
1790
|
-
const wanted = encodeURIComponent(name);
|
|
1791
|
-
for (const part of header.split(";")) {
|
|
1792
|
-
const at = part.indexOf("=");
|
|
1793
|
-
if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
|
|
1794
|
-
try {
|
|
1795
|
-
const value = decodeURIComponent(part.slice(at + 1).trim());
|
|
1796
|
-
return value === "" ? null : value;
|
|
1797
|
-
} catch {
|
|
1798
|
-
return null;
|
|
1799
|
-
}
|
|
1800
|
-
}
|
|
1801
|
-
return null;
|
|
1802
|
-
};
|
|
1803
|
-
var isOwnOrigin = (origin, host, listed = []) => {
|
|
1804
|
-
if (origin === void 0 || origin === null || !URL.canParse(origin)) return false;
|
|
1805
|
-
const asked = new URL(origin);
|
|
1806
|
-
return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
|
|
1807
|
-
};
|
|
1808
|
-
var nameOf = (key, port) => `${key}${port === "" ? "" : `.${port}`}`;
|
|
1809
|
-
var cookiesAt = (where, key, token, lastsMs) => {
|
|
1810
|
-
const name = encodeURIComponent(nameOf(key, where.port));
|
|
1811
|
-
const life = token === null ? "; Max-Age=0" : typeof lastsMs === "number" ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1e3))}` : "";
|
|
1812
|
-
const kept = `Path=/; SameSite=Lax${where.secure ? "; Secure" : ""}${life}`;
|
|
1813
|
-
return [`${where.secure ? "__Host-" : ""}${name}=${encodeURIComponent(token ?? "")}; HttpOnly; ${kept}`, `${name}.held=${token === null ? "" : "1"}; ${kept}`];
|
|
1814
|
-
};
|
|
1815
|
-
var originOf = (request) => {
|
|
1816
|
-
const said = request.headers.get("origin");
|
|
1817
|
-
if (said !== null && URL.canParse(said)) return said;
|
|
1818
|
-
const here = new URL(request.url);
|
|
1819
|
-
const scheme = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || here.protocol.slice(0, -1);
|
|
1820
|
-
return `${scheme}://${request.headers.get("host") ?? here.host}`;
|
|
1821
|
-
};
|
|
1822
|
-
var sessionCookies = (page, token, options = {}) => {
|
|
1823
|
-
const at = new URL(typeof page === "string" ? page : originOf(page));
|
|
1824
|
-
return cookiesAt({ port: at.port, secure: at.protocol === "https:" }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);
|
|
1825
|
-
};
|
|
1826
|
-
var sessionTokenOf = (cookies, where, key = DEFAULT_TOKEN_KEY) => {
|
|
1827
|
-
const name = nameOf(key, where.port);
|
|
1828
|
-
for (const secure of where.secure === void 0 ? [true, false] : [where.secure]) {
|
|
1829
|
-
const token = tokenFromCookie(cookies, `${secure ? "__Host-" : ""}${name}`);
|
|
1830
|
-
if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };
|
|
1831
|
-
}
|
|
1832
|
-
return null;
|
|
1833
|
-
};
|
|
1834
|
-
var SEALED_FOR_MS = 6e4;
|
|
1835
|
-
var sealName = (secure) => `${secure ? "__Http-" : ""}nisc.seal`;
|
|
1836
|
-
var toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1837
|
-
var fromBase64Url = (text) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0));
|
|
1838
|
-
var keyOf = async (seal) => crypto.subtle.importKey("raw", await crypto.subtle.digest("SHA-256", new TextEncoder().encode(seal)), "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
1839
|
-
var newSeal = () => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
|
|
1840
|
-
var sealOf = (cookies, secure) => tokenFromCookie(cookies, sealName(secure));
|
|
1841
|
-
var sealCookie = (seal, where) => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? "; Secure" : ""}`;
|
|
1842
|
-
var sealSession = async (seal, token, forMs = SEALED_FOR_MS) => {
|
|
1843
|
-
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
1844
|
-
const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));
|
|
1845
|
-
return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));
|
|
1846
|
-
};
|
|
1847
|
-
var openSealed = async (seal, sealed) => {
|
|
1848
|
-
try {
|
|
1849
|
-
const bytes = fromBase64Url(sealed);
|
|
1850
|
-
const opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));
|
|
1851
|
-
const { token, until } = JSON.parse(new TextDecoder().decode(opened));
|
|
1852
|
-
return typeof token === "string" && typeof until === "number" && until > Date.now() ? token : null;
|
|
1853
|
-
} catch {
|
|
1854
|
-
return null;
|
|
1855
|
-
}
|
|
1856
|
-
};
|
|
1857
|
-
|
|
1858
|
-
// src/socket.ts
|
|
1859
|
-
var PROTOCOL = 2;
|
|
1860
|
-
var PROTOCOL_MIN = 2;
|
|
1861
|
-
var SUBPROTOCOL = "nisc";
|
|
1862
|
-
var TOKEN_OFFER = "nisc.token.";
|
|
1863
|
-
var SEALED_OFFER = "nisc.sealed.";
|
|
1864
|
-
var offerToken = (token, sealed = null) => {
|
|
1865
|
-
const offer = sealed === null ? [SUBPROTOCOL] : [SUBPROTOCOL, `${SEALED_OFFER}${sealed}`];
|
|
1866
|
-
if (token === null) return offer;
|
|
1867
|
-
const bytes = String.fromCharCode(...new TextEncoder().encode(token));
|
|
1868
|
-
return [...offer, `${TOKEN_OFFER}${btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`];
|
|
1869
|
-
};
|
|
1870
|
-
var offeredToken = (offered = []) => {
|
|
1871
|
-
const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));
|
|
1872
|
-
if (offer === void 0) return null;
|
|
1873
|
-
try {
|
|
1874
|
-
const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, "+").replace(/_/g, "/"));
|
|
1875
|
-
return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;
|
|
1876
|
-
} catch {
|
|
1877
|
-
return null;
|
|
1878
|
-
}
|
|
1879
|
-
};
|
|
1880
|
-
var CLOSE_INVALID_TOKEN = 4401;
|
|
1881
|
-
var CLOSE_SIGNED_OUT = 4403;
|
|
1882
|
-
var CLOSE_SHELL_FAILED = 4500;
|
|
1883
|
-
var CLOSE_PROTOCOL_MISMATCH = 4426;
|
|
1884
|
-
var DEFAULT_REVALIDATE_MS = 60 * 1e3;
|
|
1885
|
-
var parse = (text) => {
|
|
1886
|
-
try {
|
|
1887
|
-
const value = JSON.parse(text);
|
|
1888
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1889
|
-
} catch {
|
|
1890
|
-
return null;
|
|
1891
|
-
}
|
|
1892
|
-
};
|
|
1893
|
-
var createSocket = (ctx) => {
|
|
1894
|
-
const emit = emitterOf(ctx.telemetry);
|
|
1895
|
-
let saidNotOwn = false;
|
|
1896
|
-
const live = /* @__PURE__ */ new Map();
|
|
1897
|
-
const expire = (connection) => {
|
|
1898
|
-
connection.send(JSON.stringify({ type: "error", code: "invalid_token", message: "The session token no longer resolves to this principal." }));
|
|
1899
|
-
connection.close(CLOSE_INVALID_TOKEN, "session expired");
|
|
1900
|
-
live.delete(connection);
|
|
1901
|
-
};
|
|
1902
|
-
const revalidate = async () => {
|
|
1903
|
-
for (const [connection, credential] of [...live]) {
|
|
1904
|
-
if (credential === null) continue;
|
|
1905
|
-
let resolved;
|
|
1906
|
-
try {
|
|
1907
|
-
resolved = await ctx.session(credential.token);
|
|
1908
|
-
} catch {
|
|
1909
|
-
continue;
|
|
1910
|
-
}
|
|
1911
|
-
if (resolved === credential.principal) continue;
|
|
1912
|
-
if (!live.has(connection)) continue;
|
|
1913
|
-
expire(connection);
|
|
1914
|
-
}
|
|
1915
|
-
};
|
|
1916
|
-
const revalidateMs = ctx.revalidateMs ?? DEFAULT_REVALIDATE_MS;
|
|
1917
|
-
let sweeper;
|
|
1918
|
-
if (revalidateMs > 0 && Number.isFinite(revalidateMs)) {
|
|
1919
|
-
sweeper = setInterval(() => void revalidate(), revalidateMs);
|
|
1920
|
-
sweeper.unref?.();
|
|
1921
|
-
}
|
|
1922
|
-
const accept = async (url, connection) => {
|
|
1923
|
-
const send = (message) => connection.send(JSON.stringify(message));
|
|
1924
|
-
try {
|
|
1925
|
-
await open(url, connection, send);
|
|
1926
|
-
} catch (error) {
|
|
1927
|
-
console.error("[moss/socket] refused a session:", error);
|
|
1928
|
-
live.delete(connection);
|
|
1929
|
-
const failures = error instanceof nova.DefinitionValidationError ? (error.context?.failures ?? []).map((f) => f.id) : [];
|
|
1930
|
-
const detail = failures.length > 0 ? `${String(error instanceof Error ? error.message : error)}: ${failures.join(", ")}` : String(error);
|
|
1931
|
-
try {
|
|
1932
|
-
send({ type: "error", code: "session_failed", message: `This session could not be opened \u2014 ${detail}. The refusal is this terminal's alone; the server is up.` });
|
|
1933
|
-
connection.close(CLOSE_SHELL_FAILED, "session failed");
|
|
1934
|
-
} catch {
|
|
1935
|
-
}
|
|
1936
|
-
}
|
|
1937
|
-
};
|
|
1938
|
-
const open = async (url, connection, send) => {
|
|
1939
|
-
const upClock = emit === void 0 ? void 0 : spanClock();
|
|
1940
|
-
const params = new URL(url, "http://nisc.local").searchParams;
|
|
1941
|
-
const spoken = Number(params.get("protocol") ?? "1");
|
|
1942
|
-
if (!Number.isInteger(spoken) || spoken < PROTOCOL_MIN || spoken > PROTOCOL) {
|
|
1943
|
-
const behind = spoken > PROTOCOL ? "server" : "client";
|
|
1944
|
-
send({
|
|
1945
|
-
type: "error",
|
|
1946
|
-
code: `${behind}_too_old`,
|
|
1947
|
-
message: `This terminal speaks protocol ${params.get("protocol") ?? "1"}; this server speaks ${PROTOCOL_MIN}\u2013${PROTOCOL}. ${behind === "client" ? "Reload the terminal to get the current build." : "The server has not been updated yet."}`
|
|
1948
|
-
});
|
|
1949
|
-
connection.close(CLOSE_PROTOCOL_MISMATCH, "protocol mismatch");
|
|
1950
|
-
return;
|
|
1951
|
-
}
|
|
1952
|
-
const upgrade = connection.upgrade;
|
|
1953
|
-
const key = /^[\w.-]{1,64}$/.test(params.get("key") ?? "") ? params.get("key") : DEFAULT_TOKEN_KEY;
|
|
1954
|
-
const page = upgrade !== void 0 && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : void 0;
|
|
1955
|
-
const secure = page?.protocol === "https:";
|
|
1956
|
-
const held = page === void 0 ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);
|
|
1957
|
-
const sealing = page !== void 0 && params.get("sealed") === "1";
|
|
1958
|
-
if (page === void 0 && params.get("sealed") === "1" && typeof upgrade?.origin === "string" && !saidNotOwn) {
|
|
1959
|
-
saidNotOwn = true;
|
|
1960
|
-
console.warn(`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? "nothing"}, so that is not the app\u2019s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`);
|
|
1961
|
-
}
|
|
1962
|
-
const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;
|
|
1963
|
-
const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;
|
|
1964
|
-
const sealLost = sealing && sealedOffer !== null && hadSeal === null;
|
|
1965
|
-
const seal = !sealing || sealLost ? null : hadSeal ?? (upgrade?.answer === void 0 ? null : newSeal());
|
|
1966
|
-
const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));
|
|
1967
|
-
let token = offered ?? (params.get("leave") === "1" ? null : held?.token ?? null);
|
|
1968
|
-
let principal = token === null ? null : await ctx.session(token);
|
|
1969
|
-
if (offered !== null && principal === null) {
|
|
1970
|
-
if (emit !== void 0 && upClock !== void 0) {
|
|
1971
|
-
emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "refused", attributes: { hasPrincipal: false } });
|
|
1972
|
-
}
|
|
1973
|
-
send({ type: "error", code: "invalid_token", message: "The session token did not resolve to a principal." });
|
|
1974
|
-
connection.close(CLOSE_INVALID_TOKEN, "invalid token");
|
|
1975
|
-
return;
|
|
1976
|
-
}
|
|
1977
|
-
if (principal === null) token = null;
|
|
1978
|
-
const answered = [
|
|
1979
|
-
...page === void 0 || offered === null && (held?.token ?? null) === token ? [] : token === null ? held?.clear ?? [] : sessionCookies(page.origin, token, { key, lastsMs: await ctx.sessionLastsMs?.(token) ?? null }),
|
|
1980
|
-
...seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, "http://nisc.local").pathname })] : []
|
|
1981
|
-
];
|
|
1982
|
-
if (answered.length > 0) upgrade?.answer?.(answered);
|
|
1983
|
-
if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);
|
|
1984
|
-
if (sealLost) {
|
|
1985
|
-
send({ type: "error", code: "seal_not_kept", message: "This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token." });
|
|
1986
|
-
}
|
|
1987
|
-
live.set(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
|
|
1988
|
-
connection.onClose(() => live.delete(connection));
|
|
1989
|
-
if (emit !== void 0 && upClock !== void 0) {
|
|
1990
|
-
const hadPrincipal = principal !== null;
|
|
1991
|
-
connection.onClose(() => emit({ name: "socket.close", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "ok", attributes: { hasPrincipal: hadPrincipal } }));
|
|
1992
|
-
}
|
|
1993
|
-
const { ids, hash } = await ctx.catalog(principal);
|
|
1994
|
-
send({ type: "hello", protocol: PROTOCOL, principal, catalog: { actions: ids, hash } });
|
|
1995
|
-
const wantsDelta = params.get("delta") === "1";
|
|
1996
|
-
const named = params.get("seed");
|
|
1997
|
-
const seed = named !== null && /^[0-9a-f]{8,40}$/.test(named) ? named : void 0;
|
|
1998
|
-
const path = params.get("path");
|
|
1999
|
-
const route = path === null ? void 0 : ctx.page?.(path);
|
|
2000
|
-
const host = route?.host ?? ctx.shells;
|
|
2001
|
-
const session = await host?.session(token, principal, { ...seed === void 0 ? {} : { seed }, ...route === void 0 ? {} : { inputs: route.inputs } });
|
|
2002
|
-
if (session !== void 0) {
|
|
2003
|
-
session.attach(connection, { delta: wantsDelta });
|
|
2004
|
-
connection.onClose(() => session.detach(connection));
|
|
2005
|
-
}
|
|
2006
|
-
if (emit !== void 0 && upClock !== void 0) {
|
|
2007
|
-
emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "ok", attributes: { hasPrincipal: principal !== null } });
|
|
2008
|
-
}
|
|
2009
|
-
connection.onMessage((text) => {
|
|
2010
|
-
const message = parse(text);
|
|
2011
|
-
if (message !== null && message["type"] === "reset") {
|
|
2012
|
-
if (session === void 0) {
|
|
2013
|
-
send({ type: "error", code: "no_shell", message: "This app serves no shell." });
|
|
2014
|
-
return;
|
|
2015
|
-
}
|
|
2016
|
-
session.reset();
|
|
2017
|
-
return;
|
|
2018
|
-
}
|
|
2019
|
-
if (message !== null && message["type"] === "resync") {
|
|
2020
|
-
if (session === void 0) {
|
|
2021
|
-
send({ type: "error", code: "no_shell", message: "This app serves no shell." });
|
|
2022
|
-
return;
|
|
2023
|
-
}
|
|
2024
|
-
session.resync(connection);
|
|
2025
|
-
return;
|
|
2026
|
-
}
|
|
2027
|
-
if (message !== null && message["type"] === "back") {
|
|
2028
|
-
if (session === void 0) {
|
|
2029
|
-
send({ type: "error", code: "no_shell", message: "This app serves no shell." });
|
|
2030
|
-
return;
|
|
2031
|
-
}
|
|
2032
|
-
session.back();
|
|
2033
|
-
return;
|
|
2034
|
-
}
|
|
2035
|
-
if (message !== null && message["type"] === "popTo" && typeof message["canvas"] === "string" && typeof message["instance"] === "string") {
|
|
2036
|
-
if (session === void 0) {
|
|
2037
|
-
send({ type: "error", code: "no_shell", message: "This app serves no shell." });
|
|
2038
|
-
return;
|
|
2039
|
-
}
|
|
2040
|
-
session.popTo(message["canvas"], message["instance"]);
|
|
2041
|
-
return;
|
|
2042
|
-
}
|
|
2043
|
-
if (message !== null && message["type"] === "publish" && typeof message["channel"] === "string") {
|
|
2044
|
-
if (session === void 0) {
|
|
2045
|
-
send({ type: "error", code: "no_shell", message: "This app serves no shell." });
|
|
2046
|
-
return;
|
|
2047
|
-
}
|
|
2048
|
-
session.publish(message["channel"], message["payload"]);
|
|
2049
|
-
return;
|
|
2050
|
-
}
|
|
2051
|
-
if (message === null || message["type"] !== "event" || typeof message["canvas"] !== "string") {
|
|
2052
|
-
send({ type: "error", code: "invalid_message", message: 'Messages are JSON { type: "event", canvas, event }.' });
|
|
2053
|
-
return;
|
|
2054
|
-
}
|
|
2055
|
-
if (session === void 0) {
|
|
2056
|
-
send({ type: "error", code: "no_shell", message: "This app serves no shell.", canvas: message["canvas"] });
|
|
2057
|
-
return;
|
|
2058
|
-
}
|
|
2059
|
-
const event = message["event"];
|
|
2060
|
-
if (event === null || typeof event !== "object" || Array.isArray(event)) {
|
|
2061
|
-
send({ type: "error", code: "invalid_message", message: "The event field must be a NovaEvent object.", canvas: message["canvas"] });
|
|
2062
|
-
return;
|
|
2063
|
-
}
|
|
2064
|
-
session.dispatch(message["canvas"], event);
|
|
2065
|
-
});
|
|
2066
|
-
};
|
|
2067
|
-
return Object.assign(accept, {
|
|
2068
|
-
stop: () => {
|
|
2069
|
-
if (sweeper !== void 0) clearInterval(sweeper);
|
|
2070
|
-
sweeper = void 0;
|
|
2071
|
-
}
|
|
2072
|
-
});
|
|
2073
|
-
};
|
|
2074
|
-
|
|
2075
|
-
// src/delta.ts
|
|
2076
|
-
var BLOCK = 16;
|
|
2077
|
-
var encodeDelta = (base, target) => {
|
|
2078
|
-
if (base.length < BLOCK) return [[1, target]];
|
|
2079
|
-
const index = /* @__PURE__ */ new Map();
|
|
2080
|
-
for (let i = 0; i + BLOCK <= base.length; i += 1) {
|
|
2081
|
-
const key = base.slice(i, i + BLOCK);
|
|
2082
|
-
if (!index.has(key)) index.set(key, i);
|
|
2083
|
-
}
|
|
2084
|
-
const ops = [];
|
|
2085
|
-
let literal = "";
|
|
2086
|
-
let at = 0;
|
|
2087
|
-
while (at < target.length) {
|
|
2088
|
-
const key = target.slice(at, at + BLOCK);
|
|
2089
|
-
const found = key.length === BLOCK ? index.get(key) : void 0;
|
|
2090
|
-
if (found === void 0) {
|
|
2091
|
-
literal += target[at];
|
|
2092
|
-
at += 1;
|
|
2093
|
-
continue;
|
|
2094
|
-
}
|
|
2095
|
-
let length = BLOCK;
|
|
2096
|
-
while (found + length < base.length && at + length < target.length && base[found + length] === target[at + length]) {
|
|
2097
|
-
length += 1;
|
|
2098
|
-
}
|
|
2099
|
-
if (literal !== "") {
|
|
2100
|
-
ops.push([1, literal]);
|
|
2101
|
-
literal = "";
|
|
2102
|
-
}
|
|
2103
|
-
ops.push([0, found, length]);
|
|
2104
|
-
at += length;
|
|
2105
|
-
}
|
|
2106
|
-
if (literal !== "") ops.push([1, literal]);
|
|
2107
|
-
return ops;
|
|
2108
|
-
};
|
|
2109
|
-
var frameHash = (text) => {
|
|
2110
|
-
let hash = 2166136261;
|
|
2111
|
-
for (let i = 0; i < text.length; i += 1) {
|
|
2112
|
-
hash ^= text.charCodeAt(i);
|
|
2113
|
-
hash = Math.imul(hash, 16777619);
|
|
2114
|
-
}
|
|
2115
|
-
return hash >>> 0;
|
|
2116
|
-
};
|
|
2117
|
-
|
|
2118
|
-
// src/shells.ts
|
|
2119
|
-
var INTEGRATION_PATH = /^\/integrations\/([a-z][a-z0-9-]*)\//;
|
|
2120
|
-
var flooredWire = (inner) => async (url, init) => {
|
|
2121
|
-
const integration = INTEGRATION_PATH.exec(url)?.[1];
|
|
2122
|
-
if (integration === void 0) return inner(url, init);
|
|
2123
|
-
const floor = (status) => {
|
|
2124
|
-
const body = { message: `The ${integration} add-on is not answering right now. The rest of the studio is unaffected.` };
|
|
2125
|
-
return { ok: false, status, json: async () => body, text: async () => JSON.stringify(body) };
|
|
2126
|
-
};
|
|
2127
|
-
let reply;
|
|
2128
|
-
try {
|
|
2129
|
-
reply = await inner(url, init);
|
|
2130
|
-
} catch {
|
|
2131
|
-
return floor(502);
|
|
2132
|
-
}
|
|
2133
|
-
if (reply.ok) return reply;
|
|
2134
|
-
try {
|
|
2135
|
-
const body = await reply.json();
|
|
2136
|
-
const message = body?.message;
|
|
2137
|
-
if (typeof message === "string" && message !== "The integration is unreachable.") {
|
|
2138
|
-
return { ok: false, status: reply.status, json: async () => body, text: async () => JSON.stringify(body) };
|
|
2139
|
-
}
|
|
2140
|
-
} catch {
|
|
2141
|
-
}
|
|
2142
|
-
return floor(reply.status);
|
|
2143
|
-
};
|
|
2144
|
-
var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
|
|
2145
|
-
var SWEEP_EVERY_MS = 60 * 1e3;
|
|
2146
|
-
var today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
2147
|
-
var instrumentFunctions = (fns, emit, principal) => Object.fromEntries(
|
|
2148
|
-
Object.entries(fns).map(([name, handler]) => [
|
|
2149
|
-
name,
|
|
2150
|
-
async (data, signal) => {
|
|
2151
|
-
const clock = spanClock();
|
|
2152
|
-
const hasPrincipal = principal !== null;
|
|
2153
|
-
try {
|
|
2154
|
-
const out = await handler(data, signal);
|
|
2155
|
-
emit({ name: "fn.call", startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: "ok", attributes: { fn: name, hasPrincipal } });
|
|
2156
|
-
return out;
|
|
2157
|
-
} catch (err) {
|
|
2158
|
-
emit({ name: "fn.call", startUnixNano: clock.startUnixNano, endUnixNano: clock.endUnixNano(), status: "error", attributes: { fn: name, hasPrincipal } });
|
|
2159
|
-
throw err;
|
|
2160
|
-
}
|
|
2161
|
-
}
|
|
2162
|
-
])
|
|
2163
|
-
);
|
|
2164
|
-
var createShellHost = (ctx) => {
|
|
2165
|
-
const emit = emitterOf(ctx.runtime.telemetry);
|
|
2166
|
-
const manifest = ctx.manifest ?? ctx.app.shell;
|
|
2167
|
-
if (manifest === void 0) throw new Error("createShellHost: the app manifest has no `shell`.");
|
|
2168
|
-
const shellManifest = manifest;
|
|
2169
|
-
const kept = ctx.kept ?? true;
|
|
2170
|
-
const componentNames = /* @__PURE__ */ new Set([nova.CANVAS_SLOT_NAME, nova.ACTION_SLOT_NAME]);
|
|
2171
|
-
for (const source of [ctx.app.actions, ctx.app.layouts ?? {}, shellManifest.canvases, shellManifest.layout ?? {}, shellManifest.layoutStore ?? {}, shellManifest.fragments ?? {}]) {
|
|
2172
|
-
for (const name of reflect.componentsOf(source)) componentNames.add(name);
|
|
2173
|
-
}
|
|
2174
|
-
const contracts = shellManifest.components ?? {};
|
|
2175
|
-
for (const name of Object.keys(contracts)) componentNames.add(name);
|
|
2176
|
-
const treeOf = (live, canvasId) => nova.canvasTreeOf(live.shell, canvasId);
|
|
2177
|
-
const frame = (live, canvasId) => {
|
|
2178
|
-
const message = { type: "render", canvas: canvasId, tree: treeOf(live, canvasId) };
|
|
2179
|
-
return JSON.stringify(message);
|
|
2180
|
-
};
|
|
2181
|
-
const frameOf = (live, canvasId) => {
|
|
2182
|
-
try {
|
|
2183
|
-
return frame(live, canvasId);
|
|
2184
|
-
} catch (error) {
|
|
2185
|
-
console.error(`[moss/shells] canvas "${canvasId}" failed to render \u2014 holding its last tree:`, error);
|
|
2186
|
-
return null;
|
|
2187
|
-
}
|
|
2188
|
-
};
|
|
2189
|
-
const delta = ctx.delta ?? false;
|
|
2190
|
-
const DELTA_CEILING = 0.6;
|
|
2191
|
-
const DELTA_MAX_FRAME = 64 * 1024;
|
|
2192
|
-
const shorterAsDelta = (previous, next, canvasId) => {
|
|
2193
|
-
if (previous.length > DELTA_MAX_FRAME || next.length > DELTA_MAX_FRAME) return null;
|
|
2194
|
-
try {
|
|
2195
|
-
const ops = encodeDelta(previous, next);
|
|
2196
|
-
const message = { type: "render-delta", canvas: canvasId, ops, hash: frameHash(next) };
|
|
2197
|
-
const text = JSON.stringify(message);
|
|
2198
|
-
return text.length <= next.length * DELTA_CEILING ? text : null;
|
|
2199
|
-
} catch (error) {
|
|
2200
|
-
console.error(`[moss/shells] canvas "${canvasId}" failed to encode as a delta \u2014 sending it whole:`, error);
|
|
2201
|
-
return null;
|
|
2202
|
-
}
|
|
2203
|
-
};
|
|
2204
|
-
const durable = /* @__PURE__ */ new Map();
|
|
2205
|
-
const build = async (token, principal, reset = false, idSeed, given) => {
|
|
2206
|
-
const buildClock = emit === void 0 ? void 0 : spanClock();
|
|
2207
|
-
const who = await ctx.resolve(principal);
|
|
2208
|
-
const { ids } = who.catalog;
|
|
2209
|
-
const granted = new Set(ids);
|
|
2210
|
-
const bindings = who.variants;
|
|
2211
|
-
const inputs = await shellManifest.inputs?.({ principal, actions: ids, roles: who.roles, identity: who.scope, wire: ctx.wire(token) }) ?? {};
|
|
2212
|
-
const canvases = shellManifest.canvases.map((canvas) => {
|
|
2213
|
-
const declared = canvas.initial;
|
|
2214
|
-
const candidates = declared === void 0 ? [] : Array.isArray(declared) ? declared : [declared];
|
|
2215
|
-
const seed = candidates.find((c) => granted.has(typeof c === "string" ? c : c.action));
|
|
2216
|
-
if (seed === void 0) {
|
|
2217
|
-
const { initial: _dropped, ...rest } = canvas;
|
|
2218
|
-
return rest;
|
|
2219
|
-
}
|
|
2220
|
-
const action = typeof seed === "string" ? seed : seed.action;
|
|
2221
|
-
const staticInput = typeof seed === "string" ? {} : seed.input ?? {};
|
|
2222
|
-
const withFragments = typeof seed === "string" ? void 0 : seed.with;
|
|
2223
|
-
return {
|
|
2224
|
-
...canvas,
|
|
2225
|
-
initial: { action, input: { ...staticInput, ...inputs[canvas.id] ?? {}, ...given?.[canvas.id] ?? {} }, ...withFragments !== void 0 ? { with: withFragments } : {} }
|
|
2226
|
-
};
|
|
2227
|
-
});
|
|
2228
|
-
const wire = flooredWire(ctx.wire(token));
|
|
2229
|
-
const userId = principal ?? "anonymous";
|
|
2230
|
-
const registry = nova.createComponentRegistry();
|
|
2231
|
-
for (const name of componentNames) registry.register(name, contracts[name] ?? {});
|
|
2232
|
-
let built;
|
|
2233
|
-
let liveRef;
|
|
2234
|
-
const session = {
|
|
2235
|
-
principal,
|
|
2236
|
-
roles: who.roles,
|
|
2237
|
-
identity: who.scope,
|
|
2238
|
-
actions: ids,
|
|
2239
|
-
wire,
|
|
2240
|
-
runtime: ctx.runtime,
|
|
2241
|
-
policy: who.policy,
|
|
2242
|
-
get shell() {
|
|
2243
|
-
if (built === void 0) throw new Error("moss: a function touched the shell before the session finished building.");
|
|
2244
|
-
return built;
|
|
2245
|
-
},
|
|
2246
|
-
// GRANT: the minted token to every terminal of this session — they
|
|
2247
|
-
// reconnect as the new principal; this (anonymous) session stays
|
|
2248
|
-
// ephemeral and dies on detach.
|
|
2249
|
-
grant: (token2) => {
|
|
2250
|
-
const message = JSON.stringify({ type: "session", token: token2 });
|
|
2251
|
-
for (const connection of liveRef?.connections ?? []) {
|
|
2252
|
-
if (connection.seal === void 0) connection.send(message);
|
|
2253
|
-
else {
|
|
2254
|
-
void connection.seal(token2).then(
|
|
2255
|
-
(sealed) => connection.send(JSON.stringify({ type: "session", sealed })),
|
|
2256
|
-
(error) => console.error("[moss] a sign-in could not be sealed, and was not handed over:", error)
|
|
2257
|
-
);
|
|
2258
|
-
}
|
|
2259
|
-
}
|
|
2260
|
-
},
|
|
2261
|
-
// REVOKE: forget the credential, close every terminal SIGNED_OUT,
|
|
2262
|
-
// evict the durable shell. Under moss's own credential the rows go
|
|
2263
|
-
// first — closing the terminals clears the tokens THEY held, not a
|
|
2264
|
-
// copy anywhere else. The shell is the principal's and every one of
|
|
2265
|
-
// its terminals closes, so every session the principal holds is
|
|
2266
|
-
// deleted, not only the one this shell was built with. A custom
|
|
2267
|
-
// verifier's credential is the app's to revoke; 'dev-open' stores
|
|
2268
|
-
// none. The teardown is deferred a microtask so the calling trigger
|
|
2269
|
-
// finishes before its own shell is disposed.
|
|
2270
|
-
revoke: () => {
|
|
2271
|
-
const forgotten = ctx.runtime.session === "sessions" && principal !== null ? revokeAllFor(ctx.runtime.pool, principal) : Promise.resolve();
|
|
2272
|
-
forgotten.catch((error) => console.error(`[moss] sign-out of ${principal ?? "anonymous"} did not revoke its sessions:`, error));
|
|
2273
|
-
queueMicrotask(() => {
|
|
2274
|
-
if (liveRef === void 0) return;
|
|
2275
|
-
liveRef.ended = true;
|
|
2276
|
-
if (principal !== null && durable.get(principal)?.live === liveRef) durable.delete(principal);
|
|
2277
|
-
for (const connection of [...liveRef.connections]) connection.close(CLOSE_SIGNED_OUT, "signed out");
|
|
2278
|
-
liveRef.connections.clear();
|
|
2279
|
-
if (principal !== null) liveRef.shell.dispose();
|
|
2280
|
-
});
|
|
2281
|
-
return forgotten;
|
|
2282
|
-
},
|
|
2283
|
-
// The session's own fields are stamped here so a caller cannot get them
|
|
2284
|
-
// wrong, and the shell id is read lazily — a run cannot happen before
|
|
2285
|
-
// the shell exists, but this object is built before it does.
|
|
2286
|
-
recordRun: (run) => {
|
|
2287
|
-
if (ctx.app.runs === void 0) return;
|
|
2288
|
-
ctx.app.runs({ ...run, at: Date.now(), principal, shellId: built?.id ?? "" }, session);
|
|
2289
|
-
}
|
|
2290
|
-
};
|
|
2291
|
-
const phrases = await ctx.app.phrases?.({ principal, identity: who.scope, wire: ctx.wire(token) }) ?? {};
|
|
2292
|
-
const rawFunctions = ctx.app.functions?.(session) ?? {};
|
|
2293
|
-
const functions = emit === void 0 ? rawFunctions : instrumentFunctions(rawFunctions, emit, principal);
|
|
2294
|
-
if (kept) ctx.app.onSession?.(session);
|
|
2295
|
-
const layoutStore = nova.createLayoutStore();
|
|
2296
|
-
for (const [refId, node] of Object.entries(shellManifest.layoutStore ?? {})) layoutStore.set(refId, node);
|
|
2297
|
-
let minted = 0;
|
|
2298
|
-
const shell = nova.createShell({
|
|
2299
|
-
registry,
|
|
2300
|
-
canvases,
|
|
2301
|
-
layoutStore,
|
|
2302
|
-
...idSeed === void 0 ? {} : { instanceIdFn: () => `act-${idSeed}-${minted += 1}` },
|
|
2303
|
-
...shellManifest.layout !== void 0 ? { canvasLayout: shellManifest.layout } : {},
|
|
2304
|
-
// Ring 1 then ring 2: an ungranted action doesn't exist; a granted one
|
|
2305
|
-
// carries the principal's variant layout when they hold one — the swap
|
|
2306
|
-
// happens on the definition, before the shell exists, so everything
|
|
2307
|
-
// downstream (render, serialize, the wire) is already per-principal.
|
|
2308
|
-
actions: Object.fromEntries(
|
|
2309
|
-
Object.entries(ctx.app.actions).filter(([id]) => granted.has(id)).map(([id, definition]) => {
|
|
2310
|
-
const layout = bindings.get(id);
|
|
2311
|
-
return [id, layout === void 0 ? definition : { ...definition, layout }];
|
|
2312
|
-
})
|
|
2313
|
-
),
|
|
2314
|
-
...shellManifest.fragments !== void 0 ? { fragments: shellManifest.fragments } : {},
|
|
2315
|
-
// The same seam the client shell used: prism evaluates endpoint
|
|
2316
|
-
// request/response transforms; `$.userId` and `$.today` are ambient,
|
|
2317
|
-
// never authorable by a request. The config is the action's own object
|
|
2318
|
-
// on every call, so evaluate checks it once (the source is new each time).
|
|
2319
|
-
transform: (config, source) => prism.evaluate(config, source !== null && typeof source === "object" && !Array.isArray(source) ? { ...source, userId, today: today() } : source),
|
|
2320
|
-
fetch: wire,
|
|
2321
|
-
functions,
|
|
2322
|
-
...ctx.runtime.endpointTimeoutMs === void 0 ? {} : { endpointTimeoutMs: ctx.runtime.endpointTimeoutMs },
|
|
2323
|
-
// An EMPTY book is withheld rather than passed: the pass is active when
|
|
2324
|
-
// either of these is present, and an app that does no i18n at all should
|
|
2325
|
-
// not pay a matcher per render for a dictionary with nothing in it.
|
|
2326
|
-
// `phraseKeys` alone is the source language, which still fills counted
|
|
2327
|
-
// phrases — the one job that survives having nothing to translate.
|
|
2328
|
-
...Object.keys(phrases).length === 0 ? {} : { phrases },
|
|
2329
|
-
...ctx.app.phraseKeys === void 0 ? {} : { phraseKeys: ctx.app.phraseKeys }
|
|
2330
|
-
});
|
|
2331
|
-
built = shell;
|
|
2332
|
-
const live = { shell, connections: /* @__PURE__ */ new Set(), sent: /* @__PURE__ */ new Map(), deltaReady: /* @__PURE__ */ new Set(), flushing: false, ended: false, since: Date.now(), idleSince: Date.now(), seeded: Promise.resolve() };
|
|
2333
|
-
liveRef = live;
|
|
2334
|
-
const declaredSeeds = shellManifest.seeds?.({ principal, actions: ids, roles: who.roles, wire });
|
|
2335
|
-
if (declaredSeeds !== void 0) {
|
|
2336
|
-
live.seeded = Promise.resolve(declaredSeeds).then((byCanvas) => {
|
|
2337
|
-
if (live.ended) return;
|
|
2338
|
-
for (const [canvasId, seeds] of Object.entries(byCanvas ?? {})) {
|
|
2339
|
-
for (const seed of seeds) {
|
|
2340
|
-
const action = typeof seed === "string" ? seed : seed.action;
|
|
2341
|
-
if (!granted.has(action)) continue;
|
|
2342
|
-
const input = typeof seed === "string" ? void 0 : seed.input;
|
|
2343
|
-
const withFragments = typeof seed === "string" ? void 0 : seed.with;
|
|
2344
|
-
try {
|
|
2345
|
-
shell.push(canvasId, action, input, withFragments, { history: false });
|
|
2346
|
-
} catch {
|
|
2347
|
-
}
|
|
2348
|
-
}
|
|
2349
|
-
}
|
|
2350
|
-
}).catch(() => {
|
|
2351
|
-
});
|
|
2352
|
-
}
|
|
2353
|
-
const pass = () => {
|
|
2354
|
-
if (live.ended) return;
|
|
2355
|
-
for (const canvas of shellManifest.canvases) {
|
|
2356
|
-
const next = frameOf(live, canvas.id);
|
|
2357
|
-
const previous = live.sent.get(canvas.id);
|
|
2358
|
-
if (next === null || previous === next) continue;
|
|
2359
|
-
live.sent.set(canvas.id, next);
|
|
2360
|
-
const short = delta && previous !== void 0 && live.deltaReady.size > 0 ? shorterAsDelta(previous, next, canvas.id) : null;
|
|
2361
|
-
for (const connection of live.connections) {
|
|
2362
|
-
connection.send(short !== null && live.deltaReady.has(connection) ? short : next);
|
|
2363
|
-
}
|
|
2364
|
-
}
|
|
2365
|
-
let frame2;
|
|
2366
|
-
try {
|
|
2367
|
-
frame2 = JSON.stringify({ type: "frame", tree: live.shell.getShellRenderTree() });
|
|
2368
|
-
} catch (error) {
|
|
2369
|
-
console.error("[moss/shells] the shell frame failed to render on a flush \u2014 leaving the last one in place:", error);
|
|
2370
|
-
}
|
|
2371
|
-
if (frame2 !== void 0 && frame2 !== live.sentFrame) {
|
|
2372
|
-
live.sentFrame = frame2;
|
|
2373
|
-
for (const connection of live.connections) connection.send(frame2);
|
|
2374
|
-
}
|
|
2375
|
-
};
|
|
2376
|
-
const flush = () => {
|
|
2377
|
-
if (live.flushing) return;
|
|
2378
|
-
live.flushing = true;
|
|
2379
|
-
queueMicrotask(() => {
|
|
2380
|
-
live.flushing = false;
|
|
2381
|
-
pass();
|
|
2382
|
-
setTimeout(pass, 0);
|
|
2383
|
-
});
|
|
2384
|
-
};
|
|
2385
|
-
shell.onStateChange(flush);
|
|
2386
|
-
shell.onDataChange(flush);
|
|
2387
|
-
if (emit !== void 0 && buildClock !== void 0) {
|
|
2388
|
-
emit({ name: "shell.build", startUnixNano: buildClock.startUnixNano, endUnixNano: buildClock.endUnixNano(), status: "ok", attributes: { reset, hasPrincipal: principal !== null } });
|
|
2389
|
-
}
|
|
2390
|
-
return live;
|
|
2391
|
-
};
|
|
2392
|
-
const attach = (live, connection, options) => {
|
|
2393
|
-
live.connections.add(connection);
|
|
2394
|
-
if (delta && options?.delta === true) live.deltaReady.add(connection);
|
|
2395
|
-
live.idleSince = null;
|
|
2396
|
-
let frameTree = [];
|
|
2397
|
-
try {
|
|
2398
|
-
frameTree = live.shell.getShellRenderTree();
|
|
2399
|
-
} catch (error) {
|
|
2400
|
-
console.error("[moss/shells] the shell frame failed to render \u2014 serving an empty arrangement:", error);
|
|
2401
|
-
}
|
|
2402
|
-
const frameMessage = JSON.stringify({ type: "frame", tree: frameTree });
|
|
2403
|
-
connection.send(frameMessage);
|
|
2404
|
-
live.sentFrame = frameMessage;
|
|
2405
|
-
for (const canvas of shellManifest.canvases) {
|
|
2406
|
-
const next = frameOf(live, canvas.id);
|
|
2407
|
-
if (next === null) continue;
|
|
2408
|
-
if (live.sent.get(canvas.id) !== next) {
|
|
2409
|
-
for (const other of live.connections) if (other !== connection) other.send(next);
|
|
2410
|
-
}
|
|
2411
|
-
live.sent.set(canvas.id, next);
|
|
2412
|
-
connection.send(next);
|
|
2413
|
-
}
|
|
2414
|
-
};
|
|
2415
|
-
const rebuild = async (cell) => {
|
|
2416
|
-
const old = cell.live;
|
|
2417
|
-
const next = await build(cell.token, cell.principal, true);
|
|
2418
|
-
const carried = [...old.connections].map((connection) => ({ connection, delta: old.deltaReady.has(connection) }));
|
|
2419
|
-
old.ended = true;
|
|
2420
|
-
old.connections.clear();
|
|
2421
|
-
old.shell.dispose();
|
|
2422
|
-
cell.live = next;
|
|
2423
|
-
for (const { connection, delta: wants } of carried) attach(next, connection, { delta: wants });
|
|
2424
|
-
};
|
|
2425
|
-
const sessionOn = (cell, ephemeral) => ({
|
|
2426
|
-
// Read through the cell, always: after a reset the shell behind this
|
|
2427
|
-
// session is a different object.
|
|
2428
|
-
get shell() {
|
|
2429
|
-
return cell.live.shell;
|
|
2430
|
-
},
|
|
2431
|
-
attach: (connection, options) => attach(cell.live, connection, options),
|
|
2432
|
-
// Whole frames for this one connection — the state both ends can always
|
|
2433
|
-
// agree on. It stays delta-capable: it is level with `sent` again the
|
|
2434
|
-
// moment this returns, and the checksum will catch it if it is not.
|
|
2435
|
-
resync: (connection) => {
|
|
2436
|
-
const live = cell.live;
|
|
2437
|
-
if (!live.connections.has(connection)) return;
|
|
2438
|
-
let frameTree = [];
|
|
2439
|
-
try {
|
|
2440
|
-
frameTree = live.shell.getShellRenderTree();
|
|
2441
|
-
} catch (error) {
|
|
2442
|
-
console.error("[moss/shells] the shell frame failed to render on resync \u2014 serving an empty arrangement:", error);
|
|
2443
|
-
}
|
|
2444
|
-
connection.send(JSON.stringify({ type: "frame", tree: frameTree }));
|
|
2445
|
-
for (const canvas of shellManifest.canvases) {
|
|
2446
|
-
const current = live.sent.get(canvas.id) ?? frameOf(live, canvas.id);
|
|
2447
|
-
if (current === null || current === void 0) continue;
|
|
2448
|
-
connection.send(current);
|
|
2449
|
-
}
|
|
2450
|
-
},
|
|
2451
|
-
detach: (connection) => {
|
|
2452
|
-
const live = cell.live;
|
|
2453
|
-
live.connections.delete(connection);
|
|
2454
|
-
live.deltaReady.delete(connection);
|
|
2455
|
-
if (live.connections.size > 0) return;
|
|
2456
|
-
live.idleSince = Date.now();
|
|
2457
|
-
if (!ephemeral) return;
|
|
2458
|
-
live.ended = true;
|
|
2459
|
-
live.shell.dispose();
|
|
2460
|
-
},
|
|
2461
|
-
// Transport → shell addressing: the wire tags the canvas, and nova's own
|
|
2462
|
-
// origin filter delivers the event to one instance's triggers alone.
|
|
2463
|
-
//
|
|
2464
|
-
// A terminal NAMES the instance when it knows it — a list canvas renders
|
|
2465
|
-
// several live cards, and the ActionSlot around the press says which. That
|
|
2466
|
-
// claim comes off the wire, so it is held to the canvas the event is
|
|
2467
|
-
// tagged with: an instance that is not on it (gone since the render, or on
|
|
2468
|
-
// another canvas altogether) drops the event — firing it anywhere else
|
|
2469
|
-
// would run triggers the person never pressed. With no claim, the canvas's
|
|
2470
|
-
// ACTIVE instance is the origin: on a card deck that is the only one
|
|
2471
|
-
// rendered. A canvas with nothing mounted dispatches unstamped (global).
|
|
2472
|
-
dispatch: (canvas, event) => {
|
|
2473
|
-
const { shell } = cell.live;
|
|
2474
|
-
const state = shell.getState().canvases[canvas];
|
|
2475
|
-
const claimed = event["origin"];
|
|
2476
|
-
if (claimed !== void 0) {
|
|
2477
|
-
if (typeof claimed !== "string" || !(state?.stack ?? []).some((item) => item.id === claimed)) return;
|
|
2478
|
-
shell.dispatch(event);
|
|
2479
|
-
return;
|
|
2480
|
-
}
|
|
2481
|
-
const active = state?.active;
|
|
2482
|
-
shell.dispatch(active === void 0 ? event : { ...event, origin: active.id });
|
|
2483
|
-
},
|
|
2484
|
-
publish: (channel, payload) => cell.live.shell.publish(channel, payload),
|
|
2485
|
-
back: () => cell.live.shell.back(),
|
|
2486
|
-
popTo: (canvas, instance) => cell.live.shell.popTo(canvas, instance),
|
|
2487
|
-
reset: () => void rebuild(cell).catch((err) => console.error("[moss/shells] a reset failed to rebuild", err))
|
|
2488
|
-
});
|
|
2489
|
-
const settle = async (live, waitMs) => {
|
|
2490
|
-
const started = Date.now();
|
|
2491
|
-
let timer;
|
|
2492
|
-
const deadline = new Promise((resolve2) => {
|
|
2493
|
-
timer = setTimeout(() => resolve2(false), waitMs);
|
|
2494
|
-
});
|
|
2495
|
-
const whole = live.seeded.then(() => nova.shellSettled(live.shell, { waitMs: Math.max(0, waitMs - (Date.now() - started)), stopped: () => live.ended }));
|
|
2496
|
-
const settled = await Promise.race([whole, deadline]);
|
|
2497
|
-
clearTimeout(timer);
|
|
2498
|
-
return settled;
|
|
2499
|
-
};
|
|
2500
|
-
const read = (live) => {
|
|
2501
|
-
let frameTree = [];
|
|
2502
|
-
try {
|
|
2503
|
-
frameTree = live.shell.getShellRenderTree();
|
|
2504
|
-
} catch (error) {
|
|
2505
|
-
console.error("[moss/shells] the shell frame failed to render for a snapshot \u2014 serving an empty arrangement:", error);
|
|
2506
|
-
}
|
|
2507
|
-
const trees = {};
|
|
2508
|
-
for (const canvas of shellManifest.canvases) {
|
|
2509
|
-
try {
|
|
2510
|
-
trees[canvas.id] = treeOf(live, canvas.id);
|
|
2511
|
-
} catch (error) {
|
|
2512
|
-
console.error(`[moss/shells] canvas "${canvas.id}" failed to render for a snapshot \u2014 leaving it out:`, error);
|
|
2513
|
-
}
|
|
2514
|
-
}
|
|
2515
|
-
return { frame: frameTree, trees };
|
|
2516
|
-
};
|
|
2517
|
-
const needOf = (live, principal) => {
|
|
2518
|
-
const why = [];
|
|
2519
|
-
const drawnWith = [];
|
|
2520
|
-
const ask = ctx.needOf;
|
|
2521
|
-
if (ask === void 0) return { live: true, why: ["this host was given no way to ask what its actions need"], drawnWith };
|
|
2522
|
-
if (kept && principal !== null) why.push("the app\u2019s shell is kept for whoever is signed in");
|
|
2523
|
-
for (const canvas of Object.values(live.shell.getState().canvases)) {
|
|
2524
|
-
for (const instance of canvas.stack) {
|
|
2525
|
-
const definition = live.shell.getRuntime(instance.id)?.definition;
|
|
2526
|
-
if (definition === void 0) continue;
|
|
2527
|
-
const need = ask(definition);
|
|
2528
|
-
for (const reason of need.why) why.push(`${definition.id}: ${reason}`);
|
|
2529
|
-
for (const read2 of need.drawnWith) drawnWith.push(read2);
|
|
2530
|
-
}
|
|
2531
|
-
}
|
|
2532
|
-
return { live: why.length > 0, why, drawnWith };
|
|
2533
|
-
};
|
|
2534
|
-
const DEFAULT_SNAPSHOT_WAIT_MS = 300;
|
|
2535
|
-
const durableCell = async (token, principal) => {
|
|
2536
|
-
const existing = durable.get(principal);
|
|
2537
|
-
if (existing !== void 0) {
|
|
2538
|
-
existing.token = token;
|
|
2539
|
-
return existing;
|
|
2540
|
-
}
|
|
2541
|
-
const who = await ctx.resolve(principal);
|
|
2542
|
-
const cell = { live: await build(token, principal), token, principal, roles: who.roles, installed: who.installed, hash: who.catalog.hash };
|
|
2543
|
-
durable.set(principal, cell);
|
|
2544
|
-
return cell;
|
|
2545
|
-
};
|
|
2546
|
-
const idleMs = ctx.idleMs ?? DEFAULT_IDLE_MS;
|
|
2547
|
-
const sweep = () => {
|
|
2548
|
-
const now = Date.now();
|
|
2549
|
-
for (const [principal, cell] of [...durable]) {
|
|
2550
|
-
const live = cell.live;
|
|
2551
|
-
if (live.ended) {
|
|
2552
|
-
durable.delete(principal);
|
|
2553
|
-
continue;
|
|
2554
|
-
}
|
|
2555
|
-
if (live.connections.size > 0 || live.idleSince === null) continue;
|
|
2556
|
-
if (now - live.idleSince < idleMs) continue;
|
|
2557
|
-
live.ended = true;
|
|
2558
|
-
live.shell.dispose();
|
|
2559
|
-
durable.delete(principal);
|
|
2560
|
-
}
|
|
2561
|
-
};
|
|
2562
|
-
let sweeper;
|
|
2563
|
-
if (idleMs > 0 && Number.isFinite(idleMs)) {
|
|
2564
|
-
sweeper = setInterval(sweep, Math.min(idleMs, SWEEP_EVERY_MS));
|
|
2565
|
-
sweeper.unref?.();
|
|
2566
|
-
}
|
|
2567
|
-
return {
|
|
2568
|
-
session: async (token, principal, options) => {
|
|
2569
|
-
if (principal === null || !kept) {
|
|
2570
|
-
const who = await ctx.resolve(principal);
|
|
2571
|
-
return sessionOn({ live: await build(token, principal, false, options?.seed, options?.inputs), token, principal, roles: who.roles, installed: who.installed, hash: who.catalog.hash }, true);
|
|
2572
|
-
}
|
|
2573
|
-
return sessionOn(await durableCell(token, principal), false);
|
|
2574
|
-
},
|
|
2575
|
-
snapshot: async (token, principal, options) => {
|
|
2576
|
-
const waitMs = options?.waitMs ?? DEFAULT_SNAPSHOT_WAIT_MS;
|
|
2577
|
-
if (principal !== null && kept) {
|
|
2578
|
-
const cell = await durableCell(token, principal);
|
|
2579
|
-
const settled = await settle(cell.live, waitMs);
|
|
2580
|
-
return { ...read(cell.live), settled, ...needOf(cell.live, principal) };
|
|
2581
|
-
}
|
|
2582
|
-
const seed = crypto$1.randomBytes(9).toString("hex");
|
|
2583
|
-
const live = await build(token, principal, false, seed, options?.inputs);
|
|
2584
|
-
try {
|
|
2585
|
-
const settled = await settle(live, waitMs);
|
|
2586
|
-
return { ...read(live), seed, settled, ...needOf(live, principal) };
|
|
2587
|
-
} finally {
|
|
2588
|
-
live.ended = true;
|
|
2589
|
-
live.shell.dispose();
|
|
2590
|
-
}
|
|
2591
|
-
},
|
|
2592
|
-
// RE-RESOLVED, not re-read off the cell. Adopting happens because something
|
|
2593
|
-
// the derivations were made FROM changed, and the commonest such change is a
|
|
2594
|
-
// tenant installing an integration — so the install list a shell was born with is
|
|
2595
|
-
// exactly the thing that must not be trusted here. Asynchronous and
|
|
2596
|
-
// unawaited: definitions landing a tick late simply register, which is the
|
|
2597
|
-
// same progressive path `seeds` already takes.
|
|
2598
|
-
adopt: () => {
|
|
2599
|
-
void (async () => {
|
|
2600
|
-
for (const [, cell] of durable) {
|
|
2601
|
-
if (cell.live.ended) continue;
|
|
2602
|
-
const who = await ctx.resolve(cell.principal);
|
|
2603
|
-
cell.roles = who.roles;
|
|
2604
|
-
cell.installed = who.installed;
|
|
2605
|
-
cell.hash = who.catalog.hash;
|
|
2606
|
-
const granted = new Set(who.catalog.ids);
|
|
2607
|
-
for (const [id, definition] of Object.entries(ctx.app.actions)) {
|
|
2608
|
-
if (!granted.has(id)) continue;
|
|
2609
|
-
const layout = who.variants.get(id);
|
|
2610
|
-
cell.live.shell.registerAction(layout === void 0 ? definition : { ...definition, layout });
|
|
2611
|
-
}
|
|
2612
|
-
}
|
|
2613
|
-
})().catch((err) => console.error("[moss/shells] adopt failed", err));
|
|
2614
|
-
},
|
|
2615
|
-
deliver: (principal, channel, payload) => {
|
|
2616
|
-
const cell = durable.get(principal);
|
|
2617
|
-
if (cell === void 0 || cell.live.ended) return false;
|
|
2618
|
-
try {
|
|
2619
|
-
cell.live.shell.publish(channel, payload);
|
|
2620
|
-
return true;
|
|
2621
|
-
} catch {
|
|
2622
|
-
return false;
|
|
2623
|
-
}
|
|
2624
|
-
},
|
|
2625
|
-
list: () => {
|
|
2626
|
-
const reports = [];
|
|
2627
|
-
for (const [principal, cell] of durable) {
|
|
2628
|
-
const live = cell.live;
|
|
2629
|
-
if (live.ended) continue;
|
|
2630
|
-
try {
|
|
2631
|
-
const canvases = reflect.snapshotShell(live.shell).canvases.filter((canvas) => canvas.items.length > 0).map((canvas) => ({ id: canvas.id, actions: canvas.items.map((item) => item.definitionId) }));
|
|
2632
|
-
reports.push({ principal, connections: live.connections.size, since: live.since, idleSince: live.idleSince, canvases });
|
|
2633
|
-
} catch {
|
|
2634
|
-
}
|
|
2635
|
-
}
|
|
2636
|
-
return reports;
|
|
2637
|
-
},
|
|
2638
|
-
reset: (principal) => {
|
|
2639
|
-
const cell = durable.get(principal);
|
|
2640
|
-
if (cell === void 0 || cell.live.ended) return false;
|
|
2641
|
-
void rebuild(cell).catch((err) => console.error("[moss/shells] a reset failed to rebuild", err));
|
|
2642
|
-
return true;
|
|
2643
|
-
},
|
|
2644
|
-
stop: () => {
|
|
2645
|
-
if (sweeper !== void 0) clearInterval(sweeper);
|
|
2646
|
-
sweeper = void 0;
|
|
2647
|
-
}
|
|
2648
|
-
};
|
|
2649
|
-
};
|
|
2650
|
-
|
|
2651
|
-
// src/pages.ts
|
|
2652
|
-
var segmentsOf = (path) => path.split("?")[0]?.split("/").filter((part) => part !== "") ?? [];
|
|
2653
|
-
var compile = (name, page) => {
|
|
2654
|
-
if (!page.path.startsWith("/")) throw new Error(`moss: page "${name}" has the path "${page.path}" \u2014 a page's path starts with "/".`);
|
|
2655
|
-
const segments = segmentsOf(page.path).map((part) => part.startsWith(":") ? { param: part.slice(1) } : { literal: part });
|
|
2656
|
-
for (const segment of segments) {
|
|
2657
|
-
if ("param" in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {
|
|
2658
|
-
throw new Error(`moss: page "${name}" names the parameter ":${segment.param}" in "${page.path}" \u2014 a parameter is a plain name.`);
|
|
2659
|
-
}
|
|
2660
|
-
}
|
|
2661
|
-
if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
|
|
2662
|
-
throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
|
|
2663
|
-
}
|
|
2664
|
-
return { name, segments };
|
|
2665
|
-
};
|
|
2666
|
-
var collide = (a, b) => a.segments.length === b.segments.length && a.segments.every((segment, index) => {
|
|
2667
|
-
const other = b.segments[index];
|
|
2668
|
-
return other === void 0 || "param" in segment || "param" in other || segment.literal === other.literal;
|
|
14
|
+
Object.defineProperty(exports, "createServer", {
|
|
15
|
+
enumerable: true,
|
|
16
|
+
get: function () { return chunkR66WUKGC_cjs.createServer; }
|
|
2669
17
|
});
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
return void 0;
|
|
2706
|
-
}
|
|
2707
|
-
};
|
|
2708
|
-
};
|
|
2709
|
-
var fingerprintOf = (request) => {
|
|
2710
|
-
if (request === null || typeof request !== "object" || Array.isArray(request)) return void 0;
|
|
2711
|
-
const fingerprint = Reflect.get(request, "fingerprint");
|
|
2712
|
-
return typeof fingerprint === "string" ? fingerprint : void 0;
|
|
2713
|
-
};
|
|
2714
|
-
var shellNeedOf = (definition, entries) => {
|
|
2715
|
-
const facts = reflect.livenessOf(definition);
|
|
2716
|
-
const why = [];
|
|
2717
|
-
const drawnWith = [];
|
|
2718
|
-
if (facts.gestures) why.push("a person can act on it");
|
|
2719
|
-
if (facts.opaqueLayout) why.push("its layout is kept in the store, so what can be pressed on it is not readable");
|
|
2720
|
-
for (const channel of facts.listens) why.push(`it waits on the channel "${channel}"`);
|
|
2721
|
-
for (const use of facts.endpoints) {
|
|
2722
|
-
if (!use.onOpen && !use.later) continue;
|
|
2723
|
-
if (use.kind === "fn") {
|
|
2724
|
-
why.push(`it calls the function endpoint "${use.name}", which is code`);
|
|
2725
|
-
continue;
|
|
2726
|
-
}
|
|
2727
|
-
const fingerprint = fingerprintOf(use.request);
|
|
2728
|
-
const entry = fingerprint === void 0 ? void 0 : entries.get(fingerprint);
|
|
2729
|
-
if (entry !== void 0 && !("mutation" in entry) && entry.refresh === "reactive") {
|
|
2730
|
-
why.push(`its read "${use.name}" keeps answering (${entry.fingerprint} is reactive)`);
|
|
2731
|
-
continue;
|
|
2732
|
-
}
|
|
2733
|
-
if (fingerprint !== void 0 && entry === void 0) {
|
|
2734
|
-
why.push(`its read "${use.name}" replays "${fingerprint}", which the manifest does not carry \u2014 whether it keeps answering is not readable`);
|
|
2735
|
-
continue;
|
|
2736
|
-
}
|
|
2737
|
-
if (use.onOpen) drawnWith.push(fingerprint ?? use.url ?? use.name);
|
|
2738
|
-
}
|
|
2739
|
-
return { live: why.length > 0, why, drawnWith };
|
|
2740
|
-
};
|
|
2741
|
-
|
|
2742
|
-
// src/identity.ts
|
|
2743
|
-
var DEFAULT_IDENTITY_MAX = 1e4;
|
|
2744
|
-
var DEFAULT_IDENTITY_IDLE_MS = 30 * 60 * 1e3;
|
|
2745
|
-
var SWEEP_EVERY_MS2 = 60 * 1e3;
|
|
2746
|
-
var createIdentityCache = (ctx) => {
|
|
2747
|
-
const max = ctx.max ?? DEFAULT_IDENTITY_MAX;
|
|
2748
|
-
const idleMs = ctx.idleMs ?? DEFAULT_IDENTITY_IDLE_MS;
|
|
2749
|
-
const revalidateMs = ctx.revalidateMs ?? 0;
|
|
2750
|
-
const now = ctx.now ?? Date.now;
|
|
2751
|
-
const held = /* @__PURE__ */ new Map();
|
|
2752
|
-
const tagged = /* @__PURE__ */ new Map();
|
|
2753
|
-
const untag = (principal, record) => {
|
|
2754
|
-
const tag = record.tag;
|
|
2755
|
-
if (tag === void 0) return;
|
|
2756
|
-
const group = tagged.get(tag);
|
|
2757
|
-
if (group === void 0) return;
|
|
2758
|
-
group.delete(principal);
|
|
2759
|
-
if (group.size === 0) tagged.delete(tag);
|
|
2760
|
-
};
|
|
2761
|
-
const forget = (principal) => {
|
|
2762
|
-
const entry = held.get(principal);
|
|
2763
|
-
if (entry === void 0) return false;
|
|
2764
|
-
untag(principal, entry.record);
|
|
2765
|
-
held.delete(principal);
|
|
2766
|
-
return true;
|
|
2767
|
-
};
|
|
2768
|
-
const pending = /* @__PURE__ */ new Map();
|
|
2769
|
-
let resolved = 0;
|
|
2770
|
-
let evicted = 0;
|
|
2771
|
-
let expired = 0;
|
|
2772
|
-
const evictOldest = () => {
|
|
2773
|
-
const oldest = held.keys().next();
|
|
2774
|
-
if (oldest.done === true) return;
|
|
2775
|
-
forget(oldest.value);
|
|
2776
|
-
evicted += 1;
|
|
2777
|
-
};
|
|
2778
|
-
const remember = (principal, record, at) => {
|
|
2779
|
-
forget(principal);
|
|
2780
|
-
while (held.size >= max) evictOldest();
|
|
2781
|
-
held.set(principal, { record, since: at, lastSeen: at });
|
|
2782
|
-
if (record.tag !== void 0) {
|
|
2783
|
-
const group = tagged.get(record.tag) ?? /* @__PURE__ */ new Set();
|
|
2784
|
-
group.add(principal);
|
|
2785
|
-
tagged.set(record.tag, group);
|
|
2786
|
-
}
|
|
2787
|
-
};
|
|
2788
|
-
const get = async (principal) => {
|
|
2789
|
-
const at = now();
|
|
2790
|
-
const hit = held.get(principal);
|
|
2791
|
-
if (hit !== void 0) {
|
|
2792
|
-
const stale = revalidateMs > 0 && at - hit.since >= revalidateMs;
|
|
2793
|
-
if (!stale) {
|
|
2794
|
-
held.delete(principal);
|
|
2795
|
-
hit.lastSeen = at;
|
|
2796
|
-
held.set(principal, hit);
|
|
2797
|
-
return hit.record;
|
|
2798
|
-
}
|
|
2799
|
-
expired += 1;
|
|
2800
|
-
}
|
|
2801
|
-
const inFlight = pending.get(principal);
|
|
2802
|
-
if (inFlight !== void 0) return inFlight;
|
|
2803
|
-
const work = ctx.resolve(principal).then((record) => {
|
|
2804
|
-
resolved += 1;
|
|
2805
|
-
remember(principal, record, now());
|
|
2806
|
-
return record;
|
|
2807
|
-
}).finally(() => {
|
|
2808
|
-
pending.delete(principal);
|
|
2809
|
-
});
|
|
2810
|
-
pending.set(principal, work);
|
|
2811
|
-
return work;
|
|
2812
|
-
};
|
|
2813
|
-
const sweep = idleMs > 0 ? setInterval(() => {
|
|
2814
|
-
const at = now();
|
|
2815
|
-
for (const [principal, entry] of [...held]) {
|
|
2816
|
-
if (at - entry.lastSeen >= idleMs) {
|
|
2817
|
-
forget(principal);
|
|
2818
|
-
evicted += 1;
|
|
2819
|
-
}
|
|
2820
|
-
}
|
|
2821
|
-
}, Math.min(SWEEP_EVERY_MS2, idleMs)) : void 0;
|
|
2822
|
-
sweep?.unref?.();
|
|
2823
|
-
return {
|
|
2824
|
-
get,
|
|
2825
|
-
invalidate: (principal) => {
|
|
2826
|
-
pending.delete(principal);
|
|
2827
|
-
return forget(principal);
|
|
2828
|
-
},
|
|
2829
|
-
invalidateAll: () => {
|
|
2830
|
-
held.clear();
|
|
2831
|
-
tagged.clear();
|
|
2832
|
-
pending.clear();
|
|
2833
|
-
},
|
|
2834
|
-
invalidateTag: (tag) => {
|
|
2835
|
-
const group = tagged.get(tag);
|
|
2836
|
-
if (group === void 0) return [];
|
|
2837
|
-
const principals = [...group];
|
|
2838
|
-
for (const principal of principals) {
|
|
2839
|
-
pending.delete(principal);
|
|
2840
|
-
forget(principal);
|
|
2841
|
-
}
|
|
2842
|
-
return principals;
|
|
2843
|
-
},
|
|
2844
|
-
list: () => [...held].map(([principal, entry]) => ({ principal, since: entry.since, lastSeen: entry.lastSeen })),
|
|
2845
|
-
meter: () => ({ size: held.size, max, resolved, evicted, expired }),
|
|
2846
|
-
stop: () => {
|
|
2847
|
-
if (sweep !== void 0) clearInterval(sweep);
|
|
2848
|
-
}
|
|
2849
|
-
};
|
|
2850
|
-
};
|
|
2851
|
-
|
|
2852
|
-
// src/server.ts
|
|
2853
|
-
var secretsEqual = (a, b) => crypto$1.timingSafeEqual(crypto$1.createHash("sha256").update(a).digest(), crypto$1.createHash("sha256").update(b).digest());
|
|
2854
|
-
var guardOperator = (operator, opts) => {
|
|
2855
|
-
const gate = opts.gate;
|
|
2856
|
-
if (gate !== void 0) operator.use("*", (c, next) => Promise.resolve(gate(c, next)));
|
|
2857
|
-
operator.use("*", async (c, next) => {
|
|
2858
|
-
const presented = c.req.header("x-operator-key") ?? "";
|
|
2859
|
-
if (opts.key === "" || !secretsEqual(presented, opts.key)) return c.json({ message: "Not found." }, 404);
|
|
2860
|
-
return next();
|
|
2861
|
-
});
|
|
2862
|
-
};
|
|
2863
|
-
var vexRecordToSpan = (rec) => ({
|
|
2864
|
-
name: "vex.execute",
|
|
2865
|
-
startUnixNano: rec.startUnixNano,
|
|
2866
|
-
endUnixNano: rec.endUnixNano,
|
|
2867
|
-
status: rec.status,
|
|
2868
|
-
attributes: {
|
|
2869
|
-
op: rec.kind,
|
|
2870
|
-
hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
|
|
2871
|
-
...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
|
|
2872
|
-
...rec.reach !== void 0 ? { reach: rec.reach } : {},
|
|
2873
|
-
...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
|
|
2874
|
-
...rec.rows !== void 0 ? { rows: rec.rows } : {}
|
|
2875
|
-
}
|
|
18
|
+
Object.defineProperty(exports, "defineApp", {
|
|
19
|
+
enumerable: true,
|
|
20
|
+
get: function () { return chunkR66WUKGC_cjs.defineApp; }
|
|
21
|
+
});
|
|
22
|
+
Object.defineProperty(exports, "exportDocuments", {
|
|
23
|
+
enumerable: true,
|
|
24
|
+
get: function () { return chunkR66WUKGC_cjs.exportDocuments; }
|
|
25
|
+
});
|
|
26
|
+
Object.defineProperty(exports, "migrateTables", {
|
|
27
|
+
enumerable: true,
|
|
28
|
+
get: function () { return chunkR66WUKGC_cjs.migrateTables; }
|
|
29
|
+
});
|
|
30
|
+
Object.defineProperty(exports, "mintDevToken", {
|
|
31
|
+
enumerable: true,
|
|
32
|
+
get: function () { return chunkR66WUKGC_cjs.mintDevToken; }
|
|
33
|
+
});
|
|
34
|
+
Object.defineProperty(exports, "mintSession", {
|
|
35
|
+
enumerable: true,
|
|
36
|
+
get: function () { return chunkR66WUKGC_cjs.mintSession; }
|
|
37
|
+
});
|
|
38
|
+
Object.defineProperty(exports, "renderDocument", {
|
|
39
|
+
enumerable: true,
|
|
40
|
+
get: function () { return chunkR66WUKGC_cjs.renderDocument; }
|
|
41
|
+
});
|
|
42
|
+
Object.defineProperty(exports, "revokeAllFor", {
|
|
43
|
+
enumerable: true,
|
|
44
|
+
get: function () { return chunkR66WUKGC_cjs.revokeAllFor; }
|
|
45
|
+
});
|
|
46
|
+
Object.defineProperty(exports, "sessionCookies", {
|
|
47
|
+
enumerable: true,
|
|
48
|
+
get: function () { return chunkR66WUKGC_cjs.sessionCookies; }
|
|
49
|
+
});
|
|
50
|
+
Object.defineProperty(exports, "verifyApp", {
|
|
51
|
+
enumerable: true,
|
|
52
|
+
get: function () { return chunkR66WUKGC_cjs.verifyApp; }
|
|
2876
53
|
});
|
|
2877
|
-
var createServer = async (app, runtime) => {
|
|
2878
|
-
const session = sessionVerifierOf(runtime);
|
|
2879
|
-
const emit = emitterOf(runtime.telemetry);
|
|
2880
|
-
const vexOnExecute = emit === void 0 ? void 0 : (rec) => emit(vexRecordToSpan(rec));
|
|
2881
|
-
await postgres.migrate(runtime.pool, tableSequencesOf(runtime), { mode: runtime.migrations ?? "apply" });
|
|
2882
|
-
const grammars = await createGrammarUpgrader(app);
|
|
2883
|
-
await postgres.upgradeStore(runtime.pool, INTEGRATION_ACTIONS_STORE, grammars);
|
|
2884
|
-
const data = await createDataLayer(runtime, app.entries ?? []);
|
|
2885
|
-
const report = charter.verifyCharter(
|
|
2886
|
-
app.charter,
|
|
2887
|
-
{ actions: Object.keys(app.actions), data: data.grants, layouts: Object.keys(app.layouts ?? {}) },
|
|
2888
|
-
wearableOf(app),
|
|
2889
|
-
auditClosure(app.actions, app.layouts)
|
|
2890
|
-
);
|
|
2891
|
-
if (report.errors.length > 0) {
|
|
2892
|
-
throw new Error(`Charter is incoherent \u2014 refusing to serve:
|
|
2893
|
-
${report.errors.map((e) => ` ${e.rule}: ${e.detail}`).join("\n")}`);
|
|
2894
|
-
}
|
|
2895
|
-
let verifiedReport = report;
|
|
2896
|
-
for (const cycle of reflect.chainCycles(app.actions)) {
|
|
2897
|
-
console.error(`[moss] a chain of steps that never ends: ${cycle.path} \u2014 nova stops it at its budget when it runs (RUNAWAY_CHAIN)`);
|
|
2898
|
-
}
|
|
2899
|
-
const profiles = new Set(vex.scopeProfiles(app.behaviors ?? {}));
|
|
2900
|
-
const badReach = (app.entries ?? []).filter((e) => typeof e.reach === "string").filter((e) => !profiles.has(e.reach)).map((e) => ` ${e.fingerprint} declares reach "${e.reach}"`);
|
|
2901
|
-
if (badReach.length > 0) {
|
|
2902
|
-
throw new Error(
|
|
2903
|
-
`Entries declare a reach no table offers \u2014 refusing to serve:
|
|
2904
|
-
${badReach.join("\n")}
|
|
2905
|
-
known profiles: ${[...profiles].join(", ") || "(none)"}`
|
|
2906
|
-
);
|
|
2907
|
-
}
|
|
2908
|
-
const variantErrors = verifyVariants(app);
|
|
2909
|
-
if (variantErrors.length > 0) {
|
|
2910
|
-
throw new Error(`Layout variants are incoherent \u2014 refusing to serve:
|
|
2911
|
-
${variantErrors.map((e) => ` ${e}`).join("\n")}`);
|
|
2912
|
-
}
|
|
2913
|
-
let generation;
|
|
2914
|
-
const executeAs = async (role, fingerprint, context, scope = {}) => {
|
|
2915
|
-
const roles = [role];
|
|
2916
|
-
const outcome = await vex.handleQuery(
|
|
2917
|
-
{
|
|
2918
|
-
engine: data.engine,
|
|
2919
|
-
locked: true,
|
|
2920
|
-
scopePolicy: resolvePolicyForRoles(app, data.grants, roles),
|
|
2921
|
-
policyForReach: (reach) => resolvePolicyAtReachForRoles(app, data.grants, roles, reach),
|
|
2922
|
-
// Mutation replay under the same role policy — write gates and scope
|
|
2923
|
-
// pins apply exactly as they would for a person.
|
|
2924
|
-
mutations: { client: runtime.db, policy: resolvePolicyForRoles(app, data.grants, roles) },
|
|
2925
|
-
// Machinery is observed too: a seeded entry run as a charter role is a
|
|
2926
|
-
// vex execution, and its scope carries no principal, so it reports as
|
|
2927
|
-
// `hasPrincipal: false` — which is the truth about it.
|
|
2928
|
-
...vexOnExecute !== void 0 ? { onExecute: vexOnExecute } : {}
|
|
2929
|
-
},
|
|
2930
|
-
{ fingerprint, context },
|
|
2931
|
-
scope
|
|
2932
|
-
);
|
|
2933
|
-
if (outcome.status !== 200) {
|
|
2934
|
-
console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
|
|
2935
|
-
return void 0;
|
|
2936
|
-
}
|
|
2937
|
-
const body = outcome.body;
|
|
2938
|
-
return "result" in body ? body["result"] : void 0;
|
|
2939
|
-
};
|
|
2940
|
-
const identityEntry = async (roles, fingerprint, scope) => executeAs(roles[0] ?? "", fingerprint, {}, scope);
|
|
2941
|
-
const composedResolve = async (principal) => {
|
|
2942
|
-
const config = app.identity;
|
|
2943
|
-
if (config === void 0) throw new Error("moss: identity resolved with no seam");
|
|
2944
|
-
const reader = config.as === void 0 ? void 0 : [config.as];
|
|
2945
|
-
const read = async (fingerprint, scope) => {
|
|
2946
|
-
if (reader === void 0) throw new Error("moss: identity.read needs identity.as \u2014 name the charter role the reader executes as");
|
|
2947
|
-
return identityEntry(reader, fingerprint, scope);
|
|
2948
|
-
};
|
|
2949
|
-
return config.resolve(principal, read);
|
|
2950
|
-
};
|
|
2951
|
-
const identities = app.identity !== void 0 ? createIdentityCache({
|
|
2952
|
-
resolve: composedResolve,
|
|
2953
|
-
...runtime.identityMax !== void 0 ? { max: runtime.identityMax } : {},
|
|
2954
|
-
...runtime.identityIdleMs !== void 0 ? { idleMs: runtime.identityIdleMs } : {},
|
|
2955
|
-
revalidateMs: runtime.sessionRevalidateMs ?? DEFAULT_REVALIDATE_MS
|
|
2956
|
-
}) : void 0;
|
|
2957
|
-
const keys = /* @__PURE__ */ new WeakMap();
|
|
2958
|
-
const keyOf2 = (record) => {
|
|
2959
|
-
const hit = keys.get(record);
|
|
2960
|
-
if (hit !== void 0) return hit;
|
|
2961
|
-
const key = memoKey(record.roles, record.installed);
|
|
2962
|
-
keys.set(record, key);
|
|
2963
|
-
return key;
|
|
2964
|
-
};
|
|
2965
|
-
const composeScope = (principal, resolved) => ({
|
|
2966
|
-
userId: principal ?? "anonymous",
|
|
2967
|
-
...resolved.scope,
|
|
2968
|
-
...app.scope?.(principal, resolved.record) ?? {}
|
|
2969
|
-
});
|
|
2970
|
-
const scopeValuesFor = async (principal) => composeScope(principal, await resolveIdentity(principal));
|
|
2971
|
-
const resolveIdentity = async (principal) => {
|
|
2972
|
-
if (identities !== void 0 && principal !== null) {
|
|
2973
|
-
const record = await identities.get(principal);
|
|
2974
|
-
return { roles: record.roles, scope: record.scope, installed: record.installed, key: keyOf2(record), record };
|
|
2975
|
-
}
|
|
2976
|
-
return fromSeams(principal);
|
|
2977
|
-
};
|
|
2978
|
-
function fromSeams(principal) {
|
|
2979
|
-
const roles = resolveRoles(app, principal);
|
|
2980
|
-
const installed = void 0;
|
|
2981
|
-
return { roles, scope: {}, installed, key: memoKey(roles, installed) };
|
|
2982
|
-
}
|
|
2983
|
-
const policies = /* @__PURE__ */ new Map();
|
|
2984
|
-
const policy = (resolved) => {
|
|
2985
|
-
const hit = policies.get(resolved.key);
|
|
2986
|
-
if (hit !== void 0) return hit;
|
|
2987
|
-
const compiled = resolvePolicyForRoles(app, data.grants, resolved.roles);
|
|
2988
|
-
policies.set(resolved.key, compiled);
|
|
2989
|
-
return compiled;
|
|
2990
|
-
};
|
|
2991
|
-
const reachPolicies = /* @__PURE__ */ new Map();
|
|
2992
|
-
const policyAtReach = (resolved, reach) => {
|
|
2993
|
-
const key = `${resolved.key}\0${reach}`;
|
|
2994
|
-
const hit = reachPolicies.get(key);
|
|
2995
|
-
if (hit !== void 0) return hit;
|
|
2996
|
-
const compiled = resolvePolicyAtReachForRoles(app, data.grants, resolved.roles, reach);
|
|
2997
|
-
reachPolicies.set(key, compiled);
|
|
2998
|
-
return compiled;
|
|
2999
|
-
};
|
|
3000
|
-
const staticActions = { ...app.actions };
|
|
3001
|
-
const reloadIntegrations = async () => {
|
|
3002
|
-
const fromRows = await loadIntegrationActions(runtime.pool, grammars);
|
|
3003
|
-
app.actions = { ...staticActions, ...fromRows };
|
|
3004
|
-
refresh();
|
|
3005
|
-
};
|
|
3006
|
-
const catalogs = /* @__PURE__ */ new Map();
|
|
3007
|
-
const catalog = (resolved) => {
|
|
3008
|
-
const hit = catalogs.get(resolved.key);
|
|
3009
|
-
if (hit !== void 0) return hit;
|
|
3010
|
-
const built = resolveCatalogForRoles(app, resolved.roles, resolved.installed);
|
|
3011
|
-
catalogs.set(resolved.key, built);
|
|
3012
|
-
return built;
|
|
3013
|
-
};
|
|
3014
|
-
const variantBindings = /* @__PURE__ */ new Map();
|
|
3015
|
-
const variants = (resolved) => {
|
|
3016
|
-
const hit = variantBindings.get(resolved.key);
|
|
3017
|
-
if (hit !== void 0) return hit;
|
|
3018
|
-
const built = resolveVariantsForRoles(app, resolved.roles);
|
|
3019
|
-
variantBindings.set(resolved.key, built);
|
|
3020
|
-
return built;
|
|
3021
|
-
};
|
|
3022
|
-
const asRoles = (roles, installed) => ({ roles, scope: {}, installed, key: memoKey(roles, installed) });
|
|
3023
|
-
const assertions = createAssertionSigner(runtime.signingSeed);
|
|
3024
|
-
const callIntegration = callIntegrationWith({
|
|
3025
|
-
pool: runtime.pool,
|
|
3026
|
-
installedFor: async (principal) => (await resolveIdentity(principal)).installed,
|
|
3027
|
-
scopeValuesFor,
|
|
3028
|
-
mint: assertions.mint,
|
|
3029
|
-
...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {}
|
|
3030
|
-
});
|
|
3031
|
-
const server = new hono.Hono();
|
|
3032
|
-
server.use("*", async (c, next) => {
|
|
3033
|
-
const header = c.req.header("Authorization");
|
|
3034
|
-
if (header === void 0) {
|
|
3035
|
-
c.set("principal", null);
|
|
3036
|
-
c.set("resolved", await resolveIdentity(null));
|
|
3037
|
-
return next();
|
|
3038
|
-
}
|
|
3039
|
-
const token = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : header;
|
|
3040
|
-
if (token.startsWith("ik_")) {
|
|
3041
|
-
const integration = await integrationByKey(runtime.pool, token);
|
|
3042
|
-
if (integration === void 0) {
|
|
3043
|
-
return c.json({ error: "invalid_key", message: "The integration key did not resolve." }, 401);
|
|
3044
|
-
}
|
|
3045
|
-
const actor = await app.integrationActor?.(integration, c.req.header("x-nisc-acts-for") ?? "") ?? null;
|
|
3046
|
-
if (actor === null) {
|
|
3047
|
-
return c.json({ error: "no_actor", message: "This integration has no actor there." }, 403);
|
|
3048
|
-
}
|
|
3049
|
-
const resolved = await resolveIdentity(actor);
|
|
3050
|
-
if (resolved.roles.length === 1 && resolved.roles[0] === "public") {
|
|
3051
|
-
return c.json({ error: "no_actor", message: "This integration has no actor there." }, 403);
|
|
3052
|
-
}
|
|
3053
|
-
c.set("principal", actor);
|
|
3054
|
-
c.set("resolved", resolved);
|
|
3055
|
-
return next();
|
|
3056
|
-
}
|
|
3057
|
-
const principal = await session(token);
|
|
3058
|
-
if (principal === null) {
|
|
3059
|
-
return c.json({ error: "invalid_token", message: "The session token did not resolve to a principal." }, 401);
|
|
3060
|
-
}
|
|
3061
|
-
c.set("principal", principal);
|
|
3062
|
-
try {
|
|
3063
|
-
c.set("resolved", await resolveIdentity(principal));
|
|
3064
|
-
} catch {
|
|
3065
|
-
return c.json({ error: "no_identity", message: "The session token did not resolve to a principal." }, 401);
|
|
3066
|
-
}
|
|
3067
|
-
return next();
|
|
3068
|
-
});
|
|
3069
|
-
server.get("/catalog", (c) => {
|
|
3070
|
-
const principal = c.get("principal");
|
|
3071
|
-
const { ids, hash } = catalog(c.get("resolved"));
|
|
3072
|
-
return c.json({ principal, actions: ids, hash });
|
|
3073
|
-
});
|
|
3074
|
-
const chainContext = new async_hooks.AsyncLocalStorage();
|
|
3075
|
-
server.use("/api/*", async (c, next) => {
|
|
3076
|
-
const cause = c.req.header("x-tide-cause");
|
|
3077
|
-
const depth = Number(c.req.header("x-tide-depth"));
|
|
3078
|
-
if (cause === void 0 || cause === "" || !Number.isInteger(depth) || depth < 0) return next();
|
|
3079
|
-
return chainContext.run({ cause, depth }, () => next());
|
|
3080
|
-
});
|
|
3081
|
-
const mount = (path, entities) => {
|
|
3082
|
-
server.route(
|
|
3083
|
-
path,
|
|
3084
|
-
hono$1.vex({
|
|
3085
|
-
engine: data.engine,
|
|
3086
|
-
...entities !== void 0 ? { entities: [...entities] } : {},
|
|
3087
|
-
locked: true,
|
|
3088
|
-
// `userId` is always the principal; the app's `scope` hook contributes
|
|
3089
|
-
// whatever else a principal is (a tenant, an org). Merged server-side,
|
|
3090
|
-
// unforgeable by the request — a `to:` in a behavior resolves here.
|
|
3091
|
-
// The session's stable values, then the clock's. `scope` is applied
|
|
3092
|
-
// last and per request so a value derived from today's date cannot be
|
|
3093
|
-
// held for the life of a session that began yesterday.
|
|
3094
|
-
getScope: (c) => composeScope(c.get("principal"), c.get("resolved")),
|
|
3095
|
-
getPolicy: (c) => policy(c.get("resolved")),
|
|
3096
|
-
// An entry that names a reach is served at it, not at the caller's own.
|
|
3097
|
-
getPolicyForReach: (c, reach) => policyAtReach(c.get("resolved"), reach),
|
|
3098
|
-
// One span per read and write on this surface — the busiest emission
|
|
3099
|
-
// point, and the reason vex has an observer at all.
|
|
3100
|
-
...vexOnExecute !== void 0 ? { onExecute: vexOnExecute } : {},
|
|
3101
|
-
mutations: {
|
|
3102
|
-
client: runtime.db,
|
|
3103
|
-
// Vex's write observer, fired once per committed mutation with
|
|
3104
|
-
// per-statement writes. Two consumers, in order of record:
|
|
3105
|
-
//
|
|
3106
|
-
// 1. The FACT lane — rows ride here and into tide's ledger only,
|
|
3107
|
-
// stamped with the identity the app derives from the write's
|
|
3108
|
-
// own scope. That stamp is the tenancy fence (see mintWrites).
|
|
3109
|
-
// 2. The REACTIONS — row-less by design and routed by declared
|
|
3110
|
-
// interest: table, op, count, scope, with `deliver` to push
|
|
3111
|
-
// onto living shells. A receiver that wants data re-reads it
|
|
3112
|
-
// under its own policy.
|
|
3113
|
-
//
|
|
3114
|
-
// Late-bound throughout: shells and tide stand up after the mounts.
|
|
3115
|
-
...app.reactions !== void 0 || app.facts !== void 0 ? {
|
|
3116
|
-
onWrite: (event) => {
|
|
3117
|
-
const tide = app.facts?.tide();
|
|
3118
|
-
const as = tide !== void 0 ? app.facts?.identity(event.scope) : void 0;
|
|
3119
|
-
if (tide !== void 0 && as !== void 0) {
|
|
3120
|
-
const hints = chainContext.getStore();
|
|
3121
|
-
const chain = hints === void 0 ? void 0 : app.facts?.chain?.(event.scope, hints);
|
|
3122
|
-
mintWrites(tide, event, as, Date.now(), chain).catch((err) => console.error("[moss:facts]", err));
|
|
3123
|
-
}
|
|
3124
|
-
const tools = {
|
|
3125
|
-
// Local delivery carries the payload — an optimisation for a
|
|
3126
|
-
// shell resident in THIS process. The cross-process nudge is
|
|
3127
|
-
// payload-less: a shell in another process re-reads under its
|
|
3128
|
-
// own policy, which is the row-less doctrine and the only safe
|
|
3129
|
-
// thing to send off-box. No fabric → the publish is a no-op and
|
|
3130
|
-
// this is exactly today's local deliver.
|
|
3131
|
-
deliver: (principal, channel, payload) => {
|
|
3132
|
-
const local = server.shells?.deliver(principal, channel, payload) ?? false;
|
|
3133
|
-
publishFabric({ kind: "nudge", principal, channel });
|
|
3134
|
-
return local;
|
|
3135
|
-
}
|
|
3136
|
-
};
|
|
3137
|
-
for (const write of event.writes) {
|
|
3138
|
-
if (write.rows.length === 0) continue;
|
|
3139
|
-
for (const reaction of app.reactions ?? []) {
|
|
3140
|
-
if (reaction.table !== write.table || reaction.op !== void 0 && reaction.op !== write.op) continue;
|
|
3141
|
-
try {
|
|
3142
|
-
reaction.run({ fingerprint: event.fingerprint, table: write.table, op: write.op, count: write.rows.length, scope: event.scope }, tools);
|
|
3143
|
-
} catch (err) {
|
|
3144
|
-
console.error("[moss:reactions]", err);
|
|
3145
|
-
}
|
|
3146
|
-
}
|
|
3147
|
-
}
|
|
3148
|
-
}
|
|
3149
|
-
} : {}
|
|
3150
|
-
}
|
|
3151
|
-
})
|
|
3152
|
-
);
|
|
3153
|
-
};
|
|
3154
|
-
mount("/api/vex");
|
|
3155
|
-
for (const [name, resource] of Object.entries(app.resources ?? {})) {
|
|
3156
|
-
mount(`/api/${name}/vex`, "entities" in resource ? resource.entities : resource);
|
|
3157
|
-
}
|
|
3158
|
-
const contractFingerprints = async (principal) => {
|
|
3159
|
-
const discovery = await data.engine.cache.entries?.();
|
|
3160
|
-
if (discovery === void 0) return [];
|
|
3161
|
-
const compiled = policy(await resolveIdentity(principal));
|
|
3162
|
-
return discovery.filter(({ entry }) => entry.kind === "ok" || entry.kind === "mutation").map(({ key }) => key).filter((key) => !key.startsWith("neg:")).sort().filter(() => compiled !== void 0);
|
|
3163
|
-
};
|
|
3164
|
-
server.get("/api/integrations/contract", async (c) => {
|
|
3165
|
-
const id = c.req.query("id") ?? "<your id>";
|
|
3166
|
-
const contract = buildContract(app, id);
|
|
3167
|
-
const fingerprints = await contractFingerprints(c.get("principal"));
|
|
3168
|
-
if (c.req.query("format") === "md") {
|
|
3169
|
-
return new Response(contractAsMarkdown(contract, fingerprints), {
|
|
3170
|
-
headers: { "content-type": "text/markdown; charset=utf-8" }
|
|
3171
|
-
});
|
|
3172
|
-
}
|
|
3173
|
-
return c.json({ ...contract, fingerprints, verifyKey: assertions.verifyKey });
|
|
3174
|
-
});
|
|
3175
|
-
server.get("/api/integrations/verify-key", (c) => c.json({ alg: "ed25519", key: assertions.verifyKey }));
|
|
3176
|
-
const operator = new hono.Hono();
|
|
3177
|
-
guardOperator(operator, { key: runtime.operatorKey ?? "", gate: runtime.operatorGate });
|
|
3178
|
-
operator.get("/integrations", async (c) => c.json({ integrations: await listIntegrations(runtime.pool) }));
|
|
3179
|
-
operator.post("/integrations", async (c) => {
|
|
3180
|
-
const body = await c.req.json().catch(() => ({}));
|
|
3181
|
-
const id = typeof body.id === "string" ? body.id : "";
|
|
3182
|
-
const url = typeof body.url === "string" ? body.url : "";
|
|
3183
|
-
if (id === "" || url === "") return c.json({ message: "Give an id and a url." }, 400);
|
|
3184
|
-
let payload;
|
|
3185
|
-
try {
|
|
3186
|
-
const response = await fetch(`${url.replace(/\/$/, "")}/bundle`);
|
|
3187
|
-
if (!response.ok) throw new Error(String(response.status));
|
|
3188
|
-
payload = await response.json();
|
|
3189
|
-
} catch {
|
|
3190
|
-
await runtime.pool.query(
|
|
3191
|
-
`INSERT INTO integrations (id, url, last_error) VALUES ($1, $2, $3)
|
|
3192
|
-
ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url, last_error = EXCLUDED.last_error`,
|
|
3193
|
-
[id, url, "the service did not answer with a bundle"]
|
|
3194
|
-
);
|
|
3195
|
-
return c.json({ message: "The integration did not answer with a bundle." }, 502);
|
|
3196
|
-
}
|
|
3197
|
-
const fingerprints = new Set(await data.engine.cache.keys?.() ?? []);
|
|
3198
|
-
const result = runIntake(payload, intakeContextOf(app, id, fingerprints, grammars));
|
|
3199
|
-
if (!result.ok) {
|
|
3200
|
-
await runtime.pool.query(
|
|
3201
|
-
`INSERT INTO integrations (id, url, last_error) VALUES ($1, $2, $3)
|
|
3202
|
-
ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url, last_error = EXCLUDED.last_error`,
|
|
3203
|
-
[id, url, result.reasons.join("; ")]
|
|
3204
|
-
);
|
|
3205
|
-
return c.json({ message: "Refused.", reasons: result.reasons }, 422);
|
|
3206
|
-
}
|
|
3207
|
-
const press = await copyPress(result.bundle, id, url, app.storePress);
|
|
3208
|
-
if (!press.ok) {
|
|
3209
|
-
await runtime.pool.query(
|
|
3210
|
-
`INSERT INTO integrations (id, url, last_error) VALUES ($1, $2, $3)
|
|
3211
|
-
ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url, last_error = EXCLUDED.last_error`,
|
|
3212
|
-
[id, url, press.reasons.join("; ")]
|
|
3213
|
-
);
|
|
3214
|
-
return c.json({ message: "Refused.", reasons: press.reasons }, 422);
|
|
3215
|
-
}
|
|
3216
|
-
const existing = await runtime.pool.query("SELECT status, key_hash FROM integrations WHERE id = $1", [id]);
|
|
3217
|
-
const existingRow = existing.rows[0];
|
|
3218
|
-
const wasApproved = String(existingRow?.status ?? "") === "approved";
|
|
3219
|
-
const holdsKey = typeof existingRow?.key_hash === "string" && existingRow.key_hash !== "";
|
|
3220
|
-
if (wasApproved) {
|
|
3221
|
-
const restore = { ...app.actions };
|
|
3222
|
-
app.actions = { ...app.actions, ...result.bundle.actions };
|
|
3223
|
-
try {
|
|
3224
|
-
refresh();
|
|
3225
|
-
} catch (err) {
|
|
3226
|
-
app.actions = restore;
|
|
3227
|
-
refresh();
|
|
3228
|
-
return c.json({ message: "Refused \u2014 the app would not serve this.", reasons: [String(err)] }, 422);
|
|
3229
|
-
}
|
|
3230
|
-
}
|
|
3231
|
-
await runtime.pool.query(
|
|
3232
|
-
`INSERT INTO integrations (id, url, title, tagline, description, adds, settings_action, requested_actions, requested_data, reach, frames, phrasebook, story, highlights, press, offers, needs, capabilities, configuration, documents, assistants, last_import_at, last_error)
|
|
3233
|
-
VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10::jsonb, $11::jsonb, $12::jsonb, $13::jsonb, $14::jsonb, $15::jsonb, $16::jsonb, $17::jsonb, $18::jsonb, $19::jsonb, $20::jsonb, $21::jsonb, now(), NULL)
|
|
3234
|
-
ON CONFLICT (id) DO UPDATE SET url = EXCLUDED.url,
|
|
3235
|
-
title = EXCLUDED.title, tagline = EXCLUDED.tagline, description = EXCLUDED.description,
|
|
3236
|
-
adds = EXCLUDED.adds, settings_action = EXCLUDED.settings_action,
|
|
3237
|
-
requested_actions = EXCLUDED.requested_actions,
|
|
3238
|
-
requested_data = EXCLUDED.requested_data,
|
|
3239
|
-
reach = EXCLUDED.reach, frames = EXCLUDED.frames,
|
|
3240
|
-
phrasebook = EXCLUDED.phrasebook,
|
|
3241
|
-
story = EXCLUDED.story, highlights = EXCLUDED.highlights, press = EXCLUDED.press,
|
|
3242
|
-
offers = EXCLUDED.offers, needs = EXCLUDED.needs,
|
|
3243
|
-
capabilities = EXCLUDED.capabilities,
|
|
3244
|
-
configuration = EXCLUDED.configuration,
|
|
3245
|
-
documents = EXCLUDED.documents,
|
|
3246
|
-
assistants = EXCLUDED.assistants,
|
|
3247
|
-
last_import_at = now(), last_error = NULL`,
|
|
3248
|
-
[
|
|
3249
|
-
id,
|
|
3250
|
-
url,
|
|
3251
|
-
result.bundle.meta.title,
|
|
3252
|
-
result.bundle.meta.tagline,
|
|
3253
|
-
result.bundle.meta.description,
|
|
3254
|
-
describePlacements(result.bundle, app.placementNames ?? {}),
|
|
3255
|
-
result.bundle.settings,
|
|
3256
|
-
JSON.stringify(result.bundle.grants.actions),
|
|
3257
|
-
JSON.stringify(result.bundle.grants.data),
|
|
3258
|
-
// Re-derived on every import, so a screen an integration DROPPED takes its
|
|
3259
|
-
// endpoint's reach with it. An allow-list that only ever grows is a
|
|
3260
|
-
// list of everything the integration has ever been able to do.
|
|
3261
|
-
JSON.stringify(reachOf(result.bundle, id)),
|
|
3262
|
-
JSON.stringify(result.bundle.frames),
|
|
3263
|
-
// The integration's own words, in the languages it speaks — stored beside
|
|
3264
|
-
// its actions so the app's language pass can reach them, and
|
|
3265
|
-
// re-imported whole like everything else about a bundle.
|
|
3266
|
-
JSON.stringify(result.bundle.phrasebook),
|
|
3267
|
-
JSON.stringify(result.bundle.meta.story),
|
|
3268
|
-
JSON.stringify(result.bundle.meta.highlights),
|
|
3269
|
-
// The urls the HOST answered with at copyPress — the declared paths
|
|
3270
|
-
// died the moment the bytes crossed.
|
|
3271
|
-
JSON.stringify(press.urls),
|
|
3272
|
-
// What it tells and hears — carried, never read here; the host's bus
|
|
3273
|
-
// is the consumer.
|
|
3274
|
-
JSON.stringify(result.bundle.offers),
|
|
3275
|
-
JSON.stringify(result.bundle.needs),
|
|
3276
|
-
// The verbs it gates on — carried the same way; the host's role editor
|
|
3277
|
-
// is the consumer.
|
|
3278
|
-
JSON.stringify(result.bundle.capabilities),
|
|
3279
|
-
// What a builder may set — carried the same way; the host's per-product
|
|
3280
|
-
// settings form is the consumer, and the delivery is the assertion's.
|
|
3281
|
-
JSON.stringify(result.bundle.configuration),
|
|
3282
|
-
// What an add-on lets a person edit — carried the same way; the host's
|
|
3283
|
-
// editor is the consumer.
|
|
3284
|
-
JSON.stringify(result.bundle.documents),
|
|
3285
|
-
// What an add-on's assistant knows — carried the same way; the host's
|
|
3286
|
-
// assistant is the consumer.
|
|
3287
|
-
JSON.stringify(result.bundle.assistants)
|
|
3288
|
-
]
|
|
3289
|
-
);
|
|
3290
|
-
await runtime.pool.query("DELETE FROM integration_actions WHERE integration_id = $1", [id]);
|
|
3291
|
-
for (const [actionId, definition] of Object.entries(result.bundle.actions)) {
|
|
3292
|
-
const binding = result.bundle.attachments[actionId];
|
|
3293
|
-
const attachTo = binding === void 0 ? "" : typeof binding === "string" ? binding : binding.to;
|
|
3294
|
-
const preview = binding === void 0 || typeof binding === "string" ? "" : binding.preview;
|
|
3295
|
-
await runtime.pool.query(
|
|
3296
|
-
// Stamped current: runIntake upgraded every definition to this code's grammars.
|
|
3297
|
-
"INSERT INTO integration_actions (integration_id, action_id, definition, attach_to, preview, place_in, grammar) VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7::jsonb)",
|
|
3298
|
-
[id, actionId, JSON.stringify(definition), attachTo, preview, result.bundle.placements[actionId] ?? "", JSON.stringify(grammars.stamp)]
|
|
3299
|
-
);
|
|
3300
|
-
}
|
|
3301
|
-
const key = holdsKey ? void 0 : mintIntegrationKey();
|
|
3302
|
-
if (key !== void 0) {
|
|
3303
|
-
await runtime.pool.query("UPDATE integrations SET key_hash = $2 WHERE id = $1", [id, hashIntegrationKey(key)]);
|
|
3304
|
-
}
|
|
3305
|
-
await reloadIntegrations();
|
|
3306
|
-
const status = wasApproved ? "approved" : "pending";
|
|
3307
|
-
return c.json({ id, status, actions: Object.keys(result.bundle.actions).length, ...key === void 0 ? {} : { key } });
|
|
3308
|
-
});
|
|
3309
|
-
operator.post("/integrations/:id/approve", async (c) => {
|
|
3310
|
-
const id = c.req.param("id");
|
|
3311
|
-
const row = await runtime.pool.query("SELECT requested_data FROM integrations WHERE id = $1", [id]);
|
|
3312
|
-
if (row.rows[0] === void 0) return c.json({ message: "No such integration." }, 404);
|
|
3313
|
-
const requested = row.rows[0].requested_data ?? [];
|
|
3314
|
-
await runtime.pool.query(
|
|
3315
|
-
"UPDATE integrations SET status = 'approved', approved_data = $2::jsonb WHERE id = $1",
|
|
3316
|
-
[id, JSON.stringify(requested)]
|
|
3317
|
-
);
|
|
3318
|
-
try {
|
|
3319
|
-
await reloadIntegrations();
|
|
3320
|
-
} catch (err) {
|
|
3321
|
-
await runtime.pool.query("UPDATE integrations SET status = 'pending', last_error = $2 WHERE id = $1", [id, String(err)]);
|
|
3322
|
-
await reloadIntegrations();
|
|
3323
|
-
return c.json({ message: "Refused \u2014 the app would not serve this.", reasons: [String(err)] }, 422);
|
|
3324
|
-
}
|
|
3325
|
-
return c.json({ id, status: "approved", granted: requested });
|
|
3326
|
-
});
|
|
3327
|
-
operator.delete("/integrations/:id", async (c) => {
|
|
3328
|
-
const id = c.req.param("id");
|
|
3329
|
-
await runtime.pool.query("DELETE FROM integrations WHERE id = $1", [id]);
|
|
3330
|
-
await reloadIntegrations();
|
|
3331
|
-
return c.json({ id, removed: true });
|
|
3332
|
-
});
|
|
3333
|
-
operator.post("/integrations/:id/probe", async (c) => {
|
|
3334
|
-
const id = c.req.param("id");
|
|
3335
|
-
const row = await runtime.pool.query("SELECT url, reach FROM integrations WHERE id = $1", [id]);
|
|
3336
|
-
const found = row.rows[0];
|
|
3337
|
-
const url = found?.url;
|
|
3338
|
-
if (url === void 0) return c.json({ message: "No such integration." }, 404);
|
|
3339
|
-
const body = await c.req.json().catch(() => ({}));
|
|
3340
|
-
const path = typeof body.path === "string" ? body.path : "bundle";
|
|
3341
|
-
if (path !== "bundle" && !reachDeclares(found?.reach ?? {}, `/integrations/${id}/${path}`)) {
|
|
3342
|
-
return c.json({ message: "That path is not one this integration declared." }, 404);
|
|
3343
|
-
}
|
|
3344
|
-
const started = Date.now();
|
|
3345
|
-
try {
|
|
3346
|
-
const response = await fetch(`${url.replace(/\/$/, "")}/${path}`);
|
|
3347
|
-
const text = await response.text();
|
|
3348
|
-
return c.json({ status: response.status, ms: Date.now() - started, body: text.slice(0, 2e3) });
|
|
3349
|
-
} catch (err) {
|
|
3350
|
-
return c.json({ status: 0, ms: Date.now() - started, body: String(err) });
|
|
3351
|
-
}
|
|
3352
|
-
});
|
|
3353
|
-
server.route("/operator", operator);
|
|
3354
|
-
const grants = /* @__PURE__ */ new Map();
|
|
3355
|
-
const GRANT_TTL_MS = 30 * 6e4;
|
|
3356
|
-
const sweepGrants = (now) => {
|
|
3357
|
-
for (const [token, grant] of grants) if (now >= grant.expires) grants.delete(token);
|
|
3358
|
-
};
|
|
3359
|
-
server.post("/api/integrations/frame", async (c) => {
|
|
3360
|
-
const principal = c.get("principal");
|
|
3361
|
-
if (principal === null) return c.json({ message: "Sign in first." }, 401);
|
|
3362
|
-
const body = await c.req.json().catch(() => ({}));
|
|
3363
|
-
const path = typeof body.path === "string" ? body.path : "";
|
|
3364
|
-
const id = path.split("/")[2] ?? "";
|
|
3365
|
-
const row = await runtime.pool.query("SELECT status, frames FROM integrations WHERE id = $1", [id]);
|
|
3366
|
-
const found = row.rows[0];
|
|
3367
|
-
if (found === void 0 || found.status !== "approved") return c.json({ message: "No such integration." }, 404);
|
|
3368
|
-
const resolved = await resolveIdentity(principal);
|
|
3369
|
-
if (resolved.installed !== void 0 && !resolved.installed.includes(id)) return c.json({ message: "Not installed here." }, 404);
|
|
3370
|
-
const held = new Set(catalog(resolved).ids);
|
|
3371
|
-
if (!frameAdmits(found.frames ?? {}, path, held)) return c.json({ message: "No such frame." }, 404);
|
|
3372
|
-
const now = Date.now();
|
|
3373
|
-
sweepGrants(now);
|
|
3374
|
-
const token = crypto$1.randomBytes(24).toString("hex");
|
|
3375
|
-
grants.set(token, { integration: id, principal, path, expires: now + GRANT_TTL_MS });
|
|
3376
|
-
return c.json({ src: `/integrations/${id}/frame/${token}`, expiresIn: GRANT_TTL_MS });
|
|
3377
|
-
});
|
|
3378
|
-
server.get("/integrations/:id/frame/:token", async (c) => {
|
|
3379
|
-
const id = c.req.param("id");
|
|
3380
|
-
const now = Date.now();
|
|
3381
|
-
sweepGrants(now);
|
|
3382
|
-
const grant = grants.get(c.req.param("token"));
|
|
3383
|
-
if (grant === void 0 || grant.integration !== id || now >= grant.expires) {
|
|
3384
|
-
return c.json({ message: "Not found." }, 404);
|
|
3385
|
-
}
|
|
3386
|
-
const row = await runtime.pool.query("SELECT url, status FROM integrations WHERE id = $1", [id]);
|
|
3387
|
-
const found = row.rows[0];
|
|
3388
|
-
if (found === void 0 || found.status !== "approved") return c.json({ message: "Not found." }, 404);
|
|
3389
|
-
const installed = (await resolveIdentity(grant.principal)).installed;
|
|
3390
|
-
if (installed !== void 0 && !installed.includes(id)) return c.json({ message: "Not found." }, 404);
|
|
3391
|
-
const scope = await scopeValuesFor(grant.principal);
|
|
3392
|
-
const rest = grant.path.split("/").slice(3).join("/");
|
|
3393
|
-
try {
|
|
3394
|
-
const response = await fetch(`${String(found.url).replace(/\/$/, "")}/${rest}`, {
|
|
3395
|
-
headers: { authorization: `Bearer ${assertions.mint({ integration: id, principal: grant.principal, scope })}` }
|
|
3396
|
-
});
|
|
3397
|
-
return new Response(response.body, {
|
|
3398
|
-
status: response.status,
|
|
3399
|
-
headers: { "content-type": response.headers.get("content-type") ?? "text/html; charset=utf-8" }
|
|
3400
|
-
});
|
|
3401
|
-
} catch {
|
|
3402
|
-
return c.json({ message: "The integration is unreachable." }, 502);
|
|
3403
|
-
}
|
|
3404
|
-
});
|
|
3405
|
-
const CALLBACK = /^[a-z0-9][a-z0-9-]*$/;
|
|
3406
|
-
server.post("/integrations/:id/frame/:token/:call", async (c) => {
|
|
3407
|
-
const id = c.req.param("id");
|
|
3408
|
-
const call = c.req.param("call");
|
|
3409
|
-
const now = Date.now();
|
|
3410
|
-
sweepGrants(now);
|
|
3411
|
-
const grant = grants.get(c.req.param("token"));
|
|
3412
|
-
if (grant === void 0 || grant.integration !== id || now >= grant.expires) return c.json({ message: "Not found." }, 404);
|
|
3413
|
-
if (!CALLBACK.test(call)) return c.json({ message: "Not found." }, 404);
|
|
3414
|
-
const row = await runtime.pool.query("SELECT url, status FROM integrations WHERE id = $1", [id]);
|
|
3415
|
-
const found = row.rows[0];
|
|
3416
|
-
if (found === void 0 || found.status !== "approved") return c.json({ message: "Not found." }, 404);
|
|
3417
|
-
const installed = (await resolveIdentity(grant.principal)).installed;
|
|
3418
|
-
if (installed !== void 0 && !installed.includes(id)) return c.json({ message: "Not found." }, 404);
|
|
3419
|
-
const rest = grant.path.split("/").slice(3);
|
|
3420
|
-
rest.pop();
|
|
3421
|
-
const target = [...rest, call].join("/");
|
|
3422
|
-
const scope = await scopeValuesFor(grant.principal);
|
|
3423
|
-
try {
|
|
3424
|
-
const response = await fetch(`${String(found.url).replace(/\/$/, "")}/${target}`, {
|
|
3425
|
-
method: "POST",
|
|
3426
|
-
headers: {
|
|
3427
|
-
"content-type": "application/json",
|
|
3428
|
-
authorization: `Bearer ${assertions.mint({ integration: id, principal: grant.principal, scope })}`
|
|
3429
|
-
},
|
|
3430
|
-
body: await c.req.text()
|
|
3431
|
-
});
|
|
3432
|
-
return new Response(response.body, {
|
|
3433
|
-
status: response.status,
|
|
3434
|
-
headers: {
|
|
3435
|
-
"content-type": response.headers.get("content-type") ?? "application/json",
|
|
3436
|
-
// THE CALLER IS AN OPAQUE ORIGIN, and that is deliberate: the framed
|
|
3437
|
-
// page is sandboxed WITHOUT `allow-same-origin` so it cannot reach
|
|
3438
|
-
// this app's storage or session. The cost is that its `Origin` is
|
|
3439
|
-
// literally `null`, and a browser refuses the response without a
|
|
3440
|
-
// matching allowance — which is what a vendor's embedded component
|
|
3441
|
-
// hits the moment it asks for a fresh session.
|
|
3442
|
-
//
|
|
3443
|
-
// CORS IS NOT THE FENCE HERE, so opening it costs nothing. The
|
|
3444
|
-
// credential is the unguessable, short-lived, single-path grant in the
|
|
3445
|
-
// URL; anybody holding it can call this from a server where CORS does
|
|
3446
|
-
// not apply at all. Refusing the browser only breaks the one caller
|
|
3447
|
-
// this route exists for.
|
|
3448
|
-
"access-control-allow-origin": "null",
|
|
3449
|
-
vary: "origin"
|
|
3450
|
-
}
|
|
3451
|
-
});
|
|
3452
|
-
} catch {
|
|
3453
|
-
return c.json({ message: "The integration is unreachable." }, 502);
|
|
3454
|
-
}
|
|
3455
|
-
});
|
|
3456
|
-
const hookHits = /* @__PURE__ */ new Map();
|
|
3457
|
-
const HOOK_LIMIT = 240;
|
|
3458
|
-
const HOOK_WINDOW_MS = 6e4;
|
|
3459
|
-
const hookAllows = (id, now) => {
|
|
3460
|
-
const seen = hookHits.get(id);
|
|
3461
|
-
if (seen === void 0 || now >= seen.resets) {
|
|
3462
|
-
hookHits.set(id, { count: 1, resets: now + HOOK_WINDOW_MS });
|
|
3463
|
-
return true;
|
|
3464
|
-
}
|
|
3465
|
-
seen.count += 1;
|
|
3466
|
-
return seen.count <= HOOK_LIMIT;
|
|
3467
|
-
};
|
|
3468
|
-
server.post("/integrations/:id/hook/*", async (c) => {
|
|
3469
|
-
const id = c.req.param("id");
|
|
3470
|
-
const row = await runtime.pool.query("SELECT url, status FROM integrations WHERE id = $1", [id]);
|
|
3471
|
-
const found = row.rows[0];
|
|
3472
|
-
if (found === void 0 || found.status !== "approved") return c.json({ message: "Not found." }, 404);
|
|
3473
|
-
if (!hookAllows(id, Date.now())) return c.json({ message: "Too many." }, 429);
|
|
3474
|
-
const here = new URL(c.req.url);
|
|
3475
|
-
const rest = `${here.pathname.split("/").slice(3).join("/")}${here.search}`;
|
|
3476
|
-
const headers = new Headers(c.req.raw.headers);
|
|
3477
|
-
headers.delete("authorization");
|
|
3478
|
-
headers.delete("host");
|
|
3479
|
-
try {
|
|
3480
|
-
const response = await fetch(`${String(found.url).replace(/\/$/, "")}/${rest}`, {
|
|
3481
|
-
method: "POST",
|
|
3482
|
-
headers,
|
|
3483
|
-
body: await c.req.arrayBuffer()
|
|
3484
|
-
});
|
|
3485
|
-
return new Response(response.body, {
|
|
3486
|
-
status: response.status,
|
|
3487
|
-
headers: { "content-type": response.headers.get("content-type") ?? "application/json" }
|
|
3488
|
-
});
|
|
3489
|
-
} catch {
|
|
3490
|
-
return c.json({ message: "The integration is unreachable." }, 502);
|
|
3491
|
-
}
|
|
3492
|
-
});
|
|
3493
|
-
server.all("/integrations/:id/*", async (c) => {
|
|
3494
|
-
const principal = c.get("principal");
|
|
3495
|
-
if (principal === null) return c.json({ message: "Sign in first." }, 401);
|
|
3496
|
-
const id = c.req.param("id");
|
|
3497
|
-
const row = await runtime.pool.query("SELECT url, status, reach FROM integrations WHERE id = $1", [id]);
|
|
3498
|
-
const found = row.rows[0];
|
|
3499
|
-
if (found === void 0 || found.status !== "approved") return c.json({ message: "No such integration." }, 404);
|
|
3500
|
-
const resolved = await resolveIdentity(principal);
|
|
3501
|
-
if (resolved.installed !== void 0 && !resolved.installed.includes(id)) return c.json({ message: "Not installed here." }, 404);
|
|
3502
|
-
const held = new Set(catalog(resolved).ids);
|
|
3503
|
-
if (!reachAdmits(found.reach ?? {}, c.req.path, held)) return c.json({ message: "No such integration." }, 404);
|
|
3504
|
-
const scope = await scopeValuesFor(principal);
|
|
3505
|
-
const here = new URL(c.req.url);
|
|
3506
|
-
const rest = `${here.pathname.split("/").slice(3).join("/")}${here.search}`;
|
|
3507
|
-
const headers = {
|
|
3508
|
-
"content-type": "application/json",
|
|
3509
|
-
authorization: `Bearer ${assertions.mint({ integration: id, principal, scope })}`
|
|
3510
|
-
};
|
|
3511
|
-
try {
|
|
3512
|
-
const response = await fetch(`${String(found.url).replace(/\/$/, "")}/${rest}`, {
|
|
3513
|
-
method: c.req.method,
|
|
3514
|
-
headers,
|
|
3515
|
-
...c.req.method === "GET" ? {} : { body: await c.req.text() }
|
|
3516
|
-
});
|
|
3517
|
-
return new Response(response.body, {
|
|
3518
|
-
status: response.status,
|
|
3519
|
-
headers: { "content-type": response.headers.get("content-type") ?? "application/json" }
|
|
3520
|
-
});
|
|
3521
|
-
} catch {
|
|
3522
|
-
return c.json({ message: "The integration is unreachable." }, 502);
|
|
3523
|
-
}
|
|
3524
|
-
});
|
|
3525
|
-
const entriesNow = () => new Map((app.entries ?? []).map((entry) => [entry.fingerprint, entry]));
|
|
3526
|
-
const shellContext = {
|
|
3527
|
-
app,
|
|
3528
|
-
needOf: (definition) => shellNeedOf(definition, entriesNow()),
|
|
3529
|
-
// ONE resolution per shell build, awaited. This was four synchronous
|
|
3530
|
-
// questions, and every one of them was ultimately answered out of a
|
|
3531
|
-
// resident map of the population.
|
|
3532
|
-
resolve: async (principal) => {
|
|
3533
|
-
const resolved = await resolveIdentity(principal);
|
|
3534
|
-
return { roles: resolved.roles, scope: resolved.scope, installed: resolved.installed, catalog: catalog(resolved), variants: variants(resolved), policy: policy(resolved) };
|
|
3535
|
-
},
|
|
3536
|
-
catalogFor: (roles, installed) => catalog(asRoles(roles, installed)),
|
|
3537
|
-
variantsFor: (roles) => variants(asRoles(roles, void 0)),
|
|
3538
|
-
runtime,
|
|
3539
|
-
...runtime.shellIdleMs !== void 0 ? { idleMs: runtime.shellIdleMs } : {},
|
|
3540
|
-
...runtime.shellFrameDelta !== void 0 ? { delta: runtime.shellFrameDelta } : {},
|
|
3541
|
-
wire: (token) => async (url, init) => {
|
|
3542
|
-
const isVex = url.split("?")[0]?.endsWith("/vex") === true;
|
|
3543
|
-
const follower = isVex && init?.signal !== void 0 ? createWireFollower(init.signal) : void 0;
|
|
3544
|
-
const res = await server.request(
|
|
3545
|
-
url,
|
|
3546
|
-
{
|
|
3547
|
-
method: init?.method ?? "GET",
|
|
3548
|
-
headers: { ...init?.headers ?? {}, ...token !== null ? { Authorization: `Bearer ${token}` } : {} },
|
|
3549
|
-
...init?.body !== void 0 ? { body: init.body } : {}
|
|
3550
|
-
},
|
|
3551
|
-
follower === void 0 ? void 0 : { [hono$1.VEX_LIVE_ENV]: follower.live }
|
|
3552
|
-
);
|
|
3553
|
-
if (!isVex || !res.ok) {
|
|
3554
|
-
follower?.end();
|
|
3555
|
-
return res;
|
|
3556
|
-
}
|
|
3557
|
-
const body = await res.json();
|
|
3558
|
-
const result = body !== null && typeof body === "object" && "result" in body ? body["result"] : body;
|
|
3559
|
-
follower?.handedOver();
|
|
3560
|
-
return {
|
|
3561
|
-
ok: res.ok,
|
|
3562
|
-
status: res.status,
|
|
3563
|
-
json: () => Promise.resolve(result),
|
|
3564
|
-
text: () => Promise.resolve(JSON.stringify(result)),
|
|
3565
|
-
...follower === void 0 ? {} : { onChange: follower.onChange }
|
|
3566
|
-
};
|
|
3567
|
-
}
|
|
3568
|
-
};
|
|
3569
|
-
const shells = app.shell !== void 0 ? createShellHost(shellContext) : void 0;
|
|
3570
|
-
const pageManifests = app.pages ?? {};
|
|
3571
|
-
const pageRouter = createPageRouter(pageManifests);
|
|
3572
|
-
const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost({ ...shellContext, manifest, kept: false })]));
|
|
3573
|
-
const pageAt = (path) => {
|
|
3574
|
-
const matched = pageRouter.match(path);
|
|
3575
|
-
if (matched === void 0) return void 0;
|
|
3576
|
-
const host = pageHosts.get(matched.name);
|
|
3577
|
-
const manifest = pageManifests[matched.name];
|
|
3578
|
-
if (host === void 0 || manifest === void 0) return void 0;
|
|
3579
|
-
return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
|
|
3580
|
-
};
|
|
3581
|
-
const fabricOrigin = crypto$1.randomBytes(8).toString("hex");
|
|
3582
|
-
const applyInvalidateIdentity = (principal) => {
|
|
3583
|
-
const held = identities?.invalidate(principal) ?? false;
|
|
3584
|
-
shells?.reset(principal);
|
|
3585
|
-
return held;
|
|
3586
|
-
};
|
|
3587
|
-
const applyInvalidateTenant = (tag) => (identities?.invalidateTag(tag) ?? []).length;
|
|
3588
|
-
const applyNudge = (principal, channel) => {
|
|
3589
|
-
shells?.deliver(principal, channel);
|
|
3590
|
-
};
|
|
3591
|
-
const publishFabric = wireFabric(runtime.fabric, fabricOrigin, {
|
|
3592
|
-
invalidateIdentity: applyInvalidateIdentity,
|
|
3593
|
-
invalidateTenant: applyInvalidateTenant,
|
|
3594
|
-
nudge: applyNudge
|
|
3595
|
-
});
|
|
3596
|
-
const refresh = () => {
|
|
3597
|
-
refreshLocal();
|
|
3598
|
-
generation?.bump();
|
|
3599
|
-
};
|
|
3600
|
-
const refreshLocal = () => {
|
|
3601
|
-
const nextReport = charter.verifyCharter(
|
|
3602
|
-
app.charter,
|
|
3603
|
-
{ actions: Object.keys(app.actions), data: data.grants, layouts: Object.keys(app.layouts ?? {}) },
|
|
3604
|
-
wearableOf(app),
|
|
3605
|
-
auditClosure(app.actions, app.layouts)
|
|
3606
|
-
);
|
|
3607
|
-
if (nextReport.errors.length > 0) {
|
|
3608
|
-
throw new Error(`Refresh refused \u2014 charter incoherent over the new artifacts:
|
|
3609
|
-
${nextReport.errors.map((e) => ` ${e.rule}: ${e.detail}`).join("\n")}`);
|
|
3610
|
-
}
|
|
3611
|
-
const nextVariantErrors = verifyVariants(app);
|
|
3612
|
-
if (nextVariantErrors.length > 0) {
|
|
3613
|
-
throw new Error(`Refresh refused \u2014 layout variants incoherent:
|
|
3614
|
-
${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
|
|
3615
|
-
}
|
|
3616
|
-
verifiedReport = nextReport;
|
|
3617
|
-
identities?.invalidateAll();
|
|
3618
|
-
policies.clear();
|
|
3619
|
-
reachPolicies.clear();
|
|
3620
|
-
catalogs.clear();
|
|
3621
|
-
variantBindings.clear();
|
|
3622
|
-
shells?.adopt();
|
|
3623
|
-
};
|
|
3624
|
-
{
|
|
3625
|
-
const fromRows = await loadIntegrationActions(runtime.pool, grammars);
|
|
3626
|
-
if (Object.keys(fromRows).length > 0) {
|
|
3627
|
-
app.actions = { ...staticActions, ...fromRows };
|
|
3628
|
-
refresh();
|
|
3629
|
-
}
|
|
3630
|
-
}
|
|
3631
|
-
generation = createGeneration(runtime.pool, {
|
|
3632
|
-
...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {},
|
|
3633
|
-
onMoved: async () => {
|
|
3634
|
-
const fromRows = await loadIntegrationActions(runtime.pool, grammars);
|
|
3635
|
-
app.actions = { ...staticActions, ...fromRows };
|
|
3636
|
-
refreshLocal();
|
|
3637
|
-
}
|
|
3638
|
-
});
|
|
3639
|
-
const socket = createSocket({
|
|
3640
|
-
session,
|
|
3641
|
-
catalog: async (principal) => catalog(await resolveIdentity(principal)),
|
|
3642
|
-
...shells !== void 0 ? { shells } : {},
|
|
3643
|
-
page: pageAt,
|
|
3644
|
-
...runtime.sessionRevalidateMs !== void 0 ? { revalidateMs: runtime.sessionRevalidateMs } : {},
|
|
3645
|
-
...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
|
|
3646
|
-
...runtime.origins !== void 0 ? { origins: runtime.origins } : {},
|
|
3647
|
-
...runtime.session === "sessions" ? { sessionLastsMs: (token) => sessionRemainingMs(runtime.pool, token) } : {}
|
|
3648
|
-
});
|
|
3649
|
-
return Object.assign(server, {
|
|
3650
|
-
socket,
|
|
3651
|
-
principalOf: async (token) => session(token),
|
|
3652
|
-
page: pageAt,
|
|
3653
|
-
pages: Object.entries(pageManifests).map(([name, manifest]) => ({ name, path: manifest.path })),
|
|
3654
|
-
...shells !== void 0 ? { shells } : {},
|
|
3655
|
-
refresh,
|
|
3656
|
-
charterReport: () => verifiedReport,
|
|
3657
|
-
generation: () => generation?.current() ?? -1,
|
|
3658
|
-
// Every timer this server owns, stopped once. Absent pieces (an app with no
|
|
3659
|
-
// identity seam, no shells) simply have nothing to stop — the `?.` is the
|
|
3660
|
-
// whole guard. See the type above for why this is one call and not four.
|
|
3661
|
-
close: () => {
|
|
3662
|
-
generation?.stop();
|
|
3663
|
-
identities?.stop();
|
|
3664
|
-
socket.stop();
|
|
3665
|
-
shells?.stop();
|
|
3666
|
-
for (const host of pageHosts.values()) host.stop();
|
|
3667
|
-
},
|
|
3668
|
-
executeAs,
|
|
3669
|
-
callIntegration,
|
|
3670
|
-
identity: async (principal) => {
|
|
3671
|
-
const resolved = await resolveIdentity(principal);
|
|
3672
|
-
return { roles: resolved.roles, scope: resolved.scope, ...resolved.installed !== void 0 ? { installed: resolved.installed } : {} };
|
|
3673
|
-
},
|
|
3674
|
-
invalidateTenant: (tag) => {
|
|
3675
|
-
const forgotten = applyInvalidateTenant(tag);
|
|
3676
|
-
publishFabric({ kind: "invalidate-tenant", tag });
|
|
3677
|
-
return forgotten;
|
|
3678
|
-
},
|
|
3679
|
-
invalidateIdentity: (principal) => {
|
|
3680
|
-
const held = applyInvalidateIdentity(principal);
|
|
3681
|
-
publishFabric({ kind: "invalidate-identity", principal });
|
|
3682
|
-
return held;
|
|
3683
|
-
},
|
|
3684
|
-
nudge: (principal, channel) => {
|
|
3685
|
-
applyNudge(principal, channel);
|
|
3686
|
-
publishFabric({ kind: "nudge", principal, channel });
|
|
3687
|
-
},
|
|
3688
|
-
...identities !== void 0 ? { identities: { list: identities.list, meter: identities.meter } } : {}
|
|
3689
|
-
});
|
|
3690
|
-
};
|
|
3691
|
-
|
|
3692
|
-
// src/driver.ts
|
|
3693
|
-
var DEFAULT_JANITOR_MS = 3e5;
|
|
3694
|
-
var MAX_STEPS_PER_DRAIN = 1e4;
|
|
3695
|
-
var progressOf = (report) => report.materialized + report.skippedOccurrences + report.factsMatched + report.runsCreated + report.tasksCreated + report.executed + report.reclaimed + report.runsSettled + report.parked;
|
|
3696
|
-
var createTideDriver = (config) => {
|
|
3697
|
-
const { tide } = config;
|
|
3698
|
-
const now = config.now ?? (() => Date.now());
|
|
3699
|
-
const janitorMs = config.janitorMs ?? DEFAULT_JANITOR_MS;
|
|
3700
|
-
let running = false;
|
|
3701
|
-
let queued = false;
|
|
3702
|
-
let stopped = false;
|
|
3703
|
-
let cycle;
|
|
3704
|
-
let scheduling;
|
|
3705
|
-
let timer;
|
|
3706
|
-
const drain = async () => {
|
|
3707
|
-
for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {
|
|
3708
|
-
const report = await tide.advance({ now: now() });
|
|
3709
|
-
if (progressOf(report) === 0) return;
|
|
3710
|
-
}
|
|
3711
|
-
console.error(`[moss:tide-driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps \u2014 stopping this pass; the janitor will resume it`);
|
|
3712
|
-
};
|
|
3713
|
-
const schedule = async () => {
|
|
3714
|
-
if (stopped) return;
|
|
3715
|
-
let due;
|
|
3716
|
-
try {
|
|
3717
|
-
due = await tide.nextDue(now());
|
|
3718
|
-
} catch (err) {
|
|
3719
|
-
if (!stopped) console.error("[moss:tide-driver] next due", err);
|
|
3720
|
-
return;
|
|
3721
|
-
}
|
|
3722
|
-
if (stopped) return;
|
|
3723
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
3724
|
-
if (due === void 0) return;
|
|
3725
|
-
const delay = due - now();
|
|
3726
|
-
timer = setTimeout(() => void wake(), delay > 0 ? delay : janitorMs);
|
|
3727
|
-
timer.unref?.();
|
|
3728
|
-
};
|
|
3729
|
-
const wake = () => {
|
|
3730
|
-
if (stopped) return Promise.resolve();
|
|
3731
|
-
queued = true;
|
|
3732
|
-
if (running) return cycle ?? Promise.resolve();
|
|
3733
|
-
running = true;
|
|
3734
|
-
cycle = (async () => {
|
|
3735
|
-
try {
|
|
3736
|
-
while (queued) {
|
|
3737
|
-
queued = false;
|
|
3738
|
-
await drain();
|
|
3739
|
-
}
|
|
3740
|
-
} catch (err) {
|
|
3741
|
-
console.error("[moss:tide-driver]", err);
|
|
3742
|
-
} finally {
|
|
3743
|
-
running = false;
|
|
3744
|
-
cycle = void 0;
|
|
3745
|
-
scheduling = schedule();
|
|
3746
|
-
}
|
|
3747
|
-
})();
|
|
3748
|
-
return cycle;
|
|
3749
|
-
};
|
|
3750
|
-
const janitor = setInterval(() => {
|
|
3751
|
-
if (config.retention !== void 0) {
|
|
3752
|
-
void tide.sweep(now(), config.retention).catch((err) => console.error("[moss:tide-driver] sweep", err));
|
|
3753
|
-
}
|
|
3754
|
-
void wake();
|
|
3755
|
-
}, janitorMs);
|
|
3756
|
-
janitor.unref?.();
|
|
3757
|
-
return {
|
|
3758
|
-
ingest: async (fact, options) => {
|
|
3759
|
-
const stored = await tide.ingest(fact, options);
|
|
3760
|
-
if (stored !== void 0) void wake();
|
|
3761
|
-
return stored;
|
|
3762
|
-
},
|
|
3763
|
-
fire: async (reflexId, options) => {
|
|
3764
|
-
const fact = await tide.fire(reflexId, options);
|
|
3765
|
-
void wake();
|
|
3766
|
-
return fact;
|
|
3767
|
-
},
|
|
3768
|
-
wake,
|
|
3769
|
-
stop: async () => {
|
|
3770
|
-
stopped = true;
|
|
3771
|
-
clearInterval(janitor);
|
|
3772
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
3773
|
-
await cycle;
|
|
3774
|
-
await scheduling;
|
|
3775
|
-
}
|
|
3776
|
-
};
|
|
3777
|
-
};
|
|
3778
|
-
var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
|
|
3779
|
-
var DEFAULT_ROOT = '<div id="root"></div>';
|
|
3780
|
-
var embedSnapshot = (snapshot, principal, path) => {
|
|
3781
|
-
const { frame, trees, seed, live } = snapshot;
|
|
3782
|
-
const text = JSON.stringify({ frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} }).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
3783
|
-
return `<script type="application/json" id="${SNAPSHOT_ELEMENT_ID}">${text}</script>`;
|
|
3784
|
-
};
|
|
3785
|
-
var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
|
|
3786
|
-
var escapeAttribute = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
3787
|
-
var renderDocument = async (config) => {
|
|
3788
|
-
const { server, template, request, draw } = config;
|
|
3789
|
-
const tokenKey = config.tokenKey ?? DEFAULT_TOKEN_KEY;
|
|
3790
|
-
const root = config.root ?? DEFAULT_ROOT;
|
|
3791
|
-
const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
|
|
3792
|
-
if (!template.includes(root)) return undrawn;
|
|
3793
|
-
try {
|
|
3794
|
-
const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
|
|
3795
|
-
const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
|
|
3796
|
-
const principal = token === null ? null : await server.principalOf(token);
|
|
3797
|
-
const route = server.page(request.path);
|
|
3798
|
-
const host = route?.host ?? server.shells;
|
|
3799
|
-
if (host === void 0) return undrawn;
|
|
3800
|
-
const snapshot = await host.snapshot(principal === null ? null : token, principal, {
|
|
3801
|
-
...config.waitMs !== void 0 ? { waitMs: config.waitMs } : {},
|
|
3802
|
-
...route !== void 0 ? { inputs: route.inputs } : {}
|
|
3803
|
-
});
|
|
3804
|
-
const screen = await draw(snapshot);
|
|
3805
|
-
const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
|
|
3806
|
-
const placed = template.replace(root, () => `${root.replace("></div>", () => `>${screen}</div>`)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
|
|
3807
|
-
const head = document.headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
|
|
3808
|
-
for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
|
|
3809
|
-
const html = document.placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
|
|
3810
|
-
return {
|
|
3811
|
-
html,
|
|
3812
|
-
...head !== void 0 ? { head } : {},
|
|
3813
|
-
headers: documentHeaders(principal),
|
|
3814
|
-
drawn: true,
|
|
3815
|
-
principal,
|
|
3816
|
-
...route !== void 0 ? { page: route.name } : {},
|
|
3817
|
-
live: snapshot.live,
|
|
3818
|
-
why: snapshot.why,
|
|
3819
|
-
drawnWith: snapshot.drawnWith,
|
|
3820
|
-
settled: snapshot.settled
|
|
3821
|
-
};
|
|
3822
|
-
} catch (error) {
|
|
3823
|
-
console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
|
|
3824
|
-
return undrawn;
|
|
3825
|
-
}
|
|
3826
|
-
};
|
|
3827
|
-
var exportDocuments = async (config) => {
|
|
3828
|
-
const { paths, ...rest } = config;
|
|
3829
|
-
const out = [];
|
|
3830
|
-
for (const path of paths) {
|
|
3831
|
-
const page = await renderDocument({ ...rest, request: { path, cookie: null } });
|
|
3832
|
-
out.push({
|
|
3833
|
-
path,
|
|
3834
|
-
html: page.html,
|
|
3835
|
-
...page.page !== void 0 ? { page: page.page } : {},
|
|
3836
|
-
...page.head !== void 0 ? { head: page.head } : {},
|
|
3837
|
-
drawn: page.drawn,
|
|
3838
|
-
// undrawn is not concluded finished
|
|
3839
|
-
live: page.live ?? true,
|
|
3840
|
-
why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
|
|
3841
|
-
drawnWith: page.drawnWith ?? [],
|
|
3842
|
-
settled: page.settled ?? false
|
|
3843
|
-
});
|
|
3844
|
-
}
|
|
3845
|
-
return out;
|
|
3846
|
-
};
|
|
3847
|
-
|
|
3848
|
-
exports.CLOSE_INVALID_TOKEN = CLOSE_INVALID_TOKEN;
|
|
3849
|
-
exports.CLOSE_SHELL_FAILED = CLOSE_SHELL_FAILED;
|
|
3850
|
-
exports.CLOSE_SIGNED_OUT = CLOSE_SIGNED_OUT;
|
|
3851
|
-
exports.DEFAULT_GENERATION_POLL_MS = DEFAULT_GENERATION_POLL_MS;
|
|
3852
|
-
exports.DEFAULT_IDENTITY_IDLE_MS = DEFAULT_IDENTITY_IDLE_MS;
|
|
3853
|
-
exports.DEFAULT_IDENTITY_MAX = DEFAULT_IDENTITY_MAX;
|
|
3854
|
-
exports.DEFAULT_IDLE_MS = DEFAULT_IDLE_MS;
|
|
3855
|
-
exports.DEFAULT_REVALIDATE_MS = DEFAULT_REVALIDATE_MS;
|
|
3856
|
-
exports.GENERATION_DDL = GENERATION_DDL;
|
|
3857
|
-
exports.MOSS_SEQUENCE = MOSS_SEQUENCE;
|
|
3858
|
-
exports.PROTOCOL = PROTOCOL;
|
|
3859
|
-
exports.SESSIONS_SEQUENCE = SESSIONS_SEQUENCE;
|
|
3860
|
-
exports.SNAPSHOT_ELEMENT_ID = SNAPSHOT_ELEMENT_ID;
|
|
3861
|
-
exports.TIDE_DDL = TIDE_DDL;
|
|
3862
|
-
exports.TIDE_SEQUENCE = TIDE_SEQUENCE;
|
|
3863
|
-
exports.TIDE_TABLES = TIDE_TABLES;
|
|
3864
|
-
exports.auditClosure = auditClosure;
|
|
3865
|
-
exports.buildContract = buildContract;
|
|
3866
|
-
exports.callIntegrationWith = callIntegrationWith;
|
|
3867
|
-
exports.contractAsMarkdown = contractAsMarkdown;
|
|
3868
|
-
exports.copyPress = copyPress;
|
|
3869
|
-
exports.createAssertionSigner = createAssertionSigner;
|
|
3870
|
-
exports.createDataLayer = createDataLayer;
|
|
3871
|
-
exports.createGeneration = createGeneration;
|
|
3872
|
-
exports.createIdentityCache = createIdentityCache;
|
|
3873
|
-
exports.createPageRouter = createPageRouter;
|
|
3874
|
-
exports.createServer = createServer;
|
|
3875
|
-
exports.createShellHost = createShellHost;
|
|
3876
|
-
exports.createSocket = createSocket;
|
|
3877
|
-
exports.createTideDriver = createTideDriver;
|
|
3878
|
-
exports.createTideStore = createTideStore;
|
|
3879
|
-
exports.defineApp = defineApp;
|
|
3880
|
-
exports.describePlacements = describePlacements;
|
|
3881
|
-
exports.devSession = devSession;
|
|
3882
|
-
exports.documentHeaders = documentHeaders;
|
|
3883
|
-
exports.embedSnapshot = embedSnapshot;
|
|
3884
|
-
exports.emitterOf = emitterOf;
|
|
3885
|
-
exports.exportDocuments = exportDocuments;
|
|
3886
|
-
exports.filterInstalled = filterInstalled;
|
|
3887
|
-
exports.hashIntegrationKey = hashIntegrationKey;
|
|
3888
|
-
exports.initIntegrations = initIntegrations;
|
|
3889
|
-
exports.initSessions = initSessions;
|
|
3890
|
-
exports.integrationByKey = integrationByKey;
|
|
3891
|
-
exports.integrationOfAction = integrationOfAction;
|
|
3892
|
-
exports.listAttachments = listAttachments;
|
|
3893
|
-
exports.listIntegrations = listIntegrations;
|
|
3894
|
-
exports.listPlacements = listPlacements;
|
|
3895
|
-
exports.loadIntegrationActions = loadIntegrationActions;
|
|
3896
|
-
exports.memoKeyOf = memoKeyOf;
|
|
3897
|
-
exports.migrateTables = migrateTables;
|
|
3898
|
-
exports.mintDevToken = mintDevToken;
|
|
3899
|
-
exports.mintIntegrationKey = mintIntegrationKey;
|
|
3900
|
-
exports.mintSession = mintSession;
|
|
3901
|
-
exports.mintWrites = mintWrites;
|
|
3902
|
-
exports.offerToken = offerToken;
|
|
3903
|
-
exports.renderDocument = renderDocument;
|
|
3904
|
-
exports.resolveCatalog = resolveCatalog;
|
|
3905
|
-
exports.resolveCatalogForRoles = resolveCatalogForRoles;
|
|
3906
|
-
exports.resolvePolicy = resolvePolicy;
|
|
3907
|
-
exports.resolvePolicyAtReach = resolvePolicyAtReach;
|
|
3908
|
-
exports.resolvePolicyForRoles = resolvePolicyForRoles;
|
|
3909
|
-
exports.resolveRoles = resolveRoles;
|
|
3910
|
-
exports.resolveVariants = resolveVariants;
|
|
3911
|
-
exports.resolveVariantsForRoles = resolveVariantsForRoles;
|
|
3912
|
-
exports.revokeAllFor = revokeAllFor;
|
|
3913
|
-
exports.revokeSession = revokeSession;
|
|
3914
|
-
exports.runIntake = runIntake;
|
|
3915
|
-
exports.sessionCookies = sessionCookies;
|
|
3916
|
-
exports.sessionOf = sessionOf;
|
|
3917
|
-
exports.sessionVerifierOf = sessionVerifierOf;
|
|
3918
|
-
exports.shellNeedOf = shellNeedOf;
|
|
3919
|
-
exports.spanClock = spanClock;
|
|
3920
|
-
exports.tokenFromCookie = tokenFromCookie;
|
|
3921
|
-
exports.verifyAssertion = verifyAssertion;
|
|
3922
|
-
exports.verifyVariants = verifyVariants;
|
|
3923
|
-
exports.wearableOf = wearableOf;
|
|
3924
|
-
exports.wireFabric = wireFabric;
|
|
3925
54
|
//# sourceMappingURL=index.cjs.map
|
|
3926
55
|
//# sourceMappingURL=index.cjs.map
|