Global

Members

(constant) ACK_DISMISSED_KEY :string

LocalStorage key for acknowledgment dismissal

Type:
  • string
Source:

(constant) API_CACHE_KEY :string

LocalStorage key for cached API data

Type:
  • string
Source:

(constant) API_KEY_STORAGE_KEY :string

LocalStorage key for API provider information

Type:
  • string
Source:

(constant) API_PROVIDERS

API Provider configurations for metals pricing services

Each provider configuration contains:

Properties:
Name Type Description
name string

Display name for the provider

baseUrl string

Base API endpoint URL

endpoints Object

API endpoints for different metals

parseResponse function

Function to parse API response into standard format

documentation string

URL to provider's API documentation

batchSupported boolean

Whether provider supports batch requests

batchEndpoint string

Batch request endpoint pattern

parseBatchResponse function

Function to parse batch API response

Source:

(constant) APP_VERSION :string

Application version Follows BRANCH.RELEASE.PATCH.state format State codes: a=alpha, b=beta, rc=release candidate Example: 3.03.02a → branch 3, release 03, patch 02, alpha Updated: 2026-02-12 - STACK-38/STACK-31: Responsive card view + mobile layout

Type:
  • string
Source:

(constant) APP_VERSION_KEY :string

LocalStorage key for current app version

Type:
  • string
Source:

(constant) AUTOCOMPLETE_CONFIG

Autocomplete system configuration

Source:

(constant) BRANDING_DOMAIN_OPTIONS

Domain-based branding configuration

Properties:
Name Type Description
domainMap Object.<string, string>

Map of domain keywords to custom display names. Keys are compared in lowercase and may omit the domain extension when removeExtension is true.

removeExtension boolean

When true, strips the domain extension (e.g. ".com") before lookup

alwaysOverride boolean

When true, domain mapping overrides BRANDING_TITLE across the entire application

Source:

(constant) BRANDING_DOMAIN_OVERRIDE :string|null

Title detected from the current domain or null if no mapping found

Falls back to BRANDING_TITLE when running under file:// or no domain is detected.

Type:
  • string | null
Source:

(constant) BRANDING_TITLE :string

Optional custom application title

Type:
  • string
Source:

(constant) CARD_STYLE_KEY :string

LocalStorage key for card view style (A/B/C/D) (STAK-118)

Type:
  • string
Source:

(constant) CATALOG_HISTORY_KEY :string

LocalStorage key for catalog API call history

Type:
  • string
Source:

(constant) CATALOG_MAP_KEY :string

LocalStorage key for S#/N# associations

Type:
  • string
Source:

(constant) CERT_LOOKUP_URLS :Object.<string, string>

Cert verification lookup URLs for grading authorities. {certNumber} is replaced with the actual certification number. URLs without {certNumber} open the generic verification page.

Type:
  • Object.<string, string>
Source:

(constant) CLOUD_PROVIDERS

Cloud provider configurations. Client IDs are placeholder — replace with real registered app IDs.

Source:

(constant) DEBUG :boolean

Global debug flag, can be toggled via DEV_MODE or ?debug query parameter

Type:
  • boolean
Source:

(constant) DEFAULT_API_CACHE_DURATION :number

Default cache duration in milliseconds (24 hours)

Type:
  • number
Source:

(constant) DEFAULT_API_QUOTA :number

Default monthly API call quota

Type:
  • number
Source:

(constant) DEFAULT_CURRENCY :string

Default currency code for monetary formatting

Type:
  • string
Source:

(constant) DEFAULT_SORT_COL_KEY :string

LocalStorage key for default inventory sort column

Type:
  • string
Source:

(constant) DEFAULT_SORT_DIR_KEY :string

LocalStorage key for default inventory sort direction

Type:
  • string
Source:

(constant) DESKTOP_CARD_VIEW_KEY :string

LocalStorage key for desktop card view toggle (STAK-118)

Type:
  • string
Source:

(constant) DEV_MODE :boolean

Enables verbose debug logging when true

Type:
  • boolean
Source:

(constant) DISPLAY_CURRENCY_KEY :string

LocalStorage key for display currency preference (STACK-50)

Type:
  • string
Source:

(constant) EXCHANGE_RATES_KEY :string

LocalStorage key for cached exchange rates (STACK-50)

Type:
  • string
Source:

(constant) EXCHANGE_RATE_API_URL :string

Free exchange rate API (no key required)

Type:
  • string
Source:

(constant) FALLBACK_EXCHANGE_RATES :Object.<string, number>

Fallback exchange rates (USD-based) for offline/file:// use (STACK-50) Updated Feb 2026. Used only when API fetch fails and no cached rates exist.

Type:
  • Object.<string, number>
Source:

(constant) FEATURE_FLAGS

Feature flags configuration Controls experimental features and gradual rollouts

Each feature flag contains:

Properties:
Name Type Description
enabled boolean

Default enabled state

urlOverride boolean

Allow URL parameter override

userToggle boolean

Allow user preference toggle

description string

Human-readable description

phase string

Development phase (dev/testing/beta/stable)

Source:

(constant) FEATURE_FLAGS_KEY :string

LocalStorage key for feature flags

Type:
  • string
Source:

(constant) FIELD_COERCIONS

Coercion rules: fieldId → (rawValue) => coerced value

Source:

(constant) FILTER_CHIP_CATEGORY_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>

Default filter chip category configuration. Order determines display order.

Type:
  • Array.<{id: string, label: string, enabled: boolean}>
Source:

(constant) GB_ESTIMATE_MODIFIER_KEY :string

LocalStorage key for user-configurable premium modifier

Type:
  • string
Source:

(constant) GB_ESTIMATE_PREMIUM :number

Default estimation premium multiplier (1.0 = no premium, pure 2x spot)

Type:
  • number
Source:

(constant) GB_TO_OZT :number

Conversion factor: 1 Goldback = 0.001 troy oz 24K gold

Type:
  • number
Source:

(constant) GITHUB_RELEASES_URL :string

Fallback link for static version badge

Type:
  • string
Source:

(constant) GOLDBACK_DENOMINATIONS :Array.<{weight: number, label: string, goldOz: number}>

Standard Goldback denominations with gold content. weight = denomination value (used as item.weight when weightUnit='gb') goldOz = troy oz of 24K gold per note

Type:
  • Array.<{weight: number, label: string, goldOz: number}>
Source:

(constant) GOLDBACK_ENABLED_KEY :string

LocalStorage key for Goldback pricing toggle (STACK-45)

Type:
  • string
Source:

(constant) GOLDBACK_ESTIMATE_ENABLED_KEY :string

LocalStorage key for Goldback estimation toggle (STACK-52)

Type:
  • string
Source:

(constant) GOLDBACK_PRICES_KEY :string

LocalStorage key for Goldback denomination prices (STACK-45)

Type:
  • string
Source:

(constant) GOLDBACK_PRICE_HISTORY_KEY :string

LocalStorage key for Goldback price history (STACK-45)

Type:
  • string
Source:

(constant) HEADER_SYNC_BTN_KEY :string

LocalStorage key for header sync button visibility

Type:
  • string
Source:

(constant) HEADER_TREND_BTN_KEY :string

LocalStorage key for header trend button visibility

Type:
  • string
Source:

(constant) IMAGE_MAX_BYTES :number

Max output size per image side in bytes (500 KB)

Type:
  • number
Source:

(constant) IMAGE_MAX_DIM :number

Max image dimension in px for resize

Type:
  • number
Source:

(constant) IMAGE_QUALITY :number

Default compression quality (0-1)

Type:
  • number
Source:

(constant) INLINE_CHIP_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>

Default inline chip configuration. Order determines display order.

Type:
  • Array.<{id: string, label: string, enabled: boolean}>
Source:

(constant) ITEMS_PER_PAGE_KEY :string

LocalStorage key for items per page setting

Type:
  • string
Source:

(constant) ITEM_PRICE_HISTORY_KEY :string

LocalStorage key for per-item price history (STACK-43)

Type:
  • string
Source:

(constant) ITEM_TAGS_KEY :string

LocalStorage key for item tags mapping (STAK-126)

Type:
  • string
Source:

(constant) LAST_API_SYNC_KEY :string

LocalStorage key for last API sync timestamp

Type:
  • string
Source:

(constant) LAST_CACHE_REFRESH_KEY :string

LocalStorage key for last cache refresh timestamp

Type:
  • string
Source:

(constant) LAST_VERSION_CHECK_KEY :string

LocalStorage key for last remote version check timestamp (STACK-67)

Type:
  • string
Source:

(constant) LATEST_REMOTE_URL_KEY :string

LocalStorage key for cached latest remote release URL (STACK-67)

Type:
  • string
Source:

(constant) LATEST_REMOTE_VERSION_KEY :string

LocalStorage key for cached latest remote version (STACK-67)

Type:
  • string
Source:

(constant) LAYOUT_SECTION_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>

Default layout section configuration. Order determines display order.

Type:
  • Array.<{id: string, label: string, enabled: boolean}>
Source:

(constant) LOG_TAB_RENDERERS

Dispatch map: log sub-tab key → window function name

Source:

(constant) LS_KEY :string

LocalStorage key for inventory data

Type:
  • string
Source:

(constant) MAX_LOCAL_FILE_SIZE

Maximum upload size in bytes for local imports (2MB)

Source:

(constant) MAX_TAGS_PER_ITEM :number

Maximum number of tags allowed per item (STAK-126)

Type:
  • number
Source:

(constant) MAX_TAG_LENGTH :number

Maximum characters per tag name (STAK-126)

Type:
  • number
Source:

(constant) METALS

Metal configuration object - Central registry for all metal-related information

This configuration drives the entire application's metal handling by defining:

  • Display names for user interface elements
  • Key identifiers for data structures and calculations
  • DOM element ID patterns for dynamic element selection
  • LocalStorage keys for persistent data storage
  • CSS color variables for styling and theming

Each metal configuration contains:

Properties:
Name Type Description
name string

Display name used in UI elements and forms

key string

Lowercase identifier for data objects and calculations

spotKey string

DOM ID pattern for spot price input elements

localStorageKey string

Key for storing spot prices in localStorage

color string

CSS custom property name for metal-specific styling

Adding a new metal type requires:

  1. Adding configuration here
  2. Adding corresponding HTML elements following the naming pattern
  3. Adding CSS custom properties for colors
  4. The application will automatically handle the rest through iteration
Source:

(constant) METAL_COLORS

Renders the main inventory table with all current display settings

This is the primary display function that:

  • Applies current search filters to inventory data
  • Sorts data according to user-selected column and direction
  • Implements pagination to show only current page items
  • Generates HTML table rows with interactive elements
  • Updates sort indicators in column headers
  • Refreshes pagination controls and summary totals
  • Re-establishes column resizing functionality

Called whenever inventory data changes or display settings update

Source:

(constant) METAL_ORDER_KEY :string

LocalStorage key for metal order/visibility config

Type:
  • string
Source:

(constant) METAL_SYMBOLS

Symbol mapping for API requests (metal name → ISO 4217 precious metal code)

Source:

(constant) NUMISTA_VIEW_FIELD_DEFAULTS :Object.<string, boolean>

Default Numista view field visibility. All enabled by default.

Type:
  • Object.<string, boolean>
Source:

(constant) NumistaLookup

Numista Search Lookup Module Pattern-based query rewriting for improved Numista search results. Matches user input against known coin naming patterns and rewrites queries to use Numista's canonical naming convention.

Follows the IIFE module pattern used by customMapping.js.

Source:

(constant) PREBUILT_LOOKUP_DATA

Pre-built lookup database with common precious metals items Sourced from comprehensive industry data for enhanced autocomplete suggestions

Source:

(constant) PRICE_HISTORY_COLS

Column keys for the price history table, matching order.

Source:

(constant) Remote :string

base URL for historical data (file:// fallback)

Type:
  • string
Source:

(constant) SEED_CUSTOM_RULES :Array.<{pattern: string, replacement: string, numistaId: (string|null), obverse: string, reverse: string}>

Seed custom rule definitions with embedded base64 WebP image data. Each entry becomes a custom pattern rule in NumistaLookup, visible in Settings > Images > Custom Pattern Rules with thumbnails.

Type:
  • Array.<{pattern: string, replacement: string, numistaId: (string|null), obverse: string, reverse: string}>
Source:

(constant) SEED_DATA_YEARS :Array.<number>

Years with available seed data. Updated by generate-seed-data.py.

Type:
  • Array.<number>
Source:

(constant) SEED_IMAGES_VERSION :string

Version string for seed images. Bump when images are updated so existing caches get refreshed. Stored in localStorage as 'seedImagesVer'.

Type:
  • string
Source:

(constant) SEED_INVENTORY_ITEMS

Sample inventory items for first-time users. Provides 8 items across 4 metals so new users see a populated table, learn the data model, and discover filter chips via grouped names.

3x American Silver Eagle (graded, Numista 298883) — triggers name chip 3x Canadian Gold Maple Leaf (Numista 75250) — triggers name chip 1x Platinum Round, 1x Palladium Bar

Source:

(constant) SERIAL_KEY :string

LocalStorage key for inventory serial counter

Type:
  • string
Source:

(constant) SPOT_COMPARE_MODE_KEY :string

LocalStorage key for 24h % comparison mode (STACK-92)

Type:
  • string
Source:

(constant) SPOT_HISTORY_KEY :string

LocalStorage key for spot price history

Type:
  • string
Source:

(constant) SPOT_TREND_KEY :string

LocalStorage key for persisted spot trend period

Type:
  • string
Source:

(constant) SPOT_TREND_RANGE_KEY :string

LocalStorage key for sparkline trend range preferences

Type:
  • string
Source:

(constant) STORAGE_KEY_LABELS

Friendly display names for known localStorage keys

Source:

(constant) STORAGE_TINY_THRESHOLD_KB

Keys under this KB threshold are considered "minor" and hidden by default

Source:

(constant) SUPPORTED_CURRENCIES :Array.<{code: string, name: string}>

Supported display currencies for the currency selector (STACK-50)

Type:
  • Array.<{code: string, name: string}>
Source:

(constant) SYNC_FILE_PATH

Dropbox path for the rolling sync vault file

Source:

(constant) SYNC_META_PATH

Dropbox path for the lightweight sync metadata pointer

Source:

(constant) SYNC_POLL_INTERVAL

Poll interval for remote change detection (10 minutes in ms)

Source:

(constant) SYNC_PUSH_DEBOUNCE

Debounce delay before pushing after a saveInventory() call (2 seconds)

Source:

(constant) SYNC_SCOPE_KEYS

Keys included in a sync vault (excludes API keys, tokens, spot history). Only inventory data + display preferences that are meaningful across devices.

Source:

(constant) THEME_KEY :string

LocalStorage key for theme preference

Type:
  • string
Source:

(constant) TIMEZONE_KEY :string

LocalStorage key for display timezone preference (STACK-63)

Type:
  • string
Source:

(constant) TREND_PRESETS

Trend period presets and labels for the header trend cycle button.

Source:

(constant) TREND_PRESETS

Trend period presets and labels for the header trend cycle button.

Source:

(constant) VALID_TYPES :Array.<string>

Allowed inventory item types

Type:
  • Array.<string>
Source:

(constant) VAULT_FILE_EXTENSION :Array.<string>

List of recognized localStorage keys for cleanup validation

Type:
  • Array.<string>
Source:

(constant) VERSION_ACK_KEY :string

LocalStorage key for acknowledged app version

Type:
  • string
Source:

(constant) VERSION_CHECK_TTL :number

Cache TTL for remote version check in ms (24 hours)

Type:
  • number
Source:

(constant) VERSION_CHECK_URL :string

Remote endpoint for latest version info (STACK-67)

Type:
  • string
Source:

(constant) VIEW_METADATA_TTL :number

Numista metadata cache TTL: 30 days in milliseconds. Used by viewModal.js to skip re-fetching recently cached metadata.

Type:
  • number
Source:

(constant) VIEW_MODAL_SECTION_DEFAULTS :Array.<{id: string, label: string, enabled: boolean}>

Default view modal section configuration. Order determines display order.

Type:
  • Array.<{id: string, label: string, enabled: boolean}>
Source:

(constant) _VIEW_CHART_DEFAULT_RANGE :number

Default chart range in days (-1 = from purchase date, falls back to 30d)

Type:
  • number
Source:

(constant) _VIEW_CHART_RANGES :Array.<number>

Available chart range options (0 = all, -1 = from purchase date)

Type:
  • Array.<number>
Source:

(constant) _VIEW_CHART_RANGE_LABELS :Array.<string>

Display labels for chart range pills

Type:
  • Array.<string>
Source:

(constant) __ST_COMP_PREFIX

Storage compression helpers (Phase 1C)

Source:

_cardClickBound :boolean

Type:
  • boolean
Source:

_cardClickBound :boolean

Type:
  • boolean
Source:

_cardSortBarBound :boolean

Whether card sort bar event listeners have been bound

Type:
  • boolean
Source:

_cardSortBarBound :boolean

Whether card sort bar event listeners have been bound

Type:
  • boolean
Source:

_cloudContext :object|null

Cloud context for cloud-export/cloud-import modes

Type:
  • object | null
Source:

_cvBlobUrls :Array.<string>

Blob URLs to revoke on next render

Type:
  • Array.<string>
Source:

_cvBlobUrls :Array.<string>

Blob URLs to revoke on next render

Type:
  • Array.<string>
Source:

_cvChartInstances :Array.<Chart>

Active card chart instances to destroy on re-render

Type:
  • Array.<Chart>
Source:

_cvChartInstances :Array.<Chart>

Active card chart instances to destroy on re-render

Type:
  • Array.<Chart>
Source:

_cvImageObserver :IntersectionObserver|null

Type:
  • IntersectionObserver | null
Source:

_cvImageObserver :IntersectionObserver|null

Type:
  • IntersectionObserver | null
Source:

_deleteObverseOnSave :boolean

User clicked Remove on obverse — delete on save

Type:
  • boolean
Source:

_deleteReverseOnSave :boolean

User clicked Remove on reverse — delete on save

Type:
  • boolean
Source:

_hScrollWired

Whether the custom H-scroll bar event listeners have been wired

Source:

_hScrollWired

Whether the custom H-scroll bar event listeners have been wired

Source:

_itemPriceModalFilterText :string

Filter text for the per-item modal table

Type:
  • string
Source:

_itemPriceModalUuid :string

UUID of the item currently displayed in the per-item modal

Type:
  • string
Source:

_patternMode

Settings modal listener binders (STAK-135)

Keeps listener wiring split by concern while preserving existing behavior.

Source:

_pendingObverseBlob :Blob|null

Pending obverse upload blob — saved on item commit

Type:
  • Blob | null
Source:

_pendingObversePreviewUrl :string|null

Preview object URL for obverse — revoked on modal close

Type:
  • string | null
Source:

_pendingReverseBlob :Blob|null

Pending reverse upload blob — saved on item commit

Type:
  • Blob | null
Source:

_pendingReversePreviewUrl :string|null

Preview object URL for reverse — revoked on modal close

Type:
  • string | null
Source:

_statusCells :Map.<string, HTMLElement>

Status cells keyed by catalogId for live updates

Type:
  • Map.<string, HTMLElement>
Source:

_storageTinyVisible

True = show minor keys; toggled by the button in the panel

Source:

(constant) _storedSortCol :Object

Sorting state tracking — initialized from user preference or factory default

Type:
  • Object
Source:

_syncPollerTimer :number|null

setInterval handle for the polling loop

Type:
  • number | null
Source:

_syncProvider :string

Currently active sync provider

Type:
  • string
Source:

_syncPushInFlight :boolean

Whether a push is currently in progress

Type:
  • boolean
Source:

_syncRetryDelay :number

Retry backoff multiplier for 429 / network errors

Type:
  • number
Source:

_thumbBlobUrls

Blob URLs created by _enhanceTableThumbnails — revoked on each re-render

Source:

_thumbObserver

IntersectionObserver instance for lazy-loading table thumbnails

Source:

_vaultPendingFile :Uint8Array|null

Pending file bytes for import

Type:
  • Uint8Array | null
Source:

_viewModalChartInstance :Chart|null

Price history chart instance — destroyed on modal close

Type:
  • Chart | null
Source:

_viewModalObjectUrls :Array.<string>

Active object URLs created for the current view modal session. Revoked on modal close to prevent memory leaks.

Type:
  • Array.<string>
Source:

(constant) _viewYearCache :Map.<number, Array>

Year-file cache shared with spot.js when available

Type:
  • Map.<number, Array>
Source:

(constant) _viewYearFetchPromises :Map.<number, Promise.<Array>>

In-flight fetch promises to deduplicate concurrent requests

Type:
  • Map.<number, Promise.<Array>>
Source:

activeFilters :Object.<string, FilterConfig>

Type:
Source:

apiCache :Object|null

Cached API data with timestamp

Type:
  • Object | null
Source:

apiConfig :Object|null

Current Metals API configuration

Type:
  • Object | null
Source:

apiHistoryEntries :Array.<Object>

In-memory buffer for API history log entries

Type:
  • Array.<Object>
Source:

apiHistoryFilterText :string

Active filter text for searching API history

Type:
  • string
Source:

apiHistorySortAsc :boolean

Sort direction for the API history table

Type:
  • boolean
Source:

apiHistorySortColumn :string

Current sort column for the API history table

Type:
  • string
Source:

brandingWarned

Gets the active branding name considering domain overrides

Source:

catalogHistory :Array

Catalog API call history records

Type:
  • Array
Source:

catalogMap :Object

Backward compatibility for catalogMap - now managed by catalogManager

Type:
  • Object
Source:

changeLog :Array

Change log entries

Type:
  • Array
Source:

chartInstances :Object

Chart instances for proper cleanup

Type:
  • Object
Source:

cloudBackupEnabled

Flag indicating whether cloud backup is enabled

Source:

compositionOptions :Set.<string>

Available composition options

Type:
  • Set.<string>
Source:

currentLookupTable :LookupTable|null

Current lookup table instance

Type:
Source:

detailsChartMetric :string

Current pie chart metric — purchase | melt | retail | gainLoss

Type:
  • string
Source:

detailsResizeObserver :ResizeObserver|null

Active ResizeObserver for chart resize handling

Type:
  • ResizeObserver | null
Source:

displayCurrency :string

User's selected display currency (ISO 4217), default USD (STACK-50)

Type:
  • string
Source:

editingChangeLogIndex :number|null

Change log entry currently being edited

Type:
  • number | null
Source:

editingIndex :number|null

Index of item being edited (null = no edit in progress)

Type:
  • number | null
Source:

(constant) elements :Object

Cached DOM elements for performance

Type:
  • Object
Source:

exchangeRates :Object.<string, number>

Cached exchange rates: 1 USD = rate × target currency (STACK-50)

Type:
  • Object.<string, number>
Source:

(constant) featureFlags :FeatureFlags

Global feature flags instance

Type:
Source:

gbHistoryFilterText :string

Current filter text for the history table

Type:
  • string
Source:

gbHistorySortAsc :boolean

Sort direction (true = ascending)

Type:
  • boolean
Source:

gbHistorySortColumn :string

Current sort column

Type:
  • string
Source:

goldbackEnabled :boolean

Whether Goldback denomination pricing is enabled (STACK-45)

Type:
  • boolean
Source:

goldbackEstimateEnabled :boolean

Whether Goldback real-time price estimation is enabled (STACK-52)

Type:
  • boolean
Source:

goldbackEstimateModifier :number

User-configurable premium modifier for Goldback estimation (STACK-52)

Type:
  • number
Source:

goldbackPriceHistory :Object

Goldback price history keyed by weight string (STACK-45)

Type:
  • Object
Source:

goldbackPrices :Object

Goldback denomination prices keyed by weight string (STACK-45)

Type:
  • Object
Source:

(constant) historicalDataCache :Map.<number, Array>

Cached year-file entries keyed by year

Type:
  • Map.<number, Array>
Source:

(constant) historicalFetchPromises :Map.<number, Promise.<Array>>

In-flight fetch promises to deduplicate concurrent requests

Type:
  • Map.<number, Promise.<Array>>
Source:

inventory :Array

Main inventory data structure

Type:
  • Array
Source:

itemPriceHistory :Object

Per-item price history keyed by UUID (STACK-43)

Type:
  • Object
Source:

itemTags :Object

Item tags mapping: { [uuid]: string[] } (STAK-126)

Type:
  • Object
Source:

itemsPerPage :number

Number of visible rows in the portal (scrollable table) view

Type:
  • number
Source:

marketValueViewItems :Set.<number>

Items currently showing market value instead of purchase price

Type:
  • Set.<number>
Source:

notesIndex :number|null

Index of item whose notes are being edited

Type:
  • number | null
Source:

priceHistoryFilterText :string

Filter text for the settings price history table

Type:
  • string
Source:

scheduleSyncPush :function

Debounced version of pushSyncVault

Type:
  • function
Source:

searchQuery :string

Current search query

Type:
  • string
Source:

settingsCatalogSortAsc :boolean

Sort ascending for settings catalog history table

Type:
  • boolean
Source:

settingsCatalogSortColumn :string

Sort column for settings catalog history table

Type:
  • string
Source:

settingsCloudSortAsc :boolean

Sort ascending for settings cloud activity table

Type:
  • boolean
Source:

settingsCloudSortColumn :string|null

Sort column for settings cloud activity table

Type:
  • string | null
Source:

settingsLbmaControlsBound :boolean

Prevent duplicate LBMA control binding

Type:
  • boolean
Source:

settingsLbmaLoadPromise :Promise.<Array.<Object>>|null

In-flight LBMA load promise

Type:
  • Promise.<Array.<Object>> | null
Source:

settingsLbmaReferenceCache :Array.<Object>|null

Cached LBMA reference entries

Type:
  • Array.<Object> | null
Source:

settingsLbmaSortAsc :boolean

Sort ascending for settings LBMA reference table

Type:
  • boolean
Source:

settingsLbmaSortColumn :string

Current sort column for settings LBMA reference table

Type:
  • string
Source:

settingsPriceSortAsc :boolean

Sort ascending for settings price history table

Type:
  • boolean
Source:

settingsPriceSortColumn :string

Sort column for settings price history table

Type:
  • string
Source:

settingsSpotSortAsc :boolean

Sort ascending for settings spot history table

Type:
  • boolean
Source:

settingsSpotSortColumn :string

Current sort column for settings spot history table

Type:
  • string
Source:

sparklineInstances :Object

Sparkline Chart.js instances keyed by metal (for cleanup)

Type:
  • Object
Source:

spotHistory :Array

Historical spot price records

Type:
  • Array
Source:

spotPrices :Object

Current spot prices for all metals

Type:
  • Object
Source:

Methods

_addDetail()

Add a detail item to a grid

Source:

_applyTrend(val)

Applies a trend period value to all four metal sparkline selects and updates the header trend label.

Parameters:
Name Type Description
val string

The trend period value to apply.

Source:

_applyTrend(val)

Applies a trend period value to all four metal sparkline selects and updates the header trend label.

Parameters:
Name Type Description
val string

The trend period value to apply.

Source:

_cardChipsHTML(item, smallopt) → {string}

Builds chip HTML for card views.

Parameters:
Name Type Attributes Default Description
item object
small boolean <optional>
false
Source:
Returns:
Type
string

_cardChipsHTML(item, smallopt) → {string}

Builds chip HTML for card views.

Parameters:
Name Type Attributes Default Description
item object
small boolean <optional>
false
Source:
Returns:
Type
string

_cardFmt()

Format currency using app's formatCurrency or simple fallback.

Source:

_cardFmt()

Format currency using app's formatCurrency or simple fallback.

Source:

_cardImageHTML(item, extraClassopt, sideopt) → {string}

Returns coin image HTML. Renders an with data attributes for async ImageCache resolution (same pattern as table thumbnails in inventory.js). Falls back to a metal-initial placeholder via onerror.

Parameters:
Name Type Attributes Default Description
item object
extraClass string <optional>
''
side string <optional>
'obverse'

'obverse' or 'reverse'

Source:
Returns:
Type
string

_cardImageHTML(item, extraClassopt, sideopt) → {string}

Returns coin image HTML. Renders an with data attributes for async ImageCache resolution (same pattern as table thumbnails in inventory.js). Falls back to a metal-initial placeholder via onerror.

Parameters:
Name Type Attributes Default Description
item object
extraClass string <optional>
''
side string <optional>
'obverse'

'obverse' or 'reverse'

Source:
Returns:
Type
string

_cardMetalClass(metal) → {string}

Returns metal CSS class for card border/accent.

Parameters:
Name Type Description
metal string
Source:
Returns:
Type
string

_cardMetalClass(metal) → {string}

Returns metal CSS class for card border/accent.

Parameters:
Name Type Description
metal string
Source:
Returns:
Type
string

_cloudBackupWithCachedPw()

Perform a cached-password cloud backup (encrypt + upload, no vault modal).

Source:

(async) _cloudBtnAction(btn, label, action, errorPrefix, finallyFnopt)

Run an async action while showing a loading state on a button. Saves innerHTML, disables the button, runs the action, then restores.

Parameters:
Name Type Attributes Description
btn HTMLElement
label string

loading text to show (e.g. 'Uploading…')

action function

async function to execute

errorPrefix string

prefix for alert on failure

finallyFn function <optional>

optional cleanup in finally block

Source:

(async) _cloudRestoreWithCachedPw()

Perform a cached-password cloud restore (decrypt + restore, no vault modal).

Source:

_computePortfolioSummary() → {Object}

Computes portfolio summary totals for currently filtered items.

Source:
Returns:
Type
Object

_computePortfolioSummary() → {Object}

Computes portfolio summary totals for currently filtered items.

Source:
Returns:
Type
Object

_createPriceHistoryChart(canvas, allSpotEntries, allRetailEntries, purchasePerUnit, meltFactor, daysopt, purchaseDateopt, currentRetailopt, fromTsopt, toTsopt)

Create a Chart.js line chart showing price history for the viewed item. Primary: melt value derived from spotHistory (dense daily data). Secondary: retail value anchored from purchase date/price to current market value, with sparse itemPriceHistory snapshots in between. Purchase price shown as a flat dashed reference line.

Parameters:
Name Type Attributes Default Description
canvas HTMLCanvasElement
allSpotEntries Array.<{ts:number, spot:number}>

Daily spot prices for this metal

allRetailEntries Array.<{ts:number, retail:number}>

Sparse retail value snapshots

purchasePerUnit number

Original purchase price per unit

meltFactor number

weightOz * qty * purity (melt = spot * meltFactor)

days number <optional>
0

Number of days to show (0 = all)

purchaseDate number <optional>
0

Purchase date timestamp (anchor start for retail line)

currentRetail number <optional>
0

Current market/retail value (anchor end for retail line)

fromTs number <optional>
0

Custom range start timestamp (0 = unbounded)

toTs number <optional>
0

Custom range end timestamp (0 = unbounded)

Source:

_cvEscapeAttr(s) → {string}

Escapes HTML attribute values — fallback for card-view context. The main escapeAttribute lives in inventory.js (loaded before this file).

Parameters:
Name Type Description
s string
Source:
Returns:
Type
string

_cvEscapeAttr(s) → {string}

Escapes HTML attribute values — fallback for card-view context. The main escapeAttribute lives in inventory.js (loaded before this file).

Parameters:
Name Type Description
s string
Source:
Returns:
Type
string

_darkenColor(color, amount) → {string}

Darken a hex/rgb color by a factor (0–1). 0 = no change, 1 = black.

Parameters:
Name Type Description
color string

Hex or rgb() string

amount number

Darkening factor

Source:
Returns:

Hex color

Type
string

_dataToPolylineScaled(data, w, h, globalMin, globalMax, padYopt) → {string}

Converts data to SVG polyline using a shared min/max scale.

Parameters:
Name Type Attributes Default Description
data Array.<number>
w number

SVG width

h number

SVG height

globalMin number
globalMax number
padY number <optional>
4
Source:
Returns:
Type
string

_dataToPolylineScaled(data, w, h, globalMin, globalMax, padYopt) → {string}

Converts data to SVG polyline using a shared min/max scale.

Parameters:
Name Type Attributes Default Description
data Array.<number>
w number

SVG width

h number

SVG height

globalMin number
globalMax number
padY number <optional>
4
Source:
Returns:
Type
string

_detailItem()

Create a label/value detail item element

Source:

_el()

Create element with className

Source:

(async) _enhanceCardImages(container)

Enhances card thumbnail images from IndexedDB ImageCache. Uses IntersectionObserver for lazy loading (same pattern as table thumbnails).

Parameters:
Name Type Description
container HTMLElement
Source:

(async) _enhanceCardImages(container)

Enhances card thumbnail images from IndexedDB ImageCache. Uses IntersectionObserver for lazy loading (same pattern as table thumbnails).

Parameters:
Name Type Description
container HTMLElement
Source:

(async) _enhanceTableThumbnails()

Upgrades table thumbnail src attributes from IDB blob URLs using IntersectionObserver for viewport-based lazy loading. Pre-loads 200px before viewport for smooth scrolling.

Source:

_extractMetadata(result) → {Object}

Extract metadata fields from a Numista API result.

Parameters:
Name Type Description
result Object
Source:
Returns:
Type
Object

(async) _fetchHistoricalSpotData(metalName, days, fromTsopt, toTsopt) → {Promise.<Array.<{ts:number, spot:number}>>}

Fetch full historical spot data for a metal by loading year files. Merges fetched year-file data with live spotHistory, deduplicates by day (live data wins over seed). Returns sorted {ts, spot} entries.

For ranges <= 180 days, just returns the in-memory spotHistory slice (no fetch). For longer ranges (including "All"), async-fetches year files back to 1968.

Parameters:
Name Type Attributes Default Description
metalName string

Metal name ('Silver', 'Gold', etc.)

days number

Number of days (0 = all available data)

fromTs number <optional>
0

Custom range start (0 = unbounded)

toTs number <optional>
0

Custom range end (0 = unbounded)

Source:
Returns:

Sorted daily spot entries

Type
Promise.<Array.<{ts:number, spot:number}>>

(async) _fetchNumistaResult(catalogId) → {Promise.<(Object|null)>}

Fetch a Numista item by catalogId. Returns the normalized result or null.

Parameters:
Name Type Description
catalogId string
Source:
Returns:
Type
Promise.<(Object|null)>

_fetchYearFile(year) → {Promise.<Array>}

Fetch a single year file with three-tier fallback (fetch → XHR → remote). Reuses spot.js cache/fetcher when available; falls back to own implementation. Deduplicates concurrent fetches for the same year.

Parameters:
Name Type Description
year number
Source:
Returns:
Type
Promise.<Array>

_getBulkImageSides() → {Object}

Reads tableImageSides setting and returns which sides to display.

Source:
Returns:
Type
Object

_getOrCreateHScrollBar() → {Object|null}

Creates the scrollbar DOM node (once) and inserts it after .portal-scroll.

Source:
Returns:
Type
Object | null

_getOrCreateHScrollBar() → {Object|null}

Creates the scrollbar DOM node (once) and inserts it after .portal-scroll.

Source:
Returns:
Type
Object | null

_getThumbPlaceholder(metal, type) → {string}

Generate an inline SVG data URI for a metal-themed placeholder thumbnail. Uses the metal's brand color and an icon based on item type (coin vs bar).

Parameters:
Name Type Description
metal string

Metal name (Silver, Gold, Platinum, Palladium)

type string

Item type (Coin, Bar, Round, etc.)

Source:
Returns:

data:image/svg+xml URI

Type
string

_getViewMetrics(item) → {Object}

Compute shared metrics used by all view modal section renderers.

Parameters:
Name Type Description
item Object

Inventory item

Source:
Returns:

Metrics object with currentSpot, qty, weight, purity, isGb, weightOz, metalColor

Type
Object

_imageSlot()

Create an image slot with placeholder

Source:

_initCardCharts(container)

Initializes Chart.js mini-charts on all .card-a-canvas elements. Reads spot history data from the canvas data attributes and builds the same 3-line chart as the view modal (purchase/melt/retail).

Parameters:
Name Type Description
container HTMLElement
Source:

_initCardCharts(container)

Initializes Chart.js mini-charts on all .card-a-canvas elements. Reads spot history data from the canvas data attributes and builds the same 3-line chart as the view modal (purchase/melt/retail).

Parameters:
Name Type Description
container HTMLElement
Source:

_initSpotControls()

Initialises spot controls: applies the persisted trend period on load.

The per-card elements remain in the DOM (hidden via CSS) so that the existing spot.js sparkline listeners continue to work.

Source:

_interpolateNulls(arr) → {Array.<number>}

Interpolate null gaps in an array for SVG rendering (equivalent to Chart.js spanGaps).

Parameters:
Name Type Description
arr Array.<(number|null)>
Source:
Returns:
Type
Array.<number>

_interpolateNulls(arr) → {Array.<number>}

Interpolate null gaps in an array for SVG rendering (equivalent to Chart.js spanGaps).

Parameters:
Name Type Description
arr Array.<(number|null)>
Source:
Returns:
Type
Array.<number>

_isLightColor(color) → {boolean}

Check if a color is light based on relative luminance.

Parameters:
Name Type Description
color string

Hex or rgb() string

Source:
Returns:

True if light (needs dark text)

Type
boolean

(async) _loadBulkRowImages(tr, item)

Resolves IDB images for one item and injects elements into its IMG cell, replacing the placeholder. Respects tableImageSides setting. Blob URLs are tracked in _bulkBlobUrls for cleanup on modal close.

Parameters:
Name Type Description
tr HTMLTableRowElement
item Object
Source:

(async) _loadCardImage(img)

Resolves and sets blob URL for a single card thumbnail image.

Parameters:
Name Type Description
img HTMLImageElement
Source:

(async) _loadCardImage(img)

Resolves and sets blob URL for a single card thumbnail image.

Parameters:
Name Type Description
img HTMLImageElement
Source:

_loadSectionConfig(key, defaults, legacyKeyopt, migrateFnopt) → {Array.<{id: string, label: string, enabled: boolean}>}

Generic loader for section config arrays from localStorage. Merges saved user config with defaults so new sections are auto-appended.

Parameters:
Name Type Attributes Description
key string

localStorage key

defaults Array.<{id: string, label: string, enabled: boolean}>
legacyKey string <optional>

Optional legacy key to migrate from

migrateFn function <optional>

Migration function for legacy data

Source:
Returns:
Type
Array.<{id: string, label: string, enabled: boolean}>

(async) _loadThumbImage(img)

Resolve and set blob URL for a single table thumbnail image. Checks IDB cache (user uploads → pattern images → Numista cache). Falls back to a metal-colored SVG placeholder when no image is available.

Parameters:
Name Type Description
img HTMLImageElement

Table thumbnail element with data attributes

Source:

_normalizePatterns(list) → {Array.<string>}

Normalizes a list of search patterns for comparison. Trims, lowercases, and sorts the patterns.

Parameters:
Name Type Description
list Array.<string>

The list of patterns to normalize

Source:
Returns:

The normalized list

Type
Array.<string>

_openBulkImagePopover(imgTd, item)

Opens a small inline image-management popover anchored to the IMG cell. Lets the user upload obverse/reverse photos or remove existing ones for a single item. Saves directly to imageCache and refreshes that row.

Parameters:
Name Type Description
imgTd HTMLTableDataCellElement
item Object
Source:

_openExternalPopup(url, nameopt)

Open a URL in a 1250px popup window. Most external sites block iframe embedding (X-Frame-Options), so we use window.open().

Parameters:
Name Type Attributes Default Description
url string
name string <optional>
'_blank'

Window name for reuse

Source:

_openThumbPopover(cell, item)

Opens a fixed-position popover anchored below (or above) the image cell. Shows a large preview of the resolved image for each visible side, with Upload, Camera (mobile/HTTPS only), and Remove buttons. Saves directly to imageCache and refreshes the row's thumbnails.

Parameters:
Name Type Description
cell HTMLTableDataCellElement

the td[data-column="image"] element

item Object

the full inventory item object

Source:

_parseColor(color) → {Array.<number>}

Parse a color string (hex #rrggbb or rgb(r,g,b)) into [r, g, b].

Parameters:
Name Type Description
color string
Source:
Returns:

[r, g, b] in 0-255

Type
Array.<number>

_renderSectionConfigTable(opts)

Generic section-config table renderer. Builds a checkbox + arrow reorder table for any {id, label, enabled}[] config.

Parameters:
Name Type Description
opts Object
Properties
Name Type Attributes Description
containerId string

DOM id of the container element

getConfig function

Returns the current config array

saveConfig function

Persists the updated config array

emptyText string <optional>

Text shown when config is empty (default: 'No sections available')

onApply function <optional>

Called after every change (e.g. applyLayoutOrder)

onRender function <optional>

Called to re-render after reorder (defaults to self)

Source:

_renderSortBarSummary()

Renders the portfolio summary strip in the sort bar.

Source:

_renderSortBarSummary()

Renders the portfolio summary strip in the sort bar.

Source:

(async) _restoreCdnFolderFromZip(zip)

Restores CDN images from an imported ZIP file.

Parameters:
Name Type Description
zip JSZip

The loaded ZIP object.

Source:

_saveSectionConfig(key, config)

Generic saver for section config arrays to localStorage.

Parameters:
Name Type Description
key string

localStorage key

config Array.<{id: string, label: string, enabled: boolean}>
Source:

_schedulePoll()

Schedule the next poll using the current _syncRetryDelay (respects backoff).

Source:

_section()

Create a data section with title

Source:

_setSlotImage()

Replace placeholder with actual image in a slot

Source:

_showCardImage(img, url)

Show a card image and hide its placeholder.

Parameters:
Name Type Description
img HTMLImageElement
url string
Source:

_showCardImage(img, url)

Show a card image and hide its placeholder.

Parameters:
Name Type Description
img HTMLImageElement
url string
Source:

_syncFallbackUUID()

Fallback UUID generator when generateUUID from utils.js is unavailable

Source:

_syncHScrollBar(show)

Shows or hides the custom H-scroll bar and wires events (once).

Parameters:
Name Type Description
show boolean
Source:

_syncHScrollBar(show)

Shows or hides the custom H-scroll bar and wires events (once).

Parameters:
Name Type Description
show boolean
Source:

_syncRelativeTime()

Format a timestamp as a relative time string ("just now", "5 min ago", etc.)

Source:

_syncSortBar()

Ensures the sort bar is always visible and syncs controls to the active view style. Called after every renderTable() — works around inventory.js hiding the bar in table mode.

Source:

_syncSortBar()

Ensures the sort bar is always visible and syncs controls to the active view style. Called after every renderTable() — works around inventory.js hiding the bar in table mode.

Source:

_updateHScrollThumb()

Recalculates thumb size and position from portal scroll state.

Source:

_updateHScrollThumb()

Recalculates thumb size and position from portal scroll state.

Source:

acceptAck()

Accepts the acknowledgment and hides the modal

Source:

addCompositionOption(value)

Adds a composition option and updates dropdowns

Parameters:
Name Type Description
value string

Composition to add

Source:

addItemTag(uuid, tag, persistopt) → {boolean}

Add a tag to an item. Prevents duplicates and enforces limits.

Parameters:
Name Type Attributes Default Description
uuid string

Item UUID

tag string

Tag name

persist boolean <optional>
true

Whether to save to localStorage immediately

Source:
Returns:

True if tag was added

Type
boolean

analyzeStorageData()

Analyzes localStorage data and calculates memory usage

Source:

analyzeStorageItem()

Analyzes a storage item to determine its type and content

Source:

applyColumnFilter(field, value)

Legacy function for backward compatibility with table click handlers

Parameters:
Name Type Description
field string

The field to filter by

value string

The value to filter for

Source:

applyHeaderToggleVisibility()

Shows/hides the header shortcut buttons based on stored preferences. Theme and Currency default hidden; Trend and Sync default visible.

Source:

applyLayoutOrder()

Shows/hides and reorders major page sections based on layout section config. Reads from localStorage and applies both visibility and DOM order.

Source:

applyMetalOrder()

Applies metal order config: reorders and shows/hides spot price cards and totals cards.

Source:

applyMinCountThreshold(data, minCount) → {Object}

Applies a minimum count threshold to a category data object, filtering out entries below the threshold.

Parameters:
Name Type Description
data Object

Map of { key: count }

minCount number

Minimum count to include

Source:
Returns:

Filtered map

Type
Object

applyNumistaTags(uuid, numistaTags, persistopt) → {number}

Apply Numista tags to an item from an API result. Capitalizes the first letter of each tag. Skips duplicates.

Parameters:
Name Type Attributes Default Description
uuid string

Item UUID

numistaTags Array.<string>

Array of tag strings from Numista API

persist boolean <optional>
true

Whether to call saveItemTags() after applying. Pass false when calling in a loop; caller is responsible for a single saveItemTags() after.

Source:
Returns:

Number of tags added

Type
number

applyQuickFilter(field, value, isGroupedopt, excludeopt)

Applies a quick filter for a specific field value (when clicking on table values) Supports 3-level deep filtering - clicking same filter removes it, clicking different filters stacks them

Parameters:
Name Type Attributes Default Description
field string

The field to filter by

value string

The value to filter for

isGrouped boolean <optional>
false

Whether this is a grouped/special filter (uses 'include' logic)

exclude boolean <optional>
false

Whether to apply the filter in exclusion mode

Source:

attachAutocomplete(inputEl, sourceType)

Attach autocomplete dropdown to an input element. Creates a dropdown that shows filtered suggestions from the lookup table.

Parameters:
Name Type Description
inputEl HTMLInputElement

The input element to attach to

sourceType string

Key into currentLookupTable ('names', 'purchaseLocations', 'storageLocations')

Source:

attachPriceHistorySortHeaders(table)

Attaches click-to-sort handlers to price history table headers.

Parameters:
Name Type Description
table HTMLTableElement
Source:

autoSelectDefaultProvider()

Automatically selects the primary API provider based on priority and availability. The highest-priority provider that has a stored API key is selected as default.

Source:

(async) autoSyncSpotPrices() → {Promise.<void>}

Triggers an automatic background spot price synchronization. Only runs if API keys are configured and local data is stale.

Source:
Returns:

Resolves when background sync process ends

Type
Promise.<void>

(async) backfillStaktrakrHourly() → {Promise.<number>}

Backfills the last 24 hours of hourly spot data from StakTrakr into spotHistory. Only runs when STAKTRAKR is the primary provider (rank 1) and sync succeeded.

Source:
Returns:

Count of new entries added

Type
Promise.<number>

bindAppearanceAndHeaderListeners()

Binds listeners for appearance settings (theme, display currency, timezone, header toggles).

Source:

bindCardAndTableImageListeners()

Binds listeners for card style and table image toggles.

Source:

bindCardClickHandler(container)

Binds a delegated click handler on the card grid container.

Parameters:
Name Type Description
container HTMLElement
Source:

bindCardClickHandler(container)

Binds a delegated click handler on the card grid container.

Parameters:
Name Type Description
container HTMLElement
Source:

bindCloudCacheListeners()

Wires cloud storage connect/disconnect/backup/restore buttons.

Source:

bindFilterAndNumistaListeners()

Binds listeners for filter settings and Numista integration options.

Source:

bindGoldbackActionListeners()

Binds listeners for Goldback price entry and history actions.

Source:

bindGoldbackToggleListeners()

Binds listeners for Goldback feature toggles and estimation settings.

Source:

bindImageImportExportListeners()

Binds listeners for image import/export buttons.

Source:

bindImageSettingsListeners()

Aggregates all image-related settings listeners.

Source:

bindImageSyncListeners()

Binds listeners for image sync and cache clearing operations.

Source:

bindLbmaHistoryControls()

Binds LBMA history filter controls once.

Source:

bindNumistaBulkSyncListeners()

Binds listeners for Numista bulk sync operations.

Source:

bindPatternRuleModeListeners()

Binds listeners for pattern rule mode switching and creation.

Source:

bindSettingsModalShellListeners()

Binds listeners for the settings modal shell (close button, background click).

Source:

bindSettingsNavigationListeners()

Binds listeners for settings modal navigation (sidebar, provider tabs, log tabs).

Source:

bindStorageListeners()

Wires up Storage section listeners (Refresh button, tiny-key toggle).

Source:

blobToWebP(blob, qualityopt) → {Promise.<(Blob|null)>}

Converts a Blob to WebP format.

Parameters:
Name Type Attributes Default Description
blob Blob

The source image blob.

quality number <optional>
0.85

WebP quality (0 to 1).

Source:
Returns:

WebP blob or null if failed.

Type
Promise.<(Blob|null)>

buildBulkItemRow(item, isPinned) → {HTMLTableRowElement}

Builds a table row element for a single inventory item in the bulk edit table.

Parameters:
Name Type Description
item Object

The inventory item

isPinned boolean

Whether the row is in the pinned section

Source:
Returns:

The constructed row

Type
HTMLTableRowElement

(async) buildImageExportZip(options) → {Promise.<JSZip>}

Builds a ZIP archive of all exported images.

Parameters:
Name Type Description
options Object

Export options.

Properties
Name Type Attributes Default Description
includeCdn boolean <optional>
false

Whether to include CDN images.

onProgress function <optional>
null

Progress callback.

Source:
Returns:

The generated ZIP object.

Type
Promise.<JSZip>

buildItemFields(f) → {Object}

Builds the common field object shared by both add and edit paths.

Parameters:
Name Type Description
f Object

Parsed fields from parseItemFormFields()

Source:
Returns:

Common item fields

Type
Object

buildNumistaSearchQuery(nameVal, metalVal) → {Object}

Builds a Numista search query, optionally rewriting via NumistaLookup patterns.

Parameters:
Name Type Description
nameVal string

Item name input value

metalVal string

Metal composition value

Source:
Returns:
Type
Object

buildSearchIndices(lookupTable) → {Object}

Build searchable indices with variants for all lookup data

Parameters:
Name Type Description
lookupTable LookupTable

Base lookup table data

Source:
Returns:

Enhanced lookup table with search indices

Type
Object

buildTagSection(uuid, numistaTags, onChangedopt) → {HTMLElement|null}

Build the tag display section for the view modal. Returns a DOM fragment with Numista tags (read-only) and custom tags (editable).

Parameters:
Name Type Attributes Description
uuid string

Item UUID

numistaTags Array.<string>

Numista API tags (may be empty)

onChanged function <optional>

Callback when tags change (for re-render)

Source:
Returns:

Tag section element, or null if no tags and no add capability

Type
HTMLElement | null

buildViewContent(item, index) → {DocumentFragment}

Build the full view modal body as a DocumentFragment. Sections are built eagerly then appended in user-configured order.

Parameters:
Name Type Description
item Object

Inventory item

index number

Item index for edit button

Source:
Returns:
Type
DocumentFragment

cacheLookupTable(lookupTable)

Cache lookup table to localStorage

Parameters:
Name Type Description
lookupTable LookupTable

Lookup table to cache

Source:

calculateApiUsage(selectedMetals, historyDaysopt, batchSupportedopt) → {Object}

Calculates the expected API usage (call count) for a given sync operation. Accounts for batch support and historical data backfill.

Parameters:
Name Type Attributes Default Description
selectedMetals Array.<string>

Array of metal keys to fetch

historyDays number <optional>
0

Number of days of history to include

batchSupported boolean <optional>
false

Whether the provider supports batch calls

Source:
Returns:

Usage breakdown including calls, type, and potential savings

Type
Object

calculateLevenshteinDistance(str1, str2) → {number}

Calculate Levenshtein distance between two strings

Parameters:
Name Type Description
str1 string

First string

str2 string

Second string

Source:
Returns:

Edit distance

Type
number

calculateRetailPrice(item, currentSpot) → {Object}

Calculates qty-adjusted retail value using the portfolio hierarchy: Goldback denomination price → manual market value → melt value.

Parameters:
Name Type Description
item Object

Inventory item

currentSpot number

Current spot price for the item's metal

Source:
Returns:
Type
Object

checkFileSize(file) → {boolean}

Checks if a file exceeds the local upload size limit

Parameters:
Name Type Description
file File

File to validate

Source:
Returns:

True if file is within allowed size

Type
boolean

(async) checkRemoteVersion()

Checks for a newer version from the remote version.json endpoint (STACK-67) Skips fetch on file:// protocol (static badge still shown). Caches result for 24 hours.

Source:

checkVersionChange()

Compares stored version with current and shows changelog modal if needed

Source:

cleanOrphanedItemPriceHistory() → {number}

Removes history for UUIDs not present in the current inventory. Not called automatically — available for storage optimization.

Source:
Returns:

Number of orphaned UUIDs removed

Type
number

cleanSearchTerm(term) → {string}

Strips search-operator characters from a search term for use in external URLs. Removes quotes, parentheses, and backslashes that act as search operators on eBay.

Parameters:
Name Type Description
term string

Raw search term (may contain user-entered punctuation)

Source:
Returns:

Cleaned term safe for external search queries

Type
string

cleanString(str) → {string}

Cleans a string by stripping HTML tags and control characters while preserving punctuation. Normalizes whitespace and removes diacritics.

Parameters:
Name Type Description
str string

Input string

Source:
Returns:

Cleaned string

Type
string

cleanupStorage()

Removes unknown localStorage keys to maintain a clean storage state

Iterates over all localStorage entries and deletes any keys not present in ALLOWED_STORAGE_KEYS.

Source:

(async) clearAllCachedData()

Clears all cached images and metadata after confirmation.

Source:

clearAllFilters()

Clears all active filters and resets search input and pagination.

Source:

clearApiCache()

Clears only the API cache, keeping the configuration

Source:

clearApiConfig()

Clears Metals API configuration

Source:

clearApiHistory(silentopt)

Clears all stored spot price history from localStorage and re-renders UI.

Parameters:
Name Type Attributes Default Description
silent boolean <optional>
false

If true, suppresses reopening the history modal

Source:

clearApiKey(provider)

Removes the stored API key for a given provider from configuration. Also handles fallback to other available providers if necessary.

Parameters:
Name Type Description
provider string

The unique key of the API provider

Source:

clearCatalogHistory()

Clears all catalog API history after user confirmation.

Source:

clearChangeLog()

Clears all change log entries after confirmation

Source:

clearItemPriceHistory()

Clears all item price history after user confirmation.

Source:

clearLookupCache()

Clear cached lookup table

Source:

clearSpotHistory()

Clears all spot price history after user confirmation.

Source:

clearUploadState()

Clear the pending upload state and previews for both sides.

Source:

closeCurrencyDropdown()

Closes the currency dropdown and removes the outside-click listener.

Source:

closeCurrencyDropdownOnOutside()

Click-outside handler for the currency dropdown.

Source:

closeDetailsModal()

Closes the details modal and cleans up charts

Source:

closeModalById(id)

Globally close a modal by id and clear body overflow safely.

Parameters:
Name Type Description
id string
Source:

closeNumistaResultsModal()

Close Numista results modal and clean up state

Source:

closePcgsFieldPicker()

Close the PCGS field picker modal.

Source:

closeSpotLookupModal()

Closes the spot lookup modal.

Source:

closeVaultModal()

Close the vault modal and reset state.

Source:

closeViewModal()

Close the view modal and clean up resources.

Source:

coerceFieldValue(fieldId, value) → {*}

Coerces a bulk edit field value to the correct type based on field ID.

Parameters:
Name Type Description
fieldId string

The field identifier

value string

The raw string value from the input

Source:
Returns:

The coerced value

Type
*

collectVaultData(scopeopt) → {object|null}

Collect localStorage data for vault export.

Parameters:
Name Type Attributes Default Description
scope string <optional>
'full'

'full' collects all ALLOWED_STORAGE_KEYS; 'sync' collects only SYNC_SCOPE_KEYS (inventory + display prefs, no API keys or tokens)

Source:
Returns:

Payload object or null if empty

Type
object | null

commitItemToInventory(f, isEditing, editIdx)

Commits a parsed item to inventory (add or edit mode).

Parameters:
Name Type Description
f Object

Parsed fields from parseItemFormFields()

isEditing boolean

Whether in edit mode

editIdx number | null

Index being edited (null for add)

Source:

compareVersions(a, b) → {number}

Compares two BRANCH.RELEASE.PATCH version strings

Parameters:
Name Type Description
a string

First version

b string

Second version

Source:
Returns:

Negative if a < b, 0 if equal, positive if a > b

Type
number

computeGoldbackEstimatedRate(goldSpot) → {number}

Computes the estimated 1 Goldback exchange rate from gold spot price. Formula: 2 × (goldSpot / 1000) × modifier

Parameters:
Name Type Description
goldSpot number

Current gold spot price per troy oz

Source:
Returns:

Estimated 1 Goldback rate in USD

Type
number

computeItemValuation(item, currentSpot) → {Object}

Computes normalized valuation values for an inventory item. Centralizes purchase, melt, retail, and gain/loss calculations.

Parameters:
Name Type Description
item Object

Inventory item

currentSpot number

Current spot price for the item's metal

Source:
Returns:
Type
Object

computeMeltValue(item, spot) → {number}

Computes the melt value for an inventory item. Centralises the formula: weight × qty × spot × purity.

Parameters:
Name Type Description
item Object

Inventory item (needs weight, qty, purity)

spot number

Current spot price for the item's metal

Source:
Returns:

Qty-adjusted melt value

Type
number

convertToUsd(amount, currencyopt) → {number}

Converts amount from specified currency to USD using static rates

Parameters:
Name Type Attributes Default Description
amount number

Monetary amount

currency string <optional>
"USD"

Currency code of amount

Source:
Returns:

Amount converted to USD

Type
number

createBackupData() → {Object}

Exports backup data including Metals API configuration

Source:
Returns:

Complete backup data object

Type
Object

(async) createBackupZip() → {void}

Creates a comprehensive backup ZIP file containing all application data

This function generates a complete backup archive including:

  • Current inventory data in JSON format
  • All export formats (CSV, HTML)
  • Application settings and configuration
  • Spot price history
  • README file explaining backup contents

The backup is packaged as a ZIP file for easy storage and portability. All data is exported in multiple formats to ensure compatibility and provide redundancy for data recovery scenarios.

Source:
Returns:

Downloads a ZIP file containing complete backup

Type
void
Example
// Called to generate a complete backup archive
await createBackupZip();

createBreakdownElements(breakdown) → {DocumentFragment}

Creates breakdown DOM elements for display CHANGED from renderBreakdownHTML to use DOM methods instead of innerHTML

Parameters:
Name Type Description
breakdown Object

Breakdown data object

Source:
Returns:

DOM fragment containing the breakdown elements

Type
DocumentFragment

createDummyElement() → {Object}

Helper function to create dummy DOM elements to prevent null reference errors

Source:
Returns:

A dummy element object with basic properties

Type
Object

createEmptyLookupTable() → {LookupTable}

Create an empty lookup table structure with pre-built data

Source:
Returns:

Empty lookup table with pre-built seed data

Type
LookupTable

createFieldInput(field) → {HTMLElement}

Creates the appropriate input element for a bulk edit field definition.

Parameters:
Name Type Description
field Object

Field definition from BULK_EDITABLE_FIELDS

Source:
Returns:

The input/select/textarea element

Type
HTMLElement

createPieChart(canvas, data, title) → {Chart}

Creates a pie chart with the given data

Parameters:
Name Type Description
canvas HTMLCanvasElement

Canvas element to render chart on

data Object

Chart data with labels and values

title string

Chart title

Source:
Returns:

Chart.js instance

Type
Chart

createStorageItemModal()

Creates modal HTML for detailed item view

Source:

createThumbEl(src, alt) → {HTMLElement}

Create a thumbnail element (img or placeholder) for a given blob URL.

Parameters:
Name Type Description
src string | null

Object URL or null

alt string

Alt text

Source:
Returns:
Type
HTMLElement

currentMonthKey() → {string}

Returns current month key in YYYY-MM format

Source:
Returns:

Current month identifier

Type
string

cycleSpotTrend()

Cycles through trend period presets, persists the selection, and applies it.

Source:

cycleSpotTrend()

Cycles through trend period presets, persists the selection, and applies it.

Source:

dataToPolyline(data, w, h, padYopt) → {string}

Converts an array of numeric values to SVG polyline coordinate string.

Parameters:
Name Type Attributes Default Description
data Array.<number>

Data points

w number

SVG viewBox width

h number

SVG viewBox height

padY number <optional>
4

Vertical padding

Source:
Returns:

Space-separated "x,y" pairs

Type
string

dataToPolyline(data, w, h, padYopt) → {string}

Converts an array of numeric values to SVG polyline coordinate string.

Parameters:
Name Type Attributes Default Description
data Array.<number>

Data points

w number

SVG viewBox width

h number

SVG viewBox height

padY number <optional>
4

Vertical padding

Source:
Returns:

Space-separated "x,y" pairs

Type
string

dataUriToBlob(dataUri) → {Blob}

Converts a data URI string to a Blob.

Parameters:
Name Type Description
dataUri string

Full data URI (e.g. "data:image/webp;base64,...")

Source:
Returns:
Type
Blob

debounce(func, wait) → {function}

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them.

Parameters:
Name Type Description
func function

The function to debounce.

wait number

The number of milliseconds to delay.

Source:
Returns:

Returns the new debounced function.

Type
function

debugError(…args) → {void}

Logs an error debug entry.

Parameters:
Name Type Attributes Description
args * <repeatable>
Source:
Returns:
Type
void

debugLog(…args) → {void}

Logs an informational debug entry.

Parameters:
Name Type Attributes Description
args * <repeatable>
Source:
Returns:
Type
void

debugLog(…args)

Logs messages to console when DEBUG flag is enabled

Parameters:
Name Type Attributes Description
args any <repeatable>

Values to log when debugging

Source:

debugWarn(…args) → {void}

Logs a warning debug entry.

Parameters:
Name Type Attributes Description
args * <repeatable>
Source:
Returns:
Type
void

(async) deleteItem(idx)

Deletes inventory item at specified index after confirmation

Parameters:
Name Type Description
idx number

Index of item to delete

Source:

deleteItemPriceEntry(uuid, timestamp)

Deletes a single price history entry by UUID and timestamp. Logs the deletion to the change log for undo/redo support.

Parameters:
Name Type Description
uuid string

Item UUID

timestamp number

Entry timestamp to delete

Source:

deleteItemTags(uuid)

Delete all tags for an item (called on item deletion).

Parameters:
Name Type Description
uuid string

Item UUID

Source:

deleteTagGlobal(tag) → {number}

Delete a tag from all items.

Parameters:
Name Type Description
tag string

Tag name to remove globally

Source:
Returns:

Number of items affected

Type
number

deriveSearchLabel(patterns) → {string}

Derives a default display label for a set of search patterns.

Parameters:
Name Type Description
patterns Array.<string>

The patterns to derive a label from

Source:
Returns:

The derived display label

Type
string

destroyCharts()

Destroys existing chart instances to prevent memory leaks

Source:

destroySparklines()

Destroys all sparkline Chart.js instances (cleanup)

Source:

detectCurrency(str) → {string|null}

Detects currency code from a value string containing symbols or codes

Parameters:
Name Type Description
str string

Value containing currency information

Source:
Returns:

Detected currency code or null if not found

Type
string | null

disableCloudSync()

Disable auto-sync: persist the disabled flag, stop the poller, and update UI.

Source:

dismissAllAutocompletes()

Dismiss all open autocomplete dropdowns (e.g. when the modal closes).

Source:

dismissNotesModal()

Closes the notes modal and resets the notes index.

Source:

(async) downloadCompleteBackup()

Downloads complete backup files including inventory and Metals API configuration

Source:

downloadFile(filename, content, mimeType)

Downloads a file with the specified content and filename

Parameters:
Name Type Default Description
filename string

Name of the file to download

content string

Content of the file

mimeType string text/plain

MIME type of the file (default: text/plain)

Source:

downloadStorageReport()

Shows storage report options with view and download actions

Source:

duplicateItem(idx)

Duplicates an inventory item by opening the add modal pre-filled with the source item's fields. Date preserves the original purchase date, qty resets to 1.

Parameters:
Name Type Description
idx number

Index of item to duplicate

Source:

editItem(idx)

Prepares and displays edit modal for specified inventory item

Parameters:
Name Type Description
idx number

Index of item to edit

Source:

(async) enableCloudSync(provideropt)

Enable auto-sync: do an initial push, then start the poller.

Parameters:
Name Type Attributes Default Description
provider string <optional>
'dropbox'
Source:

escapeAttribute(text) → {string}

Escapes special characters for safe inclusion in HTML attributes

Parameters:
Name Type Description
text string

Text to escape

Source:
Returns:

Escaped text safe for attribute usage

Type
string

escapeHtml(str) → {string}

Escape HTML special characters to prevent XSS when interpolating into innerHTML.

Parameters:
Name Type Description
str *

Value to escape (coerced to string)

Source:
Returns:

Escaped HTML-safe string

Type
string

escapeHtmlCatalog(str) → {string}

Escape HTML for safe insertion into innerHTML

Parameters:
Name Type Description
str string

Raw string

Source:
Returns:

Escaped string

Type
string

escapeHtmlPcgs()

Escape HTML for safe injection into innerHTML

Source:

exportCsv()

Exports current inventory to CSV format

Source:

(async) exportEncryptedBackup(password) → {Promise.<void>}

Export an encrypted vault backup.

Parameters:
Name Type Description
password string
Source:
Returns:
Type
Promise.<void>

exportGoldbackHistory()

Exports Goldback price history as CSV.

Source:

exportJson()

Exports current inventory to JSON format

Source:

exportNumistaCsv()

Exports inventory using Numista-compatible column layout

Source:

exportPdf()

Exports current inventory to PDF format

Source:

exportSpotHistory()

Exports all spot history data as a CSV file

Source:

extractUniqueValues(inventory, field, optionsopt) → {Array.<string>}

Extract unique values from inventory for a specific field

Parameters:
Name Type Attributes Default Description
inventory Array

Current inventory data

field string

Field name to extract

options Object <optional>
{}

Extraction options

Properties
Name Type Attributes Default Description
includeEmpty boolean <optional>
false

Include empty/null values

caseSensitive boolean <optional>
false

Preserve original case

Source:
Returns:

Array of unique values

Type
Array.<string>

(async) fetchBatchSpotPrices(provider, apiKey, selectedMetals, historyDaysopt, historyTimesopt) → {Promise.<Object.<string, number>>}

Executes a batch API request to retrieve spot prices for multiple metals simultaneously. Supports historical data range requests if provided by the underlying API.

Parameters:
Name Type Attributes Default Description
provider string

The unique key of the API provider

apiKey string

The API key for the provider

selectedMetals Array.<string>

Array of metal keys to fetch

historyDays number <optional>
0

Number of days of history to include

historyTimes Array.<string> <optional>
[]

Array of HH:MM times for granular history

Source:
Returns:

Map of metal keys to spot prices

Type
Promise.<Object.<string, number>>

(async) fetchExchangeRates() → {Promise.<boolean>}

Fetches latest exchange rates from the free API and caches them (STACK-50). Non-blocking — if fetch fails, existing cached/fallback rates are used.

Source:
Returns:

Whether the fetch succeeded

Type
Promise.<boolean>

(async) fetchHistoryBatched(provider, apiKey, selectedMetals, totalDays) → {Promise.<{totalEntries: number, callsMade: number}>}

Orchestrates a series of batched API requests to backfill historical spot price data. Automates the chunking process and parses results for multiple metals.

Parameters:
Name Type Description
provider string

The unique key of the API provider

apiKey string

The API key for the provider

selectedMetals Array.<string>

Array of metal keys to fetch

totalDays number

Total number of days of history to pull

Source:
Returns:

Summary of the batch operation

Type
Promise.<{totalEntries: number, callsMade: number}>

(async) fetchLatestPrices(provider, apiKey, selectedMetals) → {Promise.<Object.<string, number>>}

Fetches the most recent spot prices for selected metals using individual endpoints. Optimized for low-cost, real-time updates without full history backfill.

Parameters:
Name Type Description
provider string

The unique key of the API provider

apiKey string

The API key for the provider

selectedMetals Array.<string>

Array of metal keys to fetch

Source:
Returns:

Map of metal keys to spot prices

Type
Promise.<Object.<string, number>>

(async) fetchMetalPriceApiHourly(apiKey, selectedMetals, totalDays) → {Promise.<{totalEntries: number, callsMade: number}>}

Specialized history fetcher for MetalPriceAPI's hourly endpoint. Requests granular hourly data for a specific date range.

Parameters:
Name Type Description
apiKey string

The API key for MetalPriceAPI

selectedMetals Array.<string>

Array of metal keys to fetch

totalDays number

Number of days of history to pull

Source:
Returns:

Summary of the operation

Type
Promise.<{totalEntries: number, callsMade: number}>

(async) fetchSpotForDate(metalName, dateStr) → {Promise.<Array>}

Fetches spot price from the API for a specific date and metal. Records fetched entries into local spotHistory for future lookups.

Parameters:
Name Type Description
metalName string

Metal name ('Silver', 'Gold', etc.)

dateStr string

Target date in YYYY-MM-DD format

Source:
Returns:

Fetched entries with dayOffset

Type
Promise.<Array>

fetchSpotPrice()

Fetches and displays current spot prices from localStorage or defaults

Source:

(async) fetchSpotPricesFromApi(provider, apiKey) → {Promise.<Object.<string, number>>}

Standard interface for fetching spot prices from any supported API provider. Automatically chooses between individual latest endpoints or batch calls.

Parameters:
Name Type Description
provider string

The unique key of the API provider

apiKey string

The API key for the provider

Source:
Returns:

Map of metal keys to spot prices

Type
Promise.<Object.<string, number>>

(async) fetchStaktrakrHourlyRange(hoursBack) → {Promise.<{newCount: number, fetchCount: number}>}

Fetches hourly spot data from StakTrakr for a configurable number of hours. Skips hours already present in spotHistory to avoid duplicates.

Parameters:
Name Type Description
hoursBack number

Number of hours to look back

Source:
Returns:

Counts of new entries and successful fetches

Type
Promise.<{newCount: number, fetchCount: number}>

(async) fetchStaktrakrPrices()

Fetch spot prices from StakTrakr hourly JSON files. Walks back up to 6 hours from the current UTC hour to find data.

Source:

fetchYearFile(year) → {Promise.<Array>}

Fetches a single year file from data/spot-history-{year}.json. Three-tier loading: local fetch → local XHR → remote staktrakr.com. Caches the result (or empty array on failure) to avoid retries. Deduplicates concurrent fetches for the same year.

Parameters:
Name Type Description
year number

Year to fetch

Source:
Returns:

Array of spot history entries

Type
Promise.<Array>

fillFormFromNumistaResult()

Fill form fields from the editable picker inputs. Reads values from the numistaFieldValue_* text inputs (user may have edited them).

Source:

fillFormFromPcgsResult()

Apply checked fields from the PCGS picker to the item form. Reads values from the pcgsFieldValue_* text inputs (user may have edited them).

Source:

filterInventory() → {Array.<Object>}

Filters inventory based on the current search query and active column filters. Handles advanced multi-term, phrase, and series-specific logic for coins and metals.

Source:
Returns:

Filtered inventory items matching the search query and filters

Type
Array.<Object>
Example
filterInventory();

filterInventoryAdvanced() → {Array.<InventoryItem>}

Enhanced filter inventory function that includes advanced filters. Applies all active filters in activeFilters to the inventory.

Source:
Returns:

Filtered inventory items

Type
Array.<InventoryItem>

filterItemPriceHistoryTable()

Reads the filter input value and re-renders the price history table.

Source:

flattenGoldbackHistory()

Flattens goldbackPriceHistory into a row array for table rendering. Each entry: { denomination, label, price, timestamp }

Source:

formatCurrency(value, currencyopt) → {string}

Formats a number as a currency string using the default currency

Parameters:
Name Type Attributes Default Description
value number | string

Number to format

currency string <optional>
DEFAULT_CURRENCY

ISO currency code

Source:
Returns:

Formatted currency string (e.g., "$1,234.56")

Type
string

formatDateOnly(date) → {string}

Formats a date for display (date only, no time) using the user's timezone preference.

Parameters:
Name Type Description
date Date | string | number

Date object, ISO string, or epoch ms

Source:
Returns:

Formatted date string

Type
string

formatDisplayDate(dateStr) → {string}

Formats a date string into compact MM/DD/YY format

Parameters:
Name Type Description
dateStr string

Date in YYYY-MM-DD format

Source:
Returns:

Formatted date (e.g., "1/1/69")

Type
string

formatFileSize(bytes) → {string}

Format file size in human-readable form.

Parameters:
Name Type Description
bytes number
Source:
Returns:
Type
string

formatLossProfit(value) → {string}

Formats a profit/loss value with color coding

Parameters:
Name Type Description
value number

Profit/loss value

Source:
Returns:

HTML string with appropriate color styling

Type
string

formatOffsetLabel(offset) → {string}

Formats a day offset into a human-readable badge label.

Parameters:
Name Type Description
offset number

Day offset from target date

Source:
Returns:

Label like "Exact", "+1d", "-2d"

Type
string

formatPurchaseLocation(loc) → {string}

Formats Purchase Location for table display, wrapping URLs in hyperlinks while preserving filter behavior.

Parameters:
Name Type Description
loc string

Purchase location value

Source:
Returns:

HTML string for table cell

Type
string

formatStorageLocation(loc) → {string}

Formats Storage Location for table display with truncation

Parameters:
Name Type Description
loc string

Storage location value

Source:
Returns:

HTML string for table cell

Type
string

formatTimeOnly(date) → {string}

Formats a date for display (time only, no date) using the user's timezone preference.

Parameters:
Name Type Description
date Date | string | number

Date object, ISO string, or epoch ms

Source:
Returns:

Formatted time string

Type
string

formatTimestamp(date, optionsopt) → {string}

Formats a date/timestamp for display using the user's timezone preference (STACK-63). When timezone is "auto" (default), uses the browser's local timezone — identical to previous behavior.

Parameters:
Name Type Attributes Description
date Date | string | number

Date object, ISO string, or epoch ms

options Intl.DateTimeFormatOptions <optional>

Override individual format options

Source:
Returns:

Formatted date+time string

Type
string

formatWeight(ozt, weightUnitopt) → {string}

Formats a weight in troy ounces to either grams or ounces. If weightUnit is 'gb', displays as Goldback denomination (no gram auto-conversion).

Parameters:
Name Type Attributes Description
ozt number

Weight in troy ounces (or Goldback denomination if weightUnit='gb')

weightUnit string <optional>

Optional weight unit: 'oz', 'g', or 'gb'

Source:
Returns:

Formatted weight string with unit

Type
string

fuzzyMatch(query, target, optionsopt) → {number}

Calculates fuzzy similarity between query and target strings

Parameters:
Name Type Attributes Default Description
query string

User search input

target string

Inventory item name to match against

options Object <optional>
{}

Configuration options

Properties
Name Type Attributes Default Description
threshold number <optional>
0.6

Minimum similarity score

caseSensitive boolean <optional>
false

Case sensitive matching

Source:
Returns:

Similarity score between 0 and 1

Type
number
Example
fuzzyMatch("Ame", "American Silver Eagle") // returns ~0.7
fuzzyMatch("Eagle Amer", "American Silver Eagle") // returns ~0.8

fuzzySearch(query, targets, optionsopt) → {Array.<{text: string, score: number}>}

Search through an array of targets and return fuzzy matches

Parameters:
Name Type Attributes Default Description
query string

Search query

targets Array.<string>

Array of strings to search

options Object <optional>
{}

Configuration options

Properties
Name Type Attributes Default Description
threshold number <optional>
0.6

Minimum similarity score

maxResults number <optional>
Infinity

Maximum results to return

caseSensitive boolean <optional>
false

Case sensitive matching

Source:
Returns:

Array of results

Type
Array.<{text: string, score: number}>

generateBackupHtml(sortedInventory, timeFormatted) → {string}

Generates HTML content for backup export

Parameters:
Name Type Description
sortedInventory Array

Sorted inventory data

timeFormatted string

Formatted timestamp

Source:
Returns:

HTML content

Type
string

generateCategorySummary(inventory) → {Object}

Generates category summary from filtered inventory. Returns summary of metals, types, and item counts above minimum threshold.

Parameters:
Name Type Description
inventory Array.<Object>

The filtered inventory

Source:
Returns:

Summary of metals, types, and counts

Type
Object

generateColors(count) → {Array}

Generates a color palette for pie chart segments

Parameters:
Name Type Description
count number

Number of colors needed

Source:
Returns:

Array of color strings

Type
Array

generateItemDataTable()

Generates data table for storage item

Source:

generateLookupTable(inventoryopt, optionsopt) → {LookupTable}

Generate lookup table from current inventory data with pre-built seed data

Parameters:
Name Type Attributes Default Description
inventory Array <optional>

Inventory data (defaults to global inventory)

options Object <optional>
{}

Generation options

Properties
Name Type Attributes Default Description
includeAbbreviations boolean <optional>
true

Include metal abbreviations

buildIndices boolean <optional>
true

Build search indices

usePrebuiltData boolean <optional>
true

Include pre-built industry data

Source:
Returns:

Generated lookup table

Type
LookupTable

generateNGrams(str, nopt, caseSensitiveopt) → {Array.<string>}

Generate character n-grams from a string

Parameters:
Name Type Attributes Default Description
str string

Input string

n number <optional>
2

Length of n-gram

caseSensitive boolean <optional>
false

Preserve case if true

Source:
Returns:

Array of n-grams

Type
Array.<string>

generateReadmeContent(timeFormatted) → {string}

Generates README content for backup archive

Parameters:
Name Type Description
timeFormatted string

Formatted timestamp

Source:
Returns:

README content

Type
string

generateSparklineSVG(item, w, h, optsopt) → {string}

Generates a "since purchased" 3-line sparkline SVG matching the view modal pattern. Red dashed = purchase price (flat), Green = melt value over time, Blue = retail/market value. Uses real spot history with timestamps when available.

Parameters:
Name Type Attributes Description
item object

Inventory item

w number

SVG viewBox width

h number

SVG viewBox height

opts object <optional>

Options

Properties
Name Type Attributes Default Description
opacity number <optional>
1

SVG opacity

points number <optional>
60

Number of data points

Source:
Returns:

SVG markup string

Type
string

generateSparklineSVG(item, w, h, optsopt) → {string}

Generates a "since purchased" 3-line sparkline SVG matching the view modal pattern. Red dashed = purchase price (flat), Green = melt value over time, Blue = retail/market value. Uses real spot history with timestamps when available.

Parameters:
Name Type Attributes Description
item object

Inventory item

w number

SVG viewBox width

h number

SVG viewBox height

opts object <optional>

Options

Properties
Name Type Attributes Default Description
opacity number <optional>
1

SVG opacity

points number <optional>
60

Number of data points

Source:
Returns:

SVG markup string

Type
string

generateStorageReport()

Generates a storage utilization report

Source:

generateStorageReportHTML()

Generates comprehensive HTML storage report with theme support

Source:

(async) generateStorageReportTar()

Generates a comprehensive ZIP file with storage report and data

Source:

generateUUID() → {string}

Generates a UUID v4 string for stable item identification. Uses crypto.randomUUID() where available, with a Math.random() RFC 4122 v4 fallback for environments (e.g. file:// protocol) that lack crypto.randomUUID.

Source:
Returns:

A UUID v4 string (e.g. "550e8400-e29b-41d4-a716-446655440000")

Type
string

generateVariations(term) → {Array.<string>}

Generate searchable variations for a given term Includes common abbreviations, partial matches, and variations

Parameters:
Name Type Description
term string

Original term

Source:
Returns:

Array of searchable variations

Type
Array.<string>

get24hChange(metalName) → {Object}

Computes 24h % change using the user's selected comparison mode (STACK-92). Modes: close-close (default), open-open, open-close. Graceful degradation: when only 1 entry/day exists, first === last so all modes match.

Parameters:
Name Type Description
metalName string

'Silver', 'Gold', etc.

Source:
Returns:
Type
Object

getAllMetalsBreakdownData() → {Object}

Calculates breakdown data across all metals — by metal and by location Used when clicking the "All Metals" summary card

Source:
Returns:

Breakdown data organized by metal and location

Type
Object

getAllUniqueTags() → {Array.<string>}

Get a sorted list of all unique tags across the entire inventory.

Source:
Returns:

Sorted array of unique tag strings

Type
Array.<string>

getApiAvailability(dateStr) → {Object}

Checks whether an API lookup is possible for a given date and returns availability info.

Parameters:
Name Type Description
dateStr string

Target date in YYYY-MM-DD format

Source:
Returns:
Type
Object

getAppTitle(baseTitleopt) → {string}

Returns full application title with version when no branding is configured

Parameters:
Name Type Attributes Default Description
baseTitle string <optional>
'StakTrakr'

Base application title

Source:
Returns:

Full title with version or branding name

Type
string

getBreakdownData(metal) → {Object}

Calculates breakdown data for specified metal by type and location RENAMED from calculateBreakdownData to avoid 403 errors

Parameters:
Name Type Description
metal string

Metal type to calculate ('Silver', 'Gold', 'Platinum', or 'Palladium')

Source:
Returns:

Breakdown data organized by type and location

Type
Object

getCacheDurationMs() → {number}

Gets cache duration in milliseconds

Source:
Returns:

Cache duration

Type
number

getCachedLookupTable() → {LookupTable|null}

Get cached lookup table if valid

Source:
Returns:

Cached lookup table or null if invalid/expired

Type
LookupTable | null

getCardStyle() → {'A'|'B'|'C'|'D'}

Returns the active card style from localStorage.

Source:
Returns:
Type
'A' | 'B' | 'C' | 'D'

getCardStyle() → {'A'|'B'|'C'|'D'}

Returns the active card style from localStorage.

Source:
Returns:
Type
'A' | 'B' | 'C' | 'D'

getChartBackgroundColor() → {string}

Gets appropriate background color for charts based on current theme

Source:
Returns:

Background color

Type
string

getChartColor()

Gets chart color for given index

Source:

getChartTextColor() → {string}

Gets appropriate text color for charts based on current theme

Source:
Returns:

Text color

Type
string

getChipColors(field, value, index) → {Object}

Returns chip color and text color for a given field/value combination.

Parameters:
Name Type Description
field string

Chip field type

value string

Chip value

index number

Chip index for fallback color cycling

Source:
Returns:

Background and optional text color

Type
Object

getCompositionFirstWords(composition) → {string}

Extracts up to the first two words from a composition string while removing parenthetical content and numeric values.

Parameters:
Name Type Description
composition string

Raw composition description

Source:
Returns:

First two cleaned words joined by a space

Type
string

getContrastColor(bg) → {string}

Returns black or white contrast color for a given background. Supports hex strings and CSS variables.

Parameters:
Name Type Description
bg string

Background color in hex or CSS var format

Source:
Returns:

'#000000' or '#ffffff'

Type
string

getCryptoBackend() → {'native'|'forge'|null}

Detect available crypto backend.

Source:
Returns:
Type
'native' | 'forge' | null

getCurrencySymbol(currencyopt) → {string}

Extracts the currency symbol from Intl.NumberFormat for the given currency code (STACK-50)

Parameters:
Name Type Attributes Description
currency string <optional>

ISO 4217 code; defaults to displayCurrency

Source:
Returns:

Currency symbol (e.g. "$", "€", "£", "₽")

Type
string

getDateChunks(totalDays, maxPerRequest) → {Array.<{start: Date, end: Date}>}

Splits a requested historical time range into smaller date chunks. Ensures each request stays within the provider's maximum allowed days per call.

Parameters:
Name Type Description
totalDays number

Total number of days to fetch

maxPerRequest number

Maximum days allowed per API request

Source:
Returns:

Array of date range objects, newest first

Type
Array.<{start: Date, end: Date}>

getDebugHistory() → {Array.<string>}

Returns a copy of debug log history entries.

Source:
Returns:
Type
Array.<string>

getDefaultSyncMode(provider) → {"always"|"backup"}

Determines the default synchronization behavior for a provider. Higher priority providers default to 'always', others to 'backup'.

Parameters:
Name Type Description
provider string

The unique key of the API provider

Source:
Returns:

Recommended sync mode

Type
"always" | "backup"

getDisplayComposition(composition) → {string}

Determines display-friendly composition text.

Returns "Alloy" when the first word isn't one of the primary metals (Gold, Silver, Platinum, Palladium).

Parameters:
Name Type Description
composition string

Raw composition description

Source:
Returns:

Display text for the composition

Type
string

getEmbeddedRoadmap() → {string}

Provides embedded roadmap data as fallback when file fetch fails

Source:
Returns:

HTML string of development roadmap

Type
string

getEmbeddedSeedData() → {Array.<{spot:number, metal:string, source:string, provider:string, timestamp:string}>}

Embedded seed data fallback for file:// protocol where fetch() cannot load local JSON files. Auto-generated — do not edit by hand.

Source:
Returns:
Type
Array.<{spot:number, metal:string, source:string, provider:string, timestamp:string}>

getEmbeddedWhatsNew() → {string}

Provides embedded "What's New" data as fallback when file fetch fails

Source:
Returns:

HTML string of recent announcements

Type
string

getExchangeRate(targetCurrencyopt) → {number}

Returns the exchange rate for a target currency (STACK-50). 1 USD = getExchangeRate(code) × target currency. Falls back: cached exchangeRates → FALLBACK_EXCHANGE_RATES → 1.

Parameters:
Name Type Attributes Description
targetCurrency string <optional>

ISO 4217 code; defaults to displayCurrency

Source:
Returns:

Exchange rate multiplier

Type
number

getExistingElement(id) → {HTMLElement|null}

Helper to safely get an element by ID, returning null if not found.

Parameters:
Name Type Description
id string

The DOM element ID

Source:
Returns:

The element or null

Type
HTMLElement | null

getFilterChipCategoryConfig() → {Array.<{id: string, label: string, enabled: boolean}>}

Loads the filter chip category config from localStorage, merging with defaults so new categories added in future versions appear automatically.

Source:
Returns:
Type
Array.<{id: string, label: string, enabled: boolean}>

getFooterDomain() → {string}

Determines active domain for footer copyright

Source:
Returns:

Domain name to display

Type
string

getGoldbackDenominationPrice(weightGb) → {number|null}

Returns the denomination price for a given Goldback weight, or null.

Parameters:
Name Type Description
weightGb number

Weight in Goldback denomination units (e.g. 1, 5, 10)

Source:
Returns:

Per-unit denomination price, or null if not set

Type
number | null

getGoldbackRetailPrice(item) → {number|null}

Returns the per-unit Goldback denomination retail price, or null. Checks: weightUnit is 'gb', Goldback pricing is enabled, and a price exists.

Parameters:
Name Type Description
item Object

Inventory item

Source:
Returns:

Per-unit denomination price, or null

Type
number | null

(async) getHistoricalSparklineData(metalName, days) → {Promise.<{labels: Array.<string>, data: Array.<number>}>}

Fetches needed year files, merges with live spotHistory, filters to metal + range, deduplicates by day (live data wins over seed).

Parameters:
Name Type Description
metalName string

Metal name ('Silver', 'Gold', etc.)

days number

Number of days to look back

Source:
Returns:

Arrays for Chart.js

Type
Promise.<{labels: Array.<string>, data: Array.<number>}>

getInlineChipConfig() → {Array.<{id: string, label: string, enabled: boolean}>}

Loads the inline chip config from localStorage, merging with defaults so new chip types added in future versions appear automatically.

Source:
Returns:
Type
Array.<{id: string, label: string, enabled: boolean}>

getItemTags(uuid) → {Array.<string>}

Get all tags for an item.

Parameters:
Name Type Description
uuid string

Item UUID

Source:
Returns:

Array of tag strings (never null)

Type
Array.<string>

getLastProviderSyncTime(provider) → {number|null}

Scans the spot history log to find the most recent successful sync for a provider.

Parameters:
Name Type Description
provider string

The unique key of the API provider

Source:
Returns:

Millisecond timestamp of last sync, or null

Type
number | null

getLastUpdateTime(metalName, modeopt) → {string}

Builds two-line HTML showing source and last cache refresh or API sync info for a metal

Parameters:
Name Type Attributes Default Description
metalName string

Metal name ('Silver', 'Gold', 'Platinum', 'Palladium')

mode string <optional>
"cache"

"cache" or "api" to select timestamp

Source:
Returns:

HTML string with source line and time line

Type
string

getLayoutSectionConfig()

Loads the layout section config, with migration from old layoutVisibility format.

Source:

getLbmaReferenceYears() → {Array.<number>}

Returns the seed years configured for bundled LBMA reference data. Falls back to current year when the seed config is unavailable.

Source:
Returns:

Sorted list of years

Type
Array.<number>

getLookupStats() → {Object}

Get current lookup table stats

Source:
Returns:

Lookup table statistics

Type
Object

getMetalColor(metalKey) → {string}

Returns the theme-aware color for a metal sparkline by reading the CSS custom property (--silver, --gold, etc.) from the active theme. Falls back to hardcoded defaults if getComputedStyle is unavailable.

Parameters:
Name Type Description
metalKey string

'silver', 'gold', 'platinum', 'palladium'

Source:
Returns:

CSS color string

Type
string

getMetalOrderConfig() → {Array.<{id:string, label:string, enabled:boolean}>}

Returns the current metal order config, merging stored data with defaults. New metals added to defaults will be appended to existing stored configs.

Source:
Returns:
Type
Array.<{id:string, label:string, enabled:boolean}>

getNumistaViewFieldConfig() → {Object.<string, boolean>}

Load Numista view field config from localStorage, merged with defaults.

Source:
Returns:
Type
Object.<string, boolean>

getPasswordStrength(password) → {Object}

Evaluate password strength.

Parameters:
Name Type Description
password string
Source:
Returns:
Type
Object

getPopularNumistaItems() → {Array.<{id: string, name: string, metal: string}>}

Curated list of popular bullion items for quick-pick in the no-results modal. Focused on items silver/gold stackers commonly own.

Source:
Returns:
Type
Array.<{id: string, name: string, metal: string}>

getProviderOrder() → {Array.<string>}

Returns the effective priority order for API providers. Merges user-defined priority with legacy order and hardcoded defaults.

Source:
Returns:

Ordered list of provider keys

Type
Array.<string>

getRequiredYears(days) → {Array.<number>}

Calculates which year files are needed for a given lookback period.

Parameters:
Name Type Description
days number

Number of days to look back

Source:
Returns:

Array of year numbers to fetch

Type
Array.<number>

getSparklineData(metalName, days, intradayopt) → {Object}

Extracts sparkline data from spotHistory for a given metal and date range

Parameters:
Name Type Attributes Default Description
metalName string

Metal name ('Silver', 'Gold', etc.)

days number

Number of days to look back

intraday boolean <optional>
false

If true, keep all entries (no per-day dedup) and use midnight cutoff instead of current-time offset (STACK-66)

Source:
Returns:

Arrays for Chart.js

Type
Object

getSpotHistoryForMetal(metal, pointsopt, withTimestampsopt) → {Array.<number>|Array.<{ts:number, spot:number}>|null}

Returns recent spot prices for a given metal from spotHistory. Used by card-view sparklines (STAK-118).

Parameters:
Name Type Attributes Default Description
metal string

Metal key ('silver', 'gold', etc.)

points number <optional>
30

Number of data points to return

withTimestamps boolean <optional>
false

If true, returns {ts, spot} objects

Source:
Returns:

Array of spot prices, or null if insufficient data

Type
Array.<number> | Array.<{ts:number, spot:number}> | null

getStorageItemDescription()

Gets description for storage items

Source:

getStorageItemDisplayName()

Gets display name for storage keys

Source:

getStorageReportCSS()

Gets enhanced CSS styles for the storage report with theme support

Source:

getStorageReportJS()

Gets enhanced JavaScript for the storage report with theme and chart support

Source:

getSyncDeviceId() → {string}

Get or create a stable per-device UUID, persisted in localStorage.

Source:
Returns:
Type
string

getSyncPassword() → {Promise.<(string|null)>}

Get the session-cached sync password, or open the sync password modal. Returns a Promise that resolves with the password string, or null if cancelled.

Source:
Returns:
Type
Promise.<(string|null)>

getTemplateVariables()

Template replacement functions for documentation Used by build process to replace {{TEMPLATE}} variables

Source:

getUserFriendlyMessage(errorMessage) → {string}

Converts technical error messages to user-friendly ones

Parameters:
Name Type Description
errorMessage string

Technical error message

Source:
Returns:

User-friendly error message

Type
string

getVersionString(prefixopt) → {string}

Returns formatted version string

Parameters:
Name Type Attributes Default Description
prefix string <optional>
"v"

Prefix to add before version

Source:
Returns:

Formatted version string (e.g., "v3.03.07b")

Type
string

getViewModalSectionConfig()

Loads the view modal section config from localStorage, merged with defaults.

Source:

gramsToOzt(grams) → {number}

Converts grams to troy ounces

Parameters:
Name Type Description
grams number

Weight in grams

Source:
Returns:

Weight in troy ounces

Type
number

handleError(error, context)

Handles errors with user-friendly messaging

Parameters:
Name Type Description
error Error | string

Error to handle

context string

Context where error occurred

Source:

(async) handleHistoryPull(provider)

UI entry point for initiating a historical data pull for a provider. Validates requirements, shows cost/quota confirmation, and executes pull.

Parameters:
Name Type Description
provider string

The unique key of the API provider

Source:

(async) handleImageDeletion(uuid) → {Promise.<void>}

Handle image deletion based on deletion flags. Supports partial deletion (one side only) or full deletion (both sides).

Parameters:
Name Type Description
uuid string

Item UUID

Source:
Returns:
Type
Promise.<void>

handleProviderSave(provider)

Saves provider settings (key, cache timeout, history days) without testing or fetching

Parameters:
Name Type Description
provider string

Provider key

Source:

(async) handleProviderSync(provider) → {Promise.<void>}

Handles the UI-triggered synchronization of a single specific provider. Useful for per-provider settings cards and troubleshooting.

Parameters:
Name Type Description
provider string

The unique key of the API provider

Source:
Returns:

Resolves when the provider sync attempt completes

Type
Promise.<void>

(async) handleRemoteChange(remoteMeta)

Handle a detected remote change. If no local changes → show update-available modal, then pull on Accept. If both sides changed → show conflict modal.

Parameters:
Name Type Description
remoteMeta object

The parsed staktrakr-sync.json content

Source:

(async) handleSaveSearchPattern()

Handles the "Save Search" button click event. Prompts the user for a label and creates a new custom group.

Source:

(async) handleStaktrakrHistoryPull()

Handles user-initiated hourly history pull for STAKTRAKR. Reads days from dropdown, confirms, fetches, and updates UI.

Source:

(async) handleVaultAction()

Handle the vault modal action button (export or import).

Source:

hideAboutModal()

Hides the About modal

Source:

hideAckModal()

Hides the acknowledgment modal

Source:

hideApiHistoryModal()

Closes the API history modal.

Source:

hideApiModal()

Legacy hideApiModal — redirects to hideSettingsModal

Source:

hideApiProvidersModal()

Closes the API providers modal (legacy wrapper for hideSettingsModal).

Source:

hideCatalogHistoryModal()

Hides catalog history modal

Source:

hideDebugModal() → {void}

Hides the debug modal and restores body scrolling.

Source:
Returns:
Type
void

hideEmptyColumns()

Hides table columns that contain no data after filtering.

Source:

hideFilesModal()

Legacy hideFilesModal — redirects to hideSettingsModal

Source:

hideGoldbackHistoryModal()

Hides the Goldback price history modal.

Source:

hideManualInput(metal)

Hides manual price input for a specific metal

Parameters:
Name Type Description
metal string

Metal name (Silver, Gold, etc.)

Source:

hideProviderInfo()

Hides provider information modal

Source:

hideSettingsModal()

Closes the Settings modal.

Source:

importCsv(file, overrideopt)

Imports inventory data from CSV file with comprehensive validation and error handling

Parameters:
Name Type Attributes Default Description
file File

CSV file selected by user through file input

override boolean <optional>
false

Replace existing inventory instead of merging

Source:

(async) importEncryptedBackup(fileBytes, password) → {Promise.<void>}

Import and decrypt a vault backup.

Parameters:
Name Type Description
fileBytes Uint8Array
password string
Source:
Returns:
Type
Promise.<void>

importJson(file, overrideopt)

Imports inventory data from JSON file

Parameters:
Name Type Attributes Default Description
file File

JSON file to import

override boolean <optional>
false

Replace existing inventory instead of merging

Source:

importNumistaCsv(file, overrideopt)

Imports inventory data from a Numista CSV export

Parameters:
Name Type Attributes Default Description
file File

CSV file from Numista

override boolean <optional>
false

Replace existing inventory instead of merging

Source:

importSpotHistory(file)

Imports spot history data from a CSV or JSON file

Parameters:
Name Type Description
file File

File to import

Source:

initCardSortBar()

Binds event listeners on the card sort bar (once). Also sets up the MutationObserver that keeps the bar visible in D (table) mode.

Source:

initCardSortBar()

Binds event listeners on the card sort bar (once). Also sets up the MutationObserver that keeps the bar visible in D (table) mode.

Source:

initCloudSync()

Initialize the cloud sync module. Creates the debounced push function and starts the poller if sync was enabled.

Source:

initSpotHistoryButtons()

Wires up spot history export/import button event listeners. Called during populateApiSection() or init.

Source:

initTheme()

Initializes theme based on user preference and system settings

Source:

initializeAutocomplete(inventoryopt)

Initialize autocomplete system Should be called when inventory is loaded or changed

Parameters:
Name Type Attributes Description
inventory Array <optional>

Current inventory data

Source:

injectVersionString(elementId, prefixopt)

Inserts formatted version string into a target element

Parameters:
Name Type Attributes Default Description
elementId string

ID of the element to update

prefix string <optional>
"v"

Prefix to add before version

Source:

isCardViewActive() → {boolean}

Returns true when the card view (A/B/C) should be rendered instead of the table. Style D = table view. When D is selected, returns false so inventory.js renders the table.

Source:
Returns:
Type
boolean

isCardViewActive() → {boolean}

Returns true when the card view (A/B/C) should be rendered instead of the table. Style D = table view. When D is selected, returns false so inventory.js renders the table.

Source:
Returns:
Type
boolean

isFeatureEnabled()

Convenience functions for common feature flag operations

Source:

isGoldbackPricingActive() → {boolean}

Returns true if Goldback pricing is active (enabled + has at least one price).

Source:
Returns:
Type
boolean

isValidSelectOption(selectId, value) → {boolean}

Check if a value matches a valid values from a priority map.

Parameters:
Name Type Description
priorities Object

{ METALS_DEV: 1, ... }

Source:

(async) syncRestoreOverrideBackup()

Restore the pre-pull local snapshot saved by syncSaveOverrideBackup(). Prompts for confirmation, writes raw strings back, and refreshes the UI.

Source:

syncSaveOverrideBackup()

Snapshot all SYNC_SCOPE_KEYS raw localStorage strings into a single JSON blob. Called immediately before vaultDecryptAndRestore() in pullSyncVault().

Source:

syncSettingsUI()

Syncs all Settings UI controls with current application state. Called each time the modal opens to ensure controls reflect live values.

Source:

(async) syncSpotPricesFromApi(showProgressopt, forceSyncopt) → {Promise.<boolean>}

Initiates the spot price synchronization process across all configured providers. Handles user interaction, cache validation prompts, and UI status updates.

Parameters:
Name Type Attributes Default Description
showProgress boolean <optional>
true

Whether to display alerts and progress UI

forceSync boolean <optional>
false

If true, ignores the local cache and forces API calls

Source:
Returns:

True if at least one provider successfully synced prices

Type
Promise.<boolean>

(async) testApiConnection(provider, apiKey) → {Promise.<boolean>}

Validates an API provider's connectivity by making a lightweight test request. Usually attempts to fetch a single metal's price (e.g., silver) to verify the key.

Parameters:
Name Type Description
provider string

The unique key of the API provider

apiKey string

The API key to be tested

Source:
Returns:

True if the connection test was successful

Type
Promise.<boolean>

todayStr() → {string}

Returns current date as ISO string (YYYY-MM-DD)

Source:
Returns:

Current date in ISO format

Type
string

toggleChange(logIdx)

Toggles a logged change between undone and redone states

Parameters:
Name Type Description
logIdx number

Index of change entry in changeLog array

Source:

toggleCurrencyDropdown()

Toggles the floating currency picker dropdown anchored to the header button. Creates the dropdown lazily on first use; subsequent calls toggle visibility.

Source:

toggleGlobalPriceView()

Legacy function kept for compatibility - no longer used
Market value now has its own dedicated column

Source:

togglePriceView()

Legacy function kept for compatibility - no longer used Market value now has its own dedicated column

Source:

toggleTheme()

Cycles through available themes: dark → light → sepia → dark

Source:

toggleVaultPasswordVisibility(inputId, toggleBtn)

Toggle password visibility for a field.

Parameters:
Name Type Description
inputId string
toggleBtn HTMLElement
Source:

tokenizeWords(str, caseSensitiveopt) → {Array.<string>}

Tokenize a string into individual words

Parameters:
Name Type Attributes Default Description
str string

Input string

caseSensitive boolean <optional>
false

Preserve case if true

Source:
Returns:

Array of words

Type
Array.<string>

(async) updateAllSparklines()

Refreshes sparklines on all 4 metal cards concurrently

Source:

updateCardSortBar()

Updates the card sort bar UI to reflect current sort state and card style. Called from renderTable() whenever card view (A/B/C) is active. For D mode, _syncSortBar handles everything via MutationObserver.

Source:

updateCardSortBar()

Updates the card sort bar UI to reflect current sort state and card style. Called from renderTable() whenever card view (A/B/C) is active. For D mode, _syncSortBar handles everything via MutationObserver.

Source:

updateColumnVisibility()

Updates column visibility based on current viewport width

Source:

updateFuzzyIndicator(query, show)

Show or hide the fuzzy search indicator banner. Displayed when exact search returns 0 results but fuzzy returns > 0.

Parameters:
Name Type Description
query string

The search query that triggered fuzzy matching

show boolean

Whether to show or hide the indicator

Source:

updateHistoryPullCost(provider)

Updates the visual cost indicator for a history pull from a given provider. Displays total API calls or file fetches expected based on current settings.

Parameters:
Name Type Description
provider string

The unique key of the API provider

Source:

updateItemCount(filteredCount, totalCount)

Updates the displayed inventory item count based on active filters

Parameters:
Name Type Description
filteredCount number

Items matching current filters

totalCount number

Total items in inventory

Source:

updateLastTimestamps(source, provider, timestamp)

Stores last cache refresh and API sync timestamps

Parameters:
Name Type Description
source string

Source of spot price ('api' or 'cached')

provider string | null

Provider name if available

timestamp string

ISO timestamp of the event

Source:

updateManualSpot(metalKey)

Updates spot price for specified metal from user input

Parameters:
Name Type Description
metalKey string

Key of metal to update ('silver', 'gold', 'platinum', 'palladium')

Source:

updateMatchIndicator(password, confirm)

Update the password match indicator.

Parameters:
Name Type Description
password string
confirm string
Source:

updateModalCurrencyUI()

Updates the add/edit modal's currency symbols and placeholders (STACK-50) Sets the CSS custom property --currency-symbol on .currency-input wrappers and updates input placeholders with the current currency code.

Source:

updatePortalHeight()

Updates the max-height of .table-section to show exactly itemsPerPage rows. Measures actual rendered heights (thead + first row) so it adapts to font scaling, browser zoom, and responsive breakpoints.

If all rows fit within the computed height, max-height is removed to avoid an unnecessary scrollbar.

Called by renderTable() after rows are inserted into the DOM.

Source:

updateProviderHistoryTables()

Renders the API usage/quota visualization (progress bars) for each provider. Displays usage vs quota and handles clicks for quota adjustment modals.

Source:

updateProviderSettings(provider)

Updates persistent provider settings (like cache duration) from form inputs. Persists the updated configuration to localStorage.

Parameters:
Name Type Description
provider string

The unique key of the API provider

Source:

updateSaveSearchButton(query, fuzzyUsedopt)

Updates the visibility of the "Save Search" button based on the query.

Parameters:
Name Type Attributes Default Description
query string

The search query string

fuzzyUsed boolean <optional>
false

Whether fuzzy matching was active

Source:

(async) updateSettingsFooter()

Updates the storage + version footer bar at the bottom of the Settings modal.

Source:

(async) updateSparkline(metalKey)

Renders or updates a sparkline chart for a single metal card. For ranges >180 days, fetches historical year files asynchronously.

Parameters:
Name Type Description
metalKey string

Metal key ('silver', 'gold', etc.)

Source:

updateSpotCardColor(metalKey, newPrice)

Updates spot card color based on price movement compared to last history entry

Parameters:
Name Type Description
metalKey string

Metal key ('silver', 'gold', etc.)

newPrice number

Newly set spot price

Source:

updateSpotChangePercent(metalKey, precomputedDataopt)

Computes and displays % change on a spot card based on the selected sparkline period. Compares oldest vs newest data point in the selected range.

Parameters:
Name Type Attributes Default Description
metalKey string

Metal key ('silver', 'gold', etc.)

precomputedData Array.<number> | null <optional>
null

Pre-fetched data array from updateSparkline (avoids redundant re-fetch for historical ranges). When null, uses sync getSparklineData().

Source:

updateSpotTimestamp(metalName)

Updates spot timestamp element with toggle between cache refresh and API sync times

Parameters:
Name Type Description
metalName string

Metal name ('Silver', 'Gold', 'Platinum', 'Palladium')

Source:

updateStatusCell(catalogId, text, color)

Updates a status cell in the eligible items table for live feedback.

Parameters:
Name Type Description
catalogId string
text string
color string

CSS color value

Source:

(async) updateStorageStats()

Updates footer with localStorage usage statistics and visual usage indicator

Source:

updateStrengthBar(password)

Update the password strength bar.

Parameters:
Name Type Description
password string
Source:

updateSummary()

Calculates and updates all financial summary displays across the application

Source:

updateSyncButtonStates(syncing)

Updates sync button states based on API availability

Parameters:
Name Type Default Description
syncing boolean false

Whether sync is in progress

Source:

updateSyncStatusIndicator(state, detailopt)

Update the auto-sync status indicator in the Settings UI.

Parameters:
Name Type Attributes Description
state 'idle' | 'syncing' | 'error' | 'disabled'
detail string <optional>

optional status text (e.g. "Just now", error message)

Source:

updateThemeButton()

Sets up theme toggle event listeners

Source:

useSpotPrice(spotPrice, timestamp)

Uses a selected spot price from the lookup modal. Sets the hidden itemSpotPrice field and closes the modal.

Parameters:
Name Type Description
spotPrice number

The selected spot price

timestamp string

Timestamp of the selected entry (for reference)

Source:

validateFieldValue(field, value) → {boolean}

Enhanced validation for inline edits with comprehensive field support

Parameters:
Name Type Description
field string

Field being edited

value string

Proposed value

Source:
Returns:

Whether value is valid

Type
boolean

validateInventoryItem(item) → {Object}

Validates inventory item data

Parameters:
Name Type Description
item Object

Inventory item to validate

Source:
Returns:

Validation result with isValid flag and errors array

Type
Object

validateItemFields(f) → {string|null}

Validates mandatory item fields.

Parameters:
Name Type Description
f Object

Parsed fields from parseItemFormFields()

Source:
Returns:

Error message or null if valid

Type
string | null

(async) vaultDecrypt(ciphertext, key, iv) → {Promise.<Uint8Array>}

Decrypt ciphertext with AES-256-GCM.

Parameters:
Name Type Description
ciphertext Uint8Array

ciphertext + 16-byte auth tag

key CryptoKey | string
iv Uint8Array

12-byte nonce

Source:
Throws:

On wrong password or corrupted data (GCM auth tag mismatch)

Type
Error
Returns:

plaintext

Type
Promise.<Uint8Array>

(async) vaultDecryptAndRestore(fileBytes, password) → {Promise.<void>}

Decrypt raw vault bytes with the given password and restore data.

Parameters:
Name Type Description
fileBytes Uint8Array | ArrayBuffer
password string
Source:
Returns:
Type
Promise.<void>

(async) vaultDeriveKey(password, salt, iterations) → {Promise.<(CryptoKey|string)>}

Derive AES-256 key from password using PBKDF2.

Parameters:
Name Type Description
password string
salt Uint8Array

32-byte salt

iterations number
Source:
Returns:

Native CryptoKey or forge key bytes

Type
Promise.<(CryptoKey|string)>

(async) vaultEncrypt(plaintext, key, iv) → {Promise.<Uint8Array>}

Encrypt plaintext with AES-256-GCM.

Parameters:
Name Type Description
plaintext Uint8Array
key CryptoKey | string
iv Uint8Array

12-byte nonce

Source:
Returns:

ciphertext + 16-byte auth tag

Type
Promise.<Uint8Array>

(async) vaultEncryptToBytes(password) → {Promise.<Uint8Array>}

Encrypt inventory data with the given password and return raw vault bytes.

Parameters:
Name Type Description
password string
Source:
Returns:

serialized vault file bytes

Type
Promise.<Uint8Array>

(async) vaultEncryptToBytesScoped(password) → {Promise.<Uint8Array>}

Encrypt sync-scoped data (inventory + display prefs only) and return raw vault bytes. Used by cloud auto-sync to avoid pushing API keys or cloud tokens to remote storage.

Parameters:
Name Type Description
password string
Source:
Returns:

serialized vault file bytes

Type
Promise.<Uint8Array>

vaultRandomBytes(length) → {Uint8Array}

Generate cryptographically random bytes.

Parameters:
Name Type Description
length number
Source:
Returns:
Type
Uint8Array

(async) verifyPcgsCert(certNumber) → {Promise.<Object>}

Verify a PCGS certification number via the PCGS Public API.

Parameters:
Name Type Description
certNumber string

PCGS certification number to verify

Source:
Returns:

Verification result with coin details

Type
Promise.<Object>

wireChipSortToggle(elementId, syncIdopt)

Wires a chip sort order toggle (alpha/count) with bidirectional sync.

Parameters:
Name Type Attributes Description
elementId string

DOM id of the toggle container

syncId string <optional>

DOM id of a mirror toggle to keep in sync

Source:

wireFeatureFlagToggle(elementId, flagName, optsopt)

Wires a yes/no chip toggle to a feature flag. Handles click delegation, flag enable/disable, active-class sync, optional mirror element sync, and optional callback.

Parameters:
Name Type Attributes Description
elementId string

DOM id of the toggle container

flagName string

Feature flag key (e.g. 'GROUPED_NAME_CHIPS')

opts Object <optional>
Properties
Name Type Attributes Description
syncId string <optional>

DOM id of a mirror toggle to keep in sync

onApply function <optional>

Called after toggle with (isEnabled) arg

Source:

wireStorageToggle(elementId, storageKey, optsopt)

Wires a yes/no chip toggle to a raw localStorage key (not a feature flag). Handles click delegation, localStorage read/write, active-class sync, and optional callback.

Parameters:
Name Type Attributes Description
elementId string

DOM id of the toggle container

storageKey string

localStorage key to read/write ('true'/'false')

opts Object <optional>
Properties
Name Type Attributes Default Description
defaultVal boolean <optional>
false

Default value when no localStorage entry exists

onApply function <optional>

Called after toggle with (isEnabled) arg

Source:

xhrLoadJSON(url) → {Promise.<any>}

Loads a local JSON file via XMLHttpRequest (sync-free). Broader file:// compatibility than fetch() — works in Firefox/Safari and Chrome with --allow-file-access-from-files.

Parameters:
Name Type Description
url string

Relative or absolute URL to JSON file

Source:
Returns:

Parsed JSON

Type
Promise.<any>

Type Definitions

ApiConfig

Type:
  • Object
Properties:
Name Type Attributes Description
provider string

Currently selected provider key

keys Object.<string, string>

API keys for different providers

usage Object <optional>

Usage tracking

Source:

ApiProviderConfig

Type:
  • Object
Properties:
Name Type Attributes Description
name string

Display name for the provider

baseUrl string

Base API endpoint URL

endpoints Object.<string, string>

API endpoints for different metals

parseResponse function

Function to parse API response into standard format

documentation string

URL to provider's API documentation

batchSupported boolean

Whether provider supports batch requests

batchEndpoint string <optional>

Batch request endpoint pattern

parseBatchResponse function <optional>

Function to parse batch API response

requiresKey boolean <optional>

Whether an API key is required

Source:

CsvMappingRules

Type:
  • Object
Properties:
Name Type Attributes Description
columnMap Object.<string, string>

Mapping of CSV columns to internal item properties

ignoredColumns Array.<string> <optional>

Columns to ignore during import

Source:

DomElements

Type:
  • Object
Properties:
Name Type Description
spotPriceDisplay Object

Spot price display elements

spotSyncIcon Object

Spot sync icon elements

inventoryForm HTMLElement

Main inventory form

inventoryTable HTMLElement

Main inventory table

itemMetal HTMLElement

Metal select field

itemName HTMLElement

Name input field

itemQty HTMLElement

Quantity input field

itemType HTMLElement

Type input field

itemWeight HTMLElement

Weight input field

itemWeightUnit HTMLElement

Weight unit select field

itemPrice HTMLElement

Price input field

itemDate HTMLElement

Date input field

searchInput HTMLElement

Search input field

typeFilter HTMLElement

Type filter select field

metalFilter HTMLElement

Metal filter select field

totals Object

Totals display elements organized by metal

Source:

FilterConfig

Type:
  • Object
Properties:
Name Type Attributes Description
metal string <optional>

Metal filter

type string <optional>

Type filter

search string <optional>

Search query

Source:

InventoryItem

Type:
  • Object
Properties:
Name Type Attributes Description
metal string

Metal type (Silver, Gold, Platinum, Palladium)

composition string <optional>

Composition (Gold, Silver, Platinum, Palladium, Alloy)

name string

Display name of the item

qty number

Quantity of items

type string

Item type (Coin, Round, Bar, etc.)

weight number

Weight per item

weightUnit string <optional>

Weight unit (oz, g, kg, etc.)

purity number <optional>

Purity (0.0 to 1.0)

price number

Purchase price per item

date string

Purchase date (YYYY-MM-DD)

purchaseLocation string <optional>

Where the item was purchased

storageLocation string <optional>

Where the item is stored

notes string <optional>

User notes

spotPriceAtPurchase number <optional>

Spot price at time of purchase

premiumPerOz number <optional>

Premium paid per ounce

totalPremium number <optional>

Total premium paid for all units

marketValue number <optional>

Current market value (calculated or manual override)

numistaId string <optional>

Numista ID for lookup

year string <optional>

Year of issue

grade string <optional>

Item grade

gradingAuthority string <optional>

Grading authority (PCGS, NGC, etc.)

certNumber string <optional>

Certification number

serialNumber string <optional>

Serial number

pcgsNumber string <optional>

PCGS number for lookup

pcgsVerified boolean <optional>

Whether PCGS data has been verified

serial string <optional>

Original serial number string from import

uuid string

Unique identifier for the item

obverseImageUrl string <optional>

URL for obverse image

reverseImageUrl string <optional>

URL for reverse image

collectable boolean <optional>

Whether item is marked as collectable

Source:

LookupTable

Lookup table data structure for autocomplete suggestions

Type:
  • Object
Properties:
Name Type Description
names Array.<string>

Unique item names from inventory

purchaseLocations Array.<string>

Unique purchase locations

storageLocations Array.<string>

Unique storage locations

types Array.<string>

Unique item types

abbreviations Object

Common abbreviations and expansions

lastUpdated number

Timestamp of last update

itemCount number

Number of inventory items used to generate table

Source:

MappingRule

Type:
  • Object
Properties:
Name Type Description
regex RegExp

Pattern to match against field names

field string

Target field identifier

Source:

SpotHistoryEntry

Type:
  • Object
Properties:
Name Type Description
spot number

Spot price

metal string

Metal name (Gold, Silver, Platinum, Palladium)

source string

Data source (e.g., 'seed', 'api')

provider string

Data provider (e.g., 'LBMA', 'Metals.dev')

timestamp string

UTC timestamp (YYYY-MM-DD HH:mm:ss or ISO)

Source: