gencow 0.1.299 → 0.2.1

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 (151) hide show
  1. package/bin/gencow.mjs +0 -6
  2. package/core/package.json +1 -1
  3. package/docs/packaging.md +14 -4
  4. package/lib/cli-artifact-guard.mjs +53 -3
  5. package/lib/cli-dev-runtime.mjs +1 -0
  6. package/lib/cli-project-runtime.mjs +26 -14
  7. package/lib/codegen-command.mjs +16 -0
  8. package/lib/coding-guardrails.mjs +2 -0
  9. package/lib/dashboard-artifact.mjs +65 -0
  10. package/lib/dashboard-assets.mjs +20 -0
  11. package/lib/db-command.mjs +121 -80
  12. package/lib/db-migration-command-steps.mjs +19 -16
  13. package/lib/db-push-command.mjs +1 -1
  14. package/lib/deploy-codegen-preflight.mjs +1 -0
  15. package/lib/dev-cloud-command.mjs +1 -1
  16. package/lib/dev-local-command.mjs +19 -56
  17. package/lib/document-local-converter.mjs +11 -0
  18. package/lib/local-dashboard-plan.mjs +60 -0
  19. package/lib/local-database-commands.mjs +127 -0
  20. package/lib/local-development-migrations.mjs +157 -0
  21. package/lib/local-drizzle-database.config.mjs +10 -0
  22. package/lib/local-runtime-features.mjs +12 -0
  23. package/lib/rag-selection.mjs +7 -0
  24. package/lib/runtime-local-worker.mjs +116 -0
  25. package/lib/runtime-mode.mjs +3 -0
  26. package/lib/standalone-codegen-adapter.mjs +91 -0
  27. package/lib/ts-codegen-import-extension.mjs +228 -19
  28. package/package.json +15 -8
  29. package/runtime/config.mjs +218 -2
  30. package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
  31. package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
  32. package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
  33. package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
  34. package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
  35. package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
  36. package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
  37. package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
  38. package/runtime/engine/chunk-5575APCJ.mjs +215 -0
  39. package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
  40. package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
  41. package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
  42. package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
  43. package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
  44. package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
  45. package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
  46. package/runtime/engine/chunk-6W653LXI.mjs +13 -0
  47. package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
  48. package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
  49. package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
  50. package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
  51. package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
  52. package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
  53. package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
  54. package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
  55. package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
  56. package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
  57. package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
  58. package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
  59. package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
  60. package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
  61. package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
  62. package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
  63. package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
  64. package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
  65. package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
  66. package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
  67. package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
  68. package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
  69. package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
  70. package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
  71. package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
  72. package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
  73. package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
  74. package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
  75. package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
  76. package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
  77. package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
  78. package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
  79. package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
  80. package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
  81. package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
  82. package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
  83. package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
  84. package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
  85. package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
  86. package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
  87. package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
  88. package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
  89. package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
  90. package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
  91. package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
  92. package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
  93. package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
  94. package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
  95. package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
  96. package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
  97. package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
  98. package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
  99. package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
  100. package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
  101. package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
  102. package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
  103. package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
  104. package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
  105. package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
  106. package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
  107. package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
  108. package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
  109. package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
  110. package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
  111. package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
  112. package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
  113. package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
  114. package/runtime/engine/chunk-YRHM272W.mjs +528 -0
  115. package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
  116. package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
  117. package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
  118. package/runtime/engine/composition.mjs +325 -0
  119. package/runtime/engine/document-local.mjs +504 -0
  120. package/runtime/engine/graph.json +4134 -0
  121. package/runtime/engine/index.mjs +265 -0
  122. package/runtime/engine/local-postgres-support.mjs +69 -0
  123. package/runtime/engine/local.mjs +3275 -0
  124. package/runtime/engine/pglite-directory-lock.mjs +8 -0
  125. package/runtime/engine/rag.mjs +11 -0
  126. package/runtime/engine/search.mjs +18 -0
  127. package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
  128. package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
  129. package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
  130. package/runtime/framework-migrations/manifest.json +56 -0
  131. package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
  132. package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
  133. package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
  134. package/runtime/runtime-metadata.json +27 -0
  135. package/runtime/tooling.mjs +10399 -8951
  136. package/scripts/bundle-runtime-config.mjs +23 -0
  137. package/scripts/bundle-runtime.mjs +100 -0
  138. package/scripts/bundle-runtime.test.mjs +33 -0
  139. package/scripts/bundle-shared.mjs +3 -0
  140. package/scripts/copy-dashboard.mjs +16 -0
  141. package/scripts/pre-publish-check.mjs +23 -11
  142. package/templateFeature/ai/ai-facade.ts +38 -15
  143. package/templateFeature/ai/manifest.json +1 -0
  144. package/templateFeature/sso/sso-auth-callback.tsx +37 -5
  145. package/templateFeature/tools/manifest.json +5 -2
  146. package/templateFeature/tools/tools.ts +3 -3
  147. package/runtime/server.mjs +0 -14389
  148. package/scripts/bundle-server.mjs +0 -223
  149. package/server/config.js +0 -1
  150. package/server/index.js +0 -1
  151. package/server/package.json +0 -6
@@ -0,0 +1,32 @@
1
+ import {
2
+ runtimeDatabaseSetupError
3
+ } from "./chunk-SVJCOUI3.mjs";
4
+
5
+ // ../runtime/dist/framework-schema/ready.js
6
+ var states = /* @__PURE__ */ new WeakMap();
7
+ function createFrameworkSchemaReady(state) {
8
+ const ready = Object.freeze({ kind: "framework-schema-ready" });
9
+ states.set(ready, state);
10
+ return ready;
11
+ }
12
+ function assertFrameworkSchemaReady(ready, owner, binding, plan, requiredComponent, requiredContractVersion) {
13
+ const state = states.get(ready);
14
+ const selectedComponent = requiredComponent === void 0 ? void 0 : state?.components.find((component) => component.id === requiredComponent);
15
+ if (!state || state.owner !== owner || state.binding.appId !== binding.appId || state.binding.generationId !== binding.generationId || state.plan !== plan || requiredComponent !== void 0 && !selectedComponent || requiredContractVersion !== void 0 && (requiredComponent === void 0 || !Number.isSafeInteger(requiredContractVersion) || requiredContractVersion < 1 || selectedComponent?.contractVersion !== requiredContractVersion))
16
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
17
+ return state;
18
+ }
19
+ function frameworkSchemaReadyOutcome(ready, owner, binding, plan) {
20
+ const state = assertFrameworkSchemaReady(ready, owner, binding, plan);
21
+ return Object.freeze({ impact: state.impact, correlationId: state.correlationId });
22
+ }
23
+ function revokeFrameworkSchemaReady(ready) {
24
+ states.delete(ready);
25
+ }
26
+
27
+ export {
28
+ createFrameworkSchemaReady,
29
+ assertFrameworkSchemaReady,
30
+ frameworkSchemaReadyOutcome,
31
+ revokeFrameworkSchemaReady
32
+ };
@@ -0,0 +1,432 @@
1
+ import {
2
+ assertDatabaseGeneration,
3
+ captureManagedSchemaComponents,
4
+ createManagedSchemaPreparation,
5
+ createPostgresGroundingCitationReader,
6
+ createPostgresSearchModes,
7
+ createSearchSessionReads,
8
+ loadPgliteManagedExtensions,
9
+ runtimeDatabaseInspection
10
+ } from "./chunk-CPU4OZSX.mjs";
11
+ import {
12
+ ragManagedTableNames
13
+ } from "./chunk-N6GCLOUX.mjs";
14
+ import {
15
+ borrowRuntimeDrizzle
16
+ } from "./chunk-ADF3UR6L.mjs";
17
+ import {
18
+ markPgliteQueryFailure
19
+ } from "./chunk-A5BMQ5IC.mjs";
20
+ import {
21
+ createRuntimeScopedApplicationReads,
22
+ runtimeGenerationBackedApplicationDatabase,
23
+ runtimeScopedApplicationReads
24
+ } from "./chunk-YRHM272W.mjs";
25
+ import "./chunk-P5IIXAIE.mjs";
26
+ import "./chunk-XNFVL2OY.mjs";
27
+ import {
28
+ observeRuntimeStartupStage
29
+ } from "./chunk-KVLTJFCH.mjs";
30
+ import "./chunk-7KUJ2H2S.mjs";
31
+ import "./chunk-LINVSJEM.mjs";
32
+ import "./chunk-GOLP7OSG.mjs";
33
+ import "./chunk-QL2TQX2N.mjs";
34
+ import "./chunk-LEW5ZMLR.mjs";
35
+ import "./chunk-N2TA2IK2.mjs";
36
+ import {
37
+ snapshotRuntimeBinding
38
+ } from "./chunk-WDTKPPMU.mjs";
39
+ import "./chunk-KX2PRQPS.mjs";
40
+ import "./chunk-NAG2OXS5.mjs";
41
+ import {
42
+ snapshotRuntimeIdentity,
43
+ snapshotRuntimeRls
44
+ } from "./chunk-IKQKBE2G.mjs";
45
+ import "./chunk-IFMOTJNU.mjs";
46
+ import {
47
+ acquirePgliteDirectoryLock
48
+ } from "./chunk-VWU7JJ3P.mjs";
49
+ import "./chunk-I3GWR43K.mjs";
50
+ import {
51
+ RuntimeDatabaseRlsError,
52
+ RuntimeDiagnosticError,
53
+ createRlsDb,
54
+ issuedRuntimeDiagnostic
55
+ } from "./chunk-AEBW7XZJ.mjs";
56
+
57
+ // ../runtime/dist/adapters/database/pglite.js
58
+ import { PGlite } from "@electric-sql/pglite";
59
+
60
+ // ../runtime/dist/adapters/database/pglite-directory-owner.js
61
+ async function closePgliteDirectoryOwner(closeClient, releaseDirectory) {
62
+ await closeClient();
63
+ await releaseDirectory();
64
+ }
65
+
66
+ // ../runtime/dist/adapters/database/pglite-readiness.js
67
+ import { randomUUID } from "node:crypto";
68
+ function pgliteInitializationFailure(persistence) {
69
+ const persistent = persistence === "persistent";
70
+ return new RuntimeDiagnosticError({
71
+ code: "RUNTIME_DATABASE_INITIALIZATION_FAILED",
72
+ stage: "startup",
73
+ capability: "database",
74
+ servingStarted: false,
75
+ // Engine recovery may already have started, even though app/role SQL has not.
76
+ dataImpact: persistent ? "unknown" : "none",
77
+ retryable: false,
78
+ correlationId: randomUUID(),
79
+ retryPrecondition: persistent ? "Retry only after the failed Runtime process has exited and a readable database input is available with the supported PGlite SDK. Preserve the original directory if its state cannot be verified." : "Retry only after verifying the supported PGlite SDK and sufficient process resources; create a fresh ephemeral database owner.",
80
+ nextAction: persistent ? "Stop the failed local Runtime process and preserve its database directory. Inspect the selected SDK with pnpm why @electric-sql/pglite and verify directory permissions and the supported SDK version. If the existing input remains unreadable, restore a verified backup into a fresh configured local database directory. For CLI-managed local development, run pnpm gencow dev --local only after the retry preconditions hold; otherwise restart the original standalone launcher under those same preconditions. Do not edit internal database files or lock records or delete the original directory." : "Inspect the selected SDK with pnpm why @electric-sql/pglite and available process resources, then recreate the ephemeral database after correcting the precondition. This is a new process-lifetime database, not recovery of earlier runs."
81
+ });
82
+ }
83
+ async function awaitPgliteReadiness(client, persistence) {
84
+ try {
85
+ await client.waitReady;
86
+ } catch {
87
+ throw pgliteInitializationFailure(persistence);
88
+ }
89
+ }
90
+
91
+ // ../runtime/dist/adapters/database/shared-pglite-rls.js
92
+ var LOCAL_PGLITE_APPLICATION_ROLE = "gencow_runtime_application";
93
+ var LOCAL_PGLITE_MAINTENANCE_ROLE = "gencow_runtime_maintenance";
94
+ var LocalPgliteRlsError = class extends Error {
95
+ code;
96
+ nextAction;
97
+ constructor(code, nextAction) {
98
+ super(code);
99
+ this.code = code;
100
+ this.nextAction = nextAction;
101
+ }
102
+ };
103
+ var unsafeRole = (nextAction) => new LocalPgliteRlsError("RUNTIME_DATABASE_RLS_APPLICATION_ROLE_UNSAFE", nextAction);
104
+ async function roleRow(query2, role) {
105
+ return (await query2(`select rolname, rolsuper, rolbypassrls, rolinherit, rolcanlogin, rolcreatedb, rolcreaterole, rolreplication from pg_roles where rolname = '${role}'`)).rows?.[0];
106
+ }
107
+ async function ensureRole(query2, role) {
108
+ const maintenance = role === LOCAL_PGLITE_MAINTENANCE_ROLE;
109
+ const existing = await roleRow(query2, role);
110
+ if (!existing) {
111
+ await query2(`create role ${role} nologin nosuperuser ${maintenance ? "bypassrls" : "nobypassrls"} noinherit`);
112
+ } else if (existing.rolsuper === true || !maintenance && existing.rolbypassrls === true || existing.rolcanlogin === true || existing.rolcreatedb === true || existing.rolcreaterole === true || existing.rolreplication === true) {
113
+ if (maintenance)
114
+ throw new LocalPgliteRlsError("RUNTIME_DATABASE_RLS_UNSAFE_ROLE_UNAVAILABLE", "Use a separate non-superuser local maintenance role before restarting.");
115
+ throw unsafeRole("Use a local database directory without a privileged application role, then restart.");
116
+ } else if (maintenance && existing.rolbypassrls !== true) {
117
+ await query2(`alter role ${LOCAL_PGLITE_MAINTENANCE_ROLE} bypassrls`);
118
+ }
119
+ }
120
+ async function assertRoleReadiness(query2) {
121
+ const application = await roleRow(query2, LOCAL_PGLITE_APPLICATION_ROLE);
122
+ const maintenance = await roleRow(query2, LOCAL_PGLITE_MAINTENANCE_ROLE);
123
+ if (!application || !maintenance || application.rolsuper === true || application.rolbypassrls === true) {
124
+ throw unsafeRole("Use a non-owner, non-BYPASSRLS local application role and restart.");
125
+ }
126
+ if (maintenance.rolsuper === true || maintenance.rolbypassrls !== true)
127
+ throw new LocalPgliteRlsError("RUNTIME_DATABASE_RLS_UNSAFE_ROLE_UNAVAILABLE", "Restore a separate non-superuser local maintenance role with RLS bypass before restarting.");
128
+ const membership = await query2(`
129
+ with recursive inherited_roles(role_id) as (
130
+ select roleid from pg_auth_members where member = (select oid from pg_roles where rolname = '${LOCAL_PGLITE_APPLICATION_ROLE}')
131
+ union
132
+ select membership.roleid from pg_auth_members membership join inherited_roles inherited on membership.member = inherited.role_id
133
+ )
134
+ select exists(select 1 from inherited_roles where role_id =
135
+ (select oid from pg_roles where rolname = '${LOCAL_PGLITE_MAINTENANCE_ROLE}')) as unsafe
136
+ `);
137
+ if (membership.rows?.[0]?.unsafe === true) {
138
+ throw unsafeRole("Remove application-role membership in local maintenance before restarting.");
139
+ }
140
+ const ownedRls = await query2(`
141
+ select 1 from pg_class relation
142
+ join pg_namespace namespace on namespace.oid = relation.relnamespace
143
+ where relation.relrowsecurity
144
+ and namespace.nspname not in ('pg_catalog', 'information_schema')
145
+ and pg_has_role('${LOCAL_PGLITE_APPLICATION_ROLE}', relation.relowner, 'USAGE')
146
+ limit 1
147
+ `);
148
+ if (ownedRls.rows?.length) {
149
+ throw unsafeRole("Use a separate local schema owner for RLS-enabled relations, then restart.");
150
+ }
151
+ try {
152
+ await query2("begin");
153
+ await query2(`set local role ${LOCAL_PGLITE_APPLICATION_ROLE}`);
154
+ const selected = await query2("select current_user");
155
+ await query2("rollback");
156
+ if (selected.rows?.[0]?.current_user !== LOCAL_PGLITE_APPLICATION_ROLE) {
157
+ throw new Error("local role did not become current_user");
158
+ }
159
+ } catch {
160
+ await query2("rollback").catch(() => {
161
+ });
162
+ throw new LocalPgliteRlsError("RUNTIME_DATABASE_RLS_ENGINE_UNSUPPORTED", "Use a supported PGlite version with transaction-local role support, then restart.");
163
+ }
164
+ }
165
+ async function bootstrapLocalPgliteRls(query2, options = {}) {
166
+ try {
167
+ const excluded = [...options.excludedTableNames ?? []];
168
+ if (excluded.some((name) => typeof name !== "string" || !name || name.includes("\0")))
169
+ throw new Error("Invalid local table grant exclusion");
170
+ await ensureRole(query2, LOCAL_PGLITE_APPLICATION_ROLE);
171
+ await ensureRole(query2, LOCAL_PGLITE_MAINTENANCE_ROLE);
172
+ await query2(`grant usage on schema public to ${LOCAL_PGLITE_APPLICATION_ROLE}, ${LOCAL_PGLITE_MAINTENANCE_ROLE}`);
173
+ if (excluded.length) {
174
+ const tables = await query2(`SELECT relation.relname AS name FROM pg_class relation
175
+ JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
176
+ WHERE namespace.nspname = 'public' AND relation.relkind IN ('r','p','v','m','f')
177
+ AND relation.relname NOT IN (${excluded.map((name) => `'${name.replaceAll("'", "''")}'`).join(",")})`);
178
+ const names = (tables.rows ?? []).map((row) => {
179
+ if (typeof row.name !== "string")
180
+ throw new Error("Invalid managed grant catalog");
181
+ return `public."${row.name.replaceAll('"', '""')}"`;
182
+ });
183
+ if (names.length)
184
+ await query2(`grant select, insert, update, delete on table ${names.join(",")} to ${LOCAL_PGLITE_APPLICATION_ROLE}, ${LOCAL_PGLITE_MAINTENANCE_ROLE}`);
185
+ } else {
186
+ await query2(`grant select, insert, update, delete on all tables in schema public to ${LOCAL_PGLITE_APPLICATION_ROLE}, ${LOCAL_PGLITE_MAINTENANCE_ROLE}`);
187
+ }
188
+ await query2(`alter default privileges in schema public grant select, insert, update, delete on tables to ${LOCAL_PGLITE_APPLICATION_ROLE}, ${LOCAL_PGLITE_MAINTENANCE_ROLE}`);
189
+ await query2(`grant usage, select on all sequences in schema public to ${LOCAL_PGLITE_APPLICATION_ROLE}, ${LOCAL_PGLITE_MAINTENANCE_ROLE}`);
190
+ await query2(`alter default privileges in schema public grant usage, select on sequences to ${LOCAL_PGLITE_APPLICATION_ROLE}, ${LOCAL_PGLITE_MAINTENANCE_ROLE}`);
191
+ await assertRoleReadiness(query2);
192
+ } catch (error) {
193
+ if (error instanceof LocalPgliteRlsError)
194
+ throw error;
195
+ throw new LocalPgliteRlsError("RUNTIME_DATABASE_RLS_BOOTSTRAP_FAILED", "Correct the selected local database's role/bootstrap precondition, then restart.");
196
+ }
197
+ }
198
+
199
+ // ../runtime/dist/adapters/database/pglite.js
200
+ import { drizzle } from "drizzle-orm/pglite";
201
+
202
+ // ../runtime/dist/adapters/database/pglite-errors.js
203
+ function pgliteQueryFailure(error) {
204
+ if (issuedRuntimeDiagnostic(error))
205
+ return error;
206
+ const code = providerSqlState(error);
207
+ if (code === "42703") {
208
+ markPgliteQueryFailure(error, code);
209
+ return error;
210
+ }
211
+ const constraint = code === "23505" || code === "23514";
212
+ const schema = code === "42P01";
213
+ if (!constraint && !schema)
214
+ return error;
215
+ const diagnostic = new RuntimeDiagnosticError({
216
+ code: constraint ? "RUNTIME_DATABASE_CONSTRAINT_REJECTED" : "RUNTIME_DATABASE_SCHEMA_UNAVAILABLE",
217
+ stage: "request",
218
+ capability: "database",
219
+ servingStarted: "unchanged",
220
+ dataImpact: "unknown",
221
+ retryable: false,
222
+ retryPrecondition: constraint ? "Correct the conflicting or invalid input and inspect existing operation effects before explicitly retrying." : "Restore verified application schema readiness through its trusted database owner before retrying; preserve existing data.",
223
+ nextAction: constraint ? "Read existing records and check the declared uniqueness and value constraints; correct the input before explicitly submitting the operation again." : "Have the trusted database owner inspect schema readiness and restore the expected application schema through the documented setup or recovery flow. Do not edit applied migrations or blindly repeat writes."
224
+ });
225
+ markPgliteQueryFailure(diagnostic, code);
226
+ return diagnostic;
227
+ }
228
+ function providerSqlState(error) {
229
+ const visited = /* @__PURE__ */ new Set();
230
+ let current = error;
231
+ for (let depth = 0; current && typeof current === "object" && depth < 8 && !visited.has(current); depth++) {
232
+ visited.add(current);
233
+ const code = ownDataValue(current, "code");
234
+ if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code))
235
+ return code;
236
+ current = ownDataValue(current, "cause");
237
+ }
238
+ return void 0;
239
+ }
240
+ function ownDataValue(value, key) {
241
+ try {
242
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
243
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
244
+ } catch {
245
+ return void 0;
246
+ }
247
+ }
248
+
249
+ // ../runtime/dist/adapters/database/pglite-role-client.js
250
+ var PGLITE_APPLICATION_ROLE = "gencow_runtime_application";
251
+ var PGLITE_MAINTENANCE_ROLE = "gencow_runtime_maintenance";
252
+ function createPgliteRoleClient(owner, role) {
253
+ const statement = role === PGLITE_APPLICATION_ROLE ? `set local role ${PGLITE_APPLICATION_ROLE}` : `set local role ${PGLITE_MAINTENANCE_ROLE}`;
254
+ function queryView(client) {
255
+ return (async (...args) => {
256
+ try {
257
+ return await client.query(...args);
258
+ } catch (error) {
259
+ throw pgliteQueryFailure(error);
260
+ }
261
+ });
262
+ }
263
+ const transaction = (callback) => owner.transaction(async (client) => {
264
+ await client.query(statement);
265
+ const query2 = queryView(client);
266
+ const view = new Proxy(client, {
267
+ get(target, property) {
268
+ if (property === "query")
269
+ return query2;
270
+ const value = Reflect.get(target, property, target);
271
+ return typeof value === "function" ? value.bind(target) : value;
272
+ }
273
+ });
274
+ return callback(view);
275
+ });
276
+ return Object.freeze({ query: queryView(owner), transaction });
277
+ }
278
+
279
+ // ../runtime/dist/adapters/database/pglite.js
280
+ var SYSTEM_RLS_CONTEXT = Object.freeze({
281
+ userId: "",
282
+ currentUserId: "",
283
+ role: "system",
284
+ internalSystem: "true"
285
+ });
286
+ function startupError(code, nextAction) {
287
+ return new RuntimeDatabaseRlsError(code, "startup", nextAction);
288
+ }
289
+ async function query(client, statement) {
290
+ return await client.query(statement);
291
+ }
292
+ async function createPgliteAdapter(client, release, binding, relations) {
293
+ try {
294
+ await bootstrapLocalPgliteRls((statement) => query(client, statement), {
295
+ excludedTableNames: ragManagedTableNames
296
+ });
297
+ } catch (error) {
298
+ if (error instanceof LocalPgliteRlsError)
299
+ throw startupError(error.code, error.nextAction);
300
+ throw error;
301
+ }
302
+ const applicationDatabase = drizzle({
303
+ client: createPgliteRoleClient(client, LOCAL_PGLITE_APPLICATION_ROLE),
304
+ ...relations ? { relations } : {}
305
+ });
306
+ const maintenanceDatabase = drizzle({
307
+ client: createPgliteRoleClient(client, LOCAL_PGLITE_MAINTENANCE_ROLE)
308
+ });
309
+ const authDatabase = createRlsDb(maintenanceDatabase, SYSTEM_RLS_CONTEXT);
310
+ const authView = Object.freeze({
311
+ drizzle: borrowRuntimeDrizzle(authDatabase)
312
+ });
313
+ let disposal;
314
+ let groundingCitationReader;
315
+ const managed = createManagedSchemaPreparation({
316
+ engine: "pglite",
317
+ client,
318
+ operationalRoles: [LOCAL_PGLITE_APPLICATION_ROLE, LOCAL_PGLITE_MAINTENANCE_ROLE]
319
+ }, authView.drizzle);
320
+ return {
321
+ administrationInspection: runtimeDatabaseInspection,
322
+ borrowSearchModes(options) {
323
+ const search = (scope, assertCurrent) => createSearchSessionReads(applicationDatabase, scope, assertCurrent);
324
+ return createPostgresSearchModes({
325
+ binding,
326
+ application: search,
327
+ // The common Search facade preserves Server's admitted application
328
+ // read permissions even for managed data. Direct RAG exports retain
329
+ // their separate fixed-system authority; it is not borrowed here.
330
+ ...options?.managed ? { managed: search } : {},
331
+ config: options?.config,
332
+ assertOpen() {
333
+ if (disposal)
334
+ throw new Error("Search resource ended");
335
+ }
336
+ });
337
+ },
338
+ borrowGroundingCitationReader() {
339
+ return groundingCitationReader ??= createPostgresGroundingCitationReader({
340
+ binding,
341
+ application: (scope, assertCurrent) => createSearchSessionReads(applicationDatabase, { ...scope, ownership: "managed" }, assertCurrent),
342
+ assertOpen() {
343
+ if (disposal)
344
+ throw new Error("Grounding resource ended");
345
+ }
346
+ });
347
+ },
348
+ createRequestContext(request) {
349
+ assertDatabaseGeneration(binding, request);
350
+ const ownerBinding = snapshotRuntimeBinding(request.binding);
351
+ const identity = snapshotRuntimeIdentity(request.identity);
352
+ const rls = snapshotRuntimeRls(request.rls);
353
+ const scopedApplicationDatabase = createRlsDb(applicationDatabase, rls);
354
+ const bindApplicationReads = (assertCurrent, assertLive, assertTransactionActive) => createRuntimeScopedApplicationReads(scopedApplicationDatabase, ownerBinding, identity, rls, assertCurrent, assertLive, assertTransactionActive);
355
+ return Object.freeze({
356
+ [runtimeGenerationBackedApplicationDatabase]: true,
357
+ [runtimeScopedApplicationReads]: bindApplicationReads,
358
+ db: borrowRuntimeDrizzle(scopedApplicationDatabase),
359
+ unsafeDb: borrowRuntimeDrizzle(createRlsDb(maintenanceDatabase, SYSTEM_RLS_CONTEXT))
360
+ });
361
+ },
362
+ createWorkflowContext(attempt) {
363
+ assertDatabaseGeneration(binding, attempt);
364
+ const ownerBinding = snapshotRuntimeBinding(attempt.binding);
365
+ const identity = snapshotRuntimeIdentity(attempt.identity);
366
+ const rls = snapshotRuntimeRls(attempt.rls);
367
+ const scopedApplicationDatabase = createRlsDb(applicationDatabase, rls);
368
+ const bindApplicationReads = (assertCurrent, assertLive) => createRuntimeScopedApplicationReads(scopedApplicationDatabase, ownerBinding, identity, rls, assertCurrent, assertLive);
369
+ return Object.freeze({
370
+ [runtimeScopedApplicationReads]: bindApplicationReads,
371
+ db: borrowRuntimeDrizzle(scopedApplicationDatabase),
372
+ unsafeDb: borrowRuntimeDrizzle(createRlsDb(maintenanceDatabase, SYSTEM_RLS_CONTEXT))
373
+ });
374
+ },
375
+ borrowAuthDatabase() {
376
+ return authView;
377
+ },
378
+ managedSchema: managed.preparation,
379
+ prepareWorkflowDatabase: () => managed.preparation.prepare("workflow"),
380
+ dispose() {
381
+ if (disposal)
382
+ return disposal;
383
+ return disposal = (async () => {
384
+ await managed.close();
385
+ await release();
386
+ })();
387
+ }
388
+ };
389
+ }
390
+ async function createPgliteDatabase(input) {
391
+ const binding = snapshotRuntimeBinding(input.binding);
392
+ const components = captureManagedSchemaComponents(input.managedComponents);
393
+ const extensions = await loadPgliteManagedExtensions(components, input.search);
394
+ if (!input.dataDir) {
395
+ throw startupError("RUNTIME_DATABASE_RLS_BOOTSTRAP_FAILED", "Configure a project-local PGlite data directory, then restart.");
396
+ }
397
+ let client;
398
+ let directoryLock;
399
+ try {
400
+ directoryLock = await acquirePgliteDirectoryLock(input.dataDir);
401
+ const activeClient = new PGlite({ dataDir: directoryLock.dataDir, extensions });
402
+ client = activeClient;
403
+ await observeRuntimeStartupStage("pgliteWaitReady", () => awaitPgliteReadiness(activeClient, "persistent"));
404
+ return await observeRuntimeStartupStage("pgliteAdapterBootstrap", () => createPgliteAdapter(activeClient, () => closePgliteDirectoryOwner(() => activeClient.close(), () => directoryLock.release()), binding, input.relations));
405
+ } catch (error) {
406
+ await closePgliteDirectoryOwner(async () => {
407
+ await client?.close();
408
+ }, async () => {
409
+ await directoryLock?.release();
410
+ }).catch(() => {
411
+ });
412
+ throw error;
413
+ }
414
+ }
415
+ async function createEphemeralPgliteDatabase(input) {
416
+ const binding = snapshotRuntimeBinding(input.binding);
417
+ const components = captureManagedSchemaComponents(input.managedComponents);
418
+ const client = new PGlite({ extensions: await loadPgliteManagedExtensions(components, input.search) });
419
+ try {
420
+ await observeRuntimeStartupStage("pgliteWaitReady", () => awaitPgliteReadiness(client, "ephemeral"));
421
+ await input.initialize?.(client);
422
+ return await observeRuntimeStartupStage("pgliteAdapterBootstrap", () => createPgliteAdapter(client, () => client.close(), binding, input.relations));
423
+ } catch (error) {
424
+ await client.close().catch(() => {
425
+ });
426
+ throw error;
427
+ }
428
+ }
429
+ export {
430
+ createEphemeralPgliteDatabase,
431
+ createPgliteDatabase
432
+ };
@@ -0,0 +1,146 @@
1
+ import {
2
+ isServerCompatibleLocalStartup
3
+ } from "./chunk-I3GWR43K.mjs";
4
+ import {
5
+ RuntimeDatabaseRlsError
6
+ } from "./chunk-AEBW7XZJ.mjs";
7
+
8
+ // ../runtime/dist/adapters/database/pglite-directory-lock.js
9
+ import { unlinkSync } from "node:fs";
10
+ import { randomUUID } from "node:crypto";
11
+ import { mkdir as mkdir2, realpath, rm as rm2, writeFile } from "node:fs/promises";
12
+ import { resolve } from "node:path";
13
+
14
+ // ../runtime/dist/adapters/database/pglite-lock-epoch.js
15
+ import { createHash } from "node:crypto";
16
+ import { lstat, mkdir, readFile, rm, rmdir } from "node:fs/promises";
17
+ import { join } from "node:path";
18
+ async function readPgliteLockEpoch(lockPath) {
19
+ const before = await lstat(lockPath, { bigint: true });
20
+ if (!before.isDirectory() || before.isSymbolicLink())
21
+ throw new Error("Invalid lock directory");
22
+ const record = await readFile(join(lockPath, "owner.json"), "utf8");
23
+ const owner = JSON.parse(record);
24
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0)
25
+ throw new Error("Invalid lock owner");
26
+ const after = await lstat(lockPath, { bigint: true });
27
+ const identity = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs || stat.ctimeNs}`;
28
+ if (identity(before) !== identity(after))
29
+ throw new Error("Lock epoch changed");
30
+ return {
31
+ pid: owner.pid,
32
+ key: createHash("sha256").update(`${identity(after)}:${record}`).digest("hex")
33
+ };
34
+ }
35
+ function isPgliteOwnerDead(pid) {
36
+ try {
37
+ process.kill(pid, 0);
38
+ return false;
39
+ } catch (error) {
40
+ return error.code === "ESRCH";
41
+ }
42
+ }
43
+ async function retirePgliteLockEpoch(lockPath, epoch, stale) {
44
+ const transition = `${lockPath}.transition-${epoch.key}`;
45
+ await mkdir(transition);
46
+ try {
47
+ let current;
48
+ try {
49
+ current = await readPgliteLockEpoch(lockPath);
50
+ } catch (error) {
51
+ if (error.code === "ENOENT" && !stale)
52
+ return;
53
+ throw error;
54
+ }
55
+ if (current.key !== epoch.key) {
56
+ if (stale)
57
+ throw new Error("Stale epoch was replaced");
58
+ return;
59
+ }
60
+ if (stale && !isPgliteOwnerDead(current.pid))
61
+ throw new Error("Owner is not proven dead");
62
+ await rm(lockPath, { recursive: true, force: false });
63
+ } finally {
64
+ await rmdir(transition);
65
+ }
66
+ }
67
+
68
+ // ../runtime/dist/adapters/database/pglite-directory-lock.js
69
+ var LOCK_SUFFIX = ".gencow-runtime.lock";
70
+ function lockError(code, action) {
71
+ return new RuntimeDatabaseRlsError(code, "startup", action, "none", randomUUID());
72
+ }
73
+ function directoryInUseError() {
74
+ return lockError("RUNTIME_DATABASE_DIRECTORY_IN_USE", "Stop competing local Runtime/migration processes before running pnpm gencow dev --local. If interrupted ownership cannot be verified, preserve this directory and restore a verified backup into a fresh configured local database directory; do not edit lock records.");
75
+ }
76
+ async function acquirePgliteDirectoryLock(dataDir) {
77
+ let canonicalDir;
78
+ try {
79
+ const absoluteDir = resolve(dataDir);
80
+ await mkdir2(absoluteDir, { recursive: true });
81
+ canonicalDir = await realpath(absoluteDir);
82
+ } catch {
83
+ throw lockError("RUNTIME_DATABASE_RLS_BOOTSTRAP_FAILED", "Prepare a writable project-local PGlite database directory, then restart.");
84
+ }
85
+ if (isServerCompatibleLocalStartup()) {
86
+ try {
87
+ unlinkSync(resolve(canonicalDir, "postmaster.pid"));
88
+ } catch {
89
+ }
90
+ return { dataDir: canonicalDir, release: async () => {
91
+ } };
92
+ }
93
+ const lockPath = `${canonicalDir}${LOCK_SUFFIX}`;
94
+ try {
95
+ await mkdir2(lockPath);
96
+ } catch (error) {
97
+ if (error.code !== "EEXIST") {
98
+ throw lockError("RUNTIME_DATABASE_RLS_BOOTSTRAP_FAILED", "Prepare a writable project-local PGlite database directory, then restart.");
99
+ }
100
+ try {
101
+ const epoch2 = await readPgliteLockEpoch(lockPath);
102
+ if (!isPgliteOwnerDead(epoch2.pid))
103
+ throw directoryInUseError();
104
+ await retirePgliteLockEpoch(lockPath, epoch2, true);
105
+ await mkdir2(lockPath);
106
+ } catch {
107
+ throw directoryInUseError();
108
+ }
109
+ }
110
+ let epoch;
111
+ try {
112
+ await writeFile(resolve(lockPath, "owner.json"), JSON.stringify({ pid: process.pid, ownerId: randomUUID() }), { flag: "wx" });
113
+ epoch = await readPgliteLockEpoch(lockPath);
114
+ } catch {
115
+ await rm2(lockPath, { recursive: true, force: true }).catch(() => {
116
+ });
117
+ throw lockError("RUNTIME_DATABASE_RLS_BOOTSTRAP_FAILED", "Prepare a writable project-local PGlite database directory, then restart.");
118
+ }
119
+ let released = false;
120
+ let attempt;
121
+ return {
122
+ dataDir: canonicalDir,
123
+ release() {
124
+ if (released)
125
+ return Promise.resolve();
126
+ if (attempt)
127
+ return attempt;
128
+ const current = retirePgliteLockEpoch(lockPath, epoch, false).then(() => {
129
+ released = true;
130
+ }, () => {
131
+ throw directoryInUseError();
132
+ });
133
+ attempt = current;
134
+ void current.then(() => {
135
+ }, () => {
136
+ if (attempt === current)
137
+ attempt = void 0;
138
+ });
139
+ return current;
140
+ }
141
+ };
142
+ }
143
+
144
+ export {
145
+ acquirePgliteDirectoryLock
146
+ };