Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow overriding base url through baseUrl option #343

Merged
merged 6 commits into from
May 6, 2021
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Added

- Allow overriding base url through `baseUrl` option ([#343](https://github.com/marp-team/marp-cli/pull/343))

## v1.0.1 - 2021-04-27

### Changed
Expand Down
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { jsWithBabel } = require('ts-jest/presets')

const esModules = ['ansi-regex', 'file-url', 'strip-ansi']
const esModules = ['ansi-regex', 'strip-ansi']

module.exports = {
collectCoverageFrom: ['src/**/*.ts', 'src/**/*.tsx'],
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jest": "^24.3.6",
"file-url": "^4.0.0",
"get-stdin": "^9.0.0",
"image-size": "^1.0.0",
"is-wsl": "^2.2.0",
Expand Down Expand Up @@ -150,6 +149,7 @@
"yargs": "^16.2.0"
},
"resolutions": {
"normalize-package-data": "^3.0.2",
"pug": "^3.0.2",
"pug-runtime": "^3.0.1"
},
Expand Down
2 changes: 2 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Overwrite<T, U> = Omit<T, Extract<keyof T, keyof U>> & U
interface IMarpCLIArguments {
_?: string[]
allowLocalFiles?: boolean
baseUrl?: string
bespoke?: {
osc?: boolean
progress?: boolean
Expand Down Expand Up @@ -183,6 +184,7 @@ export class MarpCLIConfig {
type,
allowLocalFiles:
this.args.allowLocalFiles ?? this.conf.allowLocalFiles ?? false,
baseUrl: this.args.baseUrl ?? this.conf.baseUrl,
engine: this.engine.klass,
globalDirectives: {
description: this.args.description ?? this.conf.description,
Expand Down
22 changes: 14 additions & 8 deletions src/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const mimeTypes = {

export interface ConverterOption {
allowLocalFiles: boolean
baseUrl?: string
engine: Engine
globalDirectives: { theme?: string } & Partial<TemplateMeta>
html?: MarpOptions['html']
Expand Down Expand Up @@ -104,13 +105,21 @@ export class Converter {
}: { fallbackToPrintableTemplate?: boolean } = {}
): Promise<TemplateResult> {
const { lang, globalDirectives, type } = this.options

const isFile = (f: File | undefined): f is File =>
!!f && f.type === FileType.File

const resolveBase = async (f: File) =>
isChromeInWSLHost(generatePuppeteerLaunchArgs().executablePath)
? `file:${await resolveWSLPathToHost(f.absolutePath)}`
: f.absoluteFileScheme
const resolveBase = async (f?: File) => {
if (this.options.baseUrl) return this.options.baseUrl

if (isFile(f) && type !== ConvertType.html) {
return isChromeInWSLHost(generatePuppeteerLaunchArgs().executablePath)
? `file:${await resolveWSLPathToHost(f.absolutePath)}`
: f.absoluteFileScheme
}

return undefined
}

let additionals = ''

Expand All @@ -128,10 +137,7 @@ export class Converter {
return await template({
...(this.options.templateOption || {}),
lang,
base:
isFile(file) && type !== ConvertType.html
? await resolveBase(file)
: undefined,
base: await resolveBase(file),
notifyWS:
isFile(file) && this.options.watch && type === ConvertType.html
? await notifier.register(file.absolutePath)
Expand Down
7 changes: 1 addition & 6 deletions src/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import os from 'os'
import path from 'path'
import * as url from 'url'
import { promisify } from 'util'
import fileUrl from 'file-url'
import getStdin from 'get-stdin'
import globby, { GlobbyOptions } from 'globby'
import mkdirp from 'mkdirp'
Expand Down Expand Up @@ -44,11 +43,7 @@ export class File {
}

get absoluteFileScheme(): string {
if (url.pathToFileURL)
return url.pathToFileURL(this.absolutePath).toString()

// Fallback for Node < v10.12.0
return fileUrl(this.absolutePath)
return url.pathToFileURL(this.absolutePath).toString()
}

convert(output: string | false | undefined, opts: FileConvertOption): File {
Expand Down
9 changes: 7 additions & 2 deletions src/marp-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ enum OptionGroup {
}

export interface MarpCLIInternalOptions {
baseUrl?: string
stdin: boolean
throwErrorAlways: boolean
}

export type MarpCLIAPIOptions = Pick<MarpCLIInternalOptions, 'baseUrl'>

export type ObservationHelper = { stop: () => void }

const resolversForObservation: Array<(helper: ObservationHelper) => void> = []
Expand All @@ -38,7 +41,7 @@ Usage:

export const marpCli = async (
argv: string[],
{ stdin: defaultStdin, throwErrorAlways }: MarpCLIInternalOptions
{ baseUrl, stdin: defaultStdin, throwErrorAlways }: MarpCLIInternalOptions
): Promise<number> => {
let server: Server | undefined
let watcherInstance: Watcher | undefined
Expand Down Expand Up @@ -215,6 +218,7 @@ export const marpCli = async (
})

const args = {
baseUrl, // It's not intended using by the consumer so can't set through CLI arguments
...program.argv,
_: program.argv._.map((v) => v.toString()),
}
Expand Down Expand Up @@ -385,10 +389,11 @@ export const waitForObservation = () =>
resolversForObservation.push(res)
})

export const apiInterface = (argv: string[] = []) => {
export const apiInterface = (argv: string[], opts: MarpCLIAPIOptions = {}) => {
resetExecutablePath()

return marpCli(argv, {
...opts,
stdin: false,
throwErrorAlways: true,
})
Expand Down
11 changes: 11 additions & 0 deletions test/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,17 @@ describe('Converter', () => {
)
})
})

describe('with baseUrl option', () => {
it('overrides <base> href attribute to specific URL in every kind of conversion', async () => {
for (const type of Object.values(ConvertType)) {
const converter = instance({ type, baseUrl: 'https://example.com/' })
const { result } = await converter.convert(md, dummyFile)

expect(result).toContain('<base href="https://example.com/">')
}
})
})
})

describe('#convertFile', () => {
Expand Down
3 changes: 2 additions & 1 deletion test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ afterEach(() => {
describe('Marp CLI API interface', () => {
it('runs Marp CLI with specific options', async () => {
const marpCliSpy = jest.spyOn(marpCli, 'marpCli').mockResolvedValue(0)
const ret = await api([])
const ret = await api([], { baseUrl: 'https://example.com/' })

expect(ret).toBe(0)
expect(marpCliSpy).toHaveBeenCalled()

const opts: marpCli.MarpCLIInternalOptions = marpCliSpy.mock.calls[0][1]

expect(opts.baseUrl).toBe('https://example.com/')
expect(opts.stdin).toBe(false)
expect(opts.throwErrorAlways).toBe(true)
})
Expand Down
Loading