-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathinvoke-input.ts
More file actions
286 lines (261 loc) · 10.1 KB
/
Copy pathinvoke-input.ts
File metadata and controls
286 lines (261 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
* Extracts the API-level input from the CLI input object.
*
* The CLI wrapper parsing produces objects that mix API-level fields with
* CLI-level fields (doc, sessionId, out, force, etc.). Some operations wrap
* their API input in a named field (query, address, input). Some operations
* rename API field names for the CLI (commentId → id).
*
* This module strips CLI-level fields, unwraps operation-specific input
* keys, reverses param renames, and normalizes flat flags (blockId, start,
* end, nodeId, offset) into canonical `target` objects so that `invoke()`
* receives the correct input shape.
*/
import { CliError } from './errors.js';
import { CLI_DOC_OPERATIONS, type CliExposedOperationId } from '../cli/operation-set.js';
/**
* Operations whose API input is wrapped in a named field on the CLI input object.
*
* For example, the `find` wrapper produces `{ doc, sessionId, query: Query }`.
* The API's `invoke('find', input)` expects the `Query` object directly as input,
* so we extract `cliInput.query` as the invoke input.
*/
const WRAPPED_INPUT_KEY: Partial<Record<CliExposedOperationId, string>> = {
find: 'query',
getNode: 'address',
'lists.list': 'query',
'lists.insert': 'input',
'lists.indent': 'input',
'lists.outdent': 'input',
'lists.create': 'input',
'lists.attach': 'input',
'lists.detach': 'input',
'lists.join': 'input',
'lists.canJoin': 'input',
'lists.separate': 'input',
'lists.setLevel': 'input',
'lists.setValue': 'input',
'lists.continuePrevious': 'input',
'lists.canContinuePrevious': 'input',
'lists.setLevelRestart': 'input',
'lists.applyTemplate': 'input',
'lists.applyPreset': 'input',
'lists.captureTemplate': 'input',
'lists.setLevelNumbering': 'input',
'lists.setLevelBullet': 'input',
'lists.setLevelPictureBullet': 'input',
'lists.setLevelAlignment': 'input',
'lists.setLevelIndents': 'input',
'lists.setLevelTrailingCharacter': 'input',
'lists.setLevelMarkerFont': 'input',
'lists.clearLevelOverrides': 'input',
'lists.convertToText': 'input',
'create.paragraph': 'input',
'create.heading': 'input',
};
/**
* Reverse param name mapping: CLI param name → API field name.
*
* Derived from PARAM_FLAG_OVERRIDES in operation-params.ts.
* The CLI renames certain API fields for user convenience (e.g. `commentId` → `id`).
* We reverse these so `invoke()` receives the original API field names.
*/
const PARAM_RENAMES: Partial<Record<CliExposedOperationId, Record<string, string>>> = {
getNodeById: { id: 'nodeId' },
'comments.create': { parentId: 'parentCommentId' },
'comments.patch': { id: 'commentId' },
'comments.delete': { id: 'commentId' },
'comments.get': { id: 'commentId' },
};
/** Fields that belong to the CLI layer, not the document API. */
const CLI_LEVEL_KEYS = new Set(['doc', 'sessionId', 'out', 'dryRun', 'force', 'expectedRevision', 'changeMode']);
/**
* Operations where `changeMode` is part of the API input schema, not a CLI-level option.
* For these, `changeMode` must NOT be stripped from the input.
*/
const CHANGEMODE_IN_INPUT = new Set<CliExposedOperationId>(['mutations.apply', 'mutations.preview']);
const FORMAT_TARGET_OPERATIONS = CLI_DOC_OPERATIONS.filter((operationId): operationId is CliExposedOperationId =>
operationId.startsWith('format.'),
);
// ---------------------------------------------------------------------------
// Flat-flag → canonical target normalization
// ---------------------------------------------------------------------------
/**
* Operations that accept a SelectionTarget or a mutation-ready `ref`.
* The CLI still supports legacy single-block text range flags/JSON inputs and
* upgrades them to the equivalent SelectionTarget before dispatch.
*/
const SELECTION_TARGET_OPERATIONS = new Set<CliExposedOperationId>([
'insert',
'replace',
'delete',
...FORMAT_TARGET_OPERATIONS,
]);
/**
* Operations that still accept a text-range target (textAddressSchema):
* target: { kind: 'text', blockId, range: { start, end } }
*
* When the CLI input has flat `blockId` + `start` + `end` but no `target`,
* these are folded into a canonical target object.
*/
const TEXT_ADDRESS_TARGET_OPERATIONS = new Set<CliExposedOperationId>(['comments.create', 'comments.patch']);
// INSERT_OPERATION removed — insert now uses SelectionTarget via SELECTION_TARGET_OPERATIONS.
/**
* List operations that accept a list-item target (listItemAddressSchema):
* target: { kind: 'block', nodeType: 'listItem', nodeId }
*/
const LIST_TARGET_OPERATIONS = new Set<CliExposedOperationId>([
'lists.insert',
'lists.indent',
'lists.outdent',
'lists.detach',
'lists.separate',
'lists.setLevel',
'lists.setValue',
'lists.continuePrevious',
'lists.canContinuePrevious',
'lists.convertToText',
]);
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isTextAddressLike(value: unknown): value is {
kind: 'text';
blockId: string;
range: { start: number; end: number };
} {
if (!isRecord(value) || value.kind !== 'text' || typeof value.blockId !== 'string') return false;
if (!isRecord(value.range)) return false;
return typeof value.range.start === 'number' && typeof value.range.end === 'number';
}
function textAddressToSelectionTarget(target: {
blockId: string;
range: { start: number; end: number };
}): Record<string, unknown> {
return {
kind: 'selection',
start: {
kind: 'text',
blockId: target.blockId,
offset: target.range.start,
},
end: {
kind: 'text',
blockId: target.blockId,
offset: target.range.end,
},
};
}
function isCollapsedTextAddress(target: { range: { start: number; end: number } }): boolean {
return target.range.start === target.range.end;
}
function assertLegacySelectionTargetSupported(
operationId: CliExposedOperationId,
target: {
range: { start: number; end: number };
},
): void {
if (operationId.startsWith('format.') && isCollapsedTextAddress(target)) {
throw new CliError('INVALID_ARGUMENT', `${operationId} requires a non-collapsed target range.`);
}
}
/**
* Normalizes flat CLI flags into canonical `target` objects.
*
* This runs AFTER extraction and renaming, BEFORE dispatch to the document-api.
* If the input already contains a `target`, flat flags are left untouched (the
* caller provided the canonical form directly).
*/
function normalizeFlatTargetFlags(operationId: CliExposedOperationId, apiInput: unknown): unknown {
if (!isRecord(apiInput)) return apiInput;
if (apiInput.target !== undefined) {
if (SELECTION_TARGET_OPERATIONS.has(operationId) && isTextAddressLike(apiInput.target)) {
assertLegacySelectionTargetSupported(operationId, apiInput.target);
return {
...apiInput,
target: textAddressToSelectionTarget(apiInput.target),
};
}
return apiInput;
}
// --- Selection-based text mutations (insert, replace, delete, format.*) ---
if (SELECTION_TARGET_OPERATIONS.has(operationId)) {
const blockId = apiInput.blockId;
if (typeof blockId === 'string') {
// Legacy --offset for insert: expand to collapsed start/end
const hasOffset = typeof apiInput.offset === 'number';
const start = typeof apiInput.start === 'number' ? apiInput.start : hasOffset ? (apiInput.offset as number) : 0;
const end = typeof apiInput.end === 'number' ? apiInput.end : hasOffset ? (apiInput.offset as number) : 0;
assertLegacySelectionTargetSupported(operationId, { range: { start, end } });
const { blockId: _, start: _s, end: _e, offset: _o, ...rest } = apiInput;
return {
...rest,
target: textAddressToSelectionTarget({ blockId, range: { start, end } }),
};
}
return apiInput;
}
// --- Text-address operations (comments.create, comments.patch) ---
if (TEXT_ADDRESS_TARGET_OPERATIONS.has(operationId)) {
const blockId = apiInput.blockId;
if (typeof blockId === 'string') {
const start = typeof apiInput.start === 'number' ? apiInput.start : 0;
const end = typeof apiInput.end === 'number' ? apiInput.end : 0;
const { blockId: _, start: _s, end: _e, ...rest } = apiInput;
return {
...rest,
target: { kind: 'text', blockId, range: { start, end } },
};
}
return apiInput;
}
// --- Block delete (nodeType + nodeId → block target) ---
if (operationId === 'blocks.delete') {
const nodeType = apiInput.nodeType;
const nodeId = apiInput.nodeId;
if (typeof nodeType === 'string' && typeof nodeId === 'string') {
const { nodeType: _, nodeId: _n, ...rest } = apiInput;
return {
...rest,
target: { kind: 'block', nodeType, nodeId },
};
}
return apiInput;
}
// --- List operations (nodeId → listItem block target) ---
if (LIST_TARGET_OPERATIONS.has(operationId)) {
const nodeId = apiInput.nodeId;
if (typeof nodeId === 'string') {
const { nodeId: _, ...rest } = apiInput;
return {
...rest,
target: { kind: 'block', nodeType: 'listItem', nodeId },
};
}
return apiInput;
}
return apiInput;
}
/**
* Extracts the invoke-level input from a CLI input object.
*
* Returns the input that should be passed to `editor.doc.invoke({ input })`.
* Flat CLI flags (blockId, start, end, nodeId, offset) are normalized into
* canonical `target` objects before returning.
*/
export function extractInvokeInput(operationId: CliExposedOperationId, cliInput: Record<string, unknown>): unknown {
const wrapperKey = WRAPPED_INPUT_KEY[operationId];
if (wrapperKey && cliInput[wrapperKey] != null) {
// Wrapped input may also contain flat flags that need normalization
return normalizeFlatTargetFlags(operationId, cliInput[wrapperKey]);
}
const renames = PARAM_RENAMES[operationId];
const apiInput: Record<string, unknown> = {};
const keepChangeMode = CHANGEMODE_IN_INPUT.has(operationId);
for (const [key, value] of Object.entries(cliInput)) {
if (CLI_LEVEL_KEYS.has(key) && !(key === 'changeMode' && keepChangeMode)) continue;
const apiKey = renames?.[key] ?? key;
apiInput[apiKey] = value;
}
return normalizeFlatTargetFlags(operationId, apiInput);
}