@storm-software/untyped 0.24.260 → 0.24.262

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.
@@ -1,501 +0,0 @@
1
- import {
2
- writeError,
3
- writeTrace
4
- } from "./chunk-RT5SQVG7.js";
5
- import {
6
- getOutputFile
7
- } from "./chunk-NTN5YK5X.js";
8
-
9
- // src/generators/dts.ts
10
- import { writeFile } from "node:fs/promises";
11
-
12
- // ../../node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/shared/untyped.Br_uXjZG.mjs
13
- import { pascalCase } from "scule";
14
- function getType(val) {
15
- const type = typeof val;
16
- if (type === "undefined" || val === null) {
17
- return void 0;
18
- }
19
- if (Array.isArray(val)) {
20
- return "array";
21
- }
22
- return type;
23
- }
24
- function isObject(val) {
25
- return val !== null && !Array.isArray(val) && typeof val === "object";
26
- }
27
- function nonEmpty(arr) {
28
- return arr.filter(Boolean);
29
- }
30
- function unique(arr) {
31
- return [...new Set(arr)];
32
- }
33
- function joinPath(a, b = "", sep = ".") {
34
- return a ? a + sep + b : b;
35
- }
36
- function setValue(obj, path, val) {
37
- const keys = path.split(".");
38
- const _key = keys.pop();
39
- for (const key of keys) {
40
- if (!obj || typeof obj !== "object") {
41
- return;
42
- }
43
- if (!(key in obj)) {
44
- obj[key] = {};
45
- }
46
- obj = obj[key];
47
- }
48
- if (_key) {
49
- if (!obj || typeof obj !== "object") {
50
- return;
51
- }
52
- obj[_key] = val;
53
- }
54
- }
55
- function getValue(obj, path) {
56
- for (const key of path.split(".")) {
57
- if (!obj || typeof obj !== "object" || !(key in obj)) {
58
- return;
59
- }
60
- obj = obj[key];
61
- }
62
- return obj;
63
- }
64
- function mergedTypes(...types) {
65
- types = types.filter(Boolean);
66
- if (types.length === 0) {
67
- return {};
68
- }
69
- if (types.length === 1) {
70
- return types[0];
71
- }
72
- const tsTypes = normalizeTypes(
73
- types.flatMap((t) => t.tsType).filter(Boolean)
74
- );
75
- return {
76
- type: normalizeTypes(
77
- types.flatMap((t) => t.type).filter(Boolean)
78
- ),
79
- tsType: Array.isArray(tsTypes) ? tsTypes.join(" | ") : tsTypes,
80
- items: mergedTypes(
81
- ...types.flatMap((t) => t.items).filter(Boolean)
82
- )
83
- };
84
- }
85
- function normalizeTypes(val) {
86
- const arr = unique(val.filter(Boolean));
87
- if (arr.length === 0 || arr.includes("any")) {
88
- return;
89
- }
90
- return arr.length > 1 ? arr : arr[0];
91
- }
92
- function cachedFn(fn) {
93
- let val;
94
- let resolved = false;
95
- const cachedFn2 = () => {
96
- if (!resolved) {
97
- val = fn();
98
- resolved = true;
99
- }
100
- return val;
101
- };
102
- return cachedFn2;
103
- }
104
- var jsTypes = /* @__PURE__ */ new Set([
105
- "string",
106
- "number",
107
- "bigint",
108
- "boolean",
109
- "symbol",
110
- "function",
111
- "object",
112
- "any",
113
- "array"
114
- ]);
115
- function isJSType(val) {
116
- return jsTypes.has(val);
117
- }
118
- var FRIENDLY_TYPE_RE = /(typeof )?import\(["'](?<importName>[^"']+)["']\)(\[["']|\.)(?<firstType>[^\s"']+)(["']])?/g;
119
- function getTypeDescriptor(type) {
120
- if (!type) {
121
- return {};
122
- }
123
- let markdownType = type;
124
- for (const match of type.matchAll(FRIENDLY_TYPE_RE) || []) {
125
- const { importName, firstType } = match.groups || {};
126
- if (importName && firstType) {
127
- markdownType = markdownType.replace(
128
- match[0],
129
- pascalCase(importName) + pascalCase(firstType)
130
- );
131
- }
132
- }
133
- return {
134
- ...isJSType(type) ? { type } : {},
135
- tsType: type,
136
- ...markdownType === type ? {} : { markdownType }
137
- };
138
- }
139
-
140
- // ../../node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/shared/untyped.BTwOq8Jl.mjs
141
- async function resolveSchema(obj, defaults, options = {}) {
142
- const schema = await _resolveSchema(obj, "", {
143
- root: obj,
144
- defaults,
145
- resolveCache: {},
146
- ignoreDefaults: !!options.ignoreDefaults
147
- });
148
- return schema;
149
- }
150
- async function _resolveSchema(input, id, ctx) {
151
- if (id in ctx.resolveCache) {
152
- return ctx.resolveCache[id];
153
- }
154
- const schemaId = "#" + id.replace(/\./g, "/");
155
- if (!isObject(input)) {
156
- const safeInput = Array.isArray(input) ? [...input] : input;
157
- const schema2 = {
158
- type: getType(input),
159
- id: schemaId,
160
- default: ctx.ignoreDefaults ? void 0 : safeInput
161
- };
162
- normalizeSchema(schema2, { ignoreDefaults: ctx.ignoreDefaults });
163
- ctx.resolveCache[id] = schema2;
164
- if (ctx.defaults && getValue(ctx.defaults, id) === void 0) {
165
- setValue(ctx.defaults, id, schema2.default);
166
- }
167
- return schema2;
168
- }
169
- const node = { ...input };
170
- const schema = ctx.resolveCache[id] = {
171
- ...node.$schema,
172
- id: schemaId
173
- };
174
- for (const key in node) {
175
- if (key === "$resolve" || key === "$schema" || key === "$default") {
176
- continue;
177
- }
178
- schema.properties = schema.properties || {};
179
- if (!schema.properties[key]) {
180
- const child = schema.properties[key] = await _resolveSchema(
181
- node[key],
182
- joinPath(id, key),
183
- ctx
184
- );
185
- if (Array.isArray(child.tags) && child.tags.includes("@required")) {
186
- schema.required = schema.required || [];
187
- if (!schema.required.includes(key)) {
188
- schema.required.push(key);
189
- }
190
- }
191
- }
192
- }
193
- if (!ctx.ignoreDefaults) {
194
- if (ctx.defaults) {
195
- schema.default = getValue(ctx.defaults, id);
196
- }
197
- if (schema.default === void 0 && "$default" in node) {
198
- schema.default = node.$default;
199
- }
200
- if (typeof node.$resolve === "function") {
201
- schema.default = await node.$resolve(schema.default, async (key) => {
202
- return (await _resolveSchema(getValue(ctx.root, key), key, ctx)).default;
203
- });
204
- }
205
- }
206
- if (ctx.defaults) {
207
- setValue(ctx.defaults, id, schema.default);
208
- }
209
- if (!schema.type) {
210
- schema.type = getType(schema.default) || (schema.properties ? "object" : "any");
211
- }
212
- normalizeSchema(schema, { ignoreDefaults: ctx.ignoreDefaults });
213
- if (ctx.defaults && getValue(ctx.defaults, id) === void 0) {
214
- setValue(ctx.defaults, id, schema.default);
215
- }
216
- return schema;
217
- }
218
- function normalizeSchema(schema, options) {
219
- if (schema.type === "array" && !("items" in schema)) {
220
- schema.items = {
221
- type: nonEmpty(unique(schema.default.map((i) => getType(i))))
222
- };
223
- if (schema.items.type) {
224
- if (schema.items.type.length === 0) {
225
- schema.items.type = "any";
226
- } else if (schema.items.type.length === 1) {
227
- schema.items.type = schema.items.type[0];
228
- }
229
- }
230
- }
231
- if (!options.ignoreDefaults && schema.default === void 0 && ("properties" in schema || schema.type === "object" || schema.type === "any")) {
232
- const propsWithDefaults = Object.entries(schema.properties || {}).filter(([, prop]) => "default" in prop).map(([key, value]) => [key, value.default]);
233
- schema.default = Object.fromEntries(propsWithDefaults);
234
- }
235
- }
236
-
237
- // ../../node_modules/.pnpm/untyped@2.0.0/node_modules/untyped/dist/index.mjs
238
- import { genObjectKey } from "knitwork";
239
- import "scule";
240
- var GenerateTypesDefaults = {
241
- interfaceName: "Untyped",
242
- addExport: true,
243
- addDefaults: true,
244
- allowExtraKeys: void 0,
245
- partial: false,
246
- indentation: 0
247
- };
248
- var TYPE_MAP = {
249
- array: "any[]",
250
- bigint: "bigint",
251
- boolean: "boolean",
252
- number: "number",
253
- object: "",
254
- // Will be precisely defined
255
- any: "any",
256
- string: "string",
257
- symbol: "Symbol",
258
- function: "Function"
259
- };
260
- var SCHEMA_KEYS = /* @__PURE__ */ new Set([
261
- "items",
262
- "default",
263
- "resolve",
264
- "properties",
265
- "title",
266
- "description",
267
- "$schema",
268
- "type",
269
- "tsType",
270
- "markdownType",
271
- "tags",
272
- "args",
273
- "id",
274
- "returns"
275
- ]);
276
- var DECLARATION_RE = /typeof import\(["'](?<source>[^)]+)["']\)(\.(?<type>\w+)|\[["'](?<type1>\w+)["']])/g;
277
- function extractTypeImports(declarations) {
278
- const typeImports = {};
279
- const aliases = /* @__PURE__ */ new Set();
280
- const imports = [];
281
- for (const match of declarations.matchAll(DECLARATION_RE)) {
282
- const { source, type1, type = type1 } = match.groups || {};
283
- typeImports[source] = typeImports[source] || /* @__PURE__ */ new Set();
284
- typeImports[source].add(type);
285
- }
286
- for (const source in typeImports) {
287
- const sourceImports = [];
288
- for (const type of typeImports[source]) {
289
- let count = 0;
290
- let alias = type;
291
- while (aliases.has(alias)) {
292
- alias = `${type}${count++}`;
293
- }
294
- aliases.add(alias);
295
- sourceImports.push(alias === type ? type : `${type} as ${alias}`);
296
- declarations = declarations.replace(
297
- new RegExp(
298
- `typeof import\\(['"]${source}['"]\\)(\\.${type}|\\[['"]${type}['"]\\])`,
299
- "g"
300
- ),
301
- alias
302
- );
303
- }
304
- imports.push(
305
- `import type { ${sourceImports.join(", ")} } from '${source}'`
306
- );
307
- }
308
- return [...imports, declarations].join("\n");
309
- }
310
- function generateTypes(schema, opts = {}) {
311
- opts = { ...GenerateTypesDefaults, ...opts };
312
- const baseIden = " ".repeat(opts.indentation || 0);
313
- const interfaceCode = `interface ${opts.interfaceName} {
314
- ` + _genTypes(schema, baseIden + " ", opts).map((l) => l.trim().length > 0 ? l : "").join("\n") + `
315
- ${baseIden}}`;
316
- if (!opts.addExport) {
317
- return baseIden + interfaceCode;
318
- }
319
- return extractTypeImports(baseIden + `export ${interfaceCode}`);
320
- }
321
- function _genTypes(schema, spaces, opts) {
322
- const buff = [];
323
- if (!schema) {
324
- return buff;
325
- }
326
- for (const key in schema.properties) {
327
- const val = schema.properties[key];
328
- buff.push(...generateJSDoc(val, opts));
329
- if (val.tsType) {
330
- buff.push(
331
- `${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${val.tsType},
332
- `
333
- );
334
- } else if (val.type === "object") {
335
- buff.push(
336
- `${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: {`,
337
- ..._genTypes(val, spaces, opts),
338
- "},\n"
339
- );
340
- } else {
341
- let type;
342
- if (val.type === "array") {
343
- type = `Array<${getTsType(val.items || [], opts)}>`;
344
- } else if (val.type === "function") {
345
- type = genFunctionType(val, opts);
346
- } else {
347
- type = getTsType(val, opts);
348
- }
349
- buff.push(
350
- `${genObjectKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${type},
351
- `
352
- );
353
- }
354
- }
355
- if (buff.length > 0) {
356
- const last = buff.pop() || "";
357
- buff.push(last.slice(0, Math.max(0, last.length - 1)));
358
- }
359
- if (opts.allowExtraKeys === true || buff.length === 0 && opts.allowExtraKeys !== false) {
360
- buff.push("[key: string]: any");
361
- }
362
- return buff.flatMap((l) => l.split("\n")).map((l) => spaces + l);
363
- }
364
- function getTsType(type, opts) {
365
- if (Array.isArray(type)) {
366
- return [normalizeTypes(type.map((t) => getTsType(t, opts)))].flat().join("|") || "any";
367
- }
368
- if (!type) {
369
- return "any";
370
- }
371
- if (type.tsType) {
372
- return type.tsType;
373
- }
374
- if (!type.type) {
375
- return "any";
376
- }
377
- if (Array.isArray(type.type)) {
378
- return type.type.map((t) => {
379
- if (t === "object" && type.type.length > 1) {
380
- return `{
381
- ` + _genTypes(type, " ", opts).join("\n") + `
382
- }`;
383
- }
384
- return TYPE_MAP[t];
385
- }).join("|");
386
- }
387
- if (type.type === "array") {
388
- return `Array<${getTsType(type.items || [], opts)}>`;
389
- }
390
- if (type.type === "object") {
391
- return `{
392
- ` + _genTypes(type, " ", opts).join("\n") + `
393
- }`;
394
- }
395
- return TYPE_MAP[type.type] || type.type;
396
- }
397
- function genFunctionType(schema, opts) {
398
- return `(${genFunctionArgs(schema.args, opts)}) => ${getTsType(
399
- schema.returns || [],
400
- opts
401
- )}`;
402
- }
403
- function genFunctionArgs(args, opts) {
404
- return args?.map((arg) => {
405
- let argStr = arg.name;
406
- if (arg.optional || arg.default) {
407
- argStr += "?";
408
- }
409
- if (arg.type || arg.tsType) {
410
- argStr += `: ${getTsType(arg, opts)}`;
411
- }
412
- return argStr;
413
- }).join(", ") || "";
414
- }
415
- function generateJSDoc(schema, opts) {
416
- opts.defaultDescription = opts.defaultDescription || opts.defaultDescrption;
417
- let buff = [];
418
- if (schema.title) {
419
- buff.push(schema.title, "");
420
- }
421
- if (schema.description) {
422
- buff.push(schema.description, "");
423
- } else if (opts.defaultDescription && schema.type !== "object") {
424
- buff.push(opts.defaultDescription, "");
425
- }
426
- if (opts.addDefaults && schema.type !== "object" && schema.type !== "any" && !(Array.isArray(schema.default) && schema.default.length === 0)) {
427
- const stringified = JSON.stringify(schema.default);
428
- if (stringified) {
429
- buff.push(`@default ${stringified.replace(/\*\//g, String.raw`*\/`)}`);
430
- }
431
- }
432
- for (const key in schema) {
433
- if (!SCHEMA_KEYS.has(key)) {
434
- buff.push("", `@${key} ${schema[key]}`);
435
- }
436
- }
437
- if (Array.isArray(schema.tags)) {
438
- for (const tag of schema.tags) {
439
- if (tag !== "@untyped") {
440
- buff.push("", tag);
441
- }
442
- }
443
- }
444
- buff = buff.flatMap((i) => i.split("\n"));
445
- if (buff.length > 0) {
446
- return buff.length === 1 ? ["/** " + buff[0] + " */"] : ["/**", ...buff.map((i) => ` * ${i}`), "*/"];
447
- }
448
- return [];
449
- }
450
- function isRequired(schema, key, opts) {
451
- if (Array.isArray(schema.required) && schema.required.includes(key)) {
452
- return true;
453
- }
454
- return !opts.partial;
455
- }
456
-
457
- // src/generators/dts.ts
458
- function generateDeclaration(schema, generatedBy = "@storm-software/untyped") {
459
- return `
460
- // Generated by ${generatedBy}
461
- // Do not edit this file directly
462
-
463
- ${generateTypes(schema, {
464
- addExport: true,
465
- partial: true,
466
- interfaceName: `${schema.title?.replaceAll(" ", "") || "Type"}Schema`
467
- })}
468
-
469
- `;
470
- }
471
- function generateDeclarationFile(schema, file, generatedBy = "@storm-software/untyped", config) {
472
- try {
473
- const declarations = getOutputFile(file, "d.ts");
474
- writeTrace(`Writing type declaration file ${declarations}`, config);
475
- return writeFile(declarations, generateDeclaration(schema, generatedBy));
476
- } catch (error) {
477
- writeError(
478
- `Error writing declaration file for ${file.name}
479
-
480
- Error:
481
- ${error?.message ? error.message : JSON.stringify(error)}${error?.stack ? `
482
- Stack Trace: ${error.stack}` : ""}
483
-
484
- Parsed schema:
485
- ${JSON.stringify(schema)}
486
- `,
487
- config
488
- );
489
- throw error;
490
- }
491
- }
492
-
493
- export {
494
- mergedTypes,
495
- normalizeTypes,
496
- cachedFn,
497
- getTypeDescriptor,
498
- resolveSchema,
499
- generateDeclaration,
500
- generateDeclarationFile
501
- };