appstash 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Interweb, Inc. <developers@interweb.co>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,245 @@
1
+ # appstash
2
+
3
+ Simple, clean application directory resolution for Node.js applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install appstash
9
+ # or
10
+ pnpm add appstash
11
+ ```
12
+
13
+ ## Features
14
+
15
+ - **Simple API**: Just one function to get all your app directories
16
+ - **Clean structure**: `~/.<tool>/{config,cache,data,logs}` + `/tmp/<tool>`
17
+ - **Graceful fallback**: XDG directories → tmp if home fails
18
+ - **No throws**: Always returns valid paths, never throws errors
19
+ - **TypeScript**: Full type definitions included
20
+ - **Zero dependencies**: Pure Node.js implementation
21
+
22
+ ## Usage
23
+
24
+ ### Basic Usage
25
+
26
+ ```typescript
27
+ import { appstash } from 'appstash';
28
+
29
+ // Get directories for your tool
30
+ const dirs = appstash('pgpm');
31
+
32
+ console.log(dirs.config); // ~/.pgpm/config
33
+ console.log(dirs.cache); // ~/.pgpm/cache
34
+ console.log(dirs.data); // ~/.pgpm/data
35
+ console.log(dirs.logs); // ~/.pgpm/logs
36
+ console.log(dirs.tmp); // /tmp/pgpm
37
+ ```
38
+
39
+ ### Create Directories
40
+
41
+ ```typescript
42
+ import { appstash } from 'appstash';
43
+
44
+ // Get directories and create them
45
+ const dirs = appstash('pgpm', { ensure: true });
46
+
47
+ // All directories now exist
48
+ // dirs.usedFallback will be true if XDG or tmp fallback was used
49
+ ```
50
+
51
+ ### Resolve Paths
52
+
53
+ ```typescript
54
+ import { appstash, resolve } from 'appstash';
55
+
56
+ const dirs = appstash('pgpm');
57
+
58
+ // Resolve paths within directories
59
+ const configFile = resolve(dirs, 'config', 'settings.json');
60
+ // Returns: ~/.pgpm/config/settings.json
61
+
62
+ const cacheDir = resolve(dirs, 'cache', 'repos', 'my-repo');
63
+ // Returns: ~/.pgpm/cache/repos/my-repo
64
+ ```
65
+
66
+ ### Manual Ensure
67
+
68
+ ```typescript
69
+ import { appstash, ensure } from 'appstash';
70
+
71
+ const dirs = appstash('pgpm');
72
+
73
+ // Create directories later
74
+ const result = ensure(dirs);
75
+
76
+ console.log(result.created); // ['~/.pgpm', '~/.pgpm/config', ...]
77
+ console.log(result.usedFallback); // false (or true if fallback was used)
78
+ ```
79
+
80
+ ## API
81
+
82
+ ### `appstash(tool, options?)`
83
+
84
+ Get application directories for a tool.
85
+
86
+ **Parameters:**
87
+ - `tool` (string): Tool name (e.g., 'pgpm', 'lql')
88
+ - `options` (object, optional):
89
+ - `baseDir` (string): Base directory (defaults to `os.homedir()`)
90
+ - `useXdgFallback` (boolean): Use XDG fallback if home fails (default: `true`)
91
+ - `ensure` (boolean): Automatically create directories (default: `false`)
92
+ - `tmpRoot` (string): Root for temp directory (defaults to `os.tmpdir()`)
93
+
94
+ **Returns:** `AppStashResult`
95
+ ```typescript
96
+ {
97
+ root: string; // ~/.<tool>
98
+ config: string; // ~/.<tool>/config
99
+ cache: string; // ~/.<tool>/cache
100
+ data: string; // ~/.<tool>/data
101
+ logs: string; // ~/.<tool>/logs
102
+ tmp: string; // /tmp/<tool>
103
+ usedFallback?: boolean; // true if XDG or tmp fallback was used
104
+ }
105
+ ```
106
+
107
+ ### `ensure(dirs)`
108
+
109
+ Create directories if they don't exist. Never throws.
110
+
111
+ **Parameters:**
112
+ - `dirs` (AppStashResult): Directory paths from `appstash()`
113
+
114
+ **Returns:** `EnsureResult`
115
+ ```typescript
116
+ {
117
+ created: string[]; // Directories that were created
118
+ usedFallback: boolean; // true if XDG or tmp fallback was used
119
+ }
120
+ ```
121
+
122
+ ### `resolve(dirs, kind, ...parts)`
123
+
124
+ Resolve a path within a specific directory.
125
+
126
+ **Parameters:**
127
+ - `dirs` (AppStashResult): Directory paths from `appstash()`
128
+ - `kind` ('config' | 'cache' | 'data' | 'logs' | 'tmp'): Directory kind
129
+ - `parts` (string[]): Path parts to join
130
+
131
+ **Returns:** `string` - Resolved path
132
+
133
+ ## Directory Structure
134
+
135
+ ### Primary (POSIX-style)
136
+
137
+ ```
138
+ ~/.<tool>/
139
+ ├── config/ # Configuration files
140
+ ├── cache/ # Cached data
141
+ ├── data/ # Application data
142
+ └── logs/ # Log files
143
+
144
+ /tmp/<tool>/ # Temporary files
145
+ ```
146
+
147
+ ### Fallback (XDG)
148
+
149
+ If home directory is unavailable or creation fails, falls back to XDG:
150
+
151
+ ```
152
+ ~/.config/<tool>/ # Config
153
+ ~/.cache/<tool>/ # Cache
154
+ ~/.local/share/<tool>/ # Data
155
+ ~/.local/state/<tool>/logs/ # Logs
156
+ ```
157
+
158
+ ### Final Fallback (tmp)
159
+
160
+ If XDG also fails, falls back to system temp:
161
+
162
+ ```
163
+ /tmp/<tool>/
164
+ ├── config/
165
+ ├── cache/
166
+ ├── data/
167
+ └── logs/
168
+ ```
169
+
170
+ ## Examples
171
+
172
+ ### Configuration File
173
+
174
+ ```typescript
175
+ import { appstash, resolve } from 'appstash';
176
+ import fs from 'fs';
177
+
178
+ const dirs = appstash('myapp', { ensure: true });
179
+ const configPath = resolve(dirs, 'config', 'settings.json');
180
+
181
+ // Write config
182
+ fs.writeFileSync(configPath, JSON.stringify({ theme: 'dark' }));
183
+
184
+ // Read config
185
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
186
+ ```
187
+
188
+ ### Cache Management
189
+
190
+ ```typescript
191
+ import { appstash, resolve } from 'appstash';
192
+ import fs from 'fs';
193
+
194
+ const dirs = appstash('myapp', { ensure: true });
195
+ const cacheFile = resolve(dirs, 'cache', 'data.json');
196
+
197
+ // Check if cached
198
+ if (fs.existsSync(cacheFile)) {
199
+ const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
200
+ console.log('Using cached data:', cached);
201
+ } else {
202
+ // Fetch and cache
203
+ const data = await fetchData();
204
+ fs.writeFileSync(cacheFile, JSON.stringify(data));
205
+ }
206
+ ```
207
+
208
+ ### Logging
209
+
210
+ ```typescript
211
+ import { appstash, resolve } from 'appstash';
212
+ import fs from 'fs';
213
+
214
+ const dirs = appstash('myapp', { ensure: true });
215
+ const logFile = resolve(dirs, 'logs', 'app.log');
216
+
217
+ function log(message: string) {
218
+ const timestamp = new Date().toISOString();
219
+ fs.appendFileSync(logFile, `[${timestamp}] ${message}\n`);
220
+ }
221
+
222
+ log('Application started');
223
+ ```
224
+
225
+ ### Custom Base Directory
226
+
227
+ ```typescript
228
+ import { appstash } from 'appstash';
229
+
230
+ // Use a custom base directory
231
+ const dirs = appstash('myapp', {
232
+ baseDir: '/opt/myapp',
233
+ ensure: true
234
+ });
235
+
236
+ console.log(dirs.config); // /opt/myapp/.myapp/config
237
+ ```
238
+
239
+ ## Design Philosophy
240
+
241
+ - **Simple**: One function, clear structure
242
+ - **Clean**: No pollution of exports, minimal API surface
243
+ - **Graceful**: Never throws, always returns valid paths
244
+ - **Fallback**: XDG only as absolute fallback, not primary
245
+ - **Focused**: Just directory resolution, no state management
package/esm/index.d.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Result from appstash() containing all resolved directory paths
3
+ */
4
+ export interface AppStashResult {
5
+ /** Root directory: ~/.<tool> */
6
+ root: string;
7
+ /** Config directory: ~/.<tool>/config */
8
+ config: string;
9
+ /** Cache directory: ~/.<tool>/cache */
10
+ cache: string;
11
+ /** Data directory: ~/.<tool>/data */
12
+ data: string;
13
+ /** Logs directory: ~/.<tool>/logs */
14
+ logs: string;
15
+ /** Temp directory: /tmp/<tool> */
16
+ tmp: string;
17
+ /** True if XDG or tmp fallback was used during ensure */
18
+ usedFallback?: boolean;
19
+ }
20
+ /**
21
+ * Options for appstash()
22
+ */
23
+ export interface AppStashOptions {
24
+ /** Base directory (defaults to os.homedir()) */
25
+ baseDir?: string;
26
+ /** Use XDG fallback if home fails (default: true) */
27
+ useXdgFallback?: boolean;
28
+ /** Automatically create directories (default: false) */
29
+ ensure?: boolean;
30
+ /** Root for temp directory (defaults to os.tmpdir()) */
31
+ tmpRoot?: string;
32
+ }
33
+ /**
34
+ * Result from ensure() containing created directories
35
+ */
36
+ export interface EnsureResult {
37
+ /** Directories that were created */
38
+ created: string[];
39
+ /** True if XDG or tmp fallback was used */
40
+ usedFallback: boolean;
41
+ }
42
+ /**
43
+ * Resolve application directories for a given tool name
44
+ *
45
+ * Primary: ~/.<tool>/{config,cache,data,logs}
46
+ * Fallback: XDG directories (only if home fails or ensure fails)
47
+ *
48
+ * @param tool - Tool name (e.g., 'pgpm', 'lql')
49
+ * @param options - Configuration options
50
+ * @returns Resolved directory paths
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * import { appstash } from 'appstash';
55
+ *
56
+ * // Get directories without creating them
57
+ * const dirs = appstash('pgpm');
58
+ * console.log(dirs.config); // ~/.pgpm/config
59
+ *
60
+ * // Get directories and create them
61
+ * const dirs = appstash('pgpm', { ensure: true });
62
+ * ```
63
+ */
64
+ export declare function appstash(tool: string, options?: AppStashOptions): AppStashResult;
65
+ /**
66
+ * Ensure directories exist, creating them if needed
67
+ * Never throws - returns fallback paths on failure
68
+ *
69
+ * @param dirs - Directory paths to create
70
+ * @returns Result with created directories and fallback flag
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * import { appstash, ensure } from 'appstash';
75
+ *
76
+ * const dirs = appstash('pgpm');
77
+ * const result = ensure(dirs);
78
+ * console.log(result.created); // ['~/.pgpm', '~/.pgpm/config', ...]
79
+ * ```
80
+ */
81
+ export declare function ensure(dirs: AppStashResult): EnsureResult;
82
+ /**
83
+ * Resolve a path within a specific directory kind
84
+ *
85
+ * @param dirs - Directory paths from appstash()
86
+ * @param kind - Directory kind (config, cache, data, logs, tmp)
87
+ * @param parts - Path parts to join
88
+ * @returns Resolved path
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * import { appstash, resolve } from 'appstash';
93
+ *
94
+ * const dirs = appstash('pgpm');
95
+ * const dbPath = resolve(dirs, 'data', 'repos', 'my-repo');
96
+ * // Returns: ~/.pgpm/data/repos/my-repo
97
+ * ```
98
+ */
99
+ export declare function resolve(dirs: AppStashResult, kind: 'config' | 'cache' | 'data' | 'logs' | 'tmp', ...parts: string[]): string;
package/esm/index.js ADDED
@@ -0,0 +1,203 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as os from 'os';
4
+ /**
5
+ * Get home directory with fallback
6
+ */
7
+ function getHomeDir() {
8
+ try {
9
+ const home = os.homedir();
10
+ if (home && home !== '/') {
11
+ return home;
12
+ }
13
+ }
14
+ catch {
15
+ }
16
+ return null;
17
+ }
18
+ /**
19
+ * Get XDG directories as fallback
20
+ */
21
+ function getXdgDirs() {
22
+ try {
23
+ const home = getHomeDir();
24
+ if (!home)
25
+ return null;
26
+ return {
27
+ config: process.env.XDG_CONFIG_HOME || path.join(home, '.config'),
28
+ cache: process.env.XDG_CACHE_HOME || path.join(home, '.cache'),
29
+ data: process.env.XDG_DATA_HOME || path.join(home, '.local', 'share'),
30
+ state: process.env.XDG_STATE_HOME || path.join(home, '.local', 'state')
31
+ };
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ /**
38
+ * Resolve application directories for a given tool name
39
+ *
40
+ * Primary: ~/.<tool>/{config,cache,data,logs}
41
+ * Fallback: XDG directories (only if home fails or ensure fails)
42
+ *
43
+ * @param tool - Tool name (e.g., 'pgpm', 'lql')
44
+ * @param options - Configuration options
45
+ * @returns Resolved directory paths
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * import { appstash } from 'appstash';
50
+ *
51
+ * // Get directories without creating them
52
+ * const dirs = appstash('pgpm');
53
+ * console.log(dirs.config); // ~/.pgpm/config
54
+ *
55
+ * // Get directories and create them
56
+ * const dirs = appstash('pgpm', { ensure: true });
57
+ * ```
58
+ */
59
+ export function appstash(tool, options = {}) {
60
+ const { baseDir, useXdgFallback = true, ensure = false, tmpRoot = os.tmpdir() } = options;
61
+ let base;
62
+ if (baseDir) {
63
+ base = baseDir;
64
+ }
65
+ else {
66
+ const home = getHomeDir();
67
+ if (!home) {
68
+ if (useXdgFallback) {
69
+ const xdg = getXdgDirs();
70
+ if (xdg) {
71
+ const result = {
72
+ root: path.join(xdg.config, tool),
73
+ config: path.join(xdg.config, tool),
74
+ cache: path.join(xdg.cache, tool),
75
+ data: path.join(xdg.data, tool),
76
+ logs: path.join(xdg.state, tool, 'logs'),
77
+ tmp: path.join(tmpRoot, tool),
78
+ usedFallback: true
79
+ };
80
+ if (ensure) {
81
+ const ensureResult = ensureDirectories(result);
82
+ result.usedFallback = ensureResult.usedFallback;
83
+ }
84
+ return result;
85
+ }
86
+ }
87
+ const tmpBase = path.join(tmpRoot, tool);
88
+ return {
89
+ root: tmpBase,
90
+ config: path.join(tmpBase, 'config'),
91
+ cache: path.join(tmpBase, 'cache'),
92
+ data: path.join(tmpBase, 'data'),
93
+ logs: path.join(tmpBase, 'logs'),
94
+ tmp: tmpBase,
95
+ usedFallback: true
96
+ };
97
+ }
98
+ base = home;
99
+ }
100
+ const root = path.join(base, `.${tool}`);
101
+ const result = {
102
+ root,
103
+ config: path.join(root, 'config'),
104
+ cache: path.join(root, 'cache'),
105
+ data: path.join(root, 'data'),
106
+ logs: path.join(root, 'logs'),
107
+ tmp: path.join(tmpRoot, tool)
108
+ };
109
+ if (ensure) {
110
+ const ensureResult = ensureDirectories(result, useXdgFallback, tmpRoot, tool);
111
+ result.usedFallback = ensureResult.usedFallback;
112
+ }
113
+ return result;
114
+ }
115
+ /**
116
+ * Ensure directories exist, creating them if needed
117
+ * Never throws - returns fallback paths on failure
118
+ *
119
+ * @param dirs - Directory paths to create
120
+ * @returns Result with created directories and fallback flag
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * import { appstash, ensure } from 'appstash';
125
+ *
126
+ * const dirs = appstash('pgpm');
127
+ * const result = ensure(dirs);
128
+ * console.log(result.created); // ['~/.pgpm', '~/.pgpm/config', ...]
129
+ * ```
130
+ */
131
+ export function ensure(dirs) {
132
+ return ensureDirectories(dirs);
133
+ }
134
+ /**
135
+ * Internal function to ensure directories exist
136
+ */
137
+ function ensureDirectories(dirs, useXdgFallback = true, tmpRoot = os.tmpdir(), tool) {
138
+ const created = [];
139
+ let usedFallback = false;
140
+ const persistentDirs = [dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs];
141
+ for (const dir of persistentDirs) {
142
+ try {
143
+ if (!fs.existsSync(dir)) {
144
+ fs.mkdirSync(dir, { recursive: true });
145
+ created.push(dir);
146
+ }
147
+ }
148
+ catch {
149
+ usedFallback = true;
150
+ break;
151
+ }
152
+ }
153
+ if (usedFallback && useXdgFallback && tool) {
154
+ const xdg = getXdgDirs();
155
+ if (xdg) {
156
+ dirs.root = path.join(xdg.config, tool);
157
+ dirs.config = path.join(xdg.config, tool);
158
+ dirs.cache = path.join(xdg.cache, tool);
159
+ dirs.data = path.join(xdg.data, tool);
160
+ dirs.logs = path.join(xdg.state, tool, 'logs');
161
+ const xdgDirs = [dirs.config, dirs.cache, dirs.data, dirs.logs];
162
+ for (const dir of xdgDirs) {
163
+ try {
164
+ if (!fs.existsSync(dir)) {
165
+ fs.mkdirSync(dir, { recursive: true });
166
+ created.push(dir);
167
+ }
168
+ }
169
+ catch {
170
+ usedFallback = true;
171
+ const tmpBase = path.join(tmpRoot, tool);
172
+ dirs.root = tmpBase;
173
+ dirs.config = path.join(tmpBase, 'config');
174
+ dirs.cache = path.join(tmpBase, 'cache');
175
+ dirs.data = path.join(tmpBase, 'data');
176
+ dirs.logs = path.join(tmpBase, 'logs');
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ }
182
+ return { created, usedFallback };
183
+ }
184
+ /**
185
+ * Resolve a path within a specific directory kind
186
+ *
187
+ * @param dirs - Directory paths from appstash()
188
+ * @param kind - Directory kind (config, cache, data, logs, tmp)
189
+ * @param parts - Path parts to join
190
+ * @returns Resolved path
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * import { appstash, resolve } from 'appstash';
195
+ *
196
+ * const dirs = appstash('pgpm');
197
+ * const dbPath = resolve(dirs, 'data', 'repos', 'my-repo');
198
+ * // Returns: ~/.pgpm/data/repos/my-repo
199
+ * ```
200
+ */
201
+ export function resolve(dirs, kind, ...parts) {
202
+ return path.join(dirs[kind], ...parts);
203
+ }
package/index.d.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Result from appstash() containing all resolved directory paths
3
+ */
4
+ export interface AppStashResult {
5
+ /** Root directory: ~/.<tool> */
6
+ root: string;
7
+ /** Config directory: ~/.<tool>/config */
8
+ config: string;
9
+ /** Cache directory: ~/.<tool>/cache */
10
+ cache: string;
11
+ /** Data directory: ~/.<tool>/data */
12
+ data: string;
13
+ /** Logs directory: ~/.<tool>/logs */
14
+ logs: string;
15
+ /** Temp directory: /tmp/<tool> */
16
+ tmp: string;
17
+ /** True if XDG or tmp fallback was used during ensure */
18
+ usedFallback?: boolean;
19
+ }
20
+ /**
21
+ * Options for appstash()
22
+ */
23
+ export interface AppStashOptions {
24
+ /** Base directory (defaults to os.homedir()) */
25
+ baseDir?: string;
26
+ /** Use XDG fallback if home fails (default: true) */
27
+ useXdgFallback?: boolean;
28
+ /** Automatically create directories (default: false) */
29
+ ensure?: boolean;
30
+ /** Root for temp directory (defaults to os.tmpdir()) */
31
+ tmpRoot?: string;
32
+ }
33
+ /**
34
+ * Result from ensure() containing created directories
35
+ */
36
+ export interface EnsureResult {
37
+ /** Directories that were created */
38
+ created: string[];
39
+ /** True if XDG or tmp fallback was used */
40
+ usedFallback: boolean;
41
+ }
42
+ /**
43
+ * Resolve application directories for a given tool name
44
+ *
45
+ * Primary: ~/.<tool>/{config,cache,data,logs}
46
+ * Fallback: XDG directories (only if home fails or ensure fails)
47
+ *
48
+ * @param tool - Tool name (e.g., 'pgpm', 'lql')
49
+ * @param options - Configuration options
50
+ * @returns Resolved directory paths
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * import { appstash } from 'appstash';
55
+ *
56
+ * // Get directories without creating them
57
+ * const dirs = appstash('pgpm');
58
+ * console.log(dirs.config); // ~/.pgpm/config
59
+ *
60
+ * // Get directories and create them
61
+ * const dirs = appstash('pgpm', { ensure: true });
62
+ * ```
63
+ */
64
+ export declare function appstash(tool: string, options?: AppStashOptions): AppStashResult;
65
+ /**
66
+ * Ensure directories exist, creating them if needed
67
+ * Never throws - returns fallback paths on failure
68
+ *
69
+ * @param dirs - Directory paths to create
70
+ * @returns Result with created directories and fallback flag
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * import { appstash, ensure } from 'appstash';
75
+ *
76
+ * const dirs = appstash('pgpm');
77
+ * const result = ensure(dirs);
78
+ * console.log(result.created); // ['~/.pgpm', '~/.pgpm/config', ...]
79
+ * ```
80
+ */
81
+ export declare function ensure(dirs: AppStashResult): EnsureResult;
82
+ /**
83
+ * Resolve a path within a specific directory kind
84
+ *
85
+ * @param dirs - Directory paths from appstash()
86
+ * @param kind - Directory kind (config, cache, data, logs, tmp)
87
+ * @param parts - Path parts to join
88
+ * @returns Resolved path
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * import { appstash, resolve } from 'appstash';
93
+ *
94
+ * const dirs = appstash('pgpm');
95
+ * const dbPath = resolve(dirs, 'data', 'repos', 'my-repo');
96
+ * // Returns: ~/.pgpm/data/repos/my-repo
97
+ * ```
98
+ */
99
+ export declare function resolve(dirs: AppStashResult, kind: 'config' | 'cache' | 'data' | 'logs' | 'tmp', ...parts: string[]): string;
package/index.js ADDED
@@ -0,0 +1,241 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.appstash = appstash;
37
+ exports.ensure = ensure;
38
+ exports.resolve = resolve;
39
+ const fs = __importStar(require("fs"));
40
+ const path = __importStar(require("path"));
41
+ const os = __importStar(require("os"));
42
+ /**
43
+ * Get home directory with fallback
44
+ */
45
+ function getHomeDir() {
46
+ try {
47
+ const home = os.homedir();
48
+ if (home && home !== '/') {
49
+ return home;
50
+ }
51
+ }
52
+ catch {
53
+ }
54
+ return null;
55
+ }
56
+ /**
57
+ * Get XDG directories as fallback
58
+ */
59
+ function getXdgDirs() {
60
+ try {
61
+ const home = getHomeDir();
62
+ if (!home)
63
+ return null;
64
+ return {
65
+ config: process.env.XDG_CONFIG_HOME || path.join(home, '.config'),
66
+ cache: process.env.XDG_CACHE_HOME || path.join(home, '.cache'),
67
+ data: process.env.XDG_DATA_HOME || path.join(home, '.local', 'share'),
68
+ state: process.env.XDG_STATE_HOME || path.join(home, '.local', 'state')
69
+ };
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ /**
76
+ * Resolve application directories for a given tool name
77
+ *
78
+ * Primary: ~/.<tool>/{config,cache,data,logs}
79
+ * Fallback: XDG directories (only if home fails or ensure fails)
80
+ *
81
+ * @param tool - Tool name (e.g., 'pgpm', 'lql')
82
+ * @param options - Configuration options
83
+ * @returns Resolved directory paths
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * import { appstash } from 'appstash';
88
+ *
89
+ * // Get directories without creating them
90
+ * const dirs = appstash('pgpm');
91
+ * console.log(dirs.config); // ~/.pgpm/config
92
+ *
93
+ * // Get directories and create them
94
+ * const dirs = appstash('pgpm', { ensure: true });
95
+ * ```
96
+ */
97
+ function appstash(tool, options = {}) {
98
+ const { baseDir, useXdgFallback = true, ensure = false, tmpRoot = os.tmpdir() } = options;
99
+ let base;
100
+ if (baseDir) {
101
+ base = baseDir;
102
+ }
103
+ else {
104
+ const home = getHomeDir();
105
+ if (!home) {
106
+ if (useXdgFallback) {
107
+ const xdg = getXdgDirs();
108
+ if (xdg) {
109
+ const result = {
110
+ root: path.join(xdg.config, tool),
111
+ config: path.join(xdg.config, tool),
112
+ cache: path.join(xdg.cache, tool),
113
+ data: path.join(xdg.data, tool),
114
+ logs: path.join(xdg.state, tool, 'logs'),
115
+ tmp: path.join(tmpRoot, tool),
116
+ usedFallback: true
117
+ };
118
+ if (ensure) {
119
+ const ensureResult = ensureDirectories(result);
120
+ result.usedFallback = ensureResult.usedFallback;
121
+ }
122
+ return result;
123
+ }
124
+ }
125
+ const tmpBase = path.join(tmpRoot, tool);
126
+ return {
127
+ root: tmpBase,
128
+ config: path.join(tmpBase, 'config'),
129
+ cache: path.join(tmpBase, 'cache'),
130
+ data: path.join(tmpBase, 'data'),
131
+ logs: path.join(tmpBase, 'logs'),
132
+ tmp: tmpBase,
133
+ usedFallback: true
134
+ };
135
+ }
136
+ base = home;
137
+ }
138
+ const root = path.join(base, `.${tool}`);
139
+ const result = {
140
+ root,
141
+ config: path.join(root, 'config'),
142
+ cache: path.join(root, 'cache'),
143
+ data: path.join(root, 'data'),
144
+ logs: path.join(root, 'logs'),
145
+ tmp: path.join(tmpRoot, tool)
146
+ };
147
+ if (ensure) {
148
+ const ensureResult = ensureDirectories(result, useXdgFallback, tmpRoot, tool);
149
+ result.usedFallback = ensureResult.usedFallback;
150
+ }
151
+ return result;
152
+ }
153
+ /**
154
+ * Ensure directories exist, creating them if needed
155
+ * Never throws - returns fallback paths on failure
156
+ *
157
+ * @param dirs - Directory paths to create
158
+ * @returns Result with created directories and fallback flag
159
+ *
160
+ * @example
161
+ * ```typescript
162
+ * import { appstash, ensure } from 'appstash';
163
+ *
164
+ * const dirs = appstash('pgpm');
165
+ * const result = ensure(dirs);
166
+ * console.log(result.created); // ['~/.pgpm', '~/.pgpm/config', ...]
167
+ * ```
168
+ */
169
+ function ensure(dirs) {
170
+ return ensureDirectories(dirs);
171
+ }
172
+ /**
173
+ * Internal function to ensure directories exist
174
+ */
175
+ function ensureDirectories(dirs, useXdgFallback = true, tmpRoot = os.tmpdir(), tool) {
176
+ const created = [];
177
+ let usedFallback = false;
178
+ const persistentDirs = [dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs];
179
+ for (const dir of persistentDirs) {
180
+ try {
181
+ if (!fs.existsSync(dir)) {
182
+ fs.mkdirSync(dir, { recursive: true });
183
+ created.push(dir);
184
+ }
185
+ }
186
+ catch {
187
+ usedFallback = true;
188
+ break;
189
+ }
190
+ }
191
+ if (usedFallback && useXdgFallback && tool) {
192
+ const xdg = getXdgDirs();
193
+ if (xdg) {
194
+ dirs.root = path.join(xdg.config, tool);
195
+ dirs.config = path.join(xdg.config, tool);
196
+ dirs.cache = path.join(xdg.cache, tool);
197
+ dirs.data = path.join(xdg.data, tool);
198
+ dirs.logs = path.join(xdg.state, tool, 'logs');
199
+ const xdgDirs = [dirs.config, dirs.cache, dirs.data, dirs.logs];
200
+ for (const dir of xdgDirs) {
201
+ try {
202
+ if (!fs.existsSync(dir)) {
203
+ fs.mkdirSync(dir, { recursive: true });
204
+ created.push(dir);
205
+ }
206
+ }
207
+ catch {
208
+ usedFallback = true;
209
+ const tmpBase = path.join(tmpRoot, tool);
210
+ dirs.root = tmpBase;
211
+ dirs.config = path.join(tmpBase, 'config');
212
+ dirs.cache = path.join(tmpBase, 'cache');
213
+ dirs.data = path.join(tmpBase, 'data');
214
+ dirs.logs = path.join(tmpBase, 'logs');
215
+ break;
216
+ }
217
+ }
218
+ }
219
+ }
220
+ return { created, usedFallback };
221
+ }
222
+ /**
223
+ * Resolve a path within a specific directory kind
224
+ *
225
+ * @param dirs - Directory paths from appstash()
226
+ * @param kind - Directory kind (config, cache, data, logs, tmp)
227
+ * @param parts - Path parts to join
228
+ * @returns Resolved path
229
+ *
230
+ * @example
231
+ * ```typescript
232
+ * import { appstash, resolve } from 'appstash';
233
+ *
234
+ * const dirs = appstash('pgpm');
235
+ * const dbPath = resolve(dirs, 'data', 'repos', 'my-repo');
236
+ * // Returns: ~/.pgpm/data/repos/my-repo
237
+ * ```
238
+ */
239
+ function resolve(dirs, kind, ...parts) {
240
+ return path.join(dirs[kind], ...parts);
241
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "appstash",
3
+ "version": "0.2.0",
4
+ "author": "Dan Lynch <pyramation@gmail.com>",
5
+ "description": "Simple, clean application directory resolution",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/hyperweb-io/dev-utils",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/hyperweb-io/dev-utils"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/hyperweb-io/dev-utils/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "cpy ../../LICENSE README.md package.json dist --flat",
24
+ "clean": "rimraf dist/**",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "npm run clean; tsc; tsc -p tsconfig.esm.json; npm run copy",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "keywords": [
32
+ "directories",
33
+ "config",
34
+ "cache",
35
+ "data",
36
+ "logs",
37
+ "xdg",
38
+ "appdirs"
39
+ ],
40
+ "gitHead": "31b9119fbfdfd71873d2e1be7f9a9313dd077554"
41
+ }