@niscorp/moss 0.6.0 → 0.7.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 +100 -0
- package/DESIGN.md +77 -40
- package/DOCS.md +636 -78
- package/README.md +2 -2
- package/dist/{chunk-VBWNHF4H.cjs → chunk-C2DNDIQX.cjs} +4 -3
- package/dist/chunk-C2DNDIQX.cjs.map +1 -0
- package/dist/{chunk-R66WUKGC.cjs → chunk-DSTHFSTO.cjs} +1988 -1328
- package/dist/chunk-DSTHFSTO.cjs.map +1 -0
- package/dist/chunk-F45SFR7W.cjs +903 -0
- package/dist/chunk-F45SFR7W.cjs.map +1 -0
- package/dist/{chunk-NSK7QSSG.js → chunk-IMZZB4JE.js} +4 -3
- package/dist/chunk-IMZZB4JE.js.map +1 -0
- package/dist/{chunk-V5YMJL7Z.js → chunk-MTC46PGQ.js} +1971 -1309
- package/dist/chunk-MTC46PGQ.js.map +1 -0
- package/dist/chunk-MYGVHWS5.js +870 -0
- package/dist/chunk-MYGVHWS5.js.map +1 -0
- package/dist/{chunk-WKBH3UMB.js → chunk-X2Q546EB.js} +3 -3
- package/dist/{chunk-WKBH3UMB.js.map → chunk-X2Q546EB.js.map} +1 -1
- package/dist/{chunk-D3YZIAYV.cjs → chunk-Z2VA6AOE.cjs} +5 -5
- package/dist/{chunk-D3YZIAYV.cjs.map → chunk-Z2VA6AOE.cjs.map} +1 -1
- package/dist/document-AbQUbQaP.d.ts +381 -0
- package/dist/document-wHHxIXJz.d.cts +381 -0
- package/dist/{index-B411sK9M.d.cts → index-Dml1klpZ.d.cts} +4 -0
- package/dist/{index-B411sK9M.d.ts → index-Dml1klpZ.d.ts} +4 -0
- package/dist/index.cjs +17 -17
- package/dist/index.d.cts +7 -9
- package/dist/index.d.ts +7 -9
- package/dist/index.js +3 -3
- package/dist/integrations.cjs +3 -3
- package/dist/integrations.d.cts +1 -1
- package/dist/integrations.d.ts +1 -1
- package/dist/integrations.js +1 -1
- package/dist/node.cjs +8 -8
- package/dist/node.d.cts +3 -4
- package/dist/node.d.ts +3 -4
- package/dist/node.js +4 -4
- package/dist/tide.d.cts +1 -1
- package/dist/tide.d.ts +1 -1
- package/dist/unverified.cjs +3 -3
- package/dist/unverified.js +2 -2
- package/dist/vite.cjs +9 -9
- package/dist/vite.d.cts +6 -1
- package/dist/vite.d.ts +6 -1
- package/dist/vite.js +4 -4
- package/package.json +13 -13
- package/dist/app-CUnDcXQu.d.ts +0 -143
- package/dist/app-CdANzi2q.d.cts +0 -143
- package/dist/chunk-NSK7QSSG.js.map +0 -1
- package/dist/chunk-PWUO4RET.js +0 -374
- package/dist/chunk-PWUO4RET.js.map +0 -1
- package/dist/chunk-R2YPQHQH.cjs +0 -383
- package/dist/chunk-R2YPQHQH.cjs.map +0 -1
- package/dist/chunk-R66WUKGC.cjs.map +0 -1
- package/dist/chunk-V5YMJL7Z.js.map +0 -1
- package/dist/chunk-VBWNHF4H.cjs.map +0 -1
- package/dist/document-D7nroBww.d.cts +0 -169
- package/dist/document-DeTPGBil.d.ts +0 -169
|
@@ -1,25 +1,24 @@
|
|
|
1
|
-
import { sessionOn, endShell, canvasesOf, treeOf, buildShell, attach, layoutsOf } from './chunk-
|
|
2
|
-
import { emitterOf, FabricMessageSchema, spanClock } from './chunk-
|
|
1
|
+
import { entriesOf, receiveManifest, verifyManifest, functionsWarning, refusalOf, candidateOf, FRAME_LAYOUT_REF, canvasLayoutRef, freezeDeep, entryMisfits, sessionOn, endlessChains, layoutMisfits, actionLayoutRef, actionOfLayoutRef, endShell, GENERATED_ID_PREFIX, layoutNameRefusal, withLayoutInPlace, canvasesOf, treeOf, buildShell, SHELL_GONE, draftedIn, attach, holdGranted, layoutsOf, withVariants, variantLayouts } from './chunk-MYGVHWS5.js';
|
|
2
|
+
import { emitterOf, FabricMessageSchema, spanClock } from './chunk-IMZZB4JE.js';
|
|
3
3
|
import { DEFAULT_TOKEN_KEY, sessionNameOf, SNAPSHOT_ELEMENT_ID, CLOSE_SHELL_FAILED, CLOSE_PROTOCOL_MISMATCH, CLOSE_INVALID_TOKEN, CLOSE_AT_CAPACITY, PROTOCOL_MIN, PROTOCOL, offeredSealed, offeredToken, ClientMessageSchema } from './chunk-4ZGAFZGS.js';
|
|
4
4
|
import { z } from 'zod';
|
|
5
|
-
import { randomBytes, createHash, timingSafeEqual } from 'crypto';
|
|
6
|
-
import {
|
|
7
|
-
import { LayoutNodeSchema, ActionFragmentSchema, ActionDefinitionSchema, collectChannels, auditAction, DefinitionValidationError, shellSettled, CANVAS_SLOT_NAME, ACTION_SLOT_NAME } from '@niscorp/nova';
|
|
8
|
-
import { chainCycles, snapshotShell, walkNodes, isRecord, livenessOf, componentsOf } from '@niscorp/nova/reflect';
|
|
9
|
-
import { SequenceSchema, exceedsDepth, depthRefusal, createUpgrader } from '@niscorp/strata';
|
|
10
|
-
import { REFRESH_MODES, QuerySchema, MutationDefinitionSchema, createPostgresCache, createPostgresAdapter, scopeProfiles, resolve, pruneOptional, mutationMisfits, handleDiscovery, seedCache, handleQuery, mergeScopePolicies, createScopePolicy, createQueryEngine, scopeGrants, createMemoryCache, tablesChangedBy } from '@niscorp/vex';
|
|
11
|
-
import { isBinding } from '@niscorp/nova/i18n';
|
|
12
|
-
import { ConfigSchema, evaluate } from '@niscorp/prism';
|
|
5
|
+
import { randomBytes, createHash, timingSafeEqual, randomUUID } from 'crypto';
|
|
6
|
+
import { createPostgresCache, createPostgresAdapter, resolve, pruneOptional, mutationMisfits, createMemoryCache, seedCache, handleDiscovery, handleQuery, mergeScopePolicies, createScopePolicy, createQueryEngine, scopeGrants, tablesChangedBy } from '@niscorp/vex';
|
|
13
7
|
import { migrate, upgradeStore } from '@niscorp/strata/postgres';
|
|
8
|
+
import { exceedsDepth, StrataError, depthRefusal, createUpgrader } from '@niscorp/strata';
|
|
14
9
|
import { NOVA_SEQUENCE } from '@niscorp/nova/migrations';
|
|
10
|
+
import { evaluate } from '@niscorp/prism';
|
|
15
11
|
import { PRISM_SEQUENCE } from '@niscorp/prism/migrations';
|
|
12
|
+
import { VEX_SCHEMAS, VEX_SEQUENCE } from '@niscorp/vex/migrations';
|
|
13
|
+
import { resolvePrincipal, verifyCharter, resolveScoping } from '@niscorp/charter';
|
|
16
14
|
import { Hono } from 'hono';
|
|
17
15
|
import { VEX_LIVE_ENV, vex } from '@niscorp/vex/hono';
|
|
18
16
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
19
17
|
import { headOf, placeHead } from '@niscorp/nova/document';
|
|
18
|
+
import { LayoutNodeSchema, CANVAS_SLOT_NAME, DefinitionValidationError, auditAction, shellSettled, ActionDefinitionSchema, ActionFragmentSchema, ACTION_SLOT_NAME } from '@niscorp/nova';
|
|
19
|
+
import { isBinding } from '@niscorp/nova/i18n';
|
|
20
|
+
import { isRecord, walkNodes, snapshotShell, livenessOf, componentsOf } from '@niscorp/nova/reflect';
|
|
20
21
|
|
|
21
|
-
// src/manifest/app.ts
|
|
22
|
-
var defineApp = (app) => app;
|
|
23
22
|
var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
|
|
24
23
|
if (header === void 0 || header === null) return null;
|
|
25
24
|
const wanted = encodeURIComponent(name);
|
|
@@ -35,10 +34,10 @@ var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
|
|
|
35
34
|
}
|
|
36
35
|
return null;
|
|
37
36
|
};
|
|
38
|
-
var ownOriginOf = (origin, host,
|
|
37
|
+
var ownOriginOf = (origin, host, listed2 = []) => {
|
|
39
38
|
if (origin === void 0 || origin === null || !URL.canParse(origin)) return void 0;
|
|
40
39
|
const asked = new URL(origin);
|
|
41
|
-
const own = asked.host === host?.toLowerCase() ||
|
|
40
|
+
const own = asked.host === host?.toLowerCase() || listed2.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
|
|
42
41
|
return own ? asked : void 0;
|
|
43
42
|
};
|
|
44
43
|
var cookiesAt = (where, key, token, lastsMs) => {
|
|
@@ -167,8 +166,8 @@ var createHeldRecords = (max) => {
|
|
|
167
166
|
const held = /* @__PURE__ */ new Map();
|
|
168
167
|
const tagged = /* @__PURE__ */ new Map();
|
|
169
168
|
let evicted = 0;
|
|
170
|
-
const untag = (principal,
|
|
171
|
-
const tag =
|
|
169
|
+
const untag = (principal, record) => {
|
|
170
|
+
const tag = record.tag;
|
|
172
171
|
if (tag === void 0) return;
|
|
173
172
|
const group = tagged.get(tag);
|
|
174
173
|
if (group === void 0) return;
|
|
@@ -176,9 +175,9 @@ var createHeldRecords = (max) => {
|
|
|
176
175
|
if (group.size === 0) tagged.delete(tag);
|
|
177
176
|
};
|
|
178
177
|
const forget = (principal) => {
|
|
179
|
-
const
|
|
180
|
-
if (
|
|
181
|
-
untag(principal,
|
|
178
|
+
const entry = held.get(principal);
|
|
179
|
+
if (entry === void 0) return false;
|
|
180
|
+
untag(principal, entry.record);
|
|
182
181
|
held.delete(principal);
|
|
183
182
|
return true;
|
|
184
183
|
};
|
|
@@ -188,22 +187,22 @@ var createHeldRecords = (max) => {
|
|
|
188
187
|
forget(oldest.value);
|
|
189
188
|
evicted += 1;
|
|
190
189
|
};
|
|
191
|
-
const remember = (principal,
|
|
190
|
+
const remember = (principal, record, at) => {
|
|
192
191
|
forget(principal);
|
|
193
192
|
while (held.size >= max) evictOldest();
|
|
194
|
-
held.set(principal, { record
|
|
195
|
-
if (
|
|
196
|
-
const group = tagged.get(
|
|
193
|
+
held.set(principal, { record, since: at, lastSeen: at });
|
|
194
|
+
if (record.tag !== void 0) {
|
|
195
|
+
const group = tagged.get(record.tag) ?? /* @__PURE__ */ new Set();
|
|
197
196
|
group.add(principal);
|
|
198
|
-
tagged.set(
|
|
197
|
+
tagged.set(record.tag, group);
|
|
199
198
|
}
|
|
200
199
|
};
|
|
201
200
|
return {
|
|
202
201
|
of: (principal) => held.get(principal),
|
|
203
|
-
touch: (principal,
|
|
202
|
+
touch: (principal, entry, at) => {
|
|
204
203
|
held.delete(principal);
|
|
205
|
-
|
|
206
|
-
held.set(principal,
|
|
204
|
+
entry.lastSeen = at;
|
|
205
|
+
held.set(principal, entry);
|
|
207
206
|
},
|
|
208
207
|
forget,
|
|
209
208
|
remember,
|
|
@@ -217,14 +216,14 @@ var createHeldRecords = (max) => {
|
|
|
217
216
|
return principals;
|
|
218
217
|
},
|
|
219
218
|
forgetIdle: (at, idleMs) => {
|
|
220
|
-
for (const [principal,
|
|
221
|
-
if (at -
|
|
219
|
+
for (const [principal, entry] of [...held]) {
|
|
220
|
+
if (at - entry.lastSeen >= idleMs) {
|
|
222
221
|
forget(principal);
|
|
223
222
|
evicted += 1;
|
|
224
223
|
}
|
|
225
224
|
}
|
|
226
225
|
},
|
|
227
|
-
list: () => [...held].map(([principal,
|
|
226
|
+
list: () => [...held].map(([principal, entry]) => ({ principal, since: entry.since, lastSeen: entry.lastSeen })),
|
|
228
227
|
size: () => held.size,
|
|
229
228
|
evicted: () => evicted
|
|
230
229
|
};
|
|
@@ -256,11 +255,11 @@ var createIdentityCache = (ctx) => {
|
|
|
256
255
|
if (inFlight !== void 0) return inFlight.work;
|
|
257
256
|
const forgotten = /* @__PURE__ */ new Set();
|
|
258
257
|
const isStillOut = () => pending.get(principal)?.work === work;
|
|
259
|
-
const work = ctx.resolve(principal).then((
|
|
258
|
+
const work = ctx.resolve(principal).then((record) => {
|
|
260
259
|
resolved += 1;
|
|
261
|
-
const wearsForgottenTag =
|
|
262
|
-
if (isStillOut() && !wearsForgottenTag) held.remember(principal,
|
|
263
|
-
return
|
|
260
|
+
const wearsForgottenTag = record.tag !== void 0 && forgotten.has(record.tag);
|
|
261
|
+
if (isStillOut() && !wearsForgottenTag) held.remember(principal, record, now());
|
|
262
|
+
return record;
|
|
264
263
|
}).finally(() => {
|
|
265
264
|
if (isStillOut()) pending.delete(principal);
|
|
266
265
|
});
|
|
@@ -293,6 +292,7 @@ var createIdentityCache = (ctx) => {
|
|
|
293
292
|
};
|
|
294
293
|
};
|
|
295
294
|
var memoKey = (roles, installed) => `${[...roles].sort().join("\0")}\0\0${installed === void 0 ? "*" : [...installed].sort().join("\0")}`;
|
|
295
|
+
var NOBODY_USER_ID = "anonymous";
|
|
296
296
|
var assignedRoles = (assignments, principal) => principal === null ? ["public"] : assignments?.[principal] ?? ["public"];
|
|
297
297
|
var IdentityRecordSchema = z.looseObject({
|
|
298
298
|
roles: z.array(z.string()),
|
|
@@ -303,25 +303,25 @@ var IdentityRecordSchema = z.looseObject({
|
|
|
303
303
|
var recordRefusal = (issues) => new Error(
|
|
304
304
|
`moss: \`identity.resolve\` did not answer an identity record (${issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ")}). A record is { roles: string[], scope: {\u2026}, installed?: string[], tag?: string }.`
|
|
305
305
|
);
|
|
306
|
-
var resolveThrough = (
|
|
307
|
-
const role =
|
|
306
|
+
var resolveThrough = (seam, readAs) => async (principal) => {
|
|
307
|
+
const role = seam.as;
|
|
308
308
|
const read2 = async (fingerprint, scope) => {
|
|
309
309
|
if (role === void 0) throw new Error("moss: identity.read needs identity.as \u2014 name the charter role the reader executes as");
|
|
310
310
|
return readAs(role, fingerprint, scope);
|
|
311
311
|
};
|
|
312
|
-
const answered = IdentityRecordSchema.safeParse(await
|
|
312
|
+
const answered = IdentityRecordSchema.safeParse(await seam.resolve(principal, read2));
|
|
313
313
|
if (!answered.success) throw recordRefusal(answered.error.issues);
|
|
314
314
|
return answered.data;
|
|
315
315
|
};
|
|
316
316
|
var createIdentity = (config) => {
|
|
317
|
-
const
|
|
318
|
-
const cache =
|
|
317
|
+
const seam = config.seam;
|
|
318
|
+
const cache = seam === void 0 ? void 0 : createIdentityCache({ resolve: resolveThrough(seam, config.readAs), max: config.max, idleMs: config.idleMs, revalidateMs: config.revalidateMs });
|
|
319
319
|
const keys = /* @__PURE__ */ new WeakMap();
|
|
320
|
-
const keyOf2 = (
|
|
321
|
-
const hit = keys.get(
|
|
320
|
+
const keyOf2 = (record) => {
|
|
321
|
+
const hit = keys.get(record);
|
|
322
322
|
if (hit !== void 0) return hit;
|
|
323
|
-
const key = memoKey(
|
|
324
|
-
keys.set(
|
|
323
|
+
const key = memoKey(record.roles, record.installed);
|
|
324
|
+
keys.set(record, key);
|
|
325
325
|
return key;
|
|
326
326
|
};
|
|
327
327
|
const fromAssignments = (principal) => {
|
|
@@ -330,13 +330,13 @@ var createIdentity = (config) => {
|
|
|
330
330
|
};
|
|
331
331
|
const resolve2 = async (principal) => {
|
|
332
332
|
if (cache !== void 0 && principal !== null) {
|
|
333
|
-
const
|
|
334
|
-
return { roles:
|
|
333
|
+
const record = await cache.get(principal);
|
|
334
|
+
return { roles: record.roles, scope: record.scope, installed: record.installed, memoKey: keyOf2(record), record };
|
|
335
335
|
}
|
|
336
336
|
return fromAssignments(principal);
|
|
337
337
|
};
|
|
338
338
|
const composeScope = (principal, resolved) => ({
|
|
339
|
-
userId: principal ??
|
|
339
|
+
userId: principal ?? NOBODY_USER_ID,
|
|
340
340
|
...resolved.scope,
|
|
341
341
|
...config.scope?.(principal, resolved.record) ?? {}
|
|
342
342
|
});
|
|
@@ -351,1323 +351,1886 @@ var createIdentity = (config) => {
|
|
|
351
351
|
stop: () => cache?.stop()
|
|
352
352
|
};
|
|
353
353
|
};
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
354
|
+
|
|
355
|
+
// src/data/tables.ts
|
|
356
|
+
var GENERATION_DDL = [
|
|
357
|
+
/* sql */
|
|
358
|
+
`CREATE TABLE IF NOT EXISTS moss_generation (id INT PRIMARY KEY, n BIGINT NOT NULL DEFAULT 0)`,
|
|
359
|
+
/* sql */
|
|
360
|
+
`INSERT INTO moss_generation (id, n) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`
|
|
361
|
+
];
|
|
362
|
+
var MOSS_SEQUENCE = {
|
|
363
|
+
id: "nisc.moss",
|
|
364
|
+
migrations: [
|
|
365
|
+
{
|
|
366
|
+
description: "Integrations, their actions and the generation pointer, converged from any earlier shape",
|
|
367
|
+
steps: [
|
|
368
|
+
{ kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integrations (
|
|
369
|
+
id text PRIMARY KEY,
|
|
370
|
+
url text NOT NULL,
|
|
371
|
+
-- THE HASH, NEVER THE KEY. The integration key is minted at registration
|
|
372
|
+
-- (see assert.ts for the credential rule), returned once in that response,
|
|
373
|
+
-- and this is all that remains of it here. Presenting the key is the only
|
|
374
|
+
-- way to produce this value again, so a stolen database does not hold a
|
|
375
|
+
-- credential \u2014 and a lost key is re-registered, not recovered.
|
|
376
|
+
key_hash text,
|
|
377
|
+
status text NOT NULL DEFAULT 'pending',
|
|
378
|
+
-- The store card's words, straight from the bundle's meta. Columns
|
|
379
|
+
-- rather than jsonb so an app's vex read can select them like anything
|
|
380
|
+
-- else on this table.
|
|
381
|
+
title text NOT NULL DEFAULT '',
|
|
382
|
+
tagline text NOT NULL DEFAULT '',
|
|
383
|
+
description text NOT NULL DEFAULT '',
|
|
384
|
+
-- The listing page's long form, re-imported whole like everything else
|
|
385
|
+
-- about a bundle. press holds the URLS THE HOST ANSWERED WITH at
|
|
386
|
+
-- intake (copyPress), never the paths the bundle declared \u2014 the listing
|
|
387
|
+
-- composes from host ground alone.
|
|
388
|
+
story jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
389
|
+
highlights jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
390
|
+
press jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
391
|
+
-- WHAT APPEARS WHERE, as one derived sentence (describePlacements) \u2014
|
|
392
|
+
-- printed by the approval card and the store tile from this one place.
|
|
393
|
+
adds text NOT NULL DEFAULT '',
|
|
394
|
+
-- The one integration action the store may open: its settings screen.
|
|
395
|
+
settings_action text NOT NULL DEFAULT '',
|
|
396
|
+
requested_actions jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
397
|
+
requested_data jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
398
|
+
approved_data jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
399
|
+
-- What it tells and hears (bundle offers/needs), beside the grants
|
|
400
|
+
-- because they are the same kind of thing: the integration's declared
|
|
401
|
+
-- statement, written at import, replaced on re-registration. moss
|
|
402
|
+
-- never reads them; the host's bus does.
|
|
403
|
+
offers jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
404
|
+
needs jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
405
|
+
-- The verbs the integration gates on ({id, title}), for the host's role
|
|
406
|
+
-- editor to grant. Beside offers/needs because it is the same kind of
|
|
407
|
+
-- thing: a declaration written at import, replaced on re-registration,
|
|
408
|
+
-- that moss never reads \u2014 the host does.
|
|
409
|
+
capabilities jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
410
|
+
-- WHAT A BUILDER MAY SET per product \u2014 the closed-set field declaration,
|
|
411
|
+
-- beside capabilities because it is the same kind of thing: a declaration
|
|
412
|
+
-- written at import, replaced on re-registration, that moss never reads.
|
|
413
|
+
-- The host renders a settings form from it and stores the values itself.
|
|
414
|
+
configuration jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
415
|
+
-- WHAT AN ADD-ON LETS A PERSON EDIT \u2014 section types, fields, fragments,
|
|
416
|
+
-- and a section model the host's editor renders. Beside configuration
|
|
417
|
+
-- because it is the same kind of thing: a declaration written at import,
|
|
418
|
+
-- replaced on re-registration, that moss never reads \u2014 the host does.
|
|
419
|
+
documents jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
420
|
+
-- WHAT AN ADD-ON'S ASSISTANT KNOWS AND MAY DO \u2014 instructions, grounding,
|
|
421
|
+
-- blocks, tools, what it applies to. Same kind of thing, same lifecycle;
|
|
422
|
+
-- the host's assistant is the consumer.
|
|
423
|
+
assistants jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
424
|
+
-- EVERY PATH THE PROXY MAY FORWARD, derived from the bundle at intake
|
|
425
|
+
-- (reachOf). Beside the grants because it is one: a grant of reach, held
|
|
426
|
+
-- by the same row, revoked by the same delete.
|
|
427
|
+
reach jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
428
|
+
-- Pages this integration serves and the host frames. Kept apart from reach
|
|
429
|
+
-- because they are spent differently: reach is a screen's call carrying a
|
|
430
|
+
-- session, a frame is a document GET carrying a grant.
|
|
431
|
+
frames jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
432
|
+
last_import_at timestamptz,
|
|
433
|
+
last_error text
|
|
434
|
+
)
|
|
435
|
+
` },
|
|
436
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS reach jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
437
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS frames jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
438
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS phrasebook jsonb NOT NULL DEFAULT '{}'::jsonb` },
|
|
439
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS story jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
440
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS highlights jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
441
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS press jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
442
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS offers jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
443
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS needs jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
444
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS capabilities jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
445
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS configuration jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
446
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS documents jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
447
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN IF NOT EXISTS assistants jsonb NOT NULL DEFAULT '[]'::jsonb` },
|
|
448
|
+
{ kind: "sql", sql: `CREATE TABLE IF NOT EXISTS integration_actions (
|
|
449
|
+
integration_id text NOT NULL REFERENCES integrations(id) ON DELETE CASCADE,
|
|
450
|
+
action_id text NOT NULL,
|
|
451
|
+
definition jsonb NOT NULL,
|
|
452
|
+
-- The bindings, beside the artifact and never inside it: which host
|
|
453
|
+
-- action this one rides (a panel), or which menu hub lists it. Empty
|
|
454
|
+
-- means neither \u2014 reachable only through whatever else names it.
|
|
455
|
+
-- preview is the rider's display endpoint (own-prefix, validated at
|
|
456
|
+
-- intake): the host calls it with the offered ids to paint the strip.
|
|
457
|
+
attach_to text NOT NULL DEFAULT '',
|
|
458
|
+
preview text NOT NULL DEFAULT '',
|
|
459
|
+
place_in text NOT NULL DEFAULT '',
|
|
460
|
+
PRIMARY KEY (integration_id, action_id)
|
|
461
|
+
)
|
|
462
|
+
` },
|
|
463
|
+
...GENERATION_DDL.map((sql) => ({ kind: "sql", sql }))
|
|
464
|
+
]
|
|
465
|
+
},
|
|
466
|
+
{
|
|
467
|
+
description: "Stored integration actions carry the grammar stamp their definition is written in",
|
|
468
|
+
steps: [{ kind: "sql", sql: `ALTER TABLE integration_actions ADD COLUMN grammar jsonb NOT NULL DEFAULT '{}'::jsonb` }]
|
|
469
|
+
},
|
|
470
|
+
{
|
|
471
|
+
description: "No two integrations hold the hash of one key",
|
|
472
|
+
steps: [{ kind: "sql", sql: `CREATE UNIQUE INDEX integrations_key_hash_unique ON integrations (key_hash) WHERE key_hash IS NOT NULL` }]
|
|
473
|
+
},
|
|
474
|
+
{
|
|
475
|
+
description: "An integration keeps what its bundle says in the host app\u2019s own vocabulary as one value, and the columns of one product\u2019s vocabulary go",
|
|
476
|
+
steps: [
|
|
477
|
+
{ kind: "sql", sql: `ALTER TABLE integrations ADD COLUMN extension jsonb` },
|
|
478
|
+
{
|
|
479
|
+
kind: "sql",
|
|
480
|
+
sql: `ALTER TABLE integrations
|
|
481
|
+
DROP COLUMN IF EXISTS title,
|
|
482
|
+
DROP COLUMN IF EXISTS tagline,
|
|
483
|
+
DROP COLUMN IF EXISTS description,
|
|
484
|
+
DROP COLUMN IF EXISTS story,
|
|
485
|
+
DROP COLUMN IF EXISTS highlights,
|
|
486
|
+
DROP COLUMN IF EXISTS press,
|
|
487
|
+
DROP COLUMN IF EXISTS adds,
|
|
488
|
+
DROP COLUMN IF EXISTS settings_action,
|
|
489
|
+
DROP COLUMN IF EXISTS offers,
|
|
490
|
+
DROP COLUMN IF EXISTS needs,
|
|
491
|
+
DROP COLUMN IF EXISTS capabilities,
|
|
492
|
+
DROP COLUMN IF EXISTS configuration,
|
|
493
|
+
DROP COLUMN IF EXISTS documents,
|
|
494
|
+
DROP COLUMN IF EXISTS assistants,
|
|
495
|
+
DROP COLUMN IF EXISTS frames`
|
|
496
|
+
},
|
|
497
|
+
{
|
|
498
|
+
kind: "sql",
|
|
499
|
+
sql: `ALTER TABLE integration_actions
|
|
500
|
+
DROP COLUMN IF EXISTS attach_to,
|
|
501
|
+
DROP COLUMN IF EXISTS preview,
|
|
502
|
+
DROP COLUMN IF EXISTS place_in`
|
|
503
|
+
}
|
|
504
|
+
]
|
|
505
|
+
},
|
|
506
|
+
{
|
|
507
|
+
description: "The artifactory\u2019s two tables: a row for each save, and a row for each version of an artifact a save holds",
|
|
508
|
+
steps: [
|
|
509
|
+
{
|
|
510
|
+
kind: "sql",
|
|
511
|
+
sql: `CREATE TABLE artifact_saves (
|
|
512
|
+
id uuid PRIMARY KEY,
|
|
513
|
+
created_by text NOT NULL,
|
|
514
|
+
-- Whose the save is: the userId of whoever made it, written by vex.
|
|
515
|
+
principal text NOT NULL,
|
|
516
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
517
|
+
)`
|
|
518
|
+
},
|
|
519
|
+
{
|
|
520
|
+
kind: "sql",
|
|
521
|
+
sql: `CREATE TABLE artifacts (
|
|
522
|
+
save uuid NOT NULL REFERENCES artifact_saves(id),
|
|
523
|
+
kind text NOT NULL,
|
|
524
|
+
id text NOT NULL,
|
|
525
|
+
-- Whose the version is, as its save's.
|
|
526
|
+
principal text NOT NULL,
|
|
527
|
+
-- null, as SQL or as JSON: this version says none is in force.
|
|
528
|
+
body jsonb,
|
|
529
|
+
grammar jsonb NOT NULL DEFAULT '{}'::jsonb,
|
|
530
|
+
-- The save whose version of this artifact this one is a copy of.
|
|
531
|
+
copied_from uuid,
|
|
532
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
533
|
+
PRIMARY KEY (save, kind, id)
|
|
534
|
+
)`
|
|
535
|
+
},
|
|
536
|
+
// What is in force for an artifact is its latest row, and that is asked at every shell.
|
|
537
|
+
{ kind: "sql", sql: `CREATE INDEX artifacts_latest ON artifacts (principal, kind, id, created_at)` }
|
|
538
|
+
]
|
|
539
|
+
}
|
|
540
|
+
]
|
|
541
|
+
};
|
|
542
|
+
var ARTIFACT_TABLES = ["artifacts", "artifact_saves"];
|
|
543
|
+
var tableSequencesOf = (owners) => {
|
|
544
|
+
const cacheSequence = (owners.cache ?? createPostgresCache({ pool: owners.pool })).sequence;
|
|
545
|
+
return [
|
|
546
|
+
MOSS_SEQUENCE,
|
|
547
|
+
...owners.storesSessions ? [SESSIONS_SEQUENCE] : [],
|
|
548
|
+
...cacheSequence === void 0 ? [] : [cacheSequence],
|
|
549
|
+
...(owners.featureTables ?? []).flatMap((kept) => kept.sequences),
|
|
550
|
+
...owners.tables ?? []
|
|
551
|
+
];
|
|
552
|
+
};
|
|
553
|
+
var misfitOf = (entry, schema) => {
|
|
554
|
+
if (!("mutation" in entry)) {
|
|
555
|
+
try {
|
|
556
|
+
resolve(pruneOptional(entry.dsl, "all"), schema);
|
|
557
|
+
return void 0;
|
|
558
|
+
} catch (error) {
|
|
559
|
+
return error instanceof Error ? error.message : String(error);
|
|
560
|
+
}
|
|
359
561
|
}
|
|
360
|
-
|
|
361
|
-
for (const name of Object.keys(contracts)) names.add(name);
|
|
362
|
-
return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
|
|
562
|
+
return mutationMisfits(entry.mutation, schema)[0];
|
|
363
563
|
};
|
|
364
|
-
var
|
|
365
|
-
const
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const key = [...roles].sort().join("\0");
|
|
370
|
-
if (!seen.has(key)) seen.set(key, roles);
|
|
564
|
+
var misfitsOf = (entries, schema) => {
|
|
565
|
+
const misfits = /* @__PURE__ */ new Map();
|
|
566
|
+
for (const entry of entries) {
|
|
567
|
+
const why = misfitOf(entry, schema);
|
|
568
|
+
if (why !== void 0) misfits.set(entry.fingerprint, why);
|
|
371
569
|
}
|
|
372
|
-
return
|
|
570
|
+
return misfits;
|
|
373
571
|
};
|
|
374
|
-
var
|
|
375
|
-
|
|
376
|
-
|
|
572
|
+
var canonical = (value) => {
|
|
573
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
574
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
575
|
+
const keys = Object.keys(value).filter((key) => Reflect.get(value, key) !== void 0).sort();
|
|
576
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
|
|
377
577
|
};
|
|
378
|
-
var
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
return
|
|
578
|
+
var isSeededAs = async (cache, entry) => {
|
|
579
|
+
const held = await cache.get(entry.fingerprint);
|
|
580
|
+
if (held === void 0 || held.protected !== true) return false;
|
|
581
|
+
if ("mutation" in entry) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry.mutation);
|
|
582
|
+
return held.kind === "ok" && canonical(held.dsl) === canonical(entry.dsl);
|
|
382
583
|
};
|
|
383
|
-
var
|
|
384
|
-
const
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
584
|
+
var changesBetween = (before, after) => {
|
|
585
|
+
const removed = [];
|
|
586
|
+
const retyped = [];
|
|
587
|
+
for (const was of before.entities) {
|
|
588
|
+
const now = after.entities.find((entity) => entity.table === was.table);
|
|
589
|
+
if (now === void 0) {
|
|
590
|
+
removed.push(was.table);
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
for (const field of was.fields) {
|
|
594
|
+
const kept = now.fields.find((f) => f.name === field.name);
|
|
595
|
+
if (kept === void 0) removed.push(`${was.table}.${field.name}`);
|
|
596
|
+
else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
|
|
597
|
+
}
|
|
388
598
|
}
|
|
389
|
-
return
|
|
390
|
-
};
|
|
391
|
-
var resolveVariantsForRoles = (app, roles) => {
|
|
392
|
-
const variants = app.layouts ?? {};
|
|
393
|
-
return variantLayouts(variants, resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
|
|
599
|
+
return { removed, retyped };
|
|
394
600
|
};
|
|
395
|
-
var
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(withVariants(actions, ids, variants)));
|
|
402
|
-
var createRoleMemo = (config) => {
|
|
403
|
-
const catalogs = /* @__PURE__ */ new Map();
|
|
404
|
-
const variants = /* @__PURE__ */ new Map();
|
|
405
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
406
|
-
const kept = (memo, key, resolve2) => {
|
|
407
|
-
const hit = memo.get(key);
|
|
408
|
-
if (hit !== void 0) return hit;
|
|
409
|
-
const resolved = resolve2();
|
|
410
|
-
memo.set(key, resolved);
|
|
411
|
-
return resolved;
|
|
412
|
-
};
|
|
413
|
-
const roleMemo = {
|
|
414
|
-
catalogFor: (roles, installed) => kept(catalogs, memoKey(roles, installed), () => catalogFor(config.manifest(), roles, installed, config.installedOnly)),
|
|
415
|
-
variantsFor: (roles) => kept(variants, memoKey(roles, void 0), () => resolveVariantsForRoles(config.manifest(), roles)),
|
|
416
|
-
definitionsFor: (roles, installed) => kept(definitions, memoKey(roles, installed), () => definitionsFor(config.manifest().actions, roleMemo.catalogFor(roles, installed).ids, roleMemo.variantsFor(roles))),
|
|
417
|
-
drop: () => {
|
|
418
|
-
catalogs.clear();
|
|
419
|
-
variants.clear();
|
|
420
|
-
definitions.clear();
|
|
421
|
-
}
|
|
601
|
+
var oneAtATime = (query) => {
|
|
602
|
+
let last = Promise.resolve();
|
|
603
|
+
return (text, values) => {
|
|
604
|
+
const next = last.then(() => query(text, values));
|
|
605
|
+
last = next.catch(() => void 0);
|
|
606
|
+
return next;
|
|
422
607
|
};
|
|
423
|
-
return roleMemo;
|
|
424
|
-
};
|
|
425
|
-
var versionToken = (ids) => {
|
|
426
|
-
const s = ids.join("\n");
|
|
427
|
-
let h = 2166136261;
|
|
428
|
-
for (let i = 0; i < s.length; i += 1) {
|
|
429
|
-
h ^= s.charCodeAt(i);
|
|
430
|
-
h = Math.imul(h, 16777619) >>> 0;
|
|
431
|
-
}
|
|
432
|
-
return h.toString(16).padStart(8, "0");
|
|
433
608
|
};
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
entries: inForce.entries,
|
|
443
|
-
profiles: scopeProfiles(shipped.behaviors ?? {})
|
|
444
|
-
});
|
|
445
|
-
var unreadActions = (actions) => Object.entries(actions).flatMap(([id, definition]) => {
|
|
446
|
-
if (exceedsDepth(definition)) return [{ id, why: depthRefusal() }];
|
|
447
|
-
const parsed = ActionDefinitionSchema.safeParse(definition);
|
|
448
|
-
if (parsed.success) return [];
|
|
449
|
-
const first = parsed.error.issues[0];
|
|
450
|
-
return [{ id, why: first === void 0 ? "no reason given" : `${first.path.join(".") || "(root)"}: ${first.message}` }];
|
|
451
|
-
});
|
|
452
|
-
var reachErrors = (entries, profiles) => {
|
|
453
|
-
const unknown = entries.flatMap((entry2) => entry2.reach !== void 0 && !profiles.has(entry2.reach) ? [`${entry2.fingerprint} declares reach "${entry2.reach}"`] : []);
|
|
454
|
-
return unknown.length === 0 ? [] : [...unknown, `known profiles: ${[...profiles].join(", ") || "(none)"}`];
|
|
455
|
-
};
|
|
456
|
-
var endlessChains = (actions) => chainCycles(actions).map((cycle) => ({ path: cycle.path, through: cycle.steps.map((step) => step.action) }));
|
|
457
|
-
var verifyManifest = (candidate) => {
|
|
458
|
-
const unread = unreadActions(candidate.actions);
|
|
459
|
-
const refused = new Set(unread.map((action) => action.id));
|
|
460
|
-
const read2 = refused.size === 0 ? candidate : { ...candidate, actions: Object.fromEntries(Object.entries(candidate.actions).filter(([id]) => !refused.has(id))) };
|
|
461
|
-
const charter = verifyCharter(
|
|
462
|
-
read2.charter,
|
|
463
|
-
{ actions: Object.keys(read2.actions), data: read2.grants, layouts: Object.keys(read2.layouts) },
|
|
464
|
-
read2.wearable,
|
|
465
|
-
auditClosure(read2.actions, read2.layouts)
|
|
466
|
-
);
|
|
467
|
-
const found = (check, details) => details.map((detail) => ({ check, detail }));
|
|
468
|
-
return {
|
|
469
|
-
errors: [
|
|
470
|
-
...found("actions", unread.map((action) => `"${action.id}" is not an action nova reads: ${action.why}`)),
|
|
471
|
-
...found("charter", charter.errors.map((error) => `${error.rule}: ${error.detail}`)),
|
|
472
|
-
...found("reach", reachErrors(read2.entries, read2.profiles)),
|
|
473
|
-
...found("variants", verifyVariants(read2))
|
|
474
|
-
],
|
|
475
|
-
said: endlessChains(read2.actions).map((chain) => `a chain of steps that never ends: ${chain.path} \u2014 nova stops it at its budget when it runs (RUNAWAY_CHAIN)`),
|
|
476
|
-
charter
|
|
477
|
-
};
|
|
478
|
-
};
|
|
479
|
-
var verifyApp = (app, grants) => verifyManifest(candidateOf(app, { actions: app.actions, entries: entriesOf(app) }, grants));
|
|
480
|
-
var HEADLINES = {
|
|
481
|
-
boot: {
|
|
482
|
-
actions: "Actions are not ones nova reads \u2014 refusing to serve:",
|
|
483
|
-
charter: "Charter is incoherent \u2014 refusing to serve:",
|
|
484
|
-
reach: "Entries declare a reach no table offers \u2014 refusing to serve:",
|
|
485
|
-
variants: "Layout variants are incoherent \u2014 refusing to serve:"
|
|
486
|
-
},
|
|
487
|
-
refresh: {
|
|
488
|
-
actions: "Refresh refused \u2014 actions nova does not read:",
|
|
489
|
-
charter: "Refresh refused \u2014 charter incoherent over the new artifacts:",
|
|
490
|
-
reach: "Refresh refused \u2014 entries declare a reach no table offers:",
|
|
491
|
-
variants: "Refresh refused \u2014 layout variants incoherent:"
|
|
492
|
-
}
|
|
493
|
-
};
|
|
494
|
-
var refusalOf = (report, moment) => {
|
|
495
|
-
const first = report.errors[0];
|
|
496
|
-
if (first === void 0) return void 0;
|
|
497
|
-
const findings = report.errors.filter((error) => error.check === first.check).map((error) => ` ${error.detail}`);
|
|
498
|
-
return [HEADLINES[moment][first.check], ...findings].join("\n");
|
|
499
|
-
};
|
|
500
|
-
var verifyVariants = (app) => {
|
|
501
|
-
const variants = app.layouts ?? {};
|
|
502
|
-
const ids = Object.keys(variants);
|
|
503
|
-
if (ids.length === 0) return [];
|
|
504
|
-
const errors = [];
|
|
505
|
-
for (const [id, variant] of Object.entries(variants)) {
|
|
506
|
-
if (app.actions[variant.action] === void 0) {
|
|
507
|
-
errors.push(`layout variant "${id}" reshapes unknown action "${variant.action}"`);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
const wearers = /* @__PURE__ */ new Map();
|
|
511
|
-
for (const role of Object.keys(app.charter)) wearers.set(`role "${role}"`, [role]);
|
|
512
|
-
for (const roles of wearableOf(app)) wearers.set(`the combination [${[...roles].join(", ")}]`, roles);
|
|
513
|
-
wearers.set("the anonymous principal", ["public"]);
|
|
514
|
-
for (const [who, roles] of wearers) {
|
|
515
|
-
let granted;
|
|
516
|
-
try {
|
|
517
|
-
granted = resolvePrincipal(app.charter, ids, roles, "layouts");
|
|
518
|
-
} catch {
|
|
519
|
-
continue;
|
|
520
|
-
}
|
|
521
|
-
const byAction = /* @__PURE__ */ new Map();
|
|
522
|
-
for (const id of granted) {
|
|
523
|
-
const variant = variants[id];
|
|
524
|
-
if (variant !== void 0) byAction.set(variant.action, [...byAction.get(variant.action) ?? [], id]);
|
|
525
|
-
}
|
|
526
|
-
for (const [action, held] of byAction) {
|
|
527
|
-
if (held.length > 1) {
|
|
528
|
-
errors.push(`${who} holds ${held.length} variants of "${action}" (${held.sort().join(", ")}) \u2014 one variant per action per principal`);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
609
|
+
var migrateTables = async (runtime, app, options = {}) => {
|
|
610
|
+
const entries = entriesOf(app);
|
|
611
|
+
const cache = runtime.cache ?? createPostgresCache({ pool: runtime.pool });
|
|
612
|
+
const before = await createPostgresAdapter({ pool: runtime.pool }).introspect();
|
|
613
|
+
const misfitsBefore = misfitsOf(entries, before);
|
|
614
|
+
const excused = /* @__PURE__ */ new Set();
|
|
615
|
+
for (const entry of entries) {
|
|
616
|
+
if (misfitsBefore.has(entry.fingerprint) && await isSeededAs(cache, entry).catch(() => false)) excused.add(entry.fingerprint);
|
|
531
617
|
}
|
|
532
|
-
|
|
533
|
-
};
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
})
|
|
544
|
-
)
|
|
545
|
-
];
|
|
546
|
-
const issues = [];
|
|
547
|
-
for (const definition of granted) {
|
|
548
|
-
const audit = auditAction(definition, { catalog, channels });
|
|
549
|
-
if (audit.ok) continue;
|
|
550
|
-
for (const issue of audit.issues) {
|
|
551
|
-
if (issue.includes("which is not in the catalog") && !issue.includes("{{")) issues.push(`${definition.id}: ${issue}`);
|
|
618
|
+
let found = { removed: [], retyped: [], alreadyBroken: [] };
|
|
619
|
+
const owners = { pool: runtime.pool, cache: runtime.cache, storesSessions: runtime.session === "sessions", featureTables: featureTablesOf(app), tables: runtime.tables };
|
|
620
|
+
const report = await migrate(runtime.pool, tableSequencesOf(owners), {
|
|
621
|
+
...options.dryRun === true ? { dryRun: true } : {},
|
|
622
|
+
guard: async (tx) => {
|
|
623
|
+
const after = await createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
|
|
624
|
+
const refused = [];
|
|
625
|
+
const alreadyBroken = [];
|
|
626
|
+
for (const [fingerprint, why] of misfitsOf(entries, after)) {
|
|
627
|
+
if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
|
|
628
|
+
else refused.push(`${fingerprint}: ${why}`);
|
|
552
629
|
}
|
|
630
|
+
found = { ...changesBetween(before, after), alreadyBroken };
|
|
631
|
+
return refused;
|
|
553
632
|
}
|
|
554
|
-
|
|
555
|
-
};
|
|
633
|
+
});
|
|
634
|
+
return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
|
|
556
635
|
};
|
|
557
|
-
var
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
if (typeof name !== "string") return;
|
|
563
|
-
const spec = components.get(name);
|
|
564
|
-
if (spec === void 0) {
|
|
565
|
-
found.add(`layout uses "${name}", which this app has no component for`);
|
|
566
|
-
return;
|
|
567
|
-
}
|
|
568
|
-
const schema = spec.propsSchema;
|
|
569
|
-
const props = record2["props"];
|
|
570
|
-
if (!(schema instanceof z.ZodObject) || !isRecord(props)) return;
|
|
571
|
-
const shape = schema.shape;
|
|
572
|
-
for (const [key, value] of Object.entries(props)) {
|
|
573
|
-
const prop = shape[key];
|
|
574
|
-
if (prop === void 0) {
|
|
575
|
-
found.add(`"${name}" has no prop "${key}"`);
|
|
576
|
-
continue;
|
|
577
|
-
}
|
|
578
|
-
if (isDeferred(value)) continue;
|
|
579
|
-
const check = z.safeParse(prop, value);
|
|
580
|
-
if (!check.success) found.add(`"${name}" prop "${key}" \u2014 ${check.error.issues[0]?.message ?? "invalid"}`);
|
|
636
|
+
var featureTablesOf = (app) => {
|
|
637
|
+
const features = /* @__PURE__ */ new Set();
|
|
638
|
+
return (app.features ?? []).map((feature) => {
|
|
639
|
+
if (features.has(feature.name)) {
|
|
640
|
+
throw new Error(`moss: two features are named "${feature.name}". A feature's name says whose a table and a set of actions are, so no two features of an app share one.`);
|
|
581
641
|
}
|
|
642
|
+
features.add(feature.name);
|
|
643
|
+
const names = feature.tables?.names ?? [];
|
|
644
|
+
return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
|
|
582
645
|
});
|
|
583
|
-
return [...found];
|
|
584
646
|
};
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
if (checking) return;
|
|
596
|
-
checking = true;
|
|
597
|
-
try {
|
|
598
|
-
const n = await readPointer();
|
|
599
|
-
if (n === void 0 || n === seen) return;
|
|
600
|
-
if (seen !== -1 && !await follow(n)) return;
|
|
601
|
-
seen = n;
|
|
602
|
-
} finally {
|
|
603
|
-
checking = false;
|
|
604
|
-
}
|
|
605
|
-
};
|
|
606
|
-
const readPointer = async () => {
|
|
607
|
-
try {
|
|
608
|
-
return await pointer.read();
|
|
609
|
-
} catch (err) {
|
|
610
|
-
console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
|
|
611
|
-
return void 0;
|
|
612
|
-
}
|
|
613
|
-
};
|
|
614
|
-
let unfollowed;
|
|
615
|
-
const follow = async (n) => {
|
|
616
|
-
try {
|
|
617
|
-
await ctx.onMoved();
|
|
618
|
-
} catch (err) {
|
|
619
|
-
const what = `the generation pointer moved (${seen} \u2192 ${n}) and this process could not follow it: ${err instanceof Error ? err.message : String(err)}`;
|
|
620
|
-
if (unfollowed?.said !== what) {
|
|
621
|
-
console.error(`[moss:generation] ${what} \u2014 it is serving what it had, and tries again at every look; this is said again only when it changes`, err);
|
|
622
|
-
}
|
|
623
|
-
unfollowed = { said: what, tries: (unfollowed?.tries ?? 0) + 1 };
|
|
624
|
-
return false;
|
|
625
|
-
}
|
|
626
|
-
if (unfollowed !== void 0) {
|
|
627
|
-
console.log(
|
|
628
|
-
`[moss:generation] followed the generation pointer to ${n}, after ${unfollowed.tries} ${unfollowed.tries === 1 ? "look" : "looks"} that failed \u2014 this process serves what the rows say again`
|
|
629
|
-
);
|
|
630
|
-
unfollowed = void 0;
|
|
631
|
-
}
|
|
632
|
-
return true;
|
|
647
|
+
var isWrittenForRequest = (entry) => entry.kind === "unsatisfiable" || entry.requestHash !== void 0;
|
|
648
|
+
var createEntryCache = (table) => {
|
|
649
|
+
let held;
|
|
650
|
+
const fromTable = (entry) => entry !== void 0 && isWrittenForRequest(entry) ? entry : void 0;
|
|
651
|
+
const tableEntries = async () => {
|
|
652
|
+
const rows = table.entries !== void 0 ? await table.entries() : await Promise.all((await table.keys()).map(async (key) => ({ key, entry: await table.get(key) })));
|
|
653
|
+
return rows.flatMap(({ key, entry }) => {
|
|
654
|
+
const kept = fromTable(entry);
|
|
655
|
+
return kept === void 0 ? [] : [{ key, entry: kept }];
|
|
656
|
+
});
|
|
633
657
|
};
|
|
634
|
-
const
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
if (seen === n || seen === -1) seen = n + 1;
|
|
639
|
-
return;
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
throw new Error(`the pointer moved under this process ${MOVE_ATTEMPTS} times in a row`);
|
|
658
|
+
const entries = async () => {
|
|
659
|
+
const first = await held?.entries() ?? [];
|
|
660
|
+
const answered = new Set(first.map((row) => row.key));
|
|
661
|
+
return [...first, ...(await tableEntries()).filter((row) => !answered.has(row.key))];
|
|
643
662
|
};
|
|
644
|
-
void poll();
|
|
645
|
-
const timer = everyMs > 0 && everyMs <= MAX_INTERVAL_MS ? setInterval(() => void poll(), everyMs) : void 0;
|
|
646
|
-
timer?.unref?.();
|
|
647
663
|
return {
|
|
648
|
-
|
|
649
|
-
|
|
664
|
+
askFirst: (holder) => {
|
|
665
|
+
held = holder;
|
|
650
666
|
},
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
667
|
+
cache: {
|
|
668
|
+
get: async (key, scope) => await held?.get(key, scope) ?? fromTable(await table.get(key)),
|
|
669
|
+
// Vex stamps an entry it replays by writing it back: one that was not written for a request is not the table's to keep.
|
|
670
|
+
set: async (key, entry) => {
|
|
671
|
+
if (isWrittenForRequest(entry)) await table.set(key, entry);
|
|
672
|
+
},
|
|
673
|
+
delete: (key) => table.delete(key),
|
|
674
|
+
clear: () => table.clear(),
|
|
675
|
+
keys: async () => (await entries()).map((row) => row.key),
|
|
676
|
+
entries
|
|
654
677
|
}
|
|
655
678
|
};
|
|
656
679
|
};
|
|
657
|
-
var
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
dsl: depthChecked(QuerySchema),
|
|
687
|
-
mapping: depthChecked(ConfigSchema).optional(),
|
|
688
|
-
refresh: z.enum(REFRESH_MODES).optional()
|
|
689
|
-
}).strict();
|
|
690
|
-
var WriteEntrySchema = z.object({ ...entry, mutation: depthChecked(MutationDefinitionSchema) }).strict();
|
|
691
|
-
var FeatureSchema = z.looseObject({
|
|
692
|
-
name: z.string(),
|
|
693
|
-
tables: z.object({ names: strings, sequences: z.array(SequenceSchema).readonly().optional() }).strict().optional(),
|
|
694
|
-
start: seam
|
|
680
|
+
var createDataLayer = async (deps) => {
|
|
681
|
+
const adapter = createPostgresAdapter({ pool: deps.pool });
|
|
682
|
+
const table = deps.cache ?? createPostgresCache({ pool: deps.pool });
|
|
683
|
+
await table.init?.();
|
|
684
|
+
const { cache, askFirst } = createEntryCache(table);
|
|
685
|
+
const engine = createQueryEngine({ adapter, cache, ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {} });
|
|
686
|
+
const schema = await engine.introspect();
|
|
687
|
+
return { engine, adapter, schema, grants: scopeGrants(schema.entities.map((e) => e.name)), askFirst };
|
|
688
|
+
};
|
|
689
|
+
var grammarsOf = (app) => [
|
|
690
|
+
NOVA_SEQUENCE,
|
|
691
|
+
PRISM_SEQUENCE,
|
|
692
|
+
VEX_SEQUENCE,
|
|
693
|
+
...app.grammars ?? []
|
|
694
|
+
];
|
|
695
|
+
var createGrammarUpgrader = (app) => createUpgrader(grammarsOf(app), { transform: evaluate });
|
|
696
|
+
var vexRecordToSpan = (rec) => ({
|
|
697
|
+
name: "vex.execute",
|
|
698
|
+
startUnixNano: rec.startUnixNano,
|
|
699
|
+
endUnixNano: rec.endUnixNano,
|
|
700
|
+
status: rec.status,
|
|
701
|
+
attributes: {
|
|
702
|
+
op: rec.kind,
|
|
703
|
+
hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
|
|
704
|
+
...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
|
|
705
|
+
...rec.reach !== void 0 ? { reach: rec.reach } : {},
|
|
706
|
+
...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
|
|
707
|
+
...rec.rows !== void 0 ? { rows: rec.rows } : {}
|
|
708
|
+
}
|
|
695
709
|
});
|
|
696
|
-
var
|
|
697
|
-
var
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
const parsed = ManifestSchema.safeParse(app);
|
|
731
|
-
if (parsed.success) return [];
|
|
732
|
-
return parsed.error.issues.flatMap((issue) => placesOf(issue, [])).map((place) => `${place.path.map(String).join(".") || "(the manifest)"}: ${place.message}`);
|
|
733
|
-
};
|
|
734
|
-
var isData = (value) => {
|
|
735
|
-
if (Array.isArray(value)) return true;
|
|
736
|
-
const made = Object.getPrototypeOf(value);
|
|
737
|
-
return made === Object.prototype || made === null;
|
|
738
|
-
};
|
|
739
|
-
var freezeDeep = (data) => {
|
|
740
|
-
const seen = /* @__PURE__ */ new Set();
|
|
741
|
-
const pending = [data];
|
|
742
|
-
while (pending.length > 0) {
|
|
743
|
-
const value = pending.pop();
|
|
744
|
-
if (typeof value !== "object" || value === null || !isData(value) || seen.has(value)) continue;
|
|
745
|
-
seen.add(value);
|
|
746
|
-
Object.freeze(value);
|
|
747
|
-
for (const inner of Object.values(value)) pending.push(inner);
|
|
748
|
-
}
|
|
749
|
-
};
|
|
750
|
-
var receiveManifest = (app) => {
|
|
751
|
-
const misfits = manifestMisfits(app);
|
|
752
|
-
if (misfits.length > 0) throw new Error(["The manifest does not parse \u2014 refusing to serve:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
|
|
753
|
-
freezeDeep(app);
|
|
710
|
+
var resultOf = (body) => body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
|
|
711
|
+
var messageOf = (body) => body !== null && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : "no reason given";
|
|
712
|
+
var createOwnEntries = (deps) => async (own) => {
|
|
713
|
+
const cache = createMemoryCache();
|
|
714
|
+
await seedCache(cache, own.entries);
|
|
715
|
+
const schema = await deps.adapter.introspect({ entities: [...own.tables] });
|
|
716
|
+
const engine = createQueryEngine({
|
|
717
|
+
adapter: { id: deps.adapter.id, compile: deps.adapter.compile, execute: deps.adapter.execute, capabilities: deps.adapter.capabilities, introspect: async () => schema },
|
|
718
|
+
cache
|
|
719
|
+
});
|
|
720
|
+
await engine.introspect();
|
|
721
|
+
const policy = { default: "deny", entities: Object.fromEntries(own.tables.map((table) => [table, own.rules?.[table] ?? { public: true }])) };
|
|
722
|
+
const reachable = new Set((await handleDiscovery({ engine, locked: true, scopePolicy: policy })).fingerprints.map((listed2) => listed2.fingerprint));
|
|
723
|
+
const outside = own.entries.map((entry) => entry.fingerprint).filter((fingerprint) => !reachable.has(fingerprint));
|
|
724
|
+
if (outside.length > 0) {
|
|
725
|
+
throw new Error(
|
|
726
|
+
`moss: ${own.owner} handed over ${outside.length === 1 ? "an entry that reads or writes" : "entries that read or write"} a table that is not its own: ${outside.map((fingerprint) => `"${fingerprint}"`).join(", ")}. Its own entries run outside the app's policy, so they reach ${own.tables.length === 0 ? "no table, because it names none as its own" : `the tables that are its own (${own.tables.join(", ")}) and no other`}. What another table holds is read through the app's entries, under the charter.`
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
return async (fingerprint, context, scope = {}) => {
|
|
730
|
+
const outcome = await handleQuery(
|
|
731
|
+
{
|
|
732
|
+
engine,
|
|
733
|
+
locked: true,
|
|
734
|
+
scopePolicy: policy,
|
|
735
|
+
mutations: { client: deps.db, policy, onWrite: (event) => deps.engine.invalidate(tablesChangedBy(event.writes, schema)) },
|
|
736
|
+
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
|
|
737
|
+
},
|
|
738
|
+
{ fingerprint, context },
|
|
739
|
+
scope
|
|
740
|
+
);
|
|
741
|
+
if (outcome.status !== 200) throw new Error(`moss: the entry "${fingerprint}" was refused (${outcome.status}): ${messageOf(outcome.body)}`);
|
|
742
|
+
return resultOf(outcome.body);
|
|
743
|
+
};
|
|
754
744
|
};
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
var
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
745
|
+
var TABLE = "moss_generation";
|
|
746
|
+
var THE_ROW = { eq: [`${TABLE}.id`, 1] };
|
|
747
|
+
var readPointerEntry = {
|
|
748
|
+
fingerprint: "moss/generation",
|
|
749
|
+
intent: "Where the generation pointer is",
|
|
750
|
+
dsl: { from: [TABLE], fields: [`${TABLE}.n`], filter: THE_ROW, limit: 1 }
|
|
751
|
+
};
|
|
752
|
+
var movePointerEntry = {
|
|
753
|
+
fingerprint: "moss/generation-move",
|
|
754
|
+
intent: "Move the generation pointer to the next number, if it is still where it was read",
|
|
755
|
+
mutation: {
|
|
756
|
+
op: "update",
|
|
757
|
+
table: TABLE,
|
|
758
|
+
set: { n: { $context: "next" } },
|
|
759
|
+
where: { and: [THE_ROW, { eq: [`${TABLE}.n`, { $context: "seen" }] }] }
|
|
763
760
|
}
|
|
764
761
|
};
|
|
765
|
-
var
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
762
|
+
var POINTER = { owner: "the generation pointer", entries: [readPointerEntry, movePointerEntry], tables: [TABLE] };
|
|
763
|
+
var RowSchema = z.object({ n: z.coerce.number() });
|
|
764
|
+
var RowsSchema = z.array(z.unknown());
|
|
765
|
+
var createPointer = (replay) => ({
|
|
766
|
+
read: async () => {
|
|
767
|
+
const rows = RowsSchema.parse(await (await replay())(readPointerEntry.fingerprint, {}));
|
|
768
|
+
return RowSchema.parse(rows[0] ?? { n: 0 }).n;
|
|
769
|
+
},
|
|
770
|
+
// A write that changed one row answers that row; one that changed none
|
|
771
|
+
// answers no row, which does not parse: the counter moved since it was read.
|
|
772
|
+
move: async (from) => RowSchema.safeParse(await (await replay())(movePointerEntry.fingerprint, { seen: from, next: from + 1 })).success
|
|
773
|
+
});
|
|
774
|
+
var resolvePolicyForRoles = (app, grants, roles) => {
|
|
775
|
+
const behaviors = app.behaviors ?? {};
|
|
776
|
+
return mergeScopePolicies(
|
|
777
|
+
roles.map(
|
|
778
|
+
(role) => createScopePolicy(resolvePrincipal(app.charter, grants, [role], "data"), behaviors, resolveScoping(app.charter, role))
|
|
779
|
+
)
|
|
780
|
+
);
|
|
781
|
+
};
|
|
782
|
+
var resolvePolicyAtReachForRoles = (app, grants, roles, reach) => createScopePolicy(resolvePrincipal(app.charter, grants, roles, "data"), app.behaviors ?? {}, reach);
|
|
783
|
+
var createPolicies = (config) => {
|
|
784
|
+
const { grants } = config;
|
|
785
|
+
const governed = { charter: config.charter, behaviors: config.behaviors };
|
|
786
|
+
const policies = /* @__PURE__ */ new Map();
|
|
787
|
+
const reachPolicies = /* @__PURE__ */ new Map();
|
|
771
788
|
return {
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
789
|
+
of: (who) => {
|
|
790
|
+
const hit = policies.get(who.memoKey);
|
|
791
|
+
if (hit !== void 0) return hit;
|
|
792
|
+
const compiled = resolvePolicyForRoles(governed, grants, who.roles);
|
|
793
|
+
policies.set(who.memoKey, compiled);
|
|
794
|
+
return compiled;
|
|
778
795
|
},
|
|
779
|
-
|
|
780
|
-
const
|
|
781
|
-
|
|
782
|
-
return
|
|
796
|
+
atReach: (who, reach) => {
|
|
797
|
+
const key = `${who.memoKey}\0${reach}`;
|
|
798
|
+
const hit = reachPolicies.get(key);
|
|
799
|
+
if (hit !== void 0) return hit;
|
|
800
|
+
const compiled = resolvePolicyAtReachForRoles(governed, grants, who.roles, reach);
|
|
801
|
+
reachPolicies.set(key, compiled);
|
|
802
|
+
return compiled;
|
|
803
|
+
},
|
|
804
|
+
drop: () => {
|
|
805
|
+
policies.clear();
|
|
806
|
+
reachPolicies.clear();
|
|
783
807
|
}
|
|
784
808
|
};
|
|
785
809
|
};
|
|
786
|
-
var
|
|
787
|
-
const
|
|
788
|
-
|
|
789
|
-
const
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
const kept = components.get(shell2);
|
|
798
|
-
if (kept !== void 0) return kept;
|
|
799
|
-
const names = read2(shell2);
|
|
800
|
-
components.set(shell2, names);
|
|
801
|
-
return names;
|
|
810
|
+
var createExecuteAs = (deps) => async (role, fingerprint, context, scope = {}) => {
|
|
811
|
+
const roles = [role];
|
|
812
|
+
const policy = deps.policyFor(roles);
|
|
813
|
+
const outcome = await handleQuery(
|
|
814
|
+
{
|
|
815
|
+
engine: deps.engine,
|
|
816
|
+
locked: true,
|
|
817
|
+
scopePolicy: policy,
|
|
818
|
+
policyForReach: (reach) => deps.policyAtReach(roles, reach),
|
|
819
|
+
mutations: { client: deps.db, policy },
|
|
820
|
+
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
|
|
802
821
|
},
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
822
|
+
{ fingerprint, context },
|
|
823
|
+
scope
|
|
824
|
+
);
|
|
825
|
+
if (outcome.status !== 200) {
|
|
826
|
+
console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
|
|
827
|
+
return void 0;
|
|
828
|
+
}
|
|
829
|
+
const body = outcome.body;
|
|
830
|
+
return body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
|
|
807
831
|
};
|
|
808
|
-
var
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
const
|
|
815
|
-
let sets = /* @__PURE__ */ new Map();
|
|
816
|
-
let inForce = mergedActions(own, sets);
|
|
817
|
-
let report = verifiedAtBoot(candidate(inForce));
|
|
818
|
-
const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
|
|
819
|
-
const roleMemo = createRoleMemo({
|
|
820
|
-
manifest: () => ({ charter: shipped.charter, actions: inForce, layouts: shipped.layouts }),
|
|
821
|
-
installedOnly: (ids, installed) => catalogFilters.reduce((kept, narrow) => narrowedBy(narrow, kept, installed), ids)
|
|
822
|
-
});
|
|
823
|
-
const components = createComponentNames((shell2) => shellComponents({ actions: inForce, layouts: shipped.layouts }, shell2));
|
|
824
|
-
const byFingerprint = new Map(entries.map((entry2) => [entry2.fingerprint, entry2]));
|
|
832
|
+
var CREDENTIALS = /* @__PURE__ */ new Set(["authorization", "cookie", "proxy-authorization"]);
|
|
833
|
+
var writeRequestOf = (header) => ({
|
|
834
|
+
header: (name) => CREDENTIALS.has(name.toLowerCase()) ? void 0 : header(name)
|
|
835
|
+
});
|
|
836
|
+
var SAID_NOTHING = { header: () => void 0 };
|
|
837
|
+
var createWriteNotifier = () => {
|
|
838
|
+
const requests = new AsyncLocalStorage();
|
|
825
839
|
const listeners = /* @__PURE__ */ new Set();
|
|
826
|
-
let pointer;
|
|
827
|
-
const applySets = (arrived, announce) => {
|
|
828
|
-
const next = new Map([...sets, ...arrived]);
|
|
829
|
-
const actions = mergedActions(own, next);
|
|
830
|
-
const verified = verifyManifest(candidate(actions));
|
|
831
|
-
const refusal = refusalOf(verified, "refresh");
|
|
832
|
-
if (refusal !== void 0) throw new Error(refusal);
|
|
833
|
-
for (const set of arrived.values()) freezeDeep(set);
|
|
834
|
-
sets = next;
|
|
835
|
-
inForce = actions;
|
|
836
|
-
report = verified;
|
|
837
|
-
roleMemo.drop();
|
|
838
|
-
components.drop();
|
|
839
|
-
for (const listener of [...listeners]) tell(listener);
|
|
840
|
-
if (announce) pointer?.bump();
|
|
841
|
-
};
|
|
842
|
-
const reload = async () => {
|
|
843
|
-
const read2 = [];
|
|
844
|
-
for (const [source, load] of loaders) read2.push([source, await load()]);
|
|
845
|
-
applySets(new Map(read2), false);
|
|
846
|
-
};
|
|
847
840
|
return {
|
|
848
|
-
|
|
849
|
-
entries: () => entries,
|
|
850
|
-
verify: (actions) => verifyManifest(candidate(actions)),
|
|
851
|
-
report: () => report,
|
|
852
|
-
replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
|
|
853
|
-
claim: (source, owner) => {
|
|
854
|
-
owners.claim(source, owner, sets.has(source));
|
|
855
|
-
return {
|
|
856
|
-
replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
|
|
857
|
-
setLoader: (load) => {
|
|
858
|
-
loaders.set(source, load);
|
|
859
|
-
if (!sets.has(source)) sets = new Map([...sets, [source, {}]]);
|
|
860
|
-
}
|
|
861
|
-
};
|
|
862
|
-
},
|
|
863
|
-
refresh: () => applySets(/* @__PURE__ */ new Map(), true),
|
|
864
|
-
watch: () => {
|
|
865
|
-
const where = config.pointer;
|
|
866
|
-
if (pointer !== void 0 || where === void 0) return;
|
|
867
|
-
pointer = createGeneration({ read: where.read, move: where.move }, { onMoved: reload, ...where.everyMs === void 0 ? {} : { everyMs: where.everyMs } });
|
|
868
|
-
},
|
|
869
|
-
onChange: (listener) => {
|
|
841
|
+
subscribe: (listener) => {
|
|
870
842
|
listeners.add(listener);
|
|
871
843
|
return () => {
|
|
872
844
|
listeners.delete(listener);
|
|
873
845
|
};
|
|
874
846
|
},
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
847
|
+
within: (request, run) => requests.run(request, run),
|
|
848
|
+
report: (event) => {
|
|
849
|
+
const request = requests.getStore() ?? SAID_NOTHING;
|
|
850
|
+
for (const listener of [...listeners]) {
|
|
851
|
+
try {
|
|
852
|
+
listener(event, request);
|
|
853
|
+
} catch (error) {
|
|
854
|
+
console.error(`[moss:writes] somebody told of the write "${event.fingerprint}" failed. The others are still told:`, error);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
};
|
|
860
|
+
var createWireFollower = (callSignal) => {
|
|
861
|
+
const controller = new AbortController();
|
|
862
|
+
const end = () => {
|
|
863
|
+
controller.abort();
|
|
864
|
+
};
|
|
865
|
+
if (callSignal.aborted) end();
|
|
866
|
+
else callSignal.addEventListener("abort", end, { once: true });
|
|
867
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
868
|
+
let missed;
|
|
869
|
+
const live = {
|
|
870
|
+
signal: controller.signal,
|
|
871
|
+
onChange: (response) => {
|
|
872
|
+
if (handlers.size === 0) {
|
|
873
|
+
missed = { body: response.result };
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
for (const handler of [...handlers]) handler(response.result);
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
const onChange = (handler) => {
|
|
880
|
+
if (controller.signal.aborted) return () => {
|
|
881
|
+
};
|
|
882
|
+
handlers.add(handler);
|
|
883
|
+
if (missed !== void 0) {
|
|
884
|
+
const { body } = missed;
|
|
885
|
+
missed = void 0;
|
|
886
|
+
handler(body);
|
|
887
|
+
}
|
|
888
|
+
return () => {
|
|
889
|
+
handlers.delete(handler);
|
|
890
|
+
if (handlers.size === 0) end();
|
|
891
|
+
};
|
|
892
|
+
};
|
|
893
|
+
const handedOver = () => {
|
|
894
|
+
setTimeout(() => {
|
|
895
|
+
if (handlers.size === 0) end();
|
|
896
|
+
}, 0);
|
|
891
897
|
};
|
|
898
|
+
return { live, onChange, handedOver, end };
|
|
892
899
|
};
|
|
893
900
|
|
|
894
|
-
// src/data/
|
|
895
|
-
var
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
901
|
+
// src/data/routes.ts
|
|
902
|
+
var createVexRoutes = (deps) => {
|
|
903
|
+
const routes = new Hono();
|
|
904
|
+
routes.use(
|
|
905
|
+
"/api/*",
|
|
906
|
+
(c, next) => deps.writes.within(
|
|
907
|
+
writeRequestOf((name) => c.req.header(name)),
|
|
908
|
+
() => next()
|
|
909
|
+
)
|
|
910
|
+
);
|
|
911
|
+
const mount = (path, entities) => {
|
|
912
|
+
routes.route(
|
|
913
|
+
path,
|
|
914
|
+
vex({
|
|
915
|
+
engine: deps.engine,
|
|
916
|
+
...entities !== void 0 ? { entities: [...entities] } : {},
|
|
917
|
+
locked: true,
|
|
918
|
+
getScope: deps.scope,
|
|
919
|
+
getPolicy: deps.policy,
|
|
920
|
+
getPolicyForReach: deps.policyAtReach,
|
|
921
|
+
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
|
|
922
|
+
mutations: { client: deps.db, onWrite: deps.writes.report }
|
|
923
|
+
})
|
|
924
|
+
);
|
|
925
|
+
};
|
|
926
|
+
mount("/api/vex");
|
|
927
|
+
for (const [name, resource] of Object.entries(deps.resources ?? {})) {
|
|
928
|
+
mount(`/api/${name}/vex`, "entities" in resource ? resource.entities : resource);
|
|
929
|
+
}
|
|
930
|
+
return routes;
|
|
931
|
+
};
|
|
932
|
+
var createIntentAnswers = (deps) => {
|
|
933
|
+
const engines = /* @__PURE__ */ new WeakMap();
|
|
934
|
+
const engineFor = (writers) => {
|
|
935
|
+
const kept = engines.get(writers);
|
|
936
|
+
if (kept !== void 0) return kept;
|
|
937
|
+
const { adapter, schema } = deps;
|
|
938
|
+
const created = (async () => {
|
|
939
|
+
const engine = createQueryEngine({
|
|
940
|
+
adapter: { id: adapter.id, compile: adapter.compile, execute: adapter.execute, capabilities: adapter.capabilities, introspect: async () => schema },
|
|
941
|
+
cache: deps.cache,
|
|
942
|
+
generateDsl: writers.generateDsl,
|
|
943
|
+
mapToShape: writers.mapToShape,
|
|
944
|
+
...deps.behaviors !== void 0 ? { behaviors: deps.behaviors } : {},
|
|
945
|
+
...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {}
|
|
946
|
+
});
|
|
947
|
+
await engine.introspect();
|
|
948
|
+
return engine;
|
|
949
|
+
})();
|
|
950
|
+
engines.set(writers, created);
|
|
951
|
+
return created;
|
|
952
|
+
};
|
|
953
|
+
return async (writers, asked, caller) => (await engineFor(writers)).execute({ intent: asked.intent, shape: asked.shape, context: asked.context ?? {} }, { scope: caller.scope, scopePolicy: caller.policy });
|
|
954
|
+
};
|
|
955
|
+
|
|
956
|
+
// src/data/data.ts
|
|
957
|
+
var callerOfRoles = (roles) => ({ memoKey: memoKey(roles, void 0), roles });
|
|
958
|
+
var prepareEngine = async (config) => {
|
|
959
|
+
await migrate(config.pool, tableSequencesOf(config), { mode: config.migrations ?? "apply" });
|
|
960
|
+
const grammars = await createGrammarUpgrader({ grammars: config.grammars });
|
|
961
|
+
const layer = await createDataLayer(config);
|
|
962
|
+
return {
|
|
963
|
+
grammars,
|
|
964
|
+
engine: layer.engine,
|
|
965
|
+
grants: layer.grants,
|
|
966
|
+
adapter: layer.adapter,
|
|
967
|
+
askFirst: layer.askFirst,
|
|
968
|
+
upgradeStore: async (store) => {
|
|
969
|
+
await upgradeStore(config.pool, store, grammars);
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
};
|
|
973
|
+
var lazyIntentAnswers = (prepared, config) => {
|
|
974
|
+
const { engine } = prepared;
|
|
975
|
+
let answers;
|
|
976
|
+
const answering = () => {
|
|
977
|
+
if (answers !== void 0) return answers;
|
|
978
|
+
const schema = engine.getSchema();
|
|
979
|
+
if (schema === void 0) throw new Error("moss: an intent was asked before the engine had read the database.");
|
|
980
|
+
answers = createIntentAnswers({
|
|
981
|
+
adapter: prepared.adapter,
|
|
982
|
+
schema,
|
|
983
|
+
cache: engine.cache,
|
|
984
|
+
...config.behaviors !== void 0 ? { behaviors: config.behaviors } : {},
|
|
985
|
+
...config.vexConfig !== void 0 ? { vexConfig: config.vexConfig } : {}
|
|
986
|
+
});
|
|
987
|
+
return answers;
|
|
988
|
+
};
|
|
989
|
+
return answering;
|
|
990
|
+
};
|
|
991
|
+
var tablesByFeature = (config) => (feature) => {
|
|
992
|
+
const kept = (config.featureTables ?? []).find((tables) => tables.feature === feature);
|
|
993
|
+
if (kept === void 0) throw new Error(`moss: the data module was asked for the tables of a feature it was never told of ("${feature}").`);
|
|
994
|
+
return kept.names;
|
|
995
|
+
};
|
|
996
|
+
var createUpgradeStore = (prepared, tablesOf) => async (feature, store) => {
|
|
997
|
+
const own = tablesOf(feature);
|
|
998
|
+
if (store.schema !== void 0) {
|
|
999
|
+
throw new Error(
|
|
1000
|
+
`moss: the feature "${feature}" asked for the documents of a store in the schema "${store.schema}" to be upgraded. To a feature a store is named by its table alone: one of its own.`
|
|
1001
|
+
);
|
|
1002
|
+
}
|
|
1003
|
+
if (!own.includes(store.table)) {
|
|
1004
|
+
throw new Error(`moss: the feature "${feature}" asked for the documents stored in "${store.table}" to be upgraded, and that table is not its own (its own: ${own.join(", ") || "none"}).`);
|
|
1005
|
+
}
|
|
1006
|
+
await prepared.upgradeStore(store);
|
|
1007
|
+
};
|
|
1008
|
+
var createDataWith = (prepared, config) => {
|
|
1009
|
+
const { grammars, engine, grants } = prepared;
|
|
1010
|
+
const governed = { charter: config.charter, behaviors: { ...config.behaviors, ...config.rowRules } };
|
|
1011
|
+
const policies = createPolicies({ ...governed, grants });
|
|
1012
|
+
const emit = emitterOf(config.telemetry);
|
|
1013
|
+
const onExecute = emit === void 0 ? void 0 : (record) => emit(vexRecordToSpan(record));
|
|
1014
|
+
const writes = createWriteNotifier();
|
|
1015
|
+
const answering = lazyIntentAnswers(prepared, config);
|
|
1016
|
+
const ownEntries = (own, told) => createOwnEntries({ adapter: prepared.adapter, db: config.db, engine, ...told !== void 0 ? { onExecute: told } : {} })(own);
|
|
1017
|
+
const tablesOf = tablesByFeature(config);
|
|
1018
|
+
let pointerEntries;
|
|
1019
|
+
const pointerReplay = () => {
|
|
1020
|
+
pointerEntries ??= ownEntries(POINTER, void 0);
|
|
1021
|
+
return pointerEntries;
|
|
1022
|
+
};
|
|
1023
|
+
return {
|
|
1024
|
+
grants,
|
|
1025
|
+
grammars,
|
|
1026
|
+
entriesHeldBy: prepared.askFirst,
|
|
1027
|
+
fingerprints: async () => await engine.cache.keys?.() ?? [],
|
|
1028
|
+
policyOf: policies.of,
|
|
1029
|
+
// Compiled afresh and not taken from the kept ones: the caller owns its
|
|
1030
|
+
// copy, and nothing it does to it reaches a policy a request is served under.
|
|
1031
|
+
policyForRoles: (roles) => resolvePolicyForRoles(governed, grants, roles),
|
|
1032
|
+
fingerprintsFor: async (who) => (await handleDiscovery({ engine, locked: true, scopePolicy: policies.of(who) })).fingerprints.map((entry) => entry.fingerprint).sort(),
|
|
1033
|
+
vexEntry: (fingerprint) => engine.cache.get(fingerprint),
|
|
1034
|
+
compileQuery: (dsl) => {
|
|
1035
|
+
engine.compile(dsl);
|
|
1004
1036
|
},
|
|
1005
|
-
{
|
|
1006
|
-
|
|
1007
|
-
|
|
1037
|
+
executeAs: createExecuteAs({
|
|
1038
|
+
engine,
|
|
1039
|
+
db: config.db,
|
|
1040
|
+
policyFor: (roles) => policies.of(callerOfRoles(roles)),
|
|
1041
|
+
policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
|
|
1042
|
+
...onExecute !== void 0 ? { onExecute } : {}
|
|
1043
|
+
}),
|
|
1044
|
+
answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
|
|
1045
|
+
ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
|
|
1046
|
+
artifactEntries: (entries, rules) => ownEntries({ owner: "the artifactory", entries, tables: ARTIFACT_TABLES, rules }, onExecute),
|
|
1047
|
+
routes: (routing) => createVexRoutes({
|
|
1048
|
+
engine,
|
|
1049
|
+
db: config.db,
|
|
1050
|
+
resources: routing.resources,
|
|
1051
|
+
scope: routing.scope,
|
|
1052
|
+
policy: (c) => policies.of(routing.caller(c)),
|
|
1053
|
+
policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
|
|
1054
|
+
...onExecute !== void 0 ? { onExecute } : {},
|
|
1055
|
+
writes
|
|
1056
|
+
}),
|
|
1057
|
+
upgradeStore: createUpgradeStore(prepared, tablesOf),
|
|
1058
|
+
onWrite: writes.subscribe,
|
|
1059
|
+
pointer: createPointer(pointerReplay),
|
|
1060
|
+
dropOnChange: (changed) => {
|
|
1061
|
+
changed(policies.drop);
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
};
|
|
1065
|
+
var createData = async (config) => createDataWith(await prepareEngine(config), config);
|
|
1066
|
+
var DEFAULT_ROOT = '<div id="root"></div>';
|
|
1067
|
+
var embedSnapshot = (snapshot, principal, path) => {
|
|
1068
|
+
const { frame, trees, seed, live } = snapshot;
|
|
1069
|
+
const carried = { frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} };
|
|
1070
|
+
const text = JSON.stringify(carried).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1071
|
+
return `<script type="application/json" id="${SNAPSHOT_ELEMENT_ID}">${text}</script>`;
|
|
1072
|
+
};
|
|
1073
|
+
var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
|
|
1074
|
+
var rootHolding = (root) => {
|
|
1075
|
+
const closing = root.lastIndexOf("</");
|
|
1076
|
+
if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
|
|
1077
|
+
return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
|
|
1078
|
+
};
|
|
1079
|
+
var escapeAttribute = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
1080
|
+
var renderDocument = async (config) => {
|
|
1081
|
+
const { server, template, request, draw } = config;
|
|
1082
|
+
const tokenKey = config.tokenKey ?? DEFAULT_TOKEN_KEY;
|
|
1083
|
+
const root = config.root ?? DEFAULT_ROOT;
|
|
1084
|
+
const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
|
|
1085
|
+
if (!template.includes(root)) return undrawn;
|
|
1086
|
+
const holding = rootHolding(root);
|
|
1087
|
+
if (holding === void 0) {
|
|
1088
|
+
console.error(`[moss/document] the root ${root} has no place for a screen \u2014 a root is an empty element, like ${DEFAULT_ROOT}. "${request.path}" is served undrawn.`);
|
|
1089
|
+
return undrawn;
|
|
1090
|
+
}
|
|
1091
|
+
try {
|
|
1092
|
+
const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
|
|
1093
|
+
const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
|
|
1094
|
+
const principal = token === null ? null : await server.principalOf(token);
|
|
1095
|
+
const route = server.page(request.path);
|
|
1096
|
+
const host = route?.host ?? server.shells;
|
|
1097
|
+
if (host === void 0) return undrawn;
|
|
1098
|
+
const snapshot = await host.snapshot(principal === null ? null : token, principal, {
|
|
1099
|
+
...config.waitMs !== void 0 ? { waitMs: config.waitMs } : {},
|
|
1100
|
+
...route !== void 0 ? { inputs: route.inputs } : {}
|
|
1101
|
+
});
|
|
1102
|
+
const screen = await draw(snapshot);
|
|
1103
|
+
const attributes = Object.entries(config.htmlAttributes?.(snapshot) ?? {}).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
|
|
1104
|
+
const placed = template.replace(root, () => `${holding(screen)}${embedSnapshot(snapshot, principal, request.path)}`).replace(/<html([^>]*)>/, (whole, existing) => attributes === "" ? whole : `<html${existing}${attributes}>`);
|
|
1105
|
+
const head = headOf({ frame: () => snapshot.frame, canvasTree: (id) => snapshot.trees[id] ?? [] });
|
|
1106
|
+
for (const why of head?.refused ?? []) console.error(`[moss/document] "${request.path}" \u2014 ${why}`);
|
|
1107
|
+
const html = placeHead(placed, head?.elements, { ...config.site !== void 0 ? { site: config.site } : {}, path: request.path });
|
|
1108
|
+
return {
|
|
1109
|
+
html,
|
|
1110
|
+
...head !== void 0 ? { head } : {},
|
|
1111
|
+
headers: documentHeaders(principal),
|
|
1112
|
+
drawn: true,
|
|
1113
|
+
principal,
|
|
1114
|
+
...route !== void 0 ? { page: route.name } : {},
|
|
1115
|
+
live: snapshot.live,
|
|
1116
|
+
why: snapshot.why,
|
|
1117
|
+
drawnWith: snapshot.drawnWith,
|
|
1118
|
+
settled: snapshot.settled
|
|
1119
|
+
};
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
|
|
1122
|
+
return undrawn;
|
|
1123
|
+
}
|
|
1124
|
+
};
|
|
1125
|
+
|
|
1126
|
+
// src/documents/pages.ts
|
|
1127
|
+
var segmentsOf = (path) => path.split("?")[0]?.split("/").filter((part) => part !== "") ?? [];
|
|
1128
|
+
var compile = (name, page) => {
|
|
1129
|
+
if (!page.path.startsWith("/")) throw new Error(`moss: page "${name}" has the path "${page.path}" \u2014 a page's path starts with "/".`);
|
|
1130
|
+
const segments = segmentsOf(page.path).map((part) => part.startsWith(":") ? { param: part.slice(1) } : { literal: part });
|
|
1131
|
+
for (const segment of segments) {
|
|
1132
|
+
if ("param" in segment && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment.param)) {
|
|
1133
|
+
throw new Error(`moss: page "${name}" names the parameter ":${segment.param}" in "${page.path}" \u2014 a parameter is a plain name.`);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
const named = segments.flatMap((segment) => "param" in segment ? [segment.param] : []);
|
|
1137
|
+
const twice = named.find((param, index) => named.indexOf(param) !== index);
|
|
1138
|
+
if (twice !== void 0) {
|
|
1139
|
+
throw new Error(`moss: page "${name}" names the parameter ":${twice}" twice in "${page.path}" \u2014 give each parameter of a path its own name.`);
|
|
1140
|
+
}
|
|
1141
|
+
if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
|
|
1142
|
+
throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
|
|
1143
|
+
}
|
|
1144
|
+
return { name, segments };
|
|
1145
|
+
};
|
|
1146
|
+
var collide = (a, b) => a.segments.length === b.segments.length && a.segments.every((segment, index) => {
|
|
1147
|
+
const other = b.segments[index];
|
|
1148
|
+
return other === void 0 || "param" in segment || "param" in other || segment.literal === other.literal;
|
|
1149
|
+
});
|
|
1150
|
+
var createPageRouter = (pages) => {
|
|
1151
|
+
const compiled = Object.entries(pages).map(([name, page]) => compile(name, page));
|
|
1152
|
+
for (const [index, page] of compiled.entries()) {
|
|
1153
|
+
const other = compiled.slice(index + 1).find((candidate) => collide(page, candidate));
|
|
1154
|
+
if (other !== void 0) {
|
|
1155
|
+
throw new Error(`moss: pages "${page.name}" and "${other.name}" can both answer one path \u2014 give them paths that differ in a literal segment.`);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
return {
|
|
1159
|
+
match: (path) => {
|
|
1160
|
+
const parts = segmentsOf(path);
|
|
1161
|
+
for (const page of compiled) {
|
|
1162
|
+
if (page.segments.length !== parts.length) continue;
|
|
1163
|
+
const params = {};
|
|
1164
|
+
let matches = true;
|
|
1165
|
+
for (const [index, segment] of page.segments.entries()) {
|
|
1166
|
+
const part = parts[index];
|
|
1167
|
+
if (part === void 0) {
|
|
1168
|
+
matches = false;
|
|
1169
|
+
break;
|
|
1170
|
+
}
|
|
1171
|
+
if ("param" in segment) {
|
|
1172
|
+
try {
|
|
1173
|
+
params[segment.param] = decodeURIComponent(part);
|
|
1174
|
+
} catch {
|
|
1175
|
+
matches = false;
|
|
1176
|
+
break;
|
|
1177
|
+
}
|
|
1178
|
+
} else if (segment.literal !== part) {
|
|
1179
|
+
matches = false;
|
|
1180
|
+
break;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
if (matches) return { name: page.name, params };
|
|
1184
|
+
}
|
|
1185
|
+
return void 0;
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
};
|
|
1189
|
+
var exportDocuments = async (config) => {
|
|
1190
|
+
const { paths, ...rest } = config;
|
|
1191
|
+
const out = [];
|
|
1192
|
+
for (const path of paths) {
|
|
1193
|
+
const page = await renderDocument({ ...rest, request: { path, cookie: null } });
|
|
1194
|
+
out.push({
|
|
1195
|
+
path,
|
|
1196
|
+
html: page.html,
|
|
1197
|
+
...page.page !== void 0 ? { page: page.page } : {},
|
|
1198
|
+
...page.head !== void 0 ? { head: page.head } : {},
|
|
1199
|
+
drawn: page.drawn,
|
|
1200
|
+
// A page that could not be drawn is not taken to be finished.
|
|
1201
|
+
live: page.live ?? true,
|
|
1202
|
+
why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
|
|
1203
|
+
drawnWith: page.drawnWith ?? [],
|
|
1204
|
+
settled: page.settled ?? false
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
return out;
|
|
1208
|
+
};
|
|
1209
|
+
var isKept = (layout) => layout !== void 0 && layout !== null && typeof layout !== "string";
|
|
1210
|
+
var shellWithStoredLayouts = (shell) => {
|
|
1211
|
+
const layouts = {};
|
|
1212
|
+
const frame = shell.layout;
|
|
1213
|
+
if (isKept(frame)) layouts[FRAME_LAYOUT_REF] = frame;
|
|
1214
|
+
const canvases = shell.canvases.map((canvas) => {
|
|
1215
|
+
const layout = canvas.actionLayout;
|
|
1216
|
+
if (!isKept(layout)) return canvas;
|
|
1217
|
+
const ref = canvasLayoutRef(canvas.id);
|
|
1218
|
+
layouts[ref] = layout;
|
|
1219
|
+
return { ...canvas, actionLayout: ref };
|
|
1220
|
+
});
|
|
1221
|
+
return { canvases, ...isKept(frame) ? { frame: FRAME_LAYOUT_REF } : typeof frame === "string" ? { frame } : {}, layouts };
|
|
1222
|
+
};
|
|
1223
|
+
var slottedIn = /* @__PURE__ */ new WeakMap();
|
|
1224
|
+
var canvasesSlottedIn = (layout) => {
|
|
1225
|
+
const kept = slottedIn.get(layout);
|
|
1226
|
+
if (kept !== void 0) return kept;
|
|
1227
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1228
|
+
walkNodes(layout, (node) => {
|
|
1229
|
+
const id = node["component"] === CANVAS_SLOT_NAME && isRecord(node["props"]) ? node["props"]["canvasId"] : void 0;
|
|
1230
|
+
if (typeof id === "string" && id !== "" && !isBinding(id)) ids.add(id);
|
|
1231
|
+
});
|
|
1232
|
+
const found = [...ids];
|
|
1233
|
+
slottedIn.set(layout, found);
|
|
1234
|
+
return found;
|
|
1235
|
+
};
|
|
1236
|
+
var slottedCanvases = (declared, layouts) => {
|
|
1237
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1238
|
+
for (const layout of layouts) {
|
|
1239
|
+
if (layout === null || typeof layout !== "object") continue;
|
|
1240
|
+
for (const id of canvasesSlottedIn(layout)) ids.add(id);
|
|
1241
|
+
}
|
|
1242
|
+
for (const canvas of declared) ids.delete(canvas.id);
|
|
1243
|
+
return [...ids];
|
|
1244
|
+
};
|
|
1245
|
+
var shellComponents = (manifest, shell) => {
|
|
1246
|
+
const names = /* @__PURE__ */ new Set([CANVAS_SLOT_NAME, ACTION_SLOT_NAME]);
|
|
1247
|
+
for (const source of [manifest.actions, manifest.layouts ?? {}, shell.canvases, shell.layout ?? {}, shell.layoutStore ?? {}, shell.fragments ?? {}]) {
|
|
1248
|
+
for (const name of componentsOf(source)) names.add(name);
|
|
1249
|
+
}
|
|
1250
|
+
const contracts = shell.components ?? {};
|
|
1251
|
+
for (const name of Object.keys(contracts)) names.add(name);
|
|
1252
|
+
return Object.freeze(Object.fromEntries([...names].map((name) => [name, contracts[name] ?? {}])));
|
|
1253
|
+
};
|
|
1254
|
+
var SavedLayoutSchema = z.strictObject({ ref: z.string(), layout: LayoutNodeSchema, use: z.boolean().optional() });
|
|
1255
|
+
var upgradedLayoutBody = (upgrader, body, stamp) => isRecord(body) && body["layout"] !== void 0 ? { ...body, layout: upgrader.upgrade(body["layout"], { kind: "nisc.nova/layout", stamp }).document } : body;
|
|
1256
|
+
var nothingKeptUnder = (ref) => `nothing is kept under "${ref}". A saved layout takes the place of the layout of an action its holder has, under "action/<the action\u2019s id>", or of one the app\u2019s own shell declares: its own under "frame", a canvas\u2019s under "canvas/<the canvas\u2019s id>".`;
|
|
1257
|
+
var targetAt = (ref, heldTo) => {
|
|
1258
|
+
if (heldTo.ownShell?.refs.has(ref) === true) return { kit: heldTo.ownShell.kit };
|
|
1259
|
+
const action = heldTo.actionAt(ref);
|
|
1260
|
+
return action === void 0 ? void 0 : { kit: heldTo.kit, action };
|
|
1261
|
+
};
|
|
1262
|
+
var refOf = (body) => {
|
|
1263
|
+
const ref = isRecord(body) ? body["ref"] : void 0;
|
|
1264
|
+
return typeof ref === "string" ? ref : void 0;
|
|
1265
|
+
};
|
|
1266
|
+
var readLayout = (body, heldTo) => {
|
|
1267
|
+
if (exceedsDepth(body)) return { refusal: depthRefusal() };
|
|
1268
|
+
const parsed = SavedLayoutSchema.safeParse(body);
|
|
1269
|
+
if (!parsed.success) {
|
|
1270
|
+
const first = parsed.error.issues[0];
|
|
1271
|
+
return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
|
|
1272
|
+
}
|
|
1273
|
+
const { ref, layout } = parsed.data;
|
|
1274
|
+
const target = targetAt(ref, heldTo);
|
|
1275
|
+
if (target === void 0) return { refusal: nothingKeptUnder(ref) };
|
|
1276
|
+
const misfits = layoutMisfits(layout, target.kit);
|
|
1277
|
+
if (misfits.length > 0) return { refusal: misfits.join("; ") };
|
|
1278
|
+
const named = layoutNameRefusal(layout);
|
|
1279
|
+
if (named !== void 0) return { refusal: `it ${named}` };
|
|
1280
|
+
const { action } = target;
|
|
1281
|
+
if (action === void 0) return { layout: parsed.data };
|
|
1282
|
+
const found = new Set(auditAction(action).issues);
|
|
1283
|
+
const added = auditAction({ ...action, layout }).issues.filter((issue) => !found.has(issue));
|
|
1284
|
+
if (added.length > 0) return { refusal: added.join("; ") };
|
|
1285
|
+
return { layout: parsed.data };
|
|
1286
|
+
};
|
|
1287
|
+
var loaded = (version, { whose, heldTo, say }) => {
|
|
1288
|
+
const ref = refOf(version.body);
|
|
1289
|
+
if (ref === void 0 || targetAt(ref, heldTo) === void 0) return void 0;
|
|
1290
|
+
const read2 = version.unread !== void 0 ? { refusal: version.unread } : readLayout(version.body, heldTo);
|
|
1291
|
+
if ("layout" in read2) return read2.layout;
|
|
1292
|
+
(say ?? console.error)(`[moss] the layout "${version.id}" ${whose} is left out: ${read2.refusal}`);
|
|
1293
|
+
return void 0;
|
|
1294
|
+
};
|
|
1295
|
+
var isInUse = (version) => version.kind === "layout" && isRecord(version.body) && version.body["use"] === true;
|
|
1296
|
+
var isLater = (one, other) => one.createdAt === other.createdAt ? one.save > other.save : one.createdAt > other.createdAt;
|
|
1297
|
+
var layoutsInUse = (inForce2, drawnFor) => {
|
|
1298
|
+
const marked = /* @__PURE__ */ new Map();
|
|
1299
|
+
for (const version of inForce2.filter(isInUse)) {
|
|
1300
|
+
const ref = refOf(version.body);
|
|
1301
|
+
if (ref === void 0) continue;
|
|
1302
|
+
const held = marked.get(ref);
|
|
1303
|
+
if (held === void 0 || isLater(version, held)) marked.set(ref, version);
|
|
1304
|
+
}
|
|
1305
|
+
const layouts = {};
|
|
1306
|
+
for (const version of marked.values()) {
|
|
1307
|
+
const read2 = loaded(version, drawnFor);
|
|
1308
|
+
if (read2 !== void 0) layouts[read2.ref] = read2.layout;
|
|
1309
|
+
}
|
|
1310
|
+
return layouts;
|
|
1311
|
+
};
|
|
1312
|
+
var generatedId = () => `${GENERATED_ID_PREFIX}${randomUUID()}`;
|
|
1313
|
+
var VEX_ROUTE = /^\/api\/(?:[A-Za-z0-9_-]+\/)?vex$/;
|
|
1314
|
+
var endpointRefusals = async (endpoints, heldTo) => {
|
|
1315
|
+
const refusals = [];
|
|
1316
|
+
for (const [name, endpoint] of Object.entries(endpoints ?? {})) {
|
|
1317
|
+
if ("fn" in endpoint) {
|
|
1318
|
+
if (endpoint.fn.includes("{{")) refusals.push(`endpoint "${name}" names a function that is worked out when it is called, and what is generated names one written out`);
|
|
1319
|
+
else if (!heldTo.mayCall(endpoint.fn)) refusals.push(`endpoint "${name}" calls the function "${endpoint.fn}", which its owner\u2019s roles do not grant`);
|
|
1320
|
+
continue;
|
|
1321
|
+
}
|
|
1322
|
+
if (endpoint.method !== "POST" || !VEX_ROUTE.test(endpoint.url)) {
|
|
1323
|
+
refusals.push(`endpoint "${name}" calls "${endpoint.method} ${endpoint.url}", and what is generated calls only the app\u2019s vex route, with POST`);
|
|
1324
|
+
continue;
|
|
1325
|
+
}
|
|
1326
|
+
const fingerprint = isRecord(endpoint.request) ? endpoint.request["fingerprint"] : void 0;
|
|
1327
|
+
if (typeof fingerprint !== "string") {
|
|
1328
|
+
refusals.push(`endpoint "${name}" names no fingerprint`);
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
const entry = heldTo.entryOf(fingerprint);
|
|
1332
|
+
if (entry === void 0) refusals.push(`endpoint "${name}" replays "${fingerprint}", which is no entry the app ships or was handed, nor a read its owner saved`);
|
|
1333
|
+
else if ("mutation" in entry) refusals.push(`endpoint "${name}" replays "${fingerprint}", which is a write, and what is generated only reads`);
|
|
1334
|
+
else if (!(await heldTo.replayable()).has(fingerprint)) refusals.push(`endpoint "${name}" replays "${fingerprint}", which its owner may not replay`);
|
|
1335
|
+
}
|
|
1336
|
+
return refusals;
|
|
1337
|
+
};
|
|
1338
|
+
var parsedUnder = (schema, body, id, more = {}) => {
|
|
1339
|
+
if (exceedsDepth(body)) return { refusal: depthRefusal() };
|
|
1340
|
+
if (isRecord(body) && body["id"] !== void 0 && body["id"] !== id) {
|
|
1341
|
+
return { refusal: `it names the id "${String(body["id"])}". Moss gives what is generated its id: leave it out.` };
|
|
1342
|
+
}
|
|
1343
|
+
const parsed = schema.safeParse(isRecord(body) ? { ...more, ...body, id } : body);
|
|
1344
|
+
if (parsed.success) return { body: parsed.data };
|
|
1345
|
+
const first = parsed.error.issues[0];
|
|
1346
|
+
return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
|
|
1347
|
+
};
|
|
1348
|
+
var layoutRefusals = (layout, kit) => {
|
|
1349
|
+
const named = layoutNameRefusal(layout);
|
|
1350
|
+
return [...layout === void 0 || typeof layout === "string" ? [] : layoutMisfits(layout, kit), ...named === void 0 ? [] : [`it ${named}`]];
|
|
1351
|
+
};
|
|
1352
|
+
var passedOrRefused = (body, refusals) => refusals.length > 0 ? { refusal: refusals.join("; ") } : { body };
|
|
1353
|
+
var readAction = async (body, id, heldTo) => {
|
|
1354
|
+
const parsed = parsedUnder(ActionDefinitionSchema, body, id);
|
|
1355
|
+
if ("refusal" in parsed) return parsed;
|
|
1356
|
+
const action = parsed.body;
|
|
1357
|
+
return passedOrRefused(action, [
|
|
1358
|
+
...layoutRefusals(action.layout, heldTo.kit),
|
|
1359
|
+
...await endpointRefusals(action.endpoints, heldTo),
|
|
1360
|
+
...auditAction(action, { catalog: heldTo.catalog() }).issues
|
|
1361
|
+
]);
|
|
1362
|
+
};
|
|
1363
|
+
var readFragment = async (body, id, heldTo) => {
|
|
1364
|
+
const parsed = parsedUnder(ActionFragmentSchema, body, id, { kind: "fragment" });
|
|
1365
|
+
if ("refusal" in parsed) return parsed;
|
|
1366
|
+
const fragment = parsed.body;
|
|
1367
|
+
return passedOrRefused(fragment, [...layoutRefusals(fragment.layout, heldTo.kit), ...await endpointRefusals(fragment.endpoints, heldTo)]);
|
|
1368
|
+
};
|
|
1369
|
+
var generatedIn = (inForce2, kind) => inForce2.filter((version) => version.kind === kind && version.body !== null);
|
|
1370
|
+
var catalogOfGenerated = (inForce2) => generatedIn(inForce2, "action").map((version) => ({ id: version.id, input: isRecord(version.body) && isRecord(version.body["input"]) ? version.body["input"] : {} }));
|
|
1371
|
+
var generatedInForce = async (inForce2, heldTo, whose) => {
|
|
1372
|
+
const passed = async (kind, read2) => {
|
|
1373
|
+
const kept = {};
|
|
1374
|
+
for (const version of generatedIn(inForce2, kind)) {
|
|
1375
|
+
const answered = version.unread !== void 0 ? { refusal: version.unread } : await read2(version.body, version.id, heldTo);
|
|
1376
|
+
if ("body" in answered) kept[version.id] = answered.body;
|
|
1377
|
+
else if (whose !== void 0) console.error(`[moss] the ${kind} "${version.id}" ${whose} is left out: ${answered.refusal}`);
|
|
1378
|
+
}
|
|
1379
|
+
return kept;
|
|
1380
|
+
};
|
|
1381
|
+
return { actions: await passed("action", readAction), fragments: await passed("fragment", readFragment) };
|
|
1382
|
+
};
|
|
1383
|
+
var compileEntries = async (entries) => {
|
|
1384
|
+
const compiled = createMemoryCache();
|
|
1385
|
+
await seedCache(compiled, entries);
|
|
1386
|
+
return new Map((await compiled.entries?.() ?? []).map(({ key, entry }) => [key, entry]));
|
|
1387
|
+
};
|
|
1388
|
+
var mergedEntries = (own, sets) => {
|
|
1389
|
+
const byFingerprint = /* @__PURE__ */ new Map();
|
|
1390
|
+
for (const entry of [...own, ...[...sets.values()].flat()]) byFingerprint.set(entry.fingerprint, entry);
|
|
1391
|
+
return Object.freeze([...byFingerprint.values()]);
|
|
1392
|
+
};
|
|
1393
|
+
var createEntriesInForce = (own) => {
|
|
1394
|
+
let sets = /* @__PURE__ */ new Map();
|
|
1395
|
+
let list = mergedEntries(own, sets);
|
|
1396
|
+
let byFingerprint = new Map(list.map((entry) => [entry.fingerprint, entry]));
|
|
1397
|
+
let ownCompiled;
|
|
1398
|
+
let setsCompiled = /* @__PURE__ */ new Map();
|
|
1399
|
+
let compiled;
|
|
1400
|
+
return {
|
|
1401
|
+
list: () => list,
|
|
1402
|
+
byFingerprint: () => byFingerprint,
|
|
1403
|
+
holdsSet: (source) => sets.has(source),
|
|
1404
|
+
withSet: (source, handed) => mergedEntries(own, new Map([...sets, [source, handed]])),
|
|
1405
|
+
takeSet: (source, handed, taken) => {
|
|
1406
|
+
sets = new Map([...sets, [source, handed]]);
|
|
1407
|
+
list = mergedEntries(own, sets);
|
|
1408
|
+
byFingerprint = new Map(list.map((entry) => [entry.fingerprint, entry]));
|
|
1409
|
+
setsCompiled = new Map([...setsCompiled, [source, taken]]);
|
|
1410
|
+
compiled = void 0;
|
|
1008
1411
|
},
|
|
1412
|
+
compiled: () => {
|
|
1413
|
+
compiled ??= (async () => {
|
|
1414
|
+
ownCompiled ??= compileEntries(own);
|
|
1415
|
+
return new Map([...await ownCompiled, ...[...setsCompiled.values()].flatMap((set) => [...set])]);
|
|
1416
|
+
})();
|
|
1417
|
+
return compiled;
|
|
1418
|
+
}
|
|
1419
|
+
};
|
|
1420
|
+
};
|
|
1421
|
+
|
|
1422
|
+
// src/artifactory/reads.ts
|
|
1423
|
+
var SavedReadSchema = VEX_SCHEMAS["nisc.vex/entry"];
|
|
1424
|
+
var sentenceOf = (error) => error instanceof Error ? error.message : String(error);
|
|
1425
|
+
var seedOf = (fingerprint, read2) => ({ fingerprint, ...read2 });
|
|
1426
|
+
var compiledRead = async (fingerprint, read2) => {
|
|
1427
|
+
const compiled = (await compileEntries([seedOf(fingerprint, read2)])).get(fingerprint);
|
|
1428
|
+
if (compiled === void 0) return void 0;
|
|
1429
|
+
const { protected: _shipped, ...entry } = compiled;
|
|
1430
|
+
return entry;
|
|
1431
|
+
};
|
|
1432
|
+
var shippedRefusal = (fingerprint) => `"${fingerprint}" is the fingerprint of an entry the app ships or was handed, and a read somebody generated never answers in its place`;
|
|
1433
|
+
var readSaved = async (body, fingerprint, heldTo) => {
|
|
1434
|
+
if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
|
|
1435
|
+
if (exceedsDepth(body)) return { refusal: depthRefusal() };
|
|
1436
|
+
const parsed = SavedReadSchema.safeParse(body);
|
|
1437
|
+
if (!parsed.success) {
|
|
1438
|
+
const first = parsed.error.issues[0];
|
|
1439
|
+
return { refusal: first === void 0 ? "no reason given" : `${first.path.join(".") || "(the body)"}: ${first.message}` };
|
|
1440
|
+
}
|
|
1441
|
+
try {
|
|
1442
|
+
heldTo.sources.compile(parsed.data.dsl);
|
|
1443
|
+
await compiledRead(fingerprint, parsed.data);
|
|
1444
|
+
} catch (error) {
|
|
1445
|
+
return { refusal: sentenceOf(error) };
|
|
1446
|
+
}
|
|
1447
|
+
return { body: parsed.data };
|
|
1448
|
+
};
|
|
1449
|
+
var readWritten = async (fingerprint, heldTo) => {
|
|
1450
|
+
if (heldTo.isAppEntry(fingerprint)) return { refusal: shippedRefusal(fingerprint) };
|
|
1451
|
+
const entry = await heldTo.sources.written(fingerprint);
|
|
1452
|
+
if (entry === void 0 || entry.requestHash === void 0) return { refusal: `vex holds no query it wrote under "${fingerprint}"` };
|
|
1453
|
+
if (entry.kind !== "ok") return { refusal: `vex found no query to answer under "${fingerprint}"` };
|
|
1454
|
+
if (entry.shape !== void 0 && entry.mapping === void 0) {
|
|
1455
|
+
return { refusal: `vex kept no prism config for the mapping of "${fingerprint}": it was written before vex kept one. Ask for it again.` };
|
|
1456
|
+
}
|
|
1457
|
+
return readSaved(
|
|
1009
1458
|
{
|
|
1010
|
-
|
|
1011
|
-
|
|
1459
|
+
dsl: entry.dsl,
|
|
1460
|
+
...entry.mapping !== void 0 ? { mapping: entry.mapping } : {},
|
|
1461
|
+
...entry.shape !== void 0 ? { shape: entry.shape } : {},
|
|
1462
|
+
...entry.intent !== void 0 ? { intent: entry.intent } : {},
|
|
1463
|
+
...entry.reach !== void 0 ? { reach: entry.reach } : {},
|
|
1464
|
+
...entry.refresh !== void 0 ? { refresh: entry.refresh } : {}
|
|
1012
1465
|
},
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1466
|
+
fingerprint,
|
|
1467
|
+
heldTo
|
|
1468
|
+
);
|
|
1469
|
+
};
|
|
1470
|
+
var answeredRead = async (fingerprint, body) => {
|
|
1471
|
+
if (exceedsDepth(body)) return void 0;
|
|
1472
|
+
const parsed = SavedReadSchema.safeParse(body);
|
|
1473
|
+
return parsed.success ? compiledRead(fingerprint, parsed.data) : void 0;
|
|
1474
|
+
};
|
|
1475
|
+
var readsInForce = async (inForce2, heldTo, whose) => {
|
|
1476
|
+
const reads = /* @__PURE__ */ new Map();
|
|
1477
|
+
for (const version of inForce2) {
|
|
1478
|
+
if (version.kind !== "read" || version.body === null) continue;
|
|
1479
|
+
const read2 = version.unread !== void 0 ? { refusal: version.unread } : await readSaved(version.body, version.id, heldTo);
|
|
1480
|
+
if ("body" in read2) reads.set(version.id, read2.body);
|
|
1481
|
+
else if (whose !== void 0) console.error(`[moss] the read "${version.id}" ${whose} is left out: ${read2.refusal}`);
|
|
1482
|
+
}
|
|
1483
|
+
return reads;
|
|
1484
|
+
};
|
|
1485
|
+
|
|
1486
|
+
// src/artifactory/session.ts
|
|
1487
|
+
var SaveIdSchema = z.uuid();
|
|
1488
|
+
var ToSaveSchema = z.array(z.strictObject({ kind: z.string(), id: z.string().optional(), body: z.unknown() })).min(1);
|
|
1489
|
+
var NEW_ID = {
|
|
1490
|
+
layout: randomUUID,
|
|
1491
|
+
action: generatedId,
|
|
1492
|
+
fragment: generatedId,
|
|
1493
|
+
read: () => {
|
|
1494
|
+
throw new Error("moss: a read is saved under the fingerprint vex gave it: name it as the id.");
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
var listed = (version, kind) => ({
|
|
1498
|
+
kind,
|
|
1499
|
+
id: version.id,
|
|
1500
|
+
save: version.save,
|
|
1501
|
+
createdAt: version.createdAt,
|
|
1502
|
+
copiedFrom: version.copiedFrom,
|
|
1503
|
+
body: version.body
|
|
1504
|
+
});
|
|
1505
|
+
var withoutMark = ({ use: _mark, ...layout }) => layout;
|
|
1506
|
+
var checked = async (kind, id, body, heldTo) => {
|
|
1507
|
+
if (kind === "layout") {
|
|
1508
|
+
const read3 = readLayout(body, heldTo.layouts);
|
|
1509
|
+
if ("refusal" in read3) throw new Error(`moss: the layout for "${refOf(body) ?? "(no ref)"}" is refused: ${read3.refusal}`);
|
|
1510
|
+
return read3.layout;
|
|
1511
|
+
}
|
|
1512
|
+
if (kind === "read") {
|
|
1513
|
+
const read3 = heldTo.reads === void 0 ? { refusal: "no read is saved here" } : body === void 0 ? await readWritten(id, heldTo.reads) : await readSaved(body, id, heldTo.reads);
|
|
1514
|
+
if ("refusal" in read3) throw new Error(`moss: the read "${id}" is refused: ${read3.refusal}`);
|
|
1515
|
+
return read3.body;
|
|
1516
|
+
}
|
|
1517
|
+
const read2 = await (kind === "action" ? readAction : readFragment)(body, id, heldTo.generated);
|
|
1518
|
+
if ("refusal" in read2) throw new Error(`moss: the ${kind} is refused: ${read2.refusal}`);
|
|
1519
|
+
return read2.body;
|
|
1520
|
+
};
|
|
1521
|
+
var markedRefs = (versions) => {
|
|
1522
|
+
const marked = versions.flatMap((version) => {
|
|
1523
|
+
const ref = refOf(version.body);
|
|
1524
|
+
return version.kind === "layout" && isRecord(version.body) && version.body["use"] === true && ref !== void 0 ? [ref] : [];
|
|
1525
|
+
});
|
|
1526
|
+
const twice = marked.find((ref, at) => marked.indexOf(ref) !== at);
|
|
1527
|
+
if (twice !== void 0) throw new Error(`moss: two layouts of one save are marked in use for "${twice}". One is in use at a time.`);
|
|
1528
|
+
return marked;
|
|
1529
|
+
};
|
|
1530
|
+
var unmarked = (versions, inForce2) => {
|
|
1531
|
+
const layouts = versions.filter((version) => version.kind === "layout");
|
|
1532
|
+
const marked = markedRefs(layouts);
|
|
1533
|
+
const saved = new Set(layouts.map((version) => version.id));
|
|
1534
|
+
const takenOut = inForce2.flatMap((held) => isInUse(held) && saved.has(held.id) ? [refOf(held.body)] : []);
|
|
1535
|
+
const decided = /* @__PURE__ */ new Set([...marked, ...takenOut]);
|
|
1536
|
+
return inForce2.flatMap((held) => {
|
|
1537
|
+
const ref = refOf(held.body);
|
|
1538
|
+
if (!isInUse(held) || held.unread !== void 0 || !isRecord(held.body) || ref === void 0 || !decided.has(ref) || saved.has(held.id)) return [];
|
|
1539
|
+
return [{ kind: "layout", id: held.id, body: withoutMark(held.body), copiedFrom: held.save }];
|
|
1540
|
+
});
|
|
1541
|
+
};
|
|
1542
|
+
var idsOf = (versions) => versions.map(({ kind, id }) => ({ kind, id }));
|
|
1543
|
+
var savingFor = ({ holder, whose, kinds, written }, nobody) => {
|
|
1544
|
+
const requireHolder = () => {
|
|
1545
|
+
if (holder === void 0) throw new Error(nobody);
|
|
1546
|
+
return holder;
|
|
1547
|
+
};
|
|
1548
|
+
const ofKind = (kind) => {
|
|
1549
|
+
const known = kinds.find((one) => one === kind);
|
|
1550
|
+
if (known === void 0) throw new Error(`moss: "${String(kind)}" is not a kind that is saved. The kinds: ${kinds.join(", ")}.`);
|
|
1551
|
+
return known;
|
|
1552
|
+
};
|
|
1553
|
+
const askedOf = (artifacts) => {
|
|
1554
|
+
const asked = ToSaveSchema.safeParse(artifacts);
|
|
1555
|
+
if (!asked.success) throw new Error("moss: a save holds one or several artifacts, each `{ kind, id?, body }` and nothing else.");
|
|
1556
|
+
return asked.data.map((artifact) => ({ ...artifact, kind: ofKind(artifact.kind) }));
|
|
1557
|
+
};
|
|
1558
|
+
const checkedEach = async (asked, inForce2, held) => {
|
|
1559
|
+
const versions = [];
|
|
1560
|
+
for (const { kind, id: named, body } of asked) {
|
|
1561
|
+
const id = named ?? NEW_ID[kind]();
|
|
1562
|
+
if (kind === "read" && body !== void 0) throw new Error(`moss: the read "${id}" is refused: it is what vex wrote for the request. Leave the body out.`);
|
|
1563
|
+
versions.push({ kind, id, body: await checked(kind, id, body, held), copiedFrom: null });
|
|
1564
|
+
}
|
|
1565
|
+
const notTheirs = asked.find(({ kind, id }) => id !== void 0 && kind !== "read" && !inForce2.some((version) => version.kind === kind && version.id === id));
|
|
1566
|
+
if (notTheirs !== void 0) {
|
|
1567
|
+
throw new Error(`moss: there is no ${notTheirs.kind} "${notTheirs.id}" ${whose}. Leave the id out, and moss gives a new ${notTheirs.kind} its id.`);
|
|
1568
|
+
}
|
|
1569
|
+
const twice = versions.find((version, at) => versions.findIndex((other) => other.kind === version.kind && other.id === version.id) !== at);
|
|
1570
|
+
if (twice !== void 0) throw new Error(`moss: the ${twice.kind} "${twice.id}" is in one save twice.`);
|
|
1571
|
+
return versions;
|
|
1572
|
+
};
|
|
1573
|
+
const write = async (saved, versions, inForce2) => {
|
|
1574
|
+
const save2 = randomUUID();
|
|
1575
|
+
await saved.write({ id: save2, versions: [...versions, ...unmarked(versions, inForce2)] });
|
|
1576
|
+
written();
|
|
1577
|
+
return save2;
|
|
1578
|
+
};
|
|
1579
|
+
return { requireHolder, ofKind, askedOf, checkedEach, write };
|
|
1580
|
+
};
|
|
1581
|
+
var savedArtifacts = (deps) => {
|
|
1582
|
+
const { holder, whose, kinds } = deps;
|
|
1583
|
+
const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a save is somebody\u2019s.");
|
|
1584
|
+
return {
|
|
1585
|
+
save: async (artifacts) => {
|
|
1586
|
+
const holderOf = requireHolder();
|
|
1587
|
+
const asked = askedOf(artifacts);
|
|
1588
|
+
const { saved, heldTo } = await holderOf();
|
|
1589
|
+
const inForce2 = await saved.inForce();
|
|
1590
|
+
const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
|
|
1591
|
+
return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
|
|
1592
|
+
},
|
|
1593
|
+
list: async (kind) => {
|
|
1594
|
+
const only = kind === void 0 ? void 0 : ofKind(kind);
|
|
1595
|
+
if (holder === void 0) return [];
|
|
1596
|
+
const inForce2 = await (await holder()).saved.inForce();
|
|
1597
|
+
return inForce2.flatMap((version) => {
|
|
1598
|
+
const known = kinds.find((one) => one === version.kind);
|
|
1599
|
+
return version.body !== null && known !== void 0 && (only === void 0 || known === only) ? [listed(version, known)] : [];
|
|
1600
|
+
});
|
|
1601
|
+
},
|
|
1602
|
+
history: async (kind, id) => {
|
|
1603
|
+
const known = ofKind(kind);
|
|
1604
|
+
if (holder === void 0) return [];
|
|
1605
|
+
return (await (await holder()).saved.history(known, id)).map((version) => listed(version, known));
|
|
1606
|
+
},
|
|
1607
|
+
restore: async (kind, id, save2) => {
|
|
1608
|
+
const holderOf = requireHolder();
|
|
1609
|
+
const known = ofKind(kind);
|
|
1610
|
+
const { saved, heldTo } = await holderOf();
|
|
1611
|
+
const version = SaveIdSchema.safeParse(save2).success ? (await saved.history(known, id, save2))[0] : void 0;
|
|
1612
|
+
if (version === void 0) throw new Error(`moss: no ${known} "${id}" ${whose} was saved in "${save2}".`);
|
|
1613
|
+
if (version.unread !== void 0) throw new Error(`moss: the ${known} "${id}" saved in "${save2}" cannot be read: ${version.unread}`);
|
|
1614
|
+
const inForce2 = await saved.inForce();
|
|
1615
|
+
const body = version.body === null ? null : await checked(known, id, version.body, await heldTo(inForce2));
|
|
1616
|
+
return { save: await write(saved, [{ kind: known, id, body, copiedFrom: version.save }], inForce2) };
|
|
1617
|
+
},
|
|
1618
|
+
reset: async (kind, id) => {
|
|
1619
|
+
const holderOf = requireHolder();
|
|
1620
|
+
const known = ofKind(kind);
|
|
1621
|
+
const { saved } = await holderOf();
|
|
1622
|
+
const inForce2 = await saved.inForce();
|
|
1623
|
+
if (!inForce2.some((version) => version.kind === known && version.id === id && version.body !== null)) throw new Error(`moss: no ${known} "${id}" ${whose} is in force.`);
|
|
1624
|
+
return { save: await write(saved, [{ kind: known, id, body: null, copiedFrom: null }], inForce2) };
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
};
|
|
1628
|
+
|
|
1629
|
+
// src/artifactory/draft.ts
|
|
1630
|
+
var LATER_THAN_ANY_SAVE = "9999-12-31T23:59:59.999Z";
|
|
1631
|
+
var laidOver = (inForce2, drafted = []) => drafted.length === 0 ? inForce2 : [
|
|
1632
|
+
...inForce2.filter((version) => !drafted.some((one) => one.kind === version.kind && one.id === version.id)),
|
|
1633
|
+
...drafted.map((one) => ({ ...one, save: "draft", copiedFrom: null, createdAt: LATER_THAN_ANY_SAVE }))
|
|
1634
|
+
];
|
|
1635
|
+
var draftSaving = (deps) => {
|
|
1636
|
+
const { requireHolder, ofKind, askedOf, checkedEach, write } = savingFor(deps, "moss: nobody is signed in to this session, and a draft is somebody\u2019s to save.");
|
|
1637
|
+
return {
|
|
1638
|
+
// The draft with these put into it. Each is checked beside what is in force for its holder with the draft laid over.
|
|
1639
|
+
put: async (artifacts, drafted) => {
|
|
1640
|
+
const holderOf = requireHolder();
|
|
1641
|
+
const asked = askedOf(artifacts);
|
|
1642
|
+
const { saved, heldTo } = await holderOf();
|
|
1643
|
+
const inForce2 = laidOver(await saved.inForce(), drafted);
|
|
1644
|
+
const versions = await checkedEach(asked, inForce2, await heldTo(inForce2));
|
|
1645
|
+
const put = versions.map(({ kind, id, body }) => ({ kind, id, body }));
|
|
1646
|
+
const marked = new Set(markedRefs(put));
|
|
1647
|
+
const kept = drafted.flatMap((one) => {
|
|
1648
|
+
if (put.some((other) => other.kind === one.kind && other.id === one.id)) return [];
|
|
1649
|
+
const ref = refOf(one.body);
|
|
1650
|
+
const loses = one.kind === "layout" && isRecord(one.body) && one.body["use"] === true && ref !== void 0 && marked.has(ref);
|
|
1651
|
+
return [loses && isRecord(one.body) ? { ...one, body: withoutMark(one.body) } : one];
|
|
1652
|
+
});
|
|
1653
|
+
return { drafted: [...kept, ...put], put: idsOf(versions) };
|
|
1654
|
+
},
|
|
1655
|
+
save: async (drafted) => {
|
|
1656
|
+
const holderOf = requireHolder();
|
|
1657
|
+
if (drafted.length === 0) throw new Error("moss: the draft holds nothing to save.");
|
|
1658
|
+
const { saved, heldTo } = await holderOf();
|
|
1659
|
+
const inForce2 = await saved.inForce();
|
|
1660
|
+
const held = await heldTo(laidOver(inForce2, drafted));
|
|
1661
|
+
const versions = [];
|
|
1662
|
+
for (const one of drafted) {
|
|
1663
|
+
const kind = ofKind(one.kind);
|
|
1664
|
+
versions.push({ kind, id: one.id, body: await checked(kind, one.id, one.body, held), copiedFrom: null });
|
|
1665
|
+
}
|
|
1666
|
+
return { save: await write(saved, versions, inForce2), artifacts: idsOf(versions) };
|
|
1667
|
+
}
|
|
1668
|
+
};
|
|
1669
|
+
};
|
|
1670
|
+
|
|
1671
|
+
// src/artifactory/generation.ts
|
|
1672
|
+
var DEFAULT_GENERATION_POLL_MS = 60 * 1e3;
|
|
1673
|
+
var MAX_INTERVAL_MS = 2 ** 31 - 1;
|
|
1674
|
+
var MOVE_ATTEMPTS = 5;
|
|
1675
|
+
var createGeneration = (pointer, ctx) => {
|
|
1676
|
+
const everyMs = ctx.everyMs ?? DEFAULT_GENERATION_POLL_MS;
|
|
1677
|
+
let seen = -1;
|
|
1678
|
+
let checking = false;
|
|
1679
|
+
const poll = async () => {
|
|
1680
|
+
if (checking) return;
|
|
1681
|
+
checking = true;
|
|
1682
|
+
try {
|
|
1683
|
+
const n = await readPointer();
|
|
1684
|
+
if (n === void 0 || n === seen) return;
|
|
1685
|
+
if (seen !== -1 && !await follow(n)) return;
|
|
1686
|
+
seen = n;
|
|
1687
|
+
} finally {
|
|
1688
|
+
checking = false;
|
|
1689
|
+
}
|
|
1690
|
+
};
|
|
1691
|
+
const readPointer = async () => {
|
|
1692
|
+
try {
|
|
1693
|
+
return await pointer.read();
|
|
1694
|
+
} catch (err) {
|
|
1695
|
+
console.error("[moss:generation] could not read the generation pointer \u2014 this process may be serving stale resolutions", err);
|
|
1696
|
+
return void 0;
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
let unfollowed;
|
|
1700
|
+
const follow = async (n) => {
|
|
1701
|
+
try {
|
|
1702
|
+
await ctx.onMoved();
|
|
1703
|
+
} catch (err) {
|
|
1704
|
+
const what = `the generation pointer moved (${seen} \u2192 ${n}) and this process could not follow it: ${err instanceof Error ? err.message : String(err)}`;
|
|
1705
|
+
if (unfollowed?.said !== what) {
|
|
1706
|
+
console.error(`[moss:generation] ${what} \u2014 it is serving what it had, and tries again at every look; this is said again only when it changes`, err);
|
|
1707
|
+
}
|
|
1708
|
+
unfollowed = { said: what, tries: (unfollowed?.tries ?? 0) + 1 };
|
|
1709
|
+
return false;
|
|
1710
|
+
}
|
|
1711
|
+
if (unfollowed !== void 0) {
|
|
1712
|
+
console.log(
|
|
1713
|
+
`[moss:generation] followed the generation pointer to ${n}, after ${unfollowed.tries} ${unfollowed.tries === 1 ? "look" : "looks"} that failed \u2014 this process serves what the rows say again`
|
|
1714
|
+
);
|
|
1715
|
+
unfollowed = void 0;
|
|
1044
1716
|
}
|
|
1045
|
-
|
|
1046
|
-
};
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
...owners.tables ?? []
|
|
1055
|
-
];
|
|
1056
|
-
};
|
|
1057
|
-
var misfitOf = (entry2, schema) => {
|
|
1058
|
-
if (!("mutation" in entry2)) {
|
|
1059
|
-
try {
|
|
1060
|
-
resolve(pruneOptional(entry2.dsl, "all"), schema);
|
|
1061
|
-
return void 0;
|
|
1062
|
-
} catch (error) {
|
|
1063
|
-
return error instanceof Error ? error.message : String(error);
|
|
1717
|
+
return true;
|
|
1718
|
+
};
|
|
1719
|
+
const move = async () => {
|
|
1720
|
+
for (let attempt = 0; attempt < MOVE_ATTEMPTS; attempt += 1) {
|
|
1721
|
+
const n = await pointer.read();
|
|
1722
|
+
if (await pointer.move(n)) {
|
|
1723
|
+
if (seen === n || seen === -1) seen = n + 1;
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1064
1726
|
}
|
|
1065
|
-
|
|
1066
|
-
|
|
1727
|
+
throw new Error(`the pointer moved under this process ${MOVE_ATTEMPTS} times in a row`);
|
|
1728
|
+
};
|
|
1729
|
+
void poll();
|
|
1730
|
+
const timer = everyMs > 0 && everyMs <= MAX_INTERVAL_MS ? setInterval(() => void poll(), everyMs) : void 0;
|
|
1731
|
+
timer?.unref?.();
|
|
1732
|
+
return {
|
|
1733
|
+
bump: () => {
|
|
1734
|
+
void move().catch((err) => console.error("[moss:generation] could not move the pointer", err));
|
|
1735
|
+
},
|
|
1736
|
+
current: () => seen,
|
|
1737
|
+
stop: () => {
|
|
1738
|
+
if (timer !== void 0) clearInterval(timer);
|
|
1739
|
+
}
|
|
1740
|
+
};
|
|
1067
1741
|
};
|
|
1068
|
-
var
|
|
1069
|
-
const
|
|
1070
|
-
|
|
1071
|
-
const why = misfitOf(entry2, schema);
|
|
1072
|
-
if (why !== void 0) misfits.set(entry2.fingerprint, why);
|
|
1073
|
-
}
|
|
1074
|
-
return misfits;
|
|
1742
|
+
var narrowedBy = (filter, ids, installed) => {
|
|
1743
|
+
const answered = new Set(filter(ids, installed));
|
|
1744
|
+
return ids.filter((id) => answered.has(id));
|
|
1075
1745
|
};
|
|
1076
|
-
var
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(Reflect.get(value, key))}`).join(",")}}`;
|
|
1746
|
+
var catalogFor = (app, roles, installed, installedOnly) => {
|
|
1747
|
+
const granted = [...resolvePrincipal(app.charter, Object.keys(app.actions), roles, "actions")].sort();
|
|
1748
|
+
const ids = [...installedOnly(granted, installed === void 0 ? void 0 : new Set(installed))];
|
|
1749
|
+
return { ids, hash: versionToken(ids) };
|
|
1081
1750
|
};
|
|
1082
|
-
var
|
|
1083
|
-
const
|
|
1084
|
-
|
|
1085
|
-
if ("mutation" in entry2) return held.kind === "mutation" && canonical(held.mutation) === canonical(entry2.mutation);
|
|
1086
|
-
return held.kind === "ok" && canonical(held.dsl) === canonical(entry2.dsl);
|
|
1751
|
+
var resolveVariantsForRoles = (app, roles) => {
|
|
1752
|
+
const variants = app.layouts ?? {};
|
|
1753
|
+
return variantLayouts(variants, resolvePrincipal(app.charter, Object.keys(variants), roles, "layouts"));
|
|
1087
1754
|
};
|
|
1088
|
-
var
|
|
1089
|
-
|
|
1090
|
-
const
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1755
|
+
var definitionsFor = (actions, ids, variants) => Object.freeze(Object.fromEntries(withVariants(actions, ids, variants)));
|
|
1756
|
+
var actionsWithStoredLayouts = (definitions) => {
|
|
1757
|
+
const actions = {};
|
|
1758
|
+
const layouts = {};
|
|
1759
|
+
for (const [id, definition] of Object.entries(definitions)) {
|
|
1760
|
+
const layout = definition.layout;
|
|
1761
|
+
if (layout === void 0 || typeof layout === "string") {
|
|
1762
|
+
actions[id] = definition;
|
|
1095
1763
|
continue;
|
|
1096
1764
|
}
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
else if (kept.type !== field.type) retyped.push(`${was.table}.${field.name} (${field.type} \u2192 ${kept.type})`);
|
|
1101
|
-
}
|
|
1765
|
+
const ref = actionLayoutRef(id);
|
|
1766
|
+
layouts[ref] = layout;
|
|
1767
|
+
actions[id] = { ...definition, layout: { ref } };
|
|
1102
1768
|
}
|
|
1103
|
-
return {
|
|
1769
|
+
return { actions: Object.freeze(actions), layouts: Object.freeze(layouts) };
|
|
1104
1770
|
};
|
|
1105
|
-
var
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1771
|
+
var createRoleMemo = (config) => {
|
|
1772
|
+
const catalogs = /* @__PURE__ */ new Map();
|
|
1773
|
+
const variants = /* @__PURE__ */ new Map();
|
|
1774
|
+
const stored = /* @__PURE__ */ new Map();
|
|
1775
|
+
const kept = (memo, key, resolve2) => {
|
|
1776
|
+
const hit = memo.get(key);
|
|
1777
|
+
if (hit !== void 0) return hit;
|
|
1778
|
+
const resolved = resolve2();
|
|
1779
|
+
memo.set(key, resolved);
|
|
1780
|
+
return resolved;
|
|
1111
1781
|
};
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
const report = await migrate(runtime.pool, tableSequencesOf(owners), {
|
|
1125
|
-
...options.dryRun === true ? { dryRun: true } : {},
|
|
1126
|
-
guard: async (tx) => {
|
|
1127
|
-
const after = await createPostgresAdapter({ pool: { query: oneAtATime((text, values) => tx.query(text, values)) } }).introspect();
|
|
1128
|
-
const refused = [];
|
|
1129
|
-
const alreadyBroken = [];
|
|
1130
|
-
for (const [fingerprint, why] of misfitsOf(entries, after)) {
|
|
1131
|
-
if (excused.has(fingerprint)) alreadyBroken.push(`${fingerprint}: ${why}`);
|
|
1132
|
-
else refused.push(`${fingerprint}: ${why}`);
|
|
1133
|
-
}
|
|
1134
|
-
found = { ...changesBetween(before, after), alreadyBroken };
|
|
1135
|
-
return refused;
|
|
1136
|
-
}
|
|
1137
|
-
});
|
|
1138
|
-
return { ...report, ...found, ...report.applied.length === 0 ? { removed: [], retyped: [] } : {} };
|
|
1139
|
-
};
|
|
1140
|
-
var featureTablesOf = (app) => {
|
|
1141
|
-
const features = /* @__PURE__ */ new Set();
|
|
1142
|
-
return (app.features ?? []).map((feature) => {
|
|
1143
|
-
if (features.has(feature.name)) {
|
|
1144
|
-
throw new Error(`moss: two features are named "${feature.name}". A feature's name says whose a table and a set of actions are, so no two features of an app share one.`);
|
|
1782
|
+
const roleMemo = {
|
|
1783
|
+
catalogFor: (roles, installed) => kept(catalogs, memoKey(roles, installed), () => catalogFor(config.manifest(), roles, installed, config.installedOnly)),
|
|
1784
|
+
variantsFor: (roles) => kept(variants, memoKey(roles, void 0), () => resolveVariantsForRoles(config.manifest(), roles)),
|
|
1785
|
+
storedLayoutsFor: (roles, installed) => kept(
|
|
1786
|
+
stored,
|
|
1787
|
+
memoKey(roles, installed),
|
|
1788
|
+
() => actionsWithStoredLayouts(definitionsFor(config.manifest().actions, roleMemo.catalogFor(roles, installed).ids, roleMemo.variantsFor(roles)))
|
|
1789
|
+
),
|
|
1790
|
+
drop: () => {
|
|
1791
|
+
catalogs.clear();
|
|
1792
|
+
variants.clear();
|
|
1793
|
+
stored.clear();
|
|
1145
1794
|
}
|
|
1146
|
-
features.add(feature.name);
|
|
1147
|
-
const names = feature.tables?.names ?? [];
|
|
1148
|
-
return { feature: feature.name, names, sequences: feature.tables?.sequences ?? [] };
|
|
1149
|
-
});
|
|
1150
|
-
};
|
|
1151
|
-
var createDataLayer = async (deps) => {
|
|
1152
|
-
const adapter = createPostgresAdapter({ pool: deps.pool });
|
|
1153
|
-
const cache = deps.cache ?? createPostgresCache({ pool: deps.pool });
|
|
1154
|
-
await cache.init?.();
|
|
1155
|
-
const engine = createQueryEngine({ adapter, cache, ...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {} });
|
|
1156
|
-
const schema = await engine.introspect();
|
|
1157
|
-
return { engine, adapter, schema, grants: scopeGrants(schema.entities.map((e) => e.name)) };
|
|
1158
|
-
};
|
|
1159
|
-
var grammarsOf = (app) => [
|
|
1160
|
-
NOVA_SEQUENCE,
|
|
1161
|
-
PRISM_SEQUENCE,
|
|
1162
|
-
...app.grammars ?? []
|
|
1163
|
-
];
|
|
1164
|
-
var createGrammarUpgrader = (app) => createUpgrader(grammarsOf(app), { transform: evaluate });
|
|
1165
|
-
var vexRecordToSpan = (rec) => ({
|
|
1166
|
-
name: "vex.execute",
|
|
1167
|
-
startUnixNano: rec.startUnixNano,
|
|
1168
|
-
endUnixNano: rec.endUnixNano,
|
|
1169
|
-
status: rec.status,
|
|
1170
|
-
attributes: {
|
|
1171
|
-
op: rec.kind,
|
|
1172
|
-
hasPrincipal: (rec.scope["userId"] ?? "anonymous") !== "anonymous",
|
|
1173
|
-
...rec.fingerprint !== void 0 ? { fingerprint: rec.fingerprint } : {},
|
|
1174
|
-
...rec.reach !== void 0 ? { reach: rec.reach } : {},
|
|
1175
|
-
...rec.cacheHit !== void 0 ? { cache: rec.cacheHit ? "hit" : "miss" } : {},
|
|
1176
|
-
...rec.rows !== void 0 ? { rows: rec.rows } : {}
|
|
1177
|
-
}
|
|
1178
|
-
});
|
|
1179
|
-
var resultOf = (body) => body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
|
|
1180
|
-
var messageOf = (body) => body !== null && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : "no reason given";
|
|
1181
|
-
var createOwnEntries = (deps) => async (own) => {
|
|
1182
|
-
const cache = createMemoryCache();
|
|
1183
|
-
await seedCache(cache, own.entries);
|
|
1184
|
-
const schema = await deps.adapter.introspect({ entities: [...own.tables] });
|
|
1185
|
-
const engine = createQueryEngine({
|
|
1186
|
-
adapter: { id: deps.adapter.id, compile: deps.adapter.compile, execute: deps.adapter.execute, capabilities: deps.adapter.capabilities, introspect: async () => schema },
|
|
1187
|
-
cache
|
|
1188
|
-
});
|
|
1189
|
-
await engine.introspect();
|
|
1190
|
-
const policy = { default: "deny", entities: Object.fromEntries(own.tables.map((table) => [table, { public: true }])) };
|
|
1191
|
-
const reachable = new Set((await handleDiscovery({ engine, locked: true, scopePolicy: policy })).fingerprints.map((listed) => listed.fingerprint));
|
|
1192
|
-
const outside = own.entries.map((entry2) => entry2.fingerprint).filter((fingerprint) => !reachable.has(fingerprint));
|
|
1193
|
-
if (outside.length > 0) {
|
|
1194
|
-
throw new Error(
|
|
1195
|
-
`moss: ${own.owner} handed over ${outside.length === 1 ? "an entry that reads or writes" : "entries that read or write"} a table that is not its own: ${outside.map((fingerprint) => `"${fingerprint}"`).join(", ")}. Its own entries run outside the app's policy, so they reach ${own.tables.length === 0 ? "no table, because it names none as its own" : `the tables that are its own (${own.tables.join(", ")}) and no other`}. What another table holds is read through the app's entries, under the charter.`
|
|
1196
|
-
);
|
|
1197
|
-
}
|
|
1198
|
-
return async (fingerprint, context) => {
|
|
1199
|
-
const outcome = await handleQuery(
|
|
1200
|
-
{
|
|
1201
|
-
engine,
|
|
1202
|
-
locked: true,
|
|
1203
|
-
scopePolicy: policy,
|
|
1204
|
-
mutations: { client: deps.db, policy, onWrite: (event) => deps.engine.invalidate(tablesChangedBy(event.writes, schema)) },
|
|
1205
|
-
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
|
|
1206
|
-
},
|
|
1207
|
-
{ fingerprint, context },
|
|
1208
|
-
{}
|
|
1209
|
-
);
|
|
1210
|
-
if (outcome.status !== 200) throw new Error(`moss: the entry "${fingerprint}" was refused (${outcome.status}): ${messageOf(outcome.body)}`);
|
|
1211
|
-
return resultOf(outcome.body);
|
|
1212
1795
|
};
|
|
1796
|
+
return roleMemo;
|
|
1213
1797
|
};
|
|
1214
|
-
var
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
};
|
|
1221
|
-
var movePointerEntry = {
|
|
1222
|
-
fingerprint: "moss/generation-move",
|
|
1223
|
-
intent: "Move the generation pointer to the next number, if it is still where it was read",
|
|
1224
|
-
mutation: {
|
|
1225
|
-
op: "update",
|
|
1226
|
-
table: TABLE,
|
|
1227
|
-
set: { n: { $context: "next" } },
|
|
1228
|
-
where: { and: [THE_ROW, { eq: [`${TABLE}.n`, { $context: "seen" }] }] }
|
|
1798
|
+
var versionToken = (ids) => {
|
|
1799
|
+
const s = ids.join("\n");
|
|
1800
|
+
let h = 2166136261;
|
|
1801
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
1802
|
+
h ^= s.charCodeAt(i);
|
|
1803
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
1229
1804
|
}
|
|
1805
|
+
return h.toString(16).padStart(8, "0");
|
|
1230
1806
|
};
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
var
|
|
1234
|
-
var
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
// answers no row, which does not parse: the counter moved since it was read.
|
|
1241
|
-
move: async (from) => RowSchema.safeParse(await (await replay())(movePointerEntry.fingerprint, { seen: from, next: from + 1 })).success
|
|
1242
|
-
});
|
|
1243
|
-
var resolvePolicyForRoles = (app, grants, roles) => {
|
|
1244
|
-
const behaviors = app.behaviors ?? {};
|
|
1245
|
-
return mergeScopePolicies(
|
|
1246
|
-
roles.map(
|
|
1247
|
-
(role) => createScopePolicy(resolvePrincipal(app.charter, grants, [role], "data"), behaviors, resolveScoping(app.charter, role))
|
|
1248
|
-
)
|
|
1249
|
-
);
|
|
1807
|
+
|
|
1808
|
+
// src/artifactory/running.ts
|
|
1809
|
+
var mergedActions = (own, sets) => Object.freeze([...sets.values()].reduce((all, set) => ({ ...all, ...set }), { ...own }));
|
|
1810
|
+
var tell = (listener, ...told) => {
|
|
1811
|
+
try {
|
|
1812
|
+
listener(...told);
|
|
1813
|
+
} catch (error) {
|
|
1814
|
+
console.error("[moss:manifest] a listener to a manifest change threw:", error);
|
|
1815
|
+
}
|
|
1250
1816
|
};
|
|
1251
|
-
var
|
|
1252
|
-
|
|
1253
|
-
const
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
return {
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
},
|
|
1265
|
-
atReach: (who, reach) => {
|
|
1266
|
-
const key = `${who.memoKey}\0${reach}`;
|
|
1267
|
-
const hit = reachPolicies.get(key);
|
|
1268
|
-
if (hit !== void 0) return hit;
|
|
1269
|
-
const compiled = resolvePolicyAtReachForRoles(governed, grants, who.roles, reach);
|
|
1270
|
-
reachPolicies.set(key, compiled);
|
|
1271
|
-
return compiled;
|
|
1817
|
+
var createSetOwners = () => {
|
|
1818
|
+
const owners = /* @__PURE__ */ new Map();
|
|
1819
|
+
const ownerRefusalOf = (source) => {
|
|
1820
|
+
const owner = owners.get(source);
|
|
1821
|
+
return owner === void 0 ? void 0 : `the set "${source}" is ${owner}'s, and only its owner replaces it. An app hands a set over under a name of its own.`;
|
|
1822
|
+
};
|
|
1823
|
+
return {
|
|
1824
|
+
ownerRefusalOf,
|
|
1825
|
+
claim: (source, owner, handedOver) => {
|
|
1826
|
+
const held = owners.get(source);
|
|
1827
|
+
if (held !== void 0) throw new Error(`moss: the set "${source}" is ${held}'s, and ${owner} claims it too. A set has one writer.`);
|
|
1828
|
+
if (handedOver) throw new Error(`moss: the set "${source}" was handed over by the app, and ${owner} claims it. A set has one writer.`);
|
|
1829
|
+
owners.set(source, owner);
|
|
1272
1830
|
},
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1831
|
+
assertAppOwned: (source) => {
|
|
1832
|
+
const refusal = ownerRefusalOf(source);
|
|
1833
|
+
if (refusal !== void 0) throw new Error(`moss: ${refusal}`);
|
|
1834
|
+
return source;
|
|
1276
1835
|
}
|
|
1277
1836
|
};
|
|
1278
1837
|
};
|
|
1279
|
-
var
|
|
1280
|
-
const
|
|
1281
|
-
const
|
|
1282
|
-
const
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
locked: true,
|
|
1286
|
-
scopePolicy: policy,
|
|
1287
|
-
policyForReach: (reach) => deps.policyAtReach(roles, reach),
|
|
1288
|
-
mutations: { client: deps.db, policy },
|
|
1289
|
-
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {}
|
|
1290
|
-
},
|
|
1291
|
-
{ fingerprint, context },
|
|
1292
|
-
scope
|
|
1293
|
-
);
|
|
1294
|
-
if (outcome.status !== 200) {
|
|
1295
|
-
console.error(`[moss:executeAs] "${fingerprint}" as "${role}" refused (${outcome.status})`, outcome.body);
|
|
1296
|
-
return void 0;
|
|
1297
|
-
}
|
|
1298
|
-
const body = outcome.body;
|
|
1299
|
-
return body !== null && typeof body === "object" && "result" in body ? body.result : void 0;
|
|
1838
|
+
var verifiedAtBoot = (candidate) => {
|
|
1839
|
+
const report = verifyManifest(candidate);
|
|
1840
|
+
for (const line of report.said) console.error(`[moss] ${line}`);
|
|
1841
|
+
const refused = refusalOf(report, "boot");
|
|
1842
|
+
if (refused !== void 0) throw new Error(refused);
|
|
1843
|
+
return report;
|
|
1300
1844
|
};
|
|
1301
|
-
var
|
|
1302
|
-
|
|
1303
|
-
header: (name) => CREDENTIALS.has(name.toLowerCase()) ? void 0 : header(name)
|
|
1304
|
-
});
|
|
1305
|
-
var SAID_NOTHING = { header: () => void 0 };
|
|
1306
|
-
var createWriteNotifier = () => {
|
|
1307
|
-
const requests = new AsyncLocalStorage();
|
|
1308
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
1845
|
+
var createComponentNames = (read2) => {
|
|
1846
|
+
let components = /* @__PURE__ */ new WeakMap();
|
|
1309
1847
|
return {
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1848
|
+
of: (shell) => {
|
|
1849
|
+
const kept = components.get(shell);
|
|
1850
|
+
if (kept !== void 0) return kept;
|
|
1851
|
+
const names = read2(shell);
|
|
1852
|
+
components.set(shell, names);
|
|
1853
|
+
return names;
|
|
1315
1854
|
},
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
const request = requests.getStore() ?? SAID_NOTHING;
|
|
1319
|
-
for (const listener of [...listeners]) {
|
|
1320
|
-
try {
|
|
1321
|
-
listener(event, request);
|
|
1322
|
-
} catch (error) {
|
|
1323
|
-
console.error(`[moss:writes] somebody told of the write "${event.fingerprint}" failed. The others are still told:`, error);
|
|
1324
|
-
}
|
|
1325
|
-
}
|
|
1855
|
+
drop: () => {
|
|
1856
|
+
components = /* @__PURE__ */ new WeakMap();
|
|
1326
1857
|
}
|
|
1327
1858
|
};
|
|
1328
1859
|
};
|
|
1329
|
-
var
|
|
1330
|
-
const
|
|
1331
|
-
const
|
|
1332
|
-
|
|
1860
|
+
var createRunningManifest = (config) => {
|
|
1861
|
+
const { shipped } = config;
|
|
1862
|
+
const entries = createEntriesInForce(entriesOf(shipped));
|
|
1863
|
+
const candidate = (actions, held = entries.list()) => candidateOf(shipped, { actions, entries: held }, config.grants);
|
|
1864
|
+
const own = shipped.actions;
|
|
1865
|
+
const loaders = /* @__PURE__ */ new Map();
|
|
1866
|
+
const owners = createSetOwners();
|
|
1867
|
+
let sets = /* @__PURE__ */ new Map();
|
|
1868
|
+
let inForce2 = mergedActions(own, sets);
|
|
1869
|
+
let report = verifiedAtBoot(candidate(inForce2));
|
|
1870
|
+
const components = createComponentNames((shell) => shellComponents({ actions: inForce2, layouts: shipped.layouts }, shell));
|
|
1871
|
+
const componentsOf2 = (shells) => {
|
|
1872
|
+
const kit = /* @__PURE__ */ new Map();
|
|
1873
|
+
for (const shell of shells) {
|
|
1874
|
+
for (const [name, contract] of Object.entries(components.of(shell))) kit.set(name, { propsSchema: contract.meta?.propsSchema ?? kit.get(name)?.propsSchema });
|
|
1875
|
+
}
|
|
1876
|
+
return kit;
|
|
1333
1877
|
};
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
const
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1878
|
+
let ofTheApp;
|
|
1879
|
+
const catalogFilters = config.installedOnly === void 0 ? [] : [config.installedOnly];
|
|
1880
|
+
const roleMemo = createRoleMemo({
|
|
1881
|
+
manifest: () => ({ charter: shipped.charter, actions: inForce2, layouts: shipped.layouts }),
|
|
1882
|
+
installedOnly: (ids, installed) => catalogFilters.reduce((kept, narrow) => narrowedBy(narrow, kept, installed), ids)
|
|
1883
|
+
});
|
|
1884
|
+
const kitOf2 = (shell) => shell === void 0 ? ofTheApp ??= componentsOf2(config.shells) : componentsOf2([shell]);
|
|
1885
|
+
const ownShell = shipped.shell;
|
|
1886
|
+
const ownShellRefs = new Set(ownShell === void 0 ? [] : Object.keys(shellWithStoredLayouts(ownShell).layouts));
|
|
1887
|
+
const heldTo = ({ actions, layouts }, shell) => {
|
|
1888
|
+
const kit = kitOf2(shell);
|
|
1889
|
+
return {
|
|
1890
|
+
kit,
|
|
1891
|
+
// A layout saved for the frame or a canvas is the app's own shell's, whichever shell it is saved from.
|
|
1892
|
+
...ownShell !== void 0 && (shell === void 0 || shell === ownShell) ? { ownShell: { refs: ownShellRefs, kit: shell === ownShell ? kit : kitOf2(ownShell) } } : {},
|
|
1893
|
+
actionAt: (ref) => {
|
|
1894
|
+
const id = actionOfLayoutRef(ref);
|
|
1895
|
+
const action = id !== void 0 && Object.hasOwn(actions, id) ? actions[id] : void 0;
|
|
1896
|
+
const layout = Object.hasOwn(layouts, ref) ? layouts[ref] : void 0;
|
|
1897
|
+
return action === void 0 || layout === void 0 ? void 0 : { ...action, layout };
|
|
1344
1898
|
}
|
|
1345
|
-
|
|
1346
|
-
}
|
|
1899
|
+
};
|
|
1347
1900
|
};
|
|
1348
|
-
const
|
|
1349
|
-
|
|
1901
|
+
const { reads: readSources } = config;
|
|
1902
|
+
let functionsChecked = false;
|
|
1903
|
+
const sayFunctionGrants = (names) => {
|
|
1904
|
+
functionsChecked = true;
|
|
1905
|
+
const universes = { actions: Object.keys(inForce2), data: config.grants, layouts: Object.keys(shipped.layouts ?? {}) };
|
|
1906
|
+
const before = verifyCharter(shipped.charter, universes);
|
|
1907
|
+
const known = new Set([...before.errors, ...before.warnings].map((issue) => issue.detail));
|
|
1908
|
+
const after = verifyCharter(shipped.charter, { ...universes, functions: names });
|
|
1909
|
+
for (const issue of [...after.errors, ...after.warnings]) if (!known.has(issue.detail)) console.warn(`[moss] charter: ${issue.detail}`);
|
|
1910
|
+
};
|
|
1911
|
+
const grantedFunctionsOf = (roles) => (names) => {
|
|
1912
|
+
if (!functionsChecked) sayFunctionGrants(names);
|
|
1913
|
+
return resolvePrincipal(shipped.charter, names, roles, "functions");
|
|
1914
|
+
};
|
|
1915
|
+
const readsHeldTo = readSources === void 0 ? void 0 : { isAppEntry: (fingerprint) => entries.byFingerprint().has(fingerprint), sources: readSources };
|
|
1916
|
+
const heldWithGenerated = async (held, versions, who, shell, whose) => {
|
|
1917
|
+
let replayable;
|
|
1918
|
+
let catalog;
|
|
1919
|
+
const reads = readsHeldTo === void 0 ? /* @__PURE__ */ new Map() : await readsInForce(versions, readsHeldTo, whose);
|
|
1920
|
+
const checks = {
|
|
1921
|
+
kit: kitOf2(shell),
|
|
1922
|
+
entryOf: (fingerprint) => {
|
|
1923
|
+
const read2 = reads.get(fingerprint);
|
|
1924
|
+
return entries.byFingerprint().get(fingerprint) ?? (read2 === void 0 ? void 0 : seedOf(fingerprint, read2));
|
|
1925
|
+
},
|
|
1926
|
+
replayable: () => replayable ??= (async () => /* @__PURE__ */ new Set([...await who.replayable?.() ?? [], ...reads.keys()]))(),
|
|
1927
|
+
mayCall: (name) => who.roles !== void 0 && resolvePrincipal(shipped.charter, [name], who.roles, "functions").has(name),
|
|
1928
|
+
catalog: () => catalog ??= [...Object.values(held.actions).map((action) => ({ id: action.id, input: action.input ?? {} })), ...catalogOfGenerated(versions)]
|
|
1350
1929
|
};
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1930
|
+
const passed = await generatedInForce(versions, checks, whose);
|
|
1931
|
+
const stored = actionsWithStoredLayouts(passed.actions);
|
|
1932
|
+
const all = Object.keys(passed.actions).length === 0 ? held : { actions: { ...held.actions, ...stored.actions }, layouts: { ...held.layouts, ...stored.layouts } };
|
|
1933
|
+
return { all, fragments: passed.fragments, heldTo: { layouts: heldTo(all, shell), generated: checks, ...readsHeldTo !== void 0 ? { reads: readsHeldTo } : {} } };
|
|
1934
|
+
};
|
|
1935
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1936
|
+
const listenersFor = /* @__PURE__ */ new Set();
|
|
1937
|
+
const sessionDeps = (principal, callerOf, shell) => ({
|
|
1938
|
+
whose: "of yours",
|
|
1939
|
+
kinds: readSources === void 0 ? ["layout", "action", "fragment"] : ["layout", "action", "fragment", "read"],
|
|
1940
|
+
holder: principal === null ? void 0 : async () => {
|
|
1941
|
+
const caller = await callerOf();
|
|
1942
|
+
const held = roleMemo.storedLayoutsFor(caller.roles, caller.installed);
|
|
1943
|
+
return { saved: caller.saved, heldTo: async (inForce3) => (await heldWithGenerated(held, inForce3, caller, shell)).heldTo };
|
|
1944
|
+
},
|
|
1945
|
+
written: () => {
|
|
1946
|
+
if (principal !== null) for (const listener of [...listenersFor]) tell(listener, principal);
|
|
1356
1947
|
}
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1948
|
+
});
|
|
1949
|
+
let pointer;
|
|
1950
|
+
let published;
|
|
1951
|
+
let saidOfPublished = /* @__PURE__ */ new Set();
|
|
1952
|
+
const dropPublished = () => {
|
|
1953
|
+
published = void 0;
|
|
1954
|
+
saidOfPublished = /* @__PURE__ */ new Set();
|
|
1955
|
+
};
|
|
1956
|
+
const publishedNow = () => {
|
|
1957
|
+
if (published !== void 0) return published;
|
|
1958
|
+
const read2 = (async () => await config.published?.() ?? [])();
|
|
1959
|
+
published = read2;
|
|
1960
|
+
read2.catch(dropPublished);
|
|
1961
|
+
return read2;
|
|
1962
|
+
};
|
|
1963
|
+
const sayOnce = (line) => {
|
|
1964
|
+
if (saidOfPublished.has(line)) return;
|
|
1965
|
+
saidOfPublished.add(line);
|
|
1966
|
+
console.error(line);
|
|
1361
1967
|
};
|
|
1362
|
-
const
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1968
|
+
const applySets = (arrived, announce) => {
|
|
1969
|
+
const next = new Map([...sets, ...arrived]);
|
|
1970
|
+
const actions = mergedActions(own, next);
|
|
1971
|
+
const verified = verifyManifest(candidate(actions));
|
|
1972
|
+
const refusal = refusalOf(verified, "refresh");
|
|
1973
|
+
if (refusal !== void 0) throw new Error(refusal);
|
|
1974
|
+
for (const set of arrived.values()) freezeDeep(set);
|
|
1975
|
+
sets = next;
|
|
1976
|
+
inForce2 = actions;
|
|
1977
|
+
report = verified;
|
|
1978
|
+
roleMemo.drop();
|
|
1979
|
+
components.drop();
|
|
1980
|
+
ofTheApp = void 0;
|
|
1981
|
+
for (const listener of [...listeners]) tell(listener);
|
|
1982
|
+
if (announce) pointer?.bump();
|
|
1366
1983
|
};
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
const routes = new Hono();
|
|
1373
|
-
routes.use(
|
|
1374
|
-
"/api/*",
|
|
1375
|
-
(c, next) => deps.writes.within(
|
|
1376
|
-
writeRequestOf((name) => c.req.header(name)),
|
|
1377
|
-
() => next()
|
|
1378
|
-
)
|
|
1379
|
-
);
|
|
1380
|
-
const mount = (path, entities) => {
|
|
1381
|
-
routes.route(
|
|
1382
|
-
path,
|
|
1383
|
-
vex({
|
|
1384
|
-
engine: deps.engine,
|
|
1385
|
-
...entities !== void 0 ? { entities: [...entities] } : {},
|
|
1386
|
-
locked: true,
|
|
1387
|
-
getScope: deps.scope,
|
|
1388
|
-
getPolicy: deps.policy,
|
|
1389
|
-
getPolicyForReach: deps.policyAtReach,
|
|
1390
|
-
...deps.onExecute !== void 0 ? { onExecute: deps.onExecute } : {},
|
|
1391
|
-
mutations: { client: deps.db, onWrite: deps.writes.report }
|
|
1392
|
-
})
|
|
1393
|
-
);
|
|
1984
|
+
const reload = async () => {
|
|
1985
|
+
const read2 = [];
|
|
1986
|
+
for (const [source, load] of loaders) read2.push([source, await load()]);
|
|
1987
|
+
dropPublished();
|
|
1988
|
+
applySets(new Map(read2), false);
|
|
1394
1989
|
};
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
}
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
const
|
|
1407
|
-
|
|
1408
|
-
const engine = createQueryEngine({
|
|
1409
|
-
adapter: { id: adapter.id, compile: adapter.compile, execute: adapter.execute, capabilities: adapter.capabilities, introspect: async () => schema },
|
|
1410
|
-
cache: deps.cache,
|
|
1411
|
-
generateDsl: writers.generateDsl,
|
|
1412
|
-
mapToShape: writers.mapToShape,
|
|
1413
|
-
...deps.behaviors !== void 0 ? { behaviors: deps.behaviors } : {},
|
|
1414
|
-
...deps.vexConfig !== void 0 ? { config: deps.vexConfig } : {}
|
|
1415
|
-
});
|
|
1416
|
-
await engine.introspect();
|
|
1417
|
-
return engine;
|
|
1418
|
-
})();
|
|
1419
|
-
engines.set(writers, created);
|
|
1420
|
-
return created;
|
|
1990
|
+
const takeEntries = async (source, handed) => {
|
|
1991
|
+
owners.assertAppOwned(source);
|
|
1992
|
+
const misfits = entryMisfits(handed);
|
|
1993
|
+
if (misfits.length > 0) throw new Error(["Refresh refused \u2014 entries that do not parse:", ...misfits.map((misfit) => ` ${misfit}`)].join("\n"));
|
|
1994
|
+
const compiled = await compileEntries(handed);
|
|
1995
|
+
const verified = verifyManifest(candidate(inForce2, entries.withSet(source, handed)));
|
|
1996
|
+
const refusal = refusalOf(verified, "refresh");
|
|
1997
|
+
if (refusal !== void 0) throw new Error(refusal);
|
|
1998
|
+
freezeDeep(handed);
|
|
1999
|
+
entries.takeSet(source, handed, compiled);
|
|
2000
|
+
report = verified;
|
|
2001
|
+
for (const listener of [...listeners]) tell(listener);
|
|
2002
|
+
pointer?.bump();
|
|
1421
2003
|
};
|
|
1422
|
-
|
|
1423
|
-
};
|
|
1424
|
-
|
|
1425
|
-
// src/data/data.ts
|
|
1426
|
-
var callerOfRoles = (roles) => ({ memoKey: memoKey(roles, void 0), roles });
|
|
1427
|
-
var prepareEngine = async (config) => {
|
|
1428
|
-
await migrate(config.pool, tableSequencesOf(config), { mode: config.migrations ?? "apply" });
|
|
1429
|
-
const grammars = await createGrammarUpgrader({ grammars: config.grammars });
|
|
1430
|
-
const layer = await createDataLayer(config);
|
|
2004
|
+
let entriesTaken = Promise.resolve();
|
|
1431
2005
|
return {
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
2006
|
+
actions: () => inForce2,
|
|
2007
|
+
entries: entries.list,
|
|
2008
|
+
verify: (actions) => verifyManifest(candidate(actions)),
|
|
2009
|
+
report: () => report,
|
|
2010
|
+
replace: (source, actions) => applySets(/* @__PURE__ */ new Map([[owners.assertAppOwned(source), actions]]), true),
|
|
2011
|
+
// In turn: a set is compiled before it is taken, and of two handed over
|
|
2012
|
+
// the later has to be the one in force.
|
|
2013
|
+
replaceEntries: (source, handed) => {
|
|
2014
|
+
const taken = entriesTaken.then(() => takeEntries(source, handed));
|
|
2015
|
+
entriesTaken = taken.catch(() => void 0);
|
|
2016
|
+
return taken;
|
|
2017
|
+
},
|
|
2018
|
+
cacheEntry: async (fingerprint, scope) => {
|
|
2019
|
+
const shippedEntry = (await entries.compiled()).get(fingerprint);
|
|
2020
|
+
const userId = scope?.["userId"];
|
|
2021
|
+
if (shippedEntry !== void 0 || readSources === void 0 || scope === void 0 || typeof userId !== "string" || userId === NOBODY_USER_ID) return shippedEntry;
|
|
2022
|
+
const newest = (await readSources.savedOf(scope).history("read", fingerprint))[0];
|
|
2023
|
+
if (newest === void 0 || newest.body === null || newest.unread !== void 0) return void 0;
|
|
2024
|
+
return answeredRead(fingerprint, newest.body);
|
|
2025
|
+
},
|
|
2026
|
+
cacheEntries: async () => [...await entries.compiled()].map(([key, entry]) => ({ key, entry })),
|
|
2027
|
+
claim: (source, owner) => {
|
|
2028
|
+
owners.claim(source, owner, sets.has(source) || entries.holdsSet(source));
|
|
2029
|
+
return {
|
|
2030
|
+
replace: (actions) => applySets(/* @__PURE__ */ new Map([[source, actions]]), true),
|
|
2031
|
+
setLoader: (load) => {
|
|
2032
|
+
loaders.set(source, load);
|
|
2033
|
+
if (!sets.has(source)) sets = new Map([...sets, [source, {}]]);
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
},
|
|
2037
|
+
refresh: () => applySets(/* @__PURE__ */ new Map(), true),
|
|
2038
|
+
watch: () => {
|
|
2039
|
+
const where = config.pointer;
|
|
2040
|
+
if (pointer !== void 0 || where === void 0) return;
|
|
2041
|
+
pointer = createGeneration({ read: where.read, move: where.move }, { onMoved: reload, ...where.everyMs === void 0 ? {} : { everyMs: where.everyMs } });
|
|
2042
|
+
},
|
|
2043
|
+
onChange: (listener) => {
|
|
2044
|
+
listeners.add(listener);
|
|
2045
|
+
return () => {
|
|
2046
|
+
listeners.delete(listener);
|
|
2047
|
+
};
|
|
2048
|
+
},
|
|
2049
|
+
addCatalogFilter: (filter) => {
|
|
2050
|
+
catalogFilters.push(filter);
|
|
2051
|
+
roleMemo.drop();
|
|
2052
|
+
},
|
|
2053
|
+
catalogFor: roleMemo.catalogFor,
|
|
2054
|
+
artifactsFor: async (shell, { principal, roles, installed, saved, replayable, drafted }) => {
|
|
2055
|
+
const versions = saved === void 0 || principal === null ? [] : laidOver(await saved.inForce(), drafted);
|
|
2056
|
+
const whose = `of ${principal ?? "nobody"}`;
|
|
2057
|
+
const theirOwn = await heldWithGenerated(roleMemo.storedLayoutsFor(roles, installed), versions, { replayable, roles }, shell, whose);
|
|
2058
|
+
const drawable = theirOwn.heldTo.layouts;
|
|
2059
|
+
const theirs2 = layoutsInUse(versions, { whose, heldTo: drawable });
|
|
2060
|
+
const variants = roleMemo.variantsFor(roles);
|
|
2061
|
+
const underVariants = { ...drawable, actionAt: (ref) => variants.has(actionOfLayoutRef(ref) ?? "") ? void 0 : drawable.actionAt(ref) };
|
|
2062
|
+
const everybodys = layoutsInUse(await publishedNow(), { whose: "published for everybody", heldTo: underVariants, say: sayOnce });
|
|
2063
|
+
const fragments = Object.keys(theirOwn.fragments).length === 0 ? shell.fragments : { ...shell.fragments, ...theirOwn.fragments };
|
|
2064
|
+
const { layouts: ofShell, ...named } = shellWithStoredLayouts(shell);
|
|
2065
|
+
const layoutStore = { ...shell.layoutStore, ...ofShell, ...theirOwn.all.layouts, ...everybodys, ...theirs2 };
|
|
2066
|
+
return {
|
|
2067
|
+
actions: theirOwn.all.actions,
|
|
2068
|
+
...named,
|
|
2069
|
+
slottedCanvases: slottedCanvases(shell.canvases, [...Object.values(layoutStore), ...Object.values(fragments ?? {}).map((fragment) => fragment.layout)]),
|
|
2070
|
+
grantedFunctions: grantedFunctionsOf(roles),
|
|
2071
|
+
layoutStore,
|
|
2072
|
+
...fragments !== void 0 ? { fragments } : {},
|
|
2073
|
+
entries: entries.byFingerprint(),
|
|
2074
|
+
components: components.of(shell)
|
|
2075
|
+
};
|
|
2076
|
+
},
|
|
2077
|
+
sessionArtifacts: (principal, callerOf) => savedArtifacts(sessionDeps(principal, callerOf)),
|
|
2078
|
+
draftSavingFor: (shell, principal, callerOf) => draftSaving(sessionDeps(principal, callerOf, shell)),
|
|
2079
|
+
// Held to every action in force with the layout it is built with: who holds
|
|
2080
|
+
// which is asked when a shell is built for them.
|
|
2081
|
+
publishedArtifacts: (saved) => savedArtifacts({
|
|
2082
|
+
whose: "published for everybody",
|
|
2083
|
+
kinds: ["layout"],
|
|
2084
|
+
holder: async () => ({ saved, heldTo: async () => (await heldWithGenerated(actionsWithStoredLayouts(inForce2), [], {})).heldTo }),
|
|
2085
|
+
written: () => {
|
|
2086
|
+
dropPublished();
|
|
2087
|
+
for (const listener of [...listeners]) tell(listener);
|
|
2088
|
+
pointer?.bump();
|
|
2089
|
+
}
|
|
2090
|
+
}),
|
|
2091
|
+
readPublished: async () => {
|
|
2092
|
+
dropPublished();
|
|
2093
|
+
await publishedNow();
|
|
2094
|
+
},
|
|
2095
|
+
onChangeFor: (listener) => {
|
|
2096
|
+
listenersFor.add(listener);
|
|
2097
|
+
return () => {
|
|
2098
|
+
listenersFor.delete(listener);
|
|
2099
|
+
};
|
|
2100
|
+
},
|
|
2101
|
+
generation: () => pointer?.current() ?? -1,
|
|
2102
|
+
stop: () => pointer?.stop()
|
|
1456
2103
|
};
|
|
1457
|
-
return answering;
|
|
1458
2104
|
};
|
|
1459
|
-
var
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
2105
|
+
var theirs = { match: "principal", to: "userId" };
|
|
2106
|
+
var stamped = { set: "principal", to: "userId" };
|
|
2107
|
+
var MADE_BY = "artifactSavedBy";
|
|
2108
|
+
var madeBy = { set: "created_by", to: MADE_BY };
|
|
2109
|
+
var SAVE_ROW_RULES = {
|
|
2110
|
+
artifacts: { read: [theirs], write: [theirs, stamped] },
|
|
2111
|
+
artifact_saves: { read: [theirs], write: [theirs, stamped, madeBy] }
|
|
1463
2112
|
};
|
|
1464
|
-
var
|
|
1465
|
-
|
|
1466
|
-
if (
|
|
2113
|
+
var EVERYBODY = "*";
|
|
2114
|
+
var callerScope = (scope) => {
|
|
2115
|
+
if (scope["userId"] === EVERYBODY) {
|
|
1467
2116
|
throw new Error(
|
|
1468
|
-
`moss:
|
|
2117
|
+
`moss: a caller\u2019s \`userId\` is "${EVERYBODY}", and that is whose the rows published for everybody are. No caller is it: the app\u2019s sign-in or its \`scope\` answers another.`
|
|
1469
2118
|
);
|
|
1470
2119
|
}
|
|
1471
|
-
if (
|
|
1472
|
-
throw new Error(`moss:
|
|
2120
|
+
if (Object.hasOwn(scope, MADE_BY)) {
|
|
2121
|
+
throw new Error(`moss: a caller\u2019s scope carries \`${MADE_BY}\`. Who made a save is written from that value, and it is moss\u2019s to say: the app\u2019s \`scope\` names its own otherwise.`);
|
|
1473
2122
|
}
|
|
1474
|
-
|
|
1475
|
-
};
|
|
1476
|
-
var
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
const ownEntries = (own, told) => createOwnEntries({ adapter: prepared.adapter, db: config.db, engine, ...told !== void 0 ? { onExecute: told } : {} })(own);
|
|
1485
|
-
const tablesOf = tablesByFeature(config);
|
|
1486
|
-
let pointerEntries;
|
|
1487
|
-
const pointerReplay = () => {
|
|
1488
|
-
pointerEntries ??= ownEntries(POINTER, void 0);
|
|
1489
|
-
return pointerEntries;
|
|
1490
|
-
};
|
|
1491
|
-
return {
|
|
1492
|
-
grants,
|
|
1493
|
-
grammars,
|
|
1494
|
-
seed: (entries) => seedCache(engine.cache, entries),
|
|
1495
|
-
fingerprints: async () => await engine.cache.keys?.() ?? [],
|
|
1496
|
-
policyOf: policies.of,
|
|
1497
|
-
// Compiled afresh and not taken from the kept ones: the caller owns its
|
|
1498
|
-
// copy, and nothing it does to it reaches a policy a request is served under.
|
|
1499
|
-
policyForRoles: (roles) => resolvePolicyForRoles(governed, grants, roles),
|
|
1500
|
-
fingerprintsFor: async (who) => (await handleDiscovery({ engine, locked: true, scopePolicy: policies.of(who) })).fingerprints.map((entry2) => entry2.fingerprint).sort(),
|
|
1501
|
-
executeAs: createExecuteAs({
|
|
1502
|
-
engine,
|
|
1503
|
-
db: config.db,
|
|
1504
|
-
policyFor: (roles) => policies.of(callerOfRoles(roles)),
|
|
1505
|
-
policyAtReach: (roles, reach) => policies.atReach(callerOfRoles(roles), reach),
|
|
1506
|
-
...onExecute !== void 0 ? { onExecute } : {}
|
|
1507
|
-
}),
|
|
1508
|
-
answerIntent: async (writers, asked, who, scope) => answering()(writers, asked, { policy: policies.of(who), scope }),
|
|
1509
|
-
ownEntries: async (feature, entries) => ownEntries({ owner: `the feature "${feature}"`, entries, tables: tablesOf(feature) }, onExecute),
|
|
1510
|
-
routes: (routing) => createVexRoutes({
|
|
1511
|
-
engine,
|
|
1512
|
-
db: config.db,
|
|
1513
|
-
resources: routing.resources,
|
|
1514
|
-
scope: routing.scope,
|
|
1515
|
-
policy: (c) => policies.of(routing.caller(c)),
|
|
1516
|
-
policyAtReach: (c, reach) => policies.atReach(routing.caller(c), reach),
|
|
1517
|
-
...onExecute !== void 0 ? { onExecute } : {},
|
|
1518
|
-
writes
|
|
1519
|
-
}),
|
|
1520
|
-
upgradeStore: createUpgradeStore(prepared, tablesOf),
|
|
1521
|
-
onWrite: writes.subscribe,
|
|
1522
|
-
pointer: createPointer(pointerReplay),
|
|
1523
|
-
dropOnChange: (changed) => {
|
|
1524
|
-
changed(policies.drop);
|
|
1525
|
-
}
|
|
1526
|
-
};
|
|
1527
|
-
};
|
|
1528
|
-
var createData = async (config) => createDataWith(await prepareEngine(config), config);
|
|
1529
|
-
var DEFAULT_ROOT = '<div id="root"></div>';
|
|
1530
|
-
var embedSnapshot = (snapshot, principal, path) => {
|
|
1531
|
-
const { frame, trees, seed, live } = snapshot;
|
|
1532
|
-
const carried = { frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} };
|
|
1533
|
-
const text = JSON.stringify(carried).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1534
|
-
return `<script type="application/json" id="${SNAPSHOT_ELEMENT_ID}">${text}</script>`;
|
|
1535
|
-
};
|
|
1536
|
-
var documentHeaders = (principal) => principal === null ? { "cache-control": "no-cache", vary: "Cookie" } : { "cache-control": "private, no-store", vary: "Cookie" };
|
|
1537
|
-
var rootHolding = (root) => {
|
|
1538
|
-
const closing = root.lastIndexOf("</");
|
|
1539
|
-
if (closing <= 0 || !root.startsWith("<") || root[closing - 1] !== ">" || !root.endsWith(">")) return void 0;
|
|
1540
|
-
return (screen) => `${root.slice(0, closing)}${screen}${root.slice(closing)}`;
|
|
2123
|
+
return scope;
|
|
2124
|
+
};
|
|
2125
|
+
var PAGE = 500;
|
|
2126
|
+
var VERSION_COLUMNS = ["save", "kind", "id", "body", "grammar", "copied_from", "created_at"];
|
|
2127
|
+
var laterThanHeld = {
|
|
2128
|
+
and: [
|
|
2129
|
+
{ eq: ["artifacts.kind", "held.kind"] },
|
|
2130
|
+
{ eq: ["artifacts.id", "held.id"] },
|
|
2131
|
+
{ or: [{ gt: ["artifacts.created_at", "held.created_at"] }, { and: [{ eq: ["artifacts.created_at", "held.created_at"] }, { gt: ["artifacts.save", "held.save"] }] }] }
|
|
2132
|
+
]
|
|
1541
2133
|
};
|
|
1542
|
-
var
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
2134
|
+
var afterHeld = {
|
|
2135
|
+
or: [{ gt: ["held.kind", { $context: "after_kind" }] }, { and: [{ eq: ["held.kind", { $context: "after_kind" }] }, { gt: ["held.id", { $context: "after_id" }] }] }]
|
|
2136
|
+
};
|
|
2137
|
+
var inForce = {
|
|
2138
|
+
fingerprint: "artifactory/in-force",
|
|
2139
|
+
intent: "The latest version of each of the caller\u2019s artifacts, a page at a time",
|
|
2140
|
+
dsl: {
|
|
2141
|
+
from: [{ as: "held", query: { from: ["artifacts"], fields: VERSION_COLUMNS.map((column) => `artifacts.${column}`) } }],
|
|
2142
|
+
fields: VERSION_COLUMNS.map((column) => `held.${column}`),
|
|
2143
|
+
filter: { and: [{ not: { exists: { from: ["artifacts"], filter: laterThanHeld } } }, afterHeld] },
|
|
2144
|
+
sort: [
|
|
2145
|
+
{ field: "held.kind", dir: "asc" },
|
|
2146
|
+
{ field: "held.id", dir: "asc" }
|
|
2147
|
+
],
|
|
2148
|
+
limit: PAGE
|
|
1553
2149
|
}
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
...head !== void 0 ? { head } : {},
|
|
1574
|
-
headers: documentHeaders(principal),
|
|
1575
|
-
drawn: true,
|
|
1576
|
-
principal,
|
|
1577
|
-
...route !== void 0 ? { page: route.name } : {},
|
|
1578
|
-
live: snapshot.live,
|
|
1579
|
-
why: snapshot.why,
|
|
1580
|
-
drawnWith: snapshot.drawnWith,
|
|
1581
|
-
settled: snapshot.settled
|
|
1582
|
-
};
|
|
1583
|
-
} catch (error) {
|
|
1584
|
-
console.error(`[moss/document] "${request.path}" could not be drawn \u2014 serving it undrawn:`, error);
|
|
1585
|
-
return undrawn;
|
|
2150
|
+
};
|
|
2151
|
+
var history = {
|
|
2152
|
+
fingerprint: "artifactory/history",
|
|
2153
|
+
intent: "The versions of one of the caller\u2019s artifacts, the newest first",
|
|
2154
|
+
dsl: {
|
|
2155
|
+
from: ["artifacts"],
|
|
2156
|
+
fields: VERSION_COLUMNS.map((column) => `artifacts.${column}`),
|
|
2157
|
+
filter: {
|
|
2158
|
+
and: [
|
|
2159
|
+
{ eq: ["artifacts.kind", { $context: "kind" }] },
|
|
2160
|
+
{ eq: ["artifacts.id", { $context: "id" }] },
|
|
2161
|
+
{ optional: { key: "save", then: { eq: ["artifacts.save", { $context: "save" }] } } }
|
|
2162
|
+
]
|
|
2163
|
+
},
|
|
2164
|
+
sort: [
|
|
2165
|
+
{ field: "artifacts.created_at", dir: "desc" },
|
|
2166
|
+
{ field: "artifacts.save", dir: "desc" }
|
|
2167
|
+
],
|
|
2168
|
+
limit: PAGE
|
|
1586
2169
|
}
|
|
1587
2170
|
};
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
2171
|
+
var save = {
|
|
2172
|
+
fingerprint: "artifactory/save",
|
|
2173
|
+
intent: "Keep a save of the caller\u2019s and the versions it holds",
|
|
2174
|
+
mutation: [
|
|
2175
|
+
{ op: "insert", table: "artifact_saves", values: { id: { $context: "save" } } },
|
|
2176
|
+
{
|
|
2177
|
+
op: "insertEach",
|
|
2178
|
+
table: "artifacts",
|
|
2179
|
+
items: { $context: "versions" },
|
|
2180
|
+
values: { save: { $context: "save" }, kind: { $item: "kind" }, id: { $item: "id" }, body: { $item: "body" }, grammar: { $item: "grammar" }, copied_from: { $item: "copied_from" } }
|
|
1597
2181
|
}
|
|
1598
|
-
|
|
1599
|
-
const named = segments.flatMap((segment) => "param" in segment ? [segment.param] : []);
|
|
1600
|
-
const twice = named.find((param, index) => named.indexOf(param) !== index);
|
|
1601
|
-
if (twice !== void 0) {
|
|
1602
|
-
throw new Error(`moss: page "${name}" names the parameter ":${twice}" twice in "${page.path}" \u2014 give each parameter of a path its own name.`);
|
|
1603
|
-
}
|
|
1604
|
-
if (page.params !== void 0 && !page.canvases.some((canvas) => canvas.id === page.params)) {
|
|
1605
|
-
throw new Error(`moss: page "${name}" sends its path's parameters to the canvas "${page.params}", which it does not have.`);
|
|
1606
|
-
}
|
|
1607
|
-
return { name, segments };
|
|
2182
|
+
]
|
|
1608
2183
|
};
|
|
1609
|
-
var
|
|
1610
|
-
|
|
1611
|
-
|
|
2184
|
+
var SAVE_ENTRIES = [inForce, history, save];
|
|
2185
|
+
var RowSchema2 = z.object({
|
|
2186
|
+
save: z.string(),
|
|
2187
|
+
kind: z.string(),
|
|
2188
|
+
id: z.string(),
|
|
2189
|
+
body: z.unknown(),
|
|
2190
|
+
grammar: z.record(z.string(), z.coerce.number()).catch({}),
|
|
2191
|
+
copied_from: z.string().nullish(),
|
|
2192
|
+
// Drivers hand back a Date, an ISO string or a number for the same column.
|
|
2193
|
+
created_at: z.union([z.date(), z.string(), z.number()]).transform((at) => new Date(at).toISOString())
|
|
1612
2194
|
});
|
|
1613
|
-
var
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
2195
|
+
var upgradedAs = (grammarKind) => (upgrader, body, stamp) => upgrader.upgrade(body, { kind: grammarKind, stamp }).document;
|
|
2196
|
+
var upgradedBody = {
|
|
2197
|
+
layout: upgradedLayoutBody,
|
|
2198
|
+
action: upgradedAs("nisc.nova/action"),
|
|
2199
|
+
fragment: upgradedAs("nisc.nova/fragment"),
|
|
2200
|
+
read: upgradedAs("nisc.vex/entry")
|
|
2201
|
+
};
|
|
2202
|
+
var versionOf = (row, upgrader) => {
|
|
2203
|
+
const version = { save: row.save, kind: row.kind, id: row.id, copiedFrom: row.copied_from ?? null, createdAt: row.created_at };
|
|
2204
|
+
const upgrade = upgradedBody[row.kind];
|
|
2205
|
+
if (row.body === null || row.body === void 0 || upgrade === void 0) return { ...version, body: row.body ?? null };
|
|
2206
|
+
try {
|
|
2207
|
+
return { ...version, body: upgrade(upgrader, row.body, row.grammar) };
|
|
2208
|
+
} catch (error) {
|
|
2209
|
+
if (!(error instanceof StrataError)) throw error;
|
|
2210
|
+
return { ...version, body: row.body, unread: error.message.split("\n")[0] ?? error.code };
|
|
1620
2211
|
}
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
params[segment.param] = decodeURIComponent(part);
|
|
1637
|
-
} catch {
|
|
1638
|
-
matches = false;
|
|
1639
|
-
break;
|
|
1640
|
-
}
|
|
1641
|
-
} else if (segment.literal !== part) {
|
|
1642
|
-
matches = false;
|
|
1643
|
-
break;
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
if (matches) return { name: page.name, params };
|
|
2212
|
+
};
|
|
2213
|
+
var savedRowsOver = (replay, upgrader) => {
|
|
2214
|
+
const versionsIn = (answered) => z.array(RowSchema2).parse(answered).map((row) => versionOf(row, upgrader));
|
|
2215
|
+
const rows = (scope) => {
|
|
2216
|
+
const everyVersionInForce = async (after) => {
|
|
2217
|
+
const page = versionsIn(await replay(inForce.fingerprint, { after_kind: after?.kind ?? "", after_id: after?.id ?? "" }, scope));
|
|
2218
|
+
const last = page.at(-1);
|
|
2219
|
+
return page.length < PAGE || last === void 0 ? page : [...page, ...await everyVersionInForce(last)];
|
|
2220
|
+
};
|
|
2221
|
+
return {
|
|
2222
|
+
inForce: () => everyVersionInForce(),
|
|
2223
|
+
history: async (kind, id, saved) => versionsIn(await replay(history.fingerprint, { kind, id, ...saved === void 0 ? {} : { save: saved } }, scope)),
|
|
2224
|
+
write: async (saved) => {
|
|
2225
|
+
const versions = saved.versions.map((version) => ({ kind: version.kind, id: version.id, body: version.body, grammar: upgrader.stamp, copied_from: version.copiedFrom }));
|
|
2226
|
+
await replay(save.fingerprint, { save: saved.id, versions }, scope);
|
|
1647
2227
|
}
|
|
1648
|
-
|
|
1649
|
-
|
|
2228
|
+
};
|
|
2229
|
+
};
|
|
2230
|
+
return {
|
|
2231
|
+
of: (scope) => rows({ ...callerScope(scope), [MADE_BY]: scope["userId"] }),
|
|
2232
|
+
published: (by) => rows({ userId: EVERYBODY, ...by === void 0 ? {} : { [MADE_BY]: by } })
|
|
1650
2233
|
};
|
|
1651
|
-
};
|
|
1652
|
-
var exportDocuments = async (config) => {
|
|
1653
|
-
const { paths, ...rest } = config;
|
|
1654
|
-
const out = [];
|
|
1655
|
-
for (const path of paths) {
|
|
1656
|
-
const page = await renderDocument({ ...rest, request: { path, cookie: null } });
|
|
1657
|
-
out.push({
|
|
1658
|
-
path,
|
|
1659
|
-
html: page.html,
|
|
1660
|
-
...page.page !== void 0 ? { page: page.page } : {},
|
|
1661
|
-
...page.head !== void 0 ? { head: page.head } : {},
|
|
1662
|
-
drawn: page.drawn,
|
|
1663
|
-
// A page that could not be drawn is not taken to be finished.
|
|
1664
|
-
live: page.live ?? true,
|
|
1665
|
-
why: page.why ?? (page.drawn ? [] : ["the page could not be drawn"]),
|
|
1666
|
-
drawnWith: page.drawnWith ?? [],
|
|
1667
|
-
settled: page.settled ?? false
|
|
1668
|
-
});
|
|
1669
|
-
}
|
|
1670
|
-
return out;
|
|
1671
2234
|
};
|
|
1672
2235
|
|
|
1673
2236
|
// src/socket/revalidation.ts
|
|
@@ -2003,7 +2566,7 @@ var seamsFor = (feature, owned, { app, runtime, server, operator, registered, id
|
|
|
2003
2566
|
addCatalogFilter: running.addCatalogFilter,
|
|
2004
2567
|
charter: app.charter,
|
|
2005
2568
|
components: app.shell?.components ?? {},
|
|
2006
|
-
layoutMisfits: (
|
|
2569
|
+
layoutMisfits: (layout) => layoutMisfits(layout, kitOf(app)),
|
|
2007
2570
|
endlessChains,
|
|
2008
2571
|
ownEntries: (entries) => data.ownEntries(feature.name, entries),
|
|
2009
2572
|
grammars: data.grammars,
|
|
@@ -2029,7 +2592,7 @@ var shellNeedOf = (definition, entries) => {
|
|
|
2029
2592
|
const why = [];
|
|
2030
2593
|
const drawnWith = [];
|
|
2031
2594
|
if (facts.gestures) why.push("a person can act on it");
|
|
2032
|
-
if (facts.opaqueLayout) why.push("its layout is
|
|
2595
|
+
if (facts.opaqueLayout) why.push("its layout is the name of a stored layout, so what can be pressed on it is not readable");
|
|
2033
2596
|
for (const channel of facts.listens) why.push(`it waits on the channel "${channel}"`);
|
|
2034
2597
|
for (const use of facts.endpoints) {
|
|
2035
2598
|
if (!use.onOpen && !use.later) continue;
|
|
@@ -2038,12 +2601,12 @@ var shellNeedOf = (definition, entries) => {
|
|
|
2038
2601
|
continue;
|
|
2039
2602
|
}
|
|
2040
2603
|
const fingerprint = fingerprintOf(use.request);
|
|
2041
|
-
const
|
|
2042
|
-
if (
|
|
2043
|
-
why.push(`its read "${use.name}" keeps answering (${
|
|
2604
|
+
const entry = fingerprint === void 0 ? void 0 : entries.get(fingerprint);
|
|
2605
|
+
if (entry !== void 0 && !("mutation" in entry) && entry.refresh === "reactive") {
|
|
2606
|
+
why.push(`its read "${use.name}" keeps answering (${entry.fingerprint} is reactive)`);
|
|
2044
2607
|
continue;
|
|
2045
2608
|
}
|
|
2046
|
-
if (fingerprint !== void 0 &&
|
|
2609
|
+
if (fingerprint !== void 0 && entry === void 0) {
|
|
2047
2610
|
why.push(`its read "${use.name}" replays "${fingerprint}", which the manifest does not carry \u2014 whether it keeps answering is not readable`);
|
|
2048
2611
|
continue;
|
|
2049
2612
|
}
|
|
@@ -2090,7 +2653,7 @@ var needOf = (live, principal, kept) => {
|
|
|
2090
2653
|
for (const instance of canvas.stack) {
|
|
2091
2654
|
const definition = live.shell.getRuntime(instance.id)?.definition;
|
|
2092
2655
|
if (definition === void 0) continue;
|
|
2093
|
-
const need = shellNeedOf(definition, entries);
|
|
2656
|
+
const need = shellNeedOf(withLayoutInPlace(definition, live.shell.layoutStore), entries);
|
|
2094
2657
|
for (const reason of need.why) why.push(`${definition.id}: ${reason}`);
|
|
2095
2658
|
for (const read2 of need.drawnWith) drawnWith.push(read2);
|
|
2096
2659
|
}
|
|
@@ -2136,31 +2699,65 @@ var sameDocument = (one, other) => one === other || JSON.stringify(one) === JSON
|
|
|
2136
2699
|
var takeLayouts = (live, made) => {
|
|
2137
2700
|
const taken = live.layouts;
|
|
2138
2701
|
const answered = layoutsOf(made);
|
|
2139
|
-
for (const [ref,
|
|
2140
|
-
if (!sameDocument(taken.layoutStore[ref],
|
|
2702
|
+
for (const [ref, layout] of Object.entries(answered.layoutStore)) {
|
|
2703
|
+
if (!sameDocument(taken.layoutStore[ref], layout)) live.shell.setLayout(ref, layout);
|
|
2704
|
+
}
|
|
2705
|
+
for (const ref of Object.keys(taken.layoutStore)) {
|
|
2706
|
+
if (!Object.hasOwn(answered.layoutStore, ref)) live.shell.layoutStore.delete(ref);
|
|
2141
2707
|
}
|
|
2142
2708
|
for (const [id, fragment] of Object.entries(answered.fragments)) {
|
|
2143
|
-
if (!sameDocument(taken.fragments[id], fragment)) live.shell.
|
|
2709
|
+
if (!sameDocument(taken.fragments[id], fragment)) live.shell.registerAction({ ...fragment, id });
|
|
2710
|
+
}
|
|
2711
|
+
for (const id of Object.keys(taken.fragments)) {
|
|
2712
|
+
if (!Object.hasOwn(answered.fragments, id)) live.shell.removeAction(id);
|
|
2144
2713
|
}
|
|
2145
|
-
if (answered.frame !== void 0 && !sameDocument(taken.frame, answered.frame)) live.shell.setCanvasLayout(answered.frame);
|
|
2146
2714
|
live.layouts = answered;
|
|
2147
2715
|
};
|
|
2716
|
+
var takeCanvases = (live, made) => {
|
|
2717
|
+
const slotted = new Set(made.slottedCanvases);
|
|
2718
|
+
for (const id of live.slottedCanvases) if (!slotted.has(id)) live.shell.removeCanvas(id);
|
|
2719
|
+
live.slottedCanvases = slotted;
|
|
2720
|
+
};
|
|
2721
|
+
var takeComposition = (live, made) => {
|
|
2722
|
+
for (const [name, contract] of Object.entries(made.components)) {
|
|
2723
|
+
if (!live.shell.registry.has(name)) live.shell.registry.register(name, contract);
|
|
2724
|
+
}
|
|
2725
|
+
for (const id of live.actionIds) if (!Object.hasOwn(made.actions, id)) live.shell.removeAction(id);
|
|
2726
|
+
for (const definition of Object.values(made.actions)) live.shell.registerAction(definition);
|
|
2727
|
+
live.actionIds = new Set(Object.keys(made.actions));
|
|
2728
|
+
live.entries = made.entries;
|
|
2729
|
+
takeLayouts(live, made);
|
|
2730
|
+
takeCanvases(live, made);
|
|
2731
|
+
holdGranted(live.functions, made.grantedFunctions);
|
|
2732
|
+
};
|
|
2733
|
+
var adoptDraft = async (host, live, next) => {
|
|
2734
|
+
for (; ; ) {
|
|
2735
|
+
const cell = host.living.get(live);
|
|
2736
|
+
if (cell === void 0 || cell.live !== live) throw new Error(SHELL_GONE);
|
|
2737
|
+
const changes = host.changes;
|
|
2738
|
+
const made = await host.config.composition(cell.principal, draftedIn(next));
|
|
2739
|
+
if (live.ended || cell.live !== live) throw new Error(SHELL_GONE);
|
|
2740
|
+
if (changes < cell.changes) continue;
|
|
2741
|
+
cell.changes = changes;
|
|
2742
|
+
live.draft = next;
|
|
2743
|
+
takeComposition(live, made);
|
|
2744
|
+
return;
|
|
2745
|
+
}
|
|
2746
|
+
};
|
|
2148
2747
|
var adopt = (host, cell) => {
|
|
2149
2748
|
const adopting = async () => {
|
|
2150
|
-
|
|
2749
|
+
const asked = cell.live;
|
|
2750
|
+
if (asked.ended) return;
|
|
2751
|
+
const drafted = asked.draft;
|
|
2151
2752
|
const changes = host.changes;
|
|
2152
|
-
const made = await host.config.composition(cell.principal);
|
|
2153
|
-
|
|
2154
|
-
if (
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
if (!live.shell.registry.has(name)) live.shell.registry.register(name, contract);
|
|
2753
|
+
const made = await host.config.composition(cell.principal, draftedIn(drafted));
|
|
2754
|
+
if (asked.ended || changes <= cell.changes) return;
|
|
2755
|
+
if (asked.draft !== drafted) {
|
|
2756
|
+
adopt(host, cell);
|
|
2757
|
+
return;
|
|
2158
2758
|
}
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
live.actionIds = new Set(Object.keys(made.actions));
|
|
2162
|
-
live.entries = made.entries;
|
|
2163
|
-
takeLayouts(live, made);
|
|
2759
|
+
cell.changes = changes;
|
|
2760
|
+
takeComposition(asked, made);
|
|
2164
2761
|
};
|
|
2165
2762
|
adopting().catch((error) => {
|
|
2166
2763
|
console.error(`[moss/shells] the shell of ${cell.principal ?? "nobody"} could not adopt what changed, and keeps what it held:`, error);
|
|
@@ -2170,6 +2767,10 @@ var adoptAll = (host) => {
|
|
|
2170
2767
|
host.changes += 1;
|
|
2171
2768
|
for (const cell of [...host.living.values()]) adopt(host, cell);
|
|
2172
2769
|
};
|
|
2770
|
+
var adoptFor = (host, principal) => {
|
|
2771
|
+
host.changes += 1;
|
|
2772
|
+
for (const cell of shellsOf(host, principal)) adopt(host, cell);
|
|
2773
|
+
};
|
|
2173
2774
|
var build = (host, asked, wanted = () => true) => {
|
|
2174
2775
|
const changes = host.changes;
|
|
2175
2776
|
const limit = host.config.limits?.endpointTimeoutMs ?? DEFAULT_BUILD_TIMEOUT_MS;
|
|
@@ -2294,7 +2895,8 @@ var createShellHost = (config) => {
|
|
|
2294
2895
|
durable: /* @__PURE__ */ new Map(),
|
|
2295
2896
|
building: /* @__PURE__ */ new Map(),
|
|
2296
2897
|
living: /* @__PURE__ */ new Map(),
|
|
2297
|
-
changes: 0
|
|
2898
|
+
changes: 0,
|
|
2899
|
+
adoptDraft: (live, next) => adoptDraft(host, live, next)
|
|
2298
2900
|
};
|
|
2299
2901
|
const reset = (cell) => resetCell(host, cell);
|
|
2300
2902
|
const handedOut = {
|
|
@@ -2308,25 +2910,38 @@ var createShellHost = (config) => {
|
|
|
2308
2910
|
deliver: deliverTo(host),
|
|
2309
2911
|
list: () => rosterOf(host.durable),
|
|
2310
2912
|
reset: (principal) => {
|
|
2311
|
-
const
|
|
2312
|
-
for (const cell of
|
|
2313
|
-
return
|
|
2913
|
+
const theirs2 = shellsOf(host, principal);
|
|
2914
|
+
for (const cell of theirs2) reset(cell);
|
|
2915
|
+
return theirs2.length > 0;
|
|
2314
2916
|
}
|
|
2315
2917
|
};
|
|
2316
|
-
return { host: handedOut, adopt: () => adoptAll(host), stop: startSweep(host) };
|
|
2918
|
+
return { host: handedOut, adopt: () => adoptAll(host), adoptFor: (principal) => adoptFor(host, principal), stop: startSweep(host) };
|
|
2317
2919
|
};
|
|
2318
2920
|
|
|
2319
2921
|
// src/server/hosts.ts
|
|
2320
|
-
var hostConfig = (deps,
|
|
2922
|
+
var hostConfig = (deps, shell, kept) => {
|
|
2321
2923
|
const { app, runtime, identity, running, data } = deps;
|
|
2924
|
+
const callerOf = async (principal) => {
|
|
2925
|
+
const resolved = await identity.resolve(principal);
|
|
2926
|
+
return {
|
|
2927
|
+
resolved,
|
|
2928
|
+
roles: resolved.roles,
|
|
2929
|
+
installed: resolved.installed,
|
|
2930
|
+
saved: deps.savedAs(identity.composeScope(principal, resolved)),
|
|
2931
|
+
replayable: () => data.fingerprintsFor(resolved)
|
|
2932
|
+
};
|
|
2933
|
+
};
|
|
2322
2934
|
return {
|
|
2323
|
-
composition: async (principal) => {
|
|
2324
|
-
const resolved = await
|
|
2325
|
-
|
|
2935
|
+
composition: async (principal, drafted) => {
|
|
2936
|
+
const { resolved, saved, ...held } = await callerOf(principal);
|
|
2937
|
+
const who = { principal, ...held, ...principal === null ? {} : { saved, ...drafted === void 0 ? {} : { drafted } } };
|
|
2938
|
+
return { roles: resolved.roles, scope: resolved.scope, ...await running.artifactsFor(shell, who) };
|
|
2326
2939
|
},
|
|
2940
|
+
artifacts: (principal) => running.sessionArtifacts(principal, () => callerOf(principal)),
|
|
2941
|
+
draftSaving: (principal) => running.draftSavingFor(shell, principal, () => callerOf(principal)),
|
|
2327
2942
|
hooks: {
|
|
2328
|
-
...
|
|
2329
|
-
...
|
|
2943
|
+
...shell.inputs !== void 0 ? { inputs: shell.inputs } : {},
|
|
2944
|
+
...shell.seeds !== void 0 ? { seeds: shell.seeds } : {},
|
|
2330
2945
|
...app.phrases !== void 0 ? { phrases: app.phrases } : {},
|
|
2331
2946
|
...app.functions !== void 0 ? { functions: app.functions } : {},
|
|
2332
2947
|
...app.onSession !== void 0 ? { onSession: app.onSession } : {},
|
|
@@ -2338,7 +2953,7 @@ var hostConfig = (deps, shell2, kept) => {
|
|
|
2338
2953
|
wrapWire: deps.wrapWire,
|
|
2339
2954
|
answerIntent: async (principal, writers, asked) => {
|
|
2340
2955
|
const resolved = await identity.resolve(principal);
|
|
2341
|
-
return data.answerIntent(writers, asked, resolved, identity.composeScope(principal, resolved));
|
|
2956
|
+
return data.answerIntent(writers, asked, resolved, callerScope(identity.composeScope(principal, resolved)));
|
|
2342
2957
|
},
|
|
2343
2958
|
...deps.revokeSessions !== void 0 ? { revokeSessions: deps.revokeSessions } : {},
|
|
2344
2959
|
...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
|
|
@@ -2349,12 +2964,25 @@ var hostConfig = (deps, shell2, kept) => {
|
|
|
2349
2964
|
}
|
|
2350
2965
|
};
|
|
2351
2966
|
};
|
|
2967
|
+
var sayingWhatToFix = (functions) => {
|
|
2968
|
+
let said = false;
|
|
2969
|
+
return (session) => {
|
|
2970
|
+
const written = functions(session);
|
|
2971
|
+
if (!said) {
|
|
2972
|
+
said = true;
|
|
2973
|
+
const warning = functionsWarning(written);
|
|
2974
|
+
if (warning !== void 0) console.warn(warning);
|
|
2975
|
+
}
|
|
2976
|
+
return written;
|
|
2977
|
+
};
|
|
2978
|
+
};
|
|
2352
2979
|
var buildShellHosts = (deps) => {
|
|
2353
2980
|
const { app } = deps;
|
|
2981
|
+
const wired = app.functions === void 0 ? deps : { ...deps, app: { ...app, functions: sayingWhatToFix(app.functions) } };
|
|
2354
2982
|
const pageManifests = app.pages ?? {};
|
|
2355
2983
|
const pageRouter = createPageRouter(pageManifests);
|
|
2356
|
-
const shells = app.shell !== void 0 ? createShellHost(hostConfig(
|
|
2357
|
-
const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost(hostConfig(
|
|
2984
|
+
const shells = app.shell !== void 0 ? createShellHost(hostConfig(wired, app.shell, true)) : void 0;
|
|
2985
|
+
const pageHosts = new Map(Object.entries(pageManifests).map(([name, manifest]) => [name, createShellHost(hostConfig(wired, manifest, false))]));
|
|
2358
2986
|
const owned = [...shells !== void 0 ? [shells] : [], ...pageHosts.values()];
|
|
2359
2987
|
const every = owned.map((made) => made.host);
|
|
2360
2988
|
return {
|
|
@@ -2371,6 +2999,9 @@ var buildShellHosts = (deps) => {
|
|
|
2371
2999
|
adopt: () => {
|
|
2372
3000
|
for (const made of owned) made.adopt();
|
|
2373
3001
|
},
|
|
3002
|
+
adoptFor: (principal) => {
|
|
3003
|
+
for (const made of owned) made.adoptFor(principal);
|
|
3004
|
+
},
|
|
2374
3005
|
// `map`, not `some`: each host is asked, whatever the one before answered.
|
|
2375
3006
|
reset: (principal) => every.map((host) => host.reset(principal)).includes(true),
|
|
2376
3007
|
deliver: (principal, channel, payload) => every.map((host) => host.deliver(principal, channel, payload)).includes(true),
|
|
@@ -2418,7 +3049,7 @@ var mountRoutes = (server, { app, session, credentials, identity, running, data
|
|
|
2418
3049
|
"/",
|
|
2419
3050
|
data.routes({
|
|
2420
3051
|
resources: app.resources,
|
|
2421
|
-
scope: (c) => identity.composeScope(c.get("principal"), c.get("resolved")),
|
|
3052
|
+
scope: (c) => callerScope(identity.composeScope(c.get("principal"), c.get("resolved"))),
|
|
2422
3053
|
caller: (c) => c.get("resolved")
|
|
2423
3054
|
})
|
|
2424
3055
|
);
|
|
@@ -2475,7 +3106,7 @@ var operatorPrefix = (runtime) => {
|
|
|
2475
3106
|
guardOperator(operator, { key: runtime.operatorKey ?? "", gate: runtime.operatorGate });
|
|
2476
3107
|
return operator;
|
|
2477
3108
|
};
|
|
2478
|
-
var buildSignals = ({ fabric, identity, reset, deliver }) => {
|
|
3109
|
+
var buildSignals = ({ fabric, identity, reset, adopt: adopt2, deliver }) => {
|
|
2479
3110
|
const origin = randomBytes(8).toString("hex");
|
|
2480
3111
|
const applyInvalidateIdentity = (principal) => {
|
|
2481
3112
|
const held = identity.invalidate(principal);
|
|
@@ -2489,7 +3120,8 @@ var buildSignals = ({ fabric, identity, reset, deliver }) => {
|
|
|
2489
3120
|
const publish = wireFabric(fabric, origin, {
|
|
2490
3121
|
invalidateIdentity: applyInvalidateIdentity,
|
|
2491
3122
|
invalidateTag: applyInvalidateTag,
|
|
2492
|
-
nudge: applyNudge
|
|
3123
|
+
nudge: applyNudge,
|
|
3124
|
+
adopt: adopt2
|
|
2493
3125
|
});
|
|
2494
3126
|
return {
|
|
2495
3127
|
invalidateIdentity: (principal) => {
|
|
@@ -2506,6 +3138,10 @@ var buildSignals = ({ fabric, identity, reset, deliver }) => {
|
|
|
2506
3138
|
applyNudge(principal, channel);
|
|
2507
3139
|
publish({ kind: "nudge", principal, channel });
|
|
2508
3140
|
},
|
|
3141
|
+
adopt: (principal) => {
|
|
3142
|
+
adopt2(principal);
|
|
3143
|
+
publish({ kind: "adopt", principal });
|
|
3144
|
+
},
|
|
2509
3145
|
// The payload stays in this process. Across processes only the channel is
|
|
2510
3146
|
// said, and a shell there reads again under its own policy.
|
|
2511
3147
|
deliver: (principal, channel, payload) => {
|
|
@@ -2541,6 +3177,9 @@ var wireFabric = (fabric, origin, apply) => {
|
|
|
2541
3177
|
case "nudge":
|
|
2542
3178
|
apply.nudge(message.principal, message.channel);
|
|
2543
3179
|
break;
|
|
3180
|
+
case "adopt":
|
|
3181
|
+
apply.adopt(message.principal);
|
|
3182
|
+
break;
|
|
2544
3183
|
}
|
|
2545
3184
|
} catch (err) {
|
|
2546
3185
|
console.error("[moss:fabric] a remote signal failed to apply", err);
|
|
@@ -2564,6 +3203,15 @@ var createServerWith = async (app, runtime, dataOf) => {
|
|
|
2564
3203
|
return assembleServer({ app, runtime, session, revokeSessions, data });
|
|
2565
3204
|
};
|
|
2566
3205
|
var createServer = (app, runtime) => createServerWith(app, runtime, buildData);
|
|
3206
|
+
var rowRulesBeside = (behaviors) => {
|
|
3207
|
+
const declared = Object.keys(SAVE_ROW_RULES).filter((table) => Object.hasOwn(behaviors ?? {}, table));
|
|
3208
|
+
if (declared.length > 0) {
|
|
3209
|
+
throw new Error(
|
|
3210
|
+
`moss: the app\u2019s \`behaviors\` say what a caller reads and writes of ${declared.map((table) => `"${table}"`).join(" and ")}. Those rows are whoever saved them: moss keeps every read and write of them to the caller\u2019s own, and an app does not say otherwise.`
|
|
3211
|
+
);
|
|
3212
|
+
}
|
|
3213
|
+
return SAVE_ROW_RULES;
|
|
3214
|
+
};
|
|
2567
3215
|
var buildData = (app, runtime) => createData({
|
|
2568
3216
|
pool: runtime.pool,
|
|
2569
3217
|
db: runtime.db,
|
|
@@ -2576,6 +3224,7 @@ var buildData = (app, runtime) => createData({
|
|
|
2576
3224
|
grammars: app.grammars,
|
|
2577
3225
|
charter: app.charter,
|
|
2578
3226
|
behaviors: app.behaviors,
|
|
3227
|
+
rowRules: rowRulesBeside(app.behaviors),
|
|
2579
3228
|
telemetry: runtime.telemetry
|
|
2580
3229
|
});
|
|
2581
3230
|
var assembleServer = async (deps) => {
|
|
@@ -2588,25 +3237,28 @@ var assembleServer = async (deps) => {
|
|
|
2588
3237
|
}
|
|
2589
3238
|
};
|
|
2590
3239
|
var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) => {
|
|
2591
|
-
const
|
|
3240
|
+
const saved = savedRowsOver(await data.artifactEntries(SAVE_ENTRIES, SAVE_ROW_RULES), data.grammars);
|
|
3241
|
+
const running = await buildRunningManifest(app, runtime, data, saved);
|
|
2592
3242
|
stops.push(running.stop);
|
|
2593
3243
|
const identity = buildIdentity(app, runtime, data);
|
|
2594
3244
|
stops.push(identity.stop);
|
|
2595
3245
|
const server = new Hono();
|
|
2596
3246
|
const registered = emptyRegister();
|
|
2597
3247
|
mountRoutes(server, { app, session, credentials: registered.credentials, identity, running, data });
|
|
2598
|
-
const hosts = buildShellHosts({ app, runtime, identity, running, data, wire: createInternalWire(server), wrapWire: composeWireWraps(registered), revokeSessions });
|
|
3248
|
+
const hosts = buildShellHosts({ app, runtime, identity, running, data, savedAs: saved.of, wire: createInternalWire(server), wrapWire: composeWireWraps(registered), revokeSessions });
|
|
2599
3249
|
stops.push(hosts.stop);
|
|
2600
|
-
const signals = buildSignals({ fabric: runtime.fabric, identity, reset: hosts.reset, deliver: hosts.deliver });
|
|
3250
|
+
const signals = buildSignals({ fabric: runtime.fabric, identity, reset: hosts.reset, adopt: hosts.adoptFor, deliver: hosts.deliver });
|
|
2601
3251
|
running.onChange(() => {
|
|
2602
3252
|
identity.invalidateAll();
|
|
2603
3253
|
hosts.adopt();
|
|
2604
3254
|
});
|
|
3255
|
+
running.onChangeFor(signals.adopt);
|
|
2605
3256
|
const operator = operatorPrefix(runtime);
|
|
2606
3257
|
await startFeatures(app.features ?? [], { app, runtime, server, operator, registered, identity, running, data });
|
|
2607
3258
|
server.route("/operator", operator);
|
|
2608
3259
|
subscribeReactions({ app, onWrite: data.onWrite, deliver: signals.deliver });
|
|
2609
3260
|
running.watch();
|
|
3261
|
+
await running.readPublished();
|
|
2610
3262
|
const socket = buildSocket({ runtime, session, identity, running, hosts });
|
|
2611
3263
|
stops.push(socket.stop);
|
|
2612
3264
|
return Object.assign(server, {
|
|
@@ -2617,7 +3269,14 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
|
|
|
2617
3269
|
...hosts.shells !== void 0 ? { shells: hosts.shells } : {},
|
|
2618
3270
|
refresh: running.refresh,
|
|
2619
3271
|
replaceActions: running.replace,
|
|
3272
|
+
replaceEntries: running.replaceEntries,
|
|
2620
3273
|
actions: running.actions,
|
|
3274
|
+
defaults: (publisher) => {
|
|
3275
|
+
if (typeof publisher !== "string" || publisher === "") {
|
|
3276
|
+
throw new Error("moss: `defaults` is handed who publishes. What is published is everybody\u2019s, and who published it is kept with it.");
|
|
3277
|
+
}
|
|
3278
|
+
return running.publishedArtifacts(saved.published(publisher));
|
|
3279
|
+
},
|
|
2621
3280
|
catalogOf: async (principal) => {
|
|
2622
3281
|
const resolved = await identity.resolve(principal);
|
|
2623
3282
|
return running.catalogFor(resolved.roles, resolved.installed);
|
|
@@ -2638,15 +3297,18 @@ var assemble = async ({ app, runtime, session, revokeSessions, data }, stops) =>
|
|
|
2638
3297
|
...identity.roster !== void 0 ? { identities: identity.roster } : {}
|
|
2639
3298
|
});
|
|
2640
3299
|
};
|
|
2641
|
-
var buildRunningManifest = async (app, runtime, data) => {
|
|
3300
|
+
var buildRunningManifest = async (app, runtime, data, saved) => {
|
|
2642
3301
|
const running = createRunningManifest({
|
|
2643
3302
|
shipped: app,
|
|
2644
3303
|
grants: data.grants,
|
|
2645
3304
|
// Polled on the clock a socket's credential is re-verified on.
|
|
2646
|
-
pointer: { read: data.pointer.read, move: data.pointer.move, ...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {} }
|
|
3305
|
+
pointer: { read: data.pointer.read, move: data.pointer.move, ...runtime.sessionRevalidateMs !== void 0 ? { everyMs: runtime.sessionRevalidateMs } : {} },
|
|
3306
|
+
shells: [...app.shell !== void 0 ? [app.shell] : [], ...Object.values(app.pages ?? {})],
|
|
3307
|
+
...saved !== void 0 ? { published: saved.published().inForce, reads: { written: data.vexEntry, compile: data.compileQuery, savedOf: saved.of } } : {}
|
|
2647
3308
|
});
|
|
2648
3309
|
data.dropOnChange(running.onChange);
|
|
2649
|
-
|
|
3310
|
+
data.entriesHeldBy({ get: running.cacheEntry, entries: running.cacheEntries });
|
|
3311
|
+
await running.cacheEntries();
|
|
2650
3312
|
return running;
|
|
2651
3313
|
};
|
|
2652
3314
|
var buildIdentity = (app, runtime, data) => createIdentity({
|
|
@@ -2699,6 +3361,6 @@ var subscribeReactions = ({ app, onWrite, deliver }) => {
|
|
|
2699
3361
|
});
|
|
2700
3362
|
};
|
|
2701
3363
|
|
|
2702
|
-
export { MOSS_SEQUENCE, createServer,
|
|
2703
|
-
//# sourceMappingURL=chunk-
|
|
2704
|
-
//# sourceMappingURL=chunk-
|
|
3364
|
+
export { MOSS_SEQUENCE, createServer, exportDocuments, migrateTables, mintDevToken, mintSession, renderDocument, revokeAllFor, sessionCookies };
|
|
3365
|
+
//# sourceMappingURL=chunk-MTC46PGQ.js.map
|
|
3366
|
+
//# sourceMappingURL=chunk-MTC46PGQ.js.map
|