@intella/sdk 0.0.1 → 0.0.2

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 (120) hide show
  1. package/dist/agent-manager.d.ts +47 -0
  2. package/dist/agent-manager.d.ts.map +1 -0
  3. package/dist/agent-manager.js +90 -0
  4. package/dist/agent-manager.js.map +1 -0
  5. package/dist/agents/base-agent.d.ts +41 -0
  6. package/dist/agents/base-agent.d.ts.map +1 -0
  7. package/dist/agents/base-agent.js +139 -0
  8. package/dist/agents/base-agent.js.map +1 -0
  9. package/dist/agents/claude-agent.d.ts +24 -0
  10. package/dist/agents/claude-agent.d.ts.map +1 -0
  11. package/dist/agents/claude-agent.js +65 -0
  12. package/dist/agents/claude-agent.js.map +1 -0
  13. package/dist/agents/codex-agent.d.ts +25 -0
  14. package/dist/agents/codex-agent.d.ts.map +1 -0
  15. package/dist/agents/codex-agent.js +62 -0
  16. package/dist/agents/codex-agent.js.map +1 -0
  17. package/dist/agents/intella-lite-agent.d.ts +21 -0
  18. package/dist/agents/intella-lite-agent.d.ts.map +1 -0
  19. package/dist/agents/intella-lite-agent.js +43 -0
  20. package/dist/agents/intella-lite-agent.js.map +1 -0
  21. package/dist/agents/opencode-agent.d.ts +20 -0
  22. package/dist/agents/opencode-agent.d.ts.map +1 -0
  23. package/dist/agents/opencode-agent.js +36 -0
  24. package/dist/agents/opencode-agent.js.map +1 -0
  25. package/dist/filesystem/agentfs-provider.d.ts +42 -0
  26. package/dist/filesystem/agentfs-provider.d.ts.map +1 -0
  27. package/dist/filesystem/agentfs-provider.js +308 -0
  28. package/dist/filesystem/agentfs-provider.js.map +1 -0
  29. package/dist/filesystem/base-provider.d.ts +55 -0
  30. package/dist/filesystem/base-provider.d.ts.map +1 -0
  31. package/dist/filesystem/base-provider.js +44 -0
  32. package/dist/filesystem/base-provider.js.map +1 -0
  33. package/dist/filesystem/index.d.ts +4 -0
  34. package/dist/filesystem/index.d.ts.map +1 -0
  35. package/{src/filesystem/index.ts → dist/filesystem/index.js} +1 -1
  36. package/dist/filesystem/index.js.map +1 -0
  37. package/dist/filesystem/memory-provider.d.ts +44 -0
  38. package/dist/filesystem/memory-provider.d.ts.map +1 -0
  39. package/dist/filesystem/memory-provider.js +227 -0
  40. package/dist/filesystem/memory-provider.js.map +1 -0
  41. package/dist/filesystem-manager.d.ts +75 -0
  42. package/dist/filesystem-manager.d.ts.map +1 -0
  43. package/dist/filesystem-manager.js +164 -0
  44. package/dist/filesystem-manager.js.map +1 -0
  45. package/dist/index.d.ts +18 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/{src/index.ts → dist/index.js} +3 -46
  48. package/dist/index.js.map +1 -0
  49. package/dist/orchestrator.d.ts +32 -0
  50. package/dist/orchestrator.d.ts.map +1 -0
  51. package/dist/orchestrator.js +136 -0
  52. package/dist/orchestrator.js.map +1 -0
  53. package/dist/sandbox/base-provider.d.ts +106 -0
  54. package/dist/sandbox/base-provider.d.ts.map +1 -0
  55. package/dist/sandbox/base-provider.js +73 -0
  56. package/dist/sandbox/base-provider.js.map +1 -0
  57. package/dist/sandbox/daytona-provider.d.ts +93 -0
  58. package/dist/sandbox/daytona-provider.d.ts.map +1 -0
  59. package/dist/sandbox/daytona-provider.js +378 -0
  60. package/dist/sandbox/daytona-provider.js.map +1 -0
  61. package/dist/sandbox/e2b-provider.d.ts +85 -0
  62. package/dist/sandbox/e2b-provider.d.ts.map +1 -0
  63. package/dist/sandbox/e2b-provider.js +342 -0
  64. package/dist/sandbox/e2b-provider.js.map +1 -0
  65. package/dist/sandbox/modal-provider.d.ts +92 -0
  66. package/dist/sandbox/modal-provider.d.ts.map +1 -0
  67. package/dist/sandbox/modal-provider.js +516 -0
  68. package/dist/sandbox/modal-provider.js.map +1 -0
  69. package/dist/sandbox-manager.d.ts +59 -0
  70. package/dist/sandbox-manager.d.ts.map +1 -0
  71. package/dist/sandbox-manager.js +141 -0
  72. package/dist/sandbox-manager.js.map +1 -0
  73. package/dist/sdk.d.ts +173 -0
  74. package/dist/sdk.d.ts.map +1 -0
  75. package/dist/sdk.js +273 -0
  76. package/dist/sdk.js.map +1 -0
  77. package/dist/types.d.ts +419 -0
  78. package/dist/types.d.ts.map +1 -0
  79. package/dist/types.js +2 -0
  80. package/dist/types.js.map +1 -0
  81. package/dist/utils/code-extractor.d.ts +103 -0
  82. package/dist/utils/code-extractor.d.ts.map +1 -0
  83. package/dist/utils/code-extractor.js +133 -0
  84. package/dist/utils/code-extractor.js.map +1 -0
  85. package/package.json +6 -1
  86. package/examples/claude-code/README.md +0 -178
  87. package/examples/claude-code/advanced-config.ts +0 -55
  88. package/examples/claude-code/basic-usage.ts +0 -56
  89. package/examples/claude-code/model-comparison.ts +0 -50
  90. package/examples/claude-code/orchestration.ts +0 -70
  91. package/examples/claude-code/streaming.ts +0 -69
  92. package/examples/claude-code/tsconfig.json +0 -19
  93. package/examples/code-extractor/README.md +0 -77
  94. package/examples/code-extractor/example.ts +0 -145
  95. package/examples/filesystem/basic-usage.ts +0 -84
  96. package/examples/integrated-task/README.md +0 -68
  97. package/examples/integrated-task/integrated-usage.ts +0 -193
  98. package/examples/integrated-task/simple-example.ts +0 -51
  99. package/examples/integrated-task/tsconfig.json +0 -19
  100. package/examples/sandbox/basic-usage.ts +0 -173
  101. package/src/agent-manager.ts +0 -104
  102. package/src/agents/base-agent.ts +0 -166
  103. package/src/agents/claude-agent.ts +0 -77
  104. package/src/agents/codex-agent.ts +0 -72
  105. package/src/agents/intella-lite-agent.ts +0 -55
  106. package/src/agents/opencode-agent.ts +0 -45
  107. package/src/filesystem/agentfs-provider.ts +0 -328
  108. package/src/filesystem/base-provider.ts +0 -98
  109. package/src/filesystem/memory-provider.ts +0 -267
  110. package/src/filesystem-manager.ts +0 -213
  111. package/src/orchestrator.ts +0 -177
  112. package/src/sandbox/base-provider.ts +0 -184
  113. package/src/sandbox/daytona-provider.ts +0 -462
  114. package/src/sandbox/e2b-provider.ts +0 -419
  115. package/src/sandbox/modal-provider.ts +0 -597
  116. package/src/sandbox-manager.ts +0 -175
  117. package/src/sdk.ts +0 -401
  118. package/src/types.ts +0 -451
  119. package/src/utils/code-extractor.ts +0 -194
  120. package/tsconfig.json +0 -25
package/src/types.ts DELETED
@@ -1,451 +0,0 @@
1
- import { LanguageModel } from 'ai';
2
-
3
- /**
4
- * Supported agent types
5
- */
6
- export type AgentType = 'intella-lite' | 'claude' | 'codex' | 'opencode';
7
-
8
- /**
9
- * Agent configuration interface
10
- */
11
- export interface AgentConfig {
12
- /** API key for the agent (provider-specific) */
13
- apiKey?: string;
14
- /** Model identifier to use */
15
- model?: string;
16
- /** Temperature for generation (0-2) */
17
- temperature?: number;
18
- /** Maximum tokens to generate */
19
- maxTokens?: number;
20
- /** Custom headers for the provider */
21
- headers?: Record<string, string>;
22
- /** Base URL for the provider (if applicable) */
23
- baseURL?: string;
24
- /** Additional provider-specific options */
25
- [key: string]: unknown;
26
- }
27
-
28
- /**
29
- * Text part for message content
30
- */
31
- export interface TextPart {
32
- type: 'text';
33
- text: string;
34
- }
35
-
36
- /**
37
- * File part for message content (attachments)
38
- */
39
- export interface FilePart {
40
- type: 'file';
41
- data: string | Uint8Array | ArrayBuffer | Buffer | URL; // base64-encoded string or binary data
42
- filename?: string;
43
- mediaType: string;
44
- }
45
-
46
- /**
47
- * Message content can be a string or array of parts (text and/or files)
48
- */
49
- export type MessageContent = string | Array<TextPart | FilePart>;
50
-
51
- /**
52
- * Task execution request
53
- */
54
- export interface TaskRequest {
55
- /** The prompt or task description */
56
- prompt: string;
57
- /** System prompt (optional) */
58
- systemPrompt?: string;
59
- /** Additional messages for context */
60
- messages?: Array<{
61
- role: 'user' | 'assistant' | 'system';
62
- content: MessageContent;
63
- }>;
64
- /** Generation parameters */
65
- temperature?: number;
66
- maxTokens?: number;
67
- /** Additional options */
68
- [key: string]: unknown;
69
- }
70
-
71
- /**
72
- * Task execution response
73
- */
74
- export interface TaskResponse {
75
- /** Generated text response */
76
- text: string;
77
- /** Agent type that generated the response */
78
- agentType: AgentType;
79
- /** Additional metadata */
80
- metadata?: {
81
- usage?: {
82
- promptTokens?: number;
83
- completionTokens?: number;
84
- totalTokens?: number;
85
- };
86
- finishReason?: string;
87
- [key: string]: unknown;
88
- };
89
- }
90
-
91
- /**
92
- * Streaming response chunk
93
- */
94
- export interface StreamChunk {
95
- /** Text chunk */
96
- text: string;
97
- /** Agent type */
98
- agentType: AgentType;
99
- /** Whether this is the final chunk */
100
- isDone: boolean;
101
- }
102
-
103
- /**
104
- * Orchestration strategy types
105
- */
106
- export type OrchestrationStrategy = 'sequential' | 'parallel' | 'conditional';
107
-
108
- /**
109
- * Multi-agent orchestration request
110
- */
111
- export interface OrchestrationRequest {
112
- /** The task to execute */
113
- task: TaskRequest;
114
- /** List of agent types to use */
115
- agents: AgentType[];
116
- /** Orchestration strategy */
117
- strategy: OrchestrationStrategy;
118
- /** Strategy-specific options */
119
- options?: {
120
- /** For sequential: whether to pass previous results to next agent */
121
- passResults?: boolean;
122
- /** For parallel: how to combine results */
123
- combineStrategy?: 'merge' | 'first' | 'best';
124
- /** For conditional: routing function */
125
- router?: (task: TaskRequest) => AgentType;
126
- };
127
- }
128
-
129
- /**
130
- * Multi-agent orchestration response
131
- */
132
- export interface OrchestrationResponse {
133
- /** Final result */
134
- result: string;
135
- /** Individual agent responses */
136
- agentResponses: Array<{
137
- agentType: AgentType;
138
- response: string;
139
- metadata?: TaskResponse['metadata'];
140
- }>;
141
- /** Strategy used */
142
- strategy: OrchestrationStrategy;
143
- }
144
-
145
- /**
146
- * Base agent interface
147
- */
148
- export interface IAgent {
149
- /** Agent type */
150
- readonly type: AgentType;
151
- /** Execute a task and return the response */
152
- execute(request: TaskRequest): Promise<TaskResponse>;
153
- /** Stream a task execution */
154
- stream(request: TaskRequest): AsyncIterable<StreamChunk>;
155
- /** Configure the agent */
156
- configure(config: AgentConfig): void;
157
- /** Get current configuration */
158
- getConfig(): AgentConfig;
159
- /** Get the underlying language model */
160
- getModel(): LanguageModel | Promise<LanguageModel>;
161
- }
162
-
163
- /**
164
- * Supported filesystem provider types
165
- */
166
- export type FilesystemProviderType = 'agentfs' | 'memory' | 'sandbox';
167
-
168
- /**
169
- * Filesystem provider configuration
170
- */
171
- export interface FilesystemConfig {
172
- /** Provider-specific configuration */
173
- provider?: FilesystemProviderType;
174
- /** Agent ID for the filesystem (used by AgentFS) */
175
- agentId?: string;
176
- /** Database path for AgentFS */
177
- dbPath?: string;
178
- /** Additional provider-specific options */
179
- [key: string]: unknown;
180
- }
181
-
182
- /**
183
- * File statistics
184
- */
185
- export interface FileStats {
186
- /** File size in bytes */
187
- size: number;
188
- /** Whether it's a directory */
189
- isDirectory: boolean;
190
- /** Whether it's a file */
191
- isFile: boolean;
192
- /** Creation time (Unix timestamp) */
193
- createdAt?: number;
194
- /** Modification time (Unix timestamp) */
195
- modifiedAt?: number;
196
- }
197
-
198
- /**
199
- * Directory entry
200
- */
201
- export interface DirectoryEntry {
202
- /** Entry name */
203
- name: string;
204
- /** Entry path */
205
- path: string;
206
- /** Entry statistics */
207
- stats: FileStats;
208
- }
209
-
210
- /**
211
- * Tool call metadata for recording
212
- */
213
- export interface ToolCallMetadata {
214
- /** Tool name */
215
- tool: string;
216
- /** Start time (Unix timestamp in seconds) */
217
- startedAt: number;
218
- /** End time (Unix timestamp in seconds) */
219
- endedAt: number;
220
- /** Tool input parameters */
221
- input?: Record<string, unknown>;
222
- /** Tool output/result */
223
- output?: unknown;
224
- /** Tool status */
225
- status?: 'success' | 'error' | 'pending';
226
- /** Error message if status is 'error' */
227
- error?: string;
228
- }
229
-
230
- /**
231
- * Filesystem provider interface
232
- */
233
- export interface IFilesystemProvider {
234
- /** Provider type */
235
- readonly type: FilesystemProviderType;
236
- /** Initialize the filesystem */
237
- initialize(config?: FilesystemConfig): Promise<void>;
238
- /** Check if filesystem is initialized */
239
- isInitialized(): boolean;
240
- /** Close/cleanup the filesystem */
241
- close(): Promise<void>;
242
-
243
- // Filesystem operations
244
- /** Read file contents */
245
- readFile(path: string): Promise<Buffer | string>;
246
- /** Write file contents */
247
- writeFile(path: string, data: Buffer | string): Promise<void>;
248
- /** Append to file */
249
- appendFile(path: string, data: Buffer | string): Promise<void>;
250
- /** Check if file/directory exists */
251
- exists(path: string): Promise<boolean>;
252
- /** Get file/directory statistics */
253
- stat(path: string): Promise<FileStats>;
254
- /** Read directory contents */
255
- readdir(path: string): Promise<DirectoryEntry[]>;
256
- /** Create directory */
257
- mkdir(path: string, recursive?: boolean): Promise<void>;
258
- /** Remove file or directory */
259
- unlink(path: string, recursive?: boolean): Promise<void>;
260
- /** Copy file or directory */
261
- copy(src: string, dest: string): Promise<void>;
262
- /** Move/rename file or directory */
263
- move(src: string, dest: string): Promise<void>;
264
-
265
- // Key-value operations
266
- /** Get value by key */
267
- get(key: string): Promise<unknown>;
268
- /** Set value for key */
269
- set(key: string, value: unknown): Promise<void>;
270
- /** Delete key */
271
- delete(key: string): Promise<void>;
272
- /** List all keys (optionally with prefix) */
273
- listKeys(prefix?: string): Promise<string[]>;
274
- /** Check if key exists */
275
- hasKey(key: string): Promise<boolean>;
276
-
277
- // Tool call tracking
278
- /** Record a tool call */
279
- recordToolCall(metadata: ToolCallMetadata): Promise<void>;
280
- /** Get tool call history (optionally filtered) */
281
- getToolCallHistory(filter?: {
282
- tool?: string;
283
- status?: ToolCallMetadata['status'];
284
- since?: number;
285
- until?: number;
286
- limit?: number;
287
- }): Promise<ToolCallMetadata[]>;
288
- }
289
-
290
- /**
291
- * Supported sandbox provider types
292
- */
293
- export type SandboxProviderType = 'e2b' | 'daytona' | 'modal';
294
-
295
- /**
296
- * Sandbox provider configuration
297
- */
298
- export interface SandboxConfig {
299
- fromSandboxId?: string;
300
- /** Provider-specific configuration */
301
- provider?: SandboxProviderType;
302
- /** API key for the sandbox provider */
303
- apiKey?: string;
304
- /** Sandbox template ID (for E2B) or workspace ID (for Daytona) */
305
- templateId?: string;
306
- /** Base URL for the provider (if applicable) */
307
- baseURL?: string;
308
- /** Environment variables to set in the sandbox */
309
- env?: Record<string, string>;
310
- /** Timeout in milliseconds */
311
- timeout?: number;
312
- /** Additional provider-specific options */
313
- [key: string]: unknown;
314
- }
315
-
316
- /**
317
- * Command execution result
318
- */
319
- export interface CommandResult {
320
- /** Exit code */
321
- exitCode: number;
322
- /** Standard output */
323
- stdout: string;
324
- /** Standard error */
325
- stderr: string;
326
- /** Execution time in milliseconds */
327
- executionTime?: number;
328
- }
329
-
330
- /**
331
- * Code execution result (for interpreted code like Python, JavaScript, etc.)
332
- */
333
- export interface CodeExecutionResult {
334
- /** Text representation of the main result */
335
- text?: string;
336
- /** All results from the execution (including charts, tables, etc.) */
337
- results: Array<{
338
- text?: string;
339
- html?: string;
340
- markdown?: string;
341
- [key: string]: unknown;
342
- }>;
343
- /** Logs printed to stdout during execution */
344
- stdout: string[];
345
- /** Logs printed to stderr during execution */
346
- stderr: string[];
347
- /** Error information if execution failed */
348
- error?: {
349
- name: string;
350
- value: string;
351
- traceback: string;
352
- };
353
- /** Execution time in milliseconds */
354
- executionTime?: number;
355
- }
356
-
357
- /**
358
- * Sandbox execution result
359
- */
360
- export interface SandboxExecutionResult {
361
- /** Command execution result */
362
- result: CommandResult;
363
- /** Sandbox ID */
364
- sandboxId: string;
365
- /** Provider type */
366
- provider: SandboxProviderType;
367
- /** Additional metadata */
368
- metadata?: {
369
- [key: string]: unknown;
370
- };
371
- }
372
-
373
- /**
374
- * Sandbox information
375
- */
376
- export interface SandboxInfo {
377
- /** Sandbox ID */
378
- sandboxId: string;
379
- /** Provider type */
380
- provider: SandboxProviderType;
381
- /** Whether the sandbox is running */
382
- isRunning: boolean;
383
- /** Whether the sandbox is initialized */
384
- isInitialized: boolean;
385
- /** Creation timestamp (Unix timestamp in milliseconds) */
386
- createdAt?: Date | string | number;
387
- /** Additional provider-specific information */
388
- metadata?: {
389
- [key: string]: any;
390
- };
391
-
392
- /** Sandbox raw info from the provider*/
393
- info?: any;
394
- }
395
-
396
- /**
397
- * Sandbox provider interface
398
- */
399
- export interface ISandboxProvider {
400
- /** Provider type */
401
- readonly type: SandboxProviderType;
402
- /** Get the client */
403
- getClient(): any;
404
- /** Initialize/create a sandbox (or connect to existing if fromSandboxId is provided) */
405
- initialize(config?: SandboxConfig): Promise<void>;
406
- /** Connect to an existing sandbox by ID */
407
- fromSandbox(sandboxId: string, config?: SandboxConfig): Promise<any>;
408
- /** Check if sandbox is initialized */
409
- isInitialized(): boolean;
410
- /** Close/cleanup the sandbox */
411
- close(): Promise<void>;
412
- /** Get sandbox ID */
413
- getSandboxId(): string | null;
414
- /** Execute a command in the sandbox */
415
- executeCommand(command: string, options?: {
416
- cwd?: string;
417
- env?: Record<string, string>;
418
- timeout?: number;
419
- }): Promise<CommandResult>;
420
- /** Run code (e.g., Python, JavaScript) in the sandbox */
421
- runCode(code: string, options?: {
422
- language?: string;
423
- env?: Record<string, string>;
424
- timeout?: number;
425
- onStdout?: (data: string) => void;
426
- onStderr?: (data: string) => void;
427
- }): Promise<CodeExecutionResult>;
428
- /** Upload a file to the sandbox */
429
- uploadFile(localPath: string, remotePath: string): Promise<void>;
430
- /** Download a file from the sandbox */
431
- downloadFile(remotePath: string, localPath: string): Promise<void>;
432
- /** Read a file from the sandbox */
433
- readFile(path: string): Promise<string>;
434
- /** Write a file to the sandbox */
435
- writeFile(path: string, content: string): Promise<void>;
436
- /** List files in a directory */
437
- listFiles(path: string): Promise<string[]>;
438
- /** Check if a file exists */
439
- fileExists(path: string): Promise<boolean>;
440
- /** Delete a file */
441
- deleteFile(path: string): Promise<void>;
442
- /** Get sandbox status */
443
- getStatus(): Promise<{
444
- isRunning: boolean;
445
- createdAt?: number;
446
- [key: string]: unknown;
447
- }>;
448
- /** Get detailed sandbox information */
449
- getInfo(sandboxId?: string): Promise<SandboxInfo>;
450
- }
451
-
@@ -1,194 +0,0 @@
1
- /**
2
- * Represents a code block extracted from markdown
3
- */
4
- export interface CodeBlock {
5
- /** The language identifier (e.g., 'typescript', 'bash', 'python') */
6
- language: string;
7
- /** The code content without the markdown fences */
8
- code: string;
9
- /** The full match including fences (for reference) */
10
- fullMatch?: string;
11
- }
12
-
13
- /**
14
- * Options for extracting code blocks
15
- */
16
- export interface ExtractCodeBlocksOptions {
17
- /** If true, only extract code blocks with the specified language(s) */
18
- languages?: string[];
19
- /** If true, return only the code content without language info */
20
- codeOnly?: boolean;
21
- /** If true, include the full match in the result */
22
- includeFullMatch?: boolean;
23
- /** Custom wrapper for code blocks */
24
- customWrapper?: {
25
- start: string;
26
- end: string;
27
- };
28
- }
29
-
30
- /**
31
- * Extracts code blocks from markdown text.
32
- * Handles multiple code blocks and returns an array of extracted blocks.
33
- *
34
- * @param text - The markdown text containing code blocks
35
- * @param options - Optional configuration for extraction
36
- * @returns Array of code blocks or code strings (if codeOnly is true)
37
- *
38
- * @example
39
- * ```typescript
40
- * const markdown = `
41
- * Here's some code:
42
- * \`\`\`typescript
43
- * const x = 1;
44
- * \`\`\`
45
- *
46
- * And a command:
47
- * \`\`\`bash
48
- * npm install
49
- * \`\`\`
50
- * `;
51
- *
52
- * const blocks = extractCodeBlocks(markdown);
53
- * // Returns:
54
- * // [
55
- * // { language: 'typescript', code: 'const x = 1;' },
56
- * // { language: 'bash', code: 'npm install' }
57
- * // ]
58
- *
59
- * const typescriptOnly = extractCodeBlocks(markdown, { languages: ['typescript'] });
60
- * const codeStrings = extractCodeBlocks(markdown, { codeOnly: true });
61
- *
62
- * // Using custom wrapper
63
- * const customMarkdown = '<code>typescript\nconst x = 1;\n</code>';
64
- * const customBlocks = extractCodeBlocks(customMarkdown, {
65
- * customWrapper: { start: '<code>', end: '</code>' }
66
- * });
67
- * ```
68
- */
69
- export function extractCodeBlocks(
70
- text: string,
71
- options: ExtractCodeBlocksOptions = {}
72
- ): CodeBlock[] | string[] {
73
- const {
74
- languages,
75
- codeOnly = false,
76
- includeFullMatch = false,
77
- customWrapper,
78
- } = options;
79
-
80
- // Determine the wrapper strings to use
81
- const startWrapper = customWrapper?.start ?? '```';
82
- const endWrapper = customWrapper?.end ?? '```';
83
-
84
- // Escape special regex characters in the wrapper strings
85
- const escapeRegex = (str: string): string => {
86
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
87
- };
88
-
89
- const escapedStart = escapeRegex(startWrapper);
90
- const escapedEnd = escapeRegex(endWrapper);
91
-
92
- // Build regex pattern: startWrapper language?\n?code\nendWrapper
93
- // Handles:
94
- // - Optional language identifier (with optional whitespace)
95
- // - Code blocks with or without newline after language
96
- // - Empty code blocks
97
- // - Code blocks without language
98
- // - Custom wrappers
99
- const codeBlockRegex = new RegExp(
100
- `${escapedStart}(\\w+)?\\s*\\n?([\\s\\S]*?)${escapedEnd}`,
101
- 'g'
102
- );
103
-
104
- const blocks: CodeBlock[] = [];
105
- let match: RegExpExecArray | null;
106
-
107
- // Reset regex lastIndex to ensure we start from the beginning
108
- codeBlockRegex.lastIndex = 0;
109
-
110
- while ((match = codeBlockRegex.exec(text)) !== null) {
111
- const language = match[1] || '';
112
- const code = match[2]?.trim() || '';
113
-
114
- // Filter by language if specified
115
- if (languages && languages.length > 0) {
116
- const normalizedLanguage = language.toLowerCase();
117
- const normalizedLanguages = languages.map((lang) => lang.toLowerCase());
118
- if (!normalizedLanguages.includes(normalizedLanguage)) {
119
- continue;
120
- }
121
- }
122
-
123
- const codeBlock: CodeBlock = {
124
- language,
125
- code,
126
- };
127
-
128
- if (includeFullMatch) {
129
- codeBlock.fullMatch = match[0];
130
- }
131
-
132
- blocks.push(codeBlock);
133
- }
134
-
135
- // Return code strings only if requested
136
- if (codeOnly) {
137
- return blocks.map((block) => block.code);
138
- }
139
-
140
- return blocks;
141
- }
142
-
143
- /**
144
- * Extracts a single code block from markdown text.
145
- * Returns the first matching code block, or null if none found.
146
- *
147
- * @param text - The markdown text containing code blocks
148
- * @param language - Optional language filter (case-insensitive)
149
- * @returns The first matching code block, or null
150
- *
151
- * @example
152
- * ```typescript
153
- * const markdown = '```bash\nnpm install\n```';
154
- * const block = extractCodeBlock(markdown);
155
- * // Returns: { language: 'bash', code: 'npm install' }
156
- *
157
- * const tsBlock = extractCodeBlock(markdown, 'typescript');
158
- * // Returns: null (no typescript block found)
159
- * ```
160
- */
161
- export function extractCodeBlock(
162
- text: string,
163
- language?: string
164
- ): CodeBlock | null {
165
- const options: ExtractCodeBlocksOptions = language
166
- ? { languages: [language] }
167
- : {};
168
-
169
- const blocks = extractCodeBlocks(text, options) as CodeBlock[];
170
- return blocks.length > 0 ? blocks[0] : null;
171
- }
172
-
173
- /**
174
- * Extracts code content from a single code block (without language info).
175
- * Returns the code string, or null if no code block found.
176
- *
177
- * @param text - The markdown text containing code blocks
178
- * @param language - Optional language filter (case-insensitive)
179
- * @returns The code content as a string, or null
180
- *
181
- * @example
182
- * ```typescript
183
- * const markdown = '```bash\nnpm install\n```';
184
- * const code = extractCode(markdown);
185
- * // Returns: 'npm install'
186
- * ```
187
- */
188
- export function extractCode(
189
- text: string,
190
- language?: string
191
- ): string | null {
192
- const block = extractCodeBlock(text, language);
193
- return block ? block.code : null;
194
- }
package/tsconfig.json DELETED
@@ -1,25 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "ESNext",
5
- "lib": ["ES2020"],
6
- "moduleResolution": "node",
7
- "outDir": "./dist",
8
- "rootDir": "./src",
9
- "strict": true,
10
- "esModuleInterop": true,
11
- "skipLibCheck": true,
12
- "forceConsistentCasingInFileNames": true,
13
- "declaration": true,
14
- "declarationMap": true,
15
- "sourceMap": true,
16
- "resolveJsonModule": true,
17
- "noUnusedLocals": true,
18
- "noUnusedParameters": true,
19
- "noImplicitReturns": true,
20
- "noFallthroughCasesInSwitch": true
21
- },
22
- "include": ["src/**/*"],
23
- "exclude": ["node_modules", "dist"]
24
- }
25
-