@devbie/fewbie-cli 0.1.0-stage.0 → 0.1.0

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 (42) hide show
  1. package/README.md +138 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/commands/add.d.ts +1 -0
  4. package/dist/commands/add.js +29 -24
  5. package/dist/commands/add.js.map +1 -1
  6. package/dist/commands/apits-templates.d.ts +11 -0
  7. package/dist/commands/{gen-api-templates.js → apits-templates.js} +7 -7
  8. package/dist/commands/apits-templates.js.map +1 -0
  9. package/dist/commands/{gen-api.d.ts → apits.d.ts} +2 -2
  10. package/dist/commands/apits.js +125 -0
  11. package/dist/commands/apits.js.map +1 -0
  12. package/dist/commands/doctor.d.ts +24 -0
  13. package/dist/commands/doctor.js +216 -0
  14. package/dist/commands/doctor.js.map +1 -0
  15. package/dist/commands/init.js +1 -7
  16. package/dist/commands/init.js.map +1 -1
  17. package/dist/commands/update.d.ts +6 -0
  18. package/dist/commands/update.js +99 -0
  19. package/dist/commands/update.js.map +1 -0
  20. package/dist/index.js +30 -7
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/diff.d.ts +1 -0
  23. package/dist/lib/diff.js +110 -0
  24. package/dist/lib/diff.js.map +1 -0
  25. package/dist/lib/exec-interactive.js.map +1 -1
  26. package/dist/registry/api-client/item.json +1 -1
  27. package/dist/registry/auth/item.json +1 -1
  28. package/dist/registry/build.js +2 -6
  29. package/dist/registry/build.js.map +1 -1
  30. package/dist/registry/data-table/item.json +14 -0
  31. package/dist/registry/login-form/item.json +1 -1
  32. package/dist/registry/page-header/item.json +14 -0
  33. package/dist/registry/settings-required-state/item.json +17 -0
  34. package/dist/registry/store.js +1 -3
  35. package/dist/registry/store.js.map +1 -1
  36. package/dist/registry/theme/item.json +1 -1
  37. package/dist/registry/web-monitor-sdk/item.json +18 -0
  38. package/package.json +2 -2
  39. package/dist/commands/gen-api-templates.d.ts +0 -11
  40. package/dist/commands/gen-api-templates.js.map +0 -1
  41. package/dist/commands/gen-api.js +0 -105
  42. package/dist/commands/gen-api.js.map +0 -1
@@ -11,7 +11,7 @@
11
11
  "files": [
12
12
  {
13
13
  "path": "src/lib/api-client.ts",
14
- "content": "import axios, {\n type AxiosRequestConfig,\n type AxiosResponse,\n type InternalAxiosRequestConfig,\n} from \"axios\";\n\n// ---------------------------------------------------------------------------\n// Project-specific configuration — edit these for your backend contract.\n// ---------------------------------------------------------------------------\n\n/** Base URL of the API; same-origin by default. */\nconst BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? \"\";\n\n/** localStorage key of the short-lived access token. */\nconst ACCESS_TOKEN_KEY = \"access-token\";\n\n/** localStorage key of the access-token expiry epoch in milliseconds. */\nconst ACCESS_TOKEN_EXPIRES_AT_KEY = \"access-token-expires-at\";\n\n/** Endpoint that exchanges the httpOnly refresh cookie for a new access token. */\nconst REFRESH_PATH = \"/auth/refresh-access-token\";\n\n/** Paths that must never trigger a silent refresh (would recurse). */\nconst AUTH_PATH_PATTERN = /^\\/auth\\//;\n\n/** Refresh this early so business requests never carry an expired token. */\nconst PROACTIVE_REFRESH_LEAD_MS = 60_000;\n\n/** How often the proactive scheduler checks expiry. */\nconst PROACTIVE_REFRESH_CHECK_INTERVAL_MS = 30_000;\n\n/**\n * Pause before retrying a failed refresh. When another tab rotates the\n * refresh cookie, its Set-Cookie reaches this tab a moment later; the retry\n * then carries the renewed cookie.\n */\nconst REFRESH_RETRY_DELAY_MS = 1_500;\n\n// ---------------------------------------------------------------------------\n// Token storage\n// ---------------------------------------------------------------------------\n\nexport function getAccessToken(): string {\n if (typeof window === \"undefined\") return \"\";\n return window.localStorage.getItem(ACCESS_TOKEN_KEY) ?? \"\";\n}\n\n/** Persist token + expiry after login or refresh. */\nexport function setSession(token: string, expiresInSeconds?: number): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(ACCESS_TOKEN_KEY, token);\n if (typeof expiresInSeconds === \"number\" && expiresInSeconds > 0) {\n window.localStorage.setItem(\n ACCESS_TOKEN_EXPIRES_AT_KEY,\n String(Date.now() + expiresInSeconds * 1000),\n );\n }\n}\n\n/** Remove all locally stored session data. */\nexport function clearSession(): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.removeItem(ACCESS_TOKEN_KEY);\n window.localStorage.removeItem(ACCESS_TOKEN_EXPIRES_AT_KEY);\n}\n\n/** Normalized error so callers never depend on the axios error shape. */\nexport class ApiError extends Error {\n readonly status: number;\n readonly data: unknown;\n\n constructor(message: string, status: number, data: unknown) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.data = data;\n }\n}\n\n/**\n * Hook invoked when the refresh cookie is missing/expired. Wire it to your\n * router (e.g. redirect to the login page); the client itself stays\n * router-agnostic.\n */\nlet sessionExpiredHandler: (() => void) | null = null;\nexport function onSessionExpired(handler: () => void): void {\n sessionExpiredHandler = handler;\n}\n\n// ---------------------------------------------------------------------------\n// Refresh-token rotation\n// ---------------------------------------------------------------------------\n\nfunction isUnauthorized(error: unknown): boolean {\n return axios.isAxiosError(error) && error.response?.status === 401;\n}\n\n/** One refresh round-trip; persists the renewed token and its expiry. */\nasync function requestRefreshOnce(): Promise<string | null> {\n const response = await axios.get(`${BASE_URL}${REFRESH_PATH}`, {\n withCredentials: true,\n });\n // Default envelope: { token, tokenExpiresInSeconds }.\n const data = response.data as {\n token?: string;\n tokenExpiresInSeconds?: number;\n };\n if (!data?.token) return null;\n setSession(data.token, data.tokenExpiresInSeconds);\n return data.token;\n}\n\n// Shared in-flight refresh. The backend rotates the refresh cookie on every\n// call, so concurrent 401s must await the same request instead of issuing\n// parallel refreshes that invalidate each other's cookie.\nlet refreshPromise: Promise<string | null> | null = null;\n\n/** Exchange the httpOnly refresh cookie for a new access token (single-flight). */\nfunction refreshAccessToken(): Promise<string | null> {\n if (refreshPromise) return refreshPromise;\n\n refreshPromise = (async () => {\n try {\n return await requestRefreshOnce();\n } catch (firstError) {\n if (!isUnauthorized(firstError)) return null;\n // Possible cross-tab cookie rotation: retry once after a short pause.\n await new Promise((resolve) =>\n setTimeout(resolve, REFRESH_RETRY_DELAY_MS),\n );\n try {\n return await requestRefreshOnce();\n } catch {\n return null;\n }\n } finally {\n refreshPromise = null;\n }\n })();\n\n return refreshPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Proactive refresh scheduler (module-level singleton)\n// ---------------------------------------------------------------------------\n\nlet schedulerTimer: ReturnType<typeof setInterval> | null = null;\n\n/**\n * Start the scheduler that renews the token shortly before expiry. Call once\n * on the client (e.g. in the authenticated layout). Reactive 401 refresh\n * stays as a fallback for laptop sleep / scheduler drift.\n */\nexport function initProactiveTokenRefresh(): void {\n if (typeof window === \"undefined\" || schedulerTimer) return;\n\n const refreshIfDue = (): void => {\n const token = getAccessToken();\n const expiresAt = Number(\n window.localStorage.getItem(ACCESS_TOKEN_EXPIRES_AT_KEY) ?? 0,\n );\n if (\n token &&\n expiresAt &&\n Date.now() >= expiresAt - PROACTIVE_REFRESH_LEAD_MS\n ) {\n void refreshAccessToken();\n }\n };\n\n // Run immediately (tabs reopened after sleep) and then on an interval.\n refreshIfDue();\n schedulerTimer = setInterval(\n refreshIfDue,\n PROACTIVE_REFRESH_CHECK_INTERVAL_MS,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Axios instance\n// ---------------------------------------------------------------------------\n\nexport const api = axios.create({\n baseURL: BASE_URL,\n withCredentials: true,\n});\n\napi.interceptors.request.use((config) => {\n const token = getAccessToken();\n // Within the interceptor chain headers is always an AxiosHeaders instance.\n if (token) {\n config.headers.set(\"Authorization\", `Bearer ${token}`);\n }\n return config;\n});\n\napi.interceptors.response.use(\n (response) => response,\n async (error) => {\n const original = error?.config as\n | (InternalAxiosRequestConfig & { _retriedAfterRefresh?: boolean })\n | undefined;\n const url: string = original?.url ?? \"\";\n const canSilentlyRefresh =\n typeof window !== \"undefined\" &&\n !original?._retriedAfterRefresh &&\n !AUTH_PATH_PATTERN.test(url);\n\n if (isUnauthorized(error) && original && canSilentlyRefresh) {\n original._retriedAfterRefresh = true;\n const renewed = await refreshAccessToken();\n if (renewed) {\n original.headers.set(\"Authorization\", `Bearer ${renewed}`);\n return api(original);\n }\n // Refresh cookie missing or expired: the session is over.\n clearSession();\n sessionExpiredHandler?.();\n }\n\n if (axios.isAxiosError(error)) {\n const data = error.response?.data as { message?: string } | undefined;\n throw new ApiError(\n data?.message ?? error.message,\n error.response?.status ?? 0,\n data,\n );\n }\n throw error;\n },\n);\n\n// ---------------------------------------------------------------------------\n// Typed convenience methods — return the response body directly.\n// ---------------------------------------------------------------------------\n\nexport const apiClient = {\n get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api.get<unknown, AxiosResponse<T>>(url, config).then((r) => r.data);\n },\n post<T>(\n url: string,\n data?: unknown,\n config?: AxiosRequestConfig,\n ): Promise<T> {\n return api\n .post<unknown, AxiosResponse<T>>(url, data, config)\n .then((r) => r.data);\n },\n put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api\n .put<unknown, AxiosResponse<T>>(url, data, config)\n .then((r) => r.data);\n },\n patch<T>(\n url: string,\n data?: unknown,\n config?: AxiosRequestConfig,\n ): Promise<T> {\n return api\n .patch<unknown, AxiosResponse<T>>(url, data, config)\n .then((r) => r.data);\n },\n delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api\n .delete<unknown, AxiosResponse<T>>(url, config)\n .then((r) => r.data);\n },\n // HEAD/OPTIONS responses carry no body; resolve to the full AxiosResponse\n // so callers can still inspect status and headers.\n head<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {\n return api.head<unknown, AxiosResponse<T>>(url, config);\n },\n options<T>(\n url: string,\n config?: AxiosRequestConfig,\n ): Promise<AxiosResponse<T>> {\n return api.options<unknown, AxiosResponse<T>>(url, config);\n },\n};\n",
14
+ "content": "import axios, { type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from \"axios\";\n\n// ---------------------------------------------------------------------------\n// Project-specific configuration — edit these for your backend contract.\n// ---------------------------------------------------------------------------\n\n/** Base URL of the API; same-origin by default. */\nconst BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? \"\";\n\n/** localStorage key of the short-lived access token. */\nconst ACCESS_TOKEN_KEY = \"access-token\";\n\n/** localStorage key of the access-token expiry epoch in milliseconds. */\nconst ACCESS_TOKEN_EXPIRES_AT_KEY = \"access-token-expires-at\";\n\n/** Endpoint that exchanges the httpOnly refresh cookie for a new access token. */\nconst REFRESH_PATH = \"/auth/refresh-access-token\";\n\n/** Paths that must never trigger a silent refresh (would recurse). */\nconst AUTH_PATH_PATTERN = /^\\/auth\\//;\n\n/** Refresh this early so business requests never carry an expired token. */\nconst PROACTIVE_REFRESH_LEAD_MS = 60_000;\n\n/** How often the proactive scheduler checks expiry. */\nconst PROACTIVE_REFRESH_CHECK_INTERVAL_MS = 30_000;\n\n/**\n * Pause before retrying a failed refresh. When another tab rotates the\n * refresh cookie, its Set-Cookie reaches this tab a moment later; the retry\n * then carries the renewed cookie.\n */\nconst REFRESH_RETRY_DELAY_MS = 1_500;\n\n// ---------------------------------------------------------------------------\n// Token storage\n// ---------------------------------------------------------------------------\n\nexport function getAccessToken(): string {\n if (typeof window === \"undefined\") return \"\";\n return window.localStorage.getItem(ACCESS_TOKEN_KEY) ?? \"\";\n}\n\n/** Persist token + expiry after login or refresh. */\nexport function setSession(token: string, expiresInSeconds?: number): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(ACCESS_TOKEN_KEY, token);\n if (typeof expiresInSeconds === \"number\" && expiresInSeconds > 0) {\n window.localStorage.setItem(ACCESS_TOKEN_EXPIRES_AT_KEY, String(Date.now() + expiresInSeconds * 1000));\n }\n}\n\n/** Remove all locally stored session data. */\nexport function clearSession(): void {\n if (typeof window === \"undefined\") return;\n window.localStorage.removeItem(ACCESS_TOKEN_KEY);\n window.localStorage.removeItem(ACCESS_TOKEN_EXPIRES_AT_KEY);\n}\n\n/** Normalized error so callers never depend on the axios error shape. */\nexport class ApiError extends Error {\n readonly status: number;\n readonly data: unknown;\n\n constructor(message: string, status: number, data: unknown) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.data = data;\n }\n}\n\n/**\n * Hook invoked when the refresh cookie is missing/expired. Wire it to your\n * router (e.g. redirect to the login page); the client itself stays\n * router-agnostic.\n */\nlet sessionExpiredHandler: (() => void) | null = null;\nexport function onSessionExpired(handler: () => void): void {\n sessionExpiredHandler = handler;\n}\n\n// ---------------------------------------------------------------------------\n// Refresh-token rotation\n// ---------------------------------------------------------------------------\n\nfunction isUnauthorized(error: unknown): boolean {\n return axios.isAxiosError(error) && error.response?.status === 401;\n}\n\n/** One refresh round-trip; persists the renewed token and its expiry. */\nasync function requestRefreshOnce(): Promise<string | null> {\n const response = await axios.get(`${BASE_URL}${REFRESH_PATH}`, {\n withCredentials: true,\n });\n // Default envelope: { token, tokenExpiresInSeconds }.\n const data = response.data as {\n token?: string;\n tokenExpiresInSeconds?: number;\n };\n if (!data?.token) return null;\n setSession(data.token, data.tokenExpiresInSeconds);\n return data.token;\n}\n\n// Shared in-flight refresh. The backend rotates the refresh cookie on every\n// call, so concurrent 401s must await the same request instead of issuing\n// parallel refreshes that invalidate each other's cookie.\nlet refreshPromise: Promise<string | null> | null = null;\n\n/** Exchange the httpOnly refresh cookie for a new access token (single-flight). */\nfunction refreshAccessToken(): Promise<string | null> {\n if (refreshPromise) return refreshPromise;\n\n refreshPromise = (async () => {\n try {\n return await requestRefreshOnce();\n } catch (firstError) {\n if (!isUnauthorized(firstError)) return null;\n // Possible cross-tab cookie rotation: retry once after a short pause.\n await new Promise((resolve) => setTimeout(resolve, REFRESH_RETRY_DELAY_MS));\n try {\n return await requestRefreshOnce();\n } catch {\n return null;\n }\n } finally {\n refreshPromise = null;\n }\n })();\n\n return refreshPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Proactive refresh scheduler (module-level singleton)\n// ---------------------------------------------------------------------------\n\nlet schedulerTimer: ReturnType<typeof setInterval> | null = null;\n\n/**\n * Start the scheduler that renews the token shortly before expiry. Call once\n * on the client (e.g. in the authenticated layout). Reactive 401 refresh\n * stays as a fallback for laptop sleep / scheduler drift.\n */\nexport function initProactiveTokenRefresh(): void {\n if (typeof window === \"undefined\" || schedulerTimer) return;\n\n const refreshIfDue = (): void => {\n const token = getAccessToken();\n const expiresAt = Number(window.localStorage.getItem(ACCESS_TOKEN_EXPIRES_AT_KEY) ?? 0);\n if (token && expiresAt && Date.now() >= expiresAt - PROACTIVE_REFRESH_LEAD_MS) {\n void refreshAccessToken();\n }\n };\n\n // Run immediately (tabs reopened after sleep) and then on an interval.\n refreshIfDue();\n schedulerTimer = setInterval(refreshIfDue, PROACTIVE_REFRESH_CHECK_INTERVAL_MS);\n}\n\n// ---------------------------------------------------------------------------\n// Axios instance\n// ---------------------------------------------------------------------------\n\nexport const api = axios.create({\n baseURL: BASE_URL,\n withCredentials: true,\n});\n\napi.interceptors.request.use((config) => {\n const token = getAccessToken();\n // Within the interceptor chain headers is always an AxiosHeaders instance.\n if (token) {\n config.headers.set(\"Authorization\", `Bearer ${token}`);\n }\n return config;\n});\n\napi.interceptors.response.use(\n (response) => response,\n async (error) => {\n const original = error?.config as (InternalAxiosRequestConfig & { _retriedAfterRefresh?: boolean }) | undefined;\n const url: string = original?.url ?? \"\";\n const canSilentlyRefresh =\n typeof window !== \"undefined\" && !original?._retriedAfterRefresh && !AUTH_PATH_PATTERN.test(url);\n\n if (isUnauthorized(error) && original && canSilentlyRefresh) {\n original._retriedAfterRefresh = true;\n const renewed = await refreshAccessToken();\n if (renewed) {\n original.headers.set(\"Authorization\", `Bearer ${renewed}`);\n return api(original);\n }\n // Refresh cookie missing or expired: the session is over.\n clearSession();\n sessionExpiredHandler?.();\n }\n\n if (axios.isAxiosError(error)) {\n const data = error.response?.data as { message?: string } | undefined;\n throw new ApiError(data?.message ?? error.message, error.response?.status ?? 0, data);\n }\n throw error;\n },\n);\n\n// ---------------------------------------------------------------------------\n// Typed convenience methods — return the response body directly.\n// ---------------------------------------------------------------------------\n\nexport const apiClient = {\n get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api.get<unknown, AxiosResponse<T>>(url, config).then((r) => r.data);\n },\n post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.post<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.put<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n patch<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> {\n return api.patch<unknown, AxiosResponse<T>>(url, data, config).then((r) => r.data);\n },\n delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {\n return api.delete<unknown, AxiosResponse<T>>(url, config).then((r) => r.data);\n },\n // HEAD/OPTIONS responses carry no body; resolve to the full AxiosResponse\n // so callers can still inspect status and headers.\n head<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {\n return api.head<unknown, AxiosResponse<T>>(url, config);\n },\n options<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {\n return api.options<unknown, AxiosResponse<T>>(url, config);\n },\n};\n",
15
15
  "type": "registry:lib"
16
16
  }
17
17
  ]
@@ -11,7 +11,7 @@
11
11
  "files": [
12
12
  {
13
13
  "path": "src/lib/auth.ts",
14
- "content": "\"use client\";\n\nimport {\n apiClient,\n clearSession,\n getAccessToken,\n initProactiveTokenRefresh,\n onSessionExpired,\n setSession,\n} from \"@/lib/api-client\";\n\n// ---------------------------------------------------------------------------\n// Project-specific configuration — edit these for your backend contract.\n// ---------------------------------------------------------------------------\n\n/** Login endpoint; accepts the credentials object and returns a session. */\nconst LOGIN_PATH = \"/auth/login\";\n\n/** Logout endpoint (called best-effort; local session is cleared regardless). */\nconst LOGOUT_PATH = \"/auth/logout\";\n\n/** Where to redirect when the session expires or login is required. */\nconst DEFAULT_LOGIN_PATH = \"/login\";\n\n/** Login response envelope (adjust fields to match your backend). */\ninterface LoginResult {\n token: string;\n tokenExpiresInSeconds?: number;\n}\n\nexport interface LoginCredentials {\n account: string;\n password: string;\n}\n\nlet initialized = false;\n\n/**\n * Wire auth behaviour to the router and start proactive token refresh.\n * Call once on the client, e.g. in the authenticated layout's useEffect.\n */\nexport function initAuth(options?: { loginPath?: string }): void {\n if (initialized || typeof window === \"undefined\") return;\n initialized = true;\n\n const loginPath = options?.loginPath ?? DEFAULT_LOGIN_PATH;\n\n // Avoid bouncing on the login page itself.\n onSessionExpired(() => {\n if (window.location.pathname !== loginPath) {\n const redirect = encodeURIComponent(\n window.location.pathname + window.location.search,\n );\n window.location.replace(`${loginPath}?redirect=${redirect}`);\n }\n });\n\n initProactiveTokenRefresh();\n}\n\n/** Log in, persist the session, and return the raw result for callers. */\nexport async function login(\n credentials: LoginCredentials,\n): Promise<LoginResult> {\n const result = await apiClient.post<LoginResult>(LOGIN_PATH, credentials);\n setSession(result.token, result.tokenExpiresInSeconds);\n return result;\n}\n\n/** Log out; always clears the local session even if the API call fails. */\nexport async function logout(): Promise<void> {\n try {\n await apiClient.post(LOGOUT_PATH);\n } finally {\n clearSession();\n }\n}\n\nexport function isAuthenticated(): boolean {\n return Boolean(getAccessToken());\n}\n",
14
+ "content": "\"use client\";\n\nimport {\n apiClient,\n clearSession,\n getAccessToken,\n initProactiveTokenRefresh,\n onSessionExpired,\n setSession,\n} from \"@/lib/api-client\";\n\n// ---------------------------------------------------------------------------\n// Project-specific configuration — edit these for your backend contract.\n// ---------------------------------------------------------------------------\n\n/** Login endpoint; accepts the credentials object and returns a session. */\nconst LOGIN_PATH = \"/auth/login\";\n\n/** Logout endpoint (called best-effort; local session is cleared regardless). */\nconst LOGOUT_PATH = \"/auth/logout\";\n\n/** Where to redirect when the session expires or login is required. */\nconst DEFAULT_LOGIN_PATH = \"/login\";\n\n/** Login response envelope (adjust fields to match your backend). */\ninterface LoginResult {\n token: string;\n tokenExpiresInSeconds?: number;\n}\n\nexport interface LoginCredentials {\n account: string;\n password: string;\n}\n\nlet initialized = false;\n\n/**\n * Wire auth behaviour to the router and start proactive token refresh.\n * Call once on the client, e.g. in the authenticated layout's useEffect.\n */\nexport function initAuth(options?: { loginPath?: string }): void {\n if (initialized || typeof window === \"undefined\") return;\n initialized = true;\n\n const loginPath = options?.loginPath ?? DEFAULT_LOGIN_PATH;\n\n // Avoid bouncing on the login page itself.\n onSessionExpired(() => {\n if (window.location.pathname !== loginPath) {\n const redirect = encodeURIComponent(window.location.pathname + window.location.search);\n window.location.replace(`${loginPath}?redirect=${redirect}`);\n }\n });\n\n initProactiveTokenRefresh();\n}\n\n/** Log in, persist the session, and return the raw result for callers. */\nexport async function login(credentials: LoginCredentials): Promise<LoginResult> {\n const result = await apiClient.post<LoginResult>(LOGIN_PATH, credentials);\n setSession(result.token, result.tokenExpiresInSeconds);\n return result;\n}\n\n/** Log out; always clears the local session even if the API call fails. */\nexport async function logout(): Promise<void> {\n try {\n await apiClient.post(LOGOUT_PATH);\n } finally {\n clearSession();\n }\n}\n\nexport function isAuthenticated(): boolean {\n return Boolean(getAccessToken());\n}\n",
15
15
  "type": "registry:lib"
16
16
  }
17
17
  ]
@@ -36,12 +36,8 @@ async function buildRegistry(sourceRoot, outputRoot) {
36
36
  type: manifest.type,
37
37
  title: manifest.title,
38
38
  ...(manifest.description ? { description: manifest.description } : {}),
39
- ...(manifest.dependencies?.length
40
- ? { dependencies: manifest.dependencies }
41
- : {}),
42
- ...(manifest.registryDependencies?.length
43
- ? { registryDependencies: manifest.registryDependencies }
44
- : {}),
39
+ ...(manifest.dependencies?.length ? { dependencies: manifest.dependencies } : {}),
40
+ ...(manifest.registryDependencies?.length ? { registryDependencies: manifest.registryDependencies } : {}),
45
41
  ...(manifest.postInstall ? { postInstall: manifest.postInstall } : {}),
46
42
  files,
47
43
  };
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/registry/build.ts"],"names":[],"mappings":";;;;;A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AC;QACjD,MAAM,kBAAE,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC5C,MAAM,kBAAE,CAAC,SAAS,CAAC,mBAAI,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QAC9F,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/r/registry-item.json",
3
+ "name": "data-table",
4
+ "type": "registry:component",
5
+ "title": "Data table",
6
+ "description": "Generic data table with client-side sorting and pagination, built on shadcn/ui table primitives.",
7
+ "files": [
8
+ {
9
+ "path": "src/components/data-table.tsx",
10
+ "content": "\"use client\";\n\nimport { useState, useMemo, type ReactNode } from \"react\";\nimport { ArrowUpDown, ChevronLeft, ChevronRight } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { cn } from \"@/lib/utils\";\n\n/** Column definition for the data table. */\nexport interface Column<T> {\n /** Key used to access the row value; also used as the sort key. */\n accessorKey: keyof T & string;\n /** Column header label. */\n header: string;\n /** Optional custom cell renderer. Receives the row's value for this column. */\n cell?: (value: T[keyof T], row: T) => ReactNode;\n /** Disable sorting for this column. */\n enableSorting?: boolean;\n}\n\ninterface DataTableProps<T> {\n columns: Column<T>[];\n data: T[];\n /** Number of rows per page. Defaults to 10. */\n pageSize?: number;\n className?: string;\n}\n\ntype SortDir = \"asc\" | \"desc\";\n\n/**\n * Generic data table with client-side sorting and pagination.\n *\n * Pass `columns` describing each field and `data` as the row array. The\n * component manages its own sort and page state internally.\n */\nexport function DataTable<T extends Record<string, unknown>>({\n columns,\n data,\n pageSize = 10,\n className,\n}: DataTableProps<T>) {\n const [sortKey, setSortKey] = useState<string | null>(null);\n const [sortDir, setSortDir] = useState<SortDir>(\"asc\");\n const [page, setPage] = useState(0);\n\n const sorted = useMemo(() => {\n if (!sortKey) return data;\n const copy = [...data];\n copy.sort((a, b) => {\n const av = a[sortKey];\n const bv = b[sortKey];\n if (av == null && bv == null) return 0;\n if (av == null) return 1;\n if (bv == null) return -1;\n if (typeof av === \"number\" && typeof bv === \"number\") {\n return sortDir === \"asc\" ? av - bv : bv - av;\n }\n const as = String(av);\n const bs = String(bv);\n return sortDir === \"asc\" ? as.localeCompare(bs) : bs.localeCompare(as);\n });\n return copy;\n }, [data, sortKey, sortDir]);\n\n const pageCount = Math.max(1, Math.ceil(sorted.length / pageSize));\n const safePage = Math.min(page, pageCount - 1);\n const pageData = sorted.slice(safePage * pageSize, (safePage + 1) * pageSize);\n\n function toggleSort(key: string) {\n if (sortKey === key) {\n setSortDir((d) => (d === \"asc\" ? \"desc\" : \"asc\"));\n } else {\n setSortKey(key);\n setSortDir(\"asc\");\n }\n setPage(0);\n }\n\n return (\n <div className={cn(\"flex flex-col gap-3\", className)}>\n <div className=\"rounded-md border\">\n <Table>\n <TableHeader>\n <TableRow>\n {columns.map((col) => (\n <TableHead key={col.accessorKey}>\n {col.enableSorting === false ? (\n col.header\n ) : (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"-ml-3 h-8 px-2\"\n onClick={() => toggleSort(col.accessorKey)}\n >\n {col.header}\n <ArrowUpDown className=\"ml-2 size-3 opacity-50\" />\n </Button>\n )}\n </TableHead>\n ))}\n </TableRow>\n </TableHeader>\n <TableBody>\n {pageData.length === 0 ? (\n <TableRow>\n <TableCell colSpan={columns.length} className=\"h-24 text-center text-muted-foreground\">\n No results.\n </TableCell>\n </TableRow>\n ) : (\n pageData.map((row, i) => (\n <TableRow key={i}>\n {columns.map((col) => (\n <TableCell key={col.accessorKey}>\n {col.cell ? col.cell(row[col.accessorKey], row) : String(row[col.accessorKey] ?? \"\")}\n </TableCell>\n ))}\n </TableRow>\n ))\n )}\n </TableBody>\n </Table>\n </div>\n\n {pageCount > 1 && (\n <div className=\"flex items-center justify-between text-sm text-muted-foreground\">\n <span>\n {safePage * pageSize + 1}–{Math.min((safePage + 1) * pageSize, sorted.length)} of {sorted.length}\n </span>\n <div className=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={safePage === 0}\n onClick={() => setPage((p) => Math.max(0, p - 1))}\n >\n <ChevronLeft className=\"size-4\" />\n </Button>\n <span className=\"px-2\">\n {safePage + 1} / {pageCount}\n </span>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={safePage >= pageCount - 1}\n onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}\n >\n <ChevronRight className=\"size-4\" />\n </Button>\n </div>\n </div>\n )}\n </div>\n );\n}\n",
11
+ "type": "registry:component"
12
+ }
13
+ ]
14
+ }
@@ -10,7 +10,7 @@
10
10
  "files": [
11
11
  {
12
12
  "path": "src/components/login-form.tsx",
13
- "content": "\"use client\";\n\nimport { Suspense, useState, type FormEvent } from \"react\";\nimport { useRouter, useSearchParams } from \"next/navigation\";\nimport { Loader2 } from \"lucide-react\";\n\nimport { login } from \"@/lib/auth\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\n\nfunction LoginFormFields() {\n const router = useRouter();\n const searchParams = useSearchParams();\n const [account, setAccount] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n async function handleSubmit(event: FormEvent<HTMLFormElement>) {\n event.preventDefault();\n setError(null);\n setSubmitting(true);\n try {\n await login({ account, password });\n // Honor ?redirect=/path when present, otherwise go home.\n router.replace(searchParams.get(\"redirect\") ?? \"/\");\n } catch (err) {\n setError(err instanceof Error ? err.message : \"Login failed\");\n } finally {\n setSubmitting(false);\n }\n }\n\n return (\n <Card className=\"w-full max-w-sm\">\n <CardHeader>\n <CardTitle className=\"text-xl\">Sign in</CardTitle>\n <CardDescription>\n Use your account and password to continue.\n </CardDescription>\n </CardHeader>\n <CardContent>\n <form\n onSubmit={handleSubmit}\n className=\"flex flex-col gap-4\"\n noValidate\n >\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"account\">Account</Label>\n <Input\n id=\"account\"\n name=\"account\"\n autoComplete=\"username\"\n placeholder=\"you@example.com\"\n value={account}\n onChange={(event) => setAccount(event.target.value)}\n required\n />\n </div>\n\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"password\">Password</Label>\n <Input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={password}\n onChange={(event) => setPassword(event.target.value)}\n required\n />\n </div>\n\n {error ? <p className=\"text-sm text-destructive\">{error}</p> : null}\n\n <Button type=\"submit\" disabled={submitting} className=\"w-full\">\n {submitting ? (\n <Loader2 className=\"size-4 animate-spin\" />\n ) : (\n \"Sign in\"\n )}\n </Button>\n </form>\n </CardContent>\n </Card>\n );\n}\n\n// useSearchParams requires a Suspense boundary; provide one so the block can\n// be dropped into any page directly.\nexport function LoginForm() {\n return (\n <div className=\"flex min-h-svh items-center justify-center p-4\">\n <Suspense fallback={null}>\n <LoginFormFields />\n </Suspense>\n </div>\n );\n}\n",
13
+ "content": "\"use client\";\n\nimport { Suspense, useState, type FormEvent } from \"react\";\nimport { useRouter, useSearchParams } from \"next/navigation\";\nimport { Loader2 } from \"lucide-react\";\n\nimport { login } from \"@/lib/auth\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\n\nfunction LoginFormFields() {\n const router = useRouter();\n const searchParams = useSearchParams();\n const [account, setAccount] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n async function handleSubmit(event: FormEvent<HTMLFormElement>) {\n event.preventDefault();\n setError(null);\n setSubmitting(true);\n try {\n await login({ account, password });\n // Honor ?redirect=/path when present, otherwise go home.\n router.replace(searchParams.get(\"redirect\") ?? \"/\");\n } catch (err) {\n setError(err instanceof Error ? err.message : \"Login failed\");\n } finally {\n setSubmitting(false);\n }\n }\n\n return (\n <Card className=\"w-full max-w-sm\">\n <CardHeader>\n <CardTitle className=\"text-xl\">Sign in</CardTitle>\n <CardDescription>Use your account and password to continue.</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSubmit} className=\"flex flex-col gap-4\" noValidate>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"account\">Account</Label>\n <Input\n id=\"account\"\n name=\"account\"\n autoComplete=\"username\"\n placeholder=\"you@example.com\"\n value={account}\n onChange={(event) => setAccount(event.target.value)}\n required\n />\n </div>\n\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"password\">Password</Label>\n <Input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={password}\n onChange={(event) => setPassword(event.target.value)}\n required\n />\n </div>\n\n {error ? <p className=\"text-sm text-destructive\">{error}</p> : null}\n\n <Button type=\"submit\" disabled={submitting} className=\"w-full\">\n {submitting ? <Loader2 className=\"size-4 animate-spin\" /> : \"Sign in\"}\n </Button>\n </form>\n </CardContent>\n </Card>\n );\n}\n\n// useSearchParams requires a Suspense boundary; provide one so the block can\n// be dropped into any page directly.\nexport function LoginForm() {\n return (\n <div className=\"flex min-h-svh items-center justify-center p-4\">\n <Suspense fallback={null}>\n <LoginFormFields />\n </Suspense>\n </div>\n );\n}\n",
14
14
  "type": "registry:block"
15
15
  }
16
16
  ]
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/r/registry-item.json",
3
+ "name": "page-header",
4
+ "type": "registry:component",
5
+ "title": "Page header",
6
+ "description": "Standard page header with title, description, and a right-aligned actions slot.",
7
+ "files": [
8
+ {
9
+ "path": "src/components/page-header.tsx",
10
+ "content": "import type { ReactNode } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface PageHeaderProps {\n title: string;\n description?: string;\n /** Right-aligned action area (buttons, etc.). */\n actions?: ReactNode;\n className?: string;\n}\n\n/**\n * Standard page header: title with optional description on the left and an\n * actions slot on the right.\n */\nexport function PageHeader({ title, description, actions, className }: PageHeaderProps) {\n return (\n <div className={cn(\"flex flex-col gap-2 border-b pb-4 sm:flex-row sm:items-center sm:justify-between\", className)}>\n <div className=\"space-y-1\">\n <h1 className=\"text-2xl font-semibold tracking-tight\">{title}</h1>\n {description ? <p className=\"text-sm text-muted-foreground\">{description}</p> : null}\n </div>\n {actions ? <div className=\"flex items-center gap-2\">{actions}</div> : null}\n </div>\n );\n}\n",
11
+ "type": "registry:component"
12
+ }
13
+ ]
14
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/r/registry-item.json",
3
+ "name": "settings-required-state",
4
+ "type": "registry:block",
5
+ "title": "Settings required state",
6
+ "description": "Empty state shown when required configuration is missing, with a call-to-action to set it up.",
7
+ "registryDependencies": [
8
+ "page-header"
9
+ ],
10
+ "files": [
11
+ {
12
+ "path": "src/components/settings-required-state.tsx",
13
+ "content": "import type { ReactNode } from \"react\";\nimport { Settings } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { PageHeader } from \"@/components/page-header\";\n\ninterface SettingsRequiredStateProps {\n title: string;\n description: string;\n /** Label for the primary call-to-action button. */\n actionLabel: string;\n /** Called when the user clicks the primary action. */\n onAction: () => void;\n /** Optional secondary action (e.g. learn more link). */\n secondary?: ReactNode;\n}\n\n/**\n * Empty state shown when a feature requires setup that has not been completed.\n * Renders a card with an icon, explanatory text, and a primary action button.\n */\nexport function SettingsRequiredState({\n title,\n description,\n actionLabel,\n onAction,\n secondary,\n}: SettingsRequiredStateProps) {\n return (\n <div className=\"flex flex-col gap-4\">\n <PageHeader title=\"Setup required\" description=\"Complete configuration to continue.\" />\n <Card className=\"mx-auto max-w-lg\">\n <CardHeader className=\"text-center\">\n <div className=\"mx-auto mb-3 flex size-12 items-center justify-center rounded-full bg-primary/10\">\n <Settings className=\"size-6 text-primary\" />\n </div>\n <CardTitle>{title}</CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"flex flex-col items-center gap-3\">\n <Button onClick={onAction} className=\"w-full sm:w-auto\">\n {actionLabel}\n </Button>\n {secondary}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
14
+ "type": "registry:block"
15
+ }
16
+ ]
17
+ }
@@ -46,9 +46,7 @@ async function readItemFile(root, name) {
46
46
  return JSON.parse(raw);
47
47
  }
48
48
  function isBuilt(item) {
49
- return (Array.isArray(item.files) &&
50
- item.files.length > 0 &&
51
- typeof item.files[0] === "object");
49
+ return Array.isArray(item.files) && item.files.length > 0 && typeof item.files[0] === "object";
52
50
  }
53
51
  async function loadItem(root, name) {
54
52
  const item = await readItemFile(root, name);
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/registry/store.ts"],"names":[],"mappings":";;;;;AA2CA,kDAaC;AAqBD,4BA+BC;AAMD,8CA+BC;AAjJD,gEAAkC;AAClC,0DAA6B;AAE7B,0CAAyC;AAgBzC,KAAK,UAAU,cAAc,CAAC,SAAiB;IAC7C,IAAI,OAAmC,CAAC;IACxC,IAAI,CAAC;QACH,OAAO,GAAG,MAAM,kBAAE,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;IACjE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;IACD,KAAK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AK,EAAE,CAAC;QACzB,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -11,7 +11,7 @@
11
11
  "files": [
12
12
  {
13
13
  "path": "src/components/theme-provider.tsx",
14
- "content": "\"use client\";\n\nimport type { ComponentProps } from \"react\";\nimport { ThemeProvider as NextThemesProvider } from \"next-themes\";\n\nexport function ThemeProvider({\n children,\n ...props\n}: ComponentProps<typeof NextThemesProvider>) {\n return <NextThemesProvider {...props}>{children}</NextThemesProvider>;\n}\n",
14
+ "content": "\"use client\";\n\nimport type { ComponentProps } from \"react\";\nimport { ThemeProvider as NextThemesProvider } from \"next-themes\";\n\nexport function ThemeProvider({ children, ...props }: ComponentProps<typeof NextThemesProvider>) {\n return <NextThemesProvider {...props}>{children}</NextThemesProvider>;\n}\n",
15
15
  "type": "registry:component"
16
16
  },
17
17
  {
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/r/registry-item.json",
3
+ "name": "web-monitor-sdk",
4
+ "type": "registry:component",
5
+ "title": "Web monitor SDK",
6
+ "description": "Browser-side monitoring (PV/AJAX/resource/errors) via @devbie/web-monitor-sdk. Scaffolds a client component for your root layout. Heartbeat wiring is NOT included — it is handled by the template's instrumentation.ts.",
7
+ "dependencies": [
8
+ "@devbie/web-monitor-sdk"
9
+ ],
10
+ "postInstall": "Add <WebMonitor /> inside your root layout <body> (src/app/layout.tsx), then set NEXT_PUBLIC_WEB_MONITOR_API (report endpoint URL) and NEXT_PUBLIC_WEB_MONITOR_APP_ID. The component is a no-op until both env vars are present.",
11
+ "files": [
12
+ {
13
+ "path": "src/components/web-monitor.tsx",
14
+ "content": "\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Browser-side monitoring bootstrap.\n *\n * Dynamically imports @devbie/web-monitor-sdk on mount and initializes it\n * with NEXT_PUBLIC_WEB_MONITOR_API (report endpoint) and\n * NEXT_PUBLIC_WEB_MONITOR_APP_ID. Renders nothing; it is a no-op until both\n * env vars are set. Heartbeat wiring is intentionally NOT handled here —\n * it lives in the template's instrumentation.ts (Node process only).\n *\n * The dynamic import keeps the SDK out of SSR/Edge evaluation entirely:\n * the monitor bundle is only loaded in the browser when the component mounts.\n */\nexport function WebMonitor() {\n useEffect(() => {\n const api = process.env.NEXT_PUBLIC_WEB_MONITOR_API;\n const appId = process.env.NEXT_PUBLIC_WEB_MONITOR_APP_ID;\n\n // Required configuration missing — stay silent in production, warn in dev.\n if (!api || !appId) {\n if (process.env.NODE_ENV === \"development\") {\n console.warn(\n \"[WebMonitor] NEXT_PUBLIC_WEB_MONITOR_API / NEXT_PUBLIC_WEB_MONITOR_APP_ID not set; monitoring disabled.\",\n );\n }\n return;\n }\n\n let disposed = false;\n\n void import(\"@devbie/web-monitor-sdk\").then(({ default: init }) => {\n // StrictMode mounts effects twice in dev; guard against double init.\n if (disposed) return;\n init({\n appId,\n api,\n isPage: true,\n isAjax: true,\n isResource: true,\n isError: true,\n });\n });\n\n return () => {\n disposed = true;\n };\n }, []);\n\n return null;\n}\n",
15
+ "type": "registry:component"
16
+ }
17
+ ]
18
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devbie/fewbie-cli",
3
- "version": "0.1.0-stage.0",
3
+ "version": "0.1.0",
4
4
  "description": "fewbie frontend framework CLI",
5
5
  "license": "MIT",
6
6
  "author": "worldzhy",
@@ -14,7 +14,7 @@
14
14
  "access": "public"
15
15
  },
16
16
  "scripts": {
17
- "build": "tsc -p tsconfig.json && node --import tsx scripts/build-registry.ts && chmod +x dist/index.js",
17
+ "build": "npm run clean && tsc -p tsconfig.json && node --import tsx scripts/build-registry.ts && chmod +x dist/index.js",
18
18
  "clean": "rimraf dist",
19
19
  "test": "node --import tsx --test test/*.test.ts",
20
20
  "prepublishOnly": "npm run build"
@@ -1,11 +0,0 @@
1
- export declare const GENERATOR_PACKAGE_NAME = "open-api-typescript-request-generator";
2
- export declare const GENERATOR_PACKAGE_SPEC = "open-api-typescript-request-generator@^0.0.7-alpha.0";
3
- export declare const GENERATOR_BIN_RELATIVE = "node_modules/open-api-typescript-request-generator/bin/apits";
4
- export declare const CONFIG_PROJECT_PATH = "apits.config.ts";
5
- export declare const API_CLIENT_PROJECT_PATH = "src/lib/api-client.ts";
6
- export declare const ADAPTER_PROJECT_PATH = "src/api/request.ts";
7
- export declare const DEFAULT_OUTPUT_DIR = "src/api/_gen";
8
- export declare const DEFAULT_GENERATED_NAME = "api";
9
- export declare const PUBLIC_BASE_URL_ENV = "NEXT_PUBLIC_BASE_URL";
10
- export declare function renderApitsConfig(input: string): string;
11
- export declare const ADAPTER_CONTENT = "/**\n * Adapter between generated API code and the fewbie api client.\n *\n * Scaffolded by `fewbie gen api` and never overwritten afterwards \u2014 edit it\n * freely (for example to unwrap a { code, data } response envelope).\n */\nimport type { AxiosRequestConfig } from \"axios\";\n\nimport { apiClient } from \"@/lib/api-client\";\n\ntype GeneratedMethod = <Req, Res>(\n url: string,\n config?: AxiosRequestConfig,\n) => Promise<Res>;\n\n// The generator puts POST/PUT/PATCH payloads on config.data; the fewbie\n// apiClient takes the body as a separate positional argument.\nfunction withBodyData(\n call: (\n url: string,\n data?: unknown,\n config?: AxiosRequestConfig,\n ) => Promise<unknown>,\n): GeneratedMethod {\n return (url, config) => {\n const { data, ...rest } = config ?? {};\n return call(url, data, rest) as Promise<never>;\n };\n}\n\n// HEAD/OPTIONS carry no response body; return the full AxiosResponse so\n// status and headers remain observable.\nfunction responseOnly(\n call: (url: string, config?: AxiosRequestConfig) => Promise<unknown>,\n): GeneratedMethod {\n return (url, config) => call(url, config) as Promise<never>;\n}\n\nexport interface GeneratedRequest {\n get: GeneratedMethod;\n post: GeneratedMethod;\n put: GeneratedMethod;\n patch: GeneratedMethod;\n delete: GeneratedMethod;\n head: GeneratedMethod;\n options: GeneratedMethod;\n}\n\nexport const request: GeneratedRequest = {\n get: (url, config) => apiClient.get(url, config) as Promise<never>,\n delete: (url, config) => apiClient.delete(url, config) as Promise<never>,\n head: responseOnly((url, config) => apiClient.head(url, config)),\n options: responseOnly((url, config) => apiClient.options(url, config)),\n post: withBodyData((url, data, config) => apiClient.post(url, data, config)),\n put: withBodyData((url, data, config) => apiClient.put(url, data, config)),\n patch: withBodyData((url, data, config) =>\n apiClient.patch(url, data, config),\n ),\n};\n";
@@ -1 +0,0 @@
1
- {"version":3,"file":"gen-api-templates.js","sourceRoot":"","sources":["../../src/commands/gen-api-templates.ts"],"names":[],"mappings":";;;AA6BA,8CAsBC;AAzCY,QAAA,sBAAsB,GAAG,uCAAuC,CAAC;AACjE,QAAA,sBAAsB,GACjC,sDAAsD,CAAC;AAC5C,QAAA,sBAAsB,GACjC,8DAA8D,CAAC;AAEpD,QAAA,mBAAmB,GAAG,iBAAiB,CAAC;AACxC,QAAA,uBAAuB,GAAG,uBAAuB,CAAC;AAClD,QAAA,oBAAoB,GAAG,oBAAoB,CAAC;AAC5C,QAAA,kBAAkB,GAAG,cAAc,CAAC;AACpC,QAAA,sBAAsB,GAAG,KAAK,CAAC;AAC/B,QAAA,mBAAmB,GAAG,sBAAsB,CAAC;AAG1D,SAAS,kBAAkB,CAAC,KAAa;IACvC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AAC3D,CAAC;AAGD,SAAgB,iBAAiB,CAAC,KAAa;IAC7C,MAAM,SAAS,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC5C,OAAO,iCAAiC,8BAAsB;;;;;;;;sCAQ1B,SAAS;eAChC,0BAAkB;aACpB,8BAAsB;;;mCAGA,2BAAmB;;;;;;CAMrD,CAAC;AACF,CAAC;AAQY,QAAA,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2D9B,CAAC"}
@@ -1,105 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.runGenApi = runGenApi;
7
- const promises_1 = __importDefault(require("node:fs/promises"));
8
- const node_path_1 = __importDefault(require("node:path"));
9
- const node_child_process_1 = require("node:child_process");
10
- const colorette_1 = require("colorette");
11
- const errors_1 = require("../lib/errors");
12
- const exec_interactive_1 = require("../lib/exec-interactive");
13
- const gen_api_templates_1 = require("./gen-api-templates");
14
- async function exists(target) {
15
- return promises_1.default
16
- .access(target)
17
- .then(() => true)
18
- .catch(() => false);
19
- }
20
- async function readPackageJson(projectRoot) {
21
- return JSON.parse(await promises_1.default.readFile(node_path_1.default.join(projectRoot, "package.json"), "utf8"));
22
- }
23
- function runGenerator(projectRoot, args) {
24
- return new Promise((resolve, reject) => {
25
- const child = (0, node_child_process_1.spawn)(process.execPath, args, {
26
- cwd: projectRoot,
27
- stdio: "inherit",
28
- });
29
- child.on("error", reject);
30
- child.on("close", (code) => {
31
- if (code === 0)
32
- resolve();
33
- else
34
- reject(new Error(`apits exited with code ${code}`));
35
- });
36
- });
37
- }
38
- async function runGenApi(options) {
39
- const projectRoot = node_path_1.default.resolve(options.cwd ?? process.cwd());
40
- if (!(await exists(node_path_1.default.join(projectRoot, "package.json")))) {
41
- throw new errors_1.CliError(`No package.json found in ${projectRoot}. Run 'fewbie gen api' inside a fewbie project.`);
42
- }
43
- if (!(await exists(node_path_1.default.join(projectRoot, gen_api_templates_1.API_CLIENT_PROJECT_PATH)))) {
44
- throw new errors_1.CliError(`'fewbie gen api' requires the api-client item. Run 'fewbie add api-client' first.`);
45
- }
46
- const configPath = node_path_1.default.join(projectRoot, gen_api_templates_1.CONFIG_PROJECT_PATH);
47
- const hasConfig = await exists(configPath);
48
- if (!hasConfig) {
49
- if (!options.input) {
50
- throw new errors_1.CliError(`No OpenAPI input and no ${gen_api_templates_1.CONFIG_PROJECT_PATH} found.\n` +
51
- ` First run: fewbie gen api <openapi-url-or-json-file>\n` +
52
- ` Afterwards: edit ${gen_api_templates_1.CONFIG_PROJECT_PATH} to manage sources.`);
53
- }
54
- }
55
- else if (options.input) {
56
- throw new errors_1.CliError(`${gen_api_templates_1.CONFIG_PROJECT_PATH} already exists. Update its \`input\` directly (or pass -n <name> to select a source) instead of passing a positional input.`);
57
- }
58
- const adapterPath = node_path_1.default.join(projectRoot, gen_api_templates_1.ADAPTER_PROJECT_PATH);
59
- if (!(await exists(adapterPath))) {
60
- await promises_1.default.mkdir(node_path_1.default.dirname(adapterPath), { recursive: true });
61
- await promises_1.default.writeFile(adapterPath, gen_api_templates_1.ADAPTER_CONTENT);
62
- console.info(` ${(0, colorette_1.green)("added")} ${gen_api_templates_1.ADAPTER_PROJECT_PATH}`);
63
- }
64
- if (!hasConfig) {
65
- await promises_1.default.writeFile(configPath, (0, gen_api_templates_1.renderApitsConfig)(options.input));
66
- console.info(` ${(0, colorette_1.green)("added")} ${gen_api_templates_1.CONFIG_PROJECT_PATH}`);
67
- }
68
- const pkg = await readPackageJson(projectRoot);
69
- const declared = new Set([
70
- ...Object.keys(pkg.dependencies ?? {}),
71
- ...Object.keys(pkg.devDependencies ?? {}),
72
- ]);
73
- if (!declared.has(gen_api_templates_1.GENERATOR_PACKAGE_NAME)) {
74
- if (options.skipInstall) {
75
- throw new errors_1.CliError(`Generator not installed. Run: npm install -D ${gen_api_templates_1.GENERATOR_PACKAGE_SPEC}`);
76
- }
77
- console.info(`\nInstalling dev dependency: ${gen_api_templates_1.GENERATOR_PACKAGE_SPEC}`);
78
- await (0, exec_interactive_1.execInteractive)("npm", ["install", "-D", gen_api_templates_1.GENERATOR_PACKAGE_SPEC], projectRoot);
79
- }
80
- const binPath = node_path_1.default.join(projectRoot, gen_api_templates_1.GENERATOR_BIN_RELATIVE);
81
- if (!(await exists(binPath))) {
82
- throw new errors_1.CliError(`Generator binary not found at ${gen_api_templates_1.GENERATOR_BIN_RELATIVE}. Run 'npm install' and retry.`);
83
- }
84
- const genArgs = [binPath, "gen"];
85
- if (options.name)
86
- genArgs.push("-n", options.name);
87
- if (options.watch)
88
- genArgs.push("--watch");
89
- const expectedOutput = node_path_1.default.join(projectRoot, gen_api_templates_1.DEFAULT_OUTPUT_DIR, `${options.name ?? gen_api_templates_1.DEFAULT_GENERATED_NAME}.ts`);
90
- const beforeStat = await promises_1.default.stat(expectedOutput).catch(() => null);
91
- console.info((0, colorette_1.cyan)(`\nGenerating API code (${gen_api_templates_1.DEFAULT_OUTPUT_DIR})...`));
92
- await runGenerator(projectRoot, genArgs);
93
- if (!options.watch) {
94
- const afterStat = await promises_1.default.stat(expectedOutput).catch(() => null);
95
- const refreshed = afterStat !== null &&
96
- (beforeStat === null || afterStat.mtimeMs > beforeStat.mtimeMs);
97
- if (!refreshed) {
98
- throw new errors_1.CliError(`Code generation failed: ${gen_api_templates_1.DEFAULT_OUTPUT_DIR}/${options.name ?? gen_api_templates_1.DEFAULT_GENERATED_NAME}.ts was not produced or updated. See the generator output above.`);
99
- }
100
- }
101
- console.info(`\n${(0, colorette_1.bold)("Next steps")}:`);
102
- console.info(` - Set ${(0, colorette_1.yellow)(gen_api_templates_1.PUBLIC_BASE_URL_ENV)} in .env.local (generated requests read it at runtime).`);
103
- console.info(` - Import generated functions from ${gen_api_templates_1.DEFAULT_OUTPUT_DIR}/api.ts (re-run after schema changes, or use --watch).`);
104
- }
105
- //# sourceMappingURL=gen-api.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"gen-api.js","sourceRoot":"","sources":["../../src/commands/gen-api.ts"],"names":[],"mappings":";;;;;AAoEA,8BAkHC;AAtLD,gEAAkC;AAClC,0DAA6B;AAC7B,2DAA2C;AAC3C,yCAAsD;AAEtD,0CAAyC;AACzC,8DAA0D;AAC1D,2DAY6B;AAqB7B,KAAK,UAAU,MAAM,CAAC,MAAc;IAClC,OAAO,kBAAE;SACN,MAAM,CAAC,MAAM,CAAC;SACd,IAAI,CAA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