mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92017036d9 |
No files matched your search
+20
-35
@@ -178,13 +178,9 @@ ipcMain.handle('get-platform', () => {
|
||||
});
|
||||
|
||||
// Helper function to expand tilde (~) in paths
|
||||
// Handles both Unix (~/) and Windows (~\) style paths
|
||||
function expandTilde(filepath) {
|
||||
if (filepath === '~') {
|
||||
return os.homedir();
|
||||
}
|
||||
if (filepath.startsWith('~/') || filepath.startsWith('~\\')) {
|
||||
return path.join(os.homedir(), filepath.slice(2));
|
||||
if (filepath.startsWith('~/') || filepath === '~') {
|
||||
return path.join(os.homedir(), filepath.slice(1));
|
||||
}
|
||||
return filepath;
|
||||
}
|
||||
@@ -192,8 +188,10 @@ function expandTilde(filepath) {
|
||||
// Filesystem IPC handlers
|
||||
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
if (!filePath) {
|
||||
// Return error object instead of throwing to avoid Electron's noisy error logging
|
||||
return { __error: true, code: 'EINVAL', message: 'Failed to read file: path is required' };
|
||||
const err = new Error('Failed to read file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
// Don't log - empty paths are expected from isomorphic-git's ref resolution
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
@@ -201,13 +199,10 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
// If no encoding, convert Buffer to array for IPC serialization
|
||||
return encoding ? data : Array.from(data);
|
||||
} catch (error) {
|
||||
// For ENOENT/EINVAL errors, return error info instead of throwing to avoid Electron's noisy error logging
|
||||
// These are expected during module resolution and git operations
|
||||
if (error.code === 'ENOENT' || error.code === 'EINVAL') {
|
||||
return { __error: true, code: error.code, message: `Failed to read file ${filePath}: ${error.message}` };
|
||||
}
|
||||
// Re-throw other errors with original error code preserved
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
// Serialize the error code as a regular property so it survives IPC
|
||||
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
|
||||
// Copy enumerable properties including code
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
@@ -216,7 +211,11 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
console.error(err);
|
||||
// Don't log ENOENT errors - these are expected for git packed objects and missing refs
|
||||
// Only log unexpected errors
|
||||
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -264,11 +263,7 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
|
||||
|
||||
return entries;
|
||||
} catch (error) {
|
||||
// Return error object instead of throwing for expected errors to suppress Electron's noisy logging
|
||||
if (error.code === 'ENOTDIR' || error.code === 'ENOENT') {
|
||||
return { __error: true, message: error.message, code: error.code };
|
||||
}
|
||||
// For other errors, re-throw with original error code preserved
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
@@ -278,6 +273,10 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
|
||||
if (error.code !== 'ENOTDIR') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -324,12 +323,7 @@ ipcMain.handle('fs:stat', async (event, filePath) => {
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
// For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging
|
||||
// These are expected during module resolution and git operations
|
||||
if (error.code === 'ENOENT') {
|
||||
return { __error: true, code: 'ENOENT', message: `Failed to stat ${filePath}: ${error.message}` };
|
||||
}
|
||||
// Re-throw other errors with original error code preserved
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
@@ -367,10 +361,6 @@ ipcMain.handle('fs:lstat', async (event, filePath) => {
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
// For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging
|
||||
if (error.code === 'ENOENT') {
|
||||
return { __error: true, code: 'ENOENT', message: `Failed to lstat ${filePath}: ${error.message}` };
|
||||
}
|
||||
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
@@ -389,11 +379,6 @@ ipcMain.handle('fs:unlink', async (event, filePath) => {
|
||||
const fullPath = expandTilde(filePath);
|
||||
await fs.unlink(fullPath);
|
||||
} catch (error) {
|
||||
// Return error object instead of throwing for ENOENT to suppress Electron's noisy logging
|
||||
// This is expected when isomorphic-git tries to delete .git/shallow on non-shallow clones
|
||||
if (error.code === 'ENOENT') {
|
||||
return { __error: true, message: error.message, code: error.code };
|
||||
}
|
||||
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
|
||||
Generated
+11
-33
@@ -196,7 +196,6 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1832,7 +1831,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
@@ -1856,7 +1854,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
@@ -1878,7 +1875,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
@@ -5463,7 +5459,8 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
|
||||
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@types/cacheable-request": {
|
||||
"version": "6.0.3",
|
||||
@@ -5705,7 +5702,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
|
||||
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -5717,7 +5713,6 @@
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
@@ -5822,7 +5817,6 @@
|
||||
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.31.1",
|
||||
"@typescript-eslint/types": "8.31.1",
|
||||
@@ -6182,7 +6176,6 @@
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -6686,7 +6679,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.19",
|
||||
"caniuse-lite": "^1.0.30001751",
|
||||
@@ -6955,7 +6947,6 @@
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"anymatch": "~3.1.2",
|
||||
"braces": "~3.0.2",
|
||||
@@ -7756,7 +7747,8 @@
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
|
||||
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/dom-helpers": {
|
||||
"version": "5.2.1",
|
||||
@@ -7840,8 +7832,7 @@
|
||||
"version": "8.6.0",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.6.0",
|
||||
@@ -8155,7 +8146,6 @@
|
||||
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -8421,7 +8411,6 @@
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
|
||||
"integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"accepts": "^2.0.0",
|
||||
"body-parser": "^2.2.0",
|
||||
@@ -9644,7 +9633,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.27.6"
|
||||
},
|
||||
@@ -10428,7 +10416,6 @@
|
||||
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cssstyle": "^4.2.1",
|
||||
"data-urls": "^5.0.0",
|
||||
@@ -10825,6 +10812,7 @@
|
||||
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"lz-string": "bin/bin.js"
|
||||
}
|
||||
@@ -12622,7 +12610,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.8",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -12790,6 +12777,7 @@
|
||||
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1",
|
||||
"ansi-styles": "^5.0.0",
|
||||
@@ -12805,6 +12793,7 @@
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
@@ -12815,6 +12804,7 @@
|
||||
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
@@ -12827,7 +12817,8 @@
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
|
||||
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/prismjs": {
|
||||
"version": "1.30.0",
|
||||
@@ -13035,7 +13026,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -13062,7 +13052,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -13088,7 +13077,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
|
||||
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -13137,7 +13125,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
|
||||
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/mdast": "^4.0.0",
|
||||
@@ -13719,7 +13706,6 @@
|
||||
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.7"
|
||||
},
|
||||
@@ -14834,7 +14820,6 @@
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
@@ -15038,7 +15023,6 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -15334,7 +15318,6 @@
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -15862,7 +15845,6 @@
|
||||
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -16007,7 +15989,6 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -16478,7 +16459,6 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -16555,7 +16535,6 @@
|
||||
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"rollup": "dist/bin/rollup"
|
||||
},
|
||||
@@ -17015,7 +16994,6 @@
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { z } from 'zod';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
|
||||
import i18n from '@/lib/i18n';
|
||||
import { expandTildePath, normalizeToForwardSlashes } from '@/lib/pathUtils';
|
||||
|
||||
interface AppProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -157,16 +156,16 @@ function useApplyLanguage(language?: string): void {
|
||||
}, [language]);
|
||||
}
|
||||
|
||||
/** Expand FS paths with the user's home directory, if available.
|
||||
* Also normalizes to forward slashes for cross-platform consistency.
|
||||
*/
|
||||
/** Expand FS paths with the user's home directory, if available. */
|
||||
function expandPath(path: string): string {
|
||||
const homedir = window.electron?.homedir;
|
||||
if (!homedir) {
|
||||
return path;
|
||||
} else if (path.startsWith('~/')) {
|
||||
return homedir + path.slice(1);
|
||||
} else if (path === '~') {
|
||||
return homedir;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
// Expand tilde and normalize to forward slashes for consistency
|
||||
// This ensures paths work correctly on Windows where homedir uses backslashes
|
||||
const expanded = expandTildePath(path, homedir);
|
||||
return normalizeToForwardSlashes(expanded);
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { VFSImage } from '@/components/VFSImage';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { isAbsolutePath } from '@/lib/pathUtils';
|
||||
|
||||
interface ImageLightboxProps {
|
||||
imageUrl: string | null;
|
||||
@@ -47,7 +46,7 @@ export function ImageLightbox({ imageUrl, onClose }: ImageLightboxProps) {
|
||||
className="relative z-[2] flex items-center justify-center w-full h-full pointer-events-none"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{isAbsolutePath(imageUrl) ? (
|
||||
{imageUrl.startsWith('/') ? (
|
||||
<VFSImage
|
||||
path={imageUrl}
|
||||
alt="Expanded image"
|
||||
|
||||
@@ -33,6 +33,7 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { isMediaFile } from '@/lib/fileUtils';
|
||||
import { injectNostrShim, getNostrShimCode, NOSTR_SHIM_PATH } from '@/lib/nostrShim';
|
||||
|
||||
interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
@@ -319,6 +320,104 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
}, [historyIndex, navigationHistory, sendNavigationCommand]);
|
||||
|
||||
// Handle nostr.* requests from iframe (NIP-07 proxy)
|
||||
const handleNostrRequest = useCallback(async (message: {
|
||||
jsonrpc: '2.0';
|
||||
method: string;
|
||||
params: Record<string, unknown>;
|
||||
id: number;
|
||||
}) => {
|
||||
const { method, params, id } = message;
|
||||
const nostrMethod = method.replace('nostr.', '');
|
||||
|
||||
try {
|
||||
// Check if window.nostr is available in the parent
|
||||
if (!window.nostr) {
|
||||
throw new Error('Nostr extension not found. Please install a NIP-07 browser extension.');
|
||||
}
|
||||
|
||||
let result: unknown;
|
||||
|
||||
switch (nostrMethod) {
|
||||
case 'getPublicKey':
|
||||
result = await window.nostr.getPublicKey();
|
||||
break;
|
||||
|
||||
case 'signEvent':
|
||||
result = await window.nostr.signEvent(params.event as Parameters<typeof window.nostr.signEvent>[0]);
|
||||
break;
|
||||
|
||||
case 'getRelays':
|
||||
if (window.nostr.getRelays) {
|
||||
result = await window.nostr.getRelays();
|
||||
} else {
|
||||
result = {};
|
||||
}
|
||||
break;
|
||||
|
||||
case 'nip04.encrypt':
|
||||
if (!window.nostr.nip04) {
|
||||
throw new Error('NIP-04 encryption not supported by this extension');
|
||||
}
|
||||
result = await window.nostr.nip04.encrypt(
|
||||
params.pubkey as string,
|
||||
params.plaintext as string
|
||||
);
|
||||
break;
|
||||
|
||||
case 'nip04.decrypt':
|
||||
if (!window.nostr.nip04) {
|
||||
throw new Error('NIP-04 decryption not supported by this extension');
|
||||
}
|
||||
result = await window.nostr.nip04.decrypt(
|
||||
params.pubkey as string,
|
||||
params.ciphertext as string
|
||||
);
|
||||
break;
|
||||
|
||||
case 'nip44.encrypt':
|
||||
if (!window.nostr.nip44) {
|
||||
throw new Error('NIP-44 encryption not supported by this extension');
|
||||
}
|
||||
result = await window.nostr.nip44.encrypt(
|
||||
params.pubkey as string,
|
||||
params.plaintext as string
|
||||
);
|
||||
break;
|
||||
|
||||
case 'nip44.decrypt':
|
||||
if (!window.nostr.nip44) {
|
||||
throw new Error('NIP-44 decryption not supported by this extension');
|
||||
}
|
||||
result = await window.nostr.nip44.decrypt(
|
||||
params.pubkey as string,
|
||||
params.ciphertext as string
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown nostr method: ${nostrMethod}`);
|
||||
}
|
||||
|
||||
// Send success response
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: result as JSONRPCResponse['result'],
|
||||
id
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`[Preview] Nostr ${nostrMethod} error:`, error);
|
||||
sendError({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32000,
|
||||
message: error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
id
|
||||
});
|
||||
}
|
||||
}, [sendResponse, sendError]);
|
||||
|
||||
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
|
||||
const { params, id } = request;
|
||||
const { request: fetchRequest } = params;
|
||||
@@ -348,11 +447,41 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
// Skip SPA fallback for static assets (files with extensions)
|
||||
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
||||
|
||||
// Serve the nostr shim script at the special path
|
||||
if (path === NOSTR_SHIM_PATH) {
|
||||
console.log('[Preview] Serving nostr shim script');
|
||||
const shimCode = getNostrShimCode();
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {
|
||||
'Content-Type': 'application/javascript',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(new TextEncoder().encode(shimCode)),
|
||||
},
|
||||
id
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// SPA routing: try to serve the exact file first
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||
console.log(`Serving file: ${filePath}`);
|
||||
|
||||
// Inject nostr shim into index.html
|
||||
let responseBody: string;
|
||||
if (filePath === '/index.html') {
|
||||
const html = new TextDecoder().decode(bytes);
|
||||
const injectedHtml = injectNostrShim(html);
|
||||
responseBody = encodeBase64(new TextEncoder().encode(injectedHtml));
|
||||
} else {
|
||||
responseBody = encodeBase64(bytes);
|
||||
}
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -362,7 +491,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
'Content-Type': getContentType(filePath),
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body: responseBody,
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -393,6 +522,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||
console.log(`Serving index.html fallback for: ${path}`);
|
||||
|
||||
// Inject nostr shim into index.html for SPA fallback
|
||||
const html = new TextDecoder().decode(bytes);
|
||||
const injectedHtml = injectNostrShim(html);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -402,7 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
'Content-Type': 'text/html',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body: encodeBase64(new TextEncoder().encode(injectedHtml)),
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -453,12 +586,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
handleConsoleMessage(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
|
||||
handleUpdateNavigationState(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method?.startsWith('nostr.')) {
|
||||
handleNostrRequest(message);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, handleNostrRequest, projectId, previewDomain]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
|
||||
@@ -428,13 +428,11 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
|
||||
// For completed state, we need the result
|
||||
if (!result) return null;
|
||||
|
||||
// Parse "Generated image: <path>" from result
|
||||
// Path can be VFS style (/tmp/...) or OS path (C:/Users/.../Temp/... on Windows)
|
||||
const match = result.match(/Generated image:\s*([^\s\n]+)/);
|
||||
// Parse "Generated image: /tmp/filename.png" from result
|
||||
const match = result.match(/Generated image:\s*(\/tmp\/[^\s\n]+)/);
|
||||
if (match) {
|
||||
const imagePath = match[1];
|
||||
// Handle both forward and back slashes for getting filename
|
||||
const filename = imagePath.split(/[/\\]/).pop() || imagePath;
|
||||
const filename = imagePath.split('/').pop() || imagePath;
|
||||
|
||||
// Hide the image section if there was a load error
|
||||
if (imageLoadError) return null;
|
||||
|
||||
@@ -1,25 +1,4 @@
|
||||
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
import { getParentDirectory } from './pathUtils';
|
||||
|
||||
/**
|
||||
* Error object returned from IPC handlers instead of throwing
|
||||
* to avoid Electron's noisy error logging for expected errors.
|
||||
*/
|
||||
interface IPCErrorResult {
|
||||
__error: true;
|
||||
code: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if an IPC result is an error object.
|
||||
*/
|
||||
function isIPCError(result: unknown): result is IPCErrorResult {
|
||||
return result !== null &&
|
||||
typeof result === 'object' &&
|
||||
'__error' in result &&
|
||||
(result as IPCErrorResult).__error === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Electron filesystem adapter that implements JSRuntimeFS interface
|
||||
@@ -28,27 +7,9 @@ function isIPCError(result: unknown): result is IPCErrorResult {
|
||||
*
|
||||
* Note: This adapter should only be instantiated when running in Electron.
|
||||
*/
|
||||
/** Stat result with function methods matching the JSRuntimeFS interface */
|
||||
interface StatResult {
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isBlockDevice(): boolean;
|
||||
isCharacterDevice(): boolean;
|
||||
isSymbolicLink(): boolean;
|
||||
isFIFO(): boolean;
|
||||
isSocket(): boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
mtime: Date;
|
||||
ctime: Date;
|
||||
atime: Date;
|
||||
}
|
||||
|
||||
export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Cache for stat results to avoid repeated IPC calls
|
||||
private statCache = new Map<string, { result: StatResult; timestamp: number }>();
|
||||
private statCache = new Map<string, { result: Awaited<ReturnType<typeof this.electron.fs.stat>>; timestamp: number }>();
|
||||
private readonly STAT_CACHE_TTL = 1000; // 1 second TTL for stat cache
|
||||
|
||||
// Cache for ENOENT results to avoid repeated failed reads (especially for git objects)
|
||||
@@ -119,23 +80,6 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
const result = await this.electron.fs.readFile(path, encoding);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
|
||||
// Cache ENOENT errors
|
||||
if (result.code === 'ENOENT') {
|
||||
this.enoentCache.add(path);
|
||||
if (this.enoentCache.size > this.ENOENT_CACHE_MAX_SIZE) {
|
||||
const entries = Array.from(this.enoentCache);
|
||||
entries.slice(0, 1000).forEach(entry => this.enoentCache.delete(entry));
|
||||
}
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
// If no encoding, convert array to Uint8Array
|
||||
if (!encoding && Array.isArray(result)) {
|
||||
return new Uint8Array(result);
|
||||
@@ -173,7 +117,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
this.enoentCache.delete(path); // File now exists
|
||||
const parentDir = getParentDirectory(path);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -194,71 +138,19 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Use cached stat if available to avoid extra IPC call
|
||||
const cached = this.statCache.get(path);
|
||||
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
|
||||
// Note: cached.result has isFile as a function (from statResult), so we must call it
|
||||
if (cached.result.isFile()) {
|
||||
if (cached.result.isFile) {
|
||||
// This is a file, not a directory - throw ENOTDIR immediately
|
||||
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
|
||||
(err as NodeJS.ErrnoException).code = 'ENOTDIR';
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
// No cached stat - do a stat check first to avoid unnecessary readdir IPC calls on files
|
||||
// This is important for performance since FileTree iterates all entries and calls readdir on each
|
||||
try {
|
||||
const statResult = await this.stat(path);
|
||||
if (statResult.isFile()) {
|
||||
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
|
||||
(err as NodeJS.ErrnoException).code = 'ENOTDIR';
|
||||
throw err;
|
||||
}
|
||||
} catch (statError) {
|
||||
// If stat fails with ENOENT, let readdir handle it
|
||||
if ((statError as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
throw statError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.readdir(path, options?.withFileTypes);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (options?.withFileTypes) {
|
||||
const entries = result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>;
|
||||
const now = Date.now();
|
||||
|
||||
// Cache the file type info for each child entry to speed up subsequent stat/readdir calls
|
||||
// This is a key optimization - FileTree calls readdir on all children, and we can fast-fail
|
||||
// files without hitting IPC
|
||||
for (const entry of entries) {
|
||||
const childPath = path.endsWith('/') ? `${path}${entry.name}` : `${path}/${entry.name}`;
|
||||
const nowDate = new Date(now);
|
||||
const statResult: StatResult = {
|
||||
isDirectory: () => entry.isDirectory,
|
||||
isFile: () => entry.isFile,
|
||||
isBlockDevice: () => false,
|
||||
isCharacterDevice: () => false,
|
||||
isSymbolicLink: () => false,
|
||||
isFIFO: () => false,
|
||||
isSocket: () => false,
|
||||
size: 0,
|
||||
mtimeMs: now,
|
||||
ctimeMs: now,
|
||||
atimeMs: now,
|
||||
mtime: nowDate,
|
||||
ctime: nowDate,
|
||||
atime: nowDate,
|
||||
};
|
||||
this.statCache.set(childPath, { result: statResult, timestamp: now });
|
||||
}
|
||||
|
||||
// Convert plain objects to DirectoryEntry format
|
||||
return entries.map(entry => ({
|
||||
return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({
|
||||
name: entry.name,
|
||||
isDirectory: () => entry.isDirectory,
|
||||
isFile: () => entry.isFile,
|
||||
@@ -281,7 +173,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = getParentDirectory(path);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -317,14 +209,6 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.stat(path);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const statResult = {
|
||||
isDirectory: () => result.isDirectory,
|
||||
@@ -386,14 +270,6 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.lstat(path);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const statResult = {
|
||||
isDirectory: () => result.isDirectory,
|
||||
@@ -433,17 +309,10 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
try {
|
||||
const result = await this.electron.fs.unlink(path);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = getParentDirectory(path);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -462,7 +331,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = getParentDirectory(path);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -484,13 +353,13 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
this.statCache.delete(newPath);
|
||||
this.statCache.delete(`lstat:${newPath}`);
|
||||
|
||||
const oldParent = getParentDirectory(oldPath);
|
||||
const oldParent = oldPath.substring(0, oldPath.lastIndexOf('/'));
|
||||
if (oldParent) {
|
||||
this.statCache.delete(oldParent);
|
||||
this.statCache.delete(`lstat:${oldParent}`);
|
||||
}
|
||||
|
||||
const newParent = getParentDirectory(newPath);
|
||||
const newParent = newPath.substring(0, newPath.lastIndexOf('/'));
|
||||
if (newParent) {
|
||||
this.statCache.delete(newParent);
|
||||
this.statCache.delete(`lstat:${newParent}`);
|
||||
|
||||
@@ -2,7 +2,6 @@ import { join, dirname, extname } from "path-browserify";
|
||||
|
||||
import type { Loader, Plugin } from "esbuild-wasm";
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { isAbsolutePath, normalizeToForwardSlashes } from '@/lib/pathUtils';
|
||||
|
||||
interface TsConfig {
|
||||
compilerOptions?: {
|
||||
@@ -36,36 +35,21 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this looks like a bare module specifier (npm package)
|
||||
// Bare specifiers don't start with '.', '..', '/', or '@/' (our alias)
|
||||
// Examples: 'react', 'react/jsx-runtime', '@tanstack/react-query'
|
||||
const isBareSpecifier = !args.path.startsWith('.') &&
|
||||
!args.path.startsWith('/') &&
|
||||
!args.path.startsWith('@/') &&
|
||||
!isAbsolutePath(args.path);
|
||||
|
||||
let resolved: string;
|
||||
// Handle absolute paths (Unix or Windows style)
|
||||
if (isAbsolutePath(args.path)) {
|
||||
resolved = normalizeToForwardSlashes(args.path);
|
||||
if (args.path.startsWith("/")) {
|
||||
resolved = args.path;
|
||||
} else if (args.path.startsWith("@/")) {
|
||||
resolved = join(cwd, "src", args.path.slice(2));
|
||||
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl && !isBareSpecifier) {
|
||||
// Only use baseUrl for non-bare specifiers (local project paths)
|
||||
// Don't try to resolve npm packages via baseUrl
|
||||
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize to forward slashes for consistent comparison
|
||||
resolved = normalizeToForwardSlashes(resolved);
|
||||
const normalizedCwd = normalizeToForwardSlashes(cwd);
|
||||
|
||||
// Security: prevent accessing files outside the project directory
|
||||
if (isAbsolutePath(resolved) && !resolved.startsWith(normalizedCwd)) {
|
||||
if (resolved.startsWith("/") && !resolved.startsWith(cwd)) {
|
||||
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* The path where the nostr shim script is served from.
|
||||
* This special path is intercepted by PreviewPane and serves the shim JavaScript.
|
||||
*
|
||||
* NOTE: Cannot start with /_ because the iframe-fetch-client's Service Worker
|
||||
* ignores paths starting with /_ (reserved for its own system files).
|
||||
*/
|
||||
export const NOSTR_SHIM_PATH = '/.nostr/shim.js';
|
||||
|
||||
/**
|
||||
* Returns the JavaScript code for the nostr shim (without script tags).
|
||||
* This is served as an external script to work with the iframe-fetch-client's
|
||||
* document replacement which only re-executes external scripts.
|
||||
*/
|
||||
export function getNostrShimCode(): string {
|
||||
return `(function() {
|
||||
// Map to track pending requests
|
||||
var pendingRequests = new Map();
|
||||
var requestId = 0;
|
||||
|
||||
// Send a request to the parent and wait for response
|
||||
function sendNostrRequest(method, params) {
|
||||
params = params || {};
|
||||
return new Promise(function(resolve, reject) {
|
||||
var id = ++requestId;
|
||||
|
||||
pendingRequests.set(id, { resolve: resolve, reject: reject });
|
||||
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
method: 'nostr.' + method,
|
||||
params: params,
|
||||
id: id
|
||||
}, '*');
|
||||
|
||||
// Timeout after 60 seconds (signing can take time with hardware wallets)
|
||||
setTimeout(function() {
|
||||
if (pendingRequests.has(id)) {
|
||||
pendingRequests.delete(id);
|
||||
reject(new Error('Nostr request timed out'));
|
||||
}
|
||||
}, 60000);
|
||||
});
|
||||
}
|
||||
|
||||
// Handle responses from parent
|
||||
window.addEventListener('message', function(event) {
|
||||
var message = event.data;
|
||||
|
||||
// Check if this is a nostr response
|
||||
if (message && message.jsonrpc === '2.0' && message.id && pendingRequests.has(message.id)) {
|
||||
var pending = pendingRequests.get(message.id);
|
||||
pendingRequests.delete(message.id);
|
||||
|
||||
if (message.error) {
|
||||
pending.reject(new Error(message.error.message || 'Unknown error'));
|
||||
} else {
|
||||
pending.resolve(message.result);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Create the window.nostr shim
|
||||
window.nostr = {
|
||||
getPublicKey: function() {
|
||||
return sendNostrRequest('getPublicKey');
|
||||
},
|
||||
|
||||
signEvent: function(event) {
|
||||
return sendNostrRequest('signEvent', { event: event });
|
||||
},
|
||||
|
||||
getRelays: function() {
|
||||
return sendNostrRequest('getRelays');
|
||||
},
|
||||
|
||||
nip04: {
|
||||
encrypt: function(pubkey, plaintext) {
|
||||
return sendNostrRequest('nip04.encrypt', { pubkey: pubkey, plaintext: plaintext });
|
||||
},
|
||||
decrypt: function(pubkey, ciphertext) {
|
||||
return sendNostrRequest('nip04.decrypt', { pubkey: pubkey, ciphertext: ciphertext });
|
||||
}
|
||||
},
|
||||
|
||||
nip44: {
|
||||
encrypt: function(pubkey, plaintext) {
|
||||
return sendNostrRequest('nip44.encrypt', { pubkey: pubkey, plaintext: plaintext });
|
||||
},
|
||||
decrypt: function(pubkey, ciphertext) {
|
||||
return sendNostrRequest('nip44.decrypt', { pubkey: pubkey, ciphertext: ciphertext });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
console.log('[Preview] window.nostr shim installed - NIP-07 calls will be proxied to parent');
|
||||
})();`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects a reference to the nostr shim external script into an HTML string.
|
||||
* Inserts the script at the start of <head> to ensure it runs before any app code.
|
||||
*
|
||||
* We use an external script instead of inline because the iframe-fetch-client's
|
||||
* replaceDocument() only re-executes external scripts (those with src attribute).
|
||||
*/
|
||||
export function injectNostrShim(html: string): string {
|
||||
// Use external script reference - the script will be served by PreviewPane
|
||||
const shimScript = `<script src="${NOSTR_SHIM_PATH}"></script>`;
|
||||
|
||||
// Try to inject after <head> tag
|
||||
const headMatch = html.match(/<head[^>]*>/i);
|
||||
if (headMatch) {
|
||||
const insertPos = headMatch.index! + headMatch[0].length;
|
||||
return html.slice(0, insertPos) + '\n' + shimScript + '\n' + html.slice(insertPos);
|
||||
}
|
||||
|
||||
// Fallback: inject after <!DOCTYPE html> or at the very start
|
||||
const doctypeMatch = html.match(/<!DOCTYPE[^>]*>/i);
|
||||
if (doctypeMatch) {
|
||||
const insertPos = doctypeMatch.index! + doctypeMatch[0].length;
|
||||
return html.slice(0, insertPos) + '\n' + shimScript + '\n' + html.slice(insertPos);
|
||||
}
|
||||
|
||||
// Last resort: prepend
|
||||
return shimScript + '\n' + html;
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
/**
|
||||
* Cross-platform path utilities for handling both Unix and Windows path separators.
|
||||
* These utilities ensure consistent behavior across different operating systems.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the parent directory of a path, handling both forward and back slashes.
|
||||
* This is particularly important for Windows paths in Electron.
|
||||
*
|
||||
* @param path - The file or directory path
|
||||
* @returns The parent directory path, or empty string if at root
|
||||
*/
|
||||
export function getParentDirectory(path: string): string {
|
||||
// Find the last occurrence of either separator
|
||||
const lastForwardSlash = path.lastIndexOf('/');
|
||||
const lastBackSlash = path.lastIndexOf('\\');
|
||||
const lastSeparator = Math.max(lastForwardSlash, lastBackSlash);
|
||||
|
||||
if (lastSeparator === -1) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return path.substring(0, lastSeparator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a path to use forward slashes consistently.
|
||||
* This is useful for the VFS which uses Unix-style paths internally.
|
||||
*
|
||||
* @param path - The path to normalize
|
||||
* @returns The path with all backslashes converted to forward slashes
|
||||
*/
|
||||
export function normalizeToForwardSlashes(path: string): string {
|
||||
return path.replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a path to use the native separator for the current platform.
|
||||
* On Windows, uses backslashes; on Unix-like systems, uses forward slashes.
|
||||
*
|
||||
* @param path - The path to normalize
|
||||
* @returns The path with separators appropriate for the current platform
|
||||
*/
|
||||
export function normalizeToNativeSeparator(path: string): string {
|
||||
const isWindows = typeof navigator !== 'undefined'
|
||||
? navigator.platform?.toLowerCase().includes('win')
|
||||
: false;
|
||||
|
||||
if (isWindows) {
|
||||
return path.replace(/\//g, '\\');
|
||||
}
|
||||
return path.replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Join path segments with forward slashes, regardless of platform.
|
||||
* This is useful for VFS paths which always use forward slashes.
|
||||
*
|
||||
* @param segments - Path segments to join
|
||||
* @returns The joined path with forward slashes
|
||||
*/
|
||||
export function joinWithForwardSlashes(...segments: string[]): string {
|
||||
return segments
|
||||
.filter(Boolean)
|
||||
.map(s => s.replace(/^[/\\]+|[/\\]+$/g, '')) // Trim leading/trailing slashes
|
||||
.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path is absolute on any platform.
|
||||
* Recognizes:
|
||||
* - Unix absolute paths starting with /
|
||||
* - Windows absolute paths starting with \ or drive letter (C:\)
|
||||
*
|
||||
* @param path - The path to check
|
||||
* @returns True if the path is absolute
|
||||
*/
|
||||
export function isAbsolutePath(path: string): boolean {
|
||||
return path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file name from a path, handling both separators.
|
||||
*
|
||||
* @param path - The file path
|
||||
* @returns The file name
|
||||
*/
|
||||
export function getBasename(path: string): string {
|
||||
const lastForwardSlash = path.lastIndexOf('/');
|
||||
const lastBackSlash = path.lastIndexOf('\\');
|
||||
const lastSeparator = Math.max(lastForwardSlash, lastBackSlash);
|
||||
|
||||
if (lastSeparator === -1) {
|
||||
return path;
|
||||
}
|
||||
|
||||
return path.substring(lastSeparator + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand tilde (~) in paths to the home directory.
|
||||
* Works with both Unix (~/) and Windows (~\) style paths.
|
||||
*
|
||||
* @param path - The path that may contain tilde
|
||||
* @param homedir - The user's home directory
|
||||
* @returns The expanded path
|
||||
*/
|
||||
export function expandTildePath(path: string, homedir: string): string {
|
||||
if (path === '~') {
|
||||
return homedir;
|
||||
}
|
||||
if (path.startsWith('~/')) {
|
||||
return homedir + path.slice(1);
|
||||
}
|
||||
if (path.startsWith('~\\')) {
|
||||
return homedir + path.slice(1);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
+5
-7
@@ -3,7 +3,6 @@
|
||||
*/
|
||||
|
||||
import { normalize } from "path-browserify";
|
||||
import { normalizeToForwardSlashes } from "./pathUtils";
|
||||
|
||||
/**
|
||||
* Check if the given path is an absolute path
|
||||
@@ -39,12 +38,11 @@ export function isWriteAllowed(
|
||||
}
|
||||
|
||||
// For absolute paths, apply restrictions
|
||||
// Normalize to forward slashes for consistent comparison (handles both Unix and Windows paths)
|
||||
const absolutePath = normalizeToForwardSlashes(normalize(path));
|
||||
const absolutePath = normalize(path);
|
||||
|
||||
// Get configured paths with defaults and normalize them
|
||||
const tmpPath = normalizeToForwardSlashes(options?.tmpPath || '/tmp');
|
||||
const projectsPath = normalizeToForwardSlashes(options?.projectsPath || '/projects');
|
||||
// Get configured paths with defaults
|
||||
const tmpPath = options?.tmpPath || '/tmp';
|
||||
const projectsPath = options?.projectsPath || '/projects';
|
||||
|
||||
// Allow writes to tmp directory and its subdirectories
|
||||
if (absolutePath.startsWith(tmpPath + '/') || absolutePath === tmpPath) {
|
||||
@@ -58,7 +56,7 @@ export function isWriteAllowed(
|
||||
|
||||
// If we have a current working directory, allow writes within that directory tree
|
||||
if (cwd) {
|
||||
const normalizedCwd = normalizeToForwardSlashes(normalize(cwd));
|
||||
const normalizedCwd = normalize(cwd);
|
||||
if (absolutePath.startsWith(normalizedCwd + '/') || absolutePath === normalizedCwd) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { join } from "path-browserify";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand } from "../commands/ShellCommand";
|
||||
import { Git } from "../git";
|
||||
import { stripAnsiCodes } from "../ansiToHtml";
|
||||
import type { NostrSigner } from "@nostrify/nostrify";
|
||||
import { isAbsolutePath } from "../pathUtils";
|
||||
import {
|
||||
CatCommand,
|
||||
CdCommand,
|
||||
@@ -435,7 +433,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
*/
|
||||
private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise<void> {
|
||||
// Resolve the file path relative to current working directory
|
||||
const filePath = isAbsolutePath(redirectFile) ? redirectFile : join(this.cwd, redirectFile);
|
||||
const filePath = redirectFile.startsWith('/') ? redirectFile : `${this.cwd}/${redirectFile}`;
|
||||
|
||||
if (redirectType === '>') {
|
||||
// Overwrite the file
|
||||
|
||||
Reference in new issue
Block a user