@jterrazz/intelligence 2.0.0 → 3.0.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 (113) hide show
  1. package/README.md +56 -268
  2. package/dist/index.cjs +652 -2017
  3. package/dist/index.d.ts +5 -15
  4. package/dist/index.js +5 -33
  5. package/dist/index.js.map +1 -1
  6. package/dist/middleware/__tests__/logging.middleware.test.js +390 -0
  7. package/dist/middleware/__tests__/logging.middleware.test.js.map +1 -0
  8. package/dist/middleware/logging.middleware.d.ts +21 -0
  9. package/dist/middleware/logging.middleware.js +296 -0
  10. package/dist/middleware/logging.middleware.js.map +1 -0
  11. package/dist/parsing/__tests__/create-schema-prompt.test.js +53 -0
  12. package/dist/parsing/__tests__/create-schema-prompt.test.js.map +1 -0
  13. package/dist/parsing/__tests__/parse-object.test.d.ts +1 -0
  14. package/dist/parsing/__tests__/parse-object.test.js +193 -0
  15. package/dist/parsing/__tests__/parse-object.test.js.map +1 -0
  16. package/dist/parsing/__tests__/parse-text.test.d.ts +1 -0
  17. package/dist/parsing/__tests__/parse-text.test.js +167 -0
  18. package/dist/parsing/__tests__/parse-text.test.js.map +1 -0
  19. package/dist/parsing/create-schema-prompt.d.ts +28 -0
  20. package/dist/parsing/create-schema-prompt.js +42 -0
  21. package/dist/parsing/create-schema-prompt.js.map +1 -0
  22. package/dist/parsing/parse-object.d.ts +33 -0
  23. package/dist/parsing/parse-object.js +360 -0
  24. package/dist/parsing/parse-object.js.map +1 -0
  25. package/dist/parsing/parse-text.d.ts +14 -0
  26. package/dist/parsing/parse-text.js +76 -0
  27. package/dist/parsing/parse-text.js.map +1 -0
  28. package/dist/providers/openrouter.provider.d.ts +36 -0
  29. package/dist/providers/openrouter.provider.js +58 -0
  30. package/dist/providers/openrouter.provider.js.map +1 -0
  31. package/package.json +14 -15
  32. package/dist/adapters/agents/chat-agent.adapter.d.ts +0 -27
  33. package/dist/adapters/agents/chat-agent.adapter.js +0 -356
  34. package/dist/adapters/agents/chat-agent.adapter.js.map +0 -1
  35. package/dist/adapters/agents/resilient-agent.adapter.d.ts +0 -20
  36. package/dist/adapters/agents/resilient-agent.adapter.js +0 -263
  37. package/dist/adapters/agents/resilient-agent.adapter.js.map +0 -1
  38. package/dist/adapters/agents/tool-agent.adapter.d.ts +0 -30
  39. package/dist/adapters/agents/tool-agent.adapter.js +0 -400
  40. package/dist/adapters/agents/tool-agent.adapter.js.map +0 -1
  41. package/dist/adapters/models/openrouter-model.adapter.d.ts +0 -23
  42. package/dist/adapters/models/openrouter-model.adapter.js +0 -148
  43. package/dist/adapters/models/openrouter-model.adapter.js.map +0 -1
  44. package/dist/adapters/prompts/__tests__/__snapshots__/presets.test.ts.snap +0 -120
  45. package/dist/adapters/prompts/__tests__/presets.test.js +0 -31
  46. package/dist/adapters/prompts/__tests__/presets.test.js.map +0 -1
  47. package/dist/adapters/prompts/library/categories/domain.d.ts +0 -11
  48. package/dist/adapters/prompts/library/categories/domain.js +0 -12
  49. package/dist/adapters/prompts/library/categories/domain.js.map +0 -1
  50. package/dist/adapters/prompts/library/categories/format.d.ts +0 -10
  51. package/dist/adapters/prompts/library/categories/format.js +0 -11
  52. package/dist/adapters/prompts/library/categories/format.js.map +0 -1
  53. package/dist/adapters/prompts/library/categories/foundations.d.ts +0 -12
  54. package/dist/adapters/prompts/library/categories/foundations.js +0 -13
  55. package/dist/adapters/prompts/library/categories/foundations.js.map +0 -1
  56. package/dist/adapters/prompts/library/categories/language.d.ts +0 -11
  57. package/dist/adapters/prompts/library/categories/language.js +0 -12
  58. package/dist/adapters/prompts/library/categories/language.js.map +0 -1
  59. package/dist/adapters/prompts/library/categories/persona.d.ts +0 -13
  60. package/dist/adapters/prompts/library/categories/persona.js +0 -14
  61. package/dist/adapters/prompts/library/categories/persona.js.map +0 -1
  62. package/dist/adapters/prompts/library/categories/response.d.ts +0 -9
  63. package/dist/adapters/prompts/library/categories/response.js +0 -10
  64. package/dist/adapters/prompts/library/categories/response.js.map +0 -1
  65. package/dist/adapters/prompts/library/categories/tone.d.ts +0 -9
  66. package/dist/adapters/prompts/library/categories/tone.js +0 -10
  67. package/dist/adapters/prompts/library/categories/tone.js.map +0 -1
  68. package/dist/adapters/prompts/library/categories/verbosity.d.ts +0 -8
  69. package/dist/adapters/prompts/library/categories/verbosity.js +0 -9
  70. package/dist/adapters/prompts/library/categories/verbosity.js.map +0 -1
  71. package/dist/adapters/prompts/library/index.d.ts +0 -68
  72. package/dist/adapters/prompts/library/index.js +0 -26
  73. package/dist/adapters/prompts/library/index.js.map +0 -1
  74. package/dist/adapters/prompts/library/presets.d.ts +0 -17
  75. package/dist/adapters/prompts/library/presets.js +0 -45
  76. package/dist/adapters/prompts/library/presets.js.map +0 -1
  77. package/dist/adapters/prompts/system-prompt.adapter.d.ts +0 -9
  78. package/dist/adapters/prompts/system-prompt.adapter.js +0 -57
  79. package/dist/adapters/prompts/system-prompt.adapter.js.map +0 -1
  80. package/dist/adapters/prompts/user-prompt.adapter.d.ts +0 -9
  81. package/dist/adapters/prompts/user-prompt.adapter.js +0 -57
  82. package/dist/adapters/prompts/user-prompt.adapter.js.map +0 -1
  83. package/dist/adapters/providers/openrouter-provider.adapter.d.ts +0 -34
  84. package/dist/adapters/providers/openrouter-provider.adapter.js +0 -57
  85. package/dist/adapters/providers/openrouter-provider.adapter.js.map +0 -1
  86. package/dist/adapters/tools/safe-tool.adapter.d.ts +0 -27
  87. package/dist/adapters/tools/safe-tool.adapter.js +0 -283
  88. package/dist/adapters/tools/safe-tool.adapter.js.map +0 -1
  89. package/dist/adapters/utils/__tests__/structured-response-parser.test.js +0 -289
  90. package/dist/adapters/utils/__tests__/structured-response-parser.test.js.map +0 -1
  91. package/dist/adapters/utils/structured-response-parser-error.d.ts +0 -8
  92. package/dist/adapters/utils/structured-response-parser-error.js +0 -136
  93. package/dist/adapters/utils/structured-response-parser-error.js.map +0 -1
  94. package/dist/adapters/utils/structured-response-parser.d.ts +0 -60
  95. package/dist/adapters/utils/structured-response-parser.js +0 -347
  96. package/dist/adapters/utils/structured-response-parser.js.map +0 -1
  97. package/dist/ports/agent.port.d.ts +0 -17
  98. package/dist/ports/agent.port.js +0 -7
  99. package/dist/ports/agent.port.js.map +0 -1
  100. package/dist/ports/model.port.d.ts +0 -37
  101. package/dist/ports/model.port.js +0 -5
  102. package/dist/ports/model.port.js.map +0 -1
  103. package/dist/ports/prompt.port.d.ts +0 -9
  104. package/dist/ports/prompt.port.js +0 -5
  105. package/dist/ports/prompt.port.js.map +0 -1
  106. package/dist/ports/provider.port.d.ts +0 -13
  107. package/dist/ports/provider.port.js +0 -5
  108. package/dist/ports/provider.port.js.map +0 -1
  109. package/dist/ports/tool.port.d.ts +0 -11
  110. package/dist/ports/tool.port.js +0 -5
  111. package/dist/ports/tool.port.js.map +0 -1
  112. /package/dist/{adapters/prompts/__tests__/presets.test.d.ts → middleware/__tests__/logging.middleware.test.d.ts} +0 -0
  113. /package/dist/{adapters/utils/__tests__/structured-response-parser.test.d.ts → parsing/__tests__/create-schema-prompt.test.d.ts} +0 -0
@@ -0,0 +1,167 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { parseText } from '../parse-text.js';
3
+ describe('parseText', function() {
4
+ describe('empty and basic input', function() {
5
+ it('returns empty string for empty input', function() {
6
+ expect(parseText('')).toBe('');
7
+ });
8
+ it('returns trimmed text for simple input', function() {
9
+ expect(parseText(' hello world ')).toBe('hello world');
10
+ });
11
+ it('preserves newlines', function() {
12
+ expect(parseText('hello\nworld')).toBe('hello\nworld');
13
+ });
14
+ });
15
+ describe('BOM handling', function() {
16
+ it('removes BOM character at start', function() {
17
+ expect(parseText('\uFEFFhello')).toBe('hello');
18
+ });
19
+ it('removes BOM in middle of text (via invisible char removal)', function() {
20
+ expect(parseText('hello\uFEFFworld')).toBe('helloworld');
21
+ });
22
+ });
23
+ describe('line ending normalization', function() {
24
+ it('converts CRLF to LF', function() {
25
+ expect(parseText('hello\r\nworld')).toBe('hello\nworld');
26
+ });
27
+ it('converts standalone CR to LF', function() {
28
+ expect(parseText('hello\rworld')).toBe('hello\nworld');
29
+ });
30
+ });
31
+ describe('AI citation removal', function() {
32
+ it('removes oaicite markers', function() {
33
+ expect(parseText('Some text (oaicite:0){index=0} more text')).toBe('Some text more text');
34
+ });
35
+ it('removes multiple citation markers', function() {
36
+ expect(parseText('Text (oaicite:1){index=1} and (oaicite:2){index=2} here')).toBe('Text and here');
37
+ });
38
+ });
39
+ describe('invisible character removal', function() {
40
+ it('removes zero-width space', function() {
41
+ expect(parseText('hello\u200Bworld')).toBe('helloworld');
42
+ });
43
+ it('removes zero-width non-joiner', function() {
44
+ expect(parseText('hello\u200Cworld')).toBe('helloworld');
45
+ });
46
+ it('removes soft hyphen', function() {
47
+ expect(parseText('hello\u00ADworld')).toBe('helloworld');
48
+ });
49
+ it('removes direction marks', function() {
50
+ expect(parseText('hello\u200E\u200Fworld')).toBe('helloworld');
51
+ });
52
+ it('removes word joiner', function() {
53
+ expect(parseText('hello\u2060world')).toBe('helloworld');
54
+ });
55
+ });
56
+ describe('ASCII control character removal', function() {
57
+ it('removes null character', function() {
58
+ expect(parseText('hello\x00world')).toBe('helloworld');
59
+ });
60
+ it('removes bell character', function() {
61
+ expect(parseText('hello\x07world')).toBe('helloworld');
62
+ });
63
+ it('removes delete character', function() {
64
+ expect(parseText('hello\x7Fworld')).toBe('helloworld');
65
+ });
66
+ it('preserves tab and newline', function() {
67
+ expect(parseText('hello\tworld\n!')).toBe('hello\tworld\n!');
68
+ });
69
+ });
70
+ describe('em/en dash normalization', function() {
71
+ it('converts em dash with spaces to comma', function() {
72
+ expect(parseText('hello — world')).toBe('hello, world');
73
+ });
74
+ it('converts en dash with spaces to comma', function() {
75
+ expect(parseText('hello – world')).toBe('hello, world');
76
+ });
77
+ it('converts horizontal bar with spaces to comma', function() {
78
+ expect(parseText('hello ― world')).toBe('hello, world');
79
+ });
80
+ it('converts figure dash with spaces to comma', function() {
81
+ expect(parseText('hello ‒ world')).toBe('hello, world');
82
+ });
83
+ it('converts em dash without spaces to comma', function() {
84
+ expect(parseText('disparaître—ne laissant')).toBe('disparaître, ne laissant');
85
+ });
86
+ it('can be disabled via options', function() {
87
+ expect(parseText('hello — world', {
88
+ normalizeEmDashesToCommas: false
89
+ })).toBe('hello — world');
90
+ });
91
+ it('preserves em dash when disabled (no spaces)', function() {
92
+ expect(parseText('word—word', {
93
+ normalizeEmDashesToCommas: false
94
+ })).toBe('word—word');
95
+ });
96
+ });
97
+ describe('space-like character normalization', function() {
98
+ it('converts non-breaking space to regular space', function() {
99
+ expect(parseText('hello\u00A0world')).toBe('hello world');
100
+ });
101
+ it('converts em space to regular space', function() {
102
+ expect(parseText('hello\u2003world')).toBe('hello world');
103
+ });
104
+ it('converts narrow no-break space to regular space', function() {
105
+ expect(parseText('hello\u202Fworld')).toBe('hello world');
106
+ });
107
+ it('converts ideographic space to regular space', function() {
108
+ expect(parseText('hello\u3000world')).toBe('hello world');
109
+ });
110
+ });
111
+ describe('typography normalization', function() {
112
+ it('converts left single quote to straight quote', function() {
113
+ expect(parseText('it\u2018s')).toBe("it's");
114
+ });
115
+ it('converts right single quote to straight quote', function() {
116
+ expect(parseText('it\u2019s')).toBe("it's");
117
+ });
118
+ it('converts left double quote to straight quote', function() {
119
+ expect(parseText('\u201CHello\u201D')).toBe('"Hello"');
120
+ });
121
+ it('converts em dash to comma', function() {
122
+ expect(parseText('word\u2014word')).toBe('word, word');
123
+ });
124
+ it('converts en dash to comma', function() {
125
+ expect(parseText('2020\u20132021')).toBe('2020, 2021');
126
+ });
127
+ it('converts ellipsis to three dots', function() {
128
+ expect(parseText('wait\u2026')).toBe('wait...');
129
+ });
130
+ it('converts bullet point to hyphen', function() {
131
+ expect(parseText('\u2022 item')).toBe('- item');
132
+ });
133
+ });
134
+ describe('multiple space collapsing', function() {
135
+ it('collapses multiple spaces to single space', function() {
136
+ expect(parseText('hello world')).toBe('hello world');
137
+ });
138
+ it('trims leading and trailing spaces', function() {
139
+ expect(parseText(' hello world ')).toBe('hello world');
140
+ });
141
+ it('can be disabled via options', function() {
142
+ expect(parseText('hello world', {
143
+ collapseSpaces: false
144
+ })).toBe('hello world');
145
+ });
146
+ });
147
+ describe('NFKC normalization', function() {
148
+ it('normalizes fullwidth characters', function() {
149
+ expect(parseText('\uFF21\uFF22\uFF23')).toBe('ABC');
150
+ });
151
+ it('normalizes ligatures', function() {
152
+ expect(parseText('\uFB01le')).toBe('file');
153
+ });
154
+ });
155
+ describe('combined scenarios', function() {
156
+ it('handles AI-generated text with multiple issues', function() {
157
+ var input = '\uFEFF Hello\u2019s world (oaicite:0){index=0} \u2014 with\u00A0spaces ';
158
+ expect(parseText(input)).toBe("Hello's world, with spaces");
159
+ });
160
+ it('handles markdown with smart quotes and dashes', function() {
161
+ var input = '\u201CThis is a quote\u201D \u2014 Author';
162
+ expect(parseText(input)).toBe('"This is a quote", Author');
163
+ });
164
+ });
165
+ });
166
+
167
+ //# sourceMappingURL=parse-text.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/parsing/__tests__/parse-text.test.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest';\n\nimport { parseText } from '../parse-text.js';\n\ndescribe('parseText', () => {\n describe('empty and basic input', () => {\n it('returns empty string for empty input', () => {\n expect(parseText('')).toBe('');\n });\n\n it('returns trimmed text for simple input', () => {\n expect(parseText(' hello world ')).toBe('hello world');\n });\n\n it('preserves newlines', () => {\n expect(parseText('hello\\nworld')).toBe('hello\\nworld');\n });\n });\n\n describe('BOM handling', () => {\n it('removes BOM character at start', () => {\n expect(parseText('\\uFEFFhello')).toBe('hello');\n });\n\n it('removes BOM in middle of text (via invisible char removal)', () => {\n expect(parseText('hello\\uFEFFworld')).toBe('helloworld');\n });\n });\n\n describe('line ending normalization', () => {\n it('converts CRLF to LF', () => {\n expect(parseText('hello\\r\\nworld')).toBe('hello\\nworld');\n });\n\n it('converts standalone CR to LF', () => {\n expect(parseText('hello\\rworld')).toBe('hello\\nworld');\n });\n });\n\n describe('AI citation removal', () => {\n it('removes oaicite markers', () => {\n expect(parseText('Some text (oaicite:0){index=0} more text')).toBe(\n 'Some text more text',\n );\n });\n\n it('removes multiple citation markers', () => {\n expect(parseText('Text (oaicite:1){index=1} and (oaicite:2){index=2} here')).toBe(\n 'Text and here',\n );\n });\n });\n\n describe('invisible character removal', () => {\n it('removes zero-width space', () => {\n expect(parseText('hello\\u200Bworld')).toBe('helloworld');\n });\n\n it('removes zero-width non-joiner', () => {\n expect(parseText('hello\\u200Cworld')).toBe('helloworld');\n });\n\n it('removes soft hyphen', () => {\n expect(parseText('hello\\u00ADworld')).toBe('helloworld');\n });\n\n it('removes direction marks', () => {\n expect(parseText('hello\\u200E\\u200Fworld')).toBe('helloworld');\n });\n\n it('removes word joiner', () => {\n expect(parseText('hello\\u2060world')).toBe('helloworld');\n });\n });\n\n describe('ASCII control character removal', () => {\n it('removes null character', () => {\n expect(parseText('hello\\x00world')).toBe('helloworld');\n });\n\n it('removes bell character', () => {\n expect(parseText('hello\\x07world')).toBe('helloworld');\n });\n\n it('removes delete character', () => {\n expect(parseText('hello\\x7Fworld')).toBe('helloworld');\n });\n\n it('preserves tab and newline', () => {\n expect(parseText('hello\\tworld\\n!')).toBe('hello\\tworld\\n!');\n });\n });\n\n describe('em/en dash normalization', () => {\n it('converts em dash with spaces to comma', () => {\n expect(parseText('hello — world')).toBe('hello, world');\n });\n\n it('converts en dash with spaces to comma', () => {\n expect(parseText('hello – world')).toBe('hello, world');\n });\n\n it('converts horizontal bar with spaces to comma', () => {\n expect(parseText('hello ― world')).toBe('hello, world');\n });\n\n it('converts figure dash with spaces to comma', () => {\n expect(parseText('hello ‒ world')).toBe('hello, world');\n });\n\n it('converts em dash without spaces to comma', () => {\n expect(parseText('disparaître—ne laissant')).toBe('disparaître, ne laissant');\n });\n\n it('can be disabled via options', () => {\n expect(parseText('hello — world', { normalizeEmDashesToCommas: false })).toBe(\n 'hello — world',\n );\n });\n\n it('preserves em dash when disabled (no spaces)', () => {\n expect(parseText('word—word', { normalizeEmDashesToCommas: false })).toBe('word—word');\n });\n });\n\n describe('space-like character normalization', () => {\n it('converts non-breaking space to regular space', () => {\n expect(parseText('hello\\u00A0world')).toBe('hello world');\n });\n\n it('converts em space to regular space', () => {\n expect(parseText('hello\\u2003world')).toBe('hello world');\n });\n\n it('converts narrow no-break space to regular space', () => {\n expect(parseText('hello\\u202Fworld')).toBe('hello world');\n });\n\n it('converts ideographic space to regular space', () => {\n expect(parseText('hello\\u3000world')).toBe('hello world');\n });\n });\n\n describe('typography normalization', () => {\n it('converts left single quote to straight quote', () => {\n expect(parseText('it\\u2018s')).toBe(\"it's\");\n });\n\n it('converts right single quote to straight quote', () => {\n expect(parseText('it\\u2019s')).toBe(\"it's\");\n });\n\n it('converts left double quote to straight quote', () => {\n expect(parseText('\\u201CHello\\u201D')).toBe('\"Hello\"');\n });\n\n it('converts em dash to comma', () => {\n expect(parseText('word\\u2014word')).toBe('word, word');\n });\n\n it('converts en dash to comma', () => {\n expect(parseText('2020\\u20132021')).toBe('2020, 2021');\n });\n\n it('converts ellipsis to three dots', () => {\n expect(parseText('wait\\u2026')).toBe('wait...');\n });\n\n it('converts bullet point to hyphen', () => {\n expect(parseText('\\u2022 item')).toBe('- item');\n });\n });\n\n describe('multiple space collapsing', () => {\n it('collapses multiple spaces to single space', () => {\n expect(parseText('hello world')).toBe('hello world');\n });\n\n it('trims leading and trailing spaces', () => {\n expect(parseText(' hello world ')).toBe('hello world');\n });\n\n it('can be disabled via options', () => {\n expect(parseText('hello world', { collapseSpaces: false })).toBe('hello world');\n });\n });\n\n describe('NFKC normalization', () => {\n it('normalizes fullwidth characters', () => {\n expect(parseText('\\uFF21\\uFF22\\uFF23')).toBe('ABC');\n });\n\n it('normalizes ligatures', () => {\n expect(parseText('\\uFB01le')).toBe('file');\n });\n });\n\n describe('combined scenarios', () => {\n it('handles AI-generated text with multiple issues', () => {\n const input =\n '\\uFEFF Hello\\u2019s world (oaicite:0){index=0} \\u2014 with\\u00A0spaces ';\n expect(parseText(input)).toBe(\"Hello's world, with spaces\");\n });\n\n it('handles markdown with smart quotes and dashes', () => {\n const input = '\\u201CThis is a quote\\u201D \\u2014 Author';\n expect(parseText(input)).toBe('\"This is a quote\", Author');\n });\n });\n});\n"],"names":["describe","expect","it","parseText","toBe","normalizeEmDashesToCommas","collapseSpaces","input"],"mappings":"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"}
@@ -0,0 +1,28 @@
1
+ import { z } from 'zod/v4';
2
+ /**
3
+ * Creates a system prompt that instructs the model to output structured data
4
+ * matching the provided Zod schema.
5
+ *
6
+ * Use this with `generateText` when the provider doesn't support native
7
+ * structured outputs, then parse the response with `parseObject`.
8
+ *
9
+ * @param schema - A Zod schema defining the expected output structure
10
+ * @returns A system prompt string with JSON schema instructions
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { generateText } from 'ai';
15
+ * import { createSchemaPrompt, parseObject } from '@jterrazz/intelligence';
16
+ *
17
+ * const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
18
+ *
19
+ * const { text } = await generateText({
20
+ * model,
21
+ * prompt: 'Generate an article about TypeScript',
22
+ * system: createSchemaPrompt(schema),
23
+ * });
24
+ *
25
+ * const result = parseObject(text, schema);
26
+ * ```
27
+ */
28
+ export declare function createSchemaPrompt<T>(schema: z.ZodType<T>): string;
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod/v4';
2
+ /**
3
+ * Creates a system prompt that instructs the model to output structured data
4
+ * matching the provided Zod schema.
5
+ *
6
+ * Use this with `generateText` when the provider doesn't support native
7
+ * structured outputs, then parse the response with `parseObject`.
8
+ *
9
+ * @param schema - A Zod schema defining the expected output structure
10
+ * @returns A system prompt string with JSON schema instructions
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { generateText } from 'ai';
15
+ * import { createSchemaPrompt, parseObject } from '@jterrazz/intelligence';
16
+ *
17
+ * const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
18
+ *
19
+ * const { text } = await generateText({
20
+ * model,
21
+ * prompt: 'Generate an article about TypeScript',
22
+ * system: createSchemaPrompt(schema),
23
+ * });
24
+ *
25
+ * const result = parseObject(text, schema);
26
+ * ```
27
+ */ export function createSchemaPrompt(schema) {
28
+ var jsonSchema = z.toJSONSchema(schema);
29
+ var schemaJson = JSON.stringify(jsonSchema, null, 2);
30
+ var isPrimitive = [
31
+ 'boolean',
32
+ 'integer',
33
+ 'number',
34
+ 'string'
35
+ ].includes(jsonSchema.type);
36
+ if (isPrimitive) {
37
+ return "<OUTPUT_FORMAT>\nYou must respond with a ".concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(schemaJson, "\n```\n\nYour response should be only the ").concat(jsonSchema.type, " value, without any JSON wrapping or additional text.\n</OUTPUT_FORMAT>");
38
+ }
39
+ return "<OUTPUT_FORMAT>\nYou must respond with valid JSON that matches this JSON schema:\n\n```json\n".concat(schemaJson, "\n```\n\nYour response must be parseable JSON that validates against this schema. Do not include any text outside the JSON.\n</OUTPUT_FORMAT>");
40
+ }
41
+
42
+ //# sourceMappingURL=create-schema-prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/parsing/create-schema-prompt.ts"],"sourcesContent":["import { z } from 'zod/v4';\n\n/**\n * Creates a system prompt that instructs the model to output structured data\n * matching the provided Zod schema.\n *\n * Use this with `generateText` when the provider doesn't support native\n * structured outputs, then parse the response with `parseObject`.\n *\n * @param schema - A Zod schema defining the expected output structure\n * @returns A system prompt string with JSON schema instructions\n *\n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { createSchemaPrompt, parseObject } from '@jterrazz/intelligence';\n *\n * const schema = z.object({ title: z.string(), tags: z.array(z.string()) });\n *\n * const { text } = await generateText({\n * model,\n * prompt: 'Generate an article about TypeScript',\n * system: createSchemaPrompt(schema),\n * });\n *\n * const result = parseObject(text, schema);\n * ```\n */\nexport function createSchemaPrompt<T>(schema: z.ZodType<T>): string {\n const jsonSchema = z.toJSONSchema(schema);\n const schemaJson = JSON.stringify(jsonSchema, null, 2);\n\n const isPrimitive = ['boolean', 'integer', 'number', 'string'].includes(\n jsonSchema.type as string,\n );\n\n if (isPrimitive) {\n return `<OUTPUT_FORMAT>\nYou must respond with a ${jsonSchema.type} value that matches this schema:\n\n\\`\\`\\`json\n${schemaJson}\n\\`\\`\\`\n\nYour response should be only the ${jsonSchema.type} value, without any JSON wrapping or additional text.\n</OUTPUT_FORMAT>`;\n }\n\n return `<OUTPUT_FORMAT>\nYou must respond with valid JSON that matches this JSON schema:\n\n\\`\\`\\`json\n${schemaJson}\n\\`\\`\\`\n\nYour response must be parseable JSON that validates against this schema. Do not include any text outside the JSON.\n</OUTPUT_FORMAT>`;\n}\n"],"names":["z","createSchemaPrompt","schema","jsonSchema","toJSONSchema","schemaJson","JSON","stringify","isPrimitive","includes","type"],"mappings":"AAAA,SAASA,CAAC,QAAQ,SAAS;AAE3B;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,SAASC,mBAAsBC,MAAoB;IACtD,IAAMC,aAAaH,EAAEI,YAAY,CAACF;IAClC,IAAMG,aAAaC,KAAKC,SAAS,CAACJ,YAAY,MAAM;IAEpD,IAAMK,cAAc;QAAC;QAAW;QAAW;QAAU;KAAS,CAACC,QAAQ,CACnEN,WAAWO,IAAI;IAGnB,IAAIF,aAAa;QACb,OAAO,AAAC,4CAIdH,OAHwBF,WAAWO,IAAI,EAAC,iDAMPP,OAHjCE,YAAW,8CAGsC,OAAhBF,WAAWO,IAAI,EAAC;IAE/C;IAEA,OAAO,AAAC,gGAIC,OAAXL,YAAW;AAKb"}
@@ -0,0 +1,33 @@
1
+ import { z } from 'zod/v4';
2
+ /**
3
+ * Error thrown when object parsing fails.
4
+ * Contains the original text for debugging purposes.
5
+ */
6
+ export declare class ParseObjectError extends Error {
7
+ readonly cause?: unknown | undefined;
8
+ readonly text?: string | undefined;
9
+ readonly name = "ParseObjectError";
10
+ constructor(message: string, cause?: unknown | undefined, text?: string | undefined);
11
+ }
12
+ /**
13
+ * Parses AI-generated text into structured data validated against a Zod schema.
14
+ *
15
+ * Handles common AI response formats:
16
+ * - JSON wrapped in markdown code blocks
17
+ * - JSON embedded in prose text
18
+ * - Malformed JSON (auto-repaired)
19
+ * - Escaped unicode and special characters
20
+ *
21
+ * @param text - The raw AI response text
22
+ * @param schema - A Zod schema to validate and type the result
23
+ * @returns The parsed and validated data
24
+ * @throws {ParseObjectError} When parsing or validation fails
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
29
+ * const result = parseObject(aiResponse, schema);
30
+ * // result is typed as { title: string; tags: string[] }
31
+ * ```
32
+ */
33
+ export declare function parseObject<T>(text: string, schema: z.ZodSchema<T>): T;
@@ -0,0 +1,360 @@
1
+ function _array_like_to_array(arr, len) {
2
+ if (len == null || len > arr.length) len = arr.length;
3
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
+ return arr2;
5
+ }
6
+ function _array_with_holes(arr) {
7
+ if (Array.isArray(arr)) return arr;
8
+ }
9
+ function _assert_this_initialized(self) {
10
+ if (self === void 0) {
11
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
12
+ }
13
+ return self;
14
+ }
15
+ function _call_super(_this, derived, args) {
16
+ derived = _get_prototype_of(derived);
17
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
18
+ }
19
+ function _class_call_check(instance, Constructor) {
20
+ if (!(instance instanceof Constructor)) {
21
+ throw new TypeError("Cannot call a class as a function");
22
+ }
23
+ }
24
+ function _construct(Parent, args, Class) {
25
+ if (_is_native_reflect_construct()) {
26
+ _construct = Reflect.construct;
27
+ } else {
28
+ _construct = function construct(Parent, args, Class) {
29
+ var a = [
30
+ null
31
+ ];
32
+ a.push.apply(a, args);
33
+ var Constructor = Function.bind.apply(Parent, a);
34
+ var instance = new Constructor();
35
+ if (Class) _set_prototype_of(instance, Class.prototype);
36
+ return instance;
37
+ };
38
+ }
39
+ return _construct.apply(null, arguments);
40
+ }
41
+ function _define_property(obj, key, value) {
42
+ if (key in obj) {
43
+ Object.defineProperty(obj, key, {
44
+ value: value,
45
+ enumerable: true,
46
+ configurable: true,
47
+ writable: true
48
+ });
49
+ } else {
50
+ obj[key] = value;
51
+ }
52
+ return obj;
53
+ }
54
+ function _get_prototype_of(o) {
55
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
56
+ return o.__proto__ || Object.getPrototypeOf(o);
57
+ };
58
+ return _get_prototype_of(o);
59
+ }
60
+ function _inherits(subClass, superClass) {
61
+ if (typeof superClass !== "function" && superClass !== null) {
62
+ throw new TypeError("Super expression must either be null or a function");
63
+ }
64
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
65
+ constructor: {
66
+ value: subClass,
67
+ writable: true,
68
+ configurable: true
69
+ }
70
+ });
71
+ if (superClass) _set_prototype_of(subClass, superClass);
72
+ }
73
+ function _instanceof(left, right) {
74
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
75
+ return !!right[Symbol.hasInstance](left);
76
+ } else {
77
+ return left instanceof right;
78
+ }
79
+ }
80
+ function _is_native_function(fn) {
81
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
82
+ }
83
+ function _iterable_to_array_limit(arr, i) {
84
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
85
+ if (_i == null) return;
86
+ var _arr = [];
87
+ var _n = true;
88
+ var _d = false;
89
+ var _s, _e;
90
+ try {
91
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
92
+ _arr.push(_s.value);
93
+ if (i && _arr.length === i) break;
94
+ }
95
+ } catch (err) {
96
+ _d = true;
97
+ _e = err;
98
+ } finally{
99
+ try {
100
+ if (!_n && _i["return"] != null) _i["return"]();
101
+ } finally{
102
+ if (_d) throw _e;
103
+ }
104
+ }
105
+ return _arr;
106
+ }
107
+ function _non_iterable_rest() {
108
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
109
+ }
110
+ function _possible_constructor_return(self, call) {
111
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
112
+ return call;
113
+ }
114
+ return _assert_this_initialized(self);
115
+ }
116
+ function _set_prototype_of(o, p) {
117
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
118
+ o.__proto__ = p;
119
+ return o;
120
+ };
121
+ return _set_prototype_of(o, p);
122
+ }
123
+ function _sliced_to_array(arr, i) {
124
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
125
+ }
126
+ function _type_of(obj) {
127
+ "@swc/helpers - typeof";
128
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
129
+ }
130
+ function _unsupported_iterable_to_array(o, minLen) {
131
+ if (!o) return;
132
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
133
+ var n = Object.prototype.toString.call(o).slice(8, -1);
134
+ if (n === "Object" && o.constructor) n = o.constructor.name;
135
+ if (n === "Map" || n === "Set") return Array.from(n);
136
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
137
+ }
138
+ function _wrap_native_super(Class) {
139
+ var _cache = typeof Map === "function" ? new Map() : undefined;
140
+ _wrap_native_super = function wrapNativeSuper(Class) {
141
+ if (Class === null || !_is_native_function(Class)) return Class;
142
+ if (typeof Class !== "function") {
143
+ throw new TypeError("Super expression must either be null or a function");
144
+ }
145
+ if (typeof _cache !== "undefined") {
146
+ if (_cache.has(Class)) return _cache.get(Class);
147
+ _cache.set(Class, Wrapper);
148
+ }
149
+ function Wrapper() {
150
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
151
+ }
152
+ Wrapper.prototype = Object.create(Class.prototype, {
153
+ constructor: {
154
+ value: Wrapper,
155
+ enumerable: false,
156
+ writable: true,
157
+ configurable: true
158
+ }
159
+ });
160
+ return _set_prototype_of(Wrapper, Class);
161
+ };
162
+ return _wrap_native_super(Class);
163
+ }
164
+ function _is_native_reflect_construct() {
165
+ try {
166
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
167
+ } catch (_) {}
168
+ return (_is_native_reflect_construct = function() {
169
+ return !!result;
170
+ })();
171
+ }
172
+ import { jsonrepair } from 'jsonrepair';
173
+ import { z } from 'zod/v4';
174
+ /**
175
+ * Error thrown when object parsing fails.
176
+ * Contains the original text for debugging purposes.
177
+ */ export var ParseObjectError = /*#__PURE__*/ function(Error1) {
178
+ "use strict";
179
+ _inherits(ParseObjectError, Error1);
180
+ function ParseObjectError(message, cause, text) {
181
+ _class_call_check(this, ParseObjectError);
182
+ var _this;
183
+ _this = _call_super(this, ParseObjectError, [
184
+ message
185
+ ]), _define_property(_this, "cause", void 0), _define_property(_this, "text", void 0), _define_property(_this, "name", void 0), _this.cause = cause, _this.text = text, _this.name = 'ParseObjectError';
186
+ return _this;
187
+ }
188
+ return ParseObjectError;
189
+ }(_wrap_native_super(Error));
190
+ /**
191
+ * Parses AI-generated text into structured data validated against a Zod schema.
192
+ *
193
+ * Handles common AI response formats:
194
+ * - JSON wrapped in markdown code blocks
195
+ * - JSON embedded in prose text
196
+ * - Malformed JSON (auto-repaired)
197
+ * - Escaped unicode and special characters
198
+ *
199
+ * @param text - The raw AI response text
200
+ * @param schema - A Zod schema to validate and type the result
201
+ * @returns The parsed and validated data
202
+ * @throws {ParseObjectError} When parsing or validation fails
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
207
+ * const result = parseObject(aiResponse, schema);
208
+ * // result is typed as { title: string; tags: string[] }
209
+ * ```
210
+ */ export function parseObject(text, schema) {
211
+ try {
212
+ var jsonString = extractJsonString(text);
213
+ var extracted = extractBySchemaType(jsonString, schema, text);
214
+ var unescaped = unescapeJsonValues(extracted);
215
+ return schema.parse(unescaped);
216
+ } catch (error) {
217
+ if (_instanceof(error, ParseObjectError)) {
218
+ throw error;
219
+ }
220
+ if (_instanceof(error, z.ZodError)) {
221
+ throw new ParseObjectError('Failed to validate response against schema', error, text);
222
+ }
223
+ throw error;
224
+ }
225
+ }
226
+ var MARKDOWN_CODE_BLOCK_RE = /```(?:json)?\r?\n([^`]*?)\r?\n```/g;
227
+ function convertToPrimitive(value, schema) {
228
+ if (_instanceof(schema, z.ZodBoolean)) return Boolean(value);
229
+ if (_instanceof(schema, z.ZodNull)) return null;
230
+ if (_instanceof(schema, z.ZodNumber)) return Number(value);
231
+ if (_instanceof(schema, z.ZodString)) return String(value);
232
+ return value;
233
+ }
234
+ function extractArray(text, originalText) {
235
+ var start = text.indexOf('[');
236
+ var end = text.lastIndexOf(']');
237
+ if (start === -1 || end === -1) {
238
+ throw new ParseObjectError('No array found in response', undefined, originalText);
239
+ }
240
+ try {
241
+ var raw = text.slice(start, end + 1);
242
+ return JSON.parse(jsonrepair(raw));
243
+ } catch (error) {
244
+ throw new ParseObjectError('Failed to parse array JSON', error, originalText);
245
+ }
246
+ }
247
+ function extractBySchemaType(text, schema, originalText) {
248
+ if (_instanceof(schema, z.ZodArray)) {
249
+ return extractArray(text, originalText);
250
+ }
251
+ if (_instanceof(schema, z.ZodObject)) {
252
+ return extractObject(text, originalText);
253
+ }
254
+ if (_instanceof(schema, z.ZodBoolean) || _instanceof(schema, z.ZodNull) || _instanceof(schema, z.ZodNumber) || _instanceof(schema, z.ZodString)) {
255
+ return extractPrimitive(text, schema);
256
+ }
257
+ throw new ParseObjectError('Unsupported schema type', undefined, originalText);
258
+ }
259
+ function extractJsonFromCodeBlock(block) {
260
+ var content = block.replace(/```(?:json)?\r?\n([^`]*?)\r?\n```/, '$1').trim();
261
+ try {
262
+ JSON.parse(content);
263
+ return content;
264
+ } catch (e) {
265
+ return null;
266
+ }
267
+ }
268
+ function extractJsonString(text) {
269
+ var codeBlocks = text.match(MARKDOWN_CODE_BLOCK_RE);
270
+ if (codeBlocks && codeBlocks.length > 0) {
271
+ var validBlocks = codeBlocks.map(function(block) {
272
+ return extractJsonFromCodeBlock(block);
273
+ }).filter(function(block) {
274
+ return block !== null;
275
+ });
276
+ if (validBlocks.length > 0) {
277
+ return findLongestString(validBlocks);
278
+ }
279
+ }
280
+ var structures = findJsonStructures(text);
281
+ if (structures.length > 0) {
282
+ return findLongestString(structures);
283
+ }
284
+ return text.replace(/\s+/g, ' ').trim();
285
+ }
286
+ function extractObject(text, originalText) {
287
+ var start = text.indexOf('{');
288
+ var end = text.lastIndexOf('}');
289
+ if (start === -1 || end === -1) {
290
+ throw new ParseObjectError('No object found in response', undefined, originalText);
291
+ }
292
+ try {
293
+ var raw = text.slice(start, end + 1);
294
+ return JSON.parse(jsonrepair(raw));
295
+ } catch (error) {
296
+ throw new ParseObjectError('Failed to parse object JSON', error, originalText);
297
+ }
298
+ }
299
+ function extractPrimitive(text, schema) {
300
+ var trimmed = text.trim();
301
+ try {
302
+ return convertToPrimitive(JSON.parse(trimmed), schema);
303
+ } catch (e) {
304
+ return convertToPrimitive(trimmed, schema);
305
+ }
306
+ }
307
+ function findJsonStructures(text) {
308
+ var matches = [];
309
+ var depth = 0;
310
+ var start = -1;
311
+ for(var i = 0; i < text.length; i++){
312
+ var _char = text[i];
313
+ if (_char === '{' || _char === '[') {
314
+ if (depth === 0) start = i;
315
+ depth++;
316
+ } else if (_char === '}' || _char === ']') {
317
+ depth--;
318
+ if (depth === 0 && start !== -1) {
319
+ var candidate = text.slice(start, i + 1);
320
+ try {
321
+ JSON.parse(candidate);
322
+ matches.push(candidate);
323
+ } catch (e) {
324
+ // Invalid JSON, skip
325
+ }
326
+ }
327
+ }
328
+ }
329
+ return matches;
330
+ }
331
+ function findLongestString(strings) {
332
+ return strings.reduce(function(longest, current) {
333
+ return current.length > longest.length ? current : longest;
334
+ });
335
+ }
336
+ function unescapeJsonValues(json) {
337
+ if (typeof json === 'string') {
338
+ return unescapeString(json);
339
+ }
340
+ if (Array.isArray(json)) {
341
+ return json.map(unescapeJsonValues);
342
+ }
343
+ if ((typeof json === "undefined" ? "undefined" : _type_of(json)) === 'object' && json !== null) {
344
+ return Object.fromEntries(Object.entries(json).map(function(param) {
345
+ var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
346
+ return [
347
+ key,
348
+ unescapeJsonValues(value)
349
+ ];
350
+ }));
351
+ }
352
+ return json;
353
+ }
354
+ function unescapeString(text) {
355
+ return text.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\\\/g, '\\').replace(/\\u([0-9a-fA-F]{4})/g, function(_, code) {
356
+ return String.fromCharCode(Number.parseInt(code, 16));
357
+ });
358
+ }
359
+
360
+ //# sourceMappingURL=parse-object.js.map