@ecomiq/storefront 1.1.9 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +30 -415
  2. package/bin/ecomiq.mjs +165 -0
  3. package/package.json +72 -94
  4. package/src/api-proxy.ts +194 -0
  5. package/src/auth/create-storefront-auth.ts +35 -0
  6. package/src/auth/ecomiq-oauth-password-client.ts +26 -0
  7. package/src/auth/ecomiq-oauth-password-constants.ts +26 -0
  8. package/src/auth/ecomiq-oauth-password-plugin.ts +299 -0
  9. package/src/auth/ecomiq-oauth-password-types.ts +25 -0
  10. package/src/auth/ecomiq-storefront-sign-in.ts +47 -0
  11. package/src/auth/env.ts +7 -0
  12. package/src/cart-session.ts +241 -0
  13. package/src/client.ts +48 -0
  14. package/src/codegen.mjs +704 -0
  15. package/src/components/checkout/cart-sync.ts +143 -0
  16. package/src/components/checkout/checkout-external-update-banner.tsx +15 -0
  17. package/src/components/checkout/checkout-form-controls.tsx +139 -0
  18. package/src/components/checkout/checkout-line-items.tsx +43 -0
  19. package/src/components/checkout/checkout-order-summary.tsx +156 -0
  20. package/src/components/checkout/checkout-payment-section.tsx +215 -0
  21. package/src/components/checkout/checkout-session-view.tsx +240 -0
  22. package/src/components/checkout/checkout-shipping-address-section.tsx +266 -0
  23. package/src/components/checkout/checkout-shipping-section.tsx +90 -0
  24. package/src/components/checkout/checkout-states.tsx +73 -0
  25. package/src/components/checkout/form-schema.ts +229 -0
  26. package/src/components/checkout/format.ts +27 -0
  27. package/src/components/checkout/index.ts +51 -0
  28. package/src/components/checkout/types.ts +43 -0
  29. package/src/components/checkout/use-checkout-geo.ts +50 -0
  30. package/src/components/checkout/use-checkout-session.ts +583 -0
  31. package/src/components/hero.tsx +291 -0
  32. package/src/config.d.ts +69 -0
  33. package/src/config.mjs +165 -0
  34. package/src/index.ts +274 -0
  35. package/src/link.tsx +2 -0
  36. package/src/pages/checkout.$checkoutId.tsx +60 -0
  37. package/src/pages/checkout.tsx +31 -0
  38. package/src/pages/thank-you.tsx +53 -0
  39. package/src/providers/auth.tsx +69 -0
  40. package/src/providers/cart.tsx +275 -0
  41. package/src/providers/ecomiq.ts +137 -0
  42. package/src/providers/index.ts +26 -0
  43. package/src/public-config.ts +44 -0
  44. package/src/review-submission.ts +89 -0
  45. package/src/runtime/context.ts +1 -0
  46. package/src/runtime/default-layout.tsx +80 -0
  47. package/src/runtime/head.ts +126 -0
  48. package/src/runtime/page.tsx +82 -0
  49. package/src/runtime/postcss-browser-stub.mjs +5 -0
  50. package/src/server-config-store.ts +26 -0
  51. package/src/server.ts +279 -0
  52. package/src/styles.css +76 -0
  53. package/src/ui/badge.tsx +32 -0
  54. package/src/ui/button.tsx +31 -0
  55. package/src/ui/card.tsx +31 -0
  56. package/src/ui/carousel.tsx +218 -0
  57. package/src/ui/cn.ts +6 -0
  58. package/src/ui/index.ts +8 -0
  59. package/src/ui/separator.tsx +6 -0
  60. package/src/ui/skeleton.tsx +6 -0
  61. package/src/ui/storefront-error.tsx +49 -0
  62. package/src/utils.ts +36 -0
  63. package/src/vite-inline.mjs +135 -0
  64. package/templates/__root.tsx +77 -0
  65. package/templates/router.tsx +19 -0
  66. package/dist/chunk-64GLOWMJ.js +0 -216
  67. package/dist/chunk-64GLOWMJ.js.map +0 -1
  68. package/dist/chunk-AKD5IDEB.js +0 -177
  69. package/dist/chunk-AKD5IDEB.js.map +0 -1
  70. package/dist/chunk-EFEVJJWF.js +0 -1345
  71. package/dist/chunk-EFEVJJWF.js.map +0 -1
  72. package/dist/chunk-NAJQB5DN.js +0 -155
  73. package/dist/chunk-NAJQB5DN.js.map +0 -1
  74. package/dist/chunk-OABDGTBI.js +0 -253
  75. package/dist/chunk-OABDGTBI.js.map +0 -1
  76. package/dist/chunk-Q4U5OEUT.js +0 -21
  77. package/dist/chunk-Q4U5OEUT.js.map +0 -1
  78. package/dist/chunk-S7CPZ4UE.js +0 -6
  79. package/dist/chunk-S7CPZ4UE.js.map +0 -1
  80. package/dist/chunks/client.css +0 -984
  81. package/dist/chunks/client.css.map +0 -1
  82. package/dist/chunks/client.d.ts +0 -10759
  83. package/dist/chunks/client.js +0 -5398
  84. package/dist/chunks/client.js.map +0 -1
  85. package/dist/chunks/config.d.ts +0 -31
  86. package/dist/chunks/config.js +0 -5
  87. package/dist/chunks/config.js.map +0 -1
  88. package/dist/chunks/core-public.d.ts +0 -130
  89. package/dist/chunks/core-public.js +0 -92
  90. package/dist/chunks/core-public.js.map +0 -1
  91. package/dist/chunks/server-nextjs.d.ts +0 -33
  92. package/dist/chunks/server-nextjs.js +0 -59
  93. package/dist/chunks/server-nextjs.js.map +0 -1
  94. package/dist/chunks/server-tanstack.d.ts +0 -22
  95. package/dist/chunks/server-tanstack.js +0 -40
  96. package/dist/chunks/server-tanstack.js.map +0 -1
  97. package/dist/collection-DU7gREXS.d.ts +0 -4062
  98. package/dist/ecomiq-oauth-password-plugin-B_gMdGuc.d.ts +0 -3631
  99. package/dist/ecomiq-shell-ui-SWIFLQVM.js +0 -8
  100. package/dist/ecomiq-shell-ui-SWIFLQVM.js.map +0 -1
  101. package/dist/index.d.ts +0 -9
  102. package/dist/index.js +0 -1
  103. package/dist/index.js.map +0 -1
  104. package/dist/index.server.d.ts +0 -9
  105. package/dist/index.server.js +0 -8
  106. package/dist/index.server.js.map +0 -1
  107. package/dist/nextjs/api.d.ts +0 -45
  108. package/dist/nextjs/api.js +0 -32
  109. package/dist/nextjs/api.js.map +0 -1
  110. package/dist/nextjs/globals.css +0 -13
  111. package/dist/nextjs.d.ts +0 -2
  112. package/dist/nextjs.js +0 -2
  113. package/dist/nextjs.js.map +0 -1
  114. package/dist/nextjs.server.d.ts +0 -18
  115. package/dist/nextjs.server.js +0 -1
  116. package/dist/nextjs.server.js.map +0 -1
  117. package/dist/postcss.config.mjs +0 -6
  118. package/dist/react/checkout-page.css +0 -855
  119. package/dist/react/client.css +0 -984
  120. package/dist/react/payment-provider.css +0 -91
  121. package/dist/react/thank-you-page.css +0 -105
  122. package/dist/react.d.ts +0 -1
  123. package/dist/react.js +0 -2
  124. package/dist/react.js.map +0 -1
  125. package/dist/store-proxy-handler-CNzKlTFA.d.ts +0 -10
  126. package/dist/tanstack/api.d.ts +0 -41
  127. package/dist/tanstack/api.js +0 -30
  128. package/dist/tanstack/api.js.map +0 -1
  129. package/dist/tanstack.d.ts +0 -1
  130. package/dist/tanstack.js +0 -2
  131. package/dist/tanstack.js.map +0 -1
  132. package/dist/tanstack.server.d.ts +0 -18
  133. package/dist/tanstack.server.js +0 -1
  134. package/dist/tanstack.server.js.map +0 -1
@@ -0,0 +1,704 @@
1
+ /**
2
+ * Codegen de Ecomiq.
3
+ *
4
+ * Lee `pages/` y `ecomiq.config.js` del proyecto del usuario y genera una app
5
+ * interna en `.ecomiq/` que sigue las convenciones de TanStack Start
6
+ * (routes con createFileRoute, router.tsx, vite.config.ts). El usuario nunca
7
+ * ve ni edita estos archivos: son un artefacto de build, como `.next/`.
8
+ *
9
+ * Convención de páginas:
10
+ * pages/index.tsx → /
11
+ * pages/products.$productId.tsx → /products/:productId
12
+ * pages/products.index.tsx → /products
13
+ * pages/api/$.ts → /api/$ (server route / proxy)
14
+ *
15
+ * Páginas cerradas del framework (siempre generadas, no overrideables):
16
+ * /checkout/ ← redirect a /cart (checkout.index, sin layout padre)
17
+ * /checkout/$checkoutId ← flujo de checkout
18
+ * /thank-you ← post-compra
19
+ */
20
+ import {
21
+ mkdirSync,
22
+ readdirSync,
23
+ readFileSync,
24
+ rmSync,
25
+ watch as watchFileSystem,
26
+ writeFileSync,
27
+ existsSync,
28
+ symlinkSync,
29
+ lstatSync,
30
+ readlinkSync,
31
+ unlinkSync,
32
+ statSync,
33
+ realpathSync,
34
+ } from 'node:fs'
35
+ import { createRequire } from 'node:module'
36
+ import { resolve, join, relative, dirname, isAbsolute, sep } from 'node:path'
37
+
38
+ const HEADER = '/* Generado por Ecomiq — no editar. */\n'
39
+ const ROUTE_MANIFEST_FILE = 'generated-routes.json'
40
+
41
+ /** Rutas reservadas que viven solo en el package (templates no pueden overridear). */
42
+ const FRAMEWORK_LOCKED_PAGES = [
43
+ {
44
+ // index (no `checkout.tsx`): evita que TanStack anide $checkoutId bajo un layout
45
+ // que redirige a /cart.
46
+ rel: 'checkout.index.tsx',
47
+ routeId: '/checkout/',
48
+ importFrom: '@ecomiq/storefront/internal/checkout',
49
+ },
50
+ {
51
+ rel: 'checkout.$checkoutId.tsx',
52
+ routeId: '/checkout/$checkoutId',
53
+ importFrom: '@ecomiq/storefront/internal/checkout-session',
54
+ },
55
+ {
56
+ rel: 'thank-you.tsx',
57
+ routeId: '/thank-you',
58
+ importFrom: '@ecomiq/storefront/internal/thank-you',
59
+ },
60
+ ]
61
+
62
+ export async function generateApp({ cwd, appDir, frameworkRoot, config }) {
63
+ const pagesDir = resolve(cwd, 'pages')
64
+ if (!existsSync(pagesDir)) {
65
+ throw new Error('No existe la carpeta pages/. Crea al menos pages/index.tsx')
66
+ }
67
+
68
+ const srcDir = join(appDir, 'src')
69
+ const routesDir = join(srcDir, 'routes')
70
+ mkdirSync(routesDir, { recursive: true })
71
+
72
+ // ── 1. dependencias internas resolubles desde .ecomiq (soporta npm, pnpm y monorepos) ──
73
+ linkFrameworkDependencies(appDir, frameworkRoot, cwd)
74
+
75
+ // ── 2. package.json interno (type: module para que Vite resuelva bien) ──
76
+ writeGeneratedFile(
77
+ join(appDir, 'package.json'),
78
+ JSON.stringify({ name: 'ecomiq-app', private: true, type: 'module' }, null, 2),
79
+ )
80
+
81
+ // ── 3. tsconfig interno ──
82
+ writeGeneratedFile(
83
+ join(appDir, 'tsconfig.json'),
84
+ JSON.stringify(
85
+ {
86
+ compilerOptions: {
87
+ jsx: 'react-jsx',
88
+ module: 'ESNext',
89
+ moduleResolution: 'Bundler',
90
+ target: 'ES2022',
91
+ strict: true,
92
+ skipLibCheck: true,
93
+ verbatimModuleSyntax: true,
94
+ types: ['vite/client'],
95
+ },
96
+ include: ['src', '../pages', '../lib'],
97
+ },
98
+ null,
99
+ 2,
100
+ ),
101
+ )
102
+
103
+ const publicConfig = {
104
+ name: config.name,
105
+ slug: config.slug,
106
+ }
107
+ if (config.description !== undefined) publicConfig.description = config.description
108
+ if (config.theme !== undefined) publicConfig.theme = config.theme
109
+ if (config.seo !== undefined) publicConfig.seo = config.seo
110
+ if (config.analytics !== undefined) publicConfig.analytics = config.analytics
111
+ if (config.layout !== undefined) publicConfig.layout = config.layout
112
+
113
+ for (const serverOnlyKey of ['api', 'dev', 'deploy', 'env']) {
114
+ if (Object.hasOwn(publicConfig, serverOnlyKey)) {
115
+ throw new Error(`La clave server-only \`${serverOnlyKey}\` no puede serializarse en app-config.ts`)
116
+ }
117
+ }
118
+
119
+ writeGeneratedFile(
120
+ join(srcDir, 'app-config.ts'),
121
+ HEADER +
122
+ `import type { PublicEcomiqConfig } from '@ecomiq/storefront'\n\n` +
123
+ `const config = ${JSON.stringify(publicConfig, null, 2)} satisfies PublicEcomiqConfig\n` +
124
+ `export default config\n`,
125
+ )
126
+
127
+ writeGeneratedFile(
128
+ join(srcDir, 'server.ts'),
129
+ HEADER +
130
+ `import startServer, { createServerEntry } from '@tanstack/react-start/server-entry'\n` +
131
+ `import config from '../../ecomiq.config.js'\n` +
132
+ `import { registerServerConfig } from '@ecomiq/storefront/internal/server-config'\n\n` +
133
+ `export default createServerEntry({\n` +
134
+ ` async fetch(...args) {\n` +
135
+ ` let api = config.api\n` +
136
+ ` if (import.meta.env.DEV && config.dev?.apiBaseUrl) {\n` +
137
+ ` api = { ...api, baseUrl: config.dev.apiBaseUrl }\n` +
138
+ ` }\n` +
139
+ ` registerServerConfig({ slug: config.slug, api })\n` +
140
+ ` return startServer.fetch(...args)\n` +
141
+ ` },\n` +
142
+ `})\n`,
143
+ )
144
+
145
+ // ── 5. styles.css: tokens del framework + fuentes de contenido del usuario ──
146
+ const themeOverrides = buildThemeOverrides(config)
147
+ writeGeneratedFile(
148
+ join(srcDir, 'styles.css'),
149
+ HEADER.replace('/*', '/*!') +
150
+ `@import '@ecomiq/storefront/styles.css';\n` +
151
+ `@source '../../pages';\n` +
152
+ `@source '../../components';\n` +
153
+ `@source '../../lib';\n` +
154
+ `@source '../../layout.tsx';\n` +
155
+ (themeOverrides ? `\n${themeOverrides}\n` : ''),
156
+ )
157
+
158
+ // ── 6. router.tsx ──
159
+ writeTemplate(frameworkRoot, srcDir, 'router.tsx')
160
+
161
+ // ── 7. __root.tsx (shell HTML + providers) ──
162
+ writeTemplate(frameworkRoot, routesDir, '__root.tsx')
163
+
164
+ // ── 7b. user-layout.tsx: layout.tsx del usuario si existe, si no el default ──
165
+ const hasCustomLayout = existsSync(resolve(cwd, 'layout.tsx')) || existsSync(resolve(cwd, 'layout.jsx'))
166
+ writeGeneratedFile(
167
+ join(srcDir, 'user-layout.tsx'),
168
+ HEADER +
169
+ (hasCustomLayout
170
+ ? `export { default } from '../../layout'\n`
171
+ : `export { default } from '@ecomiq/storefront/internal/default-layout'\n`),
172
+ )
173
+
174
+ // ── 8. rutas generadas desde pages/ (páginas UI + API server routes) ──
175
+ const entries = listPageEntries(pagesDir)
176
+ const pageEntries = entries.filter((e) => e.kind === 'page')
177
+ const apiEntries = entries.filter((e) => e.kind === 'api')
178
+ if (pageEntries.length === 0) {
179
+ throw new Error('pages/ está vacío. Crea al menos pages/index.tsx')
180
+ }
181
+
182
+ assertNoFrameworkPageOverrides(pageEntries)
183
+
184
+ const desiredRoutes = [
185
+ ...pageEntries.map((entry) => entry.rel.replace(/\.jsx$/, '.tsx')),
186
+ ...apiEntries.map((entry) => entry.rel),
187
+ ...FRAMEWORK_LOCKED_PAGES.map((page) => page.rel),
188
+ ].sort()
189
+
190
+ for (const entry of pageEntries) {
191
+ const routeId = fileToRouteId(entry.rel)
192
+ const outFile = join(routesDir, entry.rel.replace(/\.jsx$/, '.tsx'))
193
+ mkdirSync(dirname(outFile), { recursive: true })
194
+ const importPath = relative(dirname(outFile), join(pagesDir, entry.rel))
195
+ .replace(/\\/g, '/')
196
+ .replace(/\.(tsx|jsx)$/, '')
197
+ writeGeneratedFile(outFile, routeFileSource(routeId, importPath, entry.rel))
198
+ }
199
+
200
+ for (const entry of apiEntries) {
201
+ const routeId = fileToRouteId(entry.rel)
202
+ const outFile = join(routesDir, entry.rel)
203
+ mkdirSync(dirname(outFile), { recursive: true })
204
+ // Extensión explícita: archivos como `$.ts` no resuelven bien sin ella.
205
+ const importPath = relative(dirname(outFile), join(pagesDir, entry.rel)).replace(/\\/g, '/')
206
+ writeGeneratedFile(outFile, apiRouteFileSource(routeId, importPath))
207
+ }
208
+
209
+ for (const locked of FRAMEWORK_LOCKED_PAGES) {
210
+ const outFile = join(routesDir, locked.rel)
211
+ mkdirSync(dirname(outFile), { recursive: true })
212
+ writeGeneratedFile(
213
+ outFile,
214
+ frameworkLockedPageRouteSource(locked.routeId, locked.importFrom, locked.rel),
215
+ )
216
+ }
217
+
218
+ reconcileGeneratedRoutes(appDir, routesDir, desiredRoutes)
219
+
220
+ // ── 9. wrangler.jsonc para deploy en Cloudflare Workers ──
221
+ const workerName = config.deploy?.name ?? slugify(config.name ?? 'ecomiq-store')
222
+ writeGeneratedFile(
223
+ join(appDir, 'wrangler.jsonc'),
224
+ JSON.stringify(
225
+ {
226
+ $schema: 'node_modules/wrangler/config-schema.json',
227
+ name: workerName,
228
+ main: 'src/server.ts',
229
+ compatibility_date: '2026-01-01',
230
+ compatibility_flags: ['nodejs_compat'],
231
+ observability: {
232
+ enabled: false,
233
+ head_sampling_rate: 1,
234
+ logs: {
235
+ enabled: true,
236
+ head_sampling_rate: 1,
237
+ persist: true,
238
+ invocation_logs: true,
239
+ },
240
+ traces: {
241
+ enabled: false,
242
+ persist: true,
243
+ head_sampling_rate: 1,
244
+ },
245
+ },
246
+ ...(config.deploy?.routes ? { routes: config.deploy.routes } : {}),
247
+ vars: config.env ?? {},
248
+ },
249
+ null,
250
+ 2,
251
+ ),
252
+ )
253
+
254
+ // ── 10. .gitignore para que .ecomiq no se versione dentro de sí mismo ──
255
+ writeGeneratedFile(join(appDir, '.gitignore'), '*\n')
256
+ }
257
+
258
+ export function watchPages({
259
+ cwd,
260
+ appDir,
261
+ frameworkRoot,
262
+ config,
263
+ debounceMs = 75,
264
+ /** Intervalo de polling (ms) como respaldo cuando `fs.watch` no emite eventos (p. ej. sandbox). */
265
+ pollMs = 0,
266
+ onGenerate = () => {},
267
+ onError = () => {},
268
+ }) {
269
+ const pagesDir = resolve(cwd, 'pages')
270
+ if (!existsSync(pagesDir)) {
271
+ throw new Error('No existe la carpeta pages/. Crea al menos pages/index.tsx')
272
+ }
273
+
274
+ let closed = false
275
+ let dirty = false
276
+ let running = false
277
+ let timer
278
+ let lastPagesSignature = pagesDirSignature(pagesDir)
279
+
280
+ async function flush() {
281
+ if (running || closed) return
282
+ running = true
283
+
284
+ while (dirty && !closed) {
285
+ dirty = false
286
+ try {
287
+ await generateApp({ cwd, appDir, frameworkRoot, config })
288
+ lastPagesSignature = pagesDirSignature(pagesDir)
289
+ onGenerate()
290
+ } catch (error) {
291
+ onError(error instanceof Error ? error : new Error(String(error)))
292
+ }
293
+ }
294
+
295
+ running = false
296
+ }
297
+
298
+ function schedule() {
299
+ if (closed) return
300
+ if (timer) clearTimeout(timer)
301
+ timer = setTimeout(() => {
302
+ timer = undefined
303
+ dirty = true
304
+ void flush()
305
+ }, debounceMs)
306
+ }
307
+
308
+ const watcher = watchFileSystem(pagesDir, { recursive: true }, schedule)
309
+ watcher.on('error', (error) => onError(error))
310
+
311
+ let pollTimer
312
+ if (pollMs > 0) {
313
+ pollTimer = setInterval(() => {
314
+ if (closed) return
315
+ const next = pagesDirSignature(pagesDir)
316
+ if (next !== lastPagesSignature) {
317
+ lastPagesSignature = next
318
+ schedule()
319
+ }
320
+ }, pollMs)
321
+ }
322
+
323
+ return {
324
+ close() {
325
+ closed = true
326
+ dirty = false
327
+ if (timer) clearTimeout(timer)
328
+ if (pollTimer) clearInterval(pollTimer)
329
+ watcher.close()
330
+ },
331
+ }
332
+ }
333
+
334
+ /** Firma ligera de `pages/` para detectar altas/bajas/renombres sin depender de `fs.watch`. */
335
+ function pagesDirSignature(pagesDir) {
336
+ const parts = []
337
+ for (const entry of listPageEntries(pagesDir)) {
338
+ const full = join(pagesDir, entry.rel)
339
+ parts.push(`${entry.rel}:${statSync(full).mtimeMs}`)
340
+ }
341
+ return parts.sort().join('|')
342
+ }
343
+
344
+ /** Lista pages UI (.tsx/.jsx) y API server routes (.ts) de forma recursiva. */
345
+ function listPageEntries(pagesDir, prefix = '') {
346
+ const entries = []
347
+ const dir = prefix ? join(pagesDir, prefix) : pagesDir
348
+ for (const name of readdirSync(dir).sort()) {
349
+ if (
350
+ name.startsWith('.') ||
351
+ name === '__tests__' ||
352
+ /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(name)
353
+ ) continue
354
+ const rel = prefix ? `${prefix}/${name}` : name
355
+ const full = join(pagesDir, rel)
356
+ if (statSync(full).isDirectory()) {
357
+ entries.push(...listPageEntries(pagesDir, rel))
358
+ continue
359
+ }
360
+ if (/\.(tsx|jsx)$/.test(name)) entries.push({ kind: 'page', rel })
361
+ else if (/\.ts$/.test(name) && !name.endsWith('.d.ts')) entries.push({ kind: 'api', rel })
362
+ }
363
+ return entries
364
+ }
365
+
366
+ function reconcileGeneratedRoutes(appDir, routesDir, desiredRoutes) {
367
+ const manifestPath = join(appDir, ROUTE_MANIFEST_FILE)
368
+ const previousRoutes = readRouteManifest(manifestPath)
369
+ const desired = new Set(desiredRoutes)
370
+
371
+ for (const relativePath of previousRoutes) {
372
+ if (desired.has(relativePath)) continue
373
+ const outputPath = ownedRoutePath(routesDir, relativePath)
374
+ if (outputPath) rmSync(outputPath, { force: true })
375
+ }
376
+
377
+ writeGeneratedFile(
378
+ manifestPath,
379
+ JSON.stringify({ version: 1, routes: desiredRoutes }, null, 2) + '\n',
380
+ )
381
+ }
382
+
383
+ function readRouteManifest(manifestPath) {
384
+ if (!existsSync(manifestPath)) return []
385
+
386
+ try {
387
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
388
+ if (manifest?.version !== 1 || !Array.isArray(manifest.routes)) return []
389
+ return manifest.routes.filter((route) => typeof route === 'string')
390
+ } catch {
391
+ return []
392
+ }
393
+ }
394
+
395
+ function ownedRoutePath(routesDir, relativePath) {
396
+ if (
397
+ relativePath.length === 0 ||
398
+ isAbsolute(relativePath) ||
399
+ relativePath.split('/').includes('..')
400
+ ) {
401
+ return null
402
+ }
403
+ const outputPath = resolve(routesDir, relativePath)
404
+ if (!outputPath.startsWith(resolve(routesDir) + sep)) return null
405
+ return outputPath
406
+ }
407
+
408
+ /**
409
+ * 'products.$productId.tsx' → '/products/$productId'
410
+ * 'api/$.ts' → '/api/$'
411
+ * 'index.tsx' → '/'
412
+ */
413
+ function fileToRouteId(relPath) {
414
+ const withoutExt = relPath.replace(/\.(tsx|jsx|ts)$/, '')
415
+ if (withoutExt === 'index') return '/'
416
+
417
+ const segments = []
418
+ for (const part of withoutExt.split('/')) {
419
+ const bits = part.split('.').map((s) => (s === 'index' ? '' : s))
420
+ segments.push(...bits.filter(Boolean))
421
+ }
422
+ return '/' + segments.join('/') + (withoutExt.endsWith('.index') ? '/' : '')
423
+ }
424
+
425
+ /** Relativo desde routes/<rel> hasta src/app-config. */
426
+ function appConfigImportFrom(relPath) {
427
+ const nestDepth = relPath.split('/').length - 1
428
+ return '../'.repeat(nestDepth + 1) + 'app-config'
429
+ }
430
+
431
+ /** Código de una ruta interna que envuelve la página del usuario. */
432
+ function routeFileSource(routeId, importPath, relPath) {
433
+ const appConfigImport = appConfigImportFrom(relPath)
434
+
435
+ return (
436
+ HEADER +
437
+ `import { createFileRoute } from '@tanstack/react-router'\n` +
438
+ `import appConfig from '${appConfigImport}'\n` +
439
+ `import pageModule from '${importPath}'\n` +
440
+ `import { pageToRouteOptions, PageBoundary } from '@ecomiq/storefront/internal/page'\n\n` +
441
+ `export const Route = createFileRoute('${routeId}')({\n` +
442
+ ` ...pageToRouteOptions(pageModule, appConfig),\n` +
443
+ ` component: PageComponent,\n` +
444
+ `})\n\n` +
445
+ `function PageComponent() {\n` +
446
+ ` const data = Route.useLoaderData()\n` +
447
+ ` const params = Route.useParams()\n` +
448
+ ` const search = Route.useSearch()\n` +
449
+ ` return <PageBoundary page={pageModule} data={data} params={params} search={search} />\n` +
450
+ `}\n`
451
+ )
452
+ }
453
+
454
+ /** Página cerrada del framework (import desde package, no desde pages/ del usuario). */
455
+ function frameworkLockedPageRouteSource(routeId, importFrom, relPath) {
456
+ const appConfigImport = appConfigImportFrom(relPath)
457
+
458
+ return (
459
+ HEADER +
460
+ `import { createFileRoute } from '@tanstack/react-router'\n` +
461
+ `import appConfig from '${appConfigImport}'\n` +
462
+ `import pageModule from '${importFrom}'\n` +
463
+ `import { pageToRouteOptions, PageBoundary } from '@ecomiq/storefront/internal/page'\n\n` +
464
+ `export const Route = createFileRoute('${routeId}')({\n` +
465
+ ` ...pageToRouteOptions(pageModule, appConfig),\n` +
466
+ ` component: PageComponent,\n` +
467
+ `})\n\n` +
468
+ `function PageComponent() {\n` +
469
+ ` const data = Route.useLoaderData()\n` +
470
+ ` const params = Route.useParams()\n` +
471
+ ` const search = Route.useSearch()\n` +
472
+ ` return <PageBoundary page={pageModule} data={data} params={params} search={search} />\n` +
473
+ `}\n`
474
+ )
475
+ }
476
+
477
+ function assertNoFrameworkPageOverrides(pageEntries) {
478
+ const reserved = new Map(
479
+ FRAMEWORK_LOCKED_PAGES.map((page) => [page.routeId, page.rel]),
480
+ )
481
+ // Overrides / alias legados
482
+ reserved.set('/checkout', 'checkout.tsx')
483
+ reserved.set('/checkout/$cartId', 'checkout.$cartId.tsx')
484
+
485
+ for (const entry of pageEntries) {
486
+ const routeId = fileToRouteId(entry.rel)
487
+ if (!reserved.has(routeId)) continue
488
+ throw new Error(
489
+ `La ruta ${routeId} es reservada por Ecomiq (página cerrada). ` +
490
+ `Elimina pages/${entry.rel}; las páginas de checkout y thank-you viven en @ecomiq/storefront.`,
491
+ )
492
+ }
493
+ }
494
+
495
+ /** Server route: reexporta GET/POST/... del módulo del usuario. */
496
+ function apiRouteFileSource(routeId, importPath) {
497
+ return (
498
+ HEADER +
499
+ `import { createFileRoute } from '@tanstack/react-router'\n` +
500
+ `import * as api from '${importPath}'\n\n` +
501
+ `export const Route = createFileRoute('${routeId}')({\n` +
502
+ ` server: {\n` +
503
+ ` handlers: {\n` +
504
+ ` ...(api.GET ? { GET: api.GET } : {}),\n` +
505
+ ` ...(api.POST ? { POST: api.POST } : {}),\n` +
506
+ ` ...(api.PUT ? { PUT: api.PUT } : {}),\n` +
507
+ ` ...(api.PATCH ? { PATCH: api.PATCH } : {}),\n` +
508
+ ` ...(api.DELETE ? { DELETE: api.DELETE } : {}),\n` +
509
+ ` },\n` +
510
+ ` },\n` +
511
+ `})\n`
512
+ )
513
+ }
514
+
515
+ function buildThemeOverrides(config) {
516
+ const theme = config.theme ?? {}
517
+ const map = {
518
+ primary: '--primary',
519
+ primaryForeground: '--primary-foreground',
520
+ radius: '--radius',
521
+ background: '--background',
522
+ foreground: '--foreground',
523
+ accent: '--accent',
524
+ }
525
+ const lines = Object.entries(map)
526
+ .filter(([key]) => theme[key])
527
+ .map(([key, cssVar]) => ` ${cssVar}: ${theme[key]};`)
528
+ if (lines.length === 0) return ''
529
+ return `:root {\n${lines.join('\n')}\n}`
530
+ }
531
+
532
+ function writeTemplate(frameworkRoot, targetDir, name) {
533
+ const src = resolve(frameworkRoot, 'templates', name)
534
+ writeGeneratedFile(join(targetDir, name), readFileSync(src, 'utf8'))
535
+ }
536
+
537
+ function writeGeneratedFile(path, contents) {
538
+ if (existsSync(path) && readFileSync(path, 'utf8') === contents) return
539
+ mkdirSync(dirname(path), { recursive: true })
540
+ writeFileSync(path, contents)
541
+ }
542
+
543
+ /**
544
+ * Crea `.ecomiq/node_modules` con symlinks a las dependencias del framework.
545
+ *
546
+ * Workerd (Cloudflare Vite plugin) resuelve desde la raíz `.ecomiq`, así que
547
+ * no basta con el hoisting del proyecto: hay que materializar los packages
548
+ * ahí. En installs npm/pnpm/yarn las deps suelen vivir en el node_modules del
549
+ * proyecto (o en el store de pnpm), no bajo `@ecomiq/storefront/node_modules`.
550
+ */
551
+ function linkFrameworkDependencies(appDir, frameworkRoot, projectRoot = dirname(appDir)) {
552
+ const target = join(appDir, 'node_modules')
553
+ mkdirSync(target, { recursive: true })
554
+
555
+ linkInto(join(target, '@ecomiq'), 'storefront', frameworkRoot)
556
+ const legacyFramework = join(target, '@ecomiq', 'framework')
557
+ try {
558
+ if (lstatSync(legacyFramework).isSymbolicLink()) unlinkSync(legacyFramework)
559
+ } catch {
560
+ /* no existía */
561
+ }
562
+
563
+ const resolveFrom = [
564
+ join(frameworkRoot, 'package.json'),
565
+ join(projectRoot, 'package.json'),
566
+ join(frameworkRoot, 'src', 'codegen.mjs'),
567
+ ]
568
+
569
+ const manifestPath = join(frameworkRoot, 'package.json')
570
+ let depNames = []
571
+ try {
572
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
573
+ depNames = [
574
+ ...Object.keys(manifest.dependencies ?? {}),
575
+ ...Object.keys(manifest.peerDependencies ?? {}),
576
+ ]
577
+ } catch {
578
+ depNames = []
579
+ }
580
+
581
+ // Transitive crítico que Vite/TanStack piden explícitamente en SSR.
582
+ for (const extra of ['@tanstack/react-store', '@tanstack/history', '@tanstack/router-core']) {
583
+ if (!depNames.includes(extra)) depNames.push(extra)
584
+ }
585
+
586
+ for (const name of depNames) {
587
+ const pkgDir = resolvePackageDir(name, resolveFrom)
588
+ if (!pkgDir) continue
589
+ linkPackage(target, name, pkgDir)
590
+ }
591
+
592
+ // Fallback: mirror de node_modules locales (monorepo / nested installs).
593
+ for (const source of [join(frameworkRoot, 'node_modules'), join(projectRoot, 'node_modules')]) {
594
+ linkNodeModulesTree(source, target)
595
+ }
596
+ }
597
+
598
+ function linkPackage(targetRoot, packageName, packageDir) {
599
+ if (packageName.startsWith('@')) {
600
+ const [scope, name] = packageName.split('/')
601
+ if (!scope || !name) return
602
+ linkInto(join(targetRoot, scope), name, packageDir)
603
+ return
604
+ }
605
+ linkInto(targetRoot, packageName, packageDir)
606
+ }
607
+
608
+ function linkNodeModulesTree(source, target) {
609
+ if (!existsSync(source)) return
610
+ for (const entry of readdirSync(source)) {
611
+ if (entry === '.bin' || entry.startsWith('.')) continue
612
+ if (entry.startsWith('@')) {
613
+ const scopeDir = join(source, entry)
614
+ if (!statSync(scopeDir).isDirectory()) continue
615
+ for (const scoped of readdirSync(scopeDir)) {
616
+ linkInto(join(target, entry), scoped, join(scopeDir, scoped))
617
+ }
618
+ } else {
619
+ linkInto(target, entry, join(source, entry))
620
+ }
621
+ }
622
+ }
623
+
624
+ /**
625
+ * Resuelve el directorio raíz de un package usando la resolución de Node
626
+ * (funciona con hoisting npm/yarn y el store de pnpm).
627
+ */
628
+ function resolvePackageDir(packageName, fromFiles) {
629
+ for (const fromFile of fromFiles) {
630
+ if (!existsSync(fromFile)) continue
631
+ try {
632
+ const require = createRequire(fromFile)
633
+ try {
634
+ return dirname(realpathSync(require.resolve(`${packageName}/package.json`)))
635
+ } catch {
636
+ const entry = require.resolve(packageName)
637
+ return findPackageRoot(entry, packageName)
638
+ }
639
+ } catch {
640
+ /* probar siguiente origen */
641
+ }
642
+ }
643
+ return null
644
+ }
645
+
646
+ function findPackageRoot(startPath, packageName) {
647
+ let dir = dirname(startPath)
648
+ while (true) {
649
+ const pkgPath = join(dir, 'package.json')
650
+ if (existsSync(pkgPath)) {
651
+ try {
652
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))
653
+ if (pkg.name === packageName) return realpathSync(dir)
654
+ } catch {
655
+ /* ignore */
656
+ }
657
+ }
658
+ const parent = dirname(dir)
659
+ if (parent === dir) return null
660
+ dir = parent
661
+ }
662
+ }
663
+
664
+ function linkInto(dir, name, targetPath) {
665
+ mkdirSync(dir, { recursive: true })
666
+ const linkPath = join(dir, name)
667
+ let desired
668
+ try {
669
+ desired = realpathSync(targetPath)
670
+ } catch {
671
+ desired = resolve(targetPath)
672
+ }
673
+ try {
674
+ const current = lstatSync(linkPath)
675
+ if (current.isSymbolicLink()) {
676
+ let resolved
677
+ try {
678
+ resolved = realpathSync(linkPath)
679
+ } catch {
680
+ resolved = resolve(dir, readlinkSync(linkPath))
681
+ }
682
+ if (resolved === desired) return
683
+ unlinkSync(linkPath)
684
+ } else if (current.isDirectory() || current.isFile()) {
685
+ return
686
+ }
687
+ } catch {
688
+ /* no existe aún */
689
+ }
690
+ try {
691
+ symlinkSync(desired, linkPath, 'junction')
692
+ } catch {
693
+ /* FS sin symlinks: la resolución cae al hoisting */
694
+ }
695
+ }
696
+
697
+ function slugify(s) {
698
+ return s
699
+ .toLowerCase()
700
+ .normalize('NFD')
701
+ .replace(/[\u0300-\u036f]/g, '')
702
+ .replace(/[^a-z0-9]+/g, '-')
703
+ .replace(/^-|-$/g, '')
704
+ }