@lunora/codegen 1.0.0-alpha.102 → 1.0.0-alpha.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -7,6 +7,7 @@ export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, type Solution as LunoraSolu
7
7
  import { StudioFeaturesResult } from '@lunora/shard-engine';
8
8
  import { Schema } from '@lunora/server';
9
9
  import { JsonSchema } from '@lunora/values';
10
+ import { LanguageName } from 'quicktype-core';
10
11
  /**
11
12
  * The structural schema-snapshot format and its diff, shared by `@lunora/codegen`
12
13
  * (which builds snapshots from the parsed schema IR and gates deploys on the
@@ -3337,9 +3338,220 @@ declare const validatorIrToJsonSchema: (validator: ValidatorIR) => JsonSchema;
3337
3338
  * the contract; clients switch on `error.code`. Kept sorted for stable output.
3338
3339
  */
3339
3340
  declare const LUNORA_ERROR_CODES: ReadonlyArray<string>;
3341
+ /**
3342
+ * Language-agnostic half of SDK generation: turn an OpenRPC document
3343
+ * (`_generated/openrpc.json`, see {@link file://../openrpc.ts}) into the parsed
3344
+ * shape every per-language target renders from.
3345
+ *
3346
+ * Nothing here knows about a target language. A target supplies its own member
3347
+ * naming and templates (see {@link file://./targets}); everything that would
3348
+ * otherwise be re-derived per language — how a `functionPath` splits, which
3349
+ * runtime verb a kind maps to, whether a schema is real or the untyped
3350
+ * placeholder, how namespaces group and sort — lives here exactly once.
3351
+ *
3352
+ * That single-source rule is not stylistic. `paths.ts` documents the same
3353
+ * discipline for namespaces ("if these ever disagree, runtime dispatch silently
3354
+ * misses functions"), and the failure mode here is the same in a new costume: a
3355
+ * target that re-derives a model name renders an import pointing at a class
3356
+ * quicktype never emitted.
3357
+ *
3358
+ * Deriving names in one place is necessary but NOT sufficient, because only
3359
+ * half the decision is ours: quicktype chooses whether a predicted name becomes
3360
+ * a declared type, and different backends answer differently for the same
3361
+ * schema. {@link withDeclaredModels} reconciles the two halves before a target
3362
+ * renders anything.
3363
+ */
3364
+ /** One OpenRPC method as {@link file://../openrpc.ts} emits it. */
3365
+ interface OpenRpcMethod {
3366
+ name: string;
3367
+ params?: ReadonlyArray<{
3368
+ name: string;
3369
+ schema?: Record<string, unknown>;
3370
+ }>;
3371
+ result?: {
3372
+ name: string;
3373
+ schema?: Record<string, unknown>;
3374
+ };
3375
+ summary?: string;
3376
+ "x-lunora-function-kind"?: string;
3377
+ }
3378
+ /** The `_generated/openrpc.json` document. */
3379
+ interface OpenRpcDocument {
3380
+ info?: {
3381
+ title?: string;
3382
+ version?: string;
3383
+ };
3384
+ methods: ReadonlyArray<OpenRpcMethod>;
3385
+ }
3386
+ /** The runtime verbs a generated SDK can call. Mirrors the client transports. */
3387
+ type RuntimeVerb = "action" | "mutation" | "query";
3388
+ /** One RPC function, parsed and language-neutral. */
3389
+ interface SdkMethod {
3390
+ /** Generated args model name, or `undefined` when the function takes none. */
3391
+ argsType: string | undefined;
3392
+ /** Raw exported function name (`"list"`), before any naming convention. */
3393
+ functionName: string;
3394
+ /** The wire identifier (`"messages:list"`), emitted verbatim into calls. */
3395
+ functionPath: string;
3396
+ /** Raw file namespace (`"messages"`), before any naming convention. */
3397
+ namespace: string;
3398
+ /** Generated result model name, or `undefined` while the result is untyped. */
3399
+ resultType: string | undefined;
3400
+ /** Human summary for the doc comment. */
3401
+ summary: string;
3402
+ /** Which runtime verb this dispatches to. */
3403
+ verb: RuntimeVerb;
3404
+ }
3405
+ /** One namespace's functions, sorted. */
3406
+ interface SdkNamespace {
3407
+ methods: ReadonlyArray<SdkMethod>;
3408
+ /** Raw namespace (`"messages"`); a target applies its own casing. */
3409
+ name: string;
3410
+ }
3411
+ /**
3412
+ * True when a schema actually describes a shape.
3413
+ *
3414
+ * `openrpc.ts` emits a description-only placeholder for any function without a
3415
+ * declared `.output()` (the return type is TS-inferred and absent from the IR).
3416
+ * A placeholder must never become a generated model: quicktype would render an
3417
+ * empty type, and the surface would decode every response into it — silently
3418
+ * discarding the real payload rather than leaving it untyped.
3419
+ */
3420
+ declare const isTypedSchema: (schema: Record<string, unknown> | undefined) => boolean;
3421
+ /** What a target renders from. */
3422
+ interface SdkRenderInput {
3423
+ /**
3424
+ * The rendered model source, to be written as the target's model file.
3425
+ *
3426
+ * Empty for a target that emits its own model FILES via
3427
+ * {@link SdkTarget.renderModels} — those are already written, and this string
3428
+ * exists only so the declared-model reconciliation reads one shape.
3429
+ */
3430
+ models: string;
3431
+ /** Namespaces and their functions, already sorted. */
3432
+ namespaces: ReadonlyArray<SdkNamespace>;
3433
+ }
3434
+ /**
3435
+ * One directory or file of the hand-written transport, and where it lands in the
3436
+ * output.
3437
+ *
3438
+ * `from` is relative to `sdks/<target id>/` and `to` is relative to `--out`. The
3439
+ * two differ because a repo layout and a consumable layout are not the same
3440
+ * shape: the Ruby transport lives under `lib/` so `ruby -Ilib` works in the
3441
+ * repo, while a vendored copy has no `lib` to point at, and the Rust transport
3442
+ * is the repo's root crate but a nested one in the output.
3443
+ *
3444
+ * Only the runtime is listed. A transport's own conformance suite and its
3445
+ * `generated_check/` sample are deliberately absent — they assert against
3446
+ * `protocol/fixtures/`, which is not copied, so vendoring them would ship a user
3447
+ * a test suite that cannot run.
3448
+ */
3449
+ interface SdkVendorEntry {
3450
+ /** Path under `sdks/<id>/`. A directory is copied recursively. */
3451
+ from: string;
3452
+ /** Destination path under `--out`. */
3453
+ to: string;
3454
+ }
3455
+ /** A language target. One per `--lang` value. */
3456
+ interface SdkTarget {
3457
+ /** The `--lang` value (`"python"`, `"go"`, …). */
3458
+ id: string;
3459
+ /**
3460
+ * The quicktype backend + renderer options that produce this target's
3461
+ * models, or absent when the target emits its own (see
3462
+ * {@link SdkTarget.renderModels}) or none at all.
3463
+ *
3464
+ * `LanguageName` is quicktype's own union, so a target naming a backend
3465
+ * quicktype does not ship fails to compile rather than at run time.
3466
+ */
3467
+ quicktype?: {
3468
+ lang: LanguageName;
3469
+ rendererOptions?: Record<string, string>;
3470
+ };
3471
+ /**
3472
+ * Render the SDK. Returns file contents keyed by path relative to the
3473
+ * output directory (nested paths are created as needed).
3474
+ *
3475
+ * This includes the BUILD MANIFEST the layout needs — `go.mod`, `Cargo.toml`,
3476
+ * `Package.swift`, a crate root — because those name the vendored transport
3477
+ * and are therefore part of "how this language resolves the copy", not
3478
+ * something a consumer should have to write. Languages that resolve by
3479
+ * directory (Python, Ruby, Java, Kotlin) emit no manifest.
3480
+ */
3481
+ render: (input: SdkRenderInput) => Record<string, string>;
3482
+ /**
3483
+ * Emit this target's models from the schema directly, INSTEAD of quicktype,
3484
+ * as file contents keyed by path relative to the output directory.
3485
+ *
3486
+ * Present only for the two JVM targets, and the exception is earned rather
3487
+ * than a preference: quicktype's Java and Kotlin backends rename properties
3488
+ * and, under `just-types`, emit no mapping metadata, so a model they render
3489
+ * cannot be projected back onto the wire — and the only complete mapping
3490
+ * they offer requires a Jackson / Klaxon / kotlinx dependency, which is the
3491
+ * one thing these JDK-only transports are defined not to have.
3492
+ * `targets/java.ts` records every option that was measured.
3493
+ *
3494
+ * A MAP rather than the single string quicktype returns, because Java takes
3495
+ * one file per class: its single-file render is not compilable Java at all.
3496
+ * The values are still joined for {@link SdkRenderInput.models}, so the
3497
+ * declared-model reconciliation is the same code for every target.
3498
+ */
3499
+ renderModels?: (document: OpenRpcDocument) => Record<string, string>;
3500
+ /**
3501
+ * THIRD-PARTY packages a consuming project must still install, reported by
3502
+ * the CLI. Empty for five of the seven — the transport is vendored and those
3503
+ * five reach the wire with only their standard library.
3504
+ *
3505
+ * A list, and not derivable from the transport, because a target's MODELS can
3506
+ * carry a dependency the transport does not: quicktype's Ruby backend emits
3507
+ * `Dry::Struct` types with no renderer option to avoid them, so a Ruby SDK
3508
+ * needs the gems even though `sdks/ruby` itself is dependency-free.
3509
+ */
3510
+ requires: ReadonlyArray<string>;
3511
+ /**
3512
+ * Which parts of `sdks/<id>/` are the transport, and where they land under
3513
+ * `--out`. See {@link SdkVendorEntry}.
3514
+ */
3515
+ vendor: ReadonlyArray<SdkVendorEntry>;
3516
+ }
3517
+ /** Every language `lunora sdk generate --lang` accepts, keyed by id. */
3518
+ declare const SDK_TARGETS: Readonly<Record<string, SdkTarget>>;
3519
+ /** The accepted `--lang` values, sorted — for help text and error messages. */
3520
+ declare const SDK_LANGUAGES: ReadonlyArray<string>;
3521
+ /** The files a generation run writes, keyed by path relative to the output directory. */
3522
+ type SdkFiles = Record<string, string>;
3523
+ /** What a generation run produced, plus what it had to weaken and why. */
3524
+ interface SdkResult {
3525
+ files: SdkFiles;
3526
+ /**
3527
+ * Model names predicted from the schema that the chosen backend did not
3528
+ * declare, so their call sites fell back to an untyped return. Surfaced
3529
+ * rather than swallowed — silently weaker types are how an SDK looks
3530
+ * finished while returning `Any` everywhere.
3531
+ */
3532
+ undeclared: ReadonlyArray<string>;
3533
+ /**
3534
+ * Functions whose args or result carry a `v.bigint()` or `v.bytes()`. No
3535
+ * typed model can represent those — the wire needs a tagged value that no
3536
+ * generated field produces — so their parameters stay untyped and the
3537
+ * caller passes wire values directly.
3538
+ */
3539
+ unrepresentable: ReadonlyArray<string>;
3540
+ }
3541
+ /**
3542
+ * Generate the SDK for `document` in `target`'s language.
3543
+ *
3544
+ * Async only because the model layer is: quicktype's renderer is promise-based.
3545
+ * The surface itself is pure, so a target's `render` stays synchronous and
3546
+ * unit-testable without touching quicktype.
3547
+ *
3548
+ * Models are rendered BEFORE the surface because the surface's model references
3549
+ * depend on what the backend actually declared — see {@link withDeclaredModels}.
3550
+ */
3551
+ declare const generateSdk: (document: OpenRpcDocument, target: SdkTarget) => Promise<SdkResult>;
3340
3552
  /** The matching secret rule's `kind` for a string value, or `undefined` when none matches. */
3341
3553
  declare const secretKindOf: (value: string) => string | undefined;
3342
3554
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
3343
3555
  declare const redact: (value: string) => string;
3344
3556
  declare const VERSION = "0.0.0";
3345
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3557
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, type Solution as LunoraSolu
7
7
  import { StudioFeaturesResult } from '@lunora/shard-engine';
8
8
  import { Schema } from '@lunora/server';
9
9
  import { JsonSchema } from '@lunora/values';
10
+ import { LanguageName } from 'quicktype-core';
10
11
  /**
11
12
  * The structural schema-snapshot format and its diff, shared by `@lunora/codegen`
12
13
  * (which builds snapshots from the parsed schema IR and gates deploys on the
@@ -3337,9 +3338,220 @@ declare const validatorIrToJsonSchema: (validator: ValidatorIR) => JsonSchema;
3337
3338
  * the contract; clients switch on `error.code`. Kept sorted for stable output.
3338
3339
  */
3339
3340
  declare const LUNORA_ERROR_CODES: ReadonlyArray<string>;
3341
+ /**
3342
+ * Language-agnostic half of SDK generation: turn an OpenRPC document
3343
+ * (`_generated/openrpc.json`, see {@link file://../openrpc.ts}) into the parsed
3344
+ * shape every per-language target renders from.
3345
+ *
3346
+ * Nothing here knows about a target language. A target supplies its own member
3347
+ * naming and templates (see {@link file://./targets}); everything that would
3348
+ * otherwise be re-derived per language — how a `functionPath` splits, which
3349
+ * runtime verb a kind maps to, whether a schema is real or the untyped
3350
+ * placeholder, how namespaces group and sort — lives here exactly once.
3351
+ *
3352
+ * That single-source rule is not stylistic. `paths.ts` documents the same
3353
+ * discipline for namespaces ("if these ever disagree, runtime dispatch silently
3354
+ * misses functions"), and the failure mode here is the same in a new costume: a
3355
+ * target that re-derives a model name renders an import pointing at a class
3356
+ * quicktype never emitted.
3357
+ *
3358
+ * Deriving names in one place is necessary but NOT sufficient, because only
3359
+ * half the decision is ours: quicktype chooses whether a predicted name becomes
3360
+ * a declared type, and different backends answer differently for the same
3361
+ * schema. {@link withDeclaredModels} reconciles the two halves before a target
3362
+ * renders anything.
3363
+ */
3364
+ /** One OpenRPC method as {@link file://../openrpc.ts} emits it. */
3365
+ interface OpenRpcMethod {
3366
+ name: string;
3367
+ params?: ReadonlyArray<{
3368
+ name: string;
3369
+ schema?: Record<string, unknown>;
3370
+ }>;
3371
+ result?: {
3372
+ name: string;
3373
+ schema?: Record<string, unknown>;
3374
+ };
3375
+ summary?: string;
3376
+ "x-lunora-function-kind"?: string;
3377
+ }
3378
+ /** The `_generated/openrpc.json` document. */
3379
+ interface OpenRpcDocument {
3380
+ info?: {
3381
+ title?: string;
3382
+ version?: string;
3383
+ };
3384
+ methods: ReadonlyArray<OpenRpcMethod>;
3385
+ }
3386
+ /** The runtime verbs a generated SDK can call. Mirrors the client transports. */
3387
+ type RuntimeVerb = "action" | "mutation" | "query";
3388
+ /** One RPC function, parsed and language-neutral. */
3389
+ interface SdkMethod {
3390
+ /** Generated args model name, or `undefined` when the function takes none. */
3391
+ argsType: string | undefined;
3392
+ /** Raw exported function name (`"list"`), before any naming convention. */
3393
+ functionName: string;
3394
+ /** The wire identifier (`"messages:list"`), emitted verbatim into calls. */
3395
+ functionPath: string;
3396
+ /** Raw file namespace (`"messages"`), before any naming convention. */
3397
+ namespace: string;
3398
+ /** Generated result model name, or `undefined` while the result is untyped. */
3399
+ resultType: string | undefined;
3400
+ /** Human summary for the doc comment. */
3401
+ summary: string;
3402
+ /** Which runtime verb this dispatches to. */
3403
+ verb: RuntimeVerb;
3404
+ }
3405
+ /** One namespace's functions, sorted. */
3406
+ interface SdkNamespace {
3407
+ methods: ReadonlyArray<SdkMethod>;
3408
+ /** Raw namespace (`"messages"`); a target applies its own casing. */
3409
+ name: string;
3410
+ }
3411
+ /**
3412
+ * True when a schema actually describes a shape.
3413
+ *
3414
+ * `openrpc.ts` emits a description-only placeholder for any function without a
3415
+ * declared `.output()` (the return type is TS-inferred and absent from the IR).
3416
+ * A placeholder must never become a generated model: quicktype would render an
3417
+ * empty type, and the surface would decode every response into it — silently
3418
+ * discarding the real payload rather than leaving it untyped.
3419
+ */
3420
+ declare const isTypedSchema: (schema: Record<string, unknown> | undefined) => boolean;
3421
+ /** What a target renders from. */
3422
+ interface SdkRenderInput {
3423
+ /**
3424
+ * The rendered model source, to be written as the target's model file.
3425
+ *
3426
+ * Empty for a target that emits its own model FILES via
3427
+ * {@link SdkTarget.renderModels} — those are already written, and this string
3428
+ * exists only so the declared-model reconciliation reads one shape.
3429
+ */
3430
+ models: string;
3431
+ /** Namespaces and their functions, already sorted. */
3432
+ namespaces: ReadonlyArray<SdkNamespace>;
3433
+ }
3434
+ /**
3435
+ * One directory or file of the hand-written transport, and where it lands in the
3436
+ * output.
3437
+ *
3438
+ * `from` is relative to `sdks/<target id>/` and `to` is relative to `--out`. The
3439
+ * two differ because a repo layout and a consumable layout are not the same
3440
+ * shape: the Ruby transport lives under `lib/` so `ruby -Ilib` works in the
3441
+ * repo, while a vendored copy has no `lib` to point at, and the Rust transport
3442
+ * is the repo's root crate but a nested one in the output.
3443
+ *
3444
+ * Only the runtime is listed. A transport's own conformance suite and its
3445
+ * `generated_check/` sample are deliberately absent — they assert against
3446
+ * `protocol/fixtures/`, which is not copied, so vendoring them would ship a user
3447
+ * a test suite that cannot run.
3448
+ */
3449
+ interface SdkVendorEntry {
3450
+ /** Path under `sdks/<id>/`. A directory is copied recursively. */
3451
+ from: string;
3452
+ /** Destination path under `--out`. */
3453
+ to: string;
3454
+ }
3455
+ /** A language target. One per `--lang` value. */
3456
+ interface SdkTarget {
3457
+ /** The `--lang` value (`"python"`, `"go"`, …). */
3458
+ id: string;
3459
+ /**
3460
+ * The quicktype backend + renderer options that produce this target's
3461
+ * models, or absent when the target emits its own (see
3462
+ * {@link SdkTarget.renderModels}) or none at all.
3463
+ *
3464
+ * `LanguageName` is quicktype's own union, so a target naming a backend
3465
+ * quicktype does not ship fails to compile rather than at run time.
3466
+ */
3467
+ quicktype?: {
3468
+ lang: LanguageName;
3469
+ rendererOptions?: Record<string, string>;
3470
+ };
3471
+ /**
3472
+ * Render the SDK. Returns file contents keyed by path relative to the
3473
+ * output directory (nested paths are created as needed).
3474
+ *
3475
+ * This includes the BUILD MANIFEST the layout needs — `go.mod`, `Cargo.toml`,
3476
+ * `Package.swift`, a crate root — because those name the vendored transport
3477
+ * and are therefore part of "how this language resolves the copy", not
3478
+ * something a consumer should have to write. Languages that resolve by
3479
+ * directory (Python, Ruby, Java, Kotlin) emit no manifest.
3480
+ */
3481
+ render: (input: SdkRenderInput) => Record<string, string>;
3482
+ /**
3483
+ * Emit this target's models from the schema directly, INSTEAD of quicktype,
3484
+ * as file contents keyed by path relative to the output directory.
3485
+ *
3486
+ * Present only for the two JVM targets, and the exception is earned rather
3487
+ * than a preference: quicktype's Java and Kotlin backends rename properties
3488
+ * and, under `just-types`, emit no mapping metadata, so a model they render
3489
+ * cannot be projected back onto the wire — and the only complete mapping
3490
+ * they offer requires a Jackson / Klaxon / kotlinx dependency, which is the
3491
+ * one thing these JDK-only transports are defined not to have.
3492
+ * `targets/java.ts` records every option that was measured.
3493
+ *
3494
+ * A MAP rather than the single string quicktype returns, because Java takes
3495
+ * one file per class: its single-file render is not compilable Java at all.
3496
+ * The values are still joined for {@link SdkRenderInput.models}, so the
3497
+ * declared-model reconciliation is the same code for every target.
3498
+ */
3499
+ renderModels?: (document: OpenRpcDocument) => Record<string, string>;
3500
+ /**
3501
+ * THIRD-PARTY packages a consuming project must still install, reported by
3502
+ * the CLI. Empty for five of the seven — the transport is vendored and those
3503
+ * five reach the wire with only their standard library.
3504
+ *
3505
+ * A list, and not derivable from the transport, because a target's MODELS can
3506
+ * carry a dependency the transport does not: quicktype's Ruby backend emits
3507
+ * `Dry::Struct` types with no renderer option to avoid them, so a Ruby SDK
3508
+ * needs the gems even though `sdks/ruby` itself is dependency-free.
3509
+ */
3510
+ requires: ReadonlyArray<string>;
3511
+ /**
3512
+ * Which parts of `sdks/<id>/` are the transport, and where they land under
3513
+ * `--out`. See {@link SdkVendorEntry}.
3514
+ */
3515
+ vendor: ReadonlyArray<SdkVendorEntry>;
3516
+ }
3517
+ /** Every language `lunora sdk generate --lang` accepts, keyed by id. */
3518
+ declare const SDK_TARGETS: Readonly<Record<string, SdkTarget>>;
3519
+ /** The accepted `--lang` values, sorted — for help text and error messages. */
3520
+ declare const SDK_LANGUAGES: ReadonlyArray<string>;
3521
+ /** The files a generation run writes, keyed by path relative to the output directory. */
3522
+ type SdkFiles = Record<string, string>;
3523
+ /** What a generation run produced, plus what it had to weaken and why. */
3524
+ interface SdkResult {
3525
+ files: SdkFiles;
3526
+ /**
3527
+ * Model names predicted from the schema that the chosen backend did not
3528
+ * declare, so their call sites fell back to an untyped return. Surfaced
3529
+ * rather than swallowed — silently weaker types are how an SDK looks
3530
+ * finished while returning `Any` everywhere.
3531
+ */
3532
+ undeclared: ReadonlyArray<string>;
3533
+ /**
3534
+ * Functions whose args or result carry a `v.bigint()` or `v.bytes()`. No
3535
+ * typed model can represent those — the wire needs a tagged value that no
3536
+ * generated field produces — so their parameters stay untyped and the
3537
+ * caller passes wire values directly.
3538
+ */
3539
+ unrepresentable: ReadonlyArray<string>;
3540
+ }
3541
+ /**
3542
+ * Generate the SDK for `document` in `target`'s language.
3543
+ *
3544
+ * Async only because the model layer is: quicktype's renderer is promise-based.
3545
+ * The surface itself is pure, so a target's `render` stays synchronous and
3546
+ * unit-testable without touching quicktype.
3547
+ *
3548
+ * Models are rendered BEFORE the surface because the surface's model references
3549
+ * depend on what the backend actually declared — see {@link withDeclaredModels}.
3550
+ */
3551
+ declare const generateSdk: (document: OpenRpcDocument, target: SdkTarget) => Promise<SdkResult>;
3340
3552
  /** The matching secret rule's `kind` for a string value, or `undefined` when none matches. */
3341
3553
  declare const secretKindOf: (value: string) => string | undefined;
3342
3554
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
3343
3555
  declare const redact: (value: string) => string;
3344
3556
  declare const VERSION = "0.0.0";
3345
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3557
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as C}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as L,discoverFlags as _}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as T}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as D}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as H}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as y}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as V}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as k,discoverMutators as Q}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as B,discoverNotifyCalls as K,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as X}from"./packem_shared/discover-queries-i4Vd2si7.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as fe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as le}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,P as Re,B as ge,p as Ce,L as Me,R as he,C as Ie,V as Le,Q as _e,$ as Fe,E as Te,m as Pe,F as De}from"./packem_shared/emit-B8FxCABN.mjs";import{emitApp as He}from"./packem_shared/emitApp-Dg-jOuj6.mjs";import{buildOpenApiDocument as ye,emitOpenApi as Ge,emitOpenApiModule as Ve}from"./packem_shared/buildOpenApiDocument-DcpvOBMi.mjs";import{OPENRPC_VERSION as ke,buildOpenRpcDocument as Qe,emitOpenRpc as je,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-DkNdVeNM.mjs";import{DEFAULT_TARGET as Be,platformMatrixIds as Ke,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-hQUs7FJj.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as fr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{redact as nr,secretKindOf as lr}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as Er,findSolutionByMessage as xr}from"@lunora/errors";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,Be as DEFAULT_TARGET,L as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Er as LUNORA_SOLUTION_RULES,k as MUTATORS_FILENAME,B as NOTIFY_FILENAME,ke as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,Qe as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,C as discoverContainers,h as discoverCrons,_ as discoverFlags,T as discoverFunctions,D as discoverHttpRoutes,H as discoverInserts,y as discoverMaskProcedures,V as discoverMigrations,Q as discoverMutators,z as discoverNondeterministicCalls,K as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,fe as discoverSchema,le as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,He as emitApp,ge as emitCollections,Ce as emitContainers,Me as emitCrons,he as emitDataModel,Ie as emitDrizzleSchema,Le as emitFunctions,Ge as emitOpenApi,Ve as emitOpenApiModule,je as emitOpenRpc,ze as emitOpenRpcModule,_e as emitServer,Fe as emitShard,Te as emitVectors,Pe as emitWorkflows,De as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,xr as findLunoraSolution,m as formatAdvisories,d as lintSchema,ar as parseSchemaSnapshot,Ke as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,nr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,lr as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,fr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as C}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as L,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as G}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as y}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as k}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as W,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as j}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as B,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as X}from"./packem_shared/discover-queries-i4Vd2si7.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as fe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,P as Re,B as ge,p as Ce,L as Me,R as he,C as _e,V as Le,Q as Ie,$ as Te,E as Fe,m as De,F as Pe}from"./packem_shared/emit-B8FxCABN.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-Dg-jOuj6.mjs";import{buildOpenApiDocument as ye,emitOpenApi as be,emitOpenApiModule as ke}from"./packem_shared/buildOpenApiDocument-CDYoRVC6.mjs";import{OPENRPC_VERSION as We,buildOpenRpcDocument as Ke,emitOpenRpc as Qe,emitOpenRpcModule as je}from"./packem_shared/OPENRPC_VERSION-CBWjXJgS.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as Be,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BM6kIe4w.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as fr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{SDK_LANGUAGES as nr,SDK_TARGETS as Sr,generateSdk as lr}from"./packem_shared/SDK_LANGUAGES-CAGhWtBh.mjs";import{redact as xr,secretKindOf as Ar}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as vr,findSolutionByMessage as Nr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-C-UHYeJq.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,L as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,vr as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,w as NOTIFY_FILENAME,We as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,nr as SDK_LANGUAGES,Sr as SDK_TARGETS,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,Ke as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,C as discoverContainers,h as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,y as discoverMaskProcedures,k as discoverMigrations,K as discoverMutators,j as discoverNondeterministicCalls,B as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,fe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,Ge as emitApp,ge as emitCollections,Ce as emitContainers,Me as emitCrons,he as emitDataModel,_e as emitDrizzleSchema,Le as emitFunctions,be as emitOpenApi,ke as emitOpenApiModule,Qe as emitOpenRpc,je as emitOpenRpcModule,Ie as emitServer,Te as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,Nr as findLunoraSolution,m as formatAdvisories,lr as generateSdk,Rr as isTypedSchema,d as lintSchema,ar as parseSchemaSnapshot,Be as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,xr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,Ar as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,fr as validatorIrToJsonSchema};
@@ -0,0 +1,3 @@
1
+ import{S as a}from"./emit-B8FxCABN.mjs";import{n as i}from"./paths-BmX5O1sG.mjs";import{validatorIrToJsonSchema as s,objectSchema as c,LUNORA_ERROR_CODES as u}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const p="1.3.2",m={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},d=e=>{const r=i(e.filePath),t=`${r}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:u.map((o,n)=>({code:-32e3-n,data:{code:o},message:o})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:c(e.args)}],result:{name:"result",schema:e.output?s(e.output):m},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:r}]}},l=e=>{const r=e.version??"0.0.0",t=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream").map(o=>d(o)).toSorted((o,n)=>o.name.localeCompare(n.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:r},methods:t,openrpc:p}},h=e=>`${JSON.stringify(l(e),void 0,2)}
2
+ `,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
+ `;export{p as OPENRPC_VERSION,l as buildOpenRpcDocument,h as emitOpenRpc,O as emitOpenRpcModule};
@@ -1,4 +1,4 @@
1
- import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,P as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,M as ls,F as us}from"./emit-B8FxCABN.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,y as Ss}from"./discover-queries-i4Vd2si7.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Os from"./discoverInserts-D6szWzrV.mjs";import Cs,{discoverMaskStrategies as Fs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-Dg-jOuj6.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-DcpvOBMi.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-DkNdVeNM.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
1
+ import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,P as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,M as ls,F as us}from"./emit-B8FxCABN.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,y as Ss}from"./discover-queries-i4Vd2si7.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Os from"./discoverInserts-D6szWzrV.mjs";import Cs,{discoverMaskStrategies as Fs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-Dg-jOuj6.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-CDYoRVC6.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-CBWjXJgS.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
2
2
  `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${r}
4
4
 
@@ -0,0 +1,320 @@
1
+ import{modelSources as ne,toPascalCase as s,generatedHeaderLines as f,commentText as l,stringLiteral as d,kotlinLiteral as h,referencedModels as R,allMethods as C,toSnakeCase as H,parseSpec as me,assertGeneratable as $e,withDeclaredModels as fe,unrepresentableFunctions as ye,undeclaredModels as he}from"./isTypedSchema-C-UHYeJq.mjs";import{isTypedSchema as Ir}from"./isTypedSchema-C-UHYeJq.mjs";const ge=async(e,r)=>{if(r.quicktype===void 0)return"";const t=ne(e);if(t.length===0)return"";const{InputData:n,JSONSchemaInput:a,JSONSchemaStore:i,quicktype:o}=await import("quicktype-core");class c extends i{fetch(){return Promise.resolve(void 0)}}const p=new a(new c);for(const O of t)await p.addSource({name:O.name,schema:JSON.stringify(O.schema)});const u=new n;u.addInput(p);const{lines:$}=await o({inputData:u,lang:r.quicktype.lang,rendererOptions:r.quicktype.rendererOptions??{}});return $.join(`
2
+ `)},W=`${f("go").map(e=>`// ${e}`).join(`
3
+ `)}
4
+
5
+ `,y="lunoraapi",j="lunorasdk",ve=`${j}/lunora`,be="1.22",M=e=>s(e),U=(e,r)=>{const t=r.argsType===void 0?"":`args ${r.argsType}, `,n=r.argsType===void 0?"nil":"args",a=r.resultType??"any",i=`lunora.Verb${r.verb.charAt(0).toUpperCase()}${r.verb.slice(1)}`,o=`lunora.Call[${a}](a.client, ${i}, "${d(r.functionPath)}", ${n}, shardKey)`;return[`// ${M(r.functionName)} invokes ${l(r.summary)}.`,`func (a *${e}) ${M(r.functionName)}(${t}shardKey string) (${a}, error) {`,` return ${o}`,"}"].join(`
6
+ `)},we=(e,r)=>{const t=r.argsType===void 0?"":`args ${r.argsType}, `,n=r.argsType===void 0?"nil":"args",a=`Subscribe${M(r.functionName)}`;return[`// ${a} opens a live ${l(r.functionPath)}; it re-runs on every write to the tables it reads.`,`func (a *${e}) ${a}(${t}onData lunora.DataHandler, onError lunora.ErrorHandler, shardKey string) lunora.Unsubscribe {`,` return a.client.Subscribe("${d(r.functionPath)}", ${n}, onData, onError, shardKey)`,"}"].join(`
7
+ `)},je=e=>{const r=`${s(e.name)}API`,t=e.methods.map(n=>n.verb==="query"?`${U(r,n)}
8
+
9
+ ${we(r,n)}`:U(r,n)).join(`
10
+
11
+ `);return[`// ${r} groups the functions declared in ${l(e.name)}.`,`type ${r} struct{ client *lunora.Client }`,"",t].join(`
12
+ `)},ke=({models:e,namespaces:r})=>{const t=r.map(o=>` ${s(o.name)} *${s(o.name)}API`).join(`
13
+ `),n=r.map(o=>` ${s(o.name)}: &${s(o.name)}API{client: client},`).join(`
14
+ `),a=[W,`package ${y}
15
+ `,`
16
+ `,`import "${ve}"
17
+ `,`
18
+ `,`// API is the typed entry point: api.<Namespace>.<Function>(args, shardKey).
19
+ `,`type API struct {
20
+ `,`${t}
21
+ `,`}
22
+ `,`
23
+ `,`// NewAPI binds the generated surface to a client.
24
+ `,`func NewAPI(client *lunora.Client) *API {
25
+ `,` return &API{
26
+ `,`${n}
27
+ `,` }
28
+ `,`}
29
+ `,`
30
+ `,r.map(o=>je(o)).join(`
31
+
32
+ `),`
33
+ `].join(""),i=e.length>0?`${W}package ${y}
34
+
35
+ ${e}
36
+ `:`${W}package ${y}
37
+
38
+ // No typed argument or result schemas in this deployment.
39
+ `;return{[`${y}/api.go`]:a,[`${y}/models.go`]:i,"go.mod":[`// The generated Lunora Go SDK, with the transport vendored under ./lunora.
40
+ `,`//
41
+ `,`// A consuming module wires it in without a network fetch:
42
+ `,`//
43
+ `,`// require ${j} v0.0.0
44
+ `,`// replace ${j} => ./path/to/this/directory
45
+ `,`module ${j}
46
+ `,`
47
+ `,`go ${be}
48
+ `].join("")}},Te={id:"go",quicktype:{lang:"go",rendererOptions:{"just-types":"true",package:y}},render:ke,requires:[],vendor:[{from:"lunora",to:"lunora"}]},g="lunoraapi.models",E="lunoraapi/models",_e=24,Se=new Set(["abstract","as","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","fromWire","fun","goto","if","implements","import","in","instanceof","int","interface","is","long","native","new","null","object","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","toWire","transient","true","try","typealias","typeof","val","var","void","volatile","when","while","wireValue"]),Ae=/[^A-Za-z0-9]+/gu,Oe=/([a-z0-9])([A-Z])/gu,We=/^[A-Za-z]/u,Ve=/^[A-Z]/u;let ae=class extends Error{};const m=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,Le=e=>{const r=e.anyOf??e.oneOf;if(!Array.isArray(r)||r.length===0)return;const t=r.map(n=>m(n)?.const);if(t.every(n=>typeof n=="string"))return[...new Set(t)].toSorted((n,a)=>n.localeCompare(a))},ie=e=>{const r=e.anyOf??e.oneOf;if(!Array.isArray(r)||r.length!==2)return e;const t=r.filter(n=>m(n)?.type!=="null");return t.length===1?m(t[0])??e:e},Ne=e=>{const r=s(e),t=r.charAt(0).toLowerCase()+r.slice(1),n=We.test(t)?t:`value${r}`;return Se.has(n)?`${n}_`:n},Ce=e=>{const r=e.replaceAll(Oe,"$1_$2").replaceAll(Ae,"_").toUpperCase().split("_").filter(t=>t.length>0).join("_");return Ve.test(r)?r:`VALUE_${r}`},oe=(e,r)=>{if(!r.has(e))return r.add(e),e;let t=2;for(;r.has(`${e}${String(t)}`);)t+=1;return r.add(`${e}${String(t)}`),`${e}${String(t)}`},B=(e,r)=>{if(e.has(r.name))throw new ae(`sdk: two schemas both produce the JVM model "${r.name}"`);e.set(r.name,r)},Me=(e,r,t,n,a)=>{const i=new Set(Array.isArray(r)?r.filter(c=>typeof c=="string"):[]),o=new Set;return Object.entries(e).map(([c,p])=>{const u=m(p)??{},$=!i.has(c);return{name:oe(Ne(c),o),nullable:!$&&ie(u)!==u,optional:$,type:v(u,`${t}${s(c)}`,n+1,a),wireKey:c}})},v=(e,r,t,n)=>{if(t>=_e)return{kind:"unknown"};const a=Le(e);if(a!==void 0){const u=new Set;return B(n,{constants:a.map($=>({name:oe(Ce($),u),wireValue:$})),kind:"enum",name:r}),{kind:"enum",name:r}}const i=ie(e);if(i!==e)return v(i,r,t+1,n);const o=m(e.properties);if(o!==void 0)return B(n,{fields:Me(o,e.required,r,t,n),kind:"class",name:r}),{kind:"class",name:r};const c=m(e.additionalProperties);if(c!==void 0)return{kind:"record",value:v(c,`${r}Value`,t+1,n)};const p=m(e.items);if(p!==void 0)return{item:v(p,`${r}Item`,t+1,n),kind:"list"};switch(e.type){case"boolean":return{kind:"boolean"};case"integer":case"number":return{kind:"number"};case"string":return{kind:"string"};default:return{kind:"unknown"}}},se=e=>{const r=new Map;for(const t of ne(e)){if(m(t.schema.properties)===void 0)continue;const n=new Map;try{v(t.schema,t.name,0,n)}catch(a){if(a instanceof ae)continue;throw a}if(![...n.keys()].some(a=>r.has(a)))for(const[a,i]of n)r.set(a,i)}return[...r.values()].toSorted((t,n)=>t.name.localeCompare(n.name))},A=e=>[`// GENERATED by \`lunora sdk generate --lang ${e}\` — do not edit.`,"// Run the command again to regenerate."],T=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`java.util.List<${T(e.item)}>`;case"number":return"Double";case"record":return`java.util.Map<String, ${T(e.value)}>`;case"string":return"String";default:return"Object"}},P=e=>{switch(e.kind){case"class":case"enum":return!0;case"list":return P(e.item);case"record":return P(e.value);default:return!1}},K=(e,r,t)=>{if(!P(e))return r;const n=`item${String(t)}`;switch(e.kind){case"class":return`${r} == null ? null : ${r}.toWire()`;case"enum":return`${r} == null ? null : ${r}.toValue()`;case"list":return`ModelWire.writeList(${r}, ${n} -> ${K(e.item,n,t+1)})`;case"record":return`ModelWire.writeRecord(${r}, ${n} -> ${K(e.value,n,t+1)})`;default:return r}},x=(e,r,t)=>{const n=`item${String(t)}`;switch(e.kind){case"boolean":return`ModelWire.flag(${r})`;case"class":return`ModelWire.readObject(${r}, ${e.name}::fromWire)`;case"enum":return`ModelWire.readEnum(${r}, ${e.name}::forValue)`;case"list":return`ModelWire.readList(${r}, ${n} -> ${x(e.item,n,t+1)})`;case"number":return`ModelWire.number(${r})`;case"record":return`ModelWire.readRecord(${r}, ${n} -> ${x(e.value,n,t+1)})`;case"string":return`ModelWire.text(${r})`;default:return r}},Ee=e=>{const r=l(e.wireKey);return e.optional?[" /**",` * Wire key {@code ${r}} — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key {@code ${r}}.${e.nullable?" Nullable: null is sent as an explicit null.":""} */`]},Pe=100,Ke=e=>{const r=e.fields.map(n=>`${T(n.type)} ${n.name}`),t=` public ${e.name}(${r.join(", ")}) {`;return t.length<=Pe?[t]:[` public ${e.name}(`,...r.map((n,a)=>` ${n}${a===r.length-1?") {":","}`)]},xe=e=>{const r=e.fields.flatMap(n=>{const a=`wire.put("${d(n.wireKey)}", ${K(n.type,`this.${n.name}`,0)});`;return n.optional?[` if (this.${n.name} != null) {`,` ${a}`," }"]:[` ${a}`]}),t=e.fields.map(n=>` ${x(n.type,`wire.get("${d(n.wireKey)}")`,0)}`);return[...A("java"),"",`package ${g};`,"","/**",` * The \`${e.name}\` model.`," *"," * <p>Field names are local; the keys {@link #toWire()} and {@link #fromWire(Object)} use are"," * the schema's own, emitted verbatim, so a renamed field cannot reach the wire."," */",`public final class ${e.name} {`,...e.fields.flatMap(n=>[...Ee(n),` public final ${T(n.type)} ${n.name};`,""]),...Ke(e),...e.fields.map(n=>` this.${n.name} = ${n.name};`)," }",""," /** This model as the wire-shaped map the transport encodes. */"," public java.util.Map<String, Object> toWire() {"," java.util.Map<String, Object> wire = new java.util.LinkedHashMap<>();",...r,""," return wire;"," }",""," /** Rebuild from a decoded wire value. */",` public static ${e.name} fromWire(Object value) {`," java.util.Map<String, Object> wire = ModelWire.object(value);","",...t.length===0?[` return new ${e.name}();`]:[` return new ${e.name}(`,`${t.join(`,
49
+ `)});`]," }","}",""].join(`
50
+ `)},qe=e=>[...A("java"),"",`package ${g};`,"",`/** The \`${e.name}\` union. Each constant keeps the wire string it encodes to. */`,`public enum ${e.name} {`,...e.constants.map((r,t)=>` ${r.name}("${d(r.wireValue)}")${t===e.constants.length-1?";":","}`),""," private final String value;","",` ${e.name}(String value) {`," this.value = value;"," }",""," /** The wire string this constant encodes to. */"," public String toValue() {"," return this.value;"," }",""," /** The constant a wire string decodes to. */",` public static ${e.name} forValue(String value) {`,` for (${e.name} candidate : values()) {`," if (candidate.value.equals(value)) {"," return candidate;"," }"," }","",` throw new IllegalArgumentException("${e.name}: unknown wire value " + value);`," }","}",""].join(`
51
+ `),Ie=[{lines:[' @SuppressWarnings("unchecked")'," static java.util.Map<String, Object> object(Object value) {"," return value instanceof java.util.Map"," ? (java.util.Map<String, Object>) value"," : new java.util.LinkedHashMap<String, Object>();"," }"],name:"object"},{lines:[" static String text(Object value) {"," return value instanceof String ? (String) value : null;"," }"],name:"text"},{lines:[" static Double number(Object value) {"," return value instanceof Number ? ((Number) value).doubleValue() : null;"," }"],name:"number"},{lines:[" static Boolean flag(Object value) {"," return value instanceof Boolean ? (Boolean) value : null;"," }"],name:"flag"},{lines:[" /** A nested model, or null when the payload carried no object there. */"," static <T> T readObject(Object value, java.util.function.Function<Object, T> read) {"," return value instanceof java.util.Map ? read.apply(value) : null;"," }"],name:"readObject"},{lines:[" /** An enum constant, or null when the payload carried no string there. */"," static <T> T readEnum(Object value, java.util.function.Function<String, T> read) {"," return value instanceof String ? read.apply((String) value) : null;"," }"],name:"readEnum"},{lines:[" static <T> java.util.List<T> readList("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.List)) {"," return null;"," }",""," java.util.List<T> items = new java.util.ArrayList<T>();",""," for (Object item : (java.util.List<?>) value) {"," items.add(read.apply(item));"," }",""," return items;"," }"],name:"readList"},{lines:[" static <T> java.util.Map<String, T> readRecord("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.Map)) {"," return null;"," }",""," java.util.Map<String, T> entries = new java.util.LinkedHashMap<String, T>();",""," for (java.util.Map.Entry<?, ?> entry : ((java.util.Map<?, ?>) value).entrySet()) {"," entries.put(String.valueOf(entry.getKey()), read.apply(entry.getValue()));"," }",""," return entries;"," }"],name:"readRecord"},{lines:[" static <T> java.util.List<Object> writeList("," java.util.List<T> items, java.util.function.Function<T, Object> write) {"," if (items == null) {"," return null;"," }",""," java.util.List<Object> encoded = new java.util.ArrayList<Object>(items.size());",""," for (T item : items) {"," encoded.add(write.apply(item));"," }",""," return encoded;"," }"],name:"writeList"},{lines:[" static <T> java.util.Map<String, Object> writeRecord("," java.util.Map<String, T> entries, java.util.function.Function<T, Object> write) {"," if (entries == null) {"," return null;"," }",""," java.util.Map<String, Object> encoded = new java.util.LinkedHashMap<String, Object>();",""," for (java.util.Map.Entry<String, T> entry : entries.entrySet()) {"," encoded.put(entry.getKey(), write.apply(entry.getValue()));"," }",""," return encoded;"," }"],name:"writeRecord"}],De=e=>{const r=Ie.filter(t=>e.includes(`ModelWire.${t.name}(`));return[...A("java"),"",`package ${g};`,"","/** Wire readers and writers shared by the generated models. */","final class ModelWire {"," private ModelWire() {}",...r.flatMap(t=>["",...t.lines]),"}",""].join(`
52
+ `)},Fe=e=>{const r=se(e);if(r.length===0)return{};const t={};for(const n of r)t[`${E}/${n.name}.java`]=n.kind==="enum"?qe(n):xe(n);return{[`${E}/ModelWire.java`]:De(Object.values(t).join(`
53
+ `)),...t}},q=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`List<${q(e.item)}>`;case"number":return"Double";case"record":return`Map<String, ${q(e.value)}>`;case"string":return"String";default:return"WireValue"}},b=(e,r,t)=>{const n=`item${String(t)}`,a=`entry${String(t)}`;switch(e.kind){case"boolean":return`WireValue.Bool(${r})`;case"class":return`${r}.toWire()`;case"enum":return`WireValue.Text(${r}.wireValue)`;case"list":return`WireValue.Arr(${r}.map { ${n} -> ${b(e.item,n,t+1)} })`;case"number":return`WireValue.Num(${r})`;case"record":return`WireValue.Obj(${r}.map { ${a} -> ${a}.key to ${b(e.value,`${a}.value`,t+1)} })`;case"string":return`WireValue.Text(${r})`;default:return r}},I=(e,r,t,n)=>`wireNeed(${le(e,r,t,n)}, "${h(n)}")`,le=(e,r,t,n)=>{const a=`item${String(t)}`,i=`entry${String(t)}`;switch(e.kind){case"boolean":return`wireBool(${r})`;case"class":return`wireObj(${r})?.let { ${a} -> ${e.name}.fromWire(${a}) }`;case"enum":return`wireText(${r})?.let { ${a} -> ${e.name}.forValue(${a}) }`;case"list":return`wireArr(${r})?.items?.map { ${a} -> ${I(e.item,a,t+1,`${n}[]`)} }`;case"number":return`wireNum(${r})`;case"record":return`wireObj(${r})?.fields?.associate { ${i} -> ${i}.first to ${I(e.value,`${i}.second`,t+1,`${n}{}`)} }`;case"string":return`wireText(${r})`;default:return r}},Re=e=>{const r=e.fields.map(a=>{const i=l(a.wireKey);return[...a.optional?[" /**",` * Wire key \`${i}\` — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key \`${i}\`.${a.nullable?" Nullable: null is sent as an explicit null.":""} */`],` val ${a.name}: ${q(a.type)}${a.optional||a.nullable?"?":""}${a.optional?" = null":""},`]}),t=e.fields.map(a=>{const i=h(a.wireKey);return a.optional?` ${a.name}?.let { add("${i}" to ${b(a.type,"it",0)}) }`:a.nullable?` add("${i}" to (${a.name}?.let { ${b(a.type,"it",0)} } ?: WireValue.Null))`:` add("${i}" to ${b(a.type,a.name,0)})`}),n=e.fields.map(a=>{const i=`wireField(value, "${h(a.wireKey)}")`,o=a.optional||a.nullable?le(a.type,i,0,a.wireKey):I(a.type,i,0,a.wireKey);return` ${a.name} = ${o},`});return["/**",` * The \`${e.name}\` model.`," *"," * Property names are local; the keys [toWire] and [fromWire] use are the schema's own,"," * emitted verbatim, so a renamed property cannot reach the wire."," */",`class ${e.name}(`,...r.flat(),") {"," /** This model as the wire-shaped object the transport encodes. */"," fun toWire(): WireValue ="," WireValue.Obj("," buildList {",...t," },"," )",""," companion object {"," /** Rebuild from a decoded wire value. */",` fun fromWire(value: WireValue): ${e.name} =`,` ${e.name}(`,...n," )"," }","}"]},He=e=>[`/** The \`${e.name}\` union. Each entry keeps the wire string it encodes to. */`,`enum class ${e.name}(val wireValue: String) {`,...e.constants.map(r=>` ${r.name}("${h(r.wireValue)}"),`)," ;",""," companion object {"," /** The entry a wire string decodes to. */",` fun forValue(value: String): ${e.name} =`," entries.firstOrNull { it.wireValue == value }",` ?: throw IllegalArgumentException("${e.name}: unknown wire value " + value)`," }","}"],ze=[{lines:["private fun wireField(value: WireValue, key: String): WireValue? ="," (value as? WireValue.Obj)?.fields?.firstOrNull { it.first == key }?.second"],name:"wireField"},{lines:["private fun wireText(value: WireValue?): String? = (value as? WireValue.Text)?.value"],name:"wireText"},{lines:["private fun wireNum(value: WireValue?): Double? = (value as? WireValue.Num)?.value"],name:"wireNum"},{lines:["private fun wireBool(value: WireValue?): Boolean? = (value as? WireValue.Bool)?.value"],name:"wireBool"},{lines:["private fun wireArr(value: WireValue?): WireValue.Arr? = value as? WireValue.Arr"],name:"wireArr"},{lines:["private fun wireObj(value: WireValue?): WireValue.Obj? = value as? WireValue.Obj"],name:"wireObj"},{lines:["/** A required field the payload omitted or mistyped is a contract violation, not a null. */","private fun <T> wireNeed(read: T?, label: String): T =",' read ?: throw WireFormatException("lunora: the wire payload is missing or mistyped " + label)'],name:"wireNeed"}],Ue=e=>{const r=se(e);if(r.length===0)return{};const t=r.flatMap(o=>[...o.kind==="enum"?He(o):Re(o),""]),n=ze.filter(o=>t.some(c=>c.includes(`${o.name}(`))),a=n.flatMap((o,c)=>c===0?[...o.lines]:["",...o.lines]),i=[...A("kotlin"),"",`package ${g}`,"",...n.some(o=>o.name==="wireNeed")?["import dev.lunora.WireFormatException"]:[],"import dev.lunora.WireValue","",...t,...a,""].join(`
54
+ `);return{[`${E}/Models.kt`]:i}},Be=`${f("java").map(e=>`// ${e}`).join(`
55
+ `)}
56
+
57
+ `,J="lunoraapi",Je=new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"]),D=e=>{const r=s(e),t=r.charAt(0).toLowerCase()+r.slice(1);return Je.has(t)?`${t}_`:t},Ge=e=>`Client.Verb.${e.toUpperCase()}`,ue=e=>e.argsType===void 0?{payload:"args",type:"java.util.Map<String, Object>"}:{payload:"args == null ? null : args.toWire()",type:e.argsType},G=e=>{const r=ue(e),t=`client.call(
58
+ ${Ge(e.verb)}, "${d(e.functionPath)}", ${r.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` public ${e.resultType??"Object"} ${D(e.functionName)}(${r.type} args, String shardKey) {`,` return ${e.resultType===void 0?t:`${e.resultType}.fromWire(${t})`};`," }"].join(`
59
+ `)},Ze=e=>{const r=ue(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` public Runnable subscribe${s(e.functionName)}(`,` ${r.type} args,`," java.util.function.Consumer<Object> onData,"," java.util.function.Consumer<Client.SubscriptionError> onError,"," String shardKey) {"," return client.subscribe(",` "${d(e.functionPath)}", ${r.payload}, onData, onError, shardKey);`," }"].join(`
60
+ `)},Ye=e=>{const r=`${s(e.name)}Api`,t=e.methods.map(n=>n.verb==="query"?`${G(n)}
61
+
62
+ ${Ze(n)}`:G(n)).join(`
63
+
64
+ `);return[` /** Functions declared in \`${l(e.name)}\`. */`,` public static final class ${r} {`," private final Client client;","",` ${r}(Client client) {`," this.client = client;"," }","",t.replaceAll(/^ {4}/gmu," ")," }"].join(`
65
+ `)},Qe=({namespaces:e})=>{const r=e.map(i=>` public final ${s(i.name)}Api ${D(i.name)};`).join(`
66
+ `),t=e.map(i=>` this.${D(i.name)} = new ${s(i.name)}Api(client);`).join(`
67
+ `),n=R(e).map(i=>`import ${g}.${i};
68
+ `),a=[Be,`package ${J};
69
+ `,`
70
+ `,`import dev.lunora.Client;
71
+ `,...n,`
72
+ `,"/** Typed entry point: `new Api(client).<namespace>.<function>(args, shardKey)`. */\n",`public final class Api {
73
+ `,r.length>0?`${r}
74
+
75
+ `:"",` public Api(Client client) {
76
+ `,t.length>0?`${t}
77
+ `:` // No functions in this deployment.
78
+ `,` }
79
+ `,`
80
+ `,e.map(i=>Ye(i)).join(`
81
+
82
+ `),`
83
+ }
84
+ `].join("");return{[`${J}/Api.java`]:a}},Xe={id:"java",render:Qe,renderModels:Fe,requires:[],vendor:[{from:"src/dev/lunora",to:"dev/lunora"}]},er=`${f("kotlin").map(e=>`// ${e}`).join(`
85
+ `)}
86
+
87
+ `,Z="lunoraapi",rr=new Set(["as","break","class","continue","do","else","false","for","fun","if","in","interface","is","null","object","package","return","super","this","throw","true","try","typealias","typeof","val","var","when","while"]),ce=e=>{const r=s(e),t=r.charAt(0).toLowerCase()+r.slice(1);return rr.has(t)?`\`${t}\``:t},tr=e=>`Verb.${e.toUpperCase()}`,de=e=>e.argsType===void 0?{declaration:"args: WireValue? = null",payload:"args"}:{declaration:`args: ${e.argsType}`,payload:"args.toWire()"},Y=e=>{const r=de(e),t=`client.call(${tr(e.verb)}, "${h(e.functionPath)}", ${r.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` fun ${ce(e.functionName)}(${r.declaration}, shardKey: String? = null): ${e.resultType??"WireValue"} =`,` ${e.resultType===void 0?t:`${e.resultType}.fromWire(${t})`}`].join(`
88
+ `)},nr=e=>{const r=de(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` fun subscribe${s(e.functionName)}(`,` ${r.declaration},`," onData: ((WireValue) -> Unit)?,"," onError: ((SubscriptionError) -> Unit)? = null,"," shardKey: String? = null,"," ): () -> Unit =",` client.subscribe("${h(e.functionPath)}", ${r.payload}, onData, onError, shardKey)`].join(`
89
+ `)},ar=e=>{const r=`${s(e.name)}Api`,t=e.methods.map(n=>n.verb==="query"?`${Y(n)}
90
+
91
+ ${nr(n)}`:Y(n)).join(`
92
+
93
+ `);return[`/** Functions declared in \`${l(e.name)}\`. */`,`class ${r}(private val client: Client) {`,t,"}"].join(`
94
+ `)},ir=({namespaces:e})=>{const r=e.map(i=>` val ${ce(i.name)}: ${s(i.name)}Api = ${s(i.name)}Api(client)`).join(`
95
+ `),t=e.flatMap(i=>i.methods),n=[`import dev.lunora.Client
96
+ `,...t.some(i=>i.verb==="query")?[`import dev.lunora.SubscriptionError
97
+ `]:[],`import dev.lunora.Verb
98
+ `,...t.some(i=>i.argsType===void 0||i.resultType===void 0)?[`import dev.lunora.WireValue
99
+ `]:[],...R(e).map(i=>`import ${g}.${i}
100
+ `)],a=[er,`package ${Z}
101
+ `,`
102
+ `,...n,`
103
+ `,e.map(i=>ar(i)).join(`
104
+
105
+ `),`
106
+
107
+ `,"/** Typed entry point: `Api(client).<namespace>.<function>(args)`. */\n",`class Api(client: Client) {
108
+ `,r.length>0?`${r}
109
+ `:` init { require(true) { client } }
110
+ `,`}
111
+ `].join("");return{[`${Z}/Api.kt`]:a}},or={id:"kotlin",render:ir,renderModels:Ue,requires:[],vendor:[{from:"src",to:"dev/lunora"}]},sr=new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","False","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","try","while","with","yield"]),w=`"""${f("python").join(`
112
+
113
+ `)}
114
+ """
115
+
116
+ `,V="lunora_api",z=e=>{const r=H(e);return sr.has(r)?`${r}_`:r},Q=e=>{const r=e.resultType??"Any",t=e.argsType===void 0?"self":`self, args: ${e.argsType}`,n=e.argsType===void 0?"{}":"args.to_dict()",a=`await self._client.${e.verb}("${d(e.functionPath)}", ${n}, shard_key)`;return[` async def ${z(e.functionName)}(${t}, *, shard_key: Optional[str] = None) -> ${r}:`,` """${l(e.summary)}"""`,` ${e.resultType===void 0?`return ${a}`:`return ${e.resultType}.from_dict(${a})`}`].join(`
117
+ `)},lr=e=>{const r=e.argsType===void 0?"{}":"args.to_dict()",t=["self",...e.argsType===void 0?[]:[`args: ${e.argsType}`],"on_data: Callback","on_error: Optional[ErrorCallback] = None","*","shard_key: Optional[str] = None"];return[` def subscribe_${z(e.functionName)}(`,...t.map(n=>` ${n},`)," ) -> Unsubscribe:",` """live ${l(e.summary)} — re-runs on every write to the tables it reads."""`,` return self._client.subscribe("${d(e.functionPath)}", ${r}, on_data, on_error, shard_key)`].join(`
118
+ `)},ur=e=>{const r=e.methods.map(t=>t.verb==="query"?`${Q(t)}
119
+
120
+ ${lr(t)}`:Q(t)).join(`
121
+
122
+ `);return[`class ${s(e.name)}Api:`,` """Functions declared in \`${l(e.name)}\`."""`,""," def __init__(self, client: LunoraClient) -> None:"," self._client = client","",r].join(`
123
+ `)},cr=e=>e.replaceAll(/^([ \t]*)except:$/gmu,"$1except Exception:"),dr=({models:e,namespaces:r})=>{const t=R(r),n=t.length>0?`from .models import ${t.join(", ")}
124
+ `:"",a=C(r).some(u=>u.verb==="query")?"Callback, ErrorCallback, LunoraClient, Unsubscribe":"LunoraClient",i=C(r).some(u=>u.resultType===void 0),o=r.map(u=>` self.${z(u.name)} = ${s(u.name)}Api(client)`).join(`
125
+ `),c=[w,`from typing import ${i?"Any, Optional":"Optional"}
126
+ `,`
127
+ `,`from lunora.client import ${a}
128
+ `,n,`
129
+
130
+ `,r.map(u=>ur(u)).join(`
131
+
132
+
133
+ `),`
134
+
135
+
136
+ `,`class Api:
137
+ `,' """Typed entry point: `Api(client).<namespace>.<function>(args)`."""\n',`
138
+ `,` def __init__(self, client: LunoraClient) -> None:
139
+ `,o.length>0?`${o}
140
+ `:` pass
141
+ `].join(""),p=["Api",...r.map(u=>`${s(u.name)}Api`)];return{[`${V}/__init__.py`]:[w,`from .api import ${p.join(", ")}
142
+ `,`
143
+ `,`__all__ = [${p.map(u=>`"${u}"`).join(", ")}]
144
+ `].join(""),[`${V}/api.py`]:c,[`${V}/models.py`]:e.length>0?`${w}${cr(e)}
145
+ `:`${w}# No typed argument or result schemas in this deployment.
146
+ `}},pr={id:"python",quicktype:{lang:"python",rendererOptions:{"python-version":"3.7"}},render:dr,requires:[],vendor:[{from:"lunora",to:"lunora"}]},L=`${f("ruby").map(e=>`# ${e}`).join(`
147
+ `)}
148
+
149
+ `,mr=new Set(["alias","and","begin","break","case","class","def","defined?","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield"]),pe=e=>d(e).replaceAll("#","\\#"),_=e=>{const r=H(e);return mr.has(r)?`${r}_`:r},$r=` def self.wire_args(model)
150
+ drop_nils(model.to_dynamic)
151
+ end
152
+
153
+ def self.drop_nils(value)
154
+ case value
155
+ when ::Hash then value.each_with_object({}) { |(key, item), out| out[key] = drop_nils(item) unless item.nil? }
156
+ when ::Array then value.map { |item| drop_nils(item) }
157
+ else value
158
+ end
159
+ end
160
+
161
+ `,X=e=>{const r=e.argsType===void 0?"shard_key: nil":"args, shard_key: nil",t=e.argsType===void 0?"{}":"LunoraApi.wire_args(args)",n=`@client.${e.verb}("${pe(e.functionPath)}", ${t}, shard_key)`,a=e.resultType===void 0?n:`${e.resultType}.from_dynamic!(${n})`;return[` # ${l(e.summary)}`,` def ${_(e.functionName)}(${r})`,` ${a}`," end"].join(`
162
+ `)},fr=e=>{const r=e.argsType===void 0?"on_data, on_error = nil, shard_key: nil":"args, on_data, on_error = nil, shard_key: nil",t=e.argsType===void 0?"{}":"LunoraApi.wire_args(args)";return[` # live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` def subscribe_${_(e.functionName)}(${r})`,` @client.subscribe("${pe(e.functionPath)}", ${t}, on_data, on_error, shard_key)`," end"].join(`
163
+ `)},yr=e=>{const r=e.methods.map(t=>t.verb==="query"?`${X(t)}
164
+
165
+ ${fr(t)}`:X(t)).join(`
166
+
167
+ `);return[` # Functions declared in \`${l(e.name)}\`.`,` class ${s(e.name)}Api`," def initialize(client)"," @client = client"," end","",r," end"].join(`
168
+ `)},hr=({models:e,namespaces:r})=>{const t=r.map(a=>`:${_(a.name)}`).join(", "),n=r.map(a=>` @${_(a.name)} = ${s(a.name)}Api.new(client)`).join(`
169
+ `);return{"api.rb":[`# frozen_string_literal: true
170
+
171
+ `,L,`require_relative "models"
172
+ `,`
173
+ `,`module LunoraApi
174
+ `,C(r).some(a=>a.argsType!==void 0)?$r:"",r.map(a=>yr(a)).join(`
175
+
176
+ `),`
177
+
178
+ `," # Typed entry point: `Api.new(client).<namespace>.<function>(args)`.\n",` class Api
179
+ `,t.length>0?` attr_reader ${t}
180
+
181
+ `:"",` def initialize(client)
182
+ `,n.length>0?`${n}
183
+ `:` @client = client
184
+ `,` end
185
+ `,` end
186
+ `,`end
187
+ `].join(""),"models.rb":e.length>0?`# frozen_string_literal: true
188
+
189
+ ${L}${e}
190
+ `:`# frozen_string_literal: true
191
+
192
+ ${L}# No typed argument or result schemas in this deployment.
193
+ `}},gr={id:"ruby",quicktype:{lang:"ruby",rendererOptions:{}},render:hr,requires:["dry-struct + dry-types (gems, required by the generated models)"],vendor:[{from:"lib/lunora.rb",to:"lunora.rb"},{from:"lib/lunora",to:"lunora"}]},k=`${f("rust").map(e=>`// ${e}`).join(`
194
+ `)}
195
+
196
+ `,vr=`${k}pub mod api;
197
+ pub mod models;
198
+ `,br=`# The generated Lunora Rust SDK, with the transport vendored under ./lunora.
199
+ #
200
+ # Add to a consuming crate:
201
+ #
202
+ # lunora-api = { path = "sdk/rust" }
203
+
204
+ [package]
205
+ name = "lunora-api"
206
+ version = "0.1.0"
207
+ edition = "2021"
208
+ publish = false
209
+
210
+ # Its own workspace root, so a consumer whose project IS a workspace does not
211
+ # adopt this directory as a member (which then fails to build on its own).
212
+ [workspace]
213
+
214
+ [dependencies]
215
+ lunora = { path = "lunora" }
216
+ serde = { version = "1", features = ["derive"] }
217
+ serde_json = "1"
218
+ `,wr=new Set(["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","static","struct","super","trait","true","try","type","typeof","unsafe","unsized","use","virtual","where","while","yield"]),S=e=>{const r=H(e);return wr.has(r)?`r#${r}`:r},jr=e=>`Verb::${s(e)}`,ee=e=>{const r=e.argsType===void 0?"&self, shard_key: Option<&str>":`&self, args: &${e.argsType}, shard_key: Option<&str>`,t=e.argsType===void 0?"&WireValue::Object(Vec::new())":"&from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?)",n=`self.client.call(${jr(e.verb)}, "${d(e.functionPath)}", ${t}, shard_key)`;return e.resultType===void 0?[` /// ${l(e.summary)}`,` pub fn ${S(e.functionName)}(${r}) -> Result<WireValue, ClientError> {`,` ${n}`," }"].join(`
219
+ `):[` /// ${l(e.summary)}`,` pub fn ${S(e.functionName)}(${r}) -> Result<${e.resultType}, ClientError> {`,` let raw = ${n}?;`," let json = encode_wire(&raw).map_err(ClientError::Wire)?;"," serde_json::from_value(json).map_err(|error| ClientError::Transport(error.to_string()))"," }"].join(`
220
+ `)},kr=e=>{const r=e.argsType===void 0?"":`args: &${e.argsType}, `,t=e.argsType===void 0?"WireValue::Object(Vec::new())":"from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?)";return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` pub fn subscribe_${S(e.functionName)}(`," &mut self,",` ${r}on_data: DataHandler,`," on_error: ErrorHandler,"," shard_key: Option<&str>,"," ) -> Result<String, ClientError> {"," let _ = shard_key;",` Ok(self.client.subscribe("${d(e.functionPath)}", ${t}, on_data, on_error))`," }"].join(`
221
+ `)},Tr=e=>{const r=`${s(e.name)}Api`,t=e.methods.map(n=>n.verb==="query"?`${ee(n)}
222
+
223
+ ${kr(n)}`:ee(n)).join(`
224
+
225
+ `);return[`/// Functions declared in \`${l(e.name)}\`.`,`pub struct ${r}<'client> {`," client: &'client mut Client,","}","",`impl<'client> ${r}<'client> {`,t,"}"].join(`
226
+ `)},_r=({models:e,namespaces:r})=>{const t=r.map(a=>[` /// Functions declared in \`${l(a.name)}\`.`,` pub fn ${S(a.name)}(&mut self) -> ${s(a.name)}Api<'_> {`,` ${s(a.name)}Api { client: self.client }`," }"].join(`
227
+ `)).join(`
228
+
229
+ `),n=[k,`#![allow(dead_code, unused_imports)]
230
+ `,`
231
+ `,`use lunora::client::{Client, ClientError, DataHandler, ErrorHandler, Verb};
232
+ `,`use lunora::wire::{encode_wire, from_model_json, WireValue};
233
+ `,`
234
+ `,`use crate::models::*;
235
+ `,`
236
+ `,r.map(a=>Tr(a)).join(`
237
+
238
+ `),`
239
+
240
+ `,"/// Typed entry point: `Api::new(&client).<namespace>().<function>(args)`.\n",`pub struct Api<'client> {
241
+ `,` client: &'client mut Client,
242
+ `,`}
243
+ `,`
244
+ `,`impl<'client> Api<'client> {
245
+ `,` pub fn new(client: &'client mut Client) -> Self {
246
+ `,` Self { client }
247
+ `,` }
248
+ `,t.length>0?`
249
+ ${t}
250
+ `:"",`}
251
+ `].join("");return{"Cargo.toml":br,"src/api.rs":n,"src/lib.rs":vr,"src/models.rs":e.length>0?`${k}#![allow(dead_code)]
252
+
253
+ ${e}
254
+ `:`${k}#![allow(dead_code)]
255
+
256
+ // No typed argument or result schemas in this deployment.
257
+ `}},Sr={id:"rust",quicktype:{lang:"rust",rendererOptions:{"just-types":"true"}},render:_r,requires:["serde (derive) + serde_json — declared in the emitted Cargo.toml, fetched by cargo"],vendor:[{from:"Cargo.toml",to:"lunora/Cargo.toml"},{from:"src",to:"lunora/src"}]},N=`${f("swift").map(e=>`// ${e}`).join(`
258
+ `)}
259
+
260
+ `,re="Sources/LunoraApi",Ar=`// swift-tools-version:5.9
261
+
262
+ import PackageDescription
263
+
264
+ // The generated Lunora Swift SDK, with the transport vendored under
265
+ // Sources/Lunora. Add to a consuming package — where "swift" below is the NAME OF
266
+ // THE DIRECTORY THIS FILE IS IN, which is how SwiftPM identifies a local path
267
+ // dependency. It ignores the "name:" field for that, and a bare product name in a
268
+ // target's dependencies does not resolve at all, so the directory name is the one
269
+ // spelling that works:
270
+ //
271
+ // dependencies: [.package(path: "sdk/swift")],
272
+ // targets: [
273
+ // .target(
274
+ // name: "YourTarget",
275
+ // dependencies: [.product(name: "LunoraApi", package: "swift")]
276
+ // )
277
+ // ]
278
+ let package = Package(
279
+ name: "LunoraSdk",
280
+ platforms: [.macOS(.v12), .iOS(.v15)],
281
+ products: [
282
+ .library(name: "LunoraApi", targets: ["LunoraApi"]),
283
+ .library(name: "Lunora", targets: ["Lunora"]),
284
+ ],
285
+ targets: [
286
+ .target(name: "Lunora"),
287
+ .target(name: "LunoraApi", dependencies: ["Lunora"]),
288
+ ]
289
+ )
290
+ `,Or=new Set(["as","associatedtype","borrowing","break","case","catch","class","consuming","continue","default","defer","deinit","do","else","enum","extension","fallthrough","false","fileprivate","for","func","guard","if","import","in","init","inout","internal","is","let","nil","nonisolated","open","operator","precedencegroup","private","protocol","public","repeat","rethrows","return","self","static","struct","subscript","super","switch","throw","throws","true","try","typealias","var","where","while"]),F=e=>{const r=s(e),t=r.charAt(0).toLowerCase()+r.slice(1);return Or.has(t)?`\`${t}\``:t},te=e=>{const r=e.argsType===void 0?"shardKey: String? = nil":`_ args: ${e.argsType}, shardKey: String? = nil`,t=e.argsType===void 0?"nil":"try LunoraClient.wireValue(args)",n=e.resultType??"Any",a=`try client.${e.verb}("${d(e.functionPath)}", args: ${t}, shardKey: shardKey)`,i=e.resultType===void 0?`return ${a}`:[`let raw = ${a}`," let data = try JSONSerialization.data(withJSONObject: raw, options: [.fragmentsAllowed])",` return try JSONDecoder().decode(${e.resultType}.self, from: data)`].join(`
291
+ `);return[` /// ${l(e.summary)}`,` public func ${F(e.functionName)}(${r}) throws -> ${n} {`,` ${i}`," }"].join(`
292
+ `)},Wr=e=>{const r=e.argsType===void 0?"":`_ args: ${e.argsType}, `,t=e.argsType===void 0?"nil":"try LunoraClient.wireValue(args)";return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`," @discardableResult",` public func subscribe${s(e.functionName)}(`,` ${r}onData: ((Any) -> Void)?,`," onError: ((LunoraSubscriptionError) -> Void)? = nil,"," shardKey: String? = nil"," ) throws -> LunoraUnsubscribe {",` client.subscribe("${d(e.functionPath)}", args: ${t}, onData: onData, onError: onError, shardKey: shardKey)`," }"].join(`
293
+ `)},Vr=e=>{const r=`${s(e.name)}API`,t=e.methods.map(n=>n.verb==="query"?`${te(n)}
294
+
295
+ ${Wr(n)}`:te(n)).join(`
296
+
297
+ `);return[`/// Functions declared in \`${l(e.name)}\`.`,`public struct ${r} {`," let client: LunoraClient","",t,"}"].join(`
298
+ `)},Lr=({models:e,namespaces:r})=>{const t=r.map(i=>` public let ${F(i.name)}: ${s(i.name)}API`).join(`
299
+ `),n=r.map(i=>` ${F(i.name)} = ${s(i.name)}API(client: client)`).join(`
300
+ `),a=[N,`import Foundation
301
+ `,`import Lunora
302
+ `,`
303
+ `,r.map(i=>Vr(i)).join(`
304
+
305
+ `),`
306
+
307
+ `,"/// Typed entry point: `API(client:).<namespace>.<function>(args)`.\n",`public struct API {
308
+ `,t.length>0?`${t}
309
+
310
+ `:"",` public init(client: LunoraClient) {
311
+ `,n.length>0?`${n}
312
+ `:` _ = client
313
+ `,` }
314
+ `,`}
315
+ `].join("");return{"Package.swift":Ar,[`${re}/Api.swift`]:a,[`${re}/Models.swift`]:e.length>0?`${N}${e}
316
+ `:`${N}import Foundation
317
+
318
+ // No typed argument or result schemas in this deployment.
319
+ `}},Nr={id:"swift",quicktype:{lang:"swift",rendererOptions:{"access-level":"public"}},render:Lr,requires:[],vendor:[{from:"Sources/Lunora",to:"Sources/Lunora"}]},Cr={go:Te,java:Xe,kotlin:or,python:pr,ruby:gr,rust:Sr,swift:Nr},Pr=Object.keys(Cr).toSorted((e,r)=>e.localeCompare(r)),Kr=async(e,r)=>{const t=me(e);$e(t);const n=r.renderModels?.(e),a=n===void 0?await ge(e,r):Object.values(n).join(`
320
+ `),i=fe(t,a);return{files:{...n,...r.render({models:a,namespaces:i})},undeclared:he(t,a),unrepresentable:ye(e)}};export{Pr as SDK_LANGUAGES,Cr as SDK_TARGETS,Kr as generateSdk,Ir as isTypedSchema};
@@ -0,0 +1,3 @@
1
+ import{S as b}from"./emit-B8FxCABN.mjs";import{n as p}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as x,objectSchema as l,validatorIrToJsonSchema as d}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const O="/_lunora/rest",k=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],T=e=>[...k,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const a=o.trim().toLowerCase();a!==""&&!t.includes(a)&&t.push(a)}return t.length===0?void 0:t.join(", ")},R=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},P=e=>e.scope==="public"?y(e.vary,...T(e),...f):y(e.vary,...f),q=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},j=e=>{const t=q(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},A=e=>e==="query"?"GET":"POST",h="#/components/responses/LunoraError",$=/:([A-Za-z_$][\w$]*)/gu,N=e=>[...e.matchAll($)].map(t=>t[1]),w=e=>e.replaceAll($,"{$1}"),u=e=>e.kind==="optional"?e.inner??e:e,C=e=>{const t=new Set(N(e.path)),r=[];for(const[o,a]of Object.entries(e.searchParams)){const c=u(a);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:a.kind!=="optional",schema:d(c)})}for(const[o,a]of Object.entries(e.params)){const c=u(a);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:a.kind!=="optional",schema:d(c)})}return r},v=e=>e?{content:{"application/json":{schema:d(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},E=e=>{const t=p(e.filePath),r=C(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:v(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:h}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:l(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:l(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:v(e.output),default:{$ref:h}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},_=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:R(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const a=P(r);return a!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:a,type:"string"}}),{headers:o}},I=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=j(r);if(o===void 0)return;const a=A(e.kind),c=a==="GET",n={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",..._(e.expose?.cache,c?"get":"post")},default:{$ref:h}},summary:`${a} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const s=Object.entries(e.args).map(([i,m])=>{const S=u(m);return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:m.kind!=="optional",schema:d(S)}});return s.length>0&&(n.parameters=s),{method:"get",operation:n,path:o}}return n.requestBody={content:{"application/json":{schema:l(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:n,path:o}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const s=w(n.path),i=r[s]??{};i[n.method.toLowerCase()]=E(n),r[s]=i,o.add(p(n.filePath))}const a=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of a){const{operation:s,pathKey:i}=L(n);r[i]={post:s},o.add(p(n.filePath))}for(const n of a){if(n.expose?.rest!==!0)continue;const s=I(n);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i}const c=[...o].toSorted((n,s)=>n.localeCompare(s)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:x,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},U=e=>`${JSON.stringify(D(e),void 0,2)}
2
+ `,W=e=>`${b}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
+ `;export{D as buildOpenApiDocument,U as emitOpenApi,W as emitOpenApiModule};
@@ -0,0 +1,2 @@
1
+ const m=/[^a-zA-Z0-9]+/gu,f=/([a-z0-9])([A-Z])/gu,l=t=>t.split(m).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),b=t=>t.replaceAll(f,"$1_$2").replaceAll(m,"_").toLowerCase(),c=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),h=t=>t==="query"?"query":t==="action"?"action":"mutation",n=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(s=>n(s,e+1));const a=t;if(a.type==="integer"&&a.format==="int64"||a.type==="string"&&a.contentEncoding==="base64")return!0;const{properties:r}=a;return r!==null&&typeof r=="object"&&Object.values(r).some(s=>n(s,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(s=>n(a[s],e+1))},A=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),y=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
2
+ `,"\\n").replaceAll("\r","\\r"),g=["$","{","'","$","'","}"].join(""),v=t=>y(t).split("$").join(g),p=t=>{const[e="",a=""]=t.name.split(":"),r=`${l(e)}${l(a)}`,s=t.params?.[0]?.schema,o=t.result?.schema;return{argsType:c(s)&&!n(s)?`${r}Args`:void 0,functionName:a,functionPath:t.name,namespace:e,resultType:c(o)&&!n(o)?`${r}Result`:void 0,summary:t.summary??t.name,verb:h(t["x-lunora-function-kind"])}},T=t=>{const e=new Map;for(const a of t.methods){const r=p(a),s=e.get(r.namespace);s===void 0?e.set(r.namespace,[r]):s.push(r)}return[...e.entries()].toSorted(([a],[r])=>a.localeCompare(r)).map(([a,r])=>({methods:r.toSorted((s,o)=>s.functionName.localeCompare(o.functionName)),name:a}))},S=t=>t.methods.flatMap(e=>{const a=p(e);return[{name:a.argsType,schema:e.params?.[0]?.schema},{name:a.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,a)=>e.name.localeCompare(a.name)),$=/^[A-Za-z][A-Za-z0-9]*$/u,d=t=>$.test(t),w=t=>{const e=new Map;for(const a of t.methods){const r=l(a.functionName);if(!d(r))throw new Error(`sdk: function "${a.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const s=a.verb==="query"?[r,`Subscribe${r}`]:[r];for(const o of s){const i=e.get(o);if(i!==void 0)throw new Error(`sdk: functions "${i}" and "${a.functionPath}" both generate "${o}" — rename one so the generated methods stay distinct.`);e.set(o,a.functionPath)}}},M=t=>{const e=new Map;for(const a of t){const r=l(a.name);if(!d(r))throw new Error(`sdk: namespace "${a.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const s=e.get(r);if(s!==void 0)throw new Error(`sdk: namespaces "${s}" and "${a.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,a.name),w(a)}},u=t=>t.flatMap(e=>e.methods),C=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],E=(t,e)=>{const a=r=>r!==void 0&&new RegExp(String.raw`\b${r}\b`,"u").test(e)?r:void 0;return t.map(r=>({methods:r.methods.map(s=>({...s,argsType:a(s.argsType),resultType:a(s.resultType)})),name:r.name}))},k=t=>t.methods.filter(e=>n(e.params?.[0]?.schema)||n(e.result?.schema)).map(e=>e.name).toSorted((e,a)=>e.localeCompare(a)),O=(t,e)=>[...new Set(u(t).flatMap(a=>[a.argsType,a.resultType]).filter(a=>a!==void 0&&!new RegExp(String.raw`\b${a}\b`,"u").test(e)))].toSorted((a,r)=>a.localeCompare(r)),j=t=>[...new Set(u(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,a)=>e.localeCompare(a));export{u as allMethods,M as assertGeneratable,A as commentText,C as generatedHeaderLines,n as hasUnrepresentableWireType,c as isTypedSchema,v as kotlinLiteral,S as modelSources,p as parseMethod,T as parseSpec,j as referencedModels,y as stringLiteral,l as toPascalCase,b as toSnakeCase,O as undeclaredModels,k as unrepresentableFunctions,h as verbForKind,E as withDeclaredModels};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.102",
3
+ "version": "1.0.0-alpha.104",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,8 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.74",
50
- "@lunora/agent": "1.0.0-alpha.50",
49
+ "@lunora/advisor": "1.0.0-alpha.75",
50
+ "@lunora/agent": "1.0.0-alpha.51",
51
51
  "@lunora/container": "1.0.0-alpha.29",
52
52
  "@lunora/errors": "1.0.0-alpha.20",
53
53
  "@lunora/platform": "1.0.0-alpha.9",
@@ -56,6 +56,7 @@
56
56
  "@lunora/values": "1.0.0-alpha.25",
57
57
  "@lunora/workflow": "1.0.0-alpha.26",
58
58
  "jsonc-parser": "^3.3.1",
59
+ "quicktype-core": "^26.0.0",
59
60
  "ts-morph": "^28.0.0"
60
61
  },
61
62
  "engines": {
@@ -1,3 +0,0 @@
1
- import{S as a}from"./emit-B8FxCABN.mjs";import{n as i}from"./paths-BmX5O1sG.mjs";import{objectSchema as s,LUNORA_ERROR_CODES as c}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const m="1.3.2",p={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},u=e=>{const t=i(e.filePath),r=`${t}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${r}", "args": { … } }\`).`,errors:c.map((o,n)=>({code:-32e3-n,data:{code:o},message:o})),name:r,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:s(e.args)}],result:{name:"result",schema:p},summary:`${e.kind}: ${r}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:t}]}},d=e=>{const t=e.version??"0.0.0",r=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream").map(o=>u(o)).toSorted((o,n)=>o.name.localeCompare(n.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:t},methods:r,openrpc:m}},R=e=>`${JSON.stringify(d(e),void 0,2)}
2
- `,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
- `;export{m as OPENRPC_VERSION,d as buildOpenRpcDocument,R as emitOpenRpc,O as emitOpenRpcModule};
@@ -1,3 +0,0 @@
1
- import{S}from"./emit-B8FxCABN.mjs";import{n as p}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as b,objectSchema as l,validatorIrToJsonSchema as d}from"./LUNORA_ERROR_CODES-zfAI2OFs.mjs";const x="/_lunora/rest",O=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],T=e=>[...O,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const a=o.trim().toLowerCase();a!==""&&!t.includes(a)&&t.push(a)}return t.length===0?void 0:t.join(", ")},k=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},R=e=>e.scope==="public"?y(e.vary,...T(e),...f):y(e.vary,...f),P=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},j=e=>{const t=P(e);if(t!==void 0)return`${x}/${t.namespace}/${t.name}`},q=e=>e==="query"?"GET":"POST",h="#/components/responses/LunoraError",$=/:([A-Za-z_$][\w$]*)/gu,A=e=>[...e.matchAll($)].map(t=>t[1]),N=e=>e.replaceAll($,"{$1}"),u=e=>e.kind==="optional"?e.inner??e:e,w=e=>{const t=new Set(A(e.path)),r=[];for(const[o,a]of Object.entries(e.searchParams)){const c=u(a);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:a.kind!=="optional",schema:d(c)})}for(const[o,a]of Object.entries(e.params)){const c=u(a);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:a.kind!=="optional",schema:d(c)})}return r},C=e=>e?{content:{"application/json":{schema:d(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},E=e=>{const t=p(e.filePath),r=w(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:C(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:h}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:l(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:l(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:{content:{"application/json":{schema:{description:"RPC result. The shape is TS-inferred from the function's return type; best-effort — any JSON."}}},description:"Successful RPC result (TypeScript-inferred return shape, documented best-effort)."},default:{$ref:h}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},_=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:k(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const a=R(r);return a!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:a,type:"string"}}),{headers:o}},I=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=j(r);if(o===void 0)return;const a=q(e.kind),c=a==="GET",n={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",..._(e.expose?.cache,c?"get":"post")},default:{$ref:h}},summary:`${a} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const s=Object.entries(e.args).map(([i,m])=>{const v=u(m);return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:m.kind!=="optional",schema:d(v)}});return s.length>0&&(n.parameters=s),{method:"get",operation:n,path:o}}return n.requestBody={content:{"application/json":{schema:l(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:n,path:o}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const s=N(n.path),i=r[s]??{};i[n.method.toLowerCase()]=E(n),r[s]=i,o.add(p(n.filePath))}const a=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of a){const{operation:s,pathKey:i}=L(n);r[i]={post:s},o.add(p(n.filePath))}for(const n of a){if(n.expose?.rest!==!0)continue;const s=I(n);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i}const c=[...o].toSorted((n,s)=>n.localeCompare(s)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:b,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},U=e=>`${JSON.stringify(D(e),void 0,2)}
2
- `,W=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
- `;export{D as buildOpenApiDocument,U as emitOpenApi,W as emitOpenApiModule};