Shared TypeScript utilities for removing repeated code across Sovereignbase codebases.
deriveBytes(),
EventTarget and CustomEvent are required by LanguageBroker, and
structuredClone is required for successful safeStructuredClone() results.browserHasSovereignbaseDependencies() resolves to false outside secure browser contexts and when required browser APIs are missing.npm install @sovereignbase/utils
# or
pnpm add @sovereignbase/utils
# or
yarn add @sovereignbase/utils
# or
bun add @sovereignbase/utils
# or
deno add jsr:@sovereignbase/utils
# or
vlt install jsr:@sovereignbase/utils
deriveBytes()import { deriveBytes } from '@sovereignbase/utils'
const encoder = new TextEncoder()
const bytes = await deriveBytes(
encoder.encode('account-1'),
encoder.encode('profile-encryption'),
32
)
Derives a deterministic number of domain-separated bytes with HKDF-SHA-256. Identical base, domain, and length inputs produce identical output. Use a distinct domain for each purpose.
prototype()import { prototype } from '@sovereignbase/utils'
prototype(null) // 'null'
prototype({ ok: true }) // 'record'
prototype(new URL('https://sovereignbase.dev')) // 'url'
Returns a normalized lowercase runtime tag for common primitives, serializable built-ins, and selected platform objects.
isRecord()import { isRecord } from '@sovereignbase/utils'
const value: unknown = { ok: true }
if (isRecord(value)) {
value.ok // unknown
}
Checks that a value is a plain object record: non-null, not an array, and backed by an Object constructor prototype.
safeStructuredClone()import { safeStructuredClone } from '@sovereignbase/utils'
const result = safeStructuredClone({ ok: true, nested: { count: 1 } })
if (result[0]) {
const clone = result[1]
clone // deep cloned value
}
Attempts a structured clone and returns a tuple instead of throwing on unsupported values.
getISO31661Alpha2CountryCodeSet()import {
type ISO31661Alpha2,
getISO31661Alpha2CountryCodeSet,
} from '@sovereignbase/utils'
function epicFunction1(countryCode: ISO31661Alpha2) {
const countryCodes = getISO31661Alpha2CountryCodeSet()
const isCountryCode = countryCodes.has(countryCode)
if (!isCountryCode) throw new Error('THAT IS NOT A COUNTRY CODE DUDE!')
console.log('EPIC COUNTRY CODE MOMENT:', countryCode)
}
Returns a fresh Set containing all supported ISO 3166-1 alpha-2 country codes.
BCP47LanguageTagimport { type BCP47LanguageTag } from '@sovereignbase/utils'
function setDocumentLanguage(languageTag: BCP47LanguageTag) {
document.documentElement.lang = languageTag
}
setDocumentLanguage('en-US')
Provides IANA-registered standalone language tags and Unicode CLDR locale tags, including region, script, and variant forms, without adding runtime code to the package.
LanguageBrokerimport { LanguageBroker } from '@sovereignbase/utils'
const languages = new LanguageBroker(
document.documentElement.lang,
['en-US', 'fi-FI'],
(language) => {
document.documentElement.lang = language
}
)
languages.addEventListener('change', (event) => {
console.log(`Language changed to ${event.detail}`)
})
languages.set('fi-FI')
languages.get() // 'fi-FI'
languages.has('fi-FI') // true
languages.has('sv-SE') // false
[...languages.list()] // ['en-US', 'fi-FI']
Keeps the current BCP 47 language tag within an inferred, non-empty set of supported languages and reports updates through an optional callback and typed change events. An unsupported initial string falls back to the first supported language. has() narrows strings to the supported-language union, which get(), set(), list(), callbacks, and event details also preserve.
UnicodeLocaleIdentifierimport { type UnicodeLocaleIdentifier } from '@sovereignbase/utils'
function formatDate(locale: UnicodeLocaleIdentifier, date: Date) {
return new Intl.DateTimeFormat(locale).format(date)
}
formatDate('fi-FI', new Date())
Provides the locale identifiers backed by Unicode CLDR locale data, including default-content identifiers such as en-US.
OpenGraphLocaleimport { type OpenGraphLocale } from '@sovereignbase/utils'
function localeMeta(locale: OpenGraphLocale) {
return `<meta property="og:locale" content="${locale}">`
}
localeMeta('fi_FI')
Provides CLDR-backed Open Graph locales in the protocol's language_TERRITORY format.
browserHasSovereignbaseDependencies()import { browserHasSovereignbaseDependencies } from '@sovereignbase/utils'
if (await browserHasSovereignbaseDependencies()) {
console.log('browser runtime supports Sovereignbase dependencies')
}
Checks whether the current browser environment exposes the secure-context, storage, worker, notification, Web Crypto, and WebAuthn APIs required by Sovereignbase browser features.
afterIdleFor()import { afterIdleFor } from '@sovereignbase/utils'
const saveAfterTypingStops = afterIdleFor(500, () => {
console.log('save draft')
})
document.addEventListener('input', saveAfterTypingStops)
Creates a function that resets a timer on every call and runs the callback after the requested idle timeout.
daysAsMilliseconds()import { daysAsMilliseconds } from '@sovereignbase/utils'
const retentionPeriod = daysAsMilliseconds(30)
Converts a number of 24-hour days to milliseconds.
waitFor()import { waitFor } from '@sovereignbase/utils'
await waitFor(1_000)
Returns a promise that resolves after the requested number of milliseconds.
workerd).TypeDoc documentation is generated into docs/ by npm run build:docs and as
part of the normal build.
Run npm run bench to benchmark the synchronous utility paths on the current
machine.
Apache-2.0