Skip to content

Commit

Permalink
Merge pull request #55 from Wave-Play/canary
Browse files Browse the repository at this point in the history
Additional fixes for Windows
  • Loading branch information
Pkmmte authored Jan 15, 2023
2 parents 3f1be59 + 942a256 commit 1eda5f3
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 20 deletions.
5 changes: 5 additions & 0 deletions .changeset/fuzzy-experts-allow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@waveplay/pilot': patch
---

fix(cli): custom command options should be delegated when using npm or pnpm
5 changes: 5 additions & 0 deletions .changeset/silver-days-do.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@waveplay/pilot': patch
---

fix: use correct slashes when building on windows
5 changes: 5 additions & 0 deletions .changeset/strong-moles-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@waveplay/pilot': patch
---

fix(api): use correct platform slashes in get-props
5 changes: 5 additions & 0 deletions .changeset/tasty-ladybugs-develop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@waveplay/pilot': patch
---

fix(cli): exclude pnpm from .cmd suffix on windows
5 changes: 5 additions & 0 deletions .changeset/unlucky-bees-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@waveplay/pilot': patch
---

fix: use correct absolute path protocol when importing config files on windows
10 changes: 7 additions & 3 deletions packages/pilot/src/api/get-props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ import fs from 'fs-extra'
// Namespace used for validating prop cache
const NS = '__pilot'

// Make sure to use the correct slash for the platform
const IS_WINDOWS = /^win/.test(process.platform);
const SLASH = IS_WINDOWS ? '\\' : '/';

// Root level directory of the project
const ROOT_DIR = process.cwd() + '/.pilot'
const ROOT_DIR = process.cwd() + SLASH + '.pilot'

// Create router using generated routes
const router = createRouter()
Expand Down Expand Up @@ -121,9 +125,9 @@ async function getCache(context: GetPropsContext, pilot: Pilot): Promise<Cache>

// Create cache entry with locale prefix and without query params
const cleanPath = path.includes('?') ? path.split('?')[0] : path
const localePrefix = locale ? '/' + locale : ''
const localePrefix = locale ? SLASH + locale : ''
const cache: Cache = {
file: ROOT_DIR + `/cache/static${localePrefix}${cleanPath}.json`,
file: ROOT_DIR + `${SLASH}cache${SLASH}static${localePrefix}${cleanPath}.json`,
status: 'MISS'
}

Expand Down
25 changes: 20 additions & 5 deletions packages/pilot/src/cli/commands/build/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,36 @@ import type { NextConfig } from 'next';
import type { Logger } from 'pino';
import type { BuildManifest } from '../../types';
import type { Config, PilotConfig } from '../../../client/types';
import { pathToFileURL } from 'node:url'

const GENERATED_FILE = 'config.js';

export const readConfig = async <T = any>(logger: Logger, file: string): Promise<T> => {
try {
// Try to read the config file (fallback to .mjs if .js does not exist)
let filePath = path.join(process.cwd(), file);
if (filePath.endsWith('.js') && !(await fs.pathExists(filePath))) {
let fileName = file
let filePath = path.join(process.cwd(), fileName);

// Ensure file format is resolved absolutely by all platforms correctly
filePath = pathToFileURL(filePath).toString();

// Fallback to .mjs if .js does not exist
if (fileName.endsWith('.js') && !(await fs.pathExists(filePath))) {
fileName = fileName.replace('.js', '.mjs')
filePath = filePath.replace('.js', '.mjs')
}

const config = await import(filePath);
return typeof config?.default === 'function' ? config.default(PHASE_PRODUCTION_BUILD) : config?.default;
const data = typeof config?.default === 'function' ? config.default(PHASE_PRODUCTION_BUILD) : config?.default;
if (data) {
logger.debug(`[PilotJS] Found config file: ${fileName}`)
}

return data;
} catch (e) {
logger.debug(`[PilotJS] Could not read config file: ${file}`);
if (logger.level === 'debug') {
logger.warn(e.message)
}
logger.debug(`[PilotJS] Could not read config file: ${file} (or .mjs)`);
return {} as T;
}
}
Expand Down
15 changes: 11 additions & 4 deletions packages/pilot/src/cli/commands/build/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,22 @@ const DIR_DELTA_DEPTH = packageManager === 'pnpm' ? 8 : 5;
// Name of the file that will be generated
const GENERATED_FILE = 'pages.js';

// Make sure to use the correct slash for the platform
const IS_WINDOWS = /^win/.test(process.platform);
const SLASH = IS_WINDOWS ? '\\' : '/';

export async function buildPages(logger: Logger, config?: Config) {
// Try scanning the default /pages directory first
let pages: PageRoute[] = [];
try {
pages = await readAllPages('/pages', logger, config);
pages = await readAllPages(SLASH + 'pages', logger, config);
} catch {}

// If none were found, try scanning the /src/pages directory instead
// Both of these directions are supported by NextJS, so we should support them too
if (!pages.length) {
logger.debug('[PilotJS] Could not find "/pages" directory, trying "/src/pages"');
pages = await readAllPages('/src/pages', logger, config);
pages = await readAllPages(`${SLASH}src${SLASH}pages`, logger, config);
}

// Generate file containing info for all pages, including static imports
Expand Down Expand Up @@ -106,7 +110,10 @@ const readPage = async (file: klaw.Item, readDirectory: string, logger: Logger):
let path = file.path.replace(readDirectory, '');

// Create duplicate with file extension removed for comparison purposes
const cleanPath = path.substring(0, path.lastIndexOf('.'));
let cleanPath = path.substring(0, path.lastIndexOf('.'));

// From here on out, we only need forwardslashes (Windows uses backslashes)
cleanPath = cleanPath.replace(/\\/g, '/');

// _document is very web-specific, so we don't want to include it
if (cleanPath === '/_document') {
Expand Down Expand Up @@ -143,7 +150,7 @@ const readPage = async (file: klaw.Item, readDirectory: string, logger: Logger):
// Add page stats to the list
return {
getPropsType: getPropsType,
importPath: importPath.substring(0, importPath.lastIndexOf('.')),
importPath: importPath.substring(0, importPath.lastIndexOf('.')).replace(/\\/g, '/'),
path: route
};
};
Expand Down
31 changes: 23 additions & 8 deletions packages/pilot/src/cli/commands/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ export async function action(options: OptionValues) {
const pkgManager = getPkgManager()
logger.debug(`[PilotJS] Using package manager: ${pkgManager}`)

// Whether or not this package manager requires -- to pass arguments
const isNpmBased = pkgManager === 'npm' || pkgManager === 'pnpm'

// Check if ngrok is installed
let useTunnel = options.tunnel
let localtunnel
Expand Down Expand Up @@ -97,19 +100,23 @@ export async function action(options: OptionValues) {

// Start Next.js process
const nextArgs = config.commands?.devWeb?.split(' ') ?? ['next', 'dev']
if (pkgManager === 'npm' || pkgManager === 'pnpm') {
nextArgs.splice(0, 0, 'exec')
}
if (!nextArgs.includes('-p') && !nextArgs.includes('--port')) {
if (pkgManager === 'npm' || pkgManager === 'pnpm') {
nextArgs.push('--')
}
nextArgs.push('-p', port.toString())
}
if (options.hostname) {
nextArgs.push('-H', options.hostname)
}

// Check if args include option flags
// Inserts -- before options to make sure they're being passed correctly
if (isNpmBased) {
nextArgs.splice(0, 0, 'exec')
const optionsIndex = nextArgs.findIndex((arg) => arg.startsWith('-'))
if (optionsIndex !== -1) {
nextArgs.splice(optionsIndex, 0, '--')
}
}

logger.debug(`[PilotJS] Executing: ${cmd(pkgManager)} ${nextArgs.join(' ')}`)
spawn(cmd(pkgManager), nextArgs, {
stdio: 'inherit'
Expand All @@ -133,8 +140,16 @@ export async function action(options: OptionValues) {

// Start native process
const nativeArgs = config.commands?.devNative?.split(' ') ?? ['expo', 'start']
if (pkgManager === 'npm' || pkgManager === 'pnpm') {

// Check if args include option flags
// Inserts -- before options to make sure they're being passed correctly
if (isNpmBased) {
nativeArgs.splice(0, 0, 'exec')

const optionsIndex = nativeArgs.findIndex((arg) => arg.startsWith('-'))
if (optionsIndex !== -1) {
nativeArgs.splice(optionsIndex, 0, '--')
}
}

logger.debug(`[PilotJS] Executing: ${cmd(pkgManager)} ${nativeArgs.join(' ')}`)
Expand All @@ -148,7 +163,7 @@ type PackageManager = 'npm' | 'pnpm' | 'yarn'
const IS_WINDOWS = /^win/.test(process.platform)

function cmd(packageManager: PackageManager): string {
return IS_WINDOWS ? `${packageManager}.cmd` : packageManager
return IS_WINDOWS && packageManager !== 'pnpm' ? `${packageManager}.cmd` : packageManager
}

export function getPkgManager(): PackageManager {
Expand Down

1 comment on commit 1eda5f3

@vercel
Copy link

@vercel vercel bot commented on 1eda5f3 Jan 15, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.