@aigne/afs-json 1.11.0-beta.5 → 1.11.0-beta.7

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/dist/index.cjs CHANGED
@@ -1,11 +1,22 @@
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+ const require_decorate = require('./_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.cjs');
1
3
  let node_fs_promises = require("node:fs/promises");
2
4
  let node_path = require("node:path");
5
+ let _aigne_afs = require("@aigne/afs");
6
+ let _aigne_afs_provider = require("@aigne/afs/provider");
3
7
  let _aigne_afs_utils_zod = require("@aigne/afs/utils/zod");
8
+ let ufo = require("ufo");
4
9
  let yaml = require("yaml");
5
10
  let zod = require("zod");
6
11
 
7
12
  //#region src/index.ts
8
13
  const LIST_MAX_LIMIT = 1e3;
14
+ /** Hidden key for storing AFS metadata (mirrors FS provider's .afs directory) */
15
+ const AFS_KEY = ".afs";
16
+ /** Subkey for storing metadata (mirrors FS provider's meta.yaml file) */
17
+ const META_KEY = "meta";
18
+ /** Subkey for storing child node metadata (mirrors FS provider's .nodes directory) */
19
+ const NODES_KEY = ".nodes";
9
20
  const afsJSONOptionsSchema = (0, _aigne_afs_utils_zod.camelize)(zod.z.object({
10
21
  name: (0, _aigne_afs_utils_zod.optionalize)(zod.z.string()),
11
22
  jsonPath: zod.z.string().describe("The path to the JSON/YAML file to mount"),
@@ -19,20 +30,26 @@ const afsJSONOptionsSchema = (0, _aigne_afs_utils_zod.camelize)(zod.z.object({
19
30
  * JSON/YAML objects are treated as directories, and properties/array items as files.
20
31
  * Supports nested structures and path-based access to data values.
21
32
  */
22
- var AFSJSON = class AFSJSON {
33
+ var AFSJSON = class AFSJSON extends _aigne_afs_provider.AFSBaseProvider {
23
34
  static schema() {
24
35
  return afsJSONOptionsSchema;
25
36
  }
26
- static async load({ filepath, parsed }) {
37
+ static async load({ basePath, config } = {}) {
27
38
  return new AFSJSON({
28
- ...await AFSJSON.schema().parseAsync(parsed),
29
- cwd: (0, node_path.dirname)(filepath)
39
+ ...await AFSJSON.schema().parseAsync(config),
40
+ cwd: basePath
30
41
  });
31
42
  }
43
+ name;
44
+ description;
45
+ accessMode;
46
+ agentSkills;
32
47
  jsonData = null;
33
48
  fileStats = {};
34
49
  fileFormat = "json";
50
+ resolvedJsonPath;
35
51
  constructor(options) {
52
+ super();
36
53
  this.options = options;
37
54
  (0, _aigne_afs_utils_zod.zodParse)(afsJSONOptionsSchema, options);
38
55
  let jsonPath;
@@ -55,12 +72,400 @@ var AFSJSON = class AFSJSON {
55
72
  this.description = options.description;
56
73
  this.agentSkills = options.agentSkills;
57
74
  this.accessMode = options.accessMode ?? (options.agentSkills ? "readonly" : "readwrite");
58
- this.options.jsonPath = jsonPath;
75
+ this.resolvedJsonPath = jsonPath;
76
+ }
77
+ /**
78
+ * Read metadata for a JSON node via /.meta or /path/.meta
79
+ * Returns stored metadata merged with computed type information
80
+ * Note: Meta is read-only. To write metadata, use write() with payload.meta.
81
+ */
82
+ async readMetaHandler(ctx) {
83
+ await this.ensureLoaded();
84
+ const nodePath = (0, ufo.joinURL)("/", ctx.params.path ?? "");
85
+ const segments = this.getPathSegments(nodePath);
86
+ const value = this.getValueAtPath(this.jsonData, segments);
87
+ if (value === void 0) throw new _aigne_afs.AFSNotFoundError(nodePath);
88
+ const isDir = this.isDirectoryValue(value);
89
+ const children = isDir ? this.getChildren(value) : [];
90
+ let type;
91
+ if (Array.isArray(value)) type = "array";
92
+ else if (value === null) type = "null";
93
+ else if (typeof value === "object") type = "object";
94
+ else type = typeof value;
95
+ const storedMeta = this.loadMeta(nodePath) || {};
96
+ const computedMeta = {
97
+ type,
98
+ path: nodePath
99
+ };
100
+ if (isDir) {
101
+ computedMeta.childrenCount = children.length;
102
+ if (Array.isArray(value)) computedMeta.length = value.length;
103
+ else computedMeta.keys = Object.keys(value).filter((k) => !this.isMetaKey(k));
104
+ } else computedMeta.value = value;
105
+ if (this.fileStats.birthtime) computedMeta.created = this.fileStats.birthtime;
106
+ if (this.fileStats.mtime) computedMeta.modified = this.fileStats.mtime;
107
+ return this.buildEntry((0, ufo.joinURL)(nodePath, ".meta"), {
108
+ meta: storedMeta,
109
+ content: computedMeta,
110
+ createdAt: this.fileStats.birthtime,
111
+ updatedAt: this.fileStats.mtime
112
+ });
113
+ }
114
+ async listHandler(ctx) {
115
+ await this.ensureLoaded();
116
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
117
+ const options = ctx.options;
118
+ const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
119
+ const maxChildren = typeof options?.maxChildren === "number" ? options.maxChildren : Number.MAX_SAFE_INTEGER;
120
+ const maxDepth = options?.maxDepth ?? 1;
121
+ const segments = this.getPathSegments(normalizedPath);
122
+ const value = this.getValueAtPath(this.jsonData, segments);
123
+ if (value === void 0) throw new _aigne_afs.AFSNotFoundError(normalizedPath);
124
+ if (maxDepth === 0) return { data: [] };
125
+ if (!this.isDirectoryValue(value)) return { data: [] };
126
+ const entries = [];
127
+ const rootChildren = this.getChildren(value);
128
+ const queue = (rootChildren.length > maxChildren ? rootChildren.slice(0, maxChildren) : rootChildren).map((child) => ({
129
+ path: normalizedPath === "/" ? `/${child.key}` : `${normalizedPath}/${child.key}`,
130
+ value: child.value,
131
+ depth: 1
132
+ }));
133
+ while (queue.length > 0) {
134
+ const item = queue.shift();
135
+ if (!item) break;
136
+ const { path: itemPath, value: itemValue, depth } = item;
137
+ const entry = this.valueToAFSEntry(itemPath, itemValue);
138
+ entries.push(entry);
139
+ if (entries.length >= limit) break;
140
+ if (this.isDirectoryValue(itemValue) && depth < maxDepth) {
141
+ const children = this.getChildren(itemValue);
142
+ const childrenToProcess = children.length > maxChildren ? children.slice(0, maxChildren) : children;
143
+ for (const child of childrenToProcess) {
144
+ const childPath = itemPath === "/" ? `/${child.key}` : `${itemPath}/${child.key}`;
145
+ queue.push({
146
+ path: childPath,
147
+ value: child.value,
148
+ depth: depth + 1
149
+ });
150
+ }
151
+ }
152
+ }
153
+ return { data: entries };
154
+ }
155
+ async readHandler(ctx) {
156
+ await this.ensureLoaded();
157
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
158
+ const segments = this.getPathSegments(normalizedPath);
159
+ const value = this.getValueAtPath(this.jsonData, segments);
160
+ if (value === void 0) throw new _aigne_afs.AFSNotFoundError(normalizedPath);
161
+ return this.valueToAFSEntry(normalizedPath, value);
162
+ }
163
+ /**
164
+ * Write handler - supports writing content and/or metadata
165
+ *
166
+ * | payload | behavior |
167
+ * |---------|----------|
168
+ * | { content } | write content only |
169
+ * | { metadata } | write metadata only (to .afs storage) |
170
+ * | { content, metadata } | write both |
171
+ */
172
+ async writeHandler(ctx, payload) {
173
+ await this.ensureLoaded();
174
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
175
+ const segments = this.getPathSegments(normalizedPath);
176
+ if (payload.content !== void 0) this.setValueAtPath(this.jsonData, segments, payload.content);
177
+ if (payload.meta !== void 0 && typeof payload.meta === "object") {
178
+ const finalMeta = {
179
+ ...this.loadMeta(normalizedPath) || {},
180
+ ...payload.meta
181
+ };
182
+ this.saveMeta(normalizedPath, finalMeta);
183
+ }
184
+ await this.saveToFile();
185
+ const newValue = this.getValueAtPath(this.jsonData, segments);
186
+ const isDir = this.isDirectoryValue(newValue);
187
+ const children = isDir ? this.getChildren(newValue) : [];
188
+ const storedMeta = this.loadMeta(normalizedPath) || {};
189
+ return { data: {
190
+ id: normalizedPath,
191
+ path: normalizedPath,
192
+ content: payload.content !== void 0 ? payload.content : newValue,
193
+ summary: payload.summary,
194
+ createdAt: this.fileStats.birthtime,
195
+ updatedAt: this.fileStats.mtime,
196
+ meta: {
197
+ ...storedMeta,
198
+ childrenCount: isDir ? children.length : void 0
199
+ },
200
+ userId: payload.userId,
201
+ sessionId: payload.sessionId,
202
+ linkTo: payload.linkTo
203
+ } };
204
+ }
205
+ async deleteHandler(ctx) {
206
+ await this.ensureLoaded();
207
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
208
+ const options = ctx.options;
209
+ const segments = this.getPathSegments(normalizedPath);
210
+ const value = this.getValueAtPath(this.jsonData, segments);
211
+ if (value === void 0) throw new _aigne_afs.AFSNotFoundError(normalizedPath);
212
+ if (this.isDirectoryValue(value) && this.getChildren(value).length > 0 && !options?.recursive) throw new Error(`Cannot delete directory '${normalizedPath}' without recursive option. Set recursive: true to delete directories.`);
213
+ this.deleteValueAtPath(this.jsonData, segments);
214
+ await this.saveToFile();
215
+ return { message: `Successfully deleted: ${normalizedPath}` };
216
+ }
217
+ async renameHandler(ctx, newPath) {
218
+ await this.ensureLoaded();
219
+ const normalizedOldPath = ctx.params.path ? `/${ctx.params.path}` : "/";
220
+ const normalizedNewPath = this.normalizePath(newPath);
221
+ const options = ctx.options;
222
+ const oldSegments = this.getPathSegments(normalizedOldPath);
223
+ const newSegments = this.getPathSegments(normalizedNewPath);
224
+ const oldValue = this.getValueAtPath(this.jsonData, oldSegments);
225
+ if (oldValue === void 0) throw new _aigne_afs.AFSNotFoundError(normalizedOldPath);
226
+ if (this.getValueAtPath(this.jsonData, newSegments) !== void 0 && !options?.overwrite) throw new Error(`Destination '${normalizedNewPath}' already exists. Set overwrite: true to replace it.`);
227
+ this.setValueAtPath(this.jsonData, newSegments, oldValue);
228
+ this.deleteValueAtPath(this.jsonData, oldSegments);
229
+ await this.saveToFile();
230
+ return { message: `Successfully renamed '${normalizedOldPath}' to '${normalizedNewPath}'` };
231
+ }
232
+ async searchHandler(ctx, query, options) {
233
+ await this.ensureLoaded();
234
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
235
+ const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
236
+ const caseSensitive = options?.caseSensitive ?? false;
237
+ const segments = this.getPathSegments(normalizedPath);
238
+ const rootValue = this.getValueAtPath(this.jsonData, segments);
239
+ if (rootValue === void 0) throw new _aigne_afs.AFSNotFoundError(normalizedPath);
240
+ const entries = [];
241
+ const searchQuery = caseSensitive ? query : query.toLowerCase();
242
+ const searchInValue = (valuePath, value) => {
243
+ if (entries.length >= limit) return;
244
+ let matched = false;
245
+ if (!this.isDirectoryValue(value)) {
246
+ const valueStr = typeof value === "string" ? value : JSON.stringify(value);
247
+ if ((caseSensitive ? valueStr : valueStr.toLowerCase()).includes(searchQuery)) matched = true;
248
+ }
249
+ if (matched) entries.push(this.valueToAFSEntry(valuePath, value));
250
+ if (this.isDirectoryValue(value)) {
251
+ const children = this.getChildren(value);
252
+ for (const child of children) {
253
+ if (entries.length >= limit) break;
254
+ searchInValue(valuePath === "/" ? `/${child.key}` : `${valuePath}/${child.key}`, child.value);
255
+ }
256
+ }
257
+ };
258
+ searchInValue(normalizedPath, rootValue);
259
+ return {
260
+ data: entries,
261
+ message: entries.length >= limit ? `Results truncated to limit ${limit}` : void 0
262
+ };
263
+ }
264
+ async statHandler(ctx) {
265
+ await this.ensureLoaded();
266
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
267
+ const segments = this.getPathSegments(normalizedPath);
268
+ const value = this.getValueAtPath(this.jsonData, segments);
269
+ if (value === void 0) throw new _aigne_afs.AFSNotFoundError(normalizedPath);
270
+ const isDir = this.isDirectoryValue(value);
271
+ const children = isDir ? this.getChildren(value) : [];
272
+ const meta = { ...this.loadMeta(normalizedPath) };
273
+ if (isDir) meta.childrenCount = children.length;
274
+ return { data: {
275
+ id: segments.length > 0 ? segments[segments.length - 1] : "/",
276
+ path: normalizedPath,
277
+ createdAt: this.fileStats.birthtime,
278
+ updatedAt: this.fileStats.mtime,
279
+ meta
280
+ } };
281
+ }
282
+ async readCapabilitiesHandler(_ctx) {
283
+ await this.ensureLoaded();
284
+ const operations = [
285
+ "list",
286
+ "read",
287
+ "stat",
288
+ "explain",
289
+ "search"
290
+ ];
291
+ if (this.accessMode === "readwrite") operations.push("write", "delete", "rename");
292
+ return {
293
+ id: "/.meta/.capabilities",
294
+ path: "/.meta/.capabilities",
295
+ content: {
296
+ schemaVersion: 1,
297
+ provider: this.name,
298
+ description: this.description || `JSON/YAML virtual filesystem (${this.fileFormat} format)`,
299
+ tools: [],
300
+ actions: [],
301
+ operations: this.getOperationsDeclaration()
302
+ },
303
+ meta: {
304
+ kind: "afs:capabilities",
305
+ operations
306
+ }
307
+ };
308
+ }
309
+ async explainHandler(ctx) {
310
+ await this.ensureLoaded();
311
+ const normalizedPath = (0, ufo.joinURL)("/", ctx.params.path ?? "");
312
+ const format = ctx.options?.format || "markdown";
313
+ const segments = this.getPathSegments(normalizedPath);
314
+ const value = this.getValueAtPath(this.jsonData, segments);
315
+ if (value === void 0) throw new _aigne_afs.AFSNotFoundError(normalizedPath);
316
+ const nodeName = segments.length > 0 ? segments[segments.length - 1] : "/";
317
+ const isDir = this.isDirectoryValue(value);
318
+ const storedMeta = this.loadMeta(normalizedPath);
319
+ const lines = [];
320
+ if (format === "markdown") {
321
+ lines.push(`# ${nodeName}`);
322
+ lines.push("");
323
+ lines.push(`**Path:** \`${normalizedPath}\``);
324
+ lines.push(`**Format:** ${this.fileFormat.toUpperCase()}`);
325
+ if (normalizedPath === "/") {
326
+ const topType = Array.isArray(this.jsonData) ? "array" : "object";
327
+ const children = this.getChildren(this.jsonData);
328
+ lines.push(`**Structure:** ${topType}`);
329
+ lines.push(`**Top-level keys:** ${children.length}`);
330
+ if (children.length > 0) {
331
+ lines.push("");
332
+ lines.push("## Keys");
333
+ lines.push("");
334
+ for (const child of children.slice(0, 30)) {
335
+ const childVal = child.value;
336
+ const childType = this.describeType(childVal);
337
+ lines.push(`- \`${child.key}\` — ${childType}`);
338
+ }
339
+ if (children.length > 30) lines.push(`- ... and ${children.length - 30} more`);
340
+ }
341
+ } else if (Array.isArray(value)) {
342
+ lines.push(`**Type:** array`);
343
+ lines.push(`**Elements:** ${value.length}`);
344
+ if (value.length > 0) {
345
+ const elementType = this.describeType(value[0]);
346
+ const isHomogeneous = value.every((v) => this.describeType(v) === elementType);
347
+ lines.push(`**Element type:** ${isHomogeneous ? elementType : "mixed"}`);
348
+ }
349
+ } else if (typeof value === "object" && value !== null) {
350
+ const children = this.getChildren(value);
351
+ lines.push(`**Type:** object`);
352
+ lines.push(`**Keys:** ${children.length}`);
353
+ if (children.length > 0) {
354
+ lines.push("");
355
+ lines.push("## Keys");
356
+ lines.push("");
357
+ for (const child of children.slice(0, 30)) {
358
+ const childType = this.describeType(child.value);
359
+ lines.push(`- \`${child.key}\` — ${childType}`);
360
+ }
361
+ if (children.length > 30) lines.push(`- ... and ${children.length - 30} more`);
362
+ }
363
+ } else {
364
+ const valType = value === null ? "null" : typeof value;
365
+ lines.push(`**Type:** ${valType}`);
366
+ const valStr = String(value);
367
+ if (valStr.length > 200) lines.push(`**Value:** ${valStr.slice(0, 200)}...`);
368
+ else lines.push(`**Value:** ${valStr}`);
369
+ }
370
+ if (storedMeta) {
371
+ lines.push("");
372
+ lines.push("## Metadata");
373
+ for (const [key, val] of Object.entries(storedMeta)) lines.push(`- **${key}:** ${JSON.stringify(val)}`);
374
+ }
375
+ } else {
376
+ lines.push(`${nodeName} (${isDir ? "directory" : "value"})`);
377
+ lines.push(`Path: ${normalizedPath}`);
378
+ lines.push(`Format: ${this.fileFormat}`);
379
+ if (isDir) {
380
+ const children = this.getChildren(value);
381
+ lines.push(`Children: ${children.length}`);
382
+ } else {
383
+ const valStr = String(value);
384
+ lines.push(`Type: ${value === null ? "null" : typeof value}`);
385
+ lines.push(`Value: ${valStr.length > 200 ? `${valStr.slice(0, 200)}...` : valStr}`);
386
+ }
387
+ }
388
+ return {
389
+ content: lines.join("\n"),
390
+ format
391
+ };
392
+ }
393
+ /**
394
+ * Get a human-readable type description for a JSON value.
395
+ */
396
+ describeType(value) {
397
+ if (value === null) return "null";
398
+ if (Array.isArray(value)) return `array[${value.length}]`;
399
+ if (typeof value === "object") return `object{${Object.keys(value).filter((k) => !this.isMetaKey(k)).length} keys}`;
400
+ return typeof value;
401
+ }
402
+ /**
403
+ * Check if a key is a hidden meta key that should be filtered from listings
404
+ */
405
+ isMetaKey(key) {
406
+ return key === AFS_KEY;
407
+ }
408
+ /**
409
+ * Load metadata for a node.
410
+ *
411
+ * Storage location depends on node type (mirrors FS provider's .afs structure):
412
+ * - Objects: `.afs.meta` key within the object itself
413
+ * - Primitives: parent's `.afs[".nodes"][key].meta`
414
+ */
415
+ loadMeta(nodePath) {
416
+ const segments = this.getPathSegments(nodePath);
417
+ const value = this.getValueAtPath(this.jsonData, segments);
418
+ if (value === void 0) return null;
419
+ if (this.isDirectoryValue(value) && !Array.isArray(value)) {
420
+ const afs$1 = value[AFS_KEY];
421
+ if (afs$1 && typeof afs$1 === "object" && !Array.isArray(afs$1)) {
422
+ const meta$1 = afs$1[META_KEY];
423
+ if (meta$1 && typeof meta$1 === "object" && !Array.isArray(meta$1)) return meta$1;
424
+ }
425
+ return null;
426
+ }
427
+ if (segments.length === 0) return null;
428
+ const parentSegments = segments.slice(0, -1);
429
+ const nodeKey = segments[segments.length - 1];
430
+ const parentValue = this.getValueAtPath(this.jsonData, parentSegments);
431
+ if (!parentValue || Array.isArray(parentValue) || typeof parentValue !== "object") return null;
432
+ const afs = parentValue[AFS_KEY];
433
+ if (!afs || typeof afs !== "object" || Array.isArray(afs)) return null;
434
+ const nodes = afs[NODES_KEY];
435
+ if (!nodes || typeof nodes !== "object" || Array.isArray(nodes)) return null;
436
+ const nodeEntry = nodes[nodeKey];
437
+ if (!nodeEntry || typeof nodeEntry !== "object" || Array.isArray(nodeEntry)) return null;
438
+ const meta = nodeEntry[META_KEY];
439
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
440
+ return meta;
441
+ }
442
+ /**
443
+ * Save metadata for a node.
444
+ *
445
+ * Storage location depends on node type (mirrors FS provider's .afs structure):
446
+ * - Objects: `.afs.meta` key within the object itself
447
+ * - Primitives: parent's `.afs[".nodes"][key].meta`
448
+ */
449
+ saveMeta(nodePath, meta) {
450
+ const segments = this.getPathSegments(nodePath);
451
+ const value = this.getValueAtPath(this.jsonData, segments);
452
+ if (value === void 0) throw new _aigne_afs.AFSNotFoundError(nodePath);
453
+ if (this.isDirectoryValue(value) && !Array.isArray(value)) {
454
+ if (!value[AFS_KEY]) value[AFS_KEY] = {};
455
+ value[AFS_KEY][META_KEY] = meta;
456
+ return;
457
+ }
458
+ if (segments.length === 0) throw new Error("Cannot save meta for root when root is not an object");
459
+ const parentSegments = segments.slice(0, -1);
460
+ const nodeKey = segments[segments.length - 1];
461
+ const parentValue = this.getValueAtPath(this.jsonData, parentSegments);
462
+ if (!parentValue || typeof parentValue !== "object") throw new Error(`Parent path is not an object`);
463
+ if (Array.isArray(parentValue)) throw new Error(`Cannot save meta for array elements`);
464
+ if (!parentValue[AFS_KEY]) parentValue[AFS_KEY] = {};
465
+ if (!parentValue[AFS_KEY][NODES_KEY]) parentValue[AFS_KEY][NODES_KEY] = {};
466
+ if (!parentValue[AFS_KEY][NODES_KEY][nodeKey]) parentValue[AFS_KEY][NODES_KEY][nodeKey] = {};
467
+ parentValue[AFS_KEY][NODES_KEY][nodeKey][META_KEY] = meta;
59
468
  }
60
- name;
61
- description;
62
- accessMode;
63
- agentSkills;
64
469
  /**
65
470
  * Load JSON/YAML data from file. Called lazily on first access.
66
471
  * Uses YAML parser which can handle both JSON and YAML formats.
@@ -68,12 +473,12 @@ var AFSJSON = class AFSJSON {
68
473
  async ensureLoaded() {
69
474
  if (this.jsonData !== null) return;
70
475
  try {
71
- const stats = await (0, node_fs_promises.stat)(this.options.jsonPath);
476
+ const stats = await (0, node_fs_promises.stat)(this.resolvedJsonPath);
72
477
  this.fileStats = {
73
478
  birthtime: stats.birthtime,
74
479
  mtime: stats.mtime
75
480
  };
76
- this.jsonData = (0, yaml.parse)(await (0, node_fs_promises.readFile)(this.options.jsonPath, "utf8"));
481
+ this.jsonData = (0, yaml.parse)(await (0, node_fs_promises.readFile)(this.resolvedJsonPath, "utf8"));
77
482
  } catch (error) {
78
483
  if (error.code === "ENOENT") this.jsonData = {};
79
484
  else throw error;
@@ -86,22 +491,14 @@ var AFSJSON = class AFSJSON {
86
491
  let content;
87
492
  if (this.fileFormat === "yaml") content = (0, yaml.stringify)(this.jsonData);
88
493
  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);
494
+ await (0, node_fs_promises.writeFile)(this.resolvedJsonPath, content, "utf8");
495
+ const stats = await (0, node_fs_promises.stat)(this.resolvedJsonPath);
91
496
  this.fileStats = {
92
497
  birthtime: this.fileStats.birthtime || stats.birthtime,
93
498
  mtime: stats.mtime
94
499
  };
95
500
  }
96
501
  /**
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
502
  * Get path segments from normalized path
106
503
  */
107
504
  getPathSegments(path) {
@@ -187,20 +584,20 @@ var AFSJSON = class AFSJSON {
187
584
  /**
188
585
  * Check if a value is a "directory" (object or array with children)
189
586
  */
190
- isDirectory(value) {
587
+ isDirectoryValue(value) {
191
588
  if (Array.isArray(value)) return true;
192
589
  if (typeof value === "object" && value !== null) return true;
193
590
  return false;
194
591
  }
195
592
  /**
196
- * Get children of a directory value
593
+ * Get children of a directory value (filters out .afs meta key)
197
594
  */
198
595
  getChildren(value) {
199
596
  if (Array.isArray(value)) return value.map((item, index) => ({
200
597
  key: String(index),
201
598
  value: item
202
599
  }));
203
- if (typeof value === "object" && value !== null) return Object.entries(value).map(([key, val]) => ({
600
+ if (typeof value === "object" && value !== null) return Object.entries(value).filter(([key]) => !this.isMetaKey(key)).map(([key, val]) => ({
204
601
  key,
205
602
  value: val
206
603
  }));
@@ -210,157 +607,32 @@ var AFSJSON = class AFSJSON {
210
607
  * Convert a JSON value to an AFSEntry
211
608
  */
212
609
  valueToAFSEntry(path, value) {
213
- const isDir = this.isDirectory(value);
610
+ const isDir = this.isDirectoryValue(value);
214
611
  const children = isDir ? this.getChildren(value) : [];
215
- return {
216
- id: path,
217
- path,
612
+ const kind = Array.isArray(value) ? "json:array" : isDir ? "json:object" : "json:value";
613
+ return this.buildEntry(path, {
218
614
  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",
615
+ meta: {
616
+ kind,
299
617
  childrenCount: isDir ? children.length : void 0
300
618
  },
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
- };
619
+ createdAt: this.fileStats.birthtime,
620
+ updatedAt: this.fileStats.mtime
621
+ });
362
622
  }
363
623
  };
624
+ require_decorate.__decorate([(0, _aigne_afs_provider.Meta)("/:path*")], AFSJSON.prototype, "readMetaHandler", null);
625
+ require_decorate.__decorate([(0, _aigne_afs_provider.List)("/:path*", { handleDepth: true })], AFSJSON.prototype, "listHandler", null);
626
+ require_decorate.__decorate([(0, _aigne_afs_provider.Read)("/:path*")], AFSJSON.prototype, "readHandler", null);
627
+ require_decorate.__decorate([(0, _aigne_afs_provider.Write)("/:path*")], AFSJSON.prototype, "writeHandler", null);
628
+ require_decorate.__decorate([(0, _aigne_afs_provider.Delete)("/:path*")], AFSJSON.prototype, "deleteHandler", null);
629
+ require_decorate.__decorate([(0, _aigne_afs_provider.Rename)("/:path*")], AFSJSON.prototype, "renameHandler", null);
630
+ require_decorate.__decorate([(0, _aigne_afs_provider.Search)("/:path*")], AFSJSON.prototype, "searchHandler", null);
631
+ require_decorate.__decorate([(0, _aigne_afs_provider.Stat)("/:path*")], AFSJSON.prototype, "statHandler", null);
632
+ require_decorate.__decorate([(0, _aigne_afs_provider.Read)("/.meta/.capabilities")], AFSJSON.prototype, "readCapabilitiesHandler", null);
633
+ require_decorate.__decorate([(0, _aigne_afs_provider.Explain)("/:path*")], AFSJSON.prototype, "explainHandler", null);
634
+ var src_default = AFSJSON;
364
635
 
365
636
  //#endregion
366
- exports.AFSJSON = AFSJSON;
637
+ exports.AFSJSON = AFSJSON;
638
+ exports.default = src_default;