@tano.page/protocol 0.0.0-stage → 0.8.1

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.
@@ -0,0 +1,111 @@
1
+ import { parseObject, type WorkspaceObject } from './objects';
2
+ import { parseDataTable, type DataTable } from './data-tables';
3
+
4
+ const canonical = (value: unknown): string => {
5
+ if (value === undefined) return 'undefined';
6
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
7
+ if (value && typeof value === 'object')
8
+ return `{${Object.keys(value)
9
+ .sort()
10
+ .map((key) => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`)
11
+ .join(',')}}`;
12
+ return JSON.stringify(value);
13
+ };
14
+ const same = (a: unknown, b: unknown) => canonical(a) === canonical(b);
15
+ const object = (value: unknown): value is Record<string, unknown> =>
16
+ !!value && typeof value === 'object' && !Array.isArray(value);
17
+ const identified = (value: unknown): value is { id: string }[] =>
18
+ Array.isArray(value) && value.every((item) => object(item) && typeof item.id === 'string');
19
+ /** Three-way merge by row/field/view identity and cell key, with deletion/edit conflicts. */
20
+ function mergeValue(base: unknown, ours: unknown, theirs: unknown): unknown {
21
+ if (same(base, ours) || same(ours, theirs)) return theirs;
22
+ if (same(base, theirs)) return ours;
23
+ if (object(base) && object(ours) && object(theirs)) {
24
+ const merged = Object.create(null) as Record<string, unknown>;
25
+ for (const key of new Set([
26
+ ...Object.keys(base),
27
+ ...Object.keys(ours),
28
+ ...Object.keys(theirs),
29
+ ])) {
30
+ const value = mergeValue(base[key], ours[key], theirs[key]);
31
+ if (value !== undefined) merged[key] = value;
32
+ }
33
+ return merged;
34
+ }
35
+ if (identified(base) && identified(ours) && identified(theirs)) {
36
+ const b = new Map(base.map((item) => [item.id, item])),
37
+ o = new Map(ours.map((item) => [item.id, item])),
38
+ t = new Map(theirs.map((item) => [item.id, item]));
39
+ const ids = [...new Set([...theirs, ...ours, ...base].map((item) => item.id))];
40
+ const values = new Map(ids.map((id) => [id, mergeValue(b.get(id), o.get(id), t.get(id))]));
41
+ const survivors = new Set(
42
+ base.filter((item) => o.has(item.id) && t.has(item.id)).map((item) => item.id),
43
+ );
44
+ const order = (items: { id: string }[]) =>
45
+ items.map((item) => item.id).filter((id) => survivors.has(id));
46
+ const bo = order(base),
47
+ oo = order(ours),
48
+ to = order(theirs);
49
+ if (!same(bo, oo) && !same(bo, to) && !same(oo, to)) throw new Error('顺序冲突');
50
+ const preferred = !same(bo, oo) ? ours : theirs;
51
+ const orderedIds = [...new Set([...preferred.map((item) => item.id), ...ids])];
52
+ return orderedIds.map((id) => values.get(id)).filter((item) => item !== undefined);
53
+ }
54
+ throw new Error('字段冲突');
55
+ }
56
+ export function mergeDataTable(
57
+ base: DataTable,
58
+ ours: DataTable,
59
+ theirs: DataTable,
60
+ ): DataTable | null {
61
+ if (base.id !== ours.id || base.id !== theirs.id) return null;
62
+ try {
63
+ return parseDataTable(JSON.stringify(mergeValue(base, ours, theirs)), base.id);
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ /** Merge independently edited fields. Identity/type are immutable, never inferred from a title. */
70
+ export function mergeWorkspaceObject(
71
+ base: WorkspaceObject,
72
+ ours: WorkspaceObject,
73
+ theirs: WorkspaceObject,
74
+ mergeDescription: (base: string, ours: string, theirs: string) => string | null = (b, o, t) => same(b, o) || same(o, t) ? t : same(b, t) ? o : null,
75
+ ): WorkspaceObject | null {
76
+ if (
77
+ base.id !== ours.id ||
78
+ base.id !== theirs.id ||
79
+ base.type !== ours.type ||
80
+ base.type !== theirs.type
81
+ )
82
+ return null;
83
+ const merged = { ...theirs };
84
+ for (const key of ['name', 'description', 'archived', 'properties'] as const) {
85
+ if (key === 'properties') {
86
+ const result: Record<string, unknown> = Object.assign(Object.create(null), theirs.properties);
87
+ for (const field of new Set([
88
+ ...Object.keys(base.properties),
89
+ ...Object.keys(ours.properties),
90
+ ])) {
91
+ if (same(base.properties[field], ours.properties[field])) continue;
92
+ if (
93
+ !same(base.properties[field], theirs.properties[field]) &&
94
+ !same(ours.properties[field], theirs.properties[field])
95
+ )
96
+ return null;
97
+ if (Object.hasOwn(ours.properties, field)) result[field] = ours.properties[field];
98
+ else delete result[field];
99
+ }
100
+ merged.properties = result;
101
+ } else if (key === 'description') {
102
+ const description = mergeDescription(base.description, ours.description, theirs.description);
103
+ if (description === null) return null;
104
+ merged.description = description;
105
+ } else if (!same(base[key], ours[key])) {
106
+ if (!same(base[key], theirs[key]) && !same(ours[key], theirs[key])) return null;
107
+ Object.assign(merged, { [key]: ours[key] });
108
+ }
109
+ }
110
+ return parseObject(JSON.stringify(merged));
111
+ }
@@ -0,0 +1,86 @@
1
+ import { parseCommentFile } from './comments';
2
+ import type { CommentMessage, CommentThread } from './comments';
3
+
4
+ /** Portable review records. Pending text never replaces the Markdown source. */
5
+ export interface DocumentSuggestion {
6
+ id: string;
7
+ revision: number;
8
+ authorId: string;
9
+ authorName: string;
10
+ createdAt: number;
11
+ updatedAt: number;
12
+ base: string;
13
+ from: number;
14
+ to: number;
15
+ text: string;
16
+ reason?: string;
17
+ groupId?: string;
18
+ status: 'pending' | 'applying' | 'accepted' | 'rejected';
19
+ replies?: CommentMessage[];
20
+ /** Durable write intent: recovery must never blindly replay an uncertain write. */
21
+ application?: { operationId: string; before: string; after: string; diskHash: string; resultHash?: string };
22
+ }
23
+
24
+ export function suggestionReviewThread(item: DocumentSuggestion): CommentThread {
25
+ return {
26
+ id: item.id, createdAt: item.createdAt, resolved: false, detached: false,
27
+ messages: [{ id: item.id, authorId: item.authorId, authorName: item.authorName,
28
+ createdAt: item.createdAt, body: item.reason || '编辑建议' }, ...(item.replies ?? [])],
29
+ };
30
+ }
31
+
32
+ export interface SuggestionFile {
33
+ version: 1;
34
+ workspaceId: string;
35
+ fileId: string;
36
+ suggestions: DocumentSuggestion[];
37
+ }
38
+
39
+ /** Transient positions in either the source editor or the rich-text projection. */
40
+ export interface SuggestionDecorations {
41
+ text: string;
42
+ ranges: { id: string; from: number; to: number; removed: string; inserted?: string }[];
43
+ }
44
+
45
+ export function suggestionDataPath(fileId: string) {
46
+ if (!/^[0-9a-f]{6}$/.test(fileId)) throw new Error('文档身份无效');
47
+ return `.tano/suggestions/${fileId}.tano.json`;
48
+ }
49
+
50
+ export function parseSuggestionFile(content: string, workspaceId: string, fileId: string): SuggestionFile {
51
+ const file = JSON.parse(content) as SuggestionFile;
52
+ if (!file || file.version !== 1 || file.workspaceId !== workspaceId || file.fileId !== fileId ||
53
+ !Array.isArray(file.suggestions) || file.suggestions.length > 4000)
54
+ throw new Error('建议文件身份或格式无效,原文件已保留');
55
+ const ids = new Set<string>();
56
+ const text = (value: unknown, max: number): value is string => typeof value === 'string' && value.length <= max;
57
+ for (const item of file.suggestions) {
58
+ if (!item || !text(item.id, 80) || !/^[a-z0-9-]{8,80}$/i.test(item.id) || ids.has(item.id) ||
59
+ !Number.isSafeInteger(item.revision) || item.revision < 1 ||
60
+ !text(item.authorId, 120) || !text(item.authorName, 120) ||
61
+ !Number.isFinite(item.createdAt) || !Number.isFinite(item.updatedAt) ||
62
+ !text(item.base, 2_000_000) || !text(item.text, 2_000_000) ||
63
+ !Number.isSafeInteger(item.from) || !Number.isSafeInteger(item.to) ||
64
+ item.from < 0 || item.to < item.from || item.to > item.base.length ||
65
+ !['pending', 'applying', 'accepted', 'rejected'].includes(item.status) ||
66
+ (item.reason !== undefined && !text(item.reason, 4000)) ||
67
+ (item.groupId !== undefined && !text(item.groupId, 80)))
68
+ throw new Error('建议记录格式无效,原文件已保留');
69
+ if (item.application) {
70
+ const application = item.application;
71
+ if (!text(application.operationId, 80) || !text(application.before, 2_000_000) ||
72
+ !text(application.after, 2_000_000) || !text(application.diskHash, 128) ||
73
+ (application.resultHash !== undefined && !text(application.resultHash, 128)))
74
+ throw new Error('建议写入回执无效');
75
+ }
76
+ if ((item.status === 'applying' || item.status === 'accepted') && !item.application)
77
+ throw new Error('建议缺少写入凭据');
78
+ if (item.replies !== undefined) {
79
+ if (!Array.isArray(item.replies)) throw new Error('建议回复格式无效');
80
+ parseCommentFile(JSON.stringify({ version: 1, kind: 'discussion', fileId,
81
+ threads: [suggestionReviewThread(item)] }), 'discussion', fileId);
82
+ }
83
+ ids.add(item.id);
84
+ }
85
+ return file;
86
+ }
@@ -0,0 +1,21 @@
1
+ import { validEventDate } from './object-types';
2
+ import { isShortId } from './short-id';
3
+ export interface TaskRepeat { version: 1; frequency: 'daily' | 'weekly' | 'monthly'; interval: number; anchor: string; until?: string }
4
+ export function parseTaskRepeat(value: unknown): TaskRepeat {
5
+ const rule = value as TaskRepeat;
6
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule) || rule.version !== 1 ||
7
+ !['daily', 'weekly', 'monthly'].includes(rule.frequency) || !Number.isInteger(rule.interval) || rule.interval < 1 || rule.interval > 99 ||
8
+ !validEventDate(rule.anchor) || (rule.until !== undefined && (!validEventDate(rule.until) || rule.until < rule.anchor)) ||
9
+ Object.keys(rule).some(key => !['version', 'frequency', 'interval', 'anchor', 'until'].includes(key))) throw new Error('重复任务规则无效');
10
+ return rule;
11
+ }
12
+ export function validateTaskRepeat(type: string, properties: Record<string, unknown>) {
13
+ if (properties.repeat !== undefined) {
14
+ if (!(type === 'task' || type === 'event' && properties.checkable === true)) throw new Error('只有任务可以设置重复规则');
15
+ parseTaskRepeat(properties.repeat);
16
+ }
17
+ if (properties.repeatSourceId !== undefined || properties.repeatOccurrence !== undefined) {
18
+ if (!isShortId(properties.repeatSourceId) || !validEventDate(properties.repeatOccurrence) || properties.repeat === undefined)
19
+ throw new Error('重复任务实例身份无效');
20
+ }
21
+ }
@@ -0,0 +1,49 @@
1
+ import type { WorkspaceObject } from './objects';
2
+ import { isShortId } from './short-id';
3
+ import { validEventTime } from './object-types';
4
+
5
+ export interface TaskReview {
6
+ version: 1;
7
+ id: string;
8
+ documentId: string;
9
+ documentHash: string;
10
+ criteriaHash: string;
11
+ reviewerId: string;
12
+ submitterId: string;
13
+ state: 'pending' | 'approved' | 'changes-requested';
14
+ submittedAt: string;
15
+ decidedAt?: string;
16
+ comment?: string;
17
+ }
18
+ export function parseTaskReview(value: unknown): TaskReview {
19
+ const review = value as TaskReview;
20
+ if (!review || typeof review !== 'object' || Array.isArray(review) || review.version !== 1 ||
21
+ typeof review.id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(review.id) ||
22
+ !isShortId(review.documentId) || !isShortId(review.reviewerId) || !isShortId(review.submitterId) ||
23
+ typeof review.documentHash !== 'string' || !/^[0-9a-f]{64}$/.test(review.documentHash) ||
24
+ typeof review.criteriaHash !== 'string' || !/^[0-9a-f]{64}$/.test(review.criteriaHash) ||
25
+ !['pending', 'approved', 'changes-requested'].includes(review.state) || !validEventTime(review.submittedAt) ||
26
+ (review.decidedAt !== undefined && !validEventTime(review.decidedAt)) ||
27
+ (review.comment !== undefined && (typeof review.comment !== 'string' || review.comment.length > 4000)) ||
28
+ (review.state === 'pending' && (review.decidedAt !== undefined || review.comment !== undefined)) ||
29
+ (review.state !== 'pending' && (!review.decidedAt || Date.parse(review.decidedAt) < Date.parse(review.submittedAt))) ||
30
+ (review.state === 'changes-requested' && !review.comment?.trim()) ||
31
+ Object.keys(review).some(key => !['version', 'id', 'documentId', 'documentHash', 'criteriaHash', 'reviewerId', 'submitterId', 'state', 'submittedAt', 'decidedAt', 'comment'].includes(key)))
32
+ throw new Error('交付审阅记录无效');
33
+ return review;
34
+ }
35
+ export function taskReview(object: Pick<WorkspaceObject, 'properties'>): TaskReview | null {
36
+ return object.properties.deliveryReview === undefined ? null : parseTaskReview(object.properties.deliveryReview);
37
+ }
38
+ export function submitTaskReview(object: WorkspaceObject, input: Omit<TaskReview, 'version' | 'state' | 'decidedAt' | 'comment'>): WorkspaceObject {
39
+ const review = parseTaskReview({ ...input, version: 1, state: 'pending' });
40
+ return { ...object, properties: { ...object.properties, completed: false,
41
+ ...(object.type === 'task' ? { status: 'todo' } : {}), deliveryReview: review } };
42
+ }
43
+ export function decideTaskReview(object: WorkspaceObject, decision: 'approved' | 'changes-requested', comment: string, now = new Date().toISOString()): WorkspaceObject {
44
+ const previous = taskReview(object);
45
+ if (!previous || previous.state !== 'pending') throw new Error('此交付没有待处理的审阅请求');
46
+ const review = parseTaskReview({ ...previous, state: decision, decidedAt: now, ...(comment.trim() ? { comment: comment.trim() } : {}) });
47
+ return { ...object, properties: { ...object.properties, completed: decision === 'approved',
48
+ ...(object.type === 'task' ? { status: decision === 'approved' ? 'done' : 'todo' } : {}), deliveryReview: review } };
49
+ }
@@ -0,0 +1,69 @@
1
+ import type { WorkspaceObject, WorkspaceRelation, ReferenceIdentity } from './index';
2
+ import { validObjectType } from './object-types';
3
+ import { referenceKey } from './relations';
4
+
5
+ export type ObjectViewLayout = 'table' | 'board' | 'gallery';
6
+ export interface ObjectViewQuery {
7
+ layout: ObjectViewLayout;
8
+ types: string[];
9
+ includeArchived: boolean;
10
+ filters: { field: string; operator: 'contains' | 'equals' | 'empty'; value: string }[];
11
+ sort: { field: string; direction: 'asc' | 'desc' };
12
+ groupBy: string;
13
+ /** Optional relationship query. The endpoint remains an ID, never a copied record. */
14
+ relatedTo?: ReferenceIdentity;
15
+ }
16
+ export const defaultObjectViewQuery = (): ObjectViewQuery => ({ layout: 'table', types: ['task', 'project', 'experiment'], includeArchived: false,
17
+ filters: [], sort: { field: 'name', direction: 'asc' }, groupBy: 'property:status' });
18
+ export function validateObjectViewQuery(query: ObjectViewQuery) {
19
+ const field = (value: unknown) => typeof value === 'string' && /^(name|type|description|archived|property:[\s\S]{1,100})$/.test(value);
20
+ if (!query || !['table', 'board', 'gallery'].includes(query.layout) || !Array.isArray(query.types) || query.types.length > 100 ||
21
+ query.types.some(type => !validObjectType(type)) || new Set(query.types).size !== query.types.length ||
22
+ typeof query.includeArchived !== 'boolean' || !Array.isArray(query.filters) || query.filters.length > 20 ||
23
+ query.filters.some(filter => !filter || !field(filter.field) || !['contains', 'equals', 'empty'].includes(filter.operator) || typeof filter.value !== 'string' || filter.value.length > 2000) ||
24
+ !query.sort || !field(query.sort.field) || !['asc', 'desc'].includes(query.sort.direction) || !field(query.groupBy) ||
25
+ (query.relatedTo !== undefined && (!query.relatedTo || !validObjectType(query.relatedTo.type) || !/^[0-9a-f]{6}$/.test(query.relatedTo.id))))
26
+ throw new Error('对象视图查询格式无效');
27
+ return query;
28
+ }
29
+ export function objectViewValue(object: WorkspaceObject, field: string): unknown {
30
+ return field.startsWith('property:') ? (Object.hasOwn(object.properties, field.slice(9)) ? object.properties[field.slice(9)] : undefined) : object[field];
31
+ }
32
+ export const objectViewText = (value: unknown): string => value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value);
33
+ /** All layouts consume this single projection. Rows are the original records, not copies. */
34
+ export class ViewEngine {
35
+ query(objects: readonly WorkspaceObject[], query: ObjectViewQuery, relations: readonly WorkspaceRelation[] = []) {
36
+ validateObjectViewQuery(query);
37
+ const text = (value: unknown) => objectViewText(value).toLocaleLowerCase();
38
+ const linked = new Set<string>();
39
+ if (query.relatedTo) {
40
+ const key = referenceKey(query.relatedTo);
41
+ for (const edge of relations) {
42
+ if (referenceKey(edge.source) === key) linked.add(referenceKey(edge.target));
43
+ if (referenceKey(edge.target) === key) linked.add(referenceKey(edge.source));
44
+ }
45
+ }
46
+ const seen = new Set<string>();
47
+ const rows = objects.filter(object => {
48
+ const key = referenceKey(object);
49
+ if (seen.has(key)) throw new Error('对象身份重复,无法建立视图');
50
+ seen.add(key);
51
+ return (query.includeArchived || !object.archived) && (!query.types.length || query.types.includes(object.type)) &&
52
+ (!query.relatedTo || linked.has(key)) && query.filters.every(filter => {
53
+ const value = text(objectViewValue(object, filter.field));
54
+ return filter.operator === 'empty' ? !value : filter.operator === 'equals' ? value === text(filter.value) : value.includes(text(filter.value));
55
+ });
56
+ }).sort((a, b) => {
57
+ const av = objectViewValue(a, query.sort.field), bv = objectViewValue(b, query.sort.field);
58
+ const order = typeof av === 'number' && typeof bv === 'number' ? av - bv : text(av).localeCompare(text(bv), 'zh-CN', { numeric: true });
59
+ return (query.sort.direction === 'desc' ? -order : order) || referenceKey(a).localeCompare(referenceKey(b));
60
+ });
61
+ const groups = new Map<string, WorkspaceObject[]>();
62
+ for (const row of rows) {
63
+ const key = objectViewText(objectViewValue(row, query.groupBy));
64
+ const group = groups.get(key); if (group) group.push(row); else groups.set(key, [row]);
65
+ }
66
+ return { rows, groups: [...groups].map(([name, rows]) => ({ name, rows })) };
67
+ }
68
+ }
69
+ export const viewEngine = new ViewEngine();
@@ -0,0 +1,162 @@
1
+ import type { FileEntry } from './index';
2
+ import type { ReferenceIdentity } from './objects';
3
+ import { isShortId } from './short-id';
4
+ import { validObjectType } from './object-types';
5
+ import { workspaceViewDirectory } from './workspace-paths';
6
+ import { validateFileDatabaseQuery, type FileDatabaseQuery } from './file-database';
7
+ import { validateObjectViewQuery, type ObjectViewQuery } from './view-engine';
8
+
9
+ /**
10
+ * Portable contract shared by the local workspace and future cloud adapters.
11
+ *
12
+ * File bytes remain authoritative. Objects add stable semantics and relations;
13
+ * views only project the two sources and never own content.
14
+ */
15
+ export const workspaceContractVersion = 1 as const;
16
+ export type WorkspaceLayer = 'file' | 'object' | 'view';
17
+ export type WorkspaceViewKind = 'files' | 'objects' | 'table' | 'graph';
18
+
19
+ export interface WorkspaceRevision {
20
+ /** Content revision, normally the adapter's SHA-256 hash. */
21
+ hash: string;
22
+ modified?: number;
23
+ }
24
+
25
+ export interface WorkspaceFileRef {
26
+ version: typeof workspaceContractVersion;
27
+ layer: 'file';
28
+ workspaceId: string;
29
+ fileId: string;
30
+ path: string;
31
+ revision: WorkspaceRevision;
32
+ }
33
+
34
+ export interface WorkspaceObjectRef {
35
+ version: typeof workspaceContractVersion;
36
+ layer: 'object';
37
+ workspaceId: string;
38
+ type: string;
39
+ id: string;
40
+ path: string;
41
+ revision: WorkspaceRevision;
42
+ }
43
+
44
+ export type WorkspaceViewSource =
45
+ | { layer: 'file'; fileId: string }
46
+ | { layer: 'object'; type: string; id: string };
47
+
48
+ export interface WorkspaceViewDefinition {
49
+ version: typeof workspaceContractVersion;
50
+ layer: 'view';
51
+ workspaceId: string;
52
+ id: string;
53
+ name: string;
54
+ kind: WorkspaceViewKind;
55
+ /** Static sources. Dynamic database rows resolve stable IDs from the scoped File Registry. */
56
+ sources: WorkspaceViewSource[];
57
+ /** A display/query hint. It is never executable code. */
58
+ query?: string;
59
+ /** Dynamic directory projection; source files are never imported or copied. */
60
+ database?: FileDatabaseQuery;
61
+ objectDatabase?: ObjectViewQuery;
62
+ }
63
+
64
+ const viewId = (value: unknown): value is string =>
65
+ typeof value === 'string' && /^[a-zA-Z0-9_-]{1,64}$/.test(value);
66
+
67
+ export const workspaceViewPath = (id: string) => {
68
+ if (!viewId(id)) throw new Error('视图身份无效');
69
+ return `${workspaceViewDirectory}/${id}.tano.json`;
70
+ };
71
+
72
+ export const fileIdentity = (workspaceId: string, fileId: string) => {
73
+ if (!workspaceId || !isShortId(fileId)) throw new Error('文件身份无效');
74
+ return `file://${workspaceId}/${fileId}`;
75
+ };
76
+
77
+ export const objectIdentity = (workspaceId: string, type: string, id: string) => {
78
+ if (!workspaceId || !validObjectType(type) || !isShortId(id)) throw new Error('对象身份无效');
79
+ return `object://${workspaceId}/${type}/${id}`;
80
+ };
81
+
82
+ export const viewIdentity = (workspaceId: string, id: string) => {
83
+ if (!workspaceId || !viewId(id)) throw new Error('视图身份无效');
84
+ return `view://${workspaceId}/${id}`;
85
+ };
86
+
87
+ export function fileRef(workspaceId: string, file: FileEntry, hash: string): WorkspaceFileRef {
88
+ if (file.kind !== 'file' || !isShortId(file.id) || !file.path || !hash)
89
+ throw new Error('文件来源无效');
90
+ return {
91
+ version: workspaceContractVersion,
92
+ layer: 'file',
93
+ workspaceId,
94
+ fileId: file.id,
95
+ path: file.path,
96
+ revision: { hash, modified: file.modified },
97
+ };
98
+ }
99
+
100
+ export function parseWorkspaceView(content: string): WorkspaceViewDefinition {
101
+ const value = JSON.parse(content) as WorkspaceViewDefinition;
102
+ if (
103
+ !value ||
104
+ typeof value !== 'object' ||
105
+ value.version !== workspaceContractVersion ||
106
+ value.layer !== 'view' ||
107
+ typeof value.workspaceId !== 'string' ||
108
+ !value.workspaceId.trim() ||
109
+ !viewId(value.id) ||
110
+ typeof value.name !== 'string' ||
111
+ !value.name.trim() ||
112
+ value.name.length > 200 ||
113
+ !['files', 'objects', 'table', 'graph'].includes(value.kind) ||
114
+ !Array.isArray(value.sources) ||
115
+ value.sources.length > 500 ||
116
+ (value.query !== undefined && (typeof value.query !== 'string' || value.query.length > 2000))
117
+ )
118
+ throw new Error('工作区视图格式无效');
119
+ const seen = new Set<string>();
120
+ for (const source of value.sources) {
121
+ if (!source || typeof source !== 'object') throw new Error('工作区视图来源无效');
122
+ const key = source.layer === 'file'
123
+ ? `file:${source.fileId}`
124
+ : source.layer === 'object'
125
+ ? `object:${source.type}/${source.id}`
126
+ : '';
127
+ if (
128
+ !key ||
129
+ seen.has(key) ||
130
+ (source.layer === 'file' && !isShortId(source.fileId)) ||
131
+ (source.layer === 'object' && (!validObjectType(source.type) || !isShortId(source.id)))
132
+ )
133
+ throw new Error('工作区视图来源身份无效或重复');
134
+ seen.add(key);
135
+ }
136
+ if (value.database !== undefined) {
137
+ if (value.kind !== 'files') throw new Error('文件数据库必须使用文件视图');
138
+ validateFileDatabaseQuery(value.database);
139
+ }
140
+ if (value.objectDatabase !== undefined) {
141
+ if (value.kind !== 'objects' || value.database) throw new Error('对象数据库必须使用对象视图');
142
+ validateObjectViewQuery(value.objectDatabase);
143
+ }
144
+ return value;
145
+ }
146
+
147
+ /** View sources are references, never paths. This check is deliberately pure and rebuildable. */
148
+ export function viewSources(
149
+ view: WorkspaceViewDefinition,
150
+ files: readonly WorkspaceFileRef[],
151
+ objects: readonly WorkspaceObjectRef[],
152
+ ) {
153
+ const workspaceFiles = files.filter((file) => file.workspaceId === view.workspaceId);
154
+ const workspaceObjects = objects.filter((object) => object.workspaceId === view.workspaceId);
155
+ const workspaceFileIds = new Set(workspaceFiles.map((file) => file.fileId));
156
+ const workspaceObjectIds = new Set(workspaceObjects.map((object) => `${object.type}/${object.id}`));
157
+ return view.sources.filter((source) =>
158
+ source.layer === 'file'
159
+ ? workspaceFileIds.has(source.fileId)
160
+ : workspaceObjectIds.has(`${source.type}/${source.id}`),
161
+ );
162
+ }
@@ -0,0 +1,49 @@
1
+ import { validatePath } from './paths';
2
+ import { workspacePluginPath } from './extensions';
3
+
4
+ export const workspaceDataDirectory = '.tano';
5
+ export const objectDirectory = '.tano/objects';
6
+ export const workspaceCapabilityPath = '.tano/capabilities.json';
7
+ export const workspaceFolderRegistryPath = '.tano/folders.tano.json';
8
+ export const workspaceSettingsPath = '.tano/settings.tano.json';
9
+ export const workspaceRelationPath = '.tano/relations.tano-relations.json';
10
+ export const annotationDirectory = '.tano/annotations';
11
+ export const discussionDirectory = '.tano/discussions';
12
+ export const assistantRulesPath = '.tano/rules/assistant.md';
13
+ export const templateDirectory = '.tano/templates';
14
+ export const workspaceViewDirectory = '.tano/views';
15
+ export const isWorkspaceViewPath = (path: string) =>
16
+ /^\.tano\/views\/[a-zA-Z0-9_-]{1,64}\.tano\.json$/.test(path);
17
+ export const isTemplatePath = (path: string) => /^\.tano\/templates\/[0-9a-f]{6}\.md$/.test(path);
18
+
19
+ export function commentDataPath(kind: 'annotation' | 'discussion', fileId: string) {
20
+ if (!/^[0-9a-f]{6}$/.test(fileId)) throw new Error('文档身份无效');
21
+ return `${kind === 'annotation' ? annotationDirectory : discussionDirectory}/${fileId}.tano.json`;
22
+ }
23
+
24
+ export function isWorkspaceInternalPath(path: string) {
25
+ return path === workspaceDataDirectory || path.startsWith(`${workspaceDataDirectory}/`);
26
+ }
27
+
28
+ /** Only portable Tano data is exposed to storage and sync; identity stays private. */
29
+ export function isWorkspaceDataPath(path: string) {
30
+ return (
31
+ path === workspaceCapabilityPath ||
32
+ path === workspaceFolderRegistryPath ||
33
+ path === workspaceSettingsPath ||
34
+ path === workspacePluginPath ||
35
+ path === workspaceRelationPath ||
36
+ path === assistantRulesPath ||
37
+ isTemplatePath(path) ||
38
+ isWorkspaceViewPath(path) ||
39
+ (path.startsWith('.tano/conflicts/') && path.endsWith('.json')) ||
40
+ (path.startsWith(`${objectDirectory}/`) && path.endsWith('.tano.json')) ||
41
+ /^\.tano\/(?:annotations|discussions|document-layout|suggestions|tables|files)\/[0-9a-f]{6}\.tano\.json$/.test(path)
42
+ );
43
+ }
44
+
45
+ export function validateStoragePath(path: string): string | null {
46
+ if (!isWorkspaceDataPath(path)) return validatePath(path);
47
+ if (path.length > 220) return '路径过长,请使用更短的名称';
48
+ return validatePath(path.slice(path.indexOf('/') + 1));
49
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.