noofpi 0.0.0-stage → 1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -2
  3. package/bin/noofpi.mjs +2 -0
  4. package/client.d.ts +79 -0
  5. package/dist/build-63DMFZJY.js +48 -0
  6. package/dist/chunk-2XCZWFIQ.js +253 -0
  7. package/dist/chunk-6OWKWAIW.js +68 -0
  8. package/dist/chunk-ELXCFUA4.js +97 -0
  9. package/dist/chunk-EZPJF4D4.js +314 -0
  10. package/dist/chunk-FIJJ3EGL.js +353 -0
  11. package/dist/chunk-G35DW4NA.js +129 -0
  12. package/dist/chunk-KGZP2RCF.js +51 -0
  13. package/dist/chunk-MTWSTW7V.js +44 -0
  14. package/dist/chunk-MTXQR32N.js +8 -0
  15. package/dist/chunk-NALDZ3PS.js +90 -0
  16. package/dist/chunk-NX6BO7UB.js +284 -0
  17. package/dist/chunk-SSJ2KKBZ.js +996 -0
  18. package/dist/chunk-WX2V6EYH.js +102 -0
  19. package/dist/chunk-X34Y6ESE.js +810 -0
  20. package/dist/chunk-Y3NBZ6DW.js +55 -0
  21. package/dist/chunk-YZAZ7IWK.js +27 -0
  22. package/dist/cli.js +93 -0
  23. package/dist/dev-USSN6KFV.js +149 -0
  24. package/dist/devtools-KTDSD5PR.js +564 -0
  25. package/dist/images-BNwTAi50.d.ts +36 -0
  26. package/dist/index.d.ts +115 -0
  27. package/dist/index.js +15 -0
  28. package/dist/route-rules-COilNsVT.d.ts +127 -0
  29. package/dist/runtime/default-app.js +15 -0
  30. package/dist/runtime/entry-client.js +70 -0
  31. package/dist/runtime/entry-server.js +107 -0
  32. package/dist/runtime/index.d.ts +523 -0
  33. package/dist/runtime/index.js +224 -0
  34. package/dist/runtime/routes.js +14 -0
  35. package/dist/server/bun.js +47 -0
  36. package/dist/server/index.d.ts +109 -0
  37. package/dist/server/index.js +48 -0
  38. package/dist/server/node.js +15 -0
  39. package/dist/start-U6A3PBRI.js +61 -0
  40. package/dist/validation-ClXd_DAW.d.ts +159 -0
  41. package/package.json +101 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lior Cohen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <img src="./assets/logo.svg" alt="noofpi logo" width="96" height="96">
4
+
5
+ # noofpi
6
+
7
+ A minimal Vue + Vite full-stack framework built around [doofpi](https://www.npmjs.com/package/doofpi)
8
+
9
+ File-based pages, SSR or SPA, a built-in doofpi server and a doofpi client with four fetch modes.
10
+
11
+ [![npm version](https://img.shields.io/npm/v/noofpi.svg)](https://www.npmjs.com/package/noofpi) [![MIT License](https://img.shields.io/badge/license-MIT-green.svg)](https://opensource.org/licenses/MIT)
12
+
13
+ </div>
14
+
15
+ ## Getting started
16
+
17
+ ```sh
18
+ bun create noofpi my-app
19
+ cd my-app
20
+ bun install
21
+ bun run dev
22
+ ```
23
+
24
+ To add noofpi to an existing project:
25
+
26
+ ```sh
27
+ bun add noofpi doofpi
28
+ ```
29
+
30
+ Requires Node.js 20 or newer (or Bun). `doofpi` is a peer dependency (`>=1.3.1`).
31
+
32
+ ## CLI
33
+
34
+ ```
35
+ noofpi dev Start the dev server with live reload
36
+ noofpi build Build for production into .output/
37
+ noofpi start Run the production build
38
+ ```
39
+
40
+ Options: `--root <dir>`, `--port <port>`, `--host <host>`, `--preset <name>`.
41
+
42
+ ## Documentation
43
+
44
+ https://liorcodev.github.io/noofpi-docs/
45
+
46
+ ## License
47
+
48
+ MIT
package/bin/noofpi.mjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/cli.js";
package/client.d.ts ADDED
@@ -0,0 +1,79 @@
1
+ declare module "virtual:noofpi/config" {
2
+ import type { HeadConfig, RouteRules } from "noofpi/runtime";
3
+ interface DoofpiConfig {
4
+ fetch: "dfetch" | "pfetch" | "lfetch" | "sfetch";
5
+ url: string | undefined;
6
+ root: string;
7
+ }
8
+ interface VirtualConfig {
9
+ ssr: boolean;
10
+ routeRules: RouteRules;
11
+ head: HeadConfig;
12
+ doofpi: DoofpiConfig;
13
+ devtools: boolean;
14
+ }
15
+ export const publicConfig: VirtualConfig;
16
+ /** Only defined in server builds */
17
+ export const serverConfig: VirtualConfig | undefined;
18
+ }
19
+
20
+ declare module "virtual:noofpi/i18n" {
21
+ import type { Messages } from "noofpi/runtime";
22
+ /** `undefined` unless `i18n` is configured */
23
+ export const i18nConfig:
24
+ { locales: string[]; defaultLocale: string } | undefined;
25
+ /** `app/locales/*`, keyed by file path. Server builds only (empty in the browser) */
26
+ export const messageFiles: Record<string, Messages>;
27
+ /** `app/locales/*`, keyed by file path, loaded on demand. Browser builds only (empty on the server) */
28
+ export const messageLoaders: Record<string, () => Promise<Messages>>;
29
+ }
30
+
31
+ declare module "virtual:noofpi/routes" {
32
+ import type { RouteRecordRaw } from "vue-router";
33
+ const routes: RouteRecordRaw[];
34
+ export default routes;
35
+ }
36
+
37
+ declare module "virtual:noofpi/layouts" {
38
+ import type { Component } from "vue";
39
+ const layouts: Record<string, Component>;
40
+ export default layouts;
41
+ }
42
+
43
+ declare module "virtual:noofpi/middleware" {
44
+ import type { RouteMiddleware } from "noofpi/runtime";
45
+ const middleware: Record<string, RouteMiddleware>;
46
+ export default middleware;
47
+ }
48
+
49
+ declare module "virtual:noofpi/plugins" {
50
+ import type { NoofpiPlugin } from "noofpi/runtime";
51
+ const plugins: Record<string, NoofpiPlugin>;
52
+ export default plugins;
53
+ }
54
+
55
+ declare module "virtual:noofpi/app-root" {
56
+ import type { Component } from "vue";
57
+ const component: Component;
58
+ export default component;
59
+ }
60
+
61
+ declare module "virtual:noofpi/error" {
62
+ import type { Component } from "vue";
63
+ /** `app/error.vue`, or `undefined` when the project has none */
64
+ const component: Component | undefined;
65
+ export default component;
66
+ }
67
+
68
+ declare module "*?image" {
69
+ import type { ImageSource } from "noofpi/runtime";
70
+ /** Size and AVIF / WebP variants of the image, for `<NoofpiImage>` */
71
+ const image: ImageSource;
72
+ export default image;
73
+ }
74
+
75
+ declare module "*.vue" {
76
+ import type { DefineComponent } from "vue";
77
+ const component: DefineComponent<object, object, any>;
78
+ export default component;
79
+ }
@@ -0,0 +1,48 @@
1
+ import {
2
+ OUTPUT_DIR,
3
+ createViteConfig,
4
+ finishPresetBuild,
5
+ resolveFonts
6
+ } from "./chunk-SSJ2KKBZ.js";
7
+ import "./chunk-NX6BO7UB.js";
8
+ import "./chunk-MTXQR32N.js";
9
+ import "./chunk-ELXCFUA4.js";
10
+ import "./chunk-G35DW4NA.js";
11
+ import {
12
+ usesFetchMode
13
+ } from "./chunk-FIJJ3EGL.js";
14
+ import "./chunk-Y3NBZ6DW.js";
15
+
16
+ // src/vite/build.ts
17
+ import { rm } from "fs/promises";
18
+ import path from "path";
19
+ import { build } from "vite";
20
+ async function buildApp(root, resolved, preset = resolved.build.preset) {
21
+ const config = { ...resolved, build: { preset } };
22
+ const isStatic = preset === "github-pages";
23
+ if (isStatic) {
24
+ const { fetch } = config.doofpi;
25
+ for (const mode of ["lfetch", "pfetch", "sfetch"])
26
+ if (usesFetchMode(fetch, config.routeRules, mode))
27
+ throw new Error(
28
+ `[noofpi] The github-pages preset has no server, so doofpi fetch "${mode}" cannot be used (use "dfetch")`
29
+ );
30
+ config.ssr = false;
31
+ }
32
+ const fonts = await resolveFonts(root, config);
33
+ await rm(path.join(root, OUTPUT_DIR), { recursive: true, force: true });
34
+ console.log(`
35
+ noofpi: building client (preset: ${preset})...`);
36
+ await build(createViteConfig(root, config, "client", fonts));
37
+ if (!isStatic) {
38
+ console.log("\nnoofpi: building server...");
39
+ await build(createViteConfig(root, config, "server", fonts));
40
+ }
41
+ const next = await finishPresetBuild(root, config, preset);
42
+ console.log(`
43
+ noofpi: build complete -> .output/ (${next})
44
+ `);
45
+ }
46
+ export {
47
+ buildApp
48
+ };
@@ -0,0 +1,253 @@
1
+ import {
2
+ PROXY_PREFIX,
3
+ SSR_OUTLET
4
+ } from "./chunk-MTXQR32N.js";
5
+ import {
6
+ applyCookies,
7
+ createCookieJar,
8
+ injectPayload
9
+ } from "./chunk-EZPJF4D4.js";
10
+ import {
11
+ applyHead,
12
+ resolveHead
13
+ } from "./chunk-G35DW4NA.js";
14
+ import {
15
+ applyRouteSecurity,
16
+ applySecurityHeaders,
17
+ buildCspHeader,
18
+ generateNonce,
19
+ injectNonce,
20
+ isAllowedHost,
21
+ isCrossSiteWrite,
22
+ isServerRendered,
23
+ limitRequestBody,
24
+ matchRouteRules,
25
+ usesFetchMode,
26
+ usesNonce
27
+ } from "./chunk-FIJJ3EGL.js";
28
+
29
+ // src/server/cookies.ts
30
+ var JAR = /* @__PURE__ */ Symbol.for("noofpi.request-cookies");
31
+ function bindRequestCookies(request, jar) {
32
+ request[JAR] = jar;
33
+ }
34
+ function getRequestCookies(request) {
35
+ const jar = request[JAR];
36
+ if (!jar)
37
+ throw new Error(
38
+ "[noofpi] getRequestCookies() needs the original Request of a request handled by the noofpi server"
39
+ );
40
+ return jar;
41
+ }
42
+
43
+ // src/server/proxy.ts
44
+ var FORWARDED_REQUEST_HEADERS = [
45
+ "accept",
46
+ "accept-language",
47
+ "authorization",
48
+ "cookie",
49
+ "content-type",
50
+ "if-none-match",
51
+ "if-modified-since",
52
+ "range"
53
+ ];
54
+ var DROPPED_RESPONSE_HEADERS = [
55
+ "content-encoding",
56
+ "content-length",
57
+ "transfer-encoding",
58
+ "connection",
59
+ "keep-alive"
60
+ ];
61
+ var json = (status, message) => new Response(JSON.stringify({ message }), {
62
+ status,
63
+ headers: { "Content-Type": "application/json" }
64
+ });
65
+ function resolveProxyTarget(pathname, search, base, root) {
66
+ if (!pathname.startsWith(PROXY_PREFIX + "/")) return null;
67
+ const rest = pathname.slice(PROXY_PREFIX.length);
68
+ let target;
69
+ try {
70
+ target = new URL(rest + search, base);
71
+ } catch {
72
+ return null;
73
+ }
74
+ const afterRoot = target.pathname.charAt(root.length);
75
+ const insideRoot = target.pathname.startsWith(root) && (afterRoot === "" || afterRoot === "." || afterRoot === "/");
76
+ return target.origin === new URL(base).origin && insideRoot ? target : null;
77
+ }
78
+ async function proxyRequest(request, options) {
79
+ const url = new URL(request.url);
80
+ const target = resolveProxyTarget(
81
+ url.pathname,
82
+ url.search,
83
+ options.base,
84
+ options.root
85
+ );
86
+ if (!target) return json(404, "Not found");
87
+ const headers = new Headers();
88
+ for (const name of FORWARDED_REQUEST_HEADERS) {
89
+ const value = request.headers.get(name);
90
+ if (value !== null) headers.set(name, value);
91
+ }
92
+ const hooked = await options.hook?.({ request, headers, target });
93
+ if (hooked instanceof Response) return hooked;
94
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
95
+ let upstream;
96
+ try {
97
+ upstream = await fetch(target, {
98
+ method: request.method,
99
+ headers,
100
+ // Body is streamed through untouched (binary uploads and JSON alike)
101
+ body: hasBody ? request.body : void 0,
102
+ redirect: "manual",
103
+ ...hasBody ? { duplex: "half" } : {}
104
+ });
105
+ } catch {
106
+ return json(502, "Bad gateway");
107
+ }
108
+ const responseHeaders = new Headers(upstream.headers);
109
+ for (const name of DROPPED_RESPONSE_HEADERS) responseHeaders.delete(name);
110
+ return new Response(upstream.body, {
111
+ status: upstream.status,
112
+ headers: responseHeaders
113
+ });
114
+ }
115
+
116
+ // src/server/handler.ts
117
+ var isUnder = (pathname, root) => pathname === root || pathname.startsWith(root + ".") || pathname.startsWith(root + "/");
118
+ function routeSecurity(mod, url) {
119
+ const rules = mod.config.routeRules;
120
+ return applyRouteSecurity(
121
+ mod.config.security,
122
+ rules && matchRouteRules(rules, url.pathname).security
123
+ );
124
+ }
125
+ function createHandler(options) {
126
+ const reportError = (error) => {
127
+ options.onError?.(error);
128
+ if (!options.onError) console.error(error);
129
+ };
130
+ const respond = async (mod, request, env, cookies) => {
131
+ const url = new URL(request.url);
132
+ const { ssr, doofpi } = mod.config;
133
+ const security = routeSecurity(mod, url);
134
+ const isProxy = usesFetchMode(doofpi.fetch, mod.config.routeRules, "pfetch") && url.pathname.startsWith(PROXY_PREFIX + "/");
135
+ const isApi = !!mod.doofpi && isUnder(url.pathname, doofpi.root);
136
+ if (security?.csrf && (isProxy || isApi) && isCrossSiteWrite(request, url, security.csrf)) {
137
+ return new Response(JSON.stringify({ message: "Forbidden" }), {
138
+ status: 403,
139
+ headers: { "Content-Type": "application/json" }
140
+ });
141
+ }
142
+ if (isProxy) {
143
+ return await proxyRequest(request, {
144
+ base: doofpi.url,
145
+ root: doofpi.root,
146
+ hook: mod.proxyHook
147
+ });
148
+ }
149
+ if (isApi) {
150
+ return await mod.doofpi.fetch(request, env);
151
+ }
152
+ if (request.method !== "GET" && request.method !== "HEAD") {
153
+ return new Response("Method Not Allowed", { status: 405 });
154
+ }
155
+ if (/\.[a-z0-9]+$/i.test(url.pathname))
156
+ return new Response("Not Found", { status: 404 });
157
+ const template = await options.getTemplate(url.pathname + url.search);
158
+ let html = "";
159
+ let head = resolveHead(mod.config.head);
160
+ let payload;
161
+ let status = 200;
162
+ if (mod.render && isServerRendered(ssr, mod.config.routeRules, url.pathname)) {
163
+ const result = await mod.render(url.pathname + url.search, {
164
+ origin: url.origin,
165
+ cookie: request.headers.get("cookie") ?? void 0,
166
+ cookies,
167
+ acceptLanguage: request.headers.get("accept-language") ?? void 0,
168
+ fetch: (input, init) => handler(new Request(input, init), env)
169
+ });
170
+ if (result.redirect)
171
+ return new Response(null, {
172
+ status: result.status,
173
+ headers: { Location: result.redirect }
174
+ });
175
+ if (result.error !== void 0) reportError(result.error);
176
+ html = result.html;
177
+ head = result.head ?? head;
178
+ payload = result.payload;
179
+ status = result.status;
180
+ }
181
+ let shell = applyHead(template, head);
182
+ const { csp } = security ?? {};
183
+ const nonce = usesNonce(csp) ? generateNonce() : void 0;
184
+ if (nonce) shell = injectNonce(shell, nonce);
185
+ let body = shell.replace(SSR_OUTLET, () => html);
186
+ if (payload) body = injectPayload(body, payload);
187
+ const headers = new Headers({ "Content-Type": "text/html; charset=utf-8" });
188
+ if (csp) {
189
+ const [name, value] = buildCspHeader(csp, nonce);
190
+ headers.set(name, value);
191
+ }
192
+ return new Response(request.method === "HEAD" ? null : body, {
193
+ status,
194
+ headers
195
+ });
196
+ };
197
+ const handler = async (incoming, env) => {
198
+ let request = incoming;
199
+ let tooLarge = () => false;
200
+ const payloadTooLarge = () => new Response("Payload Too Large", { status: 413 });
201
+ try {
202
+ const mod = await options.load();
203
+ const middleware = mod.middleware ?? [];
204
+ const url = new URL(request.url);
205
+ if (!isAllowedHost(url, mod.config.security?.allowedHosts))
206
+ return new Response("Invalid Host", { status: 400 });
207
+ const security = routeSecurity(mod, url);
208
+ if (security?.bodyLimit) {
209
+ const limited = limitRequestBody(request, security.bodyLimit);
210
+ request = limited.request;
211
+ tooLarge = limited.tooLarge;
212
+ }
213
+ const finish = (response2) => applySecurityHeaders(
214
+ response2,
215
+ security?.headers ?? {},
216
+ url.protocol === "https:"
217
+ );
218
+ if (tooLarge()) return finish(payloadTooLarge());
219
+ const cookies = createCookieJar({
220
+ cookie: request.headers.get("cookie"),
221
+ defaults: { secure: url.protocol === "https:" }
222
+ });
223
+ bindRequestCookies(request, cookies);
224
+ const run = async (index) => {
225
+ const current = middleware[index];
226
+ if (!current) return respond(mod, request, env, cookies);
227
+ const response2 = await current(
228
+ { request, url, env, cookies },
229
+ () => run(index + 1)
230
+ );
231
+ if (!(response2 instanceof Response))
232
+ throw new Error(
233
+ "[noofpi] Server middleware must return a Response (return next() to continue)."
234
+ );
235
+ return response2;
236
+ };
237
+ const response = applyCookies(await run(0), cookies);
238
+ return finish(tooLarge() ? payloadTooLarge() : response);
239
+ } catch (error) {
240
+ if (tooLarge()) return payloadTooLarge();
241
+ reportError(error);
242
+ return new Response("Internal Server Error", { status: 500 });
243
+ }
244
+ };
245
+ return handler;
246
+ }
247
+
248
+ export {
249
+ getRequestCookies,
250
+ resolveProxyTarget,
251
+ proxyRequest,
252
+ createHandler
253
+ };
@@ -0,0 +1,68 @@
1
+ // src/runtime/middleware.ts
2
+ import {
3
+ useRoute
4
+ } from "vue-router";
5
+ function defineRouteMiddleware(middleware) {
6
+ return middleware;
7
+ }
8
+ var GLOBAL_SUFFIX = /\.global$/;
9
+ function parseMiddlewareFile(file) {
10
+ const base = file.slice(file.lastIndexOf("/") + 1).replace(/\.[jt]s$/, "");
11
+ return {
12
+ name: base.replace(GLOBAL_SUFFIX, "").replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(),
13
+ global: GLOBAL_SUFFIX.test(base)
14
+ };
15
+ }
16
+ function createMiddlewareRegistry(modules) {
17
+ const registry = { global: [], named: {} };
18
+ for (const [file, middleware] of Object.entries(modules).sort(
19
+ ([a], [b]) => a < b ? -1 : 1
20
+ )) {
21
+ const { name, global } = parseMiddlewareFile(file);
22
+ if (global) registry.global.push(middleware);
23
+ else registry.named[name] = middleware;
24
+ }
25
+ return registry;
26
+ }
27
+ function normalizeMiddleware(value) {
28
+ if (typeof value === "string") return [value];
29
+ return Array.isArray(value) ? value.filter((name) => typeof name === "string") : [];
30
+ }
31
+ function createMiddlewareGuard(registry) {
32
+ return async (to, from) => {
33
+ const chain = [...registry.global];
34
+ for (const name of normalizeMiddleware(to.meta.middleware)) {
35
+ const middleware = registry.named[name];
36
+ if (!middleware)
37
+ throw new Error(
38
+ `[noofpi] Unknown middleware "${name}" used by ${to.path}. Add app/middleware/${name}.ts.`
39
+ );
40
+ chain.push(middleware);
41
+ }
42
+ for (const middleware of chain) {
43
+ const result = await middleware(to, from);
44
+ if (result !== void 0 && result !== true) return result;
45
+ }
46
+ };
47
+ }
48
+ function useMiddleware(names) {
49
+ if (import.meta.env.DEV) {
50
+ const route = useRoute();
51
+ const wanted = normalizeMiddleware(names);
52
+ const picked = normalizeMiddleware(route.meta.middleware);
53
+ if (wanted.join() !== picked.join()) {
54
+ console.warn(
55
+ `[noofpi] useMiddleware(${JSON.stringify(names)}) was not picked up for ${route.path}. Call it with string literals inside a page in app/pages.`
56
+ );
57
+ }
58
+ }
59
+ }
60
+
61
+ export {
62
+ defineRouteMiddleware,
63
+ parseMiddlewareFile,
64
+ createMiddlewareRegistry,
65
+ normalizeMiddleware,
66
+ createMiddlewareGuard,
67
+ useMiddleware
68
+ };
@@ -0,0 +1,97 @@
1
+ // src/i18n.ts
2
+ var LOCALE_COOKIE = "noofpi-locale";
3
+ var LOCALE_TAG = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
4
+ function resolveI18n(input) {
5
+ if (!input) return void 0;
6
+ const { locales } = input;
7
+ if (!Array.isArray(locales) || !locales.length)
8
+ throw new Error("[noofpi] i18n.locales must list at least one locale");
9
+ for (const locale of locales) {
10
+ if (typeof locale !== "string" || !LOCALE_TAG.test(locale))
11
+ throw new Error(
12
+ `[noofpi] i18n.locales must be language tags such as "en" or "pt-BR" (got "${String(locale)}")`
13
+ );
14
+ }
15
+ if (new Set(locales.map((locale) => locale.toLowerCase())).size !== locales.length)
16
+ throw new Error("[noofpi] i18n.locales must not contain duplicates");
17
+ const defaultLocale = input.defaultLocale ?? locales[0];
18
+ if (!locales.includes(defaultLocale))
19
+ throw new Error(
20
+ `[noofpi] i18n.defaultLocale "${defaultLocale}" must be one of i18n.locales (${locales.join(", ")})`
21
+ );
22
+ return { locales: [...locales], defaultLocale };
23
+ }
24
+ var baseLanguage = (tag) => tag.split("-")[0].toLowerCase();
25
+ function matchLocale(candidates, locales) {
26
+ for (const candidate of candidates) {
27
+ if (!candidate) continue;
28
+ const lower = candidate.toLowerCase();
29
+ const found = locales.find((locale) => locale.toLowerCase() === lower) ?? locales.find(
30
+ (locale) => locale.toLowerCase() === baseLanguage(candidate)
31
+ ) ?? locales.find(
32
+ (locale) => baseLanguage(locale) === baseLanguage(candidate)
33
+ );
34
+ if (found) return found;
35
+ }
36
+ return void 0;
37
+ }
38
+ function parseAcceptLanguage(header) {
39
+ if (!header) return [];
40
+ return header.split(",").map((part, index) => {
41
+ const [tag = "", ...params] = part.trim().split(";");
42
+ const q = params.map((param) => /^\s*q\s*=\s*([\d.]+)\s*$/.exec(param)?.[1]).find((value) => value !== void 0);
43
+ return { tag: tag.trim(), q: q === void 0 ? 1 : Number(q), index };
44
+ }).filter(({ tag, q }) => tag && tag !== "*" && q > 0).sort((a, b) => b.q - a.q || a.index - b.index).map(({ tag }) => tag);
45
+ }
46
+ function pickLocale(config, sources) {
47
+ return matchLocale([sources.saved], config.locales) ?? matchLocale(sources.preferred ?? [], config.locales) ?? config.defaultLocale;
48
+ }
49
+ var RTL_LANGUAGES = /* @__PURE__ */ new Set([
50
+ "ar",
51
+ "he",
52
+ "fa",
53
+ "ur",
54
+ "ps",
55
+ "sd",
56
+ "ug",
57
+ "yi",
58
+ "dv",
59
+ "ckb"
60
+ ]);
61
+ var textDirection = (locale) => RTL_LANGUAGES.has(baseLanguage(locale)) ? "rtl" : "ltr";
62
+ function lookupMessage(messages, key) {
63
+ let current = messages;
64
+ for (const part of key.split(".")) {
65
+ if (typeof current !== "object" || !Object.hasOwn(current, part))
66
+ return void 0;
67
+ current = current[part];
68
+ }
69
+ return typeof current === "string" ? current : void 0;
70
+ }
71
+ function selectPlural(message, count) {
72
+ if (typeof count !== "number" || !message.includes("|")) return message;
73
+ const forms = message.split("|").map((form) => form.trim());
74
+ if (forms.length === 2) return forms[count === 1 ? 0 : 1];
75
+ const index = count === 0 ? 0 : count === 1 ? 1 : 2;
76
+ return forms[Math.min(index, forms.length - 1)];
77
+ }
78
+ function formatMessage(message, params = {}) {
79
+ return selectPlural(message, params.count).replace(
80
+ /\{\s*(\w+)\s*\}/g,
81
+ (placeholder, name) => Object.hasOwn(params, name) ? String(params[name]) : placeholder
82
+ );
83
+ }
84
+ function translate(catalog, locale, defaultLocale, key, params) {
85
+ const message = lookupMessage(catalog[locale], key) ?? lookupMessage(catalog[defaultLocale], key);
86
+ return message === void 0 ? key : formatMessage(message, params);
87
+ }
88
+
89
+ export {
90
+ LOCALE_COOKIE,
91
+ resolveI18n,
92
+ matchLocale,
93
+ parseAcceptLanguage,
94
+ pickLocale,
95
+ textDirection,
96
+ translate
97
+ };