@rivil-solutions/site-kit 0.0.0-stage → 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 (76) hide show
  1. package/README.md +97 -2
  2. package/bin/rivil.mjs +118 -0
  3. package/blocks/booking/block.json +7 -0
  4. package/blocks/booking/files/src/components/rivil/BookingForm.tsx +187 -0
  5. package/blocks/booking/files/src/pages/programare.astro +18 -0
  6. package/blocks/careers/block.json +7 -0
  7. package/blocks/careers/files/src/components/rivil/ApplyForm.tsx +62 -0
  8. package/blocks/careers/files/src/pages/cariere/[job].astro +49 -0
  9. package/blocks/careers/files/src/pages/cariere/index.astro +32 -0
  10. package/blocks/events/block.json +7 -0
  11. package/blocks/events/files/src/components/rivil/EventCheckout.tsx +93 -0
  12. package/blocks/events/files/src/pages/evenimente/[code].astro +35 -0
  13. package/blocks/events/files/src/pages/evenimente/comanda.astro +36 -0
  14. package/blocks/events/files/src/pages/evenimente/index.astro +30 -0
  15. package/blocks/newsletter/block.json +4 -0
  16. package/blocks/newsletter/files/src/components/rivil/Newsletter.astro +35 -0
  17. package/blocks/reviews/block.json +7 -0
  18. package/blocks/reviews/files/src/components/rivil/ReviewForm.tsx +73 -0
  19. package/blocks/reviews/files/src/pages/recenzii.astro +39 -0
  20. package/blocks/stay/block.json +7 -0
  21. package/blocks/stay/files/src/components/rivil/StayBooking.tsx +121 -0
  22. package/blocks/stay/files/src/pages/rezervare.astro +11 -0
  23. package/blocks/ui/block.json +1 -0
  24. package/blocks/ui/files/src/components/rivil/ui.tsx +99 -0
  25. package/blocks/ui/files/src/styles/rivil-blocks.css +47 -0
  26. package/dist/account.d.ts +84 -0
  27. package/dist/account.js +104 -0
  28. package/dist/astro-image.d.ts +29 -0
  29. package/dist/astro-image.js +12 -0
  30. package/dist/client.d.ts +58 -0
  31. package/dist/client.js +153 -0
  32. package/dist/consent.d.ts +6 -0
  33. package/dist/consent.js +10 -0
  34. package/dist/content.d.ts +93 -0
  35. package/dist/content.js +85 -0
  36. package/dist/i18n.d.ts +30 -0
  37. package/dist/i18n.js +69 -0
  38. package/dist/images.d.ts +13 -0
  39. package/dist/images.js +26 -0
  40. package/dist/index.d.ts +13 -0
  41. package/dist/index.js +13 -0
  42. package/dist/modules.d.ts +288 -0
  43. package/dist/modules.js +49 -0
  44. package/dist/proxy.d.ts +47 -0
  45. package/dist/proxy.js +82 -0
  46. package/dist/react/index.d.ts +6 -0
  47. package/dist/react/index.js +6 -0
  48. package/dist/react/texts.d.ts +17 -0
  49. package/dist/react/texts.js +28 -0
  50. package/dist/react/useApplication.d.ts +67 -0
  51. package/dist/react/useApplication.js +94 -0
  52. package/dist/react/useBooking.d.ts +81 -0
  53. package/dist/react/useBooking.js +151 -0
  54. package/dist/react/useEventCheckout.d.ts +48 -0
  55. package/dist/react/useEventCheckout.js +104 -0
  56. package/dist/react/useReview.d.ts +58 -0
  57. package/dist/react/useReview.js +69 -0
  58. package/dist/react/useStay.d.ts +82 -0
  59. package/dist/react/useStay.js +105 -0
  60. package/dist/seo.d.ts +27 -0
  61. package/dist/seo.js +36 -0
  62. package/dist/shop.d.ts +111 -0
  63. package/dist/shop.js +167 -0
  64. package/dist/visitor.d.ts +7 -0
  65. package/dist/visitor.js +17 -0
  66. package/dist/web.d.ts +83 -0
  67. package/dist/web.js +131 -0
  68. package/dist/webhook.d.ts +20 -0
  69. package/dist/webhook.js +39 -0
  70. package/package.json +62 -4
  71. package/themes/aer.css +12 -0
  72. package/themes/cabana.css +12 -0
  73. package/themes/curte.css +12 -0
  74. package/themes/lumen.css +12 -0
  75. package/themes/miez.css +12 -0
  76. package/themes/solvar.css +12 -0
@@ -0,0 +1,47 @@
1
+ /* Formularele modulelor (programări, cazare, cariere, recenzii, evenimente). Culorile vin din variabilele din global.css și theme.css. */
2
+ .rv { display: grid; gap: 20px; }
3
+ .rv-card { border: 1px solid var(--line); border-radius: var(--radius); padding: 22px; background: var(--bg); display: grid; gap: 16px; }
4
+ .rv-card h3 { margin: 0; }
5
+ .rv-grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); }
6
+ .rv-field { display: grid; gap: 6px; }
7
+ .rv-field.rv-wide { grid-column: 1 / -1; }
8
+ .rv-field > label { font-weight: 600; font-size: 0.95rem; }
9
+ .rv input:not([type='checkbox']):not([type='radio']), .rv textarea, .rv select { font: inherit; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--bg); color: var(--fg); width: 100%; }
10
+ .rv textarea { min-height: 110px; }
11
+ .rv-help { color: var(--muted); }
12
+ .rv-check { display: flex; gap: 10px; align-items: flex-start; font-size: 0.95rem; }
13
+ .rv-check input { margin-top: 4px; }
14
+ .rv-msg { margin: 0; font-size: 0.95rem; }
15
+ .rv-error { color: #b91c1c; }
16
+ .rv-ok { color: #15803d; }
17
+ .rv-done { border: 1px solid var(--line); border-radius: var(--radius); padding: 28px; text-align: center; }
18
+ .rv-done h3 { margin: 0 0 8px; }
19
+ .rv-trap { position: absolute; left: -9999px; width: 1px; height: 1px; opacity: 0; }
20
+ .rv-pills { display: flex; flex-wrap: wrap; gap: 8px; }
21
+ .rv-pills button, .rv-option, .rv-time { font: inherit; cursor: pointer; border: 1px solid var(--line); border-radius: var(--radius); background: var(--bg); color: var(--fg); padding: 8px 14px; }
22
+ .rv-pills button[aria-pressed='true'], .rv-option[aria-pressed='true'], .rv-time[aria-pressed='true'] { border-color: var(--accent); background: var(--accent); color: var(--accent-fg); }
23
+ .rv-option { display: flex; width: 100%; justify-content: space-between; gap: 12px; text-align: left; padding: 12px 16px; }
24
+ .rv-option small { color: inherit; opacity: 0.75; display: block; }
25
+ .rv-options { display: grid; gap: 8px; }
26
+ .rv-steps { display: flex; gap: 8px; list-style: none; margin: 0; padding: 0; flex-wrap: wrap; font-size: 0.9rem; color: var(--muted); }
27
+ .rv-steps li[aria-current='step'] { color: var(--fg); font-weight: 700; }
28
+ .rv-days, .rv-times { display: grid; gap: 8px; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); }
29
+ .rv-actions { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
30
+ .rv-summary { display: grid; gap: 6px; font-size: 0.95rem; }
31
+ .rv-summary .rv-total { font-weight: 700; border-top: 1px solid var(--line); padding-top: 8px; }
32
+ .rv-rooms { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
33
+ .rv-room { border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; display: flex; flex-direction: column; }
34
+ .rv-room img { aspect-ratio: 16 / 9; object-fit: cover; width: 100%; }
35
+ .rv-room > div { padding: 16px; display: grid; gap: 8px; flex: 1; }
36
+ .rv-tickets { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
37
+ .rv-tickets li { display: grid; grid-template-columns: 1fr auto auto; gap: 12px; align-items: center; border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 16px; }
38
+ .rv-qty { display: inline-flex; align-items: center; gap: 10px; }
39
+ .rv-qty button { width: 34px; height: 34px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--bg); color: var(--fg); cursor: pointer; font: inherit; }
40
+ .rv-muted { color: var(--muted); }
41
+ .rv-spin { display: inline-block; width: 14px; height: 14px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; margin-right: 8px; vertical-align: -2px; animation: rv-spin 0.8s linear infinite; }
42
+ @keyframes rv-spin { to { transform: rotate(360deg); } }
43
+ .rv-stars { color: #d97706; letter-spacing: 2px; }
44
+ .rv-reviews { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); }
45
+ .rv-review { border: 1px solid var(--line); border-radius: var(--radius); padding: 18px; display: grid; gap: 8px; }
46
+ .rv-review blockquote { margin: 0; }
47
+ .rv-reply { border-left: 3px solid var(--line); padding-left: 12px; color: var(--muted); font-size: 0.95rem; }
@@ -0,0 +1,84 @@
1
+ import type { RequestOptions, SiteClient } from './client.js';
2
+ /**
3
+ * Cerere spre API-ul de cont (`/api/site/v1/account/<path>`), cu cheia portalului (clientul) și sesiunea clientului logat.
4
+ * Răspunsul vine așa cum l-a dat ERP-ul.
5
+ */
6
+ export declare function accountRequest(client: SiteClient, path: string, r?: RequestOptions & {
7
+ session?: string | null;
8
+ }): Promise<Response>;
9
+ /** GET pentru paginile randate pe server: `null` dacă sesiunea nu mai e validă sau ERP-ul nu răspunde. */
10
+ export declare function accountGet<T = unknown>(client: SiteClient, path: string, session: string, query?: string): Promise<T | null>;
11
+ /** Ce are nevoie proxy-ul din cookie-urile cererii; `AstroCookies` se potrivește. */
12
+ export type CookieJar = {
13
+ get(name: string): {
14
+ value: string;
15
+ } | undefined;
16
+ set(name: string, value: string, options: {
17
+ httpOnly: boolean;
18
+ sameSite: 'lax';
19
+ secure: boolean;
20
+ path: string;
21
+ maxAge: number;
22
+ }): void;
23
+ delete(name: string, options: {
24
+ path: string;
25
+ }): void;
26
+ };
27
+ export type AccountRoute = {
28
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
29
+ /** Calea din adresa site-ului (după `/api/<marcă>/account/`), de exemplu `/^me$/`. */
30
+ path: RegExp;
31
+ /** Calea din ERP, dacă diferă (`invite` -> `invite/accept`). */
32
+ erp?: string;
33
+ /** Cere client logat. */
34
+ session?: boolean;
35
+ /** Deschide o sesiune (login, invitație): tokenul primit merge în cookie, nu în browser. */
36
+ opens?: boolean;
37
+ /** Închide sesiunea. */
38
+ closes?: boolean;
39
+ /** Modifică datele clientului: trece prin `guard` (de exemplu contul demo, care rămâne cum e). */
40
+ changes?: boolean;
41
+ /** Corpul cererii: JSON (implicit pentru POST, PUT, PATCH) sau fișiere (`multipart`). */
42
+ body?: 'json' | 'multipart' | 'none';
43
+ /** Parametrii din adresă trec spre ERP: toți (`true`) sau doar cei aleși de funcție. */
44
+ query?: true | ((url: URL) => string);
45
+ /** Răspunsul e un fișier (PDF, diplomă): trece ca atare, fără să fie citit ca JSON. */
46
+ file?: boolean;
47
+ };
48
+ /** Intrarea, invitația, ieșirea și parola: aceleași pe orice portal. */
49
+ export declare const AUTH_ROUTES: AccountRoute[];
50
+ export type AccountProxyOptions = {
51
+ /** Clientul creat cu cheia portalului. */
52
+ client: SiteClient;
53
+ /** Cookie-ul httpOnly cu sesiunea; fiecare portal are al lui, ca o sesiune să nu fie valabilă pe altul. */
54
+ cookie: string;
55
+ routes: AccountRoute[];
56
+ /** Adresele de pe care pot veni scrierile, pe lângă adresa cererii. Pune adresa publică a site-ului: în spatele unui proxy, Astro vede cererea pe `localhost`. */
57
+ origins?: string[];
58
+ /**
59
+ * Se cheamă la fiecare cerere, înainte să plece spre ERP; un `Response` întors se dă vizitatorului, `null` lasă cererea să treacă.
60
+ * De exemplu contul demo, la rutele cu `changes`.
61
+ */
62
+ guard?: (c: {
63
+ route: AccountRoute;
64
+ path: string;
65
+ session: string | null;
66
+ request: Request;
67
+ }) => Promise<Response | null> | Response | null;
68
+ /** Limita pentru fișiere încărcate (implicit 25 MB). */
69
+ maxUploadBytes?: number;
70
+ /** Cât ține sesiunea în cookie (implicit 30 de zile). */
71
+ sessionMaxAgeSec?: number;
72
+ };
73
+ export type ProxyContext = {
74
+ request: Request;
75
+ path: string;
76
+ cookies: CookieJar;
77
+ clientAddress?: string;
78
+ };
79
+ /**
80
+ * Proxy-ul contului de client: browserul vorbește doar cu site-ul, iar site-ul cheamă ERP-ul cu cheia portalului. Doar rutele din listă trec.
81
+ * Tokenul de sesiune stă într-un cookie httpOnly; scrierile vin doar de pe adresele site-ului.
82
+ * În Astro: `const proxy = accountProxy({...}); export const ALL = (c) => proxy({ request: c.request, path: c.params.path, cookies: c.cookies, clientAddress: c.clientAddress })`.
83
+ */
84
+ export declare function accountProxy(o: AccountProxyOptions): (c: ProxyContext) => Promise<Response>;
@@ -0,0 +1,104 @@
1
+ import { visitorIp } from './visitor.js';
2
+ const SESSION = 'X-Account-Session';
3
+ /**
4
+ * Cerere spre API-ul de cont (`/api/site/v1/account/<path>`), cu cheia portalului (clientul) și sesiunea clientului logat.
5
+ * Răspunsul vine așa cum l-a dat ERP-ul.
6
+ */
7
+ export function accountRequest(client, path, r = {}) {
8
+ const { session, ...rest } = r;
9
+ return client.request(`/account/${path.replace(/^\/+/, '')}`, { ...rest, headers: { ...rest.headers, ...(session ? { [SESSION]: session } : {}) } });
10
+ }
11
+ /** GET pentru paginile randate pe server: `null` dacă sesiunea nu mai e validă sau ERP-ul nu răspunde. */
12
+ export async function accountGet(client, path, session, query = '') {
13
+ const res = await accountRequest(client, `${path}${query}`, { session }).catch(() => null);
14
+ if (!res?.ok)
15
+ return null;
16
+ return (await res.json());
17
+ }
18
+ /** Intrarea, invitația, ieșirea și parola: aceleași pe orice portal. */
19
+ export const AUTH_ROUTES = [
20
+ { method: 'POST', path: /^login$/, erp: 'login', opens: true },
21
+ { method: 'POST', path: /^invite$/, erp: 'invite/accept', opens: true },
22
+ { method: 'POST', path: /^logout$/, erp: 'logout', session: true, closes: true, body: 'none' },
23
+ { method: 'POST', path: /^password\/reset$/, erp: 'password/reset' },
24
+ { method: 'POST', path: /^password\/confirm$/, erp: 'password/confirm' },
25
+ ];
26
+ const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } });
27
+ const fail = (status, code, message) => json({ error: { code, message } }, status);
28
+ /**
29
+ * Proxy-ul contului de client: browserul vorbește doar cu site-ul, iar site-ul cheamă ERP-ul cu cheia portalului. Doar rutele din listă trec.
30
+ * Tokenul de sesiune stă într-un cookie httpOnly; scrierile vin doar de pe adresele site-ului.
31
+ * În Astro: `const proxy = accountProxy({...}); export const ALL = (c) => proxy({ request: c.request, path: c.params.path, cookies: c.cookies, clientAddress: c.clientAddress })`.
32
+ */
33
+ export function accountProxy(o) {
34
+ const maxUpload = o.maxUploadBytes ?? 25 * 1024 * 1024;
35
+ const maxAge = o.sessionMaxAgeSec ?? 60 * 60 * 24 * 30;
36
+ return async (c) => {
37
+ const { request, cookies } = c;
38
+ const url = new URL(request.url);
39
+ const path = String(c.path ?? '').replace(/^\/+|\/+$/g, '');
40
+ const route = o.routes.find((r) => r.method === request.method && r.path.test(path));
41
+ if (!route)
42
+ return fail(404, 'not_found', 'Not found');
43
+ const origin = request.headers.get('origin');
44
+ const allowed = new Set([url.origin, ...(o.origins ?? []).map((x) => new URL(x).origin)]);
45
+ if (origin && !allowed.has(origin))
46
+ return fail(403, 'forbidden', 'Forbidden');
47
+ const kind = route.body ?? (['POST', 'PUT', 'PATCH'].includes(route.method) ? 'json' : 'none');
48
+ const type = request.headers.get('content-type') ?? '';
49
+ // multipart se poate trimite și dintr-un formular străin, de aceea acolo originea e obligatorie
50
+ if (kind === 'multipart') {
51
+ if (!origin || !type.startsWith('multipart/form-data'))
52
+ return fail(415, 'invalid_body', 'multipart/form-data');
53
+ if (!(Number(request.headers.get('content-length')) <= maxUpload))
54
+ return fail(413, 'too_large', 'Too large');
55
+ }
56
+ if (kind === 'json' && !type.includes('application/json'))
57
+ return fail(415, 'invalid_json', 'JSON');
58
+ const session = cookies.get(o.cookie)?.value ?? null;
59
+ if (route.session && !session)
60
+ return fail(401, 'invalid_session', 'Sesiune lipsă.');
61
+ const blocked = o.guard ? await o.guard({ route, path, session, request }) : null;
62
+ if (blocked)
63
+ return blocked;
64
+ let body;
65
+ let jsonBody;
66
+ if (kind === 'json') {
67
+ jsonBody = await request.json().catch(() => undefined);
68
+ if (jsonBody === undefined)
69
+ return fail(400, 'invalid_json', 'JSON');
70
+ }
71
+ else if (kind === 'multipart')
72
+ body = await request.arrayBuffer();
73
+ const query = route.query === true ? url.search : route.query ? route.query(url) : '';
74
+ const res = await accountRequest(o.client, `${route.erp ?? path}${query}`, {
75
+ method: route.method,
76
+ session,
77
+ json: jsonBody,
78
+ body,
79
+ headers: kind === 'multipart' ? { 'content-type': type } : undefined,
80
+ visitorIp: visitorIp(request, () => c.clientAddress ?? ''),
81
+ timeoutMs: kind === 'multipart' ? 60_000 : undefined,
82
+ }).catch(() => null);
83
+ if (!res)
84
+ return fail(502, 'unavailable', 'Serviciul nu răspunde.');
85
+ if (route.closes) {
86
+ cookies.delete(o.cookie, { path: '/' });
87
+ return new Response(null, { status: 204 });
88
+ }
89
+ if (res.status === 401 && route.session)
90
+ cookies.delete(o.cookie, { path: '/' });
91
+ if (route.file && res.ok) {
92
+ return new Response(res.body, {
93
+ headers: { 'content-type': res.headers.get('content-type') ?? 'application/octet-stream', 'content-disposition': res.headers.get('content-disposition') ?? 'attachment', 'cache-control': 'private, no-store' },
94
+ });
95
+ }
96
+ const text = await res.text();
97
+ if (route.opens && res.ok) {
98
+ const out = JSON.parse(text);
99
+ cookies.set(o.cookie, out.session_token, { httpOnly: true, sameSite: 'lax', secure: url.protocol === 'https:', path: '/', maxAge });
100
+ return json({ account: out.account });
101
+ }
102
+ return new Response(text || null, { status: res.status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } });
103
+ };
104
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Serviciul de imagini pentru `<Image>` din Astro: lățimile vin direct de la sursa pozei, fără prelucrare pe serverul site-ului.
3
+ * În `astro.config.mjs`: `image: { service: { entrypoint: '@rivil-solutions/site-kit/astro-image' } }`.
4
+ * Tipurile sunt scrise aici, ca pachetul să nu depindă de o versiune anume de Astro.
5
+ */
6
+ type Transform = {
7
+ src: string | {
8
+ src: string;
9
+ };
10
+ width?: number;
11
+ widths?: number[];
12
+ [k: string]: unknown;
13
+ };
14
+ declare const service: {
15
+ getURL: (o: Transform) => string;
16
+ getSrcSet: (o: Transform) => {
17
+ transform: {
18
+ width: number;
19
+ src: string | {
20
+ src: string;
21
+ };
22
+ widths?: number[];
23
+ };
24
+ descriptor: string;
25
+ attributes: {};
26
+ }[];
27
+ getHTMLAttributes: (o: Transform) => Record<string, string>;
28
+ };
29
+ export default service;
@@ -0,0 +1,12 @@
1
+ import { imageAt, imageWidths } from './images.js';
2
+ const srcOf = (o) => (typeof o.src === 'string' ? o.src : o.src.src);
3
+ const service = {
4
+ getURL: (o) => imageAt(srcOf(o), o.width ?? 800),
5
+ getSrcSet: (o) => imageWidths(srcOf(o), o.widths).map((w) => ({ transform: { ...o, width: w }, descriptor: `${w}w`, attributes: {} })),
6
+ // tot ce nu ține de transformare ajunge pe <img> (alt, width, height, class, loading, data-*)
7
+ getHTMLAttributes: (o) => {
8
+ const { src: _src, widths: _w, densities: _d, format: _f, quality: _q, fit: _fit, position: _p, background: _b, ...attrs } = o;
9
+ return attrs;
10
+ },
11
+ };
12
+ export default service;
@@ -0,0 +1,58 @@
1
+ export type SiteClientOptions = {
2
+ /** Adresa ERP-ului, de exemplu `https://erp.rivil.app`. */
3
+ url: string;
4
+ /** Cheia de site (`rvl_<companie>_...`). Doar pe server: nu ajunge niciodată în browser. */
5
+ key: string;
6
+ /** Cât timp un răspuns e proaspăt (implicit 60 s). */
7
+ ttlMs?: number;
8
+ /** Cât timp se mai servește un răspuns vechi, cât se reîmprospătează în fundal (implicit o zi; webhook-ul golește mai devreme). */
9
+ staleMs?: number;
10
+ /** Timpul maxim al unei cereri (implicit 10 s). */
11
+ timeoutMs?: number;
12
+ /**
13
+ * Adresa vizitatorului cererii curente, când nu e dată la fiecare apel (de obicei dintr-un `AsyncLocalStorage` pus de middleware).
14
+ * Fără ea, ERP-ul ar vedea toți vizitatorii ca serverul site-ului, iar limitele s-ar aplica pe tot site-ul.
15
+ */
16
+ visitorIp?: () => string | undefined;
17
+ /** Pentru teste. */
18
+ fetch?: typeof fetch;
19
+ };
20
+ export type RequestOptions = {
21
+ method?: string;
22
+ /** Trimis ca JSON. */
23
+ json?: unknown;
24
+ /** Corp brut (de exemplu `FormData` sau un proxy de formular). */
25
+ body?: BodyInit | null;
26
+ /** Adresa vizitatorului: limitele din ERP se aplică pe el, nu pe tot site-ul. */
27
+ visitorIp?: string;
28
+ headers?: Record<string, string>;
29
+ timeoutMs?: number;
30
+ };
31
+ /** Eroarea de la ERP: `code` e stabil (bun pentru decizii), `message` e pentru om, în limba companiei. */
32
+ export declare class RivilApiError extends Error {
33
+ readonly status: number;
34
+ readonly code: string;
35
+ readonly details?: unknown | undefined;
36
+ constructor(message: string, status: number, code: string, details?: unknown | undefined);
37
+ }
38
+ /** Mesajele pe câmp dintr-o eroare de validare (422): `{ 'shipping_address.city': '...' }`. */
39
+ export declare function fieldErrors(e: unknown): Record<string, string>;
40
+ /** Citește eroarea din răspuns: `{ error: { code, message, details } }` sau, la rutele vechi, `{ error: '...' }`. */
41
+ export declare function apiError(res: Response): Promise<RivilApiError>;
42
+ export type SiteClient = ReturnType<typeof createSiteClient>;
43
+ /**
44
+ * Clientul API-ului de site (`/api/site/v1`). Citirile (`get`) stau în memorie: proaspete sub `ttlMs`, apoi se servește valoarea veche
45
+ * și se reîmprospătează în fundal; cererile identice care vin deodată se unesc într-una. `purge()` (din webhook-ul `content.*` sau
46
+ * `shop.changed`) cere din nou tot ce e în memorie, iar până sosește răspunsul se servește valoarea veche.
47
+ */
48
+ export declare function createSiteClient(o: SiteClientOptions): {
49
+ origin: string;
50
+ base: string;
51
+ request: (path: string, r?: RequestOptions) => Promise<Response>;
52
+ call: <T = unknown>(path: string, r?: RequestOptions) => Promise<T>;
53
+ get: <T = unknown>(path: string) => Promise<T | null>;
54
+ purge: (match?: (path: string, value: unknown) => boolean) => void;
55
+ forget: (match: (path: string) => boolean) => void;
56
+ clear: () => void;
57
+ imageUrl: (id: string | null | undefined, size?: "thumb") => string;
58
+ };
package/dist/client.js ADDED
@@ -0,0 +1,153 @@
1
+ import { VISITOR_HEADER } from './visitor.js';
2
+ /** Eroarea de la ERP: `code` e stabil (bun pentru decizii), `message` e pentru om, în limba companiei. */
3
+ export class RivilApiError extends Error {
4
+ status;
5
+ code;
6
+ details;
7
+ constructor(message, status, code, details) {
8
+ super(message);
9
+ this.status = status;
10
+ this.code = code;
11
+ this.details = details;
12
+ this.name = 'RivilApiError';
13
+ }
14
+ }
15
+ /** Mesajele pe câmp dintr-o eroare de validare (422): `{ 'shipping_address.city': '...' }`. */
16
+ export function fieldErrors(e) {
17
+ const fields = e instanceof RivilApiError ? e.details?.fields : undefined;
18
+ return Object.fromEntries((fields ?? []).map((f) => [f.field, f.message]));
19
+ }
20
+ /** Citește eroarea din răspuns: `{ error: { code, message, details } }` sau, la rutele vechi, `{ error: '...' }`. */
21
+ export async function apiError(res) {
22
+ const data = (await res.json().catch(() => null));
23
+ const e = data?.error;
24
+ if (e && typeof e === 'object') {
25
+ const o = e;
26
+ return new RivilApiError(String(o.message ?? `HTTP ${res.status}`), res.status, String(o.code ?? 'error'), o.details);
27
+ }
28
+ return new RivilApiError(typeof e === 'string' ? e : `HTTP ${res.status}`, res.status, 'error');
29
+ }
30
+ /**
31
+ * Clientul API-ului de site (`/api/site/v1`). Citirile (`get`) stau în memorie: proaspete sub `ttlMs`, apoi se servește valoarea veche
32
+ * și se reîmprospătează în fundal; cererile identice care vin deodată se unesc într-una. `purge()` (din webhook-ul `content.*` sau
33
+ * `shop.changed`) cere din nou tot ce e în memorie, iar până sosește răspunsul se servește valoarea veche.
34
+ */
35
+ export function createSiteClient(o) {
36
+ const origin = o.url.replace(/\/+$/, '');
37
+ const base = `${origin}/api/site/v1`;
38
+ const ttl = o.ttlMs ?? 60_000;
39
+ const stale = o.staleMs ?? 24 * 3_600_000;
40
+ const timeout = o.timeoutMs ?? 10_000;
41
+ const doFetch = o.fetch ?? fetch;
42
+ const memo = new Map();
43
+ const flight = new Map();
44
+ // reîmprospătările din fundal merg cel mult două odată, ca un webhook să nu trimită o rafală spre ERP
45
+ let active = 0;
46
+ const waiting = [];
47
+ async function slot(fn) {
48
+ if (active >= 2)
49
+ await new Promise((r) => waiting.push(r));
50
+ active++;
51
+ try {
52
+ return await fn();
53
+ }
54
+ finally {
55
+ active--;
56
+ waiting.shift()?.();
57
+ }
58
+ }
59
+ function headersFor(r) {
60
+ const h = new Headers(r.headers);
61
+ h.set('accept', 'application/json');
62
+ h.set('authorization', `Bearer ${o.key}`);
63
+ if (r.json !== undefined)
64
+ h.set('content-type', 'application/json');
65
+ const ip = r.visitorIp ?? o.visitorIp?.();
66
+ if (ip)
67
+ h.set(VISITOR_HEADER, ip);
68
+ return h;
69
+ }
70
+ /** Cererea brută, fără memorie; răspunsul vine așa cum l-a dat ERP-ul (bun pentru proxy-uri). */
71
+ function request(path, r = {}) {
72
+ return doFetch(`${base}${path}`, {
73
+ method: r.method ?? (r.json !== undefined || r.body ? 'POST' : 'GET'),
74
+ headers: headersFor(r),
75
+ body: r.json !== undefined ? JSON.stringify(r.json) : (r.body ?? undefined),
76
+ redirect: 'error',
77
+ signal: AbortSignal.timeout(r.timeoutMs ?? timeout),
78
+ });
79
+ }
80
+ /** JSON fără memorie; aruncă `RivilApiError` dacă ERP-ul refuză. Un 204 dă `null`. */
81
+ async function call(path, r = {}) {
82
+ const res = await request(path, r);
83
+ if (!res.ok)
84
+ throw await apiError(res);
85
+ if (res.status === 204)
86
+ return null;
87
+ return (await res.json());
88
+ }
89
+ /** O citire, fără memorie. `null` la 404, ca o pagină să poată răspunde „nu există”. */
90
+ async function fetchOnce(path) {
91
+ const res = await request(path);
92
+ if (res.status === 404)
93
+ return null;
94
+ if (!res.ok)
95
+ throw await apiError(res);
96
+ return res.json();
97
+ }
98
+ function refresh(path, background = false) {
99
+ let p = flight.get(path);
100
+ if (!p) {
101
+ p = (background ? slot(() => fetchOnce(path)) : fetchOnce(path))
102
+ // 404: înregistrarea a fost ștearsă, deci nici valoarea veche nu mai e bună
103
+ .then((v) => (v === null ? memo.delete(path) : memo.set(path, { at: Date.now(), v }), v))
104
+ .finally(() => flight.delete(path));
105
+ flight.set(path, p);
106
+ }
107
+ return p;
108
+ }
109
+ /** Citire cu memorie. `null` la 404. */
110
+ async function get(path) {
111
+ const hit = memo.get(path);
112
+ const age = hit ? Date.now() - hit.at : Infinity;
113
+ if (hit && age < ttl)
114
+ return hit.v;
115
+ // după `purge` (`at = 0`) valoarea veche rămâne bună până vine cea nouă
116
+ if (hit && (age < stale || hit.at === 0)) {
117
+ refresh(path, true).catch(() => undefined);
118
+ return hit.v;
119
+ }
120
+ return (await refresh(path));
121
+ }
122
+ /**
123
+ * Reîmprospătează în fundal tot ce e în memorie (sau doar intrările pentru care `match` spune da; primește calea și valoarea ținută).
124
+ * Vizitatorii primesc valoarea veche până sosește cea nouă, deci primul vizitator de după o schimbare nu mai așteaptă ERP-ul.
125
+ */
126
+ function purge(match) {
127
+ for (const [path, e] of memo) {
128
+ if (match && !match(path, e.v))
129
+ continue;
130
+ e.at = 0;
131
+ refresh(path, true).catch(() => undefined);
132
+ }
133
+ }
134
+ /** Scoate din memorie intrările alese (fără să le ceară din nou), de exemplu după ce vizitatorul a scris o recenzie. */
135
+ function forget(match) {
136
+ for (const path of [...memo.keys()])
137
+ if (match(path))
138
+ memo.delete(path);
139
+ }
140
+ /** Golește memoria de tot (pentru teste sau o schimbare de cheie). */
141
+ function clear() {
142
+ memo.clear();
143
+ }
144
+ /** Compania din cheie: `rvl_<companie>_...`. */
145
+ const tenant = o.key.split('_')[1] ?? '';
146
+ /** Adresa unui fișier din Galerie, după id. `thumb` e miniatura (latura mică 480 px). */
147
+ function imageUrl(id, size) {
148
+ if (!id)
149
+ return '';
150
+ return `${origin}/api/img/${tenant}/${id}${size ? `?size=${size}` : ''}`;
151
+ }
152
+ return { origin, base, request, call, get, purge, forget, clear, imageUrl };
153
+ }
@@ -0,0 +1,6 @@
1
+ export declare const CONSENT_ORIGIN = "https://consent.rivil.app";
2
+ /**
3
+ * Scriptul bannerului Rivil Consent, de pus primul în `<head>`: `<script src={consentScriptUrl(...)} defer>`.
4
+ * Cheia de site Consent e publică (apare în HTML). Fără cheie, adresa e goală și bannerul nu se pune.
5
+ */
6
+ export declare function consentScriptUrl(key: string | null | undefined, origin?: string): string;
@@ -0,0 +1,10 @@
1
+ export const CONSENT_ORIGIN = 'https://consent.rivil.app';
2
+ /**
3
+ * Scriptul bannerului Rivil Consent, de pus primul în `<head>`: `<script src={consentScriptUrl(...)} defer>`.
4
+ * Cheia de site Consent e publică (apare în HTML). Fără cheie, adresa e goală și bannerul nu se pune.
5
+ */
6
+ export function consentScriptUrl(key, origin = CONSENT_ORIGIN) {
7
+ if (!key)
8
+ return '';
9
+ return `${origin.replace(/\/+$/, '')}/s/${encodeURIComponent(key)}.js`;
10
+ }
@@ -0,0 +1,93 @@
1
+ import type { RequestOptions, SiteClient } from './client.js';
2
+ import { type Redirect } from './seo.js';
3
+ export type Img = {
4
+ id: string;
5
+ url: string;
6
+ width: number | null;
7
+ height: number | null;
8
+ alt: string | null;
9
+ };
10
+ export type Term = {
11
+ slug: string;
12
+ name: string;
13
+ };
14
+ export type Entry = {
15
+ id: string;
16
+ slug: string;
17
+ path: string | null;
18
+ title: string;
19
+ excerpt: string | null;
20
+ body?: string;
21
+ featured_image: Img | null;
22
+ terms: Record<string, Term[]>;
23
+ seo?: {
24
+ title: string | null;
25
+ description: string | null;
26
+ noindex: boolean;
27
+ } | null;
28
+ fields: Record<string, unknown>;
29
+ published_at?: string;
30
+ locale: string;
31
+ /** Aceeași intrare în alte limbi: limbă -> slug. */
32
+ locales?: Record<string, string>;
33
+ };
34
+ export type MenuItem = {
35
+ label: string;
36
+ url: string;
37
+ new_tab: boolean;
38
+ children?: MenuItem[];
39
+ };
40
+ export type ContentType = {
41
+ key: string;
42
+ label: string;
43
+ label_plural: string;
44
+ singleton: boolean;
45
+ /** Adresa publică a intrărilor, de exemplu `/blog/{slug}`; `null` când tipul nu are pagini proprii. */
46
+ url_pattern: string | null;
47
+ supports: string[];
48
+ taxonomies: string[];
49
+ fields: Array<Record<string, unknown>>;
50
+ };
51
+ export type SitemapItem = {
52
+ path: string;
53
+ updated_at: string;
54
+ locales: Record<string, string>;
55
+ };
56
+ /** Adresa unei intrări după tiparul tipului: `/blog/{slug}` + `salut` dă `/blog/salut`. */
57
+ export declare const entryPath: (pattern: string, slug: string) => string;
58
+ /** Slug-ul din adresă, dacă adresa se potrivește cu tiparul (`/blog/{slug}` și `/blog/salut` dau `salut`); altfel `null`. */
59
+ export declare function matchPattern(pattern: string, path: string): string | null;
60
+ /** Tipul și slug-ul pentru o adresă. Tiparele mai lungi (mai precise) au prioritate față de `/{slug}`. */
61
+ export declare function resolvePath(types: ContentType[], path: string): {
62
+ type: ContentType;
63
+ slug: string;
64
+ } | null;
65
+ /** Modulul Site (`/api/site/v1`): setări, meniuri, redirecturi, termeni, intrări, formulare. Citirile trec prin memoria clientului. */
66
+ export declare function createContentApi(client: SiteClient): {
67
+ /** Tipurile de conținut ale site-ului, cu tiparul de adresă și câmpurile. */
68
+ types(): Promise<ContentType[]>;
69
+ /** Toate adresele publice indexabile, cu variantele pe limbi. */
70
+ sitemap(): Promise<{
71
+ domain: string | null;
72
+ items: SitemapItem[];
73
+ }>;
74
+ settings(locale?: string): Promise<Record<string, Record<string, unknown>>>;
75
+ /** Meniurile site-ului, după cheie (`header`, `footer`...). */
76
+ menus(locale?: string): Promise<Record<string, MenuItem[]>>;
77
+ redirects(): Promise<Map<string, Redirect>>;
78
+ terms(taxonomy: string, locale?: string): Promise<Term[]>;
79
+ /** Intrările unui tip (`page`, `post`...). `params`: `per_page`, `page`, filtre pe câmpuri, `sort`. */
80
+ list(type: string, locale?: string, params?: Record<string, string | number | undefined>): Promise<{
81
+ items: Entry[];
82
+ total: number;
83
+ }>;
84
+ /** O intrare după slug; `null` dacă nu există sau nu e publicată. */
85
+ one(type: string, slug: string, locale?: string): Promise<Entry | null>;
86
+ /** Căutare în conținutul public. */
87
+ search(text: string, locale?: string): Promise<Entry[]>;
88
+ /**
89
+ * Trimite un formular de pe site (Site, Cereri). Răspunsul vine așa cum l-a dat ERP-ul, ca ruta site-ului să-l poată da mai departe.
90
+ * `visitorIp` e obligatoriu în practică: limitele se aplică pe vizitator.
91
+ */
92
+ submitForm(form: string, body: Record<string, unknown>, o?: Pick<RequestOptions, "visitorIp">): Promise<Response>;
93
+ };