@stacksjs/server 0.75.635 → 0.75.636

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 (2) hide show
  1. package/dist/imports.js +3 -3
  2. package/package.json +12 -12
package/dist/imports.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync,readFileSync,renameSync,statSync,unlinkSync}from"node:fs";import{dirname,isAbsolute,relative,resolve as resolvePath}from"node:path";import{fileURLToPath}from"node:url";import{plugin}from"bun";import{log}from"@stacksjs/logging/runtime";import{path}from"@stacksjs/path";import{autoImports,generateRuntimeIndex,generateGlobalsScript}from"bun-plugin-auto-imports";import{globSync}from"@stacksjs/storage/glob";import{primitiveAutoImportEntries,primitiveModules}from"./primitive-imports";import{defaultImportSpecifier,isFrameworkSourceCheckout}from"./default-import-specifier";import{browserAutoImportSurface,renderAutoImportReference}from"./auto-import-reference";const OPTIONAL_MODEL_MODULES={commerce:["config/commerce.ts"],Content:["config/cms.ts","config/blog.ts"],Forms:["config/forms.ts"],realtime:["config/realtime.ts"]};function configEnabled(configRelPaths){if(process.env.STACKS_CANONICAL_FEATURES==="1")return true;return configRelPaths.some((rel)=>existsSync(path.projectPath(rel)))}export function frameworkDefaultsDir(sub){const vendored=path.storagePath(`framework/defaults/${sub}`);return resolveDefaultsDir(existsSync(vendored)?vendored:undefined,packagedDefaultsDir(sub),vendoredDefaultsAreStale())}export function resolveDefaultsDir(vendored,packaged,vendoredIsStale){if(packaged&&vendoredIsStale)return packaged;return vendored??packaged}function packagedDefaultsDir(sub){try{const packageRoot=dirname(fileURLToPath(import.meta.resolve("@stacksjs/defaults/package.json")));const packaged=`${packageRoot}/${sub}`;return existsSync(packaged)?packaged:undefined}catch{return}}function defaultsModuleSpecifier(){const roots=existingDirs([path.storagePath("framework/defaults"),packagedDefaultsDir("")]);const sourceCheckout=isFrameworkSourceCheckout(path.projectPath());return(file)=>defaultImportSpecifier(file,roots,sourceCheckout)}function declarationModuleSpecifier(file,outputPath,mapper=defaultsModuleSpecifier()){if(!isAbsolute(file)&&!file.startsWith("."))return file;const canonical=mapper(file,outputPath);if(canonical)return canonical;const local=relative(dirname(outputPath),file).replace(/\\/g,"/").replace(/\.ts$/,"");return local.startsWith(".")?local:`./${local}`}let defaultsAreStale;function vendoredDefaultsAreStale(){if(defaultsAreStale===undefined)defaultsAreStale=path.inspectDefaultsProvenance().status==="stale";return defaultsAreStale}function existingDirs(dirs){return dirs.filter((dir)=>Boolean(dir)&&existsSync(dir))}function packageModelDirs(){try{const{packageModelRoots}=require("@stacksjs/config");return packageModelRoots().map((root)=>root.dir)}catch{return[]}}async function writeGeneratedFile(outputPath,contents){const temp=`${outputPath}.${process.pid}.tmp`;try{await Bun.write(temp,contents);renameSync(temp,outputPath)}catch(error){try{unlinkSync(temp)}catch{}throw error}}function packageJobDirs(){try{const{packageJobRoots}=require("@stacksjs/config");return packageJobRoots().map((root)=>root.dir)}catch{return[]}}function resolveDefaultModelDirs(){const root=frameworkDefaultsDir("app/Models");if(!root)return[];const dirs=[root];for(const[subdir,configPaths]of Object.entries(OPTIONAL_MODEL_MODULES)){if(configEnabled(configPaths))dirs.push(`${root}/${subdir}`)}return dirs}function scanDirTopLevel(dir){try{return globSync(`${dir}/*.ts`,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{return[]}}function scanDefineModelExports(dir,opts={}){const{recursive=true}=opts;let files=[];try{const pattern=recursive?`${dir}/**/*.ts`:`${dir}/*.ts`;files=globSync(pattern,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{return[]}const exports=[];const seen=new Set;for(const file of files){const basename=file.split("/").pop()?.replace(".ts","")||"";if(basename&&!seen.has(basename)){seen.add(basename);exports.push({name:basename,file,isDefault:true})}}return exports}const GLOBAL_SHADOW_BLOCKLIST=new Set(["Error","Request","Response","URL","Map","Set","Object","Array","Number","String","Date","Promise","Symbol"]);async function generateDefineModelIndex(entries,outputPath){const lines=["// Generated by bun-plugin-auto-imports"];const seen=new Set;const moduleSpecifier=defaultsModuleSpecifier();for(const entry of entries){const dir=typeof entry==="string"?entry:entry.dir;const recursive=typeof entry==="string"?true:entry.recursive;let files=[];try{const pattern=recursive?`${dir}/**/*.ts`:`${dir}/*.ts`;files=globSync(pattern,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{continue}for(const file of files){const basename=file.split("/").pop()?.replace(".ts","")||"";if(!basename||seen.has(basename))continue;seen.add(basename);const relativePath=moduleSpecifier(file,outputPath)??relative(dirname(outputPath),file).replace(/\\/g,"/").replace(/\.ts$/,"");if(GLOBAL_SHADOW_BLOCKLIST.has(basename)){lines.push(`// Skipped '${basename}' - would shadow a built-in global. Import directly if needed.`);lines.push(`// export { default as ${basename} } from '${relativePath}'`);continue}lines.push(`export { default as ${basename} } from '${relativePath}'`)}}await writeGeneratedFile(outputPath,`${lines.join(`
1
+ import{existsSync,readFileSync,renameSync,statSync,unlinkSync}from"node:fs";import{dirname,isAbsolute,relative,resolve as resolvePath}from"node:path";import{fileURLToPath}from"node:url";import{plugin}from"bun";import{log}from"@stacksjs/logging/runtime";import{path}from"@stacksjs/path";import{autoImports,generateRuntimeIndex,generateGlobalsScript}from"bun-plugin-auto-imports";import{globSync}from"@stacksjs/storage/glob";import{primitiveAutoImportEntries,primitiveModules}from"./primitive-imports";import{defaultImportSpecifier,isFrameworkSourceCheckout}from"./default-import-specifier";import{browserAutoImportSurface,renderAutoImportReference}from"./auto-import-reference";const OPTIONAL_MODEL_MODULES={commerce:["config/commerce.ts"],Content:["config/cms.ts","config/blog.ts"],Forms:["config/forms.ts"],realtime:["config/realtime.ts"]};function configEnabled(configRelPaths){if(process.env.STACKS_CANONICAL_FEATURES==="1")return true;return configRelPaths.some((rel)=>existsSync(path.projectPath(rel)))}export function frameworkDefaultsDir(sub){const vendored=path.storagePath(`framework/defaults/${sub}`);return resolveDefaultsDir(existsSync(vendored)?vendored:undefined,packagedDefaultsDir(sub),vendoredDefaultsAreStale())}export function resolveDefaultsDir(vendored,packaged,vendoredIsStale){if(packaged&&vendoredIsStale)return packaged;return vendored??packaged}function packagedDefaultsDir(sub){try{const packageRoot=dirname(fileURLToPath(import.meta.resolve("@stacksjs/defaults/package.json")));const packaged=`${packageRoot}/${sub}`;return existsSync(packaged)?packaged:undefined}catch{return}}function defaultsModuleSpecifier(){const roots=existingDirs([path.storagePath("framework/defaults"),packagedDefaultsDir("")]);const sourceCheckout=isFrameworkSourceCheckout(path.projectPath());return(file)=>defaultImportSpecifier(file,roots,sourceCheckout)}function declarationModuleSpecifier(file,outputPath,mapper=defaultsModuleSpecifier()){if(!isAbsolute(file)&&!file.startsWith("."))return file;const canonical=mapper(file,outputPath);if(canonical)return canonical;const local=relative(dirname(outputPath),file).replace(/\\/g,"/").replace(/\.ts$/,"");return local.startsWith(".")?local:`./${local}`}let defaultsAreStale;function vendoredDefaultsAreStale(){if(defaultsAreStale===undefined)defaultsAreStale=path.inspectDefaultsProvenance().status==="stale";return defaultsAreStale}function existingDirs(dirs){return dirs.filter((dir)=>Boolean(dir)&&existsSync(dir))}function packageModelDirs(){try{const{packageModelRoots}=require("@stacksjs/config");return packageModelRoots().map((root)=>root.dir)}catch{return[]}}async function writeGeneratedFile(outputPath,contents){try{if(readFileSync(outputPath,"utf8")===contents)return}catch(error){if(error.code!=="ENOENT")throw error}const temp=`${outputPath}.${process.pid}.tmp`;try{await Bun.write(temp,contents);renameSync(temp,outputPath)}catch(error){try{unlinkSync(temp)}catch{}throw error}}function packageJobDirs(){try{const{packageJobRoots}=require("@stacksjs/config");return packageJobRoots().map((root)=>root.dir)}catch{return[]}}function resolveDefaultModelDirs(){const root=frameworkDefaultsDir("app/Models");if(!root)return[];const dirs=[root];for(const[subdir,configPaths]of Object.entries(OPTIONAL_MODEL_MODULES)){if(configEnabled(configPaths))dirs.push(`${root}/${subdir}`)}return dirs}function scanDirTopLevel(dir){try{return globSync(`${dir}/*.ts`,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{return[]}}function scanDefineModelExports(dir,opts={}){const{recursive=true}=opts;let files=[];try{const pattern=recursive?`${dir}/**/*.ts`:`${dir}/*.ts`;files=globSync(pattern,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{return[]}const exports=[];const seen=new Set;for(const file of files){const basename=file.split("/").pop()?.replace(".ts","")||"";if(basename&&!seen.has(basename)){seen.add(basename);exports.push({name:basename,file,isDefault:true})}}return exports}const GLOBAL_SHADOW_BLOCKLIST=new Set(["Error","Request","Response","URL","Map","Set","Object","Array","Number","String","Date","Promise","Symbol"]);async function generateDefineModelIndex(entries,outputPath){const lines=["// Generated by bun-plugin-auto-imports"];const seen=new Set;const moduleSpecifier=defaultsModuleSpecifier();for(const entry of entries){const dir=typeof entry==="string"?entry:entry.dir;const recursive=typeof entry==="string"?true:entry.recursive;let files=[];try{const pattern=recursive?`${dir}/**/*.ts`:`${dir}/*.ts`;files=globSync(pattern,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{continue}for(const file of files){const basename=file.split("/").pop()?.replace(".ts","")||"";if(!basename||seen.has(basename))continue;seen.add(basename);const relativePath=moduleSpecifier(file,outputPath)??relative(dirname(outputPath),file).replace(/\\/g,"/").replace(/\.ts$/,"");if(GLOBAL_SHADOW_BLOCKLIST.has(basename)){lines.push(`// Skipped '${basename}' - would shadow a built-in global. Import directly if needed.`);lines.push(`// export { default as ${basename} } from '${relativePath}'`);continue}lines.push(`export { default as ${basename} } from '${relativePath}'`)}}await writeGeneratedFile(outputPath,`${lines.join(`
2
2
  `)}
3
3
  `)}async function generatePathIndex(entries,outputPath,options){const prefix=options.prefix??"";const extensions=options.extensions??[".ts"];const found=new Map;const moduleSpecifier=defaultsModuleSpecifier();for(const entry of entries){const dir=typeof entry==="string"?entry:entry.dir;const recursive=typeof entry==="string"?true:entry.recursive;let files=[];try{for(const extension of extensions){const pattern=recursive?`${dir}/**/*${extension}`:`${dir}/*${extension}`;files.push(...globSync(pattern).sort())}}catch{continue}const rank=(file)=>extensions.findIndex((extension)=>file.endsWith(extension));files=files.sort((left,right)=>{const byRank=rank(left)-rank(right);if(byRank!==0)return byRank;return left<right?-1:left>right?1:0});for(const file of files){const basename=file.split("/").pop()??"";if(basename.endsWith(".d.ts")||basename.endsWith(".test.ts")||basename.endsWith(".spec.ts")||basename==="index.ts")continue;const extension=extensions.find((candidate)=>file.endsWith(candidate))??"";const key=prefix+relative(dir,file).slice(0,extension.length?-extension.length:undefined);if(found.has(key))continue;found.set(key,moduleSpecifier(file,outputPath)??relative(dirname(outputPath),file).replace(/\\/g,"/"))}}const lines=["// Generated by bun-plugin-auto-imports","//","// Name to package export or relative file. The resolvers read it, and the name","// types are `keyof` over it - so a name that type-checks is a name that","// resolves. Values are paths rather than import thunks on purpose: thunks","// would make every compilation that touches a name resolve every module.",`export const ${options.exportName} = {`,...[...found.entries()].map(([key,file])=>` '${key}': '${file}',`),"} as const",""];await writeGeneratedFile(outputPath,lines.join(`
4
4
  `))}export function autoImportSourceDirs(){return existingDirs([path.resourcesPath("functions"),frameworkDefaultsDir("functions"),path.userModelsPath(),...resolveDefaultModelDirs(),path.userJobsPath(),frameworkDefaultsDir("app/Jobs"),...packageJobDirs(),path.userControllersPath(),frameworkDefaultsDir("app/Controllers"),path.appPath("Actions"),frameworkDefaultsDir("app/Actions"),path.appPath("Listeners"),frameworkDefaultsDir("app/Listeners"),path.appPath("Policies"),frameworkDefaultsDir("app/Policies"),path.appPath("Middleware"),frameworkDefaultsDir("app/Middleware"),path.resourcesPath("emails"),frameworkDefaultsDir("resources/emails")])}export function autoImportsAreStale(){const manifest=path.storagePath("framework/auto-imports/functions.ts");if(!existsSync(manifest))return true;let manifestTime;try{manifestTime=statSync(manifest).mtimeMs}catch{return true}const discovered=path.storagePath("framework/discovered-packages.json");try{if(existsSync(discovered)&&statSync(discovered).mtimeMs>manifestTime)return true}catch{}for(const dir of autoImportSourceDirs()){if(!existsSync(dir))continue;try{if(statSync(dir).mtimeMs>manifestTime)return true;for(const file of globSync(`${dir}/**/*.ts`,{ignore:["**/*.d.ts"]})){if(statSync(file).mtimeMs>manifestTime)return true}}catch{continue}}return recordedSourceFingerprint()!==autoImportSourceFingerprint()}export function autoImportSourceFingerprint(){const root=path.projectPath();const files=[];for(const dir of autoImportSourceDirs()){for(const file of globSync(`${dir}/**/*.ts`,{ignore:["**/*.d.ts"]}))files.push(relative(root,file))}files.sort();let packages="[]";try{const manifest=JSON.parse(readFileSync(path.storagePath("framework/discovered-packages.json"),"utf8"));packages=JSON.stringify(Object.keys(manifest.packages??{}).sort().map((name)=>[name,manifest.packages[name]]))}catch{}return new Bun.CryptoHasher("sha256").update(files.join(`
@@ -7,9 +7,9 @@ import{existsSync,readFileSync,renameSync,statSync,unlinkSync}from"node:fs";impo
7
7
  `)){const match=/^export (type )?\{([^}]*)\} from /.exec(line.trim());if(!match)continue;const lineIsType=Boolean(match[1]);for(const raw of match[2].split(",")){let specifier=raw.trim();if(!specifier)continue;const specifierIsType=specifier.startsWith("type ");if(specifierIsType)specifier=specifier.slice("type ".length).trim();const name=specifier.split(/\s+as\s+/).pop().trim();const typeOnly=lineIsType||specifierIsType;const previous=names.get(name);names.set(name,{typeOnly:typeOnly&&(previous?.typeOnly??true)})}}return names}export function combinedBarrel(barrels){const lines=["// Generated by bun-plugin-auto-imports",...barrels.map((b)=>`export * from './${b.name}'`)];const owners=new Map;const exported=barrels.map((b)=>({name:b.name,names:barrelExportNames(b.source)}));for(const barrel of exported){for(const name of barrel.names.keys())owners.set(name,[...owners.get(name)??[],barrel.name])}const winners=new Map;for(const[name,from]of[...owners].sort(([a],[b])=>a.localeCompare(b))){if(from.length<2)continue;const winner=from.at(-1);const typeOnly=exported.find((b)=>b.name===winner).names.get(name).typeOnly;const entry=winners.get(winner)??{value:[],type:[]};entry[typeOnly?"type":"value"].push(name);winners.set(winner,entry)}if(winners.size>0){lines.push("");lines.push("// Names more than one barrel exports, which `export *` would drop (TS2308).");for(const barrel of barrels){const entry=winners.get(barrel.name);if(entry?.value.length)lines.push(`export { ${entry.value.join(", ")} } from './${barrel.name}'`);if(entry?.type.length)lines.push(`export type { ${entry.type.join(", ")} } from './${barrel.name}'`)}}return`${lines.join(`
8
8
  `)}
9
9
  `}async function invalidateTypeScriptBuildInfo(){const cacheDir=path.storagePath("framework/.cache/typescript");try{const{readdirSync,rmSync}=await import("node:fs");for(const entry of readdirSync(cacheDir)){if(!entry.endsWith(".tsbuildinfo"))continue;rmSync(`${cacheDir}/${entry}`,{force:true});log.debug(`[auto-imports] dropped stale ${entry}`)}}catch{}}export function initiateImports(){const moduleSpecifier=defaultsModuleSpecifier();const functionsPath=path.resourcesPath("functions");const defaultFunctionsPath=frameworkDefaultsDir("functions");const userModelsPath=path.userModelsPath();const defaultModelDirs=resolveDefaultModelDirs();const[defaultsRoot,...enabledSubdirs]=defaultModelDirs;const userJobsPath=path.userJobsPath();const userControllersPath=path.userControllersPath();const defaultControllersPath=frameworkDefaultsDir("app/Controllers");const defineModelExports=[...scanDefineModelExports(userModelsPath),...packageModelDirs().flatMap((dir)=>scanDefineModelExports(dir)),...defaultsRoot?scanDefineModelExports(defaultsRoot,{recursive:false}):[],...enabledSubdirs.flatMap((d)=>scanDefineModelExports(d))];const seenJobs=new Set;const jobExports=[...scanDefineModelExports(userJobsPath),...packageJobDirs().flatMap((dir)=>scanDefineModelExports(dir))].filter((exp)=>{if(seenJobs.has(exp.name))return false;seenJobs.add(exp.name);return true});const seen=new Set;const uniqueDefineModelExports=defineModelExports.filter((exp)=>{if(seen.has(exp.name))return false;seen.add(exp.name);return true});const dtsDir=dirname(path.storagePath("framework/types/server-auto-imports.d.ts"));const defineModelImports=uniqueDefineModelExports.map((exp)=>({from:declarationModuleSpecifier(exp.file,`${dtsDir}/server-auto-imports.d.ts`,moduleSpecifier),name:"default",as:exp.name}));const jobImports=jobExports.map((exp)=>({from:declarationModuleSpecifier(exp.file,`${dtsDir}/server-auto-imports.d.ts`,moduleSpecifier),name:"default",as:exp.name}));const controllerExports=[...scanDefineModelExports(userControllersPath),...defaultControllersPath?scanDefineModelExports(defaultControllersPath):[]];const seenControllers=new Set;const uniqueControllerExports=controllerExports.filter((exp)=>{if(seenControllers.has(exp.name))return false;seenControllers.add(exp.name);return true});const controllerImports=uniqueControllerExports.map((exp)=>({from:declarationModuleSpecifier(exp.file,`${dtsDir}/server-auto-imports.d.ts`,moduleSpecifier),name:"default",as:exp.name}));const options={moduleSpecifier,dts:path.storagePath("framework/types/server-auto-imports.d.ts"),imports:[...primitiveAutoImportEntries(),...defineModelImports,...jobImports,...controllerImports],dirs:existingDirs([functionsPath,defaultFunctionsPath]),eslint:{enabled:true,filepath:path.storagePath("framework/server-auto-imports.json")}};plugin(autoImports(options));generateAutoImportFiles().catch((err)=>{console.error("[Server] Failed to generate auto-import files:",err)})}export async function generateServerAutoImportTypes(){const moduleSpecifier=defaultsModuleSpecifier();const seen=new Set;const valueExports=[...barrelExports("models"),...barrelExports("jobs"),...barrelExports("controllers"),...await ormModelGlobals()].filter((exp)=>!GLOBAL_SHADOW_BLOCKLIST.has(exp.name)).filter((exp)=>{if(seen.has(exp.name))return false;seen.add(exp.name);return true});const outputPath=path.storagePath("framework/types/server-auto-imports.d.ts");const declaredValues=new Set(valueExports.map((exp)=>exp.name));const lines=["// Generated by Stacks server auto-imports","// This file is regenerated automatically when the API starts.","export {}","declare global {"];for(const{from,name,as}of primitiveAutoImportEntries()){if(!declaredValues.has(as))lines.push(` const ${as}: typeof import('${from}')['${name}']`)}for(const exp of valueExports){if(!exp.isDefault){lines.push(` const ${exp.name}: typeof import('${exp.file}')['${exp.name}']`);continue}const relativePath=declarationModuleSpecifier(exp.file,outputPath,moduleSpecifier);lines.push(` const ${exp.name}: typeof import('${relativePath}')['default']`)}lines.push("}","");await writeGeneratedFile(outputPath,lines.join(`
10
- `));const globals={};for(const{as}of primitiveAutoImportEntries()){if(!declaredValues.has(as))globals[as]=true}for(const exp of valueExports)globals[exp.name]=true;await Bun.write(path.storagePath("framework/server-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(Object.keys(globals).sort().map((k)=>[k,true]))},null,2)}
10
+ `));const globals={};for(const{as}of primitiveAutoImportEntries()){if(!declaredValues.has(as))globals[as]=true}for(const exp of valueExports)globals[exp.name]=true;await writeGeneratedFile(path.storagePath("framework/server-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(Object.keys(globals).sort().map((k)=>[k,true]))},null,2)}
11
11
  `);const groups=primitiveModules.map(([source,names])=>({source:`\`${source}\``,names:[...names]}));for(const barrel of COMBINED_BARRELS){const file=path.storagePath(`framework/auto-imports/${barrel}.ts`);const exported=existsSync(file)?barrelExportNames(readFileSync(file,"utf8")):new Map;const names=[...exported].filter(([name,info])=>!info.typeOnly&&!GLOBAL_SHADOW_BLOCKLIST.has(name)).map(([name])=>name);if(barrel==="models"){names.push(...valueExports.filter((exp)=>!exp.isDefault).map((exp)=>exp.name))}groups.push({source:`\`auto-imports/${barrel}.ts\`${barrel==="models"?" + ORM proxies":""}`,names})}const claimed=new Set;for(const group of[...groups].reverse()){group.names=group.names.filter((name)=>{if(claimed.has(name))return false;claimed.add(name);return true})}await writeGeneratedFile(path.storagePath("framework/auto-imports/RUNTIME.md"),renderAutoImportReference(groups,await browserAutoImportSurface()))}function barrelExports(barrel){const file=path.storagePath(`framework/auto-imports/${barrel}.ts`);if(!existsSync(file))return[];const source=readFileSync(file,"utf8");const outputDir=dirname(file);const found=[];for(const line of source.split(`
12
12
  `)){const match=/^export \{ default as (\w+) \} from '([^']+)'/.exec(line.trim());if(!match)continue;const[,name,relativePath]=match;const specifier=relativePath;const file=specifier.startsWith(".")||isAbsolute(specifier)?resolvePath(outputDir,specifier.endsWith(".ts")?specifier:`${specifier}.ts`):specifier;found.push({name,file,isDefault:true})}return found}export async function pruneBrowserAutoImportTypes(){const outputPath=path.storagePath("framework/types/browser-auto-imports.d.ts");if(!existsSync(outputPath))return[];const source=readFileSync(outputPath,"utf8");const removed=[];const kept=[];for(const line of source.split(`
13
13
  `)){const match=/^ {2}const (\w+): typeof import\('([^']+)'\)\['(\w+)'\]/.exec(line);if(!match){kept.push(line);continue}const[,declaredAs]=match;removed.push(declaredAs)}const staleHeaders=new Set(["// Generated by unplugin-auto-import","// Pruned by Stacks: every name below is exported by the module beside it."]);const pruned=kept.filter((line)=>line.trim()!=="// @ts-nocheck").map((line)=>staleHeaders.has(line.trim())?"// Emptied by Stacks: nothing injects a bare name into a template. See stacksjs/stacks#2585.":line).join(`
14
- `);if(pruned===source)return removed;await Bun.write(outputPath,pruned);const globals=[...pruned.matchAll(/^ {2}const (\w+):/gm)].map((match)=>match[1]).sort();await Bun.write(path.storagePath("framework/browser-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(globals.map((name)=>[name,true]))},null,2)}
14
+ `);if(pruned===source)return removed;await writeGeneratedFile(outputPath,pruned);const globals=[...pruned.matchAll(/^ {2}const (\w+):/gm)].map((match)=>match[1]).sort();await writeGeneratedFile(path.storagePath("framework/browser-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(globals.map((name)=>[name,true]))},null,2)}
15
15
  `);return removed}async function ormModelGlobals(){try{const{modelGlobalNames}=await import("@stacksjs/orm");return(modelGlobalNames??[]).map((name)=>({name,file:"@stacksjs/orm",isDefault:false}))}catch{return[]}}let platformGlobalNames=null;export function assignBarrelGlobals(target,mod,platformNames){const skipped=[];for(const[name,value]of Object.entries(mod)){if(platformNames.has(name)){skipped.push(name);continue}target[name]=value}return skipped}export async function injectGlobalAutoImports(){if(globalThis.__stacksAutoImportsInjected)return;globalThis.__stacksAutoImportsInjected=true;platformGlobalNames??=new Set(Object.getOwnPropertyNames(globalThis));const errors=[];const importWithTimeout=async(pkg)=>{let timer;try{return await Promise.race([import(pkg),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`auto-import timed out: ${pkg}`)),4000)})])}finally{if(timer!==undefined)clearTimeout(timer)}};await Promise.all(primitiveModules.map(async([pkg,names])=>{try{const mod=await importWithTimeout(pkg);for(const name of names){if(mod[name]!==undefined)globalThis[name]=mod[name]}}catch(err){errors.push(err)}}));try{const{ensureLocalesLoaded}=await import("@stacksjs/i18n");await ensureLocalesLoaded()}catch(err){errors.push(err)}const barrels=COMBINED_BARRELS;const injected=[];for(const barrel of barrels){const barrelPath=path.storagePath(`framework/auto-imports/${barrel}.ts`);if(!existsSync(barrelPath))continue;try{const mod=await import(barrelPath);const kept=assignBarrelGlobals(globalThis,mod,platformGlobalNames);if(kept.length){log.warn(`[auto-imports] ${kept.join(", ")} from ${barrel}.ts ${kept.length===1?"is":"are"} not global: ${kept.length===1?"it":"they"} would replace the platform's own, which libraries rely on. Import ${kept.length===1?"it":"them"} where used.`)}injected.push(barrel)}catch(err){log.warn(`[auto-imports] ${barrel}.ts failed to load, so nothing it exports is available. Views and actions referencing them will throw "is not defined". Cause: ${err.message}`)}}if(!injected.includes("models")&&existsSync(path.storagePath("framework/auto-imports/models.ts")))log.warn("[auto-imports] No models were injected. Every model reference in stx views and actions will be undefined.");try{const{bootAppListeners}=await import("@stacksjs/events");await bootAppListeners({base:path.projectPath()})}catch(err){errors.push(err)}try{const{initializeAuthorization}=await import("@stacksjs/auth");await initializeAuthorization()}catch(err){errors.push(err)}if(errors.length){for(const err of errors)console.warn("[auto-imports]",err.message)}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/server",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.635",
5
+ "version": "0.75.636",
6
6
  "description": "Local development and production-ready.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,22 +58,22 @@
58
58
  "prepublishOnly": "bun run build"
59
59
  },
60
60
  "dependencies": {
61
- "@stacksjs/auth": "0.75.635",
61
+ "@stacksjs/auth": "0.75.636",
62
62
  "@stacksjs/bun-router": "^0.1.24",
63
- "@stacksjs/config": "0.75.635",
64
- "@stacksjs/events": "0.75.635",
65
- "@stacksjs/i18n": "0.75.635",
66
- "@stacksjs/logging": "0.75.635",
67
- "@stacksjs/orm": "0.75.635",
68
- "@stacksjs/path": "0.75.635",
69
- "@stacksjs/payments": "0.75.635",
70
- "@stacksjs/router": "0.75.635",
71
- "@stacksjs/storage": "0.75.635",
63
+ "@stacksjs/config": "0.75.636",
64
+ "@stacksjs/events": "0.75.636",
65
+ "@stacksjs/i18n": "0.75.636",
66
+ "@stacksjs/logging": "0.75.636",
67
+ "@stacksjs/orm": "0.75.636",
68
+ "@stacksjs/path": "0.75.636",
69
+ "@stacksjs/payments": "0.75.636",
70
+ "@stacksjs/router": "0.75.636",
71
+ "@stacksjs/storage": "0.75.636",
72
72
  "@stacksjs/stx": "^0.2.908",
73
73
  "bun-plugin-auto-imports": "^0.4.4"
74
74
  },
75
75
  "devDependencies": {
76
- "@stacksjs/validation": "0.75.635",
76
+ "@stacksjs/validation": "0.75.636",
77
77
  "better-dx": "^0.2.39"
78
78
  }
79
79
  }