assign-gingerly 0.0.25 → 0.0.27

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 CHANGED
@@ -355,6 +355,115 @@ assignGingerly(div, {
355
355
  // All instances and readonly objects preserved
356
356
  ```
357
357
 
358
+ ## Example 3c - Method Calls with withMethods
359
+
360
+ The `withMethods` option allows you to call methods as part of property assignment, which is particularly useful for DOM APIs like `classList` and `part`:
361
+
362
+ ```TypeScript
363
+ import assignGingerly from 'assign-gingerly';
364
+
365
+ const element = document.createElement('div');
366
+
367
+ // Simple method calls
368
+ assignGingerly(element, {
369
+ '?.classList?.add': 'myClass',
370
+ '?.part?.add': 'myPart'
371
+ }, { withMethods: ['add'] });
372
+
373
+ console.log(element.classList.contains('myClass')); // true
374
+ console.log(element.part.contains('myPart')); // true
375
+ ```
376
+
377
+ **How it works:**
378
+
379
+ When a path segment matches a name in the `withMethods` array/set:
380
+ - If it's the **last segment**: the method is called with the RHS value as an argument
381
+ - If it's a **middle segment** and the next segment is also a method: called with no arguments
382
+ - If it's a **middle segment** and the next segment is NOT a method: called with the next segment as a string argument
383
+ - If the property is not a function: silently skipped
384
+
385
+ **Array arguments:**
386
+
387
+ Arrays are spread as multiple arguments:
388
+
389
+ ```TypeScript
390
+ assignGingerly(element, {
391
+ '?.setAttribute': ['data-id', '123']
392
+ }, { withMethods: ['setAttribute'] });
393
+
394
+ // Equivalent to: element.setAttribute('data-id', '123')
395
+ ```
396
+
397
+ **Chained method calls:**
398
+
399
+ Methods can be chained to navigate through object hierarchies:
400
+
401
+ ```TypeScript
402
+ const elementRef = {
403
+ deref() { return this.element; },
404
+ element: document.createElement('div')
405
+ };
406
+
407
+ assignGingerly(elementRef, {
408
+ '?.deref?.classList?.add': 'active'
409
+ }, { withMethods: ['deref', 'add'] });
410
+
411
+ // Equivalent to: elementRef.deref().classList.add('active')
412
+ ```
413
+
414
+ **Complex chaining:**
415
+
416
+ ```TypeScript
417
+ const shadowRoot = {
418
+ querySelector(selector) {
419
+ return this.elements[selector];
420
+ },
421
+ elements: {
422
+ 'my-element': document.createElement('div')
423
+ }
424
+ };
425
+
426
+ assignGingerly(shadowRoot, {
427
+ '?.querySelector?.my-element?.classList?.add': 'highlighted'
428
+ }, { withMethods: ['querySelector', 'add'] });
429
+
430
+ // Equivalent to: shadowRoot.querySelector('my-element').classList.add('highlighted')
431
+ ```
432
+
433
+ **Using Set for withMethods:**
434
+
435
+ For better performance with many methods, use a Set:
436
+
437
+ ```TypeScript
438
+ const methods = new Set(['add', 'remove', 'toggle', 'setAttribute']);
439
+
440
+ assignGingerly(element, {
441
+ '?.classList?.add': 'class1',
442
+ '?.classList?.remove': 'class2',
443
+ '?.setAttribute': ['data-value', '42']
444
+ }, { withMethods: methods });
445
+ ```
446
+
447
+ **Mixing methods and normal assignments:**
448
+
449
+ ```TypeScript
450
+ assignGingerly(element, {
451
+ '?.classList?.add': 'active',
452
+ '?.dataset?.userId': '123',
453
+ '?.style?.height': '100px'
454
+ }, { withMethods: ['add'] });
455
+
456
+ // classList.add() is called
457
+ // dataset.userId and style.height are assigned normally
458
+ ```
459
+
460
+ **Benefits:**
461
+
462
+ - Cleaner syntax for DOM manipulation
463
+ - Works with any object methods, not just DOM APIs
464
+ - Silent failure for non-existent methods (garbage in, garbage out)
465
+ - Supports method chaining and complex navigation patterns
466
+
358
467
  While we are in the business of passing values of object A into object B, we might as well add some extremely common behavior that allows updating properties of object B based on the current values of object B -- things like incrementing, toggling, and deleting. Deleting is critical for assignTentatively, but is included with both functions.
359
468
 
360
469
  ## Example 4 - Incrementing values with += command
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Registry for parsers scoped to a synthesizer element (be-hive, htmx-container, etc.)
3
+ * Enables lazy-loading of complex parsers with Promise-based waiting
4
+ */
5
+ export class ScopedParserRegistry {
6
+ parsers = new Map();
7
+ pendingWaits = new Map();
8
+ /**
9
+ * Register a parser with a given name
10
+ * Resolves any pending waiters for this parser
11
+ * @param name - The name to register the parser under
12
+ * @param parser - The parser function
13
+ */
14
+ register(name, parser) {
15
+ if (this.parsers.has(name)) {
16
+ console.warn(`Parser "${name}" already registered in scoped registry, overwriting`);
17
+ }
18
+ this.parsers.set(name, parser);
19
+ // Resolve any pending waiters for this parser
20
+ const waiters = this.pendingWaits.get(name);
21
+ if (waiters) {
22
+ waiters.forEach(({ resolve }) => resolve());
23
+ this.pendingWaits.delete(name);
24
+ }
25
+ }
26
+ /**
27
+ * Get a parser by name
28
+ * @param name - The name of the parser
29
+ * @returns The parser function or undefined if not found
30
+ */
31
+ get(name) {
32
+ return this.parsers.get(name);
33
+ }
34
+ /**
35
+ * Check if a parser is registered
36
+ * @param name - The name to check
37
+ * @returns True if the parser exists
38
+ */
39
+ has(name) {
40
+ return this.parsers.has(name);
41
+ }
42
+ /**
43
+ * Wait for multiple parsers to be registered
44
+ * @param names - Array of parser names to wait for
45
+ * @param timeout - Timeout in milliseconds (default: 60000)
46
+ * @returns Promise that resolves when all parsers are registered
47
+ * @throws Error listing missing parsers if timeout expires
48
+ */
49
+ waitFor(names, timeout = 60000) {
50
+ // Check if all parsers are already registered
51
+ const missing = names.filter(name => !this.has(name));
52
+ if (missing.length === 0) {
53
+ return Promise.resolve();
54
+ }
55
+ // Create promise that resolves when all parsers are registered
56
+ return new Promise((resolve, reject) => {
57
+ let timeoutId;
58
+ // Set timeout that rejects with descriptive error
59
+ timeoutId = setTimeout(() => {
60
+ const stillMissing = names.filter(name => !this.has(name));
61
+ reject(new Error(`Timeout waiting for parsers: ${stillMissing.join(', ')}`));
62
+ }, timeout);
63
+ // Track which parsers we're waiting for
64
+ let remainingCount = missing.length;
65
+ // Create waiter for each missing parser
66
+ missing.forEach(name => {
67
+ const waiter = {
68
+ resolve: () => {
69
+ remainingCount--;
70
+ if (remainingCount === 0) {
71
+ if (timeoutId !== undefined) {
72
+ clearTimeout(timeoutId);
73
+ }
74
+ resolve();
75
+ }
76
+ },
77
+ reject
78
+ };
79
+ // Add waiter to pending list
80
+ if (!this.pendingWaits.has(name)) {
81
+ this.pendingWaits.set(name, []);
82
+ }
83
+ this.pendingWaits.get(name).push(waiter);
84
+ });
85
+ });
86
+ }
87
+ /**
88
+ * Get all registered parser names
89
+ * @returns Array of parser names
90
+ */
91
+ getNames() {
92
+ return Array.from(this.parsers.keys());
93
+ }
94
+ }
@@ -0,0 +1,111 @@
1
+ import { ParserFunction } from './types/assign-gingerly/types';
2
+
3
+ /**
4
+ * Registry for parsers scoped to a synthesizer element (be-hive, htmx-container, etc.)
5
+ * Enables lazy-loading of complex parsers with Promise-based waiting
6
+ */
7
+ export class ScopedParserRegistry {
8
+ private parsers = new Map<string, ParserFunction>();
9
+ private pendingWaits = new Map<string, Array<{
10
+ resolve: () => void;
11
+ reject: (error: Error) => void;
12
+ }>>();
13
+
14
+ /**
15
+ * Register a parser with a given name
16
+ * Resolves any pending waiters for this parser
17
+ * @param name - The name to register the parser under
18
+ * @param parser - The parser function
19
+ */
20
+ register(name: string, parser: ParserFunction): void {
21
+ if (this.parsers.has(name)) {
22
+ console.warn(`Parser "${name}" already registered in scoped registry, overwriting`);
23
+ }
24
+
25
+ this.parsers.set(name, parser);
26
+
27
+ // Resolve any pending waiters for this parser
28
+ const waiters = this.pendingWaits.get(name);
29
+ if (waiters) {
30
+ waiters.forEach(({ resolve }) => resolve());
31
+ this.pendingWaits.delete(name);
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Get a parser by name
37
+ * @param name - The name of the parser
38
+ * @returns The parser function or undefined if not found
39
+ */
40
+ get(name: string): ParserFunction | undefined {
41
+ return this.parsers.get(name);
42
+ }
43
+
44
+ /**
45
+ * Check if a parser is registered
46
+ * @param name - The name to check
47
+ * @returns True if the parser exists
48
+ */
49
+ has(name: string): boolean {
50
+ return this.parsers.has(name);
51
+ }
52
+
53
+ /**
54
+ * Wait for multiple parsers to be registered
55
+ * @param names - Array of parser names to wait for
56
+ * @param timeout - Timeout in milliseconds (default: 60000)
57
+ * @returns Promise that resolves when all parsers are registered
58
+ * @throws Error listing missing parsers if timeout expires
59
+ */
60
+ waitFor(names: string[], timeout: number = 60000): Promise<void> {
61
+ // Check if all parsers are already registered
62
+ const missing = names.filter(name => !this.has(name));
63
+ if (missing.length === 0) {
64
+ return Promise.resolve();
65
+ }
66
+
67
+ // Create promise that resolves when all parsers are registered
68
+ return new Promise((resolve, reject) => {
69
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
70
+
71
+ // Set timeout that rejects with descriptive error
72
+ timeoutId = setTimeout(() => {
73
+ const stillMissing = names.filter(name => !this.has(name));
74
+ reject(new Error(`Timeout waiting for parsers: ${stillMissing.join(', ')}`));
75
+ }, timeout);
76
+
77
+ // Track which parsers we're waiting for
78
+ let remainingCount = missing.length;
79
+
80
+ // Create waiter for each missing parser
81
+ missing.forEach(name => {
82
+ const waiter = {
83
+ resolve: () => {
84
+ remainingCount--;
85
+ if (remainingCount === 0) {
86
+ if (timeoutId !== undefined) {
87
+ clearTimeout(timeoutId);
88
+ }
89
+ resolve();
90
+ }
91
+ },
92
+ reject
93
+ };
94
+
95
+ // Add waiter to pending list
96
+ if (!this.pendingWaits.has(name)) {
97
+ this.pendingWaits.set(name, []);
98
+ }
99
+ this.pendingWaits.get(name)!.push(waiter);
100
+ });
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Get all registered parser names
106
+ * @returns Array of parser names
107
+ */
108
+ getNames(): string[] {
109
+ return Array.from(this.parsers.keys());
110
+ }
111
+ }
package/assignGingerly.js CHANGED
@@ -270,6 +270,55 @@ function isClassInstance(value) {
270
270
  // Plain objects have Object.prototype or null as prototype
271
271
  return proto !== Object.prototype && proto !== null;
272
272
  }
273
+ /**
274
+ * Helper function to evaluate a nested path with method calls
275
+ * Handles chained method calls where path segments can be methods
276
+ */
277
+ function evaluatePathWithMethods(target, pathParts, value, withMethods) {
278
+ let current = target;
279
+ let i = 0;
280
+ // Process all segments except the last one
281
+ while (i < pathParts.length - 1) {
282
+ const part = pathParts[i];
283
+ const nextPart = pathParts[i + 1];
284
+ if (withMethods.has(part)) {
285
+ const method = current[part];
286
+ if (typeof method === 'function') {
287
+ // Check if next part is also a method
288
+ if (withMethods.has(nextPart)) {
289
+ // Both are methods - call first with no args
290
+ current = method.call(current);
291
+ }
292
+ else {
293
+ // Only current is method - call with next part as string arg
294
+ current = method.call(current, nextPart);
295
+ i++; // Skip next part since we consumed it as argument
296
+ }
297
+ }
298
+ else {
299
+ // Not a function - just access property (create if needed)
300
+ if (!(part in current) || typeof current[part] !== 'object' || current[part] === null) {
301
+ current[part] = {};
302
+ }
303
+ current = current[part];
304
+ }
305
+ }
306
+ else {
307
+ // Not a method - normal property access (create if needed)
308
+ if (!(part in current) || typeof current[part] !== 'object' || current[part] === null) {
309
+ current[part] = {};
310
+ }
311
+ current = current[part];
312
+ }
313
+ i++;
314
+ }
315
+ const lastKey = pathParts[pathParts.length - 1];
316
+ return {
317
+ target: current,
318
+ lastKey,
319
+ isMethod: withMethods.has(lastKey)
320
+ };
321
+ }
273
322
  /**
274
323
  * Main assignGingerly function
275
324
  */
@@ -277,6 +326,12 @@ export function assignGingerly(target, source, options) {
277
326
  if (!target || typeof target !== 'object') {
278
327
  return target;
279
328
  }
329
+ // Convert withMethods array to Set for O(1) lookup
330
+ const withMethodsSet = options?.withMethods
331
+ ? options.withMethods instanceof Set
332
+ ? options.withMethods
333
+ : new Set(options.withMethods)
334
+ : undefined;
280
335
  const registry = options?.registry instanceof EnhancementRegistry
281
336
  ? options.registry
282
337
  : options?.registry
@@ -437,32 +492,86 @@ export function assignGingerly(target, source, options) {
437
492
  }
438
493
  if (isNestedPath(key)) {
439
494
  const pathParts = parsePath(key);
440
- const lastKey = pathParts[pathParts.length - 1];
441
- const parent = ensureNestedPath(target, pathParts);
442
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
443
- // Check if property exists and is readonly OR is a class instance
444
- if (lastKey in parent && (isReadonlyProperty(parent, lastKey) || isClassInstance(parent[lastKey]))) {
445
- // Property is readonly or a class instance - check if current value is an object
446
- const currentValue = parent[lastKey];
447
- if (typeof currentValue !== 'object' || currentValue === null) {
448
- throw new Error(`Cannot merge object into ${isReadonlyProperty(parent, lastKey) ? 'readonly ' : ''}primitive property '${String(lastKey)}'`);
495
+ // Check if we need to handle methods
496
+ if (withMethodsSet) {
497
+ const result = evaluatePathWithMethods(target, pathParts, value, withMethodsSet);
498
+ if (result.isMethod) {
499
+ // Last segment is a method - call it
500
+ const method = result.target[result.lastKey];
501
+ if (typeof method === 'function') {
502
+ if (Array.isArray(value)) {
503
+ method.apply(result.target, value);
504
+ }
505
+ else {
506
+ method.call(result.target, value);
507
+ }
449
508
  }
450
- // Recursively apply assignGingerly to the readonly object or class instance
451
- assignGingerly(currentValue, value, options);
509
+ // Silently skip if not a function
510
+ continue;
452
511
  }
453
- else {
454
- // Property is writable and not a class instance - normal recursive merge
455
- if (!(lastKey in parent) || typeof parent[lastKey] !== 'object') {
456
- parent[lastKey] = {};
512
+ // Not a method - proceed with normal assignment using evaluated target
513
+ const lastKey = result.lastKey;
514
+ const parent = result.target;
515
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
516
+ // Check if property exists and is readonly OR is a class instance
517
+ if (lastKey in parent && (isReadonlyProperty(parent, lastKey) || isClassInstance(parent[lastKey]))) {
518
+ const currentValue = parent[lastKey];
519
+ if (typeof currentValue !== 'object' || currentValue === null) {
520
+ throw new Error(`Cannot merge object into ${isReadonlyProperty(parent, lastKey) ? 'readonly ' : ''}primitive property '${String(lastKey)}'`);
521
+ }
522
+ assignGingerly(currentValue, value, options);
523
+ }
524
+ else {
525
+ // Property is writable and not a class instance - replace it
526
+ parent[lastKey] = value;
457
527
  }
458
- assignGingerly(parent[lastKey], value, options);
528
+ }
529
+ else {
530
+ parent[lastKey] = value;
459
531
  }
460
532
  }
461
533
  else {
462
- parent[lastKey] = value;
534
+ // No withMethods - use original logic
535
+ const lastKey = pathParts[pathParts.length - 1];
536
+ const parent = ensureNestedPath(target, pathParts);
537
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
538
+ // Check if property exists and is readonly OR is a class instance
539
+ if (lastKey in parent && (isReadonlyProperty(parent, lastKey) || isClassInstance(parent[lastKey]))) {
540
+ // Property is readonly or a class instance - check if current value is an object
541
+ const currentValue = parent[lastKey];
542
+ if (typeof currentValue !== 'object' || currentValue === null) {
543
+ throw new Error(`Cannot merge object into ${isReadonlyProperty(parent, lastKey) ? 'readonly ' : ''}primitive property '${String(lastKey)}'`);
544
+ }
545
+ // Recursively apply assignGingerly to the readonly object or class instance
546
+ assignGingerly(currentValue, value, options);
547
+ }
548
+ else {
549
+ // Property is writable and not a class instance - replace it
550
+ parent[lastKey] = value;
551
+ }
552
+ }
553
+ else {
554
+ parent[lastKey] = value;
555
+ }
463
556
  }
464
557
  }
465
558
  else {
559
+ // Non-nested path
560
+ // Check if this is a method call
561
+ if (withMethodsSet && withMethodsSet.has(key)) {
562
+ const method = target[key];
563
+ if (typeof method === 'function') {
564
+ if (Array.isArray(value)) {
565
+ method.apply(target, value);
566
+ }
567
+ else {
568
+ method.call(target, value);
569
+ }
570
+ }
571
+ // Silently skip if not a function
572
+ continue;
573
+ }
574
+ // Normal assignment
466
575
  if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
467
576
  // Check if property exists and is readonly OR is a class instance
468
577
  if (key in target && (isReadonlyProperty(target, key) || isClassInstance(target[key]))) {
@@ -475,7 +584,7 @@ export function assignGingerly(target, source, options) {
475
584
  assignGingerly(currentValue, value, options);
476
585
  }
477
586
  else {
478
- // Property is writable and not a class instance - simple assignment
587
+ // Property is writable and not a class instance - replace it
479
588
  target[key] = value;
480
589
  }
481
590
  }