assign-gingerly 0.0.38 → 0.0.40

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.
@@ -0,0 +1,529 @@
1
+ /**
2
+ * assignFeatures - Dependency injection for custom element features
3
+ *
4
+ * Allows custom element authors to declare supported feature slots via
5
+ * `static supportedFeatures`, then have implementations injected via
6
+ * `customElementRegistry.assignFeatures(Ctor, features)`.
7
+ *
8
+ * Features are lazily instantiated on first property access via getter-only
9
+ * properties installed on the class prototype.
10
+ */
11
+ import { parseWithAttrs } from './parseWithAttrs.js';
12
+ /**
13
+ * WeakMap storing per-instance feature caches.
14
+ * Outer key: the instance (element or other object).
15
+ * Inner map: feature key -> spawned instance.
16
+ */
17
+ const featureStorage = new WeakMap();
18
+ /**
19
+ * The features registry: maps a constructor to its accumulated feature injections.
20
+ */
21
+ export class FeaturesRegistry {
22
+ #registry = new Map();
23
+ has(ctr) {
24
+ return this.#registry.has(ctr);
25
+ }
26
+ get(ctr) {
27
+ return this.#registry.get(ctr);
28
+ }
29
+ set(ctr, key, injection) {
30
+ let features = this.#registry.get(ctr);
31
+ if (!features) {
32
+ features = new Map();
33
+ this.#registry.set(ctr, features);
34
+ }
35
+ features.set(key, injection);
36
+ }
37
+ hasKey(ctr, key) {
38
+ const features = this.#registry.get(ctr);
39
+ return features ? features.has(key) : false;
40
+ }
41
+ }
42
+ /**
43
+ * Sentinel symbol to mark stored values as raw initVals (not yet spawned).
44
+ */
45
+ const RAW_INIT_VALS = Symbol('rawInitVals');
46
+ /**
47
+ * Sentinel symbol to mark stored values as error state from failed async spawn.
48
+ */
49
+ const FEATURE_ERROR = Symbol('featureError');
50
+ /**
51
+ * WeakMap storing pending Promises for async feature resolution.
52
+ * Outer key: the instance. Inner map: feature key -> { promise, resolve, reject }.
53
+ */
54
+ const pendingFeatures = new WeakMap();
55
+ /**
56
+ * Resolves the whenFeatureReady method name from lifecycleKeys config.
57
+ * Returns undefined if lifecycleKeys is not set.
58
+ */
59
+ function resolveWhenFeatureReadyName(lifecycleKeys) {
60
+ if (lifecycleKeys === undefined)
61
+ return undefined;
62
+ if (lifecycleKeys === true)
63
+ return 'whenFeatureReady';
64
+ return lifecycleKeys.whenFeatureReady || 'whenFeatureReady';
65
+ }
66
+ /**
67
+ * Installs the whenFeatureReady method on the constructor prototype if not already present.
68
+ */
69
+ function installWhenFeatureReadyMethod(ctr, methodName) {
70
+ // Only install once per class
71
+ if (Object.getOwnPropertyDescriptor(ctr.prototype, methodName))
72
+ return;
73
+ Object.defineProperty(ctr.prototype, methodName, {
74
+ value: function (featureKey) {
75
+ // Trigger the getter (starts async resolution if needed, or returns sync instance)
76
+ const current = this[featureKey];
77
+ // Check if there's a pending async resolution for this instance + key
78
+ const pending = pendingFeatures.get(this)?.get(featureKey);
79
+ if (pending) {
80
+ return pending.promise;
81
+ }
82
+ // No pending — feature is already resolved (sync or async already completed)
83
+ return Promise.resolve(current);
84
+ },
85
+ writable: true,
86
+ enumerable: false,
87
+ configurable: true
88
+ });
89
+ }
90
+ /**
91
+ * Determines if a function is an async spawner (returns a Promise<Constructor>)
92
+ * rather than a synchronous constructor.
93
+ *
94
+ * Heuristic:
95
+ * - AsyncFunction (async () => ...) → async spawner
96
+ * - Arrow function (no .prototype) → async spawner (assumed to return Promise<Constructor>)
97
+ * - Class or function declaration (has .prototype) → synchronous constructor
98
+ */
99
+ function isAsyncSpawn(fn) {
100
+ if (typeof fn !== 'function')
101
+ return false;
102
+ // Explicit async function
103
+ if (fn.constructor.name === 'AsyncFunction')
104
+ return true;
105
+ // Arrow function or non-constructor function (no .prototype)
106
+ if (fn.prototype === undefined)
107
+ return true;
108
+ return false;
109
+ }
110
+ /**
111
+ * Installs a getter/setter pair on the constructor's prototype for the given feature key.
112
+ *
113
+ * - The setter stores raw values (pre-upgrade or early assignment) into the WeakMap
114
+ * tagged with a sentinel so the getter knows they are initVals, not spawned instances.
115
+ * - The getter spawns the feature instance on first access, using any stored raw value
116
+ * as initVals, then caches the spawned instance.
117
+ *
118
+ * If an own-property with the same key exists on the instance (e.g., set before
119
+ * the element upgraded), it is captured as initVals and deleted so the prototype
120
+ * getter/setter is no longer shadowed.
121
+ */
122
+ function installFeatureGetter(ctr, key, featuresRegistry) {
123
+ Object.defineProperty(ctr.prototype, key, {
124
+ get: function () {
125
+ // Get or create the per-instance storage
126
+ let storage = featureStorage.get(this);
127
+ if (!storage) {
128
+ storage = new Map();
129
+ featureStorage.set(this, storage);
130
+ }
131
+ const stored = storage.get(key);
132
+ // Check for error state from failed async spawn
133
+ if (stored && typeof stored === 'object' && FEATURE_ERROR in stored) {
134
+ throw stored[FEATURE_ERROR];
135
+ }
136
+ // If already spawned (not a raw sentinel, not undefined), return it
137
+ if (stored !== undefined && !(stored && typeof stored === 'object' && RAW_INIT_VALS in stored)) {
138
+ return stored;
139
+ }
140
+ // Determine initVals: from setter-stored raw value, or from own-property shadow
141
+ let initVals = undefined;
142
+ if (stored && typeof stored === 'object' && RAW_INIT_VALS in stored) {
143
+ initVals = stored[RAW_INIT_VALS];
144
+ storage.delete(key);
145
+ }
146
+ else if (Object.hasOwn(this, key)) {
147
+ initVals = this[key];
148
+ delete this[key]; // Unshadow the prototype accessor
149
+ }
150
+ // Resolve the registry — use scoped registry if available, fall back to global
151
+ const registry = (this.customElementRegistry || customElements);
152
+ const fr = registry.featuresRegistry;
153
+ if (!fr || !fr.has(ctr)) {
154
+ throw new Error(`assignFeatures: featuresRegistry missing entry for constructor`);
155
+ }
156
+ const features = fr.get(ctr);
157
+ const injection = features.get(key);
158
+ if (!injection) {
159
+ throw new Error(`assignFeatures: no injection found for feature "${key}"`);
160
+ }
161
+ // Resolve spawn: injection.spawn takes priority, then fallbackSpawn
162
+ const supportedFeatures = ctr.supportedFeatures;
163
+ const optIn = supportedFeatures?.[key];
164
+ if (!optIn) {
165
+ throw new Error(`assignFeatures: "${key}" not in static supportedFeatures`);
166
+ }
167
+ const SpawnClass = injection.spawn || optIn.fallbackSpawn;
168
+ if (!SpawnClass) {
169
+ throw new Error(`assignFeatures: no spawn implementation found for feature "${key}". ` +
170
+ `Provide spawn in assignFeatures() or fallbackSpawn in supportedFeatures.`);
171
+ }
172
+ // Build the spawn context
173
+ const shared = optIn.getSharedContext?.(this);
174
+ const ctx = {
175
+ key,
176
+ optIn,
177
+ injection,
178
+ featuresRegistry: fr,
179
+ shared
180
+ };
181
+ // Parse attributes if withAttrs is configured
182
+ let attrInitVals = undefined;
183
+ if (injection.withAttrs && this instanceof Element) {
184
+ try {
185
+ attrInitVals = parseWithAttrs(this, injection.withAttrs, true // always unprefixed for features
186
+ );
187
+ }
188
+ catch (e) {
189
+ console.error('Error parsing feature attributes:', e);
190
+ throw e;
191
+ }
192
+ }
193
+ // Merge: attributes are base layer, programmatic initVals override
194
+ if (attrInitVals) {
195
+ initVals = initVals
196
+ ? { ...attrInitVals, ...initVals }
197
+ : attrInitVals;
198
+ }
199
+ if (isAsyncSpawn(SpawnClass)) {
200
+ // Async path: SpawnClass is a function that returns Promise<Constructor>
201
+ const placeholder = initVals && typeof initVals === 'object' ? initVals : {};
202
+ storage.set(key, placeholder);
203
+ // Capture host element reference for the async callback
204
+ const hostElement = this;
205
+ // Create a pending Promise for whenFeatureReady consumers
206
+ let pendingMap = pendingFeatures.get(hostElement);
207
+ if (!pendingMap) {
208
+ pendingMap = new Map();
209
+ pendingFeatures.set(hostElement, pendingMap);
210
+ }
211
+ let resolvePending;
212
+ let rejectPending;
213
+ const promise = new Promise((resolve, reject) => {
214
+ resolvePending = resolve;
215
+ rejectPending = reject;
216
+ });
217
+ pendingMap.set(key, { promise, resolve: resolvePending, reject: rejectPending });
218
+ // Kick off async resolution
219
+ SpawnClass().then((ResolvedClass) => {
220
+ // Mutate injection so future getter calls see the resolved constructor
221
+ injection.spawn = ResolvedClass;
222
+ // Get the current placeholder (may have accumulated properties via assignGingerly)
223
+ const currentStorage = featureStorage.get(hostElement);
224
+ const currentPlaceholder = currentStorage?.get(key);
225
+ // Don't upgrade if an error was stored or if already upgraded
226
+ if (!currentPlaceholder || (typeof currentPlaceholder === 'object' && FEATURE_ERROR in currentPlaceholder)) {
227
+ return;
228
+ }
229
+ // Parse attributes at resolution time (element should be in DOM by now)
230
+ let asyncAttrInitVals = undefined;
231
+ if (injection.withAttrs && hostElement instanceof Element) {
232
+ try {
233
+ asyncAttrInitVals = parseWithAttrs(hostElement, injection.withAttrs, true // always unprefixed for features
234
+ );
235
+ }
236
+ catch (e) {
237
+ // Non-fatal: log and continue with placeholder as initVals
238
+ console.error('Error parsing feature attributes during async resolution:', e);
239
+ }
240
+ }
241
+ // Merge: attributes are base, placeholder (programmatic) overrides
242
+ const asyncInitVals = asyncAttrInitVals
243
+ ? { ...asyncAttrInitVals, ...currentPlaceholder }
244
+ : currentPlaceholder;
245
+ // Instantiate the real class with merged initVals
246
+ const realCtx = {
247
+ key,
248
+ optIn,
249
+ injection,
250
+ featuresRegistry: fr,
251
+ shared: optIn.getSharedContext?.(hostElement)
252
+ };
253
+ const instance = new ResolvedClass(hostElement, realCtx, asyncInitVals);
254
+ // Validate shape if configured
255
+ if (optIn.validateShape) {
256
+ if (!optIn.validateShape(instance)) {
257
+ const error = new Error(`assignFeatures: spawned instance for "${key}" failed shape validation`);
258
+ error.placeholder = currentPlaceholder;
259
+ currentStorage.set(key, { [FEATURE_ERROR]: error });
260
+ rejectPending(error);
261
+ pendingMap.delete(key);
262
+ return;
263
+ }
264
+ }
265
+ // Replace placeholder with real instance
266
+ currentStorage.set(key, instance);
267
+ // Resolve the pending Promise and clean up
268
+ resolvePending(instance);
269
+ pendingMap.delete(key);
270
+ }).catch((err) => {
271
+ // Store error state — getter will throw on next access
272
+ const currentStorage = featureStorage.get(hostElement);
273
+ const currentPlaceholder = currentStorage?.get(key);
274
+ const error = new Error(`assignFeatures: async spawn for "${key}" failed: ${err.message}`);
275
+ error.placeholder = currentPlaceholder;
276
+ error.cause = err;
277
+ currentStorage?.set(key, { [FEATURE_ERROR]: error });
278
+ // Reject the pending Promise and clean up
279
+ rejectPending(error);
280
+ pendingMap.delete(key);
281
+ });
282
+ return placeholder;
283
+ }
284
+ else {
285
+ // Synchronous path: SpawnClass is a constructor
286
+ const instance = new SpawnClass(this, ctx, initVals);
287
+ // Validate shape if configured
288
+ if (optIn.validateShape) {
289
+ if (!optIn.validateShape(instance)) {
290
+ throw new Error(`assignFeatures: spawned instance for "${key}" failed shape validation`);
291
+ }
292
+ }
293
+ storage.set(key, instance);
294
+ return instance;
295
+ }
296
+ },
297
+ enumerable: true,
298
+ configurable: false
299
+ });
300
+ }
301
+ /**
302
+ * Valid lifecycle callback names that can be forwarded to features.
303
+ */
304
+ const VALID_CALLBACKS = new Set([
305
+ 'connectedCallback',
306
+ 'disconnectedCallback',
307
+ 'attributeChangedCallback',
308
+ 'adoptedCallback'
309
+ ]);
310
+ /**
311
+ * WeakMap tracking which callbacks have been patched on which constructors,
312
+ * and which feature keys are registered for each callback.
313
+ * Structure: Map<Function, Map<callbackName, Set<featureKey>>>
314
+ */
315
+ const callbackRegistry = new Map();
316
+ /**
317
+ * Installs or updates lifecycle callback forwarding on a constructor's prototype.
318
+ * Patches the callback once per type, accumulating feature keys for each.
319
+ */
320
+ function installCallbackForwarding(ctr, key, callbacks) {
321
+ let ctrCallbacks = callbackRegistry.get(ctr);
322
+ if (!ctrCallbacks) {
323
+ ctrCallbacks = new Map();
324
+ callbackRegistry.set(ctr, ctrCallbacks);
325
+ }
326
+ for (const callbackName of callbacks) {
327
+ if (!VALID_CALLBACKS.has(callbackName)) {
328
+ throw new Error(`assignFeatures: invalid callbackForwarding "${callbackName}" for feature "${key}". ` +
329
+ `Valid values: ${[...VALID_CALLBACKS].join(', ')}`);
330
+ }
331
+ // Validate that the spawn class has the method (sync spawners only)
332
+ // For async spawners, validation is deferred to runtime
333
+ let featureKeys = ctrCallbacks.get(callbackName);
334
+ if (!featureKeys) {
335
+ featureKeys = new Set();
336
+ ctrCallbacks.set(callbackName, featureKeys);
337
+ // Patch the prototype callback (only once per callback type per class)
338
+ const original = ctr.prototype[callbackName];
339
+ Object.defineProperty(ctr.prototype, callbackName, {
340
+ value: function (...args) {
341
+ // Call original first
342
+ if (original)
343
+ original.apply(this, args);
344
+ // Forward to all registered features
345
+ const keys = callbackRegistry.get(ctr)?.get(callbackName);
346
+ if (keys) {
347
+ for (const featureKey of keys) {
348
+ // Access the getter (triggers lazy spawn on first connectedCallback)
349
+ const feature = this[featureKey];
350
+ // Only forward if it's a real instance (not a placeholder or error)
351
+ if (feature && typeof feature === 'object' &&
352
+ typeof feature[callbackName] === 'function' &&
353
+ !(FEATURE_ERROR in feature)) {
354
+ feature[callbackName](...args);
355
+ }
356
+ }
357
+ }
358
+ },
359
+ writable: true,
360
+ enumerable: false,
361
+ configurable: true
362
+ });
363
+ }
364
+ // Add this feature key to the set for this callback
365
+ featureKeys.add(key);
366
+ }
367
+ }
368
+ /**
369
+ * Core assignFeatures implementation.
370
+ * Validates inputs, registers injections, and installs lazy getters.
371
+ *
372
+ * Important: Call assignFeatures BEFORE customElements.define(), or at minimum
373
+ * before any instances of the element are created. The lazy getters must be on
374
+ * the prototype before instances exist to properly capture pre-set properties.
375
+ *
376
+ * @param ctr - The constructor (class) to assign features to
377
+ * @param features - Map of feature keys to their injection configs
378
+ * @param featuresRegistry - The registry to store injections in
379
+ */
380
+ export function assignFeatures(ctr, features, featuresRegistry) {
381
+ // Validate that the constructor has static supportedFeatures
382
+ const supportedFeatures = ctr.supportedFeatures;
383
+ if (!supportedFeatures) {
384
+ throw new Error(`assignFeatures: ${ctr.name || 'constructor'} does not define static supportedFeatures`);
385
+ }
386
+ for (const key of Object.keys(features)) {
387
+ // 1. Confirm the key is opted-in via supportedFeatures
388
+ if (!(key in supportedFeatures)) {
389
+ throw new Error(`assignFeatures: "${key}" is not declared in ${ctr.name || 'constructor'}.supportedFeatures`);
390
+ }
391
+ // 2. Check that the prototype doesn't already have this property defined
392
+ const existingDescriptor = Object.getOwnPropertyDescriptor(ctr.prototype, key);
393
+ if (existingDescriptor) {
394
+ throw new Error(`assignFeatures: "${key}" already exists on ${ctr.name || 'constructor'}.prototype`);
395
+ }
396
+ // 3. Check that this key hasn't already been registered for this constructor
397
+ if (featuresRegistry.hasKey(ctr, key)) {
398
+ throw new Error(`assignFeatures: "${key}" has already been assigned for ${ctr.name || 'constructor'}`);
399
+ }
400
+ // 4. Register the injection
401
+ featuresRegistry.set(ctr, key, features[key]);
402
+ // 5. Install the lazy getter on the prototype
403
+ installFeatureGetter(ctr, key, featuresRegistry);
404
+ // 6. Install callback forwarding if configured
405
+ const featureConfig = features[key];
406
+ if (featureConfig.callbackForwarding && featureConfig.callbackForwarding.length > 0) {
407
+ installCallbackForwarding(ctr, key, featureConfig.callbackForwarding);
408
+ }
409
+ }
410
+ // 6. Install whenFeatureReady method if featuresConfig.lifecycleKeys is configured
411
+ const featuresConfig = ctr.featuresConfig;
412
+ if (featuresConfig?.lifecycleKeys) {
413
+ const methodName = resolveWhenFeatureReadyName(featuresConfig.lifecycleKeys);
414
+ if (methodName) {
415
+ installWhenFeatureReadyMethod(ctr, methodName);
416
+ }
417
+ }
418
+ }
419
+ /**
420
+ * Captures own-properties that shadow feature getters and stores them as initVals.
421
+ * Call this in the custom element constructor to handle pre-upgrade property values.
422
+ *
423
+ * When an element exists in the DOM before `define()` is called, properties may have
424
+ * been set on it directly. After upgrade, these own-properties shadow the prototype
425
+ * getters installed by `assignFeatures`. This helper captures those values and deletes
426
+ * the own-properties so the getters can function properly.
427
+ *
428
+ * @param instance - The custom element instance (typically `this` in the constructor)
429
+ *
430
+ * @example
431
+ * class ClubMember extends HTMLElement {
432
+ * static supportedFeatures = { photoTaker: { fallbackSpawn: PhotoTakerImpl } }
433
+ * constructor() {
434
+ * super();
435
+ * captureFeatureInitVals(this);
436
+ * }
437
+ * }
438
+ */
439
+ export function captureFeatureInitVals(instance) {
440
+ const ctr = instance.constructor;
441
+ const supportedFeatures = ctr.supportedFeatures;
442
+ if (!supportedFeatures)
443
+ return;
444
+ for (const key of Object.keys(supportedFeatures)) {
445
+ if (Object.hasOwn(instance, key)) {
446
+ const value = instance[key];
447
+ delete instance[key];
448
+ // Store in the WeakMap so the getter can pick it up
449
+ let storage = featureStorage.get(instance);
450
+ if (!storage) {
451
+ storage = new Map();
452
+ featureStorage.set(instance, storage);
453
+ }
454
+ storage.set(key, { [RAW_INIT_VALS]: value });
455
+ }
456
+ }
457
+ }
458
+ // =============================================================================
459
+ // PropertyBag — base class for nested feature containers
460
+ // =============================================================================
461
+ /**
462
+ * PropertyBag is a base class for creating nested feature containers.
463
+ *
464
+ * Subclass it to group related features under a single namespace property.
465
+ * PropertyBag carries the `customElementRegistry` reference from the host element
466
+ * so that nested features can resolve their registries correctly.
467
+ *
468
+ * PropertyBag must be subclassed — direct instantiation throws an error.
469
+ * Subclasses must define `static supportedFeatures` to declare their feature slots.
470
+ *
471
+ * @example
472
+ * class ClubMemberBehaviors extends PropertyBag {
473
+ * static supportedFeatures = {
474
+ * commandBehavior: { fallbackSpawn: CommandFeatureImpl },
475
+ * ariaBehavior: { fallbackSpawn: AriaFeatureImpl }
476
+ * }
477
+ * }
478
+ *
479
+ * class ClubMember extends HTMLElement {
480
+ * static supportedFeatures = {
481
+ * behaviors: { fallbackSpawn: ClubMemberBehaviors }
482
+ * }
483
+ * }
484
+ *
485
+ * customElements.assignFeatures(ClubMember, { behaviors: { spawn: ClubMemberBehaviors } });
486
+ * customElements.assignFeatures(ClubMemberBehaviors, {
487
+ * commandBehavior: { spawn: CommandFeatureImpl }
488
+ * });
489
+ */
490
+ export class PropertyBag {
491
+ /** Registry reference carried from the host element */
492
+ customElementRegistry;
493
+ constructor(hostElement, ctx, initVals) {
494
+ if (this.constructor === PropertyBag) {
495
+ throw new Error('PropertyBag must be subclassed. Define static supportedFeatures on your subclass.');
496
+ }
497
+ // Carry the registry reference from the host element
498
+ this.customElementRegistry = hostElement.customElementRegistry ||
499
+ (typeof customElements !== 'undefined' ? customElements : undefined);
500
+ // Apply any initVals
501
+ if (initVals && typeof initVals === 'object') {
502
+ Object.assign(this, initVals);
503
+ }
504
+ }
505
+ }
506
+ if (typeof CustomElementRegistry !== 'undefined') {
507
+ Object.defineProperty(CustomElementRegistry.prototype, 'featuresRegistry', {
508
+ get: function () {
509
+ const registry = new FeaturesRegistry();
510
+ Object.defineProperty(this, 'featuresRegistry', {
511
+ value: registry,
512
+ writable: true,
513
+ enumerable: false,
514
+ configurable: true,
515
+ });
516
+ return registry;
517
+ },
518
+ enumerable: false,
519
+ configurable: true,
520
+ });
521
+ Object.defineProperty(CustomElementRegistry.prototype, 'assignFeatures', {
522
+ value: function (ctr, features) {
523
+ assignFeatures(ctr, features, this.featuresRegistry);
524
+ },
525
+ writable: true,
526
+ enumerable: false,
527
+ configurable: true,
528
+ });
529
+ }