crelte 0.5.14 → 0.6.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/blocks/Blocks.svelte +5 -4
  2. package/dist/blocks/Blocks.svelte.d.ts +4 -19
  3. package/dist/blocks/Blocks.svelte.d.ts.map +1 -1
  4. package/dist/crelte.d.ts +2 -2
  5. package/dist/crelte.d.ts.map +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/init/InternalApp.d.ts.map +1 -1
  9. package/dist/init/InternalApp.js +2 -2
  10. package/dist/init/server.js +4 -4
  11. package/dist/loadData/loadData.d.ts +1 -1
  12. package/dist/loadData/loadData.d.ts.map +1 -1
  13. package/dist/queries/Queries.d.ts +9 -26
  14. package/dist/queries/Queries.d.ts.map +1 -1
  15. package/dist/queries/Queries.js +10 -20
  16. package/dist/queries/gql.d.ts +2 -2
  17. package/dist/queries/gql.d.ts.map +1 -1
  18. package/dist/queries/gql.js +3 -2
  19. package/dist/queries/index.d.ts +13 -13
  20. package/dist/queries/index.d.ts.map +1 -1
  21. package/dist/queries/index.js +2 -2
  22. package/dist/queries/vars.d.ts +3 -3
  23. package/dist/queries/vars.d.ts.map +1 -1
  24. package/dist/queries/vars.js +3 -3
  25. package/dist/routing/route/BaseRoute.d.ts.map +1 -1
  26. package/dist/routing/router/ClientRouter.d.ts.map +1 -1
  27. package/dist/routing/router/ClientRouter.js +3 -2
  28. package/dist/server/CrelteServer.d.ts +1 -1
  29. package/dist/server/CrelteServer.d.ts.map +1 -1
  30. package/dist/server/Request.d.ts +2 -2
  31. package/dist/server/Request.js +2 -2
  32. package/dist/server/ServerRouter.d.ts +1 -1
  33. package/dist/server/ServerRouter.d.ts.map +1 -1
  34. package/dist/server/queries/QueriesCaching.d.ts +0 -1
  35. package/dist/server/queries/QueriesCaching.d.ts.map +1 -1
  36. package/dist/server/queries/QueriesCaching.js +0 -2
  37. package/dist/server/queries/QueryGqlRoute.d.ts +2 -0
  38. package/dist/server/queries/QueryGqlRoute.d.ts.map +1 -1
  39. package/dist/server/queries/QueryGqlRoute.js +16 -5
  40. package/dist/server/queries/QueryHandleRoute.d.ts +1 -2
  41. package/dist/server/queries/QueryHandleRoute.d.ts.map +1 -1
  42. package/dist/server/queries/QueryHandleRoute.js +2 -2
  43. package/dist/server/queries/queries.d.ts.map +1 -1
  44. package/dist/server/queries/queries.js +2 -1
  45. package/dist/server/queries/routes.d.ts +3 -4
  46. package/dist/server/queries/routes.d.ts.map +1 -1
  47. package/dist/server/queries/routes.js +3 -3
  48. package/dist/server/shared.d.ts +3 -3
  49. package/dist/server/shared.d.ts.map +1 -1
  50. package/dist/server/shared.js +6 -6
  51. package/dist/ssr/SsrCache.d.ts +2 -2
  52. package/dist/ssr/SsrCache.d.ts.map +1 -1
  53. package/dist/ssr/SsrCache.js +10 -16
  54. package/dist/static/index.d.ts +1 -1
  55. package/dist/std/encdec/escaping.d.ts +2 -0
  56. package/dist/std/encdec/escaping.d.ts.map +1 -0
  57. package/dist/std/encdec/escaping.js +41 -0
  58. package/dist/std/encdec/index.d.ts +13 -0
  59. package/dist/std/encdec/index.d.ts.map +1 -0
  60. package/dist/std/encdec/index.js +15 -0
  61. package/dist/std/index.d.ts.map +1 -1
  62. package/dist/translations/index.d.ts +2 -2
  63. package/dist/translations/index.d.ts.map +1 -1
  64. package/dist/translations/translationsPlugin.d.ts +4 -1
  65. package/dist/translations/translationsPlugin.d.ts.map +1 -1
  66. package/dist/translations/translationsPlugin.js +32 -2
  67. package/dist/utils.d.ts +1 -0
  68. package/dist/utils.d.ts.map +1 -1
  69. package/dist/utils.js +17 -0
  70. package/dist/vite/index.d.ts +1 -5
  71. package/dist/vite/index.d.ts.map +1 -1
  72. package/dist/vite/index.js +35 -76
  73. package/package.json +12 -7
  74. package/src/blocks/Blocks.svelte +4 -3
  75. package/src/crelte.ts +2 -2
  76. package/src/index.ts +2 -2
  77. package/src/init/InternalApp.ts +3 -4
  78. package/src/init/server.ts +4 -4
  79. package/src/loadData/loadData.ts +0 -2
  80. package/src/queries/Queries.ts +19 -35
  81. package/src/queries/gql.ts +7 -3
  82. package/src/queries/index.ts +19 -16
  83. package/src/queries/vars.ts +5 -7
  84. package/src/routing/route/BaseRoute.ts +1 -7
  85. package/src/routing/router/ClientRouter.ts +3 -1
  86. package/src/server/CrelteServer.ts +1 -1
  87. package/src/server/Request.ts +2 -2
  88. package/src/server/ServerRouter.ts +1 -1
  89. package/src/server/queries/QueriesCaching.ts +0 -2
  90. package/src/server/queries/QueryGqlRoute.ts +17 -10
  91. package/src/server/queries/QueryHandleRoute.ts +2 -6
  92. package/src/server/queries/queries.ts +2 -3
  93. package/src/server/queries/routes.ts +9 -6
  94. package/src/server/shared.ts +8 -8
  95. package/src/ssr/SsrCache.ts +13 -23
  96. package/src/static/index.ts +1 -1
  97. package/src/std/encdec/escaping.ts +47 -0
  98. package/src/std/encdec/index.ts +16 -0
  99. package/src/std/index.ts +1 -6
  100. package/src/translations/index.ts +2 -0
  101. package/src/translations/translationsPlugin.ts +46 -3
  102. package/src/utils.ts +21 -0
  103. package/src/vite/index.ts +40 -85
  104. package/types.d.ts +1 -1
@@ -13,7 +13,6 @@ export default class QueriesCaching {
13
13
  private cacheDir: string | null;
14
14
  private validBearerToken: string | null;
15
15
  debug: boolean;
16
- router: ServerRouter;
17
16
 
18
17
  constructor(
19
18
  platform: Platform,
@@ -21,7 +20,6 @@ export default class QueriesCaching {
21
20
  opts?: QueriesCachingOptions,
22
21
  ) {
23
22
  this.platform = platform;
24
- this.router = cs;
25
23
  this.debug = !!opts?.debug;
26
24
 
27
25
  const enableCaching = cs.getEnv('CACHING') === 'true';
@@ -10,6 +10,7 @@ import {
10
10
  validateVars,
11
11
  ValidIfFn,
12
12
  } from './routes.js';
13
+ import { cryptoSha1Hash } from '../../utils.js';
13
14
 
14
15
  export type QueryGqlArgs = {
15
16
  vars: Record<string, QueryVar> | null;
@@ -23,6 +24,7 @@ export type QueryGqlArgs = {
23
24
  export default class QueryGqlRoute {
24
25
  name: string;
25
26
  query: string;
27
+ queryHash: string;
26
28
  vars: Record<string, QueryVar> | null;
27
29
  validIfFn: ValidIfFn | null;
28
30
  cacheIfFn: CacheIfFn | null;
@@ -39,6 +41,7 @@ export default class QueryGqlRoute {
39
41
 
40
42
  this.name = name;
41
43
  this.query = query;
44
+ this.queryHash = query;
42
45
  this.vars = args.vars;
43
46
  this.validIfFn = args.validIfFn;
44
47
  this.cacheIfFn = args.cacheIfFn;
@@ -56,6 +59,10 @@ export default class QueryGqlRoute {
56
59
  else this.fillBasicDefaults();
57
60
  }
58
61
 
62
+ async init() {
63
+ this.queryHash = await cryptoSha1Hash(this.query);
64
+ }
65
+
59
66
  private fillEntryDefaults() {
60
67
  if (this.vars) return;
61
68
 
@@ -121,16 +128,11 @@ export default class QueryGqlRoute {
121
128
  let vars: Record<string, any>;
122
129
  try {
123
130
  const reqVars = await csr.req.json();
124
- vars = validateVars(
125
- this.vars,
126
- reqVars,
127
- this.validIfFn,
128
- caching.router,
129
- );
131
+ vars = validateVars(this.vars, reqVars, this.validIfFn, csr);
130
132
 
131
- if ('qName' in vars || 'xCraftSite' in vars)
133
+ if (['qName', 'qHash', 'xCraftSite'].some(name => name in vars))
132
134
  throw new Error(
133
- 'qName and xCraftSite are reserved variable names',
135
+ 'qName, qHash and xCraftSite are reserved variable names',
134
136
  );
135
137
  } catch (e) {
136
138
  return newError(e, 400);
@@ -158,7 +160,12 @@ export default class QueryGqlRoute {
158
160
  let cacheKey: string | null = null;
159
161
  const useCache = !previewToken && caching.isEnabled();
160
162
  if (useCache) {
161
- cacheKey = await calcKey({ ...vars, qName: this.name, xCraftSite });
163
+ cacheKey = await calcKey({
164
+ ...vars,
165
+ qName: this.name,
166
+ qHash: this.queryHash,
167
+ xCraftSite,
168
+ });
162
169
  const cached = await caching.getCache(cacheKey);
163
170
 
164
171
  if (logInfo) console.log(`${logInfo} ${cached ? 'hit' : 'miss'}`);
@@ -223,7 +230,7 @@ export default class QueryGqlRoute {
223
230
 
224
231
  // now we have a valid json resp.
225
232
  // should we cache it?
226
- if (cacheKey && this.cacheIfFn?.(jsonResp.data, vars)) {
233
+ if (cacheKey && this.cacheIfFn?.(jsonResp.data, vars, csr)) {
227
234
  try {
228
235
  await caching.setCache(cacheKey, jsonResp);
229
236
  if (logInfo) console.log(logInfo + ' set cache');
@@ -1,6 +1,5 @@
1
1
  import { QueryVar } from '../../queries/vars.js';
2
2
  import CrelteServerRequest from '../CrelteServer.js';
3
- import ServerRouter from '../ServerRouter.js';
4
3
  import { HandleFn, newError, validateVars, ValidIfFn } from './routes.js';
5
4
 
6
5
  // only internal
@@ -22,14 +21,11 @@ export default class QueryHandleRoute {
22
21
  this.vars = vars;
23
22
  }
24
23
 
25
- async handle(
26
- cs: ServerRouter,
27
- csr: CrelteServerRequest,
28
- ): Promise<Response> {
24
+ async handle(csr: CrelteServerRequest): Promise<Response> {
29
25
  let vars: Record<string, any>;
30
26
  try {
31
27
  const reqVars = await csr.req.json();
32
- vars = validateVars(this.vars, reqVars, this.validIfFn, cs);
28
+ vars = validateVars(this.vars, reqVars, this.validIfFn, csr);
33
29
  } catch (e) {
34
30
  return newError(e, 400);
35
31
  }
@@ -132,6 +132,7 @@ export async function initQueryRoutes(
132
132
  );
133
133
 
134
134
  const route = new QueryGqlRoute(name, rb.query, rb);
135
+ await route.init();
135
136
 
136
137
  router.post('/queries/' + route.name, csr =>
137
138
  route.handle(caching, csr),
@@ -147,9 +148,7 @@ export async function initQueryRoutes(
147
148
  rb.vars,
148
149
  );
149
150
 
150
- router.post('/queries/' + route.name, csr =>
151
- route.handle(caching.router, csr),
152
- );
151
+ router.post('/queries/' + route.name, csr => route.handle(csr));
153
152
  } else {
154
153
  throw new Error(
155
154
  `query js/ts ${name} file needs to either have ` +
@@ -1,13 +1,16 @@
1
1
  import { QueryVar } from '../../queries/vars.js';
2
2
  import CrelteServerRequest from '../CrelteServer.js';
3
- import ServerRouter from '../ServerRouter.js';
4
3
 
5
- export type CacheIfFn = (response: any, vars: Record<string, any>) => boolean;
4
+ export type CacheIfFn = (
5
+ response: any,
6
+ vars: Record<string, any>,
7
+ csr: CrelteServerRequest,
8
+ ) => boolean;
6
9
 
7
10
  /// Either throw or return a boolean
8
11
  export type ValidIfFn = (
9
12
  vars: Record<string, any>,
10
- sr: ServerRouter,
13
+ csr: CrelteServerRequest,
11
14
  ) => void | boolean;
12
15
 
13
16
  /// Anything other than returning undefined will replace the response
@@ -33,7 +36,7 @@ export function validateVars(
33
36
  qvars: Record<string, QueryVar> | null,
34
37
  vars: any,
35
38
  validIfFn: ValidIfFn | null,
36
- sr: ServerRouter,
39
+ csr: CrelteServerRequest,
37
40
  ): Record<string, any> {
38
41
  if (!vars || typeof vars !== 'object')
39
42
  throw new Error('expected an object as vars');
@@ -43,12 +46,12 @@ export function validateVars(
43
46
  const nVars: Record<string, any> = {};
44
47
 
45
48
  for (const [k, v] of Object.entries(qvars)) {
46
- nVars[k] = v.validValue(vars[k], sr);
49
+ nVars[k] = v.validValue(vars[k], csr);
47
50
  }
48
51
 
49
52
  if (validIfFn) {
50
53
  // or throw
51
- const valid = validIfFn(nVars, sr);
54
+ const valid = validIfFn(nVars, csr);
52
55
  if (typeof valid === 'boolean' && !valid)
53
56
  throw new Error('invalid variables for query');
54
57
  }
@@ -27,7 +27,7 @@ export type EnvData = {
27
27
  env: Map<string, string>;
28
28
  endpointUrl: string;
29
29
  endpointToken?: string;
30
- craftWebUrl: string;
30
+ craftBaseCpUrl: string;
31
31
  frontendUrl: string;
32
32
  viteEnv: Map<string, string>;
33
33
  };
@@ -47,8 +47,8 @@ export async function initEnvData(os: Platform): Promise<EnvData> {
47
47
 
48
48
  const endpointToken = env.get('ENDPOINT_TOKEN');
49
49
 
50
- const craftWebUrl = env.get('CRAFT_WEB_URL');
51
- if (!craftWebUrl) throw new Error('CRAFT_WEB_URL not set');
50
+ const craftBaseCpUrl = env.get('CRAFT_BASE_CP_URL');
51
+ if (!craftBaseCpUrl) throw new Error('CRAFT_BASE_CP_URL not set');
52
52
 
53
53
  const frontendUrl = env.get('FRONTEND_URL');
54
54
  if (!frontendUrl) throw new Error('FRONTEND_URL not set');
@@ -62,7 +62,7 @@ export async function initEnvData(os: Platform): Promise<EnvData> {
62
62
  env,
63
63
  endpointUrl,
64
64
  endpointToken,
65
- craftWebUrl,
65
+ craftBaseCpUrl,
66
66
  frontendUrl,
67
67
  viteEnv,
68
68
  };
@@ -145,7 +145,7 @@ export type RenderRequest = {
145
145
  htmlTemplate: string;
146
146
  ssrManifest: Record<string, string[]>;
147
147
  endpoint: string;
148
- craftWeb: string;
148
+ craftUrl: string;
149
149
  frontend: string;
150
150
  viteEnv: Map<string, string>;
151
151
  sites: SiteFromGraphQl[];
@@ -170,7 +170,7 @@ export async function modRender(
170
170
  htmlTemplate: template,
171
171
  ssrManifest: {},
172
172
  endpoint: env.endpointUrl,
173
- craftWeb: env.craftWebUrl,
173
+ craftUrl: env.craftBaseCpUrl,
174
174
  frontend: env.frontendUrl,
175
175
  viteEnv: env.viteEnv,
176
176
  sites,
@@ -199,7 +199,7 @@ export type RenderErrorRequest = {
199
199
  ssrManifest: Record<string, string[]>;
200
200
  acceptLang: string | null;
201
201
  endpoint: string;
202
- craftWeb: string;
202
+ craftUrl: string;
203
203
  frontend: string;
204
204
  viteEnv: Map<string, string>;
205
205
  };
@@ -239,7 +239,7 @@ export async function modRenderError(
239
239
  ssrManifest: {},
240
240
  acceptLang,
241
241
  endpoint: env.endpointUrl,
242
- craftWeb: env.craftWebUrl,
242
+ craftUrl: env.craftBaseCpUrl,
243
243
  frontend: env.frontendUrl,
244
244
  viteEnv: env.viteEnv,
245
245
  ...opts,
@@ -1,3 +1,6 @@
1
+ import { uneval } from 'devalue';
2
+ import { cryptoSha1Hash } from '../utils.js';
3
+
1
4
  /**
2
5
  * Calculates a key based on the json representation of the data
3
6
  *
@@ -9,20 +12,7 @@ export async function calcKey(data: any): Promise<string> {
9
12
  // specifically in the craft preview locally
10
13
  if (!crypto?.subtle) return json;
11
14
 
12
- // Convert the string data to an ArrayBuffer
13
- const encoder = new TextEncoder();
14
- const dataBuffer = encoder.encode(json);
15
-
16
- // Use the Web Crypto API to hash the data with SHA-1
17
- const hashBuffer = await crypto.subtle.digest('SHA-1', dataBuffer);
18
-
19
- // Convert the ArrayBuffer to a hex string
20
- const hashArray = Array.from(new Uint8Array(hashBuffer)); // Create an array from the buffer
21
- const hashHex = hashArray
22
- .map(b => b.toString(16).padStart(2, '0'))
23
- .join(''); // Convert to hex string
24
-
25
- return hashHex;
15
+ return await cryptoSha1Hash(json);
26
16
  }
27
17
 
28
18
  /**
@@ -147,15 +137,15 @@ export default class SsrCache {
147
137
  delete window._SSR_STORE;
148
138
  }
149
139
 
150
- private exportAsJson(): string {
151
- return JSON.stringify(Array.from(this.store.entries())).replace(
152
- /</g,
153
- '\\u003c',
154
- );
155
- }
156
-
157
140
  /** @hidden */
158
- z_exportToHead(): string {
159
- return `\n\t\t<script>window._SSR_STORE = ${this.exportAsJson()};</script>`;
141
+ z_toData(): any {
142
+ return this.store;
160
143
  }
161
144
  }
145
+
146
+ export function ssrCacheExportToHead(ssr: SsrCache) {
147
+ const data = Array.from(ssr.z_toData().entries());
148
+
149
+ // safety, uneval already escapes data: https://github.com/sveltejs/devalue#xss-mitigation
150
+ return `\n\t\t<script>window._SSR_STORE = ${uneval(data)};</script>`;
151
+ }
@@ -12,7 +12,7 @@ export type CrelteStaticRequest = CrelteRequest & {
12
12
  *
13
13
  * @example
14
14
  * ```js
15
- * router.add('/blog/:slug', async (csr) => {
15
+ * router.add('/blog/:slug', async csr => {
16
16
  * const blogData = await fetchBlogData(csr.getParam('slug'));
17
17
  *
18
18
  * return {
@@ -0,0 +1,47 @@
1
+ /*
2
+ * Code from Svelte (https://github.com/sveltejs/svelte/blob/b4968584df6be22222f58c273bdd8e04307ad36b/packages/svelte/src/escaping.js)
3
+ *
4
+ * Copyright (c) 2016-24 these people (https://github.com/sveltejs/svelte/graphs/contributors)
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ const ATTR_REGEX = /[&"<]/g;
26
+ const CONTENT_REGEX = /[&<]/g;
27
+
28
+ export function escape_html<V>(value: V, is_attr: boolean = false) {
29
+ const str = String(value ?? '');
30
+
31
+ const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
32
+ pattern.lastIndex = 0;
33
+
34
+ let escaped = '';
35
+ let last = 0;
36
+
37
+ while (pattern.test(str)) {
38
+ const i = pattern.lastIndex - 1;
39
+ const ch = str[i];
40
+ escaped +=
41
+ str.substring(last, i) +
42
+ (ch === '&' ? '&amp;' : ch === '"' ? '&quot;' : '&lt;');
43
+ last = i + 1;
44
+ }
45
+
46
+ return escaped + str.substring(last);
47
+ }
@@ -0,0 +1,16 @@
1
+ import { escape_html } from './escaping.js';
2
+
3
+ /**
4
+ * Convert newlines to <br> tags and escape HTML.
5
+ *
6
+ * #### Warning
7
+ * When used in an attribute, the `isAttr` parameter needs to be set to `true`.
8
+ *
9
+ * #### Example
10
+ * ```svelte
11
+ * {@html nl2br("Hello\nWorld")}
12
+ * ```
13
+ */
14
+ export function nl2br(str: string, isAttr: boolean = false): string {
15
+ return escape_html(str, isAttr).replace(/\n/g, '<br>');
16
+ }
package/src/std/index.ts CHANGED
@@ -31,12 +31,7 @@ export interface Cloneable {
31
31
  * A type that represents a value that can be cloned.
32
32
  */
33
33
  export type CloneableOrPrimitive =
34
- | Cloneable
35
- | string
36
- | number
37
- | boolean
38
- | null
39
- | undefined;
34
+ Cloneable | string | number | boolean | null | undefined;
40
35
 
41
36
  /**
42
37
  * Creates a clone of the provided value. The values need to be either
@@ -13,6 +13,7 @@ import {
13
13
  createTranslations,
14
14
  getTranslationsPlugin,
15
15
  type TranslateFunction,
16
+ type TranslationVarValue,
16
17
  type TranslateStore,
17
18
  type Translations,
18
19
  TranslationsPlugin,
@@ -50,6 +51,7 @@ export {
50
51
  LoaderCreator,
51
52
  TranslateStore,
52
53
  TranslateFunction,
54
+ TranslationVarValue,
53
55
  // loaders
54
56
  createFileLoader,
55
57
  createGlobalLoader,
@@ -7,8 +7,9 @@ import { getCrelte } from '../index.js';
7
7
 
8
8
  export type TranslateFunction = (
9
9
  key: string,
10
- // replacements?: Record<string, string>,
10
+ vars?: Record<string, TranslationVarValue>,
11
11
  ) => string;
12
+ export type TranslationVarValue = string | number;
12
13
  export type TranslateStore = Readable<TranslateFunction>;
13
14
  export type Translations = Record<string, string>;
14
15
  export type TranslationsPluginOptions = {
@@ -89,18 +90,60 @@ export class TranslationsPlugin implements Plugin {
89
90
  /** @hidden */
90
91
  z_createTranslateStore(namespace: string): TranslateStore {
91
92
  const store = derived(this.crelte.router.site, site => {
92
- return (key: string) => {
93
+ return (
94
+ key: string,
95
+ vars?: Record<string, TranslationVarValue>,
96
+ ) => {
93
97
  const lang = site?.language ?? this.firstLang;
94
98
  if (!lang) throw new Error('no lang');
95
99
 
96
100
  const data = this.get(lang, namespace);
97
101
  if (!data) console.error(`namespace '${namespace}' not loaded`);
98
- return data?.[key] || key;
102
+
103
+ const text = data?.[key] || key;
104
+ if (!vars) return text;
105
+ return this.z_resolveVariables(text, vars);
99
106
  };
100
107
  });
101
108
 
102
109
  return new Readable(store);
103
110
  }
111
+
112
+ /** @hidden */
113
+ z_resolveVariables(
114
+ text: string,
115
+ vars: Record<string, TranslationVarValue> = {},
116
+ ): string {
117
+ let result = '';
118
+ let index = 0;
119
+
120
+ while (index < text.length) {
121
+ const openIndex = text.indexOf('{', index);
122
+ if (openIndex === -1) {
123
+ result += text.slice(index);
124
+ break;
125
+ }
126
+
127
+ const closeIndex = text.indexOf('}', openIndex + 1);
128
+ if (closeIndex === -1) {
129
+ result += text.slice(index);
130
+ break;
131
+ }
132
+
133
+ result += text.slice(index, openIndex);
134
+
135
+ const key = text.slice(openIndex + 1, closeIndex);
136
+ if (key in vars) {
137
+ result += vars[key];
138
+ } else {
139
+ result += `{${key}}`;
140
+ }
141
+
142
+ index = closeIndex + 1;
143
+ }
144
+
145
+ return result;
146
+ }
104
147
  }
105
148
 
106
149
  /**
package/src/utils.ts CHANGED
@@ -34,3 +34,24 @@ export function urlWithPath(url: string, path?: string): URL {
34
34
  u.pathname = path ?? '';
35
35
  return u;
36
36
  }
37
+
38
+ export async function cryptoSha1Hash(str: string): Promise<string> {
39
+ // Convert the string data to an ArrayBuffer
40
+ const encoder = new TextEncoder();
41
+ const dataBuffer = encoder.encode(str);
42
+
43
+ // Use the Web Crypto API to hash the data with SHA-1
44
+ const hashBuffer = await crypto.subtle.digest('SHA-1', dataBuffer);
45
+
46
+ const bytes = new Uint8Array(hashBuffer);
47
+ // @ts-ignore using 2025 baseline feature
48
+ if (typeof bytes.toHex === 'function') return bytes.toHex();
49
+
50
+ // Convert the ArrayBuffer to a hex string
51
+ const hashArray = Array.from(bytes); // Create an array from the buffer
52
+ const hashHex = hashArray
53
+ .map(b => b.toString(16).padStart(2, '0'))
54
+ .join(''); // Convert to hex string
55
+
56
+ return hashHex;
57
+ }