data-path 1.0.0

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.js ADDED
@@ -0,0 +1,527 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ path: () => path,
24
+ unsafePath: () => unsafePath
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/constants.ts
29
+ var PATH_SEGMENTS = /* @__PURE__ */ Symbol("PATH_SEGMENTS");
30
+ var WILDCARD = "*";
31
+ var DEEP_WILDCARD = "**";
32
+
33
+ // src/utils.ts
34
+ function isCanonicalArrayIndex(key) {
35
+ const num = Number(key);
36
+ return Number.isInteger(num) && num >= 0 && num < 2 ** 32 && String(num) === key;
37
+ }
38
+ function resolveSegments(target) {
39
+ if (typeof target === "function") {
40
+ const proxy = createPathProxy([]);
41
+ const result = target(proxy);
42
+ return result?.[PATH_SEGMENTS] ?? [];
43
+ }
44
+ if (target && typeof target === "object" && "segments" in target) {
45
+ return target.segments;
46
+ }
47
+ return [];
48
+ }
49
+ function createPathProxy(segments) {
50
+ return new Proxy(
51
+ { [PATH_SEGMENTS]: segments },
52
+ {
53
+ get(target, key) {
54
+ if (key === PATH_SEGMENTS)
55
+ return target[PATH_SEGMENTS];
56
+ if (typeof key === "string" && key !== "Symbol") {
57
+ const next = isCanonicalArrayIndex(key) ? Number(key) : key;
58
+ return createPathProxy([...segments, next]);
59
+ }
60
+ return typeof key === "symbol" ? void 0 : createPathProxy(segments);
61
+ }
62
+ }
63
+ );
64
+ }
65
+ function segmentsEqual(a, b) {
66
+ if (a.length !== b.length) return false;
67
+ return a.every((s, i) => s === b[i]);
68
+ }
69
+ function matchesPrefix(full, prefix) {
70
+ if (prefix.length > full.length) return false;
71
+ let p = 0;
72
+ let f = 0;
73
+ while (p < prefix.length && f < full.length) {
74
+ if (prefix[p] === DEEP_WILDCARD) {
75
+ if (p === prefix.length - 1) return true;
76
+ const restPrefix = prefix.slice(p + 1);
77
+ for (let skip = 0; f + skip <= full.length; skip++) {
78
+ if (matchesPrefix(full.slice(f + skip), restPrefix)) return true;
79
+ }
80
+ return false;
81
+ }
82
+ if (prefix[p] !== WILDCARD && prefix[p] !== full[f]) return false;
83
+ p++;
84
+ f++;
85
+ }
86
+ return p === prefix.length;
87
+ }
88
+ function patternMatches(pattern, concrete) {
89
+ if (pattern.length !== concrete.length) return false;
90
+ for (let i = 0; i < pattern.length; i++) {
91
+ if (pattern[i] !== WILDCARD && pattern[i] !== DEEP_WILDCARD && pattern[i] !== concrete[i])
92
+ return false;
93
+ }
94
+ return true;
95
+ }
96
+
97
+ // src/impl/path-impl.ts
98
+ var TemplatePathCtor;
99
+ function setTemplatePathCtor(ctor) {
100
+ TemplatePathCtor = ctor;
101
+ }
102
+ var PathImpl = class _PathImpl {
103
+ segments;
104
+ constructor(segments) {
105
+ this.segments = segments;
106
+ }
107
+ /**
108
+ * The number of segments in this path.
109
+ */
110
+ get length() {
111
+ return this.segments.length;
112
+ }
113
+ /**
114
+ * The string representation of the path (e.g. "users.0.name").
115
+ * Useful for binding paths to form libraries or UI components.
116
+ *
117
+ * @example
118
+ * path<Root>().users[0].name.$; // "users.0.name"
119
+ */
120
+ get $() {
121
+ return this.toString();
122
+ }
123
+ /**
124
+ * Returns the string representation of the path (e.g. "users.0.name").
125
+ *
126
+ * @example
127
+ * path<Root>().users[0].name.toString(); // "users.0.name"
128
+ */
129
+ toString() {
130
+ return this.segments.join(".");
131
+ }
132
+ /**
133
+ * Extracts the value at this path from the given data object.
134
+ * Safely handles missing intermediate properties by returning `undefined` instead of throwing an error.
135
+ *
136
+ * @example
137
+ * const namePath = path<User>().name;
138
+ * const name = namePath.get({ name: "Alice" }); // "Alice"
139
+ */
140
+ get(data) {
141
+ let current = data;
142
+ for (const seg of this.segments) {
143
+ if (current == null) return void 0;
144
+ current = current[seg];
145
+ }
146
+ return current;
147
+ }
148
+ /**
149
+ * Returns an accessor function that extracts the value at this path from the given data object.
150
+ * Useful for array methods like `.map()` or `.filter()`.
151
+ *
152
+ * @example
153
+ * const names = users.map(path<User>().name.fn);
154
+ */
155
+ get fn() {
156
+ return (data) => this.get(data);
157
+ }
158
+ /**
159
+ * Sets the value at this path in the given data object, returning a new updated object (immutable).
160
+ * If intermediate properties are missing, they are automatically created as objects or arrays
161
+ * depending on the segment types (numeric keys become arrays).
162
+ *
163
+ * @example
164
+ * const namePath = path<User>().name;
165
+ * const updatedUser = namePath.set({ name: "Alice" }, "Bob"); // { name: "Bob" }
166
+ */
167
+ set(data, value) {
168
+ if (this.segments.length === 0) return value;
169
+ const setAt = (obj, segs, val) => {
170
+ if (segs.length === 1) {
171
+ const key = segs[0];
172
+ if (Array.isArray(obj)) {
173
+ const arr = [...obj];
174
+ arr[key] = val;
175
+ return arr;
176
+ }
177
+ return { ...obj, [key]: val };
178
+ }
179
+ const [first, ...rest] = segs;
180
+ const baseObj2 = obj;
181
+ const next = baseObj2[first];
182
+ const nextCopy = next != null && typeof next === "object" ? Array.isArray(next) ? [...next] : { ...next } : typeof rest[0] === "number" ? [] : {};
183
+ if (Array.isArray(baseObj2)) {
184
+ const arr = [...baseObj2];
185
+ arr[first] = setAt(nextCopy, rest, val);
186
+ return arr;
187
+ }
188
+ return { ...baseObj2, [first]: setAt(nextCopy, rest, val) };
189
+ };
190
+ const baseObj = typeof data === "object" && data !== null ? Array.isArray(data) ? [...data] : { ...data } : data;
191
+ return setAt(baseObj, this.segments, value);
192
+ }
193
+ /**
194
+ * Traverses into a collection (Array or Record) to operate on each item.
195
+ *
196
+ * @example
197
+ * const users = path<Root>().users;
198
+ * const userNames = users.each(u => u.name); // Path matches all names
199
+ */
200
+ each(expr) {
201
+ let tailSegments = [];
202
+ if (expr) {
203
+ const proxy = createPathProxy([]);
204
+ const result = expr(proxy);
205
+ tailSegments = result?.[PATH_SEGMENTS] ?? [];
206
+ }
207
+ return new TemplatePathCtor([...this.segments, WILDCARD, ...tailSegments]);
208
+ }
209
+ /**
210
+ * Traverses deeply into a structure, matching any nested property.
211
+ *
212
+ * @example
213
+ * const root = path<Root>();
214
+ * const allIds = root.deep(node => node.id); // Path matches any 'id' at any depth
215
+ */
216
+ deep(expr) {
217
+ let tailSegments = [];
218
+ if (expr) {
219
+ const proxy = createPathProxy([]);
220
+ const result = expr(proxy);
221
+ tailSegments = result?.[PATH_SEGMENTS] ?? [];
222
+ }
223
+ return new TemplatePathCtor([
224
+ ...this.segments,
225
+ DEEP_WILDCARD,
226
+ ...tailSegments
227
+ ]);
228
+ }
229
+ /**
230
+ * Checks if this path starts with the segments of another path.
231
+ *
232
+ * @example
233
+ * const a = path<Root>().users[0].name;
234
+ * const b = path<Root>().users;
235
+ * a.startsWith(b); // true
236
+ */
237
+ startsWith(other) {
238
+ return matchesPrefix(this.segments, resolveSegments(other));
239
+ }
240
+ /**
241
+ * Checks if this path encompasses the segments of another path (i.e., this path is a prefix of the other).
242
+ *
243
+ * @example
244
+ * const a = path<Root>().users;
245
+ * const b = path<Root>().users[0].name;
246
+ * a.includes(b); // true
247
+ */
248
+ includes(other) {
249
+ return matchesPrefix(resolveSegments(other), this.segments);
250
+ }
251
+ /**
252
+ * Checks if this path is exactly equal to another path.
253
+ *
254
+ * @example
255
+ * const a = path<Root>().users;
256
+ * const b = path<Root>().users;
257
+ * a.equals(b); // true
258
+ */
259
+ equals(other) {
260
+ return segmentsEqual(this.segments, resolveSegments(other));
261
+ }
262
+ /**
263
+ * Matches this path against another path, returning their relationship.
264
+ *
265
+ * @example
266
+ * const a = path<Root>().users[0];
267
+ * const b = path<Root>().users;
268
+ * a.match(b); // { relation: 'child', params: {} }
269
+ */
270
+ match(other) {
271
+ const otherSegs = resolveSegments(other);
272
+ if (segmentsEqual(this.segments, otherSegs)) {
273
+ return { relation: "equals", params: {} };
274
+ }
275
+ if (matchesPrefix(this.segments, otherSegs) && this.segments.length > otherSegs.length) {
276
+ return { relation: "child", params: {} };
277
+ }
278
+ if (matchesPrefix(otherSegs, this.segments) && otherSegs.length > this.segments.length) {
279
+ return { relation: "parent", params: {} };
280
+ }
281
+ if (patternMatches(this.segments, otherSegs)) {
282
+ return { relation: "includes", params: {} };
283
+ }
284
+ if (patternMatches(otherSegs, this.segments)) {
285
+ return { relation: "included-by", params: {} };
286
+ }
287
+ return null;
288
+ }
289
+ /**
290
+ * Appends another path to the end of this path. If the end of this path matches
291
+ * the beginning of the other path, the overlapping segments are intelligently deduplicated.
292
+ *
293
+ * @example
294
+ * const base = path<Root>().users;
295
+ * const full = base.merge(p => p[0].name); // equivalent to path<Root>().users[0].name
296
+ */
297
+ merge(other) {
298
+ const a = this.segments;
299
+ const b = resolveSegments(other);
300
+ let overlapLen = 0;
301
+ for (let len = Math.min(a.length, b.length); len >= 1; len--) {
302
+ const aSuffix = a.slice(-len);
303
+ const bPrefix = b.slice(0, len);
304
+ if (segmentsEqual(aSuffix, bPrefix)) {
305
+ overlapLen = len;
306
+ break;
307
+ }
308
+ }
309
+ const merged = overlapLen > 0 ? [...a.slice(0, -overlapLen), ...b] : [...a, ...b];
310
+ return new _PathImpl(merged);
311
+ }
312
+ /**
313
+ * Removes the segments of another path from either the beginning or the end of this path.
314
+ * Returns `null` if the other path is neither a prefix nor a suffix.
315
+ *
316
+ * @example
317
+ * const full = path<Root>().users[0].name;
318
+ * const base = path<Root>().users;
319
+ * const remainder = full.subtract(base); // equivalent to path()[0].name
320
+ */
321
+ subtract(other) {
322
+ const a = this.segments;
323
+ const b = resolveSegments(other);
324
+ if (b.length > a.length) return null;
325
+ if (segmentsEqual(a, b)) return new _PathImpl([]);
326
+ if (segmentsEqual(a.slice(0, b.length), b)) {
327
+ return new _PathImpl(a.slice(b.length));
328
+ }
329
+ if (segmentsEqual(a.slice(-b.length), b)) {
330
+ return new _PathImpl(a.slice(0, -b.length));
331
+ }
332
+ return null;
333
+ }
334
+ /**
335
+ * Returns a new path containing a subset of the segments, similar to Array.prototype.slice.
336
+ *
337
+ * @example
338
+ * const full = path<Root>().users[0].name;
339
+ * full.slice(0, 1); // equivalent to path<Root>().users
340
+ */
341
+ slice(start, end) {
342
+ const s = this.segments.slice(start, end);
343
+ return new _PathImpl(s);
344
+ }
345
+ /**
346
+ * Extends the current path using a lambda expression starting from the resolved value.
347
+ *
348
+ * @example
349
+ * const userPath = path<Root>().users[0];
350
+ * const namePath = userPath.to(u => u.name);
351
+ */
352
+ to(expr) {
353
+ const proxy = createPathProxy([]);
354
+ const result = expr(proxy);
355
+ const tailSegments = result?.[PATH_SEGMENTS] ?? [];
356
+ return new _PathImpl([...this.segments, ...tailSegments]);
357
+ }
358
+ };
359
+
360
+ // src/impl/template-path-impl.ts
361
+ var TemplatePathImpl = class _TemplatePathImpl extends PathImpl {
362
+ /**
363
+ * Traverses into a collection (Array or Record) to operate on each item, returning a TemplatePath.
364
+ *
365
+ * @example
366
+ * const users = path<Root>().users;
367
+ * const userNames = users.each(u => u.name); // TemplatePath matching all names
368
+ */
369
+ each(expr) {
370
+ let tailSegments = [];
371
+ if (expr) {
372
+ const proxy = createPathProxy([]);
373
+ const result = expr(proxy);
374
+ tailSegments = result?.[PATH_SEGMENTS] ?? [];
375
+ }
376
+ return new _TemplatePathImpl([
377
+ ...this.segments,
378
+ WILDCARD,
379
+ ...tailSegments
380
+ ]);
381
+ }
382
+ /**
383
+ * Traverses deeply into a structure, matching any nested property, returning a TemplatePath.
384
+ *
385
+ * @example
386
+ * const root = path<Root>();
387
+ * const allIds = root.deep(node => node.id); // TemplatePath matching any 'id' at any depth
388
+ */
389
+ deep(expr) {
390
+ let tailSegments = [];
391
+ if (expr) {
392
+ const proxy = createPathProxy([]);
393
+ const result = expr(proxy);
394
+ tailSegments = result?.[PATH_SEGMENTS] ?? [];
395
+ }
396
+ return new _TemplatePathImpl([
397
+ ...this.segments,
398
+ DEEP_WILDCARD,
399
+ ...tailSegments
400
+ ]);
401
+ }
402
+ /**
403
+ * Resolves this template path against actual data to return an array of concrete paths
404
+ * that exist in the given data.
405
+ *
406
+ * @example
407
+ * const template = path<Root>().users.each().name;
408
+ * const concretePaths = template.expand(data); // [path<Root>().users[0].name, ...]
409
+ */
410
+ expand(data) {
411
+ const results = [];
412
+ const walk = (currentData, segmentIdx, currentPath) => {
413
+ if (segmentIdx >= this.segments.length) {
414
+ results.push(new PathImpl(currentPath));
415
+ return;
416
+ }
417
+ const seg = this.segments[segmentIdx];
418
+ if (seg === WILDCARD) {
419
+ if (currentData != null && typeof currentData === "object") {
420
+ const keys = Array.isArray(currentData) ? Array.from(currentData.keys()) : Object.keys(currentData);
421
+ for (const key of keys) {
422
+ walk(
423
+ currentData[key],
424
+ segmentIdx + 1,
425
+ [...currentPath, key]
426
+ );
427
+ }
428
+ }
429
+ } else if (seg === DEEP_WILDCARD) {
430
+ walk(currentData, segmentIdx + 1, currentPath);
431
+ if (currentData != null && typeof currentData === "object") {
432
+ const keys = Array.isArray(currentData) ? Array.from(currentData.keys()) : Object.keys(currentData);
433
+ for (const key of keys) {
434
+ walk(
435
+ currentData[key],
436
+ segmentIdx,
437
+ [...currentPath, key]
438
+ );
439
+ }
440
+ }
441
+ } else {
442
+ if (currentData != null && typeof currentData === "object" && seg in currentData) {
443
+ walk(
444
+ currentData[seg],
445
+ segmentIdx + 1,
446
+ [...currentPath, seg]
447
+ );
448
+ }
449
+ }
450
+ };
451
+ walk(data, 0, []);
452
+ return results;
453
+ }
454
+ /**
455
+ * Extracts an array of values at this template path from the given data object.
456
+ *
457
+ * @example
458
+ * const names = path<Root>().users.each().name.get(data); // string[]
459
+ */
460
+ // @ts-expect-error Overriding get to return an array instead of a single value
461
+ get(data) {
462
+ return this.expand(data).map((p) => p.get(data));
463
+ }
464
+ /**
465
+ * Returns an accessor function that extracts an array of values at this template path from the given data object.
466
+ * Useful for array methods like `.map()` or `.filter()`.
467
+ *
468
+ * @example
469
+ * const allNames = companies.map(path<Company>().departments.each().name.fn);
470
+ */
471
+ // @ts-expect-error Overriding fn to return an array instead of a single value
472
+ get fn() {
473
+ return (data) => this.get(data);
474
+ }
475
+ /**
476
+ * Sets the provided value to all matching paths immutably.
477
+ *
478
+ * @example
479
+ * const updatedData = path<Root>().users.each().name.set(data, "Bob");
480
+ */
481
+ set(data, value) {
482
+ const paths = this.expand(data);
483
+ let current = data;
484
+ for (const p of paths) {
485
+ current = p.set(current, value);
486
+ }
487
+ return current;
488
+ }
489
+ };
490
+
491
+ // src/path.ts
492
+ setTemplatePathCtor(TemplatePathImpl);
493
+ function path(baseOrExpr, expr) {
494
+ if (!baseOrExpr) {
495
+ return new PathImpl([]);
496
+ }
497
+ if (typeof baseOrExpr === "function") {
498
+ const proxy = createPathProxy([]);
499
+ const result = baseOrExpr(proxy);
500
+ const segments = result?.[PATH_SEGMENTS] ?? [];
501
+ return new PathImpl(segments);
502
+ }
503
+ const baseSegments = baseOrExpr.segments;
504
+ if (expr) {
505
+ if (typeof expr === "function") {
506
+ const proxy = createPathProxy([]);
507
+ const result = expr(proxy);
508
+ const tailSegments = result?.[PATH_SEGMENTS] ?? [];
509
+ return new PathImpl([...baseSegments, ...tailSegments]);
510
+ } else if (typeof expr === "object" && "segments" in expr) {
511
+ return new PathImpl([
512
+ ...baseSegments,
513
+ ...expr.segments
514
+ ]);
515
+ }
516
+ }
517
+ return new PathImpl(baseSegments);
518
+ }
519
+ function unsafePath(raw) {
520
+ const segments = raw ? raw.split(".").map((s) => s === "" ? s : isCanonicalArrayIndex(s) ? Number(s) : s) : [];
521
+ return new PathImpl(segments);
522
+ }
523
+ // Annotate the CommonJS export names for ESM import in node:
524
+ 0 && (module.exports = {
525
+ path,
526
+ unsafePath
527
+ });