@aigne/afs-json 1.1.0 → 1.11.0-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -16
- package/dist/index.cjs +366 -0
- package/dist/index.d.cts +122 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +122 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +367 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +29 -43
- package/CHANGELOG.md +0 -47
- package/lib/cjs/index.d.ts +0 -108
- package/lib/cjs/index.js +0 -470
- package/lib/cjs/package.json +0 -3
- package/lib/dts/index.d.ts +0 -108
- package/lib/esm/index.d.ts +0 -108
- package/lib/esm/index.js +0 -466
- package/lib/esm/package.json +0 -3
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@ afs.mount(
|
|
|
33
33
|
new AFSJSON({
|
|
34
34
|
name: "config",
|
|
35
35
|
jsonPath: "./config.json",
|
|
36
|
-
})
|
|
36
|
+
}),
|
|
37
37
|
);
|
|
38
38
|
|
|
39
39
|
// Or mount a YAML file
|
|
@@ -41,7 +41,7 @@ afs.mount(
|
|
|
41
41
|
new AFSJSON({
|
|
42
42
|
name: "app-config",
|
|
43
43
|
jsonPath: "./config.yaml",
|
|
44
|
-
})
|
|
44
|
+
}),
|
|
45
45
|
);
|
|
46
46
|
|
|
47
47
|
// Read the entire JSON/YAML
|
|
@@ -86,6 +86,7 @@ version: "1.0.0"
|
|
|
86
86
|
```
|
|
87
87
|
|
|
88
88
|
This YAML structure becomes:
|
|
89
|
+
|
|
89
90
|
```
|
|
90
91
|
/config/ # Root object
|
|
91
92
|
/config/database/ # Nested object (directory)
|
|
@@ -99,6 +100,7 @@ This YAML structure becomes:
|
|
|
99
100
|
```
|
|
100
101
|
|
|
101
102
|
**Format Detection and Persistence:**
|
|
103
|
+
|
|
102
104
|
- Format is detected automatically from file extension (.json, .yaml, .yml)
|
|
103
105
|
- When writing to a YAML file, changes are saved in YAML format
|
|
104
106
|
- When writing to a JSON file, changes are saved in JSON format
|
|
@@ -124,6 +126,7 @@ This YAML structure becomes:
|
|
|
124
126
|
```
|
|
125
127
|
|
|
126
128
|
This structure becomes:
|
|
129
|
+
|
|
127
130
|
```
|
|
128
131
|
/config/ # Root object
|
|
129
132
|
/config/database/ # Nested object (directory)
|
|
@@ -161,6 +164,7 @@ This structure becomes:
|
|
|
161
164
|
```
|
|
162
165
|
|
|
163
166
|
This structure becomes:
|
|
167
|
+
|
|
164
168
|
```
|
|
165
169
|
/users/ # Array (directory)
|
|
166
170
|
/users/0/ # First user object (directory)
|
|
@@ -181,23 +185,23 @@ This structure becomes:
|
|
|
181
185
|
|
|
182
186
|
```typescript
|
|
183
187
|
// Read a property from an array object
|
|
184
|
-
const { data } = await afs.read(
|
|
188
|
+
const { data } = await afs.read("/modules/users/0/name");
|
|
185
189
|
console.log(data?.content); // "Alice"
|
|
186
190
|
|
|
187
191
|
// Update a nested property in an array object
|
|
188
|
-
await afs.write(
|
|
192
|
+
await afs.write("/modules/users/0/profile/age", { content: 31 });
|
|
189
193
|
|
|
190
194
|
// Add a new property to an array object
|
|
191
|
-
await afs.write(
|
|
195
|
+
await afs.write("/modules/users/0/active", { content: true });
|
|
192
196
|
|
|
193
197
|
// List all properties of an array object
|
|
194
|
-
const result = await afs.list(
|
|
198
|
+
const result = await afs.list("/modules/users/0");
|
|
195
199
|
|
|
196
200
|
// Search within array objects
|
|
197
|
-
const results = await afs.search(
|
|
201
|
+
const results = await afs.search("/modules/users", "Beijing");
|
|
198
202
|
|
|
199
203
|
// Delete from an array (shifts subsequent indices)
|
|
200
|
-
await afs.delete(
|
|
204
|
+
await afs.delete("/modules/users/1", { recursive: true });
|
|
201
205
|
// Now users/2 becomes users/1
|
|
202
206
|
```
|
|
203
207
|
|
|
@@ -205,15 +209,16 @@ await afs.delete('/modules/users/1', { recursive: true });
|
|
|
205
209
|
|
|
206
210
|
```typescript
|
|
207
211
|
interface AFSJSONOptions {
|
|
208
|
-
name?: string;
|
|
209
|
-
jsonPath: string;
|
|
210
|
-
description?: string;
|
|
211
|
-
accessMode?: "readonly" | "readwrite";
|
|
212
|
-
agentSkills?: boolean;
|
|
212
|
+
name?: string; // Module name (default: basename of jsonPath without extension)
|
|
213
|
+
jsonPath: string; // Path to JSON or YAML file
|
|
214
|
+
description?: string; // Module description
|
|
215
|
+
accessMode?: "readonly" | "readwrite"; // Access mode (default: "readwrite")
|
|
216
|
+
agentSkills?: boolean; // Enable agent skill scanning
|
|
213
217
|
}
|
|
214
218
|
```
|
|
215
219
|
|
|
216
220
|
**Note:** File format is automatically detected from the `jsonPath` extension:
|
|
221
|
+
|
|
217
222
|
- `.json` files are saved as JSON
|
|
218
223
|
- `.yaml` or `.yml` files are saved as YAML
|
|
219
224
|
|
|
@@ -225,7 +230,7 @@ afs.mount(
|
|
|
225
230
|
name: "readonly-config",
|
|
226
231
|
jsonPath: "./config.json",
|
|
227
232
|
accessMode: "readonly",
|
|
228
|
-
})
|
|
233
|
+
}),
|
|
229
234
|
);
|
|
230
235
|
|
|
231
236
|
// Reading is allowed
|
|
@@ -244,7 +249,7 @@ afs.mount(
|
|
|
244
249
|
name: "settings",
|
|
245
250
|
jsonPath: "./settings.json",
|
|
246
251
|
accessMode: "readwrite",
|
|
247
|
-
})
|
|
252
|
+
}),
|
|
248
253
|
);
|
|
249
254
|
|
|
250
255
|
// Or mount a YAML file
|
|
@@ -253,7 +258,7 @@ afs.mount(
|
|
|
253
258
|
name: "config",
|
|
254
259
|
jsonPath: "./config.yaml",
|
|
255
260
|
accessMode: "readwrite",
|
|
256
|
-
})
|
|
261
|
+
}),
|
|
257
262
|
);
|
|
258
263
|
|
|
259
264
|
// Update a value
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
let node_fs_promises = require("node:fs/promises");
|
|
2
|
+
let node_path = require("node:path");
|
|
3
|
+
let _aigne_afs_utils_zod = require("@aigne/afs/utils/zod");
|
|
4
|
+
let yaml = require("yaml");
|
|
5
|
+
let zod = require("zod");
|
|
6
|
+
|
|
7
|
+
//#region src/index.ts
|
|
8
|
+
const LIST_MAX_LIMIT = 1e3;
|
|
9
|
+
const afsJSONOptionsSchema = (0, _aigne_afs_utils_zod.camelize)(zod.z.object({
|
|
10
|
+
name: (0, _aigne_afs_utils_zod.optionalize)(zod.z.string()),
|
|
11
|
+
jsonPath: zod.z.string().describe("The path to the JSON/YAML file to mount"),
|
|
12
|
+
description: (0, _aigne_afs_utils_zod.optionalize)(zod.z.string().describe("A description of the JSON module")),
|
|
13
|
+
accessMode: (0, _aigne_afs_utils_zod.optionalize)(zod.z.enum(["readonly", "readwrite"]).describe("Access mode for this module")),
|
|
14
|
+
agentSkills: (0, _aigne_afs_utils_zod.optionalize)(zod.z.boolean().describe("Enable automatic agent skill scanning for this module"))
|
|
15
|
+
}));
|
|
16
|
+
/**
|
|
17
|
+
* AFS module for mounting JSON/YAML files as virtual file systems.
|
|
18
|
+
*
|
|
19
|
+
* JSON/YAML objects are treated as directories, and properties/array items as files.
|
|
20
|
+
* Supports nested structures and path-based access to data values.
|
|
21
|
+
*/
|
|
22
|
+
var AFSJSON = class AFSJSON {
|
|
23
|
+
static schema() {
|
|
24
|
+
return afsJSONOptionsSchema;
|
|
25
|
+
}
|
|
26
|
+
static async load({ filepath, parsed }) {
|
|
27
|
+
return new AFSJSON({
|
|
28
|
+
...await AFSJSON.schema().parseAsync(parsed),
|
|
29
|
+
cwd: (0, node_path.dirname)(filepath)
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
jsonData = null;
|
|
33
|
+
fileStats = {};
|
|
34
|
+
fileFormat = "json";
|
|
35
|
+
constructor(options) {
|
|
36
|
+
this.options = options;
|
|
37
|
+
(0, _aigne_afs_utils_zod.zodParse)(afsJSONOptionsSchema, options);
|
|
38
|
+
let jsonPath;
|
|
39
|
+
jsonPath = options.jsonPath.replaceAll("${CWD}", process.cwd());
|
|
40
|
+
if (jsonPath.startsWith("~/")) jsonPath = (0, node_path.join)(process.env.HOME || "", jsonPath.slice(2));
|
|
41
|
+
if (!(0, node_path.isAbsolute)(jsonPath)) jsonPath = (0, node_path.join)(options.cwd || process.cwd(), jsonPath);
|
|
42
|
+
const ext = (0, node_path.extname)(jsonPath).toLowerCase();
|
|
43
|
+
this.fileFormat = ext === ".yaml" || ext === ".yml" ? "yaml" : "json";
|
|
44
|
+
const extensions = [
|
|
45
|
+
".json",
|
|
46
|
+
".yaml",
|
|
47
|
+
".yml"
|
|
48
|
+
];
|
|
49
|
+
let name = (0, node_path.basename)(jsonPath);
|
|
50
|
+
for (const e of extensions) if (name.endsWith(e)) {
|
|
51
|
+
name = name.slice(0, -e.length);
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
this.name = options.name || name || "json";
|
|
55
|
+
this.description = options.description;
|
|
56
|
+
this.agentSkills = options.agentSkills;
|
|
57
|
+
this.accessMode = options.accessMode ?? (options.agentSkills ? "readonly" : "readwrite");
|
|
58
|
+
this.options.jsonPath = jsonPath;
|
|
59
|
+
}
|
|
60
|
+
name;
|
|
61
|
+
description;
|
|
62
|
+
accessMode;
|
|
63
|
+
agentSkills;
|
|
64
|
+
/**
|
|
65
|
+
* Load JSON/YAML data from file. Called lazily on first access.
|
|
66
|
+
* Uses YAML parser which can handle both JSON and YAML formats.
|
|
67
|
+
*/
|
|
68
|
+
async ensureLoaded() {
|
|
69
|
+
if (this.jsonData !== null) return;
|
|
70
|
+
try {
|
|
71
|
+
const stats = await (0, node_fs_promises.stat)(this.options.jsonPath);
|
|
72
|
+
this.fileStats = {
|
|
73
|
+
birthtime: stats.birthtime,
|
|
74
|
+
mtime: stats.mtime
|
|
75
|
+
};
|
|
76
|
+
this.jsonData = (0, yaml.parse)(await (0, node_fs_promises.readFile)(this.options.jsonPath, "utf8"));
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error.code === "ENOENT") this.jsonData = {};
|
|
79
|
+
else throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Save JSON/YAML data back to file. Only called in readwrite mode.
|
|
84
|
+
*/
|
|
85
|
+
async saveToFile() {
|
|
86
|
+
let content;
|
|
87
|
+
if (this.fileFormat === "yaml") content = (0, yaml.stringify)(this.jsonData);
|
|
88
|
+
else content = JSON.stringify(this.jsonData, null, 2);
|
|
89
|
+
await (0, node_fs_promises.writeFile)(this.options.jsonPath, content, "utf8");
|
|
90
|
+
const stats = await (0, node_fs_promises.stat)(this.options.jsonPath);
|
|
91
|
+
this.fileStats = {
|
|
92
|
+
birthtime: this.fileStats.birthtime || stats.birthtime,
|
|
93
|
+
mtime: stats.mtime
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Normalize path to ensure consistent format
|
|
98
|
+
*/
|
|
99
|
+
normalizePath(path) {
|
|
100
|
+
let normalized = path.startsWith("/") ? path : `/${path}`;
|
|
101
|
+
if (normalized.length > 1 && normalized.endsWith("/")) normalized = normalized.slice(0, -1);
|
|
102
|
+
return normalized;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Get path segments from normalized path
|
|
106
|
+
*/
|
|
107
|
+
getPathSegments(path) {
|
|
108
|
+
const normalized = this.normalizePath(path);
|
|
109
|
+
if (normalized === "/") return [];
|
|
110
|
+
return normalized.slice(1).split("/");
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Navigate to a value in the JSON structure using path segments
|
|
114
|
+
*/
|
|
115
|
+
getValueAtPath(data, segments) {
|
|
116
|
+
let current = data;
|
|
117
|
+
for (const segment of segments) {
|
|
118
|
+
if (current == null) return void 0;
|
|
119
|
+
if (Array.isArray(current)) {
|
|
120
|
+
const index = Number.parseInt(segment, 10);
|
|
121
|
+
if (Number.isNaN(index) || index < 0 || index >= current.length) return;
|
|
122
|
+
current = current[index];
|
|
123
|
+
} else if (typeof current === "object") current = current[segment];
|
|
124
|
+
else return;
|
|
125
|
+
}
|
|
126
|
+
return current;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Set a value in the JSON structure at the given path
|
|
130
|
+
*/
|
|
131
|
+
setValueAtPath(data, segments, value) {
|
|
132
|
+
if (segments.length === 0) throw new Error("Cannot set value at root path");
|
|
133
|
+
let current = data;
|
|
134
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
135
|
+
const segment = segments[i];
|
|
136
|
+
const nextSegment = segments[i + 1];
|
|
137
|
+
if (Array.isArray(current)) {
|
|
138
|
+
const index = Number.parseInt(segment, 10);
|
|
139
|
+
if (Number.isNaN(index) || index < 0) throw new Error(`Invalid array index: ${segment}`);
|
|
140
|
+
while (current.length <= index) current.push(null);
|
|
141
|
+
if (current[index] == null) current[index] = !Number.isNaN(Number.parseInt(nextSegment, 10)) ? [] : {};
|
|
142
|
+
current = current[index];
|
|
143
|
+
} else if (typeof current === "object") {
|
|
144
|
+
if (current[segment] == null) current[segment] = !Number.isNaN(Number.parseInt(nextSegment, 10)) ? [] : {};
|
|
145
|
+
current = current[segment];
|
|
146
|
+
} else throw new Error(`Cannot set property on non-object at ${segments.slice(0, i + 1).join("/")}`);
|
|
147
|
+
}
|
|
148
|
+
const lastSegment = segments[segments.length - 1];
|
|
149
|
+
if (Array.isArray(current)) {
|
|
150
|
+
const index = Number.parseInt(lastSegment, 10);
|
|
151
|
+
if (Number.isNaN(index) || index < 0) throw new Error(`Invalid array index: ${lastSegment}`);
|
|
152
|
+
current[index] = value;
|
|
153
|
+
} else if (typeof current === "object") current[lastSegment] = value;
|
|
154
|
+
else throw new Error("Cannot set property on non-object");
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Delete a value from the JSON structure at the given path
|
|
158
|
+
*/
|
|
159
|
+
deleteValueAtPath(data, segments) {
|
|
160
|
+
if (segments.length === 0) throw new Error("Cannot delete root path");
|
|
161
|
+
let current = data;
|
|
162
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
163
|
+
const segment = segments[i];
|
|
164
|
+
if (Array.isArray(current)) {
|
|
165
|
+
const index = Number.parseInt(segment, 10);
|
|
166
|
+
if (Number.isNaN(index) || index < 0 || index >= current.length) return false;
|
|
167
|
+
current = current[index];
|
|
168
|
+
} else if (typeof current === "object") {
|
|
169
|
+
if (!(segment in current)) return false;
|
|
170
|
+
current = current[segment];
|
|
171
|
+
} else return false;
|
|
172
|
+
}
|
|
173
|
+
const lastSegment = segments[segments.length - 1];
|
|
174
|
+
if (Array.isArray(current)) {
|
|
175
|
+
const index = Number.parseInt(lastSegment, 10);
|
|
176
|
+
if (Number.isNaN(index) || index < 0 || index >= current.length) return false;
|
|
177
|
+
current.splice(index, 1);
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
if (typeof current === "object") {
|
|
181
|
+
if (!(lastSegment in current)) return false;
|
|
182
|
+
delete current[lastSegment];
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Check if a value is a "directory" (object or array with children)
|
|
189
|
+
*/
|
|
190
|
+
isDirectory(value) {
|
|
191
|
+
if (Array.isArray(value)) return true;
|
|
192
|
+
if (typeof value === "object" && value !== null) return true;
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Get children of a directory value
|
|
197
|
+
*/
|
|
198
|
+
getChildren(value) {
|
|
199
|
+
if (Array.isArray(value)) return value.map((item, index) => ({
|
|
200
|
+
key: String(index),
|
|
201
|
+
value: item
|
|
202
|
+
}));
|
|
203
|
+
if (typeof value === "object" && value !== null) return Object.entries(value).map(([key, val]) => ({
|
|
204
|
+
key,
|
|
205
|
+
value: val
|
|
206
|
+
}));
|
|
207
|
+
return [];
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Convert a JSON value to an AFSEntry
|
|
211
|
+
*/
|
|
212
|
+
valueToAFSEntry(path, value) {
|
|
213
|
+
const isDir = this.isDirectory(value);
|
|
214
|
+
const children = isDir ? this.getChildren(value) : [];
|
|
215
|
+
return {
|
|
216
|
+
id: path,
|
|
217
|
+
path,
|
|
218
|
+
content: isDir ? void 0 : value,
|
|
219
|
+
createdAt: this.fileStats.birthtime,
|
|
220
|
+
updatedAt: this.fileStats.mtime,
|
|
221
|
+
metadata: {
|
|
222
|
+
type: isDir ? "directory" : "file",
|
|
223
|
+
childrenCount: isDir ? children.length : void 0
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
async list(path, options) {
|
|
228
|
+
await this.ensureLoaded();
|
|
229
|
+
const normalizedPath = this.normalizePath(path);
|
|
230
|
+
const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
|
|
231
|
+
const maxChildren = typeof options?.maxChildren === "number" ? options.maxChildren : Number.MAX_SAFE_INTEGER;
|
|
232
|
+
const maxDepth = options?.maxDepth ?? 1;
|
|
233
|
+
const segments = this.getPathSegments(normalizedPath);
|
|
234
|
+
const value = this.getValueAtPath(this.jsonData, segments);
|
|
235
|
+
if (value === void 0) throw new Error(`Path not found: ${normalizedPath}`);
|
|
236
|
+
const entries = [];
|
|
237
|
+
const queue = [{
|
|
238
|
+
path: normalizedPath,
|
|
239
|
+
value,
|
|
240
|
+
depth: 0
|
|
241
|
+
}];
|
|
242
|
+
while (queue.length > 0) {
|
|
243
|
+
const item = queue.shift();
|
|
244
|
+
if (!item) break;
|
|
245
|
+
const { path: itemPath, value: itemValue, depth } = item;
|
|
246
|
+
const entry = this.valueToAFSEntry(itemPath, itemValue);
|
|
247
|
+
entries.push(entry);
|
|
248
|
+
if (entries.length >= limit) {
|
|
249
|
+
if (entry.metadata) entry.metadata.childrenTruncated = true;
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
if (this.isDirectory(itemValue) && depth < maxDepth) {
|
|
253
|
+
const children = this.getChildren(itemValue);
|
|
254
|
+
const childrenToProcess = children.length > maxChildren ? children.slice(0, maxChildren) : children;
|
|
255
|
+
if (childrenToProcess.length < children.length && entry.metadata) entry.metadata.childrenTruncated = true;
|
|
256
|
+
for (const child of childrenToProcess) {
|
|
257
|
+
const childPath = itemPath === "/" ? `/${child.key}` : `${itemPath}/${child.key}`;
|
|
258
|
+
queue.push({
|
|
259
|
+
path: childPath,
|
|
260
|
+
value: child.value,
|
|
261
|
+
depth: depth + 1
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return { data: entries };
|
|
267
|
+
}
|
|
268
|
+
async read(path, _options) {
|
|
269
|
+
await this.ensureLoaded();
|
|
270
|
+
const normalizedPath = this.normalizePath(path);
|
|
271
|
+
const segments = this.getPathSegments(normalizedPath);
|
|
272
|
+
const value = this.getValueAtPath(this.jsonData, segments);
|
|
273
|
+
if (value === void 0) return {
|
|
274
|
+
data: void 0,
|
|
275
|
+
message: `Path not found: ${normalizedPath}`
|
|
276
|
+
};
|
|
277
|
+
return { data: this.valueToAFSEntry(normalizedPath, value) };
|
|
278
|
+
}
|
|
279
|
+
async write(path, entry, _options) {
|
|
280
|
+
await this.ensureLoaded();
|
|
281
|
+
const normalizedPath = this.normalizePath(path);
|
|
282
|
+
const segments = this.getPathSegments(normalizedPath);
|
|
283
|
+
this.setValueAtPath(this.jsonData, segments, entry.content);
|
|
284
|
+
await this.saveToFile();
|
|
285
|
+
const newValue = this.getValueAtPath(this.jsonData, segments);
|
|
286
|
+
const isDir = this.isDirectory(newValue);
|
|
287
|
+
const children = isDir ? this.getChildren(newValue) : [];
|
|
288
|
+
return { data: {
|
|
289
|
+
id: normalizedPath,
|
|
290
|
+
path: normalizedPath,
|
|
291
|
+
content: entry.content,
|
|
292
|
+
summary: entry.summary,
|
|
293
|
+
description: entry.description,
|
|
294
|
+
createdAt: this.fileStats.birthtime,
|
|
295
|
+
updatedAt: this.fileStats.mtime,
|
|
296
|
+
metadata: {
|
|
297
|
+
...entry.metadata,
|
|
298
|
+
type: isDir ? "directory" : "file",
|
|
299
|
+
childrenCount: isDir ? children.length : void 0
|
|
300
|
+
},
|
|
301
|
+
userId: entry.userId,
|
|
302
|
+
sessionId: entry.sessionId,
|
|
303
|
+
linkTo: entry.linkTo
|
|
304
|
+
} };
|
|
305
|
+
}
|
|
306
|
+
async delete(path, options) {
|
|
307
|
+
await this.ensureLoaded();
|
|
308
|
+
const normalizedPath = this.normalizePath(path);
|
|
309
|
+
const segments = this.getPathSegments(normalizedPath);
|
|
310
|
+
const value = this.getValueAtPath(this.jsonData, segments);
|
|
311
|
+
if (value === void 0) throw new Error(`Path not found: ${normalizedPath}`);
|
|
312
|
+
if (this.isDirectory(value) && this.getChildren(value).length > 0 && !options?.recursive) throw new Error(`Cannot delete directory '${normalizedPath}' without recursive option. Set recursive: true to delete directories.`);
|
|
313
|
+
this.deleteValueAtPath(this.jsonData, segments);
|
|
314
|
+
await this.saveToFile();
|
|
315
|
+
return { message: `Successfully deleted: ${normalizedPath}` };
|
|
316
|
+
}
|
|
317
|
+
async rename(oldPath, newPath, options) {
|
|
318
|
+
await this.ensureLoaded();
|
|
319
|
+
const normalizedOldPath = this.normalizePath(oldPath);
|
|
320
|
+
const normalizedNewPath = this.normalizePath(newPath);
|
|
321
|
+
const oldSegments = this.getPathSegments(normalizedOldPath);
|
|
322
|
+
const newSegments = this.getPathSegments(normalizedNewPath);
|
|
323
|
+
const oldValue = this.getValueAtPath(this.jsonData, oldSegments);
|
|
324
|
+
if (oldValue === void 0) throw new Error(`Source path not found: ${normalizedOldPath}`);
|
|
325
|
+
if (this.getValueAtPath(this.jsonData, newSegments) !== void 0 && !options?.overwrite) throw new Error(`Destination '${normalizedNewPath}' already exists. Set overwrite: true to replace it.`);
|
|
326
|
+
this.setValueAtPath(this.jsonData, newSegments, oldValue);
|
|
327
|
+
this.deleteValueAtPath(this.jsonData, oldSegments);
|
|
328
|
+
await this.saveToFile();
|
|
329
|
+
return { message: `Successfully renamed '${normalizedOldPath}' to '${normalizedNewPath}'` };
|
|
330
|
+
}
|
|
331
|
+
async search(path, query, options) {
|
|
332
|
+
await this.ensureLoaded();
|
|
333
|
+
const normalizedPath = this.normalizePath(path);
|
|
334
|
+
const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
|
|
335
|
+
const caseSensitive = options?.caseSensitive ?? false;
|
|
336
|
+
const segments = this.getPathSegments(normalizedPath);
|
|
337
|
+
const rootValue = this.getValueAtPath(this.jsonData, segments);
|
|
338
|
+
if (rootValue === void 0) throw new Error(`Path not found: ${normalizedPath}`);
|
|
339
|
+
const entries = [];
|
|
340
|
+
const searchQuery = caseSensitive ? query : query.toLowerCase();
|
|
341
|
+
const searchInValue = (valuePath, value) => {
|
|
342
|
+
if (entries.length >= limit) return;
|
|
343
|
+
let matched = false;
|
|
344
|
+
if (!this.isDirectory(value)) {
|
|
345
|
+
const valueStr = typeof value === "string" ? value : JSON.stringify(value);
|
|
346
|
+
if ((caseSensitive ? valueStr : valueStr.toLowerCase()).includes(searchQuery)) matched = true;
|
|
347
|
+
}
|
|
348
|
+
if (matched) entries.push(this.valueToAFSEntry(valuePath, value));
|
|
349
|
+
if (this.isDirectory(value)) {
|
|
350
|
+
const children = this.getChildren(value);
|
|
351
|
+
for (const child of children) {
|
|
352
|
+
if (entries.length >= limit) break;
|
|
353
|
+
searchInValue(valuePath === "/" ? `/${child.key}` : `${valuePath}/${child.key}`, child.value);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
searchInValue(normalizedPath, rootValue);
|
|
358
|
+
return {
|
|
359
|
+
data: entries,
|
|
360
|
+
message: entries.length >= limit ? `Results truncated to limit ${limit}` : void 0
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
//#endregion
|
|
366
|
+
exports.AFSJSON = AFSJSON;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { AFSAccessMode, AFSDeleteOptions, AFSDeleteResult, AFSListOptions, AFSListResult, AFSModule, AFSModuleLoadParams, AFSReadOptions, AFSReadResult, AFSRenameOptions, AFSRenameResult, AFSSearchOptions, AFSSearchResult, AFSWriteEntryPayload, AFSWriteOptions, AFSWriteResult } from "@aigne/afs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/index.d.ts
|
|
5
|
+
interface AFSJSONOptions {
|
|
6
|
+
name?: string;
|
|
7
|
+
jsonPath: string;
|
|
8
|
+
description?: string;
|
|
9
|
+
/**
|
|
10
|
+
* Access mode for this module.
|
|
11
|
+
* - "readonly": Only read operations are allowed
|
|
12
|
+
* - "readwrite": All operations are allowed (default, unless agentSkills is enabled)
|
|
13
|
+
* @default "readwrite" (or "readonly" when agentSkills is true)
|
|
14
|
+
*/
|
|
15
|
+
accessMode?: AFSAccessMode;
|
|
16
|
+
/**
|
|
17
|
+
* Enable automatic agent skill scanning for this module.
|
|
18
|
+
* When enabled, defaults accessMode to "readonly" if not explicitly set.
|
|
19
|
+
* @default false
|
|
20
|
+
*/
|
|
21
|
+
agentSkills?: boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* AFS module for mounting JSON/YAML files as virtual file systems.
|
|
25
|
+
*
|
|
26
|
+
* JSON/YAML objects are treated as directories, and properties/array items as files.
|
|
27
|
+
* Supports nested structures and path-based access to data values.
|
|
28
|
+
*/
|
|
29
|
+
declare class AFSJSON implements AFSModule {
|
|
30
|
+
options: AFSJSONOptions & {
|
|
31
|
+
cwd?: string;
|
|
32
|
+
};
|
|
33
|
+
static schema(): z.ZodEffects<z.ZodObject<{
|
|
34
|
+
name: z.ZodType<string | undefined, z.ZodTypeDef, string | undefined>;
|
|
35
|
+
jsonPath: z.ZodString;
|
|
36
|
+
description: z.ZodType<string | undefined, z.ZodTypeDef, string | undefined>;
|
|
37
|
+
accessMode: z.ZodType<"readonly" | "readwrite" | undefined, z.ZodTypeDef, "readonly" | "readwrite" | undefined>;
|
|
38
|
+
agentSkills: z.ZodType<boolean | undefined, z.ZodTypeDef, boolean | undefined>;
|
|
39
|
+
}, "strip", z.ZodTypeAny, {
|
|
40
|
+
jsonPath: string;
|
|
41
|
+
name?: string | undefined;
|
|
42
|
+
description?: string | undefined;
|
|
43
|
+
accessMode?: "readonly" | "readwrite" | undefined;
|
|
44
|
+
agentSkills?: boolean | undefined;
|
|
45
|
+
}, {
|
|
46
|
+
jsonPath: string;
|
|
47
|
+
name?: string | undefined;
|
|
48
|
+
description?: string | undefined;
|
|
49
|
+
accessMode?: "readonly" | "readwrite" | undefined;
|
|
50
|
+
agentSkills?: boolean | undefined;
|
|
51
|
+
}>, {
|
|
52
|
+
jsonPath: string;
|
|
53
|
+
name?: string | undefined;
|
|
54
|
+
description?: string | undefined;
|
|
55
|
+
accessMode?: "readonly" | "readwrite" | undefined;
|
|
56
|
+
agentSkills?: boolean | undefined;
|
|
57
|
+
}, any>;
|
|
58
|
+
static load({
|
|
59
|
+
filepath,
|
|
60
|
+
parsed
|
|
61
|
+
}: AFSModuleLoadParams): Promise<AFSJSON>;
|
|
62
|
+
private jsonData;
|
|
63
|
+
private fileStats;
|
|
64
|
+
private fileFormat;
|
|
65
|
+
constructor(options: AFSJSONOptions & {
|
|
66
|
+
cwd?: string;
|
|
67
|
+
});
|
|
68
|
+
name: string;
|
|
69
|
+
description?: string;
|
|
70
|
+
accessMode: AFSAccessMode;
|
|
71
|
+
agentSkills?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Load JSON/YAML data from file. Called lazily on first access.
|
|
74
|
+
* Uses YAML parser which can handle both JSON and YAML formats.
|
|
75
|
+
*/
|
|
76
|
+
private ensureLoaded;
|
|
77
|
+
/**
|
|
78
|
+
* Save JSON/YAML data back to file. Only called in readwrite mode.
|
|
79
|
+
*/
|
|
80
|
+
private saveToFile;
|
|
81
|
+
/**
|
|
82
|
+
* Normalize path to ensure consistent format
|
|
83
|
+
*/
|
|
84
|
+
private normalizePath;
|
|
85
|
+
/**
|
|
86
|
+
* Get path segments from normalized path
|
|
87
|
+
*/
|
|
88
|
+
private getPathSegments;
|
|
89
|
+
/**
|
|
90
|
+
* Navigate to a value in the JSON structure using path segments
|
|
91
|
+
*/
|
|
92
|
+
private getValueAtPath;
|
|
93
|
+
/**
|
|
94
|
+
* Set a value in the JSON structure at the given path
|
|
95
|
+
*/
|
|
96
|
+
private setValueAtPath;
|
|
97
|
+
/**
|
|
98
|
+
* Delete a value from the JSON structure at the given path
|
|
99
|
+
*/
|
|
100
|
+
private deleteValueAtPath;
|
|
101
|
+
/**
|
|
102
|
+
* Check if a value is a "directory" (object or array with children)
|
|
103
|
+
*/
|
|
104
|
+
private isDirectory;
|
|
105
|
+
/**
|
|
106
|
+
* Get children of a directory value
|
|
107
|
+
*/
|
|
108
|
+
private getChildren;
|
|
109
|
+
/**
|
|
110
|
+
* Convert a JSON value to an AFSEntry
|
|
111
|
+
*/
|
|
112
|
+
private valueToAFSEntry;
|
|
113
|
+
list(path: string, options?: AFSListOptions): Promise<AFSListResult>;
|
|
114
|
+
read(path: string, _options?: AFSReadOptions): Promise<AFSReadResult>;
|
|
115
|
+
write(path: string, entry: AFSWriteEntryPayload, _options?: AFSWriteOptions): Promise<AFSWriteResult>;
|
|
116
|
+
delete(path: string, options?: AFSDeleteOptions): Promise<AFSDeleteResult>;
|
|
117
|
+
rename(oldPath: string, newPath: string, options?: AFSRenameOptions): Promise<AFSRenameResult>;
|
|
118
|
+
search(path: string, query: string, options?: AFSSearchOptions): Promise<AFSSearchResult>;
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
export { AFSJSON, AFSJSONOptions };
|
|
122
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;UA4BiB,cAAA;EAAA,IAAA;EAAA,QAAA;EAAA,WAAA;EAAA;AAuCjB;;;;;EAvCiB,UAAA,GAUF,aAAA;EAAA;AA6Bf;;;;EA7Be,WAAA;AAAA;AAAA;AA6Bf;;;;;AA7Be,cA6BF,OAAA,YAAmB,SAAA;EAAA,OAAA,EAiBF,cAAA;IAAA,GAAA;EAAA;EAAA,OAAA,OAAA,GAhBf,CAAA,CAAA,UAAA,CAAA,CAAA,CAAA,SAAA;IAAA,IAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;KAI2B,mBAAA,GAAmB,OAAA,CAAA,OAAA;EAAA,QAAA,QAAA;EAAA,QAAA,SAAA;EAAA,QAAA,UAAA;EAAA,YAAA,OAAA,EAY/B,cAAA;IAAA,GAAA;EAAA;EAAA,IAAA;EAAA,WAAA;EAAA,UAAA,EAwChB,aAAA;EAAA,WAAA;EAAA;;;;EAAA,QAAA,YAAA;EAAA;;;EAAA,QAAA,UAAA;EAAA;;;EAAA,QAAA,aAAA;EAAA;;;EAAA,QAAA,eAAA;EAAA;;;EAAA,QAAA,cAAA;EAAA;;;EAAA,QAAA,cAAA;EAAA;;;EAAA,QAAA,iBAAA;EAAA;;;EAAA,QAAA,WAAA;EAAA;;;EAAA,QAAA,WAAA;EAAA;;;EAAA,QAAA,eAAA;EAAA,KAAA,IAAA,UAAA,OAAA,GAkPuB,cAAA,GAAiB,OAAA,CAAQ,aAAA;EAAA,KAAA,IAAA,UAAA,QAAA,GAmExB,cAAA,GAAiB,OAAA,CAAQ,aAAA;EAAA,MAAA,IAAA,UAAA,KAAA,EAmBpD,oBAAA,EAAA,QAAA,GACI,eAAA,GACV,OAAA,CAAQ,cAAA;EAAA,OAAA,IAAA,UAAA,OAAA,GAqC0B,gBAAA,GAAmB,OAAA,CAAQ,eAAA;EAAA,OAAA,OAAA,UAAA,OAAA,UAAA,OAAA,GA2BpD,gBAAA,GACT,OAAA,CAAQ,eAAA;EAAA,OAAA,IAAA,UAAA,KAAA,UAAA,OAAA,GA+ByC,gBAAA,GAAmB,OAAA,CAAQ,eAAA;AAAA"}
|