@gringow/gringow 0.2.1 → 0.3.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
@@ -335,14 +335,15 @@ pnpm run test
335
335
  pnpm run test:watch
336
336
  ```
337
337
 
338
- ## Integrations
338
+ ## Related Packages
339
339
 
340
- Gringow has official integrations for modern web frameworks:
340
+ Gringow provides a complete ecosystem for AI-powered translation:
341
341
 
342
- - **[@gringow/gringow-cli](https://www.npmjs.com/package/@gringow/gringow-cli)** - Command-line interface for cache management and translations
343
- - **[@gringow/gringow-vite](https://www.npmjs.com/package/@gringow/gringow-vite)** - Vite plugin for build-time translation extraction
342
+ - **[@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow)** - Core translation library
343
+ - **[@gringow/gringow-vite](https://www.npmjs.com/package/@gringow/gringow-vite)** - Vite plugin for build-time extraction
344
344
  - **[@gringow/gringow-react](https://www.npmjs.com/package/@gringow/gringow-react)** - React hooks and components
345
- - **[@gringow/gringow-shadow](https://www.npmjs.com/package/@gringow/gringow-shadow)** - Web Component layer (vanilla JS)
345
+ - **[@gringow/gringow-shadow](https://www.npmjs.com/package/@gringow/gringow-shadow)** - Web Component layer
346
+ - **[@gringow/gringow-cli](https://www.npmjs.com/package/@gringow/gringow-cli)** - CLI tool
346
347
  - **[@gringow/gringow-nextjs](https://www.npmjs.com/package/@gringow/gringow-nextjs)** - Next.js plugin (experimental)
347
348
 
348
349
  ## Related Resources
@@ -1,5 +1,4 @@
1
1
  export { createCacheId } from './create-cache-id.mjs';
2
- export { flatTemplateString } from './flat-template-string.mjs';
3
2
  export { interpolateTemplate } from './interpolate-template.mjs';
4
3
 
5
4
  declare const GRINGOW_IO_URL = "https://gringow.io";
package/dist/browser.mjs CHANGED
@@ -44,42 +44,43 @@ function md5(input) {
44
44
  return state.map(toHex).join("");
45
45
  }
46
46
 
47
- // src/create-cache-id.ts
48
- function createCacheId(text) {
49
- const hexHash = md5(text);
50
- const cacheId = `gid_${hexHash}`;
51
- return cacheId;
52
- }
53
-
54
- // src/flat-template-string.ts
55
- function flatTemplateString(givenStrings, givenValues) {
56
- const strings = [...givenStrings.raw];
57
- const values = [...givenValues];
58
- const flatted = strings.reduce((acc, item, index) => {
47
+ // src/interpolate-template.ts
48
+ function ifArray(template, givenValues) {
49
+ const strings = [...template.raw];
50
+ const hasValues = givenValues !== void 0;
51
+ return strings.reduce((acc, item, index) => {
59
52
  acc += String(item ?? "");
60
- if (index < values.length) {
61
- const value = values[index];
62
- acc += String(value ?? "");
53
+ if (index < strings.length - 1) {
54
+ acc += hasValues ? String(givenValues[index] ?? "") : `\${${index}}`;
63
55
  }
64
56
  return acc;
65
57
  }, "");
66
- return flatted;
67
58
  }
68
-
69
- // src/interpolate-template.ts
70
- function interpolateTemplate(template, values) {
71
- if (!values || values.length === 0) return template;
59
+ function ifString(template, givenValues) {
60
+ if (template?.indexOf("${") === -1) return template;
72
61
  let valueIndex = 0;
73
62
  return template.replace(/\$\{[^}]*\}/g, () => {
74
- if (valueIndex < values.length) {
75
- const value = values[valueIndex++];
76
- return value === null || value === void 0 ? "" : String(value);
77
- }
78
- return "";
63
+ const value = givenValues?.[valueIndex];
64
+ const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
65
+ valueIndex++;
66
+ return output;
79
67
  });
80
68
  }
69
+ function interpolateTemplate(template, givenValues) {
70
+ if (typeof template === "string") return ifString(template, givenValues);
71
+ if (Array.isArray(template)) return ifArray(template, givenValues);
72
+ throw new Error("Template must be a string or TemplateStringsArray");
73
+ }
74
+
75
+ // src/create-cache-id.ts
76
+ function createCacheId(text) {
77
+ const interpolatedText = interpolateTemplate(text);
78
+ const hexHash = md5(interpolatedText);
79
+ const cacheId = `gid_${hexHash}`;
80
+ return cacheId;
81
+ }
81
82
 
82
83
  // src/browser.ts
83
84
  var GRINGOW_IO_URL = "https://gringow.io";
84
85
 
85
- export { GRINGOW_IO_URL, createCacheId, flatTemplateString, interpolateTemplate };
86
+ export { GRINGOW_IO_URL, createCacheId, interpolateTemplate };
package/dist/config.d.mts CHANGED
@@ -41,12 +41,12 @@ declare const awaitedConfig: Promise<{
41
41
  llm: {
42
42
  provider: "anthropic" | "gemini" | "openai" | "groq" | "mistral" | "ollama" | "xai" | "deepseek" | "openrouter" | "cerebras" | "lmstudio" | "azure" | "meta";
43
43
  model: string | null;
44
+ prePrompt?: string | undefined;
45
+ postPrompt?: string | undefined;
44
46
  apiKey?: string | undefined;
45
47
  baseURL?: string | undefined;
46
48
  temperature?: number | undefined;
47
49
  sleep?: number | undefined;
48
- prePrompt?: string | undefined;
49
- postPrompt?: string | undefined;
50
50
  prePromptReplace?: string | undefined;
51
51
  postPromptReplace?: string | undefined;
52
52
  prePromptAppend?: string | undefined;
@@ -44,9 +44,37 @@ function md5(input) {
44
44
  return state.map(toHex).join("");
45
45
  }
46
46
 
47
+ // src/interpolate-template.ts
48
+ function ifArray(template, givenValues) {
49
+ const strings = [...template.raw];
50
+ return strings.reduce((acc, item, index) => {
51
+ acc += String(item ?? "");
52
+ if (index < strings.length - 1) {
53
+ acc += `\${${index}}`;
54
+ }
55
+ return acc;
56
+ }, "");
57
+ }
58
+ function ifString(template, givenValues) {
59
+ if (template?.indexOf("${") === -1) return template;
60
+ let valueIndex = 0;
61
+ return template.replace(/\$\{[^}]*\}/g, () => {
62
+ const value = givenValues?.[valueIndex];
63
+ const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
64
+ valueIndex++;
65
+ return output;
66
+ });
67
+ }
68
+ function interpolateTemplate(template, givenValues) {
69
+ if (typeof template === "string") return ifString(template, givenValues);
70
+ if (Array.isArray(template)) return ifArray(template);
71
+ throw new Error("Template must be a string or TemplateStringsArray");
72
+ }
73
+
47
74
  // src/create-cache-id.ts
48
75
  function createCacheId(text) {
49
- const hexHash = md5(text);
76
+ const interpolatedText = interpolateTemplate(text);
77
+ const hexHash = md5(interpolatedText);
50
78
  const cacheId = `gid_${hexHash}`;
51
79
  return cacheId;
52
80
  }
@@ -18164,9 +18164,36 @@ function md5(input) {
18164
18164
  return state.map(toHex).join("");
18165
18165
  }
18166
18166
 
18167
+ // src/interpolate-template.ts
18168
+ function ifArray(template, givenValues) {
18169
+ const strings = [...template.raw];
18170
+ return strings.reduce((acc, item, index) => {
18171
+ acc += String(item ?? "");
18172
+ if (index < strings.length - 1) {
18173
+ acc += `\${${index}}`;
18174
+ }
18175
+ return acc;
18176
+ }, "");
18177
+ }
18178
+ function ifString(template, givenValues) {
18179
+ if (template?.indexOf("${") === -1) return template;
18180
+ let valueIndex = 0;
18181
+ return template.replace(/\$\{[^}]*\}/g, () => {
18182
+ const output = `\${${valueIndex}}` ;
18183
+ valueIndex++;
18184
+ return output;
18185
+ });
18186
+ }
18187
+ function interpolateTemplate(template, givenValues) {
18188
+ if (typeof template === "string") return ifString(template);
18189
+ if (Array.isArray(template)) return ifArray(template);
18190
+ throw new Error("Template must be a string or TemplateStringsArray");
18191
+ }
18192
+
18167
18193
  // src/create-cache-id.ts
18168
18194
  function createCacheId(text) {
18169
- const hexHash = md5(text);
18195
+ const interpolatedText = interpolateTemplate(text);
18196
+ const hexHash = md5(interpolatedText);
18170
18197
  const cacheId = `gid_${hexHash}`;
18171
18198
  return cacheId;
18172
18199
  }
@@ -6,4 +6,4 @@ import '../schemas/config.shcema.mjs';
6
6
  import '../create-cache-id.mjs';
7
7
  import './clear-cache.mjs';
8
8
  import './get-cache.mjs';
9
- import '../flat-template-string.mjs';
9
+ import '../interpolate-template.mjs';
@@ -1,11 +1,11 @@
1
- import fs from 'fs/promises';
2
1
  import { cosmiconfig } from 'cosmiconfig';
3
2
  import merge from 'lodash.merge';
4
3
  import { z } from 'zod';
4
+ import fs from 'fs/promises';
5
5
  import { dirname, resolve, parse } from 'path';
6
6
  import { mkdir, stat, statSync, mkdirSync } from 'fs';
7
7
 
8
- // src/data/get-cache.ts
8
+ // src/config.ts
9
9
 
10
10
  // src/constants/default-config.ts
11
11
  var defaultConfig = {
@@ -425,8 +425,9 @@ async function getOrCreateCache() {
425
425
  // src/data/check-cache.ts
426
426
  async function checkCache(cacheId) {
427
427
  const cache = await getOrCreateCache();
428
+ const config = await awaitedConfig;
428
429
  if (cache?.[cacheId]) {
429
- console.log(`Cache hit, id:${cacheId}`);
430
+ if (config.debug) console.log(`Cache hit, id:${cacheId}`);
430
431
  return cache[cacheId];
431
432
  }
432
433
  return void 0;
@@ -6,4 +6,4 @@ import '../schemas/config.shcema.mjs';
6
6
  import '../create-cache-id.mjs';
7
7
  import './clear-cache.mjs';
8
8
  import './get-cache.mjs';
9
- import '../flat-template-string.mjs';
9
+ import '../interpolate-template.mjs';
@@ -6,4 +6,4 @@ import '../schemas/config.shcema.mjs';
6
6
  import '../create-cache-id.mjs';
7
7
  import './clear-cache.mjs';
8
8
  import './get-cache.mjs';
9
- import '../flat-template-string.mjs';
9
+ import '../interpolate-template.mjs';
@@ -6,7 +6,7 @@ import '../schemas/config.shcema.mjs';
6
6
  import '../create-cache-id.mjs';
7
7
  import './clear-cache.mjs';
8
8
  import './get-cache.mjs';
9
- import '../flat-template-string.mjs';
9
+ import '../interpolate-template.mjs';
10
10
 
11
11
  /**
12
12
  * Saves the cache to disk.
@@ -6,4 +6,4 @@ import '../schemas/config.shcema.mjs';
6
6
  import '../create-cache-id.mjs';
7
7
  import './clear-cache.mjs';
8
8
  import './get-cache.mjs';
9
- import '../flat-template-string.mjs';
9
+ import '../interpolate-template.mjs';
@@ -6,4 +6,4 @@ import './schemas/config.shcema.mjs';
6
6
  import './create-cache-id.mjs';
7
7
  import './data/clear-cache.mjs';
8
8
  import './data/get-cache.mjs';
9
- import './flat-template-string.mjs';
9
+ import './interpolate-template.mjs';
package/dist/gringow.mjs CHANGED
@@ -215,9 +215,38 @@ function md5(input) {
215
215
  return state.map(toHex).join("");
216
216
  }
217
217
 
218
+ // src/interpolate-template.ts
219
+ function ifArray(template, givenValues) {
220
+ const strings = [...template.raw];
221
+ const hasValues = givenValues !== void 0;
222
+ return strings.reduce((acc, item, index) => {
223
+ acc += String(item ?? "");
224
+ if (index < strings.length - 1) {
225
+ acc += hasValues ? String(givenValues[index] ?? "") : `\${${index}}`;
226
+ }
227
+ return acc;
228
+ }, "");
229
+ }
230
+ function ifString(template, givenValues) {
231
+ if (template?.indexOf("${") === -1) return template;
232
+ let valueIndex = 0;
233
+ return template.replace(/\$\{[^}]*\}/g, () => {
234
+ const value = givenValues?.[valueIndex];
235
+ const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
236
+ valueIndex++;
237
+ return output;
238
+ });
239
+ }
240
+ function interpolateTemplate(template, givenValues) {
241
+ if (typeof template === "string") return ifString(template, givenValues);
242
+ if (Array.isArray(template)) return ifArray(template, givenValues);
243
+ throw new Error("Template must be a string or TemplateStringsArray");
244
+ }
245
+
218
246
  // src/create-cache-id.ts
219
247
  function createCacheId(text) {
220
- const hexHash = md5(text);
248
+ const interpolatedText = interpolateTemplate(text);
249
+ const hexHash = md5(interpolatedText);
221
250
  const cacheId = `gid_${hexHash}`;
222
251
  return cacheId;
223
252
  }
@@ -479,8 +508,9 @@ async function getOrCreateCache() {
479
508
  // src/data/check-cache.ts
480
509
  async function checkCache(cacheId) {
481
510
  const cache = await getOrCreateCache();
511
+ const config = await awaitedConfig;
482
512
  if (cache?.[cacheId]) {
483
- console.log(`Cache hit, id:${cacheId}`);
513
+ if (config.debug) console.log(`Cache hit, id:${cacheId}`);
484
514
  return cache[cacheId];
485
515
  }
486
516
  return void 0;
@@ -493,21 +523,6 @@ async function writeCacheToDisk(cacheId, cached) {
493
523
  await saveCache(cache);
494
524
  return cache[cacheId];
495
525
  }
496
-
497
- // src/flat-template-string.ts
498
- function flatTemplateString(givenStrings, givenValues) {
499
- const strings = [...givenStrings.raw];
500
- const values = [...givenValues];
501
- const flatted = strings.reduce((acc, item, index) => {
502
- acc += String(item ?? "");
503
- if (index < values.length) {
504
- const value = values[index];
505
- acc += String(value ?? "");
506
- }
507
- return acc;
508
- }, "");
509
- return flatted;
510
- }
511
526
  var providerEngineMap = {
512
527
  anthropic: "anthropic",
513
528
  gemini: "google",
@@ -596,15 +611,10 @@ async function rebuild(cacheId) {
596
611
  }
597
612
  return { cacheId, translation: output };
598
613
  }
599
- async function Gringow(strings, ...values) {
614
+ async function Gringow(text, ...values) {
600
615
  const config = await awaitedConfig;
601
- let flatten;
602
- if (typeof strings === "string") {
603
- flatten = String(strings ?? "");
604
- } else {
605
- flatten = flatTemplateString(strings, values);
606
- }
607
- const cacheId = createCacheId(flatten);
616
+ const interpolated = interpolateTemplate(text.trim(), values);
617
+ const cacheId = createCacheId(interpolated);
608
618
  const cached = await checkCache(cacheId);
609
619
  if (cached !== void 0 && cached.original !== "undefined" && !cached.rebuild) {
610
620
  return { cacheId, translation: cached };
@@ -614,7 +624,7 @@ async function Gringow(strings, ...values) {
614
624
  console.log(`asking::prepend ${cacheId}:`, { prepend });
615
625
  console.log(`asking::append ${cacheId}:`, { append });
616
626
  }
617
- const translation = await askLLM(flatten, prepend, append);
627
+ const translation = await askLLM(interpolated, prepend, append);
618
628
  const output = {
619
629
  ...translation,
620
630
  prepend: cached?.prepend ?? void 0,
package/dist/index.d.mts CHANGED
@@ -2,7 +2,7 @@ export { awaitedConfig, getConfigSource, isLocalConfigFound } from './config.mjs
2
2
  export { createCacheId } from './create-cache-id.mjs';
3
3
  export { clearCache } from './data/clear-cache.mjs';
4
4
  export { getCache } from './data/get-cache.mjs';
5
- export { flatTemplateString } from './flat-template-string.mjs';
5
+ export { interpolateTemplate } from './interpolate-template.mjs';
6
6
  export { GringowConfig } from './constants/default-config.mjs';
7
7
  import 'zod';
8
8
  import './schemas/config.shcema.mjs';
@@ -77,10 +77,10 @@ declare function rebuild(cacheId: string): Promise<GringowResponse>;
77
77
  * Gringow is a function that translates a string or a template string into a
78
78
  * translated string.
79
79
  *
80
- * @param strings - The string or template string to translate.
80
+ * @param text - The string or template string to translate.
81
81
  * @param values - The values to interpolate into the string.
82
82
  * @returns The translated string.
83
83
  */
84
- declare function Gringow(strings: TemplateStringsArray | string, ...values: Array<unknown>): Promise<GringowResponse>;
84
+ declare function Gringow(text: string, ...values: Array<unknown>): Promise<GringowResponse>;
85
85
 
86
86
  export { type GringowCache, type GringowCacheItem, type GringowError, type GringowResponse, type GringowTranslation, checkCache, Gringow as default, deleteCacheItem, getOrCreateCache, rebuild, writeCacheToDisk };
package/dist/index.mjs CHANGED
@@ -221,9 +221,38 @@ function md5(input) {
221
221
  return state.map(toHex).join("");
222
222
  }
223
223
 
224
+ // src/interpolate-template.ts
225
+ function ifArray(template, givenValues) {
226
+ const strings = [...template.raw];
227
+ const hasValues = givenValues !== void 0;
228
+ return strings.reduce((acc, item, index) => {
229
+ acc += String(item ?? "");
230
+ if (index < strings.length - 1) {
231
+ acc += hasValues ? String(givenValues[index] ?? "") : `\${${index}}`;
232
+ }
233
+ return acc;
234
+ }, "");
235
+ }
236
+ function ifString(template, givenValues) {
237
+ if (template?.indexOf("${") === -1) return template;
238
+ let valueIndex = 0;
239
+ return template.replace(/\$\{[^}]*\}/g, () => {
240
+ const value = givenValues?.[valueIndex];
241
+ const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
242
+ valueIndex++;
243
+ return output;
244
+ });
245
+ }
246
+ function interpolateTemplate(template, givenValues) {
247
+ if (typeof template === "string") return ifString(template, givenValues);
248
+ if (Array.isArray(template)) return ifArray(template, givenValues);
249
+ throw new Error("Template must be a string or TemplateStringsArray");
250
+ }
251
+
224
252
  // src/create-cache-id.ts
225
253
  function createCacheId(text) {
226
- const hexHash = md5(text);
254
+ const interpolatedText = interpolateTemplate(text);
255
+ const hexHash = md5(interpolatedText);
227
256
  const cacheId = `gid_${hexHash}`;
228
257
  return cacheId;
229
258
  }
@@ -485,8 +514,9 @@ async function getOrCreateCache() {
485
514
  // src/data/check-cache.ts
486
515
  async function checkCache(cacheId) {
487
516
  const cache = await getOrCreateCache();
517
+ const config = await awaitedConfig;
488
518
  if (cache?.[cacheId]) {
489
- console.log(`Cache hit, id:${cacheId}`);
519
+ if (config.debug) console.log(`Cache hit, id:${cacheId}`);
490
520
  return cache[cacheId];
491
521
  }
492
522
  return void 0;
@@ -515,21 +545,6 @@ async function writeCacheToDisk(cacheId, cached) {
515
545
  await saveCache(cache);
516
546
  return cache[cacheId];
517
547
  }
518
-
519
- // src/flat-template-string.ts
520
- function flatTemplateString(givenStrings, givenValues) {
521
- const strings = [...givenStrings.raw];
522
- const values = [...givenValues];
523
- const flatted = strings.reduce((acc, item, index) => {
524
- acc += String(item ?? "");
525
- if (index < values.length) {
526
- const value = values[index];
527
- acc += String(value ?? "");
528
- }
529
- return acc;
530
- }, "");
531
- return flatted;
532
- }
533
548
  var providerEngineMap = {
534
549
  anthropic: "anthropic",
535
550
  gemini: "google",
@@ -618,15 +633,10 @@ async function rebuild(cacheId) {
618
633
  }
619
634
  return { cacheId, translation: output };
620
635
  }
621
- async function Gringow(strings, ...values) {
636
+ async function Gringow(text, ...values) {
622
637
  const config = await awaitedConfig;
623
- let flatten;
624
- if (typeof strings === "string") {
625
- flatten = String(strings ?? "");
626
- } else {
627
- flatten = flatTemplateString(strings, values);
628
- }
629
- const cacheId = createCacheId(flatten);
638
+ const interpolated = interpolateTemplate(text.trim(), values);
639
+ const cacheId = createCacheId(interpolated);
630
640
  const cached = await checkCache(cacheId);
631
641
  if (cached !== void 0 && cached.original !== "undefined" && !cached.rebuild) {
632
642
  return { cacheId, translation: cached };
@@ -636,7 +646,7 @@ async function Gringow(strings, ...values) {
636
646
  console.log(`asking::prepend ${cacheId}:`, { prepend });
637
647
  console.log(`asking::append ${cacheId}:`, { append });
638
648
  }
639
- const translation = await askLLM(flatten, prepend, append);
649
+ const translation = await askLLM(interpolated, prepend, append);
640
650
  const output = {
641
651
  ...translation,
642
652
  prepend: cached?.prepend ?? void 0,
@@ -648,4 +658,4 @@ async function Gringow(strings, ...values) {
648
658
  return { cacheId, translation: output };
649
659
  }
650
660
 
651
- export { awaitedConfig, checkCache, clearCache, createCacheId, Gringow as default, deleteCacheItem, flatTemplateString, getCache, getConfigSource, getOrCreateCache, isLocalConfigFound, rebuild, writeCacheToDisk };
661
+ export { awaitedConfig, checkCache, clearCache, createCacheId, Gringow as default, deleteCacheItem, getCache, getConfigSource, getOrCreateCache, interpolateTemplate, isLocalConfigFound, rebuild, writeCacheToDisk };
@@ -1,3 +1,3 @@
1
- declare function interpolateTemplate(template: string, values: unknown[]): string;
1
+ declare function interpolateTemplate(template: TemplateStringsArray | string, givenValues?: unknown[]): string;
2
2
 
3
3
  export { interpolateTemplate };
@@ -1,14 +1,29 @@
1
1
  // src/interpolate-template.ts
2
- function interpolateTemplate(template, values) {
3
- if (!values || values.length === 0) return template;
2
+ function ifArray(template, givenValues) {
3
+ const strings = [...template.raw];
4
+ const hasValues = givenValues !== void 0;
5
+ return strings.reduce((acc, item, index) => {
6
+ acc += String(item ?? "");
7
+ if (index < strings.length - 1) {
8
+ acc += hasValues ? String(givenValues[index] ?? "") : `\${${index}}`;
9
+ }
10
+ return acc;
11
+ }, "");
12
+ }
13
+ function ifString(template, givenValues) {
14
+ if (template?.indexOf("${") === -1) return template;
4
15
  let valueIndex = 0;
5
16
  return template.replace(/\$\{[^}]*\}/g, () => {
6
- if (valueIndex < values.length) {
7
- const value = values[valueIndex++];
8
- return value === null || value === void 0 ? "" : String(value);
9
- }
10
- return "";
17
+ const value = givenValues?.[valueIndex];
18
+ const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
19
+ valueIndex++;
20
+ return output;
11
21
  });
12
22
  }
23
+ function interpolateTemplate(template, givenValues) {
24
+ if (typeof template === "string") return ifString(template, givenValues);
25
+ if (Array.isArray(template)) return ifArray(template, givenValues);
26
+ throw new Error("Template must be a string or TemplateStringsArray");
27
+ }
13
28
 
14
29
  export { interpolateTemplate };
@@ -18118,105 +18118,121 @@ function getImporter(name) {
18118
18118
  // ../node_modules/.pnpm/vitest@2.1.9_@types+node@22.16.4_lightningcss@1.30.2_msw@2.12.8_@types+node@22.16.4_typescript@5.7.3__terser@5.44.1/node_modules/vitest/dist/index.js
18119
18119
  __toESM(require_dist(), 1);
18120
18120
 
18121
- // src/flat-template-string.ts
18122
- function flatTemplateString(givenStrings, givenValues) {
18123
- const strings = [...givenStrings.raw];
18124
- const values = [...givenValues];
18125
- const flatted = strings.reduce((acc, item, index) => {
18121
+ // src/interpolate-template.ts
18122
+ function ifArray(template, givenValues) {
18123
+ const strings = [...template.raw];
18124
+ const hasValues = givenValues !== void 0;
18125
+ return strings.reduce((acc, item, index) => {
18126
18126
  acc += String(item ?? "");
18127
- if (index < values.length) {
18128
- const value = values[index];
18129
- acc += String(value ?? "");
18127
+ if (index < strings.length - 1) {
18128
+ acc += hasValues ? String(givenValues[index] ?? "") : `\${${index}}`;
18130
18129
  }
18131
18130
  return acc;
18132
18131
  }, "");
18133
- return flatted;
18132
+ }
18133
+ function ifString(template, givenValues) {
18134
+ if (template?.indexOf("${") === -1) return template;
18135
+ let valueIndex = 0;
18136
+ return template.replace(/\$\{[^}]*\}/g, () => {
18137
+ const value = givenValues?.[valueIndex];
18138
+ const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
18139
+ valueIndex++;
18140
+ return output;
18141
+ });
18142
+ }
18143
+ function interpolateTemplate(template, givenValues) {
18144
+ if (typeof template === "string") return ifString(template, givenValues);
18145
+ if (Array.isArray(template)) return ifArray(template, givenValues);
18146
+ throw new Error("Template must be a string or TemplateStringsArray");
18134
18147
  }
18135
18148
 
18136
- // src/flat-template-string.test.ts
18137
- function createTemplateStringsArray(strings) {
18149
+ // src/interpolate-template.test.ts
18150
+ function tpl(strings) {
18138
18151
  return Object.assign(strings, { raw: [...strings] });
18139
18152
  }
18140
- describe("flatTemplateString", () => {
18141
- it("should concatenate simple strings without values", () => {
18142
- const result = flatTemplateString(createTemplateStringsArray(["Hello World"]), []);
18143
- globalExpect(result).toBe("Hello World");
18144
- });
18145
- it("should interpolate simple values", () => {
18146
- const result = flatTemplateString(createTemplateStringsArray(["Hello ", "!"]), ["World"]);
18147
- globalExpect(result).toBe("Hello World!");
18148
- });
18149
- it("should interpolate multiple values", () => {
18150
- const result = flatTemplateString(createTemplateStringsArray(["Hello ", ", you are ", " years old"]), ["John", 25]);
18151
- globalExpect(result).toBe("Hello John, you are 25 years old");
18152
- });
18153
- it("should handle null and undefined values", () => {
18154
- const result = flatTemplateString(createTemplateStringsArray(["Value: ", ", null: ", ", undefined: "]), [
18155
- null,
18156
- null,
18157
- void 0
18158
- ]);
18159
- globalExpect(result).toBe("Value: , null: , undefined: ");
18160
- });
18161
- it("should convert numbers to string", () => {
18162
- const result = flatTemplateString(createTemplateStringsArray(["Number: ", ""]), [42]);
18163
- globalExpect(result).toBe("Number: 42");
18164
- });
18165
- it("should convert booleans to string", () => {
18166
- const result = flatTemplateString(createTemplateStringsArray(["Boolean: ", ", false: "]), [true, false]);
18167
- globalExpect(result).toBe("Boolean: true, false: false");
18168
- });
18169
- it("should handle objects by converting to string", () => {
18170
- const obj = { name: "John", age: 30 };
18171
- const result = flatTemplateString(createTemplateStringsArray(["Object: ", ""]), [obj]);
18172
- globalExpect(result).toBe("Object: [object Object]");
18173
- });
18174
- it("should handle arrays by converting to string", () => {
18175
- const arr = [1, 2, 3];
18176
- const result = flatTemplateString(createTemplateStringsArray(["Array: ", ""]), [arr]);
18177
- globalExpect(result).toBe("Array: 1,2,3");
18178
- });
18179
- it("should handle empty strings", () => {
18180
- const result = flatTemplateString(createTemplateStringsArray(["", "middle", ""]), ["start", "end"]);
18181
- globalExpect(result).toBe("startmiddleend");
18182
- });
18183
- it("should handle complex template string", () => {
18184
- const name = "Alice";
18185
- const age = 28;
18186
- const city = "S\xE3o Paulo";
18187
- const result = flatTemplateString(
18188
- createTemplateStringsArray(["Ol\xE1, meu nome \xE9 ", ", tenho ", " anos e moro em ", "."]),
18189
- [name, age, city]
18190
- );
18191
- globalExpect(result).toBe("Ol\xE1, meu nome \xE9 Alice, tenho 28 anos e moro em S\xE3o Paulo.");
18192
- });
18193
- it("should handle values that are empty strings", () => {
18194
- const result = flatTemplateString(createTemplateStringsArray(["Start", "Middle", "End"]), ["", ""]);
18195
- globalExpect(result).toBe("StartMiddleEnd");
18196
- });
18197
- it("should preserve whitespace and line breaks", () => {
18198
- const result = flatTemplateString(createTemplateStringsArray(["Line 1\n", "Line 2\n", "Line 3"]), ["", ""]);
18199
- globalExpect(result).toBe("Line 1\nLine 2\nLine 3");
18153
+ describe("interpolateTemplate", () => {
18154
+ describe("string only \u2014 no ${...}", () => {
18155
+ it("returns the string as-is", () => {
18156
+ globalExpect(interpolateTemplate("Hello World")).toBe("Hello World");
18157
+ });
18158
+ it("returns empty string as-is", () => {
18159
+ globalExpect(interpolateTemplate("")).toBe("");
18160
+ });
18200
18161
  });
18201
- it("should handle special characters", () => {
18202
- const result = flatTemplateString(createTemplateStringsArray(["Special: ", ""]), ["@#$%^&*()"]);
18203
- globalExpect(result).toBe("Special: @#$%^&*()");
18162
+ describe("string only \u2014 with ${...}", () => {
18163
+ it("replaces single placeholder with index notation", () => {
18164
+ globalExpect(interpolateTemplate("Hello ${name}!")).toBe("Hello ${0}!");
18165
+ });
18166
+ it("replaces multiple placeholders with sequential index notation", () => {
18167
+ globalExpect(interpolateTemplate("${greeting}, ${name}! You are ${age} years old.")).toBe(
18168
+ "${0}, ${1}! You are ${2} years old."
18169
+ );
18170
+ });
18171
+ it("replaces placeholder regardless of variable name inside ${}", () => {
18172
+ globalExpect(interpolateTemplate("Value: ${someRandomVarName}")).toBe("Value: ${0}");
18173
+ });
18204
18174
  });
18205
- it("should handle emojis", () => {
18206
- const result = flatTemplateString(createTemplateStringsArray(["Hello ", "!"]), ["\u{1F44B}"]);
18207
- globalExpect(result).toBe("Hello \u{1F44B}!");
18175
+ describe("TemplateStringsArray only \u2014 no values", () => {
18176
+ it("joins parts with index notation for each slot", () => {
18177
+ globalExpect(interpolateTemplate(tpl(["Hello ", "!"]))).toBe("Hello ${0}!");
18178
+ });
18179
+ it("handles multiple slots", () => {
18180
+ globalExpect(interpolateTemplate(tpl(["", ", ", "! You are ", " years old."]))).toBe(
18181
+ "${0}, ${1}! You are ${2} years old."
18182
+ );
18183
+ });
18184
+ it("handles a single string part with no slots", () => {
18185
+ globalExpect(interpolateTemplate(tpl(["Hello World"]))).toBe("Hello World");
18186
+ });
18208
18187
  });
18209
- it("should handle template string without values (strings only)", () => {
18210
- const result = flatTemplateString(createTemplateStringsArray(["Apenas", "texto", "simples"]), []);
18211
- globalExpect(result).toBe("Apenastextosimples");
18188
+ describe("string + values \u2014 no ${...}", () => {
18189
+ it("returns string as-is and ignores values", () => {
18190
+ globalExpect(interpolateTemplate("Hello World", ["John", 42])).toBe("Hello World");
18191
+ });
18212
18192
  });
18213
- it("should handle more values than strings", () => {
18214
- const result = flatTemplateString(createTemplateStringsArray(["Start", "End"]), ["Middle1", "Middle2", "Extra"]);
18215
- globalExpect(result).toBe("StartMiddle1EndMiddle2");
18193
+ describe("string + values \u2014 with ${...}", () => {
18194
+ it("replaces placeholder with provided value", () => {
18195
+ globalExpect(interpolateTemplate("Hello ${name}!", ["John"])).toBe("Hello John!");
18196
+ });
18197
+ it("replaces multiple placeholders with sequential values", () => {
18198
+ globalExpect(interpolateTemplate("${greeting}, ${name}! You are ${age} years old.", ["Hi", "Alice", 30])).toBe(
18199
+ "Hi, Alice! You are 30 years old."
18200
+ );
18201
+ });
18202
+ it("falls back to index notation when value is undefined", () => {
18203
+ globalExpect(interpolateTemplate("${a} and ${b}", [void 0, "world"])).toBe("${0} and world");
18204
+ });
18205
+ it("falls back to index notation when value is null", () => {
18206
+ globalExpect(interpolateTemplate("${a} and ${b}", [null, "world"])).toBe("${0} and world");
18207
+ });
18208
+ it("converts number values to string", () => {
18209
+ globalExpect(interpolateTemplate("Value: ${n}", [42])).toBe("Value: 42");
18210
+ });
18211
+ it("converts boolean values to string", () => {
18212
+ globalExpect(interpolateTemplate("Flag: ${f}", [true])).toBe("Flag: true");
18213
+ });
18216
18214
  });
18217
- it("should handle fewer values than strings", () => {
18218
- const result = flatTemplateString(createTemplateStringsArray(["Start", "Middle", "End"]), ["Value"]);
18219
- globalExpect(result).toBe("StartValueMiddleEnd");
18215
+ describe("TemplateStringsArray + values", () => {
18216
+ it("interpolates with provided values", () => {
18217
+ globalExpect(interpolateTemplate(tpl(["Hello ", "!"]), ["World"])).toBe("Hello World!");
18218
+ });
18219
+ it("interpolates multiple values", () => {
18220
+ globalExpect(interpolateTemplate(tpl(["Hello ", ", you are ", " years old"]), ["John", 25])).toBe(
18221
+ "Hello John, you are 25 years old"
18222
+ );
18223
+ });
18224
+ it("handles null values as empty string", () => {
18225
+ globalExpect(interpolateTemplate(tpl(["Value: ", ", null: "]), [null, null])).toBe("Value: , null: ");
18226
+ });
18227
+ it("handles undefined values as empty string", () => {
18228
+ globalExpect(interpolateTemplate(tpl(["Start: ", ", end"]), [void 0])).toBe("Start: , end");
18229
+ });
18230
+ it("converts number values to string", () => {
18231
+ globalExpect(interpolateTemplate(tpl(["Number: ", ""]), [42])).toBe("Number: 42");
18232
+ });
18233
+ it("converts boolean values to string", () => {
18234
+ globalExpect(interpolateTemplate(tpl(["Boolean: ", ""]), [true])).toBe("Boolean: true");
18235
+ });
18220
18236
  });
18221
18237
  });
18222
18238
  /*! Bundled license information:
@@ -6,7 +6,7 @@ import '../schemas/config.shcema.mjs';
6
6
  import '../create-cache-id.mjs';
7
7
  import '../data/clear-cache.mjs';
8
8
  import '../data/get-cache.mjs';
9
- import '../flat-template-string.mjs';
9
+ import '../interpolate-template.mjs';
10
10
 
11
11
  /**
12
12
  * Asks an LLM for a response using multi-llm-ts.
@@ -46,12 +46,12 @@ declare const configSchema: z.ZodEffects<z.ZodObject<{
46
46
  }, "strip", z.ZodTypeAny, {
47
47
  provider: "anthropic" | "gemini" | "openai" | "groq" | "mistral" | "ollama" | "xai" | "deepseek" | "openrouter" | "cerebras" | "lmstudio" | "azure" | "meta";
48
48
  model: string | null;
49
+ prePrompt?: string | undefined;
50
+ postPrompt?: string | undefined;
49
51
  apiKey?: string | undefined;
50
52
  baseURL?: string | undefined;
51
53
  temperature?: number | undefined;
52
54
  sleep?: number | undefined;
53
- prePrompt?: string | undefined;
54
- postPrompt?: string | undefined;
55
55
  prePromptReplace?: string | undefined;
56
56
  postPromptReplace?: string | undefined;
57
57
  prePromptAppend?: string | undefined;
@@ -59,12 +59,12 @@ declare const configSchema: z.ZodEffects<z.ZodObject<{
59
59
  }, {
60
60
  provider: "anthropic" | "gemini" | "openai" | "groq" | "mistral" | "ollama" | "xai" | "deepseek" | "openrouter" | "cerebras" | "lmstudio" | "azure" | "meta";
61
61
  model: string | null;
62
+ prePrompt?: string | undefined;
63
+ postPrompt?: string | undefined;
62
64
  apiKey?: string | undefined;
63
65
  baseURL?: string | undefined;
64
66
  temperature?: number | undefined;
65
67
  sleep?: number | undefined;
66
- prePrompt?: string | undefined;
67
- postPrompt?: string | undefined;
68
68
  prePromptReplace?: string | undefined;
69
69
  postPromptReplace?: string | undefined;
70
70
  prePromptAppend?: string | undefined;
@@ -87,12 +87,12 @@ declare const configSchema: z.ZodEffects<z.ZodObject<{
87
87
  llm: {
88
88
  provider: "anthropic" | "gemini" | "openai" | "groq" | "mistral" | "ollama" | "xai" | "deepseek" | "openrouter" | "cerebras" | "lmstudio" | "azure" | "meta";
89
89
  model: string | null;
90
+ prePrompt?: string | undefined;
91
+ postPrompt?: string | undefined;
90
92
  apiKey?: string | undefined;
91
93
  baseURL?: string | undefined;
92
94
  temperature?: number | undefined;
93
95
  sleep?: number | undefined;
94
- prePrompt?: string | undefined;
95
- postPrompt?: string | undefined;
96
96
  prePromptReplace?: string | undefined;
97
97
  postPromptReplace?: string | undefined;
98
98
  prePromptAppend?: string | undefined;
@@ -116,12 +116,12 @@ declare const configSchema: z.ZodEffects<z.ZodObject<{
116
116
  llm: {
117
117
  provider: "anthropic" | "gemini" | "openai" | "groq" | "mistral" | "ollama" | "xai" | "deepseek" | "openrouter" | "cerebras" | "lmstudio" | "azure" | "meta";
118
118
  model: string | null;
119
+ prePrompt?: string | undefined;
120
+ postPrompt?: string | undefined;
119
121
  apiKey?: string | undefined;
120
122
  baseURL?: string | undefined;
121
123
  temperature?: number | undefined;
122
124
  sleep?: number | undefined;
123
- prePrompt?: string | undefined;
124
- postPrompt?: string | undefined;
125
125
  prePromptReplace?: string | undefined;
126
126
  postPromptReplace?: string | undefined;
127
127
  prePromptAppend?: string | undefined;
@@ -145,12 +145,12 @@ declare const configSchema: z.ZodEffects<z.ZodObject<{
145
145
  llm: {
146
146
  provider: "anthropic" | "gemini" | "openai" | "groq" | "mistral" | "ollama" | "xai" | "deepseek" | "openrouter" | "cerebras" | "lmstudio" | "azure" | "meta";
147
147
  model: string | null;
148
+ prePrompt?: string | undefined;
149
+ postPrompt?: string | undefined;
148
150
  apiKey?: string | undefined;
149
151
  baseURL?: string | undefined;
150
152
  temperature?: number | undefined;
151
153
  sleep?: number | undefined;
152
- prePrompt?: string | undefined;
153
- postPrompt?: string | undefined;
154
154
  prePromptReplace?: string | undefined;
155
155
  postPromptReplace?: string | undefined;
156
156
  prePromptAppend?: string | undefined;
@@ -174,12 +174,12 @@ declare const configSchema: z.ZodEffects<z.ZodObject<{
174
174
  llm: {
175
175
  provider: "anthropic" | "gemini" | "openai" | "groq" | "mistral" | "ollama" | "xai" | "deepseek" | "openrouter" | "cerebras" | "lmstudio" | "azure" | "meta";
176
176
  model: string | null;
177
+ prePrompt?: string | undefined;
178
+ postPrompt?: string | undefined;
177
179
  apiKey?: string | undefined;
178
180
  baseURL?: string | undefined;
179
181
  temperature?: number | undefined;
180
182
  sleep?: number | undefined;
181
- prePrompt?: string | undefined;
182
- postPrompt?: string | undefined;
183
183
  prePromptReplace?: string | undefined;
184
184
  postPromptReplace?: string | undefined;
185
185
  prePromptAppend?: string | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gringow/gringow",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "main": "./dist/index.mjs",
5
5
  "module": "./dist/index.mjs",
6
6
  "types": "./dist/index.d.mts",
@@ -10,10 +10,10 @@
10
10
  "require": "./dist/index.mjs",
11
11
  "import": "./dist/index.mjs"
12
12
  },
13
- "./flat-template-string": {
14
- "types": "./dist/flat-template-string.d.mts",
15
- "require": "./dist/flat-template-string.mjs",
16
- "import": "./dist/flat-template-string.mjs"
13
+ "./interpolate-template": {
14
+ "types": "./dist/interpolate-template.d.mts",
15
+ "require": "./dist/interpolate-template.mjs",
16
+ "import": "./dist/interpolate-template.mjs"
17
17
  },
18
18
  "./browser": {
19
19
  "types": "./dist/browser.d.mts",
@@ -1,14 +0,0 @@
1
- /**
2
- * Flattens a template string with its values into a single flat string
3
- *
4
- * @param givenStrings - The template strings
5
- * @param givenValues - The values to be interpolated
6
- * @returns The flattened string
7
- *
8
- * @example
9
- * const result = flatTemplateString`Hello ${name}!`
10
- * // result = 'Hello John!'
11
- */
12
- declare function flatTemplateString(givenStrings: TemplateStringsArray, givenValues: Array<unknown>): string;
13
-
14
- export { flatTemplateString };
@@ -1,16 +0,0 @@
1
- // src/flat-template-string.ts
2
- function flatTemplateString(givenStrings, givenValues) {
3
- const strings = [...givenStrings.raw];
4
- const values = [...givenValues];
5
- const flatted = strings.reduce((acc, item, index) => {
6
- acc += String(item ?? "");
7
- if (index < values.length) {
8
- const value = values[index];
9
- acc += String(value ?? "");
10
- }
11
- return acc;
12
- }, "");
13
- return flatted;
14
- }
15
-
16
- export { flatTemplateString };