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

feat: Make UI library optional #228

Merged
merged 10 commits into from
Sep 23, 2022
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
2 changes: 1 addition & 1 deletion cli/create-plasmo/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-plasmo",
"version": "0.54.5",
"version": "0.55.0-alpha.0",
"description": "Create Plasmo Framework Browser Extension",
"main": "dist/index.js",
"bin": "dist/index.js",
Expand Down
2 changes: 1 addition & 1 deletion cli/plasmo/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "plasmo",
"version": "0.54.5",
"version": "0.55.0-alpha.0",
"description": "The Plasmo Platform CLI",
"main": "dist/index.js",
"types": "dist/type.d.ts",
Expand Down
4 changes: 4 additions & 0 deletions cli/plasmo/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ async function dev() {
throw err
}

if (event === undefined) {
return
}

if (event.type === "buildSuccess") {
iLog(`✨ Extension reloaded in ${event.buildTime}ms!`)
await plasmoManifest.postBuild()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ const getPrioritizedIconPaths = (iconNames = baseIconNames) =>
// Use this to cache the path resolving result
const iconState = {
baseIconPaths: [] as string[],
baseIconHash: null as string,
devProvidedIcons: {} as Record<string, string[]>
}

Expand Down
36 changes: 18 additions & 18 deletions cli/plasmo/src/features/extension-devtools/load-env-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { join } from "path"

import { eLog, iLog } from "@plasmo/utils"

export type Env = Record<string, string>
export type Env = Record<string, string | undefined>
export type LoadedEnvFiles = Array<{
path: string
contents: string
Expand All @@ -27,7 +27,7 @@ export class PlasmoPublicEnv {
},
{
NODE_ENV: process.env.NODE_ENV
}
} as Env
)
}

Expand Down Expand Up @@ -72,31 +72,31 @@ export async function loadEnvConfig(dir: string) {
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
mode !== "test" && `.env.local`,
mode !== "test" ? `.env.local` : "",
`.env.${mode}`,
".env"
]
.filter(Boolean)
.filter((s) => !!s)
.map((envFile) => [envFile, join(dir, envFile)])
.filter(
([, filePath]) => existsSync(filePath) && statSync(filePath).isFile()
)

const envFiles = await Promise.all(
dotenvFilePaths.map(async ([envFile, filePath]) => {
try {
const contents = await readFile(filePath, "utf8")
return {
path: envFile,
contents
}
} catch (err: any) {
if (err.code !== "ENOENT") {
eLog(`Failed to load env from ${envFile}`, err)
}
const envFiles: LoadedEnvFiles = []

for await (const [envFile, filePath] of dotenvFilePaths) {
try {
const contents = await readFile(filePath, "utf8")
envFiles.push({
path: envFile,
contents
})
} catch (err: any) {
if (err.code !== "ENOENT") {
eLog(`Failed to load env from ${envFile}`, err)
}
})
)
}
}

const combinedEnv = processEnv(envFiles, dir)

Expand Down
14 changes: 8 additions & 6 deletions cli/plasmo/src/features/extension-devtools/package-file.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sentenceCase } from "change-case"
import { userInfo } from "os"
import getPackageJson from "package-json"
import getPackageJson, { AbbreviatedVersion } from "package-json"

import type { ExtensionManifestV3 } from "@plasmo/constants"

Expand All @@ -9,7 +9,7 @@ import type { PackageManagerInfo } from "~features/helpers/package-manager"
export const generatePackage = ({
name = "plasmo-extension",
version = "0.0.0",
packageManager = null as PackageManagerInfo
packageManager = {} as PackageManagerInfo
}) => {
const baseData = {
name,
Expand All @@ -18,7 +18,7 @@ export const generatePackage = ({
description: "A basic Plasmo extension.",
author: userInfo().username,

packageManager: "",
packageManager: undefined as string | undefined,
scripts: {
dev: "plasmo dev",
build: "plasmo build"
Expand Down Expand Up @@ -60,14 +60,16 @@ export type PackageJSON = ReturnType<typeof generatePackage> & {
export const resolveWorkspaceToLatestSemver = async (
dependencies: Record<string, string>
) => {
const output = {}
const output = {} as Record<string, string>

await Promise.all(
Object.entries(dependencies).map(async ([key, value]) => {
if (key === "plasmo") {
output[key] = process.env.APP_VERSION
output[key] = process.env.APP_VERSION as string
} else if (value === "workspace:*") {
const remotePackageData = await getPackageJson(key)
const remotePackageData = (await getPackageJson(key, {
version: "latest"
})) as unknown as AbbreviatedVersion
output[key] = remotePackageData.version
} else {
output[key] = value
Expand Down
12 changes: 6 additions & 6 deletions cli/plasmo/src/features/extension-devtools/project-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ const getWatchReasonMap = (paths: string[], reason: WatchReason) =>
paths.reduce((output, path) => {
output[path] = reason
return output
}, {}) as Record<string, WatchReason>
}, {} as Record<string, WatchReason>)

export const getProjectPath = (
{ sourceDirectory, packageFilePath, assetsDirectory }: CommonPath,
uiExt: SupportedUIExt,
browserTarget: string
browserTarget: string,
uiExt: SupportedUIExt
) => {
const getIndexList = (moduleName: string, ext = ".ts") => [
resolve(sourceDirectory, `${moduleName}.${browserTarget}${ext}`),
Expand Down Expand Up @@ -75,6 +75,8 @@ export const getProjectPath = (
const backgroundIndexList = getIndexList("background")

const watchPathReasonMap = {
[packageFilePath]: WatchReason.PackageJson,

...getWatchReasonMap(envFileList, WatchReason.EnvFile),
...getWatchReasonMap(contentIndexList, WatchReason.ContentsIndex),
...getWatchReasonMap(backgroundIndexList, WatchReason.BackgroundIndex),
Expand All @@ -87,9 +89,7 @@ export const getProjectPath = (
...getWatchReasonMap(popupHtmlList, WatchReason.PopupHtml),
...getWatchReasonMap(optionsHtmlList, WatchReason.OptionsHtml),
...getWatchReasonMap(devtoolsHtmlList, WatchReason.DevtoolsHtml),
...getWatchReasonMap(newtabHtmlList, WatchReason.NewtabHtml),

[packageFilePath]: WatchReason.PackageJson
...getWatchReasonMap(newtabHtmlList, WatchReason.NewtabHtml)
}

const contentsDirectory = resolve(sourceDirectory, "contents")
Expand Down
2 changes: 1 addition & 1 deletion cli/plasmo/src/features/extra/next-new-tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { CommonPath } from "~features/extension-devtools/common-path"
import type { PackageJSON } from "~features/extension-devtools/package-file"
import { stripUnderscore } from "~features/extension-devtools/strip-underscore"

export const generateNewTabManifest = (packageData = null as PackageJSON) => ({
export const generateNewTabManifest = (packageData: PackageJSON) => ({
name: sentenceCase(packageData.name),
description: packageData.description,
version: packageData.version,
Expand Down
2 changes: 1 addition & 1 deletion cli/plasmo/src/features/helpers/package-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export type PackageManagerInfo = {

async function getPMInfo(name: PackageManager): Promise<PackageManagerInfo> {
const data = await spawnAsync(name, ["--version"])
const version = semver.valid(data.stdout.trim())
const version = semver.valid(data.stdout.trim()) || undefined
return { name, version }
}

Expand Down
4 changes: 2 additions & 2 deletions cli/plasmo/src/features/helpers/traverse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ const defaultTransformer = (target: any) =>
export const definedTraverse = (
target: any,
transformer = defaultTransformer
) => {
): any => {
if (Array.isArray(target)) {
return target
.map((item) => definedTraverse(item, transformer))
.filter((i) => typeof i !== "undefined")
} else if (typeof target === "object") {
const result = {}
const result = {} as any

for (const key in target) {
if (target.hasOwnProperty(key)) {
Expand Down
46 changes: 28 additions & 18 deletions cli/plasmo/src/features/manifest-factory/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type {
ManifestContentScript,
ManifestPermission
} from "@plasmo/constants"
import { vLog } from "@plasmo/utils"
import { assertUnreachable, vLog } from "@plasmo/utils"

import type { CommonPath } from "~features/extension-devtools/common-path"
import { extractContentScriptMetadata } from "~features/extension-devtools/content-script"
Expand Down Expand Up @@ -58,7 +58,7 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
return this.#browser
}

envConfig: EnvConfig
envConfig!: EnvConfig
public get publicEnv() {
return this.envConfig.plasmoPublicEnv
}
Expand All @@ -68,7 +68,7 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
return this.#commonPath
}

#projectPath: ProjectPath
#projectPath!: ProjectPath
public get projectPath(): ProjectPath {
return this.#projectPath
}
Expand All @@ -78,18 +78,18 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
return this.#templatePath
}

#uiExt: SupportedUIExt
#uiExt: SupportedUIExt = ".ts"
#extSet = new Set([".ts"])

#hasher = createHasher({ trim: true, sort: true })

#hash: string
#prevHash: string
#hash = ""
#prevHash = ""

protected data: Partial<T>
protected overideManifest: Partial<T> = {}

protected packageData: PackageJSON
protected packageData!: PackageJSON
protected contentScriptMap: Map<string, ManifestContentScript> = new Map()

protected copyQueue: Array<[string, string]> = []
Expand All @@ -115,13 +115,13 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
return this.packageData.devDependencies
}

#cachedUILibrary: UILibrary
#cachedUILibrary?: UILibrary
get uiLibrary() {
return this.#cachedUILibrary
}

get staticScaffoldPath() {
return resolve(this.templatePath.staticTemplatePath, this.uiLibrary.path)
return resolve(this.templatePath.staticTemplatePath, this.uiLibrary!.path)
}

protected constructor(commonPath: CommonPath, browser: string) {
Expand All @@ -143,6 +143,9 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {

async updatePackageData() {
this.packageData = await readJson(this.commonPath.packageFilePath)
if (!this.packageData) {
throw new Error("Invalid package.json")
}

this.data.version = this.packageData.version
this.data.author = this.packageData.author
Expand All @@ -156,7 +159,7 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
}

this.data.permissions = autoPermissionList.filter(
(p) => `@plasmohq/${p}` in this.packageData.dependencies
(p) => `@plasmohq/${p}` in (this.packageData?.dependencies || {})
)

if (this.data.permissions.length === 0) {
Expand All @@ -181,22 +184,28 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
this.#scaffolder.mountExt = ".ts"
break
case "react":
default:
this.#uiExt = ".tsx"
this.#scaffolder.mountExt = ".tsx"
break
case "vanilla":
this.#uiExt = ".ts"
this.#scaffolder.mountExt = ".ts"
break
default:
assertUnreachable(this.#cachedUILibrary.name)
}

this.#extSet.add(this.#uiExt)

this.#projectPath = getProjectPath(
this.commonPath,
this.#uiExt,
this.#browser
this.#browser,
this.#uiExt
)
}

abstract togglePopup: (enable?: boolean) => this
abstract toggleBackground: (path: string, enable?: boolean) => boolean
abstract toggleBackground: (path?: string, enable?: boolean) => boolean

toggleOptions = (enable = false) => {
if (enable) {
Expand Down Expand Up @@ -236,7 +245,7 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
return this
}

toggleContentScript = async (path: string, enable = false) => {
toggleContentScript = async (path?: string, enable = false) => {
if (path === undefined) {
return false
}
Expand Down Expand Up @@ -271,7 +280,10 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
path
)

if (extname(manifestScriptPath) === this.#uiExt) {
if (
this.uiLibrary?.name !== "vanilla" &&
extname(manifestScriptPath) === this.#uiExt
) {
// copy the contents and change the manifest path
const modulePath = join("lab", manifestScriptPath).replace(
/(^src)[\\/]/,
Expand All @@ -283,8 +295,6 @@ export abstract class BaseFactory<T extends ExtensionManifest = any> {
this.commonPath.dotPlasmoDirectory,
await this.#scaffolder.createContentScriptMount(parsedModulePath)
)

// vLog(manifestScriptPath)
}

// Resolve css file paths
Expand Down
Loading