@mednours/fronton 0.2.0 → 0.4.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.
package/README.md CHANGED
@@ -9,10 +9,13 @@ bun add @mednours/fronton
9
9
  Two separate entry points, deliberately not one:
10
10
 
11
11
  - **`@mednours/fronton`** (the root import) — Node-side, meant for `vite.config.ts` only: `obfuscateTailwind()`, `frontonCompression()`, `backonProxy()`.
12
- - **`@mednours/fronton/client`** — browser-safe, meant for application code: `resolveApiBaseUrl()`, `lazyDomAnimation()`/`lazyDomMax()`.
12
+ - **`@mednours/fronton/client`** — browser-safe, meant for application code: `resolveApiBaseUrl()`. Nothing here has a peer dependency, so importing it never obliges a project to install anything.
13
+ - **`@mednours/fronton/motion`** — `lazyDomAnimation()`/`lazyDomMax()`, which need the optional `motion` peer dependency installed.
13
14
 
14
15
  Mixing these into one entry point was the first version's actual design, and it broke in a specific, findable way: importing `resolveApiBaseUrl` from a component pulled the *entire* bundle — including `postcss`, `magic-string`, and `vite-plugin-compression2` — into the client dependency graph, since esbuild had already flattened everything into a single file before Vite's bundler ever got a chance to tree-shake it. Vite's dependency scanner then warned about externalizing `node:crypto`, `node:fs`, and `zlib` for the browser, and the shipped JS bundle was measurably bigger for it (in one test project, 338 KB vs. 191 KB after the split — that's not a rounding error). Splitting the entry point at the source fixes it structurally instead of relying on a bundler to clean it up.
15
16
 
17
+ The same mistake had a second, sharper version, which is why there are three entry points rather than two: `lazyDomAnimation`/`lazyDomMax` used to sit on `/client` alongside `resolveApiBaseUrl`. They reach `motion/react` through wrapper modules that import it *statically* (see below for why that indirection is unavoidable), and `motion` is an optional peer dependency — so in any project that hadn't installed it, Vite resolved the wrappers to an empty optional-peer stub and `vite build` failed outright with `MISSING_EXPORT: "domAnimation" is not exported by "__vite-optional-peer-dep:motion/react"`. Tree-shaking can't rescue this: resolution happens first, and merely *importing* the entry point is enough to put the wrappers in the graph. Every `create-fronton` project scaffolded next to a backon backend hit it, because the generated `App.tsx` imports `resolveApiBaseUrl` from `/client`. Moving the two loaders onto their own `/motion` entry point is what keeps `/client` honest about having nothing attached to it.
18
+
16
19
  ## `obfuscateTailwind(options?)`
17
20
 
18
21
  A build-only Vite plugin (`apply: "build"` — `bun run dev` stays fully readable). After Tailwind's CSS and the JS bundle are both fully generated, it collects every real class selector Tailwind actually emitted, hashes each one to a short opaque name, and rewrites both the stylesheet and known-safe class-bearing text in the built JS/HTML to match:
@@ -83,13 +86,13 @@ fetch(`${resolveApiBaseUrl()}/api/users`);
83
86
 
84
87
  Reads `import.meta.env.VITE_API_BASE_URL`, returning `""` (relative requests) when it's unset — correct for same-origin deployment or the dev-server proxy above. This exists because the obvious alternative, a `process.env` check (the pattern backon's own generated `generate-client` script uses, correctly, since that script runs under Node/Bun), does nothing useful in a browser bundle: `process` isn't defined there, so the check just silently falls through. Only `VITE_`-prefixed variables are ever exposed to client code — Vite drops everything else on purpose, so a backend secret sitting in the same `.env` file never leaks into the browser bundle.
85
88
 
86
- ## `lazyDomAnimation()` / `lazyDomMax()` (from `@mednours/fronton/client`)
89
+ ## `lazyDomAnimation()` / `lazyDomMax()` (from `@mednours/fronton/motion`)
87
90
 
88
91
  Pre-built `<LazyMotion features={...}>` loaders for [`motion`](https://motion.dev) (née Framer Motion):
89
92
 
90
93
  ```tsx
91
94
  import { LazyMotion, m } from "motion/react";
92
- import { lazyDomAnimation } from "@mednours/fronton/client";
95
+ import { lazyDomAnimation } from "@mednours/fronton/motion";
93
96
 
94
97
  <LazyMotion features={lazyDomAnimation}>
95
98
  <m.div animate={{ opacity: 1 }} initial={{ opacity: 0 }} />
@@ -98,9 +101,9 @@ import { lazyDomAnimation } from "@mednours/fronton/client";
98
101
 
99
102
  This exists because `motion`'s own `<LazyMotion features={domAnimation}>` example is a trap if `domAnimation` gets there via a plain, static `import { domAnimation } from "motion/react"` — that still pulls the whole animation engine into the main bundle, exactly as expensive as using `motion.div` directly. `features` only saves anything when it's a function that *dynamically* imports the bundle. Verified against a real Vite build: the static form produced one 265.81 KB chunk (85.91 KB gzip); switching to a real dynamic loader dropped the main chunk to 231.51 KB (74.58 KB gzip) and moved the rest into its own 37.42 KB chunk (14.18 KB gzip) that only loads once something on the page actually animates.
100
103
 
101
- The less obvious trap, also verified against a real build: dynamically importing `"motion/react"` itself doesn't work either. Every component using `<LazyMotion>`/`<m.div>` has to statically import `LazyMotion`/`m` from `"motion/react"` — there's no lazy way to get those — and Rollup refuses to split a module into its own chunk if *anything* in the build graph already imports that exact same specifier statically, even from an unrelated file (an "ineffective dynamic import" — collapses back into one chunk). `lazyDomAnimation`/`lazyDomMax` work around this by each dynamically importing a tiny dedicated internal module that statically re-exports just one feature bundle, giving Rollup a boundary that isn't already claimed elsewhere. Confirmed end-to-end, not just in theory: this package's own build (esbuild with `--splitting`) preserves that boundary as a real separate chunk file, and feeding its actual `dist/client.js` output into a real downstream Vite build reproduced the same 231.51/37.42 KB split.
104
+ The less obvious trap, also verified against a real build: dynamically importing `"motion/react"` itself doesn't work either. Every component using `<LazyMotion>`/`<m.div>` has to statically import `LazyMotion`/`m` from `"motion/react"` — there's no lazy way to get those — and Rollup refuses to split a module into its own chunk if *anything* in the build graph already imports that exact same specifier statically, even from an unrelated file (an "ineffective dynamic import" — collapses back into one chunk). `lazyDomAnimation`/`lazyDomMax` work around this by each dynamically importing a tiny dedicated internal module that statically re-exports just one feature bundle, giving Rollup a boundary that isn't already claimed elsewhere. Confirmed end-to-end, not just in theory: this package's own build (esbuild with `--splitting`) preserves that boundary as a real separate chunk file, and feeding its actual `dist/motion.js` output into a real downstream Vite build reproduced the same 231.51/37.42 KB split.
102
105
 
103
- `lazyDomAnimation` covers drag-free interactions (hover/tap/enter-exit/animate); `lazyDomMax` is a strict superset that adds layout and drag animations — same as `motion`'s own `domAnimation`/`domMax`. `motion` is an optional peer dependency (`bun add motion`) — install it only if you actually call one of these.
106
+ `lazyDomAnimation` covers drag-free interactions (hover/tap/enter-exit/animate); `lazyDomMax` is a strict superset that adds layout and drag animations — same as `motion`'s own `domAnimation`/`domMax`. `motion` is an optional peer dependency (`bun add motion`) — install it before importing this entry point at all, not just before calling one of these, since the loaders reach `motion/react` through statically-importing wrapper modules that a bundler has to resolve either way.
104
107
 
105
108
  ## `compressImages(options?)` and `compressVideos(options?)`
106
109
 
@@ -9,6 +9,20 @@ export interface BackonProxyOptions {
9
9
  * namespace of their own. Default true.
10
10
  */
11
11
  stripPrefix?: boolean;
12
+ /**
13
+ * Forward WebSocket upgrade requests on `prefix` to the backend as well.
14
+ * Default true, because backon ships `defineWebSocket()` and a route
15
+ * registered with it is reached over the same prefix as everything else —
16
+ * without this, such a route answers fine when hit directly on the
17
+ * backend's own port but hangs forever through the dev server, with no
18
+ * error on either side to explain it.
19
+ *
20
+ * This does not interfere with Vite's own HMR socket: Vite only hands an
21
+ * upgrade to a proxy entry whose path actually matches, and HMR's socket
22
+ * is not under `prefix`. Set false only if the backend has no WebSocket
23
+ * routes and you'd rather upgrade requests 404 than be forwarded.
24
+ */
25
+ ws?: boolean;
12
26
  }
13
27
  /**
14
28
  * Builds a Vite dev-server `server.proxy` entry pointed at a backon
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/backon/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AASzC,MAAM,WAAW,kBAAkB;IACjC,wFAAwF;IACxF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAU1G"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/backon/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AASzC,MAAM,WAAW,kBAAkB;IACjC,wFAAwF;IACxF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;;;;;;OAYG;IACH,EAAE,CAAC,EAAE,OAAO,CAAC;CACd;AAED;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAmB1G"}
@@ -0,0 +1,27 @@
1
+ import type { Plugin } from "vite";
2
+ export interface BundleReportOptions {
3
+ /** Warn when an uncompressed JS/CSS asset exceeds this size in KB. Defaults to 250. */
4
+ warnThresholdKb?: number;
5
+ /** Disable console output while still collecting metrics (e.g. in custom reporters/tests). */
6
+ silent?: boolean;
7
+ /** Optional callback receiving the computed chunk entries sorted largest-first. */
8
+ onReport?: (entries: BundleAssetReport[]) => void;
9
+ }
10
+ export interface BundleAssetReport {
11
+ fileName: string;
12
+ rawBytes: number;
13
+ gzipBytes: number;
14
+ oversized: boolean;
15
+ }
16
+ /** Computes raw and gzip byte sizes for every emitted JS/CSS bundle asset. */
17
+ export declare function summarizeBundleAssets(bundle: Record<string, {
18
+ type: string;
19
+ code?: string;
20
+ source?: string | Uint8Array;
21
+ }>, warnThresholdKb?: number): BundleAssetReport[];
22
+ /**
23
+ * Zero-dependency Vite plugin that logs a sorted raw + gzip bundle breakdown
24
+ * at the end of `vite build` and flags oversized chunks that need lazy splitting.
25
+ */
26
+ export declare function bundleReport(options?: BundleReportOptions): Plugin;
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bundle-report/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAEnC,MAAM,WAAW,mBAAmB;IAClC,uFAAuF;IACvF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,8FAA8F;IAC9F,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,iBAAiB,EAAE,KAAK,IAAI,CAAC;CACnD;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;CACpB;AAMD,8EAA8E;AAC9E,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,GAAG,UAAU,CAAA;CAAE,CAAC,EACrF,eAAe,SAAM,GACpB,iBAAiB,EAAE,CAuBrB;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB,GAAG,MAAM,CAmBtE"}
package/dist/client.d.ts CHANGED
@@ -1,73 +1,54 @@
1
1
  /**
2
- * Reads the API base URL a fronton project's own components should call
3
- * against, at runtime, in the browser.
4
- *
5
- * This exists to fix a real gap: a plain `process.env.API_BASE_URL` check
6
- * (the pattern backon's own generated `generate-client` script uses,
7
- * correctly, since that script runs under Node/Bun) does nothing useful in
8
- * a Vite-built browser bundle — `process` isn't defined there, so the
9
- * check just silently falls through. Vite's own env mechanism is
10
- * `import.meta.env`, statically replaced at build time, and only
11
- * `VITE_`-prefixed variables are ever exposed to client code (Vite drops
12
- * everything else on purpose, so a backend secret sitting in the same
13
- * .env file never leaks into the browser bundle).
14
- *
15
- * Returns "" (relative requests) when unset — correct for same-origin
16
- * deployment or a dev-server proxy (see backonProxy in the root entry
17
- * point); set VITE_API_BASE_URL explicitly when the frontend and backend
18
- * are on different origins.
2
+ * Reads `import.meta.env.VITE_API_BASE_URL` at runtime in a Vite browser
3
+ * bundle, returning `""` when unset (for same-origin deploys or Vite dev proxy).
19
4
  */
20
5
  export declare function resolveApiBaseUrl(): string;
6
+ /** Structured error thrown by `createApiClient()` on non-2xx responses, matching backon's error JSON shape. */
7
+ export declare class ApiError extends Error {
8
+ readonly status: number;
9
+ readonly code: string;
10
+ readonly details?: unknown;
11
+ constructor(status: number, code: string, message: string, details?: unknown);
12
+ }
13
+ export type ApiCredentials = NonNullable<RequestInit["credentials"]>;
14
+ export type ApiBodyInit = NonNullable<RequestInit["body"]>;
15
+ export interface ApiClientOptions {
16
+ /** Override base URL (defaults to `resolveApiBaseUrl() || (DEV ? "/api" : "")`). */
17
+ baseUrl?: string;
18
+ /** Default fetch credentials mode (defaults to `"same-origin"`). */
19
+ credentials?: ApiCredentials;
20
+ /** Default headers merged into every request. */
21
+ headers?: Record<string, string>;
22
+ /** Optional custom fetch implementation (useful for tests or SSR). */
23
+ fetch?: typeof fetch;
24
+ }
25
+ export interface ApiRequestOptions extends Omit<RequestInit, "body"> {
26
+ /** Plain object/array is JSON-stringified automatically; BodyInit values pass through unchanged. */
27
+ body?: unknown;
28
+ query?: Record<string, string | number | boolean | undefined>;
29
+ }
21
30
  /**
22
- * Pre-built `<LazyMotion features={...}>` loaders for `motion` (the
23
- * animation library, née Framer Motion) — `lazyDomAnimation` for
24
- * `domAnimation` (drag/hover/tap/enter-exit), `lazyDomMax` for `domMax`
25
- * (adds layout animations, on top of everything `domAnimation` covers).
26
- *
27
- * Why this exists: `motion`'s own `<LazyMotion features={domAnimation}>`
28
- * pattern only saves anything if `features` is a function that *dynamically*
29
- * imports the feature bundle — passing the bundle directly (a plain, static
30
- * `import { domAnimation } from "motion/react"`) still pulls the whole
31
- * animation engine into the main bundle, identical in cost to using
32
- * `motion.div` outright. Verified against a real Vite build: the static
33
- * form produced one 265.81 KB chunk (85.91 KB gzip); switching to a real
34
- * dynamic loader dropped the main chunk to 231.51 KB (74.58 KB gzip) and
35
- * moved the rest into its own 37.42 KB chunk (14.18 KB gzip) that only
36
- * loads once something on the page actually animates.
37
- *
38
- * The less obvious trap, also verified against a real build: it's not
39
- * enough for *this* function to dynamically import `"motion/react"` —
40
- * every component using `<LazyMotion>`/`<m.div>` also has to statically
41
- * import `LazyMotion`/`m` from `"motion/react"` (there's no lazy way to get
42
- * those), and Rollup refuses to split a module into its own chunk if
43
- * *anything* in the build graph already imports that exact same module
44
- * specifier statically (an "ineffective dynamic import" — confirmed by
45
- * reproducing it: dynamically importing `"motion/react"` directly, even
46
- * from a completely different file than the static import, still collapsed
47
- * back into one chunk). That's why `lazyDomAnimation`/`lazyDomMax` don't
48
- * dynamically import `"motion/react"` themselves — they each dynamically
49
- * import a tiny dedicated wrapper module (./motion/dom-animation,
50
- * ./motion/dom-max) that statically re-exports just that one feature bundle,
51
- * giving Rollup a module boundary that isn't already claimed elsewhere.
52
- * fronton's own build (esbuild with `--splitting`) preserves that boundary
53
- * as a real separate output chunk rather than inlining it back together —
54
- * confirmed by building this package for real and feeding its actual
55
- * `dist/client.js` output into a real downstream Vite build.
56
- *
57
- * Usage:
58
- * ```tsx
59
- * import { LazyMotion, m } from "motion/react";
60
- * import { lazyDomAnimation } from "@mednours/fronton/client";
61
- *
62
- * <LazyMotion features={lazyDomAnimation}>
63
- * <m.div animate={{ opacity: 1 }} initial={{ opacity: 0 }} />
64
- * </LazyMotion>
65
- * ```
66
- *
67
- * `motion` is an optional peer dependency (`bun add motion`) — these two
68
- * exports are the only things in this file that need it, and only if you
69
- * actually call one.
31
+ * Lightweight typed fetch wrapper pre-wired for backon backends:
32
+ * resolves `VITE_API_BASE_URL` / dev `/api` proxy, serializes JSON bodies,
33
+ * and unwraps backon `{ error: { code, message, details } }` payloads into `ApiError`.
70
34
  */
71
- export declare const lazyDomAnimation: () => Promise<import("motion/react").FeatureBundle>;
72
- export declare const lazyDomMax: () => Promise<import("motion/react").FeatureBundle>;
35
+ export declare function createApiClient(options?: ApiClientOptions): {
36
+ request: <T = unknown>(path: string, init?: ApiRequestOptions) => Promise<T>;
37
+ get: <T = unknown>(path: string, init?: Omit<ApiRequestOptions, "method" | "body">) => Promise<T>;
38
+ post: <T = unknown>(path: string, body?: unknown, init?: Omit<ApiRequestOptions, "method" | "body">) => Promise<T>;
39
+ put: <T = unknown>(path: string, body?: unknown, init?: Omit<ApiRequestOptions, "method" | "body">) => Promise<T>;
40
+ patch: <T = unknown>(path: string, body?: unknown, init?: Omit<ApiRequestOptions, "method" | "body">) => Promise<T>;
41
+ delete: <T = unknown>(path: string, init?: Omit<ApiRequestOptions, "method">) => Promise<T>;
42
+ };
43
+ /**
44
+ * Triggers a lazy route/component dynamic import once and caches the trigger
45
+ * so repeated hover/focus events are free. Ideal for declarative React Router links.
46
+ */
47
+ export declare function preloadChunk(loader: () => Promise<unknown>): void;
48
+ /** Returns React event handlers (`onMouseEnter`, `onFocus`, `onTouchStart`) that preload a lazy chunk on intent. */
49
+ export declare function createPrefetchHandlers(loader: () => Promise<unknown>): {
50
+ onMouseEnter: () => void;
51
+ onFocus: () => void;
52
+ onTouchStart: () => void;
53
+ };
73
54
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAG1C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,eAAO,MAAM,gBAAgB,QAAO,OAAO,CAAC,OAAO,cAAc,EAAE,aAAa,CACnB,CAAC;AAC9D,eAAO,MAAM,UAAU,QAAO,OAAO,CAAC,OAAO,cAAc,EAAE,aAAa,CACnB,CAAC"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAKA;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAG1C;AAED,+GAA+G;AAC/G,qBAAa,QAAS,SAAQ,KAAK;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAE3B,YAAY,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAM3E;CACF;AAED,MAAM,MAAM,cAAc,GAAG,WAAW,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,CAAC;AACrE,MAAM,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;AAE3D,MAAM,WAAW,gBAAgB;IAC/B,oFAAoF;IACpF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oEAAoE;IACpE,WAAW,CAAC,EAAE,cAAc,CAAC;IAC7B,iDAAiD;IACjD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,sEAAsE;IACtE,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,MAAM,WAAW,iBAAkB,SAAQ,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC;IAClE,oGAAoG;IACpG,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC,CAAC;CAC/D;AAmCD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,gBAAqB;cAIrC,CAAC,kBAAkB,MAAM,SAAQ,iBAAiB,KAAQ,OAAO,CAAC,CAAC,CAAC;UA2DnF,CAAC,GAAG,OAAO,QAAQ,MAAM,SAAS,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,MAAM,CAAC;WAE3E,CAAC,GAAG,OAAO,QAAQ,MAAM,SAAS,OAAO,SAAS,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,MAAM,CAAC;UAE7F,CAAC,GAAG,OAAO,QAAQ,MAAM,SAAS,OAAO,SAAS,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,MAAM,CAAC;YAE1F,CAAC,GAAG,OAAO,QAAQ,MAAM,SAAS,OAAO,SAAS,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,MAAM,CAAC;aAE3F,CAAC,GAAG,OAAO,QAAQ,MAAM,SAAS,IAAI,CAAC,iBAAiB,EAAE,QAAQ,CAAC;EAG/E;AAID;;;GAGG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAOjE;AAED,oHAAoH;AACpH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC;IAGjE,YAAY;IACZ,OAAO;IACP,YAAY;EAEf"}
package/dist/client.js CHANGED
@@ -3,10 +3,121 @@ function resolveApiBaseUrl() {
3
3
  const value = import.meta.env?.VITE_API_BASE_URL;
4
4
  return typeof value === "string" && value.length > 0 ? value : "";
5
5
  }
6
- var lazyDomAnimation = () => import("./dom-animation-RYVDSRON.js").then((mod) => mod.default);
7
- var lazyDomMax = () => import("./dom-max-SN3JCHFZ.js").then((mod) => mod.default);
6
+ var ApiError = class extends Error {
7
+ status;
8
+ code;
9
+ details;
10
+ constructor(status, code, message, details) {
11
+ super(message);
12
+ this.name = "ApiError";
13
+ this.status = status;
14
+ this.code = code;
15
+ this.details = details;
16
+ }
17
+ };
18
+ function isBodyInit(value) {
19
+ return typeof value === "string" || value instanceof FormData || value instanceof URLSearchParams || value instanceof Blob || value instanceof ArrayBuffer || ArrayBuffer.isView(value) || typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
20
+ }
21
+ function defaultClientBaseUrl() {
22
+ const configured = resolveApiBaseUrl();
23
+ if (configured) return configured;
24
+ return import.meta.env?.DEV ? "/api" : "";
25
+ }
26
+ function buildUrl(baseUrl, path, query) {
27
+ const normalizedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
28
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
29
+ let url = `${normalizedBase}${normalizedPath}`;
30
+ if (query) {
31
+ const params = new URLSearchParams();
32
+ for (const [k, v] of Object.entries(query)) {
33
+ if (v !== void 0) params.set(k, String(v));
34
+ }
35
+ const qs = params.toString();
36
+ if (qs) url += `${url.includes("?") ? "&" : "?"}${qs}`;
37
+ }
38
+ return url;
39
+ }
40
+ function createApiClient(options = {}) {
41
+ const baseUrl = options.baseUrl ?? defaultClientBaseUrl();
42
+ const fetchFn = options.fetch ?? fetch;
43
+ async function request(path, init = {}) {
44
+ const { body, query, headers, ...rest } = init;
45
+ const mergedHeaders = new Headers(options.headers);
46
+ if (headers) {
47
+ new Headers(headers).forEach((value, key) => mergedHeaders.set(key, value));
48
+ }
49
+ let preparedBody;
50
+ if (body !== void 0) {
51
+ if (isBodyInit(body)) {
52
+ preparedBody = body;
53
+ } else {
54
+ preparedBody = JSON.stringify(body);
55
+ if (!mergedHeaders.has("Content-Type")) {
56
+ mergedHeaders.set("Content-Type", "application/json");
57
+ }
58
+ }
59
+ }
60
+ const res = await fetchFn(buildUrl(baseUrl, path, query), {
61
+ credentials: options.credentials ?? "same-origin",
62
+ ...rest,
63
+ headers: mergedHeaders,
64
+ body: preparedBody
65
+ });
66
+ if (!res.ok) {
67
+ let code = "http_error";
68
+ let message = res.statusText || `Request failed with status ${res.status}`;
69
+ let details;
70
+ const contentType2 = res.headers.get("content-type") ?? "";
71
+ if (contentType2.includes("application/json")) {
72
+ const parsed = await res.json().catch(() => void 0);
73
+ if (parsed?.error) {
74
+ code = parsed.error.code ?? code;
75
+ message = parsed.error.message ?? message;
76
+ details = parsed.error.details;
77
+ } else if (parsed?.message) {
78
+ message = parsed.message;
79
+ }
80
+ }
81
+ throw new ApiError(res.status, code, message, details);
82
+ }
83
+ if (res.status === 204 || res.headers.get("content-length") === "0") {
84
+ return void 0;
85
+ }
86
+ const contentType = res.headers.get("content-type") ?? "";
87
+ if (contentType.includes("application/json")) {
88
+ return await res.json();
89
+ }
90
+ return await res.text();
91
+ }
92
+ return {
93
+ request,
94
+ get: (path, init) => request(path, { ...init, method: "GET" }),
95
+ post: (path, body, init) => request(path, { ...init, method: "POST", body }),
96
+ put: (path, body, init) => request(path, { ...init, method: "PUT", body }),
97
+ patch: (path, body, init) => request(path, { ...init, method: "PATCH", body }),
98
+ delete: (path, init) => request(path, { ...init, method: "DELETE" })
99
+ };
100
+ }
101
+ var preloadedLoaders = /* @__PURE__ */ new WeakSet();
102
+ function preloadChunk(loader) {
103
+ if (preloadedLoaders.has(loader)) return;
104
+ preloadedLoaders.add(loader);
105
+ void loader().catch(() => {
106
+ preloadedLoaders.delete(loader);
107
+ });
108
+ }
109
+ function createPrefetchHandlers(loader) {
110
+ const trigger = () => preloadChunk(loader);
111
+ return {
112
+ onMouseEnter: trigger,
113
+ onFocus: trigger,
114
+ onTouchStart: trigger
115
+ };
116
+ }
8
117
  export {
9
- lazyDomAnimation,
10
- lazyDomMax,
118
+ ApiError,
119
+ createApiClient,
120
+ createPrefetchHandlers,
121
+ preloadChunk,
11
122
  resolveApiBaseUrl
12
123
  };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,8 @@ export { frontonCompression } from "./compression/index";
4
4
  export type { FrontonCompressionOptions } from "./compression/index";
5
5
  export { backonProxy } from "./backon/index";
6
6
  export type { BackonProxyOptions } from "./backon/index";
7
+ export { bundleReport } from "./bundle-report/index";
8
+ export type { BundleReportOptions, BundleAssetReport } from "./bundle-report/index";
7
9
  export { compressImages } from "./media/images";
8
10
  export type { CompressImagesOptions } from "./media/images";
9
11
  export { compressVideos } from "./media/videos";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,YAAY,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAOzD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,YAAY,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,YAAY,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAOpF,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -207,12 +207,60 @@ function frontonCompression(options = {}) {
207
207
 
208
208
  // src/backon/index.ts
209
209
  function backonProxy(target, options = {}) {
210
- const { prefix = "/api", stripPrefix = true } = options;
210
+ const { prefix = "/api", stripPrefix = true, ws = true } = options;
211
211
  return {
212
212
  [prefix]: {
213
213
  target,
214
214
  changeOrigin: true,
215
- ...stripPrefix ? { rewrite: (path) => path.replace(new RegExp(`^${prefix}`), "") } : {}
215
+ ws,
216
+ ...stripPrefix ? {
217
+ // Stripping a prefix off a request to the prefix itself leaves
218
+ // an empty path ("/api" -> ""), which is not a valid request
219
+ // target — fall back to "/" rather than relying on whatever the
220
+ // underlying HTTP client happens to coerce an empty string to.
221
+ rewrite: (path) => path.replace(new RegExp(`^${prefix}`), "") || "/"
222
+ } : {}
223
+ }
224
+ };
225
+ }
226
+
227
+ // src/bundle-report/index.ts
228
+ import { gzipSync } from "node:zlib";
229
+ function formatKb(bytes) {
230
+ return `${(bytes / 1024).toFixed(2)} kB`;
231
+ }
232
+ function summarizeBundleAssets(bundle, warnThresholdKb = 250) {
233
+ const thresholdBytes = warnThresholdKb * 1024;
234
+ const reports = [];
235
+ for (const [fileName, item] of Object.entries(bundle)) {
236
+ if (!/\.(?:m?js|css)$/.test(fileName)) continue;
237
+ const raw = item.type === "chunk" ? Buffer.from(item.code ?? "", "utf-8") : typeof item.source === "string" ? Buffer.from(item.source, "utf-8") : Buffer.from(item.source ?? new Uint8Array());
238
+ const gzipBytes = gzipSync(raw).length;
239
+ reports.push({
240
+ fileName,
241
+ rawBytes: raw.length,
242
+ gzipBytes,
243
+ oversized: raw.length > thresholdBytes
244
+ });
245
+ }
246
+ reports.sort((a, b) => b.rawBytes - a.rawBytes);
247
+ return reports;
248
+ }
249
+ function bundleReport(options = {}) {
250
+ const warnThresholdKb = options.warnThresholdKb ?? 250;
251
+ return {
252
+ name: "fronton:bundle-report",
253
+ apply: "build",
254
+ generateBundle(_outputOptions, bundle) {
255
+ const entries = summarizeBundleAssets(bundle, warnThresholdKb);
256
+ options.onReport?.(entries);
257
+ if (options.silent || entries.length === 0) return;
258
+ console.log("\n[fronton] Bundle report:");
259
+ for (const entry of entries) {
260
+ const flag = entry.oversized ? ` [> ${warnThresholdKb} kB \u2014 consider lazy()]` : "";
261
+ console.log(` ${entry.fileName.padEnd(38)} ${formatKb(entry.rawBytes).padStart(10)} (gzip ${formatKb(entry.gzipBytes)})${flag}`);
262
+ }
263
+ console.log();
216
264
  }
217
265
  };
218
266
  }
@@ -451,6 +499,7 @@ function compressVideos(options = {}) {
451
499
  }
452
500
  export {
453
501
  backonProxy,
502
+ bundleReport,
454
503
  compressImages,
455
504
  compressVideos,
456
505
  frontonCompression,
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Pre-built `<LazyMotion features={...}>` loaders for `motion` (the
3
+ * animation library, née Framer Motion) — `lazyDomAnimation` for
4
+ * `domAnimation` (drag/hover/tap/enter-exit), `lazyDomMax` for `domMax`
5
+ * (adds layout animations, on top of everything `domAnimation` covers).
6
+ *
7
+ * Why this exists: `motion`'s own `<LazyMotion features={domAnimation}>`
8
+ * pattern only saves anything if `features` is a function that *dynamically*
9
+ * imports the feature bundle — passing the bundle directly (a plain, static
10
+ * `import { domAnimation } from "motion/react"`) still pulls the whole
11
+ * animation engine into the main bundle, identical in cost to using
12
+ * `motion.div` outright. Verified against a real Vite build: the static
13
+ * form produced one 265.81 KB chunk (85.91 KB gzip); switching to a real
14
+ * dynamic loader dropped the main chunk to 231.51 KB (74.58 KB gzip) and
15
+ * moved the rest into its own 37.42 KB chunk (14.18 KB gzip) that only
16
+ * loads once something on the page actually animates.
17
+ *
18
+ * The less obvious trap, also verified against a real build: it's not
19
+ * enough for *this* function to dynamically import `"motion/react"` —
20
+ * every component using `<LazyMotion>`/`<m.div>` also has to statically
21
+ * import `LazyMotion`/`m` from `"motion/react"` (there's no lazy way to get
22
+ * those), and Rollup refuses to split a module into its own chunk if
23
+ * *anything* in the build graph already imports that exact same module
24
+ * specifier statically (an "ineffective dynamic import" — confirmed by
25
+ * reproducing it: dynamically importing `"motion/react"` directly, even
26
+ * from a completely different file than the static import, still collapsed
27
+ * back into one chunk). That's why `lazyDomAnimation`/`lazyDomMax` don't
28
+ * dynamically import `"motion/react"` themselves — they each dynamically
29
+ * import a tiny dedicated wrapper module (./dom-animation, ./dom-max) that
30
+ * statically re-exports just that one feature bundle, giving Rollup a
31
+ * module boundary that isn't already claimed elsewhere.
32
+ * fronton's own build (esbuild with `--splitting`) preserves that boundary
33
+ * as a real separate output chunk rather than inlining it back together —
34
+ * confirmed by building this package for real and feeding its actual
35
+ * output into a real downstream Vite build.
36
+ *
37
+ * That static re-export inside the wrappers is also why these two live on
38
+ * their own entry point (`@mednours/fronton/motion`) rather than on
39
+ * `/client` — see motion.ts's header comment for the build failure that
40
+ * caused.
41
+ *
42
+ * Usage:
43
+ * ```tsx
44
+ * import { LazyMotion, m } from "motion/react";
45
+ * import { lazyDomAnimation } from "@mednours/fronton/motion";
46
+ *
47
+ * <LazyMotion features={lazyDomAnimation}>
48
+ * <m.div animate={{ opacity: 1 }} initial={{ opacity: 0 }} />
49
+ * </LazyMotion>
50
+ * ```
51
+ *
52
+ * `motion` is an optional peer dependency (`bun add motion`) — install it
53
+ * before importing this entry point at all, not just before calling one of
54
+ * these.
55
+ */
56
+ export declare const lazyDomAnimation: () => Promise<import("motion/react").FeatureBundle>;
57
+ export declare const lazyDomMax: () => Promise<import("motion/react").FeatureBundle>;
58
+ //# sourceMappingURL=loaders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loaders.d.ts","sourceRoot":"","sources":["../../src/motion/loaders.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,eAAO,MAAM,gBAAgB,QAAO,OAAO,CAAC,OAAO,cAAc,EAAE,aAAa,CAC1B,CAAC;AACvD,eAAO,MAAM,UAAU,QAAO,OAAO,CAAC,OAAO,cAAc,EAAE,aAAa,CAC1B,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { lazyDomAnimation, lazyDomMax } from "./motion/loaders";
2
+ //# sourceMappingURL=motion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"motion.d.ts","sourceRoot":"","sources":["../src/motion.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/motion.js ADDED
@@ -0,0 +1,7 @@
1
+ // src/motion/loaders.ts
2
+ var lazyDomAnimation = () => import("./dom-animation-RYVDSRON.js").then((mod) => mod.default);
3
+ var lazyDomMax = () => import("./dom-max-SN3JCHFZ.js").then((mod) => mod.default);
4
+ export {
5
+ lazyDomAnimation,
6
+ lazyDomMax
7
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mednours/fronton",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Opinionated runtime pieces for fronton-scaffolded Vite projects — Tailwind class obfuscation, gzip/brotli compression, and backon API wiring.",
6
6
  "license": "MIT",
@@ -27,12 +27,16 @@
27
27
  "./client": {
28
28
  "types": "./dist/client.d.ts",
29
29
  "import": "./dist/client.js"
30
+ },
31
+ "./motion": {
32
+ "types": "./dist/motion.d.ts",
33
+ "import": "./dist/motion.js"
30
34
  }
31
35
  },
32
36
  "scripts": {
33
37
  "test": "bun test",
34
38
  "typecheck": "tsc --noEmit",
35
- "build": "rm -rf dist && tsc -p tsconfig.json --emitDeclarationOnly && esbuild src/index.ts src/client.ts --bundle --platform=node --format=esm --target=node18 --packages=external --splitting --outdir=dist",
39
+ "build": "rm -rf dist && tsc -p tsconfig.json --emitDeclarationOnly && esbuild src/index.ts src/client.ts src/motion.ts --bundle --platform=node --format=esm --target=node18 --packages=external --splitting --outdir=dist",
36
40
  "prepublishOnly": "bun run typecheck && bun run test && bun run build"
37
41
  },
38
42
  "peerDependencies": {
@@ -40,7 +44,7 @@
40
44
  "sharp": "^0.35.0",
41
45
  "fluent-ffmpeg": "^2.1.3",
42
46
  "ffmpeg-static": "^5.3.0",
43
- "motion": "^12.0.0"
47
+ "motion": "^12.0.0 || ^13.0.0 || ^14.0.0 || ^15.0.0"
44
48
  },
45
49
  "peerDependenciesMeta": {
46
50
  "sharp": {
@@ -57,10 +61,10 @@
57
61
  }
58
62
  },
59
63
  "dependencies": {
60
- "magic-string": "^1.2.0",
61
- "postcss": "^8.5.26",
64
+ "magic-string": "^1.4.5",
65
+ "postcss": "^8.5.34",
62
66
  "postcss-selector-parser": "^7.1.5",
63
- "vite-plugin-compression2": "^2.5.3"
67
+ "vite-plugin-compression2": "^2.5.4"
64
68
  },
65
69
  "devDependencies": {
66
70
  "@types/bun": "latest",
@@ -68,10 +72,10 @@
68
72
  "esbuild": "^0.28.2",
69
73
  "ffmpeg-static": "^5.3.0",
70
74
  "fluent-ffmpeg": "^2.1.3",
71
- "motion": "^12.42.2",
72
- "react": "^19.2.8",
73
- "sharp": "^0.35.3",
75
+ "motion": "^15.0.1",
76
+ "react": "^19.3.1",
77
+ "sharp": "^0.35.6",
74
78
  "typescript": "^7.0.2",
75
- "vite": "^8.2.1"
79
+ "vite": "^8.4.1"
76
80
  }
77
81
  }