log("Loading Comprehensive Example Plugin...")
-- ============================================================================
-- PART 1: HOOK CHAINING DEMONSTRATION
-- Multiple hooks that modify HTML content sequentially
-- ============================================================================
-- Hook 1: Add custom CSS (Priority 10 - runs first)
register_hook("post_render", function(filepath, html_content)
log("Hook 1 (Priority 10): Adding custom CSS to " .. filepath)
local custom_css = [[
]]
-- Insert CSS before closing head tag
local modified = html_insert_before(html_content, "", custom_css)
return modified -- Pass to next hook
end, 10)
-- Hook 2: Add banner (Priority 20 - runs second)
register_hook("post_render", function(filepath, html_content)
log("Hook 2 (Priority 20): Adding banner")
local banner = [[
🚀 Enhanced by Plugin System |
Processing: ]] .. filepath .. [[
]]
local modified = html_insert_after(html_content, "", banner)
return modified
end, 20)
-- Hook 3: Enhance code blocks (Priority 30 - runs third)
register_hook("post_render", function(filepath, html_content)
log("Hook 3 (Priority 30): Enhancing code blocks")
-- Add class to all code tags
local modified = html_add_class(html_content, "code", "enhanced-code")
modified = html_add_attribute(modified, "pre", "data-enhanced", "true")
return modified
end, 30)
-- Hook 4: Add footer (Priority 40 - runs last)
register_hook("post_render", function(filepath, html_content)
log("Hook 4 (Priority 40): Adding footer")
local footer = [[
]]
local modified = html_insert_before(html_content, "", footer)
return modified
end, 40)
-- ============================================================================
-- PART 2: GET ROUTES
-- Demonstrate various GET route patterns
-- ============================================================================
-- Simple text response
add_get_route("/plugin/hello", function(req)
return "Hello from Plugin!
This is a simple GET route.
"
end, 50)
-- JSON API endpoint
add_get_route("/plugin/api/info", function(req)
local info = {
plugin_name = "Comprehensive Example",
version = "1.0.0",
features = {"hooks", "routes", "file_ops"},
html_files = #list_html_files(),
markdown_files = #list_markdown_files(),
timestamp = os.date("%Y-%m-%d %H:%M:%S")
}
return 200,
{["Content-Type"] = "application/json"},
table_to_json(info)
end, 50)
-- File listing endpoint
add_get_route("/plugin/files", function(req)
local html_files = list_html_files()
local md_files = list_markdown_files()
local html = [[
File Browser
📁 File Browser
HTML Files (]] .. #html_files .. [[)
]]
for i, file in ipairs(html_files) do
html = html .. '
📄 ' .. file .. '
\n'
end
html = html .. [[
Markdown Files (]] .. #md_files .. [[)
]]
for i, file in ipairs(md_files) do
html = html .. '
📝 ' .. file .. '
\n'
end
html = html .. [[
]]
return html
end, 50)
-- ============================================================================
-- PART 3: POST ROUTES
-- Handle form submissions and API requests
-- ============================================================================
-- Contact form submission
add_post_route("/plugin/api/contact", function(req)
local data = req.data or {}
log("Contact form received:")
log(" Name: " .. (data.name or "N/A"))
log(" Email: " .. (data.email or "N/A"))
log(" Message: " .. (data.message or "N/A"))
-- Validation
if not data.name or data.name == "" then
return 400,
{["Content-Type"] = "application/json"},
table_to_json({success = false, error = "Name is required"})
end
if not data.message or data.message == "" then
return 400,
{["Content-Type"] = "application/json"},
table_to_json({success = false, error = "Message is required"})
end
-- Save to file (example)
local timestamp = os.date("%Y-%m-%d %H:%M:%S")
local submission = string_join({
"---",
"Name: " .. data.name,
"Email: " .. (data.email or "N/A"),
"Time: " .. timestamp,
"Message:",
data.message,
"---",
""
}, "\n")
-- Note: In production, you'd want better file handling
-- write_file("submissions.txt", submission)
local response = {
success = true,
message = "Thank you for your submission!",
received_at = timestamp
}
return 200,
{["Content-Type"] = "application/json"},
table_to_json(response)
end, 50)
-- File upload/create endpoint
add_post_route("/plugin/api/create-note", function(req)
local data = req.data or {}
local title = data.title or "Untitled"
local content = data.content or ""
if content == "" then
return 400,
{["Content-Type"] = "application/json"},
table_to_json({success = false, error = "Content cannot be empty"})
end
-- Create markdown file
local filename = string_replace(title, " ", "-") .. ".md"
filename = string.lower(filename)
local markdown_content = md_add_header("", 1, title)
markdown_content = md_append_content(markdown_content, content)
markdown_content = md_append_content(markdown_content,
"\n---\n*Created by plugin at " .. os.date("%Y-%m-%d %H:%M:%S") .. "*")
-- Write the file
local success = write_markdown(filename, markdown_content)
if success then
log("Created new markdown file: " .. filename)
return 200,
{["Content-Type"] = "application/json"},
table_to_json({
success = true,
message = "Note created successfully",
filename = filename
})
else
return 500,
{["Content-Type"] = "application/json"},
table_to_json({
success = false,
error = "Failed to create file"
})
end
end, 50)
-- ============================================================================
-- PART 4: DEMONSTRATION DASHBOARD
-- A full-featured page showing all capabilities
-- ============================================================================
add_get_route("/plugin/dashboard", function(req)
local html_count = #list_html_files()
local md_count = #list_markdown_files()
local html = [[
Plugin Dashboard
📄 HTML Files
]] .. html_count .. [[
Generated HTML documents
📝 Markdown Files
]] .. md_count .. [[
Source markdown files
⏰ Server Time
]] .. os.date("%H:%M") .. [[
]] .. os.date("%Y-%m-%d") .. [[
🚀 Plugin Features
- Hook Chaining: Multiple plugins modify content sequentially
- Priority System: Control execution order (0-100)
- GET Routes: Serve custom pages and APIs
- POST Routes: Handle form submissions
- HTML Manipulation: Find, replace, insert, wrap elements
- Markdown Operations: Add headers, sections, list items
- File I/O: Read, write, list files safely
- JSON Support: Parse and stringify data
- Hot Reloading: Plugins reload automatically on changes
🌐 Available API Endpoints
GET /plugin/hello - Simple greeting
GET /plugin/api/info - JSON plugin info
GET /plugin/files - File browser
GET /plugin/dashboard - This page
POST /plugin/api/contact - Submit contact form
POST /plugin/api/create-note - Create markdown note
View Files
API Info (JSON)
🔗 Hook Chain Processing Order
When a markdown file is rendered, these hooks process the HTML sequentially:
1️⃣ Add CSS (Priority 10)
→
2️⃣ Add Banner (Priority 20)
→
3️⃣ Enhance Code (Priority 30)
→
4️⃣ Add Footer (Priority 40)
Each hook receives the output from the previous hook, ensuring no modifications are lost.
💻 Example Plugin Code
-- Register a hook with priority
register_hook("post_render", function(filepath, html)
log("Processing: " .. filepath)
local modified = html_insert_after(html, "<body>",
"<div class='banner'>Hello!</div>")
return modified -- Chain to next hook
end, 20)
-- Register a POST route
add_post_route("/api/submit", function(req)
local data = req.data
log("Received: " .. data.name)
return 200,
{["Content-Type"] = "application/json"},
table_to_json({success = true})
end, 50)
]]
return html
end, 50)
-- ============================================================================
-- PART 5: UTILITY DEMONSTRATIONS
-- Show string and file utilities
-- ============================================================================
-- String manipulation API
add_get_route("/plugin/api/string-demo", function(req)
local text = "Hello, World! This is a test."
local demo = {
original = text,
split = string_split(text, " "),
replaced = string_replace(text, "World", "PyPost"),
uppercase = string.upper(text),
lowercase = string.lower(text),
match = string_match(text, "w+"),
all_words = string_match_all(text, "%w+")
}
return 200,
{["Content-Type"] = "application/json"},
table_to_json(demo)
end, 50)
-- ============================================================================
-- INITIALIZATION LOG
-- ============================================================================
log("========================================")
log("Comprehensive Plugin Loaded Successfully!")
log("========================================")
log("Registered Hooks:")
log(" - post_render (4 hooks with priorities 10, 20, 30, 40)")
log("Registered GET Routes:")
log(" - /plugin/hello")
log(" - /plugin/api/info")
log(" - /plugin/files")
log(" - /plugin/dashboard")
log(" - /plugin/api/string-demo")
log("Registered POST Routes:")
log(" - /plugin/api/contact")
log(" - /plugin/api/create-note")
log("========================================")
log("Visit /plugin/dashboard to see all features!")
log("========================================")