Skip to content

Commit

Permalink
feat: init
Browse files Browse the repository at this point in the history
  • Loading branch information
sj817 committed Sep 7, 2024
0 parents commit 429dcf6
Show file tree
Hide file tree
Showing 11 changed files with 1,063 additions and 0 deletions.
39 changes: 39 additions & 0 deletions .github/workflows/release-please.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Release and Publish
on:
push:
branches:
- main
permissions:
contents: write
pull-requests: write
jobs:
release-please:
runs-on: ubuntu-latest
steps:
- uses: google-github-actions/release-please-action@v3
id: release
with:
release-type: node
default-branch: main
# Checkout
- uses: actions/checkout@v4
if: ${{ steps.release.outputs.release_created }}
# Setup node
- uses: actions/setup-node@v3
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
if: ${{ steps.release.outputs.release_created }}
# Install dependencies
- run: npm install
env:
NODE_AUTH_TOKEN: ${{ secrets.RELEASE }}
if: ${{ steps.release.outputs.release_created }}
# Build output
- run: npm run build:npm
if: ${{ steps.release.outputs.release_created }}
# Publish to npm
- run: npm run pub
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
if: ${{ steps.release.outputs.release_created }}
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

lib/
.vscode
data
node_modules/
pnpm-lock.yaml
package-lock.json

test.js
test.ts
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# @karinjs/puppeteer-core

## 描述

轻量·高效·易用的 Puppeteer 截图、视频生成工具。

## 安装

```bash
npm install @karinjs/puppeteer-core
```

## 使用方法

```javascript
import fs from 'fs'
import Puppeteer from '@karinjs/puppeteer-core'

// 使用示例
const chrome = new Puppeteer()

await chrome.init()
/** 计算耗时 */
console.time('截图耗时')
const image = await chrome.screenshot({
file: 'https://baidu.com/',
fullPage: true,
pageGotoParams: {
waitUntil: 'networkidle2',
},
type: 'png',
setViewport: {
deviceScaleFactor: 3,
},
})
console.timeEnd('截图耗时')

fs.writeFileSync('image.png', image)

process.exit(0)

```

## 许可证

本项目使用 [MIT License](https://opensource.org/licenses/MIT) 许可协议。详见 `LICENSE` 文件。

## 使用的第三方库

本项目使用了以下开源库:

- **puppeteer-core**: 用于浏览器自动化操作,使用了 [Apache License 2.0](https://github.com/puppeteer/puppeteer/blob/main/LICENSE) 许可协议。

## 贡献

欢迎贡献代码和建议!
3 changes: 3 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import neostandard from 'neostandard'

export default neostandard({ ts: true })
48 changes: 48 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "@karinjs/puppeteer-core",
"version": "0.0.1",
"description": "轻量·高效·易用的 Puppeteer 截图、视频生成工具",
"keywords": [
"puppeteer",
"screenshot",
"karin"
],
"homepage": "https://github.com/KarinJS/puppeteer-core",
"bugs": {
"url": "https://github.com/KarinJS/puppeteer-core/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/KarinJS/puppeteer-core.git"
},
"license": "MIT",
"author": "shijin",
"type": "module",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"files": [
"lib",
"package.json"
],
"scripts": {
"build": "tsc --project tsconfig.json && tsc-alias -p tsconfig.json && npm run fix:all",
"build:npm": "tsc --project tsconfig.json && tsc-alias -p tsconfig.json",
"fix:all": "eslint lib/**/*.js --fix && eslint lib/**/*.d.ts --fix",
"pub": "npm publish --access public",
"sort": "npx sort-package-json"
},
"dependencies": {
"@types/decompress": "^4.2.7",
"decompress": "4.2.1",
"log4js": "6.9.1",
"puppeteer-core": "22.10.0"
},
"devDependencies": {
"@types/node": "20.14.2",
"eslint": "latest",
"neostandard": "latest",
"sort-package-json": "2.10.0",
"tsc-alias": "1.8.10",
"typescript": "5.4.5"
}
}
173 changes: 173 additions & 0 deletions src/common/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import fs from 'fs'
import os from 'os'
import path from 'path'
import https from 'https'
import { promisify } from 'util'
import { pipeline } from 'stream'
import decompress from 'decompress'
import { fileURLToPath } from 'url'
import { exec as execCmd, ExecOptions } from 'child_process'
import { EventEmitter } from 'events'

const streamPipeline = promisify(pipeline)

export type Platform = 'linux64' | 'mac-arm64' | 'mac-x64' | 'win32' | 'win64'

export class Common extends EventEmitter {
/**
* 项目根目录
*/
dir: string
constructor () {
super()
this.dir = this.pathDir()
}

/**
* 判断路径是否存在
*/
exists (path: string): boolean {
return fs.existsSync(path)
}

/**
* 递归创建路径
* @param dirname - 文件夹路径
*/
mkdirs (dirname: string): boolean {
if (fs.existsSync(dirname)) return true
if (this.mkdirs(path.dirname(dirname))) {
fs.mkdirSync(dirname)
return true
}
return true
}

/**
* 获取项目根目录
* @returns 项目根目录
*/
pathDir (): string {
if (process.env.KarinPuppeteerDir) return process.env.KarinPuppeteerDir
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const dir = path.join(__dirname, '../..').replace(/\\/g, '/')
return dir
}

/**
* 获取系统版本
* @returns linux64、mac-arm64、mac-x64、win32、win64
*/
Platform (): Platform {
switch (process.platform) {
case 'linux': {
return 'linux64'
}
case 'darwin': {
const platform = os.arch() === 'arm64' ? 'mac-arm64' : 'mac-x64'
return platform
}
case 'win32': {
const platform = os.arch() === 'x64' ? 'win64' : 'win32'
return platform
}
default: {
throw new Error('不支持的系统')
}
}
}

/**
* 网络探针
* @param url - 探测地址
* @param timeout - 超时时间 默认2000ms
* @returns 是否可访问
*/
async ping (url: string, timeout: number = 2000): Promise<boolean> {
return new Promise((resolve) => {
const request = https.get(url, (res) => {
resolve(res.statusCode === 200)
})

request.on('error', () => {
resolve(false)
})

request.setTimeout(timeout, () => {
request.abort()
resolve(false)
})
})
}

/**
* 下载保存文件
* @param url 下载文件地址
* @param file 保存绝对路径
* @param params fetch参数
*/
async download (url: string, file: string, params: https.RequestOptions = {}): Promise<boolean> {
try {
this.mkdirs(path.dirname(file))
console.info(`[下载文件] ${url}`)

return new Promise((resolve, reject) => {
const request = https.get(url, params, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`Failed to get '${url}' (${res.statusCode})`))
return
}

const fileStream = fs.createWriteStream(file)
streamPipeline(res, fileStream)
.then(() => resolve(true))
.catch((err) => {
console.error(`[下载文件] 错误:${err}`)
resolve(false)
})
})

request.on('error', (err) => {
console.error(`[下载文件] 错误: ${err}`)
resolve(false)
})
})
} catch (err) {
console.error(`[下载文件] 错误: ${err}`)
return false
}
}

/**
* 解压文件
* @param file zip文件路径
* @param output 输出路径
*/
async unzip (file: string, output: string) {
try {
console.info(`[解压文件] ${file}`)
await decompress(file, output)
return true
} catch (err) {
console.error(`[解压文件] 错误:${err}`)
return false
}
}

/**
* 封装exec
* @param cmd - 命令
*/
exec (cmd: string, options?: ExecOptions): Promise<string> {
return new Promise((resolve, reject) => {
execCmd(cmd, options, (error, stdout, stderr) => {
if (stdout) return resolve(stdout.toString().trim())
if (error) return reject(error)
return reject(stderr)
})
})
}
}

export const common = new Common()
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Puppeteer } from './puppeteer'

export default Puppeteer
export * from './puppeteer'
Loading

0 comments on commit 429dcf6

Please sign in to comment.