Compare commits

...

25 Commits

Author SHA1 Message Date
jaybe 13439a384f test(assets): grouped 경로 전략 검증 테스트 추가
Auto PR / open-pr (push) Successful in 21s
Auto Label PR / add-automerge-label (pull_request) Successful in 8s
CI / test (pull_request) Successful in 1m12s
2025-11-15 15:14:19 +09:00
jaybe a5b0f07f2a fix(ci): 누락 파일 추가 및 AssetManager 경로 전략 변경사항 포함
Auto PR / open-pr (push) Failing after 11s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 1m17s
2025-11-15 15:01:17 +09:00
jaybe 7e7eb1be15 feat(phase6): 자산 경로 구조 옵션(UI/미리보기/Export) + 폰트 preconnect 토글 + extras 자동 보강(robots/manifest) + 문서화
Auto PR / open-pr (push) Failing after 13s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Failing after 35s
2025-11-15 14:28:05 +09:00
jaybe 2d6afaf665 feat(font): Export Options에 폰트 preconnect 토글 추가 및 exporter 옵션 연동
Auto PR / open-pr (push) Failing after 14s
Auto Label PR / add-automerge-label (pull_request) Successful in 8s
CI / test (pull_request) Failing after 36s
2025-11-15 14:22:41 +09:00
jaybe 31eaa9343a feat(export-options): Google Sheets 템플릿 모드 옵션(UI+extras) 추가
Auto PR / open-pr (push) Successful in 22s
Auto Label PR / add-automerge-label (pull_request) Successful in 8s
CI / test (pull_request) Failing after 33s
2025-11-15 13:57:42 +09:00
jaybe 032372bb01 chore(assets): assets.json에 group/referencedAt 추가 및 AssetManager 참조 추적
Auto PR / open-pr (push) Successful in 26s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 59s
2025-11-15 13:44:23 +09:00
jaybe 176568f976 feat(assets): ZIP에 assets.json 포함 및 메타데이터(integrity 포함) 생성
Auto PR / open-pr (push) Successful in 23s
Auto Label PR / add-automerge-label (pull_request) Successful in 8s
CI / test (pull_request) Successful in 1m14s
2025-11-15 13:38:19 +09:00
jaybe 6a9a7939b2 chore: start Export Options UI polish (TDD)
Auto PR / open-pr (push) Successful in 23s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 1m14s
2025-11-15 13:25:32 +09:00
jaybe 894acbb6a1 Merge remote-tracking branch 'origin/main' into feat/manifest-robots-restore
Auto PR / open-pr (push) Successful in 18s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 1m16s
2025-11-15 13:24:32 +09:00
jaybe 899a1ba1a6 Merge pull request 'auto: PR for feat/manifest-robots-restore' (#55) from feat/manifest-robots-restore into main
CI / test (push) Successful in 57s
Auto PR / open-pr (push) Successful in 20s
Auto Label PR / add-automerge-label (pull_request) Successful in 9s
CI / test (pull_request) Successful in 1m2s
2025-11-15 04:09:15 +00:00
jaybe f385966f87 fix(exporter/head): manifest 링크와 theme-color 메타 추가로 테스트 실패 수정
Auto PR / open-pr (push) Failing after 10s
Auto Label PR / add-automerge-label (pull_request) Successful in 6s
CI / test (pull_request) Successful in 1m11s
2025-11-15 13:07:40 +09:00
jaybe c4d46a5de3 Merge remote-tracking branch 'origin/main' into feat/manifest-robots-restore
Auto PR / open-pr (push) Failing after 12s
Auto Label PR / add-automerge-label (pull_request) Successful in 8s
CI / test (pull_request) Failing after 36s
2025-11-15 12:59:19 +09:00
jaybe 2caffe9950 test(zip): Phase5 - robots/manifest 내용 검증 및 ZIP 빌드 스모크
Auto PR / open-pr (push) Failing after 4s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 59s
2025-11-15 12:45:56 +09:00
jaybe 8757809928 test(extras): robots/manifest 오버라이드 검증 테스트 복구
Auto PR / open-pr (push) Failing after 11s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 1m9s
2025-11-15 12:44:41 +09:00
jaybe 39c64e3acd Merge pull request 'auto: PR for feat/export-options-ui' (#43) from feat/export-options-ui into main
CI / test (push) Successful in 50s
2025-11-14 23:15:56 +00:00
jaybe df5786e418 Merge pull request 'auto: PR for feat/export-options-overrides' (#42) from feat/export-options-overrides into main
CI / test (push) Waiting to run
2025-11-14 23:13:57 +00:00
jaybe 76889080e8 feat(font): Google Fonts preconnect 추가 및 system-ui 폴백 TDD
Auto PR / open-pr (push) Successful in 20s
Auto Label PR / add-automerge-label (pull_request) Successful in 8s
CI / test (pull_request) Successful in 59s
2025-11-15 08:11:50 +09:00
jaybe 68c8c8ff15 feat(export-extras): manifest/robots 자동 생성 및 오버라이드 복구(TDD) 2025-11-15 08:11:16 +09:00
jaybe 9b8fbd6360 feat(export-ui): Display 드롭다운/테마컬러 HEX 검증 반영(TDD)
Auto PR / open-pr (push) Successful in 23s
CI / test (pull_request) Successful in 1m25s
Auto Label PR / add-automerge-label (pull_request) Failing after 13m45s
2025-11-15 07:37:42 +09:00
jaybe 8ada2d1947 feat(export-ui): Export 옵션 UI 추가(manifest short_name/start_url/display/theme_color, robots Disallow) 및 TDD 2025-11-15 02:35:52 +09:00
jaybe 1a405a54fa feat(export): extras 오버라이드 지원(robots/manifest) TDD 및 구현
Auto PR / open-pr (push) Successful in 22s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 1m27s
2025-11-15 02:26:54 +09:00
jaybe 5c23cf3873 feat(seo): theme-color 메타 추가 및 hero 이미지 width/height로 CLS 개선(TDD)
Auto PR / open-pr (push) Successful in 19s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 55s
2025-11-15 02:20:47 +09:00
jaybe cc2b3039a3 feat(head): manifest/ico 링크 반영 및 테스트 추가(manifest.link.tokens)
Auto PR / open-pr (push) Successful in 21s
Auto Label PR / add-automerge-label (pull_request) Successful in 8s
CI / test (pull_request) Successful in 55s
2025-11-15 02:15:44 +09:00
jaybe 0561c5d63c test(zip): ZIP 검증 강화 5차 - extras(robots.txt/manifest) 내용 검증 추가
Auto PR / open-pr (push) Successful in 19s
Auto Label PR / add-automerge-label (pull_request) Successful in 6s
CI / test (pull_request) Successful in 58s
2025-11-15 01:41:54 +09:00
jaybe e6c897a863 feat(export): site.webmanifest/robots.txt 자동 생성 및 extras 포함 (TDD)
Auto PR / open-pr (push) Successful in 19s
Auto Label PR / add-automerge-label (pull_request) Successful in 7s
CI / test (pull_request) Successful in 57s
2025-11-15 01:26:04 +09:00
21 changed files with 946 additions and 59 deletions
+58
View File
@@ -34,3 +34,61 @@ You can check out [the Next.js GitHub repository](https://github.com/vercel/next
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
## Export Bundle (Landing ZIP)
The Builder can export a production-ready ZIP that contains:
- index.html, styles.css, app.js
- assets/ hashed assets (optionally grouped by type)
- site.webmanifest, robots.txt
- Optional: sheets/ (Google Apps Script template)
- Metadata files: assets.json, assets.index.json
### Export Options UI
- Manifest
- Name, Short Name, Start URL, Display (dropdown), Theme Color (HEX only)
- Robots
- Disallow lines (textarea). Each line becomes a `Disallow:` rule.
- Google Sheets Template Mode
- Auto: include when `form.actionUrl` is empty
- Include: always include
- Exclude: never include
### site.webmanifest and robots.txt
- `site.webmanifest` is derived from page data; Export Options can override fields.
- `robots.txt` defaults to a permissive header and adds `Disallow` lines from UI.
### Asset paths and grouping
- AssetManager writes files to `assets/` with stable hash-based filenames.
- Path strategy can be configured:
- `flat` (default): `assets/<hash>.<ext>`
- `grouped`: `assets/images/...`, `assets/fonts/...`, `assets/other/...`
### assets.json
Structured metadata for all assets. Example fields per entry:
- originalName, mimeType, size
- hash8, ext, zipPath
- integrity: `sha256-<base64>` (placeholder, base64 of bytes)
- group: `images|fonts|other`
- referencedAt: array of `local:<originalName>` when referenced by the page
### assets.index.json
Simple index to quickly find assets by group:
- images: string[] of zip paths
- fonts: string[] of zip paths
- other: string[] of zip paths
### Google Sheets template (optional)
- When included, ZIP contains:
- `sheets/Code.gs`: minimal Apps Script handler (Web App)
- `sheets/README.txt`: setup instructions
- Inclusion is controlled by `sheetsMode` (Auto/Include/Exclude) and `form.actionUrl` in Auto mode.
+206 -8
View File
@@ -7,6 +7,8 @@ import { exportPage } from '@/lib/exporter/html'
import { AssetManager } from '@/lib/assets/assetManager' import { AssetManager } from '@/lib/assets/assetManager'
import { buildZip } from '@/lib/exporter/zip' import { buildZip } from '@/lib/exporter/zip'
import { buildExtrasForPage } from '@/lib/exporter/extras' import { buildExtrasForPage } from '@/lib/exporter/extras'
import { buildAssetsMetadata } from '@/lib/exporter/assets.meta'
import { buildAssetsIndex } from '@/lib/exporter/assets.index'
import type { Section } from '@/lib/state/store' import type { Section } from '@/lib/state/store'
import { createFormStore, type FormState } from '@/lib/state/formStore' import { createFormStore, type FormState } from '@/lib/state/formStore'
import FormBuilderPanel from '@/components/FormBuilderPanel' import FormBuilderPanel from '@/components/FormBuilderPanel'
@@ -48,6 +50,17 @@ export default function BuilderClientPage() {
const [ogImage, setOgImage] = useState<string>('') const [ogImage, setOgImage] = useState<string>('')
const [ga4MeasurementId, setGa4MeasurementId] = useState<string>('') const [ga4MeasurementId, setGa4MeasurementId] = useState<string>('')
const [metaPixelId, setMetaPixelId] = useState<string>('') const [metaPixelId, setMetaPixelId] = useState<string>('')
// Export Options (manifest/robots overrides)
const [manifestName, setManifestName] = useState<string>('')
const [manifestShortName, setManifestShortName] = useState<string>('')
const [manifestStartUrl, setManifestStartUrl] = useState<string>('')
const [manifestDisplay, setManifestDisplay] = useState<string>('')
const [manifestThemeColor, setManifestThemeColor] = useState<string>('')
const [robotsDisallow, setRobotsDisallow] = useState<string>('')
const [sheetsMode, setSheetsMode] = useState<'auto' | 'include' | 'exclude'>('auto')
const [assetPathStrategy, setAssetPathStrategy] = useState<'flat' | 'grouped'>('flat')
// Font optimization: allow toggling Google Fonts preconnect links in exported HTML
const [fontPreconnect, setFontPreconnect] = useState<boolean>(true)
const [viewport, setViewport] = useState<'desktop' | 'mobile'>(() => { const [viewport, setViewport] = useState<'desktop' | 'mobile'>(() => {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
try { try {
@@ -166,9 +179,22 @@ export default function BuilderClientPage() {
try { try {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const w = window as unknown as { __exportPreview?: () => { html: string; css: string; js: string } } const w = window as unknown as { __exportPreview?: () => { html: string; css: string; js: string } }
// Build an effective AssetManager based on selected path strategy
const buildEffectiveAm = (): AssetManager | undefined => {
const base = am ?? undefined
if (!base) return undefined
if (assetPathStrategy === 'flat') return base
const clone = new AssetManager({ maxBytes: 10 * 1024 * 1024, allowedExts: ['png', 'jpg', 'jpeg', 'webp', 'svg'], pathStrategy: assetPathStrategy })
for (const ref of base.list()) {
// re-add to apply new path strategy and recreate byOriginal mapping
clone.add({ name: ref.originalName, type: ref.mimeType, bytes: ref.bytes })
}
return clone
}
w.__exportPreview = () => { w.__exportPreview = () => {
try { try {
return exportPage(pageSchema.parse(pageData), { assetManager: am ?? undefined }) // Export preview with current optimization options
return exportPage(pageSchema.parse(pageData), { assetManager: buildEffectiveAm(), fontPreconnect })
} catch { } catch {
const fixed: Page = { const fixed: Page = {
...pageData, ...pageData,
@@ -178,16 +204,41 @@ export default function BuilderClientPage() {
spamProtection: pageData.form?.spamProtection ?? { honeypotFieldName: '_hp', minSubmitSeconds: 2 }, spamProtection: pageData.form?.spamProtection ?? { honeypotFieldName: '_hp', minSubmitSeconds: 2 },
}, },
} }
return exportPage(pageSchema.parse(fixed), { assetManager: am ?? undefined }) return exportPage(pageSchema.parse(fixed), { assetManager: buildEffectiveAm(), fontPreconnect })
} }
} }
} }
} catch {} } catch {}
}, [pageData, am]) }, [pageData, am, fontPreconnect, assetPathStrategy])
const doExport = useCallback(async () => { const doExport = useCallback(async () => {
const valid = pageSchema.parse(pageData) let valid = pageData as Page
const exported = exportPage(valid, { assetManager: am ?? undefined }) try {
valid = pageSchema.parse(pageData)
} catch {
const fixed: Page = {
...pageData,
form: {
actionUrl: pageData.form?.actionUrl ?? '',
fields: pageData.form?.fields ?? [],
spamProtection: pageData.form?.spamProtection ?? { honeypotFieldName: '_hp', minSubmitSeconds: 2 },
},
} as Page
valid = pageSchema.parse(fixed)
}
// Build an effective AssetManager based on selected path strategy
const buildEffectiveAm = (): AssetManager | undefined => {
const base = am ?? undefined
if (!base) return undefined
if (assetPathStrategy === 'flat') return base
const clone = new AssetManager({ maxBytes: 10 * 1024 * 1024, allowedExts: ['png', 'jpg', 'jpeg', 'webp', 'svg'], pathStrategy: assetPathStrategy })
for (const ref of base.list()) {
clone.add({ name: ref.originalName, type: ref.mimeType, bytes: ref.bytes })
}
return clone
}
// Respect font optimization toggle when exporting
const exported = exportPage(valid, { assetManager: buildEffectiveAm(), fontPreconnect })
try { try {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const w = window as unknown as { __captureExport?: boolean; __lastExport?: { html: string; css: string; js: string } } const w = window as unknown as { __captureExport?: boolean; __lastExport?: { html: string; css: string; js: string } }
@@ -196,11 +247,45 @@ export default function BuilderClientPage() {
} }
} }
} catch {} } catch {}
const assets = am ? am.toZipStructure() : {} const effectiveAm = (() => {
const extras = buildExtrasForPage(valid) const base = am ?? undefined
if (!base) return undefined
if (assetPathStrategy === 'flat') return base
const clone = new AssetManager({ maxBytes: 10 * 1024 * 1024, allowedExts: ['png', 'jpg', 'jpeg', 'webp', 'svg'], pathStrategy: assetPathStrategy })
for (const ref of base.list()) {
clone.add({ name: ref.originalName, type: ref.mimeType, bytes: ref.bytes })
}
return clone
})()
const assets = effectiveAm ? effectiveAm.toZipStructure() : {}
// Build overrides from UI options
const manifestOverrideBase: Record<string, string> = {}
if (manifestName && manifestName.trim().length > 0) manifestOverrideBase.name = manifestName.trim()
if (manifestShortName && manifestShortName.trim().length > 0) manifestOverrideBase.short_name = manifestShortName.trim()
if (manifestStartUrl && manifestStartUrl.trim().length > 0) manifestOverrideBase.start_url = manifestStartUrl.trim()
if (manifestDisplay && manifestDisplay.trim().length > 0) manifestOverrideBase.display = manifestDisplay.trim()
if (manifestThemeColor && manifestThemeColor.trim().length > 0) {
const v = manifestThemeColor.trim()
const hexOk = /^#([0-9a-fA-F]{3}){1,2}$/.test(v)
if (hexOk) {
manifestOverrideBase.theme_color = v
}
}
const manifestOverride = Object.keys(manifestOverrideBase).length > 0 ? (manifestOverrideBase as { name?: string; short_name?: string; start_url?: string; display?: string; theme_color?: string }) : undefined
const robotsTextOverride = (() => {
const lines = (robotsDisallow || '').split(/\n+/).map((s) => s.trim()).filter((s) => s.length > 0)
if (lines.length === 0) return undefined
const disallowLines = lines.map((l) => (l.startsWith('Disallow:') ? l : `Disallow: ${l}`))
return `User-agent: *\n${disallowLines.join('\n')}`
})()
const baseExtras = buildExtrasForPage(valid, { robotsText: robotsTextOverride, manifest: manifestOverride, sheetsMode })
const extras: Record<string, Uint8Array> = {
...baseExtras,
...(am ? { 'assets.json': buildAssetsMetadata(am), 'assets.index.json': buildAssetsIndex(am) } : {}),
}
const zipBytes = await buildZip({ html: exported.html, css: exported.css, js: exported.js, assets, extras }) const zipBytes = await buildZip({ html: exported.html, css: exported.css, js: exported.js, assets, extras })
download('landing.zip', zipBytes) download('landing.zip', zipBytes)
}, [pageData, am]) }, [pageData, am, manifestName, manifestShortName, manifestStartUrl, manifestDisplay, manifestThemeColor, robotsDisallow, sheetsMode, fontPreconnect, assetPathStrategy])
return ( return (
<div className="p-6 space-y-6"> <div className="p-6 space-y-6">
@@ -263,6 +348,119 @@ export default function BuilderClientPage() {
onSelect={(i) => setSelectedIndex(i)} onSelect={(i) => setSelectedIndex(i)}
/> />
</div> </div>
<div className="border rounded p-3 space-y-2">
<h2 className="text-sm font-semibold mb-1">Export Options</h2>
{/* Asset path strategy: flat vs grouped */}
<label className="block" htmlFor="ins-asset-path-strategy">
<span className="sr-only">Asset Path Strategy</span>
<select
id="ins-asset-path-strategy"
aria-label="Asset Path Strategy"
className="border rounded px-3 py-2 w-full"
value={assetPathStrategy}
onChange={(e) => setAssetPathStrategy(e.target.value as 'flat' | 'grouped')}
>
<option value="flat">Assets Path: Flat</option>
<option value="grouped">Assets Path: Grouped (images/fonts/other)</option>
</select>
</label>
{/* Font optimization toggle for Google Fonts preconnect */}
<label className="flex items-center gap-2" htmlFor="ins-font-preconnect">
<input
id="ins-font-preconnect"
type="checkbox"
aria-label="Font Preconnect"
checked={fontPreconnect}
onChange={(e) => setFontPreconnect(e.target.checked)}
/>
<span className="text-sm">Enable font preconnect (Google Fonts)</span>
</label>
<label className="block" htmlFor="ins-manifest-name">
<span className="sr-only">Manifest Name</span>
<input
id="ins-manifest-name"
aria-label="Manifest Name"
className="border rounded px-3 py-2 w-full"
value={manifestName}
onChange={(e) => setManifestName(e.target.value)}
placeholder="My App"
/>
</label>
<label className="block" htmlFor="ins-manifest-short-name">
<span className="sr-only">Manifest Short Name</span>
<input
id="ins-manifest-short-name"
aria-label="Manifest Short Name"
className="border rounded px-3 py-2 w-full"
value={manifestShortName}
onChange={(e) => setManifestShortName(e.target.value)}
placeholder="MyApp"
/>
</label>
<label className="block" htmlFor="ins-manifest-start-url">
<span className="sr-only">Manifest Start URL</span>
<input
id="ins-manifest-start-url"
aria-label="Manifest Start URL"
className="border rounded px-3 py-2 w-full"
value={manifestStartUrl}
onChange={(e) => setManifestStartUrl(e.target.value)}
placeholder="/"
/>
</label>
<label className="block" htmlFor="ins-manifest-display">
<span className="sr-only">Manifest Display</span>
<select
id="ins-manifest-display"
aria-label="Manifest Display"
className="border rounded px-3 py-2 w-full"
value={manifestDisplay}
onChange={(e) => setManifestDisplay(e.target.value)}
>
<option value="">(default)</option>
<option value="standalone">standalone</option>
<option value="minimal-ui">minimal-ui</option>
<option value="browser">browser</option>
</select>
</label>
<label className="block" htmlFor="ins-manifest-theme-color">
<span className="sr-only">Manifest Theme Color</span>
<input
id="ins-manifest-theme-color"
aria-label="Manifest Theme Color"
className="border rounded px-3 py-2 w-full"
value={manifestThemeColor}
onChange={(e) => setManifestThemeColor(e.target.value)}
placeholder="#0ea5e9"
/>
</label>
<label className="block" htmlFor="ins-robots-disallow">
<span className="sr-only">Robots Disallow</span>
<textarea
id="ins-robots-disallow"
aria-label="Robots Disallow"
className="border rounded px-3 py-2 w-full"
rows={3}
value={robotsDisallow}
onChange={(e) => setRobotsDisallow(e.target.value)}
placeholder="/private\n/tmp"
/>
</label>
<label className="block" htmlFor="ins-sheets-mode">
<span className="sr-only">Google Sheets Template Mode</span>
<select
id="ins-sheets-mode"
aria-label="Google Sheets Template Mode"
className="border rounded px-3 py-2 w-full"
value={sheetsMode}
onChange={(e) => setSheetsMode(e.target.value as 'auto'|'include'|'exclude')}
>
<option value="auto">Sheets Template: Auto</option>
<option value="include">Sheets Template: Include</option>
<option value="exclude">Sheets Template: Exclude</option>
</select>
</label>
</div>
</div> </div>
} }
right={ right={
@@ -0,0 +1,67 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import BuilderClientPage from '@/components/BuilderClientPage'
vi.mock('next-intl', () => {
return {
useTranslations: () => (key: string) => key,
}
})
const buildZipSpy = vi.fn(async (_arg: {
html: string
css: string
js: string
assets: Record<string, Uint8Array>
extras?: Record<string, Uint8Array>
}) => new Uint8Array([80, 75]))
vi.mock('@/lib/exporter/zip', () => {
return {
buildZip: (arg: {
html: string
css: string
js: string
assets: Record<string, Uint8Array>
extras?: Record<string, Uint8Array>
}) => buildZipSpy(arg),
}
})
describe('Export Options UI → manifest fields', () => {
it('passes short_name/start_url/display/theme_color to extras manifest JSON', async () => {
render(<BuilderClientPage />)
const shortName = 'MyApp'
const startUrl = '/home'
const display = 'minimal-ui'
const themeColor = '#112233'
const snInput = await screen.findByLabelText('Manifest Short Name')
fireEvent.change(snInput, { target: { value: shortName } })
const startInput = await screen.findByLabelText('Manifest Start URL')
fireEvent.change(startInput, { target: { value: startUrl } })
const displayInput = await screen.findByLabelText('Manifest Display')
fireEvent.change(displayInput, { target: { value: display } })
const colorInput = await screen.findByLabelText('Manifest Theme Color')
fireEvent.change(colorInput, { target: { value: themeColor } })
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
fireEvent.click(exportBtn)
expect(buildZipSpy).toHaveBeenCalled()
const first = buildZipSpy.mock.calls[0]
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
const td = new TextDecoder()
const manifestRaw = td.decode(extras['site.webmanifest'])
const manifest = JSON.parse(manifestRaw)
expect(manifest.short_name).toBe(shortName)
expect(manifest.start_url).toBe(startUrl)
expect(manifest.display).toBe(display)
expect(manifest.theme_color).toBe(themeColor)
})
})
@@ -0,0 +1,64 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import BuilderClientPage from '@/components/BuilderClientPage'
vi.mock('next-intl', () => {
return {
useTranslations: () => (key: string) => key,
}
})
const buildZipSpy = vi.fn(async (_arg: {
html: string
css: string
js: string
assets: Record<string, Uint8Array>
extras?: Record<string, Uint8Array>
}) => new Uint8Array([80, 75]))
vi.mock('@/lib/exporter/zip', () => {
return {
buildZip: (arg: {
html: string
css: string
js: string
assets: Record<string, Uint8Array>
extras?: Record<string, Uint8Array>
}) => buildZipSpy(arg),
}
})
describe('Export Options UI polish', () => {
it('uses a dropdown for Manifest Display and passes selected value', async () => {
render(<BuilderClientPage />)
// choose display = minimal-ui
const displaySelect = await screen.findByLabelText('Manifest Display')
fireEvent.change(displaySelect, { target: { value: 'minimal-ui' } })
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
fireEvent.click(exportBtn)
const first = buildZipSpy.mock.calls[0]
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
const td = new TextDecoder()
const manifest = JSON.parse(td.decode(extras['site.webmanifest']))
expect(manifest.display).toBe('minimal-ui')
})
it('ignores invalid theme_color override and keeps default theme when not a hex', async () => {
render(<BuilderClientPage />)
const colorInput = await screen.findByLabelText('Manifest Theme Color')
fireEvent.change(colorInput, { target: { value: 'blue' } }) // invalid hex
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
fireEvent.click(exportBtn)
const first = buildZipSpy.mock.calls[0]
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
const td = new TextDecoder()
const manifest = JSON.parse(td.decode(extras['site.webmanifest']))
expect(manifest.theme_color).toBe('#0ea5e9') // default from page.theme.primaryColor
})
})
+60
View File
@@ -0,0 +1,60 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import BuilderClientPage from '@/components/BuilderClientPage'
vi.mock('next-intl', () => {
return {
useTranslations: () => (key: string) => key,
}
})
const buildZipSpy = vi.fn(async (_arg: {
html: string
css: string
js: string
assets: Record<string, Uint8Array>
extras?: Record<string, Uint8Array>
}) => new Uint8Array([80, 75]))
vi.mock('@/lib/exporter/zip', () => {
return {
buildZip: (arg: {
html: string
css: string
js: string
assets: Record<string, Uint8Array>
extras?: Record<string, Uint8Array>
}) => buildZipSpy(arg),
}
})
describe('Export Options UI → extras overrides', () => {
it('passes manifest.name and robots Disallow to buildExtrasForPage via buildZip extras', async () => {
render(<BuilderClientPage />)
const manifestName = 'My App Custom'
const robotsDisallow = '/private\n/tmp'
const nameInput = await screen.findByLabelText('Manifest Name')
fireEvent.change(nameInput, { target: { value: manifestName } })
const robotsInput = await screen.findByLabelText('Robots Disallow')
fireEvent.change(robotsInput, { target: { value: robotsDisallow } })
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
fireEvent.click(exportBtn)
expect(buildZipSpy).toHaveBeenCalled()
const first = buildZipSpy.mock.calls[0]
expect(first && first[0]).toBeTruthy()
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
const td = new TextDecoder()
const manifestRaw = td.decode(extras['site.webmanifest'])
const robotsRaw = td.decode(extras['robots.txt'])
const manifest = JSON.parse(manifestRaw)
expect(manifest.name).toBe(manifestName)
expect(robotsRaw).toMatch(/Disallow: \/private/)
expect(robotsRaw).toMatch(/Disallow: \/tmp/)
})
})
+26
View File
@@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest'
import { AssetManager } from '@/lib/assets/assetManager'
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
describe('AssetManager pathStrategy grouped', () => {
it('writes assets under assets/images and assets/fonts when grouped', async () => {
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2'], pathStrategy: 'grouped' })
const img = await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(10) })
const font = await am.add({ name: 'main.woff2', type: 'font/woff2', bytes: u8(12) })
expect(img.path).toMatch(/^assets\/images\/[0-9a-f]{8}\.png$/)
expect(font.path).toMatch(/^assets\/fonts\/[0-9a-f]{8}\.woff2$/)
const zip = am.toZipStructure()
const keys = Object.keys(zip)
expect(keys.some(k => /^assets\/images\//.test(k))).toBe(true)
expect(keys.some(k => /^assets\/fonts\//.test(k))).toBe(true)
})
it('rewriteUrl marks referenced originals and returns grouped path', async () => {
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png'], pathStrategy: 'grouped' })
const img = await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(10) })
const rewritten = am.rewriteUrl('local:hero.png')
expect(rewritten).toBe(img.path)
expect(am.referencedList()).toContain('hero.png')
})
})
+20 -1
View File
@@ -16,6 +16,7 @@ export type AssetRef = {
export type AssetManagerOptions = { export type AssetManagerOptions = {
maxBytes: number maxBytes: number
allowedExts: string[] // e.g., ['png','jpg','jpeg','webp','svg'] allowedExts: string[] // e.g., ['png','jpg','jpeg','webp','svg']
pathStrategy?: 'flat' | 'grouped'
} }
function extOf(name: string): string { function extOf(name: string): string {
@@ -36,12 +37,15 @@ function hash8(bytes: Uint8Array): string {
export class AssetManager { export class AssetManager {
private readonly maxBytes: number private readonly maxBytes: number
private readonly allowed: Set<string> private readonly allowed: Set<string>
private readonly pathStrategy: 'flat' | 'grouped'
private byHash = new Map<string, AssetRef>() private byHash = new Map<string, AssetRef>()
private byOriginal = new Map<string, string>() // originalName -> path private byOriginal = new Map<string, string>() // originalName -> path
private referenced = new Set<string>() // originalName referenced via rewrite
constructor(opts: AssetManagerOptions) { constructor(opts: AssetManagerOptions) {
this.maxBytes = opts.maxBytes this.maxBytes = opts.maxBytes
this.allowed = new Set(opts.allowedExts.map((e) => e.toLowerCase())) this.allowed = new Set(opts.allowedExts.map((e) => e.toLowerCase()))
this.pathStrategy = opts.pathStrategy ?? 'flat'
} }
async add(file: AssetInput): Promise<AssetRef> { async add(file: AssetInput): Promise<AssetRef> {
@@ -60,7 +64,7 @@ export class AssetManager {
return existing return existing
} }
const path = `assets/${h}.${ext}` const path = this.makePath(h, ext, file.type)
const ref: AssetRef = { const ref: AssetRef = {
originalName: file.name, originalName: file.name,
mimeType: file.type, mimeType: file.type,
@@ -91,8 +95,23 @@ export class AssetManager {
if (urlOrLocalRef.startsWith('local:')) { if (urlOrLocalRef.startsWith('local:')) {
const key = urlOrLocalRef.slice('local:'.length) const key = urlOrLocalRef.slice('local:'.length)
const p = this.byOriginal.get(key) const p = this.byOriginal.get(key)
if (p) this.referenced.add(key)
return p ?? urlOrLocalRef return p ?? urlOrLocalRef
} }
return urlOrLocalRef return urlOrLocalRef
} }
referencedList(): string[] {
return Array.from(this.referenced)
}
private makePath(hash8: string, ext: string, mime: string): string {
if (this.pathStrategy === 'grouped') {
let group = 'other'
if (mime.startsWith('image/')) group = 'images'
else if (mime.startsWith('font/')) group = 'fonts'
return `assets/${group}/${hash8}.${ext}`
}
return `assets/${hash8}.${ext}`
}
} }
+22
View File
@@ -0,0 +1,22 @@
import { describe, it, expect } from 'vitest'
import { AssetManager } from '@/lib/assets/assetManager'
import { buildAssetsIndex } from '@/lib/exporter/assets.index'
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
describe('Assets index builder', () => {
it('groups assets by mime into images/fonts/other and lists zipPath', async () => {
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2','txt'] })
await am.add({ name: 'a.png', type: 'image/png', bytes: u8(4) })
await am.add({ name: 'b.woff2', type: 'font/woff2', bytes: u8(6) })
await am.add({ name: 'c.txt', type: 'text/plain', bytes: u8(2) })
const bytes = buildAssetsIndex(am)
const obj = JSON.parse(new TextDecoder().decode(bytes)) as { images: string[]; fonts: string[]; other: string[] }
expect(obj.images.length).toBe(1)
expect(obj.fonts.length).toBe(1)
expect(obj.other.length).toBe(1)
expect(obj.images[0]).toMatch(/^assets\/[0-9a-f]{8}\.png$/)
expect(obj.fonts[0]).toMatch(/^assets\/[0-9a-f]{8}\.woff2$/)
expect(obj.other[0]).toMatch(/^assets\/[0-9a-f]{8}\.txt$/)
})
})
+21
View File
@@ -0,0 +1,21 @@
import type { AssetManager } from '@/lib/assets/assetManager'
export type AssetsIndex = {
images: string[]
fonts: string[]
other: string[]
}
export function buildAssetsIndex(am: AssetManager): Uint8Array {
const images: string[] = []
const fonts: string[] = []
const other: string[] = []
for (const ref of am.list()) {
if (ref.mimeType.startsWith('image/')) images.push(ref.path)
else if (ref.mimeType.startsWith('font/')) fonts.push(ref.path)
else other.push(ref.path)
}
const obj: AssetsIndex = { images, fonts, other }
const json = JSON.stringify(obj, null, 2)
return new TextEncoder().encode(json)
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, it, expect } from 'vitest'
import { AssetManager } from '@/lib/assets/assetManager'
import { buildAssetsMetadata } from '@/lib/exporter/assets.meta'
import type { AssetMetaItem } from '@/lib/exporter/assets.meta'
function u8(n: number): Uint8Array {
const arr = new Uint8Array(n)
for (let i = 0; i < n; i++) arr[i] = (i * 31) & 0xff
return arr
}
describe('Assets metadata builder', () => {
it('emits assets.json with originalName/mime/size/hash/ext/zipPath', async () => {
const am = new AssetManager({ maxBytes: 1024 * 1024, allowedExts: ['png'] })
const bytes = u8(10)
await am.add({ name: 'hero.png', type: 'image/png', bytes })
const metaBytes = buildAssetsMetadata(am)
const json = new TextDecoder().decode(metaBytes)
const obj = JSON.parse(json) as { assets: AssetMetaItem[] }
expect(Array.isArray(obj.assets)).toBe(true)
expect(obj.assets.length).toBe(1)
const a = obj.assets[0]
expect(a.originalName).toBe('hero.png')
expect(a.mimeType).toBe('image/png')
expect(a.size).toBe(bytes.byteLength)
expect(a.ext).toBe('png')
expect(a.hash8).toMatch(/^[0-9a-f]{8}$/)
expect(a.zipPath).toMatch(/^assets\/[0-9a-f]{8}\.png$/)
})
})
+41
View File
@@ -0,0 +1,41 @@
import type { AssetManager } from '@/lib/assets/assetManager'
export type AssetMetaItem = {
originalName: string
mimeType: string
size: number
hash8: string
ext: string
zipPath: string
integrity: string
group: 'images' | 'fonts' | 'other'
referencedAt: string[]
}
export function buildAssetsMetadata(am: AssetManager): Uint8Array {
const list = am.list()
const referenced = new Set(am.referencedList())
const items: AssetMetaItem[] = list.map((ref) => {
// Browser-safe synchronous integrity: base64 of bytes as placeholder
const b64 = Buffer.from(ref.bytes).toString('base64')
const group: 'images' | 'fonts' | 'other' = ref.mimeType.startsWith('image/')
? 'images'
: ref.mimeType.startsWith('font/')
? 'fonts'
: 'other'
const referencedAt = referenced.has(ref.originalName) ? [`local:${ref.originalName}`] : []
return {
originalName: ref.originalName,
mimeType: ref.mimeType,
size: ref.bytes.byteLength,
hash8: ref.hash8,
ext: ref.ext,
zipPath: ref.path,
integrity: `sha256-${b64}`,
group,
referencedAt,
}
})
const json = JSON.stringify({ assets: items }, null, 2)
return new TextEncoder().encode(json)
}
@@ -0,0 +1,27 @@
import { describe, it, expect } from 'vitest'
import { exportPage } from '@/lib/exporter/html'
import { pageSchema, type Page } from '@/lib/schema/page'
import { AssetManager } from '@/lib/assets/assetManager'
function makePage(): Page {
return pageSchema.parse({
title: 'Path Strategy',
locale: 'en',
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'local:hero.png' } } ],
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
seo: { title: 't', description: 'd' },
})
}
describe('자산 경로 구조 옵션', () => {
it('grouped 전략일 때 이미지가 assets/images/ 경로로 렌더된다', async () => {
const page = makePage()
const am = new AssetManager({ maxBytes: 1024 * 1024, allowedExts: ['png'], pathStrategy: 'grouped' })
// add hero image asset
const bytes = new Uint8Array([1,2,3,4,5])
await am.add({ name: 'hero.png', type: 'image/png', bytes })
const out = exportPage(page, { assetManager: am })
expect(out.html).toMatch(/assets\/images\/[a-f0-9]{8}\.png/i)
})
})
+44
View File
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest'
import { buildExtrasForPage } from '@/lib/exporter/extras'
import { pageSchema, type Page } from '@/lib/schema/page'
function makePage(): Page {
return pageSchema.parse({
title: 'My Product',
locale: 'en',
theme: { primaryColor: '#0ea5e9', fontFamily: 'Inter' },
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: '', imageUrl: 'https://example.com/hero.png' } } ],
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
seo: { title: 't', description: 'd' },
})
}
function toStr(bytes: Uint8Array) {
return new TextDecoder().decode(bytes)
}
describe('extras 자동 보강', () => {
it('manifest: 잘못된 theme_color는 무시하고 기본(primaryColor) 사용', () => {
const page = makePage()
const out = buildExtrasForPage(page, { manifest: { theme_color: 'not-a-hex' } })
const manifest = JSON.parse(toStr(out['site.webmanifest']))
expect(manifest.theme_color).toBe('#0ea5e9')
})
it('manifest: short_name은 12자 이내로 자동 절단', () => {
const page = makePage()
const out = buildExtrasForPage(page, { manifest: { name: 'Super Long Product Name' } })
const manifest = JSON.parse(toStr(out['site.webmanifest']))
expect(manifest.short_name.length).toBeLessThanOrEqual(12)
})
it('robots: 주어진 plain 경로 목록을 자동으로 User-agent 헤더와 Disallow 라인으로 보강', () => {
const page = makePage()
const robotsPlain = "/admin\n/private"
const out = buildExtrasForPage(page, { robotsText: robotsPlain })
const robots = toStr(out['robots.txt'])
expect(robots).toMatch(/^User-agent: \*/)
expect(robots).toMatch(/Disallow: \/admin/)
expect(robots).toMatch(/Disallow: \/private/)
})
})
+45
View File
@@ -0,0 +1,45 @@
import { describe, it, expect } from 'vitest'
import { pageSchema, type Page } from '@/lib/schema/page'
import { buildExtrasForPage } from '@/lib/exporter/extras'
function makePage(): Page {
return pageSchema.parse({
title: 'Overrides',
locale: 'en',
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
seo: { title: 't', description: 'd' },
})
}
describe('extras 오버라이드', () => {
it('robots.txt Disallow 오버라이드가 반영된다', () => {
const page = makePage()
const extras = buildExtrasForPage(page, { robotsText: 'User-agent: *\nDisallow: /admin\nDisallow: /private' })
const robots = Buffer.from(extras['robots.txt']).toString('utf8')
expect(robots).toContain('User-agent: *')
expect(robots).toContain('Disallow: /admin')
expect(robots).toContain('Disallow: /private')
})
it('manifest 필드 오버라이드(name/short_name/start_url/display/theme_color)가 반영된다', () => {
const page = makePage()
const extras = buildExtrasForPage(page, {
manifest: {
name: 'My App',
short_name: 'MyApp',
start_url: '/start',
display: 'minimal-ui',
theme_color: '#123abc',
},
})
const manifestStr = Buffer.from(extras['site.webmanifest']).toString('utf8')
const manifest = JSON.parse(manifestStr)
expect(manifest.name).toBe('My App')
expect(manifest.short_name).toBe('MyApp')
expect(manifest.start_url).toBe('/start')
expect(manifest.display).toBe('minimal-ui')
expect(manifest.theme_color).toBe('#123abc')
})
})
+74 -35
View File
@@ -1,44 +1,83 @@
import type { Page } from '@/lib/schema/page' import type { Page } from '@/lib/schema/page'
// Sheets 템플릿 등 ZIP 루트/서브 경로에 포함할 추가 파일(extras)을 구성한다. export type ExtrasOverrides = {
// - actionUrl이 비어있을 때만 Google Apps Script 템플릿을 포함한다. robotsText?: string
export function buildExtrasForPage(page: Page): Record<string, Uint8Array> { manifest?: Partial<{
const extras: Record<string, Uint8Array> = {} name: string
const te = new TextEncoder() short_name: string
start_url: string
display: string
theme_color: string
}>
sheetsMode?: 'auto' | 'include' | 'exclude'
}
const hasAction = !!(page.form?.actionUrl && page.form.actionUrl.trim().length > 0) function toBytes(s: string): Uint8Array {
if (!hasAction) { return new TextEncoder().encode(s)
const code = `// Google Apps Script (Code.gs) }
// - Web App 으로 배포 후, 아래 doPost 핸들러가 폼 데이터를 수신합니다.
// - 시트에 저장하거나 이메일 전송 로직을 추가하세요. function buildRobots(base?: string): string {
if (base && base.trim().length > 0) {
const s = base.trim()
if (/^User-agent:/i.test(s)) return s
const lines = s.split(/\n+/).map((l) => l.trim()).filter((l) => l.length > 0)
if (lines.length === 0) return 'User-agent: *\n'
const disallowLines = lines.map((l) => (l.startsWith('Disallow:') ? l : `Disallow: ${l}`))
return `User-agent: *\n${disallowLines.join('\n')}`
}
return 'User-agent: *\n'
}
function deriveManifest(page: Page) {
const name = page.title || 'Landing'
const short_name = name.length > 12 ? name.slice(0, 12) : name
const start_url = '/'
const display = 'standalone'
const theme_color = page.theme?.primaryColor || '#0ea5e9'
return { name, short_name, start_url, display, theme_color }
}
export function buildExtrasForPage(page: Page, overrides?: ExtrasOverrides): Record<string, Uint8Array> {
const out: Record<string, Uint8Array> = {}
// robots.txt
const robotsText = buildRobots(overrides?.robotsText)
out['robots.txt'] = toBytes(robotsText)
// site.webmanifest (auto-enrich and safe-merge)
const manifestBase = deriveManifest(page)
const ov = overrides?.manifest || {}
const name = ov.name && ov.name.trim().length > 0 ? ov.name : manifestBase.name
const short_name = ov.short_name && ov.short_name.trim().length > 0
? ov.short_name
: (name.length > 12 ? name.slice(0, 12) : name)
const start_url = ov.start_url && ov.start_url.trim().length > 0 ? ov.start_url : manifestBase.start_url
const display = ov.display && ov.display.trim().length > 0 ? ov.display : manifestBase.display
const hexOk = ov.theme_color ? /^#([0-9a-fA-F]{3}){1,2}$/.test(ov.theme_color) : false
const theme_color = hexOk ? (ov.theme_color as string) : manifestBase.theme_color
const manifestMerged = { name, short_name, start_url, display, theme_color }
const manifestJson = JSON.stringify(manifestMerged, null, 2)
out['site.webmanifest'] = toBytes(manifestJson)
// Google Sheets 템플릿: 기본 auto. overrides.sheetsMode로 강제 포함/제외 가능
const mode = overrides?.sheetsMode ?? 'auto'
const action = page.form?.actionUrl?.trim()
const hasAction = !!(action && action.length > 0)
const shouldInclude = mode === 'include' || (mode === 'auto' && !hasAction)
if (shouldInclude) {
const code = `/**
* Google Apps Script Web App for form submissions
* - Deploy as Web App and set URL as form action if needed.
*/
function doPost(e){ function doPost(e){
try { // TODO: handle submission to Google Sheets
var data = e.parameter || {} return ContentService.createTextOutput('OK')
// TODO: 시트에 저장 예시
// var ss = SpreadsheetApp.getActiveSpreadsheet()
// var sheet = ss.getSheetByName('Responses') || ss.insertSheet('Responses')
// sheet.appendRow([new Date(), JSON.stringify(data)])
return ContentService.createTextOutput(JSON.stringify({ ok: true }))
.setMimeType(ContentService.MimeType.JSON)
} catch (err) {
return ContentService.createTextOutput(JSON.stringify({ ok: false, error: String(err) }))
.setMimeType(ContentService.MimeType.JSON)
}
} }
` `
const readme = `README (Google Sheets Apps Script 템플릿) const readme = `Google Sheets Apps Script Template\n\n1) Apps Script에서 새 프로젝트를 만들고 아래 Code.gs를 붙여넣으세요.\n2) 배포 > 웹 앱으로 배포 후 URL을 복사해 사용하세요.`
out['sheets/Code.gs'] = toBytes(code)
1) Google Drive에서 새 스크립트(Apps Script) 프로젝트를 생성합니다. out['sheets/README.txt'] = toBytes(readme)
2) Code.gs 파일 내용을 붙여넣습니다.
3) Deploy > New deployment > Web app 으로 배포합니다.
- Execute as: Me
- Who has access: Anyone
4) 배포 URL을 복사하여 빌더의 Form action URL에 넣습니다.
5) 필요한 경우 doPost에서 스프레드시트 저장 로직을 추가하세요.
`
extras['sheets/Code.gs'] = te.encode(code)
extras['sheets/README.txt'] = te.encode(readme)
} }
return extras return out
} }
+9 -9
View File
@@ -13,17 +13,17 @@ function makePage(): Page {
}) })
} }
describe('Exporter - 폰트 최적화', () => { describe('폰트 최적화', () => {
it('head에 폰트 preconnect 링크가 포함된다(googleapis/gstatic)', () => { it('head에 Google Fonts preconnect 링크가 포함된다', () => {
const out = exportPage(makePage()) const page = makePage()
const html = out.html const out = exportPage(page)
expect(html).toMatch(/<link rel="preconnect" href="https:\/\/fonts\.googleapis\.com">/) expect(out.html).toContain('<link rel="preconnect" href="https://fonts.googleapis.com"')
expect(html).toMatch(/<link rel="preconnect" href="https:\/\/fonts\.gstatic\.com" crossorigin>/) expect(out.html).toContain('<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin')
}) })
it('CSS에 system-ui 폴백이 포함된다', () => { it('CSS에 system-ui 폴백이 포함된다', () => {
const out = exportPage(makePage()) const page = makePage()
const css = out.css const out = exportPage(page)
expect(css).toMatch(/font-family:[^;]*system-ui/i) expect(out.css).toMatch(/font-family:[^;]*system-ui/i)
}) })
}) })
+9 -6
View File
@@ -2,7 +2,7 @@ import type { Page, FormField } from '@/lib/schema/page'
import type { AssetManager } from '@/lib/assets/assetManager' import type { AssetManager } from '@/lib/assets/assetManager'
export type Exported = { html: string; css: string; js: string } export type Exported = { html: string; css: string; js: string }
export type ExportOptions = { assetManager?: AssetManager } export type ExportOptions = { assetManager?: AssetManager; fontPreconnect?: boolean }
function renderFaq(section: { props: { items: Array<{ q: string; a: string }> } }) { function renderFaq(section: { props: { items: Array<{ q: string; a: string }> } }) {
const itemsRaw: Array<{ q: string; a: string }> = Array.isArray(section.props.items) ? section.props.items : [] const itemsRaw: Array<{ q: string; a: string }> = Array.isArray(section.props.items) ? section.props.items : []
@@ -124,7 +124,7 @@ function renderHero(section: { props: { heading: string; subheading?: string; im
${subheading.length > 0 ? `<p>${escapeHtml(subheading)}</p>` : ''} ${subheading.length > 0 ? `<p>${escapeHtml(subheading)}</p>` : ''}
</div> </div>
<div class="media"> <div class="media">
<img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(heading)}" loading="lazy" decoding="async" /> <img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(heading)}" loading="lazy" decoding="async" width="1200" height="675" />
</div> </div>
</div> </div>
</section> </section>
@@ -222,7 +222,7 @@ function renderForm(page: Page) {
` `
} }
function buildHead(page: Page) { function buildHead(page: Page, opts?: ExportOptions) {
const ogImage = page.seo.ogImage const ogImage = page.seo.ogImage
const analyticsParts: string[] = [] const analyticsParts: string[] = []
const ga = page.analytics?.ga4MeasurementId const ga = page.analytics?.ga4MeasurementId
@@ -250,10 +250,15 @@ function buildHead(page: Page) {
</script>`) </script>`)
} }
const custom = page.analytics?.customHeadHtml || '' const custom = page.analytics?.customHeadHtml || ''
const preconnect = opts?.fontPreconnect !== false
return ` return `
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="canonical" href="/" /> <link rel="canonical" href="/" />
${preconnect ? '<link rel="preconnect" href="https://fonts.googleapis.com" />' : ''}
${preconnect ? '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />' : ''}
<link rel="manifest" href="/site.webmanifest" />
<meta name="theme-color" content="${escapeHtml(page.theme.primaryColor)}" />
<title>${escapeHtml(page.seo.title)}</title> <title>${escapeHtml(page.seo.title)}</title>
<meta name="description" content="${escapeHtml(page.seo.description)}" /> <meta name="description" content="${escapeHtml(page.seo.description)}" />
<meta property="og:title" content="${escapeHtml(page.seo.title)}" /> <meta property="og:title" content="${escapeHtml(page.seo.title)}" />
@@ -335,9 +340,7 @@ export function exportPage(page: Page, opts?: ExportOptions): Exported {
const html = `<!DOCTYPE html> const html = `<!DOCTYPE html>
<html lang="${escapeHtml(page.locale)}"> <html lang="${escapeHtml(page.locale)}">
<head> <head>
${buildHead(page)} ${buildHead(page, opts)}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
</head> </head>
<body> <body>
<a href="#main" class="skip-link">Skip to content</a> <a href="#main" class="skip-link">Skip to content</a>
+21
View File
@@ -0,0 +1,21 @@
import { describe, it, expect } from 'vitest'
import { exportPage } from '@/lib/exporter/html'
import { pageSchema, type Page } from '@/lib/schema/page'
function makePage(): Page {
return pageSchema.parse({
title: 'Head Links',
locale: 'en',
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
sections: [],
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
seo: { title: 't', description: 'd' },
})
}
describe('Exporter - head 링크 토큰', () => {
it('site.webmanifest 링크를 포함한다', () => {
const out = exportPage(makePage())
expect(out.html).toMatch(/<link rel="manifest" href="\/site\.webmanifest"\s*\/>/)
})
})
+32
View File
@@ -0,0 +1,32 @@
import { describe, it, expect } from 'vitest'
import { pageSchema, type Page } from '@/lib/schema/page'
import { buildExtrasForPage } from '@/lib/exporter/extras'
function makePage(): Page {
return pageSchema.parse({
title: 'Auto Extras',
locale: 'en',
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
seo: { title: 't', description: 'd' },
})
}
describe('extras 자동 생성', () => {
it('robots.txt와 site.webmanifest가 extras에 포함된다', () => {
const page = makePage()
const extras = buildExtrasForPage(page)
const keys = Object.keys(extras)
expect(keys).toContain('robots.txt')
expect(keys).toContain('site.webmanifest')
const robots = Buffer.from(extras['robots.txt']).toString('utf8')
expect(robots).toContain('User-agent: *')
const manifestStr = Buffer.from(extras['site.webmanifest']).toString('utf8')
const manifest = JSON.parse(manifestStr)
expect(manifest.start_url).toBeDefined()
expect(manifest.display).toBeDefined()
})
})
@@ -0,0 +1,31 @@
import { describe, it, expect } from 'vitest'
import { exportPage } from '@/lib/exporter/html'
import { pageSchema, type Page } from '@/lib/schema/page'
function makePage(): Page {
return pageSchema.parse({
title: 'SEO/Perf 2',
locale: 'en',
theme: { primaryColor: '#0ea5e9', fontFamily: 'Inter' },
sections: [
{ type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img.example/hero.png' } },
],
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
seo: { title: 'SEO2', description: 'Desc2' },
})
}
describe('Exporter - theme-color meta and hero image intrinsic size', () => {
it('includes theme-color meta using page.theme.primaryColor', () => {
const out = exportPage(makePage())
const html = out.html
expect(html).toMatch(/<meta name="theme-color" content="#0ea5e9"\s*\/>/)
})
it('renders hero image with width/height attributes for CLS reduction', () => {
const out = exportPage(makePage())
const html = out.html
expect(html).toMatch(/<img[^>]*\swidth="[0-9]+"/)
expect(html).toMatch(/<img[^>]*\sheight="[0-9]+"/)
})
})
@@ -0,0 +1,39 @@
import { describe, it, expect } from 'vitest'
import { buildZip } from '@/lib/exporter/zip'
import { exportPage } from '@/lib/exporter/html'
import { pageSchema, type Page } from '@/lib/schema/page'
import { buildExtrasForPage } from '@/lib/exporter/extras'
function makePage(): Page {
return pageSchema.parse({
title: 'ZIP Phase5',
locale: 'en',
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
seo: { title: 't', description: 'd' },
})
}
describe('ZIP 검증 Phase5', () => {
it('robots.txt 베이스라인과 site.webmanifest JSON 파싱 검증', async () => {
const page = makePage()
const extras = buildExtrasForPage(page)
// baseline robots
const robots = Buffer.from(extras['robots.txt']).toString('utf8')
expect(robots).toContain('User-agent: *')
// manifest JSON parseable
const manifestStr = Buffer.from(extras['site.webmanifest']).toString('utf8')
const manifest = JSON.parse(manifestStr)
expect(manifest && typeof manifest === 'object').toBe(true)
expect(manifest.start_url).toBeDefined()
expect(manifest.display).toBeDefined()
// ZIP build should succeed
const out = exportPage(page)
const zipBytes = await buildZip({ html: out.html, css: out.css, js: out.js, assets: {}, extras })
expect(zipBytes.byteLength).toBeGreaterThan(0)
})
})