@lunora/cli 1.0.0-alpha.327 → 1.0.0-alpha.328
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/bin.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/dispatch.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +2 -2
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +1 -7
- package/dist/packem_chunks/handler19.mjs +7 -1
- package/dist/packem_chunks/handler20.mjs +1 -1
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler22.mjs +1 -3
- package/dist/packem_chunks/handler23.mjs +3 -3
- package/dist/packem_chunks/handler24.mjs +3 -1
- package/dist/packem_chunks/handler25.mjs +1 -2
- package/dist/packem_chunks/handler26.mjs +2 -99
- package/dist/packem_chunks/handler27.mjs +99 -10
- package/dist/packem_chunks/handler28.mjs +10 -0
- package/dist/packem_chunks/handler7.mjs +1 -1
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/runDeployCommand.mjs +1 -1
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/{COMMANDS-CP6waB2N.mjs → COMMANDS-Dmgapq6c.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CLEcoVhc.mjs +1 -0
- package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
- package/dist/packem_shared/{cli-BzOfNDAr.mjs → cli-NU4LQDgm.mjs} +2 -2
- package/dist/packem_shared/{import-D7qdpSmJ.mjs → import-CQYRW8GG.mjs} +10 -10
- package/dist/packem_shared/runExportCommand-DgsCoi9w.mjs +5 -0
- package/dist/packem_shared/runMigrateGenerateCommand-yxTJ8CAg.mjs +11 -0
- package/package.json +9 -9
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-BgMPHEoe.mjs +0 -1
- package/dist/packem_shared/admin-url-BhF5ufg1.mjs +0 -1
- package/dist/packem_shared/runExportCommand-DxsJHYZt.mjs +0 -5
- package/dist/packem_shared/runMigrateGenerateCommand-CDHswpMU.mjs +0 -11
|
@@ -1,99 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
|
|
3
|
-
Install it in your project:
|
|
4
|
-
|
|
5
|
-
${j(n,t)}`)}return r(e)},G=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},J=e=>{try{const t=new URL(e).pathname.replace(K,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},Q=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=T("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,p)=>(await u.query(l,[...p])).rows,schema:n??"public"}}const a=T("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??J(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},b=new Set(["_creationTime","_id"]),W={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},X={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,t)=>{const r=(t==="postgres"?W:X)[e.dataType],s=e.references===void 0?r:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},x=/^[A-Z_$][\w$]*$/i,z=/[^\dA-Z]+(.)?/gi,Z=/^\d+/,V=/[^\w-]/g,ee=/[\u003C\u003E\u002F\u2028\u2029]/g,ne={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(ee,t=>ne[t]??t),S=e=>x.test(e)?e:f(e),te=e=>x.test(e)?`.${e}`:`[${f(e)}]`,C=e=>e.replaceAll("*/",String.raw`*\/`),re=e=>{const t=e.replaceAll(V,"_");return t===""?"table":t},ae=e=>{const n=e.replaceAll(z,(r,s)=>s?.toUpperCase()??"").replace(Z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},D=e=>e.columns.filter(t=>!b.has(t.name)),se=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!b.has(n))},k=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),oe=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(b.has(o.name)){r.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=k(o,n,e.name,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${C(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!b.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!b.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
|
|
6
|
-
${s.join(`
|
|
7
|
-
`)}
|
|
8
|
-
})
|
|
9
|
-
${a.join(`
|
|
10
|
-
`)},`},ie=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>oe(a,e.dialect,r,n)).join(`
|
|
11
|
-
`);return`/**
|
|
12
|
-
* Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
|
|
13
|
-
*
|
|
14
|
-
* This file is a STARTING POINT, not a build artifact — it is written once and is
|
|
15
|
-
* yours to edit. Review it before shipping: column types are mapped
|
|
16
|
-
* conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
|
|
17
|
-
* its rows live in the external database. Re-running \`lunora introspect\` will not
|
|
18
|
-
* overwrite it unless you pass \`--force\`.
|
|
19
|
-
*/
|
|
20
|
-
import { defineSchema, defineTable, v } from "${t.serverImport}";
|
|
21
|
-
|
|
22
|
-
export default defineSchema({
|
|
23
|
-
${s}
|
|
24
|
-
});
|
|
25
|
-
`},ce=(e,t,n,r=new Set([e.name]),s=[])=>{const a=ae(e.name),o=se(e),i=new Map(D(e).map(l=>[l.name,l])),c=o.map(l=>{const p=i.get(l);if(p===void 0)return;const v=k({...p,nullable:!1},r,e.name,[]),{expression:d,known:A}=w(v,t);return!A&&v.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${p.dataType}\`).`),` ${S(l)}: ${d},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${te(e.name)}`;return`/**
|
|
26
|
-
* Generated by \`lunora introspect\` for the \`${C(e.name)}\` table — a
|
|
27
|
-
* starting point you own and edit.
|
|
28
|
-
*
|
|
29
|
-
* Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
|
|
30
|
-
* this data should be public, and gate them with your auth/RLS middleware first —
|
|
31
|
-
* \`introspect\` cannot know who is allowed to read this table.
|
|
32
|
-
*/
|
|
33
|
-
import { defineListArgs, v } from "${n.serverImport}";
|
|
34
|
-
|
|
35
|
-
import type { Doc } from "./_generated/dataModel";
|
|
36
|
-
import { c } from "./_generated/server";
|
|
37
|
-
|
|
38
|
-
const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
|
|
39
|
-
// Only index-backed columns are published as filterable, so a caller cannot
|
|
40
|
-
// reach a column you did not choose to expose. Note that \`contains\` and the
|
|
41
|
-
// negative operators still scan — narrow this list, and review it, before
|
|
42
|
-
// adding \`.expose({ rest: true })\`.
|
|
43
|
-
filter: {
|
|
44
|
-
${c.join(`
|
|
45
|
-
`)}
|
|
46
|
-
},
|
|
47
|
-
orderBy: [${m}],
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
|
|
51
|
-
|
|
52
|
-
export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
|
|
53
|
-
`},me=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:ie(e,t,n),path:"schema.ts"}];if(t.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(D(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=re(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:ce(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},y=/^[A-Z_$][\w$]*$/i,le=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,ue=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(b.has(a.name)||s.has(a.name))continue;if(!y.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:le(i)}),!a.nullable&&t!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return r},de=(e,t,n)=>{const r=[],s=new Set(t?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!b.has(i));if(!(s.has(a.name)||o.length===0)){if(!y.test(a.name)||!o.every(i=>y.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},pe=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!y.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...ue(i,c,{dialect:n,present:o,warnings:s}),...de(i,c,s))}return{edits:r,warnings:s}},ge=(e,t,n)=>{const r=P(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=pe(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=H(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},fe=`
|
|
54
|
-
SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
|
|
55
|
-
FROM information_schema.columns c
|
|
56
|
-
JOIN information_schema.tables t
|
|
57
|
-
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
58
|
-
WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
|
|
59
|
-
ORDER BY c.table_name, c.ordinal_position`,ve=`
|
|
60
|
-
SELECT tc.table_name, kcu.column_name
|
|
61
|
-
FROM information_schema.table_constraints tc
|
|
62
|
-
JOIN information_schema.key_column_usage kcu
|
|
63
|
-
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
64
|
-
WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
|
|
65
|
-
ORDER BY tc.table_name, kcu.ordinal_position`,he=`
|
|
66
|
-
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
|
|
67
|
-
FROM information_schema.table_constraints tc
|
|
68
|
-
JOIN information_schema.key_column_usage kcu
|
|
69
|
-
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
70
|
-
JOIN information_schema.constraint_column_usage ccu
|
|
71
|
-
ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
|
|
72
|
-
WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,be=`
|
|
73
|
-
SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
74
|
-
FROM pg_class t
|
|
75
|
-
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
76
|
-
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
77
|
-
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
78
|
-
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
79
|
-
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
80
|
-
WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
|
|
81
|
-
ORDER BY t.relname, i.relname, k.ord`,Ee=`
|
|
82
|
-
SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
|
|
83
|
-
FROM information_schema.COLUMNS c
|
|
84
|
-
JOIN information_schema.TABLES t
|
|
85
|
-
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
|
|
86
|
-
WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
|
|
87
|
-
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,_e=`
|
|
88
|
-
SELECT TABLE_NAME, COLUMN_NAME
|
|
89
|
-
FROM information_schema.KEY_COLUMN_USAGE
|
|
90
|
-
WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
|
|
91
|
-
ORDER BY TABLE_NAME, ORDINAL_POSITION`,ye=`
|
|
92
|
-
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
|
|
93
|
-
FROM information_schema.KEY_COLUMN_USAGE
|
|
94
|
-
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Ae=`
|
|
95
|
-
SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
|
|
96
|
-
FROM information_schema.STATISTICS
|
|
97
|
-
WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
|
|
98
|
-
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,_=e=>{const t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Se=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Ne=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},we=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n]),e(r?be:Ae,[n])]),c=_(a),m=_(o),u=_(i),l=[];for(const[p,v]of _(s)){const d=new Map((m.get(p)??[]).map(h=>[g(h,"column_name"),{column:g(h,"foreign_column"),table:g(h,"foreign_table")}])),A=v.map(h=>{const R=g(h,"column_name"),$=d.get(R);return{...Se(h,t),name:R,nullable:g(h,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Ne(u.get(p)??[],t),name:p,primaryKey:(c.get(p)??[]).map(h=>g(h,"column_name"))})}return l.sort((p,v)=>p.name.localeCompare(v.name)),{dialect:t,tables:l}},Re=e=>{try{const t=JSON.parse(I(E(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},$e=async(e,t,n)=>{const r=E(t,e.path);return O(r)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
|
|
99
|
-
`).length)} lines)`),!1):(await U(t,{recursive:!0}),await M(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},Le=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Te=async(e,t,n,r)=>{const s=ge(I(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await M(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Oe=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url==="")){const d="`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL.";return e.logger.error(d),{code:L.USAGE,error:d,written:[]}}const n=e.connection===void 0?G(e.url):e.dialect??"postgres",r=e.connection??await Q(e.url,n,e.schema,t);let s;try{s=await we(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=Le(s,e);if(a.length===0){const d="no tables found to introspect — check --schema and --tables.";return e.logger.error(d),{code:L.NOT_FOUND,error:d,written:[]}}const{files:o,warnings:i}=me({...s,tables:a},{procedures:e.procedures!==!1,serverImport:Re(t)}),c=E(t,"lunora"),m=[],u=E(c,"schema.ts"),l=O(u)&&e.force!==!0,p=l?o.filter(d=>d.path!=="schema.ts"):o;l&&await Te(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const d of p)await $e(d,c,e)&&m.push(d.path);for(const d of i)e.logger.warn(d);e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`);const v=a.map(d=>d.name);return{code:0,dialect:n,tables:v,written:m}},Fe=B(async({cwd:e,format:t,logger:n,options:r})=>{const s=await Oe({cwd:e,dryRun:r.dryRun===!0,force:r.force===!0,format:t,logger:n,procedures:r.procedures!==!1,schema:r.schema,tables:r.tables===void 0?void 0:r.tables.split(",").map(a=>a.trim()),url:r.url??process.env.DATABASE_URL});return{code:s.code,data:s.dialect===void 0?void 0:{dialect:s.dialect,dryRun:r.dryRun===!0,tables:s.tables??[],written:s.written},error:s.error}});export{Fe as execute,Re as resolveServerImport,Oe as runIntrospectCommand};
|
|
1
|
+
import{readLinkedProject as v,resolveDeployDriver as h,toolchainExecArgs as b,detectPackageManager as y}from"@lunora/config";import{d as w}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{defaultSpawner as L}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{createR2Sql as S}from"@lunora/bindings/r2sql";import{createPipelineLogReader as _}from"@lunora/runtime";const E=["trace","debug","log","info","warn","error","fatal"],T=new Set(E),f=/^\d+$/,u=(e,t)=>{if(e===void 0)return;const a=e.trim();if(f.test(a))return Number(a);const n=Date.parse(a);if(Number.isNaN(n))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return n},C=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),I=e=>{const t=e.trim();if(f.test(t))return{ts:Number(t)};let a;try{a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:n}=a,r=a.seen,s=Array.isArray(r)?r.filter(i=>typeof i=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:n}:{ts:n}},m=(e,t)=>{if(e!==void 0){if(!T.has(e))throw new TypeError(`logs: invalid ${t} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},p=e=>{const t={},a=u(e.since,"--since");a!==void 0&&(t.sinceTs=a);const n=u(e.until,"--until");n!==void 0&&(t.untilTs=n);const r=m(e.level,"--level");r!==void 0&&(t.level=r);const s=m(e.minLevel,"--min-level");if(s!==void 0&&(t.minLevel=s),e.functionPrefix!==void 0&&(t.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(t.traceId=e.traceId),e.shardKey!==void 0&&(t.shardKey=e.shardKey),e.userId!==void 0&&(t.userId=e.userId),e.limit!==void 0){const i=Number(e.limit);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);t.limit=i}return e.cursor!==void 0&&(t.cursor=I(e.cursor)),t},R=e=>{const t=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${t} ${a} ${e.functionPath} ${e.message}`},$=async e=>{const t=e.environment??process.env,a=t.R2_SQL_ACCOUNT_ID,n=t.R2_SQL_TOKEN,r=t.R2_SQL_BUCKET,s=[];if((a===void 0||a.length===0)&&s.push("R2_SQL_ACCOUNT_ID"),(n===void 0||n.length===0)&&s.push("R2_SQL_TOKEN"),(r===void 0||r.length===0)&&s.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&s.push("--table"),s.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${s.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:d.USAGE,error:"not configured"};let i;try{i=p(e)}catch(c){return e.logger.error(c instanceof Error?c.message:String(c)),{code:d.USAGE,error:"invalid option"}}const o=S({accountId:a,apiToken:n,bucket:r,fetch:e.fetch}),l=await _(o,{namespace:e.namespace,table:e.table}).query(i);for(const c of l.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(c):R(c)}
|
|
2
|
+
`);return l.rows.length===0?e.logger.info("logs --durable: no matching log records"):l.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${C(l.nextCursor)} for the next page`),{code:0,rows:l.rows}},N=async e=>{const t=e.cwd??process.cwd(),a=e.env??v(t)?.env,n=h(e.target),r=n.toolchain?.tail;if(r===void 0){const c=`logs: deploy target "${n.id}" has no log tail`;return e.logger.error(c),{code:d.USAGE,descriptor:void 0,error:c}}const s=r({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),i=b(y(t),s),o={args:i.args,command:i.command,cwd:t};return e.logger.info(`tailing logs via ${o.command} ${o.args.join(" ")}`),{code:(await(e.spawner??L)(o)).code,delegated:!0,descriptor:o}},U=w(async({argument:e,cwd:t,format:a,logger:n,options:r})=>{if(r.durable===!0){const s=await $({cursor:r.cursor,functionPrefix:r.functionPrefix,level:r.level,limit:r.limit,logger:n,minLevel:r.minLevel,namespace:r.namespace,ndjson:r.ndjson===!0,shardKey:r.shardKey,since:r.since,table:r.table,traceId:r.traceId,until:r.until,userId:r.userId});return{...s,...s.rows===void 0?{}:{delegated:!0}}}return N({cwd:t,env:r.env,format:a,logger:n,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]})});export{U as execute,N as runLogsCommand};
|
|
@@ -1,10 +1,99 @@
|
|
|
1
|
-
import{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
${
|
|
6
|
-
|
|
7
|
-
`)}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`)
|
|
1
|
+
import{existsSync as O,readFileSync as I}from"node:fs";import{writeFile as M,mkdir as U}from"node:fs/promises";import{join as E}from"@visulima/path";import{d as B}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{createRequire as F}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as Y,detectPackageManager as q,parseSchema as P,applyAdditiveEdit as H}from"@lunora/config";const K=/^\//,j=(e,t)=>{try{const{args:n,command:r}=Y(q(e),[t],{dev:!0});return`${r} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${t}`}},T=(e,t,n)=>{const r=F(E(n,"noop.cjs"));try{r.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${t}\` driver to read this database, and it isn't installed.
|
|
2
|
+
|
|
3
|
+
Install it in your project:
|
|
4
|
+
|
|
5
|
+
${j(n,t)}`)}return r(e)},G=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},J=e=>{try{const t=new URL(e).pathname.replace(K,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},Q=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=T("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,p)=>(await u.query(l,[...p])).rows,schema:n??"public"}}const a=T("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??J(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},b=new Set(["_creationTime","_id"]),W={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},X={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,t)=>{const r=(t==="postgres"?W:X)[e.dataType],s=e.references===void 0?r:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},x=/^[A-Z_$][\w$]*$/i,z=/[^\dA-Z]+(.)?/gi,Z=/^\d+/,V=/[^\w-]/g,ee=/[\u003C\u003E\u002F\u2028\u2029]/g,ne={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(ee,t=>ne[t]??t),S=e=>x.test(e)?e:f(e),te=e=>x.test(e)?`.${e}`:`[${f(e)}]`,C=e=>e.replaceAll("*/",String.raw`*\/`),re=e=>{const t=e.replaceAll(V,"_");return t===""?"table":t},ae=e=>{const n=e.replaceAll(z,(r,s)=>s?.toUpperCase()??"").replace(Z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},D=e=>e.columns.filter(t=>!b.has(t.name)),se=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!b.has(n))},k=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),oe=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(b.has(o.name)){r.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=k(o,n,e.name,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${C(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!b.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!b.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
|
|
6
|
+
${s.join(`
|
|
7
|
+
`)}
|
|
8
|
+
})
|
|
9
|
+
${a.join(`
|
|
10
|
+
`)},`},ie=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>oe(a,e.dialect,r,n)).join(`
|
|
11
|
+
`);return`/**
|
|
12
|
+
* Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
|
|
13
|
+
*
|
|
14
|
+
* This file is a STARTING POINT, not a build artifact — it is written once and is
|
|
15
|
+
* yours to edit. Review it before shipping: column types are mapped
|
|
16
|
+
* conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
|
|
17
|
+
* its rows live in the external database. Re-running \`lunora introspect\` will not
|
|
18
|
+
* overwrite it unless you pass \`--force\`.
|
|
19
|
+
*/
|
|
20
|
+
import { defineSchema, defineTable, v } from "${t.serverImport}";
|
|
21
|
+
|
|
22
|
+
export default defineSchema({
|
|
23
|
+
${s}
|
|
24
|
+
});
|
|
25
|
+
`},ce=(e,t,n,r=new Set([e.name]),s=[])=>{const a=ae(e.name),o=se(e),i=new Map(D(e).map(l=>[l.name,l])),c=o.map(l=>{const p=i.get(l);if(p===void 0)return;const v=k({...p,nullable:!1},r,e.name,[]),{expression:d,known:A}=w(v,t);return!A&&v.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${p.dataType}\`).`),` ${S(l)}: ${d},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${te(e.name)}`;return`/**
|
|
26
|
+
* Generated by \`lunora introspect\` for the \`${C(e.name)}\` table — a
|
|
27
|
+
* starting point you own and edit.
|
|
28
|
+
*
|
|
29
|
+
* Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
|
|
30
|
+
* this data should be public, and gate them with your auth/RLS middleware first —
|
|
31
|
+
* \`introspect\` cannot know who is allowed to read this table.
|
|
32
|
+
*/
|
|
33
|
+
import { defineListArgs, v } from "${n.serverImport}";
|
|
34
|
+
|
|
35
|
+
import type { Doc } from "./_generated/dataModel";
|
|
36
|
+
import { c } from "./_generated/server";
|
|
37
|
+
|
|
38
|
+
const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
|
|
39
|
+
// Only index-backed columns are published as filterable, so a caller cannot
|
|
40
|
+
// reach a column you did not choose to expose. Note that \`contains\` and the
|
|
41
|
+
// negative operators still scan — narrow this list, and review it, before
|
|
42
|
+
// adding \`.expose({ rest: true })\`.
|
|
43
|
+
filter: {
|
|
44
|
+
${c.join(`
|
|
45
|
+
`)}
|
|
46
|
+
},
|
|
47
|
+
orderBy: [${m}],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
|
|
51
|
+
|
|
52
|
+
export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
|
|
53
|
+
`},me=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:ie(e,t,n),path:"schema.ts"}];if(t.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(D(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=re(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:ce(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},y=/^[A-Z_$][\w$]*$/i,le=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,ue=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(b.has(a.name)||s.has(a.name))continue;if(!y.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:le(i)}),!a.nullable&&t!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return r},de=(e,t,n)=>{const r=[],s=new Set(t?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!b.has(i));if(!(s.has(a.name)||o.length===0)){if(!y.test(a.name)||!o.every(i=>y.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},pe=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!y.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...ue(i,c,{dialect:n,present:o,warnings:s}),...de(i,c,s))}return{edits:r,warnings:s}},ge=(e,t,n)=>{const r=P(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=pe(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=H(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},fe=`
|
|
54
|
+
SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
|
|
55
|
+
FROM information_schema.columns c
|
|
56
|
+
JOIN information_schema.tables t
|
|
57
|
+
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
58
|
+
WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
|
|
59
|
+
ORDER BY c.table_name, c.ordinal_position`,ve=`
|
|
60
|
+
SELECT tc.table_name, kcu.column_name
|
|
61
|
+
FROM information_schema.table_constraints tc
|
|
62
|
+
JOIN information_schema.key_column_usage kcu
|
|
63
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
64
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
|
|
65
|
+
ORDER BY tc.table_name, kcu.ordinal_position`,he=`
|
|
66
|
+
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
|
|
67
|
+
FROM information_schema.table_constraints tc
|
|
68
|
+
JOIN information_schema.key_column_usage kcu
|
|
69
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
70
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
71
|
+
ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
|
|
72
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,be=`
|
|
73
|
+
SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
74
|
+
FROM pg_class t
|
|
75
|
+
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
76
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
77
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
78
|
+
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
79
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
80
|
+
WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
|
|
81
|
+
ORDER BY t.relname, i.relname, k.ord`,Ee=`
|
|
82
|
+
SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
|
|
83
|
+
FROM information_schema.COLUMNS c
|
|
84
|
+
JOIN information_schema.TABLES t
|
|
85
|
+
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
|
|
86
|
+
WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
|
|
87
|
+
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,_e=`
|
|
88
|
+
SELECT TABLE_NAME, COLUMN_NAME
|
|
89
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
90
|
+
WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
|
|
91
|
+
ORDER BY TABLE_NAME, ORDINAL_POSITION`,ye=`
|
|
92
|
+
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
|
|
93
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
94
|
+
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Ae=`
|
|
95
|
+
SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
|
|
96
|
+
FROM information_schema.STATISTICS
|
|
97
|
+
WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
|
|
98
|
+
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,_=e=>{const t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Se=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Ne=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},we=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n]),e(r?be:Ae,[n])]),c=_(a),m=_(o),u=_(i),l=[];for(const[p,v]of _(s)){const d=new Map((m.get(p)??[]).map(h=>[g(h,"column_name"),{column:g(h,"foreign_column"),table:g(h,"foreign_table")}])),A=v.map(h=>{const R=g(h,"column_name"),$=d.get(R);return{...Se(h,t),name:R,nullable:g(h,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Ne(u.get(p)??[],t),name:p,primaryKey:(c.get(p)??[]).map(h=>g(h,"column_name"))})}return l.sort((p,v)=>p.name.localeCompare(v.name)),{dialect:t,tables:l}},Re=e=>{try{const t=JSON.parse(I(E(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},$e=async(e,t,n)=>{const r=E(t,e.path);return O(r)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
|
|
99
|
+
`).length)} lines)`),!1):(await U(t,{recursive:!0}),await M(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},Le=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Te=async(e,t,n,r)=>{const s=ge(I(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await M(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Oe=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url==="")){const d="`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL.";return e.logger.error(d),{code:L.USAGE,error:d,written:[]}}const n=e.connection===void 0?G(e.url):e.dialect??"postgres",r=e.connection??await Q(e.url,n,e.schema,t);let s;try{s=await we(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=Le(s,e);if(a.length===0){const d="no tables found to introspect — check --schema and --tables.";return e.logger.error(d),{code:L.NOT_FOUND,error:d,written:[]}}const{files:o,warnings:i}=me({...s,tables:a},{procedures:e.procedures!==!1,serverImport:Re(t)}),c=E(t,"lunora"),m=[],u=E(c,"schema.ts"),l=O(u)&&e.force!==!0,p=l?o.filter(d=>d.path!=="schema.ts"):o;l&&await Te(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const d of p)await $e(d,c,e)&&m.push(d.path);for(const d of i)e.logger.warn(d);e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`);const v=a.map(d=>d.name);return{code:0,dialect:n,tables:v,written:m}},Fe=B(async({cwd:e,format:t,logger:n,options:r})=>{const s=await Oe({cwd:e,dryRun:r.dryRun===!0,force:r.force===!0,format:t,logger:n,procedures:r.procedures!==!1,schema:r.schema,tables:r.tables===void 0?void 0:r.tables.split(",").map(a=>a.trim()),url:r.url??process.env.DATABASE_URL});return{code:s.code,data:s.dialect===void 0?void 0:{dialect:s.dialect,dryRun:r.dryRun===!0,tables:s.tables??[],written:s.written},error:s.error}});export{Fe as execute,Re as resolveServerImport,Oe as runIntrospectCommand};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{V as R}from"../packem_shared/cli-NU4LQDgm.mjs";import{d as G}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
|
|
2
|
+
`),{action:"created",path:o};const{errors:c,value:i}=k(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const p=i[n];if(p!==void 0&&!g(p))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(E(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const $=U(l,o,n,a,r);return $===void 0?{action:"updated",path:o}:{action:"invalid",error:$,path:o}},we=e=>{const{key:r,name:t,path:n}=e;if(!f(n))return{action:"absent",path:n};let a;try{a=h(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=k(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(E(l,r,t)===void 0)return{action:"absent",path:n};const c=U(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},ke=["global","project"],u=(e,r)=>{const t=Z(r,e);return t.length>0&&!t.startsWith("..")?t:e},Ee=(e,r)=>{const t=e.paths(r);return ke.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},$e=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},je=e=>v.filter(r=>Object.values(r.paths(e)).some(t=>f(t))),A=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=he(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${x.join(", ")}.`);return}a.push(l)}return a},Oe=e=>e.client.format==="json",Ce="https://lunora.sh/mcp",N="lunora-docs",D="lunora",_e=e=>f(s(e,"lunora"))&&X(e)!==void 0,xe=e=>{const{args:r,command:t}=ne(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Me=e=>({transport:"http",url:e}),Le=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),T=(e,r,t)=>$e(e,Le(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ue=(e,r,t)=>{const n=T(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=u(a,t.cwd);return t.force!==!0&&be({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label} → ${i}
|
|
3
|
+
${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=Se({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=u(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},Ae=(e,r,t)=>{const n=T(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${u(n,t.cwd)}
|
|
4
|
+
|
|
5
|
+
${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},Ne=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:N,preferredScope:"global",spec:Me(e.docsUrl??Ce)}),e.docsOnly!==!0&&_e(e.cwd)&&r.push({allowScopeFallback:!1,name:D,preferredScope:"project",spec:xe(te(e.cwd))}),r},De=e=>{const r=e.home??w(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of v){const a=n.paths({home:r,platform:t,projectRoot:e.cwd}),o=l=>{const c=a[l];return c===void 0?"—":u(c,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${o("project").padEnd(30)} global: ${o("global")}`)}return{code:0,written:[]}},Te=e=>e.docsOnly===!0&&e.localOnly===!0?"`--docs-only` and `--local-only` are mutually exclusive — pass at most one.":"`--local-only` was set but this directory is not a Lunora project (no `lunora/` directory and wrangler config).",Pe=(e,r,t)=>{const n=[];for(const a of e)for(const o of r){const l=a.format==="json"?Ue(a,o,t):Ae(a,o,t);l!==void 0&&n.push({action:l.action,client:a.id,path:l.path,server:o.name})}return n},Fe=e=>{const r=e.home??w(),t=e.platform??process.platform,n=A(e.clients,()=>je({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:d.USAGE,written:[]};if(n.length===0)return e.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${x.join(", ")}.`),{code:d.NOT_FOUND,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(l=>l.label).join(", ")}.`);const a=Ne(e);if(a.length===0)return e.logger.error(`mcp install: nothing to install — ${Te(e)}`),{code:d.USAGE,written:[]};const o=Pe(n,a,{...e,home:r,platform:t});return o.some(l=>l.action==="created"||l.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:o.some(l=>l.action==="invalid")?1:0,written:o}},P=100,F=1e3,j=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ie=e=>({content:[{text:e,type:"text"}]}),Re=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?P:Math.min(F,Math.max(1,Math.floor(r)))},O=(e,r)=>{if(r===void 0)return;const t=y(e,oe);return ce(t,y(e,r))?y(e,r):void 0},Ge=(e,r)=>{const t=h(e,"utf8").split(`
|
|
6
|
+
`);return t.at(-1)===""&&t.pop(),t.slice(-r).join(`
|
|
7
|
+
`)},Je=e=>[{definition:{description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const r=S(e);return j(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:O(e,r.logFile),mode:r.mode,pid:r.pid,running:!0,startedAt:r.startedAt,studioUrl:r.studioUrl,url:r.url})}},{definition:{description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(P)}, max ${String(F)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=S(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=O(e,t.logFile);if(n===void 0||!f(n))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const a=Re(r.lines),o=Ge(n,a);return Ie(o.length===0?"(the dev server log is empty)":o)}}],We=new Set(["127.0.0.1","::1","localhost"]),I=e=>{try{const{hostname:r}=new URL(e);return We.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},C=e=>{const r=e.url??S(e.cwd)?.url;if(r===void 0||r.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:r};if(!I(r))return{url:r};const t=ae(e.cwd);return t===void 0||t.length===0?{url:r}:{token:t,url:r}},Ve=async e=>{await new Promise(r=>{const t=()=>{r()};e.onclose=t,process.stdin.once("close",t),process.stdin.once("end",t)})},ze=e=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url}
|
|
8
|
+
`;const t=!I(e.url)?"the project's admin token was NOT sent to this non-local url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${t})
|
|
9
|
+
`},He=async(e,r=le)=>{const t=e.writeError??(o=>{process.stderr.write(o)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>C(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Je(e.cwd),version:e.version})}catch(o){const l=o instanceof Error?o.message:String(o);return t(`lunora mcp serve: failed to start — ${l}
|
|
10
|
+
`),{code:1,deployment:void 0}}const a=C(e);return t(ze(a)),await Ve(n),{code:0,deployment:a}},Ke=e=>{const r=[];return e.localOnly!==!0&&r.push(N),e.docsOnly!==!0&&r.push(D),r},qe=(e,r,t,n)=>{const a=we({key:e.key,name:r,path:t}),o=u(t,n.cwd);return a.action==="removed"?n.logger.success(`${e.label}: removed "${r}" from ${o}.`):a.action==="invalid"&&n.logger.error(`${e.label}: ${o} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:t}},Xe=(e,r,t,n)=>{const a=L({key:e.key,name:r,path:t}),o=u(t,n.cwd);return a==="invalid"?(n.logger.error(`${e.label}: ${o} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:t}):a==="absent"?{action:"absent",path:t}:(n.logger.info(`${e.label}: would remove "${r}" from ${o}.`),{action:"removed",path:t})},Be=(e,r,t)=>e.flatMap(n=>Ee(n,r)).filter(Oe).filter(n=>t===void 0||n.scope===t),Ze=e=>{const r=e.home??w(),t=e.platform??process.platform,n=A(e.clients,()=>v,e.logger,"uninstall");if(n===void 0)return{code:d.USAGE,removed:[]};const a=Ke(e);if(a.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:d.USAGE,removed:[]};const o=[],l={home:r,platform:t,projectRoot:e.cwd};for(const c of Be(n,l,e.scope))for(const i of a){const p=e.print===!0?Xe(c.client,i,c.path,e):qe(c.client,i,c.path,e);p.action!=="absent"&&o.push({...p,client:c.client.id,server:i})}return o.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:o.some(c=>c.action==="invalid")?1:0,removed:o}},_=e=>e.global===!0?"global":e.project===!0?"project":void 0,Qe=async(e,r)=>{const{code:t}=await He({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:R,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},mr=G(async({argument:e,cwd:r,logger:t,options:n})=>{const[a,...o]=e;if(a==="serve")return Qe(r,n);if(a==="uninstall"){const l=_(n),{code:c}=Ze({clients:o,cwd:r,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l}});return{code:c}}if(a==="install"){if(n.list===!0)return De({cwd:r,logger:t});const l=_(n),{code:c}=Fe({clients:o,cwd:r,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return t.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:d.USAGE}});export{mr as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d}from"../packem_shared/command-B--jgXSc.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-
|
|
1
|
+
import{d}from"../packem_shared/command-B--jgXSc.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-DgsCoi9w.mjs";const k=d(({argument:o,cwd:e,format:t,logger:u,options:r})=>m({cwd:e,format:t,logger:u,out:o[0]??r.out,prod:r.prod===!0,tables:r.tables,token:r.token,url:l({cwd:e,prod:r.prod===!0,url:r.url})}));export{k as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{a as n}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{I as u,r as i}from"../packem_shared/import-
|
|
1
|
+
import{d}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{a as n}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{I as u,r as i}from"../packem_shared/import-CQYRW8GG.mjs";const b=d(({argument:f,cwd:a,format:c,logger:t,options:r})=>{const o=f[0];if(!o){const e="import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]";return t.error(e),{code:m.USAGE,error:e}}if(r.from!==void 0&&!u.includes(r.from)){const e=`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`;return t.error(e),{code:m.USAGE,error:e}}return i({batchSize:r.batchSize,cwd:a,file:o,format:c,from:r.from,logger:t,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:n({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0})});export{b as execute};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{discoverMigrations as K,runCodegen as q}from"@lunora/codegen";import{readLinkedProject as N,execArgsFor as _,detectPackageManager as b,discoverContainerInfo as I,COMPOSED_WORKER_ENTRY as C,writeLinkedProject as Y,discoverSchemaInfo as z,DEV_VARS_FILE as p,parseDevVariableEntries as L,isMintableSecretKey as j,packageNamesFromBindings as J,inferLunoraBindings as U,requiredSecrets as X,generateSecretValue as Q,toolchainExecArgs as W,upsertDevVariableLine as Z,writeDevVariablesFileAtomically as ee,resolveDeployDriver as E,planToolchainInvocation as re,runPostCodegenHook as te}from"@lunora/config";import{findWranglerFile as F,readWranglerJsonc as ne,mergeWranglerEnvironment as ae,validateWranglerProject as oe,reconcileWranglerBindings as ie,reconcileWranglerCompatibilityDate as se,reconcileWranglerCrons as ce,describePreservedCrons as le}from"@lunora/config/cloudflare";import{Spinner as de}from"@visulima/spinner";import{r as ue,a as ge,e as me}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as fe,a as he}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as ve}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as pe}from"../packem_shared/command-B--jgXSc.mjs";import{r as R}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{containerBuildTag as ye}from"@lunora/container";import{a as we,i as ke}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{r as O}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as be,H as $e,a as Se,r as De}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{readFileSync as w,writeFileSync as B,existsSync as y}from"node:fs";import{join as v}from"@visulima/path";import{Project as Ee}from"ts-morph";import{m as Re,e as Ae,i as Ce}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{runMigrateDataCommand as je}from"../packem_shared/runMigrateGenerateCommand-CDHswpMU.mjs";import{c as Pe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as xe}from"../packem_shared/wrangler-secrets-CuUdFBaA.mjs";const Te=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??R(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Ne=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??we)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=ye(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=_(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:a,code:c.code,error:d}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(d),{builtTags:a,code:l.code,error:d}}a.push(n)}return{builtTags:a,code:0}},_e=e=>{const r=F(e),a=r===void 0?void 0:w(r,"utf8");return()=>{r!==void 0&&a!==void 0&&B(r,a,"utf8")}},M="<replace-with-d1-create-id>",P=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,A=(e,r)=>{const a=F(e);if(!a)return;const{parsed:t}=ne(a);if(t===void 0)return;const{error:n,merged:o}=ae(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:l}=i;return{containers:P(s),d1_databases:P(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ie=/^127(?:\.\d{1,3}){3}$/,Le=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ie.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Ue=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),We=(e,r,a,t="deploy",n)=>{const o=(A(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Ue(s.image));if(o.length===0||a())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},V=e=>y(v(e,C))?C:void 0,Fe=(e,r,a="deploy")=>{for(const t of I(e,"lunora").containers){const{image:n}=t;if(n.kind==="dockerfile"&&!y(v(e,n.dockerfilePath))){const o=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${n.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(n.kind==="build"&&!y(v(e,n.buildDir))){const o=`${a} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(o),o}}},Oe=(e,r)=>(A(e,r)?.d1_databases??[]).find(a=>a.database_id===M)?.binding,Be=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Me=(e,r,a="deploy",t)=>{const n=Oe(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${M}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},Ve=(e,r,a="deploy",t)=>{const n=A(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&Le(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},He=(e,r,a)=>{const t=Me(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=Ve(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=Fe(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=We(e,r.logger,r.dockerAvailable??ke,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},Ge=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Ke=/https:\/\/[^\s"'<>]+/u,qe=e=>{if(e===void 0)return;const r=Ge.exec(e);return r?r[0]:Ke.exec(e)?.[0]},x=e=>e===void 0?"":` (--env ${e})`,Ye=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${x(o.env)}, but this deploy published ${n}${x(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();Y(e,{env:r,linkedAt:i,workerName:R(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ze=async(e,r)=>{const a=new Ee({skipAddingFilesFromTsConfig:!0}),t=v(r,"lunora");let n;try{n=K(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await je(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},Je=async(e,r)=>{const{info:a}=z(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Re(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Ae({cwd:r,entries:n,exec:_(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},T=5,Xe=2e3,Qe=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??O({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await be({attempts:T,baseUrl:t,delayMs:Xe,fetchImpl:e.healthFetch,paths:[$e,Se],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(T)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},Ze=async(e,r,a,t,n,o)=>{await Je(e,r);const i=e.migrate?await ze(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},er=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:qe(o),workerName:R(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Ye({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await Qe(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await Ze(t,e,r,i,n,a),deployment:s,healthCheck:c}},rr=(e,r,a)=>{const t=v(e,p);if(!y(t))return;let n;try{n=L(w(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${p} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${p} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},tr=async e=>{let r=[];try{r=J(await U({projectRoot:e}))}catch{}const a=X(r).map(n=>n.key);let t=[];try{const n=v(e,p);y(n)&&(t=L(w(n,"utf8")).map(o=>o.key).filter(o=>Ce(o)))}catch{}return[...new Set([...a,...t])]},nr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=[];for(const d of a){const m=Q(),u=c({environment:r.env,key:d,temporary:r.temporary}),g=W(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${d} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${d}${s}\`.`),{minted:l,ok:!1};l.push({key:d,value:m}),n.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},ar=/^[\w-]+$/u,S=[".dev.vars",".dev.vars.*","!.dev.vars.example"],or=/\r?\n/u,ir=(e,r)=>{const a=v(e,".gitignore");try{const t=y(a)?w(a,"utf8"):"",n=new Set(t.split(or).map(c=>c.trim())),o=S.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...S.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
|
|
1
|
+
import{discoverMigrations as K,runCodegen as q}from"@lunora/codegen";import{readLinkedProject as N,execArgsFor as _,detectPackageManager as b,discoverContainerInfo as I,COMPOSED_WORKER_ENTRY as C,writeLinkedProject as Y,discoverSchemaInfo as z,DEV_VARS_FILE as p,parseDevVariableEntries as L,isMintableSecretKey as j,packageNamesFromBindings as J,inferLunoraBindings as U,requiredSecrets as X,generateSecretValue as Q,toolchainExecArgs as W,upsertDevVariableLine as Z,writeDevVariablesFileAtomically as ee,resolveDeployDriver as E,planToolchainInvocation as re,runPostCodegenHook as te}from"@lunora/config";import{findWranglerFile as F,readWranglerJsonc as ne,mergeWranglerEnvironment as ae,validateWranglerProject as oe,reconcileWranglerBindings as ie,reconcileWranglerCompatibilityDate as se,reconcileWranglerCrons as ce,describePreservedCrons as le}from"@lunora/config/cloudflare";import{Spinner as de}from"@visulima/spinner";import{r as ue,a as ge,e as me}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as fe,a as he}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as ve}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as pe}from"../packem_shared/command-B--jgXSc.mjs";import{r as R}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{containerBuildTag as ye}from"@lunora/container";import{a as we,i as ke}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{r as O}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as be,H as $e,a as Se,r as De}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{readFileSync as w,writeFileSync as B,existsSync as y}from"node:fs";import{join as v}from"@visulima/path";import{Project as Ee}from"ts-morph";import{m as Re,e as Ae,i as Ce}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{runMigrateDataCommand as je}from"../packem_shared/runMigrateGenerateCommand-yxTJ8CAg.mjs";import{c as Pe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as xe}from"../packem_shared/wrangler-secrets-CuUdFBaA.mjs";const Te=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??R(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Ne=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??we)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=ye(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=_(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:a,code:c.code,error:d}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(d),{builtTags:a,code:l.code,error:d}}a.push(n)}return{builtTags:a,code:0}},_e=e=>{const r=F(e),a=r===void 0?void 0:w(r,"utf8");return()=>{r!==void 0&&a!==void 0&&B(r,a,"utf8")}},M="<replace-with-d1-create-id>",P=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,A=(e,r)=>{const a=F(e);if(!a)return;const{parsed:t}=ne(a);if(t===void 0)return;const{error:n,merged:o}=ae(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:l}=i;return{containers:P(s),d1_databases:P(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ie=/^127(?:\.\d{1,3}){3}$/,Le=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ie.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Ue=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),We=(e,r,a,t="deploy",n)=>{const o=(A(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Ue(s.image));if(o.length===0||a())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},V=e=>y(v(e,C))?C:void 0,Fe=(e,r,a="deploy")=>{for(const t of I(e,"lunora").containers){const{image:n}=t;if(n.kind==="dockerfile"&&!y(v(e,n.dockerfilePath))){const o=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${n.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(n.kind==="build"&&!y(v(e,n.buildDir))){const o=`${a} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(o),o}}},Oe=(e,r)=>(A(e,r)?.d1_databases??[]).find(a=>a.database_id===M)?.binding,Be=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Me=(e,r,a="deploy",t)=>{const n=Oe(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${M}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},Ve=(e,r,a="deploy",t)=>{const n=A(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&Le(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},He=(e,r,a)=>{const t=Me(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=Ve(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=Fe(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=We(e,r.logger,r.dockerAvailable??ke,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},Ge=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Ke=/https:\/\/[^\s"'<>]+/u,qe=e=>{if(e===void 0)return;const r=Ge.exec(e);return r?r[0]:Ke.exec(e)?.[0]},x=e=>e===void 0?"":` (--env ${e})`,Ye=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${x(o.env)}, but this deploy published ${n}${x(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();Y(e,{env:r,linkedAt:i,workerName:R(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ze=async(e,r)=>{const a=new Ee({skipAddingFilesFromTsConfig:!0}),t=v(r,"lunora");let n;try{n=K(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await je(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},Je=async(e,r)=>{const{info:a}=z(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Re(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Ae({cwd:r,entries:n,exec:_(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},T=5,Xe=2e3,Qe=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??O({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await be({attempts:T,baseUrl:t,delayMs:Xe,fetchImpl:e.healthFetch,paths:[$e,Se],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(T)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},Ze=async(e,r,a,t,n,o)=>{await Je(e,r);const i=e.migrate?await ze(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},er=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:qe(o),workerName:R(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Ye({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await Qe(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await Ze(t,e,r,i,n,a),deployment:s,healthCheck:c}},rr=(e,r,a)=>{const t=v(e,p);if(!y(t))return;let n;try{n=L(w(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${p} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${p} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},tr=async e=>{let r=[];try{r=J(await U({projectRoot:e}))}catch{}const a=X(r).map(n=>n.key);let t=[];try{const n=v(e,p);y(n)&&(t=L(w(n,"utf8")).map(o=>o.key).filter(o=>Ce(o)))}catch{}return[...new Set([...a,...t])]},nr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=[];for(const d of a){const m=Q(),u=c({environment:r.env,key:d,temporary:r.temporary}),g=W(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${d} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${d}${s}\`.`),{minted:l,ok:!1};l.push({key:d,value:m}),n.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},ar=/^[\w-]+$/u,S=[".dev.vars",".dev.vars.*","!.dev.vars.example"],or=/\r?\n/u,ir=(e,r)=>{const a=v(e,".gitignore");try{const t=y(a)?w(a,"utf8"):"",n=new Set(t.split(or).map(c=>c.trim())),o=S.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...S.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
|
|
2
2
|
`)?`
|
|
3
3
|
`:"";B(a,`${t}${s}
|
|
4
4
|
# Lunora — never commit a minted secret
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{r as S,d as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as N,a as
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{r as S,d as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as _,b as N,a as U}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as P}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as i,exitCodeForStatus as E}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{r as I}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const y=(r,t="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(a){const s=a instanceof Error?a.message:String(a);throw new h("INTERNAL",`failed to parse ${t} as JSON: ${s}`,{cause:a})}if(typeof e!="object"||e===null||Array.isArray(e))throw new h("INTERNAL",`${t} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},O=/\/$/u,$="__lunora_admin__:runAs",T="__lunora_admin__:",k=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},p=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.status!==403||e!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},R=({args:r,claims:t,options:e,runAs:a})=>{const s=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:$}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(s.shardKey=e.shard),s},w=({cwd:r,logger:t,needsBearer:e,url:a})=>e?_(a,t,r):(I({cwd:r,url:a})??N(r)).replace(O,""),D=({args:r,claims:t},e)=>{try{return{args:y(r),claims:t===void 0?void 0:y(t,"--claims")}}catch(a){e.error(a instanceof Error?a.message:String(a));return}},J=async r=>{const t=r.cwd??process.cwd(),{logger:e}=r,a=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!a){const d="--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch.";return e.error(d),{body:void 0,code:i.USAGE,error:d,requestUrl:r.url??""}}const s=a||r.functionPath.startsWith(T),n=w({cwd:t,logger:e,needsBearer:s,url:r.url});if(n===void 0)return{body:void 0,code:i.USAGE,error:"could not resolve a usable worker URL",requestUrl:r.url??""};const o=`${n}/_lunora/rpc`,u=r.fetchImpl??U,m=D(r,e);if(m===void 0)return{body:void 0,code:i.USAGE,error:"could not parse --args / --claims as JSON",requestUrl:o};const{source:g,token:l}=s?S({cwd:t,token:r.token,url:n}):{};if(s&&l===void 0){const d="admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)";return e.error(d),{body:void 0,code:i.AUTH,error:d,requestUrl:o}}l!==void 0&&e.debug?.(`admin bearer from ${b(g)}`);const v={"content-type":"application/json",...l===void 0?{}:{authorization:`Bearer ${l}`}},A=R({args:m.args,claims:m.claims,options:r,runAs:a});e.info(`POST ${o} -> ${r.functionPath}${a?` (as ${r.as??""})`:""}`);const c=await u(o,{body:JSON.stringify(A),headers:v,method:"POST"}),f=await k(c,e);return p(e,{body:f,runAs:a,status:c.status}),{body:f,code:c.ok?0:E(c.status),error:c.ok?void 0:`${r.functionPath} failed: HTTP ${String(c.status)}`,requestUrl:o}},j=P(async({argument:r,cwd:t,format:e,logger:a,options:s})=>{const n=r[0];if(!n){const u="missing function path. Usage: lunora run <functionPath> [--args <json>]";return a.error(u),{code:i.USAGE,error:u}}const o=await J({args:s.args,as:s.as,claims:s.claims,cwd:t,format:e,functionPath:n,logger:a,shard:s.shard,token:s.token,url:s.url});return{code:o.code,data:{functionPath:n,requestUrl:o.requestUrl,result:o.body},error:o.error}});export{j as execute,k as readAndLogBody,J as runRpcCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as i,R as m,V as p,r as s}from"./cli-
|
|
1
|
+
import{C as i,R as m,V as p,r as s}from"./cli-NU4LQDgm.mjs";import"./EXIT_CODE-08cwt3MK.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-DgaSmNLc.mjs";export{i as COMMANDS,m as REGISTERED_COMMAND_NAMES,p as VERSION,s as runCli};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./admin-token-VdUnvnKW.mjs";import"./admin-url-DJB8P6Jh.mjs";import"./EXIT_CODE-08cwt3MK.mjs";import{D as a,r as I}from"./import-CQYRW8GG.mjs";import"./shared-D-zCOmgY.mjs";export{a as DEFAULT_IMPORT_BATCH_SIZE,I as runImportCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readLiveDevServerState as c}from"@lunora/config";import{LunoraError as i}from"@lunora/errors";const a=new Set(["127.0.0.1","::1","[::1]","localhost"]),h=/\/$/u,n="http://localhost:8787",l=r=>r===void 0?n:c(r)?.url??n,u=r=>r.replace(h,""),v=(r,s,e)=>{const o=r??l(e);let t;try{t=new URL(o)}catch{s.error(`invalid --url: ${o}`);return}if(!a.has(t.hostname)&&t.protocol!=="https:"){s.error(`refusing to send the admin bearer over ${t.protocol}// to ${t.hostname} — use https for non-localhost targets`);return}return u(o)},f=async(r,s)=>{try{return await fetch(r,s)}catch(e){if(!(e instanceof TypeError))throw e;const o=e.cause instanceof Error?e.cause.message:e.message,t=a.has(new URL(r).hostname)?" — is the dev server running? Start it, or pass --url to point at the worker":"";throw new i("INTERNAL",`could not reach ${r} (${o})${t}`,{cause:e})}};export{f as a,l as b,u as n,v as r};
|