@rsdk/yaml 5.12.0-next.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.
@@ -0,0 +1 @@
1
+ export * from './yaml';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./yaml"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAAuB"}
package/dist/yaml.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { z } from 'zod';
2
+ export type JSONValue = null | string | number | boolean | {
3
+ [x: string]: JSONValue;
4
+ } | Array<JSONValue>;
5
+ export declare const yaml: {
6
+ parse: typeof parse;
7
+ parseUnsafe: typeof parseUnsafe;
8
+ stringify: typeof stringify;
9
+ stringifyAny: typeof stringifyAny;
10
+ };
11
+ declare function parse<T>(schema: z.ZodType<T>, yamlString: string): T;
12
+ declare function parseUnsafe(yamlString: string): JSONValue;
13
+ declare function stringify(value: JSONValue): string;
14
+ declare function stringifyAny(value: unknown): string;
15
+ export {};
package/dist/yaml.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.yaml = void 0;
37
+ const YAML = __importStar(require("yaml"));
38
+ const stringifyString_1 = require("yaml/dist/stringify/stringifyString");
39
+ const YAML_SCALE_KEY = '!yaml_scale';
40
+ var YAMLCustomTags;
41
+ (function (YAMLCustomTags) {
42
+ YAMLCustomTags["DENO"] = "!deno";
43
+ YAMLCustomTags["EXPRESSION"] = "!expression";
44
+ YAMLCustomTags["PY"] = "!py";
45
+ YAMLCustomTags["VRL"] = "!vrl";
46
+ })(YAMLCustomTags || (YAMLCustomTags = {}));
47
+ function isVrlTagValue(value) {
48
+ return (value !== undefined &&
49
+ value !== null &&
50
+ typeof value === 'object' &&
51
+ YAML_SCALE_KEY in value &&
52
+ value[YAML_SCALE_KEY] === 'vrl');
53
+ }
54
+ function isExpressionTagValue(value) {
55
+ return (value !== undefined &&
56
+ value !== null &&
57
+ typeof value === 'object' &&
58
+ YAML_SCALE_KEY in value &&
59
+ value[YAML_SCALE_KEY] === 'expression');
60
+ }
61
+ const customTags = [
62
+ {
63
+ identify: isVrlTagValue,
64
+ resolve(rawValue) {
65
+ return rawValue;
66
+ },
67
+ stringify(item, ctx, _onComment, _onChompKeep) {
68
+ const value = item.value.vrl;
69
+ const indent = ctx.indent || '';
70
+ const lines = value.split('\n');
71
+ const blockContent = lines
72
+ .map((line, index) => index === 0 ? line : `${indent}${line}`)
73
+ .join('\n');
74
+ return `|\n${indent}${blockContent}`;
75
+ },
76
+ tag: YAMLCustomTags.VRL,
77
+ },
78
+ {
79
+ identify: isExpressionTagValue,
80
+ resolve(rawValue) {
81
+ return parseUnsafe(rawValue);
82
+ },
83
+ stringify(item, ctx, onComment, onChompKeep) {
84
+ return (0, stringifyString_1.stringifyString)({
85
+ value: YAML.stringify(item.value.expression),
86
+ }, ctx, onComment, onChompKeep);
87
+ },
88
+ tag: YAMLCustomTags.EXPRESSION,
89
+ },
90
+ {
91
+ identify: (value) => typeof value === 'string',
92
+ resolve(rawValue) {
93
+ return {
94
+ code: rawValue,
95
+ language: 'deno',
96
+ };
97
+ },
98
+ tag: YAMLCustomTags.DENO,
99
+ },
100
+ {
101
+ identify: (value) => typeof value === 'string',
102
+ resolve(rawValue) {
103
+ return {
104
+ code: rawValue,
105
+ language: 'py',
106
+ };
107
+ },
108
+ tag: YAMLCustomTags.PY,
109
+ },
110
+ ];
111
+ const customTagsArray = Object.values(customTags);
112
+ exports.yaml = { parse, parseUnsafe, stringify, stringifyAny };
113
+ function parse(schema, yamlString) {
114
+ const obj = parseUnsafe(yamlString);
115
+ const res = schema.safeParse(obj);
116
+ if (res.success) {
117
+ return res.data;
118
+ }
119
+ else {
120
+ throw new Error(`YAML document doesn't match schema ${res.error}`);
121
+ }
122
+ }
123
+ function parseUnsafe(yamlString) {
124
+ try {
125
+ return YAML.parse(yamlString, { customTags: customTagsArray });
126
+ }
127
+ catch (error) {
128
+ const message = error instanceof Error ? error.message : String(error);
129
+ throw new Error(`Invalid yaml string: ${message}`);
130
+ }
131
+ }
132
+ function stringify(value) {
133
+ return YAML.stringify(value, { customTags: customTagsArray });
134
+ }
135
+ function stringifyAny(value) {
136
+ return YAML.stringify(value, { customTags: customTagsArray });
137
+ }
138
+ //# sourceMappingURL=yaml.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"yaml.js","sourceRoot":"","sources":["../src/yaml.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,yEAAsE;AAGtE,MAAM,cAAc,GAAG,aAAa,CAAC;AAErC,IAAK,cAKJ;AALD,WAAK,cAAc;IACjB,gCAAc,CAAA;IACd,4CAA0B,CAAA;IAC1B,4BAAU,CAAA;IACV,8BAAY,CAAA;AACd,CAAC,EALI,cAAc,KAAd,cAAc,QAKlB;AAiBD,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,CACL,KAAK,KAAK,SAAS;QACnB,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,cAAc,IAAI,KAAK;QACtB,KAAiC,CAAC,cAAc,CAAC,KAAK,KAAK,CAC7D,CAAC;AACJ,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAc;IAC1C,OAAO,CACL,KAAK,KAAK,SAAS;QACnB,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,cAAc,IAAI,KAAK;QACtB,KAAiC,CAAC,cAAc,CAAC,KAAK,YAAY,CACpE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,GAAc;IAC5B;QACE,QAAQ,EAAE,aAAa;QACvB,OAAO,CAAC,QA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E,EAAE,UAAU,EAAE,eAAe,EAAE,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,eAAe,EAAE,CAAC,CAAC;AAChE,CAAC"}
package/jest.config.js ADDED
@@ -0,0 +1,9 @@
1
+ const baseConfig = require('@rsdk/jest/jest.config');
2
+
3
+ module.exports = {
4
+ ...baseConfig,
5
+ moduleNameMapper: {
6
+ ...baseConfig.moduleNameMapper,
7
+ '^yaml/dist/(.*)$': '<rootDir>/../../node_modules/yaml/dist/$1',
8
+ },
9
+ };
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@rsdk/yaml",
3
+ "version": "5.12.0-next.1",
4
+ "description": "YAML parser and serializer with custom tags and Zod validation support",
5
+ "license": "Apache License 2.0",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "url": "https://github.com/R-Vision/rsdk"
11
+ },
12
+ "main": "dist/index.js",
13
+ "scripts": {
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "peerDependencies": {
17
+ "yaml": "^2.7.0",
18
+ "zod": "^3.0.0"
19
+ },
20
+ "gitHead": "9ef9770256f8fa9285d60e87cfaf468e5a9367c5"
21
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './yaml';
@@ -0,0 +1,251 @@
1
+ import { z } from 'zod';
2
+
3
+ import { yaml } from './yaml';
4
+
5
+ describe('yaml', () => {
6
+ describe('parseUnsafe', () => {
7
+ it('should parse simple YAML', () => {
8
+ const result = yaml.parseUnsafe('name: test\nport: 3000');
9
+
10
+ expect(result).toEqual({ name: 'test', port: 3000 });
11
+ });
12
+
13
+ it('should parse YAML with arrays', () => {
14
+ const result = yaml.parseUnsafe('items:\n - one\n - two\n - three');
15
+
16
+ expect(result).toEqual({ items: ['one', 'two', 'three'] });
17
+ });
18
+
19
+ it('should parse YAML with nested objects', () => {
20
+ const result = yaml.parseUnsafe(
21
+ 'database:\n host: localhost\n port: 5432',
22
+ );
23
+
24
+ expect(result).toEqual({
25
+ database: { host: 'localhost', port: 5432 },
26
+ });
27
+ });
28
+
29
+ it('should parse null values', () => {
30
+ const result = yaml.parseUnsafe('value: null');
31
+
32
+ expect(result).toEqual({ value: null });
33
+ });
34
+
35
+ it('should parse boolean values', () => {
36
+ const result = yaml.parseUnsafe('enabled: true\ndisabled: false');
37
+
38
+ expect(result).toEqual({ enabled: true, disabled: false });
39
+ });
40
+
41
+ it('should throw on invalid YAML', () => {
42
+ expect(() => yaml.parseUnsafe('invalid: yaml: [')).toThrow(
43
+ 'Invalid yaml string',
44
+ );
45
+ });
46
+ });
47
+
48
+ describe('parse', () => {
49
+ it('should parse and validate YAML with Zod schema', () => {
50
+ const schema = z.object({
51
+ name: z.string(),
52
+ port: z.number(),
53
+ });
54
+
55
+ const result = yaml.parse(schema, 'name: test\nport: 3000');
56
+
57
+ expect(result).toEqual({ name: 'test', port: 3000 });
58
+ });
59
+
60
+ it('should throw when YAML does not match schema', () => {
61
+ const schema = z.object({
62
+ name: z.string(),
63
+ port: z.number(),
64
+ });
65
+
66
+ expect(() => yaml.parse(schema, 'name: test\nport: invalid')).toThrow(
67
+ "YAML document doesn't match schema",
68
+ );
69
+ });
70
+
71
+ it('should apply default values from schema', () => {
72
+ const schema = z.object({
73
+ name: z.string(),
74
+ port: z.number().default(3000),
75
+ });
76
+
77
+ const result = yaml.parse(schema, 'name: test');
78
+
79
+ expect(result).toEqual({ name: 'test', port: 3000 });
80
+ });
81
+
82
+ it('should validate nested schemas', () => {
83
+ const schema = z.object({
84
+ database: z.object({
85
+ host: z.string(),
86
+ port: z.number().min(1).max(65535),
87
+ }),
88
+ });
89
+
90
+ const result = yaml.parse(
91
+ schema,
92
+ 'database:\n host: localhost\n port: 5432',
93
+ );
94
+
95
+ expect(result).toEqual({
96
+ database: { host: 'localhost', port: 5432 },
97
+ });
98
+ });
99
+ });
100
+
101
+ describe('stringify', () => {
102
+ it('should stringify simple objects', () => {
103
+ const result = yaml.stringify({ name: 'test', port: 3000 });
104
+
105
+ expect(result).toContain('name: test');
106
+ expect(result).toContain('port: 3000');
107
+ });
108
+
109
+ it('should stringify arrays', () => {
110
+ const result = yaml.stringify({ items: ['one', 'two', 'three'] });
111
+
112
+ expect(result).toContain('items:');
113
+ expect(result).toContain('- one');
114
+ expect(result).toContain('- two');
115
+ expect(result).toContain('- three');
116
+ });
117
+
118
+ it('should stringify nested objects', () => {
119
+ const result = yaml.stringify({
120
+ database: { host: 'localhost', port: 5432 },
121
+ });
122
+
123
+ expect(result).toContain('database:');
124
+ expect(result).toContain('host: localhost');
125
+ expect(result).toContain('port: 5432');
126
+ });
127
+
128
+ it('should stringify null values', () => {
129
+ const result = yaml.stringify({ value: null });
130
+
131
+ expect(result).toContain('value: null');
132
+ });
133
+
134
+ it('should stringify boolean values', () => {
135
+ const result = yaml.stringify({ enabled: true, disabled: false });
136
+
137
+ expect(result).toContain('enabled: true');
138
+ expect(result).toContain('disabled: false');
139
+ });
140
+ });
141
+
142
+ describe('stringifyAny', () => {
143
+ it('should stringify objects with undefined values', () => {
144
+ const result = yaml.stringifyAny({ name: 'test', value: undefined });
145
+
146
+ expect(result).toContain('name: test');
147
+ });
148
+
149
+ it('should handle any value type', () => {
150
+ expect(yaml.stringifyAny('string')).toContain('string');
151
+ expect(yaml.stringifyAny(123)).toContain('123');
152
+ expect(yaml.stringifyAny(true)).toContain('true');
153
+ expect(yaml.stringifyAny(null)).toContain('null');
154
+ });
155
+ });
156
+
157
+ describe('custom tags', () => {
158
+ describe('!deno tag', () => {
159
+ it('should parse !deno tag', () => {
160
+ const result = yaml.parseUnsafe(
161
+ 'script: !deno |\n console.log("hello");',
162
+ );
163
+
164
+ expect(result).toEqual({
165
+ script: {
166
+ code: 'console.log("hello");\n',
167
+ language: 'deno',
168
+ },
169
+ });
170
+ });
171
+ });
172
+
173
+ describe('!py tag', () => {
174
+ it('should parse !py tag', () => {
175
+ const result = yaml.parseUnsafe('script: !py |\n print("hello")');
176
+
177
+ expect(result).toEqual({
178
+ script: {
179
+ code: 'print("hello")\n',
180
+ language: 'py',
181
+ },
182
+ });
183
+ });
184
+ });
185
+
186
+ describe('!vrl tag', () => {
187
+ it('should parse !vrl tag', () => {
188
+ const result = yaml.parseUnsafe(
189
+ 'transform: !vrl |\n .timestamp = now()',
190
+ );
191
+
192
+ expect(result).toEqual({
193
+ transform: '.timestamp = now()\n',
194
+ });
195
+ });
196
+ });
197
+
198
+ describe('!expression tag', () => {
199
+ it('should parse !expression tag with nested YAML', () => {
200
+ const result = yaml.parseUnsafe(
201
+ 'config: !expression |\n key: value\n nested:\n inner: data',
202
+ );
203
+
204
+ expect(result).toEqual({
205
+ config: {
206
+ key: 'value',
207
+ nested: { inner: 'data' },
208
+ },
209
+ });
210
+ });
211
+ });
212
+ });
213
+
214
+ describe('roundtrip', () => {
215
+ it('should roundtrip simple objects', () => {
216
+ const original = { name: 'test', port: 3000, enabled: true };
217
+ const yamlString = yaml.stringify(original);
218
+ const parsed = yaml.parseUnsafe(yamlString);
219
+
220
+ expect(parsed).toEqual(original);
221
+ });
222
+
223
+ it('should roundtrip nested objects', () => {
224
+ const original = {
225
+ database: {
226
+ host: 'localhost',
227
+ port: 5432,
228
+ credentials: {
229
+ user: 'admin',
230
+ password: 'secret',
231
+ },
232
+ },
233
+ };
234
+ const yamlString = yaml.stringify(original);
235
+ const parsed = yaml.parseUnsafe(yamlString);
236
+
237
+ expect(parsed).toEqual(original);
238
+ });
239
+
240
+ it('should roundtrip arrays', () => {
241
+ const original = {
242
+ items: [1, 2, 3],
243
+ tags: ['a', 'b', 'c'],
244
+ };
245
+ const yamlString = yaml.stringify(original);
246
+ const parsed = yaml.parseUnsafe(yamlString);
247
+
248
+ expect(parsed).toEqual(original);
249
+ });
250
+ });
251
+ });
package/src/yaml.ts ADDED
@@ -0,0 +1,148 @@
1
+ import * as YAML from 'yaml';
2
+ import { stringifyString } from 'yaml/dist/stringify/stringifyString';
3
+ import type { z } from 'zod';
4
+
5
+ const YAML_SCALE_KEY = '!yaml_scale';
6
+
7
+ enum YAMLCustomTags {
8
+ DENO = '!deno',
9
+ EXPRESSION = '!expression',
10
+ PY = '!py',
11
+ VRL = '!vrl',
12
+ }
13
+
14
+ interface VrlTagValue {
15
+ [YAML_SCALE_KEY]: 'vrl';
16
+ vrl: string;
17
+ }
18
+
19
+ interface ExpressionTagValue {
20
+ [YAML_SCALE_KEY]: 'expression';
21
+ expression: unknown;
22
+ }
23
+
24
+ interface CodeTagValue {
25
+ code: string;
26
+ language: 'deno' | 'py';
27
+ }
28
+
29
+ function isVrlTagValue(value: unknown): value is VrlTagValue {
30
+ return (
31
+ value !== undefined &&
32
+ value !== null &&
33
+ typeof value === 'object' &&
34
+ YAML_SCALE_KEY in value &&
35
+ (value as Record<string, unknown>)[YAML_SCALE_KEY] === 'vrl'
36
+ );
37
+ }
38
+
39
+ function isExpressionTagValue(value: unknown): value is ExpressionTagValue {
40
+ return (
41
+ value !== undefined &&
42
+ value !== null &&
43
+ typeof value === 'object' &&
44
+ YAML_SCALE_KEY in value &&
45
+ (value as Record<string, unknown>)[YAML_SCALE_KEY] === 'expression'
46
+ );
47
+ }
48
+
49
+ const customTags: YAML.Tags = [
50
+ {
51
+ identify: isVrlTagValue,
52
+ resolve(rawValue: string): string {
53
+ return rawValue;
54
+ },
55
+ stringify(item, ctx, _onComment, _onChompKeep): string {
56
+ const value = (item.value as VrlTagValue).vrl;
57
+ const indent = ctx.indent || '';
58
+ const lines = value.split('\n');
59
+ const blockContent = lines
60
+ .map((line: string, index: number) =>
61
+ index === 0 ? line : `${indent}${line}`,
62
+ )
63
+ .join('\n');
64
+
65
+ return `|\n${indent}${blockContent}`;
66
+ },
67
+ tag: YAMLCustomTags.VRL,
68
+ },
69
+ {
70
+ identify: isExpressionTagValue,
71
+ resolve(rawValue: string): JSONValue {
72
+ return parseUnsafe(rawValue);
73
+ },
74
+ stringify(item, ctx, onComment, onChompKeep): string {
75
+ return stringifyString(
76
+ {
77
+ value: YAML.stringify((item.value as ExpressionTagValue).expression),
78
+ },
79
+ ctx,
80
+ onComment,
81
+ onChompKeep,
82
+ );
83
+ },
84
+ tag: YAMLCustomTags.EXPRESSION,
85
+ },
86
+ {
87
+ identify: (value: unknown): value is string => typeof value === 'string',
88
+ resolve(rawValue: string): CodeTagValue {
89
+ return {
90
+ code: rawValue,
91
+ language: 'deno',
92
+ };
93
+ },
94
+ tag: YAMLCustomTags.DENO,
95
+ },
96
+ {
97
+ identify: (value: unknown): value is string => typeof value === 'string',
98
+ resolve(rawValue: string): CodeTagValue {
99
+ return {
100
+ code: rawValue,
101
+ language: 'py',
102
+ };
103
+ },
104
+ tag: YAMLCustomTags.PY,
105
+ },
106
+ ];
107
+
108
+ const customTagsArray = Object.values(customTags);
109
+
110
+ export type JSONValue =
111
+ | null
112
+ | string
113
+ | number
114
+ | boolean
115
+ | { [x: string]: JSONValue }
116
+ | Array<JSONValue>;
117
+
118
+ export const yaml = { parse, parseUnsafe, stringify, stringifyAny };
119
+
120
+ function parse<T>(schema: z.ZodType<T>, yamlString: string): T {
121
+ const obj = parseUnsafe(yamlString);
122
+
123
+ const res = schema.safeParse(obj);
124
+
125
+ if (res.success) {
126
+ return res.data;
127
+ } else {
128
+ throw new Error(`YAML document doesn't match schema ${res.error}`);
129
+ }
130
+ }
131
+
132
+ function parseUnsafe(yamlString: string): JSONValue {
133
+ try {
134
+ return YAML.parse(yamlString, { customTags: customTagsArray });
135
+ } catch (error: unknown) {
136
+ const message = error instanceof Error ? error.message : String(error);
137
+
138
+ throw new Error(`Invalid yaml string: ${message}`);
139
+ }
140
+ }
141
+
142
+ function stringify(value: JSONValue): string {
143
+ return YAML.stringify(value, { customTags: customTagsArray });
144
+ }
145
+
146
+ function stringifyAny(value: unknown): string {
147
+ return YAML.stringify(value, { customTags: customTagsArray });
148
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": [
4
+ "node_modules",
5
+ "dist",
6
+ "test",
7
+ "testFuzz",
8
+ "**/*.spec.ts",
9
+ "**/*.test.ts",
10
+ "**/*.test.e2e.ts",
11
+ "**/*.test.manual-e2e.ts"
12
+ ]
13
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "@rsdk/tsconfig/base.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "outDir": "dist"
6
+ }
7
+ }