@lunora/cli 1.0.0-alpha.126 → 1.0.0-alpha.128
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 +42 -6
- package/dist/index.d.ts +42 -6
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -1
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- 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 +2 -2
- package/dist/packem_chunks/handler19.mjs +1 -1
- package/dist/packem_chunks/handler21.mjs +7 -2
- package/dist/packem_chunks/handler22.mjs +2 -99
- package/dist/packem_chunks/handler23.mjs +99 -11
- package/dist/packem_chunks/handler24.mjs +11 -0
- package/dist/packem_chunks/handler3.mjs +2 -2
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +4 -4
- package/dist/packem_chunks/planDevCommand.mjs +6 -6
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -4
- package/dist/packem_chunks/runDeployCommand.mjs +1 -1
- package/dist/packem_chunks/runInitCommand.mjs +1 -1
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +3 -3
- package/dist/packem_shared/COMMANDS-BHb52jlk.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs +12 -0
- package/dist/packem_shared/cli-BxL0WCh4.mjs +3 -0
- package/dist/packem_shared/commands-C5pu77HK.mjs +19 -0
- package/dist/packem_shared/deploy-target-Dvr9vxpR.mjs +1 -0
- package/dist/packem_shared/platform-diagnostics-C4TFj5Pu.mjs +4 -0
- package/dist/packem_shared/runAddCommand-CuvJ0l7a.mjs +1 -0
- package/dist/packem_shared/{storage-BHSN9Vgb.mjs → storage-BazhWFmM.mjs} +1 -1
- package/dist/packem_shared/wrangler-name-CHDf3rMP.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-DDDUuryf.mjs +1 -0
- package/package.json +9 -8
- package/dist/packem_shared/COMMANDS-DmB3_936.mjs +0 -3
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs +0 -8
- package/dist/packem_shared/commands-B1SpMXov.mjs +0 -19
- package/dist/packem_shared/runAddCommand-BF35qSZ2.mjs +0 -1
- package/dist/packem_shared/wrangler-name-HIl0Z6yx.mjs +0 -1
- package/dist/packem_shared/wrangler-secrets-BMRJwKQU.mjs +0 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{e}from"./packem_shared/cli-BxL0WCh4.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
3
3
|
`),process.exit(1)}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { CodegenOptions, SchemaIR } from '@lunora/codegen';
|
|
2
2
|
import '@visulima/cerebro';
|
|
3
|
-
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets
|
|
4
|
-
|
|
3
|
+
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets } from '@lunora/config';
|
|
4
|
+
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
|
+
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
6
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
6
7
|
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
7
8
|
type CommandName = (typeof COMMANDS)[number];
|
|
@@ -64,6 +65,14 @@ interface CodegenCommandOptions {
|
|
|
64
65
|
/** Output format: `pretty` (default) or `json`. */
|
|
65
66
|
format?: string;
|
|
66
67
|
logger: Logger;
|
|
68
|
+
/**
|
|
69
|
+
* Fail the run when any ERROR-level advisory is reported. Defaults to CI
|
|
70
|
+
* detection so a local `lunora codegen` stays advisory while a pipeline
|
|
71
|
+
* gates on it; `--no-strict-advisories` forces it off either way.
|
|
72
|
+
*/
|
|
73
|
+
strictAdvisories?: boolean;
|
|
74
|
+
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
75
|
+
target?: string;
|
|
67
76
|
}
|
|
68
77
|
interface CodegenCommandResult {
|
|
69
78
|
advisories: ReadonlyArray<{
|
|
@@ -73,8 +82,10 @@ interface CodegenCommandResult {
|
|
|
73
82
|
remediation: string;
|
|
74
83
|
}>;
|
|
75
84
|
cronTriggers: ReadonlyArray<string>;
|
|
76
|
-
/** Set when the run
|
|
85
|
+
/** Set when the run failed: an invalid `--format`, an unregistered target, or an error-level platform diagnostic. */
|
|
77
86
|
error?: string;
|
|
87
|
+
/** ERROR-level advisories that made the run fail, when strict mode is on. */
|
|
88
|
+
failedAdvisories: number;
|
|
78
89
|
outputDirectory: string;
|
|
79
90
|
}
|
|
80
91
|
declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
|
|
@@ -150,9 +161,10 @@ interface ImportCommandResult {
|
|
|
150
161
|
inserted: number;
|
|
151
162
|
}
|
|
152
163
|
/**
|
|
153
|
-
* Stream an NDJSON file
|
|
154
|
-
* `/_lunora/admin/import`.
|
|
155
|
-
* multi-GiB
|
|
164
|
+
* Stream an NDJSON file — or a `npx convex export --path <dir>` directory — in
|
|
165
|
+
* chunks, POSTing each batch to `/_lunora/admin/import`. The line buffer stays
|
|
166
|
+
* bounded by `batchSize`, so a multi-GiB source imports without buffering
|
|
167
|
+
* everything in memory.
|
|
156
168
|
*/
|
|
157
169
|
declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
|
|
158
170
|
/**
|
|
@@ -346,6 +358,14 @@ interface DeployCommandOptions {
|
|
|
346
358
|
secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
|
|
347
359
|
skipCodegen?: boolean;
|
|
348
360
|
spawner?: Spawner;
|
|
361
|
+
/**
|
|
362
|
+
* Deploy target. Falls back to `"target"` in `lunora.json`, then
|
|
363
|
+
* `"cloudflare"`, which selects the wrangler
|
|
364
|
+
* toolchain — i.e. today's behavior for every project. An unregistered name
|
|
365
|
+
* throws rather than falling back, so a typo can never ship the app to the
|
|
366
|
+
* wrong provider.
|
|
367
|
+
*/
|
|
368
|
+
target?: string;
|
|
349
369
|
/**
|
|
350
370
|
* Deploy to a temporary Cloudflare account (`wrangler deploy --temporary`).
|
|
351
371
|
* For unauthenticated use only: wrangler provisions a short-lived account +
|
|
@@ -396,6 +416,8 @@ interface CodegenWatcherOptions {
|
|
|
396
416
|
lunoraDirectory?: string;
|
|
397
417
|
/** Project root containing the `lunora/` directory. */
|
|
398
418
|
projectRoot: string;
|
|
419
|
+
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
420
|
+
target?: string;
|
|
399
421
|
}
|
|
400
422
|
interface CodegenWatcherHandle {
|
|
401
423
|
/** Stop watching and cancel any pending regeneration. */
|
|
@@ -495,6 +517,10 @@ interface DevCommandOptions {
|
|
|
495
517
|
startWorker?: WorkerSpawner;
|
|
496
518
|
/** Disable the embedded studio server. */
|
|
497
519
|
studio?: boolean;
|
|
520
|
+
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
521
|
+
target?: string;
|
|
522
|
+
/** Disable the `wrangler dev` spawn — an external task runner owns the worker. */
|
|
523
|
+
worker?: boolean;
|
|
498
524
|
/** `wrangler dev` port. */
|
|
499
525
|
workerPort?: number;
|
|
500
526
|
}
|
|
@@ -547,6 +573,16 @@ interface DevCommandPlan {
|
|
|
547
573
|
};
|
|
548
574
|
studioEnabled: boolean;
|
|
549
575
|
studioPort: number;
|
|
576
|
+
/**
|
|
577
|
+
* Whether this process spawns `wrangler dev`.
|
|
578
|
+
*
|
|
579
|
+
* `--no-worker` turns it off so an external task runner (Turbo, Nx, vis, a
|
|
580
|
+
* Procfile) can own worker supervision while `lunora dev` still provides
|
|
581
|
+
* codegen-watch and Studio. Without it, `lunora dev` insisted on being the
|
|
582
|
+
* process root, which is what blocked running the Lunora worker as one node
|
|
583
|
+
* in a larger dev graph.
|
|
584
|
+
*/
|
|
585
|
+
workerEnabled: boolean;
|
|
550
586
|
workerOrigin: string;
|
|
551
587
|
workerPort: number;
|
|
552
588
|
/** The primary child `lunora dev` spawns: `wrangler dev` (wrangler flavor) or the framework/`vite dev` server (vite / framework-worker). */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { CodegenOptions, SchemaIR } from '@lunora/codegen';
|
|
2
2
|
import '@visulima/cerebro';
|
|
3
|
-
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets
|
|
4
|
-
|
|
3
|
+
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets } from '@lunora/config';
|
|
4
|
+
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
|
+
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
6
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
6
7
|
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
7
8
|
type CommandName = (typeof COMMANDS)[number];
|
|
@@ -64,6 +65,14 @@ interface CodegenCommandOptions {
|
|
|
64
65
|
/** Output format: `pretty` (default) or `json`. */
|
|
65
66
|
format?: string;
|
|
66
67
|
logger: Logger;
|
|
68
|
+
/**
|
|
69
|
+
* Fail the run when any ERROR-level advisory is reported. Defaults to CI
|
|
70
|
+
* detection so a local `lunora codegen` stays advisory while a pipeline
|
|
71
|
+
* gates on it; `--no-strict-advisories` forces it off either way.
|
|
72
|
+
*/
|
|
73
|
+
strictAdvisories?: boolean;
|
|
74
|
+
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
75
|
+
target?: string;
|
|
67
76
|
}
|
|
68
77
|
interface CodegenCommandResult {
|
|
69
78
|
advisories: ReadonlyArray<{
|
|
@@ -73,8 +82,10 @@ interface CodegenCommandResult {
|
|
|
73
82
|
remediation: string;
|
|
74
83
|
}>;
|
|
75
84
|
cronTriggers: ReadonlyArray<string>;
|
|
76
|
-
/** Set when the run
|
|
85
|
+
/** Set when the run failed: an invalid `--format`, an unregistered target, or an error-level platform diagnostic. */
|
|
77
86
|
error?: string;
|
|
87
|
+
/** ERROR-level advisories that made the run fail, when strict mode is on. */
|
|
88
|
+
failedAdvisories: number;
|
|
78
89
|
outputDirectory: string;
|
|
79
90
|
}
|
|
80
91
|
declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
|
|
@@ -150,9 +161,10 @@ interface ImportCommandResult {
|
|
|
150
161
|
inserted: number;
|
|
151
162
|
}
|
|
152
163
|
/**
|
|
153
|
-
* Stream an NDJSON file
|
|
154
|
-
* `/_lunora/admin/import`.
|
|
155
|
-
* multi-GiB
|
|
164
|
+
* Stream an NDJSON file — or a `npx convex export --path <dir>` directory — in
|
|
165
|
+
* chunks, POSTing each batch to `/_lunora/admin/import`. The line buffer stays
|
|
166
|
+
* bounded by `batchSize`, so a multi-GiB source imports without buffering
|
|
167
|
+
* everything in memory.
|
|
156
168
|
*/
|
|
157
169
|
declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
|
|
158
170
|
/**
|
|
@@ -346,6 +358,14 @@ interface DeployCommandOptions {
|
|
|
346
358
|
secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
|
|
347
359
|
skipCodegen?: boolean;
|
|
348
360
|
spawner?: Spawner;
|
|
361
|
+
/**
|
|
362
|
+
* Deploy target. Falls back to `"target"` in `lunora.json`, then
|
|
363
|
+
* `"cloudflare"`, which selects the wrangler
|
|
364
|
+
* toolchain — i.e. today's behavior for every project. An unregistered name
|
|
365
|
+
* throws rather than falling back, so a typo can never ship the app to the
|
|
366
|
+
* wrong provider.
|
|
367
|
+
*/
|
|
368
|
+
target?: string;
|
|
349
369
|
/**
|
|
350
370
|
* Deploy to a temporary Cloudflare account (`wrangler deploy --temporary`).
|
|
351
371
|
* For unauthenticated use only: wrangler provisions a short-lived account +
|
|
@@ -396,6 +416,8 @@ interface CodegenWatcherOptions {
|
|
|
396
416
|
lunoraDirectory?: string;
|
|
397
417
|
/** Project root containing the `lunora/` directory. */
|
|
398
418
|
projectRoot: string;
|
|
419
|
+
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
420
|
+
target?: string;
|
|
399
421
|
}
|
|
400
422
|
interface CodegenWatcherHandle {
|
|
401
423
|
/** Stop watching and cancel any pending regeneration. */
|
|
@@ -495,6 +517,10 @@ interface DevCommandOptions {
|
|
|
495
517
|
startWorker?: WorkerSpawner;
|
|
496
518
|
/** Disable the embedded studio server. */
|
|
497
519
|
studio?: boolean;
|
|
520
|
+
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
521
|
+
target?: string;
|
|
522
|
+
/** Disable the `wrangler dev` spawn — an external task runner owns the worker. */
|
|
523
|
+
worker?: boolean;
|
|
498
524
|
/** `wrangler dev` port. */
|
|
499
525
|
workerPort?: number;
|
|
500
526
|
}
|
|
@@ -547,6 +573,16 @@ interface DevCommandPlan {
|
|
|
547
573
|
};
|
|
548
574
|
studioEnabled: boolean;
|
|
549
575
|
studioPort: number;
|
|
576
|
+
/**
|
|
577
|
+
* Whether this process spawns `wrangler dev`.
|
|
578
|
+
*
|
|
579
|
+
* `--no-worker` turns it off so an external task runner (Turbo, Nx, vis, a
|
|
580
|
+
* Procfile) can own worker supervision while `lunora dev` still provides
|
|
581
|
+
* codegen-watch and Studio. Without it, `lunora dev` insisted on being the
|
|
582
|
+
* process root, which is what blocked running the Lunora worker as one node
|
|
583
|
+
* in a larger dev graph.
|
|
584
|
+
*/
|
|
585
|
+
workerEnabled: boolean;
|
|
550
586
|
workerOrigin: string;
|
|
551
587
|
workerPort: number;
|
|
552
588
|
/** The primary child `lunora dev` spawns: `wrangler dev` (wrangler flavor) or the framework/`vite dev` server (vite / framework-worker). */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{s as o,t as n,e as a}from"./packem_shared/cli-BxL0WCh4.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as x}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as s,runDevCommand as u}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as R}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as E}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as A}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as M}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as _,pail as h}from"./packem_shared/createLogger--C3x1FNE.mjs";import{diffSnapshots as L,renderAddColumn as O,renderCreateIndex as b,renderCreateTable as w,renderDropIndex as B,renderDropTable as F,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as q}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as N,defaultSpawner as Q}from"./packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{default as j}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{k as $,q as rr,D as er}from"./packem_shared/commands-C5pu77HK.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,N as createRecordingSpawner,Q as defaultSpawner,L as diffSnapshots,M as insertSchemaExtension,h as pail,j as parseManifest,s as planDevCommand,O as renderAddColumn,b as renderCreateIndex,w as renderCreateTable,B as renderDropIndex,F as renderDropTable,P as renderMigrationFile,$ as runAddCommand,rr as runBuildIndexCommand,a as runCli,t as runCodegenCommand,C as runDeployCommand,u as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,R as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as y,readFileSync as $}from"node:fs";import{findWranglerFile as b}from"@lunora/config";import{join as p,basename as h}from"@visulima/path";import{i as k}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S,r as T,d as j,s as U}from"../packem_shared/output-format-D7cKB-O5.mjs";import{B as g,C as x}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as C,r as
|
|
1
|
+
import{existsSync as y,readFileSync as $}from"node:fs";import{findWranglerFile as b}from"@lunora/config/cloudflare";import{join as p,basename as h}from"@visulima/path";import{i as k}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S,r as T,d as j,s as U}from"../packem_shared/output-format-D7cKB-O5.mjs";import{B as g,C as x}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as C,r as R,l as q,i as B,o as l,u as D,a as m,b as F,c as L,e as f,f as M,g as d,n as N,h as W,s as u,j as A,k as O,p as G,m as J,q as K}from"../packem_shared/storage-BazhWFmM.mjs";import{k as P}from"../packem_shared/commands-C5pu77HK.mjs";const Q=r=>{const e=r.trim().toLowerCase();return O.find(a=>a.value===e||a.label.toLowerCase()===e||e==="auth0"&&a.value==="auth-auth0"||e==="clerk"&&a.value==="auth-clerk")?.value},w=r=>{try{const e=JSON.parse($(p(r,"package.json"),"utf8"));return{...e.dependencies,...e.devDependencies}}catch{return{}}},V=async r=>{const e=r.cwd??process.cwd(),a=W(w(e));return a!==void 0?a:r.yes===!0?(r.logger.warn(`add: couldn't detect your framework — using "${u}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),u):await(r.promptSelect??((o,s,n)=>g(o,s,n)))("Which framework is your app?",A,{default:u})??u},X=async r=>{if(r.provider!==void 0&&r.provider!==""){const a=Q(r.provider);return a===void 0?(r.logger.warn(`add: unknown --provider "${r.provider}" — using "${d}" (email & password).`),d):a}if(r.yes===!0)return d;const e=r.promptSelect??((a,o,s)=>g(a,o,s));return N(e)},c=r=>r.promptText??((e,a)=>x(e,a)),Y=async r=>{const e=h(r.cwd??process.cwd());if(r.bucket!==void 0&&r.bucket!==""){const a=B(r.bucket);if(a!==void 0)return a;const o=l(e);return r.logger.warn(`add: "${r.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${o}".`),o}return r.yes===!0?l(e):D(c(r),e)},Z=async r=>{const e=a=>{r.logger.warn(`add: ${a}`)};if(r.mailTo!==void 0&&r.mailTo!=="")return m(r.mailTo,e);if(r.yes!==!0)return m(await c(r)(F,{placeholder:"you@yourdomain.com"}),e)},z=async r=>{const e=h(r.cwd??process.cwd());if(r.db!==void 0&&r.db!==""){const a=L(r.db);if(a!==void 0)return a;const o=f(e);return r.logger.warn(`add: "${r.db}" isn't a usable D1 database name — using "${o}".`),o}return r.yes===!0?f(e):M(c(r),e)},E=async(r,e)=>r.kind==="auth"?[await X(e)]:r.kind==="auth-ui"?[await V(e)]:r.kind==="email"?[q]:[r.item],H=async r=>{const e=r.cwd??process.cwd(),a=r.feature===void 0?void 0:C(r.feature);if(a===void 0)return r.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!y(p(e,"lunora"))||b(e)===void 0)return r.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};if(a.kind==="auth-ui"&&R(w(e)))return r.logger.error("add: auth-ui has no React Native port — the screens render DOM elements and a stylesheet, which Metro has nothing to mount. Build the screens with React Native primitives against the same better-auth client (`@lunora/react-native/auth`); `lunora add auth` still installs the server half."),{code:1,items:[]};const o=await E(a,r),s=[];if(o.includes("storage")){const t=await Y(r);s.push(i=>G(i,t))}if(o.includes("mail")){const t=await Z(r);t!==void 0&&s.push(i=>J(i,t))}if(o.some(t=>t==="auth"||t.startsWith("auth-"))){const t=await z(r);s.push(i=>K(i,t))}const n=s.length>0?t=>{let i=t;for(const v of s)i=v(i);return i}:void 0;return{code:(await P({allowUnsafeSource:r.allowUnsafeSource,cwd:e,from:r.from,logger:r.logger,names:[...o],ref:r.ref,source:r.source,transformManifest:n,yes:!0})).code,items:o}},ir=k(async({argument:r,cwd:e,logger:a,options:o})=>{const s=S("add",o.format);if(s!==void 0)return a.error(s),{code:1};const n=U(o.format,a),t=await H({allowUnsafeSource:o.allowUnsafeSource===!0,bucket:o.bucket,cwd:e,db:o.db,feature:r[0],from:o.from,logger:n,mailTo:o.mailTo,provider:o.provider,ref:o.ref,source:o.source,yes:o.yes===!0});return T(o.format)&&j({code:t.code,items:t.items}),{code:t.code}});export{ir as execute,H as runAddFeature};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-
|
|
1
|
+
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const s=p(({argument:r,cwd:t,logger:e,options:o})=>m({cwd:t,logger:e,out:r[0]??o.out,prod:o.prod===!0,tables:o.tables,token:o.token,url:u({cwd:t,prod:o.prod===!0,url:o.url})}));export{s as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as
|
|
1
|
+
import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as p}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runImportCommand as i}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const l=n(({argument:a,cwd:e,logger:r,options:o})=>{const t=a[0];return t?i({batchSize:o.batchSize,cwd:e,file:t,logger:r,prod:o.prod===!0,table:o.table,token:o.token,url:p({cwd:e,prod:o.prod===!0,url:o.url}),yes:o.yes===!0}):(r.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{l as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as c,rmSync as m}from"node:fs";import{join as u}from"node:path";import{writeLinkedProject as s,LINKED_PROJECT_FILE as t}from"@lunora/config";import{i as d}from"../packem_shared/command-Bjv4VmYA.mjs";import{d as a}from"../packem_shared/wrangler-name-
|
|
1
|
+
import{existsSync as c,rmSync as m}from"node:fs";import{join as u}from"node:path";import{writeLinkedProject as s,LINKED_PROJECT_FILE as t}from"@lunora/config";import{i as d}from"../packem_shared/command-Bjv4VmYA.mjs";import{d as a}from"../packem_shared/wrangler-name-CHDf3rMP.mjs";const k=r=>{try{const{protocol:o}=new URL(r);return o==="http:"||o==="https:"}catch{return!1}},p=(r,o)=>{const e=u(r,t);return c(e)?(m(e),o.success(`link: removed ${t}`),{code:0}):(o.warn(`link: no ${t} to remove`),{code:0})},v=r=>{const o=r.cwd??process.cwd(),{logger:e}=r;if(r.remove)return p(o,e);if(r.url===void 0||r.url==="")return e.error("link requires a deployed Worker URL. Usage: lunora link --url <https://your-worker>"),{code:1};if(!k(r.url))return e.error(`link: invalid --url "${r.url}" — expected an http(s) URL`),{code:1};const i=r.now??(()=>new Date().toISOString()),n={env:r.env,linkedAt:i(),workerName:r.name??a(o),workerUrl:r.url},l=s(o,n);return e.success(`link: ${n.workerName??"(unnamed worker)"} -> ${r.url}`),e.info(`link: wrote ${l}`),n.env!==void 0&&e.info(`link: environment "${n.env}"`),{code:0,link:n}},h=d(({cwd:r,logger:o,options:e})=>v({cwd:r,env:e.env,logger:o,name:e.name,remove:e.remove===!0,url:e.url}));export{h as execute,v as runLinkCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runCodegen as
|
|
1
|
+
import{runCodegen as g}from"@lunora/codegen";import{resolveTargetOrThrow as d,resolveDeployDriver as p}from"@lunora/config";import{r as m}from"../packem_shared/api-spec-BENwiyUa.mjs";import{l as f}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{i as u}from"../packem_shared/command-Bjv4VmYA.mjs";import{a as h}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{k as w}from"../packem_shared/schema-drift-gate-CpqG-xP4.mjs";import{validateWranglerProject as v}from"@lunora/config/cloudflare";const S=async(e,t,a=[],i)=>{const s={crons:a,projectRoot:e},n=p(i);try{const r=await n.infer(s),l=[r.shardNamespaces.length>0?`${String(r.shardNamespaces.length)} shard namespace(s)`:void 0,r.queues.length>0?`${String(r.queues.length)} queue(s)`:void 0,r.workflows.length>0?`${String(r.workflows.length)} workflow(s)`:void 0,r.containers.length>0?`${String(r.containers.length)} container(s)`:void 0,r.globalDatabase?"global database":void 0,r.objectStorage?"object storage":void 0,r.keyValueStore?"key-value store":void 0].filter(c=>c!==void 0);l.length>0&&t.info(`${n.name} target requires: ${l.join(", ")}`)}catch{}const o=await n.provision(s);o.changed&&t.success(`provisioned: ${o.added.join(", ")} → ${o.configPath??"wrangler.jsonc"}`);for(const r of o.warnings)t.warn(r)},b=async e=>{const t=e.cwd??process.cwd(),a=d(t,e.target);e.logger.info("running codegen");let i;try{i=g({apiSpec:e.apiSpec,projectRoot:t,target:a}),e.logger.success("codegen complete"),h(i.platformDiagnostics,e.logger)}catch(o){const r=o instanceof Error?o.message:String(o);return e.logger.error(f(o)),{code:1,error:`codegen failed: ${r}`,validation:{problems:[],wranglerPath:void 0}}}const s=w({allowDrift:e.allowSchemaDrift===!0,codegen:i,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(s.blocked)return{code:1,error:"schema drift gate blocked prepare",schemaDrift:{blocked:!0,reason:s.reason},validation:{problems:[],wranglerPath:void 0}};await S(t,e.logger,i.cronTriggers,a);const n=v({projectRoot:t});if(n.problems.length>0){e.logger.error("wrangler.jsonc validation failed:");for(const o of n.problems)e.logger.error(` - ${o}`);return{code:1,error:"wrangler validation failed",validation:n}}return s.rebless?.(),e.logger.success("project is ready to deploy"),{code:0,validation:n}},R=u(({cwd:e,logger:t,options:a})=>b({allowSchemaDrift:a.allowSchemaDrift===!0,apiSpec:m(a.apiSpec),cwd:e,logger:t,target:a.target,updateSchemaBaseline:a.updateSchemaBaseline===!0}));export{R as execute,b as runPrepareCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{
|
|
1
|
+
import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{k as c,D as f,q as a}from"../packem_shared/commands-C5pu77HK.mjs";const i=n(({argument:u,cwd:s,logger:o,options:e})=>{const r=u[0],t=u.slice(1);return r==="add"?c({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,diff:e.diff===!0,dryRun:e.dryRun===!0,from:e.from,json:e.json===!0,logger:o,names:t,overwrite:e.overwrite===!0,ref:e.ref,source:e.source,yes:e.yes===!0}):r==="list"?c({cwd:s,from:e.from,json:e.json===!0,list:!0,logger:o,names:[],ref:e.ref,source:e.source}):r==="view"?f({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,from:e.from,logger:o,names:t,ref:e.ref,source:e.source}):r==="build"?a({check:e.check===!0,from:e.from,logger:o,out:e.out}):(o.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{i as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as c,readFileSync as g,readdirSync as p,statSync as k,mkdirSync as S,writeFileSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";import{AGENT_RULES_DIR as u,detectAgentRules as L,LUNORA_SKILL_NAMES as R}from"@lunora/config";import{join as l,relative as $,resolve as j,dirname as d}from"@visulima/path";import{i as I}from"../packem_shared/command-Bjv4VmYA.mjs";const b=(r=d(v(import.meta.url)))=>{let e=r;for(let n=0;n<6;n+=1){const t=l(e,"package.json");if(c(t))try{if(JSON.parse(g(t,"utf8")).name==="@lunora/cli"){const s=l(e,"skills");return c(s)?s:void 0}}catch{}const o=d(e);if(o===e)break;e=o}},A=r=>p(r).filter(e=>{const n=l(r,e);return k(n).isDirectory()&&c(l(n,"SKILL.md"))}),m=(r,e,n)=>{S(e,{recursive:!0});let t=!1;for(const o of p(r)){const s=l(r,o),i=l(e,o);if(k(s).isDirectory()){t=m(s,i,n)||t;continue}c(i)&&!n||(y(i,g(s)),t=!0)}return t},_=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],x=r=>{let e=r;for(;;){if(_.some(t=>c(l(e,t))))return e;const n=d(e);if(n===e)return r;e=n}},f=(r,e)=>e===void 0?x(r):j(r,e),D=r=>{const e=r.cwd??process.cwd(),n=f(e,r.dir),t=r.overwrite===!0,o=b();if(o===void 0)return r.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const s=[],i=[];for(const a of A(o)){const w=l(n,u,a);m(l(o,a),w,t)?s.push(a):i.push(a)}const h=$(e,l(n,u))||u;return s.length>0&&r.logger.success(`Installed ${String(s.length)} Lunora skill(s) into ${h}/: ${s.join(", ")}.`),i.length>0&&r.logger.info(`Skipped ${String(i.length)} existing skill(s) (re-run with --overwrite to replace): ${i.join(", ")}.`),r.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:s,skipped:i}},E=r=>{const e=r.cwd??process.cwd(),n=f(e,r.dir),t=L(n);return t.installed?(r.logger.success(`Lunora agent rules are installed (${String(t.present.length)}/${String(R.length)} skills).`),t.missing.length>0&&r.logger.info(`Missing: ${t.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:t.present,skipped:[]}):(r.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:r.strict===!0?1:0,installed:t.present,skipped:[]})},M=I(({argument:r,cwd:e,logger:n,options:t})=>{const o=r[0]??"check";return o==="install"?D({cwd:e,dir:t.dir,logger:n,overwrite:t.overwrite===!0}):o==="check"?E({cwd:e,dir:t.dir,logger:n,strict:t.strict===!0}):(n.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:1})});export{M as execute,b as resolveBundledSkillsDirectory,E as runRulesCheck,D as runRulesInstall};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as
|
|
1
|
+
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as j}from"node:fs/promises";import{tmpdir as $}from"node:os";import{discoverSchema as k,schemaFromIr as C}from"@lunora/codegen";import{seedPlan as R}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as x}from"ts-morph";import{i as z}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as A}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{i as F}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{runImportCommand as I}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";import{runResetCommand as T}from"./runResetCommand.mjs";const p=r=>{if(r===void 0)return!0;try{const{hostname:e}=new URL(r);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}catch{return!1}},N=(r,e)=>typeof e=="bigint"?Number(e):e instanceof ArrayBuffer?[...new Uint8Array(e)]:e,c=r=>({code:r,conflicts:0,generated:0,inserted:0,ndjson:""}),U=(r,e)=>{if(!y(e))return r.logger.error(`schema not found: ${e} — run \`vis generate lunora-table --name=<name>\` to create one`),c(1);if(r.reset===!0&&(r.prod===!0||!p(r.url)))return r.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),c(1)},P=async(r,e,t,o)=>{const l=await S(m($(),"lunora-seed-")),a=m(l,"rows.ndjson");await v(a,r,"utf8");try{const n=await I({batchSize:o.batchSize,cwd:t,fetchImpl:o.fetchImpl,file:a,logger:o.logger,prod:o.prod,token:o.token,url:o.url}),d=n.body?.conflicts??0;return d>0&&o.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:n.code,conflicts:d,generated:e,inserted:n.inserted,ndjson:r}}finally{await j(l,{force:!0,recursive:!0}).catch(()=>{})}},_=(r,e)=>{if(r.table===void 0||e.tables.some(o=>o.name===r.table))return;const t=e.tables.map(o=>o.name).join(", ");return r.logger.error(`unknown table "${r.table}" — schema defines: ${t||"(no tables)"}`),c(1)},B=async(r,e)=>{if(!(!(r.prod===!0||!p(r.url))||r.yes===!0)){if(!process.stdin.isTTY&&r.confirm===void 0)return r.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),c(1);if(!await(r.confirm??F)(`This will insert ${String(e)} generated row(s) into ${r.url??"the production worker"}. Continue?`))return r.logger.info("seed: aborted"),c(1)}},G=async r=>{const e=r.cwd??process.cwd(),t=m(e,"lunora","schema.ts"),o=U(r,t);if(o!==void 0)return o;const l=new x({skipAddingFilesFromTsConfig:!0}),a=k(l,t),n=_(r,a);if(n!==void 0)return n;const d=C(a),g=R(d,{defaultCount:r.count??10,now:r.now,only:r.table===void 0?void 0:[r.table],seed:r.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const b of f)u.push(JSON.stringify({doc:b,table:h},N));const i=u.length>0?`${u.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await B(r,s);return w!==void 0?w:P(i,s,e,r)},W=z(async({cwd:r,logger:e,options:t})=>({code:(await
|
|
3
|
+
`:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await B(r,s);return w!==void 0?w:P(i,s,e,r)},W=z(async({cwd:r,logger:e,options:t})=>({code:(await G({batchSize:t.batchSize,count:t.count,cwd:r,dryRun:t.dryRun===!0,logger:e,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:A({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{W as execute,G as runSeedCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as d}from"node:fs";import{join as m}from"node:path";import{runCodegen as w}from"@lunora/codegen";import{r as u}from"../packem_shared/api-spec-BENwiyUa.mjs";import{c as y}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{i as v}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{M as $,P as k}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{i as j,r as P,d as U,s as x}from"../packem_shared/output-format-D7cKB-O5.mjs";import{k as E}from"../packem_shared/schema-drift-gate-CpqG-xP4.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{validateWranglerProject as D}from"@lunora/config/cloudflare";const T=async(r,o)=>{if(!d(m(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const e=$(k(r),"tsc",["--noEmit","-p","tsconfig.json"]),t=await o({args:e.args,command:e.command,cwd:r});return t.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(t.code)}`}},R="/_lunora/health",p=r=>(r.endsWith("/")?r.slice(0,-1):r)+R,C=async(r,o)=>{const e=p(r);let t;try{t=await o(e)}catch(a){const i=a instanceof Error?a.message:String(a);return{error:`health probe failed: could not reach ${e} (${i})`}}return t.ok?{}:{error:`health probe failed: ${e} returned HTTP ${String(t.status)}`}},W=async(r,o)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const e=await C(r.healthUrl,r.healthFetch??(t=>fetch(t)));if(e.error===void 0){o.success(`verify: health probe ok (${p(r.healthUrl)})`);return}return e.error},A=(r,o,e,t)=>{if(o.length===0&&e.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:t};if(e.length>0){r.warn("verify: warnings:");for(const a of e)r.warn(` - ${a}`)}if(o.length>0){r.error("verify: errors:");for(const a of o){r.error(` - ${a}`);const i=y(a);i!==void 0&&r.error(i)}return{code:1,errors:o,warnings:e,wranglerPath:t}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:e,wranglerPath:t}},F=async r=>{const o=r.cwd??process.cwd(),e=x(r.format,r.logger),t=j("verify",r.format);if(t!==void 0)return r.logger.error(t),{code:1,error:t,errors:[],warnings:[],wranglerPath:void 0};const a=D({projectRoot:o}),i=[...a.report.errors],l=[...a.report.warnings];try{const n=S(o,r.target);if(n.target===void 0){const c=n.error??"unknown deploy target";return e.error(c),{code:1,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const s=w({apiSpec:r.apiSpec,dryRun:!0,projectRoot:o,target:n.target}),h=E({allowDrift:r.allowSchemaDrift===!0,codegen:s,logger:e,readOnly:!0});h.blocked&&i.push(h.reason)}catch(n){const s=n instanceof Error?n.message:String(n);i.push(`codegen failed: ${s}`)}if(r.typecheck!==!1){const n=await T(o,r.spawner??b);n.error!==void 0&&i.push(n.error),n.warning!==void 0&&l.push(n.warning)}const f=await W(r,e);f!==void 0&&i.push(f);const g=A(e,i,l,a.wranglerPath);return P(r.format)&&U(g),g},L=v(async({cwd:r,logger:o,options:e})=>({code:(await F({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:u(e.apiSpec),cwd:r,format:e.format,healthUrl:e.healthUrl,logger:o,target:e.target,typecheck:e.typecheck===!1?!1:void 0})).code}));export{L as execute,F as runVerifyCommand};
|
|
@@ -1,2 +1,7 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)
|
|
1
|
+
import{writeFileSync as $,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as D,d as M,s as F,r as N}from"../packem_shared/output-format-D7cKB-O5.mjs";import{o as g}from"../packem_shared/cli-BxL0WCh4.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(r,e)=>r.length>=e?r:r+" ".repeat(e-r.length),C=r=>`${r.id} (${r.visibility} ${r.kind})`,m=r=>{let e=0;for(const o of r)e=Math.max(e,o.id.length);return e},p=(r,e)=>` ${u(String(r.score),3)} ${l[r.coverage]} ${u(r.id,e)} ${r.visibility} ${r.kind}`,E=r=>{if(!r.comparable)return[` baseline not comparable (${r.reason}) — regenerate it; this run cannot verify anything`];if(!r.regressed)return[` no regression against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];const e=[` REGRESSED against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];for(const o of r.dropped)e.push(` ${o.id}: ${String(o.before)} → ${String(o.after)}`);for(const o of r.newFailing)e.push(` ${o}: now failing`);for(const o of r.worsened)e.push(` ${o}: more findings than the baseline`);return r.projectRegressed&&e.push(" project: new schema/config rules fired"),e},J=(r,e)=>{const o=r.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),n=m(o),t=[`advisor health ${String(r.score)}/100 — ${r.grade}`,` ${String(r.summary.clean)} clean · ${String(r.summary.warned)} warned · ${String(r.summary.failing)} failing · ${String(r.summary.exempt)} exempt (${String(r.summary.procedures)} procedures, ${String(r.summary.rulesFired)} rules fired)`];return r.project.checks.length>0&&t.push("",` project ${String(r.project.score)}/100 — ${r.project.checks.map(i=>i.name).join(", ")}`),o.length>0&&t.push("",...o.map(i=>p(i,n)),""," run with --all for every procedure, or --entry <file#export> for one"),e!==void 0&&t.push("",...E(e)),t.join(`
|
|
2
|
+
`)},O=r=>r.coverage==="exempt"?[` exempt: ${r.exemptReason===void 0||r.exemptReason===""?"no reason given":r.exemptReason}`]:r.checks.map(e=>{const o=e.occurrences>1?`, ×${String(e.occurrences)}`:"";return` ${e.name} (−${String(e.weight)}${o})`}),B=r=>{const e=new Map;for(const o of r){const n=e.get(o.file);n===void 0?e.set(o.file,[o]):n.push(o)}return[...e].toSorted(([o],[n])=>y(o,n))},P=r=>{const e=m(r.procedures),o=[`advisor health ${String(r.score)}/100 — ${r.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[n,t]of B(r.procedures)){o.push("",` ${n}`);for(const i of t)o.push(p(i,e),...O(i))}return o.join(`
|
|
3
|
+
`)},T=(r,e)=>{const o=r.procedures.find(t=>t.id===e);if(o===void 0){const t=r.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${e} in the map. Known ids:`,...t,r.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
|
+
`)}const n=[`${C(o)} — ${String(o.score)}/100, ${o.coverage}`,` weight in the global mean: ${String(o.weight)}`];if(o.checks.length===0)return n.push(""," no rule fired"),n.join(`
|
|
5
|
+
`);n.push(""," rules fired:");for(const t of o.checks)n.push(` [${t.level}] ${t.name} −${String(t.weight)}${t.occurrences>1?` (×${String(t.occurrences)})`:""}`);return n.join(`
|
|
6
|
+
`)},q=new Date(0).toISOString(),f=(r,e)=>w(e)?e:b(r,e),G=r=>{if(r===void 0)return{value:void 0};if(r===null||r==="")return{error:"--min-score needs a value between 0 and 100"};const e=Number(r);return Number.isFinite(e)&&e>=0&&e<=100?{value:e}:{error:"--min-score must be a number between 0 and 100"}},H=(r,e,o)=>{const n=f(e,o===null||o===""?g:o);if(!v(n))return{error:`baseline not found at ${n} — generate one with \`lunora advisor\` and commit it`};const t=j(JSON.parse(S(n,"utf8")));return t===void 0?{error:`baseline at ${n} is malformed — regenerate it with \`lunora advisor\``}:{comparison:R(r,t)}},I=r=>`baseline is not comparable (${r}) — regenerate it; this run verified nothing`,K=(r,e,o)=>e.entry!==void 0?T(r,e.entry):e.all===!0?P(r):J(r,o),L=r=>{const e=r.cwd??process.cwd(),o=N(r.format),n=F(r.format,r.logger),t=D("advisor",r.format);if(t!==void 0)return r.logger.error(t),{error:t};const i=G(r.minScore);if("error"in i)return r.logger.error(i.error),{error:i.error};const{advisorContext:d,advisories:h}=k({dryRun:!0,projectRoot:e});if(d===void 0){const s="advisor evidence unavailable — codegen ran with linting disabled";return r.logger.error(s),{error:s}}const c=x(d.procedureProtections??[],h,{generatedAt:r.generatedAt??q}),a={map:c};if(r.baseline!==void 0){const s=H(c,e,r.baseline);if("error"in s)return r.logger.error(s.error),{...a,error:s.error};a.comparison=s.comparison,s.comparison.comparable||r.logger.error(I(s.comparison.reason))}if(r.write!==!1){const s=f(e,r.out??g);$(s,`${JSON.stringify(c,void 0,4)}
|
|
7
|
+
`,"utf8"),a.written=s}return a.belowMinScore=i.value!==void 0&&c.score<i.value,a.belowMinScore&&n.error(`advisor score ${String(c.score)} is below the required ${String(i.value)}`),o?(M(a),a):(n.info(K(c,r,a.comparison)),a.written!==void 0&&n.success(`wrote ${a.written}`),a)},z=r=>r.error!==void 0||r.belowMinScore===!0?!0:r.comparison!==void 0&&(!r.comparison.comparable||r.comparison.regressed),_=A(({cwd:r,logger:e,options:o})=>{const n=L({all:o.all,baseline:o.baseline,cwd:r,entry:o.entry,format:o.format,logger:e,minScore:o.minScore,out:o.out,write:o.write});return{code:z(n)?1:0}});export{_ as execute,L as runAdvisorCommand};
|
|
@@ -1,99 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
|
|
3
|
-
Install it in your project:
|
|
4
|
-
|
|
5
|
-
pnpm add -D ${n}`)}return a(e)},j=e=>{const n=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(n==="postgres"||n==="postgresql")return"postgres";if(n==="mysql"||n==="mariadb")return"mysql";throw new w("INTERNAL",`Unrecognised database URL scheme \`${n}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},H=e=>{try{const n=new URL(e).pathname.replace(Y,"");return n===""?void 0:decodeURIComponent(n)}catch{return}},J=async(e,n,t,a=process.cwd())=>{if(n==="postgres"){const o=R("pg","pg",a).Client,c=new o({connectionString:e});return await c.connect(),{close:async()=>{await c.end()},execute:async(m,d)=>(await c.query(m,[...d])).rows,schema:t??"public"}}const s=R("mysql2/promise","mysql2",a).createConnection,r=await s(e),i=t??H(e);if(i===void 0)throw new w("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await r.end()},execute:async(o,c)=>{const[m]=await r.execute(o,[...c]);return Array.isArray(m)?m:[]},schema:i}},h=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()"},P={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()"},N=(e,n)=>{const t=(n==="postgres"?W:P)[e.dataType],a=e.references===void 0?t:`v.id(${JSON.stringify(e.references.table)})`;let s=a??"v.any()";for(let r=0;r<e.arrayDepth;r+=1)s=`v.array(${s})`;return e.nullable&&(s=`v.optional(${s})`),{expression:s,known:a!==void 0}},M=/^[A-Z_$][\w$]*$/i,K=/[^\dA-Z]+(.)?/gi,Q=/^\d+/,G=/[^\w-]/g,z=/[\u003C\u003E\u002F\u2028\u2029]/g,X={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},b=e=>JSON.stringify(e).replaceAll(z,n=>X[n]??n),$=e=>M.test(e)?e:b(e),Z=e=>M.test(e)?`.${e}`:`[${b(e)}]`,I=e=>e.replaceAll("*/",String.raw`*\/`),V=e=>{const n=e.replaceAll(G,"_");return n===""?"table":n},ee=e=>{const n=e.replaceAll(K,(t,a)=>a?.toUpperCase()??"").replace(Q,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(n=>!h.has(n.name)),te=e=>{const n=new Set(e.primaryKey);for(const t of e.indexes)for(const a of t.columns)n.add(a);for(const t of e.columns)t.references!==void 0&&n.add(t.name);return[...n].filter(t=>!h.has(t))},D=(e,n,t,a)=>e.references===void 0||n.has(e.references.table)?e:(a.push(`${t}.${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}),ne=(e,n,t,a)=>{const s=[];for(const i of e.columns){if(h.has(i.name)){a.push(`${e.name}.${i.name}: skipped — \`${i.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const o=D(i,t,e.name,a),{expression:c,known:m}=N(o,n);!m&&o.references===void 0&&(a.push(`${e.name}.${i.name}: no mapping for SQL type \`${i.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${I(i.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${$(i.name)}: ${c},`)}const r=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(i=>!h.has(i))){const i=e.primaryKey.map(o=>b(o)).join(", ");r.push(` .index(${b(`by_${e.primaryKey.join("_")}`)}, [${i}], { unique: true })`)}for(const i of e.indexes){const o=i.columns.filter(d=>!h.has(d));if(o.length===0)continue;const c=o.map(d=>b(d)).join(", "),m=i.unique?", { unique: true }":"";r.push(` .index(${b(i.name)}, [${c}]${m})`)}return` ${$(e.name)}: defineTable({
|
|
6
|
-
${s.join(`
|
|
7
|
-
`)}
|
|
8
|
-
})
|
|
9
|
-
${r.join(`
|
|
10
|
-
`)},`},ae=(e,n,t)=>{const a=new Set(e.tables.map(r=>r.name)),s=e.tables.map(r=>ne(r,e.dialect,a,t)).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 "${n.serverImport}";
|
|
21
|
-
|
|
22
|
-
export default defineSchema({
|
|
23
|
-
${s}
|
|
24
|
-
});
|
|
25
|
-
`},re=(e,n,t,a=new Set([e.name]),s=[])=>{const r=ee(e.name),i=te(e),o=new Map(C(e).map(l=>[l.name,l])),c=i.map(l=>{const g=o.get(l);if(g===void 0)return;const p=D({...g,nullable:!1},a,e.name,[]),{expression:E,known:A}=N(p,n);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${g.dataType}\`).`),` ${$(l)}: ${E},`}).filter(l=>l!==void 0),m=[b("_creationTime"),...i.map(l=>b(l))].join(", "),d=`ctx.db${Z(e.name)}`;return`/**
|
|
26
|
-
* Generated by \`lunora introspect\` for the \`${I(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 "${t.serverImport}";
|
|
34
|
-
|
|
35
|
-
import type { Doc } from "./_generated/dataModel";
|
|
36
|
-
import { c } from "./_generated/server";
|
|
37
|
-
|
|
38
|
-
const ${r}List = defineListArgs<Doc<${b(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(${r}List.args).query(({ args, ctx }) => ${d}.findMany(${r}List.toQueryArgs(args)));
|
|
51
|
-
|
|
52
|
-
export const get = c.query.input({ id: v.id(${b(e.name)}) }).query(({ args, ctx }) => ${d}.get(args.id));
|
|
53
|
-
`},se=(e,n)=>{const t=[],a=new Set(e.tables.map(r=>r.name)),s=[{contents:ae(e,n,t),path:"schema.ts"}];if(n.procedures){const r=new Map([["schema","the generated schema module"]]);for(const i of e.tables){if(C(i).length===0){t.push(`${i.name}: no usable columns — procedure module skipped.`);continue}const o=V(i.name);o!==i.name&&t.push(`${i.name}: written as \`${o}.ts\` — the table name isn't usable as a filename.`);const c=r.get(o);if(c!==void 0){t.push(`${i.name}: procedure module skipped — its filename \`${o}.ts\` collides with table \`${c}\`.`);continue}r.set(o,i.name),s.push({contents:re(i,e.dialect,n,a,t),path:`${o}.ts`})}}return{files:s,warnings:t}},_=/^[A-Z_$][\w$]*$/i,ie=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,oe=(e,n,t)=>{const a=[],s=new Set(n?.columns.map(r=>r.name));for(const r of e.columns){if(h.has(r.name)||s.has(r.name))continue;if(!_.test(r.name)){t.warnings.push(`${e.name}.${r.name}: skipped — column names must be bare identifiers to merge.`);continue}const i=r.references!==void 0&&!t.present.has(r.references.table),{expression:o}=N(i?{...r,references:void 0}:r,t.dialect);a.push({column:r.name,kind:"addOptionalColumn",table:e.name,validator:ie(o)}),!r.nullable&&n!==void 0&&t.warnings.push(`${e.name}.${r.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return a},ce=(e,n,t)=>{const a=[],s=new Set(n?.indexes.map(r=>r.name));for(const r of e.indexes){const i=r.columns.filter(o=>!h.has(o));if(!(s.has(r.name)||i.length===0)){if(!_.test(r.name)||!i.every(o=>_.test(o))){t.push(`${e.name}: index \`${r.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}a.push({fields:i,kind:"addIndex",name:r.name,table:e.name,...r.unique?{unique:!0}:{}})}}return a},me=(e,n,t)=>{const a=[],s=[],r=new Map(n.map(o=>[o.name,o])),i=new Set([...r.keys(),...e.tables.map(o=>o.name)]);for(const o of e.tables){if(!_.test(o.name)){s.push(`${o.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=r.get(o.name);c===void 0&&a.push({global:{backend:"hyperdrive"},kind:"addTable",table:o.name}),a.push(...oe(o,c,{dialect:t,present:i,warnings:s}),...ce(o,c,s))}return{edits:a,warnings:s}},le=(e,n,t)=>{const a=U(e);if(!a.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${a.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=me(n,a.tables,t),r=[...s.warnings];let i=e,o=0;for(const c of s.edits){const m=F(i,c);m.ok?(i=m.text,o+=1):r.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:o,warnings:r,...o===0?{}:{text:i}}},u=(e,n)=>{const t=e[n]??e[n.toLowerCase()]??e[n.toUpperCase()];return typeof t=="string"?t:typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):""},ue=`
|
|
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`,de=`
|
|
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`,pe=`
|
|
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'`,ge=`
|
|
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`,be=`
|
|
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`,fe=`
|
|
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`,he=`
|
|
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`,ve=`
|
|
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`,y=e=>{const n=new Map;for(const t of e){const a=u(t,"table_name"),s=n.get(a);s===void 0?n.set(a,[t]):s.push(t)}return n},ye=(e,n)=>{const t=u(e,"data_type").toLowerCase();if(n!=="postgres")return{arrayDepth:0,dataType:t};const a=u(e,"udt_name").toLowerCase();return t==="array"&&a.startsWith("_")?{arrayDepth:1,dataType:a.slice(1)}:{arrayDepth:0,dataType:a===""?t:a}},_e=(e,n)=>{const t=new Map;for(const a of e){const s=u(a,"index_name"),r=n==="postgres"?u(a,"is_unique")==="true":u(a,"NON_UNIQUE")==="0",i=t.get(s);i===void 0?t.set(s,{columns:[u(a,"column_name")],unique:r}):i.columns.push(u(a,"column_name"))}return[...t.entries()].map(([a,s])=>({columns:s.columns,name:a,unique:s.unique}))},Ee=async(e,n,t)=>{const a=n==="postgres",[s,r,i,o]=await Promise.all([e(a?ue:be,[t]),e(a?de:fe,[t]),e(a?pe:he,[t]),e(a?ge:ve,[t])]),c=y(r),m=y(i),d=y(o),l=[];for(const[g,p]of y(s)){const E=new Map((m.get(g)??[]).map(f=>[u(f,"column_name"),{column:u(f,"foreign_column"),table:u(f,"foreign_table")}])),A=p.map(f=>{const S=u(f,"column_name"),L=E.get(S);return{...ye(f,n),name:S,nullable:u(f,"is_nullable").toUpperCase()==="YES",...L===void 0?{}:{references:L}}});l.push({columns:A,indexes:_e(d.get(g)??[],n),name:g,primaryKey:(c.get(g)??[]).map(f=>u(f,"column_name"))})}return l.sort((g,p)=>g.name.localeCompare(p.name)),{dialect:n,tables:l}},Ae=e=>{try{const n=JSON.parse(O(v(e,"package.json"),"utf8"));return n.dependencies?.lunorash===void 0&&n.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},$e=async(e,n,t)=>{const a=v(n,e.path);return T(a)&&t.force!==!0?(t.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):t.dryRun===!0?(t.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
|
|
99
|
-
`).length)} lines)`),!1):(await k(n,{recursive:!0}),await x(a,e.contents,"utf8"),t.logger.info(`wrote lunora/${e.path}`),!0)},we=(e,n)=>{const t=n.tables;if(t===void 0||t.length===0)return e.tables;for(const a of t)e.tables.some(s=>s.name===a)||n.logger.warn(`--tables: no table named "${a}" exists in this schema — skipped.`);return e.tables.filter(a=>t.includes(a.name))},Ne=async(e,n,t,a)=>{const s=le(O(e,"utf8"),n,t);for(const r of s.warnings)a.logger.warn(r);return s.text===void 0?(a.logger.info("lunora/schema.ts is already up to date with the database."),!1):a.dryRun===!0?(a.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await x(e,s.text,"utf8"),a.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Se=async e=>{const n=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const t=e.connection===void 0?j(e.url):e.dialect??"postgres",a=e.connection??await J(e.url,t,e.schema,n);let s;try{s=await Ee(a.execute,t,a.schema)}finally{e.connection===void 0&&await a.close()}const r=we(s,e);if(r.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:i,warnings:o}=se({...s,tables:r},{procedures:e.procedures!==!1,serverImport:Ae(n)}),c=v(n,"lunora"),m=[],d=v(c,"schema.ts"),l=T(d)&&e.force!==!0,g=l?i.filter(p=>p.path!=="schema.ts"):i;l&&await Ne(d,{tables:r},t,e)&&m.push("schema.ts");for(const p of g)await $e(p,c,e)&&m.push(p.path);for(const p of o)e.logger.warn(p);return e.logger.info(`introspected ${String(r.length)} table(s) from ${t}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Ce=B(async({cwd:e,logger:n,options:t})=>({code:(await Se({cwd:e,dryRun:t.dryRun===!0,force:t.force===!0,logger:n,procedures:t.procedures!==!1,schema:t.schema,tables:t.tables===void 0?void 0:t.tables.split(",").map(a=>a.trim()),url:t.url??process.env.DATABASE_URL})).code}));export{Ce as execute,Ae as resolveServerImport,Se as runIntrospectCommand};
|
|
1
|
+
import{readLinkedProject as g,resolveDeployDriver as p}from"@lunora/config";import{i as f}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as v,P as h}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{createR2Sql as w}from"@lunora/bindings/r2sql";import{createPipelineLogReader as y}from"@lunora/runtime";const S=new Set(["debug","error","fatal","info","log","trace","warn"]),u=/^\d+$/,c=(r,o)=>{if(r===void 0)return;const t=r.trim();if(u.test(t))return Number(t);const e=Date.parse(t);if(Number.isNaN(e))throw new TypeError(`logs: invalid ${o} "${r}" — pass epoch-millis or an ISO 8601 date`);return e},_=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64url"),$=r=>{const o=r.trim();if(u.test(o))return{ts:Number(o)};let t;try{t=JSON.parse(Buffer.from(o,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof t!="object"||t===null||typeof t.ts!="number"||!Number.isFinite(t.ts))throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:e}=t,i=t.seen,n=Array.isArray(i)?i.filter(s=>typeof s=="string"):void 0;return n!==void 0&&n.length>0?{seen:n,ts:e}:{ts:e}},d=(r,o)=>{if(r!==void 0){if(!S.has(r))throw new TypeError(`logs: invalid ${o} "${r}" — expected one of trace, debug, log, info, warn, error, fatal`);return r}},L=r=>{const o={},t=c(r.since,"--since");t!==void 0&&(o.sinceTs=t);const e=c(r.until,"--until");e!==void 0&&(o.untilTs=e);const i=d(r.level,"--level");i!==void 0&&(o.level=i);const n=d(r.minLevel,"--min-level");if(n!==void 0&&(o.minLevel=n),r.functionPrefix!==void 0&&(o.functionPathPrefix=r.functionPrefix),r.traceId!==void 0&&(o.traceId=r.traceId),r.shardKey!==void 0&&(o.shardKey=r.shardKey),r.userId!==void 0&&(o.userId=r.userId),r.limit!==void 0){const s=Number(r.limit);if(!Number.isFinite(s))throw new TypeError(`logs: invalid --limit "${r.limit}" — expected a number`);o.limit=s}return r.cursor!==void 0&&(o.cursor=$(r.cursor)),o},T=r=>{const o=new Date(r.ts).toISOString(),t=r.level.toUpperCase().padEnd(5);return`${o} ${t} ${r.functionPath} ${r.message}`},I=async r=>{const o=r.environment??process.env,t=o.R2_SQL_ACCOUNT_ID,e=o.R2_SQL_TOKEN,i=o.R2_SQL_BUCKET,n=[];if((t===void 0||t.length===0)&&n.push("R2_SQL_ACCOUNT_ID"),(e===void 0||e.length===0)&&n.push("R2_SQL_TOKEN"),(i===void 0||i.length===0)&&n.push("R2_SQL_BUCKET"),(r.table===void 0||r.table.length===0)&&n.push("--table"),n.length>0)return r.logger.error(`logs --durable: R2 SQL not configured (missing ${n.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:1,error:"not configured"};let s;try{s=L(r)}catch(a){return r.logger.error(a instanceof Error?a.message:String(a)),{code:1,error:"invalid option"}}const m=w({accountId:t,apiToken:e,bucket:i,fetch:r.fetch}),l=await y(m,{namespace:r.namespace,table:r.table}).query(s);for(const a of l.rows)process.stdout.write(`${r.ndjson===!0?JSON.stringify(a):T(a)}
|
|
2
|
+
`);return l.rows.length===0?r.logger.info("logs --durable: no matching log records"):l.nextCursor!==void 0&&r.logger.info(`logs --durable: more rows available — pass --cursor ${_(l.nextCursor)} for the next page`),{code:0,rows:l.rows}},N=new Set(["json","pretty"]),x=async r=>{const o=r.cwd??process.cwd();if(r.format!==void 0&&!N.has(r.format))return r.logger.error(`logs: unknown --format "${r.format}" — expected pretty | json`),{code:1,descriptor:void 0,error:"invalid format"};const t=r.env??g(o)?.env,e=p(r.target);if(e.toolchain===void 0)return r.logger.error(`logs: deploy target "${e.id}" has no command-line toolchain`),{code:1,descriptor:void 0,error:"no toolchain"};const i=e.toolchain.tail({environment:t,format:r.format,search:r.search,status:r.status,temporary:r.temporary,worker:r.worker}),n=v(h(o),i.tool,i.args),s={args:n.args,command:n.command,cwd:o};return r.logger.info(`tailing logs via ${s.command} ${s.args.join(" ")}`),{code:(await(r.spawner??b)(s)).code,descriptor:s}},Q=f(({argument:r,cwd:o,logger:t,options:e})=>e.durable===!0?I({cursor:e.cursor,functionPrefix:e.functionPrefix,level:e.level,limit:e.limit,logger:t,minLevel:e.minLevel,namespace:e.namespace,ndjson:e.ndjson===!0,shardKey:e.shardKey,since:e.since,table:e.table,traceId:e.traceId,until:e.until,userId:e.userId}):x({cwd:o,env:e.env,format:e.format,logger:t,search:e.search,status:e.status,target:e.target,temporary:e.temporary===!0,worker:r[0]}));export{Q as execute,x as runLogsCommand};
|