@gencow/core 0.1.28 → 0.1.29

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.
Files changed (65) hide show
  1. package/dist/auth-config.d.ts +92 -5
  2. package/dist/config.d.ts +107 -0
  3. package/dist/config.js +12 -0
  4. package/dist/context.d.ts +139 -0
  5. package/dist/context.js +3 -0
  6. package/dist/crud.d.ts +5 -5
  7. package/dist/crud.js +19 -35
  8. package/dist/document-types.d.ts +2 -2
  9. package/dist/http-action.d.ts +77 -0
  10. package/dist/http-action.js +41 -0
  11. package/dist/index.d.ts +21 -5
  12. package/dist/index.js +12 -3
  13. package/dist/platform-capacity-profile.d.ts +19 -0
  14. package/dist/platform-capacity-profile.js +94 -0
  15. package/dist/procedure.d.ts +58 -0
  16. package/dist/procedure.js +115 -0
  17. package/dist/rag-schema.d.ts +449 -540
  18. package/dist/reactive-mutation-types.d.ts +11 -0
  19. package/dist/reactive-mutation-types.js +1 -0
  20. package/dist/reactive-mutation.d.ts +51 -0
  21. package/dist/reactive-mutation.js +75 -0
  22. package/dist/reactive-query-types.d.ts +12 -0
  23. package/dist/reactive-query-types.js +1 -0
  24. package/dist/reactive-query.d.ts +14 -0
  25. package/dist/reactive-query.js +28 -0
  26. package/dist/reactive-realtime.d.ts +48 -0
  27. package/dist/reactive-realtime.js +236 -0
  28. package/dist/reactive.d.ts +16 -5
  29. package/dist/reactive.js +65 -0
  30. package/dist/runtime-env-policy.js +1 -1
  31. package/dist/server.d.ts +1 -1
  32. package/dist/storage-metering.d.ts +13 -0
  33. package/dist/storage-metering.js +18 -0
  34. package/dist/storage.d.ts +3 -1
  35. package/dist/storage.js +11 -7
  36. package/dist/wake-app-result.d.ts +22 -0
  37. package/dist/wake-app-result.js +11 -0
  38. package/dist/workflow-types.d.ts +13 -1
  39. package/dist/workflow.d.ts +1 -1
  40. package/dist/workflow.js +136 -11
  41. package/dist/workflows-api.js +71 -3
  42. package/package.json +4 -1
  43. package/src/auth-config.ts +104 -3
  44. package/src/config.ts +119 -0
  45. package/src/context.ts +152 -0
  46. package/src/crud.ts +18 -35
  47. package/src/document-types.ts +9 -2
  48. package/src/http-action.ts +101 -0
  49. package/src/index.ts +77 -19
  50. package/src/platform-capacity-profile.ts +114 -0
  51. package/src/procedure.ts +283 -0
  52. package/src/reactive-mutation-types.ts +13 -0
  53. package/src/reactive-mutation.ts +115 -0
  54. package/src/reactive-query-types.ts +14 -0
  55. package/src/reactive-query.ts +48 -0
  56. package/src/reactive-realtime.ts +267 -0
  57. package/src/runtime-env-policy.ts +1 -1
  58. package/src/server.ts +6 -1
  59. package/src/storage-metering.ts +35 -0
  60. package/src/storage.ts +14 -6
  61. package/src/wake-app-result.ts +37 -0
  62. package/src/workflow-types.ts +13 -1
  63. package/src/workflow.ts +166 -12
  64. package/src/workflows-api.ts +82 -3
  65. package/src/reactive.ts +0 -593
package/dist/index.d.ts CHANGED
@@ -4,16 +4,30 @@
4
4
  * Provides: query, mutation, storage, scheduler, auth
5
5
  * All with Convex-compatible DX patterns.
6
6
  */
7
- export type { GencowCtx, AuthCtx, UserIdentity, QueryDef, MutationDef, RealtimeCtx, HttpActionDef, HttpActionRequest, HttpActionResponse, HttpActionHandler, AIContext, AIMessage, AIResult, } from "./reactive.js";
7
+ export type { GencowCtx, AuthCtx, UserIdentity, RealtimeCtx, RealtimeNotifyEvent, AIContext, AIMessage, AIResult, } from "./context.js";
8
+ export { defineApi } from "./context.js";
9
+ export type { QueryDef } from "./reactive-query-types.js";
10
+ export type { MutationDef } from "./reactive-mutation-types.js";
11
+ export type { HttpActionDef, HttpActionRequest, HttpActionResponse, HttpActionHandler, } from "./http-action.js";
8
12
  export type { SearchPrimitive, SearchScope, SearchFilter, SearchOptions, VectorSearchOptions, HybridSearchOptions, SearchHit, SearchResponse, SearchTierConfig, } from "./search-types.js";
9
13
  export type { DocumentVisibility, DocumentConvertMode, DocumentConvertProvider, DocumentResolvedProvider, DocumentConvertInput, DocumentPage, DocumentSection, DocumentProviderTrace, DocumentConvertResult, DocumentCacheArtifact, DocumentCacheKeyInput, GencowServicesCtx, WorkflowDocumentServicesCtx, } from "./document-types.js";
10
14
  export { buildDocumentCacheKey } from "./document-types.js";
15
+ export type { WakeAppBootFailedResult, WakeAppDeferredResult, WakeAppDeferredStatus, WakeAppResult, WakeAppSuccessResult, WakeAppSuccessStatus, } from "./wake-app-result.js";
16
+ export { DEFAULT_WAKE_RETRY_AFTER_SEC, buildWakeAppBootFailedResult, buildWakeAppSuccessResult, isWakeAppDeferredResult, } from "./wake-app-result.js";
17
+ export type { PlatformCapacityPreset, PlatformCapacityProfileName } from "./platform-capacity-profile.js";
18
+ export { PLATFORM_CAPACITY_ENV_KEYS, PLATFORM_CAPACITY_PRESETS, PLATFORM_CAPACITY_PROFILE_ENV, detectPlatformCapacityProfile, resolvePlatformCapacityPreset, } from "./platform-capacity-profile.js";
11
19
  export type { RagIngestReindexMode, RagIngestInput, RagIngestWorkflowArgs, RagIngestStartResult, RagIngestJobStatus, RagIngestJobRecord, } from "./rag-ingest-types.js";
12
20
  export type { CitationCoverage, ClaimSupportStatus, GroundedAnswerMode, Citation, ClaimEvidenceMap, GroundedAnswer, GroundingBudget, GroundedClaimInput, GroundedCompareInput, GroundedTopicInput, GroundedAnswerInput, GroundingRuntime, } from "./grounded-answer-types.js";
13
21
  export { DEFAULT_GROUNDING_BUDGET } from "./grounded-answer-types.js";
14
22
  export type { RagOperationKind, RagOperationMetricUnit, RagIndexHealth, RagOperationMetric, RagOperationsSummary, RagEvaluationExpectedClaim, RagEvaluationFixture, RagEvaluationFixtureResult, RagEvaluationRunResult, RagReindexMode, RagReindexPlan, } from "./rag-operations-types.js";
15
- export { ragCorpora, ragSources, ragSections, ragChunks, ragIngestJobs, ragOperationMetrics } from "./rag-schema.js";
16
- export { query, mutation, httpAction, buildRealtimeCtx, subscribe, unsubscribe, registerClient, deregisterClient, handleWsMessage, getQueryHandler, getQueryDef, getRegisteredQueries, getRegisteredMutations, getRegisteredHttpActions, } from "./reactive.js";
23
+ export { ragCorpora, ragSources, ragSections, ragChunks, ragIngestJobs, ragOperationMetrics, } from "./rag-schema.js";
24
+ export { buildQuerySubscriptionKey, subscriptionKeyMatchesQueryKey } from "./reactive-realtime.js";
25
+ export { query, getQueryHandler, getQueryDef, getRegisteredQueries } from "./reactive-query.js";
26
+ export { mutation, getRegisteredMutations } from "./reactive-mutation.js";
27
+ export { procQuery, procMutation } from "./procedure.js";
28
+ export type { GencowProcedureBuilder, GencowProcedureDef, GencowProcedureMiddleware, GencowProcedureHandler, } from "./procedure.js";
29
+ export { httpAction, getRegisteredHttpActions } from "./http-action.js";
30
+ export { subscribe, unsubscribe, registerClient, deregisterClient, buildRealtimeCtx, handleWsMessage, } from "./reactive-realtime.js";
17
31
  export type { Storage, StoredFile } from "./storage.js";
18
32
  export { createScheduler, getSchedulerInfo } from "./scheduler.js";
19
33
  export type { Scheduler, ScheduleOptions, FailedJob, CreateSchedulerOptions, ScheduledJobRecord, } from "./scheduler.js";
@@ -29,11 +43,13 @@ export { filterTenantRuntimeEnvVars, isReservedTenantRuntimeEnvKey } from "./run
29
43
  export { cronJobs } from "./crons.js";
30
44
  export type { CronJobsBuilder, CronJobDef, IntervalOptions, DailyOptions, WeeklyOptions } from "./crons.js";
31
45
  export { defineAuth } from "./auth-config.js";
32
- export type { GencowAuthConfig, AuthEmailVerification } from "./auth-config.js";
46
+ export type { GencowAuthConfig, AuthEmailVerification, AuthPasswordReset, AuthEvents, AuthHookContext, AuthUserLike, AuthOAuthConfig, SocialProviderConfig, SocialProvidersConfig, KakaoConfig, NaverConfig, CustomOAuthProvider, OAuthUserInfo, } from "./auth-config.js";
47
+ export { defineConfig } from "./config.js";
48
+ export type { GencowConfig, GencowDbConfig, GencowDeployConfig } from "./config.js";
33
49
  export { ownerRls, getOwnerRlsMeta, registerOwnerRls } from "./rls.js";
34
50
  export type { OwnerRlsMeta } from "./rls.js";
35
51
  export { createRlsDb } from "./rls-db.js";
36
52
  export type { RlsSessionContext } from "./rls-db.js";
37
- export { crud, parseFilterNode, applyFilterOp, getOwnerRlsTables, getRegisteredCrudCodegenMeta } from "./crud.js";
53
+ export { crud, parseFilterNode, applyFilterOp, getOwnerRlsTables, getRegisteredCrudCodegenMeta, } from "./crud.js";
38
54
  export type { CrudCodegenMeta } from "./crud.js";
39
55
  export { crud as gencowCrud } from "./crud.js";
package/dist/index.js CHANGED
@@ -4,10 +4,18 @@
4
4
  * Provides: query, mutation, storage, scheduler, auth
5
5
  * All with Convex-compatible DX patterns.
6
6
  */
7
+ export { defineApi } from "./context.js";
7
8
  export { buildDocumentCacheKey } from "./document-types.js";
9
+ export { DEFAULT_WAKE_RETRY_AFTER_SEC, buildWakeAppBootFailedResult, buildWakeAppSuccessResult, isWakeAppDeferredResult, } from "./wake-app-result.js";
10
+ export { PLATFORM_CAPACITY_ENV_KEYS, PLATFORM_CAPACITY_PRESETS, PLATFORM_CAPACITY_PROFILE_ENV, detectPlatformCapacityProfile, resolvePlatformCapacityPreset, } from "./platform-capacity-profile.js";
8
11
  export { DEFAULT_GROUNDING_BUDGET } from "./grounded-answer-types.js";
9
- export { ragCorpora, ragSources, ragSections, ragChunks, ragIngestJobs, ragOperationMetrics } from "./rag-schema.js";
10
- export { query, mutation, httpAction, buildRealtimeCtx, subscribe, unsubscribe, registerClient, deregisterClient, handleWsMessage, getQueryHandler, getQueryDef, getRegisteredQueries, getRegisteredMutations, getRegisteredHttpActions, } from "./reactive.js";
12
+ export { ragCorpora, ragSources, ragSections, ragChunks, ragIngestJobs, ragOperationMetrics, } from "./rag-schema.js";
13
+ export { buildQuerySubscriptionKey, subscriptionKeyMatchesQueryKey } from "./reactive-realtime.js";
14
+ export { query, getQueryHandler, getQueryDef, getRegisteredQueries } from "./reactive-query.js";
15
+ export { mutation, getRegisteredMutations } from "./reactive-mutation.js";
16
+ export { procQuery, procMutation } from "./procedure.js";
17
+ export { httpAction, getRegisteredHttpActions } from "./http-action.js";
18
+ export { subscribe, unsubscribe, registerClient, deregisterClient, buildRealtimeCtx, handleWsMessage, } from "./reactive-realtime.js";
11
19
  export { createScheduler, getSchedulerInfo } from "./scheduler.js";
12
20
  export { workflow, getWorkflowDef, getRegisteredWorkflows, getWorkflowResumeActionName, getWorkflowRealtimeKey, createWorkflowRealtimeToken, serializeWorkflowValue, deserializeWorkflowValue, parseWorkflowDurationMs, DEFAULT_WORKFLOW_MAX_DURATION_MS, DEFAULT_WORKFLOW_MAX_RETRIES, WORKFLOW_RESUME_ACTION_PREFIX, WORKFLOW_REALTIME_KEY_PREFIX, } from "./workflow.js";
13
21
  export { deriveWorkflowStatus } from "./workflow-types.js";
@@ -17,9 +25,10 @@ export { withRetry } from "./retry.js";
17
25
  export { filterTenantRuntimeEnvVars, isReservedTenantRuntimeEnvKey } from "./runtime-env-policy.js";
18
26
  export { cronJobs } from "./crons.js";
19
27
  export { defineAuth } from "./auth-config.js";
28
+ export { defineConfig } from "./config.js";
20
29
  // ─── RLS + CRUD Factory ───────────
21
30
  export { ownerRls, getOwnerRlsMeta, registerOwnerRls } from "./rls.js";
22
31
  export { createRlsDb } from "./rls-db.js";
23
- export { crud, parseFilterNode, applyFilterOp, getOwnerRlsTables, getRegisteredCrudCodegenMeta } from "./crud.js";
32
+ export { crud, parseFilterNode, applyFilterOp, getOwnerRlsTables, getRegisteredCrudCodegenMeta, } from "./crud.js";
24
33
  // Deprecated alias — 하위호환용, 향후 메이저 버전에서 제거 예정
25
34
  export { crud as gencowCrud } from "./crud.js";
@@ -0,0 +1,19 @@
1
+ export type PlatformCapacityProfileName = "prod" | "dev" | "local";
2
+ export interface PlatformCapacityPreset {
3
+ profile: PlatformCapacityProfileName;
4
+ maxConcurrentRunning: number | null;
5
+ maxConcurrentWake: number | null;
6
+ maxWakeQueueMs: number;
7
+ minAvailableRamMB: number | null;
8
+ evictionThresholdMB: number | null;
9
+ sleepTimeoutMinutes: number;
10
+ sleepMaxPerCycle: number;
11
+ warmPoolMinIdle: number;
12
+ warmPoolMax: number;
13
+ deployCandidateReserve: number;
14
+ }
15
+ export declare const PLATFORM_CAPACITY_PROFILE_ENV = "GENCOW_CAPACITY_PROFILE";
16
+ export declare const PLATFORM_CAPACITY_ENV_KEYS: readonly ["GENCOW_CAPACITY_PROFILE", "MAX_CONCURRENT_RUNNING", "MAX_CONCURRENT_WAKE", "MAX_WAKE_QUEUE_MS", "MIN_AVAILABLE_RAM_MB", "WAKE_RETRY_AFTER_SEC", "EVICTION_THRESHOLD_MB", "GENCOW_SLEEP_TIMEOUT_MINUTES", "GENCOW_SLEEP_MAX_PER_CYCLE", "WARM_POOL_MIN_IDLE", "WARM_POOL_MAX", "DEPLOY_CANDIDATE_RESERVE", "GENCOW_APP_PORT_RANGE", "COWBOX_WARM_POOL_PORT_RANGE"];
17
+ export declare const PLATFORM_CAPACITY_PRESETS: Record<PlatformCapacityProfileName, PlatformCapacityPreset>;
18
+ export declare function detectPlatformCapacityProfile(env?: Record<string, string | undefined>): PlatformCapacityProfileName;
19
+ export declare function resolvePlatformCapacityPreset(env?: Record<string, string | undefined>): PlatformCapacityPreset;
@@ -0,0 +1,94 @@
1
+ export const PLATFORM_CAPACITY_PROFILE_ENV = "GENCOW_CAPACITY_PROFILE";
2
+ export const PLATFORM_CAPACITY_ENV_KEYS = [
3
+ PLATFORM_CAPACITY_PROFILE_ENV,
4
+ "MAX_CONCURRENT_RUNNING",
5
+ "MAX_CONCURRENT_WAKE",
6
+ "MAX_WAKE_QUEUE_MS",
7
+ "MIN_AVAILABLE_RAM_MB",
8
+ "WAKE_RETRY_AFTER_SEC",
9
+ "EVICTION_THRESHOLD_MB",
10
+ "GENCOW_SLEEP_TIMEOUT_MINUTES",
11
+ "GENCOW_SLEEP_MAX_PER_CYCLE",
12
+ "WARM_POOL_MIN_IDLE",
13
+ "WARM_POOL_MAX",
14
+ "DEPLOY_CANDIDATE_RESERVE",
15
+ "GENCOW_APP_PORT_RANGE",
16
+ "COWBOX_WARM_POOL_PORT_RANGE",
17
+ ];
18
+ export const PLATFORM_CAPACITY_PRESETS = Object.freeze({
19
+ prod: Object.freeze({
20
+ profile: "prod",
21
+ maxConcurrentRunning: 600,
22
+ maxConcurrentWake: 20,
23
+ maxWakeQueueMs: 5000,
24
+ minAvailableRamMB: 8192,
25
+ evictionThresholdMB: 16384,
26
+ sleepTimeoutMinutes: 15,
27
+ sleepMaxPerCycle: 50,
28
+ warmPoolMinIdle: 10,
29
+ warmPoolMax: 650,
30
+ deployCandidateReserve: 40,
31
+ }),
32
+ dev: Object.freeze({
33
+ profile: "dev",
34
+ maxConcurrentRunning: 60,
35
+ maxConcurrentWake: 5,
36
+ maxWakeQueueMs: 3000,
37
+ minAvailableRamMB: 2048,
38
+ evictionThresholdMB: 4096,
39
+ sleepTimeoutMinutes: 10,
40
+ sleepMaxPerCycle: 20,
41
+ warmPoolMinIdle: 3,
42
+ warmPoolMax: 70,
43
+ deployCandidateReserve: 5,
44
+ }),
45
+ local: Object.freeze({
46
+ profile: "local",
47
+ maxConcurrentRunning: null,
48
+ maxConcurrentWake: null,
49
+ maxWakeQueueMs: 5000,
50
+ minAvailableRamMB: null,
51
+ evictionThresholdMB: null,
52
+ sleepTimeoutMinutes: 30,
53
+ sleepMaxPerCycle: 10,
54
+ warmPoolMinIdle: 3,
55
+ warmPoolMax: 10,
56
+ deployCandidateReserve: 0,
57
+ }),
58
+ });
59
+ function normalizeDomain(value) {
60
+ return (value || "")
61
+ .trim()
62
+ .toLowerCase()
63
+ .replace(/^https?:\/\//, "")
64
+ .replace(/\/.*$/, "");
65
+ }
66
+ export function detectPlatformCapacityProfile(env = process.env) {
67
+ const explicit = env[PLATFORM_CAPACITY_PROFILE_ENV]?.trim().toLowerCase();
68
+ if (explicit) {
69
+ if (["prod", "production", "128gb"].includes(explicit))
70
+ return "prod";
71
+ if (["dev", "development", "16gb"].includes(explicit))
72
+ return "dev";
73
+ if (["local", "test", "disabled"].includes(explicit))
74
+ return "local";
75
+ throw new Error(`Invalid ${PLATFORM_CAPACITY_PROFILE_ENV}: ${explicit}. Expected prod, dev, or local.`);
76
+ }
77
+ const baseDomain = normalizeDomain(env.BASE_DOMAIN);
78
+ if (baseDomain === "gencow.dev")
79
+ return "dev";
80
+ if (baseDomain === "gencow.app")
81
+ return "prod";
82
+ const platformUrl = normalizeDomain(env.GENCOW_PLATFORM_URL);
83
+ if (platformUrl === "gencow.dev")
84
+ return "dev";
85
+ if (platformUrl === "gencow.app")
86
+ return "prod";
87
+ if (env.NODE_ENV === "production" && env.IS_PLATFORM === "true")
88
+ return "prod";
89
+ return "local";
90
+ }
91
+ export function resolvePlatformCapacityPreset(env = process.env) {
92
+ const profile = detectPlatformCapacityProfile(env);
93
+ return { ...PLATFORM_CAPACITY_PRESETS[profile] };
94
+ }
@@ -0,0 +1,58 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { GencowCtx } from "./context.js";
3
+ type InferInputSchema<TSchema> = TSchema extends {
4
+ "~standard": {
5
+ types: {
6
+ input: infer TInput;
7
+ };
8
+ };
9
+ } ? TInput : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferInput<TSchema> : unknown;
10
+ type InferOutputSchema<TSchema> = TSchema extends {
11
+ "~standard": {
12
+ types: {
13
+ output: infer TOutput;
14
+ };
15
+ };
16
+ } ? TOutput : TSchema extends {
17
+ _output: infer TOutput;
18
+ } ? TOutput : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : unknown;
19
+ type NextFn<TContext, TInput, TOutput> = (overrides?: {
20
+ context?: TContext;
21
+ input?: TInput;
22
+ }) => Promise<TOutput>;
23
+ export type GencowProcedureMiddleware<TContext, TInput, TOutput> = (options: {
24
+ context: TContext;
25
+ input: TInput;
26
+ next: NextFn<TContext, TInput, TOutput>;
27
+ }) => Promise<TOutput> | TOutput;
28
+ export type GencowProcedureHandler<TContext, TInput, TOutput> = (options: {
29
+ context: TContext;
30
+ input: TInput;
31
+ }) => Promise<TOutput> | TOutput;
32
+ export interface GencowProcedureDef<TKind extends "query" | "mutation" = "query" | "mutation", TContext = any, TInput = unknown, TOutput = unknown> {
33
+ kind: TKind;
34
+ name: string;
35
+ /** When false (default), RPC requires an authenticated user. */
36
+ isPublic: boolean;
37
+ middlewares: readonly GencowProcedureMiddleware<TContext, TInput, TOutput>[];
38
+ inputSchema?: StandardSchemaV1;
39
+ outputSchema?: StandardSchemaV1;
40
+ inputValidationIndex: number;
41
+ outputValidationIndex: number;
42
+ handler: (context: TContext, input: TInput) => Promise<TOutput>;
43
+ }
44
+ export interface GencowProcedureBuilder<TKind extends "query" | "mutation" = "query" | "mutation", TContext = any, TInput = unknown, TOutput = unknown> {
45
+ name(name: string): GencowProcedureBuilder<TKind, TContext, TInput, TOutput>;
46
+ /**
47
+ * Allow calling this procedure without authentication (like `query("x", { public: true, ... })`).
48
+ * Default is authenticated-only.
49
+ */
50
+ allowPublic(): GencowProcedureBuilder<TKind, TContext, TInput, TOutput>;
51
+ use(middleware: GencowProcedureMiddleware<TContext, TInput, TOutput>): GencowProcedureBuilder<TKind, TContext, TInput, TOutput>;
52
+ input<TNextSchema extends StandardSchemaV1>(schema: TNextSchema): GencowProcedureBuilder<TKind, TContext, InferInputSchema<TNextSchema>, TOutput>;
53
+ output<TNextSchema extends StandardSchemaV1>(schema: TNextSchema): GencowProcedureBuilder<TKind, TContext, TInput, InferOutputSchema<TNextSchema>>;
54
+ handler(handler: GencowProcedureHandler<TContext, TInput, TOutput>): GencowProcedureDef<TKind, TContext, TInput, TOutput>;
55
+ }
56
+ export declare const procQuery: GencowProcedureBuilder<"query", GencowCtx>;
57
+ export declare const procMutation: GencowProcedureBuilder<"mutation", GencowCtx>;
58
+ export {};
@@ -0,0 +1,115 @@
1
+ function hasStandardSchema(schema) {
2
+ return (!!schema &&
3
+ typeof schema === "object" &&
4
+ "~standard" in schema &&
5
+ !!schema["~standard"] &&
6
+ typeof schema["~standard"].validate === "function");
7
+ }
8
+ async function validateWithSchema(schema, value) {
9
+ if (!schema)
10
+ return value;
11
+ if (hasStandardSchema(schema)) {
12
+ const result = (await schema["~standard"].validate(value));
13
+ if ("issues" in result && result.issues.length > 0) {
14
+ throw new Error(result.issues[0]?.message ?? "Validation failed");
15
+ }
16
+ if ("value" in result) {
17
+ return result.value;
18
+ }
19
+ throw new Error("Validation failed");
20
+ }
21
+ throw new Error("procQuery/procMutation only supports Standard Schema v1 validators");
22
+ }
23
+ function composeMiddlewares(middlewares, handler, inputSchema, outputSchema, inputValidationIndex, outputValidationIndex) {
24
+ return async (initialContext, initialInput) => {
25
+ let idx = -1;
26
+ const boundedInputValidationIndex = Math.min(Math.max(0, inputValidationIndex), middlewares.length);
27
+ const boundedOutputValidationIndex = Math.min(Math.max(0, outputValidationIndex), middlewares.length);
28
+ const run = async (currentIdx, context, input) => {
29
+ if (currentIdx <= idx) {
30
+ throw new Error("next() called multiple times in the same middleware");
31
+ }
32
+ idx = currentIdx;
33
+ let currentInput = input;
34
+ if (currentIdx === boundedInputValidationIndex) {
35
+ currentInput = (await validateWithSchema(inputSchema, currentInput));
36
+ }
37
+ if (currentIdx === middlewares.length) {
38
+ const output = await handler({ context, input: currentInput });
39
+ if (currentIdx === boundedOutputValidationIndex) {
40
+ return await validateWithSchema(outputSchema, output);
41
+ }
42
+ return output;
43
+ }
44
+ const middleware = middlewares[currentIdx];
45
+ const output = await middleware({
46
+ context,
47
+ input: currentInput,
48
+ next: async (overrides) => {
49
+ return await run(currentIdx + 1, (overrides?.context ?? context), (overrides?.input ?? currentInput));
50
+ },
51
+ });
52
+ if (currentIdx === boundedOutputValidationIndex) {
53
+ return await validateWithSchema(outputSchema, output);
54
+ }
55
+ return output;
56
+ };
57
+ return await run(0, initialContext, initialInput);
58
+ };
59
+ }
60
+ class GencowProcedureBuilderImpl {
61
+ kind;
62
+ procedureName;
63
+ middlewares;
64
+ inputSchema;
65
+ outputSchema;
66
+ inputValidationIndex;
67
+ outputValidationIndex;
68
+ isPublic;
69
+ constructor(kind, procedureName, middlewares = [], inputSchema, outputSchema, inputValidationIndex = -1, outputValidationIndex = -1, isPublic = false) {
70
+ this.kind = kind;
71
+ this.procedureName = procedureName;
72
+ this.middlewares = middlewares;
73
+ this.inputSchema = inputSchema;
74
+ this.outputSchema = outputSchema;
75
+ this.inputValidationIndex = inputValidationIndex;
76
+ this.outputValidationIndex = outputValidationIndex;
77
+ this.isPublic = isPublic;
78
+ }
79
+ name(name) {
80
+ return new GencowProcedureBuilderImpl(this.kind, name, this.middlewares, this.inputSchema, this.outputSchema, this.inputValidationIndex, this.outputValidationIndex, this.isPublic);
81
+ }
82
+ allowPublic() {
83
+ return new GencowProcedureBuilderImpl(this.kind, this.procedureName, this.middlewares, this.inputSchema, this.outputSchema, this.inputValidationIndex, this.outputValidationIndex, true);
84
+ }
85
+ use(middleware) {
86
+ return new GencowProcedureBuilderImpl(this.kind, this.procedureName, [...this.middlewares, middleware], this.inputSchema, this.outputSchema, this.inputValidationIndex, this.outputValidationIndex, this.isPublic);
87
+ }
88
+ input(schema) {
89
+ const nextInputValidationIndex = this.middlewares.length < 0 ? 0 : this.middlewares.length;
90
+ return new GencowProcedureBuilderImpl(this.kind, this.procedureName, this.middlewares, schema, this.outputSchema, nextInputValidationIndex, this.outputValidationIndex, this.isPublic);
91
+ }
92
+ output(schema) {
93
+ const nextOutputValidationIndex = this.middlewares.length < 0 ? 0 : this.middlewares.length;
94
+ return new GencowProcedureBuilderImpl(this.kind, this.procedureName, this.middlewares, this.inputSchema, schema, this.inputValidationIndex, nextOutputValidationIndex, this.isPublic);
95
+ }
96
+ handler(handler) {
97
+ if (!this.procedureName) {
98
+ throw new Error("Procedure name is required. Call .name(...) before .handler(...)");
99
+ }
100
+ const run = composeMiddlewares(this.middlewares, handler, this.inputSchema, this.outputSchema, this.inputValidationIndex, this.outputValidationIndex);
101
+ return {
102
+ kind: this.kind,
103
+ name: this.procedureName,
104
+ isPublic: this.isPublic,
105
+ middlewares: [...this.middlewares],
106
+ inputSchema: this.inputSchema,
107
+ outputSchema: this.outputSchema,
108
+ inputValidationIndex: this.inputValidationIndex,
109
+ outputValidationIndex: this.outputValidationIndex,
110
+ handler: run,
111
+ };
112
+ }
113
+ }
114
+ export const procQuery = new GencowProcedureBuilderImpl("query");
115
+ export const procMutation = new GencowProcedureBuilderImpl("mutation");