Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

type: copies for other people go through the field-class projection (#688)

nyblneteae4d148b296
diff --git a/scripts/test-export-secrets.ts b/scripts/test-export-secrets.ts
index b719b9b9..fd72a100 100644
--- a/scripts/test-export-secrets.ts
+++ b/scripts/test-export-secrets.ts
@@ -442,7 +442,12 @@ for (const app of CLIP_APPS) {
const fn = embed.slice(embed.indexOf('export function readArtifact'))
ok(/return \{[^}]*doc:\s*embedSafe\(/.test(fn.slice(0, fn.indexOf('\n}') + 2)),
'type/src/embed.ts: readArtifact keeps the source document only through embedSafe — embedded documents don\'t carry sharing keys in')
- ok(/return withoutEmbeddedCaps\(withoutCaps\(doc\)\)/.test(model),
+ // Judged inside docForExport's OWN body, with comments masked: a file-wide
+ // match, or one that reads comments, would still pass
+ // if the strip moved into a helper docForExport no longer called. The body
+ // now projects through the kernel copy table too, so the strip is matched
+ // as an expression rather than as the whole return statement.
+ ok(/withoutEmbeddedCaps\(withoutCaps\(doc\)\)/.test(mask(exportedBody(model, 'docForExport'))),
'type/src/model.ts: docForExport also strips embedded documents\' keys')
ok(/const clone = \(doc: TypeDoc\): TypeDoc => withoutEmbeddedCaps\(/.test(share),
'type/src/share.ts: every share copy is built from an embed-safe clone')
diff --git a/scripts/test-type-share.ts b/scripts/test-type-share.ts
index e0c0aa5f..fe2141cb 100644
--- a/scripts/test-type-share.ts
+++ b/scripts/test-type-share.ts
@@ -28,6 +28,10 @@ register('./lib/ts-resolve-hooks.mjs', import.meta.url)
const { readerCopy, inviteCopy } = await import('../type/src/share.ts')
const { emptyDoc, parseDoc, docForExport } = await import('../type/src/model.ts')
const { mintCollab } = await import('../kernel/src/sync/online.ts')
+const { mergeDoc } = await import('../type/src/merge.ts')
+const { newThread, writeThreads } = await import('../type/src/comments.ts')
+const { sign, newKey } = await import('../type/src/canon.ts')
+const { TYPE_FIELDS, HISTORY_CLASS } = await import('../type/src/docclass.ts')
import type { TypeDoc } from '../type/src/model.ts'
let checks = 0, failures = 0
@@ -187,5 +191,152 @@ console.log('\nembedded documents don\'t carry sharing keys out\n')
'and so do the recovery snapshot and the version history, which any local page can read')
}
+// ════════════════════════════════════════════════════════════════════════════
+// WHAT EACH COPY MAY CARRY — the field-class projection.
+//
+// Every outward copy is built by the kernel's `projectForCopy` with type's
+// field-class map (type/src/docclass.ts). This rig runs EVERY outward builder
+// type has against two sources:
+//
+// FULL carries a whole earlier draft (revisions), an internal comment
+// thread, a real signature, a real owner key, and a field this build
+// does not declare. Each carries a MARKER string a leak would show.
+// BARE carries none of the history at all (the absent-field lesson: a rule
+// can quietly skip a field the fixture never had, so every rule is
+// also run against a source that LACKS the field).
+//
+// The FULL fixture is built through type's own constructors — newThread /
+// writeThreads, canon's sign, mintCollab — and then through parseDoc, so it is
+// the shape the app actually holds. Before any "the copy does not carry X"
+// check, the rig asserts the SOURCE does carry X: a fixture that silently
+// lost its comment would make every "no comment in the copy" check pass for
+// free, which is how a rig ends up certifying a leak.
+//
+// Builders (type has exactly these three; there is no duplicate or template
+// copy, and print renders HTML without embedding the document):
+// readerCopy share.ts tier 'reader'
+// inviteCopy share.ts tier 'invite', with and without history
+// docForExport model.ts tier 'copyJSON' — Copy document JSON AND mail merge
+//
+// Lives in this rig, not its own file, because this rig is already run by CI
+// and every copy checked here is a share copy.
+
+const H = (s: string) => console.log(`\n=== ${s} ===`)
+
+const DRAFT = 'DELETED-DRAFT-WORDING-30-DAYS'
+const NOTE = 'INTERNAL-COMMENT-WE-CAN-GO-TO-90'
+const FUTURE = 'UNDECLARED-FUTURE-FIELD-VALUE'
+
+async function full(): Promise<{ doc: TypeDoc; ownerPriv: string }> {
+ const collab = await mintCollab()
+ const d = { ...emptyDoc(), title: 'Services Agreement', collab } as TypeDoc
+ d.body = [{ id: 'p1', kind: 'para', text: 'Payment is due within 60 days.' }]
+ d.revisions = [{ id: 'rev1', at: '2026-10-01T00:00:00.000Z', label: 'Revision 1',
+ body: [{ id: 'p1', kind: 'para', text: DRAFT }] }]
+ writeThreads(d, [newThread(d.body[0], 0, 7, 'Bob', NOTE)])
+ d.signatures = [await sign(d, await newKey(), { name: 'Alice', prev: null })]
+ ;(d as Record<string, unknown>).futureField = FUTURE
+ const r = parseDoc(JSON.stringify(d))
+ if (!r.ok) throw new Error('FULL fixture did not parse')
+ return { doc: r.doc, ownerPriv: collab.ownerPriv as string }
+}
+
+async function bare(): Promise<{ doc: TypeDoc; ownerPriv: string }> {
+ const collab = await mintCollab()
+ const raw = { ...emptyDoc(), collab } as Record<string, unknown>
+ raw.body = [{ id: 'p1', kind: 'para', text: 'Payment is due within 60 days.' }]
+ delete raw.revisions; delete raw.signatures; delete raw.comments
+ const r = parseDoc(JSON.stringify(raw))
+ if (!r.ok) throw new Error('BARE fixture did not parse')
+ return { doc: r.doc, ownerPriv: collab.ownerPriv as string }
+}
+
+const has = (o: unknown, s: string) => JSON.stringify(o).includes(s)
+const carriesHistory = (o: TypeDoc) =>
+ (o.revisions?.length ?? 0) > 0 || (o.signatures?.length ?? 0) > 0 || o.comments !== undefined
+
+H('the FULL fixture really carries everything a leak would show')
+const F = await full()
+ok(has(F.doc, DRAFT), 'the source holds a whole earlier draft in revisions')
+ok(has(F.doc, NOTE), 'the source holds an internal comment thread (it survived parseDoc)')
+ok(F.doc.signatures.length === 1, 'the source holds a real signature')
+ok(has(F.doc, FUTURE), 'the source holds a field this build does not declare')
+ok(typeof (F.doc.collab as { ownerPriv?: string }).ownerPriv === 'string', 'the source holds a real owner private key')
+
+H('a VIEW-ONLY copy carries no history (tier reader)')
+{
+ const r = readerCopy(F.doc)
+ ok(!has(r, DRAFT), 'no earlier draft — the wording negotiated away stays here')
+ ok(!has(r, NOTE), 'no internal comment')
+ ok(!r.signatures?.length, 'no signatures: one covering history the copy lacks would read "changed" forever')
+ for (const k of HISTORY_CLASS) ok(!(k in r), `${k} is absent as a FIELD, not merely emptied`)
+ ok(!has(r, FUTURE), 'an undeclared field does not ride along')
+ ok(r.readonly === true, 'the copy is read-only (set by the tier, not by the source)')
+ ok(!('ownerPriv' in (r.collab as object)), 'and holds no owner key')
+ ok(r.collab?.role === 'reader' && r.collab?.on === true, 'and is a live reader')
+ ok(r.body[0].text === F.doc.body[0].text && r.title === F.doc.title, 'while the document itself is intact')
+}
+{
+ const B = await bare()
+ const r = readerCopy(B.doc)
+ ok(r.readonly === true, 'BARE: still read-only — the mode is a property of the tier, not of the source')
+ ok(!carriesHistory(r), 'BARE: invents no history')
+ ok(r.body[0].text === B.doc.body[0].text, 'BARE: content intact')
+}
+
+H('Copy document JSON carries no history and no credentials (tier copyJSON)')
+{
+ const j = docForExport(F.doc)
+ ok(!has(j, DRAFT) && !has(j, NOTE) && !j.signatures?.length, 'no draft, no comment, no signature')
+ ok(!('collab' in j), 'no collaboration block at all')
+ ok(!has(j, FUTURE), 'no undeclared field')
+ ok(j.body[0].text === F.doc.body[0].text && j.docId === F.doc.docId, 'content and identity intact')
+ const B = await bare()
+ ok(!carriesHistory(docForExport(B.doc)), 'BARE: invents no history')
+}
+
+H('mail merge: every letter is a new document with no history (copyJSON + a fresh identity)')
+{
+ const a = mergeDoc(F.doc, { Name: 'Ada' }, ['Name'], 'list.bento.html')
+ const b = mergeDoc(F.doc, { Name: 'Grace' }, ['Name'], 'list.bento.html')
+ ok(a.docId !== b.docId, 'two letters have distinct docIds')
+ ok(a.docId !== F.doc.docId && b.docId !== F.doc.docId, 'neither reuses the source document\'s identity')
+ for (const [n, m] of [['first', a], ['second', b]] as const) {
+ ok(!has(m, DRAFT) && !has(m, NOTE), `the ${n} letter carries no draft and no comment`)
+ ok(!m.signatures.length && !m.revisions.length, `the ${n} letter carries no signatures and no revisions`)
+ ok(!('collab' in m), `the ${n} letter carries no collaboration block`)
+ }
+ const B = await bare()
+ ok(!carriesHistory(mergeDoc(B.doc, { Name: 'X' }, ['Name'], 's')), 'BARE: invents no history')
+}
+
+H('an INVITE keeps history by default, and leaves it out when asked (tier invite)')
+{
+ const keep = await inviteCopy(F.doc, F.ownerPriv)
+ ok(has(keep, DRAFT) && has(keep, NOTE) && keep.signatures.length === 1,
+ 'by default the invitee gets the history — the kernel\'s invite rule')
+ ok(!('ownerPriv' in (keep.collab as object)), 'but never the owner key')
+ ok(keep.collab?.on === true, 'and joins live')
+ ok(!has(keep, FUTURE), 'an undeclared field stays behind even here — an invite is a file for someone else')
+ ok(keep.readonly !== true, 'an editor copy is not read-only')
+
+ const out = await inviteCopy(F.doc, F.ownerPriv, { withHistory: false })
+ for (const k of HISTORY_CLASS) ok(!(k in out), `"Leave version history out" drops ${k}`)
+ ok(!has(out, DRAFT) && !has(out, NOTE), 'so the earlier draft and the comment are gone')
+ ok(out.body[0].text === F.doc.body[0].text, 'and the document itself is untouched')
+ ok(out.collab?.on === true && !!(out.collab as { invite?: unknown }).invite, 'still a working invite')
+
+ const B = await bare()
+ ok(!carriesHistory(await inviteCopy(B.doc, B.ownerPriv)), 'BARE: invents no history')
+}
+
+H('the class map is the single source')
+{
+ ok(TYPE_FIELDS.revisions === 'history' && TYPE_FIELDS.comments === 'history' &&
+ TYPE_FIELDS.signatures === 'history', 'revisions, comments and signatures are history')
+ ok([...HISTORY_CLASS].sort().join() === 'comments,revisions,signatures',
+ 'the invite opt-out list is DERIVED from the map, not hand-listed')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/type/src/collab.ts b/type/src/collab.ts
index 7e8add94..fc0c7b6d 100644
--- a/type/src/collab.ts
+++ b/type/src/collab.ts
@@ -245,6 +245,66 @@ export function initCollab(store: Store, editor: Editor): void {
wireOnlineStatus();
}
+ /**
+ * The one step before an invite of a document that has version history: say
+ * the copy carries it, and offer to leave it out (default: include). Resolves
+ * true = include, false = leave out, null = cancelled. Built the way about.ts
+ * builds a dialog; the Save button is the user gesture the file picker needs.
+ * Same wording as bento/spaces' invite, so the suite says one thing.
+ */
+ function confirmInviteHistory(): Promise<boolean | null> {
+ return new Promise(resolve => {
+ let answered = false;
+ const back = document.createElement('div');
+ back.className = 't-overlay';
+ const card = document.createElement('div');
+ card.className = 't-dlg';
+ card.setAttribute('role', 'dialog');
+ const title = t('Invite to edit…').replace(/…$/, '');
+ card.setAttribute('aria-label', title);
+ const h = document.createElement('h2');
+ h.className = 't-dlg-h';
+ h.textContent = title;
+ const note = document.createElement('p');
+ note.textContent = t('This copy includes the document’s version history.');
+ const label = document.createElement('label');
+ label.className = 't-row';
+ const cb = document.createElement('input');
+ cb.type = 'checkbox';
+ cb.className = 't-invite-leaveout';
+ label.append(cb, document.createTextNode(' ' + t('Leave version history out')));
+ label.title = t('Versions include text that was deleted. This file keeps them either way.');
+ const foot = document.createElement('div');
+ foot.className = 't-dlg-foot';
+ const close = (v: boolean | null) => {
+ if (answered) return;
+ answered = true;
+ back.remove();
+ document.removeEventListener('keydown', onKey);
+ resolve(v);
+ };
+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') close(null); };
+ const cancel = document.createElement('button');
+ cancel.type = 'button';
+ cancel.className = 't-btn';
+ cancel.textContent = t('Cancel');
+ cancel.addEventListener('click', () => close(null));
+ const go = document.createElement('button');
+ go.type = 'button';
+ go.className = 't-btn t-primary';
+ go.textContent = t('Save invite…');
+ go.addEventListener('click', () => close(!cb.checked));
+ foot.append(cancel, go);
+ card.append(h, note, label, foot);
+ back.append(card);
+ // The scrim and Escape both close without an answer: that is a cancel.
+ back.addEventListener('click', e => { if (e.target === back) close(null); });
+ document.addEventListener('keydown', onKey);
+ document.body.append(back);
+ queueMicrotask(() => go.focus());
+ });
+ }
+
async function inviteToEdit() {
await goLive();
const c = store.doc.collab;
@@ -252,10 +312,22 @@ export function initCollab(store: Store, editor: Editor): void {
toast(t('Only the document owner can mint editor invites'));
return;
}
+ // An invite carries the version history by default (the kernel's invite
+ // tier), and every revision is a WHOLE earlier draft — text that was
+ // deleted. So when there is any, say so and offer to leave it out, before
+ // the file exists. Comments and signatures are in the same class and go with
+ // it, but they also reach an invitee over the live session, so the choice
+ // that matters here is the revisions, and that is what the note names.
+ let withHistory = true;
+ if (store.doc.revisions.length > 0) {
+ const keep = await confirmInviteHistory();
+ if (keep === null) return;
+ withHistory = keep;
+ }
session.stampInto(store.doc);
// Built in share.ts, the one place share copies are minted (and the place
// test-export-secrets and test-type-share inspect).
- const clone = await inviteCopy(store.doc, c.ownerPriv);
+ const clone = await inviteCopy(store.doc, c.ownerPriv, { withHistory });
try {
const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'invite' });
if (ok) toast(t('Editor copy saved — recipients join live with edit access'));
diff --git a/type/src/docclass.ts b/type/src/docclass.ts
new file mode 100644
index 00000000..ed9172f4
--- /dev/null
+++ b/type/src/docclass.ts
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// How each TOP-LEVEL field of a bento/type document is copied — this app's row
+// in the kernel's field classification (kernel/src/docfields.ts).
+//
+// Not to be confused with fields.ts, which is `{{tokens}}` resolved at render.
+// This file is about the document's own keys: which of them a copy handed to
+// someone else may carry.
+//
+// THE MAP IS EXHAUSTIVE, and the compiler holds it to that. `satisfies` over the
+// document's DECLARED keys fails tsc on a key missing here and on one that is
+// not a field, so a new field cannot reach a copy without somebody deciding what
+// it is. A field that arrives undeclared (a newer build's, an agent's) is
+// unclassified, and the kernel drops it from every copy except the file itself
+// and the owner's duplicate.
+//
+// Every copy for someone else is built by `projectForCopy(doc, TYPE_FIELDS,
+// tier)` (share.ts; model.ts docForExport), which starts from an EMPTY object
+// and carries a field only when the kernel's table says so for that tier.
+//
+// NOT bound into the sync shape (sync/crdt.ts TYPE_SHAPE) yet. Binding it
+// changes live sync — `comments` is history-class here, and a bound map stops
+// syncing a history key unless it is named in `syncHistory` — and whether live
+// readers should see comments is awaiting a maintainer ruling. Today, unbound,
+// type syncs by the engine's denylist exactly as before.
+
+import type { FieldClass, FieldsOfClass, ModeFieldsOk } from '../../kernel/src/docfields.ts';
+import type { TypeDoc } from './model.ts';
+
+/** The keys TypeDoc declares — its index signature (`[extra: string]`) removed,
+ * which would otherwise make `keyof` plain `string` and the map exhaustive over
+ * nothing. Same helper as spaces/src/docclass.ts. */
+type DeclaredKeys<T> = keyof {
+ [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K]
+};
+
+export const TYPE_FIELDS = {
+ // identity — re-minted on a duplicate, never on any other copy
+ docId: 'identity',
+ // mode — SET per copy by the kernel's MODE_FIELD_RULES (a reader copy is
+ // readonly, a template copy a template), never simply stripped. In type the
+ // only reader of `readonly` is autosave (a read-only copy has nothing of its
+ // own to recover), so a reader copy now carrying readonly:true stops it
+ // snapshotting content it cannot edit; nothing else changes.
+ readonly: 'mode',
+ template: 'mode',
+ // capability — every field under it is a bearer key; projected through the
+ // kernel's allowlists (collabForReader / collabForInvite), including `sync`
+ collab: 'capability',
+ // history — kept by the file and an invite (unless the inviter leaves it
+ // out); dropped from every reader-tier copy, Copy document JSON and mail merge.
+ // revisions each one is a WHOLE earlier draft: wording that was
+ // negotiated away is exactly what a view-only recipient must
+ // not receive.
+ // comments internal discussion of the text, not the text.
+ // signatures HISTORY, not content, for now. Signatures cover content AND
+ // revisions, and a reader copy drops revisions, so a kept
+ // signature would read "changed" in every reader copy — which
+ // trains a reader to ignore a red ✗ and hides a real tamper
+ // the day one happens. Dropped until canon signs a commitment
+ // to the history rather than the history itself, which a
+ // reader copy could carry and verify; then this becomes content.
+ revisions: 'history',
+ comments: 'history',
+ signatures: 'history',
+ // content — the document itself
+ format: 'content',
+ version: 'content',
+ title: 'content',
+ subtitle: 'content',
+ meta: 'content',
+ page: 'content',
+ body: 'content',
+ footnotes: 'content',
+ layout: 'content',
+ styles: 'content',
+ type: 'content',
+ optical: 'content',
+ track: 'content',
+ merge: 'content',
+ fonts: 'content',
+ assets: 'content',
+ // content, but NOT an edit: excluded from the recovery key (autosave.ts)
+ modified: 'content',
+} satisfies Record<DeclaredKeys<TypeDoc>, FieldClass>;
+
+/** tsc fails here if the fields classed 'mode' stop being exactly the kernel's
+ * two (readonly, template). */
+const _modeOk: ModeFieldsOk<typeof TYPE_FIELDS> = true;
+void _modeOk;
+
+/** The fields classed 'history', READ from the map rather than hand-listed, so
+ * a history field added later is covered by the invite's "Leave version
+ * history out" the day it is declared. */
+export type HistoryField = FieldsOfClass<typeof TYPE_FIELDS, 'history'>;
+export const HISTORY_CLASS: readonly HistoryField[] =
+ (Object.keys(TYPE_FIELDS) as Array<keyof typeof TYPE_FIELDS>)
+ .filter((k): k is HistoryField => TYPE_FIELDS[k] === 'history');
diff --git a/type/src/i18n/de.ts b/type/src/i18n/de.ts
index 5bcaa45e..732b2d91 100644
--- a/type/src/i18n/de.ts
+++ b/type/src/i18n/de.ts
@@ -461,4 +461,8 @@ export const de: Catalog = {
"Drop a Bento document here": "Ein Bento-Dokument hier ablegen",
"Choose a file…": "Datei auswählen…",
"Compare with a file…": "Mit einer Datei vergleichen…",
+ "This copy includes the document’s version history.": "Diese Kopie enthält den Versionsverlauf des Dokuments.",
+ "Leave version history out": "Versionsverlauf weglassen",
+ "Versions include text that was deleted. This file keeps them either way.": "Versionen enthalten auch gelöschten Text. Diese Datei behält sie in jedem Fall.",
+ "Save invite…": "Einladung speichern…",
}
diff --git a/type/src/i18n/es.ts b/type/src/i18n/es.ts
index ac78b807..6131d573 100644
--- a/type/src/i18n/es.ts
+++ b/type/src/i18n/es.ts
@@ -461,4 +461,8 @@ export const es: Catalog = {
"Drop a Bento document here": "Suelta aquí un documento de Bento",
"Choose a file…": "Elegir un archivo…",
"Compare with a file…": "Comparar con un archivo…",
+ "This copy includes the document’s version history.": "Esta copia incluye el historial de versiones del documento.",
+ "Leave version history out": "Dejar fuera el historial de versiones",
+ "Versions include text that was deleted. This file keeps them either way.": "Las versiones incluyen texto que se borró. Este archivo las conserva en cualquier caso.",
+ "Save invite…": "Guardar invitación…",
}
diff --git a/type/src/i18n/fr.ts b/type/src/i18n/fr.ts
index 5bf91789..5060f946 100644
--- a/type/src/i18n/fr.ts
+++ b/type/src/i18n/fr.ts
@@ -461,4 +461,8 @@ export const fr: Catalog = {
"Drop a Bento document here": "Déposez ici un document Bento",
"Choose a file…": "Choisir un fichier…",
"Compare with a file…": "Comparer avec un fichier…",
+ "This copy includes the document’s version history.": "Cette copie inclut l’historique des versions du document.",
+ "Leave version history out": "Ne pas inclure l’historique des versions",
+ "Versions include text that was deleted. This file keeps them either way.": "Les versions contiennent du texte supprimé. Ce fichier les conserve dans tous les cas.",
+ "Save invite…": "Enregistrer l’invitation…",
}
diff --git a/type/src/i18n/it.ts b/type/src/i18n/it.ts
index abeda12d..f6414a4e 100644
--- a/type/src/i18n/it.ts
+++ b/type/src/i18n/it.ts
@@ -461,4 +461,8 @@ export const it: Catalog = {
"Drop a Bento document here": "Trascina qui un documento Bento",
"Choose a file…": "Scegli un file…",
"Compare with a file…": "Confronta con un file…",
+ "This copy includes the document’s version history.": "Questa copia include la cronologia delle versioni del documento.",
+ "Leave version history out": "Escludi la cronologia delle versioni",
+ "Versions include text that was deleted. This file keeps them either way.": "Le versioni includono testo eliminato. Questo file le conserva in ogni caso.",
+ "Save invite…": "Salva l’invito…",
}
diff --git a/type/src/i18n/ja.ts b/type/src/i18n/ja.ts
index f08f7dec..b5818452 100644
--- a/type/src/i18n/ja.ts
+++ b/type/src/i18n/ja.ts
@@ -461,4 +461,8 @@ export const ja: Catalog = {
"Drop a Bento document here": "Bento の文書をここにドロップ",
"Choose a file…": "ファイルを選択…",
"Compare with a file…": "ファイルと比較…",
+ "This copy includes the document’s version history.": "このコピーには、文書のバージョン履歴が含まれます。",
+ "Leave version history out": "バージョン履歴を含めない",
+ "Versions include text that was deleted. This file keeps them either way.": "バージョンには削除された本文も含まれます。このファイルにはどちらの場合も残ります。",
+ "Save invite…": "招待を保存…",
}
diff --git a/type/src/i18n/packed.ts b/type/src/i18n/packed.ts
index 04803b23..048d2688 100644
--- a/type/src/i18n/packed.ts
+++ b/type/src/i18n/packed.ts
@@ -169,6 +169,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Label — “Table 2”": ["ラベル — 「表 2」","标签 —“表 2”","標籤 —「表 2」","Etiqueta: «Tabla 2»","Étiquette : « Tableau 2 »","Beschriftung – „Tabelle 2“","Etichetta: «Tabella 2»","Rótulo — “Tabela 2”"],
"Landscape": ["横向き","横向","橫向","Horizontal","Paysage","Querformat","Orizzontale","Paisagem"],
"Layout": ["レイアウト","布局","版面","Diseño","Mise en page","Layout","Layout","Layout"],
+ "Leave version history out": ["バージョン履歴を含めない","不包含版本历史","不包含版本歷程","Dejar fuera el historial de versiones","Ne pas inclure l’historique des versions","Versionsverlauf weglassen","Escludi la cronologia delle versioni","Deixar de fora o histórico de versões"],
"Left": ["左揃え","左对齐","靠左","Izquierda","Gauche","Links","Sinistra","Esquerda"],
"Left / right (in)": ["左 / 右(インチ)","左 / 右(英寸)","左 / 右(英吋)","Izquierda / derecha (in)","Gauche / droite (po)","Links / rechts (Zoll)","Sinistra / destra (in)","Esquerda / direita (pol)"],
"Left / right (mm)": ["左 / 右(mm)","左 / 右(毫米)","左 / 右(公釐)","Izquierda / derecha (mm)","Gauche / droite (mm)","Links / rechts (mm)","Sinistra / destra (mm)","Esquerda / direita (mm)"],
@@ -291,6 +292,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Right": ["右揃え","右对齐","靠右","Derecha","Droite","Rechts","Destra","Direita"],
"Save": ["保存","保存","儲存","Guardar","Enregistrer","Speichern","Salva","Salvar"],
"Save (⌘S)": ["保存 (⌘S)","保存 (⌘S)","儲存 (⌘S)","Guardar (⌘S)","Enregistrer (⌘S)","Speichern (⌘S)","Salva (⌘S)","Salvar (⌘S)"],
+ "Save invite…": ["招待を保存…","保存邀请…","儲存邀請…","Guardar invitación…","Enregistrer l’invitation…","Einladung speichern…","Salva l’invito…","Salvar convite…"],
"Save to {file}": ["{file} に保存","保存到 {file}","儲存至 {file}","Guardar en {file}","Enregistrer dans {file}","In {file} speichern","Salva su {file}","Salvar em {file}"],
"Saved": ["保存済み","已保存","已儲存","Guardado","Enregistré","Gespeichert","Salvato","Salvo"],
"Saved to {file}": ["{file} に保存しました","已保存到 {file}","已儲存至 {file}","Guardado en {file}","Enregistré dans {file}","In {file} gespeichert","Salvato su {file}","Salvo em {file}"],
@@ -372,6 +374,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": ["このブラウザはファイルへの書き戻しができないため、保存のたびに新しいコピーが作成されます。パソコン版の Chrome や Edge ならその場に保存できます。","此浏览器无法回写到文件,因此每次保存都会生成新副本。电脑版 Chrome 和 Edge 可以直接原地保存。","這個瀏覽器無法回寫至檔案,因此每次儲存都會產生新副本。電腦版 Chrome 和 Edge 可以直接原地儲存。","Este navegador no puede reescribir el archivo, así que cada vez que guardas se crea una copia nueva. Chrome y Edge en un ordenador pueden guardar en el mismo archivo.","Ce navigateur ne peut pas réécrire le fichier, donc chaque enregistrement crée une nouvelle copie. Chrome et Edge sur ordinateur peuvent enregistrer sur place.","Dieser Browser kann die Datei nicht zurückschreiben, daher erstellt jedes Speichern eine neue Kopie. Chrome und Edge auf einem Computer können direkt speichern.","Questo browser non può riscrivere il file, quindi ogni salvataggio crea una nuova copia. Chrome ed Edge su computer possono salvare direttamente nel file.","Este navegador não consegue escrever de volta no arquivo, então cada vez que você salva ele cria uma nova cópia. O Chrome e o Edge em um computador conseguem salvar no lugar."],
"This browser will download each file separately — expect one prompt per row.": ["このブラウザーはファイルを 1 つずつダウンロードします — 行ごとに確認が表示されます。","此浏览器会分别下载每个文件——每一行都会出现一次提示。","此瀏覽器會分別下載每個檔案——每一列都會出現一次提示。","Este navegador descargará cada archivo por separado: habrá un aviso por fila.","Ce navigateur téléchargera chaque fichier séparément — attendez-vous à une invite par ligne.","Dieser Browser lädt jede Datei einzeln herunter – rechnen Sie mit einer Abfrage pro Zeile.","Questo browser scaricherà ogni file separatamente: attendi una richiesta per riga.","Este navegador vai baixar cada arquivo separadamente — espere um aviso por linha."],
"This build cannot render captions yet — apply the core patch listed at the top of xref.ts": ["このビルドではまだキャプションを描画できません — xref.ts の先頭に記載されているコアパッチを適用してください","此构建版本尚不能渲染题注——请应用 xref.ts 顶部列出的核心补丁","此建置版本尚無法渲染題注 — 請套用 xref.ts 頂端列出的核心修補","Esta compilación aún no puede renderizar títulos: aplica el parche del núcleo indicado al principio de xref.ts","Cette version ne peut pas encore afficher les légendes — appliquez le correctif du noyau indiqué en haut de xref.ts","Dieser Build kann Beschriftungen noch nicht rendern – wenden Sie den Kern-Patch oben in xref.ts an","Questa build non può ancora renderizzare le didascalie: applica la patch del core indicata in cima a xref.ts","Esta versão ainda não consegue renderizar legendas — aplique o patch do núcleo listado no topo de xref.ts"],
+ "This copy includes the document’s version history.": ["このコピーには、文書のバージョン履歴が含まれます。","此副本包含文档的版本历史。","此副本包含文件的版本歷程。","Esta copia incluye el historial de versiones del documento.","Cette copie inclut l’historique des versions du document.","Diese Kopie enthält den Versionsverlauf des Dokuments.","Questa copia include la cronologia delle versioni del documento.","Esta cópia inclui o histórico de versões do documento."],
"This document has no live session to follow": ["この文書には追従できるライブセッションがありません","此文档没有可跟随的实时协作","這份文件沒有可跟隨的即時協作","Este documento no tiene ninguna sesión en directo que seguir","Ce document n'a aucune session en direct à suivre","Dieses Dokument hat keine Live-Sitzung, der man folgen könnte","Questo documento non ha una sessione in diretta da seguire","Este documento não tem sessão ao vivo para acompanhar"],
"This document has no sources yet. Import some BibTeX first.": ["この文書にはまだ出典がありません。まず BibTeX をインポートしてください。","本文档尚无来源。请先导入一些 BibTeX。","本文件尚無來源。請先匯入一些 BibTeX。","Este documento aún no tiene fuentes. Importa primero algo de BibTeX.","Ce document n'a pas encore de sources. Importez d'abord du BibTeX.","Dieses Dokument hat noch keine Quellen. Importieren Sie zuerst etwas BibTeX.","Questo documento non ha ancora fonti. Importa prima del BibTeX.","Este documento ainda não tem fontes. Importe algum BibTeX primeiro."],
"This embed could not be displayed safely.": ["この埋め込みは安全に表示できませんでした。","无法安全显示此嵌入内容。","無法安全顯示此嵌入內容。","Este contenido incrustado no se pudo mostrar de forma segura.","Cet élément intégré n'a pas pu être affiché en toute sécurité.","Dieses eingebettete Element konnte nicht sicher angezeigt werden.","Questo elemento incorporato non può essere visualizzato in modo sicuro.","Não foi possível exibir esta incorporação com segurança."],
@@ -415,6 +418,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Version history…": ["バージョン履歴…","版本历史记录…","版本歷程記錄…","Historial de versiones…","Historique des versions…","Versionsverlauf…","Cronologia versioni…","Histórico de versões…"],
"Version {v} is available.": ["バージョン {v} が利用可能です。","有新版本 {v} 可用。","有新版本 {v} 可用。","La versión {v} está disponible.","La version {v} est disponible.","Version {v} ist verfügbar.","La versione {v} è disponibile.","A versão {v} está disponível."],
"Versions are saved automatically as you edit, kept only in this browser, and never uploaded. Restoring is undoable with ⌘Z.": ["バージョンは編集中に自動保存され、このブラウザにのみ保持され、アップロードされることはありません。復元は ⌘Z で元に戻せます。","版本会在你编辑时自动保存,仅保留在此浏览器中,绝不会上传。恢复操作可用 ⌘Z 撤销。","版本會在你編輯時自動儲存,僅保留在這個瀏覽器中,絕不會上傳。還原可用 ⌘Z 復原。","Las versiones se guardan automáticamente mientras editas, se conservan solo en este navegador y nunca se suben. Restaurar se puede deshacer con ⌘Z.","Les versions sont enregistrées automatiquement au fil de vos modifications, conservées uniquement dans ce navigateur et jamais téléversées. La restauration est annulable avec ⌘Z.","Versionen werden beim Bearbeiten automatisch gespeichert, nur in diesem Browser aufbewahrt und nie hochgeladen. Das Wiederherstellen lässt sich mit ⌘Z rückgängig machen.","Le versioni vengono salvate automaticamente mentre modifichi, conservate solo in questo browser e mai caricate online. Il ripristino è annullabile con ⌘Z.","As versões são salvas automaticamente conforme você edita, mantidas apenas neste navegador e nunca enviadas. A restauração pode ser desfeita com ⌘Z."],
+ "Versions include text that was deleted. This file keeps them either way.": ["バージョンには削除された本文も含まれます。このファイルにはどちらの場合も残ります。","版本中包含已删除的文字。无论如何,此文件都会保留它们。","版本中包含已刪除的文字。無論如何,此檔案都會保留它們。","Las versiones incluyen texto que se borró. Este archivo las conserva en cualquier caso.","Les versions contiennent du texte supprimé. Ce fichier les conserve dans tous les cas.","Versionen enthalten auch gelöschten Text. Diese Datei behält sie in jedem Fall.","Le versioni includono testo eliminato. Questo file le conserva in ogni caso.","As versões incluem texto que foi apagado. Este arquivo as mantém de qualquer forma."],
"View-only copy saved — it follows the live session": ["閲覧専用のコピーを保存しました — ライブセッションに追従します","已保存只读副本 — 它会跟随实时协作","已儲存唯讀副本 — 它會跟隨即時協作","Copia de solo lectura guardada: sigue la sesión en directo","Copie en lecture seule enregistrée — elle suit la session en direct","Schreibgeschützte Kopie gespeichert – sie folgt der Live-Sitzung","Copia di sola lettura salvata: segue la sessione in diretta","Cópia somente leitura salva — ela acompanha a sessão ao vivo"],
"View-only copy…": ["閲覧専用のコピー…","只读副本…","唯讀副本…","Copia de solo lectura…","Copie en lecture seule…","Schreibgeschützte Kopie …","Copia di sola lettura…","Cópia somente para visualização…"],
"Viewer": ["閲覧者","查看者","檢視者","Lector","Lecteur","Betrachter","Lettore","Visualizador"],
diff --git a/type/src/i18n/pt.ts b/type/src/i18n/pt.ts
index 40d5a271..e428e283 100644
--- a/type/src/i18n/pt.ts
+++ b/type/src/i18n/pt.ts
@@ -472,4 +472,8 @@ export const pt: Catalog = {
"Drop a Bento document here": "Solte um documento Bento aqui",
"Choose a file…": "Escolher um arquivo…",
"Compare with a file…": "Comparar com um arquivo…",
+ "This copy includes the document’s version history.": "Esta cópia inclui o histórico de versões do documento.",
+ "Leave version history out": "Deixar de fora o histórico de versões",
+ "Versions include text that was deleted. This file keeps them either way.": "As versões incluem texto que foi apagado. Este arquivo as mantém de qualquer forma.",
+ "Save invite…": "Salvar convite…",
}
diff --git a/type/src/i18n/zh-Hans.ts b/type/src/i18n/zh-Hans.ts
index 1dea9576..95340f0e 100644
--- a/type/src/i18n/zh-Hans.ts
+++ b/type/src/i18n/zh-Hans.ts
@@ -461,4 +461,8 @@ export const zhHans: Catalog = {
"Drop a Bento document here": "将 Bento 文档拖放到此处",
"Choose a file…": "选择文件…",
"Compare with a file…": "与文件比较…",
+ "This copy includes the document’s version history.": "此副本包含文档的版本历史。",
+ "Leave version history out": "不包含版本历史",
+ "Versions include text that was deleted. This file keeps them either way.": "版本中包含已删除的文字。无论如何,此文件都会保留它们。",
+ "Save invite…": "保存邀请…",
}
diff --git a/type/src/i18n/zh-Hant.ts b/type/src/i18n/zh-Hant.ts
index dc90a854..bf0a8e62 100644
--- a/type/src/i18n/zh-Hant.ts
+++ b/type/src/i18n/zh-Hant.ts
@@ -461,4 +461,8 @@ export const zhHant: Catalog = {
"Drop a Bento document here": "將 Bento 文件拖放到此處",
"Choose a file…": "選擇檔案…",
"Compare with a file…": "與檔案比較…",
+ "This copy includes the document’s version history.": "此副本包含文件的版本歷程。",
+ "Leave version history out": "不包含版本歷程",
+ "Versions include text that was deleted. This file keeps them either way.": "版本中包含已刪除的文字。無論如何,此檔案都會保留它們。",
+ "Save invite…": "儲存邀請…",
}
diff --git a/type/src/merge.ts b/type/src/merge.ts
index d326311b..63dfe7bd 100644
--- a/type/src/merge.ts
+++ b/type/src/merge.ts
@@ -288,6 +288,14 @@ export function sourceOfDoc(parsed: unknown): MergeSource | null {
export function mergeDoc(template: TypeDoc, row: Record<string, string>,
columns: string[], source: string): TypeDoc {
const out = JSON.parse(JSON.stringify(docForExport(template))) as TypeDoc;
+ // TIER GAP. A merged letter is a file for someone else with a FRESH identity,
+ // no capability and no history, and the kernel's copy table has no tier that
+ // says exactly that: 'duplicate' resets identity but KEEPS history, 'copyJSON'
+ // drops history but keeps docId. So this projects at 'copyJSON' (via
+ // docForExport) and then mints the identity here — the one post-projection
+ // identity edit projectForCopy's contract otherwise forbids. A 'merge' tier
+ // (content only; fresh identity; no capability; no history; modes dropped)
+ // would remove it; raised with kernel.
out.docId = newDocId();
out.signatures = [];
out.revisions = [];
diff --git a/type/src/model.ts b/type/src/model.ts
index 2d961f29..1b8386e5 100644
--- a/type/src/model.ts
+++ b/type/src/model.ts
@@ -12,7 +12,8 @@
// the container.
import { normalize, shift as shiftMarks, type Mark } from './inline.ts';
-import { withoutCaps } from '../../kernel/src/docfields.ts';
+import { withoutCaps, projectForCopy } from '../../kernel/src/docfields.ts';
+import { TYPE_FIELDS } from './docclass.ts';
// value import is safe: xref.ts imports only TYPES from this module, precisely
// so the core can call into it without a cycle
import { shiftRefs } from './xref.ts';
@@ -449,13 +450,20 @@ export function copyIsReceiveOnly(collab: TypeDoc['collab'] | undefined): boolea
* document JSON" into a chat hands over write access to a live room, which is
* not revocable by deleting the message.
*
- * It strips by REMOVING the field rather than by listing the fields to keep,
- * deliberately: a private field added to CollabCreds later is then covered
- * without anyone remembering to update this. scripts/test-export-secrets.ts
- * asserts that shape across every app that has a clipboard export.
+ * Built FROM EMPTY by the kernel's copy table at tier 'copyJSON'
+ * (`projectForCopy`, with docclass.ts's TYPE_FIELDS): the whole capability
+ * block goes, and so does history — every revision (a WHOLE earlier draft),
+ * comment and signature. Text that leaves the app is a copy for someone else,
+ * whoever pastes it. A key this build does not declare is dropped too, so a
+ * field added later fails closed rather than riding out on the clipboard.
+ * scripts/test-export-secrets.ts asserts the credential half across every app
+ * with a clipboard export; scripts/test-type-share.ts asserts the rest.
+ *
+ * Mail merge (merge.ts) builds every per-recipient file from this, then mints a
+ * fresh docId per output — see the tier-gap note there.
*/
export function docForExport(doc: TypeDoc): TypeDoc {
- return withoutEmbeddedCaps(withoutCaps(doc));
+ return projectForCopy(withoutEmbeddedCaps(withoutCaps(doc)), TYPE_FIELDS, 'copyJSON');
}
/**
diff --git a/type/src/share.ts b/type/src/share.ts
index e425bb42..b043c09b 100644
--- a/type/src/share.ts
+++ b/type/src/share.ts
@@ -16,14 +16,18 @@
// a copy keeps only what is on the list, so an arrived-with field it does not
// know is dropped, not carried.
//
-// The private fields a copy must not carry are now the kernel's shared ALLOWLIST
-// (kernel/src/docfields.ts): a reader/invite copy keeps only what is on the list,
-// so a new field in `collab` — private or not — fails CLOSED instead of riding
-// along. The whole-block default drop lives in docForExport.
+// Every copy is now built FROM EMPTY by the kernel's copy table
+// (`projectForCopy`, kernel/src/docfields.ts) using type's field-class map
+// (docclass.ts). A field reaches a copy only when its class's cell for that tier
+// says so: the private halves of `collab` go through the kernel's allowlists,
+// and history — every revision (a WHOLE earlier draft), every comment, every
+// signature — stays out of a view-only copy. The copies used to be a deep clone
+// with only `collab` rewritten, so they carried all of it.
import { mintInvite } from './sync/online.ts';
-import { collabForReader, collabForInvite } from '../../kernel/src/docfields.ts';
+import { projectForCopy } from '../../kernel/src/docfields.ts';
import { withoutEmbeddedCaps, type TypeDoc } from './model.ts';
+import { TYPE_FIELDS, HISTORY_CLASS } from './docclass.ts';
// Every share copy starts here, so every one is embed-safe: an embedded
// document never carries its own sharing keys out of this file, however it got
@@ -37,10 +41,28 @@ const clone = (doc: TypeDoc): TypeDoc => withoutEmbeddedCaps(JSON.parse(JSON.str
* role come from mintInvite, never from the source — so a legacy writer key or a
* source invite can never ride along.
*/
-export async function inviteCopy(doc: TypeDoc, ownerPriv: string): Promise<TypeDoc> {
- const out = clone(doc);
+export interface InviteOpts {
+ /**
+ * Keep the history class in the copy — the kernel's invite rule, and the
+ * default. `false` is the inviter's "Leave version history out": the copy is
+ * the invite tier exactly, minus every field classed 'history'. History
+ * remembers text that was deleted, and an invite is a file for someone else.
+ */
+ withHistory?: boolean;
+}
+
+export async function inviteCopy(doc: TypeDoc, ownerPriv: string, opts: InviteOpts = {}): Promise<TypeDoc> {
const invite = await mintInvite(ownerPriv, 'writer');
- out.collab = { ...collabForInvite(out.collab!, invite), on: true } as TypeDoc['collab'];
+ // Tier 'invite': collab through collabForInvite (room, read key, public keys,
+ // sync, the FRESH invite — never a private half), the modes dropped (a
+ // template:true copy would open as a roomless new document), history kept,
+ // and any key this build does not declare left behind.
+ const out = projectForCopy(clone(doc), TYPE_FIELDS, 'invite', { invite });
+ if (out.collab) out.collab.on = true;
+ // The inviter chose to leave history out: drop it by CLASS, never by name.
+ if (opts.withHistory === false) {
+ for (const k of HISTORY_CLASS) delete (out as unknown as Record<string, unknown>)[k];
+ }
return out;
}
@@ -51,7 +73,9 @@ export async function inviteCopy(doc: TypeDoc, ownerPriv: string): Promise<TypeD
* tries to send.
*/
export function readerCopy(doc: TypeDoc): TypeDoc {
- const out = clone(doc);
- out.collab = { ...collabForReader(out.collab!), on: true } as TypeDoc['collab'];
+ // Tier 'reader': collab through collabForReader, readonly SET true, and every
+ // history field — revisions, comments, signatures — dropped.
+ const out = projectForCopy(clone(doc), TYPE_FIELDS, 'reader');
+ if (out.collab) out.collab.on = true;
return out;
}