type-flash 1.3.1 → 1.3.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.
- package/README.md +0 -3
- package/dist/index.d.mts +7 -10
- package/dist/index.d.ts +7 -10
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -345,9 +345,6 @@ const code = generate(jsonData, {
|
|
|
345
345
|
### Q: 生成的类型名为什么是 UserProfile 而不是 Profile?
|
|
346
346
|
A: type-flash 默认会用父级类型名 + 字段名来生成子类型名,避免重名。如果想自定义类型名,可以使用 `typeNameMap` 配置。
|
|
347
347
|
|
|
348
|
-
### Q: 为什么数组里的 null 会保留?
|
|
349
|
-
A: 联合类型中的 `null` 会如实保留,例如 `(string | null)[]` 或 `string | null`,与 JSON 数据结构一致。
|
|
350
|
-
|
|
351
348
|
### Q: 支持循环引用的 JSON 吗?
|
|
352
349
|
A: 支持。type-flash 会自动检测循环引用并生成合法的 type alias,不会出现栈溢出。
|
|
353
350
|
|
package/dist/index.d.mts
CHANGED
|
@@ -176,6 +176,10 @@ declare class TypeNamer {
|
|
|
176
176
|
* @returns 类型名,如果是内联类型则返回 null
|
|
177
177
|
*/
|
|
178
178
|
nameType(type: TSTypeNode, context?: NamingContext): string | null;
|
|
179
|
+
/**
|
|
180
|
+
* 注册结构 key 别名(用于结构等价但 key 不同的类型复用同一名称)
|
|
181
|
+
*/
|
|
182
|
+
registerStructKey(structKey: string, name: string): void;
|
|
179
183
|
/**
|
|
180
184
|
* 生成类型名
|
|
181
185
|
*/
|
|
@@ -348,7 +352,7 @@ declare class CodeFormatter {
|
|
|
348
352
|
/**
|
|
349
353
|
* 创建联合类型节点
|
|
350
354
|
*/
|
|
351
|
-
declare function createUnion(types: TSTypeNode[]):
|
|
355
|
+
declare function createUnion(types: TSTypeNode[]): TSTypeNode;
|
|
352
356
|
/**
|
|
353
357
|
* 合并两个类型为联合类型
|
|
354
358
|
*/
|
|
@@ -381,21 +385,14 @@ declare function inferObjectType(obj: Record<string, unknown>, seen?: WeakSet<ob
|
|
|
381
385
|
declare function isStructurallyEqual(a: TSTypeNode, b: TSTypeNode): boolean;
|
|
382
386
|
|
|
383
387
|
/**
|
|
384
|
-
|
|
385
388
|
* type-flash - 增强功能模块
|
|
386
|
-
|
|
387
389
|
*
|
|
388
|
-
|
|
389
390
|
* 核心功能:
|
|
390
|
-
|
|
391
391
|
* - 可选属性处理
|
|
392
|
-
|
|
393
392
|
*/
|
|
394
393
|
|
|
395
394
|
/**
|
|
396
|
-
|
|
397
395
|
* 可选属性处理器
|
|
398
|
-
|
|
399
396
|
*/
|
|
400
397
|
declare class OptionalHandler {
|
|
401
398
|
private markOptional;
|
|
@@ -403,12 +400,12 @@ declare class OptionalHandler {
|
|
|
403
400
|
constructor(markOptional?: boolean);
|
|
404
401
|
process(jsonData: any, type: TSTypeNode): TSTypeNode;
|
|
405
402
|
private processRecursive;
|
|
403
|
+
/** 将子树中对 oldRef 的引用替换为 newRef,保持循环引用一致 */
|
|
404
|
+
private relinkReferences;
|
|
406
405
|
private processArrayObjects;
|
|
407
406
|
}
|
|
408
407
|
/**
|
|
409
|
-
|
|
410
408
|
* 应用所有增强功能
|
|
411
|
-
|
|
412
409
|
*/
|
|
413
410
|
declare function applyEnhancements(jsonData: any, type: TSTypeNode, options: GenerateOptions): TSTypeNode;
|
|
414
411
|
|
package/dist/index.d.ts
CHANGED
|
@@ -176,6 +176,10 @@ declare class TypeNamer {
|
|
|
176
176
|
* @returns 类型名,如果是内联类型则返回 null
|
|
177
177
|
*/
|
|
178
178
|
nameType(type: TSTypeNode, context?: NamingContext): string | null;
|
|
179
|
+
/**
|
|
180
|
+
* 注册结构 key 别名(用于结构等价但 key 不同的类型复用同一名称)
|
|
181
|
+
*/
|
|
182
|
+
registerStructKey(structKey: string, name: string): void;
|
|
179
183
|
/**
|
|
180
184
|
* 生成类型名
|
|
181
185
|
*/
|
|
@@ -348,7 +352,7 @@ declare class CodeFormatter {
|
|
|
348
352
|
/**
|
|
349
353
|
* 创建联合类型节点
|
|
350
354
|
*/
|
|
351
|
-
declare function createUnion(types: TSTypeNode[]):
|
|
355
|
+
declare function createUnion(types: TSTypeNode[]): TSTypeNode;
|
|
352
356
|
/**
|
|
353
357
|
* 合并两个类型为联合类型
|
|
354
358
|
*/
|
|
@@ -381,21 +385,14 @@ declare function inferObjectType(obj: Record<string, unknown>, seen?: WeakSet<ob
|
|
|
381
385
|
declare function isStructurallyEqual(a: TSTypeNode, b: TSTypeNode): boolean;
|
|
382
386
|
|
|
383
387
|
/**
|
|
384
|
-
|
|
385
388
|
* type-flash - 增强功能模块
|
|
386
|
-
|
|
387
389
|
*
|
|
388
|
-
|
|
389
390
|
* 核心功能:
|
|
390
|
-
|
|
391
391
|
* - 可选属性处理
|
|
392
|
-
|
|
393
392
|
*/
|
|
394
393
|
|
|
395
394
|
/**
|
|
396
|
-
|
|
397
395
|
* 可选属性处理器
|
|
398
|
-
|
|
399
396
|
*/
|
|
400
397
|
declare class OptionalHandler {
|
|
401
398
|
private markOptional;
|
|
@@ -403,12 +400,12 @@ declare class OptionalHandler {
|
|
|
403
400
|
constructor(markOptional?: boolean);
|
|
404
401
|
process(jsonData: any, type: TSTypeNode): TSTypeNode;
|
|
405
402
|
private processRecursive;
|
|
403
|
+
/** 将子树中对 oldRef 的引用替换为 newRef,保持循环引用一致 */
|
|
404
|
+
private relinkReferences;
|
|
406
405
|
private processArrayObjects;
|
|
407
406
|
}
|
|
408
407
|
/**
|
|
409
|
-
|
|
410
408
|
* 应用所有增强功能
|
|
411
|
-
|
|
412
409
|
*/
|
|
413
410
|
declare function applyEnhancements(jsonData: any, type: TSTypeNode, options: GenerateOptions): TSTypeNode;
|
|
414
411
|
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var S=Object.defineProperty;var
|
|
2
|
-
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(r){return{kind:"primitive",type:r}}function G(){return{kind:"null"}}function L(){return{kind:"undefined"}}function W(r){return{kind:"array",elementType:r}}function v(r=[]){return{kind:"object",properties:r}}function k(r){let e=[],t=new Set;for(let n of r)if(n.kind==="union")for(let i of n.types){let o=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(n);t.has(i)||(t.add(i),e.push(n))}return e.length===1?e[0]:{kind:"union",types:e}}function p(r,e=new Set){if(e.has(r))return"circular";switch(r.kind){case"primitive":return`primitive:${r.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof r.value}:${String(r.value)}`;case"array":return`array:${p(r.elementType,e)}`;case"object":{e.add(r);let t=`object:${r.properties.map(n=>`${n.name}:${p(n.type,e)}:${n.optional}`).sort().join(",")}`;return e.delete(r),t}case"union":return`union:${r.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${r.name}:${r.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function d(r,e){return p(r)===p(e)?r:r.kind==="object"&&e.kind==="object"?b(r,e):r.kind==="array"&&e.kind==="array"?W(d(r.elementType,e.elementType)):k([r,e])}function b(r,e){let t=new Map;for(let n of r.properties)t.set(n.name,{...n});for(let n of e.properties){let i=t.get(n.name);i?(i.type=d(i.type,n.type),i.optional=i.optional||n.optional):t.set(n.name,{...n,optional:!0})}for(let[n,i]of t)e.properties.some(s=>s.name===n)||(i.optional=!0);return v(Array.from(t.values()))}function K(r){if(r instanceof Date||r instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(r))return u("string");let e=Object.prototype.toString.call(r);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function l(r,e=new WeakSet,t=new WeakMap){if(r===null)return G();if(r===void 0)return L();if(typeof r=="function")return u("Function");if(typeof r=="string")return u("string");if(typeof r=="number")return u("number");if(typeof r=="boolean")return u("boolean");if(Array.isArray(r))return j(r,e,t);if(typeof r=="object"&&r!==null){let n=K(r);if(n)return n;let i=r;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=v([]);t.set(i,o);let s=[];for(let[a,T]of Object.entries(i))s.push({name:a,type:l(T,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function j(r,e,t=new WeakMap){if(r.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let n=r.map(o=>l(o,e,t)),i=n[0];for(let o=1;o<n.length;o++)i=d(i,n[o]);return{kind:"array",elementType:i}}function $(r,e=new WeakSet,t=new WeakMap){return l(r,e,t)}function h(r,e){return r===e?!0:p(r)===p(e)}function c(r,e=new WeakMap){if(e.has(r))return e.get(r);let t;switch(r.kind){case"primitive":return t={kind:"primitive",type:r.type},e.set(r,t),t;case"null":return t={kind:"null"},e.set(r,t),t;case"undefined":return t={kind:"undefined"},e.set(r,t),t;case"literal":return t={kind:"literal",value:r.value},e.set(r,t),t;case"array":return t={kind:"array",elementType:{}},e.set(r,t),t.elementType=c(r.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:r.isRecord,valueType:r.valueType},e.set(r,t),t.properties=r.properties.map(n=>({name:n.name,optional:n.optional,type:c(n.type,e)})),r.valueType&&(t.valueType=c(r.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(r,t),t.types=r.types.map(n=>c(n,e)),t;case"generic":return t={kind:"generic",name:r.name,typeArgs:[]},e.set(r,t),t.typeArgs=r.typeArgs.map(n=>c(n,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(r,t),t}}var f=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let n=this.buildPathKey(t);if(this.customNameMap[n])return this.applyAffixes(this.customNameMap[n]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let o=this.generateName(e,t);return o=this.formatName(o),o=this.ensureUniqueName(o),o=this.applyAffixes(o),this.namedTypes.set(i,o),o}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let n=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${n}`:n}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let n=`${e}${t+1}`;return this.nameCounter.set(e,t+1),n}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return p(e)}getSimpleTypeKey(e){return p(e)}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},y=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset(),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let n=this.collected.find(o=>o.name===t),i=this.collected.filter(o=>o.name!==t);return n?[n,...i]:this.collected}collectRecursive(e,t){let n=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(n)){this.seenStructs.add(n),this.collected.push({name:i,type:c(e)});for(let o of e.properties)this.collectRecursive(o.type,{fieldName:o.name,parentName:i,path:t.path?`${t.path}.${o.name}`:o.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return p(e)}};var m=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||h(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:n}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,n,i)}formatObjectType(e,t,n){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${n}interface ${e} {`):s.push(`${n}type ${e} = {`);for(let a of o){let T=this.formatPropertyName(a.name),P=a.optional?"?":"",w=this.formatType(a.type);s.push(`${i}${T}${P}: ${w};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),n=this.sortProperties(e.properties);if(n.length===0)return"{}";let i=["{"];for(let o of n){let s=this.formatPropertyName(o.name),a=o.optional?"?":"",T=this.formatType(o.type);i.push(`${t}${s}${a}: ${T};`)}return i.push("}"),this.joinLines(i)}formatUnionType(e){return e.map(t=>this.formatType(t)).join(" | ")}formatPropertyName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:`'${e}'`}sortProperties(e){return this.options.sortProperties==="definition"?[...e]:[...e].sort((t,n)=>t.name.localeCompare(n.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`${this.eol}${this.eol}`)}generateOutput(e,t){let n=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${n}${this.eol}${this.eol}${i}${this.eol}`}};var g=class{constructor(e=!0){this.seen=new WeakSet;this.markOptional=e}process(e,t){return this.markOptional?this.processRecursive(e,t):t}processRecursive(e,t){if(t.kind==="array"&&Array.isArray(e)){let n=t.elementType;if(n.kind==="object"){let i=this.processArrayObjects(e,n);return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e,n)}}if(t.kind==="object"&&e&&typeof e=="object"){if(this.seen.has(t))return t;this.seen.add(t);let n={...t,properties:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of n.properties)i.type===t&&(i.type=n);return this.seen.delete(t),n}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(n=>this.processRecursive(e,n))}:t}processArrayObjects(e,t){if(e.length<=1)return t;let n={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))n[s]=(n[s]||0)+1;return{...t,properties:t.properties.map(o=>{let a=(n[o.name]||0)<i;return{...o,optional:a}})}}};function N(r,e,t){return t.markOptional?new g(t.markOptional).process(r,e):e}function O(r,e={}){let t={...x,...e},n=l(r);n=N(r,n,t);let i=new f({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new y(i).collect(n,t.rootName);return new m(t,i).generateOutput(s,t.rootName)}function A(r,e={}){let t=JSON.parse(r);return O(t,e)}var _={generate:O,generateFromString:A};0&&(module.exports={CodeFormatter,OptionalHandler,TypeCollector,TypeNamer,applyEnhancements,createUnion,generate,generateFromString,inferArrayType,inferObjectType,inferType,isStructurallyEqual,mergeObjects,mergeTypes});
|
|
1
|
+
"use strict";var S=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var U=(r,e)=>{for(var t in e)S(r,t,{get:e[t],enumerable:!0})},E=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of D(e))!M.call(r,i)&&i!==t&&S(r,i,{get:()=>e[i],enumerable:!(n=C(e,i))||n.enumerable});return r};var G=r=>E(S({},"__esModule",{value:!0}),r);var q={};U(q,{CodeFormatter:()=>T,OptionalHandler:()=>h,TypeCollector:()=>m,TypeNamer:()=>y,applyEnhancements:()=>N,createUnion:()=>b,default:()=>_,generate:()=>x,generateFromString:()=>P,inferArrayType:()=>O,inferObjectType:()=>A,inferType:()=>l,isStructurallyEqual:()=>f,mergeObjects:()=>j,mergeTypes:()=>g});module.exports=G(q);var v={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,markOptional:!0,indentSize:2,lineEnding:`
|
|
2
|
+
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(r){return{kind:"primitive",type:r}}function k(){return{kind:"null"}}function L(){return{kind:"undefined"}}function K(r){return{kind:"array",elementType:r}}function $(r=[]){return{kind:"object",properties:r}}function b(r){let e=[],t=new Set;for(let n of r)if(n.kind==="union")for(let i of n.types){let o=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(n);t.has(i)||(t.add(i),e.push(n))}return e.some(n=>n.kind==="null")?k():e.length===1?e[0]:{kind:"union",types:e}}function p(r,e=new Set){if(e.has(r))return"circular";switch(r.kind){case"primitive":return`primitive:${r.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof r.value}:${String(r.value)}`;case"array":return`array:${p(r.elementType,e)}`;case"object":{e.add(r);let t=`object:${r.properties.map(n=>n.type===r||e.has(n.type)?`${n.name}:self:${n.optional}`:`${n.name}:${p(n.type,e)}:${n.optional}`).sort().join(",")}`;return e.delete(r),t}case"union":return`union:${r.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${r.name}:${r.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function g(r,e){return p(r)===p(e)?r:r.kind==="null"||e.kind==="null"?k():r.kind==="object"&&e.kind==="object"?j(r,e):r.kind==="array"&&e.kind==="array"?K(g(r.elementType,e.elementType)):b([r,e])}function j(r,e){let t=new Map;for(let n of r.properties)t.set(n.name,{...n});for(let n of e.properties){let i=t.get(n.name);i?(i.type=g(i.type,n.type),i.optional=i.optional||n.optional):t.set(n.name,{...n,optional:!0})}for(let[n,i]of t)e.properties.some(s=>s.name===n)||(i.optional=!0);return $(Array.from(t.values()))}function W(r){if(r instanceof Date||r instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(r))return u("string");let e=Object.prototype.toString.call(r);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function l(r,e=new WeakSet,t=new WeakMap){if(r===null)return k();if(r===void 0)return L();if(typeof r=="function")return u("Function");if(typeof r=="string")return u("string");if(typeof r=="number")return u("number");if(typeof r=="boolean")return u("boolean");if(Array.isArray(r))return O(r,e,t);if(typeof r=="object"&&r!==null){let n=W(r);if(n)return n;let i=r;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=$([]);t.set(i,o);let s=[];for(let[a,d]of Object.entries(i))s.push({name:a,type:l(d,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function O(r,e,t=new WeakMap){if(r.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let n=r.map(o=>l(o,e,t)),i=n[0];for(let o=1;o<n.length;o++)i=g(i,n[o]);return{kind:"array",elementType:i}}function A(r,e=new WeakSet,t=new WeakMap){return l(r,e,t)}function f(r,e){return r===e?!0:p(r)===p(e)}function c(r,e=new WeakMap){if(e.has(r))return e.get(r);let t;switch(r.kind){case"primitive":return t={kind:"primitive",type:r.type},e.set(r,t),t;case"null":return t={kind:"null"},e.set(r,t),t;case"undefined":return t={kind:"undefined"},e.set(r,t),t;case"literal":return t={kind:"literal",value:r.value},e.set(r,t),t;case"array":return t={kind:"array",elementType:{}},e.set(r,t),t.elementType=c(r.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:r.isRecord,valueType:r.valueType},e.set(r,t),t.properties=r.properties.map(n=>({name:n.name,optional:n.optional,type:c(n.type,e)})),r.valueType&&(t.valueType=c(r.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(r,t),t.types=r.types.map(n=>c(n,e)),t;case"generic":return t={kind:"generic",name:r.name,typeArgs:[]},e.set(r,t),t.typeArgs=r.typeArgs.map(n=>c(n,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(r,t),t}}var y=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let n=this.buildPathKey(t);if(this.customNameMap[n])return this.applyAffixes(this.customNameMap[n]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let o=this.generateName(e,t);return o=this.formatName(o),o=this.ensureUniqueName(o),o=this.applyAffixes(o),this.namedTypes.set(i,o),o}registerStructKey(e,t){this.namedTypes.set(e,t)}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let n=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${n}`:n}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let n=`${e}${t+1}`;return this.nameCounter.set(e,t+1),n}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return p(e)}getSimpleTypeKey(e){return p(e)}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},m=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset(),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let n=this.collected.find(o=>o.name===t),i=this.collected.filter(o=>o.name!==t);return n?[n,...i]:this.collected}collectRecursive(e,t){let n=this.getStructKey(e);if(e.kind==="object"){let i=this.collected.find(s=>f(s.type,e));if(i){this.namer.registerStructKey(n,i.name);return}let o=this.namer.nameType(e,t);if(o&&!this.seenStructs.has(n)){this.seenStructs.add(n),this.collected.push({name:o,type:c(e)});for(let s of e.properties)this.collectRecursive(s.type,{fieldName:s.name,parentName:o,path:t.path?`${t.path}.${s.name}`:s.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return p(e)}};var T=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||f(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:n}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,n,i)}formatObjectType(e,t,n){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${n}interface ${e} {`):s.push(`${n}type ${e} = {`);for(let a of o){let d=this.formatPropertyName(a.name),w=a.optional?"?":"",R=this.formatType(a.type);s.push(`${i}${d}${w}: ${R};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),n=this.sortProperties(e.properties);if(n.length===0)return"{}";let i=["{"];for(let o of n){let s=this.formatPropertyName(o.name),a=o.optional?"?":"",d=this.formatType(o.type);i.push(`${t}${s}${a}: ${d};`)}return i.push("}"),this.joinLines(i)}formatUnionType(e){return e.map(t=>this.formatType(t)).join(" | ")}formatPropertyName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:`'${e}'`}sortProperties(e){return this.options.sortProperties==="definition"?[...e]:[...e].sort((t,n)=>t.name.localeCompare(n.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`${this.eol}${this.eol}`)}generateOutput(e,t){let n=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${n}${this.eol}${this.eol}${i}${this.eol}`}};var h=class{constructor(e=!0){this.seen=new WeakSet;this.markOptional=e}process(e,t){return this.markOptional?this.processRecursive(e,t):t}processRecursive(e,t){if(t.kind==="array"&&Array.isArray(e)){let{elementType:n}=t;if(n.kind==="object"){let i=e.length>1?this.processArrayObjects(e,n):n;for(let o of e)o!==null&&typeof o=="object"&&!Array.isArray(o)&&(i=this.processRecursive(o,i));return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e[0],n)}}if(t.kind==="object"&&e&&typeof e=="object"&&!Array.isArray(e)){if(this.seen.has(t))return t;this.seen.add(t);let n={...t,properties:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of n.properties)i.type=this.relinkReferences(i.type,t,n);return this.seen.delete(t),n}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(n=>this.processRecursive(e,n))}:t}relinkReferences(e,t,n){if(e===t)return n;switch(e.kind){case"array":return{...e,elementType:this.relinkReferences(e.elementType,t,n)};case"object":return{...e,properties:e.properties.map(i=>({...i,type:this.relinkReferences(i.type,t,n)}))};case"union":return{...e,types:e.types.map(i=>this.relinkReferences(i,t,n))};default:return e}}processArrayObjects(e,t){if(e.length<=1)return t;let n={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))n[s]=(n[s]||0)+1;return{...t,properties:t.properties.map(o=>{let a=(n[o.name]||0)<i;return{...o,optional:a}})}}};function N(r,e,t){return t.markOptional?new h(t.markOptional).process(r,e):e}function x(r,e={}){let t={...v,...e},n=l(r);n=N(r,n,t);let i=new y({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new m(i).collect(n,t.rootName);return new T(t,i).generateOutput(s,t.rootName)}function P(r,e={}){let t=JSON.parse(r);return x(t,e)}var _={generate:x,generateFromString:P};0&&(module.exports={CodeFormatter,OptionalHandler,TypeCollector,TypeNamer,applyEnhancements,createUnion,generate,generateFromString,inferArrayType,inferObjectType,inferType,isStructurallyEqual,mergeObjects,mergeTypes});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(r){return{kind:"primitive",type:r}}function A(){return{kind:"null"}}function P(){return{kind:"undefined"}}function w(r){return{kind:"array",elementType:r}}function k(r=[]){return{kind:"object",properties:r}}function b(r){let e=[],t=new Set;for(let n of r)if(n.kind==="union")for(let i of n.types){let o=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(n);t.has(i)||(t.add(i),e.push(n))}return e.length===1?e[0]:{kind:"union",types:e}}function p(r,e=new Set){if(e.has(r))return"circular";switch(r.kind){case"primitive":return`primitive:${r.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof r.value}:${String(r.value)}`;case"array":return`array:${p(r.elementType,e)}`;case"object":{e.add(r);let t=`object:${r.properties.map(n=>`${n.name}:${p(n.type,e)}:${n.optional}`).sort().join(",")}`;return e.delete(r),t}case"union":return`union:${r.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${r.name}:${r.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function d(r,e){return p(r)===p(e)?r:r.kind==="object"&&e.kind==="object"?j(r,e):r.kind==="array"&&e.kind==="array"?w(d(r.elementType,e.elementType)):b([r,e])}function j(r,e){let t=new Map;for(let n of r.properties)t.set(n.name,{...n});for(let n of e.properties){let i=t.get(n.name);i?(i.type=d(i.type,n.type),i.optional=i.optional||n.optional):t.set(n.name,{...n,optional:!0})}for(let[n,i]of t)e.properties.some(s=>s.name===n)||(i.optional=!0);return k(Array.from(t.values()))}function R(r){if(r instanceof Date||r instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(r))return u("string");let e=Object.prototype.toString.call(r);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function l(r,e=new WeakSet,t=new WeakMap){if(r===null)return A();if(r===void 0)return P();if(typeof r=="function")return u("Function");if(typeof r=="string")return u("string");if(typeof r=="number")return u("number");if(typeof r=="boolean")return u("boolean");if(Array.isArray(r))return O(r,e,t);if(typeof r=="object"&&r!==null){let n=R(r);if(n)return n;let i=r;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=k([]);t.set(i,o);let s=[];for(let[a,f]of Object.entries(i))s.push({name:a,type:l(f,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function O(r,e,t=new WeakMap){if(r.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let n=r.map(o=>l(o,e,t)),i=n[0];for(let o=1;o<n.length;o++)i=d(i,n[o]);return{kind:"array",elementType:i}}function C(r,e=new WeakSet,t=new WeakMap){return l(r,e,t)}function h(r,e){return r===e?!0:p(r)===p(e)}function c(r,e=new WeakMap){if(e.has(r))return e.get(r);let t;switch(r.kind){case"primitive":return t={kind:"primitive",type:r.type},e.set(r,t),t;case"null":return t={kind:"null"},e.set(r,t),t;case"undefined":return t={kind:"undefined"},e.set(r,t),t;case"literal":return t={kind:"literal",value:r.value},e.set(r,t),t;case"array":return t={kind:"array",elementType:{}},e.set(r,t),t.elementType=c(r.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:r.isRecord,valueType:r.valueType},e.set(r,t),t.properties=r.properties.map(n=>({name:n.name,optional:n.optional,type:c(n.type,e)})),r.valueType&&(t.valueType=c(r.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(r,t),t.types=r.types.map(n=>c(n,e)),t;case"generic":return t={kind:"generic",name:r.name,typeArgs:[]},e.set(r,t),t.typeArgs=r.typeArgs.map(n=>c(n,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(r,t),t}}var y=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let n=this.buildPathKey(t);if(this.customNameMap[n])return this.applyAffixes(this.customNameMap[n]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let o=this.generateName(e,t);return o=this.formatName(o),o=this.ensureUniqueName(o),o=this.applyAffixes(o),this.namedTypes.set(i,o),o}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let n=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${n}`:n}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let n=`${e}${t+1}`;return this.nameCounter.set(e,t+1),n}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return p(e)}getSimpleTypeKey(e){return p(e)}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},m=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset(),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let n=this.collected.find(o=>o.name===t),i=this.collected.filter(o=>o.name!==t);return n?[n,...i]:this.collected}collectRecursive(e,t){let n=this.getStructKey(e);if(e.kind==="object"){let i=this.namer.nameType(e,t);if(i&&!this.seenStructs.has(n)){this.seenStructs.add(n),this.collected.push({name:i,type:c(e)});for(let o of e.properties)this.collectRecursive(o.type,{fieldName:o.name,parentName:i,path:t.path?`${t.path}.${o.name}`:o.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return p(e)}};var T=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||h(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:n}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,n,i)}formatObjectType(e,t,n){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${n}interface ${e} {`):s.push(`${n}type ${e} = {`);for(let a of o){let f=this.formatPropertyName(a.name),v=a.optional?"?":"",$=this.formatType(a.type);s.push(`${i}${f}${v}: ${$};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),n=this.sortProperties(e.properties);if(n.length===0)return"{}";let i=["{"];for(let o of n){let s=this.formatPropertyName(o.name),a=o.optional?"?":"",f=this.formatType(o.type);i.push(`${t}${s}${a}: ${f};`)}return i.push("}"),this.joinLines(i)}formatUnionType(e){return e.map(t=>this.formatType(t)).join(" | ")}formatPropertyName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:`'${e}'`}sortProperties(e){return this.options.sortProperties==="definition"?[...e]:[...e].sort((t,n)=>t.name.localeCompare(n.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`${this.eol}${this.eol}`)}generateOutput(e,t){let n=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${n}${this.eol}${this.eol}${i}${this.eol}`}};var g=class{constructor(e=!0){this.seen=new WeakSet;this.markOptional=e}process(e,t){return this.markOptional?this.processRecursive(e,t):t}processRecursive(e,t){if(t.kind==="array"&&Array.isArray(e)){let n=t.elementType;if(n.kind==="object"){let i=this.processArrayObjects(e,n);return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e,n)}}if(t.kind==="object"&&e&&typeof e=="object"){if(this.seen.has(t))return t;this.seen.add(t);let n={...t,properties:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of n.properties)i.type===t&&(i.type=n);return this.seen.delete(t),n}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(n=>this.processRecursive(e,n))}:t}processArrayObjects(e,t){if(e.length<=1)return t;let n={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))n[s]=(n[s]||0)+1;return{...t,properties:t.properties.map(o=>{let a=(n[o.name]||0)<i;return{...o,optional:a}})}}};function N(r,e,t){return t.markOptional?new g(t.markOptional).process(r,e):e}function x(r,e={}){let t={...S,...e},n=l(r);n=N(r,n,t);let i=new y({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new m(i).collect(n,t.rootName);return new T(t,i).generateOutput(s,t.rootName)}function D(r,e={}){let t=JSON.parse(r);return x(t,e)}var Z={generate:x,generateFromString:D};export{T as CodeFormatter,g as OptionalHandler,m as TypeCollector,y as TypeNamer,N as applyEnhancements,b as createUnion,Z as default,x as generate,D as generateFromString,O as inferArrayType,C as inferObjectType,l as inferType,h as isStructurallyEqual,j as mergeObjects,d as mergeTypes};
|
|
1
|
+
var k={rootName:"Root",outputStyle:"interface",namingStyle:"PascalCase",sortProperties:"alpha",addExport:!0,markOptional:!0,indentSize:2,lineEnding:`
|
|
2
|
+
`,typeNameMap:{},typePrefix:"",typeSuffix:""};function u(n){return{kind:"primitive",type:n}}function N(){return{kind:"null"}}function P(){return{kind:"undefined"}}function w(n){return{kind:"array",elementType:n}}function b(n=[]){return{kind:"object",properties:n}}function j(n){let e=[],t=new Set;for(let r of n)if(r.kind==="union")for(let i of r.types){let o=p(i);t.has(o)||(t.add(o),e.push(i))}else{let i=p(r);t.has(i)||(t.add(i),e.push(r))}return e.some(r=>r.kind==="null")?N():e.length===1?e[0]:{kind:"union",types:e}}function p(n,e=new Set){if(e.has(n))return"circular";switch(n.kind){case"primitive":return`primitive:${n.type}`;case"null":return"null";case"undefined":return"undefined";case"literal":return`literal:${typeof n.value}:${String(n.value)}`;case"array":return`array:${p(n.elementType,e)}`;case"object":{e.add(n);let t=`object:${n.properties.map(r=>r.type===n||e.has(r.type)?`${r.name}:self:${r.optional}`:`${r.name}:${p(r.type,e)}:${r.optional}`).sort().join(",")}`;return e.delete(n),t}case"union":return`union:${n.types.map(t=>p(t,e)).sort().join("|")}`;case"generic":return`generic:${n.name}:${n.typeArgs.map(t=>p(t,e)).join(",")}`;default:return"unknown"}}function g(n,e){return p(n)===p(e)?n:n.kind==="null"||e.kind==="null"?N():n.kind==="object"&&e.kind==="object"?O(n,e):n.kind==="array"&&e.kind==="array"?w(g(n.elementType,e.elementType)):j([n,e])}function O(n,e){let t=new Map;for(let r of n.properties)t.set(r.name,{...r});for(let r of e.properties){let i=t.get(r.name);i?(i.type=g(i.type,r.type),i.optional=i.optional||r.optional):t.set(r.name,{...r,optional:!0})}for(let[r,i]of t)e.properties.some(s=>s.name===r)||(i.optional=!0);return b(Array.from(t.values()))}function R(n){if(n instanceof Date||n instanceof RegExp||typeof Buffer!="undefined"&&Buffer.isBuffer(n))return u("string");let e=Object.prototype.toString.call(n);return e==="[object Date]"||e==="[object RegExp]"?u("string"):e==="[object Map]"||e==="[object Set]"||e==="[object WeakMap]"||e==="[object WeakSet]"?u("unknown"):null}function l(n,e=new WeakSet,t=new WeakMap){if(n===null)return N();if(n===void 0)return P();if(typeof n=="function")return u("Function");if(typeof n=="string")return u("string");if(typeof n=="number")return u("number");if(typeof n=="boolean")return u("boolean");if(Array.isArray(n))return x(n,e,t);if(typeof n=="object"&&n!==null){let r=R(n);if(r)return r;let i=n;if(e.has(i)){let a=t.get(i);if(a)return a}e.add(i);let o=b([]);t.set(i,o);let s=[];for(let[a,f]of Object.entries(i))s.push({name:a,type:l(f,e,t),optional:!1});return o.properties=s,e.delete(i),o}return u("unknown")}function x(n,e,t=new WeakMap){if(n.length===0)return{kind:"array",elementType:{kind:"primitive",type:"unknown"}};let r=n.map(o=>l(o,e,t)),i=r[0];for(let o=1;o<r.length;o++)i=g(i,r[o]);return{kind:"array",elementType:i}}function C(n,e=new WeakSet,t=new WeakMap){return l(n,e,t)}function y(n,e){return n===e?!0:p(n)===p(e)}function c(n,e=new WeakMap){if(e.has(n))return e.get(n);let t;switch(n.kind){case"primitive":return t={kind:"primitive",type:n.type},e.set(n,t),t;case"null":return t={kind:"null"},e.set(n,t),t;case"undefined":return t={kind:"undefined"},e.set(n,t),t;case"literal":return t={kind:"literal",value:n.value},e.set(n,t),t;case"array":return t={kind:"array",elementType:{}},e.set(n,t),t.elementType=c(n.elementType,e),t;case"object":return t={kind:"object",properties:[],isRecord:n.isRecord,valueType:n.valueType},e.set(n,t),t.properties=n.properties.map(r=>({name:r.name,optional:r.optional,type:c(r.type,e)})),n.valueType&&(t.valueType=c(n.valueType,e)),t;case"union":return t={kind:"union",types:[]},e.set(n,t),t.types=n.types.map(r=>c(r,e)),t;case"generic":return t={kind:"generic",name:n.name,typeArgs:[]},e.set(n,t),t.typeArgs=n.typeArgs.map(r=>c(r,e)),t;default:return t={kind:"primitive",type:"unknown"},e.set(n,t),t}}var m=class{constructor(e={}){this.namedTypes=new Map;this.nameCounter=new Map;this.processing=new WeakSet;this.circularRefs=new Map;this.namingStyle=e.namingStyle||"PascalCase",this.prefix=e.prefix||"",this.suffix=e.suffix||"",this.customNameMap=e.customNameMap||{}}nameType(e,t={depth:0}){if(e.kind!=="object")return null;let r=this.buildPathKey(t);if(this.customNameMap[r])return this.applyAffixes(this.customNameMap[r]);let i=this.getTypeKey(e);if(this.namedTypes.has(i))return this.namedTypes.get(i);let o=this.generateName(e,t);return o=this.formatName(o),o=this.ensureUniqueName(o),o=this.applyAffixes(o),this.namedTypes.set(i,o),o}registerStructKey(e,t){this.namedTypes.set(e,t)}generateName(e,t){if(e.kind==="object"){if(t.fieldName){let r=this.toPascalCase(t.fieldName);return t.parentName?`${t.parentName}${r}`:r}return t.parentName?`${t.parentName}Item`:"AnonymousObject"}return"UnknownType"}ensureUniqueName(e){let t=this.nameCounter.get(e)||0;if(t===0)return this.nameCounter.set(e,1),e;let r=`${e}${t+1}`;return this.nameCounter.set(e,t+1),r}applyAffixes(e){let t=e;return this.prefix&&(t=this.toPascalCase(this.prefix)+t),this.suffix&&(t=t+this.toPascalCase(this.suffix)),t}buildPathKey(e){return e.path||""}getTypeKey(e){return p(e)}getSimpleTypeKey(e){return p(e)}toPascalCase(e){return e?e.replace(/[-_\s]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim().split(" ").filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):""}toCamelCase(e){let t=this.toPascalCase(e);return t.charAt(0).toLowerCase()+t.slice(1)}formatName(e){return this.namingStyle==="camelCase"?this.toCamelCase(e):this.toPascalCase(e)}isCircular(e){return this.processing.has(e)}markProcessing(e){this.processing.add(e)}unmarkProcessing(e){this.processing.delete(e)}getAllNamedTypes(){return new Map(this.namedTypes)}reset(){this.namedTypes.clear(),this.nameCounter.clear(),this.processing=new WeakSet,this.circularRefs.clear()}},T=class{constructor(e){this.collected=[];this.seenStructs=new Set;this.namer=e}collect(e,t){this.collected=[],this.seenStructs.clear(),this.namer.reset(),this.collectRecursive(e,{fieldName:t,parentName:void 0,path:t,depth:0});let r=this.collected.find(o=>o.name===t),i=this.collected.filter(o=>o.name!==t);return r?[r,...i]:this.collected}collectRecursive(e,t){let r=this.getStructKey(e);if(e.kind==="object"){let i=this.collected.find(s=>y(s.type,e));if(i){this.namer.registerStructKey(r,i.name);return}let o=this.namer.nameType(e,t);if(o&&!this.seenStructs.has(r)){this.seenStructs.add(r),this.collected.push({name:o,type:c(e)});for(let s of e.properties)this.collectRecursive(s.type,{fieldName:s.name,parentName:o,path:t.path?`${t.path}.${s.name}`:s.name,depth:t.depth+1})}return}if(e.kind==="array"){this.collectRecursive(e.elementType,{fieldName:t.fieldName?t.fieldName+"Item":void 0,parentName:t.parentName,path:t.path,depth:t.depth+1});return}if(e.kind==="union"){for(let i of e.types)this.collectRecursive(i,t);return}if(e.kind==="generic"){for(let i of e.typeArgs)this.collectRecursive(i,{...t,depth:t.depth+1});return}}getStructKey(e){return p(e)}};var d=class{constructor(e,t){this.allNamedTypes=[];this.options=e,this.namer=t}get eol(){return this.options.lineEnding}joinLines(e){return e.join(this.eol)}findTypeName(e){if(e.kind!=="object")return null;for(let t of this.allNamedTypes)if(t.type===e||y(t.type,e))return t.name;return null}formatTypeDef(e){let{name:t,type:r}=e,i=this.options.addExport?"export ":"";return this.formatObjectType(t,r,i)}formatObjectType(e,t,r){let i=" ".repeat(this.options.indentSize),o=this.sortProperties(t.properties),s=[];this.options.outputStyle==="interface"?s.push(`${r}interface ${e} {`):s.push(`${r}type ${e} = {`);for(let a of o){let f=this.formatPropertyName(a.name),$=a.optional?"?":"",A=this.formatType(a.type);s.push(`${i}${f}${$}: ${A};`)}return this.options.outputStyle==="interface"?s.push("}"):s.push("};"),this.joinLines(s)}formatType(e){if(e.kind==="object"){let t=this.findTypeName(e);if(t)return t}switch(e.kind){case"primitive":return e.type;case"null":return"null";case"undefined":return"undefined";case"array":return this.formatArrayType(e);case"object":return this.formatInlineObject(e);case"union":return this.formatUnionType(e.types);case"literal":return this.formatLiteral(e.value);case"generic":return`${e.name}<${e.typeArgs.map(t=>this.formatType(t)).join(", ")}>`;default:return"unknown"}}formatLiteral(e){return typeof e=="string"?`'${e}'`:String(e)}formatArrayType(e){let t=this.formatType(e.elementType);return e.elementType.kind==="union"?`(${t})[]`:`${t}[]`}formatInlineObject(e){let t=" ".repeat(this.options.indentSize),r=this.sortProperties(e.properties);if(r.length===0)return"{}";let i=["{"];for(let o of r){let s=this.formatPropertyName(o.name),a=o.optional?"?":"",f=this.formatType(o.type);i.push(`${t}${s}${a}: ${f};`)}return i.push("}"),this.joinLines(i)}formatUnionType(e){return e.map(t=>this.formatType(t)).join(" | ")}formatPropertyName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:`'${e}'`}sortProperties(e){return this.options.sortProperties==="definition"?[...e]:[...e].sort((t,r)=>t.name.localeCompare(r.name))}formatAll(e){return this.allNamedTypes=e,e.map(t=>this.formatTypeDef(t)).join(`${this.eol}${this.eol}`)}generateOutput(e,t){let r=this.joinLines(["/**"," * Generated by type-flash",` * Root type: ${t}`," */"]),i=this.formatAll(e);return`${r}${this.eol}${this.eol}${i}${this.eol}`}};var h=class{constructor(e=!0){this.seen=new WeakSet;this.markOptional=e}process(e,t){return this.markOptional?this.processRecursive(e,t):t}processRecursive(e,t){if(t.kind==="array"&&Array.isArray(e)){let{elementType:r}=t;if(r.kind==="object"){let i=e.length>1?this.processArrayObjects(e,r):r;for(let o of e)o!==null&&typeof o=="object"&&!Array.isArray(o)&&(i=this.processRecursive(o,i));return{...t,elementType:i}}return{...t,elementType:this.processRecursive(e[0],r)}}if(t.kind==="object"&&e&&typeof e=="object"&&!Array.isArray(e)){if(this.seen.has(t))return t;this.seen.add(t);let r={...t,properties:t.properties.map(i=>i.type===t?{...i}:{...i,type:this.processRecursive(e[i.name],i.type)})};for(let i of r.properties)i.type=this.relinkReferences(i.type,t,r);return this.seen.delete(t),r}return t.kind==="union"&&Array.isArray(e)?{...t,types:t.types.map(r=>this.processRecursive(e,r))}:t}relinkReferences(e,t,r){if(e===t)return r;switch(e.kind){case"array":return{...e,elementType:this.relinkReferences(e.elementType,t,r)};case"object":return{...e,properties:e.properties.map(i=>({...i,type:this.relinkReferences(i.type,t,r)}))};case"union":return{...e,types:e.types.map(i=>this.relinkReferences(i,t,r))};default:return e}}processArrayObjects(e,t){if(e.length<=1)return t;let r={},i=e.length;for(let o of e)if(o&&typeof o=="object")for(let s of Object.keys(o))r[s]=(r[s]||0)+1;return{...t,properties:t.properties.map(o=>{let a=(r[o.name]||0)<i;return{...o,optional:a}})}}};function S(n,e,t){return t.markOptional?new h(t.markOptional).process(n,e):e}function v(n,e={}){let t={...k,...e},r=l(n);r=S(n,r,t);let i=new m({namingStyle:t.namingStyle,prefix:t.typePrefix,suffix:t.typeSuffix,customNameMap:t.typeNameMap}),s=new T(i).collect(r,t.rootName);return new d(t,i).generateOutput(s,t.rootName)}function D(n,e={}){let t=JSON.parse(n);return v(t,e)}var F={generate:v,generateFromString:D};export{d as CodeFormatter,h as OptionalHandler,T as TypeCollector,m as TypeNamer,S as applyEnhancements,j as createUnion,F as default,v as generate,D as generateFromString,x as inferArrayType,C as inferObjectType,l as inferType,y as isStructurallyEqual,O as mergeObjects,g as mergeTypes};
|