Flurryx

From fmflurry/settings-opencode · View interactive version

Flurryx is an AI agent skill from the GitHub repository fmflurry/settings-opencode. Signal-first reactive state management for Angular. Bridge RxJS streams into cache-aware stores, keyed resources, mirrored state, and replayable history. Use when generating or modifying Angular code that uses flurryx for state management, when a write must invalidate a cached slot, or when scaffold

How to use this skill

Skill file

flurryx

Signal-first reactive state management for Angular. RxJS in, signals out.

When to Activate

Imports

// main API
import {
  Store, BaseStore, LazyStore,
  syncToStore, syncToKeyedStore,
  SkipIfCached, Loading,
  clearAllStores,
  mirrorKey, deriveKey, collectKeyed,
  cloneValue, createSnapshotRestorePatch,
  createInMemoryStoreMessageChannel,
  createStorageStoreMessageChannel,
  createLocalStorageStoreMessageChannel,
  createSessionStorageStoreMessageChannel,
  createCompositeStoreMessageChannel,
  isKeyedResourceData, createKeyedResourceData, isAnyKeyLoading,
  CACHE_NO_TIMEOUT, DEFAULT_CACHE_TTL_MS,
  defaultErrorNormalizer,
} from 'flurryx';

import type {
  ResourceState, StoreEnum, ResourceStatus, ResourceErrors,
  KeyedResourceData, KeyedResourceKey,
  StoreSignal, KeyedStoreSignal, KeyedResourceState, ValueOrSignal,
  StoreOptions, StoreCacheInvalidateEvent,
  MirrorOptions, DeriveOptions, CollectKeyedOptions,
  SyncToStoreOptions, SyncToKeyedStoreOptions, ErrorNormalizer,
  // history
  StoreHistory, StoreHistoryEntry,
  StoreDeadLetterEntry, StoreDeadLetterCommand, StoreDeadLetterMeta,
  DeadLetterCommandResolverResult,
  // messages
  StoreMessage, StoreSnapshot, StoreMessageStatus,
  UpdateStoreMessage, ClearStoreMessage, ClearAllStoreMessage,
  StartLoadingStoreMessage, StopLoadingStoreMessage,
  UpdateKeyedOneStoreMessage, ClearKeyedOneStoreMessage,
  StartKeyedLoadingStoreMessage, EnsureKeyedSlotStoreMessage,
  // channels
  StoreMessageRecord, StoreMessageChannel,
  StoreMessageChannelStorage, StoreMessageChannelOptions,
  CompositeStoreMessageChannelOptions,
  StorageStoreMessageChannelOptions,
  BrowserStorageStoreMessageChannelOptions,
} from 'flurryx';

// HTTP-only — pulls @angular/common/http
import { httpErrorNormalizer } from 'flurryx/http';

Prefer flurryx. Use flurryx/http only for httpErrorNormalizer. Avoid direct @flurryx/core | @flurryx/store | @flurryx/rx unless host already depends.

Hard Rules

Core Flow

Observable -> syncToStore / syncToKeyedStore -> Store signal -> Template

ResourceState<T>

Every slot wraps ResourceState<T>:

interface ResourceState<T> {
  isLoading?: boolean;
  data?: T;
  status?: 'Success' | 'Error';
  errors?: Array<{ code: string; message: string }>;
}

Lifecycle: idle -> loading -> Success | Error.

KeyedResourceData

Per-entity cache:

type KeyedResourceData<TKey extends string | number, TValue> =
  Partial<Record<TKey, ResourceState<TValue>>>;

Helpers:

Store Builder

Interface form (preferred)

interface ProductStoreConfig {
  LIST: Product[];
  DETAIL: Product;
  ITEMS: KeyedResourceData<string, Item>;
}

export const ProductStore = Store.for<ProductStoreConfig>().build();

Naming: <Feature>StoreConfig + <Feature>Store. Slots are raw types; flurryx wraps in ResourceState<T>.

Enum-constrained form

const Keys = { LIST: 'LIST', DETAIL: 'DETAIL' } as const;
export const ProductStore = Store.for(Keys)
  .resource('LIST').as<Product[]>()
  .resource('DETAIL').as<Product>()
  .build();

.build() only callable when all enum keys defined.

Fluent form

export const ProductStore = Store
  .resource('LIST').as<Product[]>()
  .resource('DETAIL').as<Product>()
  .build();

Builder methods (all forms)

StoreOptions extends StoreMessageChannelOptions -> supply channel to override default in-memory channel.

IStore API

store.get(key) returns:

Writes (publish broker messages)

Cache invalidation

Hooks

History / Replay

Reactive signals on store

Global

Rx Operators

syncToStore

this.api.getProducts().pipe(
  syncToStore(this.store, 'LIST', {
    completeOnFirstEmission: true,           // default true (take(1))
    callbackAfterComplete: () => {},
    errorNormalizer: defaultErrorNormalizer, // default
    deadLetterCommand: { type: '...', payload: {} },
  })
).subscribe();

Success -> { data, isLoading: false, status: 'Success', errors: undefined }.

Error -> { data: undefined, isLoading: false, status: 'Error', errors: normalized } + DLQ meta from HTTP-like errors.

syncToKeyedStore

this.api.getInvoice(id).pipe(
  syncToKeyedStore(this.store, 'ITEMS', id, {
    mapResponse: (r) => r.data,    // optional response unwrap
    completeOnFirstEmission: true,
    callbackAfterComplete: () => {},
    errorNormalizer,
    deadLetterCommand,
  })
).subscribe();

Bootstraps isLoading: true for that key on subscribe (via defer). Per-key Success/Error; recomputes top-level isLoading from remaining keys.

Decorators

@SkipIfCached

@SkipIfCached(
  storeKey,
  (i) => i.store,
  returnObservable = false,
  timeoutMs = DEFAULT_CACHE_TTL_MS,  // CACHE_NO_TIMEOUT for infinite
)

Cache hit (skip) when: status === 'Success' OR isLoading === true, args match (JSON.stringify), TTL not expired.

Cache miss when: idle, status === 'Error', expired, or args changed.

Keyed: if first arg is string|number AND slot is KeyedResourceData, tracks cache per resourceKey automatically.

returnObservable: true -> uses shareReplay({ bufferSize: 1, refCount: true }) for in-flight dedup; method must return Observable.

@Loading

@Loading(storeKey, (i) => i.store)

Calls startLoading(key) before method. If first arg is string|number and store has startKeyedLoading, calls startKeyedLoading(key, resourceKey) instead.

Composition

@SkipIfCached MUST be outermost (short-circuits before loading). @Loading above @SkipIfCached -> potential infinite loading loops.

Standalone Functions

mirrorKey

mirrorKey(sourceStore, sourceKey, targetStore, targetKey?, options?: MirrorOptions)
// MirrorOptions: { destroyRef?, direction?: 'bidirectional' | 'source-to-target' }
// Default direction: 'bidirectional' — updates flow both ways with loop guard.
// Set direction: 'source-to-target' for one-way mirroring.
// returns cleanup () => void

deriveKey

deriveKey(source, sourceKey, target, targetKey, {
  mapData: (data, state) => mappedData,
  destroyRef?,
})
// returns cleanup. Mirrors isLoading/status/errors, maps data.

collectKeyed

collectKeyed(source, sourceKey, target, targetKey?, {
  extractId: (entity | undefined) => key | undefined,
  destroyRef?,
})
// CollectKeyedOptions. Aggregates single-entity emissions into keyed cache.

Message Channels

Default = in-memory.

Store.for<Config>().build({
  channel: createLocalStorageStoreMessageChannel({
    storageKey: 'app.store',
    serialize?,    // optional
    deserialize?,
  }),
});

Factories:

StoreMessageChannelStorage: getItem | setItem | removeItem. Serializer handles undefined, Date, Map, Set, Array, plain objects.

Error Normalizers

defaultErrorNormalizer(err) checks in order:

  1. { error: { errors: [...] } } -> returns inner array
  2. { status, message } -> [{ code: String(status), message }]
  3. Error -> [{ code: 'UNKNOWN', message: err.message }]
  4. else -> [{ code: 'UNKNOWN', message: String(err) }]

httpErrorNormalizer (from flurryx/http):

Patterns

Facade (preferred when codebase uses facades)

@Injectable()
export class ProductFacade {
  private readonly api = inject(GetProductsUseCase);
  readonly store = inject(ProductStore);

  getProducts() { return this.store.get('LIST'); }
  getProduct(id: string) { return this.store.get('ITEMS').for(id); }

  @SkipIfCached('LIST', (i: ProductFacade) => i.store)
  @Loading('LIST', (i: ProductFacade) => i.store)
  loadProducts() {
    this.api.execute().pipe(syncToStore(this.store, 'LIST')).subscribe();
  }

  @SkipIfCached('ITEMS', (i: ProductFacade) => i.store)
  @Loading('ITEMS', (i: ProductFacade) => i.store)
  loadProduct(id: string) {
    this.api.byId(id).pipe(syncToKeyedStore(this.store, 'ITEMS', id)).subscribe();
  }
}

store MUST be public + readonly so decorator getters can reach it.

Service-led (when no facade layer)

Same shape, @Injectable({ providedIn: 'root' }) service holds store.

Component

@Component({
  template: `
    @if (state().isLoading) { <app-spinner/> }
    @for (p of products(); track p.id) { ... }
  `,
})
export class ProductListComponent {
  private readonly facade = inject(ProductFacade);
  readonly state = this.facade.getProducts();
  readonly products = computed(() => this.state().data ?? []);

  constructor() { this.facade.loadProducts(); }
}

Read state().data | isLoading | status | errors. Use computed() for derived UI.

Keyed reads in component

readonly id = input.required<string>();
readonly invoiceState = computed(() => this.facade.store.get('ITEMS').for(this.id())());

.for(idOrSignal) is computed-safe and supports raw or signal keys. Snapshot reads state().data?.[id] still work.

Mirroring at builder level

export const SessionStore = Store.for<SessionStoreConfig>()
  .mirror(CustomerStore, 'CUSTOMERS')
  .mirrorSelf('CUSTOMER_DETAILS', 'CUSTOMER_SNAPSHOT')
  .derive(OrdersStore, 'TOTAL', { mapData: (data) => formatTotal(data) })
  .mirrorKeyed(InvoiceStore, 'DETAIL', { extractId: (inv) => inv?.id }, 'INVOICES')
  .build();

Mirrors propagate update + onCacheInvalidate. Self-mirror with same source/target throws.

Lifecycle / Resets

Replay & Dead Letters

store.undo();  store.redo();
store.restoreStoreAt(0);          // snapshot nav, no broker
store.restoreResource('LIST', 5); // single-key restore
store.replay(12);                 // re-publish via broker
store.replay([12, 13, 14]);
store.replayDeadLetters();        // bool/int per id
store.replayDeadLetterCommand(id, async (entry) => ({ resolved: true, clear: true }));

Dead letter entry: { id, message, attempts, error, httpStatus, httpMessage, command, failedAt }.

DLQ command meta on update -> update(key, state, { deadLetter: { error, httpStatus?, httpMessage?, command? } }). syncToStore/syncToKeyedStore populate this from HTTP-like errors automatically.

Stale data

A stale slot is not a reason for you to delete @SkipIfCached, drop CACHE_NO_TIMEOUT, or shrink a TTL. Do that only when the task, spec, or PR description explicitly says to remove the cache, and then name the knock-on effects (callers that still expect the cached value, tests that only cover the hit). Otherwise the cache stays. The write that changes the cached data invalidates or updates that entry in the same change.

Same module: store.invalidateCacheFor('LIST'). Keyed: store.invalidateCacheFor('ITEMS', id). clear / clearKeyedOne also drop that slot's cached entries when the state itself must go. A mirror forwards onCacheInvalidate.

Another module does not import this store. It emits a change through a root-level service. The facade that owns the cache subscribes and invalidates.

@Injectable({ providedIn: 'root' })
export class ListChanges {
  private readonly changed = new Subject<string>();
  readonly changed$ = this.changed.asObservable();
  notify(key: string): void { this.changed.next(key); }
}

// writer, after the successful write
this.changes.notify('LIST');

// facade that caches LIST
this.changes.changed$.subscribe((key) => {
  if (key === 'LIST') this.store.invalidateCacheFor('LIST');
});

Tests cover the cached hit and a refetch, or a fresh value, after that invalidation.

Anti-Patterns

Quick Reference

| Task | API |

| --- | --- |

| Define store | Store.for<Config>().build() |

| Read slot | store.get('LIST') |

| Read keyed entry | store.get('ITEMS').for(id) |

| Write slot | store.update('LIST', { data }) |

| Write keyed entry | store.updateKeyedOne('ITEMS', id, entity) |

| Sync resource | syncToStore(store, 'LIST', opts?) |

| Sync keyed | syncToKeyedStore(store, 'ITEMS', id, opts?) |

| Skip cache | @SkipIfCached(key, (i)=>i.store, retObs?, ttl?) |

| Mark loading | @Loading(key, (i)=>i.store) |

| Mirror state | .mirror | .mirrorSelf | .mirrorKeyed | .derive | .deriveSelf (builder) |

| Standalone mirror | mirrorKey | deriveKey | collectKeyed |

| Clear slot | store.clear('LIST') |

| Clear keyed entry | store.clearKeyedOne('ITEMS', id) |

| Invalidate cache | store.invalidateCacheFor('ITEMS', id?) |

| Reset all stores | clearAllStores() |

| History | undo | redo | restoreStoreAt | restoreResource | replay | replayDeadLetters |

| Channel | createInMemory | LocalStorage | SessionStorage | Storage | Composite ...MessageChannel |

| Error norm | defaultErrorNormalizer / httpErrorNormalizer (from flurryx/http) |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.