@lupinum/ginko-server 0.0.0-stage → 0.18.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 +13 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/convex/_generated/api.d.ts +185 -0
- package/convex/_generated/api.js +23 -0
- package/convex/_generated/dataModel.d.ts +60 -0
- package/convex/_generated/server.d.ts +162 -0
- package/convex/_generated/server.js +101 -0
- package/convex/account.ts +110 -0
- package/convex/agent.ts +814 -0
- package/convex/auth.config.ts +4 -0
- package/convex/auth.ts +62 -0
- package/convex/backup.ts +94 -0
- package/convex/betterAuth/_generated/api.ts +56 -0
- package/convex/betterAuth/_generated/component.ts +431 -0
- package/convex/betterAuth/_generated/dataModel.ts +60 -0
- package/convex/betterAuth/_generated/server.ts +169 -0
- package/convex/betterAuth/adapter.ts +7 -0
- package/convex/betterAuth/convex.config.ts +3 -0
- package/convex/betterAuth/schema.ts +102 -0
- package/convex/betterAuth/schemaMetadata.ts +697 -0
- package/convex/betterAuth/schemaOptions.ts +13 -0
- package/convex/betterAuth/schemaPlugins.ts +13 -0
- package/convex/bundle.ts +183 -0
- package/convex/changes.ts +136 -0
- package/convex/cleanup.ts +44 -0
- package/convex/connect.ts +143 -0
- package/convex/convex.config.ts +7 -0
- package/convex/crons.ts +14 -0
- package/convex/demo.ts +72 -0
- package/convex/entries.ts +1770 -0
- package/convex/facts.ts +129 -0
- package/convex/files.ts +631 -0
- package/convex/http.ts +21 -0
- package/convex/image.ts +45 -0
- package/convex/images.ts +54 -0
- package/convex/invites.ts +227 -0
- package/convex/lib/access.ts +180 -0
- package/convex/lib/agentTools.ts +331 -0
- package/convex/lib/content.ts +317 -0
- package/convex/lib/corpus.ts +83 -0
- package/convex/lib/diff.ts +50 -0
- package/convex/lib/fail.ts +27 -0
- package/convex/lib/files.ts +70 -0
- package/convex/lib/history.ts +103 -0
- package/convex/lib/i18n.ts +52 -0
- package/convex/lib/input.ts +57 -0
- package/convex/lib/library.ts +28 -0
- package/convex/lib/lifecycle.ts +100 -0
- package/convex/lib/list.ts +112 -0
- package/convex/lib/migrations.ts +126 -0
- package/convex/lib/names.ts +56 -0
- package/convex/lib/pending.ts +84 -0
- package/convex/lib/policy.ts +155 -0
- package/convex/lib/publicness.ts +87 -0
- package/convex/lib/reminders.ts +27 -0
- package/convex/lib/search.ts +132 -0
- package/convex/lib/siteUrl.ts +95 -0
- package/convex/lib/status.ts +109 -0
- package/convex/lib/translation.ts +56 -0
- package/convex/lib/trees.ts +43 -0
- package/convex/lib/write.ts +296 -0
- package/convex/mail.ts +136 -0
- package/convex/members.ts +129 -0
- package/convex/migrations.ts +105 -0
- package/convex/navigation.ts +276 -0
- package/convex/ops.ts +50 -0
- package/convex/proposals.ts +753 -0
- package/convex/refresh.ts +163 -0
- package/convex/release.ts +435 -0
- package/convex/reminders.ts +116 -0
- package/convex/retention.ts +121 -0
- package/convex/routes/bundle.ts +62 -0
- package/convex/routes/connect.ts +80 -0
- package/convex/routes/export.ts +23 -0
- package/convex/routes/file.ts +34 -0
- package/convex/routes/key.ts +53 -0
- package/convex/routes/mcp.ts +300 -0
- package/convex/routes/release.ts +66 -0
- package/convex/routes/upload.ts +94 -0
- package/convex/schema.ts +443 -0
- package/convex/search.ts +58 -0
- package/convex/seed.ts +624 -0
- package/convex/siteDeletion.ts +78 -0
- package/convex/sites.ts +393 -0
- package/convex/tasks.ts +51 -0
- package/convex/tsconfig.json +27 -0
- package/convex/uploads.ts +429 -0
- package/convex/uploadsNode.ts +86 -0
- package/convex/views.ts +111 -0
- package/i18n/de.json +364 -0
- package/i18n/en.json +364 -0
- package/i18n/es.json +364 -0
- package/i18n/fr.json +364 -0
- package/package.json +45 -3
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// "Sofort von der Seite nehmen" (SPEC 4.4): asks the site to re-render every page that a
|
|
2
|
+
// change may have made stale, and checks each answer against the revision it must show.
|
|
3
|
+
import { routeUrls, type Schema } from '@lupinum/ginko/internal'
|
|
4
|
+
import { v, type Infer } from 'convex/values'
|
|
5
|
+
import { internal } from './_generated/api'
|
|
6
|
+
import { action, internalMutation, internalQuery } from './_generated/server'
|
|
7
|
+
import { actorFor, fail, recordOp, replayed } from './lib/access'
|
|
8
|
+
import { isFetchableSiteUrl } from './lib/siteUrl'
|
|
9
|
+
|
|
10
|
+
export const MAX_PATHS = 500
|
|
11
|
+
export const BATCH = 20
|
|
12
|
+
export const RETRY_MS = 5_000
|
|
13
|
+
export const RETRIES = 3
|
|
14
|
+
|
|
15
|
+
type Rev = { schemaRev: number; contentRev: number }
|
|
16
|
+
|
|
17
|
+
interface Plan {
|
|
18
|
+
hash: string
|
|
19
|
+
url: string
|
|
20
|
+
token: string
|
|
21
|
+
min: Rev
|
|
22
|
+
paths: string[]
|
|
23
|
+
/** More than MAX_PATHS addresses: only the pages and the sitemap were sent. The Studio says so in the owner's language. */
|
|
24
|
+
limited: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const rowValidator = v.object({ path: v.string(), status: v.number(), rev: v.union(v.string(), v.null()), ok: v.boolean() })
|
|
28
|
+
type Row = Infer<typeof rowValidator>
|
|
29
|
+
/** What a refresh answers: one row per path, and whether only the pages and the sitemap were sent. */
|
|
30
|
+
const refreshResult = v.object({ results: v.array(rowValidator), limited: v.boolean() })
|
|
31
|
+
type RefreshResult = Infer<typeof refreshResult>
|
|
32
|
+
|
|
33
|
+
/** Relative, plain paths without duplicates; anything else is dropped. */
|
|
34
|
+
function clean(paths: Iterable<string>): string[] {
|
|
35
|
+
return [...new Set([...paths].map(normalize).filter((p): p is string => p !== null))]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Only relative, plain paths go to the site. */
|
|
39
|
+
function normalize(path: string): string | null {
|
|
40
|
+
const p = path.trim()
|
|
41
|
+
if (!p.startsWith('/') || p.startsWith('//') || /[\\?#]/.test(p) || p.split('/').includes('..')) return null
|
|
42
|
+
return p
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Who may refresh, which paths, and the proof each answer must carry (SPEC 4.4 steps 1–2). */
|
|
46
|
+
export const plan = internalQuery({
|
|
47
|
+
args: { site: v.string(), opId: v.string() },
|
|
48
|
+
handler: async (ctx, args): Promise<{ replay: RefreshResult } | ({ replay?: undefined } & Plan)> => {
|
|
49
|
+
const actor = await actorFor(ctx, args.site)
|
|
50
|
+
if (actor.role === 'staff') fail('FORBIDDEN', 'errors.ownersAndAdminsOnly')
|
|
51
|
+
const { hash, result } = await replayed(ctx, actor, args.opId, args)
|
|
52
|
+
// The stored result of this op is the one `record` stored.
|
|
53
|
+
if (result !== undefined) return { replay: result as RefreshResult }
|
|
54
|
+
|
|
55
|
+
const token = actor.site.refreshToken
|
|
56
|
+
if (!token) fail('INVALID', 'errors.reloadKeyMissing')
|
|
57
|
+
// The token goes to this address, so it must be a public one (SSRF); stored URLs are checked again here, not only when saved.
|
|
58
|
+
if (!isFetchableSiteUrl(actor.site.url, process.env.GINKO_LOCAL === '1')) fail('INVALID', 'errors.siteUrlNotAllowed')
|
|
59
|
+
|
|
60
|
+
const schema = actor.site.schema as Schema
|
|
61
|
+
const pages = new Set<string>(['/sitemap.xml'])
|
|
62
|
+
for (const paths of Object.values(schema.pages)) for (const page of Object.values(paths)) if (page) pages.add(page)
|
|
63
|
+
|
|
64
|
+
// Every routed entry, deleted ones too: a page that a change hid, or a deletion removed, must be re-rendered.
|
|
65
|
+
const routed = new Set<string>()
|
|
66
|
+
for (const [key, brick] of Object.entries(schema.bricks)) {
|
|
67
|
+
if (brick.kind !== 'collection' || !brick.route) continue
|
|
68
|
+
const rows = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', actor.site._id).eq('brick', key)).collect()
|
|
69
|
+
// Every locale's address, also where the entry is untranslated today: a removed translation must purge its page.
|
|
70
|
+
for (const row of rows) {
|
|
71
|
+
const urls = routeUrls(schema, brick, { id: row._id, order: row.order, data: row.data, prints: row.prints })
|
|
72
|
+
for (const url of Object.values(urls)) if (url) routed.add(url)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const all = clean([...pages, ...routed])
|
|
77
|
+
const limited = all.length > MAX_PATHS
|
|
78
|
+
return {
|
|
79
|
+
hash,
|
|
80
|
+
url: actor.site.url,
|
|
81
|
+
token,
|
|
82
|
+
min: { schemaRev: actor.site.schemaRev, contentRev: actor.site.contentRev },
|
|
83
|
+
paths: limited ? clean(pages) : all,
|
|
84
|
+
limited,
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Stores the outcome under the opId, so a retry after a lost answer gets the same one. Two
|
|
91
|
+
* concurrent refreshes can both pass `plan`; the first recording wins and both get its result.
|
|
92
|
+
*/
|
|
93
|
+
export const record = internalMutation({
|
|
94
|
+
args: { site: v.string(), opId: v.string(), hash: v.string(), result: refreshResult },
|
|
95
|
+
handler: async (ctx, args): Promise<RefreshResult> => {
|
|
96
|
+
const actor = await actorFor(ctx, args.site)
|
|
97
|
+
const row = await ctx.db.query('ops').withIndex('by_site_actor_op', (q) => q.eq('site', actor.site._id).eq('actor', actor.user.id).eq('opId', args.opId)).unique()
|
|
98
|
+
if (row) {
|
|
99
|
+
if (row.hash !== args.hash) fail('OP_REUSED', 'errors.actionReusedWithOtherContent')
|
|
100
|
+
return row.result
|
|
101
|
+
}
|
|
102
|
+
await recordOp(ctx, actor, args.opId, args.hash, args.result)
|
|
103
|
+
// Only a refresh that every page confirmed counts as "last update"; a partly failed one leaves the time as it was.
|
|
104
|
+
const rows = args.result.results
|
|
105
|
+
if (rows.length > 0 && rows.every((r) => r.ok)) await ctx.db.patch(actor.site._id, { lastRefreshAt: Date.now() })
|
|
106
|
+
return args.result
|
|
107
|
+
},
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
function sleep(ms: number) {
|
|
111
|
+
return new Promise<void>((resolve) => setTimeout(resolve, ms))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** True when the answer proves that the page shows at least the minimum revision. */
|
|
115
|
+
function proves(rev: string | null, min: Rev): boolean {
|
|
116
|
+
const match = rev?.match(/^(\d+)\.(\d+)$/)
|
|
117
|
+
if (!match) return false
|
|
118
|
+
return Number(match[1]) >= min.schemaRev && Number(match[2]) >= min.contentRev
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function requestOnce(p: Plan, path: string): Promise<Row> {
|
|
122
|
+
const minRev = `${p.min.schemaRev}.${p.min.contentRev}`
|
|
123
|
+
try {
|
|
124
|
+
const response = await fetch(`${p.url.replace(/\/+$/, '')}${path}`, {
|
|
125
|
+
headers: { 'x-prerender-revalidate': p.token, 'x-ginko-min-rev': minRev },
|
|
126
|
+
redirect: 'manual',
|
|
127
|
+
})
|
|
128
|
+
await response.body?.cancel()
|
|
129
|
+
const rev = response.headers.get('x-ginko-rev')
|
|
130
|
+
// 503 keeps the old page on the site, so it is retried like a missing proof.
|
|
131
|
+
return { path, status: response.status, rev, ok: response.status !== 503 && proves(rev, p.min) }
|
|
132
|
+
} catch {
|
|
133
|
+
// A network error is treated like a 503: the site may answer on the next try.
|
|
134
|
+
return { path, status: 0, rev: null, ok: false }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function refreshPath(p: Plan, path: string): Promise<Row> {
|
|
139
|
+
let row: Row = { path, status: 0, rev: null, ok: false }
|
|
140
|
+
for (let attempt = 0; attempt <= RETRIES; attempt++) {
|
|
141
|
+
if (attempt > 0) await sleep(RETRY_MS)
|
|
142
|
+
row = await requestOnce(p, path)
|
|
143
|
+
if (row.ok) break
|
|
144
|
+
}
|
|
145
|
+
return row
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Sends the paths in batches of 20. Results keep the order of the paths. */
|
|
149
|
+
export const urgentRefresh = action({
|
|
150
|
+
args: { site: v.string(), opId: v.string() },
|
|
151
|
+
// Typed by hand: the action calls this module's own functions, so TypeScript cannot infer its result.
|
|
152
|
+
handler: async (ctx, args): Promise<RefreshResult> => {
|
|
153
|
+
const p = await ctx.runQuery(internal.refresh.plan, args)
|
|
154
|
+
if (p.replay !== undefined) return p.replay
|
|
155
|
+
const plan: Plan = p
|
|
156
|
+
const results: Row[] = []
|
|
157
|
+
for (let i = 0; i < plan.paths.length; i += BATCH) {
|
|
158
|
+
results.push(...(await Promise.all(plan.paths.slice(i, i + BATCH).map((path) => refreshPath(plan, path)))))
|
|
159
|
+
}
|
|
160
|
+
const result = { results, limited: plan.limited }
|
|
161
|
+
return ctx.runMutation(internal.refresh.record, { site: args.site, opId: args.opId, hash: plan.hash, result })
|
|
162
|
+
},
|
|
163
|
+
})
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// Schema releases and push keys (SPEC 5, 10). The CLI reaches `release` and `state` through
|
|
2
|
+
// the HTTP routes in routes/release.ts, which resolve the push key to its site first; the
|
|
3
|
+
// internal functions here trust that site id. Owners and admins use the public mutations.
|
|
4
|
+
import type { Fields, Json, Locale } from '@lupinum/ginko'
|
|
5
|
+
import { byteSize, checkSchema, defaultsFor, entryBytes, fitsBudget, diffSchema, recheckAll, releaseData, sha256, stableJson, validate, type MigrationDescriptor, type Schema } from '@lupinum/ginko/internal'
|
|
6
|
+
import { v } from 'convex/values'
|
|
7
|
+
import type { Doc, Id } from './_generated/dataModel'
|
|
8
|
+
import type { MutationCtx, QueryCtx } from './_generated/server'
|
|
9
|
+
import { internalMutation, internalQuery, mutation } from './_generated/server'
|
|
10
|
+
import { actorFor, checkRev, fail } from './lib/access'
|
|
11
|
+
import { nextPrints, treesOf, type Data, type Prints } from './lib/content'
|
|
12
|
+
import { msg, recorded } from './lib/history'
|
|
13
|
+
import { isFetchableSiteUrl } from './lib/siteUrl'
|
|
14
|
+
import { storageSums } from './lib/lifecycle'
|
|
15
|
+
import { putTrees } from './lib/trees'
|
|
16
|
+
import { BUDGET, checkNewFiles, checkNewLinks, entryUses, overBudget, same, sizeText, syncEntryRefs } from './lib/write'
|
|
17
|
+
import { labelOf } from './entries'
|
|
18
|
+
import { droppedFactsInUse } from './facts'
|
|
19
|
+
|
|
20
|
+
const scope = v.union(v.literal('release'), v.literal('pull'), v.literal('check'), v.literal('export'))
|
|
21
|
+
|
|
22
|
+
/** SPEC 5.2 step 9. */
|
|
23
|
+
export const RELEASE_LIMITS = { documents: 4000, writes: 4000, argBytes: 8 * 1024 * 1024 } as const
|
|
24
|
+
|
|
25
|
+
// 32 symbols: 256 is a multiple of 32, so a random byte maps to each symbol equally often.
|
|
26
|
+
const KEY_ALPHABET = 'abcdefghijkmnpqrstuvwxyz23456789'
|
|
27
|
+
|
|
28
|
+
type Entry = Doc<'entries'>
|
|
29
|
+
|
|
30
|
+
const current = (site: Doc<'sites'>) => ({ schemaRev: site.schemaRev, contentRev: site.contentRev })
|
|
31
|
+
|
|
32
|
+
/** Owner or admin of the site: the right to make and revoke its push keys (also for `ginko connect`, connect.ts). */
|
|
33
|
+
export async function ownerOf(ctx: QueryCtx, slug: string) {
|
|
34
|
+
const actor = await actorFor(ctx, slug)
|
|
35
|
+
if (actor.role === 'staff') fail('FORBIDDEN', 'errors.onlyOwnersAdminsManageKeys')
|
|
36
|
+
return actor
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function secret(): string {
|
|
40
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32))
|
|
41
|
+
return Array.from(bytes, (b) => KEY_ALPHABET[b % KEY_ALPHABET.length]).join('')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function allEntries(ctx: QueryCtx, site: Id<'sites'>): Promise<Entry[]> {
|
|
45
|
+
return ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site)).collect()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The entry a single brick starts with: its defaults, prints, trees, budget bytes and one revision per field (SPEC 5.2 step 7). */
|
|
49
|
+
interface NewSingle {
|
|
50
|
+
brick: string
|
|
51
|
+
data: Record<string, Json>
|
|
52
|
+
prints: Prints
|
|
53
|
+
fields: Fields
|
|
54
|
+
trees: { json: string; bytes: number }
|
|
55
|
+
bytes: number
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function newSingle(brick: string, fields: Fields, main: Locale): Promise<NewSingle> {
|
|
59
|
+
const data = defaultsFor(fields)
|
|
60
|
+
const prints = nextPrints({ fields, roots: Object.keys(data), before: {}, after: data, prints: {}, main, confirm: undefined })
|
|
61
|
+
return { brick, data, prints, fields, trees: await treesOf(fields, data), bytes: entryBytes(data, prints) }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Stores a new single. The release, devPush and the import's close (seed:importDone) share this write. */
|
|
65
|
+
export async function insertSingle(ctx: MutationCtx, site: Id<'sites'>, single: NewSingle, locales: Schema['locales']) {
|
|
66
|
+
const fieldRevs = Object.fromEntries(Object.keys(single.fields).map((name) => [name, 1]))
|
|
67
|
+
const id = await ctx.db.insert('entries', {
|
|
68
|
+
site, brick: single.brick, kind: 'single', order: 0, data: single.data, rev: 1, fieldRevs, lifeRev: 1,
|
|
69
|
+
prints: single.prints, bytes: single.bytes, treeBytes: single.trees.bytes, contentAt: Date.now(),
|
|
70
|
+
})
|
|
71
|
+
await putTrees(ctx, site, id, single.trees.json)
|
|
72
|
+
await syncEntryRefs(ctx, site, id, await entryUses(ctx, single.fields, single.data, locales))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The scopes of a publishing key made on the Team page (its "release" purpose); `ginko connect` gives the same. */
|
|
76
|
+
export const PUBLISHING_SCOPES = ['release', 'check', 'pull', 'export'] as const
|
|
77
|
+
|
|
78
|
+
export async function insertPushKey(ctx: MutationCtx, site: Doc<'sites'>, input: { label: string; scopes: ('release' | 'pull' | 'check' | 'export')[]; createdBy: string }) {
|
|
79
|
+
const label = input.label.trim()
|
|
80
|
+
if (label.length < 1 || label.length > 60) fail('INVALID', 'errors.nameLength1To60')
|
|
81
|
+
const scopes = [...new Set(input.scopes)]
|
|
82
|
+
if (scopes.length === 0) fail('INVALID', 'errors.keyNeedsScope')
|
|
83
|
+
const key = `ginko_${site.slug}_${secret()}`
|
|
84
|
+
const id = await ctx.db.insert('pushKeys', { site: site._id, hash: sha256(key), label, scopes, createdBy: input.createdBy })
|
|
85
|
+
return { id, key }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Owner or admin creates a push key; the plaintext is returned once and only its SHA-256 is stored (SPEC 10). */
|
|
89
|
+
export const createPushKey = mutation({
|
|
90
|
+
args: { site: v.string(), label: v.string(), scopes: v.array(scope) },
|
|
91
|
+
handler: async (ctx, args) => {
|
|
92
|
+
const actor = await ownerOf(ctx, args.site)
|
|
93
|
+
return insertPushKey(ctx, actor.site, { label: args.label, scopes: args.scopes, createdBy: actor.user.id })
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
/** The CI key of a new deployment's first site, next to sites:bootstrap. Internal: deploy or admin key only. */
|
|
98
|
+
export const bootstrapKey = internalMutation({
|
|
99
|
+
args: { site: v.string(), label: v.string(), scopes: v.array(scope) },
|
|
100
|
+
handler: async (ctx, args) => {
|
|
101
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
102
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteMissing')
|
|
103
|
+
return insertPushKey(ctx, site, { label: args.label, scopes: args.scopes, createdBy: 'bootstrap' })
|
|
104
|
+
},
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The push keys of a site, for operators (`npx convex run release:pushKeys '{"site":"linde"}'`): to find a
|
|
109
|
+
* leaked key by its label and revoke it with `release:revokePushKeyAsOperator`. Never the key or its hash.
|
|
110
|
+
*/
|
|
111
|
+
export const pushKeys = internalQuery({
|
|
112
|
+
args: { site: v.string() },
|
|
113
|
+
handler: async (ctx, args) => {
|
|
114
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
115
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteMissing')
|
|
116
|
+
const rows = await ctx.db.query('pushKeys').withIndex('by_site', (q) => q.eq('site', site._id)).collect()
|
|
117
|
+
return rows.map((r) => ({ id: r._id, label: r.label, scopes: r.scopes, createdBy: r.createdBy, createdAt: r._creationTime, lastUsedAt: r.lastUsedAt ?? null, revokedAt: r.revokedAt ?? null }))
|
|
118
|
+
},
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
/** `revokePushKey` for operators, who have a deploy key but no session. */
|
|
122
|
+
export const revokePushKeyAsOperator = internalMutation({
|
|
123
|
+
args: { key: v.id('pushKeys') },
|
|
124
|
+
handler: async (ctx, args) => {
|
|
125
|
+
const row = await ctx.db.get(args.key)
|
|
126
|
+
if (!row) fail('NOT_FOUND', 'errors.keyNotFound')
|
|
127
|
+
if (!row.revokedAt) await ctx.db.patch(row._id, { revokedAt: Date.now() })
|
|
128
|
+
return { id: row._id }
|
|
129
|
+
},
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
/** Owner or admin revokes a push key of the site. Revoking twice changes nothing. */
|
|
133
|
+
export const revokePushKey = mutation({
|
|
134
|
+
args: { site: v.string(), key: v.string() },
|
|
135
|
+
handler: async (ctx, args) => {
|
|
136
|
+
const actor = await ownerOf(ctx, args.site)
|
|
137
|
+
const id = ctx.db.normalizeId('pushKeys', args.key)
|
|
138
|
+
const row = id ? await ctx.db.get(id) : null
|
|
139
|
+
if (!row || row.site !== actor.site._id) fail('NOT_FOUND', 'errors.keyNotFound')
|
|
140
|
+
if (!row.revokedAt) await ctx.db.patch(row._id, { revokedAt: Date.now() })
|
|
141
|
+
return { id: row._id }
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
/** The HTTP layer looks a key up by its hash. Revocation and scope are checked there. */
|
|
146
|
+
export const pushKey = internalQuery({
|
|
147
|
+
args: { hash: v.string() },
|
|
148
|
+
handler: async (ctx, args) => {
|
|
149
|
+
const key = await ctx.db.query('pushKeys').withIndex('by_hash', (q) => q.eq('hash', args.hash)).unique()
|
|
150
|
+
if (!key) return null
|
|
151
|
+
const site = await ctx.db.get(key.site)
|
|
152
|
+
if (!site || site.deleting) return null
|
|
153
|
+
return { keyId: key._id, site: key.site, siteSlug: site.slug, scopes: key.scopes, revokedAt: key.revokedAt ?? null, lastUsedAt: key.lastUsedAt ?? null }
|
|
154
|
+
},
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
/** Stamps when a push key was last used. Called at most once an hour per key, so CI runs add almost no writes. */
|
|
158
|
+
export const touchPushKey = internalMutation({
|
|
159
|
+
args: { key: v.id('pushKeys') },
|
|
160
|
+
handler: async (ctx, { key }) => {
|
|
161
|
+
await ctx.db.patch(key, { lastUsedAt: Date.now() })
|
|
162
|
+
},
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
/** SPEC 5.1 step 2: schema, revisions, applied migrations and the data of every entry, deleted ones too. */
|
|
166
|
+
export const state = internalQuery({
|
|
167
|
+
args: { site: v.id('sites') },
|
|
168
|
+
handler: async (ctx, args) => {
|
|
169
|
+
const site = await ctx.db.get(args.site)
|
|
170
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteNotFound')
|
|
171
|
+
const migrations = await ctx.db.query('migrationsApplied').withIndex('by_site_id', (q) => q.eq('site', args.site)).collect()
|
|
172
|
+
const entries = await allEntries(ctx, args.site)
|
|
173
|
+
return {
|
|
174
|
+
site: site.slug,
|
|
175
|
+
schema: site.schema as Json,
|
|
176
|
+
schemaRev: site.schemaRev,
|
|
177
|
+
contentRev: site.contentRev,
|
|
178
|
+
migrations: migrations.map((m) => ({ id: m.id, brick: m.brick, fills: m.fills, fingerprint: m.fingerprint, schemaRev: m.schemaRev })),
|
|
179
|
+
entries: entries.map((e) => ({ id: e._id, brick: e.brick, kind: e.kind, order: e.order, data: e.data as Json, deletedAt: e.deletedAt ?? null })),
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* SPEC 5.2: one transaction that checks the candidate schema and the migration writes of the
|
|
186
|
+
* CLI, then stores the schema and every changed entry. Steps are numbered as in the spec.
|
|
187
|
+
*/
|
|
188
|
+
export const release = internalMutation({
|
|
189
|
+
args: {
|
|
190
|
+
site: v.id('sites'),
|
|
191
|
+
/** Who sends it, for the change row, e.g. `pushkey:<id>`. */
|
|
192
|
+
actor: v.string(),
|
|
193
|
+
commit: v.string(),
|
|
194
|
+
expectedSchemaRev: v.number(),
|
|
195
|
+
expectedContentRev: v.number(),
|
|
196
|
+
schema: v.any(),
|
|
197
|
+
writes: v.array(v.object({ entry: v.string(), fields: v.record(v.string(), v.any()) })),
|
|
198
|
+
},
|
|
199
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
200
|
+
const site = await ctx.db.get(args.site)
|
|
201
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteNotFound')
|
|
202
|
+
|
|
203
|
+
// 1. The same commit again: the stored answer, nothing changes.
|
|
204
|
+
if (site.release?.commit === args.commit) return { schemaRev: site.release.schemaRev, contentRev: site.release.contentRev }
|
|
205
|
+
|
|
206
|
+
// 2.
|
|
207
|
+
checkRev(args.expectedSchemaRev)
|
|
208
|
+
checkRev(args.expectedContentRev)
|
|
209
|
+
if (args.expectedSchemaRev !== site.schemaRev) fail('CHANGED_SINCE', 'errors.schemaChangedMeanwhileRetry', undefined, current(site))
|
|
210
|
+
if (args.writes.length > RELEASE_LIMITS.writes || byteSize(args) > RELEASE_LIMITS.argBytes) fail('RELEASE_TOO_LARGE', 'errors.releaseTooLarge')
|
|
211
|
+
|
|
212
|
+
const stored = site.schema as Schema
|
|
213
|
+
const next = args.schema as Schema
|
|
214
|
+
const problems = checkSchema(next)
|
|
215
|
+
if (problems.length) fail('INVALID', 'errors.schemaInvalid', undefined, { problems: problems as unknown as Json })
|
|
216
|
+
// The key names the site; its config may not speak for another one. (checkSchema already requires an
|
|
217
|
+
// http(s) URL: it is where "Update website now" sends the site's refresh token.)
|
|
218
|
+
if (next.site !== site.slug) fail('INVALID', 'errors.siteNameMismatchInSchema')
|
|
219
|
+
// The release may move the site to a new address, but only to one the platform may call (no internal hosts).
|
|
220
|
+
if (next.url !== site.url && !isFetchableSiteUrl(next.url, process.env.GINKO_LOCAL === '1')) fail('INVALID', 'errors.siteUrlNotAllowed')
|
|
221
|
+
|
|
222
|
+
// 3. Migration changes are reported first: they name the exact fix (new ID). The ledger of
|
|
223
|
+
// applied migrations is the permanent identity: the schema forgets a migration once it is
|
|
224
|
+
// dropped from the config, the ledger does not (SPEC 2.6). One row per ID, never a second one.
|
|
225
|
+
const ledger = await ctx.db.query('migrationsApplied').withIndex('by_site_id', (q) => q.eq('site', args.site)).collect()
|
|
226
|
+
const applied = new Map<string, MigrationDescriptor>()
|
|
227
|
+
for (const m of [...stored.migrations, ...ledger]) applied.set(m.id, { id: m.id, brick: m.brick, fills: m.fills, fingerprint: m.fingerprint })
|
|
228
|
+
const rejected = [...diffSchema({ ...stored, migrations: [...applied.values()] }, next).rejected, ...await droppedFactsInUse(ctx, site, next)]
|
|
229
|
+
const changedMigrations = rejected.filter((r) => r.kind === 'migrationChanged')
|
|
230
|
+
if (changedMigrations.length) fail('MIGRATION_CHANGED', 'errors.knownMigrationChanged', undefined, { rejected: changedMigrations as unknown as Json })
|
|
231
|
+
if (rejected.length) fail('SCHEMA_REJECTED', 'errors.schemaBreaksChangeRules', undefined, { rejected: rejected as unknown as Json })
|
|
232
|
+
|
|
233
|
+
// 4. Applied IDs with the same descriptor are done; the diff above rejects any other known ID.
|
|
234
|
+
const fresh = next.migrations.filter((m) => !applied.has(m.id))
|
|
235
|
+
const main = next.locales[0]!
|
|
236
|
+
for (const m of fresh) {
|
|
237
|
+
if (next.bricks[m.brick]?.fields[m.fills]?.type === 'slug') fail('INVALID', 'errors.migrationCannotSetSlug', { id: m.id })
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// 5. New migrations or writes need the content the CLI planned against.
|
|
241
|
+
if ((fresh.length > 0 || args.writes.length > 0) && args.expectedContentRev !== site.contentRev) {
|
|
242
|
+
fail('CHANGED_SINCE', 'errors.contentChangedMeanwhileRetry', undefined, current(site))
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const entries = await allEntries(ctx, args.site)
|
|
246
|
+
const byId = new Map(entries.map((e) => [e._id, e]))
|
|
247
|
+
|
|
248
|
+
// 6. Completeness: each new migration writes its field once for every entry of its brick, deleted ones too.
|
|
249
|
+
const fillsOf = new Map<string, Set<string>>()
|
|
250
|
+
for (const m of fresh) fillsOf.set(m.brick, (fillsOf.get(m.brick) ?? new Set<string>()).add(m.fills))
|
|
251
|
+
const writesOf = new Map<Id<'entries'>, Record<string, Json>>()
|
|
252
|
+
for (const w of args.writes) {
|
|
253
|
+
const id = ctx.db.normalizeId('entries', w.entry)
|
|
254
|
+
const entry = id ? byId.get(id) : undefined
|
|
255
|
+
if (!id || !entry) fail('NOT_FOUND', 'errors.writeEntryNotFound', undefined, { entry: w.entry })
|
|
256
|
+
const allowed = fillsOf.get(entry.brick) ?? new Set<string>()
|
|
257
|
+
const got = writesOf.get(id) ?? {}
|
|
258
|
+
for (const [field, value] of Object.entries(w.fields)) {
|
|
259
|
+
if (!allowed.has(field) || Object.hasOwn(got, field)) {
|
|
260
|
+
fail('MIGRATION_INCOMPLETE', 'errors.writesDoNotFitMigrations', undefined, { entry: w.entry, field })
|
|
261
|
+
}
|
|
262
|
+
got[field] = value as Json
|
|
263
|
+
}
|
|
264
|
+
writesOf.set(id, got)
|
|
265
|
+
}
|
|
266
|
+
for (const m of fresh) {
|
|
267
|
+
for (const entry of entries) {
|
|
268
|
+
if (entry.brick === m.brick && !Object.hasOwn(writesOf.get(entry._id) ?? {}, m.fills)) {
|
|
269
|
+
fail('MIGRATION_INCOMPLETE', 'errors.migrationMissingForEntry', { id: m.id }, { migration: m.id, entry: entry._id })
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// 7. Candidate on the server: new required defaults (also new list columns) and writes into every
|
|
275
|
+
// entry, new singles from defaults. Same rules as the CLI's candidate (core releaseData).
|
|
276
|
+
const updates: { entry: Entry; data: Record<string, Json>; prints: Prints; roots: string[]; trees: { json: string; bytes: number }; bytes: number }[] = []
|
|
277
|
+
const checked: { entry: Entry; data: Record<string, Json> }[] = []
|
|
278
|
+
for (const [key, brick] of Object.entries(next.bricks)) {
|
|
279
|
+
if (!Object.hasOwn(stored.bricks, key)) continue
|
|
280
|
+
const all = recheckAll(stored, next, key)
|
|
281
|
+
for (const entry of entries.filter((e) => e.brick === key)) {
|
|
282
|
+
const before = entry.data as Record<string, Json>
|
|
283
|
+
const { data, roots } = releaseData(stored.bricks[key]!.fields, brick.fields, before, writesOf.get(entry._id) ?? {})
|
|
284
|
+
const prints = nextPrints({ fields: brick.fields, roots, before, after: data, prints: entry.prints, main, confirm: undefined })
|
|
285
|
+
const changed = roots.filter((r) => !same(data[r], before[r]) || !same(printsOf(prints, r), printsOf(entry.prints, r)))
|
|
286
|
+
// The trash keeps no trees.
|
|
287
|
+
const trees = entry.deletedAt === undefined ? await treesOf(brick.fields, data) : { json: '', bytes: 0 }
|
|
288
|
+
if (changed.length) updates.push({ entry, data, prints, roots: changed, trees, bytes: entryBytes(data, prints) })
|
|
289
|
+
if (changed.length || all) checked.push({ entry, data })
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const created: NewSingle[] = []
|
|
294
|
+
for (const [key, brick] of Object.entries(next.bricks)) {
|
|
295
|
+
if (Object.hasOwn(stored.bricks, key) || brick.kind !== 'single') continue
|
|
296
|
+
created.push(await newSingle(key, brick.fields, main))
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Every entry of a brick whose fields changed, not only the written ones (break-it 9): a lowered
|
|
300
|
+
// min off the step grid or a migration that returned nothing must not be stored as valid.
|
|
301
|
+
for (const c of checked) {
|
|
302
|
+
const result = await validate(next, c.entry.brick, c.data, { mode: 'release' })
|
|
303
|
+
if (result.errors.length) fail('INVALID', 'errors.entryNoLongerFitsAfterRelease', undefined, { entry: c.entry._id, errors: result.errors as unknown as Json })
|
|
304
|
+
}
|
|
305
|
+
for (const c of created) {
|
|
306
|
+
const result = await validate(next, c.brick, c.data, { mode: 'release' })
|
|
307
|
+
if (result.errors.length) fail('INVALID', 'errors.newSingletonDoesNotFit', { brick: c.brick }, { brick: c.brick, errors: result.errors as unknown as Json })
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Files: a file that an entry did not reference before must be a ready upload of this site (SPEC 4.3).
|
|
311
|
+
// An image field takes images only, also through a release (break-it 9).
|
|
312
|
+
for (const u of updates) await checkNewFiles(ctx, args.site, next.bricks[u.entry.brick]!.fields, u.entry.data as Data, u.data)
|
|
313
|
+
for (const c of created) await checkNewFiles(ctx, args.site, c.fields, {}, c.data)
|
|
314
|
+
|
|
315
|
+
// Links: no live entry may get a new broken link. Checked against the new schema (its pages) with all written entries in place; drafts are not online.
|
|
316
|
+
await checkNewLinks(ctx, { ...site, schema: next }, updates
|
|
317
|
+
.filter((u) => !u.entry.deletedAt && u.entry.state !== 'draft')
|
|
318
|
+
.map((u) => ({ entry: u.entry, fields: next.bricks[u.entry.brick]!.fields, before: u.entry.data as Data, after: u.data })))
|
|
319
|
+
|
|
320
|
+
// Budget (SPEC 3, 5.2 step 9). Documents are the entries written plus the singles created.
|
|
321
|
+
if (updates.length + created.length > RELEASE_LIMITS.documents) fail('RELEASE_TOO_LARGE', 'errors.releaseTooLarge')
|
|
322
|
+
const updated = new Map(updates.map((u) => [u.entry._id, u]))
|
|
323
|
+
// A written live entry and a created single must fit the entry limit unless they do not grow. An entry the release
|
|
324
|
+
// does not touch is not checked, nor a removed one (the trash counts apart); the error names the entry.
|
|
325
|
+
const tooLarge = [
|
|
326
|
+
...created.map((c) => ({ after: c.bytes, before: 0, title: labelOf(next, c.brick, c.data), entry: undefined })),
|
|
327
|
+
...updates.filter((u) => !u.entry.deletedAt).map((u) => ({ after: u.bytes, before: u.entry.bytes, title: labelOf(next, u.entry.brick, u.data), entry: u.entry._id })),
|
|
328
|
+
].find((e) => !fitsBudget(e.after, e.before, BUDGET.entryBytes))
|
|
329
|
+
if (tooLarge) {
|
|
330
|
+
fail('TOO_LARGE', 'errors.releaseEntryTooLarge', { title: tooLarge.title, used: sizeText(tooLarge.after), limit: sizeText(BUDGET.entryBytes) }, tooLarge.entry ? { entry: tooLarge.entry } : undefined)
|
|
331
|
+
}
|
|
332
|
+
// entryCount and bytes count live entries only (SPEC 4.2 remove); removed ones are in trashBytes.
|
|
333
|
+
const entryCount = entries.filter((e) => !e.deletedAt).length + created.length
|
|
334
|
+
const after = storageSums([
|
|
335
|
+
...entries.map((e) => { const u = updated.get(e._id); return u ? { deletedAt: e.deletedAt, bytes: u.bytes, treeBytes: u.trees.bytes } : e }),
|
|
336
|
+
...created.map((c) => ({ bytes: c.bytes, treeBytes: c.trees.bytes })),
|
|
337
|
+
])
|
|
338
|
+
if (entryCount > BUDGET.entries) fail('TOO_LARGE', 'errors.siteEntryCapReached')
|
|
339
|
+
if (!fitsBudget(after.bytes, site.bytes, BUDGET.siteBytes)) fail('TOO_LARGE', 'errors.siteStorageLimitReached', overBudget(after.bytes, BUDGET.siteBytes))
|
|
340
|
+
if (!fitsBudget(after.treeBytes, site.treeBytes ?? 0, BUDGET.treeBytes)) fail('TOO_LARGE', 'errors.entryTooComplex')
|
|
341
|
+
|
|
342
|
+
// 8. Write: schema, entries, migrations, contentRev only when an entry changed, release record, change row.
|
|
343
|
+
const changedContent = updates.length > 0 || created.length > 0
|
|
344
|
+
const schemaRev = site.schemaRev + 1
|
|
345
|
+
const contentRev = changedContent ? site.contentRev + 1 : site.contentRev
|
|
346
|
+
for (const u of updates) {
|
|
347
|
+
const rev = u.entry.rev + 1
|
|
348
|
+
const fieldRevs = { ...u.entry.fieldRevs }
|
|
349
|
+
for (const root of u.roots) fieldRevs[root] = rev
|
|
350
|
+
await ctx.db.patch(u.entry._id, { data: u.data, prints: u.prints, trees: undefined, rev, fieldRevs, bytes: u.bytes, treeBytes: u.trees.bytes })
|
|
351
|
+
await putTrees(ctx, args.site, u.entry._id, u.trees.json)
|
|
352
|
+
await syncEntryRefs(ctx, args.site, u.entry._id, await entryUses(ctx, next.bricks[u.entry.brick]!.fields, u.data, next.locales))
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
for (const c of created) await insertSingle(ctx, args.site, c, next.locales)
|
|
356
|
+
|
|
357
|
+
for (const m of fresh) {
|
|
358
|
+
await ctx.db.insert('migrationsApplied', { site: args.site, id: m.id, brick: m.brick, fills: m.fills, fingerprint: m.fingerprint, schemaRev })
|
|
359
|
+
}
|
|
360
|
+
const at = Date.now()
|
|
361
|
+
await ctx.db.patch(args.site, {
|
|
362
|
+
schema: next as unknown as Json,
|
|
363
|
+
// The config owns the site's name and URL: "Seite ansehen", invites and the refresh target follow it.
|
|
364
|
+
name: next.name,
|
|
365
|
+
url: next.url,
|
|
366
|
+
schemaRev,
|
|
367
|
+
contentRev,
|
|
368
|
+
entryCount,
|
|
369
|
+
...after,
|
|
370
|
+
release: { commit: args.commit, schemaRev, contentRev, at },
|
|
371
|
+
})
|
|
372
|
+
await ctx.db.insert('changes', {
|
|
373
|
+
site: args.site, brick: '', actor: args.actor, opId: `release:${args.commit}`, kind: 'release',
|
|
374
|
+
...recorded(msg('history.release', { commit: args.commit.slice(0, 7) })), contentRev, at,
|
|
375
|
+
})
|
|
376
|
+
return { schemaRev, contentRev }
|
|
377
|
+
},
|
|
378
|
+
})
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* `pnpm local:dev` (SPEC 5.3): stores the site's schema in the LOCAL platform; rejected changes go
|
|
382
|
+
* through and come back as warnings. Internal, so only `npx convex run` with the deployment's
|
|
383
|
+
* admin key can call it — no sign-in needed locally, unreachable for browsers. A site that does
|
|
384
|
+
* not exist yet is created, so a fresh local backend works without setup. Every non-retired
|
|
385
|
+
* single brick gets its one entry when it has none, so its entry can be saved at once.
|
|
386
|
+
*/
|
|
387
|
+
export const devPush = internalMutation({
|
|
388
|
+
args: { site: v.string(), schema: v.any() },
|
|
389
|
+
handler: async (ctx, args) => {
|
|
390
|
+
if (process.env.GINKO_LOCAL !== '1') fail('FORBIDDEN', 'errors.devPushLocalOnly')
|
|
391
|
+
const next = args.schema as Schema
|
|
392
|
+
const problems = checkSchema(next)
|
|
393
|
+
if (problems.length) fail('INVALID', 'errors.schemaInvalid', undefined, { problems: problems as unknown as Json })
|
|
394
|
+
if (next.site !== args.site) fail('INVALID', 'errors.siteNameMismatchInSchema')
|
|
395
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
396
|
+
if (!site) {
|
|
397
|
+
const id = await ctx.db.insert('sites', {
|
|
398
|
+
slug: args.site, name: next.name, url: next.url, previewOrigins: ['http://localhost:3000'], schema: next as unknown as Json,
|
|
399
|
+
schemaRev: 1, contentRev: 1, entryCount: 0, bytes: 0, trashBytes: 0, treeBytes: 0, release: null,
|
|
400
|
+
})
|
|
401
|
+
await createMissingSingles(ctx, (await ctx.db.get(id))!, next)
|
|
402
|
+
return { schemaRev: 1, changes: [], warnings: [] }
|
|
403
|
+
}
|
|
404
|
+
const stored = site.schema as Schema
|
|
405
|
+
const diff = diffSchema(stored, next)
|
|
406
|
+
const changes = diff.changes
|
|
407
|
+
const rejected = [...diff.rejected, ...await droppedFactsInUse(ctx, site, next)]
|
|
408
|
+
const changed = stableJson(next as unknown as Json) !== stableJson(stored as unknown as Json)
|
|
409
|
+
const schemaRev = changed ? site.schemaRev + 1 : site.schemaRev
|
|
410
|
+
if (changed) await ctx.db.patch(site._id, { schema: next as unknown as Json, name: next.name, url: next.url, schemaRev })
|
|
411
|
+
await createMissingSingles(ctx, site, next)
|
|
412
|
+
return { schemaRev, changes: changes as unknown as Json, warnings: rejected as unknown as Json }
|
|
413
|
+
},
|
|
414
|
+
})
|
|
415
|
+
|
|
416
|
+
/** devPush: the missing single entries, with the site's counters kept exact (entryCount, the byte sums). */
|
|
417
|
+
async function createMissingSingles(ctx: MutationCtx, site: Doc<'sites'>, schema: Schema) {
|
|
418
|
+
const entries = await allEntries(ctx, site._id)
|
|
419
|
+
const filled = new Set(entries.map((e) => e.brick))
|
|
420
|
+
const main = schema.locales[0]!
|
|
421
|
+
const created: NewSingle[] = []
|
|
422
|
+
for (const [key, brick] of Object.entries(schema.bricks)) {
|
|
423
|
+
if (brick.kind === 'single' && !brick.retired && !filled.has(key)) created.push(await newSingle(key, brick.fields, main))
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
for (const single of created) await insertSingle(ctx, site._id, single, schema.locales)
|
|
427
|
+
await ctx.db.patch(site._id, {
|
|
428
|
+
entryCount: entries.filter((e) => !e.deletedAt).length + created.length,
|
|
429
|
+
...storageSums([...entries, ...created.map((c) => ({ bytes: c.bytes, treeBytes: c.trees.bytes }))]),
|
|
430
|
+
})
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function printsOf(prints: Prints, root: string) {
|
|
434
|
+
return Object.fromEntries(Object.entries(prints).filter(([leaf]) => leaf === root || leaf.startsWith(`${root}.`)))
|
|
435
|
+
}
|