From ae9d8e40587dafbb977091580ff54e82a2e99a78 Mon Sep 17 00:00:00 2001 From: Joakim Date: Thu, 4 Sep 2025 22:16:35 +0200 Subject: [PATCH] refactor: implement script tag approach for library inclusion - Add script tags to demo-site HTML files for manual development - Disable CLI inline script injection to prevent duplicate scripts - Add library serving endpoints to servedev command - Update build process to auto-copy library to demo-site - Add CDN URL helpers for future production deployment - Update .gitignore for generated demo-site files Fixes .insertr-gate authentication for manual npm run serve workflow while maintaining clean separation between CLI and manual setups. --- .gitignore | 5 +- CLEANUP_SUMMARY.md | 76 --- DEVELOPMENT.md | 215 -------- DEVELOPMENT_QUICKSTART.md | 39 -- INITIAL.md | 98 ---- LIBRARY.md | 138 ----- RESEARCH.md | 682 ------------------------- demo-site/about.html | 1 + demo-site/index.html | 2 + insertr-cli/cmd/servedev.go | 24 + insertr-cli/pkg/content/injector.go | 33 +- insertr-cli/pkg/content/library.go | 24 + insertr-cli/scripts/rebuild-library.sh | 2 +- lib/package.json | 4 +- 14 files changed, 68 insertions(+), 1275 deletions(-) delete mode 100644 CLEANUP_SUMMARY.md delete mode 100644 DEVELOPMENT.md delete mode 100644 DEVELOPMENT_QUICKSTART.md delete mode 100644 INITIAL.md delete mode 100644 LIBRARY.md delete mode 100644 RESEARCH.md diff --git a/.gitignore b/.gitignore index 66b900b..1c2c209 100644 --- a/.gitignore +++ b/.gitignore @@ -70,4 +70,7 @@ insertr-cli/build-errors.log *.sqlite3 # Local development files -.local/ \ No newline at end of file +.local/ + +# Demo site generated files +demo-site/insertr.js \ No newline at end of file diff --git a/CLEANUP_SUMMARY.md b/CLEANUP_SUMMARY.md deleted file mode 100644 index 7086826..0000000 --- a/CLEANUP_SUMMARY.md +++ /dev/null @@ -1,76 +0,0 @@ -# Code Cleanup Summary - -## Artifacts Removed from Architecture Pivot - -### πŸ—‘οΈ **Obsolete Assets Removed** -- `insertr-cli/assets/editor/insertr-editor.js` - Legacy inline editor script -- `insertr-cli/assets/editor/` directory - No longer needed -- Unused `marked` npm dependency from root package.json - -### 🧹 **Root Package.json Cleanup** -**Before:** -```json -{ - "description": "Edit-in-place CMS for client websites - simple integration with class-based content editing", - "main": "demo-site/insertr/insertr.js", - "keywords": ["cms", "edit-in-place", "inline-editing", "client-websites", "go", "htmx", "alpine"], - "dependencies": { - "marked": "^16.2.1" - } -} -``` - -**After:** -```json -{ - "description": "The Tailwind of CMS - Zero-configuration content editing for any static site", - "main": "lib/dist/insertr.js", - "keywords": ["cms", "headless-cms", "static-site-generator", "build-time-enhancement", "zero-config", "go", "javascript"], - "dependencies": {} -} -``` - -### βœ… **Legacy Code Preserved (Intentionally)** -- `demo-site/archive/` - Contains original prototype for reference -- `scripts/dev.js` - Still useful for testing original prototype -- Legacy npm scripts (`dev:*`) - Kept for prototype development -- `demo-site/README.md` - Accurately describes prototype functionality - -### πŸ”§ **Enhanced .gitignore** -Added new build artifacts: -```gitignore -# Build outputs -lib/dist/ # Library build output -insertr-cli/insertr # CLI executable -insertr-cli/tmp/ # Air temporary files -insertr-cli/build-errors.log # Air error logs -``` - -### 🎯 **What Was NOT Removed** -- **Archive directory**: `demo-site/archive/` kept for reference -- **Development scripts**: Legacy scripts still work for prototype testing -- **Documentation references**: Accurate historical context preserved -- **Go embed assets**: `insertr-cli/pkg/content/assets/` must stay for embedding - -## Validation - -### βœ… **Build System Verified** -```bash -npm run build # βœ… Works -cd insertr-cli && air # βœ… Hot reload works -./insertr enhance # βœ… CLI works with embedded library -``` - -### βœ… **Architecture Clean** -- No dead code or unused imports in Go -- No obsolete script references -- Clean dependency tree (1 package removed) -- Updated project metadata reflects current architecture - -### 🎯 **Result** -The codebase now cleanly separates: -1. **Current Architecture**: `lib/` + `insertr-cli/` with proper embedding -2. **Legacy Prototype**: `demo-site/archive/` for reference -3. **Test Content**: `demo-site/` HTML files for enhancement testing - -No functionality was lost, and the transition from prototype to production architecture is complete. \ No newline at end of file diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md deleted file mode 100644 index 1b5b276..0000000 --- a/DEVELOPMENT.md +++ /dev/null @@ -1,215 +0,0 @@ -# Insertr Development Guide - -## Quick Start - -### Full-Stack Development (Recommended) -1. **Install dependencies**: - ```bash - npm install # Root project dependencies - cd lib && npm install # Library dependencies - ``` - -2. **Start hot reload development**: - ```bash - cd insertr-cli && air # Starts server with library hot reload - ``` - - Watches both Go CLI changes AND JavaScript library changes - - Automatically rebuilds library β†’ CLI β†’ serves enhanced content - - Visit http://localhost:3000 to see results - -### Library-Only Development -```bash -cd lib && npm run watch # Just develop the JavaScript library -``` - -### Legacy Frontend Development -```bash -npm run dev # Legacy live-server (demo-site only) -``` - -## Development Workflow - -### Hot Reload Development (Current Phase) - -**πŸ”₯ NEW**: Full-stack hot reload with Air integration! - -- **Library Source**: `lib/src/` - Independent JavaScript library -- **CLI Integration**: `insertr-cli/` - Go CLI with embedded library -- **Demo Site**: `demo-site/` - Test website for enhancement -- **Automatic Rebuilds**: Changes to JS library trigger full rebuild cycle - -#### How Hot Reload Works: -1. Edit JavaScript in `lib/src/` -2. Air detects changes β†’ Rebuilds library β†’ Copies to CLI β†’ Rebuilds CLI -3. Enhanced development server serves updated content -4. Manual browser refresh shows changes - -### Legacy Frontend Development - -- **Demo Site**: `demo-site/` contains the prototype website -- **Core Library**: `demo-site/insertr/insertr.js` - the old prototype library -- **Mock API**: `demo-site/mock-api/content.json` - sample backend data structure - -### Testing the Three User Types - -1. **Customer View**: Open the site normally - clean, no edit interface -2. **Client View**: Click "Login as Client" then "Edit Mode: On" - see edit buttons -3. **Developer View**: Look at the HTML source to see simple integration - -### Making Changes - -#### Modern Development (lib/ + insertr-cli/) -- **Library Changes**: Edit `lib/src/**/*.js` β†’ Air automatically rebuilds everything -- **CLI Changes**: Edit Go files in `insertr-cli/` β†’ Air rebuilds and restarts server -- **Demo Content**: Edit `demo-site/*.html` β†’ Air serves enhanced versions -- **Hot Reload**: Changes trigger full rebuild cycle (library β†’ CLI β†’ enhanced content) - -#### Legacy Development (demo-site/) -- **Live Reload**: The server automatically refreshes when you save changes -- **JavaScript**: Edit `demo-site/insertr/insertr.js` for prototype functionality -- **Content**: Edit HTML files to test different content structures - -### Adding New Features - -1. **Content Types**: Extend the `createEditForm()` method in insertr.js -2. **UI Components**: Add new CSS classes and corresponding JavaScript -3. **Authentication**: Modify the mock auth system in `toggleAuthentication()` - -## Project Structure - -``` -insertr/ -β”œβ”€β”€ DEVELOPMENT.md # This file -β”œβ”€β”€ LIBRARY.md # Library architecture documentation -β”œβ”€β”€ package.json # Root project configuration -β”‚ -β”œβ”€β”€ lib/ # πŸ†• Independent JavaScript Library -β”‚ β”œβ”€β”€ src/ -β”‚ β”‚ β”œβ”€β”€ core/ -β”‚ β”‚ β”‚ β”œβ”€β”€ insertr.js # Core library functionality -β”‚ β”‚ β”‚ β”œβ”€β”€ editor.js # Visual editing interface -β”‚ β”‚ β”‚ └── api-client.js # Content API client -β”‚ β”‚ └── index.js # Library entry point -β”‚ β”œβ”€β”€ dist/ -β”‚ β”‚ β”œβ”€β”€ insertr.js # Built library (development) -β”‚ β”‚ └── insertr.min.js # Built library (production) -β”‚ β”œβ”€β”€ package.json # Library dependencies -β”‚ └── rollup.config.js # Build configuration -β”‚ -β”œβ”€β”€ insertr-cli/ # πŸ†• Go CLI with Embedded Library -β”‚ β”œβ”€β”€ pkg/content/ -β”‚ β”‚ β”œβ”€β”€ assets/ # Embedded library files (auto-copied) -β”‚ β”‚ β”œβ”€β”€ library.go # Go embed declarations -β”‚ β”‚ β”œβ”€β”€ enhancer.go # HTML enhancement orchestrator -β”‚ β”‚ β”œβ”€β”€ injector.go # Content injection logic -β”‚ β”‚ └── ... -β”‚ β”œβ”€β”€ scripts/ -β”‚ β”‚ └── rebuild-library.sh # Air helper script -β”‚ β”œβ”€β”€ .air.toml # Hot reload configuration -β”‚ └── insertr # Built CLI executable -β”‚ -β”œβ”€β”€ demo-site/ # Test website for enhancement -β”‚ β”œβ”€β”€ index.html # Demo homepage -β”‚ β”œβ”€β”€ about.html # Demo about page -β”‚ └── assets/style.css # Demo site styling -β”‚ -└── scripts/ - └── build.js # Integrated build script -``` - -## Development Scripts - -### Root Scripts -- `npm run build` - Build library + CLI with embedded assets -- `npm run dev` - Legacy live-server (demo-site only) - -### Library Scripts (cd lib/) -- `npm run build` - Build library to dist/ -- `npm run watch` - Watch and rebuild library on changes - -### CLI Scripts (cd insertr-cli/) -- `air` - πŸ”₯ Hot reload server (library + CLI + enhanced content) -- `go build -o insertr` - Manual CLI build -- `./insertr enhance ` - Enhance static site -- `./insertr servedev ` - Development server with enhancement - -### Hot Reload Workflow -```bash -cd insertr-cli && air # Start hot reload development -# Edit lib/src/**/*.js # Air detects β†’ rebuilds β†’ serves -# Edit cmd/**/*.go # Air detects β†’ rebuilds β†’ serves -# Edit ../demo-site/ # Air serves enhanced versions -``` - -## Testing Different Scenarios - -### Content Types -- **Simple Text**: Logo, titles, short descriptions -- **Rich Content**: Paragraphs with markdown, lists, links -- **Mixed Content**: Cards with multiple editable sections - -### User Flows -1. **First Visit**: Customer sees clean site -2. **Client Login**: Authentication state changes -3. **Edit Mode**: Toggle editing interface -4. **Content Editing**: Click edit β†’ modify β†’ save -5. **Multi-page**: Test persistence across pages - -### Browser Testing -Test in different browsers to ensure compatibility: -- Chrome/Edge (Chromium) -- Firefox -- Safari (if on macOS) - -## Future Development Phases - -### Phase 2: Backend Integration -- Go HTTP server with REST API -- Real authentication with Authentik OAuth -- File-based content persistence -- Git version control - -### Phase 3: Production Features -- Multi-tenant support -- Admin dashboard -- Content validation -- Image upload -- Deployment automation - -## Contributing Guidelines - -1. **Make changes** in small, focused commits -2. **Test thoroughly** across different content types -3. **Update documentation** when adding new features -4. **Follow existing code style** and patterns - -## Debugging Tips - -### JavaScript Console -- Open browser dev tools (F12) -- Check for errors in Console tab -- Use `window.insertr` to inspect library state - -### Local Storage -- View saved content: `localStorage.getItem('insertr_content')` -- Clear saved content: `localStorage.clear()` - -### Network Simulation -- The library simulates network delays and occasional failures -- Check browser Network tab to see mock API calls (when implemented) - -## Common Issues - -### Live Server Not Working -- Ensure port 3000 is available -- Try different port: `live-server demo-site --port=3001` - -### Changes Not Reflecting -- Hard refresh browser (Ctrl+F5 / Cmd+Shift+R) -- Check browser cache settings -- Verify file paths are correct - -### Edit Buttons Not Showing -- Check authentication state (click "Login as Client") -- Enable edit mode (click "Edit Mode: Off" β†’ "Edit Mode: On") -- Verify elements have `class="insertr"` and `data-content-id` \ No newline at end of file diff --git a/DEVELOPMENT_QUICKSTART.md b/DEVELOPMENT_QUICKSTART.md deleted file mode 100644 index 9a0217e..0000000 --- a/DEVELOPMENT_QUICKSTART.md +++ /dev/null @@ -1,39 +0,0 @@ -# Insertr Development Quickstart - -## Project Structure - -- `lib/` - JavaScript library development (all Node.js tooling) -- `insertr-cli/` - Go CLI application -- `demo-site/` - Static HTML demo site - -## Getting Started - -### Library Development -```bash -cd lib/ -npm install -npm run serve # Start development server -npm run check # Validate setup -npm run demo # Show demo instructions -``` - -### CLI Development -```bash -cd insertr-cli/ -air # Hot reload development server -``` - -### Build Everything -```bash -cd lib/ -npm run build:all # Builds library + CLI with embedded assets -``` - -## Architecture - -The CLI embeds the JavaScript library at build time for distribution. During development: -- `lib/` contains the JavaScript library source and build tools -- Air (Go hot reload) watches `lib/src/` and rebuilds when library changes -- Demo site served from `lib/` package for unified development experience - -All Node.js dependencies and scripts are now consolidated in the `lib/` package. \ No newline at end of file diff --git a/INITIAL.md b/INITIAL.md deleted file mode 100644 index 4cf0fc3..0000000 --- a/INITIAL.md +++ /dev/null @@ -1,98 +0,0 @@ -# Insertr -A content management system for client websites. - -I host a few client services and static web-sites and I want to integrate content management for the client. They should be able to change the content of the site, if not the layout. I am open to hearing about existing solutions, but I am considering building my own. If I were to build my own CMS I imagine an edit-in-place experience - probably with Go on the backend and something like htmx/alpine on the front-end, although I would be open for other alternatives. - -## Features / User stories -This list is not exhaustive and will be expanded as we research. - -### Users -This application have to keep three types of users in mind. -- *The developer* - Creating web-sites or services for small businisses -- *The client* - The one in daily control of the content. Sign in - make changes - see outcome. A simple system for any tech-litteracy level. "Update however and whenever you will, without involving tech support." -- *The customer* - Client's customers who will view and consume the site or service. - -### MVP -- [ ] Client should sign in through a SSO (I am hosting an authentik instance that should manage users through oAuth). -- [ ] See the public-facing version of their page, but with an edit button in the top right corner of "content components". If they click the button the content will be replaced with a form coresponding to the component's content, rendered in markdown. They can edit the content and submit/save their changes. -- [ ] This will trigger an update of the content on the server. - -If I were to write a wish list it would be: -- [ ] Slapp a class on a div:
|
, and it works. - -## Research Results (Completed) - -### Existing Solutions Analysis -- **TinaCMS**: Git-based with visual editing, but requires Next.js/React framework -- **Strapi**: Full headless CMS, complex setup, Node.js based -- **Contentful**: Commercial solution, API-based, not self-hosted -- **Ghost**: Publishing-focused, not suitable for general content management -- **Conclusion**: No existing solution offers the simple "add a class and it works" approach - -### Tech Stack Decision: Go + htmx/Alpine -**Rationale:** -- **Go**: Fast, single binary deployment, excellent web server performance -- **htmx**: Perfect for edit-in-place with partial page updates -- **Alpine.js**: Lightweight reactive behaviors without framework complexity -- **Architecture**: Dynamic (not static site generation) for real-time editing - -### Authentication Integration -- **Authentik OAuth 2.0**: Standard flow for client authentication -- **JWT tokens**: For API authorization and session management -- **Multi-tenant**: Role-based access per site/content section - -## Prototype Roadmap - -### Phase 1: Frontend Proof-of-Concept -**Goal**: Demonstrate edit-in-place functionality with mock data -**Deliverables**: -- [ ] Demo business website (Acme Consulting example) -- [ ] insertr.js library with core functionality -- [ ] Three user view modes (Customer/Client/Developer) -- [ ] Mock authentication flow -- [ ] Inline editing with markdown support - -### Phase 2: Backend Integration -**Goal**: Connect to Go server with real data persistence -**Deliverables**: -- [ ] Go HTTP server with REST API -- [ ] File-based content storage -- [ ] Authentik OAuth integration -- [ ] Git-based version control - -### Phase 3: Production Features -**Goal**: Multi-tenant deployment ready system -**Deliverables**: -- [ ] Admin dashboard -- [ ] Content validation and security -- [ ] Deployment automation -- [ ] Documentation and examples - -## User Experience Design - -### The Customer (End User) -- Clean website experience with no edit interface -- Fast loading, no unnecessary JavaScript - -### The Client (Content Manager) -- Same website + subtle edit indicators (✏️ icons) -- Click to edit β†’ inline form β†’ save/cancel -- Markdown editing for rich content -- Immediate visual feedback - -### The Developer (Integration) -```html - - -
-

Editable Content

-
-``` - -## Next Immediate Steps -1. Create demo website mockup -2. Build core insertr.js library -3. Implement edit-in-place UI -4. Add mock authentication flow -5. Test with multiple content types - diff --git a/LIBRARY.md b/LIBRARY.md deleted file mode 100644 index 02d9c4e..0000000 --- a/LIBRARY.md +++ /dev/null @@ -1,138 +0,0 @@ -# Insertr Library Architecture - -## Overview - -Insertr now uses a proper separation between the JavaScript library and Go CLI, following the "Tailwind of CMS" philosophy where the library can be developed independently and embedded into the CLI at build time. - -## Project Structure - -``` -insertr/ -β”œβ”€β”€ lib/ # Independent JavaScript library -β”‚ β”œβ”€β”€ src/ -β”‚ β”‚ β”œβ”€β”€ core/ -β”‚ β”‚ β”‚ β”œβ”€β”€ insertr.js # Main library core -β”‚ β”‚ β”‚ β”œβ”€β”€ editor.js # Visual editing functionality -β”‚ β”‚ β”‚ └── api-client.js # Content API client -β”‚ β”‚ └── index.js # Library entry point -β”‚ β”œβ”€β”€ dist/ -β”‚ β”‚ β”œβ”€β”€ insertr.js # Built library (dev) -β”‚ β”‚ └── insertr.min.js # Built library (production) -β”‚ β”œβ”€β”€ package.json -β”‚ └── rollup.config.js # Build configuration -β”œβ”€β”€ insertr-cli/ # Go CLI with embedded library -β”‚ β”œβ”€β”€ pkg/content/ -β”‚ β”‚ β”œβ”€β”€ assets/ # Embedded library files -β”‚ β”‚ β”‚ β”œβ”€β”€ insertr.js # From lib/dist/ -β”‚ β”‚ β”‚ └── insertr.min.js # From lib/dist/ -β”‚ β”‚ β”œβ”€β”€ library.go # Go embed declarations -β”‚ β”‚ β”œβ”€β”€ injector.go # HTML injection logic -β”‚ β”‚ └── ... -β”‚ └── insertr # Built CLI executable -└── scripts/ - └── build.js # Integrated build script -``` - -## Build Process - -### 1. Library Development (`lib/`) -```bash -cd lib -npm install -npm run build # Creates dist/insertr.js and dist/insertr.min.js -npm run watch # Development mode with file watching -``` - -### 2. CLI Integration (`insertr-cli/`) -The CLI uses Go's `//go:embed` directive to embed the built library: - -```go -//go:embed assets/insertr.min.js -var libraryMinJS string - -//go:embed assets/insertr.js -var libraryJS string -``` - -### 3. Integrated Build (Root) -```bash -npm run build # Builds both library AND CLI with embedded assets -``` - -This script: -1. Builds the JavaScript library (`lib/dist/`) -2. Copies built assets to CLI (`insertr-cli/pkg/content/assets/`) -3. Builds Go CLI with embedded library - -## Library Features - -### Core Functionality (`src/core/insertr.js`) -- Element discovery: `findEnhancedElements()` -- Metadata extraction: `getElementMetadata()` -- Element management: `getAllElements()` - -### Visual Editor (`src/core/editor.js`) -- Hover effects and visual indicators -- Click-to-edit functionality -- Content update handling -- Dynamic style injection - -### API Client (`src/core/api-client.js`) -- RESTful content API communication -- CRUD operations for content -- Error handling and fallbacks - -## CLI Integration - -### Asset Embedding (`pkg/content/library.go`) -```go -func GetLibraryScript(minified bool) string { - if minified { - return libraryMinJS // Production: smaller file size - } - return libraryJS // Development: readable code -} -``` - -### HTML Injection (`pkg/content/injector.go`) -```go -func (i *Injector) InjectEditorAssets(doc *html.Node, isDevelopment bool, libraryScript string) { - // Injects the embedded library as inline \ No newline at end of file diff --git a/demo-site/index.html b/demo-site/index.html index 29496f0..316eb12 100644 --- a/demo-site/index.html +++ b/demo-site/index.html @@ -80,6 +80,8 @@
+ + \ No newline at end of file diff --git a/insertr-cli/cmd/servedev.go b/insertr-cli/cmd/servedev.go index ecc8cca..9f26e28 100644 --- a/insertr-cli/cmd/servedev.go +++ b/insertr-cli/cmd/servedev.go @@ -80,6 +80,12 @@ func runServedev(cmd *cobra.Command, args []string) { serveEditorAsset(w, r, assetPath) }) + // Handle insertr library files + http.HandleFunc("/insertr/", func(w http.ResponseWriter, r *http.Request) { + assetPath := strings.TrimPrefix(r.URL.Path, "/insertr/") + serveLibraryAsset(w, r, assetPath) + }) + // Handle all other requests with our enhanced file server http.Handle("/", fileServer) @@ -120,6 +126,24 @@ func serveEditorAsset(w http.ResponseWriter, r *http.Request, assetPath string) http.ServeFile(w, r, assetFile) } +// serveLibraryAsset serves the insertr library files from embedded assets +func serveLibraryAsset(w http.ResponseWriter, r *http.Request, assetPath string) { + w.Header().Set("Content-Type", "application/javascript") + + var script string + switch assetPath { + case "insertr.js": + script = content.GetLibraryScript(false) + case "insertr.min.js": + script = content.GetLibraryScript(true) + default: + http.NotFound(w, r) + return + } + + w.Write([]byte(script)) +} + // enhancedFileSystem wraps http.FileSystem to provide enhanced HTML serving type enhancedFileSystem struct { fs http.FileSystem diff --git a/insertr-cli/pkg/content/injector.go b/insertr-cli/pkg/content/injector.go index ac65a2e..b64e1ce 100644 --- a/insertr-cli/pkg/content/injector.go +++ b/insertr-cli/pkg/content/injector.go @@ -133,32 +133,17 @@ func (i *Injector) addContentAttributes(node *html.Node, contentID string, conte i.addClass(node, "insertr") } -// InjectEditorAssets adds editor JavaScript and CSS to HTML document +// InjectEditorAssets adds editor JavaScript to HTML document func (i *Injector) InjectEditorAssets(doc *html.Node, isDevelopment bool, libraryScript string) { - if !isDevelopment { - return // Only inject in development mode for now - } + // TODO: Implement script injection strategy when we have CDN hosting + // For now, script injection is disabled since HTML files should include their own script tags + // Future options: + // 1. Inject CDN script tag: + // 2. Inject local script tag for development: + // 3. Continue with inline injection for certain use cases - // Find the head element - head := i.findHeadElement(doc) - if head == nil { - return - } - - // Add inline script with embedded library - // Note: Using html.TextNode for scripts can cause issues with HTML entity encoding - // Instead, we'll insert the script tag as raw HTML - scriptHTML := fmt.Sprintf(``, libraryScript) - - // Parse the script HTML and append to head - scriptNodes, err := html.ParseFragment(strings.NewReader(scriptHTML), head) - if err == nil && len(scriptNodes) > 0 { - for _, node := range scriptNodes { - head.AppendChild(node) - } - } + // Currently disabled to avoid duplicate scripts + return } // findHeadElement finds the element in the document diff --git a/insertr-cli/pkg/content/library.go b/insertr-cli/pkg/content/library.go index 7427bc4..06a3f36 100644 --- a/insertr-cli/pkg/content/library.go +++ b/insertr-cli/pkg/content/library.go @@ -2,6 +2,7 @@ package content import ( _ "embed" + "fmt" ) // Embedded library assets @@ -24,3 +25,26 @@ func GetLibraryScript(minified bool) string { func GetLibraryVersion() string { return "1.0.0" } + +// GetLibraryURL returns the appropriate library URL for script injection +func GetLibraryURL(minified bool, isDevelopment bool) string { + if isDevelopment { + // Local development URLs - relative to served content + if minified { + return "/insertr/insertr.min.js" + } + return "/insertr/insertr.js" + } + + // Production URLs - use CDN + return GetLibraryCDNURL(minified) +} + +// GetLibraryCDNURL returns the CDN URL for production use +func GetLibraryCDNURL(minified bool) string { + version := GetLibraryVersion() + if minified { + return fmt.Sprintf("https://cdn.jsdelivr.net/npm/@insertr/lib@%s/dist/insertr.min.js", version) + } + return fmt.Sprintf("https://cdn.jsdelivr.net/npm/@insertr/lib@%s/dist/insertr.js", version) +} diff --git a/insertr-cli/scripts/rebuild-library.sh b/insertr-cli/scripts/rebuild-library.sh index 8356186..b34cb74 100755 --- a/insertr-cli/scripts/rebuild-library.sh +++ b/insertr-cli/scripts/rebuild-library.sh @@ -7,7 +7,7 @@ set -e echo "πŸ”„ Library changed, rebuilding..." -# Build the library +# Build the library (this will also copy to demo-site) cd ../lib npm run build --silent diff --git a/lib/package.json b/lib/package.json index 160f975..82fa9db 100644 --- a/lib/package.json +++ b/lib/package.json @@ -10,7 +10,9 @@ "src/" ], "scripts": { - "build": "rollup -c", + "build": "rollup -c && npm run copy:demo", + "build:only": "rollup -c", + "copy:demo": "cp dist/insertr.js ../demo-site/insertr.js", "watch": "rollup -c -w", "dev": "rollup -c -w", "serve": "node scripts/dev.js serve",