@lunora/codegen 1.0.0-alpha.198 → 1.0.0-alpha.199
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/dist/index.d.mts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-CDtTXGzv.mjs → GENERATED_HEADER-CEgr9fSF.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-Cm2-NfDm.mjs → MUTATORS_FILENAME-B7EXNAFK.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-jY7xMuEF.mjs → OPENRPC_VERSION-D6-0Hn3B.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-DB65NOJO.mjs → SCHEMA_SNAPSHOT_FILENAME-BpSBAMAb.mjs} +4 -4
- package/dist/packem_shared/{buildOpenApiDocument-DYE4THNn.mjs → buildOpenApiDocument-DCGde3iO.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-C9O2RBTz.mjs → discoverFunctions-DRf4ucil.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-S81Iv_iB.mjs → discoverHttpRoutes-_ME7hLcW.mjs} +1 -1
- package/dist/packem_shared/{emit-ClBYG2gj.mjs → emit-BuaY_1hY.mjs} +104 -93
- package/dist/packem_shared/{emitApp-CgHXUpdD.mjs → emitApp-nInCbDo8.mjs} +14 -9
- package/dist/packem_shared/unwrap-handler-return-Da99uRXX.mjs +1 -0
- package/package.json +1 -1
- package/dist/packem_shared/unwrap-handler-return-CmIWbykC.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as w,G as
|
|
1
|
+
import{A as w,G as y}from"./emit-BuaY_1hY.mjs";const k=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[k(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},N=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],L=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${a}"]>>): this {
|
|
3
3
|
this.shardExtras.${a} = factory as NonNullable<ShardConfig["${a}"]>;
|
|
4
4
|
|
|
@@ -52,7 +52,12 @@ import{A as w,G as k}from"./emit-ClBYG2gj.mjs";const y=e=>`has${e.charAt(0).toUp
|
|
|
52
52
|
this.shardSelector = selector;
|
|
53
53
|
|
|
54
54
|
return this;
|
|
55
|
-
}`,...e.
|
|
55
|
+
}`,...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
|
|
56
|
+
public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
|
|
57
|
+
this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
|
|
58
|
+
|
|
59
|
+
return this;
|
|
60
|
+
}`]:[],...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
|
|
56
61
|
public storage(declaration: StorageDeclaration<Env>): this {
|
|
57
62
|
this.storageDeclaration = declaration;
|
|
58
63
|
|
|
@@ -129,7 +134,7 @@ import{A as w,G as k}from"./emit-ClBYG2gj.mjs";const y=e=>`has${e.charAt(0).toUp
|
|
|
129
134
|
? {
|
|
130
135
|
scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
|
|
131
136
|
}
|
|
132
|
-
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
137
|
+
: {}),`]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
133
138
|
${a.join(`
|
|
134
139
|
`)}
|
|
135
140
|
`:""},B=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
@@ -384,7 +389,7 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
|
|
|
384
389
|
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
385
390
|
};
|
|
386
391
|
}
|
|
387
|
-
`:""
|
|
392
|
+
`:"",H=e=>e?`
|
|
388
393
|
/**
|
|
389
394
|
* Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
|
|
390
395
|
*
|
|
@@ -619,7 +624,7 @@ const buildGlobalCdcApplier =
|
|
|
619
624
|
|
|
620
625
|
return request.changes.length;
|
|
621
626
|
};
|
|
622
|
-
`:""
|
|
627
|
+
`:"",$=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),F=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=N(t),n=B(t),i=a?` let auth: LunoraAuth | null = null;
|
|
623
628
|
let authInit: Promise<void> | null = null;
|
|
624
629
|
`:"",o=a?`
|
|
625
630
|
const initAuth = async (env: Env): Promise<void> => {
|
|
@@ -680,7 +685,7 @@ ${u.map(p=>` { agent: lunoraAgentDefinitions.${p.exportName}, binding
|
|
|
680
685
|
`:"",f=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
681
686
|
public build(): ComposedApp {
|
|
682
687
|
return this.assemble();
|
|
683
|
-
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${
|
|
688
|
+
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${I(t).join(`
|
|
684
689
|
`)}
|
|
685
690
|
|
|
686
691
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
@@ -708,7 +713,7 @@ interface ComposedApp extends LunoraWorker {
|
|
|
708
713
|
* first request so per-isolate singletons are built once.
|
|
709
714
|
*/
|
|
710
715
|
class AppBuilder<Env extends object> {
|
|
711
|
-
${
|
|
716
|
+
${L(t).join(`
|
|
712
717
|
`)}
|
|
713
718
|
|
|
714
719
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
@@ -798,7 +803,7 @@ ${n.join(`
|
|
|
798
803
|
return options;
|
|
799
804
|
}
|
|
800
805
|
}
|
|
801
|
-
${
|
|
806
|
+
${H(t.hasGlobal)}
|
|
802
807
|
/**
|
|
803
808
|
* Shape of the project's root \`lunora.config.*\`.
|
|
804
809
|
*
|
|
@@ -829,5 +834,5 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
829
834
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
830
835
|
|
|
831
836
|
export { AppBuilder, defineApp };
|
|
832
|
-
export type { ${
|
|
837
|
+
export type { ${$(t)} };
|
|
833
838
|
`};export{F as emitApp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as u,SyntaxKind as f}from"ts-morph";import{posix as y}from"node:path";const j=/\bany\b(?!\s*(?:\?\s*)?:)/u,R=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,k=e=>j.test(e.replaceAll(R,"")),w="/_generated/",U=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},C=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,E=e=>{for(const t of e.getAncestors())if(u.isModuleDeclaration(t)){const n=C.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},D=new WeakMap,L=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=D.get(n.compilerSymbol);return r===void 0&&(r=new Map,D.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},x=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),O=(e,t,n)=>e.getModuleSpecifierValue()===t&&x(e,n)?n:void 0,$=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},P=(e,t,n)=>{if(!x(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:L(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},h=/^\.\.?(?:$|\/)/u,q=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),B=(e,t)=>{const n=t.getModuleSpecifierValue();if(!h.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:q.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${y.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=y.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},F=(e,t,n)=>{const r=E(t);for(const s of e.getImportDeclarations()){const i=r===void 0?$(s,t)??P(s,t,n):O(s,r,n);if(i!==void 0)return{exportName:i,specifier:B(e,s)??s.getModuleSpecifierValue()}}},K=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),g={kind:"verbatim"},m={kind:"expand"},V=new Set([f.ClassDeclaration,f.EnumDeclaration,f.EnumMember,f.InterfaceDeclaration,f.TypeAliasDeclaration]),W=e=>E(e)!==void 0||u.isExportable(e)&&e.isExported(),I=(e,t,n)=>{const r=e.getSourceFile();if(r.getSymbol()===void 0&&E(e)===void 0||!V.has(e.getKind()))return g;const s=r.getFilePath();if(s.includes(w))return g;if(s===n)return m;const i=u.isEnumMember(e)?e.getParent():e;if(!u.hasName(i))return m;const o=F(t.getSourceFile(),i,i.getName());return o===void 0?W(i)?g:m:K(o.specifier,t)?m:{kind:"qualify",qualified:o}},N=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1;for(const a of[s,r].flatMap(c=>c?.getDeclarations()??[])){const c=I(a,t,n);if(c.kind==="qualify"&&i.has(a))return c;o||=c.kind!=="verbatim"}return o?m:g},G=(e,t,n)=>{const r=u.isPropertySignature(e)||u.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return g;let s=!1;for(const i of[r,...r.getDescendantsOfKind(f.TypeReference)].filter(o=>u.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const a of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const c=I(a,t,n);if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?m:g},X=/^[A-Za-z_$][\w$]*$/u,H=e=>X.test(e)?e:JSON.stringify(e),M=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},p=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,b=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),N(e,t,n).kind!=="verbatim"||M(e).some(s=>b(s,t,n,r))?!0:p(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>G(i,t,n).kind!=="verbatim")?!0:b(s.getTypeAtLocation(t),t,n,r)):!1),Y=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(u.isPropertySignature(n)||u.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},J=32,z=8,Q=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),a=o?i(o,t,n,r,s):void 0;if(a!==void 0)return o?.isUnion()?`(${a})[]`:`${a}[]`},Z=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getUnionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(c)}return o.join(" | ")},ee=(e,t,n,r,s,i)=>{if(!p(e))return;const o=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),l=Y(a,c),_=l&&c.isUnion()?c.getUnionTypes().filter(v=>!v.isUndefined()):[c],T=[];for(const v of _){const A=i(v,t,n,r+1,s);if(A===void 0)return;T.push(A)}o.push(`${H(a.getName())}${l?"?":""}: ${T.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},te=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>u.isClassDeclaration(t)||u.isClassExpression(t)),S=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>J)return!0;const i=new Set(r).add(e);if(M(e).some(l=>S(l,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return S(o,t,n+1,i,s);if(U(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(l=>l?.getDeclarations()??[]).some(l=>u.isClassDeclaration(l)||u.isClassExpression(l)))return!0;const c=p(e)&&e.getProperties().some(l=>S(l.getTypeAtLocation(t),t,n+1,i,s));return c||s.add(e),c},re=(e,t,n,r,s,i,o)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const l=o(c,n,r,s+1,i);if(l===void 0)return;a.push(l)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},se=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>u.isEnumDeclaration(t)||u.isEnumMember(t)),d=(e,t,n,r,s)=>{if(r>z||s.has(e))return;const i=N(e,t,n);if(i.kind==="verbatim"&&!b(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!ne(e)){if(e.isEnumLiteral())return te(e);if(i.kind==="qualify"&&!se(e)){const a=re(i.qualified,e,t,n,r,o,d);if(a!==void 0)return a}return e.isArray()?Q(e,t,n,r,o,d):e.isUnion()?Z(e,t,n,r,o,d):ee(e,t,n,r,o,d)}},ae=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let n=t.getReturnType();const s=(n.getSymbol()??n.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=n.getTypeArguments()[0];a&&(n=a)}const i=n.getText(e);if(!i||i==="any"||i==="never"||k(i)||S(n,e,0,new Set))return"unknown";const o=e.getSourceFile().getFilePath();return b(n,e,o)?d(n,e,o,0,new Set)??"unknown":i};export{d as e,k as i,b as r,ae as u};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Node as l,SyntaxKind as f}from"ts-morph";import{posix as A}from"node:path";const j=/\bany\b(?!\s*(?:\?\s*)?:)/u,R=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,k=e=>j.test(e.replaceAll(R,"")),w="/_generated/",U=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},C=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,D=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=C.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},y=new WeakMap,L=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=y.get(n.compilerSymbol);return r===void 0&&(r=new Map,y.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},N=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),O=(e,t,n)=>e.getModuleSpecifierValue()===t&&N(e,n)?n:void 0,$=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},P=(e,t,n)=>{if(!N(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:L(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},h=/^\.\.?(?:$|\/)/u,q=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),B=(e,t)=>{const n=t.getModuleSpecifierValue();if(!h.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:q.get(r.getExtension());if(r===void 0||s===void 0)return;const o=`${A.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,i=A.relative(e.getDirectoryPath(),o);return i.startsWith(".")?i:`./${i}`},K=(e,t,n)=>{const r=D(t);for(const s of e.getImportDeclarations()){const o=r===void 0?$(s,t)??P(s,t,n):O(s,r,n);if(o!==void 0)return{exportName:o,specifier:B(e,s)??s.getModuleSpecifierValue()}}},V=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),g={kind:"verbatim"},d={kind:"expand"},F=new Set([f.ClassDeclaration,f.EnumDeclaration,f.EnumMember,f.InterfaceDeclaration,f.TypeAliasDeclaration]),x=(e,t,n)=>{const r=e.getSourceFile();if(r.getSymbol()===void 0&&D(e)===void 0||!F.has(e.getKind()))return g;const s=r.getFilePath();if(s.includes(w))return g;if(s===n)return d;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return d;const i=K(t.getSourceFile(),o,o.getName());return i===void 0?g:V(i.specifier,t)?d:{kind:"qualify",qualified:i}},I=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),o=new Set((r??s)?.getDeclarations());let i=!1;for(const a of[s,r].flatMap(c=>c?.getDeclarations()??[])){const c=x(a,t,n);if(c.kind==="qualify"&&o.has(a))return c;i||=c.kind!=="verbatim"}return i?d:g},W=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return g;let s=!1;for(const o of[r,...r.getDescendantsOfKind(f.TypeReference)].filter(i=>l.isTypeReference(i))){const i=o.getTypeName().getSymbol();for(const a of(i?.getAliasedSymbol()??i)?.getDeclarations()??[]){const c=x(a,t,n);if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?d:g},G=/^[A-Za-z_$][\w$]*$/u,X=e=>G.test(e)?e:JSON.stringify(e),M=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},E=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,b=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),I(e,t,n).kind!=="verbatim"||M(e).some(s=>b(s,t,n,r))?!0:E(e)?e.getProperties().some(s=>s.getDeclarations().some(o=>W(o,t,n).kind!=="verbatim")?!0:b(s.getTypeAtLocation(t),t,n,r)):!1),H=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},Y=32,J=8,z=(e,t,n,r,s,o)=>{const i=e.getArrayElementType(),a=i?o(i,t,n,r,s):void 0;if(a!==void 0)return i?.isUnion()?`(${a})[]`:`${a}[]`},Q=(e,t,n,r,s,o)=>{const i=[];for(const a of e.getUnionTypes()){const c=o(a,t,n,r,s);if(c===void 0)return;i.push(c)}return i.join(" | ")},Z=(e,t,n,r,s,o)=>{if(!E(e))return;const i=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=H(a,c),_=u&&c.isUnion()?c.getUnionTypes().filter(v=>!v.isUndefined()):[c],T=[];for(const v of _){const p=o(v,t,n,r+1,s);if(p===void 0)return;T.push(p)}i.push(`${X(a.getName())}${u?"?":""}: ${T.join(" | ")}`)}return i.length>0?`{ ${i.join("; ")} }`:"{}"},ee=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},te=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),S=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Y)return!0;const o=new Set(r).add(e);if(M(e).some(u=>S(u,t,n+1,o,s)))return!0;const i=e.getArrayElementType();if(i!==void 0)return S(i,t,n+1,o,s);if(U(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const c=E(e)&&e.getProperties().some(u=>S(u.getTypeAtLocation(t),t,n+1,o,s));return c||s.add(e),c},ne=(e,t,n,r,s,o,i)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=i(c,n,r,s+1,o);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},re=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>J||s.has(e))return;const o=I(e,t,n);if(o.kind==="verbatim"&&!b(e,t,n))return e.getText(t);const i=new Set(s).add(e);if(!te(e)){if(e.isEnumLiteral())return ee(e);if(o.kind==="qualify"&&!re(e)){const a=ne(o.qualified,e,t,n,r,i,m);if(a!==void 0)return a}return e.isArray()?z(e,t,n,r,i,m):e.isUnion()?Q(e,t,n,r,i,m):Z(e,t,n,r,i,m)}},oe=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let n=t.getReturnType();const s=(n.getSymbol()??n.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=n.getTypeArguments()[0];a&&(n=a)}const o=n.getText(e);if(!o||o==="any"||o==="never"||k(o)||S(n,e,0,new Set))return"unknown";const i=e.getSourceFile().getFilePath();return b(n,e,i)?m(n,e,i,0,new Set)??"unknown":o};export{m as e,k as i,b as r,oe as u};
|