Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions electron/handlers/devServers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import { RUNTIME_PATHS } from '../lib/runtimePaths';
import { commandNeedsShell, sameFilesystemPath } from '../lib/platform';
import { createKeyedQueue } from '../lib/serialQueue';
import type { DevServer } from '../lib/mainTypes';
import { SHORT_COMMAND, errorMessage, isWin, parseOptionalString, parseRecord, readJson, toPosix } from '../lib/mainHelpers';
import { SHORT_COMMAND, errorMessage, parseOptionalString, parseRecord, readJson, toPosix } from '../lib/mainHelpers';
import { localAstroBin } from '../project/projectFiles';
import { findFreePort, nodeCliCommand, resolveNodeBin, run, spawnAstroServer, stopProcessTree } from '../lib/nodeTools';
import { previewSupportFiles, renderComponentPreviewPage } from '../previewServer/componentPreview';
import { probeUrl } from '../preview/devProbe';
Expand Down Expand Up @@ -645,21 +646,20 @@ export class DevServers {
);
}

const binName = isWin ? 'astro.cmd' : 'astro';
const localBin = path.join(projectPath, 'node_modules', '.bin', binName);
if (!fs.existsSync(localBin)) {
if (!fs.existsSync(localAstroBin(projectPath))) {
// Dependencies missing or incomplete — install with the right PM first.
await installDependencies(this.host, projectPath);
assertActive();
this.host.send('progress', PROGRESS_CLEARED);
if (!fs.existsSync(localBin)) {
if (!fs.existsSync(localAstroBin(projectPath))) {
throw new Error(
'astro is not installed in this project (no node_modules/.bin/astro after install). ' + 'Is astro listed in package.json dependencies?',
);
}
}

return localBin;
// Looked up again: the install is what may have made it, and under Bun it is `astro.exe`, not `astro.cmd`.
return localAstroBin(projectPath);
}

private async failureDetail(projectPath: string, localBin: string, startedAtMs: number): Promise<string> {
Expand Down
4 changes: 2 additions & 2 deletions electron/handlers/emdashInstall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {
type EmDashPreviewState,
} from '../../shared/properties/emdashInstall';
import { PNPM_TOLERATE_IGNORED_BUILDS, detectPackageManager } from '../project/packageManager';
import type { PackageManager } from '../../shared/properties/packageManager';
import { packageManagerProgram, type PackageManager } from '../../shared/properties/packageManager';
import { RUN_CANCELLED, runCreateCommand } from '../project/starter';
import { ensureToolPath, git } from '../lib/nodeTools';
import { commit } from '../git/gitSnapshot';
Expand Down Expand Up @@ -296,7 +296,7 @@ async function install(
const options = { signal: context.controller.signal, timeoutMs: EMDASH_INSTALL_LIMITS.runMsMax };
try {
context.onLog(`> ${plan.command}\n\n`);
await context.deps.runCommand(windows ? `${plan.manager}.cmd` : plan.manager, addArguments(plan.manager), root, context.onLog, options);
await context.deps.runCommand(packageManagerProgram(plan.manager, { windows }), addArguments(plan.manager), root, context.onLog, options);
writeLiveConfigIfAbsent(root);
appendIgnoreLines(root);
config = registerInAstroConfig(root, context.deps.verifyConfig);
Expand Down
6 changes: 2 additions & 4 deletions electron/handlers/previewHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@
// its render check, and stopping it.

import { MAIN_LIMITS } from '../lib/mainLimits';
import * as path from 'path';
import * as fs from 'fs';
import * as previewWorktree from '../preview/previewWorktree';
import { checkPreviewRender } from '../preview/previewCheck';
import { isWin } from '../lib/mainHelpers';
import { findFreePort, git, spawnAstroServer } from '../lib/nodeTools';
import { localAstroBin } from '../project/projectFiles';
import { serverAlive } from '../preview/devServerChecks';
import { previewServers, stopPreview } from '../preview/previewServers';
import type { MainHost } from './mainHost';
Expand All @@ -30,8 +29,7 @@ function registerPreviewAtCommitHandler({ ipcMain }: Pick<MainHost, 'ipcMain'>):
return { url: running.url, ref, reused: true as const };
}

const bin = isWin ? 'astro.cmd' : 'astro';
const localBin = path.join(projectPath, 'node_modules', '.bin', bin);
const localBin = localAstroBin(projectPath);
if (!fs.existsSync(localBin)) {
throw new Error('This project’s packages aren’t installed, so an older version can’t be shown. ' + 'Install them and try again.');
}
Expand Down
9 changes: 5 additions & 4 deletions electron/handlers/projectHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { isWin } from '../lib/mainHelpers';
import { ensureToolPath, run } from '../lib/nodeTools';
import { isAstroProject } from '../project/projectFiles';
import { detectPackageManager, installArguments } from '../project/packageManager';
import { packageManagerLabel, type PackageManager } from '../../shared/properties/packageManager';
import { packageManagerLabel, packageManagerProgram, type PackageManager } from '../../shared/properties/packageManager';
import type { MainHost } from './mainHost';
import { translateMain } from '../lib/mainLocale';
import { folderOpenChoice, siteFolderChoice } from '../project/folderOpen';
Expand Down Expand Up @@ -115,6 +115,7 @@ function registerProjectCreateStarterHandlers({ ipcMain, send }: Pick<MainHost,
starter,
parentPath,
name,
manager: packageManager,
onLog: (text) => send('create:log', text),
});
const label = STARTERS[starter]?.label ?? starter;
Expand Down Expand Up @@ -195,10 +196,10 @@ function normalizedRequest<Request extends { readonly sourcePath: string; readon
}

export async function installDependencies({ send }: Pick<MainHost, 'send'>, directory: string, pm: PackageManager = detectPackageManager(directory)) {
ensureToolPath(); // npm/pnpm/yarn are Node shims — same PATH problem as astro
ensureToolPath(); // npm/pnpm/yarn are Node shims, and bun lives in ~/.bun/bin — same PATH problem as astro
send('progress', { message: `Installing dependencies (${pm} install)…` });
try {
await run(isWin ? `${pm}.cmd` : pm, [...installArguments(pm)], directory, {
await run(packageManagerProgram(pm, { windows: isWin }), [...installArguments(pm)], directory, {
timeout: 10 * 60 * 1000,
shell: isWin,
});
Expand All @@ -214,7 +215,7 @@ export async function installDependencies({ send }: Pick<MainHost, 'send'>, dire
// any folder exists. On Windows a missing command fails without ENOENT, so any failure counts.
async function requirePackageManager(manager: PackageManager): Promise<void> {
try {
await run(isWin ? `${manager}.cmd` : manager, ['--version'], os.homedir());
await run(packageManagerProgram(manager, { windows: isWin }), ['--version'], os.homedir());
} catch {
throw new Error(`${packageManagerLabel(manager)} is not installed. Install it or choose npm.`);
}
Expand Down
7 changes: 2 additions & 5 deletions electron/handlers/thumbnails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,12 @@
// makes "the site as it is now" true for a project that was last edited
// somewhere else entirely. One instance per main process, made by main.ts.

import * as path from 'path';
import type { ChildProcess } from 'child_process';
import * as thumbs from '../project/thumbs';
import { sameFilesystemPath } from '../lib/platform';
import { createSerialQueue } from '../lib/serialQueue';
import { isWin } from '../lib/mainHelpers';
import { findFreePort, spawnAstroServer, stopProcessTree } from '../lib/nodeTools';
import { hasDependencies } from '../project/projectFiles';
import { hasDependencies, localAstroBin } from '../project/projectFiles';
import { serverAlive } from '../preview/devServerChecks';
import type { DevServers } from './devServers';
import type { MainHost } from './mainHost';
Expand Down Expand Up @@ -128,8 +126,7 @@ export function registerThumbnailHandlers({
// A dev server of the project's own, for one capture: the canvas's server is
// left alone, and the temporary one is stopped however the capture ends.
async function withTemporaryServer(projectPath: string, signal: AbortSignal, capture: (url: string) => ReturnType<typeof thumbs.capture>) {
const binName = isWin ? 'astro.cmd' : 'astro';
const localBin = path.join(projectPath, 'node_modules', '.bin', binName);
const localBin = localAstroBin(projectPath);
const port = await findFreePort(4400 + Math.floor(Math.random() * 200));
if (signal.aborted) {
return { ok: false as const, error: 'skipped' };
Expand Down
15 changes: 13 additions & 2 deletions electron/project/projectFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,24 @@ export function isAstroProject(directory: string): boolean {
return false;
}

// The project's own `astro` command in node_modules/.bin. On Windows npm, pnpm and Yarn leave `astro.cmd`, while Bun
// leaves `astro.exe` (and no .cmd), so whichever is there is the one; when neither is, the path npm would have made.
export function localAstroBin(projectPath: string): string {
const folder = path.join(projectPath, 'node_modules', '.bin');
if (!isWin) {
return path.join(folder, 'astro');
}
const executable = path.join(folder, 'astro.exe');
const shim = path.join(folder, 'astro.cmd');
return fs.existsSync(shim) || !fs.existsSync(executable) ? shim : executable;
}

// Astro has to be installed for a page to be rendered at all; without it the
// card can only offer to open the project. A workspace hoists node_modules to its root, so each parent counts.
export function hasDependencies(projectPath: string): boolean {
const binName = isWin ? 'astro.cmd' : 'astro';
return ancestorsOf(projectPath).some(
(directory) =>
fs.existsSync(path.join(directory, 'node_modules', '.bin', binName)) ||
fs.existsSync(localAstroBin(directory)) ||
fs.existsSync(path.join(directory, 'node_modules', 'astro', 'package.json')) ||
// Yarn Plug'n'Play keeps packages in a cache and no node_modules at all.
fs.existsSync(path.join(directory, '.pnp.cjs')),
Expand Down
65 changes: 60 additions & 5 deletions electron/project/starter.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawn } from 'child_process';

import { toRecord } from '../../shared/core/record';
import { commandNeedsShell } from '../lib/platform';
import { stopProcessTree } from '../lib/nodeTools';
import { packageManagerProgram, type PackageManager } from '../../shared/properties/packageManager';

// Starting a site from a starter.
//
Expand Down Expand Up @@ -51,6 +53,40 @@ export const RUN_CANCELLED = 'The command was cancelled.';
interface RunOptions {
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
/** Extra variables for this child only, laid over the app's own. */
readonly environment?: Readonly<Record<string, string>>;
}

// The Lumos scaffolder (create-lumos 0.3.9) links its skill folders with symlinks and, where Windows refuses them
// (no Developer Mode, no admin), falls back to `copyFile` on the folder, which always fails with EPERM. This preload
// makes that one fallback copy the folder instead. It touches nothing else: files go to the original `copyFile`.
const COPY_DIRECTORIES_SHIM = `const fsp = require('node:fs/promises');
const { statSync } = require('node:fs');
const original = fsp.copyFile;
fsp.copyFile = async function copyFile(source, target, mode) {
let directory = false;
try {
directory = statSync(source).isDirectory();
} catch {
directory = false;
}
if (directory) {
return fsp.cp(source, target, { recursive: true });
}
return original.call(this, source, target, mode);
};
require('node:module').syncBuiltinESMExports();
`;

// NODE_OPTIONS for a scaffolder run: the shim written to the temp folder, joined to whatever the person already set.
function scaffolderEnvironment(): Readonly<Record<string, string>> {
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'stacki-scaffold-'));
const file = path.join(folder, 'copyDirectories.cjs');
fs.writeFileSync(file, COPY_DIRECTORIES_SHIM, 'utf8');
// Forward slashes: a backslash escapes inside the quotes NODE_OPTIONS reads.
const preload = `--require "${file.replace(/\\/g, '/')}"`;
const existing = process.env['NODE_OPTIONS'];
return { NODE_OPTIONS: existing === undefined || existing.length === 0 ? preload : `${existing} ${preload}` };
}

const run = (cmd: string, args: readonly string[], cwd: string, onLog?: OnLog, options: RunOptions = {}): Promise<string> =>
Expand All @@ -69,6 +105,7 @@ const run = (cmd: string, args: readonly string[], cwd: string, onLog?: OnLog, o
FORCE_COLOR: '0',
NO_COLOR: '1',
CI: '1', // npm asks before downloading a scaffolder; nobody is here to answer
...options.environment,
},
});
} catch (error: unknown) {
Expand Down Expand Up @@ -134,16 +171,34 @@ interface CreateStarterOptions {
readonly name?: string;
/** The npm command to run, so a test can hand it one that needs no network. */
readonly npm?: string;
/** The manager the person chose. Bun runs the scaffolder itself (`bun create`); the others run it through npm, which every Node install has. */
readonly manager?: PackageManager;
readonly onLog?: OnLog;
}

// Bun has its own `create`, which downloads and runs the scaffolder. It takes no `--yes` and no `--` separator:
// what follows the folder name goes to the scaffolder as it is.
function scaffolderCommand(
manager: PackageManager | undefined,
create: string,
folder: string,
): { readonly label: string; readonly program: string; readonly args: readonly string[] } {
if (manager === 'bun') {
return { label: 'bun', program: packageManagerProgram('bun', { windows: isWin }), args: ['create', create, folder, '--no-install'] };
}
return { label: 'npm', program: packageManagerProgram('npm', { windows: isWin }), args: ['create', create, folder, '--yes', '--', '--no-install'] };
}

/**
* Runs a starter's scaffolder in `parentPath` to make `parentPath/name`.
* Installing what it needs and its first commit (`startSiteHistory`) are the
* caller's — this is the part that has to be right before anything is
* installed into it.
*/
async function createStarter({ starter = 'lumos', parentPath, name, npm, onLog }: CreateStarterOptions = {}): Promise<{ ok: boolean; projectPath: string }> {
async function createStarter({ starter = 'lumos', parentPath, name, npm, manager, onLog }: CreateStarterOptions = {}): Promise<{
ok: boolean;
projectPath: string;
}> {
const template = STARTERS[starter];
if (!template) {
throw new Error(`${starter} is not a starter this app knows.`);
Expand All @@ -153,9 +208,9 @@ async function createStarter({ starter = 'lumos', parentPath, name, npm, onLog }

// `--no-install`: the app installs afterwards, where a failure is an error
// the wizard can show rather than a line in a log that scrolled past.
const args = ['create', template.create, folder, '--yes', '--', '--no-install'];
onLog?.(`> npm create ${template.create} ${folder}\n\n`);
await run(npm || (isWin ? 'npm.cmd' : 'npm'), args, path.dirname(directory), onLog);
const command = scaffolderCommand(manager, template.create, folder);
onLog?.(`> ${command.label} create ${template.create} ${folder}\n\n`);
await run(npm || command.program, command.args, path.dirname(directory), onLog, { environment: scaffolderEnvironment() });

if (!fs.existsSync(path.join(directory, 'package.json'))) {
throw new Error('The starter finished but there is no package.json in it.');
Expand Down Expand Up @@ -231,4 +286,4 @@ function newSiteDirectory(parentPath: string | undefined, name: string | undefin
return directory;
}

export { createStarter, newSiteDirectory, run as runCreateCommand, startSiteHistory, STARTERS };
export { createStarter, newSiteDirectory, run as runCreateCommand, scaffolderEnvironment, startSiteHistory, STARTERS };
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/ar/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'إغلاق (تُحفظ التعديلات مباشرة)',
'workspace.code.title': 'الكود',
'workspace.notifications.copied': 'تم النسخ',
'workspace.notifications.copy': 'نسخ',
'workspace.notifications.dismiss': 'تجاهل الإشعار',
'workspace.notifications.label': 'الإشعارات',
'workspace.notifications.loadMore': 'تحميل المزيد ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/de/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'Schließen (Änderungen werden sofort gespeichert)',
'workspace.code.title': 'Code', // same
'workspace.notifications.copied': 'Kopiert',
'workspace.notifications.copy': 'Kopieren',
'workspace.notifications.dismiss': 'Benachrichtigung schließen',
'workspace.notifications.label': 'Benachrichtigungen',
'workspace.notifications.loadMore': 'Mehr laden ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/en/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { CatalogOf } from '../../../../core/i18n/catalog';
export const messages = {
'workspace.code.close': 'Close (edits are saved live)',
'workspace.code.title': 'Code',
'workspace.notifications.copied': 'Copied',
'workspace.notifications.copy': 'Copy',
'workspace.notifications.dismiss': 'Dismiss notification',
'workspace.notifications.label': 'Notifications',
'workspace.notifications.loadMore': 'Load more ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/es/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'Cerrar (los cambios se guardan al instante)',
'workspace.code.title': 'Código',
'workspace.notifications.copied': 'Copiado',
'workspace.notifications.copy': 'Copiar',
'workspace.notifications.dismiss': 'Descartar notificación',
'workspace.notifications.label': 'Notificaciones',
'workspace.notifications.loadMore': 'Cargar más ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/fr/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'Fermer (les modifications sont enregistrées en direct)',
'workspace.code.title': 'Code', // same
'workspace.notifications.copied': 'Copié',
'workspace.notifications.copy': 'Copier',
'workspace.notifications.dismiss': 'Ignorer la notification',
'workspace.notifications.label': 'Notifications', // same
'workspace.notifications.loadMore': 'Charger plus ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/he/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'סגירה (העריכות נשמרות מיד)',
'workspace.code.title': 'קוד',
'workspace.notifications.copied': 'הועתק',
'workspace.notifications.copy': 'העתקה',
'workspace.notifications.dismiss': 'סגירת ההתראה',
'workspace.notifications.label': 'התראות',
'workspace.notifications.loadMore': 'טעינת עוד ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/hi/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'बंद करें (बदलाव तुरंत सहेजे जाते हैं)',
'workspace.code.title': 'कोड',
'workspace.notifications.copied': 'कॉपी हो गया',
'workspace.notifications.copy': 'कॉपी करें',
'workspace.notifications.dismiss': 'सूचना हटाएँ',
'workspace.notifications.label': 'सूचनाएँ',
'workspace.notifications.loadMore': 'और लोड करें ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/id/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'Tutup (suntingan disimpan langsung)',
'workspace.code.title': 'Kode',
'workspace.notifications.copied': 'Disalin',
'workspace.notifications.copy': 'Salin',
'workspace.notifications.dismiss': 'Tutup notifikasi',
'workspace.notifications.label': 'Notifikasi',
'workspace.notifications.loadMore': 'Muat lebih banyak ({count})',
Expand Down
2 changes: 2 additions & 0 deletions shared/properties/i18n/messages/it/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace';
export const messages = {
'workspace.code.close': 'Chiudi (le modifiche vengono salvate in tempo reale)',
'workspace.code.title': 'Codice',
'workspace.notifications.copied': 'Copiato',
'workspace.notifications.copy': 'Copia',
'workspace.notifications.dismiss': 'Ignora notifica',
'workspace.notifications.label': 'Notifiche',
'workspace.notifications.loadMore': 'Carica altre ({count})',
Expand Down
Loading