openadminjs 0.2.0 → 0.3.0-rc.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 (219) hide show
  1. package/README.md +106 -151
  2. package/dist/adapt-package-manager.js +4 -1
  3. package/dist/create-project.d.ts +46 -0
  4. package/dist/create-project.js +417 -150
  5. package/dist/doctor.d.ts +13 -0
  6. package/dist/doctor.js +35 -6
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.js +257 -39
  9. package/dist/render-schema.d.ts +0 -17
  10. package/dist/render-schema.js +25 -29
  11. package/dist/resource-slug.d.ts +1 -0
  12. package/dist/resource-slug.js +7 -0
  13. package/dist/runtime-mode.d.ts +16 -0
  14. package/dist/runtime-mode.js +138 -0
  15. package/dist/upgrade.d.ts +10 -0
  16. package/dist/upgrade.js +133 -0
  17. package/package.json +14 -11
  18. package/template/.dockerignore +15 -0
  19. package/template/.env.production.example +5 -0
  20. package/template/Dockerfile +12 -0
  21. package/template/README.md +4 -3
  22. package/template/apps/admin/app/api/auth/login/route.ts +9 -9
  23. package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
  24. package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
  25. package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
  26. package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
  27. package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
  28. package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
  29. package/template/apps/admin/app/api-tokens/page.tsx +39 -39
  30. package/template/apps/admin/app/assistant/page.tsx +11 -0
  31. package/template/apps/admin/app/dashboard/page.tsx +45 -462
  32. package/template/apps/admin/app/globals.css +52 -16
  33. package/template/apps/admin/app/layout.tsx +1 -1
  34. package/template/apps/admin/app/login/page.tsx +13 -145
  35. package/template/apps/admin/app/plugins/page.tsx +16 -402
  36. package/template/apps/admin/app/profile/page.tsx +5 -2
  37. package/template/apps/admin/app/settings/page.tsx +14 -265
  38. package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
  39. package/template/apps/admin/components/app-shell.tsx +25 -373
  40. package/template/apps/admin/components/auth-guard.tsx +8 -28
  41. package/template/apps/admin/components/logo.tsx +1 -30
  42. package/template/apps/admin/components/resource-form.tsx +3 -3
  43. package/template/apps/admin/components/resource-table.tsx +12 -8
  44. package/template/apps/admin/lib/api.ts +45 -107
  45. package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
  46. package/template/apps/admin/lib/server-api.ts +7 -0
  47. package/template/apps/admin/lib/tokens.ts +9 -81
  48. package/template/apps/admin/middleware.ts +9 -50
  49. package/template/apps/admin/next.config.mjs +4 -0
  50. package/template/apps/admin/package.json +2 -1
  51. package/template/apps/admin/public/brand/favicon.svg +4 -1
  52. package/template/apps/admin/tailwind.config.ts +9 -8
  53. package/template/apps/api/package.json +10 -6
  54. package/template/apps/api/src/access/catalog.ts +4 -0
  55. package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
  56. package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
  57. package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
  58. package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
  59. package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
  60. package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
  61. package/template/apps/api/src/admin/admin.controller.ts +17 -4
  62. package/template/apps/api/src/admin/admin.module.ts +2 -2
  63. package/template/apps/api/src/admin/resource-policy.ts +1 -0
  64. package/template/apps/api/src/admin/resource-query.ts +1 -0
  65. package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
  66. package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
  67. package/template/apps/api/src/auth/auth.controller.ts +4 -2
  68. package/template/apps/api/src/auth/auth.service.ts +68 -83
  69. package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
  70. package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
  71. package/template/apps/api/src/common/api-exception.filter.ts +1 -0
  72. package/template/apps/api/src/common/auth.guard.ts +66 -39
  73. package/template/apps/api/src/common/json-field-codec.ts +12 -13
  74. package/template/apps/api/src/common/prisma.service.ts +9 -17
  75. package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
  76. package/template/apps/api/src/graphql/graphql.module.ts +5 -4
  77. package/template/apps/api/src/health/health.controller.ts +6 -0
  78. package/template/apps/api/src/main.ts +11 -2
  79. package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
  80. package/template/apps/api/src/resources/commerce.resource.ts +3 -34
  81. package/template/apps/api/src/resources/operations.resource.ts +1 -0
  82. package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
  83. package/template/apps/api/src/store/payment/payment.module.ts +2 -3
  84. package/template/apps/api/src/store/payment/payment.service.ts +121 -227
  85. package/template/apps/api/webpack.config.cjs +2 -1
  86. package/template/apps/web/next.config.mjs +4 -0
  87. package/template/apps/web/public/brand/favicon.svg +4 -1
  88. package/template/compose.yaml +56 -0
  89. package/template/examples/crm-admin/README.md +31 -0
  90. package/template/examples/crm-admin/package.json +17 -0
  91. package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
  92. package/template/examples/crm-admin/src/index.ts +7 -0
  93. package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
  94. package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
  95. package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
  96. package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
  97. package/template/examples/crm-admin/tsconfig.json +7 -0
  98. package/template/package.json +6 -1
  99. package/template/packages/admin-client/package.json +18 -0
  100. package/template/packages/admin-client/src/contracts.ts +29 -0
  101. package/template/packages/admin-client/src/index.ts +2 -0
  102. package/template/packages/admin-client/src/preferences.ts +57 -0
  103. package/template/packages/admin-client/tsconfig.json +12 -0
  104. package/template/packages/auth/package.json +1 -1
  105. package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
  106. package/template/packages/brand/src/generate-assets.mjs +17 -186
  107. package/template/packages/core/package.json +1 -1
  108. package/template/packages/mail/package.json +1 -1
  109. package/template/packages/nest/package.json +22 -0
  110. package/template/packages/nest/src/api-exception.filter.ts +23 -0
  111. package/template/packages/nest/src/index.ts +3 -0
  112. package/template/packages/nest/src/resource-policy.ts +64 -0
  113. package/template/packages/nest/src/resource-query.ts +103 -0
  114. package/template/packages/nest/tsconfig.json +12 -0
  115. package/template/packages/notifications/package.json +1 -1
  116. package/template/packages/payments/package.json +1 -1
  117. package/template/packages/permissions/package.json +1 -1
  118. package/template/packages/permissions/src/index.ts +2 -2
  119. package/template/packages/plugin-sdk/package.json +1 -1
  120. package/template/packages/plugin-sdk/src/index.ts +2 -2
  121. package/template/packages/prisma/package.json +21 -0
  122. package/template/packages/prisma/schema/ai.prisma +36 -0
  123. package/template/packages/prisma/schema/audit.prisma +13 -0
  124. package/template/packages/prisma/schema/commerce.prisma +79 -0
  125. package/template/packages/prisma/schema/content.prisma +27 -0
  126. package/template/packages/prisma/schema/core.prisma +106 -0
  127. package/template/packages/prisma/schema/header.prisma +8 -0
  128. package/template/packages/prisma/schema/jobs.prisma +9 -0
  129. package/template/packages/prisma/schema/media.prisma +9 -0
  130. package/template/packages/prisma/schema/modules.json +47 -0
  131. package/template/packages/prisma/schema/notifications.prisma +9 -0
  132. package/template/packages/prisma/schema/settings.prisma +8 -0
  133. package/template/packages/prisma/schema/tokens.prisma +10 -0
  134. package/template/packages/prisma/src/index.d.ts +12 -0
  135. package/template/packages/prisma/src/index.mjs +138 -0
  136. package/template/packages/queue/package.json +1 -1
  137. package/template/packages/resource/package.json +1 -1
  138. package/template/packages/resource/src/index.ts +1 -0
  139. package/template/packages/storage/package.json +1 -1
  140. package/template/packages/storage/src/index.ts +37 -0
  141. package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
  142. package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
  143. package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
  144. package/template/prisma/schema.prisma +82 -54
  145. package/template/prisma/seed.ts +14 -38
  146. package/template/runtime-versions.json +15 -0
  147. package/template/scripts/db-init.mjs +33 -0
  148. package/template/scripts/install-crm.mjs +50 -0
  149. package/template/scripts/migrate-existing.mjs +65 -0
  150. package/template/scripts/schema.mjs +48 -0
  151. package/template/tsconfig.base.json +23 -5
  152. package/LICENSE +0 -21
  153. package/dist/adapt-package-manager.test.d.ts +0 -1
  154. package/dist/adapt-package-manager.test.js +0 -76
  155. package/dist/cli.e2e.test.d.ts +0 -1
  156. package/dist/cli.e2e.test.js +0 -87
  157. package/dist/create-project.test.d.ts +0 -1
  158. package/dist/create-project.test.js +0 -275
  159. package/dist/database-providers.integration.test.d.ts +0 -1
  160. package/dist/database-providers.integration.test.js +0 -64
  161. package/dist/db-commands.test.d.ts +0 -1
  162. package/dist/db-commands.test.js +0 -27
  163. package/dist/doctor.test.d.ts +0 -1
  164. package/dist/doctor.test.js +0 -102
  165. package/dist/index.test.d.ts +0 -1
  166. package/dist/index.test.js +0 -11
  167. package/dist/render-schema.test.d.ts +0 -1
  168. package/dist/render-schema.test.js +0 -57
  169. package/dist/resource-slug.test.d.ts +0 -1
  170. package/dist/resource-slug.test.js +0 -9
  171. package/dist/secrets.test.d.ts +0 -1
  172. package/dist/secrets.test.js +0 -36
  173. package/dist/security.test.d.ts +0 -1
  174. package/dist/security.test.js +0 -54
  175. package/dist/validate-name.test.d.ts +0 -1
  176. package/dist/validate-name.test.js +0 -63
  177. package/template/apps/admin/.storybook/main.ts +0 -12
  178. package/template/apps/admin/.storybook/preview.ts +0 -10
  179. package/template/apps/admin/app/login/page.test.tsx +0 -18
  180. package/template/apps/admin/components/auth-guard.test.tsx +0 -55
  181. package/template/apps/admin/components/logo.stories.tsx +0 -24
  182. package/template/apps/admin/lib/api.test.ts +0 -118
  183. package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
  184. package/template/apps/admin/vitest.config.ts +0 -7
  185. package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
  186. package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
  187. package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
  188. package/template/apps/api/src/app.module.test.ts +0 -12
  189. package/template/apps/api/src/auth/auth.service.test.ts +0 -78
  190. package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
  191. package/template/apps/api/src/common/auth.guard.test.ts +0 -62
  192. package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
  193. package/template/apps/api/src/common/json-field-codec.test.ts +0 -76
  194. package/template/apps/api/src/common/prisma.service.test.ts +0 -19
  195. package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
  196. package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
  197. package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
  198. package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +0 -26
  199. package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
  200. package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
  201. package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
  202. package/template/apps/api/src/queue/queue.service.test.ts +0 -33
  203. package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
  204. package/template/apps/api/vitest.config.ts +0 -21
  205. package/template/apps/web/lib/seo.test.ts +0 -41
  206. package/template/apps/web/vitest.config.ts +0 -19
  207. package/template/packages/auth/src/index.test.ts +0 -10
  208. package/template/packages/brand/src/index.test.ts +0 -9
  209. package/template/packages/core/src/index.test.ts +0 -27
  210. package/template/packages/core/vitest.config.ts +0 -9
  211. package/template/packages/mail/src/index.test.ts +0 -23
  212. package/template/packages/notifications/src/index.test.ts +0 -9
  213. package/template/packages/permissions/src/blueprints.test.ts +0 -62
  214. package/template/packages/permissions/src/index.test.ts +0 -34
  215. package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
  216. package/template/packages/plugin-sdk/vitest.config.ts +0 -5
  217. package/template/packages/queue/src/index.test.ts +0 -12
  218. package/template/packages/resource/src/index.test.ts +0 -196
  219. package/template/packages/storage/src/index.test.ts +0 -10
@@ -0,0 +1,33 @@
1
+ import {readFileSync,existsSync,readdirSync} from "node:fs";
2
+ import {join,resolve} from "node:path";
3
+ import {spawnSync} from "node:child_process";
4
+ import {createRequire} from "node:module";
5
+ const root=process.cwd();
6
+ const {schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
7
+ const schema=join(root,"prisma/schema.prisma"),provider=schemaProvider(readFileSync(schema,"utf8"));
8
+ const history=join(root,"prisma/migrations");
9
+ const hasHistory=existsSync(history)&&readdirSync(history,{withFileTypes:true}).some(e=>e.isDirectory());
10
+ const cli=resolve("node_modules/prisma/build/index.js");
11
+ if(!existsSync(cli))throw Error("Install dependencies first");
12
+ if(!process.env.DATABASE_URL){
13
+ const envFile=[join(root,".env"),join(root,"apps/api/.env")].find(existsSync);
14
+ if(envFile){
15
+ const dotenv=createRequire(join(root,"apps/api/package.json"))("dotenv");
16
+ dotenv.config({path:envFile});
17
+ }
18
+ }
19
+ if(!process.env.DATABASE_URL)throw Error("Set DATABASE_URL for this project");
20
+ const url=process.env.DATABASE_URL;
21
+ if(provider==="sqlite"?!url.startsWith("file:"):provider==="mysql"?!url.startsWith("mysql:"):!/^postgres(?:ql)?:/.test(url))throw Error("Database URL and schema provider mismatch");
22
+ if(provider==="postgresql"&&!hasHistory)throw Error("PostgreSQL requires reviewed migration history");
23
+ if(!hasHistory&&process.env.NODE_ENV==="production")throw Error("Production requires reviewed migration history; schema push is disabled");
24
+ if(hasHistory){
25
+ const lock=readFileSync(join(history,"migration_lock.toml"),"utf8");
26
+ if(!lock.includes('provider = "'+provider+'"'))throw Error("Migration provider mismatch");
27
+ }
28
+ const run=args=>{
29
+ const result=spawnSync(process.execPath,[cli,...args,"--schema",schema],{stdio:"inherit"});
30
+ if(result.error||result.status!==0)process.exit(result.status??1);
31
+ };
32
+ run(hasHistory?["migrate","deploy"]:["db","push","--skip-generate"]);
33
+ run(["generate"]);
@@ -0,0 +1,50 @@
1
+ import {readFileSync,writeFileSync,existsSync,mkdirSync,rmSync,readdirSync} from "node:fs";
2
+ import {resolve,join} from "node:path";
3
+ import {fileURLToPath} from "node:url";
4
+ import {createHash} from "node:crypto";
5
+ const root=process.cwd();
6
+ const example=fileURLToPath(new URL("../examples/crm-admin/",import.meta.url));
7
+ const schemaPath=join(root,"prisma/schema.prisma");
8
+ const registryPath=join(root,"apps/api/src/resources/registry.ts");
9
+ const args=process.argv.slice(2);
10
+ if(args.length!==1||!["--dry-run","--apply"].includes(args[0]))throw Error("Usage: node scripts/install-crm.mjs --dry-run|--apply");
11
+ const schema=readFileSync(schemaPath,"utf8"),registry=readFileSync(registryPath,"utf8");
12
+ const names=["companies","contacts","deals","activities"];
13
+ const fragment=readFileSync(join(example,"prisma/models.fragment.prisma"),"utf8");
14
+ for(const name of ["Contact","Company","Deal","Activity"])if(new RegExp("\\bmodel\\s+"+name+"\\s*\\{").test(schema))throw Error("Existing model: "+name);
15
+ const resourceDir=join(root,"apps/api/src/resources/crm");
16
+ if(existsSync(resourceDir))throw Error("CRM directory already exists");
17
+ const marker="export const resources = [";
18
+ if(registry.split(marker).length!==2)throw Error("Registry changed; merge the example manually");
19
+ for(const name of names)if(registry.includes("crm/"+name+".resource"))throw Error("Already registered");
20
+ const source=names.map(name=>[name,readFileSync(join(example,"src/resources/"+name+".resource.ts"),"utf8")]);
21
+ const imports=names.map(name=>"import crm_"+name+" from \"./crm/"+name+".resource\";").join("\n");
22
+ const nextRegistry=imports+"\n"+registry.replace(marker,marker+"\n "+names.map(n=>"crm_"+n).join(",\n ")+",");
23
+ console.log("Plan: add a CRM schema module, add 4 resource modules, register 4 resources. No database commands.");
24
+ if(args[0]==="--dry-run")process.exit(0);
25
+ const moduleDir=join(root,"prisma/modules"),manifestPath=join(moduleDir,"manifest.json"),moduleFile=join(moduleDir,"crm.prisma");
26
+ const originalManifest=existsSync(manifestPath)?readFileSync(manifestPath,"utf8"):undefined;
27
+ const manifest=originalManifest?JSON.parse(originalManifest):null;
28
+ const sha=s=>createHash("sha256").update(s).digest("hex");
29
+ if(existsSync(moduleFile))throw Error("CRM schema module already exists");
30
+ const {composeSchema,schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
31
+ const provider=schemaProvider(schema);
32
+ let nextSchema;
33
+ if(manifest){
34
+ if(manifest.lastSchemaHash!==sha(schema))throw Error("Adopted schema has drift; reconcile first");
35
+ nextSchema=schema+"\n"+fragment+"\n";
36
+ }else{
37
+ const custom=existsSync(moduleDir)?readdirSync(moduleDir).filter(n=>n.endsWith(".prisma")).sort().map(n=>[n,readFileSync(join(moduleDir,n),"utf8")]):[];
38
+ if(composeSchema({provider,customFragments:custom.map(x=>x[1])})!==schema)throw Error("Schema has local edits; run schema adopt before installing CRM");
39
+ nextSchema=composeSchema({provider,customFragments:[...custom,["crm.prisma",fragment]].sort((a,b)=>a[0].localeCompare(b[0])).map(x=>x[1])});
40
+ }
41
+ try{
42
+ mkdirSync(resourceDir);
43
+ for(const [name,body] of source)writeFileSync(join(resourceDir,name+".resource.ts"),body,{flag:"wx"});
44
+ mkdirSync(moduleDir,{recursive:true});
45
+ writeFileSync(moduleFile,manifest?"\n"+fragment+"\n":fragment,{flag:"wx"});
46
+ writeFileSync(schemaPath,nextSchema);
47
+ if(manifest){manifest.files.push("crm.prisma");manifest.lastSchemaHash=sha(nextSchema);writeFileSync(manifestPath,JSON.stringify(manifest,null,2)+"\n");}
48
+ writeFileSync(registryPath,nextRegistry);
49
+ }catch(error){rmSync(moduleFile,{force:true});if(originalManifest)writeFileSync(manifestPath,originalManifest);writeFileSync(schemaPath,schema);writeFileSync(registryPath,registry);rmSync(resourceDir,{recursive:true,force:true});throw error;}
50
+ console.log("CRM installed. Review schema, create a migration and seed permissions before starting.");
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Plan a same-provider upgrade of a V1 project. Does not apply SQL, mark
3
+ * migrations as applied, change source files, or write credentials.
4
+ */
5
+ import {readFileSync,writeFileSync,mkdirSync,existsSync,readdirSync} from "node:fs";
6
+ import {resolve,join} from "node:path";
7
+ import {spawnSync} from "node:child_process";
8
+ import {createHash} from "node:crypto";
9
+ const {mergeLegacySchema,providers,schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
10
+ const args=process.argv.slice(2);
11
+ if(args.length!==2||args[0]!=="--out")throw Error("Usage: node scripts/migrate-existing.mjs --out <new-directory> (DATABASE_URL must point to a staging copy)");
12
+ const root=process.cwd(),source=join(root,"prisma/schema.prisma"),out=resolve(args[1]);
13
+ if(existsSync(out))throw Error("Output directory already exists");
14
+ if(!process.env.DATABASE_URL)throw Error("Set DATABASE_URL explicitly to an isolated staging database");
15
+ const original=readFileSync(source,"utf8"),provider=schemaProvider(original);
16
+ if(!providers.includes(provider))throw Error("Unsupported provider");
17
+ const url=process.env.DATABASE_URL;
18
+ if(provider==="sqlite"?!url.startsWith("file:"):provider==="mysql"?!url.startsWith("mysql:"):!/^postgres(?:ql)?:/.test(url))throw Error("DATABASE_URL provider mismatch");
19
+ const plan=mergeLegacySchema(original,provider);
20
+ const prisma=join(root,"node_modules/prisma/build/index.js");
21
+ if(!existsSync(prisma))throw Error("Install this project's Prisma 6 CLI first");
22
+ function run(args,allowed=[0]){
23
+ const r=spawnSync(process.execPath,[prisma,...args],{cwd:root,env:process.env,encoding:"utf8",maxBuffer:20*1024*1024});
24
+ if(!allowed.includes(r.status))throw Error("Prisma command failed: "+args[0]+" "+args[1]+" (exit "+r.status+"). Validate schema/connection in staging.");
25
+ return {status:r.status,stdout:r.stdout||""};
26
+ }
27
+ // Refuse a plan based on a stale datamodel. Never introspect and overwrite source.
28
+ const drift=run(["migrate","diff","--from-schema-datasource",source,"--to-schema-datamodel",source,"--exit-code"],[0,2]);
29
+ if(drift.status===2)throw Error("Live staging database differs from the supplied source schema; reconcile drift before planning");
30
+ mkdirSync(out,{recursive:false,mode:0o700});
31
+ const write=(name,value)=>writeFileSync(join(out,name),value,{flag:"wx",mode:0o600});
32
+ const target=join(out,"target.prisma");
33
+ write("target.prisma",plan.schema);
34
+ write("source.prisma",original);
35
+ run(["validate","--schema",target]);
36
+ const sql=run(["migrate","diff","--from-schema-datamodel",source,"--to-schema-datamodel",target,"--script"]).stdout;
37
+ const quote=name=>provider==="mysql"?"\x60"+name+"\x60":'"'+name+'"';
38
+ const cleanup=[];
39
+ if(provider==="sqlite")for(const {table,field} of plan.normalizations){const t=quote(table),f=quote(field);cleanup.push("UPDATE "+t+" SET "+f+" = json_quote("+f+") WHERE "+f+" IS NOT NULL AND NOT json_valid("+f+");");}
40
+ if(plan.clearLegacyRefresh&&/\brefreshTokenHash\s+String\?/.test(original))cleanup.push("UPDATE "+quote("User")+" SET "+quote("refreshTokenHash")+" = NULL;");
41
+ if(plan.revokeLegacyKeys&&/^model ApiToken\s*\{/m.test(original))cleanup.push("UPDATE "+quote("ApiToken")+" SET "+quote("revokedAt")+" = CURRENT_TIMESTAMP WHERE "+quote("revokedAt")+" IS NULL;");
42
+ const upgrade=(cleanup.length?"-- Preserve legacy JSON semantics and invalidate obsolete credentials.\n"+cleanup.join("\n")+"\n\n":"")+sql;
43
+ write("upgrade.sql",upgrade);
44
+ const history=join(root,"prisma/migrations");
45
+ const hasHistory=existsSync(history)&&readdirSync(history,{withFileTypes:true}).some(e=>e.isDirectory());
46
+ if(!hasHistory){
47
+ const baseline=run(["migrate","diff","--from-empty","--to-schema-datamodel",source,"--script"]).stdout;
48
+ write("baseline.sql",baseline);
49
+ write("migration_lock.toml",'provider = "'+provider+'"\n');
50
+ }
51
+ const flags=upgrade.split("\n").filter(l=>/\bDROP\b|\bTRUNCATE\b|\bDELETE\s+FROM\b|ALTER\s+COLUMN|MODIFY\s+COLUMN|NOT NULL/i.test(l)).map(l=>l.trim()).slice(0,100);
52
+ // These are file integrity checksums, not credential hashes. The files contain schema/DDL, not rows.
53
+ const fileChecksum=name=>createHash("sha256").update(readFileSync(join(out,name))).digest("hex");
54
+ write("plan.json",JSON.stringify({provider,sourceSha256:fileChecksum("source.prisma"),targetSha256:fileChecksum("target.prisma"),upgradeSha256:fileChecksum("upgrade.sql"),hasMigrationHistory:hasHistory,changes:plan.changes,reviewRequired:flags},null,2)+"\n");
55
+ write("README.md",[
56
+ "# Reviewed migration plan — never apply blindly",
57
+ "",
58
+ "Generated against a staging database whose schema matched the source datamodel. Source schema and database were not modified.",
59
+ "Back up the database and files; stop writers. Review target.prisma, upgrade.sql and plan.json, including all table rebuilds and constraints. Check row counts, foreign keys, JSON values and legacy credential revocation after applying to a disposable copy.",
60
+ hasHistory?"Existing migration history detected: do not create a duplicate baseline. For PostgreSQL projects with the original OpenAdminJS history, use the unchanged shipped migrations; do not apply this equivalent SQL on top. For customized histories, add reviewed SQL as a new migration only after checking the deployed migration history.":"No local migration history: confirm the database truly has no applied migration records. Copy baseline.sql into prisma/migrations/00000000000000_existing_baseline/migration.sql, copy migration_lock.toml, then mark that baseline applied with prisma migrate resolve --applied 00000000000000_existing_baseline --schema prisma/schema.prisma. Never execute baseline.sql against the existing database. Add upgrade.sql as a new timestamped migration.",
61
+ "Replace schema.prisma with reviewed target.prisma, then run prisma migrate deploy and prisma generate in staging; run schema adopt to split the updated project without losing custom models.",
62
+ "No automatic SQL application or rollback is provided. Restore the pre-migration database + application snapshot if staging fails. MySQL DDL is not generally transactional; SQLite table rebuilds require sufficient disk space.",
63
+ "For SQLite legacy JSON, valid JSON text stays JSON; invalid text is converted to a JSON string. Review malformed scope values separately; obsolete API keys are revoked.",
64
+ ].join("\n")+"\n");
65
+ console.log("Migration plan written to "+out+"; database unchanged. Review before applying.");
@@ -0,0 +1,48 @@
1
+ import {existsSync,readFileSync,writeFileSync,mkdirSync,readdirSync,lstatSync,renameSync} from "node:fs";
2
+ import {join,resolve} from "node:path";
3
+ import {createHash} from "node:crypto";
4
+ const {composeSchema,splitSchema,moduleNames,providers,schemaProvider}=await import("../packages/prisma/src/index.mjs").catch(()=>import("@openadminjs/prisma"));
5
+ const root=process.cwd(),schema=join(root,"prisma/schema.prisma"),dir=join(root,"prisma/modules"),manifest=join(dir,"manifest.json");
6
+ const [command,...args]=process.argv.slice(2);
7
+ const hash=text=>createHash("sha256").update(text).digest("hex");
8
+ const read=path=>readFileSync(path,"utf8");
9
+ function readLocal(path){if(lstatSync(path).isSymbolicLink())throw Error("Symbolic links not allowed in schema modules");return read(path);}
10
+ function providerOf(text){const p=schemaProvider(text);if(!providers.includes(p))throw Error("Unknown schema provider");return p;}
11
+ const current=read(schema);
12
+ if(command==="adopt"){
13
+ if(existsSync(dir))throw Error("prisma/modules already exists; refusing overwrite");
14
+ const chunks=splitSchema(current);
15
+ mkdirSync(dir,{recursive:false});
16
+ for(const chunk of chunks)writeFileSync(join(dir,chunk.name+".prisma"),chunk.content,{flag:"wx"});
17
+ writeFileSync(manifest,JSON.stringify({mode:"adopted",provider:providerOf(current),files:chunks.map(c=>c.name+".prisma"),lastSchemaHash:hash(current)},null,2)+"\n",{flag:"wx"});
18
+ console.log("Adopted existing schema losslessly. Database and migrations unchanged.");
19
+ }else if(command==="check"||command==="compose"){
20
+ let next,config;
21
+ if(existsSync(manifest)){
22
+ if(lstatSync(dir).isSymbolicLink())throw Error("Symlinked schema module directory");
23
+ config=JSON.parse(readLocal(manifest));
24
+ if(config.mode!=="adopted"||!Array.isArray(config.files)||new Set(config.files).size!==config.files.length)throw Error("Invalid adoption manifest");
25
+ for(const file of config.files)if(!/^[a-zA-Z0-9_-]+\.prisma$/.test(file))throw Error("Invalid module filename");
26
+ next=config.files.map(file=>readLocal(join(dir,file))).join("");
27
+ if(providerOf(next)!==config.provider)throw Error("Provider changes require a separate migration");
28
+ }else{
29
+ const custom=existsSync(dir)?readdirSync(dir).filter(x=>x.endsWith(".prisma")).sort().map(x=>readLocal(join(dir,x))):[];
30
+ next=composeSchema({provider:providerOf(current),customFragments:custom});
31
+ }
32
+ if(command==="check"){if(current!==next)throw Error("Schema drift: review modules and compose; do not edit generated schema directly");console.log("Schema matches modules");}
33
+ else{
34
+ if(!args.includes("--write")){process.stdout.write(next);process.exit(0);}
35
+ if(current===next){console.log("Schema already current");process.exit(0);}
36
+ if(config&&config.lastSchemaHash!==hash(current))throw Error("Generated schema changed since adoption; merge your edits first");
37
+ if(!config&&!args.includes("--replace-generated"))throw Error("Review output first; use --write --replace-generated only for a known generated schema, or adopt existing schema");
38
+ const backup=schema+".before-compose";
39
+ if(existsSync(backup))throw Error("Preserve or remove previous schema backup before composing again");
40
+ writeFileSync(backup,current,{flag:"wx"});
41
+ const temp=schema+".tmp";writeFileSync(temp,next,{flag:"wx"});renameSync(temp,schema);
42
+ if(config){config.lastSchemaHash=hash(next);writeFileSync(manifest,JSON.stringify(config,null,2)+"\n");}
43
+ console.log("Schema composed. Database unchanged; validate and create a reviewed migration.");
44
+ }
45
+ }else if(command==="profile"){
46
+ const provider=args[0],modules=args.slice(1);
47
+ process.stdout.write(composeSchema({provider,modules:modules.length?modules:moduleNames}));
48
+ }else throw Error("Usage: schema.mjs check | adopt | compose [--write] | profile <provider> [modules...]");
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "target": "ES2022",
4
- "lib": ["ES2022", "DOM", "DOM.Iterable"],
4
+ "lib": [
5
+ "ES2022",
6
+ "DOM",
7
+ "DOM.Iterable"
8
+ ],
5
9
  "module": "ESNext",
6
10
  "moduleResolution": "Bundler",
7
11
  "strict": true,
@@ -14,10 +18,24 @@
14
18
  "forceConsistentCasingInFileNames": true,
15
19
  "baseUrl": ".",
16
20
  "paths": {
17
- "@openadminjs/core": ["packages/core/src/index.ts"],
18
- "@openadminjs/resource": ["packages/resource/src/index.ts"],
19
- "@openadminjs/auth": ["packages/auth/src/index.ts"],
20
- "@openadminjs/permissions": ["packages/permissions/src/index.ts"]
21
+ "@openadminjs/core": [
22
+ "packages/core/src/index.ts"
23
+ ],
24
+ "@openadminjs/resource": [
25
+ "packages/resource/src/index.ts"
26
+ ],
27
+ "@openadminjs/auth": [
28
+ "packages/auth/src/index.ts"
29
+ ],
30
+ "@openadminjs/permissions": [
31
+ "packages/permissions/src/index.ts"
32
+ ],
33
+ "@openadminjs/nest": [
34
+ "packages/nest/src/index.ts"
35
+ ],
36
+ "@openadminjs/admin-client": [
37
+ "packages/admin-client/src/index.ts"
38
+ ]
21
39
  }
22
40
  }
23
41
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 OpenAdminJS contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1 +0,0 @@
1
- export {};
@@ -1,76 +0,0 @@
1
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { tmpdir } from "node:os";
4
- import { describe, expect, it } from "vitest";
5
- import { adaptProjectForPackageManager } from "./adapt-package-manager.js";
6
- import { createProject } from "./create-project.js";
7
- const BASE_OPTIONS = {
8
- database: "postgresql",
9
- superadminEmail: "admin@localhost.dev",
10
- superadminPassword: "password1234",
11
- databaseUrl: "postgresql://localhost:5432/my-app?schema=public",
12
- redisUrl: "redis://localhost:6379",
13
- jwtSecret: "test-jwt-secret",
14
- jwtRefreshSecret: "test-jwt-refresh-secret",
15
- adminOrigin: "http://localhost:3000",
16
- apiPort: "4000",
17
- git: false,
18
- install: false
19
- };
20
- describe("adaptProjectForPackageManager", () => {
21
- it("keeps pnpm layout unchanged", () => {
22
- const cwd = mkdtempSync(join(tmpdir(), "openadminjs-adapt-"));
23
- try {
24
- const result = createProject({ ...BASE_OPTIONS, packageManager: "pnpm", projectName: "pnpm-app", cwd });
25
- expect(existsSync(join(result.targetDir, "pnpm-workspace.yaml"))).toBe(true);
26
- const root = JSON.parse(readFileSync(join(result.targetDir, "package.json"), "utf8"));
27
- expect(root.packageManager).toContain("pnpm");
28
- }
29
- finally {
30
- rmSync(cwd, { recursive: true, force: true });
31
- }
32
- });
33
- it("adapts npm projects with workspaces and npm scripts", () => {
34
- const cwd = mkdtempSync(join(tmpdir(), "openadminjs-adapt-"));
35
- try {
36
- const result = createProject({ ...BASE_OPTIONS, packageManager: "npm", projectName: "npm-app", cwd });
37
- expect(existsSync(join(result.targetDir, "pnpm-workspace.yaml"))).toBe(false);
38
- const root = JSON.parse(readFileSync(join(result.targetDir, "package.json"), "utf8"));
39
- expect(root.workspaces).toEqual(["apps/*", "packages/*"]);
40
- expect(root.scripts?.["db:migrate"]).toContain("--workspace=@openadminjs/api");
41
- expect(root.overrides?.["@nestjs/common"]).toBeTruthy();
42
- expect(root.pnpm).toBeUndefined();
43
- const apiPkg = JSON.parse(readFileSync(join(result.targetDir, "apps", "api", "package.json"), "utf8"));
44
- expect(apiPkg.dependencies["@openadminjs/core"]).toBe("workspace:*");
45
- }
46
- finally {
47
- rmSync(cwd, { recursive: true, force: true });
48
- }
49
- });
50
- it("adapts yarn projects and replaces workspace protocol with *", () => {
51
- const cwd = mkdtempSync(join(tmpdir(), "openadminjs-adapt-"));
52
- try {
53
- const result = createProject({ ...BASE_OPTIONS, packageManager: "yarn", projectName: "yarn-app", cwd });
54
- expect(existsSync(join(result.targetDir, "pnpm-workspace.yaml"))).toBe(false);
55
- const root = JSON.parse(readFileSync(join(result.targetDir, "package.json"), "utf8"));
56
- expect(root.scripts?.dev).toContain("yarn workspace @openadminjs/api dev");
57
- const apiPkg = JSON.parse(readFileSync(join(result.targetDir, "apps", "api", "package.json"), "utf8"));
58
- expect(apiPkg.dependencies["@openadminjs/core"]).toBe("*");
59
- }
60
- finally {
61
- rmSync(cwd, { recursive: true, force: true });
62
- }
63
- });
64
- it("is a no-op for pnpm when called directly", () => {
65
- const dir = mkdtempSync(join(tmpdir(), "openadminjs-adapt-"));
66
- try {
67
- writeFileSync(join(dir, "package.json"), `${JSON.stringify({ name: "x", scripts: { dev: "pnpm dev" }, packageManager: "pnpm@9.15.0" }, null, 2)}\n`);
68
- writeFileSync(join(dir, "pnpm-workspace.yaml"), "packages:\n - apps/*\n");
69
- adaptProjectForPackageManager(dir, "pnpm");
70
- expect(existsSync(join(dir, "pnpm-workspace.yaml"))).toBe(true);
71
- }
72
- finally {
73
- rmSync(dir, { recursive: true, force: true });
74
- }
75
- });
76
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,87 +0,0 @@
1
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
- import { spawnSync } from "node:child_process";
3
- import { dirname, join } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { tmpdir } from "node:os";
6
- import { beforeAll, describe, expect, it } from "vitest";
7
- const here = dirname(fileURLToPath(import.meta.url));
8
- const cliRoot = join(here, "..");
9
- const distEntry = join(cliRoot, "dist", "index.js");
10
- const pkgVersion = JSON.parse(readFileSync(join(cliRoot, "package.json"), "utf8")).version;
11
- function run(args, cwd = cliRoot) {
12
- return spawnSync(process.execPath, [distEntry, ...args], { cwd, encoding: "utf8" });
13
- }
14
- beforeAll(() => {
15
- // Compile the CLI to dist via the TypeScript compiler entry (works in CI and sandbox).
16
- const tsc = join(cliRoot, "node_modules", "typescript", "bin", "tsc");
17
- const res = spawnSync(process.execPath, [tsc, "-p", "tsconfig.json"], { cwd: cliRoot, encoding: "utf8" });
18
- if (res.status !== 0)
19
- throw new Error(`tsc build failed: ${res.stderr || res.stdout}`);
20
- if (!existsSync(distEntry))
21
- throw new Error("dist/index.js not produced");
22
- }, 60000);
23
- describe("openadminjs CLI e2e", () => {
24
- it("--version prints the package version and exits 0", () => {
25
- const r = run(["--version"]);
26
- expect(r.status).toBe(0);
27
- expect(r.stdout).toContain(`openadminjs ${pkgVersion}`);
28
- });
29
- it("-v behaves like --version", () => {
30
- const r = run(["-v"]);
31
- expect(r.status).toBe(0);
32
- expect(r.stdout).toContain(`openadminjs ${pkgVersion}`);
33
- });
34
- it("--help exits 0 and lists commands", () => {
35
- const r = run(["--help"]);
36
- expect(r.status).toBe(0);
37
- expect(r.stdout).toMatch(/create/);
38
- expect(r.stdout).toMatch(/generate/);
39
- expect(r.stdout).toMatch(/doctor/);
40
- });
41
- it("unknown command errors and exits non-zero", () => {
42
- const r = run(["definitely-not-a-command"]);
43
- expect(r.status).not.toBe(0);
44
- expect(r.stderr).toMatch(/Unknown command/);
45
- expect(r.stderr).toMatch(/--help/);
46
- });
47
- it("db migrate --dry-run prints the command without running it", () => {
48
- const r = run(["db", "migrate", "dev", "--dry-run"]);
49
- expect(r.status).toBe(0);
50
- expect(r.stdout).toMatch(/db:migrate/);
51
- });
52
- it("generate field is routed to its own handler (not the generic generate)", () => {
53
- const proj = mkdtempSync(join(tmpdir(), "oaj-e2e-"));
54
- try {
55
- const resDir = join(proj, "apps", "api", "src", "resources");
56
- mkdirSync(resDir, { recursive: true });
57
- writeFileSync(join(resDir, "post.resource.ts"), `import { defineResource } from '@openadminjs/core';\n\nexport default defineResource({\n name: 'posts',\n model: 'Post',\n fields: {\n id: { type: 'id', label: 'ID' },\n },\n permissions: {},\n});\n`);
58
- const r = run(["generate", "field", "post", "title", "--type", "text", "--required"], proj);
59
- expect(r.status).toBe(0);
60
- const updated = readFileSync(join(resDir, "post.resource.ts"), "utf8");
61
- expect(updated).toContain("title:");
62
- expect(updated).toContain("required: true");
63
- }
64
- finally {
65
- rmSync(proj, { recursive: true, force: true });
66
- }
67
- });
68
- it("generate resource creates a resource file and rejects unsafe names", () => {
69
- const proj = mkdtempSync(join(tmpdir(), "oaj-e2e-"));
70
- try {
71
- const ok = run(["generate", "resource", "BlogPost"], proj);
72
- expect(ok.status).toBe(0);
73
- expect(existsSync(join(proj, "apps", "api", "src", "resources", "blog-post.resource.ts"))).toBe(true);
74
- const bad = run(["generate", "resource", "../evil"], proj);
75
- expect(bad.status).not.toBe(0);
76
- expect(existsSync(join(proj, "..", "evil.resource.ts"))).toBe(false);
77
- }
78
- finally {
79
- rmSync(proj, { recursive: true, force: true });
80
- }
81
- });
82
- it("generate with unknown kind errors", () => {
83
- const r = run(["generate", "bogus", "x"]);
84
- expect(r.status).not.toBe(0);
85
- expect(r.stderr).toMatch(/Unknown generate kind/);
86
- });
87
- });
@@ -1 +0,0 @@
1
- export {};