create-erxes 0.0.0-stage → 0.1.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 (69) hide show
  1. package/README.md +23 -2
  2. package/dist/index.js +481 -0
  3. package/dist/templates/base/.agents/skills/endpoint/SKILL.md +21 -0
  4. package/dist/templates/base/.agents/skills/schema-change/SKILL.md +28 -0
  5. package/dist/templates/base/.agents/skills/verify/SKILL.md +24 -0
  6. package/dist/templates/base/.github/workflows/ci.yml +44 -0
  7. package/dist/templates/base/AGENTS.md +60 -0
  8. package/dist/templates/base/CLAUDE.md +1 -0
  9. package/dist/templates/base/Dockerfile +13 -0
  10. package/dist/templates/base/_dockerignore +4 -0
  11. package/dist/templates/base/_env.example +15 -0
  12. package/dist/templates/base/_gitignore +11 -0
  13. package/dist/templates/base/_node-version +1 -0
  14. package/dist/templates/base/api/AGENTS.md +22 -0
  15. package/dist/templates/base/api/drizzle/0000_items.sql +13 -0
  16. package/dist/templates/base/api/drizzle/meta/0000_snapshot.json +126 -0
  17. package/dist/templates/base/api/drizzle/meta/_journal.json +13 -0
  18. package/dist/templates/base/api/drizzle.config.ts +16 -0
  19. package/dist/templates/base/api/openapi.json +450 -0
  20. package/dist/templates/base/api/package.json +50 -0
  21. package/dist/templates/base/api/scripts/openapi.ts +27 -0
  22. package/dist/templates/base/api/src/__tests__/server.test.ts +51 -0
  23. package/dist/templates/base/api/src/config.ts +43 -0
  24. package/dist/templates/base/api/src/core.ts +37 -0
  25. package/dist/templates/base/api/src/db/client.ts +30 -0
  26. package/dist/templates/base/api/src/db/migrate.ts +86 -0
  27. package/dist/templates/base/api/src/db/schema.ts +34 -0
  28. package/dist/templates/base/api/src/db/table.ts +8 -0
  29. package/dist/templates/base/api/src/logger.ts +5 -0
  30. package/dist/templates/base/api/src/main.ts +23 -0
  31. package/dist/templates/base/api/src/modules/items/__tests__/items.test.ts +86 -0
  32. package/dist/templates/base/api/src/modules/items/items.ts +121 -0
  33. package/dist/templates/base/api/src/orpc.ts +25 -0
  34. package/dist/templates/base/api/src/router.ts +10 -0
  35. package/dist/templates/base/api/src/server.ts +58 -0
  36. package/dist/templates/base/api/src/telemetry.ts +27 -0
  37. package/dist/templates/base/api/src/test/core-functions.sql +18 -0
  38. package/dist/templates/base/api/src/test/setup.ts +68 -0
  39. package/dist/templates/base/api/tsconfig.json +9 -0
  40. package/dist/templates/base/knip.ts +22 -0
  41. package/dist/templates/base/package.json +31 -0
  42. package/dist/templates/base/pnpm-workspace.yaml +20 -0
  43. package/dist/templates/base/tools/check-generated.ts +78 -0
  44. package/dist/templates/base/tools/check-rls.sh +30 -0
  45. package/dist/templates/base/tools/check-rls.sql +109 -0
  46. package/dist/templates/base/tools/no-org-id.sql +5 -0
  47. package/dist/templates/base/tools/test/no-skips.ts +58 -0
  48. package/dist/templates/base/tsconfig.base.json +16 -0
  49. package/dist/templates/base/tsconfig.json +9 -0
  50. package/dist/templates/base/ui/AGENTS.md +18 -0
  51. package/dist/templates/base/ui/package.json +32 -0
  52. package/dist/templates/base/ui/rsbuild.config.ts +36 -0
  53. package/dist/templates/base/ui/src/__Pascal__.tsx +9 -0
  54. package/dist/templates/base/ui/src/config.tsx +11 -0
  55. package/dist/templates/base/ui/src/index.ts +3 -0
  56. package/dist/templates/base/ui/src/items/ItemSheet.tsx +107 -0
  57. package/dist/templates/base/ui/src/items/ItemsPage.tsx +116 -0
  58. package/dist/templates/base/ui/src/items/useItems.ts +79 -0
  59. package/dist/templates/base/ui/src/orpc.ts +32 -0
  60. package/dist/templates/base/ui/tsconfig.json +11 -0
  61. package/dist/templates/base/vite.config.ts +63 -0
  62. package/dist/templates/migrate/.agents/skills/plugin-migrate/SKILL.md +61 -0
  63. package/dist/templates/migrate/migration/checklist.ts +429 -0
  64. package/dist/templates/migrate/migration/core-map.ts +149 -0
  65. package/dist/templates/migrate/migration/import-map.ts +4 -0
  66. package/dist/templates/migrate/migration/inventory.ts +881 -0
  67. package/dist/templates/migrate/package.json +15 -0
  68. package/dist/templates/migrate/scripts/import-mongo.ts +143 -0
  69. package/package.json +32 -3
@@ -0,0 +1,86 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { sql } from 'drizzle-orm';
4
+ import { readMigrationFiles } from 'drizzle-orm/migrator';
5
+ import { z } from 'zod';
6
+ import { db, pool } from './client.ts';
7
+
8
+ /** Our own tracking table: core and other plugins in the same database keep theirs. */
9
+ export const MIGRATIONS_TABLE = '__drizzle_migrations___id__';
10
+
11
+ const migrationsTable = sql`${sql.identifier('public')}.${sql.identifier(MIGRATIONS_TABLE)}`;
12
+
13
+ /** `drizzle/` next to `src/` in development (src/db/) and next to `dist/` in the bundle. */
14
+ const migrationsFolder = () => {
15
+ const candidates = ['../../drizzle', '../drizzle'].map((dir) =>
16
+ resolve(import.meta.dirname, dir),
17
+ );
18
+
19
+ const found = candidates.find((dir) => existsSync(join(dir, 'meta', '_journal.json')));
20
+
21
+ if (!found) throw new Error(`No migrations in ${candidates.join(' or ')}`);
22
+
23
+ return found;
24
+ };
25
+
26
+ const Journal = z.object({ entries: z.array(z.object({ tag: z.string() })) });
27
+
28
+ /**
29
+ * Applies pending migrations and returns their tags. One transaction under a
30
+ * transaction-scoped advisory lock, so replicas starting together and
31
+ * transaction poolers are safe. Bookkeeping matches Drizzle's (hash +
32
+ * timestamp), so drizzle-kit keeps working.
33
+ */
34
+ export const runMigrations = async () => {
35
+ const folder = migrationsFolder();
36
+ const migrations = readMigrationFiles({ migrationsFolder: folder });
37
+
38
+ const { entries } = Journal.parse(
39
+ JSON.parse(readFileSync(join(folder, 'meta', '_journal.json'), 'utf8')),
40
+ );
41
+
42
+ return db.transaction(async (tx) => {
43
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtext('__id__:migrate'))`);
44
+ await tx.execute(sql`
45
+ create table if not exists ${migrationsTable} (
46
+ id serial primary key,
47
+ hash text not null,
48
+ created_at bigint
49
+ )
50
+ `);
51
+
52
+ const { rows } = await tx.execute<{ created_at: string | null }>(
53
+ sql`select created_at from ${migrationsTable} order by created_at desc limit 1`,
54
+ );
55
+
56
+ const last = Number(rows[0]?.created_at ?? 0);
57
+
58
+ const pending = migrations
59
+ .map((migration, index) => ({
60
+ ...migration,
61
+ tag: entries[index]?.tag ?? String(migration.folderMillis),
62
+ }))
63
+ .filter((migration) => migration.folderMillis > last);
64
+
65
+ if (!pending.length) return [];
66
+
67
+ // A query without parameters goes over Postgres's simple protocol, which runs many
68
+ // statements in order. Each ends on its own line, so a trailing `--` comment can't hide
69
+ // the separator, and an empty statement between two semicolons is allowed.
70
+ await tx.execute(sql.raw(pending.flatMap((migration) => migration.sql).join('\n;\n')));
71
+ await tx.execute(
72
+ sql`insert into ${migrationsTable} (hash, created_at) values ${sql.join(
73
+ pending.map((migration) => sql`(${migration.hash}, ${migration.folderMillis})`),
74
+ sql`, `,
75
+ )}`,
76
+ );
77
+
78
+ return pending.map((migration) => migration.tag);
79
+ });
80
+ };
81
+
82
+ // `pnpm db:migrate` applies them without starting the API.
83
+ if (import.meta.main) {
84
+ await runMigrations();
85
+ await pool.end();
86
+ }
@@ -0,0 +1,34 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { sql } from 'drizzle-orm';
3
+ import { index, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
4
+ import { table } from './table.ts';
5
+
6
+ /** Names are unique per organisation, ignoring case. A write that breaks it fails with 23505. */
7
+ export const ITEM_NAME_INDEX = '__id___items_org_name_key';
8
+
9
+ /**
10
+ * The reference table. `org_id` is the core organisation; row-level security
11
+ * (`core_enable_tenant_rls` in the migration) shows each transaction only its
12
+ * organisation's rows. Ids are text, so imported Mongo `_id`s fit.
13
+ */
14
+ export const items = table(
15
+ 'items',
16
+ {
17
+ id: text()
18
+ .primaryKey()
19
+ .$defaultFn(() => randomUUID()),
20
+ orgId: text().notNull(),
21
+ name: text().notNull(),
22
+ description: text().notNull().default(''),
23
+ createdBy: text().notNull(),
24
+ createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
25
+ updatedAt: timestamp({ withTimezone: true })
26
+ .notNull()
27
+ .defaultNow()
28
+ .$onUpdate(() => new Date()),
29
+ },
30
+ (t) => [
31
+ index('__id___items_org_created_idx').on(t.orgId, t.createdAt.desc(), t.id.desc()),
32
+ uniqueIndex(ITEM_NAME_INDEX).on(t.orgId, sql`lower(${t.name})`),
33
+ ],
34
+ );
@@ -0,0 +1,8 @@
1
+ import { pgTableCreator } from 'drizzle-orm/pg-core';
2
+
3
+ /**
4
+ * Every table is `__id___<name>`: the plugin shares core's database, and core
5
+ * gives its role rights on its own tables only. Name indexes and constraints
6
+ * in full (`__id___items_org_created_idx`).
7
+ */
8
+ export const table = pgTableCreator((name) => `__id___${name}`);
@@ -0,0 +1,5 @@
1
+ import { pino } from 'pino';
2
+ import { config, PLUGIN } from '#/config.ts';
3
+
4
+ /** JSON logs on stdout. With OpenTelemetry on, each line carries its trace id. */
5
+ export const logger = pino({ name: PLUGIN, level: config.logLevel });
@@ -0,0 +1,23 @@
1
+ import { config } from '#/config.ts';
2
+ import { core, manifest } from '#/core.ts';
3
+ import { pool } from '#/db/client.ts';
4
+ import { runMigrations } from '#/db/migrate.ts';
5
+ import { logger } from '#/logger.ts';
6
+ import { createApp } from '#/server.ts';
7
+
8
+ const applied = await runMigrations();
9
+
10
+ if (applied.length) logger.info({ applied }, 'applied migrations');
11
+
12
+ // Core installs it automatically in development and self-hosted (PLUGINS_AUTO_INSTALL).
13
+ await core.registerManifest(manifest);
14
+
15
+ const server = createApp().listen(config.port, () => {
16
+ logger.info(`API on ${config.publicUrl}, UI entry ${manifest.ui.entry}`);
17
+ });
18
+
19
+ const stop = () => server.close(() => void pool.end());
20
+
21
+ process.once('SIGTERM', stop);
22
+
23
+ process.once('SIGINT', stop);
@@ -0,0 +1,86 @@
1
+ import type { PluginMember } from '@erxes/plugin-sdk';
2
+ import { createRouterClient } from '@orpc/server';
3
+ import { describe, expect, it } from 'vite-plus/test';
4
+ import { PERMISSIONS } from '#/core.ts';
5
+ import { router } from '#/router.ts';
6
+
7
+ /** The typed client the UI uses, served in-process as this member. */
8
+ const clientAs = (orgId: string, permissions: string[] = Object.values(PERMISSIONS)) => {
9
+ const member: PluginMember = {
10
+ userId: `user-${orgId}`,
11
+ orgId,
12
+ role: 'member',
13
+ permissions,
14
+ can: (action) => permissions.includes(action),
15
+ tier: 'pro',
16
+ access: 'full',
17
+ canChange: () => true,
18
+ };
19
+
20
+ return createRouterClient(router, { context: { member } });
21
+ };
22
+
23
+ describe('items', () => {
24
+ it('creates, lists newest first in pages, updates and deletes', async () => {
25
+ const client = clientAs('org-a');
26
+ const first = await client.items.create({ name: 'First' });
27
+ const second = await client.items.create({ name: 'Second' });
28
+
29
+ expect(first).toMatchObject({ name: 'First', description: '', createdBy: 'user-org-a' });
30
+ expect(first).not.toHaveProperty('orgId');
31
+
32
+ const page = await client.items.list({ limit: 1 });
33
+
34
+ expect(page.items.map((item) => item.id)).toEqual([second.id]);
35
+ expect(page.nextCursor).toBe(second.id);
36
+
37
+ const next = await client.items.list({ limit: 1, cursor: second.id });
38
+
39
+ expect(next.items.map((item) => item.id)).toEqual([first.id]);
40
+ expect(next.nextCursor).toBeNull();
41
+
42
+ await expect(
43
+ client.items.update({ id: first.id, name: 'First', description: 'Changed' }),
44
+ ).resolves.toMatchObject({ name: 'First', description: 'Changed' });
45
+ await expect(client.items.remove({ id: first.id })).resolves.toEqual({ id: first.id });
46
+ await expect(client.items.list({})).resolves.toMatchObject({ items: [{ id: second.id }] });
47
+ });
48
+
49
+ it('refuses a name the organisation already uses, ignoring case', async () => {
50
+ const client = clientAs('org-b');
51
+ const taken = { code: 'ITEM_NAME_TAKEN', status: 409, defined: true };
52
+
53
+ await client.items.create({ name: 'Tools' });
54
+ const other = await client.items.create({ name: 'Parts' });
55
+
56
+ await expect(client.items.create({ name: 'tools' })).rejects.toMatchObject({
57
+ ...taken,
58
+ data: { name: 'tools' },
59
+ });
60
+ await expect(client.items.update({ id: other.id, name: 'TOOLS' })).rejects.toMatchObject({
61
+ ...taken,
62
+ data: { name: 'TOOLS' },
63
+ });
64
+ });
65
+
66
+ it('shows and changes only the items of its own organisation', async () => {
67
+ const theirs = await clientAs('org-c').items.create({ name: 'Shared name' });
68
+ const ours = clientAs('org-d');
69
+
70
+ await expect(ours.items.list({})).resolves.toMatchObject({ items: [] });
71
+ await expect(ours.items.create({ name: 'Shared name' })).resolves.toMatchObject({
72
+ name: 'Shared name',
73
+ });
74
+ await expect(ours.items.update({ id: theirs.id, name: 'Mine now' })).rejects.toMatchObject({
75
+ code: 'NOT_FOUND',
76
+ });
77
+ await expect(ours.items.remove({ id: theirs.id })).rejects.toMatchObject({ code: 'NOT_FOUND' });
78
+ });
79
+
80
+ it('refuses members without the permission', async () => {
81
+ const viewer = clientAs('org-e', [PERMISSIONS.view]);
82
+
83
+ await expect(viewer.items.create({ name: 'No' })).rejects.toMatchObject({ code: 'FORBIDDEN' });
84
+ await expect(viewer.items.list({})).resolves.toMatchObject({ items: [] });
85
+ });
86
+ });
@@ -0,0 +1,121 @@
1
+ import { type ORPCErrorConstructorMap, ORPCError } from '@orpc/server';
2
+ import { and, desc, eq, getTableColumns, ilike, sql } from 'drizzle-orm';
3
+ import { z } from 'zod';
4
+ import { PERMISSIONS } from '#/core.ts';
5
+ import { uniqueViolation } from '#/db/client.ts';
6
+ import { ITEM_NAME_INDEX, items } from '#/db/schema.ts';
7
+ import { reads, writes } from '#/orpc.ts';
8
+
9
+ /** What a procedure returns: the row without `org_id`, which the caller already knows. */
10
+ const { orgId, ...columns } = getTableColumns(items);
11
+
12
+ const Name = z.string().trim().min(1).max(200);
13
+ const Description = z.string().trim().max(5000);
14
+
15
+ const Item = z.object({
16
+ id: z.string(),
17
+ name: Name,
18
+ description: Description,
19
+ createdBy: z.string(),
20
+ createdAt: z.date(),
21
+ updatedAt: z.date(),
22
+ });
23
+
24
+ /** The failures a client can branch on: `isDefinedError(error) && error.code === ...`. */
25
+ const itemErrors = {
26
+ ITEM_NAME_TAKEN: {
27
+ status: 409,
28
+ message: 'Another item has this name',
29
+ data: z.object({ name: z.string() }),
30
+ },
31
+ };
32
+
33
+ /** The one place Postgres's 23505 on the name index becomes ITEM_NAME_TAKEN. */
34
+ const nameTaken =
35
+ (errors: ORPCErrorConstructorMap<typeof itemErrors>, name: string) =>
36
+ (error: unknown): never => {
37
+ if (uniqueViolation(error) === ITEM_NAME_INDEX)
38
+ throw errors.ITEM_NAME_TAKEN({ data: { name } });
39
+
40
+ throw error;
41
+ };
42
+
43
+ const escapeLike = (text: string) => text.replaceAll(/[\\%_]/g, '\\$&');
44
+
45
+ /** Newest first, in keyset pages: `nextCursor` is the id to pass for the next page. */
46
+ const list = reads(PERMISSIONS.view)
47
+ .input(
48
+ z.object({
49
+ search: z.string().trim().max(200).optional(),
50
+ cursor: z.string().optional(),
51
+ limit: z.number().int().min(1).max(100).default(50),
52
+ }),
53
+ )
54
+ .output(z.object({ items: z.array(Item), nextCursor: z.string().nullable() }))
55
+ .handler(async ({ input, context: { tx } }) => {
56
+ const after = input.cursor
57
+ ? sql`(${items.createdAt}, ${items.id}) < (select created_at, id from ${items} where id = ${input.cursor})`
58
+ : undefined;
59
+
60
+ const rows = await tx
61
+ .select(columns)
62
+ .from(items)
63
+ .where(
64
+ and(input.search ? ilike(items.name, `%${escapeLike(input.search)}%`) : undefined, after),
65
+ )
66
+ .orderBy(desc(items.createdAt), desc(items.id))
67
+ .limit(input.limit + 1);
68
+
69
+ const page = rows.slice(0, input.limit);
70
+
71
+ return {
72
+ items: page,
73
+ nextCursor: rows.length > input.limit ? (page.at(-1)?.id ?? null) : null,
74
+ };
75
+ });
76
+
77
+ const create = writes(PERMISSIONS.manage)
78
+ .errors(itemErrors)
79
+ .input(z.object({ name: Name, description: Description.default('') }))
80
+ .output(Item)
81
+ .handler(async ({ input, context: { tx, member }, errors }) => {
82
+ const [item] = await tx
83
+ .insert(items)
84
+ .values({ ...input, orgId: member.orgId, createdBy: member.userId })
85
+ .returning(columns)
86
+ .catch(nameTaken(errors, input.name));
87
+
88
+ if (!item) throw new ORPCError('INTERNAL_SERVER_ERROR');
89
+
90
+ return item;
91
+ });
92
+
93
+ const update = writes(PERMISSIONS.manage)
94
+ .errors(itemErrors)
95
+ .input(z.object({ id: z.string(), name: Name, description: Description.optional() }))
96
+ .output(Item)
97
+ .handler(async ({ input: { id, ...fields }, context: { tx }, errors }) => {
98
+ const [item] = await tx
99
+ .update(items)
100
+ .set(fields)
101
+ .where(eq(items.id, id))
102
+ .returning(columns)
103
+ .catch(nameTaken(errors, fields.name));
104
+
105
+ if (!item) throw new ORPCError('NOT_FOUND', { message: 'No such item' });
106
+
107
+ return item;
108
+ });
109
+
110
+ const remove = writes(PERMISSIONS.manage)
111
+ .input(z.object({ id: z.string() }))
112
+ .output(z.object({ id: z.string() }))
113
+ .handler(async ({ input, context: { tx } }) => {
114
+ const [item] = await tx.delete(items).where(eq(items.id, input.id)).returning({ id: items.id });
115
+
116
+ if (!item) throw new ORPCError('NOT_FOUND', { message: 'No such item' });
117
+
118
+ return item;
119
+ });
120
+
121
+ export const itemProcedures = { list, create, update, remove };
@@ -0,0 +1,25 @@
1
+ import type { PluginMember } from '@erxes/plugin-sdk';
2
+ import { ORPCError, os } from '@orpc/server';
3
+ import { withOrg } from '#/db/client.ts';
4
+
5
+ /** server.ts has verified the session token: `context.member` is the signed-in member. */
6
+ const base = os.$context<{ member: PluginMember }>();
7
+
8
+ const inOrg = (action: string, change: boolean) =>
9
+ base.middleware(({ context: { member }, next }) => {
10
+ if (!member.can(action)) {
11
+ throw new ORPCError('FORBIDDEN', { message: `You need the ${action} permission` });
12
+ }
13
+
14
+ if (change && !member.canChange()) {
15
+ throw new ORPCError('FORBIDDEN', { message: 'Read-only: this plugin left your plan' });
16
+ }
17
+
18
+ return withOrg(member.orgId, async (tx) => next({ context: { tx } }));
19
+ });
20
+
21
+ /** A read: the member holds `action`; `context.tx` is their organisation's transaction. */
22
+ export const reads = (action: string) => base.use(inOrg(action, false));
23
+
24
+ /** A change: like `reads`, and refused while the organisation is read-only. */
25
+ export const writes = (action: string) => base.use(inOrg(action, true));
@@ -0,0 +1,10 @@
1
+ import type { RouterClient } from '@orpc/server';
2
+ import { itemProcedures } from '#/modules/items/items.ts';
3
+
4
+ /** Every procedure, served at `/api/rpc/<group>/<name>`. */
5
+ export const router = {
6
+ items: itemProcedures,
7
+ };
8
+
9
+ /** The typed client the UI builds (`ui/src/orpc.ts`). */
10
+ export type Client = RouterClient<typeof router>;
@@ -0,0 +1,58 @@
1
+ import { bearerOf, verifyPluginSession } from '@erxes/plugin-sdk';
2
+ import { onError, ORPCError } from '@orpc/server';
3
+ import { RPCHandler } from '@orpc/server/node';
4
+ import cors from 'cors';
5
+ import express from 'express';
6
+ import { pinoHttp } from 'pino-http';
7
+ import { config, PLUGIN } from '#/config.ts';
8
+ import { logger } from '#/logger.ts';
9
+ import { router } from '#/router.ts';
10
+
11
+ const rpc = new RPCHandler(router, {
12
+ interceptors: [
13
+ onError((error) => {
14
+ if (!(error instanceof ORPCError) || error.status >= 500) logger.error(error);
15
+ }),
16
+ ],
17
+ });
18
+
19
+ /** The member behind a request from the plugin UI, or null without a valid session token. */
20
+ const memberOf = async (authorization: string | undefined) => {
21
+ const token = bearerOf(authorization);
22
+
23
+ if (!token) return null;
24
+
25
+ return verifyPluginSession(token, { coreUrl: config.coreUrl, plugin: PLUGIN }).catch(() => null);
26
+ };
27
+
28
+ export const createApp = () => {
29
+ const app = express();
30
+
31
+ app.disable('x-powered-by');
32
+ app.use(pinoHttp({ logger }));
33
+ // The plugin UI runs inside web and calls this API from web's origin.
34
+ app.use(cors({ origin: config.coreUiOrigin, maxAge: 600 }));
35
+
36
+ app.get('/health', (_req, res) => {
37
+ res.json({ ok: true });
38
+ });
39
+
40
+ // erxes-ui's pluginFetch adds a 5-minute session token core issued for this member and plugin.
41
+ app.use('/api/rpc', async (req, res, next) => {
42
+ const member = await memberOf(req.headers.authorization);
43
+
44
+ if (!member) {
45
+ res.status(401).json({ message: 'Open this plugin inside erxes to sign in' });
46
+
47
+ return;
48
+ }
49
+
50
+ const { matched } = await rpc.handle(req, res, { prefix: '/api/rpc', context: { member } });
51
+
52
+ if (!matched) next();
53
+ });
54
+
55
+ if (config.uiDir) app.use('/ui', express.static(config.uiDir));
56
+
57
+ return app;
58
+ };
@@ -0,0 +1,27 @@
1
+ import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
2
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
3
+ import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
4
+ import { PinoInstrumentation } from '@opentelemetry/instrumentation-pino';
5
+ import { NodeSDK } from '@opentelemetry/sdk-node';
6
+ import { register } from 'import-in-the-middle/register-hooks.mjs';
7
+ import { config } from '#/config.ts';
8
+
9
+ // Loaded before the app with `node --import ./src/telemetry.ts`. Off unless an
10
+ // OTLP endpoint is set.
11
+ if (config.tracing) {
12
+ // ESM modules are patched through this in-thread loader hook (module.registerHooks).
13
+ register();
14
+
15
+ const sdk = new NodeSDK({
16
+ serviceName: '__id__-api',
17
+ instrumentations: [
18
+ new HttpInstrumentation(),
19
+ new ExpressInstrumentation(),
20
+ new PgInstrumentation(),
21
+ new PinoInstrumentation(),
22
+ ],
23
+ });
24
+
25
+ sdk.start();
26
+ process.once('SIGTERM', () => void sdk.shutdown());
27
+ }
@@ -0,0 +1,18 @@
1
+ -- Core's tenant functions, which plugin migrations call, as erxes
2
+ -- packages/db/drizzle defines them. Tests and tools/check-rls.sh install them
3
+ -- in their throwaway databases.
4
+ CREATE OR REPLACE FUNCTION core_tenant_visible(p_org_id text) RETURNS boolean
5
+ LANGUAGE sql STABLE AS $$
6
+ SELECT p_org_id = current_setting('app.org_id', true)
7
+ $$;
8
+ CREATE OR REPLACE FUNCTION core_enable_tenant_rls(p_table regclass, p_column text DEFAULT 'org_id') RETURNS void
9
+ LANGUAGE plpgsql AS $$
10
+ BEGIN
11
+ IF p_column !~ '^[a-z_][a-z0-9_]*$' THEN
12
+ RAISE EXCEPTION 'core_enable_tenant_rls: invalid column %', p_column;
13
+ END IF;
14
+ EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', p_table);
15
+ EXECUTE format('ALTER TABLE %s FORCE ROW LEVEL SECURITY', p_table);
16
+ EXECUTE format('DROP POLICY IF EXISTS tenant ON %s', p_table);
17
+ EXECUTE format('CREATE POLICY tenant ON %s USING (core_tenant_visible(%I)) WITH CHECK (core_tenant_visible(%I))', p_table, p_column, p_column);
18
+ END $$;
@@ -0,0 +1,68 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { Client } from 'pg';
4
+ import { afterAll } from 'vite-plus/test';
5
+
6
+ // Runs before each test file: a throwaway database owned by a role without
7
+ // BYPASSRLS, like the plugin role core creates, migrated from drizzle/.
8
+ const adminUrl = process.env.DATA_TEST_URL;
9
+
10
+ if (!adminUrl) {
11
+ throw new Error(
12
+ 'Set DATA_TEST_URL to a Postgres superuser, e.g. postgres://postgres:postgres@127.0.0.1:5432/postgres',
13
+ );
14
+ }
15
+
16
+ const ROLE = '__id___test';
17
+ const database = `__id___test_${randomBytes(4).toString('hex')}`;
18
+
19
+ // Core's tenant functions, which plugin migrations call.
20
+ const CORE_FUNCTIONS = readFileSync(new URL('./core-functions.sql', import.meta.url), 'utf8');
21
+
22
+ const urlOf = (name: string, role?: string) => {
23
+ const url = new URL(adminUrl);
24
+
25
+ url.pathname = `/${name}`;
26
+
27
+ if (role) {
28
+ url.username = role;
29
+ url.password = role;
30
+ }
31
+
32
+ return url.toString();
33
+ };
34
+
35
+ const run = async (url: string, statement: string) => {
36
+ const client = new Client({ connectionString: url });
37
+
38
+ await client.connect();
39
+
40
+ try {
41
+ await client.query(statement);
42
+ } finally {
43
+ await client.end();
44
+ }
45
+ };
46
+
47
+ await run(
48
+ adminUrl,
49
+ `DO $$ BEGIN CREATE ROLE ${ROLE} LOGIN NOBYPASSRLS PASSWORD '${ROLE}';
50
+ EXCEPTION WHEN duplicate_object OR unique_violation THEN NULL; END $$`,
51
+ );
52
+
53
+ await run(adminUrl, `CREATE DATABASE ${database} OWNER ${ROLE}`);
54
+
55
+ await run(urlOf(database), CORE_FUNCTIONS);
56
+
57
+ process.env.DATA_URL = urlOf(database, ROLE);
58
+
59
+ const { runMigrations } = await import('#/db/migrate.ts');
60
+
61
+ await runMigrations();
62
+
63
+ afterAll(async () => {
64
+ const { pool } = await import('#/db/client.ts');
65
+
66
+ await pool.end();
67
+ await run(adminUrl, `DROP DATABASE IF EXISTS ${database} WITH (FORCE)`);
68
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "module": "nodenext",
5
+ "moduleResolution": "nodenext",
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src", "scripts", "drizzle.config.ts"]
9
+ }
@@ -0,0 +1,22 @@
1
+ import type { KnipConfig } from 'knip';
2
+
3
+ const config: KnipConfig = {
4
+ workspaces: {
5
+ '.': {
6
+ entry: ['{tools,migration,scripts}/*.ts'],
7
+ project: ['*.ts', '{tools,migration,scripts}/**/*.ts'],
8
+ // Oxlint runs tsrs-lint through OXLINT_TSGOLINT_PATH in the check task.
9
+ ignoreDependencies: ['tsrs'],
10
+ },
11
+ api: {
12
+ entry: ['scripts/*.ts'],
13
+ project: ['src/**/*.ts', 'scripts/**/*.ts'],
14
+ },
15
+ ui: {
16
+ entry: ['src/config.tsx', 'src/__Pascal__.tsx'],
17
+ project: ['src/**/*.{ts,tsx}'],
18
+ },
19
+ },
20
+ };
21
+
22
+ export default config;
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@__id__/plugin",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "__description__",
6
+ "type": "module",
7
+ "scripts": {
8
+ "build": "pnpm --filter @__id__/api build && pnpm --filter @__id__/ui build",
9
+ "db:generate": "pnpm --filter @__id__/api db:generate",
10
+ "db:check": "pnpm --filter @__id__/api db:check",
11
+ "db:migrate": "pnpm --filter @__id__/api db:migrate",
12
+ "openapi": "pnpm --filter @__id__/api openapi",
13
+ "check:generated": "node tools/check-generated.ts",
14
+ "check:rls": "bash tools/check-rls.sh",
15
+ "dev:api": "pnpm --filter @__id__/api dev",
16
+ "dev:ui": "pnpm --filter @__id__/ui dev",
17
+ "image:context": "pnpm build && rm -rf .runtime && pnpm --filter @__id__/api deploy --prod .runtime"
18
+ },
19
+ "devDependencies": {
20
+ "@erxes/lint": "0.1.0",
21
+ "@types/node": "^26.6.6",
22
+ "knip": "^6.45.1",
23
+ "tsrs": "0.25.0-ts7.1.0-beta",
24
+ "typescript": "7.0.2",
25
+ "vite-plus": "catalog:"
26
+ },
27
+ "engines": {
28
+ "node": ">=26"
29
+ },
30
+ "packageManager": "pnpm@__pnpmVersion__"
31
+ }
@@ -0,0 +1,20 @@
1
+ packages:
2
+ - api
3
+ - ui
4
+ # `pnpm deploy` copies api/ with real files for the image.
5
+ injectWorkspacePackages: true
6
+ catalog:
7
+ vite: npm:@voidzero-dev/vite-plus-core@1.6.0
8
+ vite-plus: 1.6.0
9
+ # Core publishes its packages under the v2-next tag, often more than once a day;
10
+ # the release-age gate stays on for everything else.
11
+ minimumReleaseAgeExclude:
12
+ - '@erxes/*'
13
+ overrides:
14
+ 'vite@*': 'catalog:'
15
+ # Install scripts nothing here needs: esbuild ships its binary as an optional
16
+ # dependency, and the other two only print or check.
17
+ allowBuilds:
18
+ core-js-pure: false
19
+ esbuild: false
20
+ protobufjs: false