@lunora/codegen 1.0.0-alpha.25 → 1.0.0-alpha.250
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/LICENSE.md +6 -0
- package/README.md +1 -1
- package/dist/index.d.mts +3755 -1247
- package/dist/index.d.ts +3755 -1247
- package/dist/index.mjs +1 -34
- package/dist/packem_shared/AGENTS_FILENAME-D8SgT3OR.mjs +1 -0
- package/dist/packem_shared/CONTAINERS_FILENAME-C13yKxas.mjs +1 -0
- package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TARGET-vMWzRzRF.mjs +1 -0
- package/dist/packem_shared/FLAGS_FILENAME-W5XQz_Po.mjs +1 -0
- package/dist/packem_shared/GENERATED_HEADER-DSXl0YM2.mjs +1 -0
- package/dist/packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs +1 -0
- package/dist/packem_shared/MUTATORS_FILENAME-DqWOgC5Z.mjs +1 -0
- package/dist/packem_shared/NOTIFY_FILENAME-C1J_47et.mjs +1 -0
- package/dist/packem_shared/OPENRPC_VERSION-Cr7Zzp6s.mjs +3 -0
- package/dist/packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs +1 -0
- package/dist/packem_shared/QUEUES_FILENAME-RGwht3Xu.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-jefy8GTn.mjs +11 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs +372 -0
- package/dist/packem_shared/SHAPES_FILENAME-DRUFomCj.mjs +1 -0
- package/dist/packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs +18 -0
- package/dist/packem_shared/WORKFLOWS_FILENAME-4-ib4HH-.mjs +1 -0
- package/dist/packem_shared/buildOpenApiDocument-SxfElVzK.mjs +3 -0
- package/dist/packem_shared/capabilities-CqnIsyA9.mjs +20 -0
- package/dist/packem_shared/chain-mte5djRJ.mjs +1 -0
- package/dist/packem_shared/classify-procedure-call-CmcShAze.mjs +1 -0
- package/dist/packem_shared/context-property-calls-CWf9-6G5.mjs +1 -0
- package/dist/packem_shared/contextPropertiesRead-BGy4tGCY.mjs +1 -0
- package/dist/packem_shared/declared-output-Iaar469J.mjs +1 -0
- package/dist/packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs +1 -0
- package/dist/packem_shared/discoverAuthApiCalls-DoSN_yc3.mjs +1 -0
- package/dist/packem_shared/discoverCrons-BEALHx1S.mjs +1 -0
- package/dist/packem_shared/discoverFunctions-BcBzcG5x.mjs +1 -0
- package/dist/packem_shared/discoverHttpRoutes-CJHS4llq.mjs +1 -0
- package/dist/packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs +1 -0
- package/dist/packem_shared/discoverInserts-DpuLYPPd.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-B0w8gM0S.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-Dt7ywfZv.mjs +1 -0
- package/dist/packem_shared/discoverNondeterministicCalls-CNJV2BiP.mjs +1 -0
- package/dist/packem_shared/discoverQueries-BcdqjYky.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs +1 -0
- package/dist/packem_shared/discoverRlsMetadata-mXBmPOGj.mjs +1 -0
- package/dist/packem_shared/discoverRlsProcedures-F4Cy-kSi.mjs +1 -0
- package/dist/packem_shared/discoverSandboxUsage-BnsPld5I.mjs +1 -0
- package/dist/packem_shared/discoverSchema-D5R60b4F.mjs +1 -0
- package/dist/packem_shared/discoverStorageRulesMetadata-D3Ot9g5f.mjs +1 -0
- package/dist/packem_shared/emitAgents-3XP5C-VJ.mjs +1 -0
- package/dist/packem_shared/emitApi-DdW9RyGG.mjs +154 -0
- package/dist/packem_shared/emitApp-T_My13i6.mjs +860 -0
- package/dist/packem_shared/emitCrons-BRKXFGFu.mjs +83 -0
- package/dist/packem_shared/emitDataModel-D3WuEZ4b.mjs +113 -0
- package/dist/packem_shared/emitDrizzleSchema-Cv0HtLR3.mjs +15 -0
- package/dist/packem_shared/emitFunctions-BgNeOZt_.mjs +249 -0
- package/dist/packem_shared/emitServer-DQxwHVPM.mjs +374 -0
- package/dist/packem_shared/emitShard-BDfiH_JF.mjs +1 -0
- package/dist/packem_shared/exported-procedure-chains-D48EXUVQ.mjs +1 -0
- package/dist/packem_shared/fingerprintSchemaSources-Cl1CJFeh.mjs +1 -0
- package/dist/packem_shared/formatAdvisories-DwmUKYuc.mjs +2 -0
- package/dist/packem_shared/index-D7dKfGPh.mjs +1 -0
- package/dist/packem_shared/ir-DBSvhNa-.mjs +1 -0
- package/dist/packem_shared/isD1GlobalTable-udvHAAzD.mjs +1 -0
- package/dist/packem_shared/isTypedSchema-CKzc3ioR.mjs +4 -0
- package/dist/packem_shared/json-data-Chfs2Cz5.mjs +1 -0
- package/dist/packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs +1 -0
- package/dist/packem_shared/loadProjectConfig-nNIDOrlR.mjs +1 -0
- package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
- package/dist/packem_shared/modules-DyCocr1e.mjs +1 -0
- package/dist/packem_shared/parse-validator-C6fHL7OS.mjs +1 -0
- package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
- package/dist/packem_shared/qualifiers-BhOL15WZ.mjs +1 -0
- package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
- package/dist/packem_shared/readServiceBindings-CeQvSswr.mjs +1 -0
- package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
- package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
- package/dist/packem_shared/shard-f7coQFS9.mjs +1435 -0
- package/dist/packem_shared/shard-runtime-CyEbIjPA.mjs +321 -0
- package/dist/packem_shared/shared-DjUziztz.mjs +9 -0
- package/dist/packem_shared/unwrap-handler-return-DVY_kFF7.mjs +1 -0
- package/package.json +16 -7
- package/dist/packem_shared/CONTAINERS_FILENAME-DlP6YM_Q.mjs +0 -224
- package/dist/packem_shared/CodegenDiagnosticError-DeblMkzO.mjs +0 -23
- package/dist/packem_shared/FLAGS_FILENAME-B1vE0LIo.mjs +0 -139
- package/dist/packem_shared/GENERATED_HEADER-BullHnLo.mjs +0 -3265
- package/dist/packem_shared/LUNORA_ERROR_CODES-CySpQPD3.mjs +0 -61
- package/dist/packem_shared/LUNORA_SOLUTION_RULES-BTejmZp-.mjs +0 -131
- package/dist/packem_shared/MUTATORS_FILENAME-BhqdPtKp.mjs +0 -81
- package/dist/packem_shared/OPENRPC_VERSION-D7MAVX3K.mjs +0 -60
- package/dist/packem_shared/QUEUES_FILENAME-B5_eWCRe.mjs +0 -119
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-BAcxxSdB.mjs +0 -1130
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-wWGP2_5E.mjs +0 -245
- package/dist/packem_shared/SHAPES_FILENAME-ChV7MqgE.mjs +0 -94
- package/dist/packem_shared/WORKFLOWS_FILENAME-CCisG0Vy.mjs +0 -124
- package/dist/packem_shared/buildOpenApiDocument-Bm56LsBb.mjs +0 -183
- package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
- package/dist/packem_shared/discoverAuthApiCalls-CoirYbg6.mjs +0 -62
- package/dist/packem_shared/discoverCrons-Cev7RRAf.mjs +0 -257
- package/dist/packem_shared/discoverFunctions-BWMczzBx.mjs +0 -465
- package/dist/packem_shared/discoverHttpRoutes-CfP6cMzt.mjs +0 -131
- package/dist/packem_shared/discoverInserts-C7zxXkUf.mjs +0 -61
- package/dist/packem_shared/discoverMaskProcedures-Cm81kwrb.mjs +0 -217
- package/dist/packem_shared/discoverMigrations-Bi5nJ0mJ.mjs +0 -97
- package/dist/packem_shared/discoverNondeterministicCalls-C4M8AXmQ.mjs +0 -122
- package/dist/packem_shared/discoverQueries-B0wGT-xe.mjs +0 -62
- package/dist/packem_shared/discoverR2sqlCalls-BVNMd428.mjs +0 -80
- package/dist/packem_shared/discoverRlsMetadata-BS9GOGC5.mjs +0 -280
- package/dist/packem_shared/discoverSchema-KYq55qu3.mjs +0 -864
- package/dist/packem_shared/discoverStorageRulesMetadata-Da8BKXcI.mjs +0 -97
- package/dist/packem_shared/emitApp-BUN7hhlY.mjs +0 -666
- package/dist/packem_shared/formatAdvisories-DdjK7sgh.mjs +0 -81
- package/dist/packem_shared/parse-validator-Cabb60UV.mjs +0 -133
- package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
- package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import{relative as Ne,isAbsolute as Me,sep as Ae}from"node:path";import{LunoraError as z}from"@lunora/errors";import{C as De}from"./capabilities-CqnIsyA9.mjs";import{p as Se}from"./ir-DBSvhNa-.mjs";import{a as p,G as Fe,u as We,d as Qe}from"./shared-DjUziztz.mjs";const Pe=/\.([cm]?)tsx?$/u,je=(l,n=[])=>{const r=new Set;for(const t of l.tables)for(const d of Object.values(t.shape)){const s=We(d);s.kind==="storage"&&typeof s.bucket=="string"&&s.bucket!==""&&r.add(s.bucket)}for(const t of n)t!==""&&t!=="default"&&r.add(t);return["default",...[...r].toSorted((t,d)=>t.localeCompare(d))]},He=({agents:l=[],capabilities:n=new Set,containers:r=[],env:t,hasVectors:d=!0,hasFlags:s=!1,hasNotify:U=!1,identity:i,queues:O=[],schema:C,generatedDirectory:N="",services:y=[],storageRuleBuckets:X=[],topics:M=[],useUmbrella:J=!1,workflows:A=[]}={})=>{const o=Qe(J),m=n.has("ai"),D=n.has("payments"),S=n.has("x402"),K=je(C??{tables:[]},X).map(e=>JSON.stringify(e)).join(" | "),Y=m?`import type { LunoraAi } from "@lunora/ai";
|
|
2
|
+
`:"",Z=m?`
|
|
3
|
+
readonly ai: LunoraAi;`:"",ee=D?`import type { LunoraPayment } from "@lunora/payment";
|
|
4
|
+
`:"",te=D?`
|
|
5
|
+
readonly payments: LunoraPayment;`:"",ae=S?`import type { X402Pay } from "@lunora/x402/pay";
|
|
6
|
+
`:"",re=S?`
|
|
7
|
+
readonly x402: X402Pay;`:"",F=e=>e.sandbox===!0?"SandboxContainerAccessor":"ContainerAccessor",oe=[...new Set(r.map(e=>F(e)))].toSorted((e,a)=>e.localeCompare(a)),ne=r.length>0?`import type { ${oe.join(", ")} } from "@lunora/container";
|
|
8
|
+
`:"",se=r.length>0?`
|
|
9
|
+
readonly containers: {${r.map(e=>`
|
|
10
|
+
readonly ${e.exportName}: ${F(e)};`).join("")}
|
|
11
|
+
};`:"",W=[...m?[" /** Workers AI binding (the conventional `env.AI`), narrowing `ctx.ai`. */\n readonly AI?: unknown;"]:[],...r.map(e=>(p(e.bindingName,`container binding "${e.bindingName}"`),` /** Durable Object namespace for the \`${e.exportName}\` container. */
|
|
12
|
+
readonly ${e.bindingName}?: unknown;`)),...O.map(e=>(p(e.bindingName,`queue binding "${e.bindingName}"`),` /** Queue producer binding for the \`${e.exportName}\` queue. */
|
|
13
|
+
readonly ${e.bindingName}?: unknown;`))].join(`
|
|
14
|
+
`),ie=`
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* This project's Cloudflare bindings, as far as codegen can discover them from
|
|
18
|
+
* \`lunora/\` source — the container/workflow Durable Object namespaces and the
|
|
19
|
+
* conventional Workers AI binding. Bindings the config layer reconciles from
|
|
20
|
+
* user-named wrangler config (R2/KV/D1/\`services\`/queues/…) aren't statically
|
|
21
|
+
* visible here, so the open index signature keeps them reachable (cast at the
|
|
22
|
+
* use site). Service bindings (\`env.<SERVICE>.fetch(...)\` / RPC stubs) live
|
|
23
|
+
* under this signature too — Lunora can't type a third-party worker's RPC
|
|
24
|
+
* surface, so treat them as \`Fetcher\`/\`Service<unknown>\` and cast.
|
|
25
|
+
*/
|
|
26
|
+
export interface CloudflareBindings {
|
|
27
|
+
readonly [binding: string]: unknown;${W?`
|
|
28
|
+
${W}`:""}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Alias for {@link CloudflareBindings} — the typed shape of \`env\`. */
|
|
32
|
+
export type Env = CloudflareBindings;`,Q=e=>De.map(a=>a.serverCtxField!==void 0&&e.includes(a.tier)&&n.has(a.key)?a.serverCtxField:"").join(""),P=Q(["every"]),de=Q(["every","action"]),c=d&&(C?.vectorIndexes.length??0)>0,h=c?' | "vectors"':"",j=c?`
|
|
33
|
+
readonly vectors: VectorSearch<VectorIndexName>;`:"",le=c?`
|
|
34
|
+
readonly vectors: VectorSearchReader<VectorIndexName>;`:"",ce=c?`import type { VectorSearch, VectorSearchReader } from "${o.server}";
|
|
35
|
+
import type { VectorIndexName } from "./dataModel.js";
|
|
36
|
+
`:"",b=s?`
|
|
37
|
+
/** Feature-flag evaluation (OpenFeature). Reads are memoized per request; evaluations never throw — a provider error resolves to the supplied default. */
|
|
38
|
+
readonly flags: import("${o.flags}").LunoraFlags;`:"",f=U?`
|
|
39
|
+
/** Multi-channel notifications (@lunora/notify): send / chat / inApp / webhook plus the push device sub-facade. Sends are external I/O — confine them to action handlers. */
|
|
40
|
+
readonly notify: import("@lunora/notify").LunoraNotify;
|
|
41
|
+
/** Device push sub-facade — the same object as ctx.notify.push (register / send / broadcast). Sends belong in action handlers. */
|
|
42
|
+
readonly push: import("@lunora/notify").LunoraPush;`:"",u=A.length>0,ue=u?`import type { WorkflowHandle } from "@lunora/workflow";
|
|
43
|
+
import type * as lunoraWorkflowDefinitions from "../workflows.js";
|
|
44
|
+
`:"",pe=u?`
|
|
45
|
+
|
|
46
|
+
/** Params type carried by a \`defineWorkflow\` definition (its phantom \`__params\`). */
|
|
47
|
+
type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params }
|
|
48
|
+
? unknown extends Params
|
|
49
|
+
? Record<string, unknown>
|
|
50
|
+
: NonNullable<Params>
|
|
51
|
+
: Record<string, unknown>;
|
|
52
|
+
|
|
53
|
+
/** This project's declared workflows, addressable from \`ctx.workflows\` by their \`lunora/workflows.ts\` export name. */
|
|
54
|
+
export interface LunoraWorkflows {
|
|
55
|
+
${A.map(e=>` get(name: ${JSON.stringify(e.exportName)}): WorkflowHandle<WorkflowParamsOf<typeof lunoraWorkflowDefinitions.${e.exportName}>>;`).join(`
|
|
56
|
+
`)}
|
|
57
|
+
}`:"",E=u?' | "workflows"':"",L=u?`
|
|
58
|
+
readonly workflows: LunoraWorkflows;`:"",q=Se(O),x=q.length>0,g=M.length>0,T=[...x?["QueueProducer"]:[],...g?["TopicPublisher"]:[]],ye=T.length>0?`import type { ${T.join(", ")} } from "@lunora/queue";
|
|
59
|
+
import type * as lunoraQueueDefinitions from "../queues.js";
|
|
60
|
+
`:"",me=T.length>0?"\n\n/** Message body type carried by a `defineQueue` / `defineTopic` definition (its phantom `__lunoraBody`). */\ntype QueueBodyOf<Definition> = Definition extends { __lunoraBody?: infer Body } ? (unknown extends Body ? unknown : NonNullable<Body>) : unknown;":"",he=x?`
|
|
61
|
+
|
|
62
|
+
/** This project's declared queues, addressable from \`ctx.queues\` by their \`lunora/queues.ts\` export name. */
|
|
63
|
+
export interface LunoraQueues {
|
|
64
|
+
${q.map(e=>` readonly ${e.exportName}: QueueProducer<QueueBodyOf<typeof lunoraQueueDefinitions.${e.exportName}>>;`).join(`
|
|
65
|
+
`)}
|
|
66
|
+
}`:"",be=g?`
|
|
67
|
+
|
|
68
|
+
/** This project's declared topics, addressable from \`ctx.topics\` by their \`lunora/queues.ts\` export name. */
|
|
69
|
+
export interface LunoraTopics {
|
|
70
|
+
${M.map(e=>` readonly ${e.exportName}: TopicPublisher<QueueBodyOf<typeof lunoraQueueDefinitions.${e.exportName}>>;`).join(`
|
|
71
|
+
`)}
|
|
72
|
+
}`:"",fe=`${me}${he}${be}`,G=x?`
|
|
73
|
+
readonly queues: LunoraQueues;`:"",V=g?`
|
|
74
|
+
readonly topics: LunoraTopics;`:"",v=y.length>0,xe=e=>{if(N==="")throw new z("INTERNAL","@lunora/codegen: emitServer needs `generatedDirectory` to import an RPC service's types");const a=Ne(N,e);if(Me(a))throw new z("INTERNAL",`@lunora/codegen: an RPC service's entry (${e}) must be on the same drive as the app`);const R=a.split(Ae).join("/").replace(Pe,".$1js");return R.startsWith(".")?R:`./${R}`},_=y.filter(e=>e.rpcEntrypoint!==void 0),ge=_.length>0?"ServiceFetcher, ServiceRpc":"ServiceFetcher",Te=v?`import type { ${ge} } from "${o.server}";
|
|
75
|
+
${_.map(e=>`import type * as lunoraService_${e.name} from ${JSON.stringify(xe(e.main))};
|
|
76
|
+
`).join("")}`:"",ve=v?`
|
|
77
|
+
|
|
78
|
+
/** This project's service bindings (\`lunora.config\` \`services\`), addressable from \`ctx.services\` in actions. */
|
|
79
|
+
export interface LunoraServices {
|
|
80
|
+
${y.map(e=>{p(e.name,`service "${e.name}"`);const a=e.rpcEntrypoint===void 0?"ServiceFetcher":`ServiceRpc<typeof lunoraService_${e.name}.${e.rpcEntrypoint}>`;return` readonly ${e.name}: ${a};`}).join(`
|
|
81
|
+
`)}
|
|
82
|
+
}`:"",ke=v?`
|
|
83
|
+
readonly services: LunoraServices;`:"",k=l.length>0,we=k?`import type { AgentHandle } from "@lunora/agent";
|
|
84
|
+
`:"",Ie=k?`
|
|
85
|
+
|
|
86
|
+
/** This project's declared agents, addressable from \`ctx.agents\` by their \`lunora/agents.ts\` export name. */
|
|
87
|
+
export interface LunoraAgents {
|
|
88
|
+
${l.map(e=>(p(e.exportName,`agent export "${e.exportName}"`),` readonly ${e.exportName}: AgentHandle;`)).join(`
|
|
89
|
+
`)}
|
|
90
|
+
}`:"",H=k?`
|
|
91
|
+
readonly agents: LunoraAgents;`:"",$e=i?`import type { InferIdentity } from "${o.server}";
|
|
92
|
+
import type * as lunoraIdentityContract from "../identity.js";
|
|
93
|
+
`:"",Be=i?`
|
|
94
|
+
|
|
95
|
+
/** This app's declared identity claim contract (\`defineIdentity\` in \`lunora/identity.ts\`) — the typed shape of \`ctx.auth.getIdentity()\`, the RLS policy \`ctx.auth.identity\`, and the \`authorizeShard\`/\`authorizeFanOut\` identity argument. */
|
|
96
|
+
export type Identity = InferIdentity<typeof lunoraIdentityContract.${i.exportName}>;
|
|
97
|
+
|
|
98
|
+
/** \`ctx.auth\` narrowed so \`getIdentity()\` resolves the declared {@link Identity} contract instead of the untyped claim bag. */
|
|
99
|
+
type NarrowedAuth = Omit<QueryCtxBase["auth"], "getIdentity"> & { getIdentity: () => Promise<Identity | null> };`:"",w=i?' | "auth"':"",I=i?`
|
|
100
|
+
readonly auth: NarrowedAuth;`:"",Re=i?", Identity":"",Oe=t?`import type * as lunoraEnvContract from "../env.js";
|
|
101
|
+
`:"",Ce=t?`
|
|
102
|
+
|
|
103
|
+
/** This app's declared env contract (\`defineEnv\` in \`lunora/env.ts\`) — the validated, coercion-aware shape of \`ctx.env\`. */
|
|
104
|
+
export type LunoraEnv = ReturnType<typeof lunoraEnvContract.${t.exportName}>;`:"",$=t?' | "env"':"",B=t?"\n /** Validated, typed environment declared by `defineEnv` in `lunora/env.ts` — parsed & coercion-aware config values (`ctx.env.STRIPE_KEY`); a missing or invalid value throws at read time. */\n readonly env: LunoraEnv;":"";return`${Fe}import { createPolicyDsl, defineMutator as defineMutatorBase, initLunora, v as vBase } from "${o.server}";
|
|
105
|
+
import type {
|
|
106
|
+
ActionBuilder,
|
|
107
|
+
ActionCtx as ActionCtxBase,
|
|
108
|
+
ColumnValidator,
|
|
109
|
+
DatabaseReader,
|
|
110
|
+
DatabaseWriter,
|
|
111
|
+
EmptyArgs,
|
|
112
|
+
InternalActionBuilder,
|
|
113
|
+
InternalMutationBuilder,
|
|
114
|
+
InternalQueryBuilder,
|
|
115
|
+
MutationBuilder,
|
|
116
|
+
MutationCtx as MutationCtxBase,
|
|
117
|
+
MutationStorage,
|
|
118
|
+
MutatorDefinition,
|
|
119
|
+
QueryBuilder,
|
|
120
|
+
QueryCtx as QueryCtxBase,
|
|
121
|
+
ReadOnlyStorage,
|
|
122
|
+
RegisteredMutator,
|
|
123
|
+
Storage as StorageBase,
|
|
124
|
+
TableReader,
|
|
125
|
+
Validator,
|
|
126
|
+
} from "${o.server}";
|
|
127
|
+
|
|
128
|
+
import type {
|
|
129
|
+
DatabaseReaderFacade as DatabaseReaderFacadeOf,
|
|
130
|
+
DatabaseWriterFacade as DatabaseWriterFacadeOf,
|
|
131
|
+
LoadWith as LoadWithOf,
|
|
132
|
+
TableReaderFacade as TableReaderFacadeOf,
|
|
133
|
+
TableWriterFacade as TableWriterFacadeOf,
|
|
134
|
+
WithArg as WithArgOf,
|
|
135
|
+
} from "${o.serverDataModel}";
|
|
136
|
+
|
|
137
|
+
export type {
|
|
138
|
+
AggregateOp,
|
|
139
|
+
GroupByEntry,
|
|
140
|
+
OrderBy,
|
|
141
|
+
QueryArgs,
|
|
142
|
+
QueryPage,
|
|
143
|
+
RankPage,
|
|
144
|
+
RankResult,
|
|
145
|
+
RestrictableQueryOptions,
|
|
146
|
+
RestrictableQueryOptionsOf,
|
|
147
|
+
SearchFilterBuilder,
|
|
148
|
+
SearchReader,
|
|
149
|
+
TableAggregateOptions,
|
|
150
|
+
TableAggregateOptionsOf,
|
|
151
|
+
TableGroupByOptions,
|
|
152
|
+
TableGroupByOptionsOf,
|
|
153
|
+
TableRankOptions,
|
|
154
|
+
TableRankPageOptions,
|
|
155
|
+
Where,
|
|
156
|
+
WhereOf,
|
|
157
|
+
WhereOperators,
|
|
158
|
+
} from "${o.serverDataModel}";
|
|
159
|
+
|
|
160
|
+
import type { DataModel, Doc, GeoIndexNamesByTable, Id as IdOfTable, IndexNamesByTable, Insert, InsertModel, RankIndexNamesByTable, Relations, SearchIndexNamesByTable, TableName } from "./dataModel.js";
|
|
161
|
+
${ce}${Y}${ee}${ae}${ne}${ue}${ye}${Te}${we}${$e}${Oe}
|
|
162
|
+
export type { AppTableName, DataModel, Doc, Id, TableName } from "./dataModel.js";
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The query-DSL bindings: \`@lunora/server/data-model\`'s generics parameterized
|
|
166
|
+
* over this project's \`DataModel\` / \`InsertModel\` / \`Relations\` / index maps.
|
|
167
|
+
*
|
|
168
|
+
* They live here rather than in \`dataModel.ts\` because they are the half that
|
|
169
|
+
* needs the SERVER package. Keeping \`dataModel.ts\` free of it lets a sibling
|
|
170
|
+
* package — a web app, another Worker — compile \`api.ts\` for its \`Doc\`/\`Id\`
|
|
171
|
+
* types without installing a server dependency to do it.
|
|
172
|
+
*/
|
|
173
|
+
|
|
174
|
+
/** The \`with\` argument for table \`T\` — see \`@lunora/server/data-model\`. */
|
|
175
|
+
export type WithArg<T extends keyof DataModel> = WithArgOf<DataModel, Relations, T>;
|
|
176
|
+
|
|
177
|
+
/** \`Doc<T>\` narrowed to exactly the relations requested in the with-arg \`W\`. */
|
|
178
|
+
export type LoadWith<T extends keyof DataModel, W> = LoadWithOf<DataModel, Relations, T, W>;
|
|
179
|
+
|
|
180
|
+
/** Read-only typed table accessor exposed on \`QueryCtx.db.<table>\`. */
|
|
181
|
+
export type TableReaderFacade<T extends keyof DataModel> = TableReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
|
|
182
|
+
|
|
183
|
+
/** Read-write typed table accessor exposed on \`MutationCtx.db.<table>\` / \`ActionCtx.db.<table>\`. */
|
|
184
|
+
export type TableWriterFacade<T extends keyof DataModel> = TableWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, T, GeoIndexNamesByTable>;
|
|
185
|
+
|
|
186
|
+
/** Per-table read facade — \`ctx.db.<table>\` on a \`QueryCtx\`. */
|
|
187
|
+
export type DatabaseReaderFacade = DatabaseReaderFacadeOf<DataModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
|
|
188
|
+
|
|
189
|
+
/** Per-table read-write facade — \`ctx.db.<table>\` on a \`MutationCtx\` / \`ActionCtx\`. */
|
|
190
|
+
export type DatabaseWriterFacade = DatabaseWriterFacadeOf<DataModel, InsertModel, Relations, RankIndexNamesByTable, SearchIndexNamesByTable, GeoIndexNamesByTable>;
|
|
191
|
+
|
|
192
|
+
/** Insert builder returned by \`ctx.orm.insert(table)\`. */
|
|
193
|
+
export interface OrmInsertBuilder<T extends keyof DataModel> {
|
|
194
|
+
values: (values: Insert<T>) => Promise<IdOfTable<T>>;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Replace builder returned by \`ctx.orm.replace(table, id)\` — swaps the whole document. */
|
|
198
|
+
export interface OrmReplaceBuilder<T extends keyof DataModel> {
|
|
199
|
+
with: (values: Insert<T>) => Promise<void>;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Update builder returned by \`ctx.orm.update(table, id)\` — patches the named fields. */
|
|
203
|
+
export interface OrmUpdateBuilder<T extends keyof DataModel> {
|
|
204
|
+
set: (values: Partial<Insert<T>>) => Promise<void>;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Read-only ORM surface — \`ctx.orm\` on a \`QueryCtx\`. Mirrors \`ctx.db\` reads under a kitcn-style \`query\` namespace. */
|
|
208
|
+
export interface OrmReader {
|
|
209
|
+
query: DatabaseReaderFacade;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Read-write ORM surface — \`ctx.orm\` on a \`MutationCtx\` / \`ActionCtx\`. Writes are addressed by id, like \`ctx.db\`. */
|
|
213
|
+
export interface OrmWriter extends OrmReader {
|
|
214
|
+
delete: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => Promise<void>;
|
|
215
|
+
insert: <T extends keyof DataModel>(table: T) => OrmInsertBuilder<T>;
|
|
216
|
+
replace: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmReplaceBuilder<T>;
|
|
217
|
+
update: <T extends keyof DataModel>(table: T, id: IdOfTable<T>) => OrmUpdateBuilder<T>;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Storage buckets this schema declares (\`v.storage("name")\`), narrowing \`ctx.storage.bucket(name)\`. */
|
|
221
|
+
export type StorageBucketName = ${K};${ie}${pe}${fe}${ve}${Ie}${Be}${Ce}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Project-typed contexts. The base contexts from \`@lunora/server\` are
|
|
225
|
+
* untyped against the schema; here \`db\` is widened to the generated per-table
|
|
226
|
+
* facade (\`ctx.db.<table>.findMany(...)\`) while keeping the legacy structural
|
|
227
|
+
* \`db.get\`/\`db.query\` surface for back-compat, and \`storage\` is narrowed so
|
|
228
|
+
* \`ctx.storage.bucket(name)\` autocompletes the declared buckets.
|
|
229
|
+
*/
|
|
230
|
+
/**
|
|
231
|
+
* The Convex-style fluent reader \`ctx.db.query(table)\`, bound to this schema:
|
|
232
|
+
* a table-name literal narrows the row type, so \`.collect()\` / \`.first()\` /
|
|
233
|
+
* \`.take()\` (and the \`.withIndex()\` / \`.filter()\` / \`.order()\` chain) resolve
|
|
234
|
+
* as \`Doc<table>\` with no \`as unknown as Doc<...>\` casts. The per-table accessor
|
|
235
|
+
* \`ctx.db.<table>\` stays available alongside it via the facade.
|
|
236
|
+
*
|
|
237
|
+
* Intersected with the wide \`(string) => TableReader\` signature so the bound
|
|
238
|
+
* \`ctx.db\` is still structurally assignable to schema-agnostic consumers that
|
|
239
|
+
* call \`db.query(someString)\` (e.g. \`@lunora/ratelimit\`'s \`createDbStore\`).
|
|
240
|
+
*
|
|
241
|
+
* The three index-name unions are what make \`.withIndex("by_TYPO")\` a compile
|
|
242
|
+
* error: each resolves to the table's declared names, or \`never\` when it
|
|
243
|
+
* declares none of that kind. Without them a renamed or dropped index left
|
|
244
|
+
* every call site typechecking, and the query either threw at runtime or
|
|
245
|
+
* degraded silently to a full table scan.
|
|
246
|
+
*/
|
|
247
|
+
type TypedTableQuery = (<T extends TableName>(
|
|
248
|
+
table: T,
|
|
249
|
+
) => TableReader<Doc<T>, IndexNamesByTable[T], SearchIndexNamesByTable[T], GeoIndexNamesByTable[T]>) &
|
|
250
|
+
((table: string) => TableReader);
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The point read \`ctx.db.get(id)\`, bound to this schema: an \`Id<"table">\`
|
|
254
|
+
* carries its table name, so the resolved document is typed \`Doc<table>\` (or
|
|
255
|
+
* \`null\` when absent) with no \`as Doc<...>\` cast. Mirrors {@link TypedTableQuery}.
|
|
256
|
+
*/
|
|
257
|
+
type TypedTableGet = <T extends TableName>(id: IdOfTable<T>) => Promise<Doc<T> | null>;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Resolves the \`asId\` table argument: a literal in {@link TableName} passes through, a
|
|
261
|
+
* genuinely-wide \`string\` (a computed name) passes through, and any OTHER literal
|
|
262
|
+
* collapses to \`never\` so it fails to typecheck.
|
|
263
|
+
*
|
|
264
|
+
* The \`string extends T\` arm is what distinguishes "the caller passed a computed
|
|
265
|
+
* string" from "the caller passed a misspelled literal" — only the wide \`string\` type
|
|
266
|
+
* is a supertype of \`string\`.
|
|
267
|
+
*/
|
|
268
|
+
type AsIdTable<T extends string> = T extends TableName ? T : string extends T ? T : never;
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The id parse boundary \`ctx.db.asId(table, id)\`, bound to this schema: a misspelled
|
|
272
|
+
* table literal is a compile error rather than a call that hands back a confidently-
|
|
273
|
+
* branded id for a table that does not exist. Mirrors {@link TypedTableQuery} /
|
|
274
|
+
* {@link TypedTableGet}.
|
|
275
|
+
*
|
|
276
|
+
* Deliberately NOT an intersection with a wide \`(string, string) => string\` overload:
|
|
277
|
+
* overload resolution would fall through to it for a bad literal, silently restoring
|
|
278
|
+
* the very typo hole this narrowing exists to close. {@link AsIdTable} instead keeps a
|
|
279
|
+
* computed table name working — and keeps \`ctx.db\` structurally assignable to
|
|
280
|
+
* schema-agnostic consumers — without accepting an invalid literal.
|
|
281
|
+
*/
|
|
282
|
+
type TypedAsId = <T extends string>(tableName: AsIdTable<T>, id: string) => IdOfTable<T & TableName>;
|
|
283
|
+
|
|
284
|
+
export interface QueryCtx extends Omit<QueryCtxBase, "db" | "storage"${h}${w}${$}> {
|
|
285
|
+
readonly db: Omit<DatabaseReader, "asId" | "query" | "get"> & DatabaseReaderFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
286
|
+
readonly orm: OrmReader;
|
|
287
|
+
readonly storage: ReadOnlyStorage<StorageBucketName>;${le}${P}${b}${f}${B}${I}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export interface MutationCtx extends Omit<MutationCtxBase, "db" | "storage"${h}${E}${w}${$}> {
|
|
291
|
+
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
292
|
+
readonly orm: OrmWriter;
|
|
293
|
+
readonly storage: MutationStorage<StorageBucketName>;${j}${P}${b}${f}${B}${L}${G}${V}${H}${I}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export interface ActionCtx extends Omit<ActionCtxBase, "db" | "storage"${h}${E}${w}${$}> {
|
|
297
|
+
readonly db: Omit<DatabaseWriter, "asId" | "query" | "get"> & DatabaseWriterFacade & { asId: TypedAsId; query: TypedTableQuery; get: TypedTableGet };
|
|
298
|
+
readonly orm: OrmWriter;
|
|
299
|
+
readonly storage: StorageBase<StorageBucketName>;${j}${de}${Z}${te}${re}${se}${b}${f}${ke}${B}${L}${G}${V}${H}${I}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Procedure builders bound to this project's typed contexts. Chain
|
|
304
|
+
* \`.input({...})\` to declare args, \`.use(middleware)\` for rate limiting / RLS /
|
|
305
|
+
* masking (each middleware may refine \`ctx\`), then the terminal
|
|
306
|
+
* \`.query()\` / \`.mutation()\` / \`.action()\` with a \`({ ctx, args }) => ...\`
|
|
307
|
+
* handler. \`.output(validator)\` and (queries) \`.stream()\` are also available.
|
|
308
|
+
*/
|
|
309
|
+
const lunoraBuilders = initLunora.dataModel<DataModel>().create();
|
|
310
|
+
|
|
311
|
+
/** \`query\` builder bound to this project's typed {@link QueryCtx}. */
|
|
312
|
+
export const query = lunoraBuilders.query as unknown as QueryBuilder<QueryCtx, EmptyArgs>;
|
|
313
|
+
|
|
314
|
+
/** \`mutation\` builder bound to this project's typed {@link MutationCtx}. */
|
|
315
|
+
export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder<MutationCtx, EmptyArgs>;
|
|
316
|
+
|
|
317
|
+
/** \`action\` builder bound to this project's typed {@link ActionCtx}. */
|
|
318
|
+
export const action = lunoraBuilders.action as unknown as ActionBuilder<ActionCtx, EmptyArgs>;
|
|
319
|
+
|
|
320
|
+
/** \`internalQuery\` builder bound to this project's typed {@link QueryCtx} — never exposed on \`api\`. */
|
|
321
|
+
export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder<QueryCtx, EmptyArgs>;
|
|
322
|
+
|
|
323
|
+
/** \`internalMutation\` builder bound to this project's typed {@link MutationCtx} — never exposed on \`api\`. */
|
|
324
|
+
export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder<MutationCtx, EmptyArgs>;
|
|
325
|
+
|
|
326
|
+
/** \`internalAction\` builder bound to this project's typed {@link ActionCtx} — never exposed on \`api\`. */
|
|
327
|
+
export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder<ActionCtx, EmptyArgs>;
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* \`defineMutator\` bound to this project's typed {@link MutationCtx} — declare
|
|
331
|
+
* custom mutators (\`lunora/mutators.ts\`) with it instead of importing from
|
|
332
|
+
* \`${o.server}\`, and the authoritative \`server\` impl's \`ctx\` carries the
|
|
333
|
+
* schema-typed \`ctx.db\` (\`ctx.db.query("nodes")\` resolves \`Doc<"nodes">\`,
|
|
334
|
+
* \`ctx.db.patch(id, …)\` takes an \`Id<"nodes">\`) with no hand-written ctx type and
|
|
335
|
+
* no \`as unknown as\` cast. Runtime-identical to the package export; only the
|
|
336
|
+
* context type narrows, so discovery finds a mutator authored either way.
|
|
337
|
+
* @example
|
|
338
|
+
* export const setText = defineMutator({
|
|
339
|
+
* args: { id: v.id("nodes"), text: v.string() },
|
|
340
|
+
* server: async (ctx, args) => { await ctx.db.patch(args.id, { text: args.text }); },
|
|
341
|
+
* });
|
|
342
|
+
*/
|
|
343
|
+
export const defineMutator = defineMutatorBase as unknown as <Args extends Record<string, Validator> = Record<string, Validator>, ClientTx = unknown, R = unknown>(
|
|
344
|
+
definition: MutatorDefinition<Args, MutationCtx, ClientTx, R>,
|
|
345
|
+
) => RegisteredMutator<Args, MutationCtx, ClientTx, R>;
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* \`definePolicy\` bound to THIS schema's {@link DataModel} + {@link Relations}.
|
|
349
|
+
* Import it from here (\`./_generated/server\`) instead of \`@lunora/server\` to get
|
|
350
|
+
* a relation-aware RLS authoring surface: \`table\` autocompletes to a real table
|
|
351
|
+
* name and the \`when\` predicate type-checks against the table's columns **and**
|
|
352
|
+
* its declared relations — \`{ author: { is: {...} } }\`, \`{ posts: { some: {...} } }\`,
|
|
353
|
+
* etc. (the \`@lunora/do\` pre-resolver resolves relation predicates on reads).
|
|
354
|
+
* Runtime-identical to \`@lunora/server\`'s \`definePolicy\`; only the types narrow,
|
|
355
|
+
* so the \`rls()\` chain discovers a policy authored either way the same.
|
|
356
|
+
*/
|
|
357
|
+
export const definePolicy = createPolicyDsl<DataModel, Relations${Re}>();
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* The validator builder \`v\`, with \`v.id(...)\` constrained to THIS schema's
|
|
361
|
+
* table names — so the argument autocompletes and returns a precise
|
|
362
|
+
* \`Id<"table">\`. Identical to \`@lunora/server\`'s \`v\` at runtime; the only
|
|
363
|
+
* difference is the tightened \`id\` type.
|
|
364
|
+
*
|
|
365
|
+
* Import \`v\` from here (\`./_generated/server\`) in your queries/mutations/actions
|
|
366
|
+
* to get table-name autocomplete. \`lunora/schema.ts\` can't use it — it is the
|
|
367
|
+
* file that defines the table names, so they aren't known yet there; pass the
|
|
368
|
+
* names as string literals and the generated \`Id<"table">\` types still catch a
|
|
369
|
+
* typo wherever the id is used.
|
|
370
|
+
*/
|
|
371
|
+
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
372
|
+
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
373
|
+
};
|
|
374
|
+
`};export{He as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./ir-DBSvhNa-.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as f}from"./shard-f7coQFS9.mjs";import"./shard-runtime-CyEbIjPA.mjs";import"./shared-DjUziztz.mjs";export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-CmcShAze.mjs";const f=s=>{const i=[];for(const r of s.getVariableStatements())if(r.isExported())for(const t of r.getDeclarations()){const e=t.getInitializer(),o=e&&a.isCallExpression(e)?n(e):void 0;o?.receiver&&i.push({name:t.getName(),receiver:o.receiver})}return i};export{f as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const S=t=>{if(!s(t))return"unreadable";const e=u(t),o=h(t,"schema.ts");s(o)&&e.push(o);const r=c("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(i(a))}catch{}return r.digest("hex")};export{S as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{runAdvisor as i}from"@lunora/advisor";const d=n=>[...n.indexes.map(e=>({fields:e.fields,kind:"index",name:e.name,unique:e.unique})),...n.searchIndexes.map(e=>({fields:[e.field,...e.filterFields??[]],kind:"search",name:e.name})),...n.rankIndexes.map(e=>({fields:[...e.sortBy.map(r=>r.field),...e.partitionBy??[]],kind:"rank",name:e.name})),...n.vectorIndexes.filter(e=>e.field!==void 0).map(e=>({fields:[e.field],kind:"vector",name:e.name})),...(n.geoIndexes??[]).map(e=>({fields:[e.field],kind:"geo",name:e.name}))],l=n=>{const e={};for(const[r,s]of Object.entries(n.shape))e[r]=s.kind==="optional"?s.inner?.kind??"optional":s.kind;return e},m=n=>({rlsMode:n.rlsMode,tables:n.tables.map(e=>({externallyManaged:e.externallyManaged??!1,externalSource:e.externalSource?{hasReconcile:e.externalSource.hasReconcile??!1,hasSoftDelete:e.externalSource.hasSoftDelete??!1,hasTenantBy:e.externalSource.hasTenantBy,mode:e.externalSource.mode,unanalyzable:e.externalSource.unanalyzable}:void 0,columnKinds:l(e),fields:Object.keys(e.shape),indexes:d(e),isPublic:e.isPublic??!1,name:e.name,relations:e.relations.map(r=>({field:r.field,kind:r.kind,name:r.name,onDelete:r.onDelete,references:r.references,table:r.table})),commitOrdered:e.commitOrdered,shardKind:typeof e.shardMode=="string"?e.shardMode:"shardBy",softDelete:e.softDelete,ttl:e.ttl}))}),c=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,table:e.table})),u=n=>n.map(e=>({exportName:e.exportName,file:`lunora/${e.filePath}.ts`,line:e.line,owner:e.owner})),f=n=>{const{argumentValidators:e,mutators:r,queries:s,schema:t,shapes:o,...a}=n;return{...a,argValidators:e,mutators:r===void 0?void 0:u(r),queries:s??[],schema:m(t),shapes:o===void 0?void 0:c(o)}},p=n=>i(f(n),{source:"static"}),v=n=>{if(n.length===0)return"";const e=`@lunora/codegen: ${String(n.length)} schema advisor finding${n.length===1?"":"s"}`,r=n.map(s=>` [${s.level}] ${s.name}: ${s.detail}`);return[e,...r].join(`
|
|
2
|
+
`)};export{v as formatAdvisories,p as lintSchema,f as toAdvisorContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as r}from"ts-morph";import{propertyKeyName as f,listLunoraSourceFiles as m,lunoraRelativePath as p,tablesAccessedIn as d}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{w as g,c as h}from"./classify-procedure-call-CmcShAze.mjs";const u=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return f(e)},k=e=>g(e,"use","mask"),x=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();if(t&&r.isStringLiteral(t)){const s=t.getLiteralText();if(s==="redact"||s==="hash")return s}}return"custom"},v=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const i of t.getProperties()){const n=u(i);if(n===void 0||!r.isPropertyAssignment(i))continue;const o=i.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=u(a);c!==void 0&&s.push({column:c,table:n})}}return s},P=e=>{const t=k(e);return{maskColumns:t.flatMap(s=>v(s)),usesMask:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),C=new Set(["delete","insert","patch","replace"]),M=(e,t)=>{if(!r.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const i=h(s);if(!i)return;const n=i.receiver?P(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:o,tablesWritten:a}=d(e,y,C);return{exportName:e.getName(),file:t,maskColumns:n.maskColumns,tablesRead:o,tablesWritten:a,usesMask:n.usesMask,visibility:i.visibility}},E=(e,t)=>{const s=[];for(const i of m(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i),o=p(t,i);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=M(c,o);l&&s.push(l)}}return s};export{u as a,E as d,k as m,x as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=s=>s.filter(o=>o.topic===void 0),e=(s,o)=>s.filter(i=>i.topic===o),a=s=>typeof s.shardMode=="object"&&s.shardMode.kind==="shardBy";export{a as i,t as p,e as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=l=>l.shardMode==="global"&&l.globalBackend!=="hyperdrive",o=l=>l.shardMode==="global"&&l.globalBackend==="hyperdrive";export{e as isD1GlobalTable,o as isHyperdriveGlobalTable};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
const g=/[^a-zA-Z0-9]+/gu,T=/([a-z0-9])([A-Z])/gu,p=t=>t.split(g).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),R=t=>t.replaceAll(T,"$1_$2").replaceAll(g,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),j=t=>t==="query"?"query":t==="action"?"action":"mutation",l=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>l(o,e+1));const n=t;if(n.format==="int64"&&(n.type===void 0||n.type==="string")||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(o=>l(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>l(n[o],e+1))},I=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),E=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),C=["$","{","'","$","'","}"].join(""),x=t=>E(t).split("$").join(C),z=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,b=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const n=t;return n.type==="null"||Array.isArray(n.type)&&n.type.includes("null")?!0:["anyOf","oneOf"].some(r=>{const o=n[r];return Array.isArray(o)&&o.some(s=>b(s,e+1))})},N=(t,e,n)=>e.length===0?n===0?[]:[t]:e.map(r=>({properties:{...t.properties,...r.properties},required:new Set([...t.required,...r.required])})),P=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const n=t.required;return[{properties:e,required:new Set(Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}]},m=(t,e,n)=>{const r=t[e];return Array.isArray(r)?r.flatMap(o=>A(o,n+1)):[]},A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[...P(n),...m(n,"allOf",e)],o={properties:Object.assign({},...r.map(a=>a.properties)),required:new Set(r.flatMap(a=>[...a.required]))},s=[...m(n,"anyOf",e),...m(n,"oneOf",e)];return N(o,s,r.length)},w=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const n=t,r=[n];for(const o of["anyOf","oneOf","allOf"]){const s=n[o];if(Array.isArray(s))for(const a of s)r.push(...w(a,e+1))}return r},y=(t,e,n,r=0)=>{if(r>f||t===null||typeof t!="object")return;const o=A(t),s=[...new Set(o.flatMap(a=>Object.keys(a.properties)))].toSorted((a,c)=>a.localeCompare(c));for(const a of s){const c=[...e,a],u=o.every(i=>i.required.has(a)),h=o.map(i=>i.properties[a]).filter(i=>i!==void 0);u?h.some(i=>b(i))&&n.nullable.push(c):n.optional.push(c);for(const i of h)y(i,c,n,r+1)}for(const a of w(t))for(const c of["additionalProperties","items"]){const u=a[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],n,r+1)}},k=(t,e)=>t.join("\0").localeCompare(e.join("\0")),q=t=>{const e={nullable:[],optional:[]};y(t,[],e);const n=r=>[...new Map(r.map(o=>[o.join("\0"),o])).values()].toSorted(k);return{nullable:n(e.nullable),optional:n(e.optional)}},$=t=>{const[e="",n=""]=t.name.split(":"),r=`${p(e)}${p(n)}`,o=t.params?.[0]?.schema,s=t.result?.schema;return{argsNullPaths:q(o),argsType:d(o)&&!l(o)?`${r}Args`:void 0,takesArgs:d(o),functionName:n,functionPath:t.name,namespace:e,resultType:d(s)&&!l(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:j(t["x-lunora-function-kind"])}},H=t=>{const e=new Map;for(const n of t.methods){const r=$(n),o=e.get(r.namespace);o===void 0?e.set(r.namespace,[r]):o.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((o,s)=>o.functionName.localeCompare(s.functionName)),name:n}))},U=t=>t.methods.flatMap(e=>{const n=$(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),L=/^[A-Za-z][A-Za-z0-9]*$/u,S=t=>L.test(t),D=t=>{const e=new Map;for(const n of t.methods){const r=p(n.functionName);if(!S(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const o=n.verb==="query"?[r,`Subscribe${r}`,`Watch${r}`]:[r];for(const s of o){const a=e.get(s);if(a!==void 0){const c=s.startsWith("Watch")?' (the Dart target emits a "watch" Stream member for every query)':"";throw new Error(`sdk: functions "${a}" and "${n.functionPath}" both generate "${s}"${c} — rename one so the generated methods stay distinct.`)}e.set(s,n.functionPath)}}},W=t=>{const e=new Map;for(const n of t){const r=p(n.name);if(!S(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const o=e.get(r);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),D(n)}},Z=(t,e,n)=>{for(const r of t){const o=new Map;for(const s of r.methods)for(const a of n(s)){const c=o.get(a);if(c!==void 0&&c!==s.functionPath)throw new Error(`sdk: functions "${c}" and "${s.functionPath}" both generate the ${e} member "${a}" — rename one so the generated methods stay distinct.`);o.set(a,s.functionPath)}}},M=t=>t.flatMap(e=>e.methods),F=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],_=/^\s*(?:#|\/\/|\/\*|\*)/u,v=t=>t.split(`
|
|
3
|
+
`).filter(e=>!_.test(e)).join(`
|
|
4
|
+
`),O=(t,e)=>new RegExp(String.raw`\b${e}\b`,"u").test(t),G=(t,e)=>{const n=v(e),r=o=>o!==void 0&&O(n,o)?o:void 0;return t.map(o=>({methods:o.methods.map(s=>({...s,argsType:r(s.argsType),resultType:r(s.resultType)})),name:o.name}))},B=t=>t.methods.filter(e=>l(e.params?.[0]?.schema)||l(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),V=(t,e)=>{const n=v(e);return[...new Set(M(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!O(n,r)))].toSorted((r,o)=>r.localeCompare(o))},K=t=>[...new Set(M(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{M as allMethods,z as argsChoice,Z as assertDistinctMembers,W as assertGeneratable,I as commentText,F as generatedHeaderLines,l as hasUnrepresentableWireType,d as isTypedSchema,x as kotlinLiteral,U as modelSources,q as nullPathsOf,$ as parseMethod,H as parseSpec,K as referencedModels,E as stringLiteral,p as toPascalCase,R as toSnakeCase,V as undeclaredModels,B as unrepresentableFunctions,j as verbForKind,G as withDeclaredModels};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=(r,s)=>`JSON.parse(${JSON.stringify(JSON.stringify(r))}) as ${s}`;export{a as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as x,realpathSync as P,lstatSync as A,statSync as O}from"node:fs";import{dirname as N,join as f,relative as w,sep as T,extname as m}from"node:path";import{Node as s,VariableDeclarationKind as F,SyntaxKind as S}from"ts-morph";import{diagnosticAt as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findProjectConfigFile as I}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const D=/\.ts$/u,u=(t,e)=>w(t,e).split(T).join("/").replace(D,""),C=new Set(["_generated","node_modules"]),_=(t,e,i)=>t==="schema.ts"&&e===i,j=t=>{try{return O(t)}catch{console.warn(`@lunora/codegen: skipping ${t} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},y=(t,e,i,n)=>{let o,r;try{o=x(t),r=P(t)}catch{return e}if(n.has(r))return e;n.add(r);for(const a of o){const l=f(t,a),c=j(l);c!==void 0&&(c.isDirectory()?C.has(a)||y(l,e,i,n):c.isFile()&&m(a)===".ts"&&!_(a,t,i)&&e.push(l))}return e},b=t=>y(t,[],t,new Set),z=["src/server","src/index.ts","src/worker.ts"],V=new Set([".ts",".tsx"]),h=(t,e=[])=>{let i;try{i=A(t)}catch{return e}if(i.isFile())return V.has(m(t))&&e.push(t),e;if(!i.isDirectory())return e;for(const n of x(t))n==="_generated"||n==="node_modules"||h(f(t,n),e);return e},K=t=>{const e=N(t),i=b(t).map(r=>({displayPath:u(t,r),filePath:r})),n=new Set(i.map(r=>r.filePath)),o=I(e);for(const r of[...z.flatMap(a=>h(f(e,a))),...o===void 0?[]:[o]])n.has(r)||(n.add(r),i.push({displayPath:u(e,r),filePath:r}));return i},v=(t,e,i)=>{const n=[];for(const{displayPath:o,filePath:r}of e){const a=t.getSourceFile(r)??t.addSourceFileAtPath(r);for(const l of a.getDescendantsOfKind(S.CallExpression)){const c=i(l,o);c!==void 0&&n.push(c)}}return n},J=(t,e,i)=>v(t,b(e).map(n=>({displayPath:u(e,n),filePath:n})),i),Z=(t,e,i)=>v(t,K(e),i),tt=t=>{for(const e of t.getAncestors()){if(s.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0)return e.getName();if(s.isExportAssignment(e)&&!e.isExportEquals())return"default"}return""},L=t=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isNumericLiteral(t))return t.getLiteralText();if(s.isComputedPropertyName(t)){const e=t.getExpression();if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText()}return t.getText()},k=t=>L(t.getNameNode()),et=t=>L(t.getPropertyNameNode()??t.getNameNode()),p=(t,e)=>t?.getProperties().find(i=>!s.isSpreadAssignment(i)&&k(i)===e),it=(t,e)=>{if(e){const r=t.getArguments()[0];return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0}const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=p(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const o=n.getInitializer();return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0},st=(t,e)=>{if(!t||!s.isObjectLiteralExpression(t))return;const i=p(t,e);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},M=t=>{const e=t?.getDeclarations().find(o=>s.isVariableDeclaration(o));if(e===void 0||!s.isVariableDeclaration(e))return;const i=e.getParent();if(!s.isVariableDeclarationList(i)||i.getDeclarationKind()!==F.Const)return;const n=i.getParent();return s.isVariableStatement(n)&&s.isSourceFile(n.getParent())?e.getInitializer():void 0},$=t=>M(t.getSymbol()),nt=t=>{if(!t)return;if(s.isObjectLiteralExpression(t))return t;if(!s.isIdentifier(t))return;const e=$(t);return e!==void 0&&s.isObjectLiteralExpression(e)?e:void 0},g=t=>s.isPropertyAccessExpression(t)&&t.getName()==="db"||s.isIdentifier(t)&&t.getText()==="db",q=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),rt=t=>{const e=t.getExpression();if(!s.isPropertyAccessExpression(e)||!q.has(e.getName()))return;const i=e.getExpression();if(g(i)){const n=t.getArguments()[0];return{options:t.getArguments()[1],table:n&&s.isStringLiteral(n)?n.getLiteralText():""}}if(s.isPropertyAccessExpression(i)){const n=i.getExpression();if(g(n))return{options:t.getArguments()[0],table:i.getName()}}},d=(t,e)=>{const i=t.getExpression();return!s.isPropertyAccessExpression(i)||!e.has(i.getName())?!1:g(i.getExpression())},E=t=>{const e=t.getArguments()[0];return e&&s.isStringLiteral(e)?e.getLiteralText():""},ot=(t,e,i)=>{const n=new Set,o=new Set;for(const r of t.getDescendantsOfKind(S.CallExpression))if(d(r,e)){const a=E(r);a!==""&&n.add(a)}else if(d(r,i)){const a=E(r);a!==""&&o.add(a)}return{tablesRead:[...n],tablesWritten:[...o]}},B=t=>{let e=t;for(;e&&(s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isParenthesizedExpression(e)||s.isNonNullExpression(e));)e=e.getExpression();return e},at=t=>{const e=B(t);return e&&s.isCallExpression(e)?e:void 0},ct=t=>{const e=t.getExportAssignment(o=>!o.isExportEquals());if(!e)return;const i=e.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},lt=t=>{const e=t.getArguments()[1];return e&&s.isStringLiteral(e)?e.getLiteralValue():""},ut=(t,e)=>{if(!s.isObjectLiteralExpression(t))return;const i=p(t,e);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},U=t=>{const e=t.getStatements(),[i]=e;if(e.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},gt=t=>{if(s.isObjectLiteralExpression(t))return t;if(s.isParenthesizedExpression(t)){const e=t.getExpression();return s.isObjectLiteralExpression(e)?e:void 0}return s.isBlock(t)?U(t):void 0},ft=t=>s.isIdentifier(t)&&t.getText()==="ctx",pt=t=>(e,i,n)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw R(e,`${t} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},W=new Set(["api","internal"]),dt=new Set(["run","runAction","runMutation","runQuery"]),Et=t=>{if(t===void 0||!s.isPropertyAccessExpression(t))return;const e=[];let i=t;for(;s.isPropertyAccessExpression(i);)e.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&W.has(i.getText())&&e.length>=2?e:void 0};export{dt as RUN_METHODS,D as TS_EXTENSION_RE,et as bindingKeyName,J as collectCallRows,Z as collectSecurityCallRows,ct as defaultExportExpression,tt as enclosingExportName,p as findObjectProperty,Et as functionReferenceSegments,it as handlerOf,ft as isContextIdentifier,g as isDatabaseAccessor,lt as limitNameOf,b as listLunoraSourceFiles,K as listSecurityScanFiles,u as lunoraRelativePath,gt as objectLiteralFromCallbackBody,nt as optionsObjectLiteral,st as propertyInitializer,k as propertyKeyName,L as propertyNameText,rt as readTargetOf,pt as stringPropertyFor,ut as stringPropertyOf,M as symbolConstInitializer,E as tableArgumentOf,ot as tablesAccessedIn,B as unwrapExpression,at as unwrapToCallExpression};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as E,readFileSync as y}from"node:fs";import{basename as P}from"node:path";import{createJiti as x}from"jiti";import{Project as S,Node as t}from"ts-morph";import{propertyKeyName as l}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{findProjectConfigFile as v}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as T}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const f=new Map,F=async i=>{const r=v(i);if(r===void 0)return{};let e;try{const n=E(r);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=f.get(r);if(s?.key===e)return s.value;const a=(async()=>{try{const u=(await x(r,{interopDefault:!1,moduleCache:!1}).import(r))?.default;return{config:u!==null&&typeof u=="object"?u:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return f.set(r,{key:e,value:a}),a},L=i=>{let e=i.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e)||t.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&t.isIdentifier(e))for(e=i.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e));)e=e.getExpression();return e!==void 0&&t.isObjectLiteralExpression(e)?e:void 0},c=(i,r)=>t.isPropertyAssignment(i)?i.getInitializer():r.getVariableDeclaration(l(i))?.getInitializer(),g=i=>{let r=i;for(;r!==void 0&&(t.isSatisfiesExpression(r)||t.isAsExpression(r)||t.isParenthesizedExpression(r));)r=r.getExpression();return r},h=(i,r)=>{const e=g(i);if(e===void 0||!t.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),a=s.filter(o=>t.isPropertyAssignment(o)&&!t.isComputedPropertyName(o.getNameNode())||t.isShorthandPropertyAssignment(o));if(a.length!==s.length)return{advisor:{unreadable:!0}};const n=a.find(o=>l(o)==="minSeverity");if(n===void 0)return{advisor:{}};const u=c(n,r);return u!==void 0&&t.isStringLiteral(u)?{advisor:{minSeverity:u.getLiteralValue()}}:{advisor:{unreadable:!0}}},A=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),b=(i,r)=>{const e=i.getProperty(r);if(e!==void 0)return(t.isPropertyAssignment(e)?e.getInitializer():void 0)??"unreadable"},m=(i,r)=>{const e=b(i,r);if(e!==void 0)return e!=="unreadable"&&(t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():!1},j=i=>{const r=b(i,"rpc");if(r!==void 0)return r!=="unreadable"&&t.isFalseLiteral(r)?!1:"unreadable"},N=i=>{const r=g(i);if(r===void 0||!t.isObjectLiteralExpression(r))return{services:{unreadable:!0}};const e={};for(const s of r.getProperties()){if(!t.isPropertyAssignment(s)||t.isComputedPropertyName(s.getNameNode()))return{services:{unreadable:!0}};const a=g(s.getInitializer());if(a===void 0||!t.isObjectLiteralExpression(a)||a.getProperties().some(d=>!t.isPropertyAssignment(d)))return{services:{unreadable:!0}};const n=m(a,"dir"),u=m(a,"entrypoint"),o=j(a);if(typeof n!="string"||u===!1||o==="unreadable")return{services:{unreadable:!0}};e[l(s)]={dir:n,...u===void 0?{}:{entrypoint:u},...o===void 0?{}:{rpc:o}}}return{services:{declared:e}}},w=(i,r)=>{if(t.isGetAccessorDeclaration(i)||t.isMethodDeclaration(i))return A.get(l(i))??{};if(!t.isPropertyAssignment(i)&&!t.isShorthandPropertyAssignment(i))return{};const e=l(i);if(e==="advisor")return h(c(i,r),r);if(e==="services")return N(c(i,r));if(e!=="target"&&e!=="remote")return{};const s=c(i,r);return s===void 0?{unreadable:!0}:e==="target"?t.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:t.isTrueLiteral(s)||t.isFalseLiteral(s)?{remote:s.getLiteralValue()}:t.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},V=i=>{const r=v(i);if(r===void 0)return{};let e;try{e=y(r,"utf8")}catch{return{unreadable:!0}}const a=new S({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(P(r),e,{overwrite:!0}),n=L(a);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(o=>t.isSpreadAssignment(o))){const o=d=>n.getProperties().some(p=>!t.isSpreadAssignment(p)&&l(p)===d);return{...o("advisor")?{advisor:{unreadable:!0}}:{},...o("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let u={};for(const o of n.getProperties())u={...u,...w(o,a)};return u};export{T as PROJECT_CONFIG_FILENAMES,v as findProjectConfigFile,F as loadProjectConfig,V as readProjectConfigLiterals};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=/(?:^|\/)_generated\/server(?:\.js)?$/u,s=new Set(["@lunora/server","lunorash/server"]),o=e=>s.has(e),n=e=>r.test(e),t=e=>o(e)||n(e),a=new Set(["@lunora/scheduler",...s]),E=e=>a.has(e);export{t as a,o as b,E as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as g}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{Node as n,VariableDeclarationKind as h}from"ts-morph";import{diagnosticAt as v}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{propertyKeyName as E}from"./listLunoraSourceFiles-CSlcBYlo.mjs";let f;const j=e=>{f=e},A=/^[A-Za-z_$][\w$]*$/u,p=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","serverDefault","unique"]),k=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":case"serverDefault":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},N=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","email","int","length","max","min","pattern","positive","url"]),I=new Set(["meta"]),L=new Set(["strip"]),l=new Set,g=new Set,S=e=>{const t=e.getSymbol();let r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(r!==void 0&&n.isShorthandPropertyAssignment(r)){const i=r.getValueSymbol();r=(i?.getAliasedSymbol()??i)?.getValueDeclaration()}if(!(r===void 0||!n.isVariableDeclaration(r)))return r.getInitializer()},T=e=>{const t=e.getParent();return!n.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===h.Const},u=e=>{if(n.isParenthesizedExpression(e)||n.isAsExpression(e)||n.isSatisfiesExpression(e))return u(e.getExpression());if(n.isObjectLiteralExpression(e))return e;if(n.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),i=r!==void 0&&n.isPropertyAssignment(r)?r.getInitializer():void 0;return i===void 0?void 0:u(i)}if(!n.isIdentifier(e)||l.has(e))return;const t=S(e);if(!(t===void 0||!T(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},w="v",D=e=>{if(n.isIdentifier(e))return!0;let t=e;for(;n.isCallExpression(t);){const r=t.getExpression();if(!n.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return n.isIdentifier(t)&&t.getText()===w},c=e=>{if(n.isIdentifier(e)&&!l.has(e)){const t=S(e);if(t!==void 0&&D(t)){l.add(e);try{return c(t)}finally{l.delete(e)}}}return n.isCallExpression(e)?P(e):{kind:"any",sourceText:e.getText()}},R=e=>{const t=u(e.getExpression());if(t===void 0||g.has(t))return{};g.add(t);try{return b(t)}finally{g.delete(t)}},b=e=>{const t={};for(const r of e.getProperties()){if(n.isSpreadAssignment(r)){Object.assign(t,R(r));continue}const i=n.isShorthandPropertyAssignment(r);if(!i&&!n.isPropertyAssignment(r))continue;const o=r.getNameNode();if(n.isComputedPropertyName(o))continue;const a=i?r.getNameNode():r.getInitializer();if(!a)continue;const s=E(r);if(!A.test(s))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(s)}`);t[s]=c(a)}return t},d=(e,t)=>e&&n.isExpression(e)?c(e):t,V=e=>e===void 0?"undefined":n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),O=e=>{const t=e&&f?f(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},x=(e,t,r)=>{if(N.has(e))return{kind:e};const[i,o]=t;switch(e){case"array":return{inner:d(i,{kind:"any"}),kind:"array"};case"from":return O(i);case"id":{if(!i||!n.isStringLiteral(i))throw v(i??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${i?i.getText():"no argument"}.`);return{kind:"id",tableName:i.getLiteralText()}}case"literal":return{kind:"literal",literalValue:V(i)};case"object":return i&&n.isObjectLiteralExpression(i)?{kind:"object",shape:b(i)}:{kind:"object",shape:{}};case"optional":return{inner:d(i,{kind:"any"}),kind:"optional"};case"record":return{keyType:d(i,{kind:"string"}),kind:"record",valueType:d(o,{kind:"any"})};case"storage":return i&&n.isStringLiteral(i)?{bucket:i.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>n.isExpression(a)).map(a=>c(a))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},M=e=>{const[t]=e;if(e.length!==1||t===void 0||!n.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},P=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),i=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||L.has(r)){const o=t.getExpression(),a=n.isExpression(o)?c(o):{kind:"any"};if(p.has(r))return k(a,r);if(!m.has(r))return a;const s=r==="max"&&a.kind==="string"?M(i):void 0;return s!==void 0?{...a,hasRefinement:!0,stringMaxLength:Math.min(a.stringMaxLength??s,s)}:{...a,hasRefinement:!0,unmodelledRefinement:!0}}return x(r,i,e)};export{c as a,b as p,u as r,j as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/\/index$/u,s=/[^\dA-Za-z]/gu,c=e=>e.replace(a,"").replaceAll(s,"_");export{c as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as E}from"./declared-output-Iaar469J.mjs";import{v as u}from"./shared-DjUziztz.mjs";const p=/import\("(?<spec>(?:\.\.?\/)*_generated\/[^"]+)"\)/gu,l=/^(?:\.\.?\/)*_generated\//u,i=/\.[A-Za-z]\w*$/u,R=t=>t.replaceAll(p,(e,r)=>{const o=r.replace(l,"./");return`import("${i.test(o)?o:`${o}.js`}")`}),_=/import\("(?<spec>[^"]+)"\)/gu,a="node_modules/",m=/^@types\//u,A=t=>t.replaceAll(_,(e,r)=>{const o=r.lastIndexOf(a);if(o===-1||o>0&&r[o-1]!=="/")return e;const s=r.slice(o+a.length);return s===""||m.test(s)?e:`import("${s}")`}),I=/import\("(?<spec>\.\.?\/[^"]+)"\)/gu,f=/^(?:\.\.?\/)+/u,g=t=>{const e=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r===".."&&e.length>0&&e.at(-1)!==".."){e.pop();continue}e.push(r)}return e.join("/")},S=(t,e)=>t.replaceAll(I,(r,o)=>{if(l.test(o.replace(f,"")))return r;const s=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",c=`../${g(`${s}/${o}`)}`;return`import("${i.test(c)?c:`${c}.js`}")`}),v=(t,e)=>R(S(A(t),e)),d=["client","do","errors","flags","observability","platform","ratelimit","runtime","server","values"],L=new RegExp(String.raw`import\("@lunora/(?<pkg>${d.join("|")})(?<subpath>/[^"]*)?"\)`,"gu"),T={flags:new Set(["/web"]),platform:new Set},M=(t,e)=>e?t.replaceAll(L,(r,o,s)=>{const n=T[o];return s&&n&&!n.has(s)?r:`import("lunorash/${o}${s??""}")`}):t,O=t=>["Doc","Id"].filter(e=>new RegExp(String.raw`(?<![.$\w])${e}<`,"u").test(t)),U=t=>E(t)?u(t.output):t.returnType;export{M as a,v as b,U as c,O as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as r,readFileSync as a}from"node:fs";import{join as d}from"node:path";const m=o=>{const n=d(o,"package.json");if(r(n))try{const s=JSON.parse(a(n,"utf8")),t=new Set;for(const c of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const e=s[c];if(e!==null&&typeof e=="object")for(const i of Object.keys(e))t.add(i)}return t}catch{return}};export{m as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as g,readFileSync as p}from"node:fs";import{isAbsolute as w,resolve as m,join as u}from"node:path";import{ts as h}from"ts-morph";import{readProjectConfigLiterals as E}from"./loadProjectConfig-nNIDOrlR.mjs";const f=/^[A-Za-z_$][\w$]*$/u,$=["wrangler.jsonc","wrangler.json"],b=t=>`SERVICE_${t.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/gu,"_").toUpperCase()}`,y=(t,e)=>{const r=$.map(n=>u(e,n)).find(n=>g(n));if(r===void 0){const n=g(u(e,"wrangler.toml"))?" (its wrangler.toml is not read — Lunora reads a service's config as JSON(C) only)":"";throw new Error(`@lunora/codegen: service "${t}" points at ${e}, which has no wrangler.jsonc / wrangler.json${n}`)}const o=h.parseConfigFileTextToJson(r,p(r,"utf8"));if(o.error!==void 0||typeof o.config!="object"||o.config===null)throw new Error(`@lunora/codegen: service "${t}": ${r} is not valid JSON(C)`);return{config:o.config,path:r}},v=(t,e)=>{const r=t.route??e.route,o=t.routes??e.routes;return!(r!==void 0||Array.isArray(o)&&o.length>0)&&(t.workers_dev??e.workers_dev)!==!1},S=(t,e,r)=>{if(!f.test(e))throw new Error(`@lunora/codegen: service key "${e}" must be an identifier — it becomes ctx.services.${e}`);if(r.entrypoint!==void 0&&!f.test(r.entrypoint))throw new Error(`@lunora/codegen: service "${e}": entrypoint "${r.entrypoint}" must name an exported WorkerEntrypoint class`);const o=w(r.dir)?r.dir:m(t,r.dir),{config:n,path:s}=y(e,o),{main:c,name:l}=n;if(typeof l!="string"||l==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no Worker "name"`);if(typeof c!="string"||c==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no "main" entry module`);const d=Object.entries(n.env??{}).map(([i,a])=>[i,a??{}]);return{binding:b(e),...r.entrypoint===void 0?{}:{entrypoint:r.entrypoint},envWorkers:Object.fromEntries(d.flatMap(([i,a])=>typeof a.name=="string"&&a.name!==""?[[i,a.name]]:[])),main:m(o,c),name:e,publicScopes:[...v(n,n)?[""]:[],...d.filter(([,i])=>v(i,n)).map(([i])=>i)],...r.entrypoint===void 0||r.rpc===!1?{}:{rpcEntrypoint:r.entrypoint},worker:l,wranglerPath:s}},j=t=>{const{services:e}=E(t);if(e?.unreadable===!0)throw new Error('@lunora/codegen: lunora.config `services` must be an inline object of { dir: "…", entrypoint?: "…", rpc?: false } literals — codegen reads it without running the file');const r=Object.entries(e?.declared??{}).map(([o,n])=>S(t,o,n)).toSorted((o,n)=>o.name.localeCompare(n.name));for(const[o,n]of r.entries()){const s=r.slice(o+1).find(c=>c.binding===n.binding);if(s!==void 0)throw new Error(`@lunora/codegen: services "${n.name}" and "${s.name}" both map to the binding ${n.binding} — rename one`)}return r},A=t=>{try{return{services:j(t)}}catch(e){return{error:e instanceof Error?e.message:String(e),services:[]}}};export{A as readServiceBindings,j as resolveServiceBindings};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=/[\w+/=-]{40,}/u,n=/[a-z]/u,E=/[A-Z]/u,_=/\d/u,c=/\b(?:[\da-f]{32,}|[\dA-F]{32,})\b/u,o=t=>{const e=s.exec(t)?.[0];return e===void 0?!1:n.test(e)&&E.test(e)&&_.test(e)},i=t=>c.test(t),r=/\b(?:sk|rk)_live_[\dA-Za-z]{20,}/u,a=/\bAKIA[\dA-Z]{16}\b/u,R=/\bgh[posru]_[\dA-Za-z]{36,}/u,d=/\bsk-[\dA-Za-z]{32,}/u,A=/\bxox[abprs]-[\dA-Za-z-]{10,}/u,k=/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----/u,S=[{kind:"stripe_live_key",test:t=>r.test(t)},{kind:"aws_access_key",test:t=>a.test(t)},{kind:"github_token",test:t=>R.test(t)},{kind:"openai_key",test:t=>d.test(t)},{kind:"slack_token",test:t=>A.test(t)},{kind:"private_key",test:t=>k.test(t)},{kind:"high_entropy",test:o},{kind:"hex_secret",test:i}],u=new Set(["hex_secret","high_entropy"]),h=new Set(["auth","bearer","credential","credentials","hmac","key","keys","passphrase","password","private","secret","secrets","signature","signing","token"]),p=/([a-z\d])([A-Z])/gu,T=/[^A-Za-z\d]+/u,I=t=>t.replaceAll(p,"$1 $2").split(T).filter(Boolean).map(e=>e.toLowerCase()),l=t=>t!==void 0&&I(t).some(e=>h.has(e)),K=t=>S.find(e=>e.test(t))?.kind,b=t=>u.has(t),g=t=>`${t.slice(0,4)}…(${String(t.length)} chars)`;export{S as SECRET_RULES,b as isHeuristicSecretKind,l as isSecretishName,g as redact,K as secretKindOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=e=>{try{return JSON.parse(e)}catch{const t=e.trim();return t.length>=2&&(t.startsWith("'")||t.startsWith('"'))&&t.at(-1)===t[0]?t.slice(1,-1):t}},n=e=>{const t={};return e.column!==void 0&&(t.column={defaultValue:e.column.hasDefault===!0?null:void 0,notNull:e.column.notNull,unique:e.column.unique}),e.inner!==void 0&&(t.inner=n(e.inner)),e.members!==void 0&&(t.members=e.members.map(a=>n(a))),e.shape!==void 0&&(t.shape=Object.fromEntries(Object.entries(e.shape).map(([a,l])=>[a,n(l)]))),e.tableName!==void 0&&(t.tableName=e.tableName),e.literalValue!==void 0&&(t.value=s(e.literalValue)),e.keyType!==void 0&&(t.keyValidator=n(e.keyType)),e.valueType!==void 0&&(t.valueValidator=n(e.valueType)),{_meta:t,kind:e.kind}},m=e=>({tables:Object.fromEntries(e.tables.map(a=>[a.name,{shape:Object.fromEntries(Object.entries(a.shape).map(([l,o])=>[l,n(o)]))}]))});export{m as schemaFromIr};
|