@supalive/core 1.13.1 → 1.14.0

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 (50) hide show
  1. package/README.md +1 -2
  2. package/dist/helper-CUSGbt2A.d.ts +15 -0
  3. package/dist/helper-CUSGbt2A.d.ts.map +1 -0
  4. package/dist/helper-CVcjwD3k.js +73 -0
  5. package/dist/helper-CVcjwD3k.js.map +1 -0
  6. package/dist/index-f7mNbMhq.d.ts +2301 -0
  7. package/dist/index-f7mNbMhq.d.ts.map +1 -0
  8. package/dist/mysql-BX5hfgfE.d.ts +114 -0
  9. package/dist/mysql-BX5hfgfE.d.ts.map +1 -0
  10. package/dist/mysql-v_0U0NU4.js +623 -0
  11. package/dist/mysql-v_0U0NU4.js.map +1 -0
  12. package/dist/overlap-checker-DVbh0YC4.js +259 -0
  13. package/dist/overlap-checker-DVbh0YC4.js.map +1 -0
  14. package/dist/postgres-EUz8TYFn.d.ts +118 -0
  15. package/dist/postgres-EUz8TYFn.d.ts.map +1 -0
  16. package/dist/postgres-vYRyZJZd.js +868 -0
  17. package/dist/postgres-vYRyZJZd.js.map +1 -0
  18. package/dist/query-Bk2W-ynQ.js +730 -0
  19. package/dist/query-Bk2W-ynQ.js.map +1 -0
  20. package/dist/realtime_db-DnZKn_FZ.js +312 -0
  21. package/dist/realtime_db-DnZKn_FZ.js.map +1 -0
  22. package/dist/schema-DRtz5h5l.js +131 -0
  23. package/dist/schema-DRtz5h5l.js.map +1 -0
  24. package/dist/src/client/index.d.ts +1 -1
  25. package/dist/src/client/index.js +1 -1
  26. package/dist/src/exports/mysql.d.ts +1 -1
  27. package/dist/src/exports/postgres.d.ts +1 -1
  28. package/dist/src/exports/procedure.d.ts +2 -2
  29. package/dist/src/exports/procedure.js +2 -2
  30. package/dist/src/exports/schema-sql.d.ts +2 -2
  31. package/dist/src/exports/schema-sql.js +3 -3
  32. package/dist/src/exports/schema-sql.js.map +1 -1
  33. package/dist/src/exports/server.d.ts +4 -4
  34. package/dist/src/exports/server.d.ts.map +1 -1
  35. package/dist/src/exports/server.js +3 -3
  36. package/dist/src/exports/server.js.map +1 -1
  37. package/dist/src/exports/sub-manager-worker-entry.js +1 -1
  38. package/dist/src/exports/types.d.ts +8 -3
  39. package/dist/src/exports/types.d.ts.map +1 -0
  40. package/dist/src/exports/types.js +20 -1
  41. package/dist/src/exports/types.js.map +1 -0
  42. package/dist/sub-worker-dispatch-CC0w_sx0.js +826 -0
  43. package/dist/sub-worker-dispatch-CC0w_sx0.js.map +1 -0
  44. package/dist/sub-worker-dispatch-UGC9vwQJ.js +826 -0
  45. package/dist/sub-worker-dispatch-UGC9vwQJ.js.map +1 -0
  46. package/dist/types_db-Dw2RHWrd.js +172 -0
  47. package/dist/types_db-Dw2RHWrd.js.map +1 -0
  48. package/dist/types_server-B7elBQyz.d.ts +523 -0
  49. package/dist/types_server-B7elBQyz.d.ts.map +1 -0
  50. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-DRtz5h5l.js","names":["z"],"sources":["../src/db/schema.ts"],"sourcesContent":["import { z, ZodRawShape } from \"zod\";\nimport { commitTsCodec, unwrapZodType } from \"./codec\";\nimport { LiveQueryHandle } from \"../client\";\nimport { tableNameToId } from \"./table-id\";\n\nexport interface ColumnCodec<TData = unknown, TDriver = unknown> {\n encode?: (value: TData) => TDriver;\n decode?: (value: TDriver) => TData;\n}\n\n// Constrain a codec's decoded type to match the schema field's inferred type.\n// Without this, `decode` could return any value (e.g. a string outside an enum)\n// and silently override the schema's declared type at the type level.\ntype SchemaCodecField<TSchema extends ZodRawShape, K extends PropertyKey> =\n K extends keyof TSchema\n ? TSchema[K] extends z.ZodTypeAny ? z.infer<TSchema[K]> : unknown\n : K extends keyof BaseSchema\n ? BaseSchema[K] extends z.ZodTypeAny ? z.infer<BaseSchema[K]> : unknown\n : unknown;\n\nexport type SchemaCodecs<TSchema extends ZodRawShape> = Partial<{\n [K in keyof (TSchema & BaseSchema)]: ColumnCodec<SchemaCodecField<TSchema, K>, any>;\n}>;\n\nexport interface SchemaColumnsOptions<TSchema extends ZodRawShape = ZodRawShape> {\n codecs?: SchemaCodecs<TSchema>;\n}\n\nexport interface SchemaColumnMapping {\n [key: string]: string;\n}\n\nexport interface DeclarativeIndex {\n name: string;\n columns: string[];\n unique?: boolean;\n type?: \"btree\" | \"hash\" | \"gin\" | \"gist\" | \"spgist\" | \"brin\";\n where?: string;\n using?: string;\n options?: string;\n tablespace?: string;\n}\n\nexport type IndexDefinition = string | DeclarativeIndex;\n\nexport interface DefineSchemaConfig<TSchema extends ZodRawShape> {\n name: string;\n schema: TSchema;\n options?: SchemaColumnsOptions<TSchema>;\n columns?: SchemaColumnMapping;\n indexes?: IndexDefinition[];\n}\n\n// Tuple-wrap the `undefined` checks so they don't fall through to the\n// object-shape conditionals when consumers compile under `strict: false`\n// (without `strictNullChecks`, `undefined` is assignable to object types and\n// would otherwise match `{ decode: ... }` / `ColumnCodec<...>` with all\n// `infer`s collapsing to `unknown`).\ntype CodecDataType<TCodec, TFallback> =\n [TCodec] extends [undefined] ? TFallback\n : TCodec extends { decode: (...args: any[]) => infer TDecoded } ? TDecoded\n : TCodec extends ColumnCodec<infer TData, unknown> ? TData\n : TFallback;\n\ntype ZodOutput<TZod> =\n [TZod] extends [undefined] ? unknown\n : TZod extends z.ZodTypeAny ? z.infer<TZod>\n : unknown;\nexport type ComputedDataType<TCodec, TZod> = CodecDataType<TCodec, ZodOutput<TZod>>;\nexport type ComputedCodec<TData, TDriver> = ColumnCodec<TData, TDriver>;\nexport type OverrideField<TObj, TKey extends PropertyKey, TValue> = Omit<TObj, TKey> & { [K in TKey]: TValue };\nexport interface ComputedFieldConfig<\n TField extends string,\n TDecoded = unknown,\n TDriver = unknown,\n TZodType extends z.ZodTypeAny | undefined = undefined,\n> {\n field: TField;\n sql: string;\n alias?: string;\n type?: TZodType;\n codec?: {\n decode: (value: TDriver) => TDecoded;\n encode?: (value: TDecoded) => TDriver;\n };\n}\n\nexport type ComputedField = {\n field: string;\n sql: string;\n alias: string;\n codec?: ColumnCodec<any, any>;\n};\n\nexport function defineComputedField<\n TField extends string,\n TDecoded = unknown,\n TDriver = unknown,\n TZodType extends z.ZodTypeAny | undefined = undefined,\n>(\n config: ComputedFieldConfig<TField, TDecoded, TDriver, TZodType>\n): ComputedFieldConfig<TField, TDecoded, TDriver, TZodType> {\n return config;\n}\n\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\ntype ApplySchemaCodecs<TBase, TCodecs> = {\n [K in keyof TBase]: K extends keyof TCodecs ? CodecDataType<TCodecs[K], TBase[K]> : TBase[K];\n};\n\n// Only apply codecs when `options.codecs` is explicitly provided. Without this\n// guard, the default constraint (`SchemaColumnsOptions<TSchema>`) makes\n// `TOptions[\"codecs\"]` infer as `Partial<{ [K]: ColumnCodec<any, any> }>`,\n// which collapses every field to `any` inside `ApplySchemaCodecs`.\ntype ResolveSchemaType<\n TSchema extends ZodRawShape,\n TOptions extends SchemaColumnsOptions<TSchema>\n> = TOptions extends { codecs: infer TCodecs }\n ? Prettify<ApplySchemaCodecs<z.infer<z.ZodObject<TSchema & BaseSchema>>, TCodecs>>\n : Prettify<z.infer<z.ZodObject<TSchema & BaseSchema>>>;\n\n// Helper to detect if a Zod type is optional or nullable\ntype IsOptionalField<T> =\n T extends z.ZodOptional<any> ? true :\n T extends z.ZodNullable<any> ? true :\n T extends z.ZodDefault<any> ? true :\n false;\n\n// Split schema keys into required vs optional\ntype OptionalKeys<TZod extends ZodRawShape> = {\n [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? K : never\n}[keyof TZod];\n\ntype RequiredKeys<TZod extends ZodRawShape> = {\n [K in keyof TZod]: IsOptionalField<TZod[K]> extends true ? never : K\n}[keyof TZod];\n\n// Add a base shape type that all schemas will include\ntype BaseSchema = {\n id: z.ZodString;\n commitTs: z.ZodCoercedBigInt;\n};\n\n/**\n * Read the effective max length declared on a Zod string (via `.max(n)` /\n * `.length(n)`), unwrapping optional/nullable/default wrappers. Returns\n * undefined for non-strings or unconstrained strings. Mirrors the reader in\n * schema-sql.ts (kept local to avoid a schema <-> schema-sql import cycle) and\n * is used to carry a primary-key id's length into the injected id column so the\n * SQL generator can emit `VARCHAR(n)` instead of an (invalid-as-a-MySQL-PK)\n * `TEXT`.\n */\nfunction readZodStringMax(field: unknown): number | undefined {\n const unwrapped = unwrapZodType(field);\n if (!(unwrapped instanceof z.ZodString)) return undefined;\n\n const checks = unwrapped.def?.checks ?? [];\n let maxLength: number | undefined;\n for (const check of checks) {\n const c = check?._zod?.def ?? check;\n if (c?.check === \"length_equals\" || c?.check === \"size_equals\") {\n const len = (c as any).length ?? (c as any).size;\n if (typeof len === \"number\") maxLength = maxLength === undefined ? len : Math.min(maxLength, len);\n }\n if (c?.check === \"max_length\" || c?.check === \"max_size\") {\n const len = (c as any).maximum ?? (c as any).max;\n if (typeof len === \"number\") maxLength = maxLength === undefined ? len : Math.min(maxLength, len);\n }\n }\n return maxLength;\n}\n\nexport const schemaRegistry = new Map<string, SchemaDefinition<string, any, any>>();\nexport const shouldTrackSchema = process.env.NODE_ENV !== 'production';\n\nfunction getAutoIdCodec(idMeta: Record<string, unknown>, userCodec: unknown): ColumnCodec<any, any> | undefined {\n if (userCodec) return undefined;\n const rawType = (idMeta.pgType as string | undefined) ?? (idMeta.mysqlType as string | undefined);\n if (!rawType) return undefined;\n\n const upper = rawType.toUpperCase().replace(/\\(.*\\)/, \"\").trim();\n if ([\"BIGINT\", \"INT8\", \"SERIAL8\"].includes(upper)) {\n return {\n encode: (v: string) => BigInt(v),\n decode: (v: unknown) => String(v),\n };\n }\n if ([\"INTEGER\", \"INT\", \"SERIAL\", \"INT4\", \"SMALLINT\", \"INT2\"].includes(upper)) {\n return {\n encode: (v: string) => Number(v),\n decode: (v: unknown) => String(v),\n };\n }\n if ([\"DECIMAL\", \"NUMERIC\", \"FLOAT\", \"REAL\", \"DOUBLE\", \"FLOAT8\", \"FLOAT4\"].includes(upper)) {\n return {\n encode: (v: string) => Number(v),\n decode: (v: unknown) => String(v),\n };\n }\n if (upper === \"BOOLEAN\" || upper === \"BOOL\" || (upper.startsWith(\"TINYINT\") && rawType.toUpperCase().includes(\"(1)\"))) {\n return {\n encode: (v: string) => v === \"true\" || v === \"1\",\n decode: (v: unknown) => String(v),\n };\n }\n return undefined;\n}\n\nexport function defineSchema<\n TSchema extends ZodRawShape,\n TName extends string,\n TOptions extends SchemaColumnsOptions<TSchema> = SchemaColumnsOptions<TSchema>\n>(\n config: DefineSchemaConfig<TSchema> & { name: TName; options?: TOptions }\n): SchemaDefinition<TName, Prettify<TSchema & BaseSchema>, ResolveSchemaType<TSchema, TOptions>> {\n const columns: Record<string, string> = {};\n\n if (config.columns) {\n Object.assign(columns, { 'id': 'id', 'commitTs': 'commit_ts', ...config.columns });\n } else {\n // Default: use field name as column name\n for (const key of Object.keys(config.schema)) {\n columns[key] = key;\n }\n columns['id'] = 'id';\n columns['commitTs'] = 'commit_ts';\n }\n\n // Preserve user's id meta (pgType, mysqlType, etc.) so the SQL generator\n // can emit the correct raw type. primaryKey is always forced true.\n const idMeta: Record<string, unknown> = {};\n if (\"id\" in config.schema) {\n const userMeta = (config.schema.id as any)?.meta?.();\n if (userMeta) {\n for (const k of Object.keys(userMeta)) {\n if (k === \"primaryKey\") continue; // always forced true\n idMeta[k] = userMeta[k];\n }\n }\n }\n\n // Preserve the user's id length constraint (`zodPrimaryIdColumn().max(32)`)\n // so the SQL generator emits `VARCHAR(n)`. `.max()` is a Zod *check*, not\n // metadata, so it isn't captured by `idMeta` above and must be re-applied to\n // the injected id — otherwise the PK renders as `TEXT`, which MySQL cannot\n // use as a primary key.\n const userIdMax = \"id\" in config.schema ? readZodStringMax(config.schema.id) : undefined;\n const idColumn = userIdMax !== undefined ? z.string().max(userIdMax) : z.string();\n\n // Merge id/commitTs into the Zod schema, user-defined fields win for everything else,\n // but id/commitTs are always forced to their correct types\n const augmentedShape = {\n ...config.schema,\n // always string, even if user defined it differently\n id: idColumn.meta({ primaryKey: true, ...idMeta }),\n // always bigint, mapped to commit_ts column\n commitTs: z.coerce.bigint(),\n };\n\n const userCodecs = config.options?.codecs;\n const autoIdCodec = getAutoIdCodec(idMeta, userCodecs?.id);\n const mergedCodecs = {\n ...(autoIdCodec ? { id: autoIdCodec } : {}),\n ...userCodecs,\n commitTs: commitTsCodec,\n };\n\n const result = {\n tableId: tableNameToId(config.name),\n table: config.name,\n schema: z.object(augmentedShape),\n columnsOptions: {\n ...config.options,\n codecs: mergedCodecs,\n },\n columns,\n indexes: config.indexes ?? [],\n } as SchemaDefinition<TName, TSchema & BaseSchema, ResolveSchemaType<TSchema, TOptions>>;\n\n if (shouldTrackSchema) {\n schemaRegistry.set(config.name, result);\n }\n\n return result\n}\n\n// tableNameToId now lives in ./table-id (leaf module, also home to the memoized\n// tableIdOf). Re-exported here so existing `from \"./schema\"` imports still resolve.\nexport { tableNameToId };\n\n// Stored codec map is intentionally loose: the strict per-field constraint is\n// enforced on the input (`DefineSchemaConfig.options`), but storing the strict\n// type here would break variance when assigning a specific schema to a generic\n// `SchemaDefinition<string, ZodRawShape>` constraint (ColumnCodec.encode is\n// contravariant in its data type).\nexport interface StoredSchemaColumnsOptions {\n codecs?: Record<string, ColumnCodec<any, any>>;\n}\n\nexport interface SchemaDefinition<\n TTable extends string,\n TZod extends ZodRawShape,\n TData = z.infer<z.ZodObject<TZod>>\n> {\n tableId: Uint8Array;\n table: TTable;\n schema: z.ZodObject<TZod>;\n columnsOptions: StoredSchemaColumnsOptions;\n columns: Record<string, string>;\n indexes: IndexDefinition[];\n _dataType?: TData;\n}\n\nexport type InferSchema<T extends SchemaDefinition<string, ZodRawShape, any>> =\n T extends SchemaDefinition<string, ZodRawShape, infer TData> ? TData : never;\n\nexport type InsertData<T extends SchemaDefinition<string, ZodRawShape, any>> =\n T extends SchemaDefinition<string, infer TZod, infer TData>\n ? {\n [K in RequiredKeys<TZod> as K extends \"id\" | \"commitTs\" ? never : K]:\n Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never\n } & {\n [K in OptionalKeys<TZod> as K extends \"id\" | \"commitTs\" ? never : K]?:\n Extract<K, string> extends keyof TData ? TData[Extract<K, string>] : never\n }\n : never;\n\nexport interface Model {\n table: string;\n tableId: Uint8Array,\n columns: Record<string, string>;\n reverseColumns: Record<string, string>;\n types: Record<string, string>;\n codecs: Record<string, ColumnCodec<any, any>>;\n}\n\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ReturnLiveQuery<\n TLiveQueryFn extends (...args: any[]) => MaybePromise<LiveQueryHandle<any>>\n> =\n Awaited<ReturnType<TLiveQueryFn>> extends LiveQueryHandle<infer T>\n ? T\n : never;\n\nexport type ReturnQuery<TQueryFn extends (...args: any[]) => any> =\n Awaited<ReturnType<TQueryFn>>;\n\nexport type QueryArgs<TQueryFn extends (...args: any[]) => any> =\n Parameters<TQueryFn>[0];\n\nexport type MutationArgs<TMutationFn extends (...args: any[]) => any> =\n Parameters<TMutationFn>[0];\n\nexport type ActionArgs<TActionFn extends (...args: any[]) => any> =\n Parameters<TActionFn>[0];"],"mappings":";;;AA8FA,SAAgB,oBAMZ,QACwD;CACxD,OAAO;AACX;;;;;;;;;;AAkDA,SAAS,iBAAiB,OAAoC;CAC1D,MAAM,YAAY,cAAc,KAAK;CACrC,IAAI,EAAE,qBAAqBA,IAAE,YAAY,OAAO,KAAA;CAEhD,MAAM,SAAS,UAAU,KAAK,UAAU,CAAC;CACzC,IAAI;CACJ,KAAK,MAAM,SAAS,QAAQ;EACxB,MAAM,IAAI,OAAO,MAAM,OAAO;EAC9B,IAAI,GAAG,UAAU,mBAAmB,GAAG,UAAU,eAAe;GAC5D,MAAM,MAAO,EAAU,UAAW,EAAU;GAC5C,IAAI,OAAO,QAAQ,UAAU,YAAY,cAAc,KAAA,IAAY,MAAM,KAAK,IAAI,WAAW,GAAG;EACpG;EACA,IAAI,GAAG,UAAU,gBAAgB,GAAG,UAAU,YAAY;GACt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utationResult, Er as LiveResult, Et as createActionBuilder, Fr as Predicate, G as RPCError, Gr as RawPointReadSchema, Gt as DefsToMap, Hr as RangeRead, Ht as SupaliveDb, In as defineComputedField, Ir as PredicateSchema, J as ActionProcedures, Jr as RawReadEntry, Jt as ResultOf, K as WSClientOptions, Kr as RawRangeRead, Kt as ParamsOf, Ln as defineSchema, Lr as QueryCacheEntry, Mr as OrPredicateSchema, Nn as SchemaColumnsOptions, Nr as PointRead, Or as NO_RETRY, Ot as createMutationBuilder, Pn as SchemaDefinition, Pr as PointReadSchema, Q as MutationProcedures, Qr as RetryConfig, Qt as DbWriter, Rr as QueryCacheEntrySchema, Sn as InferSchema, Sr as CompareOperatorSchema, St as QueryCtx, Tr as LeafPredicateSchema, Tt as TypeOf, U as ClientPublicState, Un as Database, Ur as RangeReadSchema, Ut as sleep, Vr as QuerySpec, W as HeartbeatOptions, Wn as DbQueryResult, Wr as RawPointRead, Wt as AnyQueryDef, Xr as ReadEntry, Xt as defineQuery, Y as AppRouter, Yn as RawClient, Yr as RawReadEntrySchema, Yt as _resetGlobalDefs, Zr as ReadEntrySchema, Zt as DbReader, _r as CachedPgMetadata, _t as MutationCtx, a as CallOptions, ai as normalizeToBytes, at as router, br as CommitTs, bt as OutputOf, c as LiveQueryHandle, ct as ActionFn, d as WSClientMethods, dt as ContextOf, ei as WriteEntrySchema, et as PublicProcedures, f as createClient, fn as matchesPredicate, gr as BigIntSchema, gt as MutationConfig, hr as AndPredicateSchema, i as createCaller, ii as normalizeIdToBytes, jn as SchemaCodecs, jr as OrPredicate, kr as OccAbortError, kt as createQueryBuilder, l as LiveQueryState, lt as ActionProcedure, mn as ColumnCodec, mr as AndPredicate, n as CallerFromRouter, ni as WriteOpSchema, nt as RegisteredProcedure, o as ClientFromProcedures, ot as ActionConfig, q as WsClientManager, qn as PooledClient, qr as RawRangeReadSchema, qt as QueryDefinition, r as CallerOptions, ri as bytesFromJson, rt as Router, s as ClientOptions, st as ActionCtx, t as CallerFromProcedures, ti as WriteOp, tt as QueryProcedures, u as LiveQueryStatus, ut as AnyProcedure, vn as ComputedFieldConfig, vr as CachedPgMetadataSchema, vt as MutationFn, wn as Model, wr as LeafPredicate, wt as QueryProcedure, xr as CompareOperator, xt as QueryConfig, yr as CommitLogEntry, yt as MutationProcedure, zr as QueryCacheMetadata } from "../../index-C_i3U4cd.js";
1
+ import { $ as ProcedureNames, $r as WriteEntrySchema, $t as TxContext, Ar as OrPredicate, Br as QuerySpec, Cn as InsertData, Cr as LeafPredicate, Ct as QueryFn, Dr as NO_RETRY, Er as MutationResult, Et as createActionBuilder, Fr as PredicateSchema, G as RPCError, Gr as RawRangeRead, Gt as DefsToMap, Hn as Database, Hr as RangeReadSchema, Ht as SupaliveDb, In as defineComputedField, Ir as QueryCacheEntry, J as ActionProcedures, Jn as RawClient, Jr as RawReadEntrySchema, Jt as ResultOf, K as WSClientOptions, Kn as PooledClient, Kr as RawRangeReadSchema, Kt as ParamsOf, Ln as defineSchema, Lr as QueryCacheEntrySchema, Mr as PointRead, Nn as SchemaColumnsOptions, Nr as PointReadSchema, Or as OccAbortError, Ot as createMutationBuilder, Pn as SchemaDefinition, Pr as Predicate, Q as MutationProcedures, Qr as WriteEntry, Qt as DbWriter, Rr as QueryCacheMetadata, Sn as InferSchema, Sr as DEFAULT_RETRY, St as QueryCtx, Tr as LiveResult, Tt as TypeOf, U as ClientPublicState, Un as DbQueryResult, Ur as RawPointRead, Ut as sleep, Vr as RangeRead, W as HeartbeatOptions, Wr as RawPointReadSchema, Wt as AnyQueryDef, Xr as ReadEntrySchema, Xt as defineQuery, Y as AppRouter, Yr as ReadEntry, Yt as _resetGlobalDefs, Zr as RetryConfig, Zt as DbReader, _r as CachedPgMetadataSchema, _t as MutationCtx, a as CallOptions, at as router, br as CompareOperator, bt as OutputOf, c as LiveQueryHandle, ct as ActionFn, d as WSClientMethods, dt as ContextOf, ei as WriteOp, et as PublicProcedures, f as createClient, fn as matchesPredicate, gr as CachedPgMetadata, gt as MutationConfig, hr as BigIntSchema, i as createCaller, ii as normalizeToBytes, jn as SchemaCodecs, jr as OrPredicateSchema, kr as OccConflictError, kt as createQueryBuilder, l as LiveQueryState, lt as ActionProcedure, mn as ColumnCodec, mr as AndPredicateSchema, n as CallerFromRouter, ni as bytesFromJson, nt as RegisteredProcedure, o as ClientFromProcedures, ot as ActionConfig, pr as AndPredicate, q as WsClientManager, qr as RawReadEntry, qt as QueryDefinition, r as CallerOptions, ri as normalizeIdToBytes, rt as Router, s as ClientOptions, st as ActionCtx, t as CallerFromProcedures, ti as WriteOpSchema, tt as QueryProcedures, u as LiveQueryStatus, ut as AnyProcedure, vn as ComputedFieldConfig, vr as CommitLogEntry, vt as MutationFn, wn as Model, wr as LeafPredicateSchema, wt as QueryProcedure, xr as CompareOperatorSchema, xt as QueryConfig, yr as CommitTs, yt as MutationProcedure, zr as QueryCacheMetadataSchema } from "../../index-f7mNbMhq.js";
2
2
  export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientFromProcedures, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
@@ -1,7 +1,7 @@
1
1
  import { c as parentConn, i as createActionBuilder, n as getContextRegistry, o as createMutationBuilder, r as router, s as createQueryBuilder, u as primaryOnlyConn } from "../../router-Kgrlci8X.js";
2
2
  import { r as supaliveStringify } from "../../helper-zdJT5FUc.js";
3
3
  import { o as matchesPredicate } from "../../query-Xw2hi6TB.js";
4
- import { n as defineSchema, t as defineComputedField } from "../../schema-DLue3K2s.js";
4
+ import { n as defineSchema, t as defineComputedField } from "../../schema-DRtz5h5l.js";
5
5
  import { C as normalizeIdToBytes, S as bytesFromJson, _ as RawRangeReadSchema, a as DEFAULT_RETRY, b as WriteEntrySchema, c as OccAbortError, d as PointReadSchema, f as PredicateSchema, g as RawPointReadSchema, h as RangeReadSchema, i as CompareOperatorSchema, l as OccConflictError, m as QueryCacheMetadataSchema, n as BigIntSchema, o as LeafPredicateSchema, p as QueryCacheEntrySchema, r as CachedPgMetadataSchema, s as NO_RETRY, t as AndPredicateSchema, u as OrPredicateSchema, v as RawReadEntrySchema, w as normalizeToBytes, x as WriteOpSchema, y as ReadEntrySchema } from "../../types_db-OUou3o2Z.js";
6
6
  import { l as ServerMessageSchema } from "../../types_client_rpc-ByGwoRCL.js";
7
7
  import { a as TxContext, i as DbWriter, n as sleep, r as DbReader, t as SupaliveDb } from "../../realtime_db-CVze3gM0.js";
@@ -1,2 +1,2 @@
1
- import { t as MySqlDatabase } from "../../mysql-Di6iuKWT.js";
1
+ import { t as MySqlDatabase } from "../../mysql-BX5hfgfE.js";
2
2
  export { MySqlDatabase };
@@ -1,2 +1,2 @@
1
- import { t as PgDatabase } from "../../postgres-CkhK4DqZ.js";
1
+ import { t as PgDatabase } from "../../postgres-EUz8TYFn.js";
2
2
  export { PgDatabase };
@@ -1,4 +1,4 @@
1
- import { $ as ProcedureNames, An as ReturnQuery, At as patchZod$1, Bn as trackSchema, Cn as InsertData, Ct as QueryFn, Dn as Prettify, Dt as createJobBuilder, En as OverrideField, Et as createActionBuilder, Fn as StoredSchemaColumnsOptions, In as defineComputedField, J as ActionProcedures, Ln as defineSchema, Mn as SchemaColumnMapping, Nn as SchemaColumnsOptions, On as QueryArgs, Ot as createMutationBuilder, Pn as SchemaDefinition, Q as MutationProcedures, Rn as schemaRegistry, Sn as InferSchema, St as QueryCtx, Tn as MutationArgs, Tt as TypeOf, Vn as tableNameToId, X as ContextRegistry, Y as AppRouter, Z as JobProcedures, _n as ComputedField, _t as MutationCtx, an as OrderDirection, at as router, bn as DefineSchemaConfig, bt as OutputOf, cn as buildPredicateSql, ct as ActionFn, dn as jsonPathExtract, dt as ContextOf, en as IdAndCommitTs, et as PublicProcedures, fn as matchesPredicate, ft as JobConfig, gn as ComputedDataType, gt as MutationConfig, hn as ComputedCodec, ht as JobProcedure, in as OrderByOptions, it as getContextRegistry, jn as SchemaCodecs, jt as z$1, kn as ReturnLiveQuery, kt as createQueryBuilder, ln as jsonContains, lt as ActionProcedure, mn as ColumnCodec, mt as JobFn, nn as JsonHasKeyMultiOptions, nt as RegisteredProcedure, on as PaginationClause, ot as ActionConfig, pn as ActionArgs, pt as JobCtx, rn as JsonOpOptions, rt as Router, sn as QueryBuilder, st as ActionCtx, tn as JsonContainsOptions, tt as QueryProcedures, un as jsonPathExists, ut as AnyProcedure, vn as ComputedFieldConfig, vt as MutationFn, wn as Model, wt as QueryProcedure, xn as IndexDefinition, xt as QueryConfig, yn as DeclarativeIndex, yt as MutationProcedure, zn as shouldTrackSchema } from "../../index-C_i3U4cd.js";
1
+ import { $ as ProcedureNames, An as ReturnQuery, At as patchZod$1, Bn as tableNameToId, Cn as InsertData, Ct as QueryFn, Dn as Prettify, Dt as createJobBuilder, En as OverrideField, Et as createActionBuilder, Fn as StoredSchemaColumnsOptions, In as defineComputedField, J as ActionProcedures, Ln as defineSchema, Mn as SchemaColumnMapping, Nn as SchemaColumnsOptions, On as QueryArgs, Ot as createMutationBuilder, Pn as SchemaDefinition, Q as MutationProcedures, Rn as schemaRegistry, Sn as InferSchema, St as QueryCtx, Tn as MutationArgs, Tt as TypeOf, X as ContextRegistry, Y as AppRouter, Z as JobProcedures, _n as ComputedField, _t as MutationCtx, an as OrderDirection, at as router, bn as DefineSchemaConfig, bt as OutputOf, cn as buildPredicateSql, ct as ActionFn, dn as jsonPathExtract, dt as ContextOf, en as IdAndCommitTs, et as PublicProcedures, fn as matchesPredicate, ft as JobConfig, gn as ComputedDataType, gt as MutationConfig, hn as ComputedCodec, ht as JobProcedure, in as OrderByOptions, it as getContextRegistry, jn as SchemaCodecs, jt as z$1, kn as ReturnLiveQuery, kt as createQueryBuilder, ln as jsonContains, lt as ActionProcedure, mn as ColumnCodec, mt as JobFn, nn as JsonHasKeyMultiOptions, nt as RegisteredProcedure, on as PaginationClause, ot as ActionConfig, pn as ActionArgs, pt as JobCtx, rn as JsonOpOptions, rt as Router, sn as QueryBuilder, st as ActionCtx, tn as JsonContainsOptions, tt as QueryProcedures, un as jsonPathExists, ut as AnyProcedure, vn as ComputedFieldConfig, vt as MutationFn, wn as Model, wt as QueryProcedure, xn as IndexDefinition, xt as QueryConfig, yn as DeclarativeIndex, yt as MutationProcedure, zn as shouldTrackSchema } from "../../index-f7mNbMhq.js";
2
2
  import { n as stableStringify, r as supaliveStringify, t as groupByToMap } from "../../helper-CiacMqje.js";
3
3
 
4
4
  //#region src/exports/procedure.d.ts
@@ -14,5 +14,5 @@ declare module "zod" {
14
14
  }
15
15
  } //# sourceMappingURL=procedure.d.ts.map
16
16
  //#endregion
17
- export { ActionArgs, type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, type AnyProcedure, type AppRouter, ColumnCodec, ComputedCodec, ComputedDataType, ComputedField, ComputedFieldConfig, type ContextOf, ContextRegistry, DeclarativeIndex, DefineSchemaConfig, IdAndCommitTs, IndexDefinition, InferSchema, InsertData, type JobConfig, type JobCtx, type JobFn, type JobProcedure, type JobProcedures, JsonContainsOptions, JsonHasKeyMultiOptions, JsonOpOptions, Model, MutationArgs, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, OrderByOptions, OrderDirection, type OutputOf, OverrideField, PaginationClause, Prettify, type ProcedureNames, type PublicProcedures, QueryArgs, QueryBuilder, type QueryConfig, type QueryCtx, type QueryFn, type QueryProcedure, type QueryProcedures, type RegisteredProcedure, ReturnLiveQuery, ReturnQuery, type Router, SchemaCodecs, SchemaColumnMapping, SchemaColumnsOptions, SchemaDefinition, StoredSchemaColumnsOptions, type TypeOf, buildPredicateSql, createActionBuilder, createJobBuilder, createMutationBuilder, createQueryBuilder, defineComputedField, defineSchema, getContextRegistry, groupByToMap, jsonContains, jsonPathExists, jsonPathExtract, matchesPredicate, patchZod, router, schemaRegistry, shouldTrackSchema, stableStringify, supaliveStringify, tableNameToId, trackSchema, z };
17
+ export { ActionArgs, type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, type AnyProcedure, type AppRouter, ColumnCodec, ComputedCodec, ComputedDataType, ComputedField, ComputedFieldConfig, type ContextOf, ContextRegistry, DeclarativeIndex, DefineSchemaConfig, IdAndCommitTs, IndexDefinition, InferSchema, InsertData, type JobConfig, type JobCtx, type JobFn, type JobProcedure, type JobProcedures, JsonContainsOptions, JsonHasKeyMultiOptions, JsonOpOptions, Model, MutationArgs, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, OrderByOptions, OrderDirection, type OutputOf, OverrideField, PaginationClause, Prettify, type ProcedureNames, type PublicProcedures, QueryArgs, QueryBuilder, type QueryConfig, type QueryCtx, type QueryFn, type QueryProcedure, type QueryProcedures, type RegisteredProcedure, ReturnLiveQuery, ReturnQuery, type Router, SchemaCodecs, SchemaColumnMapping, SchemaColumnsOptions, SchemaDefinition, StoredSchemaColumnsOptions, type TypeOf, buildPredicateSql, createActionBuilder, createJobBuilder, createMutationBuilder, createQueryBuilder, defineComputedField, defineSchema, getContextRegistry, groupByToMap, jsonContains, jsonPathExists, jsonPathExtract, matchesPredicate, patchZod, router, schemaRegistry, shouldTrackSchema, stableStringify, supaliveStringify, tableNameToId, z };
18
18
  //# sourceMappingURL=procedure.d.ts.map
@@ -2,11 +2,11 @@ import { a as createJobBuilder, d as z$1, i as createActionBuilder, l as patchZo
2
2
  import { n as tableNameToId } from "../../table-id-DyrJBKAQ.js";
3
3
  import { n as stableStringify, r as supaliveStringify, t as groupByToMap } from "../../helper-zdJT5FUc.js";
4
4
  import { a as jsonPathExtract, i as jsonPathExists, n as buildPredicateSql, o as matchesPredicate, r as jsonContains, t as QueryBuilder } from "../../query-Xw2hi6TB.js";
5
- import { a as trackSchema, i as shouldTrackSchema, n as defineSchema, r as schemaRegistry, t as defineComputedField } from "../../schema-DLue3K2s.js";
5
+ import { i as shouldTrackSchema, n as defineSchema, r as schemaRegistry, t as defineComputedField } from "../../schema-DRtz5h5l.js";
6
6
  //#region src/exports/procedure.ts
7
7
  const z = z$1;
8
8
  const patchZod = patchZod$1;
9
9
  //#endregion
10
- export { ContextRegistry, QueryBuilder, buildPredicateSql, createActionBuilder, createJobBuilder, createMutationBuilder, createQueryBuilder, defineComputedField, defineSchema, getContextRegistry, groupByToMap, jsonContains, jsonPathExists, jsonPathExtract, matchesPredicate, patchZod, router, schemaRegistry, shouldTrackSchema, stableStringify, supaliveStringify, tableNameToId, trackSchema, z };
10
+ export { ContextRegistry, QueryBuilder, buildPredicateSql, createActionBuilder, createJobBuilder, createMutationBuilder, createQueryBuilder, defineComputedField, defineSchema, getContextRegistry, groupByToMap, jsonContains, jsonPathExists, jsonPathExtract, matchesPredicate, patchZod, router, schemaRegistry, shouldTrackSchema, stableStringify, supaliveStringify, tableNameToId, z };
11
11
 
12
12
  //# sourceMappingURL=procedure.js.map
@@ -1,4 +1,4 @@
1
- import { Bn as trackSchema, Pn as SchemaDefinition, Rn as schemaRegistry } from "../../index-C_i3U4cd.js";
1
+ import { Pn as SchemaDefinition, Rn as schemaRegistry } from "../../index-f7mNbMhq.js";
2
2
 
3
3
  //#region src/db/schema-sql.d.ts
4
4
  type SqlDialect = "postgres" | "mysql";
@@ -65,5 +65,5 @@ interface CoreTablesSqlOptions {
65
65
  }
66
66
  declare function coreTablesSql(dialect?: SqlDialect, options?: CoreTablesSqlOptions): string[];
67
67
  //#endregion
68
- export { type CoreTablesSqlOptions, type GenerateSchemaSqlOptions, type SchemaToCreateTableOptions, type SqlDialect, coreTablesSql, generateSchemaSql, schemaRegistry, schemaToCreateTable, trackSchema };
68
+ export { type CoreTablesSqlOptions, type GenerateSchemaSqlOptions, type SchemaToCreateTableOptions, type SqlDialect, coreTablesSql, generateSchemaSql, schemaRegistry, schemaToCreateTable };
69
69
  //# sourceMappingURL=schema-sql.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { a as unwrapZodType } from "../../table-id-DyrJBKAQ.js";
2
- import { a as trackSchema, r as schemaRegistry } from "../../schema-DLue3K2s.js";
2
+ import { r as schemaRegistry } from "../../schema-DRtz5h5l.js";
3
3
  import { z as z$1 } from "zod";
4
4
  //#region src/db/core_tables.ts
5
5
  function coreTablesSql(dialect = "postgres", options) {
@@ -253,7 +253,7 @@ function maxPrimaryKeyLength(schemas) {
253
253
  return max;
254
254
  }
255
255
  function generateSchemaSql(schemas, options) {
256
- const dialect = options?.dialect ?? "postgres";
256
+ const dialect = options?.dialect ?? "mysql";
257
257
  const header = options?.header ?? true;
258
258
  const includeCoreTables = options?.includeCoreTables ?? true;
259
259
  let list;
@@ -294,6 +294,6 @@ function generateSchemaSql(schemas, options) {
294
294
  return parts.join("\n");
295
295
  }
296
296
  //#endregion
297
- export { coreTablesSql, generateSchemaSql, schemaRegistry, schemaToCreateTable, trackSchema };
297
+ export { coreTablesSql, generateSchemaSql, schemaRegistry, schemaToCreateTable };
298
298
 
299
299
  //# sourceMappingURL=schema-sql.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-sql.js","names":["z"],"sources":["../../../src/db/core_tables.ts","../../../src/db/schema-sql.ts"],"sourcesContent":["import type { SqlDialect } from \"./schema-sql\";\n\n/**\n * DDL for the core, framework-owned database objects that every Supalive\n * database must have alongside the user's own tables:\n *\n * - `commit_logs` — the append-only OCC change log (+ its lookup indexes).\n * - `metadata` — the small key/value table holding the OCC watermarks\n * (`latest_committed_ts`, `min_retained_ts`) and the\n * core schema version (`core_version`).\n * - `global_commit_ts` — the monotonic commit-timestamp source: a SEQUENCE on\n * Postgres, a single-row `BIGINT` counter table on MySQL.\n *\n * These are all pure schema (DDL), so they belong in the generated `schema.sql`\n * (see {@link generateSchemaSql}, which prepends them by default) and get\n * migrated ahead of runtime by your normal migration pipeline — a single\n * generated file fully describes the database.\n *\n * Data seeding (the `metadata` rows and the MySQL counter's initial `0`) and\n * any runtime-only schema changes live in `initCore` — see\n * {@link file://./init_db.ts}.\n */\n\nexport interface CoreTablesSqlOptions {\n /** Emit `IF NOT EXISTS` on `CREATE TABLE`/`CREATE INDEX`/`CREATE SEQUENCE`. Default true. */\n ifNotExists?: boolean;\n /**\n * MySQL only: the SQL type of `commit_logs.id`, which stores the changed\n * row's primary key encoded as bytes. Defaults to `VARBINARY(255)`.\n * `generateSchemaSql` derives a tighter value from the app's largest id\n * column; an app with fixed-width binary ids can override to e.g.\n * `BINARY(16)` (but note: variable-length ids must use VARBINARY — a fixed\n * BINARY column zero-pads stored values, which would break the OCC id match).\n */\n commitLogIdType?: string;\n}\n\nexport function coreTablesSql(\n dialect: SqlDialect = \"postgres\",\n options?: CoreTablesSqlOptions,\n): string[] {\n const ifNotExists = options?.ifNotExists ?? true;\n const t = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n const i = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n const commitLogIdType = options?.commitLogIdType ?? \"VARBINARY(255)\";\n\n if (dialect === \"mysql\") {\n return [\n // MySQL has no sequences: a single-row counter table advanced via\n // LAST_INSERT_ID (see MySqlDatabase.getNextTimestamp). Seeded to 0\n // by initCore.\n `CREATE TABLE ${t}global_commit_ts (\\n` +\n ` id BIGINT NOT NULL\\n` +\n `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`,\n // `id` holds the changed row's primary key encoded as bytes. Row ids\n // are variable-length (a prefixed string id can exceed 16 bytes), so\n // the default is VARBINARY, mirroring Postgres' flexible BYTEA — a\n // fixed BINARY column zero-pads stored values, breaking the OCC id\n // match. Sized via `commitLogIdType` (generateSchemaSql derives it\n // from the app's largest id column). `table_id` is a fixed 16-byte\n // table hash and stays BINARY(16).\n `CREATE TABLE ${t}commit_logs (\\n` +\n ` id ${commitLogIdType} NOT NULL,\\n` +\n ` ts BIGINT NOT NULL,\\n` +\n ` table_id BINARY(16) NOT NULL,\\n` +\n ` data LONGBLOB NOT NULL,\\n` +\n ` PRIMARY KEY (ts, table_id, id),\\n` +\n ` INDEX commit_logs_by_table_and_id (table_id, id, ts)\\n` +\n `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;`,\n `CREATE TABLE ${t}metadata (\\n` +\n ` meta_key VARCHAR(64) NOT NULL PRIMARY KEY,\\n` +\n ` meta_value BIGINT NOT NULL\\n` +\n `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`,\n ];\n }\n\n return [\n // Monotonic OCC commit-timestamp source (see PgDatabase.getNextTimestamp).\n `CREATE SEQUENCE ${t}global_commit_ts START 1 INCREMENT 1 NO CYCLE;`,\n `CREATE TABLE ${t}commit_logs (\\n` +\n ` id BYTEA NOT NULL,\\n` +\n ` ts BIGINT NOT NULL,\\n` +\n ` table_id BYTEA NOT NULL,\\n` +\n ` data BYTEA NOT NULL,\\n` +\n ` PRIMARY KEY (ts, table_id, id)\\n` +\n `);`,\n `CREATE INDEX ${i}commit_logs_by_table_and_id ON commit_logs (table_id, id, ts);`,\n `CREATE INDEX ${i}commit_logs_by_table_ts_and_id ON commit_logs (table_id, ts, id);`,\n `CREATE TABLE ${t}metadata (\\n` +\n ` meta_key TEXT PRIMARY KEY,\\n` +\n ` meta_value BIGINT NOT NULL\\n` +\n `);`,\n ];\n}\n","import { z } from \"zod\";\nimport { SchemaDefinition, schemaRegistry } from \"./schema\";\nimport type { DeclarativeIndex } from \"./schema\";\nimport { unwrapZodType } from \"./codec\";\nimport { coreTablesSql } from \"./core_tables\";\n\nexport type SqlDialect = \"postgres\" | \"mysql\";\n\nfunction getFieldMeta(field: unknown): Record<string, unknown> | undefined {\n const f = field as any;\n const meta = typeof f.meta === \"function\" ? f.meta() : undefined;\n if (meta) return meta;\n\n const unwrapped = unwrapZodType(field);\n if (unwrapped !== field) {\n const innerMeta = typeof (unwrapped as any).meta === \"function\" ? (unwrapped as any).meta() : undefined;\n if (innerMeta) return innerMeta;\n }\n\n return undefined;\n}\n\nfunction getStringMaxLength(field: unknown): number | undefined {\n const unwrapped = unwrapZodType(field);\n if (!(unwrapped instanceof z.ZodString)) return undefined;\n\n const checks: any[] = (unwrapped as any).def?.checks ?? [];\n let maxLength: number | undefined;\n\n for (const check of checks) {\n const c = check._zod?.def ?? check.def ?? check;\n if (c.check === \"length_equals\" || c.check === \"size_equals\") {\n const len = c.length ?? c.size;\n if (typeof len === \"number\") maxLength = maxLength === undefined ? len : Math.min(maxLength, len);\n }\n if (c.check === \"max_length\" || c.check === \"max_size\") {\n const len = c.maximum ?? c.max;\n if (typeof len === \"number\") maxLength = maxLength === undefined ? len : Math.min(maxLength, len);\n }\n }\n\n return maxLength;\n}\n\nfunction isOptional(field: unknown): boolean {\n return (\n field instanceof z.ZodOptional ||\n field instanceof z.ZodNullable\n );\n}\n\nfunction escapeSQLString(s: string): string {\n return `'${s.replace(/'/g, \"''\")}'`;\n}\n\nfunction getDefaultFromZod(field: unknown): string | undefined {\n if (!(field instanceof z.ZodDefault)) return undefined;\n\n try {\n const f = field as any;\n let value = f.defaultValue;\n if (value === undefined) value = f.def?.defaultValue;\n if (typeof value === \"function\") value = value();\n\n if (value === undefined) return undefined;\n if (value === null) return \"NULL\";\n if (typeof value === \"string\") return escapeSQLString(value);\n if (typeof value === \"number\") return value.toString();\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"bigint\") return value.toString();\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\nconst VARCHAR_MAX = 65535;\n\nfunction jsonType(dialect: SqlDialect): string {\n return dialect === \"mysql\" ? \"JSON\" : \"JSONB\";\n}\n\n// Extract the string literal values of a Zod enum across Zod v4 internal\n// shapes (`.options` array, or `.def.entries` object map).\nfunction getEnumValues(en: unknown): string[] {\n const e = en as any;\n if (Array.isArray(e?.options)) return e.options.filter((v: unknown): v is string => typeof v === \"string\");\n const entries = e?.def?.entries ?? e?._def?.entries ?? e?.def?.values;\n if (entries && typeof entries === \"object\") {\n return Object.values(entries).filter((v): v is string => typeof v === \"string\");\n }\n return [];\n}\n\n// Maps a scalar (non-collection) Zod type to a native SQL column type.\n// Returns undefined for types that don't have a simple scalar mapping\n// (objects, records, nested arrays, unknown types), so callers can decide\n// how to fall back. `field` is the original (possibly wrapped) node used to\n// read length constraints; `unwrapped` is the underlying scalar type.\nfunction getScalarSqlType(unwrapped: unknown, field: unknown, dialect: SqlDialect): string | undefined {\n if (unwrapped instanceof z.ZodString) {\n const maxLen = getStringMaxLength(field);\n if (maxLen !== undefined && maxLen <= VARCHAR_MAX) return `VARCHAR(${maxLen})`;\n return \"TEXT\";\n }\n\n if (unwrapped instanceof z.ZodNumber) return \"BIGINT\";\n\n if (unwrapped instanceof z.ZodBoolean) {\n return dialect === \"mysql\" ? \"TINYINT(1)\" : \"BOOLEAN\";\n }\n\n if (unwrapped instanceof z.ZodDate) {\n return dialect === \"mysql\" ? \"DATETIME(3)\" : \"TIMESTAMPTZ\";\n }\n\n if (unwrapped instanceof z.ZodBigInt) return \"BIGINT\";\n\n if (unwrapped instanceof z.ZodEnum) {\n // Enums are a bounded set of short string literals, so size the column\n // to the longest literal (`VARCHAR(n)`) rather than `TEXT`. This is both\n // more efficient and, crucially, indexable on MySQL — status/type enums\n // are indexed and MySQL cannot index a `TEXT` column without a prefix\n // length. Adding a longer variant later is a normal migration.\n const values = getEnumValues(unwrapped);\n const maxLen = values.reduce((m, v) => Math.max(m, v.length), 0);\n if (maxLen > 0 && maxLen <= VARCHAR_MAX) return `VARCHAR(${maxLen})`;\n return \"VARCHAR(30)\";\n }\n\n return undefined;\n}\n\nfunction getArrayElement(arr: z.ZodArray): unknown {\n return arr.element ?? arr.def?.element ?? arr.def?.type;\n}\n\n// Resolves the SQL type for an array field. MySQL has no native array column\n// type, so arrays are stored as JSON. Postgres supports native arrays of\n// scalar types (e.g. TEXT[], BIGINT[]); arrays of objects/records or nested\n// arrays fall back to JSONB.\nfunction getArraySqlType(arr: z.ZodArray, dialect: SqlDialect): string {\n if (dialect === \"mysql\") return \"JSON\";\n\n const rawElement = getArrayElement(arr);\n const element = unwrapZodType(rawElement);\n\n // Honor an explicit SQL type declared on the element's meta.\n const elementMeta = getFieldMeta(rawElement);\n if (elementMeta) {\n if (typeof elementMeta.pgType === \"string\") return `${elementMeta.pgType}[]`;\n }\n\n const scalar = getScalarSqlType(element, rawElement, dialect);\n if (scalar !== undefined) return `${scalar}[]`;\n\n return \"JSONB\";\n}\n\nfunction getSqlType(field: unknown, dialect: SqlDialect): string {\n const meta = getFieldMeta(field);\n if (meta) {\n const dialectKey = dialect === \"mysql\" ? \"mysqlType\" : \"pgType\";\n if (typeof meta[dialectKey] === \"string\") return meta[dialectKey] as string;\n }\n\n const unwrapped = unwrapZodType(field);\n\n if (unwrapped instanceof z.ZodArray) {\n return getArraySqlType(unwrapped, dialect);\n }\n\n if (unwrapped instanceof z.ZodObject || unwrapped instanceof z.ZodRecord) {\n return jsonType(dialect);\n }\n\n return getScalarSqlType(unwrapped, field, dialect) ?? \"TEXT\";\n}\n\nfunction isPrimaryKey(field: unknown): boolean {\n const meta = getFieldMeta(field);\n return meta?.primaryKey === true;\n}\n\nfunction getDefaultValue(field: unknown): string | undefined {\n const meta = getFieldMeta(field);\n if (meta && meta.defaultValue !== undefined) {\n // A string is treated as a raw SQL expression (e.g. \"now()\") for\n // backwards compatibility; other values are converted to SQL literals.\n if (typeof meta.defaultValue === \"string\") return meta.defaultValue;\n\n const value = meta.defaultValue;\n if (value === null) return \"NULL\";\n if (typeof value === \"number\") return value.toString();\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"bigint\") return value.toString();\n }\n\n return getDefaultFromZod(field);\n}\n\n// Does `schema` already declare an index equivalent to the auto commit_ts one\n// (same generated name, or a single-column index on commit_ts)?\nfunction hasCommitTsIndex(schema: SchemaDefinition<string, any, any>): boolean {\n const commitCol = schema.columns[\"commitTs\"] ?? \"commit_ts\";\n const autoName = `${schema.table}_commit_ts_idx`;\n return (schema.indexes ?? []).some(idx => {\n if (typeof idx === \"string\") return idx.includes(autoName);\n if (idx.name === autoName) return true;\n return idx.columns.length === 1 &&\n (idx.columns[0] === \"commitTs\" || idx.columns[0] === commitCol);\n });\n}\n\n// MySQL CREATE INDEX has no IF NOT EXISTS and — more importantly — some\n// declarative schema tools (e.g. planetscale/schemadiff) only accept indexes\n// declared INLINE in CREATE TABLE, not as standalone CREATE INDEX statements.\n// So on MySQL we fold every declarative index (plus the auto commit_ts index)\n// into `KEY` / `UNIQUE KEY` lines inside the table body. Raw-string indexes\n// can't be folded and are left for the caller to emit separately.\nfunction mysqlInlineIndexLines(schema: SchemaDefinition<string, any, any>): string[] {\n const columns: Record<string, string> = schema.columns;\n const lines: string[] = [];\n\n for (const idx of schema.indexes ?? []) {\n if (typeof idx === \"string\") continue;\n const cols = idx.columns.map(c => columns[c] ?? c).join(\", \");\n lines.push(` ${idx.unique ? \"UNIQUE KEY\" : \"KEY\"} ${idx.name} (${cols})`);\n }\n\n if (!hasCommitTsIndex(schema)) {\n const commitCol = columns[\"commitTs\"] ?? \"commit_ts\";\n lines.push(` KEY ${schema.table}_commit_ts_idx (${commitCol})`);\n }\n\n return lines;\n}\n\nexport interface SchemaToCreateTableOptions {\n dialect?: SqlDialect;\n ifNotExists?: boolean;\n}\n\nexport function schemaToCreateTable(\n schema: SchemaDefinition<string, any, any>,\n options?: SchemaToCreateTableOptions,\n): string {\n const dialect = options?.dialect ?? \"postgres\";\n const ifNotExists = options?.ifNotExists ?? true;\n\n const tableName = schema.table;\n const shape = schema.schema.shape;\n const columns: Record<string, string> = schema.columns;\n\n const userKeys = Object.keys(shape).filter(k => k !== \"id\" && k !== \"commitTs\");\n const orderedKeys = [\"id\", ...userKeys, \"commitTs\"];\n\n const lines: string[] = [];\n\n for (const fieldName of orderedKeys) {\n const field = shape[fieldName];\n if (!field) continue;\n\n const colName = columns[fieldName] ?? fieldName;\n if (!colName) continue;\n\n let sqlType = getSqlType(field, dialect);\n const notNull = !isOptional(field);\n const pk = isPrimaryKey(field);\n let defaultVal = fieldName === \"commitTs\" ? \"0\" : getDefaultValue(field);\n\n // MySQL cannot use a TEXT column as a PRIMARY KEY without a prefix\n // length. A primary key is always short and indexable, so fall back to a\n // bounded VARCHAR when no explicit length was declared.\n if (pk && dialect === \"mysql\" && sqlType === \"TEXT\") {\n sqlType = \"VARCHAR(255)\";\n }\n\n // MySQL never expresses a datetime/timestamp default as `now()` and\n // requires the default's fractional precision to match the column's. So\n // for any DATETIME/TIMESTAMP column with a now()/CURRENT_TIMESTAMP-style\n // default, emit `CURRENT_TIMESTAMP(p)` with the column's precision (or a\n // bare `CURRENT_TIMESTAMP` when the column has none) — honoring a custom\n // mysqlType (e.g. `TIMESTAMP`, `DATETIME(6)`) too. Postgres keeps `now()`.\n if (dialect === \"mysql\" && defaultVal) {\n const dt = /^(?:DATETIME|TIMESTAMP)(?:\\((\\d+)\\))?$/i.exec(sqlType.trim());\n const isNowLike = /^(?:now\\(\\s*\\d*\\s*\\)|current_timestamp(?:\\(\\s*\\d*\\s*\\))?)$/i.test(defaultVal.trim());\n if (dt && isNowLike) {\n const precision = dt[1];\n defaultVal = precision !== undefined ? `CURRENT_TIMESTAMP(${precision})` : \"CURRENT_TIMESTAMP\";\n }\n }\n\n // MySQL canonicalizes scalar column defaults as quoted strings in its\n // stored table definition (`DEFAULT '0'`, boolean → `'0'`/`'1'`). Emit\n // them the same way so a declarative diff against a live database is a\n // no-op instead of a spurious MODIFY on every run. CURRENT_TIMESTAMP(3),\n // NULL, and already-quoted string defaults are left untouched.\n if (dialect === \"mysql\" && defaultVal !== undefined) {\n const dv = defaultVal.trim();\n if (/^-?\\d+$/.test(dv)) defaultVal = `'${dv}'`;\n else if (/^true$/i.test(dv)) defaultVal = \"'1'\";\n else if (/^false$/i.test(dv)) defaultVal = \"'0'\";\n }\n\n let line = ` ${colName} ${sqlType}`;\n if (notNull) line += \" NOT NULL\";\n if (pk) line += \" PRIMARY KEY\";\n if (defaultVal !== undefined) line += ` DEFAULT ${defaultVal}`;\n\n lines.push(line);\n }\n\n // MySQL: fold indexes into the table body (see mysqlInlineIndexLines).\n if (dialect === \"mysql\") {\n lines.push(...mysqlInlineIndexLines(schema));\n }\n\n const ifNot = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n // MySQL stores an explicit ENGINE/charset in its canonical table definition;\n // emit them so a declarative diff against a live database doesn't report a\n // spurious charset change on every run (utf8mb4 is the MySQL 8 default).\n const tableOptions = dialect === \"mysql\" ? \" ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\" : \"\";\n return `CREATE TABLE ${ifNot}${tableName} (\\n${lines.join(\",\\n\")}\\n)${tableOptions};`;\n}\n\nexport function formatDeclarativeIndex(\n idx: DeclarativeIndex,\n tableName: string,\n columns: Record<string, string>,\n options?: { ifNotExists?: boolean },\n): string {\n // MySQL's CREATE INDEX has no `IF NOT EXISTS`, so this must be omittable\n // (callers pass ifNotExists:false for MySQL / migration-tool input).\n const ifNot = (options?.ifNotExists ?? true) ? \"IF NOT EXISTS \" : \"\";\n const colNames = idx.columns.map(c => columns[c] ?? c).join(\", \");\n let sql = `CREATE ${idx.unique ? \"UNIQUE \" : \"\"}INDEX ${ifNot}${idx.name} ON ${tableName}`;\n if (idx.type) sql += ` USING ${idx.type}`;\n sql += ` (${colNames})`;\n if (idx.where) sql += ` WHERE ${idx.where}`;\n return sql + \";\";\n}\n\nexport interface SchemaIndexesOptions {\n /** Emit `IF NOT EXISTS` on the auto-generated commit_ts index. Default true. */\n ifNotExists?: boolean;\n}\n\nexport function schemaIndexes(\n schema: SchemaDefinition<string, any, any>,\n options?: SchemaIndexesOptions,\n): string[] {\n const out = (schema.indexes ?? []).map(idx => {\n if (typeof idx === \"string\") return idx;\n return formatDeclarativeIndex(idx, schema.table, schema.columns, { ifNotExists: options?.ifNotExists });\n });\n\n // Every table has a `commit_ts` column (OCC) that is otherwise unindexed.\n // Auto-add an index on it unless the user already declared one covering\n // the commit_ts field or one with the same generated name.\n const commitCol = schema.columns[\"commitTs\"] ?? \"commit_ts\";\n const autoName = `${schema.table}_commit_ts_idx`;\n const alreadyDeclared = (schema.indexes ?? []).some(idx => {\n if (typeof idx === \"string\") return idx.includes(autoName);\n if (idx.name === autoName) return true;\n return idx.columns.length === 1 &&\n (idx.columns[0] === \"commitTs\" || idx.columns[0] === commitCol);\n });\n if (!alreadyDeclared) {\n const ifNot = (options?.ifNotExists ?? true) ? \"IF NOT EXISTS \" : \"\";\n out.push(`CREATE INDEX ${ifNot}${autoName} ON ${schema.table} (${commitCol});`);\n }\n\n return out;\n}\n\nexport interface GenerateSchemaSqlOptions {\n dialect?: SqlDialect;\n ifNotExists?: boolean;\n header?: boolean;\n /**\n * Prepend the framework-owned core tables (`commit_logs`, `metadata`) and\n * their indexes so the generated SQL fully describes the database. Default\n * true. Non-table core bootstrap (sequences, seed rows) is handled at\n * runtime by `initCore`, not emitted here.\n */\n includeCoreTables?: boolean;\n /**\n * MySQL only: override the SQL type of `commit_logs.id`. By default it is\n * auto-derived as `VARBINARY(max(32, largestIdColumnLength))` — wide enough\n * for the app's biggest primary key, with a 32-byte floor. Override for an\n * app with fixed-width binary ids (e.g. `\"BINARY(16)\"`). Ignored on Postgres\n * (always `BYTEA`).\n */\n commitLogIdType?: string;\n}\n\n/**\n * The largest declared primary-key string length across `schemas` (via the id\n * column's `.max(n)`), or undefined when none declare one. Used to size the\n * MySQL `commit_logs.id` column so it can hold any row's encoded id.\n */\nfunction maxPrimaryKeyLength(schemas: SchemaDefinition<string, any, any>[]): number | undefined {\n let max: number | undefined;\n for (const schema of schemas) {\n const idField = (schema.schema as any)?.shape?.id;\n const len = getStringMaxLength(idField);\n if (typeof len === \"number\") max = max === undefined ? len : Math.max(max, len);\n }\n return max;\n}\n\nexport function generateSchemaSql(\n schemas?: Map<string, SchemaDefinition<string, any, any>> | SchemaDefinition<string, any, any>[],\n options?: GenerateSchemaSqlOptions,\n): string {\n const dialect = options?.dialect ?? \"postgres\";\n const header = options?.header ?? true;\n const includeCoreTables = options?.includeCoreTables ?? true;\n\n let list: SchemaDefinition<string, any, any>[];\n\n if (schemas instanceof Map) {\n list = [...schemas.values()];\n } else if (Array.isArray(schemas)) {\n list = schemas;\n } else {\n list = [...schemaRegistry.values()];\n }\n\n list = list.filter(s => s?.table);\n list.sort((a, b) => a.table.localeCompare(b.table));\n\n const parts: string[] = [];\n\n if (header) {\n parts.push(\"-- Generated by Supalive Schema Generator\");\n parts.push(`-- Dialect: ${dialect}`);\n parts.push(`-- Tables: ${list.length}${includeCoreTables ? \" (+ core)\" : \"\"}`);\n parts.push(\"\");\n }\n\n if (includeCoreTables) {\n // MySQL: size commit_logs.id to the app's largest id column (32-byte\n // floor), unless the caller overrode the type. VARBINARY (not BINARY) so\n // variable-length ids aren't zero-padded, which would break the OCC id\n // match. Ignored on Postgres (BYTEA).\n const commitLogIdType = dialect === \"mysql\"\n ? (options?.commitLogIdType ?? `VARBINARY(${Math.max(32, maxPrimaryKeyLength(list) ?? 0)})`)\n : options?.commitLogIdType;\n\n parts.push(\"-- Core tables (framework-owned)\");\n for (const stmt of coreTablesSql(dialect, { ifNotExists: options?.ifNotExists, commitLogIdType })) {\n parts.push(stmt);\n }\n parts.push(\"\");\n }\n\n for (const schema of list) {\n parts.push(schemaToCreateTable(schema, { ...options, dialect }));\n if (dialect === \"mysql\") {\n // Declarative indexes and the auto commit_ts index are folded inline\n // into the CREATE TABLE above; only raw-string (verbatim SQL) indexes\n // remain to be emitted as separate statements.\n for (const idx of schema.indexes ?? []) {\n if (typeof idx === \"string\") parts.push(idx);\n }\n } else {\n const indexStmts = schemaIndexes(schema, { ifNotExists: options?.ifNotExists });\n for (const stmt of indexStmts) {\n parts.push(stmt);\n }\n }\n parts.push(\"\");\n }\n\n return parts.join(\"\\n\");\n}\n"],"mappings":";;;;AAqCA,SAAgB,cACZ,UAAsB,YACtB,SACQ;CACR,MAAM,cAAc,SAAS,eAAe;CAC5C,MAAM,IAAI,cAAc,mBAAmB;CAC3C,MAAM,IAAI,cAAc,mBAAmB;CAC3C,MAAM,kBAAkB,SAAS,mBAAmB;CAEpD,IAAI,YAAY,SACZ,OAAO;EAIH,gBAAgB,EAAE;EAUlB,gBAAgB,EAAE,wBACR,gBAAgB;EAO1B,gBAAgB,EAAE;CAItB;CAGJ,OAAO;EAEH,mBAAmB,EAAE;EACrB,gBAAgB,EAAE;EAOlB,gBAAgB,EAAE;EAClB,gBAAgB,EAAE;EAClB,gBAAgB,EAAE;CAItB;AACJ;;;ACrFA,S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AY;QAIP,MAAM,OAAO,OAAO,WAAW,CAAC,GACjC,IAAI,OAAO,QAAQ,UAAU,MAAM,KAAK,GAAG;EAAA,OAE5C;GACH,MAAM,aAAa,cAAc,QAAQ,EAAE,aAAa,SAAS,YAAY,CAAC;GAC9E,KAAK,MAAM,QAAQ,YACf,MAAM,KAAK,IAAI;EAEvB;EACA,MAAM,KAAK,EAAE;CACjB;CAEA,OAAO,MAAM,KAAK,IAAI;AAC1B"}
1
+ {"version":3,"file":"schema-sql.js","names":["z"],"sources":["../../../src/db/core_tables.ts","../../../src/db/schema-sql.ts"],"sourcesContent":["import type { SqlDialect } from \"./schema-sql\";\n\n/**\n * DDL for the core, framework-owned database objects that every Supalive\n * database must have alongside the user's own tables:\n *\n * - `commit_logs` — the append-only OCC change log (+ its lookup indexes).\n * - `metadata` — the small key/value table holding the OCC watermarks\n * (`latest_committed_ts`, `min_retained_ts`) and the\n * core schema version (`core_version`).\n * - `global_commit_ts` — the monotonic commit-timestamp source: a SEQUENCE on\n * Postgres, a single-row `BIGINT` counter table on MySQL.\n *\n * These are all pure schema (DDL), so they belong in the generated `schema.sql`\n * (see {@link generateSchemaSql}, which prepends them by default) and get\n * migrated ahead of runtime by your normal migration pipeline — a single\n * generated file fully describes the database.\n *\n * Data seeding (the `metadata` rows and the MySQL counter's initial `0`) and\n * any runtime-only schema changes live in `initCore` — see\n * {@link file://./init_db.ts}.\n */\n\nexport interface CoreTablesSqlOptions {\n /** Emit `IF NOT EXISTS` on `CREATE TABLE`/`CREATE INDEX`/`CREATE SEQUENCE`. Default true. */\n ifNotExists?: boolean;\n /**\n * MySQL only: the SQL type of `commit_logs.id`, which stores the changed\n * row's primary key encoded as bytes. Defaults to `VARBINARY(255)`.\n * `generateSchemaSql` derives a tighter value from the app's largest id\n * column; an app with fixed-width binary ids can override to e.g.\n * `BINARY(16)` (but note: variable-length ids must use VARBINARY — a fixed\n * BINARY column zero-pads stored values, which would break the OCC id match).\n */\n commitLogIdType?: string;\n}\n\nexport function coreTablesSql(\n dialect: SqlDialect = \"postgres\",\n options?: CoreTablesSqlOptions,\n): string[] {\n const ifNotExists = options?.ifNotExists ?? true;\n const t = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n const i = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n const commitLogIdType = options?.commitLogIdType ?? \"VARBINARY(255)\";\n\n if (dialect === \"mysql\") {\n return [\n // MySQL has no sequences: a single-row counter table advanced via\n // LAST_INSERT_ID (see MySqlDatabase.getNextTimestamp). Seeded to 0\n // by initCore.\n `CREATE TABLE ${t}global_commit_ts (\\n` +\n ` id BIGINT NOT NULL\\n` +\n `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`,\n // `id` holds the changed row's primary key encoded as bytes. Row ids\n // are variable-length (a prefixed string id can exceed 16 bytes), so\n // the default is VARBINARY, mirroring Postgres' flexible BYTEA — a\n // fixed BINARY column zero-pads stored values, breaking the OCC id\n // match. Sized via `commitLogIdType` (generateSchemaSql derives it\n // from the app's largest id column). `table_id` is a fixed 16-byte\n // table hash and stays BINARY(16).\n `CREATE TABLE ${t}commit_logs (\\n` +\n ` id ${commitLogIdType} NOT NULL,\\n` +\n ` ts BIGINT NOT NULL,\\n` +\n ` table_id BINARY(16) NOT NULL,\\n` +\n ` data LONGBLOB NOT NULL,\\n` +\n ` PRIMARY KEY (ts, table_id, id),\\n` +\n ` INDEX commit_logs_by_table_and_id (table_id, id, ts)\\n` +\n `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;`,\n `CREATE TABLE ${t}metadata (\\n` +\n ` meta_key VARCHAR(64) NOT NULL PRIMARY KEY,\\n` +\n ` meta_value BIGINT NOT NULL\\n` +\n `) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`,\n ];\n }\n\n return [\n // Monotonic OCC commit-timestamp source (see PgDatabase.getNextTimestamp).\n `CREATE SEQUENCE ${t}global_commit_ts START 1 INCREMENT 1 NO CYCLE;`,\n `CREATE TABLE ${t}commit_logs (\\n` +\n ` id BYTEA NOT NULL,\\n` +\n ` ts BIGINT NOT NULL,\\n` +\n ` table_id BYTEA NOT NULL,\\n` +\n ` data BYTEA NOT NULL,\\n` +\n ` PRIMARY KEY (ts, table_id, id)\\n` +\n `);`,\n `CREATE INDEX ${i}commit_logs_by_table_and_id ON commit_logs (table_id, id, ts);`,\n `CREATE INDEX ${i}commit_logs_by_table_ts_and_id ON commit_logs (table_id, ts, id);`,\n `CREATE TABLE ${t}metadata (\\n` +\n ` meta_key TEXT PRIMARY KEY,\\n` +\n ` meta_value BIGINT NOT NULL\\n` +\n `);`,\n ];\n}\n","import { z } from \"zod\";\nimport { SchemaDefinition, schemaRegistry } from \"./schema\";\nimport type { DeclarativeIndex } from \"./schema\";\nimport { unwrapZodType } from \"./codec\";\nimport { coreTablesSql } from \"./core_tables\";\n\nexport type SqlDialect = \"postgres\" | \"mysql\";\n\nfunction getFieldMeta(field: unknown): Record<string, unknown> | undefined {\n const f = field as any;\n const meta = typeof f.meta === \"function\" ? f.meta() : undefined;\n if (meta) return meta;\n\n const unwrapped = unwrapZodType(field);\n if (unwrapped !== field) {\n const innerMeta = typeof (unwrapped as any).meta === \"function\" ? (unwrapped as any).meta() : undefined;\n if (innerMeta) return innerMeta;\n }\n\n return undefined;\n}\n\nfunction getStringMaxLength(field: unknown): number | undefined {\n const unwrapped = unwrapZodType(field);\n if (!(unwrapped instanceof z.ZodString)) return undefined;\n\n const checks: any[] = (unwrapped as any).def?.checks ?? [];\n let maxLength: number | undefined;\n\n for (const check of checks) {\n const c = check._zod?.def ?? check.def ?? check;\n if (c.check === \"length_equals\" || c.check === \"size_equals\") {\n const len = c.length ?? c.size;\n if (typeof len === \"number\") maxLength = maxLength === undefined ? len : Math.min(maxLength, len);\n }\n if (c.check === \"max_length\" || c.check === \"max_size\") {\n const len = c.maximum ?? c.max;\n if (typeof len === \"number\") maxLength = maxLength === undefined ? len : Math.min(maxLength, len);\n }\n }\n\n return maxLength;\n}\n\nfunction isOptional(field: unknown): boolean {\n return (\n field instanceof z.ZodOptional ||\n field instanceof z.ZodNullable\n );\n}\n\nfunction escapeSQLString(s: string): string {\n return `'${s.replace(/'/g, \"''\")}'`;\n}\n\nfunction getDefaultFromZod(field: unknown): string | undefined {\n if (!(field instanceof z.ZodDefault)) return undefined;\n\n try {\n const f = field as any;\n let value = f.defaultValue;\n if (value === undefined) value = f.def?.defaultValue;\n if (typeof value === \"function\") value = value();\n\n if (value === undefined) return undefined;\n if (value === null) return \"NULL\";\n if (typeof value === \"string\") return escapeSQLString(value);\n if (typeof value === \"number\") return value.toString();\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"bigint\") return value.toString();\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\nconst VARCHAR_MAX = 65535;\n\nfunction jsonType(dialect: SqlDialect): string {\n return dialect === \"mysql\" ? \"JSON\" : \"JSONB\";\n}\n\n// Extract the string literal values of a Zod enum across Zod v4 internal\n// shapes (`.options` array, or `.def.entries` object map).\nfunction getEnumValues(en: unknown): string[] {\n const e = en as any;\n if (Array.isArray(e?.options)) return e.options.filter((v: unknown): v is string => typeof v === \"string\");\n const entries = e?.def?.entries ?? e?._def?.entries ?? e?.def?.values;\n if (entries && typeof entries === \"object\") {\n return Object.values(entries).filter((v): v is string => typeof v === \"string\");\n }\n return [];\n}\n\n// Maps a scalar (non-collection) Zod type to a native SQL column type.\n// Returns undefined for types that don't have a simple scalar mapping\n// (objects, records, nested arrays, unknown types), so callers can decide\n// how to fall back. `field` is the original (possibly wrapped) node used to\n// read length constraints; `unwrapped` is the underlying scalar type.\nfunction getScalarSqlType(unwrapped: unknown, field: unknown, dialect: SqlDialect): string | undefined {\n if (unwrapped instanceof z.ZodString) {\n const maxLen = getStringMaxLength(field);\n if (maxLen !== undefined && maxLen <= VARCHAR_MAX) return `VARCHAR(${maxLen})`;\n return \"TEXT\";\n }\n\n if (unwrapped instanceof z.ZodNumber) return \"BIGINT\";\n\n if (unwrapped instanceof z.ZodBoolean) {\n return dialect === \"mysql\" ? \"TINYINT(1)\" : \"BOOLEAN\";\n }\n\n if (unwrapped instanceof z.ZodDate) {\n return dialect === \"mysql\" ? \"DATETIME(3)\" : \"TIMESTAMPTZ\";\n }\n\n if (unwrapped instanceof z.ZodBigInt) return \"BIGINT\";\n\n if (unwrapped instanceof z.ZodEnum) {\n // Enums are a bounded set of short string literals, so size the column\n // to the longest literal (`VARCHAR(n)`) rather than `TEXT`. This is both\n // more efficient and, crucially, indexable on MySQL — status/type enums\n // are indexed and MySQL cannot index a `TEXT` column without a prefix\n // length. Adding a longer variant later is a normal migration.\n const values = getEnumValues(unwrapped);\n const maxLen = values.reduce((m, v) => Math.max(m, v.length), 0);\n if (maxLen > 0 && maxLen <= VARCHAR_MAX) return `VARCHAR(${maxLen})`;\n return \"VARCHAR(30)\";\n }\n\n return undefined;\n}\n\nfunction getArrayElement(arr: z.ZodArray): unknown {\n return arr.element ?? arr.def?.element ?? arr.def?.type;\n}\n\n// Resolves the SQL type for an array field. MySQL has no native array column\n// type, so arrays are stored as JSON. Postgres supports native arrays of\n// scalar types (e.g. TEXT[], BIGINT[]); arrays of objects/records or nested\n// arrays fall back to JSONB.\nfunction getArraySqlType(arr: z.ZodArray, dialect: SqlDialect): string {\n if (dialect === \"mysql\") return \"JSON\";\n\n const rawElement = getArrayElement(arr);\n const element = unwrapZodType(rawElement);\n\n // Honor an explicit SQL type declared on the element's meta.\n const elementMeta = getFieldMeta(rawElement);\n if (elementMeta) {\n if (typeof elementMeta.pgType === \"string\") return `${elementMeta.pgType}[]`;\n }\n\n const scalar = getScalarSqlType(element, rawElement, dialect);\n if (scalar !== undefined) return `${scalar}[]`;\n\n return \"JSONB\";\n}\n\nfunction getSqlType(field: unknown, dialect: SqlDialect): string {\n const meta = getFieldMeta(field);\n if (meta) {\n const dialectKey = dialect === \"mysql\" ? \"mysqlType\" : \"pgType\";\n if (typeof meta[dialectKey] === \"string\") return meta[dialectKey] as string;\n }\n\n const unwrapped = unwrapZodType(field);\n\n if (unwrapped instanceof z.ZodArray) {\n return getArraySqlType(unwrapped, dialect);\n }\n\n if (unwrapped instanceof z.ZodObject || unwrapped instanceof z.ZodRecord) {\n return jsonType(dialect);\n }\n\n return getScalarSqlType(unwrapped, field, dialect) ?? \"TEXT\";\n}\n\nfunction isPrimaryKey(field: unknown): boolean {\n const meta = getFieldMeta(field);\n return meta?.primaryKey === true;\n}\n\nfunction getDefaultValue(field: unknown): string | undefined {\n const meta = getFieldMeta(field);\n if (meta && meta.defaultValue !== undefined) {\n // A string is treated as a raw SQL expression (e.g. \"now()\") for\n // backwards compatibility; other values are converted to SQL literals.\n if (typeof meta.defaultValue === \"string\") return meta.defaultValue;\n\n const value = meta.defaultValue;\n if (value === null) return \"NULL\";\n if (typeof value === \"number\") return value.toString();\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"bigint\") return value.toString();\n }\n\n return getDefaultFromZod(field);\n}\n\n// Does `schema` already declare an index equivalent to the auto commit_ts one\n// (same generated name, or a single-column index on commit_ts)?\nfunction hasCommitTsIndex(schema: SchemaDefinition<string, any, any>): boolean {\n const commitCol = schema.columns[\"commitTs\"] ?? \"commit_ts\";\n const autoName = `${schema.table}_commit_ts_idx`;\n return (schema.indexes ?? []).some(idx => {\n if (typeof idx === \"string\") return idx.includes(autoName);\n if (idx.name === autoName) return true;\n return idx.columns.length === 1 &&\n (idx.columns[0] === \"commitTs\" || idx.columns[0] === commitCol);\n });\n}\n\n// MySQL CREATE INDEX has no IF NOT EXISTS and — more importantly — some\n// declarative schema tools (e.g. planetscale/schemadiff) only accept indexes\n// declared INLINE in CREATE TABLE, not as standalone CREATE INDEX statements.\n// So on MySQL we fold every declarative index (plus the auto commit_ts index)\n// into `KEY` / `UNIQUE KEY` lines inside the table body. Raw-string indexes\n// can't be folded and are left for the caller to emit separately.\nfunction mysqlInlineIndexLines(schema: SchemaDefinition<string, any, any>): string[] {\n const columns: Record<string, string> = schema.columns;\n const lines: string[] = [];\n\n for (const idx of schema.indexes ?? []) {\n if (typeof idx === \"string\") continue;\n const cols = idx.columns.map(c => columns[c] ?? c).join(\", \");\n lines.push(` ${idx.unique ? \"UNIQUE KEY\" : \"KEY\"} ${idx.name} (${cols})`);\n }\n\n if (!hasCommitTsIndex(schema)) {\n const commitCol = columns[\"commitTs\"] ?? \"commit_ts\";\n lines.push(` KEY ${schema.table}_commit_ts_idx (${commitCol})`);\n }\n\n return lines;\n}\n\nexport interface SchemaToCreateTableOptions {\n dialect?: SqlDialect;\n ifNotExists?: boolean;\n}\n\nexport function schemaToCreateTable(\n schema: SchemaDefinition<string, any, any>,\n options?: SchemaToCreateTableOptions,\n): string {\n const dialect = options?.dialect ?? \"postgres\";\n const ifNotExists = options?.ifNotExists ?? true;\n\n const tableName = schema.table;\n const shape = schema.schema.shape;\n const columns: Record<string, string> = schema.columns;\n\n const userKeys = Object.keys(shape).filter(k => k !== \"id\" && k !== \"commitTs\");\n const orderedKeys = [\"id\", ...userKeys, \"commitTs\"];\n\n const lines: string[] = [];\n\n for (const fieldName of orderedKeys) {\n const field = shape[fieldName];\n if (!field) continue;\n\n const colName = columns[fieldName] ?? fieldName;\n if (!colName) continue;\n\n let sqlType = getSqlType(field, dialect);\n const notNull = !isOptional(field);\n const pk = isPrimaryKey(field);\n let defaultVal = fieldName === \"commitTs\" ? \"0\" : getDefaultValue(field);\n\n // MySQL cannot use a TEXT column as a PRIMARY KEY without a prefix\n // length. A primary key is always short and indexable, so fall back to a\n // bounded VARCHAR when no explicit length was declared.\n if (pk && dialect === \"mysql\" && sqlType === \"TEXT\") {\n sqlType = \"VARCHAR(255)\";\n }\n\n // MySQL never expresses a datetime/timestamp default as `now()` and\n // requires the default's fractional precision to match the column's. So\n // for any DATETIME/TIMESTAMP column with a now()/CURRENT_TIMESTAMP-style\n // default, emit `CURRENT_TIMESTAMP(p)` with the column's precision (or a\n // bare `CURRENT_TIMESTAMP` when the column has none) — honoring a custom\n // mysqlType (e.g. `TIMESTAMP`, `DATETIME(6)`) too. Postgres keeps `now()`.\n if (dialect === \"mysql\" && defaultVal) {\n const dt = /^(?:DATETIME|TIMESTAMP)(?:\\((\\d+)\\))?$/i.exec(sqlType.trim());\n const isNowLike = /^(?:now\\(\\s*\\d*\\s*\\)|current_timestamp(?:\\(\\s*\\d*\\s*\\))?)$/i.test(defaultVal.trim());\n if (dt && isNowLike) {\n const precision = dt[1];\n defaultVal = precision !== undefined ? `CURRENT_TIMESTAMP(${precision})` : \"CURRENT_TIMESTAMP\";\n }\n }\n\n // MySQL canonicalizes scalar column defaults as quoted strings in its\n // stored table definition (`DEFAULT '0'`, boolean → `'0'`/`'1'`). Emit\n // them the same way so a declarative diff against a live database is a\n // no-op instead of a spurious MODIFY on every run. CURRENT_TIMESTAMP(3),\n // NULL, and already-quoted string defaults are left untouched.\n if (dialect === \"mysql\" && defaultVal !== undefined) {\n const dv = defaultVal.trim();\n if (/^-?\\d+$/.test(dv)) defaultVal = `'${dv}'`;\n else if (/^true$/i.test(dv)) defaultVal = \"'1'\";\n else if (/^false$/i.test(dv)) defaultVal = \"'0'\";\n }\n\n let line = ` ${colName} ${sqlType}`;\n if (notNull) line += \" NOT NULL\";\n if (pk) line += \" PRIMARY KEY\";\n if (defaultVal !== undefined) line += ` DEFAULT ${defaultVal}`;\n\n lines.push(line);\n }\n\n // MySQL: fold indexes into the table body (see mysqlInlineIndexLines).\n if (dialect === \"mysql\") {\n lines.push(...mysqlInlineIndexLines(schema));\n }\n\n const ifNot = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n // MySQL stores an explicit ENGINE/charset in its canonical table definition;\n // emit them so a declarative diff against a live database doesn't report a\n // spurious charset change on every run (utf8mb4 is the MySQL 8 default).\n const tableOptions = dialect === \"mysql\" ? \" ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\" : \"\";\n return `CREATE TABLE ${ifNot}${tableName} (\\n${lines.join(\",\\n\")}\\n)${tableOptions};`;\n}\n\nexport function formatDeclarativeIndex(\n idx: DeclarativeIndex,\n tableName: string,\n columns: Record<string, string>,\n options?: { ifNotExists?: boolean },\n): string {\n // MySQL's CREATE INDEX has no `IF NOT EXISTS`, so this must be omittable\n // (callers pass ifNotExists:false for MySQL / migration-tool input).\n const ifNot = (options?.ifNotExists ?? true) ? \"IF NOT EXISTS \" : \"\";\n const colNames = idx.columns.map(c => columns[c] ?? c).join(\", \");\n let sql = `CREATE ${idx.unique ? \"UNIQUE \" : \"\"}INDEX ${ifNot}${idx.name} ON ${tableName}`;\n if (idx.type) sql += ` USING ${idx.type}`;\n sql += ` (${colNames})`;\n if (idx.where) sql += ` WHERE ${idx.where}`;\n return sql + \";\";\n}\n\nexport interface SchemaIndexesOptions {\n /** Emit `IF NOT EXISTS` on the auto-generated commit_ts index. Default true. */\n ifNotExists?: boolean;\n}\n\nexport function schemaIndexes(\n schema: SchemaDefinition<string, any, any>,\n options?: SchemaIndexesOptions,\n): string[] {\n const out = (schema.indexes ?? []).map(idx => {\n if (typeof idx === \"string\") return idx;\n return formatDeclarativeIndex(idx, schema.table, schema.columns, { ifNotExists: options?.ifNotExists });\n });\n\n // Every table has a `commit_ts` column (OCC) that is otherwise unindexed.\n // Auto-add an index on it unless the user already declared one covering\n // the commit_ts field or one with the same generated name.\n const commitCol = schema.columns[\"commitTs\"] ?? \"commit_ts\";\n const autoName = `${schema.table}_commit_ts_idx`;\n const alreadyDeclared = (schema.indexes ?? []).some(idx => {\n if (typeof idx === \"string\") return idx.includes(autoName);\n if (idx.name === autoName) return true;\n return idx.columns.length === 1 &&\n (idx.columns[0] === \"commitTs\" || idx.columns[0] === commitCol);\n });\n if (!alreadyDeclared) {\n const ifNot = (options?.ifNotExists ?? true) ? \"IF NOT EXISTS \" : \"\";\n out.push(`CREATE INDEX ${ifNot}${autoName} ON ${schema.table} (${commitCol});`);\n }\n\n return out;\n}\n\nexport interface GenerateSchemaSqlOptions {\n dialect?: SqlDialect;\n ifNotExists?: boolean;\n header?: boolean;\n /**\n * Prepend the framework-owned core tables (`commit_logs`, `metadata`) and\n * their indexes so the generated SQL fully describes the database. Default\n * true. Non-table core bootstrap (sequences, seed rows) is handled at\n * runtime by `initCore`, not emitted here.\n */\n includeCoreTables?: boolean;\n /**\n * MySQL only: override the SQL type of `commit_logs.id`. By default it is\n * auto-derived as `VARBINARY(max(32, largestIdColumnLength))` — wide enough\n * for the app's biggest primary key, with a 32-byte floor. Override for an\n * app with fixed-width binary ids (e.g. `\"BINARY(16)\"`). Ignored on Postgres\n * (always `BYTEA`).\n */\n commitLogIdType?: string;\n}\n\n/**\n * The largest declared primary-key string length across `schemas` (via the id\n * column's `.max(n)`), or undefined when none declare one. Used to size the\n * MySQL `commit_logs.id` column so it can hold any row's encoded id.\n */\nfunction maxPrimaryKeyLength(schemas: SchemaDefinition<string, any, any>[]): number | undefined {\n let max: number | undefined;\n for (const schema of schemas) {\n const idField = (schema.schema as any)?.shape?.id;\n const len = getStringMaxLength(idField);\n if (typeof len === \"number\") max = max === undefined ? len : Math.max(max, len);\n }\n return max;\n}\n\nexport function generateSchemaSql(\n schemas?: Map<string, SchemaDefinition<string, any, any>> | SchemaDefinition<string, any, any>[],\n options?: GenerateSchemaSqlOptions,\n): string {\n const dialect = options?.dialect ?? \"mysql\";\n const header = options?.header ?? true;\n const includeCoreTables = options?.includeCoreTables ?? true;\n\n let list: SchemaDefinition<string, any, any>[];\n\n if (schemas instanceof Map) {\n list = [...schemas.values()];\n } else if (Array.isArray(schemas)) {\n list = schemas;\n } else {\n list = [...schemaRegistry.values()];\n }\n\n list = list.filter(s => s?.table);\n list.sort((a, b) => a.table.localeCompare(b.table));\n\n const parts: string[] = [];\n\n if (header) {\n parts.push(\"-- Generated by Supalive Schema Generator\");\n parts.push(`-- Dialect: ${dialect}`);\n parts.push(`-- Tables: ${list.length}${includeCoreTables ? \" (+ core)\" : \"\"}`);\n parts.push(\"\");\n }\n\n if (includeCoreTables) {\n // MySQL: size commit_logs.id to the app's largest id column (32-byte\n // floor), unless the caller overrode the type. VARBINARY (not BINARY) so\n // variable-length ids aren't zero-padded, which would break the OCC id\n // match. Ignored on Postgres (BYTEA).\n const commitLogIdType = dialect === \"mysql\"\n ? (options?.commitLogIdType ?? `VARBINARY(${Math.max(32, maxPrimaryKeyLength(list) ?? 0)})`)\n : options?.commitLogIdType;\n\n parts.push(\"-- Core tables (framework-owned)\");\n for (const stmt of coreTablesSql(dialect, { ifNotExists: options?.ifNotExists, commitLogIdType })) {\n parts.push(stmt);\n }\n parts.push(\"\");\n }\n\n for (const schema of list) {\n parts.push(schemaToCreateTable(schema, { ...options, dialect }));\n if (dialect === \"mysql\") {\n // Declarative indexes and the auto commit_ts index are folded inline\n // into the CREATE TABLE above; only raw-string (verbatim SQL) indexes\n // remain to be emitted as separate statements.\n for (const idx of schema.indexes ?? []) {\n if (typeof idx === \"string\") parts.push(idx);\n }\n } else {\n const indexStmts = schemaIndexes(schema, { ifNotExists: options?.ifNotExists });\n for (const stmt of indexStmts) {\n parts.push(stmt);\n }\n }\n parts.push(\"\");\n }\n\n return parts.join(\"\\n\");\n}\n"],"mappings":";;;;AAqCA,SAAgB,cACZ,UAAsB,YACtB,SACQ;CACR,MAAM,cAAc,SAAS,eAAe;CAC5C,MAAM,IAAI,cAAc,mBAAmB;CAC3C,MAAM,IAAI,cAAc,mBAAmB;CAC3C,MAAM,kBAAkB,SAAS,mBAAmB;CAEpD,IAAI,YAAY,SACZ,OAAO;EAIH,gBAAgB,EAAE;EAUlB,gBAAgB,EAAE,wBACR,gBAAgB;EAO1B,gBAAgB,EAAE;CAItB;CAGJ,OAAO;EAEH,mBAAmB,EAAE;EACrB,gBAAgB,EAAE;EAOlB,gBAAgB,EAAE;EAClB,gBAAgB,EAAE;EAClB,gBAAgB,EAAE;CAItB;AACJ;;;ACrFA,SAAS,aAAa,OAAqD;CACvE,MAAM,IAAI;CACV,MAAM,OAAO,OAAO,EAAE,SAAS,aAAa,EAAE,KAAK,IAAI,KAAA;CACvD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,MAAM,aAAa,cAAc,QAAQ,EAAE,aAAa,SAAS,YAAY,CAAC;GAC9E,KAAK,MAAM,QAAQ,YACf,MAAM,KAAK,IAAI;EAEvB;EACA,MAAM,KAAK,EAAE;CACjB;CAEA,OAAO,MAAM,KAAK,IAAI;AAC1B"}
@@ -1,7 +1,7 @@
1
- import { $n as AffectedSubscription, Bt as ScheduleHandle, E as Context, Ft as IncomingJobRequest, Ht as SupaliveDb, It as JobClient, Lt as JobScheduler, Mt as DevScheduler, Nt as DevSchedulerOptions, Pt as EnqueueOptions, Qn as CacheLayer, Rt as QStashScheduler, Un as Database, Vt as ScheduledJobDef, ar as RegisterSubscriptionResult, cr as UnregisterSubscriptionResult, dr as UpdateSubscriptionReadSetParams, er as InvalidateWritesetParams, fr as UpdateSubscriptionReadSetParamsSchema, ir as RegisterSubscriptionParamsSchema, nr as InvalidateWritesetResult, or as UnregisterSubscriptionParams, pr as UpdateSubscriptionReadSetResult, rr as RegisterSubscriptionParams, rt as Router, sr as UnregisterSubscriptionParamsSchema, tr as InvalidateWritesetParamsSchema, zt as QStashSchedulerOptions } from "../../index-C_i3U4cd.js";
2
- import { t as MySqlDatabase } from "../../mysql-Di6iuKWT.js";
3
- import { t as PgDatabase } from "../../postgres-CkhK4DqZ.js";
4
- import { C as SubManagerLink, S as SubManagerClient, b as SupaliveServerConfig, p as DatabaseConfig, u as SubId, x as UpstashConfig, y as SubscriptionManagerConfig } from "../../types_server-CG453PHb.js";
1
+ import { $n as InvalidateWritesetParams, Bt as ScheduleHandle, E as Context, Ft as IncomingJobRequest, Hn as Database, Ht as SupaliveDb, It as JobClient, Lt as JobScheduler, Mt as DevScheduler, Nt as DevSchedulerOptions, Pt as EnqueueOptions, Qn as AffectedSubscription, Rt as QStashScheduler, Vt as ScheduledJobDef, Zn as CacheLayer, ar as UnregisterSubscriptionParams, dr as UpdateSubscriptionReadSetParamsSchema, er as InvalidateWritesetParamsSchema, fr as UpdateSubscriptionReadSetResult, ir as RegisterSubscriptionResult, nr as RegisterSubscriptionParams, or as UnregisterSubscriptionParamsSchema, rr as RegisterSubscriptionParamsSchema, rt as Router, sr as UnregisterSubscriptionResult, tr as InvalidateWritesetResult, ur as UpdateSubscriptionReadSetParams, zt as QStashSchedulerOptions } from "../../index-f7mNbMhq.js";
2
+ import { t as MySqlDatabase } from "../../mysql-BX5hfgfE.js";
3
+ import { t as PgDatabase } from "../../postgres-EUz8TYFn.js";
4
+ import { C as SubManagerLink, S as SubManagerClient, b as SupaliveServerConfig, p as DatabaseConfig, u as SubId, x as UpstashConfig, y as SubscriptionManagerConfig } from "../../types_server-B7elBQyz.js";
5
5
  import pino, { Level } from "pino";
6
6
  import Redis$1 from "ioredis";
7
7
 
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","names":[],"sources":["../../../src/server/supalive-server.ts","../../../src/logger.ts","../../../src/server/sub-manager.ts","../../../src/db/init_db.ts","../../../src/server/sub_hash.ts"],"mappings":";;;;;;;;;;;cA6Ha,uBAAA,kBAAyC,OAAA;EAAA,QAC5C,MAAA;EAAA,QACA,UAAA;EAAA,QAEA,UAAA;EAAA,QACA,GAAA;EAAA,QAEA,KAAA;EAAA,QACA,QAAA;EA0K2B;EAAA,iBAxKlB,iBAAA;EAAA,QACT,EAAA;EAAA,QACA,eAAA;EAAA,QACA,MAAA;EAAA,QAMA,kBAAA;EAAA,QAIA,WAAA;EAAA,QAEA,SAAA;EAAA,QACA,OAAA;EAAA,QACA,SAAA;EAAA,QACA,UAAA;EAirC0D;EAAA,QA/qC1D,OAAA;EAAA,QAEA,QAAA;EAAA,QACA,mBAAA;EAAA,QACA,gBAAA;EAAA,QAEA,KAAA;cAMI,MAAA,EAAQ,oBAAA,CAAqB,QAAA;EArCjC;;;;;;;;;;;;EAAA,QAiJA,qBAAA;EAAA,QAqBA,kBAAA;EAOR,cAAA,CAAe,MAAA,EAAQ,MAAA,MAAY,QAAA;EAK7B,KAAA,IAAS,OAAA;EArJP;;;;;;EAAA,QA6KM,gBAA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;EAEA,iBAAA;EAEA,iBAAA;EAEA,oBAAA;EAEA,eAAA;AAAA;AAAA,iBAGY,cAAA,CAAe,MAAA,EAAQ,qBAAA;EAA0B,UAAA,EAAY,UAAA;EAAY,cAAA,GAAiB,OAAA;AAAA;;;;iBCvLpF,SAAA,CAAU,KAAA,YAAiB,OAAO;;;;;cAS3C,kBAAA;;;;;;;;;iBAgDS,sBAAA,CACpB,SAAA,UACA,KAAA,oBACA,aAAA,WACC,OAAO;;;;;;iBAWY,gBAAA,CACpB,SAAA,UACA,KAAA,oBACA,aAAA,WACC,OAAO"}
1
+ {"version":3,"file":"server.d.ts","names":[],"sources":["../../../src/server/supalive-server.ts","../../../src/logger.ts","../../../src/server/sub-manager.ts","../../../src/db/init_db.ts","../../../src/server/sub_hash.ts"],"mappings":";;;;;;;;;;;cA6Ha,uBAAA,kBAAyC,OAAA;EAAA,QAC5C,MAAA;EAAA,QACA,UAAA;EAAA,QAEA,UAAA;EAAA,QACA,GAAA;EAAA,QAEA,KAAA;EAAA,QACA,QAAA;EA0K2B;EAAA,iBAxKlB,iBAAA;EAAA,QACT,EAAA;EAAA,QACA,eAAA;EAAA,QACA,MAAA;EAAA,QAMA,kBAAA;EAAA,QAIA,WAAA;EAAA,QAEA,SAAA;EAAA,QACA,OAAA;EAAA,QACA,SAAA;EAAA,QACA,UAAA;EAirC0D;EAAA,QA/qC1D,OAAA;EAAA,QAEA,QAAA;EAAA,QACA,mBAAA;EAAA,QACA,gBAAA;EAAA,QAEA,KAAA;cAMI,MAAA,EAAQ,oBAAA,CAAqB,QAAA;EArCjC;;;;;;;;;;;;EAAA,QAiJA,qBAAA;EAAA,QAqBA,kBAAA;EAOR,cAAA,CAAe,MAAA,EAAQ,MAAA,MAAY,QAAA;EAK7B,KAAA,IAAS,OAAA;EArJP;;;;;;EAAA,QA6KM,gBAAA;EApCN;EAoDR,WAAA,CAAY,IAAA;EA7CW;;;;;EAsDjB,WAAA,CAAY,IAAA,UAAc,IAAA,WAAe,I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AAQ,qBAAA;EAA0B,UAAA,EAAY,UAAA;EAAY,cAAA,GAAiB,OAAA;AAAA;;;;iBCvLpF,SAAA,CAAU,KAAA,YAAiB,OAAO;;;;;cAS3C,kBAAA;;;;;;;;;iBAgDS,sBAAA,CACpB,SAAA,UACA,KAAA,oBACA,aAAA,WACC,OAAO;;;;;;iBAWY,gBAAA,CACpB,SAAA,UACA,KAAA,oBACA,aAAA,WACC,OAAO"}
@@ -5,7 +5,7 @@ import { i as AuthenticationError, o as ClientMessageSchema } from "../../types_
5
5
  import { n as RemoteSubscriptionMessageSchema } from "../../types_server-BhC19R2a.js";
6
6
  import { n as sleep } from "../../realtime_db-CVze3gM0.js";
7
7
  import { n as resolveReadRouting, t as makeConnRouting } from "../../read-routing-BUcQAwnd.js";
8
- import { C as appInstanceId, D as serializeMapValue, E as logger, S as RetentionWatermark, T as logLevelOf, _ as UnregisterSubscriptionResultSchema, a as bootstrapDbTypes, b as UpdateSubscriptionReadSetResultSchema, c as initCore, d as InvalidateWritesetParamsSchema, f as InvalidateWritesetResultSchema, g as UnregisterSubscriptionParamsSchema, h as RegisterSubscriptionResultSchema, i as DB_QUERY_TIMEOUT_MS, l as initDatabase, m as RegisterSubscriptionParamsSchema, n as SubscriptionWorker, o as createDatabase, p as RegisterSubscriptionBatchResultSchema, r as CORE_VERSION, s as initCacheLayer, t as dispatchWorkerMessage, u as CacheLayer, v as UnregisterSubscriptionsResultSchema, w as isProduction, x as RETENTION_WATERMARK_CHANNEL, y as UpdateSubscriptionReadSetParamsSchema } from "../../sub-worker-dispatch-CzwVHQVi.js";
8
+ import { C as appInstanceId, D as serializeMapValue, E as logger, S as RetentionWatermark, T as logLevelOf, _ as UnregisterSubscriptionResultSchema, a as bootstrapDbTypes, b as UpdateSubscriptionReadSetResultSchema, c as initCore, d as InvalidateWritesetParamsSchema, f as InvalidateWritesetResultSchema, g as UnregisterSubscriptionParamsSchema, h as RegisterSubscriptionResultSchema, i as DB_QUERY_TIMEOUT_MS, l as initDatabase, m as RegisterSubscriptionParamsSchema, n as SubscriptionWorker, o as createDatabase, p as RegisterSubscriptionBatchResultSchema, r as CORE_VERSION, s as initCacheLayer, t as dispatchWorkerMessage, u as CacheLayer, v as UnregisterSubscriptionsResultSchema, w as isProduction, x as RETENTION_WATERMARK_CHANNEL, y as UpdateSubscriptionReadSetParamsSchema } from "../../sub-worker-dispatch-CC0w_sx0.js";
9
9
  import { v4 } from "uuid";
10
10
  import { createServer } from "http";
11
11
  import { WebSocket, WebSocketServer } from "ws";
@@ -738,7 +738,7 @@ var HttpRpcHandler = class {
738
738
  res.setHeader("access-control-allow-origin", origin);
739
739
  res.setHeader("vary", "Origin");
740
740
  } else return;
741
- res.setHeader("access-control-allow-methods", "POST, OPTIONS");
741
+ res.setHeader("access-control-allow-methods", "POST, GET, OPTIONS");
742
742
  res.setHeader("access-control-allow-headers", "authorization, content-type");
743
743
  res.setHeader("access-control-max-age", "86400");
744
744
  }
@@ -1050,7 +1050,7 @@ var SupaliveWebSocketServer = class {
1050
1050
  */
1051
1051
  async handleHttpRequest(req, res) {
1052
1052
  const path = (req.url ?? "/").split("?")[0];
1053
- if (req.method === "GET" && (path === "/_health" || path === `${this.jobPath}/_health`)) return sendJson(res, 200, {
1053
+ if (req.method === "GET" && path === "/_health") return sendJson(res, 200, {
1054
1054
  status: "ok",
1055
1055
  instanceId: this.instanceId
1056
1056
  });