@akin2unde/flowui-core 0.2.0 → 0.3.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.cjs CHANGED
@@ -20,7 +20,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ AsyncLabelStore: () => AsyncLabelStore,
23
24
  clampNumber: () => clampNumber,
25
+ createAsyncLabelStore: () => createAsyncLabelStore,
24
26
  createTheme: () => createTheme,
25
27
  defaultTheme: () => defaultTheme,
26
28
  enabledSelectableDescendants: () => enabledSelectableDescendants,
@@ -648,9 +650,305 @@ function selectedTreeModels(nodes, values) {
648
650
  const selected = new Set(values);
649
651
  return flattenTree(nodes).filter((node) => selected.has(node.value));
650
652
  }
653
+
654
+ // src/async-label.ts
655
+ var idle = Object.freeze({ status: "idle" });
656
+ var loading = Object.freeze({ status: "loading" });
657
+ var defaults = {
658
+ batchWindowMs: 10,
659
+ maxBatchSize: 100,
660
+ maxConcurrentBatches: 4,
661
+ cacheTtlMs: 3e5,
662
+ missingTtlMs: 3e4,
663
+ maxCacheEntries: 1e3,
664
+ requestTimeoutMs: 3e4
665
+ };
666
+ var AsyncLabelStore = class {
667
+ constructor(config) {
668
+ this.config = config;
669
+ this.scope = config.scopeKey ?? "default";
670
+ this.options = { ...defaults, ...config.options };
671
+ for (const [name, value] of Object.entries(this.options)) {
672
+ const minimum = [
673
+ "batchWindowMs",
674
+ "cacheTtlMs",
675
+ "missingTtlMs",
676
+ "maxCacheEntries"
677
+ ].includes(name) ? 0 : 1;
678
+ if (!Number.isInteger(value) || value < minimum)
679
+ throw new RangeError(`Invalid AsyncLabel option: ${name}`);
680
+ }
681
+ for (const lookup of Object.values(config.lookups)) {
682
+ if (lookup.cacheTtlMs !== void 0 && (!Number.isFinite(lookup.cacheTtlMs) || lookup.cacheTtlMs < 0)) {
683
+ throw new RangeError("Invalid lookup cacheTtlMs");
684
+ }
685
+ }
686
+ }
687
+ config;
688
+ options;
689
+ entries = /* @__PURE__ */ new Map();
690
+ cache = /* @__PURE__ */ new Map();
691
+ queue = /* @__PURE__ */ new Map();
692
+ controllers = /* @__PURE__ */ new Set();
693
+ timer;
694
+ active = 0;
695
+ generation = 0;
696
+ disposed = false;
697
+ scope;
698
+ get scopeKey() {
699
+ return this.scope;
700
+ }
701
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
702
+ get cacheSize() {
703
+ return this.cache.size;
704
+ }
705
+ key(lookup, code) {
706
+ if (code === void 0 || code === null || String(code).trim() === "")
707
+ return void 0;
708
+ return JSON.stringify([lookup, String(code)]);
709
+ }
710
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
711
+ getSnapshot(lookup, code) {
712
+ const key = this.key(lookup, code);
713
+ if (!key || this.disposed) return idle;
714
+ const entry = this.entries.get(key);
715
+ if (entry) return entry.state;
716
+ const cached = this.cache.get(key);
717
+ return cached && cached.expiresAt > Date.now() ? cached.state : idle;
718
+ }
719
+ subscribe(lookup, code, listener) {
720
+ const key = this.key(lookup, code);
721
+ if (!key || this.disposed) return () => {
722
+ };
723
+ let entry = this.entries.get(key);
724
+ if (!entry) {
725
+ entry = {
726
+ key,
727
+ lookup,
728
+ code: String(code),
729
+ state: idle,
730
+ listeners: /* @__PURE__ */ new Set(),
731
+ version: 0,
732
+ pending: false
733
+ };
734
+ this.entries.set(key, entry);
735
+ }
736
+ entry.listeners.add(listener);
737
+ this.request(entry);
738
+ return () => {
739
+ entry.listeners.delete(listener);
740
+ if (!entry.listeners.size) {
741
+ if (this.queue.delete(key)) entry.pending = false;
742
+ if (!entry.pending) this.entries.delete(key);
743
+ }
744
+ };
745
+ }
746
+ emit(entry) {
747
+ for (const listener of [...entry.listeners]) listener();
748
+ }
749
+ request(entry) {
750
+ if (entry.pending || this.disposed) return;
751
+ const cached = this.cache.get(entry.key);
752
+ if (cached && cached.expiresAt > Date.now()) {
753
+ this.cache.delete(entry.key);
754
+ this.cache.set(entry.key, cached);
755
+ entry.state = cached.state;
756
+ this.emit(entry);
757
+ return;
758
+ }
759
+ this.cache.delete(entry.key);
760
+ if (!Object.hasOwn(this.config.lookups, entry.lookup)) {
761
+ entry.state = {
762
+ status: "error",
763
+ error: new Error(`Unknown lookup: ${entry.lookup}`)
764
+ };
765
+ this.emit(entry);
766
+ return;
767
+ }
768
+ entry.pending = true;
769
+ entry.state = loading;
770
+ this.queue.set(entry.key, entry);
771
+ this.emit(entry);
772
+ this.schedule();
773
+ }
774
+ schedule() {
775
+ if (this.timer !== void 0 || this.disposed || !this.queue.size) return;
776
+ this.timer = setTimeout(() => {
777
+ this.timer = void 0;
778
+ this.flush();
779
+ }, this.options.batchWindowMs);
780
+ }
781
+ flush() {
782
+ while (!this.disposed && this.active < this.options.maxConcurrentBatches && this.queue.size) {
783
+ const first = this.queue.values().next().value;
784
+ const batch = [];
785
+ for (const entry of this.queue.values()) {
786
+ if (entry.lookup === first.lookup) {
787
+ batch.push(entry);
788
+ this.queue.delete(entry.key);
789
+ if (batch.length === this.options.maxBatchSize) break;
790
+ }
791
+ }
792
+ void this.runBatch(first.lookup, batch);
793
+ }
794
+ }
795
+ cacheResult(entry, state) {
796
+ const ttl = state.status === "missing" ? this.options.missingTtlMs : this.config.lookups[entry.lookup].cacheTtlMs ?? this.options.cacheTtlMs;
797
+ if (!ttl || !this.options.maxCacheEntries) return;
798
+ this.cache.delete(entry.key);
799
+ this.cache.set(entry.key, { state, expiresAt: Date.now() + ttl });
800
+ while (this.cache.size > this.options.maxCacheEntries)
801
+ this.cache.delete(this.cache.keys().next().value);
802
+ }
803
+ async runBatch(lookup, batch) {
804
+ const generation = this.generation;
805
+ const scopeKey = this.scope;
806
+ const versions = batch.map((entry) => entry.version);
807
+ const controller = new AbortController();
808
+ this.controllers.add(controller);
809
+ this.active++;
810
+ let timeout;
811
+ const cancelled = new Promise((_, reject) => {
812
+ controller.signal.addEventListener(
813
+ "abort",
814
+ () => reject(controller.signal.reason ?? new Error("Lookup cancelled")),
815
+ { once: true }
816
+ );
817
+ timeout = setTimeout(
818
+ () => controller.abort(new Error("Lookup request timed out")),
819
+ this.options.requestTimeoutMs
820
+ );
821
+ });
822
+ try {
823
+ const result = await Promise.race([
824
+ Promise.resolve().then(() => {
825
+ if (controller.signal.aborted) throw controller.signal.reason;
826
+ return this.config.lookups[lookup].resolve(
827
+ batch.map((entry) => entry.code),
828
+ { scopeKey, signal: controller.signal }
829
+ );
830
+ }),
831
+ cancelled
832
+ ]);
833
+ if (this.disposed || generation !== this.generation) return;
834
+ batch.forEach((entry, index) => {
835
+ if (entry.version !== versions[index]) return;
836
+ const valid = result && Object.hasOwn(result, entry.code) && (typeof result[entry.code] === "string" || result[entry.code] === null);
837
+ entry.state = !valid ? {
838
+ status: "error",
839
+ error: new Error(`Incomplete lookup response for ${entry.code}`)
840
+ } : result[entry.code] === null ? { status: "missing" } : { status: "ready", label: result[entry.code] };
841
+ entry.pending = false;
842
+ if (entry.state.status !== "error")
843
+ this.cacheResult(entry, entry.state);
844
+ this.emit(entry);
845
+ if (!entry.listeners.size) this.entries.delete(entry.key);
846
+ });
847
+ } catch (error) {
848
+ if (this.disposed || generation !== this.generation) return;
849
+ batch.forEach((entry, index) => {
850
+ if (entry.version !== versions[index]) return;
851
+ entry.pending = false;
852
+ entry.state = { status: "error", error };
853
+ this.emit(entry);
854
+ if (!entry.listeners.size) this.entries.delete(entry.key);
855
+ });
856
+ } finally {
857
+ clearTimeout(timeout);
858
+ this.controllers.delete(controller);
859
+ if (generation === this.generation) {
860
+ this.active--;
861
+ this.flush();
862
+ }
863
+ }
864
+ }
865
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
866
+ invalidate(lookup, code) {
867
+ const key = code === void 0 ? void 0 : this.key(lookup ?? "", code);
868
+ const matches = (entryKey, name) => key ? entryKey === key : !lookup || name === lookup;
869
+ for (const cachedKey of this.cache.keys()) {
870
+ const name = JSON.parse(cachedKey)[0];
871
+ if (matches(cachedKey, name)) this.cache.delete(cachedKey);
872
+ }
873
+ for (const entry of this.entries.values()) {
874
+ if (!matches(entry.key, entry.lookup)) continue;
875
+ entry.version++;
876
+ entry.pending = false;
877
+ this.queue.delete(entry.key);
878
+ entry.state = idle;
879
+ if (entry.listeners.size) this.request(entry);
880
+ else this.entries.delete(entry.key);
881
+ }
882
+ }
883
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
884
+ prime(lookup, code, label) {
885
+ const key = this.key(lookup, code);
886
+ if (!key || this.disposed) return;
887
+ if (!Object.hasOwn(this.config.lookups, lookup))
888
+ throw new Error(`Unknown lookup: ${lookup}`);
889
+ const entry = this.entries.get(key) ?? {
890
+ key,
891
+ lookup,
892
+ code: String(code),
893
+ state: idle,
894
+ listeners: /* @__PURE__ */ new Set(),
895
+ version: 0,
896
+ pending: false
897
+ };
898
+ entry.version++;
899
+ entry.pending = false;
900
+ this.queue.delete(key);
901
+ entry.state = label === null ? { status: "missing" } : { status: "ready", label };
902
+ this.cacheResult(entry, entry.state);
903
+ this.emit(entry);
904
+ }
905
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
906
+ setScope(scopeKey) {
907
+ if (scopeKey === this.scope || this.disposed) return;
908
+ this.scope = scopeKey;
909
+ this.reset();
910
+ }
911
+ clear() {
912
+ if (!this.disposed) this.reset();
913
+ }
914
+ reset() {
915
+ this.generation++;
916
+ this.active = 0;
917
+ clearTimeout(this.timer);
918
+ this.timer = void 0;
919
+ for (const controller of this.controllers) controller.abort();
920
+ this.controllers.clear();
921
+ this.queue.clear();
922
+ this.cache.clear();
923
+ for (const entry of this.entries.values()) {
924
+ entry.version++;
925
+ entry.pending = false;
926
+ entry.state = idle;
927
+ if (entry.listeners.size) this.request(entry);
928
+ else this.entries.delete(entry.key);
929
+ }
930
+ }
931
+ dispose() {
932
+ if (this.disposed) return;
933
+ this.disposed = true;
934
+ this.generation++;
935
+ clearTimeout(this.timer);
936
+ this.timer = void 0;
937
+ for (const controller of this.controllers) controller.abort();
938
+ this.controllers.clear();
939
+ this.queue.clear();
940
+ this.cache.clear();
941
+ this.entries.clear();
942
+ }
943
+ };
944
+ function createAsyncLabelStore(config) {
945
+ return new AsyncLabelStore(config);
946
+ }
651
947
  // Annotate the CommonJS export names for ESM import in node:
652
948
  0 && (module.exports = {
949
+ AsyncLabelStore,
653
950
  clampNumber,
951
+ createAsyncLabelStore,
654
952
  createTheme,
655
953
  defaultTheme,
656
954
  enabledSelectableDescendants,
package/dist/index.d.cts CHANGED
@@ -514,4 +514,83 @@ declare function enabledSelectableDescendants(node: TreeModel): TreeModel[];
514
514
  declare function filterTree(nodes: TreeModel[], query: string): TreeModel[];
515
515
  declare function selectedTreeModels(nodes: TreeModel[], values: SelectionValue[]): TreeModel[];
516
516
 
517
- export { type AlignValue, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelProps, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TableColumn, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, themeToCSS };
517
+ /** Code-to-text results. null is a confirmed missing value; absent keys are errors. */
518
+ type LabelResults = Readonly<Record<string, string | null>>;
519
+ interface LabelResolverContext {
520
+ readonly scopeKey: string;
521
+ readonly signal: AbortSignal;
522
+ }
523
+ interface LabelLookup {
524
+ resolve(codes: readonly string[], context: LabelResolverContext): Promise<LabelResults>;
525
+ cacheTtlMs?: number;
526
+ }
527
+ interface AsyncLabelOptions {
528
+ batchWindowMs?: number;
529
+ maxBatchSize?: number;
530
+ maxConcurrentBatches?: number;
531
+ cacheTtlMs?: number;
532
+ missingTtlMs?: number;
533
+ /** Maximum completed results across all lookups in this store. */
534
+ maxCacheEntries?: number;
535
+ requestTimeoutMs?: number;
536
+ }
537
+ interface AsyncLabelConfig {
538
+ lookups: Readonly<Record<string, LabelLookup>>;
539
+ scopeKey?: string;
540
+ options?: AsyncLabelOptions;
541
+ }
542
+ type AsyncLabelState = {
543
+ readonly status: "idle";
544
+ } | {
545
+ readonly status: "loading";
546
+ } | {
547
+ readonly status: "ready";
548
+ readonly label: string;
549
+ } | {
550
+ readonly status: "missing";
551
+ } | {
552
+ readonly status: "error";
553
+ readonly error: unknown;
554
+ };
555
+ type AsyncLabelCode = string | number | null | undefined;
556
+ type Listener = () => void;
557
+ /** Framework-neutral, provider-owned lookup store. Never create a global user cache. */
558
+ declare class AsyncLabelStore {
559
+ private readonly config;
560
+ private readonly options;
561
+ private readonly entries;
562
+ private readonly cache;
563
+ private readonly queue;
564
+ private readonly controllers;
565
+ private timer?;
566
+ private active;
567
+ private generation;
568
+ private disposed;
569
+ private scope;
570
+ constructor(config: AsyncLabelConfig);
571
+ get scopeKey(): string;
572
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
573
+ get cacheSize(): number;
574
+ private key;
575
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
576
+ getSnapshot(lookup: string, code: AsyncLabelCode): AsyncLabelState;
577
+ subscribe(lookup: string, code: AsyncLabelCode, listener: Listener): () => void;
578
+ private emit;
579
+ private request;
580
+ private schedule;
581
+ private flush;
582
+ private cacheResult;
583
+ private runBatch;
584
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
585
+ invalidate(lookup?: string, code?: AsyncLabelCode): void;
586
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
587
+ prime(lookup: string, code: AsyncLabelCode, label: string | null): void;
588
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
589
+ setScope(scopeKey: string): void;
590
+ clear(): void;
591
+ private reset;
592
+ dispose(): void;
593
+ }
594
+ declare function createAsyncLabelStore(config: AsyncLabelConfig): AsyncLabelStore;
595
+
596
+ export { type AlignValue, type AsyncLabelCode, type AsyncLabelConfig, type AsyncLabelOptions, type AsyncLabelState, AsyncLabelStore, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelLookup, type LabelProps, type LabelResolverContext, type LabelResults, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TableColumn, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createAsyncLabelStore, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, themeToCSS };
package/dist/index.d.ts CHANGED
@@ -514,4 +514,83 @@ declare function enabledSelectableDescendants(node: TreeModel): TreeModel[];
514
514
  declare function filterTree(nodes: TreeModel[], query: string): TreeModel[];
515
515
  declare function selectedTreeModels(nodes: TreeModel[], values: SelectionValue[]): TreeModel[];
516
516
 
517
- export { type AlignValue, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelProps, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TableColumn, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, themeToCSS };
517
+ /** Code-to-text results. null is a confirmed missing value; absent keys are errors. */
518
+ type LabelResults = Readonly<Record<string, string | null>>;
519
+ interface LabelResolverContext {
520
+ readonly scopeKey: string;
521
+ readonly signal: AbortSignal;
522
+ }
523
+ interface LabelLookup {
524
+ resolve(codes: readonly string[], context: LabelResolverContext): Promise<LabelResults>;
525
+ cacheTtlMs?: number;
526
+ }
527
+ interface AsyncLabelOptions {
528
+ batchWindowMs?: number;
529
+ maxBatchSize?: number;
530
+ maxConcurrentBatches?: number;
531
+ cacheTtlMs?: number;
532
+ missingTtlMs?: number;
533
+ /** Maximum completed results across all lookups in this store. */
534
+ maxCacheEntries?: number;
535
+ requestTimeoutMs?: number;
536
+ }
537
+ interface AsyncLabelConfig {
538
+ lookups: Readonly<Record<string, LabelLookup>>;
539
+ scopeKey?: string;
540
+ options?: AsyncLabelOptions;
541
+ }
542
+ type AsyncLabelState = {
543
+ readonly status: "idle";
544
+ } | {
545
+ readonly status: "loading";
546
+ } | {
547
+ readonly status: "ready";
548
+ readonly label: string;
549
+ } | {
550
+ readonly status: "missing";
551
+ } | {
552
+ readonly status: "error";
553
+ readonly error: unknown;
554
+ };
555
+ type AsyncLabelCode = string | number | null | undefined;
556
+ type Listener = () => void;
557
+ /** Framework-neutral, provider-owned lookup store. Never create a global user cache. */
558
+ declare class AsyncLabelStore {
559
+ private readonly config;
560
+ private readonly options;
561
+ private readonly entries;
562
+ private readonly cache;
563
+ private readonly queue;
564
+ private readonly controllers;
565
+ private timer?;
566
+ private active;
567
+ private generation;
568
+ private disposed;
569
+ private scope;
570
+ constructor(config: AsyncLabelConfig);
571
+ get scopeKey(): string;
572
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
573
+ get cacheSize(): number;
574
+ private key;
575
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
576
+ getSnapshot(lookup: string, code: AsyncLabelCode): AsyncLabelState;
577
+ subscribe(lookup: string, code: AsyncLabelCode, listener: Listener): () => void;
578
+ private emit;
579
+ private request;
580
+ private schedule;
581
+ private flush;
582
+ private cacheResult;
583
+ private runBatch;
584
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
585
+ invalidate(lookup?: string, code?: AsyncLabelCode): void;
586
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
587
+ prime(lookup: string, code: AsyncLabelCode, label: string | null): void;
588
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
589
+ setScope(scopeKey: string): void;
590
+ clear(): void;
591
+ private reset;
592
+ dispose(): void;
593
+ }
594
+ declare function createAsyncLabelStore(config: AsyncLabelConfig): AsyncLabelStore;
595
+
596
+ export { type AlignValue, type AsyncLabelCode, type AsyncLabelConfig, type AsyncLabelOptions, type AsyncLabelState, AsyncLabelStore, type AutocompleteProps, type BadgeProps, type BaseUIProps, type BorderProps, type BreadcrumbItem, type BreadcrumbProps, type BreakpointName, type ButtonGroupProps, type ButtonProps, type CSSLength, type CSSVariableStyle, type CardProps, type CarouselProps, type ChartData, type ChartProps, type ChartSeries, type ChartType, type ColorPalette, type ColorScale, type ColorShade, type ColorValue, type ComponentSize, type ComponentVariant, type DateTimeMode, type DateTimeProps, type DeepPartial, type DialogPosition, type DimensionValue, type DisableableProps, type DividerProps, type DropdownBehaviorProps, type DropdownModel, type FileUploadProps, type FlexContainerProps, type FlexDirection, type FlexItemProps, type FlexWrap, type FlowInputMode, type FlowUIStyle, type FlowUITheme, type FocusableProps, type HStackProps, type IconProps, type ImageProps, type InputProps, type JustifyValue, type KnobProps, type LabelLookup, type LabelProps, type LabelResolverContext, type LabelResults, type LayoutProps, type ListboxProps, type LoadingProps, type MenuItem, type MultiSelectProps, type NotificationHorizontal, type NotificationProps, type NotificationType, type NotificationVertical, type OTPInputProps, type Orientation, type PaletteColor, type PasswordInputProps, type PhoneCountry, type PhoneInputProps, type PhoneNumberValue, type PopoverProps, type PositionProps, type PositionValue, type RadiusToken, type RadiusValue, type RatingProps, type ReadOnlyProps, type RequiredProps, type ResolvedStyle, type ResponsiveObject, type ResponsiveValue, type SchemeColor, type SelectOption, type SelectionValue, type SliderProps, type SortDirection, type SortState, type SpacingProps, type SpacingToken, type SpacingValue, type StackProps, type StyleResolution, type SwitchProps, type TabItem, type TableColumn, type ThemeColorScheme, type ThemeMode, type TimelineItem, type TimelineProps, type TooltipLocation, type TooltipProps, type TreeDropdownProps, type TreeModel, type TreeMultiSelectProps, type TreeProps, type TypographyProps, type VStackProps, type VisualProps, clampNumber, createAsyncLabelStore, createTheme, defaultTheme, enabledSelectableDescendants, exportTableToExcel, exportTableToPdf, filterTree, flattenTree, flowClass, formatLocalDateTime, resolveColorValue, resolveFlowStyle, responsiveCSS, sanitizeInputValue, selectedTreeModels, setLocalDayBoundary, themeToCSS };
package/dist/index.js CHANGED
@@ -606,8 +606,304 @@ function selectedTreeModels(nodes, values) {
606
606
  const selected = new Set(values);
607
607
  return flattenTree(nodes).filter((node) => selected.has(node.value));
608
608
  }
609
+
610
+ // src/async-label.ts
611
+ var idle = Object.freeze({ status: "idle" });
612
+ var loading = Object.freeze({ status: "loading" });
613
+ var defaults = {
614
+ batchWindowMs: 10,
615
+ maxBatchSize: 100,
616
+ maxConcurrentBatches: 4,
617
+ cacheTtlMs: 3e5,
618
+ missingTtlMs: 3e4,
619
+ maxCacheEntries: 1e3,
620
+ requestTimeoutMs: 3e4
621
+ };
622
+ var AsyncLabelStore = class {
623
+ constructor(config) {
624
+ this.config = config;
625
+ this.scope = config.scopeKey ?? "default";
626
+ this.options = { ...defaults, ...config.options };
627
+ for (const [name, value] of Object.entries(this.options)) {
628
+ const minimum = [
629
+ "batchWindowMs",
630
+ "cacheTtlMs",
631
+ "missingTtlMs",
632
+ "maxCacheEntries"
633
+ ].includes(name) ? 0 : 1;
634
+ if (!Number.isInteger(value) || value < minimum)
635
+ throw new RangeError(`Invalid AsyncLabel option: ${name}`);
636
+ }
637
+ for (const lookup of Object.values(config.lookups)) {
638
+ if (lookup.cacheTtlMs !== void 0 && (!Number.isFinite(lookup.cacheTtlMs) || lookup.cacheTtlMs < 0)) {
639
+ throw new RangeError("Invalid lookup cacheTtlMs");
640
+ }
641
+ }
642
+ }
643
+ config;
644
+ options;
645
+ entries = /* @__PURE__ */ new Map();
646
+ cache = /* @__PURE__ */ new Map();
647
+ queue = /* @__PURE__ */ new Map();
648
+ controllers = /* @__PURE__ */ new Set();
649
+ timer;
650
+ active = 0;
651
+ generation = 0;
652
+ disposed = false;
653
+ scope;
654
+ get scopeKey() {
655
+ return this.scope;
656
+ }
657
+ /** Useful for diagnostics; active subscribers are separate from the bounded cache. */
658
+ get cacheSize() {
659
+ return this.cache.size;
660
+ }
661
+ key(lookup, code) {
662
+ if (code === void 0 || code === null || String(code).trim() === "")
663
+ return void 0;
664
+ return JSON.stringify([lookup, String(code)]);
665
+ }
666
+ /** Pure, stable snapshots; reading a snapshot never starts a network request. */
667
+ getSnapshot(lookup, code) {
668
+ const key = this.key(lookup, code);
669
+ if (!key || this.disposed) return idle;
670
+ const entry = this.entries.get(key);
671
+ if (entry) return entry.state;
672
+ const cached = this.cache.get(key);
673
+ return cached && cached.expiresAt > Date.now() ? cached.state : idle;
674
+ }
675
+ subscribe(lookup, code, listener) {
676
+ const key = this.key(lookup, code);
677
+ if (!key || this.disposed) return () => {
678
+ };
679
+ let entry = this.entries.get(key);
680
+ if (!entry) {
681
+ entry = {
682
+ key,
683
+ lookup,
684
+ code: String(code),
685
+ state: idle,
686
+ listeners: /* @__PURE__ */ new Set(),
687
+ version: 0,
688
+ pending: false
689
+ };
690
+ this.entries.set(key, entry);
691
+ }
692
+ entry.listeners.add(listener);
693
+ this.request(entry);
694
+ return () => {
695
+ entry.listeners.delete(listener);
696
+ if (!entry.listeners.size) {
697
+ if (this.queue.delete(key)) entry.pending = false;
698
+ if (!entry.pending) this.entries.delete(key);
699
+ }
700
+ };
701
+ }
702
+ emit(entry) {
703
+ for (const listener of [...entry.listeners]) listener();
704
+ }
705
+ request(entry) {
706
+ if (entry.pending || this.disposed) return;
707
+ const cached = this.cache.get(entry.key);
708
+ if (cached && cached.expiresAt > Date.now()) {
709
+ this.cache.delete(entry.key);
710
+ this.cache.set(entry.key, cached);
711
+ entry.state = cached.state;
712
+ this.emit(entry);
713
+ return;
714
+ }
715
+ this.cache.delete(entry.key);
716
+ if (!Object.hasOwn(this.config.lookups, entry.lookup)) {
717
+ entry.state = {
718
+ status: "error",
719
+ error: new Error(`Unknown lookup: ${entry.lookup}`)
720
+ };
721
+ this.emit(entry);
722
+ return;
723
+ }
724
+ entry.pending = true;
725
+ entry.state = loading;
726
+ this.queue.set(entry.key, entry);
727
+ this.emit(entry);
728
+ this.schedule();
729
+ }
730
+ schedule() {
731
+ if (this.timer !== void 0 || this.disposed || !this.queue.size) return;
732
+ this.timer = setTimeout(() => {
733
+ this.timer = void 0;
734
+ this.flush();
735
+ }, this.options.batchWindowMs);
736
+ }
737
+ flush() {
738
+ while (!this.disposed && this.active < this.options.maxConcurrentBatches && this.queue.size) {
739
+ const first = this.queue.values().next().value;
740
+ const batch = [];
741
+ for (const entry of this.queue.values()) {
742
+ if (entry.lookup === first.lookup) {
743
+ batch.push(entry);
744
+ this.queue.delete(entry.key);
745
+ if (batch.length === this.options.maxBatchSize) break;
746
+ }
747
+ }
748
+ void this.runBatch(first.lookup, batch);
749
+ }
750
+ }
751
+ cacheResult(entry, state) {
752
+ const ttl = state.status === "missing" ? this.options.missingTtlMs : this.config.lookups[entry.lookup].cacheTtlMs ?? this.options.cacheTtlMs;
753
+ if (!ttl || !this.options.maxCacheEntries) return;
754
+ this.cache.delete(entry.key);
755
+ this.cache.set(entry.key, { state, expiresAt: Date.now() + ttl });
756
+ while (this.cache.size > this.options.maxCacheEntries)
757
+ this.cache.delete(this.cache.keys().next().value);
758
+ }
759
+ async runBatch(lookup, batch) {
760
+ const generation = this.generation;
761
+ const scopeKey = this.scope;
762
+ const versions = batch.map((entry) => entry.version);
763
+ const controller = new AbortController();
764
+ this.controllers.add(controller);
765
+ this.active++;
766
+ let timeout;
767
+ const cancelled = new Promise((_, reject) => {
768
+ controller.signal.addEventListener(
769
+ "abort",
770
+ () => reject(controller.signal.reason ?? new Error("Lookup cancelled")),
771
+ { once: true }
772
+ );
773
+ timeout = setTimeout(
774
+ () => controller.abort(new Error("Lookup request timed out")),
775
+ this.options.requestTimeoutMs
776
+ );
777
+ });
778
+ try {
779
+ const result = await Promise.race([
780
+ Promise.resolve().then(() => {
781
+ if (controller.signal.aborted) throw controller.signal.reason;
782
+ return this.config.lookups[lookup].resolve(
783
+ batch.map((entry) => entry.code),
784
+ { scopeKey, signal: controller.signal }
785
+ );
786
+ }),
787
+ cancelled
788
+ ]);
789
+ if (this.disposed || generation !== this.generation) return;
790
+ batch.forEach((entry, index) => {
791
+ if (entry.version !== versions[index]) return;
792
+ const valid = result && Object.hasOwn(result, entry.code) && (typeof result[entry.code] === "string" || result[entry.code] === null);
793
+ entry.state = !valid ? {
794
+ status: "error",
795
+ error: new Error(`Incomplete lookup response for ${entry.code}`)
796
+ } : result[entry.code] === null ? { status: "missing" } : { status: "ready", label: result[entry.code] };
797
+ entry.pending = false;
798
+ if (entry.state.status !== "error")
799
+ this.cacheResult(entry, entry.state);
800
+ this.emit(entry);
801
+ if (!entry.listeners.size) this.entries.delete(entry.key);
802
+ });
803
+ } catch (error) {
804
+ if (this.disposed || generation !== this.generation) return;
805
+ batch.forEach((entry, index) => {
806
+ if (entry.version !== versions[index]) return;
807
+ entry.pending = false;
808
+ entry.state = { status: "error", error };
809
+ this.emit(entry);
810
+ if (!entry.listeners.size) this.entries.delete(entry.key);
811
+ });
812
+ } finally {
813
+ clearTimeout(timeout);
814
+ this.controllers.delete(controller);
815
+ if (generation === this.generation) {
816
+ this.active--;
817
+ this.flush();
818
+ }
819
+ }
820
+ }
821
+ /** Refetch active labels and evict cached results; lookup/code may be omitted. */
822
+ invalidate(lookup, code) {
823
+ const key = code === void 0 ? void 0 : this.key(lookup ?? "", code);
824
+ const matches = (entryKey, name) => key ? entryKey === key : !lookup || name === lookup;
825
+ for (const cachedKey of this.cache.keys()) {
826
+ const name = JSON.parse(cachedKey)[0];
827
+ if (matches(cachedKey, name)) this.cache.delete(cachedKey);
828
+ }
829
+ for (const entry of this.entries.values()) {
830
+ if (!matches(entry.key, entry.lookup)) continue;
831
+ entry.version++;
832
+ entry.pending = false;
833
+ this.queue.delete(entry.key);
834
+ entry.state = idle;
835
+ if (entry.listeners.size) this.request(entry);
836
+ else this.entries.delete(entry.key);
837
+ }
838
+ }
839
+ /** Publish a definitive save result, protecting it from older in-flight responses. */
840
+ prime(lookup, code, label) {
841
+ const key = this.key(lookup, code);
842
+ if (!key || this.disposed) return;
843
+ if (!Object.hasOwn(this.config.lookups, lookup))
844
+ throw new Error(`Unknown lookup: ${lookup}`);
845
+ const entry = this.entries.get(key) ?? {
846
+ key,
847
+ lookup,
848
+ code: String(code),
849
+ state: idle,
850
+ listeners: /* @__PURE__ */ new Set(),
851
+ version: 0,
852
+ pending: false
853
+ };
854
+ entry.version++;
855
+ entry.pending = false;
856
+ this.queue.delete(key);
857
+ entry.state = label === null ? { status: "missing" } : { status: "ready", label };
858
+ this.cacheResult(entry, entry.state);
859
+ this.emit(entry);
860
+ }
861
+ /** Scope changes cancel batches and prevent old results from entering the new scope. */
862
+ setScope(scopeKey) {
863
+ if (scopeKey === this.scope || this.disposed) return;
864
+ this.scope = scopeKey;
865
+ this.reset();
866
+ }
867
+ clear() {
868
+ if (!this.disposed) this.reset();
869
+ }
870
+ reset() {
871
+ this.generation++;
872
+ this.active = 0;
873
+ clearTimeout(this.timer);
874
+ this.timer = void 0;
875
+ for (const controller of this.controllers) controller.abort();
876
+ this.controllers.clear();
877
+ this.queue.clear();
878
+ this.cache.clear();
879
+ for (const entry of this.entries.values()) {
880
+ entry.version++;
881
+ entry.pending = false;
882
+ entry.state = idle;
883
+ if (entry.listeners.size) this.request(entry);
884
+ else this.entries.delete(entry.key);
885
+ }
886
+ }
887
+ dispose() {
888
+ if (this.disposed) return;
889
+ this.disposed = true;
890
+ this.generation++;
891
+ clearTimeout(this.timer);
892
+ this.timer = void 0;
893
+ for (const controller of this.controllers) controller.abort();
894
+ this.controllers.clear();
895
+ this.queue.clear();
896
+ this.cache.clear();
897
+ this.entries.clear();
898
+ }
899
+ };
900
+ function createAsyncLabelStore(config) {
901
+ return new AsyncLabelStore(config);
902
+ }
609
903
  export {
904
+ AsyncLabelStore,
610
905
  clampNumber,
906
+ createAsyncLabelStore,
611
907
  createTheme,
612
908
  defaultTheme,
613
909
  enabledSelectableDescendants,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akin2unde/flowui-core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Framework-independent contracts, themes and style resolution for FlowUI.",
5
5
  "author": "Akintunde Morakinyo",
6
6
  "repository": {
@@ -36,7 +36,8 @@
36
36
  "scripts": {
37
37
  "build": "tsup src/index.ts --format esm,cjs --dts --clean",
38
38
  "typecheck": "tsc --noEmit",
39
- "test": "vitest run"
39
+ "test": "vitest run",
40
+ "prepack": "node ../../scripts/prepack.mjs core"
40
41
  },
41
42
  "dependencies": {
42
43
  "csstype": "^3.1.3"