@lunora/cli 1.0.0-alpha.131 → 1.0.0-alpha.133
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/README.md +1 -1
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +36 -7
- package/dist/index.d.ts +36 -7
- 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/handler13.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +1 -1
- package/dist/packem_chunks/handler2.mjs +2 -2
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler22.mjs +1 -1
- package/dist/packem_chunks/handler23.mjs +1 -99
- package/dist/packem_chunks/handler24.mjs +99 -11
- package/dist/packem_chunks/handler25.mjs +11 -0
- package/dist/packem_chunks/handler3.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +1 -1
- package/dist/packem_chunks/handler6.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +3 -8
- 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 +68 -73
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +1 -1
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/COMMANDS-BEkrtuj_.mjs +1 -0
- package/dist/packem_shared/advisory-gate-yaOOyUQl.mjs +1 -0
- package/dist/packem_shared/cli-Cmbw5lEB.mjs +3 -0
- package/dist/packem_shared/commands-BvfzxKAa.mjs +19 -0
- package/dist/packem_shared/createRecordingSpawner-SKs4R1fc.mjs +1 -0
- package/dist/packem_shared/detect-package-manager-D9r2z_X6.mjs +1 -0
- package/dist/packem_shared/{post-codegen-hook-CjhP1OmV.mjs → post-codegen-hook-reEtIN59.mjs} +1 -1
- package/dist/packem_shared/resolve-target-CeiNrCAx.mjs +1 -0
- package/dist/packem_shared/runAddCommand-oQMYPkp6.mjs +1 -0
- package/dist/packem_shared/{storage-BazhWFmM.mjs → storage-CSzKwh4L.mjs} +1 -1
- package/dist/packem_shared/wrangler-secrets-DzYgUxU-.mjs +1 -0
- package/package.json +12 -12
- package/dist/packem_shared/COMMANDS-CCuhsVyI.mjs +0 -1
- package/dist/packem_shared/cli-0uJWyeda.mjs +0 -3
- package/dist/packem_shared/commands-C5pu77HK.mjs +0 -19
- package/dist/packem_shared/createRecordingSpawner-ByIqBepG.mjs +0 -1
- package/dist/packem_shared/detect-package-manager-C4aS7HE4.mjs +0 -1
- package/dist/packem_shared/resolve-target-vxaXHmvg.mjs +0 -1
- package/dist/packem_shared/runAddCommand-CuvJ0l7a.mjs +0 -1
- package/dist/packem_shared/wrangler-secrets-DHpbsDN9.mjs +0 -1
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
</a>
|
|
8
8
|
|
|
9
|
-
<h3 align="center">The Lunora CLI: init, dev, deploy, codegen,
|
|
9
|
+
<h3 align="center">The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands</h3>
|
|
10
10
|
|
|
11
11
|
<!-- END_PACKAGE_OG_IMAGE_PLACEHOLDER -->
|
|
12
12
|
|
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{f as s}from"./packem_shared/cli-Cmbw5lEB.mjs";try{const r=await s();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,10 +1,10 @@
|
|
|
1
|
-
import { CodegenOptions, SchemaIR } from '@lunora/codegen';
|
|
1
|
+
import { CodegenOptions, Finding, SchemaIR } from '@lunora/codegen';
|
|
2
2
|
import '@visulima/cerebro';
|
|
3
3
|
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets } from '@lunora/config';
|
|
4
4
|
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
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';
|
|
6
6
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
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
|
+
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
8
8
|
type CommandName = (typeof COMMANDS)[number];
|
|
9
9
|
declare const VERSION: string;
|
|
10
10
|
interface RunCliOptions {
|
|
@@ -77,7 +77,7 @@ interface CodegenCommandOptions {
|
|
|
77
77
|
interface CodegenCommandResult {
|
|
78
78
|
advisories: ReadonlyArray<{
|
|
79
79
|
detail: string;
|
|
80
|
-
level:
|
|
80
|
+
level: Finding["level"];
|
|
81
81
|
name: string;
|
|
82
82
|
remediation: string;
|
|
83
83
|
}>;
|
|
@@ -187,9 +187,20 @@ interface SpawnDescriptor {
|
|
|
187
187
|
* Capture the child's stdout (in addition to streaming it to the parent), so
|
|
188
188
|
* the caller can parse it — used by `deploy` to read the deployed URL from
|
|
189
189
|
* `wrangler deploy` output. Each chunk is still teed to the parent's stdout
|
|
190
|
-
* so the user sees live progress. Mutually exclusive with `stdoutToStderr
|
|
190
|
+
* so the user sees live progress. Mutually exclusive with `stdoutToStderr`
|
|
191
|
+
* and `captureStdoutSilently`.
|
|
191
192
|
*/
|
|
192
193
|
captureStdout?: boolean;
|
|
194
|
+
/**
|
|
195
|
+
* Capture the child's stdout WITHOUT teeing it to the parent's stdout —
|
|
196
|
+
* for output that is parsed, never displayed (e.g. `wrangler secret list
|
|
197
|
+
* --format json`). Unlike `captureStdout`, nothing is written to
|
|
198
|
+
* `process.stdout`, so it can't interleave with — and corrupt — a
|
|
199
|
+
* caller's own stdout (notably `lunora deploy --format json`, which must
|
|
200
|
+
* emit exactly one JSON document). Mutually exclusive with `captureStdout`
|
|
201
|
+
* and `stdoutToStderr`.
|
|
202
|
+
*/
|
|
203
|
+
captureStdoutSilently?: boolean;
|
|
193
204
|
command: string;
|
|
194
205
|
cwd?: string;
|
|
195
206
|
env?: Readonly<Record<string, string>>;
|
|
@@ -211,7 +222,7 @@ interface SpawnResult {
|
|
|
211
222
|
code: number;
|
|
212
223
|
/** The captured stderr, present only when the descriptor set `captureStderr`. */
|
|
213
224
|
stderr?: string;
|
|
214
|
-
/** The captured stdout, present only when the descriptor set `captureStdout`. */
|
|
225
|
+
/** The captured stdout, present only when the descriptor set `captureStdout` or `captureStdoutSilently`. */
|
|
215
226
|
stdout?: string;
|
|
216
227
|
}
|
|
217
228
|
/**
|
|
@@ -358,6 +369,16 @@ interface DeployCommandOptions {
|
|
|
358
369
|
secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
|
|
359
370
|
skipCodegen?: boolean;
|
|
360
371
|
spawner?: Spawner;
|
|
372
|
+
/**
|
|
373
|
+
* Fail the deploy when codegen reports an ERROR-level advisory. Same
|
|
374
|
+
* option `lunora codegen` exposes as `--no-strict-advisories`; defaults to
|
|
375
|
+
* CI detection (on in CI, off locally) so a legitimately-partial target
|
|
376
|
+
* can still be shipped interactively. Does NOT gate platform diagnostics
|
|
377
|
+
* (`platform_unsupported_feature` / `platform_unknown_target`), which
|
|
378
|
+
* always block — those mean the emitted `ctx.*` surface does not match
|
|
379
|
+
* what the target can serve, not merely a style nit.
|
|
380
|
+
*/
|
|
381
|
+
strictAdvisories?: boolean;
|
|
361
382
|
/**
|
|
362
383
|
* Deploy target. Falls back to `"target"` in `lunora.json`, then
|
|
363
384
|
* `"cloudflare"`, which selects the wrangler
|
|
@@ -383,6 +404,14 @@ interface DeployCommandResult {
|
|
|
383
404
|
descriptor: SpawnDescriptor | undefined;
|
|
384
405
|
/** Set when the run aborted before reaching the wrangler invocation. */
|
|
385
406
|
error?: string;
|
|
407
|
+
/**
|
|
408
|
+
* The `.dev.vars`-shaped filename (never a full path, never a value) a
|
|
409
|
+
* secret minted during this run was recorded into, when the missing-
|
|
410
|
+
* secret gate minted one — `.dev.vars` for the default environment, or a
|
|
411
|
+
* `.dev.vars.<env>` sibling for an explicit `--env`. `undefined` when
|
|
412
|
+
* nothing was minted this run.
|
|
413
|
+
*/
|
|
414
|
+
mintedSecretsFile?: string;
|
|
386
415
|
/** The schema-drift gate verdict, when it ran (skipped on `--skip-codegen`). */
|
|
387
416
|
schemaDrift?: {
|
|
388
417
|
blocked: boolean;
|
|
@@ -608,11 +637,11 @@ declare const runDevCommand: (options: DevCommandOptions) => Promise<{
|
|
|
608
637
|
code: number;
|
|
609
638
|
plan: DevCommandPlan;
|
|
610
639
|
}>;
|
|
611
|
-
/** Supported CI providers. */
|
|
612
|
-
type CiProvider = "github" | "gitlab";
|
|
613
640
|
type PackageManager = "pnpm" | "npm" | "yarn" | "bun";
|
|
614
641
|
/** True when `manager` is on PATH — probed by running `<manager> --version`. Injectable for tests. */
|
|
615
642
|
type PackageManagerProbe = (manager: PackageManager) => boolean;
|
|
643
|
+
/** Supported CI providers. */
|
|
644
|
+
type CiProvider = "github" | "gitlab";
|
|
616
645
|
/** The per-framework auth-UI registry items (`auth-ui` resolves to one of these). */
|
|
617
646
|
type AuthUiItem = "auth-ui-angular" | "auth-ui-react" | "auth-ui-solid" | "auth-ui-svelte" | "auth-ui-vue";
|
|
618
647
|
/** A registry item a feature can install. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { CodegenOptions, SchemaIR } from '@lunora/codegen';
|
|
1
|
+
import { CodegenOptions, Finding, SchemaIR } from '@lunora/codegen';
|
|
2
2
|
import '@visulima/cerebro';
|
|
3
3
|
import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets } from '@lunora/config';
|
|
4
4
|
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
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';
|
|
6
6
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
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
|
+
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
8
8
|
type CommandName = (typeof COMMANDS)[number];
|
|
9
9
|
declare const VERSION: string;
|
|
10
10
|
interface RunCliOptions {
|
|
@@ -77,7 +77,7 @@ interface CodegenCommandOptions {
|
|
|
77
77
|
interface CodegenCommandResult {
|
|
78
78
|
advisories: ReadonlyArray<{
|
|
79
79
|
detail: string;
|
|
80
|
-
level:
|
|
80
|
+
level: Finding["level"];
|
|
81
81
|
name: string;
|
|
82
82
|
remediation: string;
|
|
83
83
|
}>;
|
|
@@ -187,9 +187,20 @@ interface SpawnDescriptor {
|
|
|
187
187
|
* Capture the child's stdout (in addition to streaming it to the parent), so
|
|
188
188
|
* the caller can parse it — used by `deploy` to read the deployed URL from
|
|
189
189
|
* `wrangler deploy` output. Each chunk is still teed to the parent's stdout
|
|
190
|
-
* so the user sees live progress. Mutually exclusive with `stdoutToStderr
|
|
190
|
+
* so the user sees live progress. Mutually exclusive with `stdoutToStderr`
|
|
191
|
+
* and `captureStdoutSilently`.
|
|
191
192
|
*/
|
|
192
193
|
captureStdout?: boolean;
|
|
194
|
+
/**
|
|
195
|
+
* Capture the child's stdout WITHOUT teeing it to the parent's stdout —
|
|
196
|
+
* for output that is parsed, never displayed (e.g. `wrangler secret list
|
|
197
|
+
* --format json`). Unlike `captureStdout`, nothing is written to
|
|
198
|
+
* `process.stdout`, so it can't interleave with — and corrupt — a
|
|
199
|
+
* caller's own stdout (notably `lunora deploy --format json`, which must
|
|
200
|
+
* emit exactly one JSON document). Mutually exclusive with `captureStdout`
|
|
201
|
+
* and `stdoutToStderr`.
|
|
202
|
+
*/
|
|
203
|
+
captureStdoutSilently?: boolean;
|
|
193
204
|
command: string;
|
|
194
205
|
cwd?: string;
|
|
195
206
|
env?: Readonly<Record<string, string>>;
|
|
@@ -211,7 +222,7 @@ interface SpawnResult {
|
|
|
211
222
|
code: number;
|
|
212
223
|
/** The captured stderr, present only when the descriptor set `captureStderr`. */
|
|
213
224
|
stderr?: string;
|
|
214
|
-
/** The captured stdout, present only when the descriptor set `captureStdout`. */
|
|
225
|
+
/** The captured stdout, present only when the descriptor set `captureStdout` or `captureStdoutSilently`. */
|
|
215
226
|
stdout?: string;
|
|
216
227
|
}
|
|
217
228
|
/**
|
|
@@ -358,6 +369,16 @@ interface DeployCommandOptions {
|
|
|
358
369
|
secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
|
|
359
370
|
skipCodegen?: boolean;
|
|
360
371
|
spawner?: Spawner;
|
|
372
|
+
/**
|
|
373
|
+
* Fail the deploy when codegen reports an ERROR-level advisory. Same
|
|
374
|
+
* option `lunora codegen` exposes as `--no-strict-advisories`; defaults to
|
|
375
|
+
* CI detection (on in CI, off locally) so a legitimately-partial target
|
|
376
|
+
* can still be shipped interactively. Does NOT gate platform diagnostics
|
|
377
|
+
* (`platform_unsupported_feature` / `platform_unknown_target`), which
|
|
378
|
+
* always block — those mean the emitted `ctx.*` surface does not match
|
|
379
|
+
* what the target can serve, not merely a style nit.
|
|
380
|
+
*/
|
|
381
|
+
strictAdvisories?: boolean;
|
|
361
382
|
/**
|
|
362
383
|
* Deploy target. Falls back to `"target"` in `lunora.json`, then
|
|
363
384
|
* `"cloudflare"`, which selects the wrangler
|
|
@@ -383,6 +404,14 @@ interface DeployCommandResult {
|
|
|
383
404
|
descriptor: SpawnDescriptor | undefined;
|
|
384
405
|
/** Set when the run aborted before reaching the wrangler invocation. */
|
|
385
406
|
error?: string;
|
|
407
|
+
/**
|
|
408
|
+
* The `.dev.vars`-shaped filename (never a full path, never a value) a
|
|
409
|
+
* secret minted during this run was recorded into, when the missing-
|
|
410
|
+
* secret gate minted one — `.dev.vars` for the default environment, or a
|
|
411
|
+
* `.dev.vars.<env>` sibling for an explicit `--env`. `undefined` when
|
|
412
|
+
* nothing was minted this run.
|
|
413
|
+
*/
|
|
414
|
+
mintedSecretsFile?: string;
|
|
386
415
|
/** The schema-drift gate verdict, when it ran (skipped on `--skip-codegen`). */
|
|
387
416
|
schemaDrift?: {
|
|
388
417
|
blocked: boolean;
|
|
@@ -608,11 +637,11 @@ declare const runDevCommand: (options: DevCommandOptions) => Promise<{
|
|
|
608
637
|
code: number;
|
|
609
638
|
plan: DevCommandPlan;
|
|
610
639
|
}>;
|
|
611
|
-
/** Supported CI providers. */
|
|
612
|
-
type CiProvider = "github" | "gitlab";
|
|
613
640
|
type PackageManager = "pnpm" | "npm" | "yarn" | "bun";
|
|
614
641
|
/** True when `manager` is on PATH — probed by running `<manager> --version`. Injectable for tests. */
|
|
615
642
|
type PackageManagerProbe = (manager: PackageManager) => boolean;
|
|
643
|
+
/** Supported CI providers. */
|
|
644
|
+
type CiProvider = "github" | "gitlab";
|
|
616
645
|
/** The per-framework auth-UI registry items (`auth-ui` resolves to one of these). */
|
|
617
646
|
type AuthUiItem = "auth-ui-angular" | "auth-ui-react" | "auth-ui-solid" | "auth-ui-svelte" | "auth-ui-vue";
|
|
618
647
|
/** A registry item a feature can install. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{p as o,i as n,f as a}from"./packem_shared/cli-Cmbw5lEB.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as i}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.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 D}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 F,renderAddColumn as L,renderCreateIndex as O,renderCreateTable as b,renderDropIndex as w,renderDropTable as B,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as G}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as Q,defaultSpawner as V}from"./packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{default as q}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as K,REQUIRED_FLAG as Y,validateWranglerProject as Z,validateWranglerConfig as k}from"@lunora/config/cloudflare";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{I as $,F as rr,E as er}from"./packem_shared/commands-BvfzxKAa.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,K as REQUIRED_COMPATIBILITY_DATE,Y as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,Q as createRecordingSpawner,V as defaultSpawner,F as diffSnapshots,M as insertSchemaExtension,h as pail,q as parseManifest,s as planDevCommand,L as renderAddColumn,O as renderCreateIndex,b as renderCreateTable,w as renderDropIndex,B 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,i as runImportCommand,g as runInitCommand,R as runMigrateGenerateCommand,er as runRegistryViewCommand,D as runResetCommand,A as runRpcCommand,G as schemaIrToSnapshot,Z as validateWrangler,k as validateWranglerConfig,U as validatorKindToSqlType};
|
|
@@ -1 +1 @@
|
|
|
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
|
|
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 I,q as J}from"../packem_shared/storage-CSzKwh4L.mjs";import{I as K}from"../packem_shared/commands-BvfzxKAa.mjs";const P=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{}}},Q=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},V=async r=>{if(r.provider!==void 0&&r.provider!==""){const a=P(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)),X=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)},Y=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)},z=async(r,e)=>r.kind==="auth"?[await V(e)]:r.kind==="auth-ui"?[await Q(e)]:r.kind==="email"?[q]:[r.item],E=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 z(a,r),s=[];if(o.includes("storage")){const t=await X(r);s.push(i=>G(i,t))}if(o.includes("mail")){const t=await Y(r);t!==void 0&&s.push(i=>I(i,t))}if(o.some(t=>t==="auth"||t.startsWith("auth-"))){const t=await Z(r);s.push(i=>J(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 K({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 E({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,E as runAddFeature};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{
|
|
1
|
+
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{d as u}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runExportCommand as d}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const a=p(({argument:r,cwd:t,logger:e,options:o})=>d({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{a as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as
|
|
1
|
+
import{i as d}from"../packem_shared/command-Bjv4VmYA.mjs";import{d as n}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runImportCommand as p}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const l=d(({argument:a,cwd:e,logger:r,options:o})=>{const t=a[0];return t?p({batchSize:o.batchSize,cwd:e,file:t,logger:r,prod:o.prod===!0,table:o.table,token:o.token,url:n({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,2 +1,2 @@
|
|
|
1
|
-
import{u as m}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as $}from"../packem_shared/command-Bjv4VmYA.mjs";import{
|
|
1
|
+
import{u as m}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as $}from"../packem_shared/command-Bjv4VmYA.mjs";import{d as S}from"../packem_shared/resolve-target-CeiNrCAx.mjs";const M="__lunora_admin__:getFunctionStats",y=10,v=/\/$/u,u=(o,e)=>({calls:o.calls,conflicts:o.conflicts??0,errors:o.errors,lastErrorMessage:o.lastErrorMessage,maxDurationMs:o.maxDurationMs,meanDurationMs:o.calls===0?0:o.totalDurationMs/o.calls,path:o.path,rate:e}),w=(o,e)=>{const t=o.filter(r=>(r.conflicts??0)>0).map(r=>u(r,r.calls===0?0:(r.conflicts??0)/r.calls)).toSorted((r,s)=>s.rate-r.rate||s.conflicts-r.conflicts).slice(0,e),i=o.filter(r=>r.errors>0).map(r=>u(r,r.calls===0?0:r.errors/r.calls)).toSorted((r,s)=>s.rate-r.rate||s.errors-r.errors).slice(0,e),n=o.map(r=>u(r,0)).toSorted((r,s)=>s.maxDurationMs-r.maxDurationMs).slice(0,e);return{errorHotspots:i,latencyOutliers:n,totalFunctions:o.length,writeContention:t}},p=o=>`${(o*100).toFixed(1)}%`,f=o=>o<1e3?`${Math.round(o).toString()}ms`:`${(o/1e3).toFixed(2)}s`,d=(o,e,t,i)=>[o,...e.length===0?[` ${t}`]:e.map(n=>` ${i(n)}`)],O=o=>{const e=t=>t.lastErrorMessage?` — ${t.lastErrorMessage}`:"";return[`Insights over ${o.totalFunctions.toString()} function${o.totalFunctions===1?"":"s"}`,"",...d("Write-conflict hot-spots (OCC contention — candidates for sharding):",o.writeContention,"none — no write conflicts observed",t=>`${t.path} ${t.conflicts.toString()}/${t.calls.toString()} calls (${p(t.rate)})`),"",...d("Error hot-spots:",o.errorHotspots,"none — no errors observed",t=>`${t.path} ${t.errors.toString()}/${t.calls.toString()} calls (${p(t.rate)})${e(t)}`),"",...d("Latency outliers (slowest single call):",o.latencyOutliers,"none — no functions have run",t=>`${t.path} max ${f(t.maxDurationMs)}, mean ${f(t.meanDurationMs)} over ${t.calls.toString()} calls`)].join(`
|
|
2
2
|
`)},N=o=>o===void 0||!Number.isFinite(o)||o<=0?y:Math.floor(o),x=async o=>{if(o.prod&&o.url===void 0)return o.logger.error("--prod requires an explicit --url (refusing to report from the implicit localhost worker)"),{code:1};const e=o.token??process.env.LUNORA_ADMIN_TOKEN;if(!e)return o.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN"),{code:1};const t=m(o.url,o.logger,o.cwd);if(t===void 0)return{code:1};const i=`${t.replace(v,"")}/_lunora/rpc`,n=globalThis.fetch;if(typeof n!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");const r={args:{},functionPath:M};o.shard!==void 0&&(r.shardKey=o.shard),o.logger.info(`POST ${i} -> insights`);const s=await n(i,{body:JSON.stringify(r),headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},method:"POST"}),a=await s.text();if(!s.ok)return o.logger.error(`insights failed: HTTP ${String(s.status)}: ${a}`),{code:1};let l;try{l=JSON.parse(a)}catch{return o.logger.error(`insights failed: worker returned non-JSON: ${a}`),{code:1}}const h=l.result??l,{functions:g}=h;if(!Array.isArray(g))return o.logger.error("insights failed: response carried no `functions` array"),{code:1};const c=w(g,N(o.limit));return o.logger.info(o.json?JSON.stringify(c,void 0,2):O(c)),{code:0,report:c}},k=$(({cwd:o,logger:e,options:t})=>{const i=t.limit===void 0?void 0:Number.parseInt(t.limit,10);return x({cwd:o,json:t.json,limit:i,logger:e,prod:t.prod,shard:t.shard,token:t.token,url:S({cwd:o,prod:t.prod===!0,url:t.url})})});export{w as buildInsightsReport,k as execute,O as formatInsightsReport,x as runInsightsCommand};
|
|
@@ -1 +1 @@
|
|
|
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 w}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{m as h}from"../packem_shared/post-codegen-hook-
|
|
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 w}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{m as h}from"../packem_shared/post-codegen-hook-reEtIN59.mjs";import{R as v}from"../packem_shared/schema-drift-gate-d12lMICD.mjs";import{validateWranglerProject as S}from"@lunora/config/cloudflare";const b=async(r,o,a=[],i)=>{const l={crons:a,projectRoot:r},n=p(i);try{const e=await n.infer(l),s=[e.shardNamespaces.length>0?`${String(e.shardNamespaces.length)} shard namespace(s)`:void 0,e.queues.length>0?`${String(e.queues.length)} queue(s)`:void 0,e.workflows.length>0?`${String(e.workflows.length)} workflow(s)`:void 0,e.containers.length>0?`${String(e.containers.length)} container(s)`:void 0,e.globalDatabase?"global database":void 0,e.objectStorage?"object storage":void 0,e.keyValueStore?"key-value store":void 0].filter(c=>c!==void 0);s.length>0&&o.info(`${n.name} target requires: ${s.join(", ")}`)}catch{}const t=await n.provision(l);t.changed&&o.success(`provisioned: ${t.added.join(", ")} → ${t.configPath??"wrangler.jsonc"}`);for(const e of t.warnings)o.warn(e)},$=async r=>{const o=r.cwd??process.cwd(),a=d(o,r.target);r.logger.info("running codegen");let i;try{i=g({apiSpec:r.apiSpec,projectRoot:o,target:a}),r.logger.success("codegen complete"),w(i.platformDiagnostics,r.logger)}catch(e){const s=e instanceof Error?e.message:String(e);return r.logger.error(f(e)),{code:1,error:`codegen failed: ${s}`,validation:{problems:[],wranglerPath:void 0}}}const l=await h({cwd:o,logger:r.logger,spawner:r.spawner});if(l.error!==void 0)return r.logger.error(l.error),{code:1,error:l.error,validation:{problems:[],wranglerPath:void 0}};const n=v({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"prepare",logger:r.logger,updateBaseline:r.updateSchemaBaseline===!0});if(n.blocked)return{code:1,error:"schema drift gate blocked prepare",schemaDrift:{blocked:!0,reason:n.reason},validation:{problems:[],wranglerPath:void 0}};await b(o,r.logger,i.cronTriggers,a);const t=S({projectRoot:o});if(t.problems.length>0){r.logger.error("wrangler.jsonc validation failed:");for(const e of t.problems)r.logger.error(` - ${e}`);return{code:1,error:"wrangler validation failed",validation:t}}return n.rebless?.(),r.logger.success("project is ready to deploy"),{code:0,validation:t}},x=u(({cwd:r,logger:o,options:a})=>$({allowSchemaDrift:a.allowSchemaDrift===!0,apiSpec:m(a.apiSpec),cwd:r,logger:o,target:a.target,updateSchemaBaseline:a.updateSchemaBaseline===!0}));export{x as execute,$ 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{I as c,E as f,F as a}from"../packem_shared/commands-BvfzxKAa.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,3 +1,3 @@
|
|
|
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{
|
|
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{d as A}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{i as F}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{runImportCommand as I}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.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)}},H=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
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)},V=z(async({cwd:r,logger:e,options:t})=>({code:(await H({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{V as execute,H as runSeedCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as p}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 $,
|
|
1
|
+
import{existsSync as p}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 $,l as j}from"../packem_shared/detect-package-manager-D9r2z_X6.mjs";import{i as k,r as P,d as U,s as x}from"../packem_shared/output-format-D7cKB-O5.mjs";import{R as E}from"../packem_shared/schema-drift-gate-d12lMICD.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{validateWranglerProject as D}from"@lunora/config/cloudflare";const R=async(r,o)=>{if(!p(m(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const e=$(j(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)}`}},T="/_lunora/health",d=r=>(r.endsWith("/")?r.slice(0,-1):r)+T,C=async(r,o)=>{const e=d(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 (${d(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=k("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,command:"verify",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 R(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,2 @@
|
|
|
1
|
-
import{mkdtempSync as p,rmSync as
|
|
2
|
-
`):F(
|
|
1
|
+
import{mkdtempSync as p,rmSync as l,existsSync as c,readdirSync as u,statSync as y}from"node:fs";import{tmpdir as g}from"node:os";import{join as f,relative as m}from"node:path";import{i as $}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as S,l as z}from"../packem_shared/detect-package-manager-D9r2z_X6.mjs";import{defaultSpawner as B}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";const w=t=>{const r=[],e=i=>{for(const o of u(i)){const s=f(i,o),n=y(s);n.isDirectory()?e(s):n.isFile()&&r.push({path:m(t,s),sizeBytes:n.size})}};return e(t),r},d=t=>t<1024?`${String(t)} B`:t<1024*1024?`${(t/1024).toFixed(1)} KiB`:`${(t/(1024*1024)).toFixed(2)} MiB`,h=t=>{const r=w(t),e=r.toSorted((o,s)=>s.sizeBytes-o.sizeBytes),i=r.reduce((o,s)=>o+s.sizeBytes,0);return{generatedFiles:r.filter(o=>o.path.includes("_generated")),outdir:t,topModules:e.slice(0,10),totalBytes:i,totalFiles:r.length}},F=(t,r)=>{if(r.info(`outdir: ${t.outdir}`),r.info(`total: ${String(t.totalFiles)} files, ${d(t.totalBytes)}`),t.topModules.length>0){r.info(""),r.info("top modules by size:");for(const e of t.topModules)r.info(` ${d(e.sizeBytes).padStart(10," ")} ${e.path}`)}if(t.generatedFiles.length>0){r.info(""),r.info(`_generated/ files: ${String(t.generatedFiles.length)}`);for(const e of t.generatedFiles)r.info(` ${d(e.sizeBytes).padStart(10," ")} ${e.path}`)}},v=async t=>{const r=t.cwd??process.cwd(),{logger:e}=t;let i,o,s=!1;if(t.inspectOnly)i=t.inspectOnly;else{i=p(f(g(),"lunora-analyze-")),s=!0;const n=S(z(r),"wrangler",["deploy","--dry-run","--outdir",i]);o={args:n.args,command:n.command,cwd:r},e.info(`analyze: building via ${o.command} ${o.args.join(" ")}`);const a=await(t.spawner??B)(o);if(a.code!==0)return e.error(`analyze: wrangler dry-run failed (exit ${String(a.code)})`),l(i,{force:!0,recursive:!0}),{code:a.code,descriptor:o,report:void 0}}try{if(!c(i))return e.error(`analyze: outdir not found at ${i}`),{code:1,descriptor:o,report:void 0};const n=h(i);return t.json?process.stdout.write(`${JSON.stringify(n,void 0,2)}
|
|
2
|
+
`):F(n,e),{code:0,descriptor:o,report:n}}finally{if(s&&c(i))try{l(i,{force:!0,recursive:!0})}catch{}}},k=$(({cwd:t,logger:r,options:e})=>v({cwd:t,json:e.json===!0,logger:r}));export{k as execute,v as runAnalyzeCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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-Cmbw5lEB.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
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
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
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(`
|
|
@@ -1,2 +1,2 @@
|
|
|
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,
|
|
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,l as h}from"../packem_shared/detect-package-manager-D9r2z_X6.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-SKs4R1fc.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
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};
|
|
@@ -1,99 +1 @@
|
|
|
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{readdirSync as E,lstatSync as x,existsSync as N}from"node:fs";import{join as p,basename as R}from"node:path";import{pathToFileURL as b}from"node:url";import{i as F}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as O,r as g,d as v,s as T}from"../packem_shared/output-format-D7cKB-O5.mjs";const h=".eval.ts",_=new Set([".git","_generated","dist","node_modules"]),$=(r,o=[])=>{let e;try{e=E(r)}catch{return o}for(const t of e){const n=p(r,t);let s;try{s=x(n)}catch{continue}if(s.isDirectory()){if(_.has(t))continue;$(n,o)}else s.isFile()&&t.endsWith(h)&&o.push(n)}return o.toSorted((t,n)=>t.localeCompare(n))},A=r=>typeof r=="object"&&r!==null&&typeof r.run=="function",S=r=>typeof r=="number"&&Number.isFinite(r)&&r>=0&&r<=1,C="evals",I='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',L=/unknown file extension ".ts"/i,y=r=>r instanceof Error?r.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:L.test(r.message):!1,m=r=>R(r,h),U=r=>({average:r.result?.average,error:r.error,items:r.result?.items,name:r.name,passed:r.passed,path:r.path,threshold:r.threshold}),w=r=>({code:r.code,error:r.error,evals:r.evals.map(o=>U(o))}),l=(r,o,e)=>{r.error(e);const t={code:1,error:e,evals:[]};return g(o)&&v(w(t)),t},k=(r,o,e)=>{if(!N(r))return e.info(`eval: no "${o}" directory — nothing to run`),[];const t=$(r);return t.length===0&&e.info(`eval: no ${h} files found under "${o}"`),t},D=async r=>{const o=(await import(b(r).href)).default;if(!A(o))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return o},H=async(r,o)=>{let e;try{e=await D(r)}catch(s){if(y(s))throw s;return{error:s instanceof Error?s.message:String(s),name:m(r),passed:!1,path:r}}const t=e.name??m(r);if(e.threshold!==void 0&&!S(e.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(e.threshold)}`,name:t,passed:!1,path:r};const n=e.threshold??o;try{const s=await e.run(),d=n===void 0||s.average>=n;return{name:t,passed:d,path:r,result:s,threshold:n}}catch(s){return{error:s instanceof Error?s.message:String(s),name:t,passed:!1,path:r,threshold:n}}},M=async(r,o)=>{const e=[];for(const t of r)e.push(await H(t,o));return e},j=r=>{if(r.error!==void 0)return`ERROR: ${r.error}`;const o=r.passed?"pass":"FAIL",e=r.result?.items.length??0;return`${o} (${String(e)} cases)`},J=r=>{if(r.length===0)return[];const o=Math.max(4,...r.map(t=>t.name.length)),e=[`${"NAME".padEnd(o)} SCORE THRESHOLD STATUS`];for(const t of r){const n=t.result===void 0?"—":t.result.average.toFixed(3),s=t.threshold===void 0?"—":t.threshold.toFixed(3);e.push(`${t.name.padEnd(o)} ${n.padEnd(6)} ${s.padEnd(9)} ${j(t)}`)}return e},W=async r=>{const o=r.cwd??process.cwd(),e=T(r.format,r.logger),t=O("eval",r.format);if(t!==void 0)return r.logger.error(t),{code:1,error:t,evals:[]};if(r.threshold!==void 0&&!S(r.threshold))return l(e,r.format,`eval: --threshold must be a number in [0, 1] — received "${String(r.threshold)}"`);const n=r.dir??C,s=p(o,n),d=k(s,n,e);let i;try{i=await M(d,r.threshold)}catch(a){if(!y(a))throw a;return l(e,r.format,I)}if(r.threshold!==void 0&&i.length===0){const a=`eval: --threshold ${String(r.threshold)} was set but 0 eval files were discovered under "${n}" — nothing was gated`;return l(e,r.format,a)}for(const a of J(i))e.info(a);const c=i.filter(a=>!a.passed),u=c.length>0?1:0;u===0?e.success(`eval: ${String(i.length)} eval(s) passed`):e.error(`eval: ${String(c.length)}/${String(i.length)} eval(s) failed`);const f={code:u,evals:i};return g(r.format)&&v(w(f)),f},B=F(async({cwd:r,logger:o,options:e})=>({code:(await W({cwd:r,dir:e.dir,format:e.format,logger:o,threshold:e.threshold})).code}));export{B as execute,W as runEvalCommand};
|