### Install Dependencies and Start Development Server Source: https://github.com/cloudcreate-ai/cloudcreate.ai/blob/main/README.md Run this command to install project dependencies and start the local development server. ```bash npm install && npm run dev ``` -------------------------------- ### SvelteKit Static Adapter Configuration for Cloudflare Pages Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Configure your `svelte.config.js` for static site generation using the `@sveltejs/adapter-static`. This setup is suitable for deployment on platforms like Cloudflare Pages. ```javascript // svelte.config.js import adapter from '@sveltejs/adapter-static'; import { PRERENDER_PATHS } from './src/lib/site-paths.js'; export default { kit: { prerender: { handleMissingId: 'ignore', // /table uses hash anchors; skip id validation entries: [...PRERENDER_PATHS], }, adapter: adapter({ pages: 'build', assets: 'build', fallback: undefined, precompress: false, strict: true, }), alias: { $lib: 'src/lib' }, }, }; ``` -------------------------------- ### Get Image Dimensions with createImageBitmap Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Reads pixel dimensions from an image File without decoding the full pixel buffer. Requires importing `getImageDimensions` from `$lib/imageProcessor.js`. ```javascript import { getImageDimensions } from '$lib/imageProcessor.js'; const file = new File([pngBytes], 'photo.png', { type: 'image/png' }); const { width, height } = await getImageDimensions(file); console.log(`${width} × ${height}`); // e.g. "1920 × 1080" ``` -------------------------------- ### Build Project for Production Source: https://github.com/cloudcreate-ai/cloudcreate.ai/blob/main/README.md Execute this command to build the project for production deployment. ```bash npm run build ``` -------------------------------- ### CloudCreate.ai Project Build and Deployment Commands Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt A collection of command-line instructions for local development, production builds, deployment, and Docker operations for the CloudCreate.ai project. ```bash # Local development npm install && npm run dev # Production build + sitemap generation npm run build # Deploy to Cloudflare Pages npm run deploy # Docker docker build -t cloudcreate-ai:latest . docker compose -f docker-compose.yml up -d --build # Pull public image docker pull ghcr.io/cloudcreate-ai/cloudcreate-ai:latest ``` -------------------------------- ### buildFileItem(file, id) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Constructs a standard item descriptor for batch tools, including a preview URL, detected format, and image dimensions. ```APIDOC ## buildFileItem(file, id) ### Description Builds the standard item shape used by compress, resize, and other batch tools — includes a `previewUrl` via `createObjectURL`, detected format, and image dimensions. ### Parameters - **file** (File) - The input file object. - **id** (number) - A unique identifier for the item. ### Returns - **object** - An item descriptor object with properties like `id`, `file`, `previewUrl`, `name`, `format`, `size`, `width`, `height`, and `status`. ### Example ```js import { buildFileItem } from '$lib/batchHelpers.js'; const file = /* File from input */; const item = await buildFileItem(file, 1); console.log(item); // { id: 1, file: File, previewUrl: "blob:...", name: "photo.jpg", format: "JPEG", size: 204800, width: 1920, height: 1080, status: "pending" } ``` ``` -------------------------------- ### Archive and Compress URL Parameter Helpers Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Functions to parse and build URL parameters specifically for archive and compression formats. Ensure the correct import path is used. ```javascript import { parseArchiveCompressQuery, buildArchiveCompressQuery } from '$lib/urlParams/archiveCompressQuery.js'; // Parse: /archive/compress?fmt=targz const sp = new URLSearchParams('fmt=targz'); const { format } = parseArchiveCompressQuery(sp); console.log(format); // "targz" // Build: format selector default const params = buildArchiveCompressQuery('zip'); console.log(params.toString()); // "fmt=zip" // Supported formats: "zip" | "gzip" | "targz" | "brotli" ``` -------------------------------- ### Build File Item Descriptor with Preview URL and Dimensions Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Constructs a standard item descriptor for batch tools. It includes a preview URL generated using `createObjectURL`, detected image format, and dimensions. Ensure a File object is available as input. ```javascript import { buildFileItem } from '$lib/batchHelpers.js'; const file = /* File from input */; const item = await buildFileItem(file, 1); console.log(item); // { // id: 1, // file: File, // previewUrl: "blob:...", // name: "photo.jpg", // format: "JPEG", // size: 204800, // width: 1920, // height: 1080, // status: "pending" // } ``` -------------------------------- ### generateAppStoreIcon(file) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Generates a 1024x1024 opaque PNG icon suitable for app stores. ```APIDOC ## generateAppStoreIcon(file) ### Description Center-crops to square, composites onto a white background (satisfying Apple's no-transparency rule), scales to 1024×1024, and encodes as PNG. ### Method `generateAppStoreIcon(file: File): Promise<{ blob: Blob, name: string }>" ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { generateAppStoreIcon } from '$lib/appStoreIcon.js'; const file = /* source image File */; const { blob, name } = await generateAppStoreIcon(file); console.log(name); // "my-logo-1024.png" console.log(blob.type); // "image/png" // Trigger download const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); ``` ### Response #### Success Response (200) - **blob** (Blob) - The generated 1024x1024 PNG icon as a Blob object. - **name** (string) - The suggested filename for the icon (e.g., "my-logo-1024.png"). #### Response Example ```json { "blob": "", "name": "my-logo-1024.png" } ``` ``` -------------------------------- ### Generate App Store Icon (1024x1024 PNG) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Creates a 1024x1024 opaque PNG App Store icon by center-cropping, compositing onto a white background, and scaling. Import `generateAppStoreIcon` from `$lib/appStoreIcon.js`. The function returns an object with the icon's Blob and name, suitable for triggering a download. ```javascript import { generateAppStoreIcon } from '$lib/appStoreIcon.js'; const file = /* source image File */; const { blob, name } = await generateAppStoreIcon(file); console.log(name); // "my-logo-1024.png" console.log(blob.type); // "image/png" // Trigger download const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); ``` -------------------------------- ### generateFavicons(file, sizes, options) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Generates multi-size PNG favicons from a source image, with an option to include a .ico file. ```APIDOC ## generateFavicons(file, sizes, options) ### Description Center-crops the source image to a square, then scales and encodes each requested size as PNG. Optionally packs a 16×16 PNG into a `.ico` container (PNG-in-ICO, Vista+). ### Method `generateFavicons(file: File, sizes: number[], options?: { includeIco?: boolean }): Promise>" ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { generateFavicons, FAVICON_SIZES } from '$lib/faviconGenerator.js'; const file = /* source image File */; const sizes = [16, 32, 48, 180, 192, 512]; const results = await generateFavicons(file, sizes, { includeIco: true }); for (const r of results) { console.log(r.name, r.format, r.blob.size); // "favicon-16x16.png" "png" // "favicon-32x32.png" "png" // ... // "favicon.ico" "ico" } // Available size definitions console.log(FAVICON_SIZES); // [ // { size: 16, name: 'favicon-16x16', desc: 'Browser tab' }, // { size: 32, name: 'favicon-32x32', desc: 'Browser tab (high DPI)' }, // { size: 48, name: 'favicon-48x48', desc: 'Windows site icon' }, // { size: 180, name: 'apple-touch-icon', desc: 'Apple Touch Icon' }, // { size: 192, name: 'android-chrome-192x192', desc: 'Android Chrome' }, // { size: 512, name: 'android-chrome-512x512', desc: 'PWA' }, // ] ``` ### Response #### Success Response (200) - **Array<{ name: string, format: string, blob: Blob }>**: An array of objects, where each object represents a generated favicon file. - **name** (string) - The filename of the favicon. - **format** (string) - The format of the favicon (e.g., 'png', 'ico'). - **blob** (Blob) - The favicon file as a Blob object. #### Response Example ```json [ { "name": "favicon-16x16.png", "format": "png", "blob": "" }, { "name": "favicon.ico", "format": "ico", "blob": "" } ] ``` ``` -------------------------------- ### URL Parameter Helpers: parseCropQuery, buildCropQuery Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Functions for serializing and deserializing crop page state to and from URLSearchParams. These helpers support short aliases for parameters like aspect ratio, quality, and format, enabling the creation of shareable links. ```APIDOC ## URL Parameter Helpers ### `parseCropQuery(sp)` Deserializes URLSearchParams into an object representing crop page state. ### `buildCropQuery(...)` Serializes crop page state into URLSearchParams. Supports custom ratios and various parameters. #### Parameters for `buildCropQuery`: - `aspectRatio` (number | string) - The desired aspect ratio (e.g., 16/9 or 'custom'). - `width` (number) - Custom width if `aspectRatio` is 'custom'. - `height` (number) - Custom height if `aspectRatio` is 'custom'. - `format` (string) - The target image format (e.g., 'webp', 'jpeg'). - `quality` (number) - The image quality setting (0-100). #### Example Usage: ```js import { parseCropQuery, buildCropQuery } from '$lib/urlParams/cropQuery.js'; // Parse a shareable URL const sp = new URLSearchParams('preset=16:9&q=85&f=webp'); const state = parseCropQuery(sp); // state: { aspectRatio: 1.7778, quality: 85, targetFormat: 'webp' } // Build a shareable URL from current state const params = buildCropQuery(16/9, 0, 0, 'webp', 85); console.log(params.toString()); // "preset=16%3A9&q=85&f=webp" // Custom ratio const params2 = buildCropQuery('custom', 4, 3, 'jpeg', 90); console.log(params2.toString()); // "preset=custom&cw=4&ch=3&q=90&f=jpeg" ``` ``` -------------------------------- ### URL Parameter Helpers: parseArchiveCompressQuery, buildArchiveCompressQuery Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Utilities for handling the archive format URL parameter. `parseArchiveCompressQuery` extracts the format from URLSearchParams, while `buildArchiveCompressQuery` constructs the parameter string for a given format. ```APIDOC ## URL Parameter Helpers ### `parseArchiveCompressQuery(sp)` Parses URLSearchParams to extract the archive format. ### `buildArchiveCompressQuery(format)` Builds URLSearchParams for the archive format. #### Parameters: - `format` (string) - The desired archive format. Supported formats: "zip" | "gzip" | "targz" | "brotli". #### Example Usage: ```js import { parseArchiveCompressQuery, buildArchiveCompressQuery } from '$lib/urlParams/archiveCompressQuery.js'; // Parse: /archive/compress?fmt=targz const sp = new URLSearchParams('fmt=targz'); const { format } = parseArchiveCompressQuery(sp); console.log(format); // "targz" // Build: format selector default const params = buildArchiveCompressQuery('zip'); console.log(params.toString()); // "fmt=zip" ``` ``` -------------------------------- ### Fetch and Normalize Batch Resizing Specifications Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Fetches a JSON array of spec rows for batch resizing and normalizes each row. Normalization includes type coercion, applying defaults (e.g., `quality: 75`, `format: 'webp'`), clamping values, and expanding abbreviations (e.g., `jpg` to `jpeg`). Can load default specs or normalize a custom row. ```javascript import { loadBatchSpecs, normalizeBatchSpecRow } from '$lib/batchSpecHelpers.js'; // Load the default built-in spec table const specs = await loadBatchSpecs(); // fetches /specs/batch-specs.json // Or normalise a custom row inline const row = normalizeBatchSpecRow({ name: 'op_flash_312x555', width: 312, height: 555, format: 'webp', quality: 85, quantity: 2, renameRule: '{prefix}_vertical', }); // { name: 'op_flash_312x555', width: 312, height: 555, format: 'webp', // quality: 85, maxSizeKb: undefined, quantity: 2, renameRule: '{prefix}_vertical' } ``` -------------------------------- ### SEO Metadata: resolveSeo, buildSeoTexts Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Functions for computing per-page SEO titles and descriptions. `resolveSeo` maps a logical path to an SEO specification, and `buildSeoTexts` applies this specification using a translation function to generate the final metadata strings. ```APIDOC ## SEO Metadata ### `resolveSeo(logicalPath)` Resolves the SEO specification for a given logical path. It prioritizes exact matches, then sidebar href matches, then longest prefix matches, falling back to a default. ### `buildSeoTexts(spec, t)` Applies the resolved SEO specification (`spec`) and a translation function (`t`) to generate the final `{ title, description }` strings for SEO metadata. #### Parameters: - `spec` (object) - The SEO specification object resolved by `resolveSeo`. - `t` (function) - A translation function (e.g., from an i18n library). #### Example Usage: ```js import { resolveSeo, buildSeoTexts } from '$lib/seoMeta.js'; import { t } from '$lib/i18n.js'; // Home page const homeSpec = resolveSeo('/'); const { title, description } = buildSeoTexts(homeSpec, t); // title: "CloudCreate.ai – Creative toolkit for the AI era" // description: "Creative toolkit for the AI era" // Tool page const cropSpec = resolveSeo('/image/crop'); const cropTexts = buildSeoTexts(cropSpec, t); // title: "Image Crop · CloudCreate.ai" // description: "Crop by drag or exact pixels—free or fixed ratios, pick output format; instant creative framing in the browser." // Unknown path falls back to site default const unknownSpec = resolveSeo('/some/unknown/path'); const unknownTexts = buildSeoTexts(unknownSpec, t); // title: "CloudCreate.ai – Creative toolkit for the AI era" ``` ``` -------------------------------- ### Compute Per-Page SEO Title and Description Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt These functions generate SEO metadata. `resolveSeo` maps a logical path to a `SeoSpec`, considering exact matches, sidebar href matches, longest prefixes, and fallbacks. `buildSeoTexts` then uses this spec with a translation function (`t()`) to produce the final `{ title, description }` strings. ```javascript import { resolveSeo, buildSeoTexts } from '$lib/seoMeta.js'; import { t } from '$lib/i18n.js'; // Home page const homeSpec = resolveSeo('/'); const { title, description } = buildSeoTexts(homeSpec, t); // title: "CloudCreate.ai – Creative toolkit for the AI era" // description: "Creative toolkit for the AI era" // Tool page const cropSpec = resolveSeo('/image/crop'); const cropTexts = buildSeoTexts(cropSpec, t); // title: "Image Crop · CloudCreate.ai" // description: "Crop by drag or exact pixels—free or fixed ratios, pick output format; instant creative framing in the browser." // Unknown path falls back to site default const unknownSpec = resolveSeo('/some/unknown/path'); const unknownTexts = buildSeoTexts(unknownSpec, t); // title: "CloudCreate.ai – Creative toolkit for the AI era" ``` -------------------------------- ### Generate Favicons and ICO Files Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Generates multi-size PNG favicons and an optional `.ico` file from a source image. Imports `generateFavicons` and `FAVICON_SIZES` from `$lib/faviconGenerator.js`. The function returns an array of objects, each containing the name, format, and Blob of the generated icon. ```javascript import { generateFavicons, FAVICON_SIZES } from '$lib/faviconGenerator.js'; const file = /* source image File */; const sizes = [16, 32, 48, 180, 192, 512]; const results = await generateFavicons(file, sizes, { includeIco: true }); for (const r of results) { console.log(r.name, r.format, r.blob.size); // "favicon-16x16.png" "png" // "favicon-32x32.png" "png" // ... // "favicon.ico" "ico" } // Available size definitions console.log(FAVICON_SIZES); // [ // { size: 16, name: 'favicon-16x16', desc: 'Browser tab' }, // { size: 32, name: 'favicon-32x32', desc: 'Browser tab (high DPI)' }, // { size: 48, name: 'favicon-48x48', desc: 'Windows site icon' }, // { size: 180, name: 'apple-touch-icon', desc: 'Apple Touch Icon' }, // { size: 192, name: 'android-chrome-192x192', desc: 'Android Chrome' }, // { size: 512, name: 'android-chrome-512x512', desc: 'PWA' }, // ] ``` -------------------------------- ### Locale-Aware Path Helpers Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt These helpers manage locale prefixes in URLs. Use `getLogicalPath` to strip prefixes, `pathForLocale` to generate locale-prefixed paths for language switching, and `localePath` to build internal links that preserve the current language prefix. ```javascript import { getLogicalPath, pathForLocale, localePath } from '$lib/localePath.js'; getLogicalPath('/en/image/compress'); // "/image/compress" getLogicalPath('/zh/pdf'); // "/pdf" getLogicalPath('/image/resize'); // "/image/resize" (no prefix → unchanged) getLogicalPath('/en'); // "/" pathForLocale('zh', '/en/image/crop'); // "/zh/image/crop" pathForLocale('en', '/pdf/compress'); // "/en/pdf/compress" // Keep current language when generating an internal link localePath('/zh/image/compress', '/image/batch'); // "/zh/image/batch" localePath('/en/tools', '/css/minify'); // "/en/css/minify" localePath('/pdf', '/pdf/compress'); // "/pdf/compress" ``` -------------------------------- ### Navigation & Tool Registry: findToolByHref, getFavoriteKeyForCurrentPage Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Utilities for resolving tool metadata from URLs and determining the canonical key for the current page, useful for navigation and favorite management. ```APIDOC ## Navigation & Tool Registry ### `findToolByHref(href)` **Description**: Looks up a tool's full metadata object from `ALL_SIDEBAR_GROUPS` based on its href. **Parameters**: - **href** (string): The URL path of the tool. **Returns**: - (object): The tool's metadata object (e.g., `{ id, titleKey, href, icon }`). ### `getFavoriteKeyForCurrentPage(pathname, urlHash)` **Description**: Computes the canonical favorite key for the active URL, stripping locale prefixes. **Parameters**: - **pathname** (string): The URL pathname. - **urlHash** (string, optional): The URL hash fragment. **Returns**: - (string): The canonical favorite key for the page. ### Usage Example ```js import { findToolByHref, getFavoriteKeyForCurrentPage } from '$lib/toolList.js'; const tool = findToolByHref('/image/compress'); // { id: 'compress', titleKey: 'home.compressTitle', href: '/image/compress', icon: '🗜️' } const key = getFavoriteKeyForCurrentPage('/zh/image/compress'); // "/image/compress" ``` ``` -------------------------------- ### Locale Routing: getLogicalPath, pathForLocale, localePath Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Helper functions for managing locale prefixes in URLs. `getLogicalPath` removes locale prefixes, `pathForLocale` generates paths with a specified locale, and `localePath` creates internal links that retain the current language prefix. ```APIDOC ## Locale Routing ### `getLogicalPath(pathname)` Strips locale prefixes (e.g., `/en`, `/zh`) from a given pathname to return the logical path. ### `pathForLocale(locale, pathname)` Generates a pathname with the specified locale prefix prepended. ### `localePath(pathname, logicalPath)` Builds an in-app href that preserves the current language prefix while using a provided logical path. #### Example Usage: ```js import { getLogicalPath, pathForLocale, localePath } from '$lib/localePath.js'; getLogicalPath('/en/image/compress'); // "/image/compress" getLogicalPath('/zh/pdf'); // "/pdf" getLogicalPath('/image/resize'); // "/image/resize" (no prefix → unchanged) getLogicalPath('/en'); // "/" pathForLocale('zh', '/en/image/crop'); // "/zh/image/crop" pathForLocale('en', '/pdf/compress'); // "/en/pdf/compress" // Keep current language when generating an internal link localePath('/zh/image/compress', '/image/batch'); // "/zh/image/batch" localePath('/en/tools', '/css/minify'); // "/en/css/minify" localePath('/pdf', '/pdf/compress'); // "/pdf/compress" ``` ``` -------------------------------- ### Persist Favorites and Recents with localStorage Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Use these functions to manage user preferences like favorites and recently used tools, which are persisted in localStorage. Ensure the necessary stores are imported. ```javascript import { favorites, recentlyUsed, toggleFavorite, recordToolUsed } from '$lib/stores/userPrefsStore.js'; import { get } from 'svelte/store'; // Add to favorites toggleFavorite('/image/crop'); console.log(get(favorites)); // ["/image/crop"] // Toggle off (already favorited) toggleFavorite('/image/crop'); console.log(get(favorites)); // [] // Record a tool visit (called in +layout.svelte on route change) recordToolUsed('/en/image/compress'); console.log(get(recentlyUsed)); // [{ href: '/image/compress', usedAt: 1718000000000 }] ``` -------------------------------- ### CSS Processing: minifyBasic, minifyAggressive, beautify Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt These functions allow for client-side processing of CSS. `minifyBasic` removes comments and whitespace. `minifyAggressive` performs additional optimizations like shortening values. `beautify` formats minified CSS for readability. ```APIDOC ## CSS Processing Functions ### `minifyBasic(css)` **Description**: Strips comments and excess whitespace from CSS. ### `minifyAggressive(css)` **Description**: Strips comments and excess whitespace, and additionally shortens values and removes redundancies. ### `beautify(css)` **Description**: Pretty-prints minified CSS. ### Usage Example ```js import { minifyBasic, minifyAggressive, beautify } from '$lib/cssTools.js'; const src = ` /* header styles */ .header { background-color: #ffffff; padding: 16px 16px 16px 16px; font-size: 1.0em; } `; const basic = minifyBasic(src); const aggressive = minifyAggressive(src); const pretty = beautify(aggressive); ``` ``` -------------------------------- ### Tool Metadata Resolution Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Utility functions to find tool metadata by URL path. `findToolByHref` retrieves full tool details, and `getFavoriteKeyForCurrentPage` generates a canonical key for the current page, useful for managing favorites. ```javascript import { findToolByHref, getFavoriteKeyForCurrentPage } from '$lib/toolList.js'; const tool = findToolByHref('/image/compress'); // { id: 'compress', titleKey: 'home.compressTitle', href: '/image/compress', icon: '🗜️' } const tool2 = findToolByHref('/table#table-convert'); // { id: 'tableConvert', ..., href: '/table', hash: '#table-convert', icon: '🔄' } // On /zh/image/compress — strips locale prefix, then finds the canonical key const key = getFavoriteKeyForCurrentPage('/zh/image/compress'); // "/image/compress" const key2 = getFavoriteKeyForCurrentPage('/table', '#table-convert'); // "/table#table-convert" ``` -------------------------------- ### assignInputsToSpecs(specs, fileItems) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Automatically matches uploaded images to spec rows based on aspect ratio. ```APIDOC ## assignInputsToSpecs(specs, fileItems) ### Description Groups spec rows by aspect ratio (to 2 decimal places), then selects the best-matching uploaded image for each group, returning `{ spec, assignedFile }` pairs. Unmatched rows get `assignedFile: null`. ### Parameters - **specs** (Array) - An array of spec objects, each with `name`, `width`, `height`, `format`, and `quality` properties. - **fileItems** (Array) - An array of file item objects, each with a `file` and dimensions (`width`, `height`). ### Returns - **Array** - An array of assignment objects, where each object contains a `spec` and an `assignedFile` (or `null` if no match). ### Example ```js import { assignInputsToSpecs } from '$lib/batchSpecHelpers.js'; const specs = [ { name: 'banner', width: 1200, height: 628, format: 'webp', quality: 85 }, { name: 'square', width: 500, height: 500, format: 'png', quality: 90 }, ]; const fileItems = [ { file: landscapeFile, width: 1920, height: 1005 }, // ratio ≈ 1.91 { file: squareFile, width: 800, height: 800 }, // ratio = 1.00 ]; const assignments = assignInputsToSpecs(specs, fileItems); // [ // { spec: { name: 'banner', ... }, assignedFile: landscapeFile }, // { spec: { name: 'square', ... }, assignedFile: squareFile }, // ] ``` ``` -------------------------------- ### Aggregate Compression Statistics Across a Batch Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Calculates total original bytes, total new bytes, and the reduction ratio percentage for all items with `status === 'done'`. Returns `null` if no items are completed. Input is an array of item objects, each potentially having `size`, `newSize`, and `status` properties. ```javascript import { computeTotalStats } from '$lib/batchHelpers.js'; const items = [ { status: 'done', size: 200000, newSize: 80000 }, { status: 'done', size: 150000, newSize: 70000 }, { status: 'pending', size: 100000 }, ]; const stats = computeTotalStats(items); // { totalOriginal: 350000, totalNew: 150000, ratio: 57.14 } // → "57.14% smaller overall" if (!stats) console.log('No completed items yet.'); ``` -------------------------------- ### Auto-Match Images to Spec Rows by Aspect Ratio Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Groups spec rows by aspect ratio (to two decimal places) and then selects the best-matching uploaded image for each group. Returns an array of `{ spec, assignedFile }` pairs. Unmatched spec rows will have `assignedFile: null`. Requires `specs` and `fileItems` arrays as input. ```javascript import { assignInputsToSpecs } from '$lib/batchSpecHelpers.js'; const specs = [ { name: 'banner', width: 1200, height: 628, format: 'webp', quality: 85 }, { name: 'square', width: 500, height: 500, format: 'png', quality: 90 }, ]; const fileItems = [ { file: landscapeFile, width: 1920, height: 1005 }, // ratio ≈ 1.91 { file: squareFile, width: 800, height: 800 }, // ratio = 1.00 ]; const assignments = assignInputsToSpecs(specs, fileItems); // [ // { spec: { name: 'banner', ... }, assignedFile: landscapeFile }, // { spec: { name: 'square', ... }, assignedFile: squareFile }, // ] ``` -------------------------------- ### Configure Google Analytics with gtag.js Source: https://github.com/cloudcreate-ai/cloudcreate.ai/blob/main/src/app.html This snippet initializes the Google Analytics data layer and configures the tracking ID. Ensure this is placed in the head of your HTML document. ```html window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-JTN9PC43N7'); %sveltekit.head% ``` -------------------------------- ### Serialize/Deserialize Crop Page State to URLSearchParams Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt These functions help manage the state of the image crop tool by converting it to and from URL search parameters. This allows for shareable links that restore the tool's exact configuration. Supports short aliases for parameters. ```javascript import { parseCropQuery, buildCropQuery } from '$lib/urlParams/cropQuery.js'; // Parse a shareable URL: /image/crop?preset=16:9&q=85&f=webp const sp = new URLSearchParams('preset=16:9&q=85&f=webp'); const state = parseCropQuery(sp); // { aspectRatio: 1.7778, quality: 85, targetFormat: 'webp' } // Build a shareable URL from current state const params = buildCropQuery(16/9, 0, 0, 'webp', 85); console.log(params.toString()); // "preset=16%3A9&q=85&f=webp" // Custom ratio const params2 = buildCropQuery('custom', 4, 3, 'jpeg', 90); console.log(params2.toString()); // "preset=custom&cw=4&ch=3&q=90&f=jpeg" ``` -------------------------------- ### Download Processed Blobs as a Timestamped ZIP Archive Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Bundles multiple processed blobs into a ZIP archive with a human-readable timestamp. If only one item is provided, it's downloaded directly. Duplicate filenames are automatically suffixed. Requires an array of objects, each with a `blob` and `outputName`. ```javascript import { downloadAsZip } from '$lib/batchHelpers.js'; const processed = [ { blob: new Blob([...]), outputName: 'hero.webp' }, { blob: new Blob([...]), outputName: 'thumb.webp' }, { blob: new Blob([...]), outputName: 'thumb.webp' }, // duplicate → "thumb_1.webp" ]; await downloadAsZip(processed, 'my-images.zip'); // → triggers download of "my-images-2025-06-15_12-30-45.zip" ``` -------------------------------- ### computeTotalStats(items) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Aggregates compression statistics across a batch of items, returning total original and new bytes, and the reduction ratio. ```APIDOC ## computeTotalStats(items) ### Description Returns total original bytes, total new bytes, and the reduction ratio percentage over all items that have `status === 'done'`. ### Parameters - **items** (Array) - An array of item objects, each potentially having `size`, `newSize`, and `status` properties. ### Returns - **object | null** - An object containing `totalOriginal`, `totalNew`, and `ratio` if there are completed items, otherwise `null`. ### Example ```js import { computeTotalStats } from '$lib/batchHelpers.js'; const items = [ { status: 'done', size: 200000, newSize: 80000 }, { status: 'done', size: 150000, newSize: 70000 }, { status: 'pending', size: 100000 }, ]; const stats = computeTotalStats(items); // { totalOriginal: 350000, totalNew: 150000, ratio: 57.14 } // → "57.14% smaller overall" if (!stats) console.log('No completed items yet.'); ``` ``` -------------------------------- ### Pull Public Container Image Source: https://github.com/cloudcreate-ai/cloudcreate.ai/blob/main/README.md Use this command to pull the latest public container image from GHCR for CloudCreate.ai. ```bash docker pull ghcr.io/cloudcreate-ai/cloudcreate-ai:latest ``` -------------------------------- ### User Preferences: toggleFavorite, recordToolUsed Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Functions to persist user favorites and recently used tools in localStorage. `toggleFavorite` adds or removes a tool from favorites. `recordToolUsed` logs a tool visit, maintaining a capped list of recently used tools. ```APIDOC ## User Preferences ### `toggleFavorite(href)` Adds or removes a tool href from the user's favorites list. ### `recordToolUsed(pathname, hash)` Records a tool visit, pushing it to a capped (8-item) recency list. Normalizes locale prefixes before storing. #### Example Usage: ```js import { favorites, recentlyUsed, toggleFavorite, recordToolUsed } from '$lib/stores/userPrefsStore.js'; import { get } from 'svelte/store'; // Add to favorites toggleFavorite('/image/crop'); console.log(get(favorites)); // ["/image/crop"] // Toggle off (already favorited) toggleFavorite('/image/crop'); console.log(get(favorites)); // [] // Record a tool visit recordToolUsed('/en/image/compress'); console.log(get(recentlyUsed)); // [{ href: '/image/compress', usedAt: }] ``` ``` -------------------------------- ### downloadAsZip(items, zipName) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Packs processed blobs into a ZIP archive with a timestamped name. Handles single item downloads directly. ```APIDOC ## downloadAsZip(items, zipName) ### Description If there is only one item it downloads directly; for multiple items it bundles them with `JSZip` and appends a human-readable timestamp (e.g. `images-2025-06-15_12-30-45.zip`). Duplicate filenames are auto-suffixed. ### Parameters - **items** (Array) - An array of objects, where each object has a `blob` and `outputName` property. - **zipName** (string) - The base name for the ZIP file. ### Example ```js import { downloadAsZip } from '$lib/batchHelpers.js'; const processed = [ { blob: new Blob([...]), outputName: 'hero.webp' }, { blob: new Blob([...]), outputName: 'thumb.webp' }, { blob: new Blob([...]), outputName: 'thumb.webp' }, // duplicate → "thumb_1.webp" ]; await downloadAsZip(processed, 'my-images.zip'); // → triggers download of "my-images-2025-06-15_12-30-45.zip" ``` ``` -------------------------------- ### Recursively Read Files from DataTransfer (Drag-and-Drop) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Traverses `FileSystemEntry` trees from a drag-and-drop event using `webkitGetAsEntry`. This preserves the internal folder structure of dragged folders, allowing for paths like `subfolder/image.png` to be maintained. The function returns an array of objects, each containing a `file` and its `name`. ```javascript import { readFilesFromDataTransfer } from '$lib/archiveTools.js'; document.addEventListener('drop', async (e) => { e.preventDefault(); const entries = await readFilesFromDataTransfer(e.dataTransfer); for (const { file, name } of entries) { console.log(name, file.size); // "src/assets/logo.png" 12345 // "src/components/Header.svelte" 6789 } }); ``` -------------------------------- ### loadBatchSpecs(url?) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Fetches and normalizes a JSON array of spec rows for batch resizing, applying defaults and clamping values. ```APIDOC ## loadBatchSpecs(url?) ### Description Fetches a JSON array of spec rows (used by the Image Batch tool) and normalises each row: coerces types, applies defaults (`quality: 75`, `format: 'webp'`), clamps values, and expands `jpg` → `jpeg`. ### Parameters - **url** (string, optional) - The URL to fetch the spec table JSON from. Defaults to a built-in spec table. ### Returns - **Promise>** - A promise that resolves to an array of normalized spec row objects. ### Example ```js import { loadBatchSpecs, normalizeBatchSpecRow } from '$lib/batchSpecHelpers.js'; // Load the default built-in spec table const specs = await loadBatchSpecs(); // fetches /specs/batch-specs.json // Or normalise a custom row inline const row = normalizeBatchSpecRow({ name: 'op_flash_312x555', width: 312, height: 555, format: 'webp', quality: 85, quantity: 2, renameRule: '{prefix}_vertical', }); // { name: 'op_flash_312x555', width: 312, height: 555, format: 'webp', // quality: 85, maxSizeKb: undefined, quantity: 2, renameRule: '{prefix}_vertical' } ``` ``` -------------------------------- ### Client-side CSS Processing Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Use these functions to minify or beautify CSS strings. `minifyBasic` removes comments and whitespace, `minifyAggressive` further optimizes values, and `beautify` formats minified CSS for readability. ```javascript import { minifyBasic, minifyAggressive, beautify } from '$lib/cssTools.js'; const src = ` /* header styles */ .header { background-color: #ffffff; padding: 16px 16px 16px 16px; font-size: 1.0em; } `; const basic = minifyBasic(src); // ".header{background-color:#ffffff;padding:16px 16px 16px 16px;font-size:1.0em;}" const aggressive = minifyAggressive(src); // ".header{background:#fff;padding:16px;font-size:1em;}" const pretty = beautify(aggressive); // ".header { // background: #fff; // padding: 16px; // font-size: 1em; // }" ``` -------------------------------- ### getImageDimensions(file) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Reads pixel dimensions from an image File without decoding the full pixel buffer, using `createImageBitmap` for efficiency. ```APIDOC ## getImageDimensions(file) ### Description Reads pixel dimensions from any image File without decoding the full pixel buffer into memory by using `createImageBitmap`. ### Method `getImageDimensions(file: File): Promise<{ width: number, height: number }>" ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { getImageDimensions } from '$lib/imageProcessor.js'; const file = new File([pngBytes], 'photo.png', { type: 'image/png' }); const { width, height } = await getImageDimensions(file); console.log(`${width} × ${height}`); // e.g. "1920 × 1080" ``` ### Response #### Success Response (200) - **width** (number) - The width of the image in pixels. - **height** (number) - The height of the image in pixels. #### Response Example ```json { "width": 1920, "height": 1080 } ``` ``` -------------------------------- ### Bilingual String Lookup and Locale Management Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Provides functions for internationalization (i18n) with English and Chinese support. `t` and `tLang` perform string lookups, while `setLocale` changes the active language and persists it to localStorage. ```javascript import { t, tLang, setLocale, locale } from '$lib/i18n.js'; // Reactive lookup (returns current locale's string) console.log(t('common.compress')); // "Compress" (en) or "压缩" (zh) console.log(t('home.compressTitle')); // "Image Compress" // Force English regardless of stored preference console.log(tLang('en', 'crop.title')); // "Image Crop" console.log(tLang('zh', 'crop.title')); // "图片裁剪" // Switch the whole app to Chinese setLocale('zh'); // Subscribe to locale changes locale.subscribe((lang) => { console.log('Locale changed to:', lang); // "zh" }); ``` -------------------------------- ### readFilesFromDataTransfer(dataTransfer) Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Recursively reads files from a drag-and-drop event's DataTransfer object, preserving folder structure. ```APIDOC ## readFilesFromDataTransfer(dataTransfer) ### Description Traverses `FileSystemEntry` trees (via `webkitGetAsEntry`) so that dragging entire folders preserves their internal paths (e.g. `subfolder/image.png`). ### Parameters - **dataTransfer** (DataTransfer) - The `dataTransfer` object from a drag-and-drop event. ### Returns - **Promise>** - A promise that resolves to an array of objects, where each object contains a `file` (File object) and its `name` (path). ### Example ```js import { readFilesFromDataTransfer } from '$lib/archiveTools.js'; document.addEventListener('drop', async (e) => { e.preventDefault(); const entries = await readFilesFromDataTransfer(e.dataTransfer); for (const { file, name } of entries) { console.log(name, file.size); // "src/assets/logo.png" 12345 // "src/components/Header.svelte" 6789 } }); ``` ``` -------------------------------- ### Table Tools: parseTableFile, tableToBlob Source: https://context7.com/cloudcreate-ai/cloudcreate.ai/llms.txt Functions for parsing and converting tabular data between various formats like CSV, TSV, XLSX, and JSON. ```APIDOC ## Table Data Tools ### `parseTableFile(file)` **Description**: Parses CSV, TSV, XLSX, or JSON files into a uniform row-column structure. **Parameters**: - **file** (File): The file object to parse. ### `tableToBlob(data, format)` **Description**: Serializes tabular data into a specified format and returns it as a Blob. **Parameters**: - **data** (object): The tabular data, typically with `headers` and `rows` properties. - **format** (string): The desired output format (e.g., 'csv', 'tsv', 'xlsx', 'json'). ### Usage Example ```js import { parseTableFile, tableToBlob, FORMATS } from '$lib/tableTools.js'; const csvFile = new File(['name,age\nAlice,30\nBob,25'], 'data.csv', { type: 'text/csv' }); const tableData = await parseTableFile(csvFile); // { headers: ['name', 'age'], rows: [['Alice', '30'], ['Bob', '25']] } console.log(FORMATS); // ['csv', 'tsv', 'xlsx', 'json'] const blob = await tableToBlob(tableData, 'xlsx'); // ... code to download the blob ... ``` ``` -------------------------------- ### SvelteKit Body Placeholder Source: https://github.com/cloudcreate-ai/cloudcreate.ai/blob/main/src/app.html This is a SvelteKit specific placeholder for the body content. It should be placed within the body tag of your HTML. ```html %sveltekit.body% ```