@stacksjs/utils 0.64.6 → 0.67.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/src/base.ts DELETED
@@ -1,12 +0,0 @@
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 DELETED
@@ -1,15 +0,0 @@
1
- import { path as p } from '@stacksjs/path'
2
-
3
- export async function cleanProject() {
4
- const $ = Bun.$
5
- await $`rm -rf ${p.projectPath('bun.lockb')}`
6
- await $`rm -rf ${p.projectPath('yarn.lock')}` // just in case
7
- await $`rm -rf ${p.projectPath('node_modules/')}`
8
- await $`rm -rf ${p.frameworkPath('dist')}`
9
- await $`rm -rf ${p.frameworkPath('node_modules')}`
10
- await $`rm -rf ${p.frameworkPath('**/dist')}`
11
- await $`rm -rf ${p.frameworkPath('**/node_modules')}`
12
- await $`rm -rf ${p.frameworkCloudPath('cdk.out/')}`
13
- await $`rm -rf ${p.frameworkCloudPath('cdk.context.json')}`
14
- await $`rm -rf ${p.frameworkCloudPath('dist.zip')}`
15
- }
package/src/config.ts DELETED
@@ -1,25 +0,0 @@
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'
package/src/debounce.ts DELETED
@@ -1 +0,0 @@
1
- export { debounce } from 'perfect-debounce'
package/src/equal.ts DELETED
@@ -1,24 +0,0 @@
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) return false
7
-
8
- if (type1 === 'array') {
9
- if (value1.length !== value2.length) return false
10
-
11
- return value1.every((item: any, i: number) => {
12
- return isDeepEqual(item, value2[i])
13
- })
14
- }
15
- if (type1 === 'object') {
16
- const keyArr = Object.keys(value1)
17
- if (keyArr.length !== Object.keys(value2).length) return false
18
-
19
- return keyArr.every((key: string) => {
20
- return isDeepEqual(value1[key], value2[key])
21
- })
22
- }
23
- return Object.is(value1, value2)
24
- }
@@ -1 +0,0 @@
1
- export { getExportsSize } from 'export-size'
package/src/find.ts DELETED
@@ -1,88 +0,0 @@
1
- import type { Dirent } from 'node:fs'
2
- import fs from 'node:fs/promises'
3
- import os from 'node:os'
4
- import path from 'node:path'
5
- import { italic } from '@stacksjs/cli'
6
- import { log } from '@stacksjs/logging'
7
-
8
- const targetFileName = 'buddy' // The exact name of the target file
9
-
10
- const excludePatterns = [
11
- 'node_modules',
12
- 'dist',
13
- 'vendor',
14
- `${os.homedir()}/Documents`,
15
- `${os.homedir()}/Pictures`,
16
- `${os.homedir()}/Library`,
17
- `${os.homedir()}/.Trash`,
18
- /.*out.*|.*\.out.*|out-.*/, // exclude any folder with 'out' in the name
19
- /.*\/\..*/, // exclude any folder that starts with a dot
20
- ]
21
-
22
- interface FindStacksProjectsOptions {
23
- quiet?: boolean
24
- }
25
-
26
- export async function findStacksProjects(dir?: string, options?: FindStacksProjectsOptions): Promise<string[]> {
27
- dir = dir || os.homedir()
28
-
29
- if (!options?.quiet) {
30
- log.info(`Searching for Stacks projects in: ${italic(dir)}`)
31
- log.info(`This may take a few moments...`)
32
- console.log('')
33
- console.log(italic(' Please note, while Stacks is searching for projects on your machine,'))
34
- console.log(italic(' you may be asked for permissions to scan certain directories.'))
35
- console.log('')
36
- log.debug(`Excluding directories: ${excludePatterns.join(', ')}`)
37
- }
38
-
39
- const foundProjects = await searchDirectory(dir)
40
-
41
- if (!foundProjects) throw new Error('No Stacks projects found')
42
-
43
- return foundProjects
44
- }
45
-
46
- async function searchDirectory(directory: string) {
47
- const foundProjects: string[] = []
48
-
49
- const isExcluded = excludePatterns.some((pattern) =>
50
- typeof pattern === 'string' ? directory.includes(pattern) : pattern.test(directory),
51
- )
52
- if (isExcluded) return
53
-
54
- let items: Dirent[]
55
- try {
56
- items = await fs.readdir(directory, { withFileTypes: true })
57
- } catch (error) {
58
- console.error(`Error reading directory ${directory}:`, error)
59
- return
60
- }
61
-
62
- let buddyFileFound = false
63
- let storageDirFound = false
64
-
65
- for (const item of items) {
66
- if (item.isFile() && item.name === targetFileName) {
67
- buddyFileFound = true
68
- } else if (item.isDirectory()) {
69
- // Recursively search in directories
70
- const fullPath = path.join(directory, item.name)
71
- if (item.name === 'storage') {
72
- // Check if the 'storage/framework/core/buddy/' structure exists within this directory
73
- try {
74
- const storagePath = path.join(fullPath, 'framework/core/buddy')
75
- await fs.access(storagePath)
76
- storageDirFound = true
77
- } catch (error) {
78
- // The specific directory structure does not exist
79
- }
80
- }
81
- await searchDirectory(fullPath)
82
- }
83
- }
84
-
85
- if (buddyFileFound && storageDirFound) foundProjects.push(directory) // Both conditions are met
86
-
87
- return foundProjects
88
- }
package/src/function.ts DELETED
@@ -1,32 +0,0 @@
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?.())
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 DELETED
@@ -1,10 +0,0 @@
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
- } catch (error) {
8
- return false
9
- }
10
- }
package/src/glob.ts DELETED
@@ -1 +0,0 @@
1
- export { glob } from '@stacksjs/storage'
package/src/guards.ts DELETED
@@ -1,39 +0,0 @@
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 DELETED
@@ -1,35 +0,0 @@
1
- import { config } from '@stacksjs/config'
2
- import { log } from '@stacksjs/logging'
3
- import { path as p } from '@stacksjs/path'
4
- import { hashPaths } from '@stacksjs/storage'
5
-
6
- export function originRequestFunctionHash() {
7
- try {
8
- return hashPaths(p.cloudPath('src/edge'))
9
- } catch (error: any) {
10
- log.error('Are we in a Docker container? Failed to hash paths. Error below:')
11
- log.error(error)
12
- return undefined
13
- }
14
- }
15
-
16
- export function websiteSourceHash() {
17
- const docsSrc = [p.projectPath('docs')]
18
- const websiteSrc = [
19
- p.projectPath('resources/views'),
20
- p.projectPath('resources/assets'),
21
- p.projectPath('resources/lang'),
22
- p.projectPath('resources/functions'),
23
- p.projectPath('resources/components'),
24
- p.projectPath('resources/modules'),
25
- p.projectPath('resources/stores'),
26
- ]
27
-
28
- return config.app.docMode === true ? hashPaths(docsSrc) : hashPaths(websiteSrc)
29
- }
30
-
31
- export function docsSourceHash() {
32
- const docsSrc = [p.projectPath('docs')]
33
-
34
- return hashPaths(docsSrc)
35
- }
package/src/helpers.ts DELETED
@@ -1,174 +0,0 @@
1
- import type { AddressInfo } from 'node:net'
2
- import { runAction } from '@stacksjs/actions'
3
- import { log, runCommand } from '@stacksjs/cli'
4
- import { app, ui } from '@stacksjs/config'
5
- import type { NpmScript } from '@stacksjs/enums'
6
- import { Action } from '@stacksjs/enums'
7
- import type { Result } from '@stacksjs/error-handling'
8
- import { err, handleError, ok } from '@stacksjs/error-handling'
9
- import { frameworkPath, projectPath } from '@stacksjs/path'
10
- import * as storage from '@stacksjs/storage'
11
- import type { CliOptions, Manifest, Subprocess } from '@stacksjs/types'
12
- import { parse } from 'yaml'
13
-
14
- // import { semver } from './versions'
15
-
16
- export async function packageManager() {
17
- const { packageManager } = await storage.readPackageJson(frameworkPath('package.json'))
18
- return packageManager
19
- }
20
-
21
- export async function initProject(): Promise<Result<Subprocess, Error>> {
22
- if (app.env !== 'production') log.info('Project not yet initialized, generating application key...')
23
- else handleError('Please run `buddy key:generate` to generate an application key')
24
-
25
- const result = await runAction(Action.KeyGenerate, { cwd: projectPath() })
26
-
27
- if (result.isErr()) return err(handleError(result.error))
28
-
29
- log.info('Application key generated.')
30
-
31
- return ok(result.value)
32
- }
33
-
34
- export async function ensureProjectIsInitialized() {
35
- if (storage.isFile(projectPath('.env'))) return await isAppKeySet()
36
-
37
- // copy the .env.example file to .env
38
- if (storage.isFile(projectPath('.env.example'))) await runCommand('cp .env.example .env', { cwd: projectPath() })
39
- else console.error('no .env.example file found')
40
-
41
- return await isAppKeySet()
42
- }
43
-
44
- export async function installIfVersionMismatch() {
45
- // const requiredBunVersion = '0.8.1'
46
- // const installedBunVersion = process.version
47
- // if (!semver.satisfies(installedBunVersion, requiredBunVersion)) {
48
- // log.warn(`Installed Bun version ${italic(installedBunVersion)} does not satisfy required version ${italic(requiredBunVersion)}. Adding it to your environment. One moment...`)
49
- // await runCommand(`tea +bun.sh${requiredBunVersion} >/dev/null 2>&1`)
50
- // }
51
- }
52
-
53
- export async function frameworkVersion(): Promise<string> {
54
- return (await storage.readPackageJson(frameworkPath('package.json'))).version
55
- }
56
-
57
- export async function isAppKeySet() {
58
- const env = await storage.readTextFile('.env', projectPath())
59
- const lines = env.data.split('\n')
60
- const appKey = lines.find((line) => line.startsWith('APP_KEY='))
61
-
62
- return !!(appKey && appKey.length > 16)
63
- }
64
-
65
- /**
66
- * Determines the utilized reset preset.
67
- *
68
- * @url https://www.npmjs.com/package/@unocss/reset
69
- * @param preset
70
- */
71
- export function determineResetPreset(preset?: string) {
72
- if (ui.reset) preset = ui.reset
73
-
74
- if (preset === 'tailwind') return ["import '@unocss/reset/tailwind.css'"]
75
-
76
- if (preset === 'normalize') return ["import '@unocss/reset/normalize.css'"]
77
-
78
- if (preset === 'sanitize')
79
- return ["import '@unocss/reset/sanitize/sanitize.css'", "import '@unocss/reset/sanitize/assets.css"]
80
-
81
- if (preset === 'eric-meyer') return ["import '@unocss/reset/eric-meyer.css'"]
82
-
83
- if (preset === 'antfu') return ["import '@unocss/reset/antfu.css'"]
84
-
85
- return []
86
- }
87
-
88
- /**
89
- * Determines whether the specified value is a package manifest.
90
- */
91
- export function isManifest(obj: any): obj is Manifest {
92
- return (
93
- obj &&
94
- typeof obj === 'object' &&
95
- isOptionalString(obj.name) &&
96
- isOptionalString(obj.version) &&
97
- isOptionalString(obj.description)
98
- )
99
- }
100
-
101
- /**
102
- * Determines whether the specified value is a string, null, or undefined.
103
- */
104
- export function isOptionalString(value: any): value is string | undefined {
105
- const type = typeof value
106
- return value === null || type === 'undefined' || type === 'string'
107
- }
108
-
109
- export async function setEnvValue(key: string, value: string) {
110
- const file = await storage.readTextFile(projectPath('.env'))
111
-
112
- await storage.writeTextFile({
113
- path: projectPath('.env'),
114
- data: file.data.replace(/APP_KEY=/g, `APP_KEY=${value}`), // todo: do not hardcode the APP_KEY here and instead use the key parameter
115
- })
116
- }
117
-
118
- /**
119
- * Runs the specified NPM script in the package.json file.
120
- */
121
- export async function runNpmScript(script: NpmScript, options?: CliOptions): Promise<Result<Subprocess, Error>> {
122
- const { data: manifest } = await storage.readJsonFile('package.json', frameworkPath())
123
-
124
- // simple, yet effective check to see if the script exists
125
- if (isManifest(manifest) && hasScript(manifest, script)) return await runCommand(`bun --bun run ${script}`, options)
126
-
127
- return err(handleError(`The ${script} script does not exist in the package.json file.`))
128
- }
129
-
130
- /**
131
- * Determines whether the specified NPM script exists in the given manifest.
132
- */
133
- export function hasScript(manifest: Manifest, script: NpmScript): boolean {
134
- const scripts = manifest.scripts as Record<NpmScript, string> | undefined
135
-
136
- if (scripts && typeof scripts === 'object') return Boolean(scripts[script])
137
-
138
- return false
139
- }
140
-
141
- export function parseYaml(content: any) {
142
- return parse(content)
143
- }
144
-
145
- /**
146
- * Determines the level of debugging.
147
- *
148
- * The debug level is determined by the following:
149
- * 1. The --verbose flag
150
- * 2. The debug property in the app configuration
151
- *
152
- * Currently, we don't support a custom debug level,
153
- * though, we would like to in the future.
154
- *
155
- * @param options
156
- */
157
- export function determineDebugLevel(options?: CliOptions) {
158
- if (options?.verbose === true) return true
159
-
160
- return app.debug === true
161
- }
162
-
163
- export function isIpv6(address: AddressInfo): boolean {
164
- return (
165
- address.family === 'IPv6' ||
166
- // in node >=18.0 <18.4 this was an integer value. This was changed in a minor version.
167
- // See: https://github.com/laravel/vite-plugin/issues/103
168
-
169
- // @ts-expect-error-next-line
170
- address.family === 6
171
- )
172
- }
173
-
174
- export { dump as dumpYaml, load as loadYaml } from 'js-yaml'
package/src/index.ts DELETED
@@ -1,21 +0,0 @@
1
- export * from './base'
2
- export * from './clean'
3
- export * from './config'
4
- export * from './debounce'
5
- export * from './equal'
6
- export * from './export-size'
7
- export * from './find'
8
- export * from './function'
9
- export * from './git'
10
- export * from './guards'
11
- export * from './hash'
12
- export * from './helpers'
13
- export * from './macroable'
14
- export * from './math'
15
- export * from './promise'
16
- export * from './regex'
17
- export * from './retry'
18
- export * from './sleep'
19
- export * from './throttle'
20
- export * from './vendors'
21
- export * from './versions'
package/src/macroable.ts DELETED
@@ -1 +0,0 @@
1
- export { Macroable } from 'macroable'
package/src/math.ts DELETED
@@ -1,30 +0,0 @@
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/promise.ts DELETED
@@ -1,116 +0,0 @@
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) _promise = fn()
32
- return _promise
33
- }
34
- wrapper.reset = async () => {
35
- const _prev = _promise
36
- _promise = undefined
37
- if (_prev) await _prev
38
- }
39
-
40
- return wrapper
41
- }
42
-
43
- /**
44
- * Create a promise lock.
45
- *
46
- * @category Promise
47
- * @example
48
- * ```
49
- * const lock = createPromiseLock()
50
- *
51
- * lock.run(async () => {
52
- * await doSomething()
53
- * })
54
- *
55
- * // in anther context:
56
- * await lock.wait() // it will wait all tasking finished
57
- * ```
58
- */
59
- export function createPromiseLock() {
60
- const locks: Promise<any>[] = []
61
-
62
- return {
63
- async run<T = void>(fn: () => Promise<T>): Promise<T> {
64
- const p = fn()
65
- locks.push(p)
66
- try {
67
- return await p
68
- } finally {
69
- remove(locks, p)
70
- }
71
- },
72
- async wait(): Promise<void> {
73
- await Promise.allSettled(locks)
74
- },
75
- isWaiting() {
76
- return Boolean(locks.length)
77
- },
78
- clear() {
79
- locks.length = 0
80
- },
81
- }
82
- }
83
-
84
- /**
85
- * Return a Promise with `resolve` and `reject` methods
86
- *
87
- * @category Promise
88
- * @example
89
- * ```
90
- * const promise = createControlledPromise()
91
- *
92
- * await promise
93
- *
94
- * // in anther context:
95
- * promise.resolve(data)
96
- * ```
97
- */
98
- export function createControlledPromise<T>(): ControlledPromise<T> {
99
- let resolve: any
100
- let reject: any
101
-
102
- const promise = new Promise<T>((_resolve, _reject) => {
103
- resolve = _resolve
104
- reject = _reject
105
- }) as ControlledPromise<T>
106
-
107
- promise.resolve = resolve
108
-
109
- promise.reject = reject
110
- return promise
111
- }
112
-
113
- /**
114
- * Create a promise that will be resolved after `ms` milliseconds.
115
- */
116
- // export { sleep, sleepSync } from 'bun'
package/src/regex.ts DELETED
@@ -1,35 +0,0 @@
1
- export type {
2
- Flag,
3
- MagicRegExp,
4
- MagicRegExpMatchArray,
5
- Input,
6
- MapToStringCapturedBy,
7
- StringCapturedBy,
8
- } from 'magic-regexp'
9
- export {
10
- createRegExp,
11
- caseInsensitive,
12
- anyOf,
13
- carriageReturn,
14
- char,
15
- charIn,
16
- charNotIn,
17
- digit,
18
- dotAll,
19
- exactly,
20
- global,
21
- letter,
22
- linefeed,
23
- maybe,
24
- multiline,
25
- not,
26
- oneOrMore,
27
- sticky,
28
- tab,
29
- unicode,
30
- whitespace,
31
- withIndices,
32
- word,
33
- wordBoundary,
34
- wordChar,
35
- } from 'magic-regexp'