hanzio 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -6
  3. package/dist/api-wrapper/endpoint.d.ts +8 -5
  4. package/dist/api-wrapper/transport.d.ts +1 -0
  5. package/dist/api-wrapper/types.d.ts +7 -0
  6. package/dist/{index-wjyb9bsd.js → index-hyt6c56h.js} +39 -12
  7. package/dist/index-ktynw3vs.js +37 -0
  8. package/dist/{index-181e6vfw.js → index-w882zry3.js} +1 -1
  9. package/dist/{index-j1ybktbr.js → index-zbj9s3s3.js} +6 -4
  10. package/dist/secrets/core.d.ts +7 -0
  11. package/dist/secrets/index.d.ts +3 -1
  12. package/dist/secrets/public-config.d.ts +7 -0
  13. package/dist/secrets/vite.d.ts +1 -0
  14. package/dist/secrets/worker.d.ts +1 -0
  15. package/dist/src/api-wrapper/index.js +1 -1
  16. package/dist/src/secrets/index.js +14 -8
  17. package/dist/src/secrets/vite.js +5 -1
  18. package/dist/src/secrets/worker.js +8 -4
  19. package/package.json +10 -3
  20. package/src/api-wrapper/README.md +738 -0
  21. package/src/api-wrapper/create-client.ts +9 -3
  22. package/src/api-wrapper/endpoint.ts +19 -5
  23. package/src/api-wrapper/transport.ts +6 -2
  24. package/src/api-wrapper/types.ts +13 -0
  25. package/src/crypto/README.md +144 -0
  26. package/src/format/README.md +120 -0
  27. package/src/i18n/README.md +65 -0
  28. package/src/jwt/README.md +70 -0
  29. package/src/p-queue/README.md +237 -0
  30. package/src/secrets/README.md +413 -0
  31. package/src/secrets/core.ts +72 -16
  32. package/src/secrets/index.ts +16 -4
  33. package/src/secrets/public-config.ts +47 -0
  34. package/src/secrets/vite.ts +2 -0
  35. package/src/secrets/worker.ts +2 -0
  36. package/src/sitemap/README.md +61 -0
  37. package/src/storage/README.md +71 -0
  38. package/src/typedswitch/README.md +319 -0
  39. package/dist/index-srt06xd2.js +0 -15
@@ -68,6 +68,15 @@ export type SecretSet<K extends string, Parsed = Record<K, string>> = {
68
68
  reload: (options?: SecretRequestOptions) => Promise<SecretSet<K, Parsed>>
69
69
  }
70
70
 
71
+ /** A declaration that must be loaded explicitly before its values can be read. */
72
+ export type LazySecretSet<
73
+ K extends string,
74
+ Parsed = Record<K, string>
75
+ > = SecretSet<K, Parsed> & {
76
+ /** Initialize once. Concurrent calls share a load; use reload to refresh. */
77
+ load: (options?: SecretRequestOptions) => Promise<LazySecretSet<K, Parsed>>
78
+ }
79
+
71
80
  // Shared across bundled entry points and package copies in the same JS realm.
72
81
  // Only helper-written values are registered; original environment overrides aren't.
73
82
  const registryKey = Symbol.for('hanzio.secrets.environmentWrites.v1')
@@ -118,21 +127,19 @@ function readOverrides<K extends string>(
118
127
  ) as Partial<Record<K, string>>
119
128
  }
120
129
 
121
- export async function defineSecretSet<
130
+ export function createSecretSet<
122
131
  const Keys extends readonly string[],
123
132
  Parsed = Record<Keys[number], string>
124
133
  >(
125
134
  keys: Keys,
126
135
  options: CustomLoaderDefineSecretSetOptions<Keys[number], Parsed>,
127
136
  environmentVariables?: EnvironmentVariables
128
- ): Promise<SecretSet<Keys[number], Parsed>> {
137
+ ): LazySecretSet<Keys[number], Parsed> {
129
138
  type K = Keys[number]
130
139
 
131
140
  const keySet = [...new Set(keys)] as K[]
132
- const environment = resolveSecretEnvironment(
133
- options.environment,
134
- environmentVariables
135
- )
141
+ let environment: string | undefined
142
+ let initialized = false
136
143
  const logger =
137
144
  options.logger === false ? undefined : (options.logger ?? defaultLogger)
138
145
 
@@ -157,7 +164,8 @@ export async function defineSecretSet<
157
164
  // Build, validate, and commit one snapshot under the caller’s deadline.
158
165
  const loadSnapshot = async (
159
166
  request: SecretRequestOptions,
160
- signal: AbortSignal
167
+ signal: AbortSignal,
168
+ environment: string
161
169
  ) => {
162
170
  // Fetch only keys that lack genuine local overrides.
163
171
  const local = readOverrides(keySet, environmentVariables)
@@ -261,6 +269,7 @@ export async function defineSecretSet<
261
269
  cached = next
262
270
  parsed = nextParsed
263
271
  sources = nextSources
272
+ initialized = true
264
273
  }
265
274
 
266
275
  const load = (request: SecretRequestOptions = {}): Promise<void> => {
@@ -273,12 +282,18 @@ export async function defineSecretSet<
273
282
  const start = Date.now()
274
283
 
275
284
  try {
285
+ environment ??= resolveSecretEnvironment(
286
+ options.environment,
287
+ environmentVariables
288
+ )
289
+ const resolvedEnvironment = environment
290
+
276
291
  await withSecretDeadline(
277
292
  {
278
293
  timeoutMs: request.timeoutMs ?? options.timeoutMs,
279
294
  signal: request.signal ?? options.signal
280
295
  },
281
- (signal) => loadSnapshot(request, signal)
296
+ (signal) => loadSnapshot(request, signal, resolvedEnvironment)
282
297
  )
283
298
 
284
299
  // Report the sources of committed values, not attempted fetches.
@@ -293,7 +308,7 @@ export async function defineSecretSet<
293
308
  const counts = Object.fromEntries(sourceCounts)
294
309
 
295
310
  log('info', 'Loaded secrets', {
296
- environment,
311
+ environment: resolvedEnvironment,
297
312
  count: keySet.length,
298
313
  durationMs: Date.now() - start,
299
314
  source: Object.keys(counts).join(' + ') || 'none',
@@ -306,7 +321,7 @@ export async function defineSecretSet<
306
321
  : new SecretLoadError('LOADER', 'Secret loading failed.')
307
322
 
308
323
  log('error', 'Secret loading failed', {
309
- environment,
324
+ environment: environment ?? 'unresolved',
310
325
  count: keySet.length,
311
326
  durationMs: Date.now() - start,
312
327
  code: safe.code
@@ -321,8 +336,19 @@ export async function defineSecretSet<
321
336
  return inFlight
322
337
  }
323
338
 
324
- const secretSet: SecretSet<K, Parsed> = {
339
+ const assertLoaded = () => {
340
+ if (!initialized) {
341
+ throw new SecretLoadError(
342
+ 'CONFIGURATION',
343
+ 'Secret set has not been loaded. Await load() before reading values.'
344
+ )
345
+ }
346
+ }
347
+
348
+ const secretSet: LazySecretSet<K, Parsed> = {
325
349
  secret(key) {
350
+ assertLoaded()
351
+
326
352
  if (!Object.hasOwn(cached, key)) {
327
353
  throw new SecretLoadError('MISSING_SECRETS', `Secret ${key} not found`)
328
354
  }
@@ -331,9 +357,29 @@ export async function defineSecretSet<
331
357
  },
332
358
 
333
359
  // Return copies so consumers cannot mutate the internal snapshots.
334
- secrets: () => ({ ...cached }),
335
- parsed: () => structuredClone(parsed),
336
- sources: () => ({ ...sources }),
360
+ secrets() {
361
+ assertLoaded()
362
+
363
+ return { ...cached }
364
+ },
365
+ parsed() {
366
+ assertLoaded()
367
+
368
+ return structuredClone(parsed)
369
+ },
370
+ sources() {
371
+ assertLoaded()
372
+
373
+ return { ...sources }
374
+ },
375
+
376
+ async load(request) {
377
+ if (!initialized) {
378
+ await load(request)
379
+ }
380
+
381
+ return secretSet
382
+ },
337
383
 
338
384
  async reload(request) {
339
385
  await load(request)
@@ -342,7 +388,17 @@ export async function defineSecretSet<
342
388
  }
343
389
  }
344
390
 
345
- await load()
346
-
347
391
  return secretSet
348
392
  }
393
+
394
+ /** Compatibility API: declares and loads a complete snapshot before returning. */
395
+ export async function defineSecretSet<
396
+ const Keys extends readonly string[],
397
+ Parsed = Record<Keys[number], string>
398
+ >(
399
+ keys: Keys,
400
+ options: CustomLoaderDefineSecretSetOptions<Keys[number], Parsed>,
401
+ environmentVariables?: EnvironmentVariables
402
+ ): Promise<SecretSet<Keys[number], Parsed>> {
403
+ return createSecretSet(keys, options, environmentVariables).load()
404
+ }
@@ -1,5 +1,6 @@
1
1
  import {
2
- defineSecretSet as defineCoreSecretSet,
2
+ createSecretSet as createCoreSecretSet,
3
+ type LazySecretSet,
3
4
  type CommonSecretSetOptions,
4
5
  type CustomLoaderDefineSecretSetOptions,
5
6
  type SecretSet,
@@ -51,13 +52,13 @@ export function getSecretEnvironment(): SecretEnvironment {
51
52
  ) as SecretEnvironment
52
53
  }
53
54
 
54
- export async function defineSecretSet<
55
+ export function createSecretSet<
55
56
  const Keys extends readonly string[],
56
57
  Parsed = Record<Keys[number], string>
57
58
  >(
58
59
  keys: Keys,
59
60
  options: DefineSecretSetOptions<Keys[number], Parsed>
60
- ): Promise<SecretSet<Keys[number], Parsed>> {
61
+ ): LazySecretSet<Keys[number], Parsed> {
61
62
  let loader: SecretSetLoader<Keys[number]>
62
63
 
63
64
  if (!options.loader) {
@@ -69,7 +70,7 @@ export async function defineSecretSet<
69
70
  }
70
71
 
71
72
  // Supply process.env only from this Node/Bun entry point, keeping the core portable.
72
- return defineCoreSecretSet(
73
+ return createCoreSecretSet(
73
74
  keys,
74
75
  { ...options, loader },
75
76
  getProcessEnvironment()
@@ -92,3 +93,14 @@ function createDefaultInfisicalLoader<K extends string, Parsed>(
92
93
  options.clientSecretEnvKey ?? 'INFISICAL_CLIENT_SECRET'
93
94
  })
94
95
  }
96
+
97
+ /** Compatibility API: load immediately and fail before application startup. */
98
+ export async function defineSecretSet<
99
+ const Keys extends readonly string[],
100
+ Parsed = Record<Keys[number], string>
101
+ >(
102
+ keys: Keys,
103
+ options: DefineSecretSetOptions<Keys[number], Parsed>
104
+ ): Promise<SecretSet<Keys[number], Parsed>> {
105
+ return createSecretSet(keys, options).load()
106
+ }
@@ -0,0 +1,47 @@
1
+ import type { SecretSet } from './core'
2
+ import { SecretLoadError } from './errors'
3
+
4
+ /**
5
+ * Read only explicitly listed public values. No process globals, secret loader,
6
+ * environment writes, or async initialization; safe in frontend tooling.
7
+ * Validate application-specific formats with your schema after secrets().
8
+ */
9
+ export function readPublicConfig<const Keys extends readonly string[]>(
10
+ keys: Keys,
11
+ values: Readonly<Record<string, string | undefined>>
12
+ ): Pick<SecretSet<Keys[number]>, 'secret' | 'secrets'> {
13
+ type K = Keys[number]
14
+
15
+ const snapshot = Object.fromEntries(
16
+ keys.map((key) => [
17
+ key,
18
+ Object.hasOwn(values, key) ? values[key] : undefined
19
+ ])
20
+ )
21
+ const missing = keys.filter(
22
+ (key) => typeof snapshot[key] !== 'string' || !snapshot[key]
23
+ )
24
+
25
+ if (missing.length) {
26
+ throw new SecretLoadError(
27
+ 'MISSING_SECRETS',
28
+ `Missing required public configuration: ${missing.join(', ')}`
29
+ )
30
+ }
31
+
32
+ const configured = snapshot as Record<K, string>
33
+
34
+ return {
35
+ secret(key) {
36
+ if (!Object.hasOwn(configured, key)) {
37
+ throw new SecretLoadError(
38
+ 'CONFIGURATION',
39
+ `Public key ${key} is not configured.`
40
+ )
41
+ }
42
+
43
+ return configured[key]
44
+ },
45
+ secrets: () => ({ ...configured })
46
+ }
47
+ }
@@ -57,3 +57,5 @@ export function viteSecretSetPlugin<K extends string>(
57
57
  config: () => ({ define: getViteDefine(secretSet, options) })
58
58
  }
59
59
  }
60
+
61
+ export { readPublicConfig } from './public-config'
@@ -2,3 +2,5 @@
2
2
  export * from './core'
3
3
  export { cloudflareWorkerEnvLoader } from './worker-loader'
4
4
  export type { SecretRequestOptions } from './deadline'
5
+
6
+ export { readPublicConfig } from './public-config'
@@ -0,0 +1,61 @@
1
+ ---
2
+ description: Discover and crawl XML sitemaps for URL discovery; uses the local p-queue utility for concurrency.
3
+ ---
4
+
5
+ # hanzio/sitemap
6
+
7
+ `getDomainSitemap(domain, options)` finds a domain's sitemaps (the `Sitemap:` lines in robots.txt first, then common locations like `/sitemap.xml`) and crawls them with bounded parallelism using the local `hanzio/p-queue` utility.
8
+
9
+ - A document whose root element is `<sitemapindex>` is treated as a list of child sitemaps. A document whose root element is `<urlset>` is treated as a list of pages.
10
+ - `<loc>` values are XML-entity decoded, and CDATA is supported.
11
+ - Gzipped sitemaps (`.xml.gz`) are decompressed with `DecompressionStream`.
12
+ - Every request has its own timeout (`AbortSignal.timeout`).
13
+
14
+ Requires runtime `fetch`, `AbortSignal.timeout` and `DecompressionStream` (Node 18+, Bun, modern browsers), or pass your own `fetch`.
15
+
16
+ ```ts
17
+ import { getDomainSitemap, getDomainSitemapEntries } from 'hanzio/sitemap'
18
+
19
+ const urls = await getDomainSitemap('example.com', {
20
+ filterIndexes: 'posts', // substring, RegExp or (url) => boolean
21
+ filterUrls: /\/blog\//,
22
+ maxUrls: 1000
23
+ })
24
+
25
+ // With lastmod
26
+ const entries = await getDomainSitemapEntries('example.com')
27
+ // [{ loc: 'https://example.com/a', lastmod: '2024-01-05' }, ...]
28
+ ```
29
+
30
+ ## Options (`SitemapOptions`)
31
+
32
+ | Option | Default | Description |
33
+ | --- | --- | --- |
34
+ | `filterIndexes` | none | Only follow child sitemaps that match (substring, RegExp or predicate). |
35
+ | `filterUrls` | none | Only keep page URLs that match. |
36
+ | `concurrency` | `10` | The maximum number of sitemap fetches that run at the same time. |
37
+ | `maxDepth` | `5` | The maximum sitemap-index nesting depth. |
38
+ | `maxUrls` | none | Stop crawling after this many URLs have been collected. |
39
+ | `timeout` | `10000` | The timeout for each request, in ms. |
40
+ | `userAgent` | `'SitemapCrawler/1.0'` | The `User-Agent` header sent with each request. |
41
+ | `fetch` | `globalThis.fetch` | A custom fetch implementation. |
42
+ | `onError` | `console.warn` | `(url, error) => void`, called when a robots.txt or sitemap request fails. |
43
+ | `respectRobots` | `false` | Drop page URLs that robots.txt disallows for `userAgent` (reuses the robots.txt fetched for discovery). A missing or failed robots.txt allows everything. |
44
+
45
+ Both functions throw `No sitemaps found for the domain` when discovery finds nothing.
46
+
47
+ ## robots.txt
48
+
49
+ `parseRobotsTxt(body, userAgent = '*')` returns the rules for one crawler, following RFC 9309: the groups that name its product token (case-insensitive, so `MyBot/2.0` matches `User-agent: mybot`), merged, or else the `User-agent: *` groups. Directive names are case-insensitive and `#` comments are ignored. `sitemaps` lists every `Sitemap:` line.
50
+
51
+ `isAllowedByRobots(rules, url)` checks an absolute URL or a path (plus query string). The longest matching pattern wins, `Allow` wins a tie, `*` matches any characters and a trailing `$` anchors the end. An empty `Disallow:` allows everything, and `/robots.txt` is always allowed.
52
+
53
+ ```ts
54
+ import { isAllowedByRobots, parseRobotsTxt } from 'hanzio/sitemap'
55
+
56
+ const rules = parseRobotsTxt(body, 'MyBot/1.0')
57
+ // { allow: ['/cart/help'], disallow: ['/cart/'], sitemaps: [...], crawlDelaySec?: 5 }
58
+
59
+ isAllowedByRobots(rules, 'https://example.com/cart/add?id=1') // false
60
+ isAllowedByRobots(rules, '/cart/help') // true
61
+ ```
@@ -0,0 +1,71 @@
1
+ ---
2
+ description: Typed persisted values over localStorage/sessionStorage or async stores like React Native AsyncStorage, with fallbacks that never throw.
3
+ ---
4
+
5
+ # hanzio/storage
6
+
7
+ `createStorageItem` wraps one key in `localStorage` (or any `SyncStorageLike`) as a typed value. It never throws:
8
+
9
+ - A missing, corrupt (bad JSON) or invalid (`parse` throws) value reads as `fallback`.
10
+ - When the storage throws (quota exceeded, Safari private mode, sandboxed iframes), the latest `set`/`remove` is kept in memory for that item, so reads stay consistent for the session.
11
+ - Without an accessible `globalThis.localStorage` (SSR, Node, Bun, blocked access) it uses a shared in-memory store.
12
+
13
+ ```ts
14
+ import { z } from 'zod'
15
+ import { createStorageItem } from 'hanzio/storage'
16
+
17
+ const PanelPrefs = z.object({ open: z.boolean(), width: z.number() })
18
+
19
+ const panelPrefs = createStorageItem({
20
+ key: 'panel-prefs',
21
+ fallback: { open: false, width: 320 },
22
+ parse: PanelPrefs.parse
23
+ })
24
+
25
+ panelPrefs.get() // { open: false, width: 320 }
26
+ panelPrefs.set({ open: true, width: 400 })
27
+ panelPrefs.remove()
28
+
29
+ // Another tab changed it (the `storage` event). Returns an unsubscribe function.
30
+ const stop = panelPrefs.subscribe((prefs) => console.log(prefs))
31
+ ```
32
+
33
+ Use `sessionStorage` or plain strings:
34
+
35
+ ```ts
36
+ const sendOnEnter = createStorageItem({
37
+ key: 'send-on-enter',
38
+ fallback: false,
39
+ storage: sessionStorage,
40
+ serialize: String,
41
+ deserialize: (raw) => raw === 'true'
42
+ })
43
+ ```
44
+
45
+ ## Async stores
46
+
47
+ `createAsyncStorageItem` takes the same options, but `storage` is required and the methods return promises. It never rejects.
48
+
49
+ ```ts
50
+ import AsyncStorage from '@react-native-async-storage/async-storage'
51
+ import { createAsyncStorageItem } from 'hanzio/storage'
52
+
53
+ const readIds = createAsyncStorageItem({
54
+ key: '@notification_read_session_ids',
55
+ fallback: [] as string[],
56
+ storage: AsyncStorage,
57
+ parse: z.array(z.string()).parse
58
+ })
59
+
60
+ await readIds.set([...(await readIds.get()), 'abc'])
61
+ ```
62
+
63
+ ## API
64
+
65
+ | Export | Description |
66
+ | --- | --- |
67
+ | `createStorageItem(options)` | `{ key, get, set, remove, subscribe }` over a `SyncStorageLike` (default `localStorage`). |
68
+ | `createAsyncStorageItem(options)` | `{ key, get, set, remove }` over an `AsyncStorageLike`. |
69
+ | `createMemoryStorage()` | A `Map`-backed `SyncStorageLike`, for tests and SSR. |
70
+
71
+ Options: `key`, `fallback`, `storage`, `parse` (validate the deserialized value; throwing means `fallback`), `serialize` (default `JSON.stringify`), `deserialize` (default `JSON.parse`).