admindb 2.1.1 → 2.3.0

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 (119) hide show
  1. package/README.md +368 -335
  2. package/dist/app.js +227 -1
  3. package/dist/auth/config.d.ts +1 -1
  4. package/dist/auth/config.js +109 -1
  5. package/dist/auth/crypto.js +98 -1
  6. package/dist/auth/index.js +21 -1
  7. package/dist/auth/middleware.js +78 -1
  8. package/dist/auth/routes.js +64 -1
  9. package/dist/auth/types.js +7 -1
  10. package/dist/cli/args.d.ts +1 -1
  11. package/dist/cli/args.js +309 -1
  12. package/dist/cli/config.js +118 -1
  13. package/dist/cli/index.js +20 -1
  14. package/dist/cli/runner.js +208 -1
  15. package/dist/cli.js +4 -1
  16. package/dist/data/chain.d.ts +1 -0
  17. package/dist/data/chain.js +130 -0
  18. package/dist/data/datasets.d.ts +1 -1
  19. package/dist/data/datasets.js +171 -1
  20. package/dist/data/detector.d.ts +1 -1
  21. package/dist/data/detector.js +535 -1
  22. package/dist/data/engine.d.ts +1 -1
  23. package/dist/data/engine.js +586 -1
  24. package/dist/data/index.d.ts +1 -1
  25. package/dist/data/index.js +30 -1
  26. package/dist/data/prng.d.ts +1 -0
  27. package/dist/data/prng.js +73 -0
  28. package/dist/data/registry.d.ts +1 -0
  29. package/dist/data/registry.js +805 -0
  30. package/dist/data/schema-graph.d.ts +1 -0
  31. package/dist/data/schema-graph.js +210 -0
  32. package/dist/data/strategies.d.ts +1 -1
  33. package/dist/data/strategies.js +100 -1
  34. package/dist/data/templates.d.ts +1 -0
  35. package/dist/data/templates.js +134 -0
  36. package/dist/data/types.d.ts +1 -1
  37. package/dist/data/types.js +5 -1
  38. package/dist/data/validator.d.ts +1 -0
  39. package/dist/data/validator.js +160 -0
  40. package/dist/db/database.d.ts +1 -1
  41. package/dist/db/database.js +472 -1
  42. package/dist/db/export.d.ts +1 -1
  43. package/dist/db/export.js +67 -1
  44. package/dist/db/filters.d.ts +1 -1
  45. package/dist/db/filters.js +119 -1
  46. package/dist/db/index.js +24 -1
  47. package/dist/db/introspection.js +164 -1
  48. package/dist/db/manager.js +327 -1
  49. package/dist/db/migrations.js +100 -1
  50. package/dist/db/postgres.d.ts +1 -1
  51. package/dist/db/postgres.js +687 -1
  52. package/dist/db/types.d.ts +1 -1
  53. package/dist/db/types.js +6 -1
  54. package/dist/index.d.ts +1 -1
  55. package/dist/index.js +52 -1
  56. package/dist/public/css/app.css +1 -1
  57. package/dist/public/js/api.js +1 -1
  58. package/dist/public/js/browse.js +1 -1
  59. package/dist/public/js/common.js +1 -0
  60. package/dist/public/js/databases.js +1 -1
  61. package/dist/public/js/designer.js +1 -1
  62. package/dist/public/js/forms.js +1 -1
  63. package/dist/public/js/home.js +1 -0
  64. package/dist/public/js/inspector.js +1 -1
  65. package/dist/public/js/query.js +1 -1
  66. package/dist/public/js/schema.js +1 -1
  67. package/dist/public/js/seed.js +1 -1
  68. package/dist/routes/api/erd.d.ts +1 -0
  69. package/dist/routes/api/erd.js +45 -0
  70. package/dist/routes/api/helpers.d.ts +1 -1
  71. package/dist/routes/api/helpers.js +213 -1
  72. package/dist/routes/api/import-export.js +82 -1
  73. package/dist/routes/api/index.js +48 -1
  74. package/dist/routes/api/query.js +74 -1
  75. package/dist/routes/api/rows.js +358 -1
  76. package/dist/routes/api/seed.js +167 -1
  77. package/dist/routes/api/tables.js +216 -1
  78. package/dist/routes/databases.js +210 -1
  79. package/dist/routes/index.js +19 -1
  80. package/dist/routes/pages.js +446 -1
  81. package/dist/serverless.js +149 -1
  82. package/dist/sql/classifier.js +24 -1
  83. package/dist/sql/error-analyzer.d.ts +1 -0
  84. package/dist/sql/error-analyzer.js +550 -0
  85. package/dist/sql/generator.d.ts +1 -1
  86. package/dist/sql/generator.js +245 -1
  87. package/dist/sql/index.js +18 -1
  88. package/dist/types/api.d.ts +1 -1
  89. package/dist/types/api.js +2 -1
  90. package/dist/utils/colors.js +54 -1
  91. package/dist/utils/common.d.ts +1 -1
  92. package/dist/utils/common.js +185 -1
  93. package/dist/utils/csv.d.ts +1 -1
  94. package/dist/utils/csv.js +61 -1
  95. package/dist/utils/datatype.js +167 -1
  96. package/dist/utils/icons.js +81 -1
  97. package/dist/utils/index.js +20 -1
  98. package/dist/utils/logger.js +36 -1
  99. package/dist/views/layouts/main.hbs +1 -74
  100. package/dist/views/pages/databases.hbs +1 -233
  101. package/dist/views/pages/designer.hbs +1 -89
  102. package/dist/views/pages/erd.hbs +1 -0
  103. package/dist/views/pages/error.hbs +1 -10
  104. package/dist/views/pages/form.hbs +1 -59
  105. package/dist/views/pages/home.hbs +1 -124
  106. package/dist/views/pages/info.hbs +1 -0
  107. package/dist/views/pages/login.hbs +1 -98
  108. package/dist/views/pages/query.hbs +1 -87
  109. package/dist/views/pages/schema.hbs +1 -298
  110. package/dist/views/pages/seed-select.hbs +251 -0
  111. package/dist/views/pages/seed.hbs +273 -167
  112. package/dist/views/pages/table.hbs +1 -327
  113. package/dist/views/partials/navbar.hbs +1 -83
  114. package/dist/views/partials/sidebar.hbs +1 -117
  115. package/docs/API.md +149 -144
  116. package/docs/EXAMPLES.md +579 -576
  117. package/docs/SECURITY.md +265 -265
  118. package/package.json +79 -78
  119. package/dist/public/js/icons.js +0 -1
@@ -1 +1,535 @@
1
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.normName=void 0,exports.isTimestampName=isTimestampName,exports.findInMap=findInMap,exports.extractCheckExprs=extractCheckExprs,exports.parseChecks=parseChecks,exports.detectPlan=detectPlan,exports.buildColumnConfigs=function(info){const fkByColumn=new Map(info.foreignKeys.map(fk=>[fk.from,fk])),uniqueCols=new Set,jsonIndexKeys=new Map;for(const ix of info.indexes??[])if(ix.unique&&1===ix.columns.length&&ix.columns[0]&&uniqueCols.add(ix.columns[0]),ix.sql&&/json_extract|->>|->\s*'|json_/i.test(ix.sql))for(const{col:col,keys:keys}of extractJsonColumns(ix.sql)){if(!col)continue;const merged=new Set([...jsonIndexKeys.get(col)??[],...keys]);merged.size&&jsonIndexKeys.set(col,[...merged])}const checkInfo=parseChecks(info.sql??null);return info.columns.map(col=>{const fk=fkByColumn.get(col.name)??null,strategies=(0,strategies_1.strategiesFor)(col,fk),unique=uniqueCols.has(col.name);let defaultPlan=detectPlan(col,fk);if("fk"!==defaultPlan.strategy&&!col.pk&&function(col,hasJsonIndex){if(!(0,strategies_1.isTextishType)(col.type))return!1;if(hasJsonIndex)return!0;const dflt=String(col.dflt_value??"").trim();if(dflt.startsWith("{")||dflt.startsWith("'{\""))return!0;const name=(0,exports.normName)(col.name);return/^(permissions|settings|config|configuration|preferences|prefs|metadata|meta|attributes|payload|options|allowedapps|socialaccounts|positions|fcmtokens|fcm_tokens|scopes|profile|json|jsonb)$/.test(name)||/(^|_)(settings|config|configuration|permissions|prefs|metadata|attributes|payload|options|allowedapps|scopes|profile)$/.test(name)}(col,jsonIndexKeys.has(col.name))){const keys=jsonIndexKeys.get(col.name),useKeys=keys&&keys.length?keys:["scope","enabled","allowedApps"],allowed=findInMap(checkInfo.jsonAllowed,col.name),jsonValues={};if(allowed)for(const k of useKeys){const vals=allowed.get(k);vals&&vals.length&&(jsonValues[k]=vals)}defaultPlan={strategy:"json",jsonKeys:useKeys,...Object.keys(jsonValues).length?{jsonValues:jsonValues}:{}}}const colAllowed=findInMap(checkInfo.columnAllowed,col.name);colAllowed&&colAllowed.length>0&&"fk"!==defaultPlan.strategy&&!col.pk&&(defaultPlan=1===colAllowed.length?{strategy:"fixed",value:colAllowed[0]}:{strategy:"list",values:[...colAllowed]});const colRange=findInMap(checkInfo.columnRange,col.name);return!colRange||"int"!==defaultPlan.strategy&&"decimal"!==defaultPlan.strategy||(null!=colRange.min&&(defaultPlan.min=colRange.min),null!=colRange.max&&(defaultPlan.max=colRange.max)),strategies.some(s=>s.id===defaultPlan.strategy)&&(col.pk||!col.notnull||null!=col.dflt_value||"skip"!==defaultPlan.strategy&&"null"!==defaultPlan.strategy)||(defaultPlan=(0,strategies_1.fallbackPlanFor)(col)),{name:col.name,type:col.type,pk:col.pk>0,notnull:!!col.notnull,hasDefault:null!=col.dflt_value,unique:unique,fk:fk,strategies:strategies,defaultPlan:defaultPlan}})},exports.sanitizeColumnPlan=function(raw){if(!raw||"object"!=typeof raw)return null;const r=raw;if("string"!=typeof r.strategy||!r.strategy)return null;const out={strategy:r.strategy};void 0!==r.values&&null!==r.values&&Array.isArray(r.values)&&(out.values=r.values.map(x=>String(x)));if(void 0!==r.jsonKeys&&null!==r.jsonKeys){const rawKeys=Array.isArray(r.jsonKeys)?r.jsonKeys.map(String):String(r.jsonKeys).split(/[,;]/);out.jsonKeys=rawKeys.map(s=>s.trim()).filter(Boolean)}for(const key of STR_PLAN_KEYS)void 0!==r[key]&&null!==r[key]&&(out[key]=String(r[key]));for(const key of NUM_PLAN_KEYS)if(void 0!==r[key]&&null!==r[key]){const n=Number(r[key]);Number.isFinite(n)&&(out[key]=n)}if(r.jsonValues&&"object"==typeof r.jsonValues&&!Array.isArray(r.jsonValues)){const jv={};for(const[k,vals]of Object.entries(r.jsonValues))if(Array.isArray(vals)){const cleaned=vals.map(x=>String(x).trim()).filter(Boolean);cleaned.length&&(jv[k]=cleaned)}Object.keys(jv).length&&(out.jsonValues=jv)}return out};const strategies_1=require("./strategies");function isTimestampName(name){return/created|updated|modified|registered|joined|timestamp|lastused|lastseen|lastlogin|lastactivity|accessed|viewed|visited|^ts$/.test(name)||/^(created|updated|deleted|archived|occurred|started|ended|expires|published|processed|completed|inserted|requested|resolved|used|seen|accessed|viewed|visited|logged|active)at$/.test(name)}function findInMap(map,colName){if(map.has(colName))return map.get(colName);const lower=colName.toLowerCase();for(const[k,v]of map.entries())if(k.toLowerCase()===lower)return v}function extractCheckExprs(sql){const out=[],re=/CHECK\s*\(/gi;let m;for(;m=re.exec(sql);){let depth=1,i=m.index+m[0].length;const start=i;for(;i<sql.length&&depth>0;){const ch=sql[i];if("'"!==ch){if('"'===ch||"`"===ch||"["===ch){const close="["===ch?"]":ch;for(i+=1;i<sql.length&&sql[i]!==close;)sql[i]===close&&sql[i+1]===close?i+=2:i+=1;i+=1;continue}if("("===ch)depth+=1;else if(")"===ch&&(depth-=1,0===depth))break;i+=1}else for(i+=1;i<sql.length;)if("'"===sql[i]){if("'"!==sql[i+1]){i+=1;break}i+=2}else i+=1}out.push(sql.slice(start,i))}return out}function parseChecks(sql){const info={columnAllowed:new Map,columnRange:new Map,jsonAllowed:new Map,ordering:new Map};if(!sql)return info;const setOrdering=(col,other,key,orEqual)=>{const c=info.ordering.get(col)??{};c[key]={column:other,orEqual:orEqual},info.ordering.set(col,c)},setColumnAllowed=(col,vals)=>{if(!col||!vals.length)return;const existing=findInMap(info.columnAllowed,col);if(existing)for(const v of vals)existing.includes(v)||existing.push(v);else info.columnAllowed.set(col,[...vals])};for(const expr of extractCheckExprs(sql)){const jw1=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(?:->>|->)\s*'([^']+)'\s*\)*\s*IN\s*\(([^)]*)\)/gi,jw2=/json_extract\s*\(\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'\s*\)\s*\)*\s*IN\s*\(([^)]*)\)/gi;for(const re of[jw1,jw2]){let m;for(;m=re.exec(expr);){const col=m[1]||m[2]||m[3]||m[4],key=m[5],inContent=m[6],strValues=(inContent.match(/'(?:[^']|'')*'/g)??[]).map(s=>s.slice(1,-1).replace(/''/g,"'")),values=strValues.length?strValues:inContent.match(/-?\b\d+(?:\.\d+)?\b/g)??[];if(values.length&&col&&key){const byCol=findInMap(info.jsonAllowed,col)??new Map;byCol.set(key,values),info.jsonAllowed.set(col,byCol)}}}const colIn=/(?:^|[^(->>\w])(?:\(\s*)?(?:(?:lower|upper|trim|coalesce)\s*\(\s*)?(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*,\s*[^)]+)?\s*\)?\s*\)?\s*IN\s*\(([^)]*)\)/gi;let mColIn;for(;mColIn=colIn.exec(expr);){const col=mColIn[1]||mColIn[2]||mColIn[3]||mColIn[4];if(!col||["json_extract","strftime","datetime","date","length","typeof"].includes(col.toLowerCase()))continue;const matchPos=mColIn.index;if(expr.slice(Math.max(0,matchPos-5),matchPos).includes("->"))continue;const inContent=mColIn[5],strValues=(inContent.match(/'(?:[^']|'')*'/g)??[]).map(s=>s.slice(1,-1).replace(/''/g,"'")),values=strValues.length?strValues:inContent.match(/-?\b\d+(?:\.\d+)?\b/g)??[];values.length&&setColumnAllowed(col,values)}const eqOr=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*=\s*'((?:[^']|'')*)'/gi;let mEq;const eqByCol=new Map;for(;mEq=eqOr.exec(expr);){const col=mEq[1]||mEq[2]||mEq[3]||mEq[4],val=mEq[5].replace(/''/g,"'");if(col&&!["json_extract","lower","upper","trim","strftime","datetime"].includes(col.toLowerCase())){const cur=eqByCol.get(col)??[];cur.includes(val)||cur.push(val),eqByCol.set(col,cur)}}for(const[col,vals]of eqByCol.entries())setColumnAllowed(col,vals);const numCmp1=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|>|<=|<)\s*(-?\d+(?:\.\d+)?)/g;let mNum1;for(;mNum1=numCmp1.exec(expr);){const col=mNum1[1]||mNum1[2]||mNum1[3]||mNum1[4],op=mNum1[5],val=Number(mNum1[6]);if(col&&Number.isFinite(val)&&!["json_extract","length","strftime","datetime"].includes(col.toLowerCase())){const cur=findInMap(info.columnRange,col)??{};">="===op||">"===op?cur.min=null!=cur.min?Math.max(cur.min,">"===op?val+1:val):">"===op?val+1:val:cur.max=null!=cur.max?Math.min(cur.max,"<"===op?val-1:val):"<"===op?val-1:val,info.columnRange.set(col,cur)}}const ord=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|<=|>|<)\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))/g;let m2;for(;m2=ord.exec(expr);){const a=m2[1]||m2[2]||m2[3]||m2[4],op=m2[5],b=m2[6]||m2[7]||m2[8]||m2[9];a&&b&&!/^\d+$/.test(a)&&!/^\d+$/.test(b)&&(["json_extract","strftime","datetime","date","length"].includes(a.toLowerCase())||["json_extract","strftime","datetime","date","length"].includes(b.toLowerCase())||(">"===op||">="===op?(setOrdering(a,b,"after",">="===op),setOrdering(b,a,"before",">="===op)):(setOrdering(a,b,"before","<="===op),setOrdering(b,a,"after","<="===op))))}}return info}exports.normName=s=>String(s).toLowerCase().replace(/[^a-z0-9]/g,"");const isHashName=name=>/^(hash|digest|secret|passphrase)$|tokenhash|passwordhash|passhash|accesskey|apikey|api_key|secretkey|clientsecret|appsecret|appid|privatekey|publickey/.test(name),isTokenName=name=>/^prefix$|tokenprefix|(code|ref|reference|sku|ticketno|ticketnum|orderno|order_no|trackingno|trackingnum|invno|invoiceno|serialno)$/.test(name);function extractJsonColumns(sql){const out=[],push=(col,key)=>{let entry=out.find(e=>e.col===col);if(entry||(entry={col:col,keys:[]},out.push(entry)),key){const last=key.split(".").pop().replace(/[\[\]"]/g,"");last&&!entry.keys.includes(last)&&entry.keys.push(last)}},arrow=/"([^"]+)"\s*(?:->>|->)\s*'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)\s*(?:->>|->)\s*'([^']+)'/g;let m;for(;m=arrow.exec(sql);)push(m[1]||m[3],m[2]||m[4]);const jx=/json_extract\s*\(\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'/g;for(;m=jx.exec(sql);)push(m[1]||m[2],m[3]);return out}const TEXT_PATTERNS=[[/avatar|picture|photo|image|img|thumbnail|icon|logo/,()=>({strategy:"avatar"})],[/company|organization|org|firm|corp|employer|agency/,()=>({strategy:"company"})],[/job|title|role|position|occupation|profession/,()=>({strategy:"job"})],[/currency|curr|currencycode/,()=>({strategy:"currency"})],[/countrycode|countryiso|isocountry|cca2/,()=>({strategy:"countryCode"})],[/state|province|region/,n=>/status|statement/.test(n)?{strategy:"status"}:{strategy:"state"}],[/status|stage|phase|state/,()=>({strategy:"status"})],[/color|colour|theme|hexcolor/,()=>({strategy:"color",format:"hex"})],[/mac|macaddress|hwaddr/,()=>({strategy:"mac"})],[/creditcard|cardnumber|cardno|ccnumber|ccno/,()=>({strategy:"creditCard"})],[/slug|permalink|handle|alias/,()=>({strategy:"slug"})],[/(lastname|surname|familyname)/,()=>({strategy:"last"})],[/email|mail/,()=>({strategy:"email"})],[/(username|login|handle|nick|nickname|account|user)/,()=>({strategy:"username"})],[/(phone|mobile|telephone|cell|fax)/,()=>({strategy:"phone"})],[/city|town/,()=>({strategy:"city"})],[/country|nation/,()=>({strategy:"country"})],[/postal|zip/,()=>({strategy:"postal"})],[/address|street|addr/,()=>({strategy:"address"})],[/url|website|site|link|homepage|href/,()=>({strategy:"url"})],[/domain|host/,()=>({strategy:"domain"})],[/^ip$|ipaddr|ipv4|ip_address/,()=>({strategy:"ip"})],[/bio|about|overview|article|body|post|story/,()=>({strategy:"paragraph"})],[/description|content|comment|message|note|summary|details|remarks/,()=>({strategy:"sentence",minLen:1,maxLen:2})],[/title|subject|category|type|tag|label/,()=>({strategy:"words",minLen:1,maxLen:3})]];function detectPlan(col,fk){const type=(col.type||"").toUpperCase(),rawName=col.name.toLowerCase(),name=(0,exports.normName)(col.name);if(fk)return{strategy:"fk"};if(col.pk)return type.startsWith("INT")||"SERIAL"===type||"BIGSERIAL"===type?{strategy:"skip"}:"TEXT"===type||"BLOB"===type||"UUID"===type?{strategy:"uuid"}:{strategy:"skip"};if("UUID"===type)return{strategy:"uuid"};if("JSON"===type||"JSONB"===type)return{strategy:"json"};if("INET"===type)return{strategy:"ip"};if("BOOLEAN"===type||"BOOL"===type)return{strategy:"bool"};if("BYTEA"===type||"BLOB"===type)return{strategy:"bytes",minLen:8,maxLen:32};if((type.startsWith("INT")||type.startsWith("INTEGER"))&&/(^|_)(is|has|can|should|did)_|_flag$|active|enabled|verified|published|deleted|archived|paid|completed|approved/.test(rawName))return{strategy:"bool"};if("DATE"===type||/^date|birthdate|dob|birthday/.test(rawName))return name.includes("birth")?{strategy:"date",from:"1950-01-01",to:"2000-12-31"}:{strategy:"date",from:"2020-01-01",to:"2026-12-31"};if("DATETIME"===type||"TIMESTAMP"===type||isTimestampName(name))return{strategy:"datetime",from:"2024-01-01T00:00:00",to:"2026-12-31T23:59:59"};if("TIME"===type||"time"===name)return{strategy:"time"};if(type.startsWith("INTEGER")&&/(timestamp|epoch|unix|createdtime|updatedtime)/.test(name))return{strategy:"timestampUnix",format:"sec"};if(/^(lat|latitude)$/.test(name))return{strategy:"latitude"};if(/^(lng|lon|longitude)$/.test(name))return{strategy:"longitude"};if(type.startsWith("INTEGER"))return name.includes("year")?{strategy:"int",min:1990,max:2026}:name.includes("age")?{strategy:"int",min:18,max:90}:/(count|quantity|qty|stock|views|likes|total|num|number)$/.test(name)?{strategy:"int",min:0,max:1e5}:name.includes("rating")||name.includes("score")?{strategy:"int",min:1,max:5}:/(order|rank|position|seq|sequence|priority|sort|step)$/.test(name)?{strategy:"sequence",start:1,step:1}:{strategy:"int",min:1,max:1e3};if("REAL"===type||type.includes("DECIMAL")||type.includes("NUMERIC")||type.includes("FLOAT")||type.includes("DOUBLE"))return/(price|cost|amount|total|salary|balance|fee|charge|budget)/.test(name)?{strategy:"decimal",min:1,max:5e3,precision:2}:name.includes("rating")?{strategy:"decimal",min:1,max:5,precision:1}:{strategy:"decimal",min:1,max:1e3,precision:2};if("BLOB"===type)return{strategy:"bytes",minLen:8,maxLen:32};if(/currency|curr|currencycode/.test(name))return{strategy:"currency"};if(/countrycode|countryiso|isocountry|cca2/.test(name))return{strategy:"countryCode"};if(/state|province|region/.test(name)&&!/status|statement/.test(name))return{strategy:"state"};if(/status|stage|phase|state/.test(name))return{strategy:"status"};if(/color|colour|theme|hexcolor/.test(name))return{strategy:"color",format:"hex"};if(/mac|macaddress|hwaddr/.test(name))return{strategy:"mac"};if(/creditcard|cardnumber|cardno|ccnumber|ccno/.test(name))return{strategy:"creditCard"};if(/slug|permalink|handle|alias/.test(name))return{strategy:"slug"};if(isHashName(name))return{strategy:"hash",minLen:32,maxLen:64};if(isTokenName(name))return{strategy:"token",minLen:6,maxLen:12};if(/uuid|guid/.test(name)||"id"===name||"uid"===name||"key"===name)return{strategy:"uuid"};if(name.includes("first")&&name.includes("name"))return{strategy:"first"};if(/(lastname|surname|familyname)/.test(name)||name.includes("last")&&name.includes("name"))return{strategy:"last"};if("name"===name||"fullname"===name||name.includes("full")&&name.includes("name"))return{strategy:"fullname"};for(const[pattern,createPlan]of TEXT_PATTERNS)if(pattern.test(name))return createPlan(name);return{strategy:"words",minLen:1,maxLen:4}}const STR_PLAN_KEYS=["value","from","to","prefix","suffix","pattern","format"],NUM_PLAN_KEYS=["min","max","precision","minLen","maxLen","nullPct","start","step"];
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normName = void 0;
4
+ exports.isTimestampName = isTimestampName;
5
+ exports.findInMap = findInMap;
6
+ exports.extractCheckExprs = extractCheckExprs;
7
+ exports.parseChecks = parseChecks;
8
+ exports.detectPlan = detectPlan;
9
+ exports.buildColumnConfigs = buildColumnConfigs;
10
+ exports.sanitizeColumnPlan = sanitizeColumnPlan;
11
+ const strategies_1 = require("./strategies");
12
+ const normName = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
13
+ exports.normName = normName;
14
+ function isTimestampName(name) {
15
+ return (/created|updated|modified|registered|joined|timestamp|lastused|lastseen|lastlogin|lastactivity|accessed|viewed|visited|^ts$/.test(name) ||
16
+ /^(created|updated|deleted|archived|occurred|started|ended|expires|published|processed|completed|inserted|requested|resolved|used|seen|accessed|viewed|visited|logged|active)at$/.test(name));
17
+ }
18
+ function findInMap(map, colName) {
19
+ if (map.has(colName))
20
+ return map.get(colName);
21
+ const lower = colName.toLowerCase();
22
+ for (const [k, v] of map.entries()) {
23
+ if (k.toLowerCase() === lower)
24
+ return v;
25
+ }
26
+ return undefined;
27
+ }
28
+ function extractCheckExprs(sql) {
29
+ const out = [];
30
+ const re = /CHECK\s*\(/gi;
31
+ let m;
32
+ while ((m = re.exec(sql))) {
33
+ let depth = 1;
34
+ let i = m.index + m[0].length;
35
+ const start = i;
36
+ while (i < sql.length && depth > 0) {
37
+ const ch = sql[i];
38
+ if (ch === "'") {
39
+ i++;
40
+ while (i < sql.length) {
41
+ if (sql[i] === "'") {
42
+ if (sql[i + 1] === "'")
43
+ i += 2;
44
+ else {
45
+ i++;
46
+ break;
47
+ }
48
+ }
49
+ else
50
+ i++;
51
+ }
52
+ continue;
53
+ }
54
+ if (ch === '"' || ch === '`' || ch === '[') {
55
+ const close = ch === '[' ? ']' : ch;
56
+ i++;
57
+ while (i < sql.length && sql[i] !== close) {
58
+ if (sql[i] === close && sql[i + 1] === close)
59
+ i += 2;
60
+ else
61
+ i++;
62
+ }
63
+ i++;
64
+ continue;
65
+ }
66
+ if (ch === '(')
67
+ depth++;
68
+ else if (ch === ')') {
69
+ depth--;
70
+ if (depth === 0)
71
+ break;
72
+ }
73
+ i++;
74
+ }
75
+ out.push(sql.slice(start, i));
76
+ }
77
+ return out;
78
+ }
79
+ function parseChecks(sql) {
80
+ const info = {
81
+ columnAllowed: new Map(),
82
+ columnRange: new Map(),
83
+ columnLength: new Map(),
84
+ jsonAllowed: new Map(),
85
+ ordering: new Map(),
86
+ };
87
+ if (!sql)
88
+ return info;
89
+ const setOrdering = (col, other, key, orEqual) => {
90
+ const c = info.ordering.get(col) ?? {};
91
+ c[key] = { column: other, orEqual };
92
+ info.ordering.set(col, c);
93
+ };
94
+ const setColumnAllowed = (col, vals) => {
95
+ if (!col || !vals.length)
96
+ return;
97
+ const existing = findInMap(info.columnAllowed, col);
98
+ if (existing) {
99
+ for (const v of vals)
100
+ if (!existing.includes(v))
101
+ existing.push(v);
102
+ }
103
+ else {
104
+ info.columnAllowed.set(col, [...vals]);
105
+ }
106
+ };
107
+ for (const expr of extractCheckExprs(sql)) {
108
+ const jw1 = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(?:->>|->)\s*'([^']+)'\s*(?:\)\s*)*IN\s*\(([^)]*)\)/gi;
109
+ const jw2 = /json_extract\s*\(\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'\s*\)\s*(?:\)\s*)*IN\s*\(([^)]*)\)/gi;
110
+ for (const re of [jw1, jw2]) {
111
+ let m;
112
+ while ((m = re.exec(expr))) {
113
+ const col = m[1] || m[2] || m[3] || m[4];
114
+ const key = m[5];
115
+ const inContent = m[6];
116
+ const strValues = (inContent.match(/'(?:[^']|'')*'/g) ?? []).map((s) => s.slice(1, -1).replace(/''/g, "'"));
117
+ const values = strValues.length ? strValues : (inContent.match(/-?\b\d+(?:\.\d+)?\b/g) ?? []);
118
+ if (values.length && col && key) {
119
+ const byCol = findInMap(info.jsonAllowed, col) ?? new Map();
120
+ byCol.set(key, values);
121
+ info.jsonAllowed.set(col, byCol);
122
+ }
123
+ }
124
+ }
125
+ const colIn = /(?:^|[^\w"'\`\[])(?:\s*\(\s*)*(?:(?:lower|upper|trim|coalesce)\s*\(\s*)?(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*,\s*[^)]+)?(?:\s*\)\s*)*\s*IN\s*\(([^)]*)\)/gi;
126
+ let mColIn;
127
+ while ((mColIn = colIn.exec(expr))) {
128
+ const col = mColIn[1] || mColIn[2] || mColIn[3] || mColIn[4];
129
+ if (!col || ['json_extract', 'strftime', 'datetime', 'date', 'length', 'typeof'].includes(col.toLowerCase()))
130
+ continue;
131
+ if (expr.slice(Math.max(0, mColIn.index - 5), mColIn.index).includes('->'))
132
+ continue;
133
+ const inContent = mColIn[5];
134
+ const strValues = (inContent.match(/'(?:[^']|'')*'/g) ?? []).map((s) => s.slice(1, -1).replace(/''/g, "'"));
135
+ const values = strValues.length ? strValues : (inContent.match(/-?\b\d+(?:\.\d+)?\b/g) ?? []);
136
+ if (values.length)
137
+ setColumnAllowed(col, values);
138
+ }
139
+ const eqOr = /(?:^|[^\w"'\`\[])(?:\s*\(\s*)*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*\)\s*)*\s*=\s*'((?:[^']|'')*)'/gi;
140
+ let mEq;
141
+ const eqByCol = new Map();
142
+ while ((mEq = eqOr.exec(expr))) {
143
+ const col = mEq[1] || mEq[2] || mEq[3] || mEq[4];
144
+ const val = mEq[5].replace(/''/g, "'");
145
+ if (col && !['json_extract', 'lower', 'upper', 'trim', 'strftime', 'datetime'].includes(col.toLowerCase())) {
146
+ const cur = eqByCol.get(col) ?? [];
147
+ if (!cur.includes(val))
148
+ cur.push(val);
149
+ eqByCol.set(col, cur);
150
+ }
151
+ }
152
+ for (const [col, vals] of eqByCol.entries())
153
+ setColumnAllowed(col, vals);
154
+ const numCmp1 = /(?:^|[^\w"'\`\[])(?:\s*\(\s*)*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*\)\s*)*\s*(>=|>|<=|<)\s*(-?\d+(?:\.\d+)?)/g;
155
+ let mNum1;
156
+ while ((mNum1 = numCmp1.exec(expr))) {
157
+ const col = mNum1[1] || mNum1[2] || mNum1[3] || mNum1[4];
158
+ const op = mNum1[5];
159
+ const val = Number(mNum1[6]);
160
+ if (col && Number.isFinite(val) && !['json_extract', 'length', 'strftime', 'datetime'].includes(col.toLowerCase())) {
161
+ const cur = findInMap(info.columnRange, col) ?? {};
162
+ if (op === '>=' || op === '>')
163
+ cur.min = cur.min != null ? Math.max(cur.min, op === '>' ? val + 1 : val) : (op === '>' ? val + 1 : val);
164
+ else
165
+ cur.max = cur.max != null ? Math.min(cur.max, op === '<' ? val - 1 : val) : (op === '<' ? val - 1 : val);
166
+ info.columnRange.set(col, cur);
167
+ }
168
+ }
169
+ const lenRe1 = /length\s*\(\s*(?:\s*\(\s*)*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*\)\s*)*\s*\)\s*(=|==|>=|>|<=|<)\s*(\d+)/gi;
170
+ let mLen1;
171
+ while ((mLen1 = lenRe1.exec(expr))) {
172
+ const col = mLen1[1] || mLen1[2] || mLen1[3] || mLen1[4];
173
+ const op = mLen1[5];
174
+ const val = Number(mLen1[6]);
175
+ if (col && Number.isFinite(val)) {
176
+ const cur = findInMap(info.columnLength, col) ?? {};
177
+ if (op === '=' || op === '==') {
178
+ cur.exact = val;
179
+ cur.min = val;
180
+ cur.max = val;
181
+ }
182
+ else if (op === '>=' || op === '>') {
183
+ cur.min = op === '>' ? val + 1 : val;
184
+ }
185
+ else if (op === '<=' || op === '<') {
186
+ cur.max = op === '<' ? val - 1 : val;
187
+ }
188
+ info.columnLength.set(col, cur);
189
+ }
190
+ }
191
+ const ord = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|<=|>|<)\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))/g;
192
+ let m2;
193
+ while ((m2 = ord.exec(expr))) {
194
+ const a = m2[1] || m2[2] || m2[3] || m2[4];
195
+ const op = m2[5];
196
+ const b = m2[6] || m2[7] || m2[8] || m2[9];
197
+ if (!a || !b || /^\d+$/.test(a) || /^\d+$/.test(b))
198
+ continue;
199
+ if (['json_extract', 'strftime', 'datetime', 'date', 'length'].includes(a.toLowerCase()))
200
+ continue;
201
+ if (['json_extract', 'strftime', 'datetime', 'date', 'length'].includes(b.toLowerCase()))
202
+ continue;
203
+ if (op === '>' || op === '>=') {
204
+ setOrdering(a, b, 'after', op === '>=');
205
+ setOrdering(b, a, 'before', op === '>=');
206
+ }
207
+ else {
208
+ setOrdering(a, b, 'before', op === '<=');
209
+ setOrdering(b, a, 'after', op === '<=');
210
+ }
211
+ }
212
+ }
213
+ return info;
214
+ }
215
+ const isHashName = (name) => /^(hash|digest|secret|passphrase)$|tokenhash|passwordhash|passhash|accesskey|apikey|api_key|secretkey|clientsecret|appsecret|appid|privatekey|publickey/.test(name);
216
+ const isTokenName = (name) => /^prefix$|tokenprefix|(code|ref|reference|sku|ticketno|ticketnum|orderno|order_no|trackingno|trackingnum|invno|invoiceno|serialno)$/.test(name);
217
+ function isJsonColumn(col, hasJsonIndex) {
218
+ if (!(0, strategies_1.isTextishType)(col.type))
219
+ return false;
220
+ if (hasJsonIndex)
221
+ return true;
222
+ const dflt = String(col.dflt_value ?? '').trim();
223
+ if (dflt.startsWith('{') || dflt.startsWith("'{\""))
224
+ return true;
225
+ const name = (0, exports.normName)(col.name);
226
+ return /^(permissions|settings|config|configuration|preferences|prefs|metadata|meta|attributes|payload|options|allowedapps|socialaccounts|positions|fcmtokens|fcm_tokens|scopes|profile|json|jsonb)$/.test(name) ||
227
+ /(^|_)(settings|config|configuration|permissions|prefs|metadata|attributes|payload|options|allowedapps|scopes|profile)$/.test(name);
228
+ }
229
+ function extractJsonColumns(sql) {
230
+ const out = [];
231
+ const push = (col, key) => {
232
+ let entry = out.find((e) => e.col === col);
233
+ if (!entry) {
234
+ entry = { col, keys: [] };
235
+ out.push(entry);
236
+ }
237
+ if (key) {
238
+ const last = key.split('.').pop().replace(/[\[\]"]/g, '');
239
+ if (last && !entry.keys.includes(last))
240
+ entry.keys.push(last);
241
+ }
242
+ };
243
+ const arrow = /"([^"]+)"\s*(?:->>|->)\s*'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)\s*(?:->>|->)\s*'([^']+)'/g;
244
+ let m;
245
+ while ((m = arrow.exec(sql)))
246
+ push(m[1] || m[3], m[2] || m[4]);
247
+ const jx = /json_extract\s*\(\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'/g;
248
+ while ((m = jx.exec(sql)))
249
+ push(m[1] || m[2], m[3]);
250
+ return out;
251
+ }
252
+ const TEXT_PATTERNS = [
253
+ [/avatar|picture|photo|image|img|thumbnail|icon|logo/, () => ({ strategy: 'avatar' })],
254
+ [/company|organization|org|firm|corp|employer|agency/, () => ({ strategy: 'company' })],
255
+ [/department|division|dept/, () => ({ strategy: 'department' })],
256
+ [/productcategory|categoryname|^category$/, () => ({ strategy: 'productCategory' })],
257
+ [/productname|producttitle|^product$|^item$|itemname/, () => ({ strategy: 'product' })],
258
+ [/paymentmethod|paymenttype|paymentmode|paymentprovider/, () => ({ strategy: 'paymentMethod' })],
259
+ [/transactiontype|txntype|txtype/, () => ({ strategy: 'transactionType' })],
260
+ [/techskill|skill|skills|techstack|technology/, () => ({ strategy: 'techSkill' })],
261
+ [/orderstatus|shipmentstatus|deliverystatus/, () => ({ strategy: 'orderStatus' })],
262
+ [/job|title|role|position|occupation|profession/, () => ({ strategy: 'job' })],
263
+ [/currency|curr|currencycode/, () => ({ strategy: 'currency' })],
264
+ [/countrycode|countryiso|isocountry|cca2/, () => ({ strategy: 'countryCode' })],
265
+ [/state|province|region/, (n) => (/status|statement/.test(n) ? { strategy: 'status' } : { strategy: 'state' })],
266
+ [/status|stage|phase|state/, () => ({ strategy: 'status' })],
267
+ [/color|colour|theme|hexcolor/, () => ({ strategy: 'color', format: 'hex' })],
268
+ [/mac|macaddress|hwaddr/, () => ({ strategy: 'mac' })],
269
+ [/creditcard|cardnumber|cardno|ccnumber|ccno/, () => ({ strategy: 'creditCard' })],
270
+ [/slug|permalink|handle|alias/, () => ({ strategy: 'slug' })],
271
+ [/(lastname|surname|familyname)/, () => ({ strategy: 'last' })],
272
+ [/email|mail/, () => ({ strategy: 'email' })],
273
+ [/(username|login|handle|nick|nickname|account|user)/, () => ({ strategy: 'username' })],
274
+ [/(phone|mobile|telephone|cell|fax)/, () => ({ strategy: 'phone' })],
275
+ [/city|town/, () => ({ strategy: 'city' })],
276
+ [/country|nation/, () => ({ strategy: 'country' })],
277
+ [/postal|zip/, () => ({ strategy: 'postal' })],
278
+ [/address|street|addr/, () => ({ strategy: 'address' })],
279
+ [/url|website|site|link|homepage|href/, () => ({ strategy: 'url' })],
280
+ [/domain|host/, () => ({ strategy: 'domain' })],
281
+ [/^ip$|ipaddr|ipv4|ip_address/, () => ({ strategy: 'ip' })],
282
+ [/bio|about|overview|article|body|post|story/, () => ({ strategy: 'paragraph' })],
283
+ [/description|content|comment|message|note|summary|details|remarks/, () => ({ strategy: 'sentence', minLen: 1, maxLen: 2 })],
284
+ [/title|subject|category|type|tag|label/, () => ({ strategy: 'words', minLen: 1, maxLen: 3 })],
285
+ ];
286
+ function detectPlan(col, fk) {
287
+ const type = (col.type || '').toUpperCase();
288
+ const rawName = col.name.toLowerCase();
289
+ const name = (0, exports.normName)(col.name);
290
+ if (fk)
291
+ return { strategy: 'fk' };
292
+ if (col.pk) {
293
+ if (type.startsWith('INT') || type === 'SERIAL' || type === 'BIGSERIAL')
294
+ return { strategy: 'skip' };
295
+ if (type.includes('TEXT') || type.includes('CHAR') || type.includes('VARCHAR') || type.includes('STRING') || type === 'BLOB' || type === 'UUID')
296
+ return { strategy: 'uuid' };
297
+ if (col.notnull && col.dflt_value == null)
298
+ return { strategy: 'uuid' };
299
+ return { strategy: 'skip' };
300
+ }
301
+ if (type === 'UUID')
302
+ return { strategy: 'uuid' };
303
+ if (type === 'JSON' || type === 'JSONB')
304
+ return { strategy: 'json' };
305
+ if (type === 'INET')
306
+ return { strategy: 'ip' };
307
+ if (type === 'BOOLEAN' || type === 'BOOL')
308
+ return { strategy: 'bool' };
309
+ if (type === 'BYTEA' || type === 'BLOB')
310
+ return { strategy: 'bytes', minLen: 8, maxLen: 32 };
311
+ if ((type.startsWith('INT') || type.startsWith('INTEGER')) && /(^|_)(is|has|can|should|did)_|_flag$|active|enabled|verified|published|deleted|archived|paid|completed|approved/.test(rawName)) {
312
+ return { strategy: 'bool' };
313
+ }
314
+ if (type === 'DATE' || /^date|birthdate|dob|birthday/.test(rawName)) {
315
+ return name.includes('birth') ? { strategy: 'date', from: '1950-01-01', to: '2000-12-31' } : { strategy: 'date', from: '2020-01-01', to: '2026-12-31' };
316
+ }
317
+ if (type === 'DATETIME' || type === 'TIMESTAMP' || isTimestampName(name)) {
318
+ return { strategy: 'datetime', from: '2024-01-01T00:00:00', to: '2026-12-31T23:59:59' };
319
+ }
320
+ if (type === 'TIME' || name === 'time')
321
+ return { strategy: 'time' };
322
+ if (type.startsWith('INTEGER') && /(timestamp|epoch|unix|createdtime|updatedtime)/.test(name)) {
323
+ return { strategy: 'timestampUnix', format: 'sec' };
324
+ }
325
+ if (/^(lat|latitude)$/.test(name))
326
+ return { strategy: 'latitude' };
327
+ if (/^(lng|lon|longitude)$/.test(name))
328
+ return { strategy: 'longitude' };
329
+ if (type.startsWith('INTEGER')) {
330
+ if (name.includes('year'))
331
+ return { strategy: 'int', min: 1990, max: 2026 };
332
+ if (name.includes('age'))
333
+ return { strategy: 'int', min: 18, max: 90 };
334
+ if (/(count|quantity|qty|stock|views|likes|total|num|number)$/.test(name))
335
+ return { strategy: 'int', min: 0, max: 100000 };
336
+ if (name.includes('rating') || name.includes('score'))
337
+ return { strategy: 'int', min: 1, max: 5 };
338
+ if (/(order|rank|position|seq|sequence|priority|sort|step)$/.test(name))
339
+ return { strategy: 'sequence', start: 1, step: 1 };
340
+ return { strategy: 'int', min: 1, max: 1000 };
341
+ }
342
+ if (type === 'REAL' || type.includes('DECIMAL') || type.includes('NUMERIC') || type.includes('FLOAT') || type.includes('DOUBLE')) {
343
+ if (/(price|cost|amount|total|salary|balance|fee|charge|budget)/.test(name))
344
+ return { strategy: 'decimal', min: 1, max: 5000, precision: 2 };
345
+ if (name.includes('rating'))
346
+ return { strategy: 'decimal', min: 1, max: 5, precision: 1 };
347
+ return { strategy: 'decimal', min: 1, max: 1000, precision: 2 };
348
+ }
349
+ if (type === 'BLOB')
350
+ return { strategy: 'bytes', minLen: 8, maxLen: 32 };
351
+ if (/currency|curr|currencycode/.test(name))
352
+ return { strategy: 'currency' };
353
+ if (/countrycode|countryiso|isocountry|cca2/.test(name))
354
+ return { strategy: 'countryCode' };
355
+ if (/state|province|region/.test(name) && !/status|statement/.test(name))
356
+ return { strategy: 'state' };
357
+ if (/status|stage|phase|state/.test(name))
358
+ return { strategy: 'status' };
359
+ if (/color|colour|theme|hexcolor/.test(name))
360
+ return { strategy: 'color', format: 'hex' };
361
+ if (/mac|macaddress|hwaddr/.test(name))
362
+ return { strategy: 'mac' };
363
+ if (/creditcard|cardnumber|cardno|ccnumber|ccno/.test(name))
364
+ return { strategy: 'creditCard' };
365
+ if (/slug|permalink|handle|alias/.test(name))
366
+ return { strategy: 'slug' };
367
+ if (isHashName(name))
368
+ return { strategy: 'hash', minLen: 32, maxLen: 64 };
369
+ if (isTokenName(name))
370
+ return { strategy: 'token', minLen: 6, maxLen: 12 };
371
+ if (/uuid|guid/.test(name) || name === 'id' || name === 'uid' || name === 'key')
372
+ return { strategy: 'uuid' };
373
+ if (name.includes('first') && name.includes('name'))
374
+ return { strategy: 'first' };
375
+ if (/(lastname|surname|familyname)/.test(name) || (name.includes('last') && name.includes('name')))
376
+ return { strategy: 'last' };
377
+ if (name === 'name' || name === 'fullname' || (name.includes('full') && name.includes('name')))
378
+ return { strategy: 'fullname' };
379
+ for (const [pattern, createPlan] of TEXT_PATTERNS) {
380
+ if (pattern.test(name))
381
+ return createPlan(name);
382
+ }
383
+ return { strategy: 'words', minLen: 1, maxLen: 4 };
384
+ }
385
+ function buildColumnConfigs(info) {
386
+ const fkByColumn = new Map(info.foreignKeys.map((fk) => [fk.from, fk]));
387
+ const uniqueCols = new Set();
388
+ const jsonIndexKeys = new Map();
389
+ for (const ix of info.indexes ?? []) {
390
+ if (ix.unique && ix.columns.length === 1 && ix.columns[0])
391
+ uniqueCols.add(ix.columns[0]);
392
+ if (ix.sql && /json_extract|->>|->\s*'|json_/i.test(ix.sql)) {
393
+ for (const { col, keys } of extractJsonColumns(ix.sql)) {
394
+ if (!col)
395
+ continue;
396
+ const merged = new Set([...(jsonIndexKeys.get(col) ?? []), ...keys]);
397
+ if (merged.size)
398
+ jsonIndexKeys.set(col, [...merged]);
399
+ }
400
+ }
401
+ }
402
+ if (info.sql) {
403
+ const uqRe = /UNIQUE\s*\(\s*([^)]+)\s*\)/gi;
404
+ let uqM;
405
+ while ((uqM = uqRe.exec(info.sql))) {
406
+ const rawCols = uqM[1].split(',').map((s) => s.trim().replace(/[`"\[\]]/g, ''));
407
+ if (rawCols.length === 1 && rawCols[0])
408
+ uniqueCols.add(rawCols[0]);
409
+ }
410
+ }
411
+ const checkInfo = parseChecks(info.sql ?? null);
412
+ const colNames = info.columns.map((c) => c.name.toLowerCase());
413
+ const hasFirstName = colNames.includes('first_name') || colNames.includes('firstname');
414
+ const hasLastName = colNames.includes('last_name') || colNames.includes('lastname');
415
+ const fullNameCol = info.columns.find((c) => {
416
+ const lc = c.name.toLowerCase();
417
+ return lc === 'full_name' || lc === 'fullname' || lc === 'name' || lc === 'customer_name';
418
+ });
419
+ return info.columns.map((col) => {
420
+ const fk = fkByColumn.get(col.name) ?? null;
421
+ const strategies = (0, strategies_1.strategiesFor)(col, fk);
422
+ const unique = uniqueCols.has(col.name);
423
+ let defaultPlan = detectPlan(col, fk);
424
+ if (defaultPlan.strategy !== 'fk' && !col.pk && isJsonColumn(col, jsonIndexKeys.has(col.name))) {
425
+ const keys = jsonIndexKeys.get(col.name);
426
+ const useKeys = keys && keys.length ? keys : ['scope', 'enabled', 'allowedApps'];
427
+ const allowed = findInMap(checkInfo.jsonAllowed, col.name);
428
+ const jsonValues = {};
429
+ if (allowed) {
430
+ for (const k of useKeys) {
431
+ const vals = allowed.get(k);
432
+ if (vals && vals.length)
433
+ jsonValues[k] = vals;
434
+ }
435
+ }
436
+ defaultPlan = {
437
+ strategy: 'json',
438
+ jsonKeys: useKeys,
439
+ ...(Object.keys(jsonValues).length ? { jsonValues } : {}),
440
+ };
441
+ }
442
+ const colAllowed = findInMap(checkInfo.columnAllowed, col.name);
443
+ if (colAllowed && colAllowed.length > 0 && defaultPlan.strategy !== 'fk' && !col.pk) {
444
+ defaultPlan = colAllowed.length === 1 ? { strategy: 'fixed', value: colAllowed[0] } : { strategy: 'list', values: [...colAllowed] };
445
+ }
446
+ const colRange = findInMap(checkInfo.columnRange, col.name);
447
+ if (colRange && (defaultPlan.strategy === 'int' || defaultPlan.strategy === 'decimal')) {
448
+ if (colRange.min != null)
449
+ defaultPlan.min = colRange.min;
450
+ if (colRange.max != null)
451
+ defaultPlan.max = colRange.max;
452
+ }
453
+ const colLen = findInMap(checkInfo.columnLength, col.name);
454
+ if (colLen && defaultPlan.strategy !== 'fk' && !col.pk) {
455
+ if (colLen.exact != null) {
456
+ defaultPlan = { strategy: 'token', minLen: colLen.exact, maxLen: colLen.exact };
457
+ }
458
+ else {
459
+ if (colLen.min != null)
460
+ defaultPlan.minLen = colLen.min;
461
+ if (colLen.max != null)
462
+ defaultPlan.maxLen = colLen.max;
463
+ }
464
+ }
465
+ if (defaultPlan.strategy === 'email' && !col.pk) {
466
+ if (hasFirstName && hasLastName) {
467
+ defaultPlan = { strategy: 'template', template: '{{first_name}}.{{last_name}}@example.com' };
468
+ }
469
+ else if (fullNameCol && fullNameCol.name !== col.name) {
470
+ defaultPlan = { strategy: 'template', template: `{{${fullNameCol.name}}}@example.com` };
471
+ }
472
+ }
473
+ if ((col.name.toLowerCase() === 'full_name' || col.name.toLowerCase() === 'fullname') && hasFirstName && hasLastName && !col.pk) {
474
+ defaultPlan = { strategy: 'template', template: '{{first_name}} {{last_name}}' };
475
+ }
476
+ if (!strategies.some((s) => s.id === defaultPlan.strategy) || (!col.pk && col.notnull && col.dflt_value == null && (defaultPlan.strategy === 'skip' || defaultPlan.strategy === 'null'))) {
477
+ defaultPlan = (0, strategies_1.fallbackPlanFor)(col);
478
+ }
479
+ return {
480
+ name: col.name,
481
+ type: col.type,
482
+ pk: col.pk > 0,
483
+ notnull: Boolean(col.notnull),
484
+ hasDefault: col.dflt_value != null,
485
+ unique,
486
+ fk,
487
+ strategies,
488
+ defaultPlan,
489
+ };
490
+ });
491
+ }
492
+ const STR_PLAN_KEYS = ['value', 'from', 'to', 'prefix', 'suffix', 'pattern', 'format', 'template', 'refTable', 'refColumn'];
493
+ const NUM_PLAN_KEYS = ['min', 'max', 'precision', 'minLen', 'maxLen', 'nullPct', 'start', 'step'];
494
+ function sanitizeColumnPlan(raw) {
495
+ if (!raw || typeof raw !== 'object')
496
+ return null;
497
+ const r = raw;
498
+ if (typeof r.strategy !== 'string' || !r.strategy)
499
+ return null;
500
+ const out = { strategy: r.strategy };
501
+ if (Array.isArray(r.values)) {
502
+ out.values = r.values.map(String);
503
+ }
504
+ if (r.unique !== undefined && r.unique !== null) {
505
+ out.unique = Boolean(r.unique);
506
+ }
507
+ if (r.jsonKeys !== undefined && r.jsonKeys !== null) {
508
+ const rawKeys = Array.isArray(r.jsonKeys) ? r.jsonKeys.map(String) : String(r.jsonKeys).split(/[,;]/);
509
+ out.jsonKeys = rawKeys.map((s) => s.trim()).filter(Boolean);
510
+ }
511
+ for (const key of STR_PLAN_KEYS) {
512
+ if (r[key] !== undefined && r[key] !== null)
513
+ out[key] = String(r[key]);
514
+ }
515
+ for (const key of NUM_PLAN_KEYS) {
516
+ if (r[key] !== undefined && r[key] !== null) {
517
+ const n = Number(r[key]);
518
+ if (Number.isFinite(n))
519
+ out[key] = n;
520
+ }
521
+ }
522
+ if (r.jsonValues && typeof r.jsonValues === 'object' && !Array.isArray(r.jsonValues)) {
523
+ const jv = {};
524
+ for (const [k, vals] of Object.entries(r.jsonValues)) {
525
+ if (Array.isArray(vals)) {
526
+ const cleaned = vals.map((x) => String(x).trim()).filter(Boolean);
527
+ if (cleaned.length)
528
+ jv[k] = cleaned;
529
+ }
530
+ }
531
+ if (Object.keys(jv).length)
532
+ out.jsonValues = jv;
533
+ }
534
+ return out;
535
+ }
@@ -1 +1 @@
1
- import type {IDatabase,TableInfoData,WhereClause} from '../db/index';import{type ColumnGeneratorConfig,type ColumnPlan,type GenerateResult} from './types';export declare function generateRows(db:IDatabase,info:TableInfoData,configs:ColumnGeneratorConfig[],count:number,plan?:Record<string,ColumnPlan>):Promise<GenerateResult>;export declare function buildSeedInsertSql(table:string,rows:WhereClause[][]):string;
1
+ import type {IDatabase,TableInfoData,WhereClause} from '../db/index';import{type ColumnGeneratorConfig,type ColumnPlan,type ErChainResult,type GenerateResult,type GenerationOptions,type GenerationPlan} from './types';export declare class SeedEngine{static executePlan(db:IDatabase,plan:GenerationPlan,optionsOverride?:Partial<GenerationOptions>):Promise<ErChainResult>;}export declare function buildSeedInsertSql(table:string,rows:WhereClause[][]):string;export declare function buildChainInsertSql(executionOrder:string[],tableResults:ErChainResult['tableResults']):string;export declare function generateRows(db:IDatabase,info:TableInfoData,configs:ColumnGeneratorConfig[],count:number,plan?:Record<string,ColumnPlan>,truncate?:boolean):Promise<GenerateResult>;