@ecmaos/coreutils 0.3.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +48 -0
  3. package/dist/commands/awk.d.ts +4 -0
  4. package/dist/commands/awk.d.ts.map +1 -0
  5. package/dist/commands/awk.js +324 -0
  6. package/dist/commands/awk.js.map +1 -0
  7. package/dist/commands/chgrp.d.ts +4 -0
  8. package/dist/commands/chgrp.d.ts.map +1 -0
  9. package/dist/commands/chgrp.js +187 -0
  10. package/dist/commands/chgrp.js.map +1 -0
  11. package/dist/commands/chmod.d.ts.map +1 -1
  12. package/dist/commands/chmod.js +139 -2
  13. package/dist/commands/chmod.js.map +1 -1
  14. package/dist/commands/chown.d.ts +4 -0
  15. package/dist/commands/chown.d.ts.map +1 -0
  16. package/dist/commands/chown.js +257 -0
  17. package/dist/commands/chown.js.map +1 -0
  18. package/dist/commands/cksum.d.ts +4 -0
  19. package/dist/commands/cksum.d.ts.map +1 -0
  20. package/dist/commands/cksum.js +124 -0
  21. package/dist/commands/cksum.js.map +1 -0
  22. package/dist/commands/cmp.d.ts +4 -0
  23. package/dist/commands/cmp.d.ts.map +1 -0
  24. package/dist/commands/cmp.js +120 -0
  25. package/dist/commands/cmp.js.map +1 -0
  26. package/dist/commands/column.d.ts +4 -0
  27. package/dist/commands/column.d.ts.map +1 -0
  28. package/dist/commands/column.js +274 -0
  29. package/dist/commands/column.js.map +1 -0
  30. package/dist/commands/cp.d.ts.map +1 -1
  31. package/dist/commands/cp.js +81 -4
  32. package/dist/commands/cp.js.map +1 -1
  33. package/dist/commands/cron.d.ts.map +1 -1
  34. package/dist/commands/cron.js +116 -23
  35. package/dist/commands/cron.js.map +1 -1
  36. package/dist/commands/curl.d.ts +4 -0
  37. package/dist/commands/curl.d.ts.map +1 -0
  38. package/dist/commands/curl.js +238 -0
  39. package/dist/commands/curl.js.map +1 -0
  40. package/dist/commands/du.d.ts +4 -0
  41. package/dist/commands/du.d.ts.map +1 -0
  42. package/dist/commands/du.js +168 -0
  43. package/dist/commands/du.js.map +1 -0
  44. package/dist/commands/echo.d.ts.map +1 -1
  45. package/dist/commands/echo.js +125 -2
  46. package/dist/commands/echo.js.map +1 -1
  47. package/dist/commands/env.d.ts +4 -0
  48. package/dist/commands/env.d.ts.map +1 -0
  49. package/dist/commands/env.js +129 -0
  50. package/dist/commands/env.js.map +1 -0
  51. package/dist/commands/expand.d.ts +4 -0
  52. package/dist/commands/expand.d.ts.map +1 -0
  53. package/dist/commands/expand.js +197 -0
  54. package/dist/commands/expand.js.map +1 -0
  55. package/dist/commands/factor.d.ts +4 -0
  56. package/dist/commands/factor.d.ts.map +1 -0
  57. package/dist/commands/factor.js +141 -0
  58. package/dist/commands/factor.js.map +1 -0
  59. package/dist/commands/fmt.d.ts +4 -0
  60. package/dist/commands/fmt.d.ts.map +1 -0
  61. package/dist/commands/fmt.js +278 -0
  62. package/dist/commands/fmt.js.map +1 -0
  63. package/dist/commands/fold.d.ts +4 -0
  64. package/dist/commands/fold.d.ts.map +1 -0
  65. package/dist/commands/fold.js +253 -0
  66. package/dist/commands/fold.js.map +1 -0
  67. package/dist/commands/groups.d.ts +4 -0
  68. package/dist/commands/groups.d.ts.map +1 -0
  69. package/dist/commands/groups.js +61 -0
  70. package/dist/commands/groups.js.map +1 -0
  71. package/dist/commands/head.d.ts.map +1 -1
  72. package/dist/commands/head.js +184 -77
  73. package/dist/commands/head.js.map +1 -1
  74. package/dist/commands/hostname.d.ts +4 -0
  75. package/dist/commands/hostname.d.ts.map +1 -0
  76. package/dist/commands/hostname.js +80 -0
  77. package/dist/commands/hostname.js.map +1 -0
  78. package/dist/commands/less.d.ts.map +1 -1
  79. package/dist/commands/less.js +1 -0
  80. package/dist/commands/less.js.map +1 -1
  81. package/dist/commands/man.d.ts.map +1 -1
  82. package/dist/commands/man.js +3 -1
  83. package/dist/commands/man.js.map +1 -1
  84. package/dist/commands/mount.d.ts +4 -0
  85. package/dist/commands/mount.d.ts.map +1 -0
  86. package/dist/commands/mount.js +1136 -0
  87. package/dist/commands/mount.js.map +1 -0
  88. package/dist/commands/od.d.ts +4 -0
  89. package/dist/commands/od.d.ts.map +1 -0
  90. package/dist/commands/od.js +342 -0
  91. package/dist/commands/od.js.map +1 -0
  92. package/dist/commands/pr.d.ts +4 -0
  93. package/dist/commands/pr.d.ts.map +1 -0
  94. package/dist/commands/pr.js +298 -0
  95. package/dist/commands/pr.js.map +1 -0
  96. package/dist/commands/printf.d.ts +4 -0
  97. package/dist/commands/printf.d.ts.map +1 -0
  98. package/dist/commands/printf.js +271 -0
  99. package/dist/commands/printf.js.map +1 -0
  100. package/dist/commands/readlink.d.ts +4 -0
  101. package/dist/commands/readlink.d.ts.map +1 -0
  102. package/dist/commands/readlink.js +104 -0
  103. package/dist/commands/readlink.js.map +1 -0
  104. package/dist/commands/realpath.d.ts +4 -0
  105. package/dist/commands/realpath.d.ts.map +1 -0
  106. package/dist/commands/realpath.js +111 -0
  107. package/dist/commands/realpath.js.map +1 -0
  108. package/dist/commands/rev.d.ts +4 -0
  109. package/dist/commands/rev.d.ts.map +1 -0
  110. package/dist/commands/rev.js +134 -0
  111. package/dist/commands/rev.js.map +1 -0
  112. package/dist/commands/shuf.d.ts +4 -0
  113. package/dist/commands/shuf.d.ts.map +1 -0
  114. package/dist/commands/shuf.js +221 -0
  115. package/dist/commands/shuf.js.map +1 -0
  116. package/dist/commands/sleep.d.ts +4 -0
  117. package/dist/commands/sleep.d.ts.map +1 -0
  118. package/dist/commands/sleep.js +102 -0
  119. package/dist/commands/sleep.js.map +1 -0
  120. package/dist/commands/strings.d.ts +4 -0
  121. package/dist/commands/strings.d.ts.map +1 -0
  122. package/dist/commands/strings.js +170 -0
  123. package/dist/commands/strings.js.map +1 -0
  124. package/dist/commands/tac.d.ts +4 -0
  125. package/dist/commands/tac.d.ts.map +1 -0
  126. package/dist/commands/tac.js +130 -0
  127. package/dist/commands/tac.js.map +1 -0
  128. package/dist/commands/time.d.ts +4 -0
  129. package/dist/commands/time.d.ts.map +1 -0
  130. package/dist/commands/time.js +126 -0
  131. package/dist/commands/time.js.map +1 -0
  132. package/dist/commands/umount.d.ts +4 -0
  133. package/dist/commands/umount.d.ts.map +1 -0
  134. package/dist/commands/umount.js +103 -0
  135. package/dist/commands/umount.js.map +1 -0
  136. package/dist/commands/uname.d.ts +4 -0
  137. package/dist/commands/uname.d.ts.map +1 -0
  138. package/dist/commands/uname.js +149 -0
  139. package/dist/commands/uname.js.map +1 -0
  140. package/dist/commands/unexpand.d.ts +4 -0
  141. package/dist/commands/unexpand.d.ts.map +1 -0
  142. package/dist/commands/unexpand.js +286 -0
  143. package/dist/commands/unexpand.js.map +1 -0
  144. package/dist/commands/uptime.d.ts +4 -0
  145. package/dist/commands/uptime.d.ts.map +1 -0
  146. package/dist/commands/uptime.js +62 -0
  147. package/dist/commands/uptime.js.map +1 -0
  148. package/dist/commands/view.d.ts +1 -0
  149. package/dist/commands/view.d.ts.map +1 -1
  150. package/dist/commands/view.js +408 -66
  151. package/dist/commands/view.js.map +1 -1
  152. package/dist/commands/yes.d.ts +4 -0
  153. package/dist/commands/yes.d.ts.map +1 -0
  154. package/dist/commands/yes.js +58 -0
  155. package/dist/commands/yes.js.map +1 -0
  156. package/dist/index.d.ts +24 -0
  157. package/dist/index.d.ts.map +1 -1
  158. package/dist/index.js +82 -0
  159. package/dist/index.js.map +1 -1
  160. package/package.json +12 -3
  161. package/src/commands/awk.ts +340 -0
  162. package/src/commands/chmod.ts +141 -2
  163. package/src/commands/chown.ts +321 -0
  164. package/src/commands/cksum.ts +133 -0
  165. package/src/commands/cmp.ts +126 -0
  166. package/src/commands/column.ts +273 -0
  167. package/src/commands/cp.ts +93 -4
  168. package/src/commands/cron.ts +115 -23
  169. package/src/commands/curl.ts +231 -0
  170. package/src/commands/echo.ts +122 -2
  171. package/src/commands/env.ts +143 -0
  172. package/src/commands/expand.ts +207 -0
  173. package/src/commands/factor.ts +151 -0
  174. package/src/commands/fmt.ts +293 -0
  175. package/src/commands/fold.ts +257 -0
  176. package/src/commands/groups.ts +72 -0
  177. package/src/commands/head.ts +176 -77
  178. package/src/commands/hostname.ts +81 -0
  179. package/src/commands/less.ts +1 -0
  180. package/src/commands/man.ts +4 -1
  181. package/src/commands/mount.ts +1302 -0
  182. package/src/commands/od.ts +327 -0
  183. package/src/commands/pr.ts +291 -0
  184. package/src/commands/printf.ts +271 -0
  185. package/src/commands/readlink.ts +102 -0
  186. package/src/commands/realpath.ts +126 -0
  187. package/src/commands/rev.ts +143 -0
  188. package/src/commands/shuf.ts +218 -0
  189. package/src/commands/sleep.ts +109 -0
  190. package/src/commands/strings.ts +176 -0
  191. package/src/commands/tac.ts +138 -0
  192. package/src/commands/time.ts +144 -0
  193. package/src/commands/umount.ts +116 -0
  194. package/src/commands/uname.ts +130 -0
  195. package/src/commands/unexpand.ts +305 -0
  196. package/src/commands/uptime.ts +73 -0
  197. package/src/commands/view.ts +463 -73
  198. package/src/index.ts +82 -0
  199. package/tsconfig.json +4 -0
@@ -0,0 +1,1136 @@
1
+ // TODO: Dropbox and S3 are WIP
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import { Fetch, InMemory, resolveMountConfig, SingleBuffer } from '@zenfs/core';
5
+ import { IndexedDB, WebStorage, WebAccess, /* XML */ } from '@zenfs/dom';
6
+ import { Iso, Zip } from '@zenfs/archives';
7
+ import { Dropbox, /* S3Bucket, */ GoogleDrive } from '@zenfs/cloud';
8
+ import { TerminalCommand } from '../shared/terminal-command.js';
9
+ import { writelnStdout, writelnStderr } from '../shared/helpers.js';
10
+ /**
11
+ * Parse a single fstab line
12
+ * @param line - The line to parse
13
+ * @returns Parsed entry or null if line is empty/comment
14
+ */
15
+ function parseFstabLine(line) {
16
+ const trimmed = line.trim();
17
+ // Skip empty lines and comments
18
+ if (trimmed === '' || trimmed.startsWith('#')) {
19
+ return null;
20
+ }
21
+ // Split by whitespace (space or tab)
22
+ // Format: source target type [options]
23
+ const parts = trimmed.split(/\s+/);
24
+ if (parts.length < 3) {
25
+ // Need at least source, target, and type
26
+ return null;
27
+ }
28
+ const source = parts[0] || '';
29
+ const target = parts[1] || '';
30
+ const type = parts[2] || '';
31
+ const options = parts.slice(3).join(' ') || undefined;
32
+ // Validate required fields
33
+ if (!target || !type) {
34
+ return null;
35
+ }
36
+ return {
37
+ source: source || '',
38
+ target,
39
+ type,
40
+ options
41
+ };
42
+ }
43
+ /**
44
+ * Parse a complete fstab file
45
+ * @param content - The fstab file content
46
+ * @returns Array of parsed fstab entries
47
+ */
48
+ function parseFstabFile(content) {
49
+ const lines = content.split('\n');
50
+ const entries = [];
51
+ for (const line of lines) {
52
+ if (!line)
53
+ continue;
54
+ const parsed = parseFstabLine(line);
55
+ if (parsed) {
56
+ entries.push(parsed);
57
+ }
58
+ }
59
+ return entries;
60
+ }
61
+ function printUsage(process, terminal) {
62
+ const usage = `Usage: mount [OPTIONS] [SOURCE] TARGET
63
+ mount [-a|--all]
64
+ mount [-l|--list]
65
+
66
+ Mount a filesystem.
67
+
68
+ Options:
69
+ -t, --type TYPE filesystem type (fetch, indexeddb, webstorage, webaccess, memory, singlebuffer, zip, iso, googledrive)
70
+ -o, --options OPTS mount options (comma-separated key=value pairs)
71
+ -a, --all mount all filesystems listed in /etc/fstab
72
+ -l, --list list all mounted filesystems
73
+ --help display this help and exit
74
+
75
+ Filesystem types:
76
+ fetch mount a remote filesystem via HTTP fetch
77
+ indexeddb mount an IndexedDB-backed filesystem
78
+ webstorage mount a WebStorage-backed filesystem (localStorage or sessionStorage)
79
+ webaccess mount a filesystem using the File System Access API
80
+ memory mount an in-memory filesystem
81
+ singlebuffer mount a filesystem backed by a single buffer
82
+ zip mount a readonly filesystem from a zip archive (requires SOURCE file or URL)
83
+ iso mount a readonly filesystem from an ISO image (requires SOURCE file or URL)
84
+ googledrive mount a Google Drive filesystem (requires apiKey via -o apiKey, optionally clientId for OAuth)
85
+
86
+ Mount options:
87
+ baseUrl=URL base URL for fetch operations (fetch type)
88
+ size=BYTES buffer size in bytes for singlebuffer type (default: 1048576)
89
+ storage=TYPE storage type for webstorage (localStorage or sessionStorage, default: localStorage)
90
+ apiKey=KEY Google API key (googledrive type, required)
91
+ clientId=ID Google OAuth client ID (googledrive type, optional)
92
+ scope=SCOPE OAuth scope (googledrive type, default: https://www.googleapis.com/auth/drive)
93
+ cacheTTL=SECONDS cache TTL in seconds for cloud backends (optional)
94
+
95
+ Examples:
96
+ mount -l list all mounted filesystems
97
+ mount -t memory /mnt/tmp mount memory filesystem at /mnt/tmp
98
+ mount -t indexeddb mydb /mnt/db mount IndexedDB store 'mydb' at /mnt/db
99
+ mount -t webstorage /mnt/storage mount WebStorage filesystem using localStorage
100
+ mount -t webstorage /mnt/storage -o storage=sessionStorage
101
+ mount -t webaccess /mnt/access mount File System Access API filesystem
102
+ mount -t fetch /api /mnt/api mount fetch filesystem at /mnt/api
103
+ mount -t fetch /api /mnt/api -o baseUrl=https://example.com
104
+ mount -t singlebuffer /mnt/buf mount singlebuffer filesystem at /mnt/buf
105
+ mount -t singlebuffer /mnt/buf -o size=2097152
106
+ mount -t zip https://example.com/archive.zip /mnt/zip
107
+ mount -t zip /tmp/archive.zip /mnt/zip
108
+ mount -t iso https://example.com/image.iso /mnt/iso
109
+ mount -t iso /tmp/image.iso /mnt/iso
110
+ mount -t googledrive /mnt/gdrive -o apiKey=YOUR_API_KEY # readonly/public
111
+ mount -t googledrive /mnt/gdrive -o clientId=YOUR_CLIENT_ID # rw/private`;
112
+ writelnStderr(process, terminal, usage);
113
+ }
114
+ export function createCommand(kernel, shell, terminal) {
115
+ return new TerminalCommand({
116
+ command: 'mount',
117
+ description: 'Mount a filesystem',
118
+ kernel,
119
+ shell,
120
+ terminal,
121
+ run: async (pid, argv) => {
122
+ const process = kernel.processes.get(pid);
123
+ if (argv.length > 0 && (argv[0] === '--help' || argv[0] === '-h')) {
124
+ printUsage(process, terminal);
125
+ return 0;
126
+ }
127
+ let listMode = false;
128
+ let allMode = false;
129
+ let type;
130
+ let options;
131
+ const positionalArgs = [];
132
+ for (let i = 0; i < argv.length; i++) {
133
+ const arg = argv[i];
134
+ if (arg === '-l' || arg === '--list') {
135
+ listMode = true;
136
+ }
137
+ else if (arg === '-a' || arg === '--all') {
138
+ allMode = true;
139
+ }
140
+ else if (arg === '-t' || arg === '--type') {
141
+ if (i + 1 < argv.length) {
142
+ type = argv[i + 1];
143
+ i++;
144
+ }
145
+ else {
146
+ await writelnStderr(process, terminal, chalk.red('mount: option requires an argument -- \'t\''));
147
+ return 1;
148
+ }
149
+ }
150
+ else if (arg === '-o' || arg === '--options') {
151
+ if (i + 1 < argv.length) {
152
+ options = argv[i + 1];
153
+ i++;
154
+ }
155
+ else {
156
+ await writelnStderr(process, terminal, chalk.red('mount: option requires an argument -- \'o\''));
157
+ return 1;
158
+ }
159
+ }
160
+ else if (arg && !arg.startsWith('-')) {
161
+ positionalArgs.push(arg);
162
+ }
163
+ }
164
+ if (listMode || (argv.length === 0 && !allMode)) {
165
+ const mountList = Array.from(kernel.filesystem.mounts.entries());
166
+ if (mountList.length === 0) {
167
+ await writelnStdout(process, terminal, 'No filesystems mounted.');
168
+ return 0;
169
+ }
170
+ const mountRows = mountList.map(([target, mount]) => {
171
+ const mountObj = mount;
172
+ const store = mountObj.store;
173
+ const backendName = store?.constructor?.name || mountObj.constructor?.name || 'Unknown';
174
+ const metadata = mountObj.metadata?.();
175
+ const name = metadata?.name || backendName;
176
+ return {
177
+ target: chalk.blue(target),
178
+ name: chalk.gray(name)
179
+ };
180
+ });
181
+ for (const row of mountRows) {
182
+ await writelnStdout(process, terminal, `${row.target.padEnd(30)} ${row.name}`);
183
+ }
184
+ return 0;
185
+ }
186
+ if (allMode) {
187
+ try {
188
+ const fstabPath = '/etc/fstab';
189
+ if (!(await shell.context.fs.promises.exists(fstabPath))) {
190
+ await writelnStderr(process, terminal, chalk.yellow(`mount: ${fstabPath} not found`));
191
+ return 1;
192
+ }
193
+ const content = await shell.context.fs.promises.readFile(fstabPath, 'utf-8');
194
+ const entries = parseFstabFile(content);
195
+ if (entries.length === 0) {
196
+ await writelnStdout(process, terminal, 'No entries found in /etc/fstab');
197
+ return 0;
198
+ }
199
+ await writelnStdout(process, terminal, `Mounting ${entries.length} filesystem(s) from /etc/fstab...`);
200
+ let successCount = 0;
201
+ let failCount = 0;
202
+ for (const entry of entries) {
203
+ try {
204
+ const entryType = entry.type;
205
+ const entrySource = entry.source || '';
206
+ const entryTarget = path.resolve('/', entry.target);
207
+ const entryOptions = entry.options;
208
+ // Validate entry
209
+ if (!entryType) {
210
+ await writelnStderr(process, terminal, chalk.yellow(`mount: skipping entry for ${entryTarget}: missing type`));
211
+ failCount++;
212
+ continue;
213
+ }
214
+ if (!entryTarget) {
215
+ await writelnStderr(process, terminal, chalk.yellow(`mount: skipping entry: missing target`));
216
+ failCount++;
217
+ continue;
218
+ }
219
+ // Check if filesystem type doesn't require source but one is provided
220
+ const noSourceTypes = ['memory', 'singlebuffer', 'webstorage', 'webaccess', 'xml', 'dropbox', 'googledrive'];
221
+ if (entrySource && noSourceTypes.includes(entryType.toLowerCase())) {
222
+ await writelnStderr(process, terminal, chalk.yellow(`mount: ${entryType} filesystem does not require a source, ignoring source for ${entryTarget}`));
223
+ }
224
+ // Check if filesystem type requires source but none is provided
225
+ const requiresSourceTypes = ['zip', 'iso', 'fetch', 'indexeddb'];
226
+ if (!entrySource && requiresSourceTypes.includes(entryType.toLowerCase())) {
227
+ await writelnStderr(process, terminal, chalk.yellow(`mount: skipping ${entryTarget}: ${entryType} filesystem requires a source`));
228
+ failCount++;
229
+ continue;
230
+ }
231
+ // Create target directory if needed
232
+ const parentDir = path.dirname(entryTarget);
233
+ if (parentDir !== entryTarget && !(await shell.context.fs.promises.exists(parentDir))) {
234
+ await shell.context.fs.promises.mkdir(parentDir, { recursive: true });
235
+ }
236
+ if (!(await shell.context.fs.promises.exists(entryTarget))) {
237
+ await shell.context.fs.promises.mkdir(entryTarget, { recursive: true });
238
+ }
239
+ // Parse mount options
240
+ const mountOptions = entryOptions?.split(',').reduce((acc, option) => {
241
+ const [key, value] = option.split('=');
242
+ if (key && value) {
243
+ acc[key.trim()] = value.trim();
244
+ }
245
+ return acc;
246
+ }, {}) || {};
247
+ // Perform the mount based on type
248
+ switch (entryType.toLowerCase()) {
249
+ case 'fetch': {
250
+ let fetchBaseUrl = mountOptions.baseUrl || '';
251
+ let indexUrl;
252
+ if (entrySource && /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(entrySource)) {
253
+ indexUrl = entrySource;
254
+ }
255
+ else {
256
+ if (!fetchBaseUrl) {
257
+ throw new Error('fetch filesystem requires either a full URL as source or baseUrl option');
258
+ }
259
+ fetchBaseUrl = new URL(fetchBaseUrl).toString();
260
+ indexUrl = new URL(entrySource || 'index.json', fetchBaseUrl).toString();
261
+ }
262
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
263
+ backend: Fetch,
264
+ index: indexUrl,
265
+ baseUrl: fetchBaseUrl,
266
+ disableAsyncCache: true,
267
+ }));
268
+ break;
269
+ }
270
+ case 'indexeddb':
271
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
272
+ backend: IndexedDB,
273
+ storeName: entrySource || entryTarget
274
+ }));
275
+ break;
276
+ case 'webstorage': {
277
+ const storageType = mountOptions.storage?.toLowerCase() || 'localstorage';
278
+ let storage;
279
+ if (storageType === 'sessionstorage') {
280
+ if (typeof sessionStorage === 'undefined') {
281
+ throw new Error('sessionStorage is not available in this environment');
282
+ }
283
+ storage = sessionStorage;
284
+ }
285
+ else if (storageType === 'localstorage') {
286
+ if (typeof localStorage === 'undefined') {
287
+ throw new Error('localStorage is not available in this environment');
288
+ }
289
+ storage = localStorage;
290
+ }
291
+ else {
292
+ throw new Error(`invalid storage type '${storageType}'. Use 'localStorage' or 'sessionStorage'`);
293
+ }
294
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
295
+ backend: WebStorage,
296
+ storage
297
+ }));
298
+ break;
299
+ }
300
+ case 'webaccess': {
301
+ if (typeof window === 'undefined') {
302
+ throw new Error('File System Access API is not available in this environment');
303
+ }
304
+ const win = window;
305
+ if (!win.showDirectoryPicker) {
306
+ throw new Error('File System Access API is not available in this environment');
307
+ }
308
+ // For fstab, we can't interactively pick a directory, so skip
309
+ await writelnStderr(process, terminal, chalk.yellow(`mount: skipping ${entryTarget}: webaccess requires interactive directory selection`));
310
+ failCount++;
311
+ continue;
312
+ }
313
+ case 'memory':
314
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
315
+ backend: InMemory
316
+ }));
317
+ break;
318
+ case 'singlebuffer': {
319
+ const bufferSize = mountOptions.size
320
+ ? parseInt(mountOptions.size, 10)
321
+ : 1048576;
322
+ if (isNaN(bufferSize) || bufferSize <= 0) {
323
+ throw new Error('invalid buffer size for singlebuffer type');
324
+ }
325
+ let buffer;
326
+ try {
327
+ buffer = new SharedArrayBuffer(bufferSize);
328
+ }
329
+ catch {
330
+ buffer = new ArrayBuffer(bufferSize);
331
+ }
332
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
333
+ backend: SingleBuffer,
334
+ buffer
335
+ }));
336
+ break;
337
+ }
338
+ case 'zip': {
339
+ if (!entrySource) {
340
+ throw new Error('zip filesystem requires a source file or URL');
341
+ }
342
+ let arrayBuffer;
343
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(entrySource)) {
344
+ const response = await fetch(entrySource);
345
+ if (!response.ok) {
346
+ throw new Error(`failed to fetch archive: ${response.status} ${response.statusText}`);
347
+ }
348
+ arrayBuffer = await response.arrayBuffer();
349
+ }
350
+ else {
351
+ const sourcePath = path.resolve('/', entrySource);
352
+ if (!(await shell.context.fs.promises.exists(sourcePath))) {
353
+ throw new Error(`archive file not found: ${sourcePath}`);
354
+ }
355
+ const fileData = await shell.context.fs.promises.readFile(sourcePath);
356
+ arrayBuffer = new Uint8Array(fileData).buffer;
357
+ }
358
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
359
+ backend: Zip,
360
+ data: arrayBuffer
361
+ }));
362
+ break;
363
+ }
364
+ case 'iso': {
365
+ if (!entrySource) {
366
+ throw new Error('iso filesystem requires a source file or URL');
367
+ }
368
+ let uint8Array;
369
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(entrySource)) {
370
+ const response = await fetch(entrySource);
371
+ if (!response.ok) {
372
+ throw new Error(`failed to fetch ISO image: ${response.status} ${response.statusText}`);
373
+ }
374
+ const arrayBuffer = await response.arrayBuffer();
375
+ uint8Array = new Uint8Array(arrayBuffer);
376
+ }
377
+ else {
378
+ const sourcePath = path.resolve('/', entrySource);
379
+ if (!(await shell.context.fs.promises.exists(sourcePath))) {
380
+ throw new Error(`ISO image file not found: ${sourcePath}`);
381
+ }
382
+ uint8Array = await shell.context.fs.promises.readFile(sourcePath);
383
+ }
384
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
385
+ backend: Iso,
386
+ data: uint8Array
387
+ }));
388
+ break;
389
+ }
390
+ case 'dropbox': {
391
+ if (!mountOptions.client) {
392
+ throw new Error('dropbox filesystem requires client configuration');
393
+ }
394
+ let clientConfig;
395
+ try {
396
+ clientConfig = JSON.parse(mountOptions.client);
397
+ }
398
+ catch {
399
+ throw new Error('invalid JSON in client option');
400
+ }
401
+ if (!clientConfig.accessToken) {
402
+ throw new Error('client configuration must include accessToken');
403
+ }
404
+ const dropboxModule = await import('dropbox');
405
+ const DropboxClient = dropboxModule.Dropbox;
406
+ const client = new DropboxClient(clientConfig);
407
+ const cacheTTL = mountOptions.cacheTTL ? parseInt(mountOptions.cacheTTL, 10) : undefined;
408
+ await kernel.filesystem.fsSync.mount(entryTarget, await resolveMountConfig({
409
+ backend: Dropbox,
410
+ client,
411
+ ...(cacheTTL && !isNaN(cacheTTL) ? { cacheTTL } : {})
412
+ }));
413
+ break;
414
+ }
415
+ case 'googledrive': {
416
+ if (typeof window === 'undefined') {
417
+ throw new Error('Google Drive API requires a browser environment');
418
+ }
419
+ if (!mountOptions.apiKey) {
420
+ throw new Error('googledrive filesystem requires apiKey option');
421
+ }
422
+ // Google Drive mounting is complex and requires interactive auth
423
+ // For fstab, we'll skip it with a warning
424
+ await writelnStderr(process, terminal, chalk.yellow(`mount: skipping ${entryTarget}: googledrive requires interactive authentication`));
425
+ failCount++;
426
+ continue;
427
+ }
428
+ default:
429
+ throw new Error(`unknown filesystem type '${entryType}'`);
430
+ }
431
+ const successMessage = entrySource
432
+ ? chalk.green(`Mounted ${entryType} filesystem from ${entrySource} to ${entryTarget}`)
433
+ : chalk.green(`Mounted ${entryType} filesystem at ${entryTarget}`);
434
+ await writelnStdout(process, terminal, successMessage);
435
+ successCount++;
436
+ }
437
+ catch (error) {
438
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
439
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to mount ${entry.target}: ${errorMessage}`));
440
+ failCount++;
441
+ }
442
+ }
443
+ await writelnStdout(process, terminal, `\nMount summary: ${successCount} succeeded, ${failCount} failed`);
444
+ return failCount > 0 ? 1 : 0;
445
+ }
446
+ catch (error) {
447
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to process /etc/fstab: ${error instanceof Error ? error.message : 'Unknown error'}`));
448
+ return 1;
449
+ }
450
+ }
451
+ if (positionalArgs.length === 0) {
452
+ await writelnStderr(process, terminal, chalk.red('mount: missing target argument'));
453
+ await writelnStderr(process, terminal, 'Try \'mount --help\' for more information.');
454
+ return 1;
455
+ }
456
+ if (positionalArgs.length > 2) {
457
+ await writelnStderr(process, terminal, chalk.red('mount: too many arguments'));
458
+ await writelnStderr(process, terminal, 'Try \'mount --help\' for more information.');
459
+ return 1;
460
+ }
461
+ if (!type) {
462
+ await writelnStderr(process, terminal, chalk.red('mount: filesystem type must be specified'));
463
+ await writelnStderr(process, terminal, 'Try \'mount --help\' for more information.');
464
+ return 1;
465
+ }
466
+ const source = positionalArgs.length === 2 ? positionalArgs[0] : '';
467
+ const targetArg = positionalArgs[positionalArgs.length - 1];
468
+ if (!targetArg) {
469
+ await writelnStderr(process, terminal, chalk.red('mount: missing target argument'));
470
+ return 1;
471
+ }
472
+ const target = path.resolve(shell.cwd, targetArg);
473
+ if (positionalArgs.length === 2 && (type.toLowerCase() === 'memory' || type.toLowerCase() === 'singlebuffer' || type.toLowerCase() === 'webstorage' || type.toLowerCase() === 'webaccess' || type.toLowerCase() === 'xml' || type.toLowerCase() === 'dropbox' /* || type.toLowerCase() === 's3' */ || type.toLowerCase() === 'googledrive')) {
474
+ await writelnStderr(process, terminal, chalk.yellow(`mount: ${type.toLowerCase()} filesystem does not require a source`));
475
+ await writelnStderr(process, terminal, `Usage: mount -t ${type.toLowerCase()} TARGET`);
476
+ return 1;
477
+ }
478
+ if (positionalArgs.length === 1 && (type.toLowerCase() === 'zip' || type.toLowerCase() === 'iso')) {
479
+ await writelnStderr(process, terminal, chalk.red(`mount: ${type.toLowerCase()} filesystem requires a source file or URL`));
480
+ await writelnStderr(process, terminal, `Usage: mount -t ${type.toLowerCase()} SOURCE TARGET`);
481
+ return 1;
482
+ }
483
+ try {
484
+ const parentDir = path.dirname(target);
485
+ if (parentDir !== target && !(await shell.context.fs.promises.exists(parentDir))) {
486
+ await shell.context.fs.promises.mkdir(parentDir, { recursive: true });
487
+ }
488
+ if (!(await shell.context.fs.promises.exists(target))) {
489
+ await shell.context.fs.promises.mkdir(target, { recursive: true });
490
+ }
491
+ const mountOptions = options?.split(',').reduce((acc, option) => {
492
+ const [key, value] = option.split('=');
493
+ if (key && value) {
494
+ acc[key.trim()] = value.trim();
495
+ }
496
+ return acc;
497
+ }, {}) || {};
498
+ switch (type.toLowerCase()) {
499
+ case 'fetch': {
500
+ let fetchBaseUrl = new URL(mountOptions.baseUrl || '').toString();
501
+ let indexUrl;
502
+ if (source && /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(source)) {
503
+ indexUrl = source;
504
+ }
505
+ else {
506
+ indexUrl = new URL(source || 'index.json', fetchBaseUrl).toString();
507
+ }
508
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
509
+ backend: Fetch,
510
+ index: indexUrl,
511
+ baseUrl: fetchBaseUrl,
512
+ disableAsyncCache: true,
513
+ }));
514
+ break;
515
+ }
516
+ case 'indexeddb':
517
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
518
+ backend: IndexedDB,
519
+ storeName: source || target
520
+ }));
521
+ break;
522
+ case 'webstorage': {
523
+ const storageType = mountOptions.storage?.toLowerCase() || 'localstorage';
524
+ let storage;
525
+ if (storageType === 'sessionstorage') {
526
+ if (typeof sessionStorage === 'undefined') {
527
+ await writelnStderr(process, terminal, chalk.red('mount: sessionStorage is not available in this environment'));
528
+ return 1;
529
+ }
530
+ storage = sessionStorage;
531
+ }
532
+ else if (storageType === 'localstorage') {
533
+ if (typeof localStorage === 'undefined') {
534
+ await writelnStderr(process, terminal, chalk.red('mount: localStorage is not available in this environment'));
535
+ return 1;
536
+ }
537
+ storage = localStorage;
538
+ }
539
+ else {
540
+ await writelnStderr(process, terminal, chalk.red(`mount: invalid storage type '${storageType}'. Use 'localStorage' or 'sessionStorage'`));
541
+ return 1;
542
+ }
543
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
544
+ backend: WebStorage,
545
+ storage
546
+ }));
547
+ break;
548
+ }
549
+ case 'webaccess': {
550
+ if (typeof window === 'undefined') {
551
+ await writelnStderr(process, terminal, chalk.red('mount: File System Access API is not available in this environment'));
552
+ return 1;
553
+ }
554
+ const win = window;
555
+ if (!win.showDirectoryPicker) {
556
+ await writelnStderr(process, terminal, chalk.red('mount: File System Access API is not available in this environment'));
557
+ return 1;
558
+ }
559
+ try {
560
+ const directoryHandle = await win.showDirectoryPicker();
561
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
562
+ backend: WebAccess,
563
+ handle: directoryHandle
564
+ }));
565
+ }
566
+ catch (error) {
567
+ if (error instanceof Error && error.name === 'AbortError') {
568
+ await writelnStderr(process, terminal, chalk.yellow('mount: directory selection cancelled'));
569
+ return 1;
570
+ }
571
+ throw error;
572
+ }
573
+ break;
574
+ }
575
+ // TODO: Some more work needs to be done with the XML backend
576
+ // case 'xml': {
577
+ // if (typeof document === 'undefined') {
578
+ // await writelnStderr(process, terminal, chalk.red('mount: XML backend requires DOM APIs (document) which are not available in this environment'))
579
+ // return 1
580
+ // }
581
+ // let root: Element | undefined
582
+ // if (mountOptions.root) {
583
+ // const rootSelector = mountOptions.root
584
+ // const element = document.querySelector(rootSelector)
585
+ // if (!element) {
586
+ // await writelnStderr(process, terminal, chalk.yellow(`mount: root element '${rootSelector}' not found, creating new element`))
587
+ // root = new DOMParser().parseFromString('<fs></fs>', 'application/xml').documentElement
588
+ // root.setAttribute('id', 'xmlfs-' + Math.random().toString(36).substring(2, 15))
589
+ // root.setAttribute('style', 'display: none')
590
+ // } else {
591
+ // root = element as Element
592
+ // }
593
+ // } else {
594
+ // root = new DOMParser().parseFromString('<fs></fs>', 'application/xml').documentElement
595
+ // root.setAttribute('id', 'xmlfs-' + Math.random().toString(36).substring(2, 15))
596
+ // root.setAttribute('style', 'display: none')
597
+ // }
598
+ // if (!root) throw new Error('Failed to create root element')
599
+ // const rootNode = document.createElement('file')
600
+ // rootNode.setAttribute('paths', JSON.stringify(['/']))
601
+ // rootNode.setAttribute('nlink', '1')
602
+ // rootNode.setAttribute('mode', (constants.S_IFDIR | 0o777).toString(16))
603
+ // rootNode.setAttribute('uid', (0).toString(16))
604
+ // rootNode.setAttribute('gid', (0).toString(16))
605
+ // rootNode.textContent = '[]'
606
+ // root.appendChild(rootNode)
607
+ // try {
608
+ // const config = {
609
+ // backend: XML,
610
+ // root
611
+ // } as { backend: typeof XML; root: Element }
612
+ // document.body.appendChild(root)
613
+ // const mountConfig = await resolveMountConfig(config)
614
+ // await kernel.filesystem.fsSync.mount(target, mountConfig)
615
+ // } catch (error) {
616
+ // const errorMessage = error instanceof Error ? error.message : String(error)
617
+ // await writelnStderr(process, terminal, chalk.red(`mount: failed to mount XML filesystem: ${errorMessage}`))
618
+ // if (error instanceof Error && error.stack) {
619
+ // await writelnStderr(process, terminal, chalk.gray(`Stack: ${error.stack}`))
620
+ // }
621
+ // return 1
622
+ // }
623
+ // break
624
+ // }
625
+ case 'memory':
626
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
627
+ backend: InMemory
628
+ }));
629
+ break;
630
+ case 'singlebuffer': {
631
+ const bufferSize = mountOptions.size
632
+ ? parseInt(mountOptions.size, 10)
633
+ : 1048576;
634
+ if (isNaN(bufferSize) || bufferSize <= 0) {
635
+ await writelnStderr(process, terminal, chalk.red('mount: invalid buffer size for singlebuffer type'));
636
+ return 1;
637
+ }
638
+ let buffer;
639
+ try {
640
+ buffer = new SharedArrayBuffer(bufferSize);
641
+ }
642
+ catch {
643
+ buffer = new ArrayBuffer(bufferSize);
644
+ }
645
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
646
+ backend: SingleBuffer,
647
+ buffer
648
+ }));
649
+ break;
650
+ }
651
+ case 'zip': {
652
+ if (!source) {
653
+ await writelnStderr(process, terminal, chalk.red('mount: zip filesystem requires a source file or URL'));
654
+ return 1;
655
+ }
656
+ let arrayBuffer;
657
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(source)) {
658
+ await writelnStdout(process, terminal, chalk.gray(`Fetching archive from ${source}...`));
659
+ const response = await fetch(source);
660
+ if (!response.ok) {
661
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to fetch archive: ${response.status} ${response.statusText}`));
662
+ return 1;
663
+ }
664
+ arrayBuffer = await response.arrayBuffer();
665
+ }
666
+ else {
667
+ const sourcePath = path.resolve(shell.cwd, source);
668
+ if (!(await shell.context.fs.promises.exists(sourcePath))) {
669
+ await writelnStderr(process, terminal, chalk.red(`mount: archive file not found: ${sourcePath}`));
670
+ return 1;
671
+ }
672
+ await writelnStdout(process, terminal, chalk.gray(`Reading archive from ${sourcePath}...`));
673
+ const fileData = await shell.context.fs.promises.readFile(sourcePath);
674
+ arrayBuffer = new Uint8Array(fileData).buffer;
675
+ }
676
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
677
+ backend: Zip,
678
+ data: arrayBuffer
679
+ }));
680
+ break;
681
+ }
682
+ case 'iso': {
683
+ if (!source) {
684
+ await writelnStderr(process, terminal, chalk.red('mount: iso filesystem requires a source file or URL'));
685
+ return 1;
686
+ }
687
+ let uint8Array;
688
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(source)) {
689
+ await writelnStdout(process, terminal, chalk.gray(`Fetching ISO image from ${source}...`));
690
+ const response = await fetch(source);
691
+ if (!response.ok) {
692
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to fetch ISO image: ${response.status} ${response.statusText}`));
693
+ return 1;
694
+ }
695
+ const arrayBuffer = await response.arrayBuffer();
696
+ uint8Array = new Uint8Array(arrayBuffer);
697
+ }
698
+ else {
699
+ const sourcePath = path.resolve(shell.cwd, source);
700
+ if (!(await shell.context.fs.promises.exists(sourcePath))) {
701
+ await writelnStderr(process, terminal, chalk.red(`mount: ISO image file not found: ${sourcePath}`));
702
+ return 1;
703
+ }
704
+ await writelnStdout(process, terminal, chalk.gray(`Reading ISO image from ${sourcePath}...`));
705
+ uint8Array = await shell.context.fs.promises.readFile(sourcePath);
706
+ }
707
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
708
+ backend: Iso,
709
+ data: uint8Array
710
+ }));
711
+ break;
712
+ }
713
+ case 'dropbox': {
714
+ if (!mountOptions.client) {
715
+ await writelnStderr(process, terminal, chalk.red('mount: dropbox filesystem requires client configuration'));
716
+ await writelnStderr(process, terminal, 'Usage: mount -t dropbox TARGET -o client=\'{"accessToken":"..."}\'');
717
+ return 1;
718
+ }
719
+ try {
720
+ let clientConfig;
721
+ try {
722
+ clientConfig = JSON.parse(mountOptions.client);
723
+ }
724
+ catch {
725
+ await writelnStderr(process, terminal, chalk.red('mount: invalid JSON in client option'));
726
+ return 1;
727
+ }
728
+ if (!clientConfig.accessToken) {
729
+ await writelnStderr(process, terminal, chalk.red('mount: client configuration must include accessToken'));
730
+ return 1;
731
+ }
732
+ const dropboxModule = await import('dropbox');
733
+ const DropboxClient = dropboxModule.Dropbox;
734
+ const client = new DropboxClient(clientConfig);
735
+ const cacheTTL = mountOptions.cacheTTL ? parseInt(mountOptions.cacheTTL, 10) : undefined;
736
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
737
+ backend: Dropbox,
738
+ client,
739
+ ...(cacheTTL && !isNaN(cacheTTL) ? { cacheTTL } : {})
740
+ }));
741
+ }
742
+ catch (error) {
743
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to mount dropbox filesystem: ${error instanceof Error ? error.message : 'Unknown error'}`));
744
+ return 1;
745
+ }
746
+ break;
747
+ }
748
+ /* case 's3': {
749
+ if (!mountOptions.bucket) {
750
+ await writelnStderr(process, terminal, chalk.red('mount: s3 filesystem requires bucket option'))
751
+ await writelnStderr(process, terminal, 'Usage: mount -t s3 TARGET -o bucket=my-bucket')
752
+ return 1
753
+ }
754
+
755
+ try {
756
+ // Start with default config
757
+ let clientConfigRaw: { region?: string; credentials?: { accessKeyId?: string; secretAccessKey?: string; sessionToken?: string }; [key: string]: unknown } = {}
758
+
759
+ // Parse client config if provided
760
+ if (mountOptions.client) {
761
+ try {
762
+ clientConfigRaw = JSON.parse(mountOptions.client)
763
+ } catch {
764
+ await writelnStderr(process, terminal, chalk.red('mount: invalid JSON in client option'))
765
+ return 1
766
+ }
767
+ }
768
+
769
+ // Set region: use from config, then env var, then default
770
+ if (!clientConfigRaw.region) {
771
+ clientConfigRaw.region = shell.env.get('AWS_DEFAULT_REGION') || 'us-east-1'
772
+ }
773
+
774
+ // Use environment variables as defaults if credentials not provided
775
+ if (!clientConfigRaw.credentials) {
776
+ const accessKeyId = shell.env.get('AWS_ACCESS_KEY_ID')
777
+ const secretAccessKey = shell.env.get('AWS_SECRET_ACCESS_KEY')
778
+ const sessionToken = shell.env.get('AWS_SESSION_TOKEN')
779
+
780
+ if (accessKeyId && secretAccessKey) {
781
+ clientConfigRaw.credentials = {
782
+ accessKeyId,
783
+ secretAccessKey,
784
+ ...(sessionToken ? { sessionToken } : {})
785
+ }
786
+ }
787
+ } else {
788
+ // Validate credentials if provided
789
+ if (!clientConfigRaw.credentials.accessKeyId || !clientConfigRaw.credentials.secretAccessKey) {
790
+ await writelnStderr(process, terminal, chalk.yellow('mount: credentials object should include both accessKeyId and secretAccessKey'))
791
+ await writelnStderr(process, terminal, 'Note: If credentials are not provided, AWS SDK will use default credential chain (env vars, IAM role, etc.)')
792
+ }
793
+ }
794
+
795
+ // Configure for browser environment if needed
796
+ if (typeof window !== 'undefined') {
797
+ // Ensure we're using fetch for browser requests
798
+ if (!clientConfigRaw.requestHandler) {
799
+ // The AWS SDK v3 uses fetch by default in browsers, but we can explicitly set it
800
+ // This helps ensure CORS is handled properly
801
+ clientConfigRaw.requestHandler = undefined // Let SDK use default browser fetch
802
+ }
803
+ }
804
+
805
+ const s3Module = await import('@aws-sdk/client-s3')
806
+ const S3Client = s3Module.S3
807
+ const client = new S3Client(clientConfigRaw as never)
808
+ const bucketName = mountOptions.bucket
809
+ const prefix = mountOptions.prefix
810
+ const cacheTTL = mountOptions.cacheTTL ? parseInt(mountOptions.cacheTTL, 10) : undefined
811
+
812
+ try {
813
+ await kernel.filesystem.fsSync.mount(
814
+ target,
815
+ await resolveMountConfig({
816
+ backend: S3Bucket,
817
+ client,
818
+ bucketName,
819
+ ...(prefix ? { prefix } : {}),
820
+ ...(cacheTTL && !isNaN(cacheTTL) ? { cacheTTL } : {})
821
+ })
822
+ )
823
+ } catch (mountError) {
824
+ const errorMessage = mountError instanceof Error ? mountError.message : String(mountError)
825
+ // Provide helpful guidance for common S3 errors
826
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to mount s3 filesystem: ${errorMessage}`))
827
+ await writelnStderr(process, terminal, chalk.yellow('\nS3 CORS configuration may be required:'))
828
+ await writelnStderr(process, terminal, 'For browser access, your S3 bucket needs CORS configuration:')
829
+ await writelnStderr(process, terminal, ' {')
830
+ await writelnStderr(process, terminal, ' "CORSRules": [{')
831
+ await writelnStderr(process, terminal, ' "AllowedOrigins": ["*"],')
832
+ await writelnStderr(process, terminal, ' "AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"],')
833
+ await writelnStderr(process, terminal, ' "AllowedHeaders": ["*"],')
834
+ await writelnStderr(process, terminal, ' "ExposeHeaders": ["ETag"],')
835
+ await writelnStderr(process, terminal, ' "MaxAgeSeconds": 3000')
836
+ await writelnStderr(process, terminal, ' }]')
837
+ await writelnStderr(process, terminal, ' }')
838
+ await writelnStderr(process, terminal, chalk.gray('\nAlso ensure your bucket policy allows the required operations.'))
839
+ throw mountError
840
+ }
841
+ } catch (error) {
842
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to mount s3 filesystem: ${error instanceof Error ? error.message : 'Unknown error'}`))
843
+ if (error instanceof Error && error.stack) {
844
+ await writelnStderr(process, terminal, chalk.gray(error.stack))
845
+ }
846
+ return 1
847
+ }
848
+ break
849
+ } */
850
+ case 'googledrive': {
851
+ try {
852
+ if (typeof window === 'undefined') {
853
+ await writelnStderr(process, terminal, chalk.red('mount: Google Drive API requires a browser environment'));
854
+ return 1;
855
+ }
856
+ // if (!mountOptions.apiKey) {
857
+ // await writelnStderr(process, terminal, chalk.red('mount: googledrive filesystem requires apiKey option'))
858
+ // await writelnStderr(process, terminal, 'Usage: mount -t googledrive TARGET -o apiKey=YOUR_API_KEY')
859
+ // return 1
860
+ // }
861
+ const win = window;
862
+ // Load Google Identity Services library if not already loaded
863
+ if (!win.google?.accounts) {
864
+ await writelnStdout(process, terminal, chalk.gray('Loading Google Identity Services library...'));
865
+ await new Promise((resolve, reject) => {
866
+ const script = document.createElement('script');
867
+ script.src = 'https://accounts.google.com/gsi/client';
868
+ script.async = true;
869
+ script.defer = true;
870
+ script.onload = () => resolve();
871
+ script.onerror = () => reject(new Error('Failed to load Google Identity Services script'));
872
+ document.head.appendChild(script);
873
+ });
874
+ }
875
+ // Wait for google.accounts to be available
876
+ let attempts = 0;
877
+ while (!win.google?.accounts && attempts < 50) {
878
+ await new Promise(resolve => setTimeout(resolve, 100));
879
+ attempts++;
880
+ }
881
+ if (!win.google?.accounts) {
882
+ await writelnStderr(process, terminal, chalk.red('mount: Failed to load Google Identity Services library'));
883
+ return 1;
884
+ }
885
+ // Load Google API script if not already loaded
886
+ if (!win.gapi) {
887
+ await writelnStdout(process, terminal, chalk.gray('Loading Google API client library...'));
888
+ await new Promise((resolve, reject) => {
889
+ const script = document.createElement('script');
890
+ script.src = 'https://apis.google.com/js/api.js';
891
+ script.onload = () => resolve();
892
+ script.onerror = () => reject(new Error('Failed to load Google API script'));
893
+ document.head.appendChild(script);
894
+ });
895
+ }
896
+ // Wait for gapi to be available
897
+ attempts = 0;
898
+ while (!win.gapi && attempts < 50) {
899
+ await new Promise(resolve => setTimeout(resolve, 100));
900
+ attempts++;
901
+ }
902
+ if (!win.gapi) {
903
+ await writelnStderr(process, terminal, chalk.red('mount: Failed to load Google API client library'));
904
+ return 1;
905
+ }
906
+ if (!win.gapi.client || !win.gapi.client.drive) {
907
+ await writelnStdout(process, terminal, chalk.gray('Initializing Google API client...'));
908
+ const initConfig = {
909
+ apiKey: mountOptions.apiKey,
910
+ discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
911
+ };
912
+ // Load the client module
913
+ await new Promise((resolve, reject) => {
914
+ if (!win.gapi?.load) {
915
+ reject(new Error('gapi.load is not available'));
916
+ return;
917
+ }
918
+ win.gapi.load('client', () => {
919
+ if (!win.gapi?.client?.init) {
920
+ reject(new Error('gapi.client.init is not available'));
921
+ return;
922
+ }
923
+ win.gapi.client.init(initConfig)
924
+ .then(() => {
925
+ setTimeout(() => {
926
+ if (win.gapi?.client?.drive) {
927
+ resolve();
928
+ }
929
+ else {
930
+ reject(new Error('API discovery response missing required fields. The Drive API discovery document may have failed to load. This could be due to: network issues, invalid API key, or the Drive API not being enabled in your Google Cloud project.'));
931
+ }
932
+ }, 1000);
933
+ })
934
+ .catch((error) => {
935
+ const err = error;
936
+ let errorMessage = 'Unknown error';
937
+ errorMessage = JSON.stringify({
938
+ error: err.error,
939
+ details: err.details
940
+ }, null, 2);
941
+ const lowerError = err.error?.toLowerCase();
942
+ if (lowerError?.includes('discovery') || lowerError?.includes('API') || lowerError?.includes('required fields')) {
943
+ reject(new Error(`API discovery failed: ${errorMessage}. This could be due to: network issues, invalid API key, or the Drive API not being enabled in your Google Cloud project.`));
944
+ }
945
+ else {
946
+ reject(new Error(err.error || err.details || 'Unknown error'));
947
+ }
948
+ });
949
+ });
950
+ });
951
+ // Verify Drive API is loaded
952
+ if (!win.gapi?.client?.drive) {
953
+ // Try one more time with a longer wait
954
+ await new Promise((resolve, reject) => {
955
+ let attempts = 0;
956
+ const checkDrive = () => {
957
+ if (win.gapi?.client?.drive) {
958
+ resolve();
959
+ }
960
+ else if (attempts < 10) {
961
+ attempts++;
962
+ setTimeout(checkDrive, 200);
963
+ }
964
+ else {
965
+ reject(new Error('Failed to load Drive API. The discovery document may have failed to load. Check the browser console for network errors (502 Bad Gateway suggests a network issue).'));
966
+ }
967
+ };
968
+ checkDrive();
969
+ });
970
+ }
971
+ }
972
+ if (!win.gapi?.client?.drive) {
973
+ await writelnStderr(process, terminal, chalk.red('mount: Google Drive API is not available'));
974
+ await writelnStderr(process, terminal, chalk.yellow('Troubleshooting steps:'));
975
+ await writelnStderr(process, terminal, ' 1. Check the browser console for network errors (502 Bad Gateway suggests a network/server issue)');
976
+ await writelnStderr(process, terminal, ' 2. Verify your API key is valid and has the Drive API enabled');
977
+ await writelnStderr(process, terminal, ' 3. Ensure the Drive API is enabled in your Google Cloud project');
978
+ await writelnStderr(process, terminal, ' 4. Check if there are any API key restrictions (HTTP referrers, IP addresses, etc.)');
979
+ await writelnStderr(process, terminal, ' 5. Try refreshing the page and mounting again');
980
+ return 1;
981
+ }
982
+ // Handle OAuth authentication if clientId is provided
983
+ if (mountOptions.clientId) {
984
+ await writelnStdout(process, terminal, chalk.gray('Checking authentication status...'));
985
+ const driveScope = mountOptions.scope || 'https://www.googleapis.com/auth/drive';
986
+ // Check if user is already authenticated
987
+ try {
988
+ const client = win.gapi?.client;
989
+ if (client?.request) {
990
+ await client.request({
991
+ path: 'https://www.googleapis.com/drive/v3/about?fields=user'
992
+ });
993
+ }
994
+ }
995
+ catch (error) {
996
+ // User needs to authenticate using Google Identity Services
997
+ await writelnStdout(process, terminal, chalk.gray('Authentication required. Please sign in to Google...'));
998
+ try {
999
+ if (!win.google?.accounts?.oauth2) {
1000
+ throw new Error('Google Identity Services OAuth2 is not available');
1001
+ }
1002
+ await new Promise((resolve, reject) => {
1003
+ const tokenClient = win.google?.accounts?.oauth2?.initTokenClient({
1004
+ client_id: mountOptions.clientId,
1005
+ scope: driveScope,
1006
+ callback: (response) => {
1007
+ if (response.access_token && win.gapi?.client?.setToken) {
1008
+ win.gapi.client.setToken({ access_token: response.access_token });
1009
+ resolve();
1010
+ }
1011
+ else {
1012
+ reject(new Error('Failed to obtain access token'));
1013
+ }
1014
+ },
1015
+ });
1016
+ tokenClient?.requestAccessToken();
1017
+ });
1018
+ }
1019
+ catch (authError) {
1020
+ const authErrMsg = authError instanceof Error ? authError.message : String(authError);
1021
+ if (authErrMsg.toLowerCase().includes('popup') || authErrMsg.toLowerCase().includes('blocked')) {
1022
+ throw new Error(`OAuth authentication failed: ${authErrMsg}. Please allow popups for this site.`);
1023
+ }
1024
+ else if (authErrMsg.toLowerCase().includes('origin') || authErrMsg.toLowerCase().includes('authorized')) {
1025
+ throw new Error(`OAuth authentication failed: ${authErrMsg}. Your origin may not be authorized in Google Cloud Console. Add your current origin to the OAuth client's authorized JavaScript origins.`);
1026
+ }
1027
+ throw authError;
1028
+ }
1029
+ }
1030
+ }
1031
+ const drive = win.gapi.client.drive;
1032
+ const cacheTTL = mountOptions.cacheTTL ? parseInt(mountOptions.cacheTTL) : undefined;
1033
+ await kernel.filesystem.fsSync.mount(target, await resolveMountConfig({
1034
+ backend: GoogleDrive,
1035
+ drive: drive,
1036
+ disableAsyncCache: true,
1037
+ ...(cacheTTL && !isNaN(cacheTTL) ? { cacheTTL } : {})
1038
+ }));
1039
+ }
1040
+ catch (error) {
1041
+ let errorMessage = 'Unknown error';
1042
+ if (error instanceof Error) {
1043
+ errorMessage = error.message || error.toString();
1044
+ }
1045
+ else if (typeof error === 'string') {
1046
+ errorMessage = error;
1047
+ }
1048
+ else if (error && typeof error === 'object') {
1049
+ // Try to extract error message from object
1050
+ const err = error;
1051
+ errorMessage =
1052
+ (typeof err.message === 'string' ? err.message : '') ||
1053
+ (typeof err.error === 'string' ? err.error : '') ||
1054
+ (typeof err.details === 'string' ? err.details : '') ||
1055
+ (typeof err.reason === 'string' ? err.reason : '') ||
1056
+ (err.toString && typeof err.toString === 'function' ? err.toString() : '') ||
1057
+ JSON.stringify(error);
1058
+ }
1059
+ else {
1060
+ errorMessage = String(error);
1061
+ }
1062
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to mount googledrive filesystem: ${errorMessage}`));
1063
+ // Provide specific guidance for common errors
1064
+ const lowerMessage = errorMessage.toLowerCase();
1065
+ if (lowerMessage.includes('popup') || lowerMessage.includes('blocked')) {
1066
+ await writelnStderr(process, terminal, chalk.yellow('\nOAuth popup was blocked. Common causes:'));
1067
+ await writelnStderr(process, terminal, ' • Browser popup blocker is enabled');
1068
+ await writelnStderr(process, terminal, ' • Browser security restrictions');
1069
+ await writelnStderr(process, terminal, chalk.gray('\nTo fix this:'));
1070
+ await writelnStderr(process, terminal, ' 1. Allow popups for this site in your browser settings');
1071
+ await writelnStderr(process, terminal, ' 2. Try the mount command again');
1072
+ }
1073
+ else if (lowerMessage.includes('origin') || lowerMessage.includes('authorized')) {
1074
+ await writelnStderr(process, terminal, chalk.yellow('\nOAuth authentication failed. Common causes:'));
1075
+ await writelnStderr(process, terminal, ' • Your domain/origin is not authorized in Google Cloud Console');
1076
+ await writelnStderr(process, terminal, ' • Invalid or incorrect OAuth client ID');
1077
+ await writelnStderr(process, terminal, chalk.gray('\nTo fix this:'));
1078
+ await writelnStderr(process, terminal, ' 1. Go to Google Cloud Console > APIs & Services > Credentials');
1079
+ await writelnStderr(process, terminal, ' 2. Find your OAuth 2.0 Client ID');
1080
+ await writelnStderr(process, terminal, ' 3. Add your current origin to "Authorized JavaScript origins"');
1081
+ await writelnStderr(process, terminal, ' (e.g., http://localhost:30443 or your domain)');
1082
+ await writelnStderr(process, terminal, ' 4. If you only need read-only access, try mounting without clientId:');
1083
+ await writelnStderr(process, terminal, ' mount -t googledrive /mnt/gdrive -o apiKey=YOUR_API_KEY');
1084
+ }
1085
+ else if (lowerMessage.includes('discovery') || lowerMessage.includes('api discovery') || lowerMessage.includes('required fields')) {
1086
+ await writelnStderr(process, terminal, chalk.yellow('\nThe Drive API discovery document failed to load. Common causes:'));
1087
+ await writelnStderr(process, terminal, ' • Network connectivity issues (check for 502 Bad Gateway in console)');
1088
+ await writelnStderr(process, terminal, ' • Invalid or restricted API key');
1089
+ await writelnStderr(process, terminal, ' • Drive API not enabled in Google Cloud project');
1090
+ await writelnStderr(process, terminal, ' • CORS or browser security restrictions');
1091
+ await writelnStderr(process, terminal, chalk.gray('\nCheck the browser console for detailed network error messages.'));
1092
+ }
1093
+ else if (lowerMessage.includes('network') || lowerMessage.includes('fetch') || lowerMessage.includes('502') || lowerMessage.includes('bad gateway')) {
1094
+ await writelnStderr(process, terminal, chalk.yellow('\nNetwork error detected. This may be a temporary issue with Google\'s servers.'));
1095
+ await writelnStderr(process, terminal, ' • Wait a few moments and try again');
1096
+ await writelnStderr(process, terminal, ' • Check your internet connection');
1097
+ await writelnStderr(process, terminal, ' • Verify the API key is correct');
1098
+ }
1099
+ // Show full error details if it's an object (for debugging)
1100
+ if (error && typeof error === 'object' && !(error instanceof Error)) {
1101
+ try {
1102
+ const errorStr = JSON.stringify(error, null, 2);
1103
+ if (errorStr !== '{}' && errorStr.length < 500) {
1104
+ await writelnStderr(process, terminal, chalk.gray(`\nError details:\n${errorStr}`));
1105
+ }
1106
+ }
1107
+ catch {
1108
+ // Ignore JSON stringify errors
1109
+ }
1110
+ }
1111
+ if (error instanceof Error && error.stack && !lowerMessage.includes('discovery') && !lowerMessage.includes('network')) {
1112
+ await writelnStderr(process, terminal, chalk.gray(`\nStack trace:\n${error.stack}`));
1113
+ }
1114
+ return 1;
1115
+ }
1116
+ break;
1117
+ }
1118
+ default:
1119
+ await writelnStderr(process, terminal, chalk.red(`mount: unknown filesystem type '${type}'`));
1120
+ await writelnStderr(process, terminal, 'Supported types: fetch, indexeddb, webstorage, webaccess, memory, singlebuffer, zip, iso, dropbox, s3, googledrive');
1121
+ return 1;
1122
+ }
1123
+ const successMessage = source
1124
+ ? chalk.green(`Mounted ${type} filesystem from ${source} to ${target}`)
1125
+ : chalk.green(`Mounted ${type} filesystem at ${target}`);
1126
+ await writelnStdout(process, terminal, successMessage);
1127
+ return 0;
1128
+ }
1129
+ catch (error) {
1130
+ await writelnStderr(process, terminal, chalk.red(`mount: failed to mount filesystem: ${error instanceof Error ? error.message : 'Unknown error'}`));
1131
+ return 1;
1132
+ }
1133
+ }
1134
+ });
1135
+ }
1136
+ //# sourceMappingURL=mount.js.map