t0n 0.20260913.0 → 0.20260915.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # `t0n`
2
2
 
3
- Collection of elegant typescript resources that are used across ZUNQ web applications.
3
+ Collection of elegant typescript resources that are used across web applications.
4
4
 
5
5
  ## Install
6
6
 
@@ -21,4 +21,4 @@ bun test
21
21
 
22
22
  ## License
23
23
 
24
- This package is licensed under the [MIT license](https://github.com/attla/t0n/blob/main/LICENSE) © [Zunq](https://zunq.com)
24
+ This package is licensed under the [MIT license](https://github.com/attla/t0n/blob/main/LICENSE) © [HUB](https://hub.bi)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "t0n",
3
3
  "description": "Collection of elegant typescript resources for web artisans",
4
- "version": "0.20260913.0",
4
+ "version": "0.20260915.0",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "files": ["src"],
@@ -25,19 +25,16 @@
25
25
  },
26
26
  "devDependencies": {
27
27
  "bun-types": "^1.4.0",
28
- "tsx": "^4.19.4",
29
28
  "typescript": "^5.9.3"
30
29
  },
31
- "packageManager": "bun@1.3.14",
32
- "engines": {
33
- "node": ">=18.0.0"
34
- },
30
+ "sideEffects": false,
31
+ "packageManager": "bun@1.4.0",
35
32
  "publishConfig": {
36
33
  "registry": "https://registry.npmjs.org"
37
34
  },
38
- "author": "Zunq <open-source@zunq.com>",
35
+ "author": "HUB <foss@hub.bi>",
39
36
  "license": "MIT",
40
- "homepage": "https://zunq.dev",
37
+ "homepage": "https://hub.bi/docs/t0n",
41
38
  "repository": "git://github.com/attla/t0n",
42
39
  "bugs": "https://github.com/attla/t0n/issues",
43
40
  "keywords": [
package/src/base64.ts CHANGED
@@ -1,57 +1,96 @@
1
- export class Base64 {
2
- static encode(data: any): string {
3
- const type = typeof data
4
- data = this.toString(data, type)
1
+ export function encodeBase64(buf: Uint8Array) {
2
+ let binary = ''
3
+ for (const byte of buf)
4
+ binary += String.fromCharCode(byte)
5
5
 
6
- const length = data?.byteLength || data.length
7
- return length < 1 ? '' : Buffer.from(data).toString('base64')
8
- }
6
+ return btoa(binary)
7
+ }
9
8
 
10
- static decode(data: string): string {
11
- if (typeof data !== 'string')
12
- throw new TypeError('Expected input to be a string')
9
+ const PADDING_CACHE = ['', '===', '==', '=']
10
+ export function decodeBase64(str: string) {
11
+ const remainder = str.length % 4
12
+ if (remainder)
13
+ str += PADDING_CACHE[remainder]
13
14
 
14
- if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data))
15
- throw new Error('Invalid Base64 string')
15
+ const binary = atob(str)
16
16
 
17
- try {
18
- return Buffer.from(data, 'base64').toString('utf8')
19
- } catch (e) {
20
- throw new Error('Invalid base64 characters')
21
- }
17
+ const bytes = new Uint8Array(binary.length)
18
+ const half = binary.length / 2
19
+ for (let i = 0, j = binary.length - 1; i <= half; i++, j--) {
20
+ bytes[i] = binary.charCodeAt(i)
21
+ bytes[j] = binary.charCodeAt(j)
22
22
  }
23
23
 
24
- // https://www.npmjs.com/package/crypt?activeTab=code
25
- // https://github.com/puleos/object-hash/blob/master/index.js
26
- // https://github.com/shuding/stable-hash/blob/main/src/index.ts
27
- static toString(data: any, type?: string): string | Uint8Array | ArrayBuffer {
28
- type ??= typeof data
29
- if (Buffer.isBuffer(data)) return data
30
-
31
- if (type === 'string') return data
32
- // if (type === 'string' || Buffer.isBuffer(data)) return data
24
+ return bytes
25
+ }
33
26
 
34
- if (Array.isArray(data) || ['function', 'symbol'].includes(type))
35
- return data.toString()
36
- else if (data === null || ['number', 'bigint', 'boolean', 'undefined'].includes(type))
37
- return String(data)
38
- else if (type === 'object' && !(data instanceof Uint8Array) && !(data instanceof ArrayBuffer))
39
- return JSON.stringify(data)
27
+ const BASE_MAP: Record<string, string> = { '=': '', '+': '-', '/': '_' }
28
+ const URL_MAP: Record<string, string> = { _: '/', '-': '+' }
29
+ export function encodeBase64Url(buf: Uint8Array) {
30
+ return encodeBase64(buf).replace(/[=+/]/g, c => BASE_MAP[c] ?? c)
31
+ }
40
32
 
41
- return data
42
- }
33
+ export function decodeBase64Url(str: string) {
34
+ return decodeBase64(str.replace(/[-_]/g, c => URL_MAP[c] ?? c))
43
35
  }
44
36
 
45
- export class UrlSafeBase64 {
46
- static encode(data: any): string {
47
- return Base64.encode(data)?.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') || ''
48
- }
49
37
 
50
- static decode(data: string): string {
51
- const remainder = data.length % 4
52
- if (remainder)
53
- data += '='.repeat(4 - remainder)
54
38
 
55
- return Base64.decode(data.replace(/-/g, '+').replace(/_/g, '/'))
56
- }
57
- }
39
+ // oldest
40
+ // export class Base64 {
41
+ // static encode(data: any): string {
42
+ // const type = typeof data
43
+ // data = this.toString(data, type)
44
+
45
+ // const length = data?.byteLength || data.length
46
+ // return length < 1 ? '' : Buffer.from(data).toString('base64')
47
+ // }
48
+
49
+ // static decode(data: string): string {
50
+ // if (typeof data !== 'string')
51
+ // throw new TypeError('Expected input to be a string')
52
+
53
+ // if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data))
54
+ // throw new Error('Invalid Base64 string')
55
+
56
+ // try {
57
+ // return Buffer.from(data, 'base64').toString('utf8')
58
+ // } catch (e) {
59
+ // throw new Error('Invalid base64 characters')
60
+ // }
61
+ // }
62
+
63
+ // // https://www.npmjs.com/package/crypt?activeTab=code
64
+ // // https://github.com/puleos/object-hash/blob/master/index.js
65
+ // // https://github.com/shuding/stable-hash/blob/main/src/index.ts
66
+ // static toString(data: any, type?: string): string | Uint8Array | ArrayBuffer {
67
+ // type ??= typeof data
68
+ // if (Buffer.isBuffer(data)) return data
69
+
70
+ // if (type === 'string') return data
71
+ // // if (type === 'string' || Buffer.isBuffer(data)) return data
72
+
73
+ // if (Array.isArray(data) || ['function', 'symbol'].includes(type))
74
+ // return data.toString()
75
+ // else if (data === null || ['number', 'bigint', 'boolean', 'undefined'].includes(type))
76
+ // return String(data)
77
+ // else if (type === 'object' && !(data instanceof Uint8Array) && !(data instanceof ArrayBuffer))
78
+ // return JSON.stringify(data)
79
+
80
+ // return data
81
+ // }
82
+ // }
83
+
84
+ // export class UrlSafeBase64 {
85
+ // static encode(data: any): string {
86
+ // return Base64.encode(data)?.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') || ''
87
+ // }
88
+
89
+ // static decode(data: string): string {
90
+ // const remainder = data.length % 4
91
+ // if (remainder)
92
+ // data += '='.repeat(4 - remainder)
93
+
94
+ // return Base64.decode(data.replace(/-/g, '+').replace(/_/g, '/'))
95
+ // }
96
+ // }
package/src/encode.ts ADDED
@@ -0,0 +1,24 @@
1
+ const encoder = new TextEncoder()
2
+ const dencoder = new TextDecoder()
3
+
4
+ export function textEncode(val: string) {
5
+ return encoder.encode(val) as Uint8Array
6
+ }
7
+ export function textDecode(val: Uint8Array) {
8
+ return dencoder.decode(val)
9
+ }
10
+
11
+ const HEX = '0123456789abcdef'
12
+ export function bytesToHex(buffer: Uint8Array): string {
13
+ const bytes = new Uint8Array(buffer)
14
+ const hex = new Array<string>(bytes.length * 2)
15
+
16
+ for (let i = 0; i < bytes.length; i++) {
17
+ const byte = bytes[i]
18
+
19
+ hex[i * 2] = HEX[byte >>> 4]
20
+ hex[i * 2 + 1] = HEX[byte & 0x0f]
21
+ }
22
+
23
+ return hex.join('')
24
+ }
package/src/env.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { get, has, set, remove } from './obj'
2
+
3
+ const obj: Record<string, unknown> = {}
4
+
5
+ export function hasEnv(key: string) {
6
+ try {
7
+ return has(obj, key) || key in process.env
8
+ } catch {
9
+ return false
10
+ }
11
+ }
12
+
13
+ export function getEnv<T = unknown>(key: string, defaultValue: T): T
14
+ export function getEnv<T = unknown>(key: string, defaultValue?: T): T | undefined
15
+ export function getEnv<T = unknown>(key: string, defaultValue?: T) {
16
+ try {
17
+ return get<T>(obj, key) ?? process?.env[key] ?? defaultValue
18
+ } catch {
19
+ return defaultValue
20
+ }
21
+ }
22
+
23
+ export function setEnv(key: string, val: unknown) {
24
+ set(obj, key, val)
25
+ }
26
+ export function addEnv<T = unknown>(env: Record<string, T>) {
27
+ Object.assign(obj, env)
28
+ }
29
+ export function removeEnv(key: string) {
30
+ remove(obj, key)
31
+ }
package/src/id.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { UrlSafeBase64 } from './base64'
1
+ import { encodeBase64Url } from 'hono/utils/encode'
2
2
 
3
3
  const idCache = new Set<string>()
4
4
 
@@ -10,7 +10,7 @@ export function newID() {
10
10
  const bytes = new Uint8Array(8)
11
11
  crypto.getRandomValues(bytes)
12
12
 
13
- id = UrlSafeBase64.encode(String.fromCharCode(...bytes)).slice(0, 8)
13
+ id = encodeBase64Url(bytes).slice(0, 8)
14
14
 
15
15
  attempts++
16
16
  } while (idCache.has(id) && attempts < maxAttempts)
package/src/index.ts CHANGED
@@ -2,7 +2,9 @@ export * from './attempt'
2
2
  export * from './base64'
3
3
  export * from './databag'
4
4
  export * from './date'
5
+ export * from './encode'
5
6
  export * from './enum'
7
+ export * from './env'
6
8
  export * from './envir'
7
9
  export * from './event'
8
10
  export * from './id'
@@ -11,6 +13,7 @@ export * from './json'
11
13
  export * from './lenght'
12
14
  export * from './lru-cache'
13
15
  export * from './obj'
16
+ export * from './rand'
14
17
  export * from './string'
15
18
  export * from './timestamp'
16
19
  export * from './toint'
package/src/obj.ts CHANGED
@@ -22,18 +22,18 @@ export function isPath(key: string): boolean {
22
22
  return key.indexOf('.') !== -1
23
23
  }
24
24
 
25
- export function get<T = unknown>(obj: AnyObject, key: string): T | undefined {
26
- if (key.indexOf('.') === -1) return obj[key] as T | undefined
25
+ export function get<T = unknown>(obj: AnyObject, key: string, defaultValue?: T): T | undefined {
26
+ if (key.indexOf('.') === -1) return obj[key] as T | undefined ?? defaultValue
27
27
 
28
28
  const segments = parse(key)
29
29
  let current: any = obj
30
30
 
31
31
  for (let i = 0, l = segments.length; i < l; i++) {
32
- if (current == null) return undefined
32
+ if (current == null) return defaultValue
33
33
  current = current[segments[i]]
34
34
  }
35
35
 
36
- return current
36
+ return current ?? defaultValue
37
37
  }
38
38
 
39
39
  export function set(obj: AnyObject, key: string, value: unknown): void {
package/src/rand.ts ADDED
@@ -0,0 +1,88 @@
1
+
2
+ export function randBytes(size: number) {
3
+ return crypto.getRandomValues(new Uint8Array(size))
4
+ // const bytes = new Uint8Array(size)
5
+ // crypto.getRandomValues(bytes)
6
+ // return bytes
7
+ }
8
+ // function randBytes(len: number): Buffer {
9
+ // return typeof randomBytes === 'function' ? randomBytes(len) : randBytesFallback(len)
10
+ // }
11
+ // function randBytesFallback(len: number): Buffer {
12
+ // const bytes = Buffer.alloc(len)
13
+ // for (let i = 0; i < len; i++)
14
+ // bytes[i] = Math.floor(Math.random() * 256) & 0xFF
15
+
16
+ // return bytes
17
+ // }
18
+
19
+ export function randBetween(min: number, max: number) {
20
+ min = Math.ceil(min)
21
+ return Math.floor(Math.random() * (Math.floor(max) - min + 1)) + min
22
+ }
23
+
24
+ const sortedCache: Record<string, any> = {}
25
+ export function sortBySeed<T extends string | string[]>(data: T, seed: number | string | null = null): T {
26
+ if (!seed) return data
27
+
28
+ const numericSeed = typeof seed === 'string' ? hashStringToNumber(seed) : seed
29
+
30
+ const dataString = Array.isArray(data) ? JSON.stringify(data) : data as string
31
+ const key = `${hashStringToNumber(dataString)}-${numericSeed}`
32
+
33
+ if (sortedCache[key])
34
+ return sortedCache[key] as T
35
+
36
+ const isArray = Array.isArray(data)
37
+ const items = isArray ? [...data] : splitUnicodeString(data)
38
+
39
+ const rng = createSeededRNG(numericSeed)
40
+ const randomized = items
41
+ .map((item, index) => ({ item, sortKey: rng() }))
42
+ .sort((a, b) => a.sortKey - b.sortKey)
43
+ .map(x => x.item)
44
+
45
+ const result = (isArray ? randomized : randomized.join('')) as T
46
+ sortedCache[key] = result
47
+ return result
48
+ }
49
+
50
+ export function splitUnicodeString(str: string): string[] {
51
+ return str.split(/(?!^)(?=.)/u).filter(Boolean)
52
+ }
53
+
54
+ export function createSeededRNG(seed: number): () => number {
55
+ return function() {
56
+ seed |= 0
57
+ seed = seed + 0x6D2B79F5 | 0
58
+ let t = Math.imul(seed ^ seed >>> 15, 1 | seed)
59
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t
60
+ return ((t ^ t >>> 14) >>> 0) / 4294967296
61
+ }
62
+ }
63
+
64
+ export function hashStringToNumber(str: string): number {
65
+ let hash = 5381
66
+ for (let i = 0; i < str.length; i++)
67
+ hash = (hash * 33) ^ str.charCodeAt(i)
68
+
69
+ return hash >>> 0
70
+ }
71
+
72
+
73
+ export function randObject(obj: Record<string, any>): Record<string, any> {
74
+ const keys = Object.keys(obj)
75
+
76
+ for (let i = keys.length - 1; i > 0; i--) {
77
+ const j = (Math.random() * (i + 1)) | 0
78
+ ;[keys[i], keys[j]] = [keys[j], keys[i]]
79
+ }
80
+
81
+ const out: Record<string, any> = {}
82
+ for (let i = 0; i < keys.length; i++) {
83
+ const k = keys[i]
84
+ out[k] = obj[k]
85
+ }
86
+
87
+ return out
88
+ }