pinokiod 7.2.8 → 7.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/kernel/api/index.js +26 -0
- package/kernel/index.js +2 -0
- package/kernel/watch/context.js +42 -0
- package/kernel/watch/drivers/fs.js +71 -0
- package/kernel/watch/drivers/poll.js +33 -0
- package/kernel/watch/index.js +158 -0
- package/package.json +1 -1
- package/server/features/drafts/index.js +41 -0
- package/server/features/drafts/parser.js +169 -0
- package/server/features/drafts/public/drafts.js +1546 -0
- package/server/{routes/draft_import.js → features/drafts/registry_import.js} +35 -77
- package/server/features/drafts/routes.js +68 -0
- package/server/features/drafts/service.js +261 -0
- package/server/features/drafts/watcher.js +76 -0
- package/server/features/index.js +13 -0
- package/server/index.js +25 -36
- package/server/views/app.ejs +159 -14
- package/server/views/terminal.ejs +8 -6
- package/server/lib/drafts.js +0 -376
- package/server/public/drafts.js +0 -632
package/kernel/api/index.js
CHANGED
|
@@ -417,6 +417,12 @@ class Api {
|
|
|
417
417
|
await this.process(script.on.stop)
|
|
418
418
|
}
|
|
419
419
|
}
|
|
420
|
+
if (this.kernel.watch && typeof this.kernel.watch.stop === "function") {
|
|
421
|
+
if (req.params.id) {
|
|
422
|
+
await this.kernel.watch.stop(req.params.id)
|
|
423
|
+
}
|
|
424
|
+
await this.kernel.watch.stop(requestPath)
|
|
425
|
+
}
|
|
420
426
|
// reset modules
|
|
421
427
|
let modpath = this.resolvePath(cwd, req.params.uri)
|
|
422
428
|
if (this.child_procs[modpath]) {
|
|
@@ -1456,6 +1462,25 @@ class Api {
|
|
|
1456
1462
|
}
|
|
1457
1463
|
return false
|
|
1458
1464
|
}
|
|
1465
|
+
async startWatchersForRequest(request, script, scriptDir, input) {
|
|
1466
|
+
if (!this.kernel.watch || typeof this.kernel.watch.startForScript !== "function") {
|
|
1467
|
+
return
|
|
1468
|
+
}
|
|
1469
|
+
const id = request.id || request.path
|
|
1470
|
+
if (!id) {
|
|
1471
|
+
return
|
|
1472
|
+
}
|
|
1473
|
+
const cwd = request.cwd || scriptDir
|
|
1474
|
+
await this.kernel.watch.startForScript({
|
|
1475
|
+
id,
|
|
1476
|
+
request,
|
|
1477
|
+
script,
|
|
1478
|
+
cwd,
|
|
1479
|
+
dirname: scriptDir,
|
|
1480
|
+
input,
|
|
1481
|
+
args: input
|
|
1482
|
+
})
|
|
1483
|
+
}
|
|
1459
1484
|
createQueue(queue_id, concurrency) {
|
|
1460
1485
|
this.queues[queue_id] = fastq.promise(async ({ request, rawrpc, input, step, total, cwd, args }) => {
|
|
1461
1486
|
try {
|
|
@@ -1697,6 +1722,7 @@ class Api {
|
|
|
1697
1722
|
}
|
|
1698
1723
|
|
|
1699
1724
|
const initialPayload = typeof request.input === "undefined" ? {} : request.input
|
|
1725
|
+
await this.startWatchersForRequest(request, script, cwd, initialPayload)
|
|
1700
1726
|
this.queue(request, steps[0], initialPayload, 0, steps.length, cwd, initialPayload)
|
|
1701
1727
|
|
|
1702
1728
|
} else {
|
package/kernel/index.js
CHANGED
|
@@ -40,6 +40,7 @@ const Git = require('./git')
|
|
|
40
40
|
const Connect = require('./connect')
|
|
41
41
|
const Favicon = require('./favicon')
|
|
42
42
|
const AppLauncher = require('./app_launcher')
|
|
43
|
+
const WatchManager = require('./watch')
|
|
43
44
|
const { DownloaderHelper } = require('node-downloader-helper');
|
|
44
45
|
const { ProxyAgent } = require('proxy-agent');
|
|
45
46
|
const fakeUa = require('fake-useragent');
|
|
@@ -975,6 +976,7 @@ class Kernel {
|
|
|
975
976
|
this.loader = new Loader()
|
|
976
977
|
this.bin = new Bin(this)
|
|
977
978
|
this.api = new Api(this)
|
|
979
|
+
this.watch = new WatchManager(this)
|
|
978
980
|
this.python = new Python(this)
|
|
979
981
|
this.shell = new Shells(this)
|
|
980
982
|
this.appLauncher = new AppLauncher(this)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const path = require("path")
|
|
2
|
+
const { watchFs } = require("./drivers/fs")
|
|
3
|
+
const { poll } = require("./drivers/poll")
|
|
4
|
+
|
|
5
|
+
class WatchContext {
|
|
6
|
+
constructor(options = {}) {
|
|
7
|
+
this.kernel = options.kernel
|
|
8
|
+
this.manager = options.manager
|
|
9
|
+
this.id = options.id
|
|
10
|
+
this.cwd = path.resolve(options.cwd)
|
|
11
|
+
this.dirname = path.resolve(options.dirname || options.cwd)
|
|
12
|
+
this.request = options.request
|
|
13
|
+
this.script = options.script
|
|
14
|
+
this.declaration = options.declaration
|
|
15
|
+
this.input = options.input || {}
|
|
16
|
+
this.args = options.args || this.input
|
|
17
|
+
this.watch = {
|
|
18
|
+
fs: (targetPath, callback, watchOptions = {}) => {
|
|
19
|
+
return watchFs(this.resolve(targetPath), callback, {
|
|
20
|
+
...watchOptions,
|
|
21
|
+
onError: watchOptions.onError || ((error) => {
|
|
22
|
+
console.warn("[watch.fs]", error && error.message ? error.message : error)
|
|
23
|
+
})
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
resolve(targetPath) {
|
|
30
|
+
return this.kernel.api.resolvePath(this.cwd, String(targetPath || "."))
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
resolveModule(targetPath) {
|
|
34
|
+
return this.kernel.api.resolvePath(this.dirname, String(targetPath || "."))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
poll(interval, callback, options = {}) {
|
|
38
|
+
return poll(interval, callback, options)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = WatchContext
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
const fs = require("fs")
|
|
2
|
+
const path = require("path")
|
|
3
|
+
const ParcelWatcher = require("@parcel/watcher")
|
|
4
|
+
|
|
5
|
+
const DEFAULT_IGNORE = [
|
|
6
|
+
"**/.git/**",
|
|
7
|
+
"**/node_modules/**",
|
|
8
|
+
"**/__pycache__/**",
|
|
9
|
+
"**/.venv/**",
|
|
10
|
+
"**/venv/**",
|
|
11
|
+
"**/env/**"
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
function isInside(candidate, parent) {
|
|
15
|
+
const relative = path.relative(parent, candidate)
|
|
16
|
+
return relative === "" || (!!relative && !relative.startsWith("..") && !path.isAbsolute(relative))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function nearestExistingDirectory(targetPath) {
|
|
20
|
+
let current = path.resolve(targetPath)
|
|
21
|
+
while (current && current !== path.dirname(current)) {
|
|
22
|
+
const stats = await fs.promises.stat(current).catch(() => null)
|
|
23
|
+
if (stats && stats.isDirectory()) {
|
|
24
|
+
return current
|
|
25
|
+
}
|
|
26
|
+
current = path.dirname(current)
|
|
27
|
+
}
|
|
28
|
+
return current || path.parse(path.resolve(targetPath)).root
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function watchFs(targetPath, callback, options = {}) {
|
|
32
|
+
const resolvedTarget = path.resolve(targetPath)
|
|
33
|
+
const targetStats = await fs.promises.stat(resolvedTarget).catch(() => null)
|
|
34
|
+
const watchRoot = targetStats && targetStats.isDirectory()
|
|
35
|
+
? resolvedTarget
|
|
36
|
+
: await nearestExistingDirectory(resolvedTarget)
|
|
37
|
+
const filterToTarget = watchRoot !== resolvedTarget
|
|
38
|
+
|
|
39
|
+
const subscription = await ParcelWatcher.subscribe(
|
|
40
|
+
watchRoot,
|
|
41
|
+
(error, events) => {
|
|
42
|
+
if (error) {
|
|
43
|
+
if (typeof options.onError === "function") {
|
|
44
|
+
options.onError(error)
|
|
45
|
+
}
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
const normalizedEvents = Array.isArray(events) ? events : []
|
|
49
|
+
const filteredEvents = filterToTarget
|
|
50
|
+
? normalizedEvents.filter((event) => event && event.path && isInside(path.resolve(event.path), resolvedTarget))
|
|
51
|
+
: normalizedEvents
|
|
52
|
+
if (filteredEvents.length === 0) {
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
callback(filteredEvents)
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
ignore: Array.isArray(options.ignore) ? options.ignore : DEFAULT_IGNORE
|
|
59
|
+
}
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
return async () => {
|
|
63
|
+
if (subscription && typeof subscription.unsubscribe === "function") {
|
|
64
|
+
await subscription.unsubscribe().catch(() => {})
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = {
|
|
70
|
+
watchFs
|
|
71
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
function poll(interval, callback, options = {}) {
|
|
2
|
+
const delay = Math.max(100, Number(interval || options.interval || 1000))
|
|
3
|
+
let stopped = false
|
|
4
|
+
let running = false
|
|
5
|
+
|
|
6
|
+
const tick = async () => {
|
|
7
|
+
if (stopped || running) return
|
|
8
|
+
running = true
|
|
9
|
+
try {
|
|
10
|
+
await callback()
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (typeof options.onError === "function") {
|
|
13
|
+
options.onError(error)
|
|
14
|
+
}
|
|
15
|
+
} finally {
|
|
16
|
+
running = false
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (options.immediate !== false) {
|
|
21
|
+
setTimeout(tick, 0)
|
|
22
|
+
}
|
|
23
|
+
const timer = setInterval(tick, delay)
|
|
24
|
+
|
|
25
|
+
return async () => {
|
|
26
|
+
stopped = true
|
|
27
|
+
clearInterval(timer)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
module.exports = {
|
|
32
|
+
poll
|
|
33
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
const path = require("path")
|
|
2
|
+
const WatchContext = require("./context")
|
|
3
|
+
|
|
4
|
+
class WatchManager {
|
|
5
|
+
constructor(kernel) {
|
|
6
|
+
this.kernel = kernel
|
|
7
|
+
this.handlers = new Map()
|
|
8
|
+
this.sessions = new Map()
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
registerHandler(name, handler) {
|
|
12
|
+
const normalized = typeof name === "string" ? name.trim() : ""
|
|
13
|
+
if (!normalized) {
|
|
14
|
+
throw new Error("watch handler name is required")
|
|
15
|
+
}
|
|
16
|
+
this.handlers.set(normalized, handler)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
hasHandler(script, handlerName) {
|
|
20
|
+
const watches = script && Array.isArray(script.watch) ? script.watch : []
|
|
21
|
+
return watches.some((watch) => watch && watch.handler === handlerName)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
renderDeclaration(raw, memory) {
|
|
25
|
+
let rendered = raw
|
|
26
|
+
let pass = 0
|
|
27
|
+
while (true) {
|
|
28
|
+
rendered = this.kernel.template.render(rendered, memory)
|
|
29
|
+
if (this.kernel.template.istemplate(rendered)) {
|
|
30
|
+
pass += 1
|
|
31
|
+
if (pass >= 4) break
|
|
32
|
+
} else {
|
|
33
|
+
break
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return this.kernel.template.flatten(rendered)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
buildMemory({ request, script, cwd, dirname, input, args }) {
|
|
40
|
+
return {
|
|
41
|
+
script: this.kernel.script,
|
|
42
|
+
input,
|
|
43
|
+
args,
|
|
44
|
+
cwd,
|
|
45
|
+
dirname,
|
|
46
|
+
uri: request.uri,
|
|
47
|
+
self: script,
|
|
48
|
+
kernel: this.kernel,
|
|
49
|
+
...this.kernel.vars
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async resolveExternalHandler(ctx, uri) {
|
|
54
|
+
const modpath = ctx.resolveModule(uri)
|
|
55
|
+
const loaded = await this.kernel.loader.load(modpath)
|
|
56
|
+
let handler = loaded && loaded.resolved
|
|
57
|
+
if (typeof handler === "function") {
|
|
58
|
+
handler = new handler()
|
|
59
|
+
}
|
|
60
|
+
return handler
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async startForScript(options = {}) {
|
|
64
|
+
const script = options.script
|
|
65
|
+
const declarations = script && Array.isArray(script.watch) ? script.watch : []
|
|
66
|
+
if (declarations.length === 0) {
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const id = options.id
|
|
71
|
+
if (!id) {
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
await this.stop(id)
|
|
75
|
+
|
|
76
|
+
const input = options.input || {}
|
|
77
|
+
const args = options.args || input
|
|
78
|
+
const cwd = path.resolve(options.cwd)
|
|
79
|
+
const dirname = path.resolve(options.dirname || options.cwd)
|
|
80
|
+
const memory = this.buildMemory({
|
|
81
|
+
request: options.request || {},
|
|
82
|
+
script,
|
|
83
|
+
cwd,
|
|
84
|
+
dirname,
|
|
85
|
+
input,
|
|
86
|
+
args
|
|
87
|
+
})
|
|
88
|
+
const disposers = []
|
|
89
|
+
|
|
90
|
+
for (const rawDeclaration of declarations) {
|
|
91
|
+
if (!rawDeclaration || typeof rawDeclaration !== "object") {
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
const declaration = this.renderDeclaration(rawDeclaration, memory)
|
|
96
|
+
const ctx = new WatchContext({
|
|
97
|
+
kernel: this.kernel,
|
|
98
|
+
manager: this,
|
|
99
|
+
id,
|
|
100
|
+
cwd,
|
|
101
|
+
dirname,
|
|
102
|
+
request: options.request,
|
|
103
|
+
script,
|
|
104
|
+
declaration,
|
|
105
|
+
input,
|
|
106
|
+
args
|
|
107
|
+
})
|
|
108
|
+
const methodName = typeof declaration.method === "string" ? declaration.method.trim() : ""
|
|
109
|
+
let handler = null
|
|
110
|
+
if (declaration.handler) {
|
|
111
|
+
handler = this.handlers.get(String(declaration.handler).trim())
|
|
112
|
+
} else if (declaration.uri) {
|
|
113
|
+
handler = await this.resolveExternalHandler(ctx, declaration.uri)
|
|
114
|
+
}
|
|
115
|
+
if (!handler || !methodName || typeof handler[methodName] !== "function") {
|
|
116
|
+
console.warn("[watch] handler not found", declaration)
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
const cleanup = await handler[methodName](ctx, declaration.params || {})
|
|
120
|
+
if (cleanup) {
|
|
121
|
+
disposers.push(cleanup)
|
|
122
|
+
}
|
|
123
|
+
} catch (error) {
|
|
124
|
+
console.warn("[watch] failed to start", error && error.message ? error.message : error)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (disposers.length > 0) {
|
|
129
|
+
this.sessions.set(id, disposers)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async stop(id) {
|
|
134
|
+
const normalized = typeof id === "string" ? id : ""
|
|
135
|
+
if (!normalized || !this.sessions.has(normalized)) {
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
const disposers = this.sessions.get(normalized) || []
|
|
139
|
+
this.sessions.delete(normalized)
|
|
140
|
+
for (const disposer of disposers.reverse()) {
|
|
141
|
+
try {
|
|
142
|
+
if (typeof disposer === "function") {
|
|
143
|
+
await disposer()
|
|
144
|
+
} else if (disposer && typeof disposer.stop === "function") {
|
|
145
|
+
await disposer.stop()
|
|
146
|
+
} else if (disposer && typeof disposer.dispose === "function") {
|
|
147
|
+
await disposer.dispose()
|
|
148
|
+
} else if (disposer && typeof disposer.unsubscribe === "function") {
|
|
149
|
+
await disposer.unsubscribe()
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
console.warn("[watch] cleanup failed", error && error.message ? error.message : error)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
module.exports = WatchManager
|
package/package.json
CHANGED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const { createDraftService } = require("./service")
|
|
2
|
+
const registerDraftRoutes = require("./routes")
|
|
3
|
+
const DraftWatcher = require("./watcher")
|
|
4
|
+
|
|
5
|
+
function createDraftFeature(options = {}) {
|
|
6
|
+
const { app, kernel } = options
|
|
7
|
+
if (!app) {
|
|
8
|
+
throw new Error("app is required")
|
|
9
|
+
}
|
|
10
|
+
if (!kernel) {
|
|
11
|
+
throw new Error("kernel is required")
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const service = createDraftService({
|
|
15
|
+
kernel,
|
|
16
|
+
taskWorkspaceLinks: options.taskWorkspaceLinks
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
registerDraftRoutes(app, {
|
|
20
|
+
...options,
|
|
21
|
+
drafts: service
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
if (kernel.watch && typeof kernel.watch.registerHandler === "function") {
|
|
25
|
+
kernel.watch.registerHandler("draft", new DraftWatcher({ drafts: service }))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
service,
|
|
30
|
+
async start() {
|
|
31
|
+
await service.start()
|
|
32
|
+
},
|
|
33
|
+
async stop() {
|
|
34
|
+
await service.stop()
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
module.exports = {
|
|
40
|
+
createDraftFeature
|
|
41
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
const fs = require("fs")
|
|
2
|
+
const path = require("path")
|
|
3
|
+
|
|
4
|
+
const RESULT_RELATIVE_DIR = path.join(".pinokio", "draft")
|
|
5
|
+
const POST_FILENAME = "post.md"
|
|
6
|
+
const METADATA_FILENAME = "pinokio.json"
|
|
7
|
+
const DEFAULT_READY_FILENAME = METADATA_FILENAME
|
|
8
|
+
const PREVIEW_CHARS = 1200
|
|
9
|
+
const MEDIA_EXTENSIONS = new Set([
|
|
10
|
+
".apng",
|
|
11
|
+
".avif",
|
|
12
|
+
".gif",
|
|
13
|
+
".jpeg",
|
|
14
|
+
".jpg",
|
|
15
|
+
".m4a",
|
|
16
|
+
".mp3",
|
|
17
|
+
".mp4",
|
|
18
|
+
".ogg",
|
|
19
|
+
".png",
|
|
20
|
+
".svg",
|
|
21
|
+
".wav",
|
|
22
|
+
".webm",
|
|
23
|
+
".webp"
|
|
24
|
+
])
|
|
25
|
+
|
|
26
|
+
function normalizeWhitespace(value) {
|
|
27
|
+
return String(value || "").replace(/\s+/g, " ").trim()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function extractTitle(markdown, workspaceName) {
|
|
31
|
+
const lines = String(markdown || "").split(/\r?\n/)
|
|
32
|
+
for (const line of lines) {
|
|
33
|
+
const match = line.match(/^#\s+(.+?)\s*#*\s*$/)
|
|
34
|
+
if (match && match[1]) {
|
|
35
|
+
return normalizeWhitespace(match[1]).slice(0, 140) || "Draft"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return workspaceName ? `Draft for ${workspaceName}` : "Draft"
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function normalizeTitle(value) {
|
|
42
|
+
return normalizeWhitespace(value).slice(0, 160)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseDraftMetadata(raw) {
|
|
46
|
+
const parsed = JSON.parse(String(raw || ""))
|
|
47
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
48
|
+
return {}
|
|
49
|
+
}
|
|
50
|
+
const metadata = { ...parsed }
|
|
51
|
+
if (typeof metadata.title === "string") {
|
|
52
|
+
metadata.title = normalizeTitle(metadata.title)
|
|
53
|
+
} else {
|
|
54
|
+
delete metadata.title
|
|
55
|
+
}
|
|
56
|
+
return metadata
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function extractTitleAndBody(markdown, fallbackTitle) {
|
|
60
|
+
const lines = String(markdown || "").split(/\r?\n/)
|
|
61
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
62
|
+
const match = lines[i].match(/^#\s+(.+?)\s*#*\s*$/)
|
|
63
|
+
if (!match || !match[1]) continue
|
|
64
|
+
const title = normalizeWhitespace(match[1]).slice(0, 160)
|
|
65
|
+
const bodyLines = [...lines.slice(0, i), ...lines.slice(i + 1)]
|
|
66
|
+
while (bodyLines.length && !bodyLines[0].trim()) bodyLines.shift()
|
|
67
|
+
return { title: title || fallbackTitle, body: bodyLines.join("\n").trim() }
|
|
68
|
+
}
|
|
69
|
+
return { title: fallbackTitle, body: String(markdown || "").trim() }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function buildExcerpt(markdown) {
|
|
73
|
+
const stripped = String(markdown || "")
|
|
74
|
+
.replace(/```[\s\S]*?```/g, " ")
|
|
75
|
+
.replace(/!\[[^\]]*]\([^)]+\)/g, " ")
|
|
76
|
+
.replace(/\[[^\]]+]\([^)]+\)/g, (match) => {
|
|
77
|
+
const label = match.match(/^\[([^\]]+)]/)
|
|
78
|
+
return label && label[1] ? ` ${label[1]} ` : " "
|
|
79
|
+
})
|
|
80
|
+
.replace(/^#+\s+/gm, "")
|
|
81
|
+
.replace(/[*_`>#-]/g, " ")
|
|
82
|
+
return normalizeWhitespace(stripped).slice(0, PREVIEW_CHARS)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function isExternalRef(value) {
|
|
86
|
+
return /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(value)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function normalizeMarkdownRef(value) {
|
|
90
|
+
const raw = String(value || "").trim().replace(/^<|>$/g, "")
|
|
91
|
+
if (!raw || raw.includes("\0") || isExternalRef(raw) || path.isAbsolute(raw)) {
|
|
92
|
+
return ""
|
|
93
|
+
}
|
|
94
|
+
const withoutHash = raw.split("#")[0]
|
|
95
|
+
const withoutQuery = withoutHash.split("?")[0]
|
|
96
|
+
if (!withoutQuery) {
|
|
97
|
+
return ""
|
|
98
|
+
}
|
|
99
|
+
let decoded = withoutQuery
|
|
100
|
+
try {
|
|
101
|
+
decoded = decodeURIComponent(withoutQuery)
|
|
102
|
+
} catch (_) {
|
|
103
|
+
}
|
|
104
|
+
const normalized = path.posix.normalize(decoded.replace(/\\/g, "/"))
|
|
105
|
+
if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../") || normalized.includes("/../")) {
|
|
106
|
+
return ""
|
|
107
|
+
}
|
|
108
|
+
return normalized
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function collectMarkdownRefs(markdown) {
|
|
112
|
+
const refs = []
|
|
113
|
+
const seen = new Set()
|
|
114
|
+
const patterns = [
|
|
115
|
+
/!\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g,
|
|
116
|
+
/\[(?:video|audio|media|image|screenshot|file|asset)[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/gi,
|
|
117
|
+
/\[[^\]]+]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g
|
|
118
|
+
]
|
|
119
|
+
for (const pattern of patterns) {
|
|
120
|
+
let match = null
|
|
121
|
+
while ((match = pattern.exec(markdown))) {
|
|
122
|
+
const ref = normalizeMarkdownRef(match[1])
|
|
123
|
+
if (!ref || seen.has(ref)) continue
|
|
124
|
+
seen.add(ref)
|
|
125
|
+
refs.push(ref)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return refs
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function describeMediaRefs(markdown, baseDir, options = {}) {
|
|
132
|
+
const refs = collectMarkdownRefs(markdown)
|
|
133
|
+
const media = []
|
|
134
|
+
for (const ref of refs) {
|
|
135
|
+
const ext = path.extname(ref).toLowerCase()
|
|
136
|
+
if (options.mediaOnly !== false && !MEDIA_EXTENSIONS.has(ext)) {
|
|
137
|
+
continue
|
|
138
|
+
}
|
|
139
|
+
const filePath = path.resolve(baseDir, ref)
|
|
140
|
+
const relative = path.relative(baseDir, filePath)
|
|
141
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
142
|
+
continue
|
|
143
|
+
}
|
|
144
|
+
const stats = await fs.promises.stat(filePath).catch(() => null)
|
|
145
|
+
media.push({
|
|
146
|
+
ref,
|
|
147
|
+
path: filePath,
|
|
148
|
+
bytes: stats && stats.isFile() ? stats.size : 0,
|
|
149
|
+
mtimeMs: stats && stats.isFile() ? stats.mtimeMs : 0,
|
|
150
|
+
exists: Boolean(stats && stats.isFile())
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
return media
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
module.exports = {
|
|
157
|
+
METADATA_FILENAME,
|
|
158
|
+
DEFAULT_READY_FILENAME,
|
|
159
|
+
RESULT_RELATIVE_DIR,
|
|
160
|
+
POST_FILENAME,
|
|
161
|
+
buildExcerpt,
|
|
162
|
+
collectMarkdownRefs,
|
|
163
|
+
describeMediaRefs,
|
|
164
|
+
extractTitle,
|
|
165
|
+
extractTitleAndBody,
|
|
166
|
+
normalizeMarkdownRef,
|
|
167
|
+
normalizeTitle,
|
|
168
|
+
parseDraftMetadata
|
|
169
|
+
}
|