Repository navigation
Expand file tree
/
Copy pathpathAtom.ts
More file actions
369 lines (349 loc) · 12.6 KB
/
Copy pathpathAtom.ts
File metadata and controls
369 lines (349 loc) · 12.6 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/**
* PathAtom grammar helpers (mirror of shared/atoms/path_atom.py).
* Genetic tag: shared.atoms.path.gen1 / repo.platform.sdk.agent_protocol.gen1
*/
export type PathSegKind = 'key' | 'index' | 'uid';
export interface PathSegment {
kind: PathSegKind;
value: string | number;
containerKey?: string;
}
const DENIED = new Set(['__proto__', 'prototype', 'constructor']);
/** Parse `a.b`, `items[0]`, `items{uid}` / `items[@uid=x]`. */
export function parsePath(path: string): PathSegment[] {
const raw = (path || '').trim();
if (!raw || raw.length > 512) throw new Error('invalid_path');
const parts: string[] = [];
let cur = '';
let depthSq = 0;
let depthBrace = 0;
for (const ch of raw) {
if (ch === '[') {
depthSq++;
cur += ch;
} else if (ch === ']') {
depthSq = Math.max(0, depthSq - 1);
cur += ch;
} else if (ch === '{') {
depthBrace++;
cur += ch;
} else if (ch === '}') {
depthBrace = Math.max(0, depthBrace - 1);
cur += ch;
} else if (ch === '.' && depthSq === 0 && depthBrace === 0) {
if (cur) parts.push(cur);
cur = '';
} else {
cur += ch;
}
}
if (cur) parts.push(cur);
if (!parts.length || parts.length > 64) throw new Error('invalid_path');
return parts.map((part) => {
let m = part.match(/^(.+)\{([^}]+)\}$/) || part.match(/^(.+)\[@uid=([^\]]+)\]$/);
if (m) {
if (DENIED.has(m[1])) throw new Error('invalid_path_segment');
return { kind: 'uid' as const, value: m[2], containerKey: m[1] };
}
m = part.match(/^(.+)\[(\d+)\]$/);
if (m) {
if (DENIED.has(m[1])) throw new Error('invalid_path_segment');
return { kind: 'index' as const, value: Number(m[2]), containerKey: m[1] };
}
if (DENIED.has(part)) throw new Error('invalid_path_segment');
return { kind: 'key' as const, value: part };
});
}
function entityKey(item: unknown): string | null {
if (!item || typeof item !== 'object') return null;
const o = item as Record<string, unknown>;
for (const k of ['uid', 'id', 'key']) {
if (o[k] != null && o[k] !== '') return String(o[k]);
}
return null;
}
function resolveUid(node: unknown, uid: string): unknown {
if (Array.isArray(node)) {
return node.find((i) => entityKey(i) === uid);
}
if (node && typeof node === 'object') {
const o = node as Record<string, unknown>;
if (uid in o) return o[uid];
for (const v of Object.values(o)) {
if (entityKey(v) === uid) return v;
}
}
return undefined;
}
/** Get value at PathAtom path; flat protein short-circuit when path in root. */
export function getPath(root: unknown, path: string): unknown {
if (root == null || !path) return undefined;
if (typeof root === 'object' && !Array.isArray(root) && path in (root as object)) {
return (root as Record<string, unknown>)[path];
}
let segs: PathSegment[];
try {
segs = parsePath(path);
} catch {
return undefined;
}
let current: unknown = root;
for (const seg of segs) {
if (current == null) return undefined;
if (seg.kind === 'key') {
if (typeof current !== 'object' || Array.isArray(current)) return undefined;
current = (current as Record<string, unknown>)[String(seg.value)];
} else if (seg.kind === 'index') {
const key = seg.containerKey!;
if (typeof current !== 'object' || Array.isArray(current)) return undefined;
const lst = (current as Record<string, unknown>)[key];
if (!Array.isArray(lst)) return undefined;
current = lst[Number(seg.value)];
} else {
const key = seg.containerKey!;
if (typeof current !== 'object' || Array.isArray(current)) return undefined;
current = resolveUid((current as Record<string, unknown>)[key], String(seg.value));
}
}
return current;
}
/** Structured GET: subset by paths (flat map). */
export function projectPaths(root: unknown, paths: string[]): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const p of paths) out[p] = getPath(root, p);
return out;
}
function ensureListPad(lst: unknown[], index: number, fill: unknown): void {
while (lst.length <= index) lst.push(structuredCloneSafe(fill));
}
function structuredCloneSafe<T>(v: T): T {
if (v == null || typeof v !== 'object') return v;
try {
return structuredClone(v);
} catch {
return JSON.parse(JSON.stringify(v)) as T;
}
}
/**
* Set value at PathAtom path (mirror of ``shared.atoms.path_atom.set_path``).
* Returns updated root (deep-copied levels when ``copyRoot``).
*/
export function setPath(
root: Record<string, unknown> | null | undefined,
path: string,
value: unknown,
opts?: { copyRoot?: boolean; listKey?: string },
): Record<string, unknown> {
const copyRoot = opts?.copyRoot !== false;
const listKey = opts?.listKey ?? 'uid';
const result: Record<string, unknown> = copyRoot
? structuredCloneSafe(root && typeof root === 'object' ? root : {})
: ((root && typeof root === 'object' ? root : {}) as Record<string, unknown>);
const segments = parsePath(path);
if (!segments.length) return result;
let current: Record<string, unknown> | unknown[] = result;
for (let i = 0; i < segments.length - 1; i++) {
const seg = segments[i]!;
if (seg.kind === 'key') {
const key = String(seg.value);
const cur = current as Record<string, unknown>;
if (cur[key] == null || typeof cur[key] !== 'object' || Array.isArray(cur[key])) {
cur[key] = {};
}
current = cur[key] as Record<string, unknown>;
} else if (seg.kind === 'index') {
const key = seg.containerKey!;
const cur = current as Record<string, unknown>;
if (!Array.isArray(cur[key])) cur[key] = [];
const lst = cur[key] as unknown[];
const idx = Number(seg.value);
ensureListPad(lst, idx, {});
if (lst[idx] == null || typeof lst[idx] !== 'object') lst[idx] = {};
current = lst[idx] as Record<string, unknown>;
} else {
const key = seg.containerKey!;
const uid = String(seg.value);
const cur = current as Record<string, unknown>;
if (cur[key] == null) cur[key] = [];
const node = cur[key];
if (node && typeof node === 'object' && !Array.isArray(node)) {
const map = node as Record<string, unknown>;
if (map[uid] == null || typeof map[uid] !== 'object') {
map[uid] = { [listKey]: uid };
}
current = map[uid] as Record<string, unknown>;
} else {
const lst = Array.isArray(node) ? node : [];
cur[key] = lst;
let found = lst.find(
(item) => item && typeof item === 'object' && entityKey(item) === uid,
) as Record<string, unknown> | undefined;
if (!found) {
found = { [listKey]: uid };
lst.push(found);
}
current = found;
}
}
}
const final = segments[segments.length - 1]!;
if (final.kind === 'key') {
(current as Record<string, unknown>)[String(final.value)] = value;
} else if (final.kind === 'index') {
const key = final.containerKey!;
const cur = current as Record<string, unknown>;
if (!Array.isArray(cur[key])) cur[key] = [];
const lst = cur[key] as unknown[];
const idx = Number(final.value);
ensureListPad(lst, idx, null);
lst[idx] = value;
} else {
const key = final.containerKey!;
const uid = String(final.value);
let payload = value;
if (payload && typeof payload === 'object' && !Array.isArray(payload) && !(listKey in (payload as object))) {
payload = { ...(payload as Record<string, unknown>), [listKey]: uid };
}
const cur = current as Record<string, unknown>;
if (cur[key] == null) cur[key] = [];
const node = cur[key];
if (node && typeof node === 'object' && !Array.isArray(node)) {
(node as Record<string, unknown>)[uid] = payload;
} else {
const lst = Array.isArray(node) ? node : [];
cur[key] = lst;
const ix = lst.findIndex(
(item) => item && typeof item === 'object' && entityKey(item) === uid,
);
if (ix >= 0) lst[ix] = payload;
else lst.push(payload);
}
}
return result;
}
export function matchesWhere(item: unknown, where: Record<string, unknown>): boolean {
if (!item || typeof item !== 'object' || Array.isArray(item)) return false;
const rec = item as Record<string, unknown>;
for (const [key, val] of Object.entries(where)) {
if (rec[key] !== val) return false;
}
return true;
}
export function selectListIndexes(
items: unknown,
where: Record<string, unknown>,
opts?: { count?: number },
): { indexes: number[]; error?: string } {
if (!Array.isArray(items)) return { indexes: [], error: 'write_mode_unsupported' };
if (!where || typeof where !== 'object' || !Object.keys(where).length) {
return { indexes: [], error: 'anchor_not_found' };
}
const matches = items.map((it, i) => (matchesWhere(it, where) ? i : -1)).filter((i) => i >= 0);
if (!matches.length) return { indexes: [], error: 'anchor_not_found' };
if (opts?.count == null && matches.length > 1) {
return { indexes: [], error: 'ambiguous_anchor' };
}
if (opts?.count != null) return { indexes: matches.slice(0, Number(opts.count)) };
return { indexes: [matches[0]] };
}
export function insertRelativeToWhere(
root: Record<string, unknown>,
listPath: string,
where: Record<string, unknown>,
value: unknown,
opts: { before: boolean; copyRoot?: boolean },
): Record<string, unknown> {
const copyRoot = opts.copyRoot !== false;
const result: Record<string, unknown> = copyRoot ? structuredCloneSafe(root) : root;
const lst = getPath(result, listPath);
const { indexes, error } = selectListIndexes(lst, where);
if (error) throw new Error(error);
const idx = indexes[0]!;
const insertIdx = opts.before ? idx : idx + 1;
return insertAtPath(result, listPath, insertIdx, value, { copyRoot: false });
}
export function moveListItem(
root: Record<string, unknown>,
listPath: string,
opts?: {
fromIndex?: number;
toIndex?: number;
uid?: string;
beforeUid?: string;
listKey?: string;
copyRoot?: boolean;
},
): Record<string, unknown> {
const copyRoot = opts?.copyRoot !== false;
const listKey = opts?.listKey ?? 'uid';
const result: Record<string, unknown> = copyRoot ? structuredCloneSafe(root) : root;
const lst = getPath(result, listPath);
if (!Array.isArray(lst)) throw new Error('write_mode_unsupported');
const newList = [...lst];
let fromIndex = opts?.fromIndex;
if (fromIndex == null && opts?.uid) {
fromIndex = newList.findIndex((it) => entityKey(it) === String(opts.uid));
if (fromIndex < 0) fromIndex = undefined;
}
if (fromIndex == null) throw new Error('anchor_not_found');
const fi = Number(fromIndex);
if (fi < 0 || fi >= newList.length) throw new Error('index_out_of_range');
const item = newList.splice(fi, 1)[0];
if (opts?.toIndex != null) {
let ti = Number(opts.toIndex);
if (ti < 0) ti = 0;
if (ti > newList.length) ti = newList.length;
newList.splice(ti, 0, item);
} else if (opts?.beforeUid) {
const ti = newList.findIndex((it) => entityKey(it) === String(opts.beforeUid));
if (ti < 0) throw new Error('anchor_not_found');
newList.splice(ti, 0, item);
} else {
newList.push(item);
}
return setPath(result, listPath, newList, { copyRoot: false });
}
/** Insert into list at path (mirror of ``insert_at_path``). */
export function insertAtPath(
root: Record<string, unknown>,
path: string,
index: number,
value: unknown,
opts?: { copyRoot?: boolean },
): Record<string, unknown> {
const copyRoot = opts?.copyRoot !== false;
const result: Record<string, unknown> = copyRoot
? structuredCloneSafe(root)
: root;
const lst = getPath(result, path);
if (!Array.isArray(lst)) {
throw new Error('write_mode_unsupported');
}
const idx = Number(index);
if (idx < 0 || idx > lst.length) {
throw new Error('index_out_of_range');
}
const nextList = [...lst];
nextList.splice(idx, 0, value);
return setPath(result, path, nextList, { copyRoot: false });
}
/** Delete a dotted path segment (mirror of ``delete_path`` for simple dot paths). */
export function deletePath(
root: Record<string, unknown>,
path: string,
): Record<string, unknown> {
const result = structuredCloneSafe(root);
const parts = (path || '').split('.').filter(Boolean);
if (!parts.length) return result;
let cur: Record<string, unknown> = result;
for (let i = 0; i < parts.length - 1; i++) {
const key = parts[i]!;
const next = cur[key];
if (!next || typeof next !== 'object' || Array.isArray(next)) {
return result;
}
cur = next as Record<string, unknown>;
}
delete cur[parts[parts.length - 1]!];
return result;
}