@stacksjs/utils 0.58.48 → 0.58.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -884,7 +884,7 @@ function prettyBytes(number, options) {
884
884
  return prefix + numberString + separator + unit;
885
885
  }
886
886
  // package.json
887
- var version = "0.58.48";
887
+ var version = "0.58.49";
888
888
  export {
889
889
  wordChar,
890
890
  wordBoundary,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/utils",
3
3
  "type": "module",
4
- "version": "0.58.48",
4
+ "version": "0.58.49",
5
5
  "description": "The Stacks helper functions.",
6
6
  "author": "Chris Breuer",
7
7
  "license": "MIT",
@@ -42,7 +42,8 @@
42
42
  ],
43
43
  "files": [
44
44
  "README.md",
45
- "dist"
45
+ "dist",
46
+ "src"
46
47
  ],
47
48
  "scripts": {
48
49
  "build": "bun --bun build.ts",
package/src/base.ts ADDED
@@ -0,0 +1,12 @@
1
+ export { toString } from '@stacksjs/strings'
2
+
3
+ export function assert(condition: boolean, message: string): asserts condition {
4
+ if (!condition)
5
+ throw new Error(message)
6
+ }
7
+
8
+ // export function noop() {}
9
+
10
+ export async function loop(times: number, callback: any) {
11
+ [...Array(times)].forEach(async (item, i) => await callback(i))
12
+ }
package/src/clean.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { path as p } from '@stacksjs/path'
2
+ import { rimraf } from './delete'
3
+
4
+ export async function cleanProject() {
5
+ return await rimraf([
6
+ p.projectPath('bun.lockb'),
7
+ p.projectPath('yarn.lock'),
8
+ p.projectPath('node_modules/'),
9
+ p.frameworkPath('dist'),
10
+ p.frameworkPath('node_modules'),
11
+ p.frameworkPath('**/dist'),
12
+ p.frameworkPath('**/node_modules'),
13
+ p.cloudPath('cdk.out/'),
14
+ p.cloudPath('cdk.context.json'),
15
+ p.cloudPath('dist.zip'),
16
+ ])
17
+ }
package/src/config.ts ADDED
@@ -0,0 +1,25 @@
1
+ export {
2
+ defineApp,
3
+ defineCache,
4
+ defineCli,
5
+ defineCdn,
6
+ defineCronJob,
7
+ defineJob,
8
+ defineDependencies,
9
+ defineDatabase,
10
+ defineDns,
11
+ defineEmailConfig,
12
+ defineGit,
13
+ defineHashing,
14
+ defineLibrary,
15
+ defineNotification,
16
+ defineSms,
17
+ defineEmail,
18
+ defineChat,
19
+ definePayment,
20
+ defineQueue,
21
+ defineSearchEngine,
22
+ defineServices,
23
+ defineStorage,
24
+ defineUi,
25
+ } from '@stacksjs/config'
@@ -0,0 +1,29 @@
1
+ export {
2
+ add,
3
+ allocate,
4
+ compare,
5
+ convert,
6
+ equal,
7
+ greaterThan,
8
+ greaterThanOrEqual,
9
+ hasSubUnits,
10
+ isZero,
11
+ lessThan,
12
+ lessThanOrEqual,
13
+ maximum,
14
+ minimum,
15
+ multiply,
16
+ normalizeScale,
17
+ dinero,
18
+ dinero as money,
19
+ subtract,
20
+ toSnapshot,
21
+ toUnits,
22
+ toDecimal,
23
+ trimScale,
24
+ haveSameCurrency,
25
+ haveSameAmount,
26
+ dinero as currency,
27
+ } from 'dinero.js'
28
+ export { USD } from '@dinero.js/currencies'
29
+ export type { Dinero, Currency } from 'dinero.js'
@@ -0,0 +1 @@
1
+ export { debounce } from 'perfect-debounce'
package/src/delete.ts ADDED
@@ -0,0 +1 @@
1
+ export { rimraf } from 'rimraf'
package/src/equal.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { getTypeName } from '@stacksjs/types'
2
+
3
+ export function isDeepEqual(value1: any, value2: any): boolean {
4
+ const type1 = getTypeName(value1)
5
+ const type2 = getTypeName(value2)
6
+ if (type1 !== type2)
7
+ return false
8
+
9
+ if (type1 === 'array') {
10
+ if (value1.length !== value2.length)
11
+ return false
12
+
13
+ return value1.every((item: any, i: number) => {
14
+ return isDeepEqual(item, value2[i])
15
+ })
16
+ }
17
+ if (type1 === 'object') {
18
+ const keyArr = Object.keys(value1)
19
+ if (keyArr.length !== Object.keys(value2).length)
20
+ return false
21
+
22
+ return keyArr.every((key: string) => {
23
+ return isDeepEqual(value1[key], value2[key])
24
+ })
25
+ }
26
+ return Object.is(value1, value2)
27
+ }
@@ -0,0 +1 @@
1
+ export { getExportsSize } from 'export-size'
@@ -0,0 +1,32 @@
1
+ import type { Fn, Nullable } from '@stacksjs/types'
2
+
3
+ /**
4
+ * Call every function in an array
5
+ */
6
+ export function batchInvoke(functions: Nullable<Fn>[]) {
7
+ functions.forEach(fn => fn && fn())
8
+ }
9
+
10
+ // /**
11
+ // * Call the function
12
+ // */
13
+ // export function invoke(fn: Fn) {
14
+ // return fn()
15
+ // }
16
+
17
+ /**
18
+ * Pass the value through the callback, and return the value
19
+ *
20
+ * @example
21
+ * ```
22
+ * function createUser(name: string): User {
23
+ * return tap(new User, user => {
24
+ * user.name = name
25
+ * })
26
+ * }
27
+ * ```
28
+ */
29
+ export function tap<T>(value: T, callback: (value: T) => void): T {
30
+ callback(value)
31
+ return value
32
+ }
package/src/git.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { execSync } from 'node:child_process'
2
+
3
+ export function isGitClean() {
4
+ try {
5
+ execSync('git diff-index --quiet HEAD --')
6
+ return true
7
+ }
8
+ catch (error) {
9
+ return false
10
+ }
11
+ }
package/src/glob.ts ADDED
@@ -0,0 +1 @@
1
+ export { glob } from '@stacksjs/storage'
package/src/guards.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Type guard to filter out null-ish values
3
+ *
4
+ * @category Guards
5
+ * @example array.filter(notNullish)
6
+ */
7
+ export function notNullish<T>(v: T | null | undefined): v is NonNullable<T> {
8
+ return v != null
9
+ }
10
+
11
+ /**
12
+ * Type guard to filter out null values
13
+ *
14
+ * @category Guards
15
+ * @example array.filter(noNull)
16
+ */
17
+ export function noNull<T>(v: T | null): v is Exclude<T, null> {
18
+ return v !== null
19
+ }
20
+
21
+ /**
22
+ * Type guard to filter out null-ish values
23
+ *
24
+ * @category Guards
25
+ * @example array.filter(notUndefined)
26
+ */
27
+ export function notUndefined<T>(v: T): v is Exclude<T, undefined> {
28
+ return v !== undefined
29
+ }
30
+
31
+ /**
32
+ * Type guard to filter out falsy values
33
+ *
34
+ * @category Guards
35
+ * @example array.filter(isTruthy)
36
+ */
37
+ export function isTruthy<T>(v: T): v is NonNullable<T> {
38
+ return Boolean(v)
39
+ }
package/src/hash.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { hashPaths } from '@stacksjs/storage'
2
+ import { path as p } from '@stacksjs/path'
3
+ import { config } from '@stacksjs/config'
4
+
5
+ export const originRequestFunctionHash = hashPaths(p.cloudPath('src/edge'))
6
+
7
+ const docsSrc = [
8
+ p.projectPath('docs'),
9
+ p.projectPath('config/docs.ts'),
10
+ ]
11
+
12
+ const websiteSrc = [
13
+ p.projectPath('resources/views'),
14
+ // p.projectPath('config/app.ts'),
15
+ ]
16
+
17
+ export const websiteSourceHash = config.app.docMode === true ? hashPaths(docsSrc) : hashPaths(websiteSrc)
package/src/helpers.ts ADDED
@@ -0,0 +1,187 @@
1
+ import type { AddressInfo } from 'node:net'
2
+
3
+ // import { runAction } from '@stacksjs/actions'
4
+ import { log, runCommand } from '@stacksjs/cli'
5
+ import type { Result } from '@stacksjs/error-handling'
6
+ import { err, handleError, ok } from '@stacksjs/error-handling'
7
+ import { frameworkPath, projectPath } from '@stacksjs/path'
8
+ import * as storage from '@stacksjs/storage'
9
+ import type { CliOptions, Manifest, StacksError, SyncSubprocess } from '@stacksjs/types'
10
+ import type { NpmScript } from '@stacksjs/enums'
11
+ import { Action } from '@stacksjs/enums'
12
+ import { parse } from 'yaml'
13
+
14
+ // import { semver } from './versions'
15
+ import { app, ui } from '@stacksjs/config'
16
+
17
+ export async function packageManager() {
18
+ const { packageManager } = await storage.readPackageJson(frameworkPath('package.json'))
19
+ return packageManager
20
+ }
21
+
22
+ export async function initProject(): Promise<Result<SyncSubprocess, StacksError>> {
23
+ if (app.env !== 'production')
24
+ log.info('Project not yet initialized, generating application key...')
25
+ else
26
+ handleError('Please run `buddy key:generate` to generate an application key')
27
+
28
+ const result = await runAction(Action.KeyGenerate, { cwd: projectPath() })
29
+
30
+ if (result.isErr())
31
+ return err(handleError(result.error))
32
+
33
+ log.info('Application key generated.')
34
+
35
+ return ok(result.value)
36
+ }
37
+
38
+ export async function ensureProjectIsInitialized() {
39
+ if (storage.isFile(projectPath('.env')))
40
+ return await isAppKeySet()
41
+
42
+ // copy the .env.example file to .env
43
+ if (storage.isFile(projectPath('.env.example')))
44
+ await runCommand('cp .env.example .env', { cwd: projectPath() })
45
+ else
46
+ console.error('no .env.example file found')
47
+
48
+ return await isAppKeySet()
49
+ }
50
+
51
+ export async function installIfVersionMismatch() {
52
+ // const requiredBunVersion = '0.8.1'
53
+ // const installedBunVersion = process.version
54
+
55
+ // if (!semver.satisfies(installedBunVersion, requiredBunVersion)) {
56
+ // log.warn(`Installed Bun version ${italic(installedBunVersion)} does not satisfy required version ${italic(requiredBunVersion)}. Adding it to your environment. One moment...`)
57
+ // await runCommand(`tea +bun.sh${requiredBunVersion} >/dev/null 2>&1`)
58
+ // }
59
+ }
60
+
61
+ export async function frameworkVersion(): Promise<string> {
62
+ return (await storage.readPackageJson(frameworkPath('package.json'))).version
63
+ }
64
+
65
+ export async function isAppKeySet() {
66
+ const env = await storage.readTextFile('.env', projectPath())
67
+ const lines = env.data.split('\n')
68
+ const appKey = lines.find(line => line.startsWith('APP_KEY='))
69
+
70
+ return !!(appKey && appKey.length > 16)
71
+ }
72
+
73
+ /**
74
+ * Determines the utilized reset preset.
75
+ *
76
+ * @url https://www.npmjs.com/package/@unocss/reset
77
+ * @param preset
78
+ */
79
+ export function determineResetPreset(preset?: string) {
80
+ if (ui.reset)
81
+ preset = ui.reset
82
+
83
+ if (preset === 'tailwind')
84
+ return ['import \'@unocss/reset/tailwind.css\'']
85
+
86
+ if (preset === 'normalize')
87
+ return ['import \'@unocss/reset/normalize.css\'']
88
+
89
+ if (preset === 'sanitize')
90
+ return ['import \'@unocss/reset/sanitize/sanitize.css\'', 'import \'@unocss/reset/sanitize/assets.css']
91
+
92
+ if (preset === 'eric-meyer')
93
+ return ['import \'@unocss/reset/eric-meyer.css\'']
94
+
95
+ if (preset === 'antfu')
96
+ return ['import \'@unocss/reset/antfu.css\'']
97
+
98
+ return []
99
+ }
100
+
101
+ /**
102
+ * Determines whether the specified value is a package manifest.
103
+ */
104
+ export function isManifest(obj: any): obj is Manifest {
105
+ return obj
106
+ && typeof obj === 'object'
107
+ && isOptionalString(obj.name)
108
+ && isOptionalString(obj.version)
109
+ && isOptionalString(obj.description)
110
+ }
111
+
112
+ /**
113
+ * Determines whether the specified value is a string, null, or undefined.
114
+ */
115
+ export function isOptionalString(value: any): value is string | undefined {
116
+ const type = typeof value
117
+ return value === null
118
+ || type === 'undefined'
119
+ || type === 'string'
120
+ }
121
+
122
+ export async function setEnvValue(key: string, value: string) {
123
+ const file = await storage.readTextFile(projectPath('.env'))
124
+
125
+ await storage.writeTextFile({
126
+ path: projectPath('.env'),
127
+ data: file.data.replace(/APP_KEY=/g, `APP_KEY=${value}`), // todo: do not hardcode the APP_KEY here and instead use the key parameter
128
+ })
129
+ }
130
+
131
+ /**
132
+ * Runs the specified NPM script in the package.json file.
133
+ */
134
+ export async function runNpmScript(script: NpmScript, options?: CliOptions): Promise<Result<SyncSubprocess, StacksError>> {
135
+ const { data: manifest } = await storage.readJsonFile('package.json', frameworkPath())
136
+
137
+ if (isManifest(manifest) && hasScript(manifest, script)) // simple, yet effective check to see if the script exists
138
+ return await runCommand(`bun --bun run ${script}`, options)
139
+
140
+ return err(handleError(`The ${script} script does not exist in the package.json file.`))
141
+ }
142
+
143
+ /**
144
+ * Determines whether the specified NPM script exists in the given manifest.
145
+ */
146
+ export function hasScript(manifest: Manifest, script: NpmScript): boolean {
147
+ const scripts = manifest.scripts as Record<NpmScript, string> | undefined
148
+
149
+ if (scripts && typeof scripts === 'object')
150
+ return Boolean(scripts[script])
151
+
152
+ return false
153
+ }
154
+
155
+ export function parseYaml(content: any) {
156
+ return parse(content)
157
+ }
158
+
159
+ /**
160
+ * Determines the level of debugging.
161
+ *
162
+ * The debug level is determined by the following:
163
+ * 1. The --verbose flag
164
+ * 2. The debug property in the app configuration
165
+ *
166
+ * Currently, we don't support a custom debug level,
167
+ * though, we would like to in the future.
168
+ *
169
+ * @param options
170
+ */
171
+ export function determineDebugLevel(options?: CliOptions) {
172
+ if (options?.verbose === true)
173
+ return true
174
+
175
+ return app.debug === true
176
+ }
177
+
178
+ export function isIpv6(address: AddressInfo): boolean {
179
+ return address.family === 'IPv6'
180
+ // in node >=18.0 <18.4 this was an integer value. This was changed in a minor version.
181
+ // See: https://github.com/laravel/vite-plugin/issues/103
182
+
183
+ // @ts-expect-error-next-line
184
+ || address.family === 6
185
+ }
186
+
187
+ export { dump as dumpYaml, load as loadYaml } from 'js-yaml'
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ export * from './base'
2
+ export * from './clean'
3
+ export * from './config'
4
+ export * from './currency'
5
+ export * from './debounce'
6
+ export * from './delete'
7
+ export * from './equal'
8
+ export * from './export-size'
9
+ export * from './function'
10
+ export * from './git'
11
+ export * from './guards'
12
+ export * from './hash'
13
+ export * from './helpers'
14
+ export * from './macroable'
15
+ export * from './math'
16
+ export * from './p'
17
+ export * from './promise'
18
+ export * from './regex'
19
+ export * from './sleep'
20
+ export * from './throttle'
21
+ export * from './vendors'
22
+ export * from './versions'
@@ -0,0 +1 @@
1
+ export { Macroable } from 'macroable'
package/src/math.ts ADDED
@@ -0,0 +1,30 @@
1
+ export const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n))
2
+
3
+ export function rand(min: number, max: number) {
4
+ min = Math.ceil(min)
5
+ max = Math.floor(max)
6
+ return Math.floor(Math.random() * (max - min + 1)) + min
7
+ }
8
+
9
+ // not, -> exported as well in ../regex
10
+ export {
11
+ and,
12
+ createGenericProjection,
13
+ createProjection,
14
+ logicNot,
15
+ logicOr,
16
+ or,
17
+ useAbs,
18
+ useAverage,
19
+ useCeil,
20
+ useClamp,
21
+ useFloor,
22
+ useMath,
23
+ useMax,
24
+ useMin,
25
+ usePrecision,
26
+ useProjection,
27
+ useRound,
28
+ useSum,
29
+ useTrunc,
30
+ } from '@vueuse/math'
package/src/p.ts ADDED
@@ -0,0 +1,119 @@
1
+ import pLimit from 'p-limit'
2
+
3
+ /**
4
+ * Internal marker for filtered items
5
+ */
6
+ const VOID = Symbol('p-void')
7
+
8
+ interface POptions {
9
+ /**
10
+ * How many promises are resolved at the same time.
11
+ */
12
+ concurrency?: number | undefined
13
+ }
14
+
15
+ class PInstance<T = any> extends Promise<Awaited<T>[]> {
16
+ private promises = new Set<T | Promise<T>>()
17
+
18
+ get promise(): Promise<Awaited<T>[]> {
19
+ let batch
20
+ const items = [...Array.from(this.items), ...Array.from(this.promises)]
21
+
22
+ if (this.options?.concurrency) {
23
+ const limit = pLimit(this.options.concurrency)
24
+ batch = Promise.all(items.map(p => limit(() => p)))
25
+ }
26
+ else {
27
+ batch = Promise.all(items)
28
+ }
29
+
30
+ return batch.then(l => l.filter((i: any) => i !== VOID))
31
+ }
32
+
33
+ constructor(public items: Iterable<T> = [], public options?: POptions) {
34
+ super(() => {})
35
+ }
36
+
37
+ add(...args: (T | Promise<T>)[]) {
38
+ args.forEach((i) => {
39
+ this.promises.add(i)
40
+ })
41
+ }
42
+
43
+ map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>> {
44
+ return new PInstance(
45
+ Array.from(this.items)
46
+ .map(async (i, idx) => {
47
+ const v = await i
48
+ if ((v as any) === VOID)
49
+ return VOID as unknown as U
50
+ return fn(v, idx)
51
+ }),
52
+ this.options,
53
+ )
54
+ }
55
+
56
+ filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>> {
57
+ return new PInstance(
58
+ Array.from(this.items)
59
+ .map(async (i, idx) => {
60
+ const v = await i
61
+ const r = await fn(v, idx)
62
+ if (!r)
63
+ return VOID as unknown as T
64
+ return v
65
+ }),
66
+ this.options,
67
+ )
68
+ }
69
+
70
+ forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void> {
71
+ return this.map(fn).then()
72
+ }
73
+
74
+ reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U> {
75
+ return this.promise.then(array => array.reduce(fn, initialValue))
76
+ }
77
+
78
+ clear() {
79
+ this.promises.clear()
80
+ }
81
+
82
+ then(fn?: () => PromiseLike<any>) {
83
+ const p = this.promise
84
+
85
+ if (fn)
86
+ return p.then(fn)
87
+
88
+ return p
89
+ }
90
+
91
+ catch(fn?: (err: unknown) => PromiseLike<any>) {
92
+ return this.promise.catch(fn)
93
+ }
94
+
95
+ finally(fn?: () => void) {
96
+ return this.promise.finally(fn)
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Utility for managing multiple promises.
102
+ *
103
+ * @see https://github.com/antfu/utils/tree/main/docs/p.md
104
+ * @category Promise
105
+ * @example
106
+ * ```
107
+ * import { p } from '@stacksjs/utils'
108
+ *
109
+ * const items = [1, 2, 3, 4, 5]
110
+ *
111
+ * await p(items)
112
+ * .map(async i => await multiply(i, 3))
113
+ * .filter(async i => await isEven(i))
114
+ * // [6, 12]
115
+ * ```
116
+ */
117
+ export function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T> {
118
+ return new PInstance(items, options)
119
+ }
package/src/promise.ts ADDED
@@ -0,0 +1,117 @@
1
+ import { remove } from '@stacksjs/arrays'
2
+
3
+ export interface SingletonPromiseReturn<T> {
4
+ (): Promise<T>
5
+ /**
6
+ * Reset current staled promise.
7
+ * Await it to have proper shutdown.
8
+ */
9
+ reset: () => Promise<void>
10
+ }
11
+
12
+ // export { peek } from 'bun'
13
+
14
+ /**
15
+ * Promise with `resolve` and `reject` methods of itself
16
+ */
17
+ export interface ControlledPromise<T = void> extends Promise<T> {
18
+ resolve(value: T | PromiseLike<T>): void
19
+ reject(reason?: any): void
20
+ }
21
+
22
+ /**
23
+ * Create singleton promise function.
24
+ *
25
+ * @category Promise
26
+ */
27
+ export function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T> {
28
+ let _promise: Promise<T> | undefined
29
+
30
+ function wrapper() {
31
+ if (!_promise)
32
+ _promise = fn()
33
+ return _promise
34
+ }
35
+ wrapper.reset = async () => {
36
+ const _prev = _promise
37
+ _promise = undefined
38
+ if (_prev)
39
+ await _prev
40
+ }
41
+
42
+ return wrapper
43
+ }
44
+
45
+ /**
46
+ * Create a promise lock.
47
+ *
48
+ * @category Promise
49
+ * @example
50
+ * ```
51
+ * const lock = createPromiseLock()
52
+ *
53
+ * lock.run(async () => {
54
+ * await doSomething()
55
+ * })
56
+ *
57
+ * // in anther context:
58
+ * await lock.wait() // it will wait all tasking finished
59
+ * ```
60
+ */
61
+ export function createPromiseLock() {
62
+ const locks: Promise<any>[] = []
63
+
64
+ return {
65
+ async run<T = void>(fn: () => Promise<T>): Promise<T> {
66
+ const p = fn()
67
+ locks.push(p)
68
+ try {
69
+ return await p
70
+ }
71
+ finally {
72
+ remove(locks, p)
73
+ }
74
+ },
75
+ async wait(): Promise<void> {
76
+ await Promise.allSettled(locks)
77
+ },
78
+ isWaiting() {
79
+ return Boolean(locks.length)
80
+ },
81
+ clear() {
82
+ locks.length = 0
83
+ },
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Return a Promise with `resolve` and `reject` methods
89
+ *
90
+ * @category Promise
91
+ * @example
92
+ * ```
93
+ * const promise = createControlledPromise()
94
+ *
95
+ * await promise
96
+ *
97
+ * // in anther context:
98
+ * promise.resolve(data)
99
+ * ```
100
+ */
101
+ export function createControlledPromise<T>(): ControlledPromise<T> {
102
+ let resolve: any, reject: any
103
+ const promise = new Promise<T>((_resolve, _reject) => {
104
+ resolve = _resolve
105
+ reject = _reject
106
+ }) as ControlledPromise<T>
107
+
108
+ promise.resolve = resolve
109
+
110
+ promise.reject = reject
111
+ return promise
112
+ }
113
+
114
+ /**
115
+ * Create a promise that will be resolved after `ms` milliseconds.
116
+ */
117
+ // export { sleep, sleepSync } from 'bun'
package/src/regex.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type { Flag, MagicRegExp, MagicRegExpMatchArray, Input, MapToStringCapturedBy, StringCapturedBy } from 'magic-regexp'
2
+ export { createRegExp, caseInsensitive, anyOf, carriageReturn, char, charIn, charNotIn, digit, dotAll, exactly, global, letter, linefeed, maybe, multiline, not, oneOrMore, sticky, tab, unicode, whitespace, withIndices, word, wordBoundary, wordChar } from 'magic-regexp'
package/src/sleep.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Pauses execution for a specified number of milliseconds.
3
+ * @param ms The number of milliseconds to pause execution.
4
+ * @returns A promise that resolves after the specified delay.
5
+ */
6
+ export function sleep(ms: number): Promise<void> {
7
+ return new Promise(resolve => setTimeout(resolve, ms))
8
+ }
9
+
10
+ /**
11
+ * Pauses execution for a specified number of milliseconds.
12
+ * @param ms The number of milliseconds to pause execution.
13
+ * @returns A promise that resolves after the specified delay.
14
+ */
15
+ export function wait(ms: number): Promise<void> {
16
+ return new Promise(resolve => setTimeout(resolve, ms))
17
+ }
18
+
19
+ /**
20
+ * Pauses execution for a specified number of milliseconds.
21
+ * @param ms The number of milliseconds to pause execution.
22
+ * @returns A promise that resolves after the specified delay.
23
+ */
24
+ export function delay(ms: number): Promise<void> {
25
+ return new Promise(resolve => setTimeout(resolve, ms))
26
+ }
27
+
28
+ /**
29
+ * Pauses execution until a specified condition is met.
30
+ * @param condition The condition to wait for.
31
+ * @param interval The interval at which to check the condition, in milliseconds. Defaults to 1000.
32
+ * @returns A promise that resolves when the condition is met.
33
+ */
34
+ export function waitUntil(condition: () => boolean, interval: number = 1000): Promise<void> {
35
+ return new Promise((resolve) => {
36
+ const check = setInterval(() => {
37
+ if (condition()) {
38
+ clearInterval(check)
39
+ resolve()
40
+ }
41
+ }, interval)
42
+ })
43
+ }
44
+
45
+ /**
46
+ * Pauses execution while a specified condition is met.
47
+ * @param condition The condition to wait while.
48
+ * @param interval The interval at which to check the condition, in milliseconds. Defaults to 1000.
49
+ * @returns A promise that resolves when the condition is no longer met.
50
+ */
51
+ export function waitWhile(condition: () => boolean, interval: number = 1000): Promise<void> {
52
+ return new Promise((resolve) => {
53
+ const check = setInterval(() => {
54
+ if (!condition()) {
55
+ clearInterval(check)
56
+ resolve()
57
+ }
58
+ }, interval)
59
+ })
60
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Throttle a function.
3
+ *
4
+ * @param {Function} fn - The function to throttle.
5
+ * @param {number} [wait] - The time to wait between function calls.
6
+ * @returns {Function} - A new function that throttles the calls to the original function.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * // logs window dimensions at most every 250ms
11
+ * window.addEventListener(
12
+ * "resize",
13
+ * throttle(function (evt) {
14
+ * console.log(window.innerWidth)
15
+ * console.log(window.innerHeight)
16
+ * }, 250)
17
+ * )
18
+ * ```
19
+ */
20
+
21
+ export function throttle(fn: Function, wait = 300) {
22
+ let inThrottle: boolean
23
+ let lastFn: ReturnType<typeof setTimeout>
24
+ let lastTime: number
25
+
26
+ return function (this: unknown, ...args: any[]) {
27
+ if (!inThrottle) {
28
+ fn.apply(this, args)
29
+
30
+ lastTime = Date.now()
31
+ inThrottle = true
32
+ }
33
+ else {
34
+ clearTimeout(lastFn)
35
+
36
+ lastFn = setTimeout(() => {
37
+ if (Date.now() - lastTime >= wait) {
38
+ fn.apply(this, args) // Use 'this' directly
39
+ lastTime = Date.now()
40
+ }
41
+ }, Math.max(wait - (Date.now() - lastTime), 0))
42
+ }
43
+ }
44
+ }
package/src/vendors.ts ADDED
@@ -0,0 +1,258 @@
1
+ export {
2
+ asyncComputed,
3
+ breakpointsAntDesign,
4
+ breakpointsBootstrapV5,
5
+ breakpointsMasterCss,
6
+ breakpointsQuasar,
7
+ breakpointsSematic,
8
+ breakpointsTailwind,
9
+ breakpointsVuetify,
10
+ cloneFnJSON,
11
+ computedAsync,
12
+ computedInject,
13
+ createFetch,
14
+ createReusableTemplate,
15
+ createTemplatePromise,
16
+ createUnrefFn,
17
+ customStorageEventName,
18
+ defaultDocument,
19
+ defaultLocation,
20
+ defaultNavigator,
21
+ defaultWindow,
22
+ executeTransition,
23
+ formatTimeAgo,
24
+ getSSRHandler,
25
+ mapGamepadToXbox360Controller,
26
+ onClickOutside,
27
+ onKeyDown,
28
+ onKeyPressed,
29
+ onKeyStroke,
30
+ onKeyUp,
31
+ onLongPress,
32
+ onStartTyping,
33
+ setSSRHandler,
34
+ templateRef,
35
+ unrefElement,
36
+ useActiveElement,
37
+ useAnimate,
38
+ useAsyncQueue,
39
+ useAsyncState,
40
+ useBase64,
41
+ useBattery,
42
+ useBluetooth,
43
+ useBreakpoints,
44
+ useBroadcastChannel,
45
+ useBrowserLocation,
46
+ useCached,
47
+ useClipboard,
48
+ useCloned,
49
+ useColorMode,
50
+ useConfirmDialog,
51
+ useCssVar,
52
+ useCurrentElement,
53
+ useCycleList,
54
+ useDark,
55
+ useDebouncedRefHistory,
56
+ useDeviceMotion,
57
+ useDeviceOrientation,
58
+ useDevicePixelRatio,
59
+ useDevicesList,
60
+ useDisplayMedia,
61
+ useDocumentVisibility,
62
+ useDraggable,
63
+ useDropZone,
64
+ useElementBounding,
65
+ useElementByPoint,
66
+ useElementHover,
67
+ useElementSize,
68
+ useElementVisibility,
69
+ useEventBus,
70
+ useEventListener,
71
+ useEventSource,
72
+ useEyeDropper,
73
+ useFavicon,
74
+ useFetch,
75
+ useFileDialog,
76
+ useFileSystemAccess,
77
+ useFocus,
78
+ useFocusWithin,
79
+ useFps,
80
+ useFullscreen,
81
+ useGamepad,
82
+ useGeolocation,
83
+ useIdle,
84
+ useImage,
85
+ useInfiniteScroll,
86
+ useIntersectionObserver,
87
+ useKeyModifier,
88
+ useLocalStorage,
89
+ useMagicKeys,
90
+ useManualRefHistory,
91
+ useMediaControls,
92
+ useMediaQuery,
93
+ useMemoize,
94
+ useMemory,
95
+ useMounted,
96
+ useMouse,
97
+ useMouseInElement,
98
+ useMousePressed,
99
+ useMutationObserver,
100
+ useNavigatorLanguage,
101
+ useNetwork,
102
+ useObjectUrl,
103
+ useOffsetPagination,
104
+ useOnline,
105
+ usePageLeave,
106
+ useParallax,
107
+ useParentElement,
108
+ usePerformanceObserver,
109
+ usePermission,
110
+ usePointer,
111
+ usePointerLock,
112
+ usePointerSwipe,
113
+ usePreferredColorScheme,
114
+ usePreferredContrast,
115
+ usePreferredDark,
116
+ usePreferredLanguages,
117
+ usePreferredReducedMotion,
118
+ usePrevious,
119
+ useRafFn,
120
+ useRefHistory,
121
+ useResizeObserver,
122
+ useScreenOrientation,
123
+ useScreenSafeArea,
124
+ useScriptTag,
125
+ useScroll,
126
+ useScrollLock,
127
+ useSessionStorage,
128
+ useShare,
129
+ useSorted,
130
+ useSpeechRecognition,
131
+ useSpeechSynthesis,
132
+ useStepper,
133
+ useStorage,
134
+ useStorageAsync,
135
+ useStyleTag,
136
+ useSupported,
137
+ useSwipe,
138
+ useTemplateRefsList,
139
+ useTextDirection,
140
+ useTextSelection,
141
+ useTextareaAutosize,
142
+ useThrottledRefHistory,
143
+ useTimeAgo,
144
+ useTimeoutPoll,
145
+ useTimestamp,
146
+ useTitle,
147
+ useTransition,
148
+ useToggle,
149
+ useUrlSearchParams,
150
+ useUserMedia,
151
+ useVModel,
152
+ useVModels,
153
+ useVibrate,
154
+ useVirtualList,
155
+ useWakeLock,
156
+ useWebNotification,
157
+ useWebSocket,
158
+ useWebWorker,
159
+ useWebWorkerFn,
160
+ useWindowFocus,
161
+ useWindowScroll,
162
+ useWindowSize,
163
+ useDateFormat,
164
+ useNow,
165
+ watchArray,
166
+ watchAtMost,
167
+ watchDebounced,
168
+ watchDeep,
169
+ watchIgnorable,
170
+ watchImmediate,
171
+ watchOnce,
172
+ watchPausable,
173
+ watchThrottled,
174
+ watchTriggerable,
175
+ watchWithFilter,
176
+ whenever,
177
+ syncRef,
178
+ syncRefs,
179
+ throttledRef,
180
+ throttledWatch,
181
+ toReactive,
182
+ tryOnBeforeMount,
183
+ tryOnBeforeUnmount,
184
+ tryOnMounted,
185
+ tryOnScopeDispose,
186
+ tryOnUnmounted,
187
+ until,
188
+ isDefined,
189
+ ignorableWatch,
190
+ extendRef,
191
+ eagerComputed,
192
+ debouncedRef,
193
+ debouncedWatch,
194
+ createReactiveFn,
195
+ createSharedComposable,
196
+ createInjectionState,
197
+ createGlobalState,
198
+ createEventHook,
199
+ controlledRef,
200
+ controlledComputed,
201
+ computedEager,
202
+ computedWithControl,
203
+ autoResetRef,
204
+ injectLocal,
205
+ makeDestructurable,
206
+ pausableWatch,
207
+ provideLocal,
208
+ reactify,
209
+ reactifyObject,
210
+ reactiveComputed,
211
+ reactiveOmit,
212
+ reactivePick,
213
+ refAutoReset,
214
+ refDebounced,
215
+ refDefault,
216
+ refThrottled,
217
+ refWithControl,
218
+ resolveRef,
219
+ resolveUnref,
220
+ useArrayDifference,
221
+ useArrayEvery,
222
+ useArrayFilter,
223
+ useArrayFind,
224
+ useArrayFindIndex,
225
+ useArrayIncludes,
226
+ useArrayMap,
227
+ useArrayReduce,
228
+ useArraySome,
229
+ useArrayUnique,
230
+ useClipboardItems,
231
+ useCounter,
232
+ useDebounce,
233
+ useDebounceFn,
234
+ useInterval,
235
+ useIntervalFn,
236
+ useLastChanged,
237
+ useThrottle,
238
+ useThrottleFn,
239
+ useTimeout,
240
+ useTimeoutFn,
241
+ useToNumber,
242
+ useToString,
243
+ } from '@vueuse/core'
244
+
245
+ export type {
246
+ // Head,
247
+ HeadObject,
248
+ HeadObjectPlain,
249
+ } from '@vueuse/head'
250
+
251
+ export {
252
+ Head,
253
+ HeadVuePlugin,
254
+ createHead,
255
+ renderHeadToString,
256
+ } from '@vueuse/head'
257
+
258
+ export { default as readableSize } from 'pretty-bytes'
@@ -0,0 +1,6 @@
1
+ import { version } from '../package.json'
2
+
3
+ // import { semver } from 'bun'
4
+
5
+ export { version }
6
+ // export { version, semver }