create-erxes 0.0.0-stage → 0.1.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 (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 +20 -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 +59 -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/package.json +47 -0
  20. package/dist/templates/base/api/src/__tests__/server.test.ts +51 -0
  21. package/dist/templates/base/api/src/config.ts +43 -0
  22. package/dist/templates/base/api/src/core.ts +37 -0
  23. package/dist/templates/base/api/src/db/client.ts +30 -0
  24. package/dist/templates/base/api/src/db/migrate.ts +80 -0
  25. package/dist/templates/base/api/src/db/schema.ts +34 -0
  26. package/dist/templates/base/api/src/db/table.ts +8 -0
  27. package/dist/templates/base/api/src/logger.ts +5 -0
  28. package/dist/templates/base/api/src/main.ts +23 -0
  29. package/dist/templates/base/api/src/migrate.ts +9 -0
  30. package/dist/templates/base/api/src/modules/items/__tests__/items.test.ts +92 -0
  31. package/dist/templates/base/api/src/modules/items/items.ts +127 -0
  32. package/dist/templates/base/api/src/orpc.ts +25 -0
  33. package/dist/templates/base/api/src/router.ts +10 -0
  34. package/dist/templates/base/api/src/server.ts +58 -0
  35. package/dist/templates/base/api/src/telemetry.ts +27 -0
  36. package/dist/templates/base/api/src/test/core-functions.sql +18 -0
  37. package/dist/templates/base/api/src/test/setup.ts +68 -0
  38. package/dist/templates/base/api/tsconfig.json +9 -0
  39. package/dist/templates/base/knip.ts +21 -0
  40. package/dist/templates/base/package.json +30 -0
  41. package/dist/templates/base/pnpm-workspace.yaml +20 -0
  42. package/dist/templates/base/tools/check-generated.ts +70 -0
  43. package/dist/templates/base/tools/check-rls.sh +30 -0
  44. package/dist/templates/base/tools/check-rls.sql +109 -0
  45. package/dist/templates/base/tools/no-org-id.sql +5 -0
  46. package/dist/templates/base/tools/test/no-skips.ts +58 -0
  47. package/dist/templates/base/tsconfig.base.json +16 -0
  48. package/dist/templates/base/tsconfig.json +9 -0
  49. package/dist/templates/base/ui/AGENTS.md +34 -0
  50. package/dist/templates/base/ui/package.json +35 -0
  51. package/dist/templates/base/ui/rsbuild.config.ts +39 -0
  52. package/dist/templates/base/ui/src/__Pascal__.tsx +14 -0
  53. package/dist/templates/base/ui/src/config.tsx +11 -0
  54. package/dist/templates/base/ui/src/index.ts +3 -0
  55. package/dist/templates/base/ui/src/items/ItemSheet.tsx +107 -0
  56. package/dist/templates/base/ui/src/items/ItemsPage.tsx +143 -0
  57. package/dist/templates/base/ui/src/items/useItems.ts +79 -0
  58. package/dist/templates/base/ui/src/orpc.ts +32 -0
  59. package/dist/templates/base/ui/src/styles.css +8 -0
  60. package/dist/templates/base/ui/tsconfig.json +11 -0
  61. package/dist/templates/base/vite.config.ts +62 -0
  62. package/dist/templates/migrate/.agents/skills/plugin-migrate/SKILL.md +66 -0
  63. package/dist/templates/migrate/migration/checklist.ts +429 -0
  64. package/dist/templates/migrate/migration/core-map.ts +150 -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,59 @@
1
+ # __title__
2
+
3
+ __description__
4
+
5
+ An erxes plugin for the new core (Postgres). `api/` is the API: Express 5,
6
+ oRPC and Drizzle. `ui/` is the Module Federation remote web loads. Read the
7
+ `AGENTS.md` in the folder you edit. `api/src/modules/items` and `ui/src/items`
8
+ are the reference feature: copy their shape for a new one.
9
+
10
+ <!-- quality:start -->
11
+
12
+ ## Quality
13
+
14
+ Every erxes repo on the new stack has this section, unchanged. The brackets name the checks that
15
+ enforce a rule; `review` marks the part no tool can check. The rewrite keeps every feature and improves the
16
+ architecture. Agents write the code and the checks judge it, so a green check lets a change ship
17
+ without line-by-line review.
18
+
19
+ - `vp run check` is the type check: oxfmt, type-aware oxlint on tsrs and knip in about 10 s. Run it after each edit and before each commit; it replaces `tsc`. `vp run fix` formats and autofixes. [vp run check]
20
+ - Port what a feature does, not its code. Fix what the old code got wrong instead of carrying it over. [review]
21
+ - Use a maintained library when one does the job. Keep dependencies near their latest release and off deprecated APIs. [typescript/no-deprecated, review]
22
+ - One way to do each job. Search for the existing helper before writing one, merge the repeats you find, delete what nothing uses. [knip, review]
23
+ - Types flow from the database schema to the contract to the UI. Infer them, so each shape is written once. [pnpm check:generated, review]
24
+ - Parse outside input with zod and narrow it, so the code needs no `any`, cast or `!`. [typescript/no-explicit-any, typescript/no-unsafe-type-assertion, typescript/no-non-null-assertion]
25
+ - Lint and type rules are the spec: when one fires, fix the code. Silencing it is never the fix, whether by a disable comment, `@ts-ignore`, an override, an ignore, a weaker option or a raised limit. A rule that is wrong changes in its own PR. [typescript/ban-ts-comment, review]
26
+ - Split a file or function that outgrows its limit by responsibility (router, service, queries). [max-lines, max-lines-per-function, review]
27
+ - Finish the work in the change, with no TODO or FIXME left in code. [no-warning-comments]
28
+ - Tests call the public interface (HTTP, the typed client, the rendered page) and assert what it does, never source strings or code shapes. [review]
29
+ - Every test runs: a skipped test or an empty suite fails the run. A failing test gets its code or its wrong expectation fixed, never loosened or deleted. [vp run test, review]
30
+ - Log through the structured logger, with the facts as fields. A caught error is rethrown or logged with its context. [no-console, review]
31
+ - Make the long-term change in one go, with no backward-compatibility shim, stopgap or speculative option. [review]
32
+ - Docs, PRs and copy are short: plain words, active voice, what it does or the number. [review]
33
+
34
+ <!-- quality:end -->
35
+
36
+ ## This repo
37
+
38
+ - `vp run check` runs the escape guard, format, lint, types, knip, the docs guard
39
+ and `pnpm check:generated`, which compares the migrations with the schema.
40
+ - Other gates: `vp run test` on real Postgres via `DATA_TEST_URL`,
41
+ `pnpm check:rls`, `pnpm build`. `vp run fix` formats and fixes lint.
42
+ - Core finds the plugin by these names, so they stay fixed: plugin `__id__`,
43
+ remote `__id___ui` exposing `./config` and `./__id__`, pages under `/__id__/*`.
44
+ - Every table, index and constraint starts with `__id___`, and every table has
45
+ `org_id` with forced row-level security, or is listed in `tools/no-org-id.sql`
46
+ with the reason. Core and other plugins share the database. [pnpm check:rls]
47
+ - The lint rules are `@erxes/lint`'s preset (`vite.config.ts`). It,
48
+ `tools/test/no-skips.ts` and `tools/check-rls.sql` come from core unchanged, as
49
+ does the quality section above. Change them in core.
50
+ - The API reaches core through `@erxes/plugin-sdk` (`api/src/core.ts`), the UI
51
+ through `@erxes/core-contract/client` with the member's session. Neither reads
52
+ `core_*` tables or imports core's app code.
53
+ - Members are signed in by core: the UI sends a session token, the API checks it
54
+ with `verifyPluginSession`. There is no public route yet, because core can't
55
+ tell a public request's organisation.
56
+ - Skills in `.agents/skills/`: `endpoint` for a procedure, `schema-change` for a
57
+ table or column, `verify` before calling a change done.__migrationSkill__
58
+ - What core promises plugins, and what counts as a breaking change, is core's
59
+ `plugin-contract` skill (erxes repo, branch `postgre`).
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,13 @@
1
+ # Packages what `pnpm image:context` built on the host: the bundled API with
2
+ # its production node_modules (.runtime) and the UI remote, served at /ui.
3
+ FROM node:26-bookworm-slim
4
+ ARG VERSION=0.1.0
5
+ WORKDIR /app
6
+ COPY --chown=node:node .runtime/ ./
7
+ COPY --chown=node:node ui/dist/ ./ui/
8
+ ENV NODE_ENV=production PORT=__apiPort__ UI_DIR=/app/ui VERSION=$VERSION
9
+ USER node
10
+ EXPOSE __apiPort__
11
+ HEALTHCHECK --interval=10s --timeout=5s --start-period=30s --retries=5 \
12
+ CMD node -e "fetch('http://127.0.0.1:'+process.env.PORT+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
13
+ CMD ["node", "--enable-source-maps", "--import", "./dist/telemetry.mjs", "dist/main.mjs"]
@@ -0,0 +1,4 @@
1
+ # The image only takes what `pnpm image:context` builds.
2
+ *
3
+ !.runtime
4
+ !ui/dist
@@ -0,0 +1,15 @@
1
+ # The API reads this file in development (`pnpm dev:api`). Copy it to .env.
2
+ PORT=__apiPort__
3
+ # Postgres as the plugin's role: run `pnpm db:plugin-role __id__` in the core repo.
4
+ DATA_URL=postgres://erxes_plugin___id__:change-me@127.0.0.1:5434/erxes
5
+ # Core's address, without /core/v1.
6
+ CORE_URL=http://localhost:3400
7
+ # The secret after `__id__:` in core's CORE_PLUGIN_KEYS (32+ characters).
8
+ PLUGIN_SECRET=change-me-to-the-secret-in-core-plugin-keys
9
+ PUBLIC_URL=http://localhost:__apiPort__
10
+ # `pnpm dev:ui` serves the remote here; in the image the API serves it at /ui.
11
+ UI_ENTRY_URL=http://localhost:__uiPort__/remoteEntry.js
12
+ # web's address, which calls this API from the browser.
13
+ CORE_UI_URL=http://localhost:3500
14
+ # Traces go to an OTLP collector when this is set.
15
+ # OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
@@ -0,0 +1,11 @@
1
+ node_modules/
2
+ dist/
3
+ .runtime/
4
+ coverage/
5
+ .scratch/
6
+ *.tsbuildinfo
7
+ *.log
8
+ .env
9
+ .env.*
10
+ !.env.example
11
+ .DS_Store
@@ -0,0 +1 @@
1
+ 26
@@ -0,0 +1,22 @@
1
+ # api
2
+
3
+ Node 26 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`.
4
+
5
+ - `src/main.ts` starts in this order: migrations, `core.registerManifest(manifest)`,
6
+ then the server. Core installs the plugin itself in development
7
+ (`PLUGINS_AUTO_INSTALL`).
8
+ - `src/core.ts` holds the core client and the manifest. Every permission, event
9
+ and kind in the manifest starts with `__id__.`. A new scope waits for the
10
+ owner's approval, so ask for one only when a procedure needs it.
11
+ - `src/server.ts` verifies the session token on `/api/rpc/*` and hands
12
+ procedures `context.member` (`PluginMember`: `orgId`, `userId`, `can()`,
13
+ `canChange()`).
14
+ - `src/orpc.ts`: build every procedure on `reads(action)` or `writes(action)`.
15
+ Both check the permission and run the handler in `withOrg(member.orgId)`, so
16
+ row-level security shows `context.tx` one organisation's rows. Queries carry
17
+ no org filter; only an insert sets `orgId`, from `context.member`.
18
+ - Call core (`core.forOrg(orgId)...`) outside `context.tx`; a failed core call
19
+ must not roll back the plugin's own change.
20
+ - Tests: `vite-plus/test`, run with `call(procedure, input, { context: { member } })`.
21
+ `src/test/setup.ts` gives each file its own database, owned by a role without
22
+ BYPASSRLS, so row-level security is real in tests.
@@ -0,0 +1,13 @@
1
+ CREATE TABLE "__id___items" (
2
+ "id" text PRIMARY KEY NOT NULL,
3
+ "org_id" text NOT NULL,
4
+ "name" text NOT NULL,
5
+ "description" text DEFAULT '' NOT NULL,
6
+ "created_by" text NOT NULL,
7
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
8
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
9
+ );
10
+ --> statement-breakpoint
11
+ CREATE INDEX "__id___items_org_created_idx" ON "__id___items" USING btree ("org_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
12
+ CREATE UNIQUE INDEX "__id___items_org_name_key" ON "__id___items" USING btree ("org_id",lower("name"));--> statement-breakpoint
13
+ SELECT core_enable_tenant_rls('__id___items');
@@ -0,0 +1,126 @@
1
+ {
2
+ "id": "5ccdfe2d-a57a-4573-bbee-ba11f21e7ddc",
3
+ "prevId": "00000000-0000-0000-0000-000000000000",
4
+ "version": "7",
5
+ "dialect": "postgresql",
6
+ "tables": {
7
+ "public.__id___items": {
8
+ "name": "__id___items",
9
+ "schema": "",
10
+ "columns": {
11
+ "id": {
12
+ "name": "id",
13
+ "type": "text",
14
+ "primaryKey": true,
15
+ "notNull": true
16
+ },
17
+ "org_id": {
18
+ "name": "org_id",
19
+ "type": "text",
20
+ "primaryKey": false,
21
+ "notNull": true
22
+ },
23
+ "name": {
24
+ "name": "name",
25
+ "type": "text",
26
+ "primaryKey": false,
27
+ "notNull": true
28
+ },
29
+ "description": {
30
+ "name": "description",
31
+ "type": "text",
32
+ "primaryKey": false,
33
+ "notNull": true,
34
+ "default": "''"
35
+ },
36
+ "created_by": {
37
+ "name": "created_by",
38
+ "type": "text",
39
+ "primaryKey": false,
40
+ "notNull": true
41
+ },
42
+ "created_at": {
43
+ "name": "created_at",
44
+ "type": "timestamp with time zone",
45
+ "primaryKey": false,
46
+ "notNull": true,
47
+ "default": "now()"
48
+ },
49
+ "updated_at": {
50
+ "name": "updated_at",
51
+ "type": "timestamp with time zone",
52
+ "primaryKey": false,
53
+ "notNull": true,
54
+ "default": "now()"
55
+ }
56
+ },
57
+ "indexes": {
58
+ "__id___items_org_created_idx": {
59
+ "name": "__id___items_org_created_idx",
60
+ "columns": [
61
+ {
62
+ "expression": "org_id",
63
+ "isExpression": false,
64
+ "asc": true,
65
+ "nulls": "last"
66
+ },
67
+ {
68
+ "expression": "created_at",
69
+ "isExpression": false,
70
+ "asc": false,
71
+ "nulls": "last"
72
+ },
73
+ {
74
+ "expression": "id",
75
+ "isExpression": false,
76
+ "asc": false,
77
+ "nulls": "last"
78
+ }
79
+ ],
80
+ "isUnique": false,
81
+ "concurrently": false,
82
+ "method": "btree",
83
+ "with": {}
84
+ },
85
+ "__id___items_org_name_key": {
86
+ "name": "__id___items_org_name_key",
87
+ "columns": [
88
+ {
89
+ "expression": "org_id",
90
+ "isExpression": false,
91
+ "asc": true,
92
+ "nulls": "last"
93
+ },
94
+ {
95
+ "expression": "lower(\"name\")",
96
+ "asc": true,
97
+ "isExpression": true,
98
+ "nulls": "last"
99
+ }
100
+ ],
101
+ "isUnique": true,
102
+ "concurrently": false,
103
+ "method": "btree",
104
+ "with": {}
105
+ }
106
+ },
107
+ "foreignKeys": {},
108
+ "compositePrimaryKeys": {},
109
+ "uniqueConstraints": {},
110
+ "policies": {},
111
+ "checkConstraints": {},
112
+ "isRLSEnabled": false
113
+ }
114
+ },
115
+ "enums": {},
116
+ "schemas": {},
117
+ "sequences": {},
118
+ "roles": {},
119
+ "policies": {},
120
+ "views": {},
121
+ "_meta": {
122
+ "columns": {},
123
+ "schemas": {},
124
+ "tables": {}
125
+ }
126
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": "7",
3
+ "dialect": "postgresql",
4
+ "entries": [
5
+ {
6
+ "idx": 0,
7
+ "version": "7",
8
+ "when": 1794580159751,
9
+ "tag": "0000_items",
10
+ "breakpoints": true
11
+ }
12
+ ]
13
+ }
@@ -0,0 +1,16 @@
1
+ import { defineConfig } from 'drizzle-kit';
2
+
3
+ // `pnpm db:generate` writes a SQL migration from changes in src/db/schema.ts.
4
+ // The API applies pending migrations on startup (src/db/migrate.ts).
5
+ export default defineConfig({
6
+ dialect: 'postgresql',
7
+ schema: './src/db/schema.ts',
8
+ out: './drizzle',
9
+ casing: 'snake_case',
10
+ // Same table as the API's migrator.
11
+ migrations: { schema: 'public', table: '__drizzle_migrations___id__' },
12
+ // Core and other plugins share the database: drizzle-kit must never see their tables.
13
+ tablesFilter: ['__id___*'],
14
+ strict: true,
15
+ verbose: true,
16
+ });
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@__id__/api",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "files": [
6
+ "dist",
7
+ "drizzle",
8
+ "src"
9
+ ],
10
+ "type": "module",
11
+ "imports": {
12
+ "#/*": "./src/*"
13
+ },
14
+ "exports": "./src/router.ts",
15
+ "scripts": {
16
+ "dev": "node --env-file-if-exists=../.env --import ./src/telemetry.ts --watch-path=src src/main.ts",
17
+ "build": "vp pack src/main.ts src/telemetry.ts --format esm --sourcemap --no-dts",
18
+ "start": "node --enable-source-maps --import ./dist/telemetry.mjs dist/main.mjs",
19
+ "db:generate": "drizzle-kit generate",
20
+ "db:migrate": "node --env-file-if-exists=../.env src/migrate.ts",
21
+ "db:check": "drizzle-kit check"
22
+ },
23
+ "dependencies": {
24
+ "@erxes/core-contract": "0.1.0-v2.2",
25
+ "@erxes/plugin-sdk": "0.1.0-v2.2",
26
+ "@opentelemetry/instrumentation-express": "^0.73.0",
27
+ "@opentelemetry/instrumentation-http": "^0.301.1",
28
+ "@opentelemetry/instrumentation-pg": "^0.78.0",
29
+ "@opentelemetry/instrumentation-pino": "^0.71.0",
30
+ "@opentelemetry/sdk-node": "^0.301.1",
31
+ "@orpc/server": "1.16.2",
32
+ "cors": "^2.8.6",
33
+ "drizzle-orm": "0.45.4",
34
+ "express": "^5.3.0",
35
+ "import-in-the-middle": "^3.6.0",
36
+ "pg": "^8.23.1",
37
+ "pino": "^10.4.0",
38
+ "pino-http": "^11.0.0",
39
+ "zod": "^4.6.7"
40
+ },
41
+ "devDependencies": {
42
+ "@types/cors": "^2.8.19",
43
+ "@types/express": "^5.0.6",
44
+ "@types/pg": "^8.23.1",
45
+ "drizzle-kit": "0.31.11"
46
+ }
47
+ }
@@ -0,0 +1,51 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
2
+ import { config } from '#/config.ts';
3
+ import { createApp } from '#/server.ts';
4
+
5
+ let base = '';
6
+ let server: ReturnType<ReturnType<typeof createApp>['listen']>;
7
+
8
+ beforeAll(async () => {
9
+ await new Promise<void>((resolve) => {
10
+ server = createApp().listen(0, () => resolve());
11
+ });
12
+
13
+ const address = server.address();
14
+
15
+ if (!address || typeof address === 'string') throw new Error('not listening on a port');
16
+
17
+ base = `http://127.0.0.1:${address.port}`;
18
+ });
19
+
20
+ afterAll(() => {
21
+ server.close();
22
+ });
23
+
24
+ describe('server', () => {
25
+ it('answers health checks', async () => {
26
+ expect((await fetch(`${base}/health`)).status).toBe(200);
27
+ });
28
+
29
+ it('refuses procedures without a valid session token', async () => {
30
+ const url = `${base}/api/rpc/items/list`;
31
+
32
+ expect((await fetch(url, { method: 'POST' })).status).toBe(401);
33
+ expect(
34
+ (await fetch(url, { method: 'POST', headers: { authorization: 'Bearer forged' } })).status,
35
+ ).toBe(401);
36
+ });
37
+
38
+ it('lets web call it from the browser', async () => {
39
+ const response = await fetch(`${base}/api/rpc/items/list`, {
40
+ method: 'OPTIONS',
41
+ headers: {
42
+ origin: config.coreUiOrigin,
43
+ 'access-control-request-method': 'POST',
44
+ 'access-control-request-headers': 'authorization,content-type',
45
+ },
46
+ });
47
+
48
+ expect(response.headers.get('access-control-allow-origin')).toBe(config.coreUiOrigin);
49
+ expect(response.headers.get('access-control-allow-headers')).toContain('authorization');
50
+ });
51
+ });
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+
3
+ /** The plugin's name in core: tables, permissions, events and the UI remote all start with it. */
4
+ export const PLUGIN = '__id__';
5
+
6
+ /** Every setting the API reads. Nothing else touches `process.env`. */
7
+ const Env = z.object({
8
+ PORT: z.coerce.number().int().positive().default(__apiPort__),
9
+ /** Postgres as the plugin's own role (`pnpm db:plugin-role __id__` in core). */
10
+ DATA_URL: z.url(),
11
+ /** Core's address, without `/core/v1`. */
12
+ CORE_URL: z.url(),
13
+ /** This plugin's secret from core's `CORE_PLUGIN_KEYS`. */
14
+ PLUGIN_SECRET: z.string().min(32),
15
+ /** Where core and browsers reach this API. */
16
+ PUBLIC_URL: z.url().default('http://localhost:__apiPort__'),
17
+ /** The UI remote's entry; the built UI is served at `/ui` unless this points elsewhere. */
18
+ UI_ENTRY_URL: z.url().optional(),
19
+ /** The built UI to serve at `/ui` (the image sets it). */
20
+ UI_DIR: z.string().optional(),
21
+ /** web's origin, which calls this API from the browser. Defaults to CORE_URL's origin. */
22
+ CORE_UI_URL: z.url().optional(),
23
+ LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),
24
+ VERSION: z.string().default('0.1.0'),
25
+ /** Traces go to this OTLP collector; the SDK reads the other OTEL_* variables itself. */
26
+ OTEL_EXPORTER_OTLP_ENDPOINT: z.url().optional(),
27
+ });
28
+
29
+ const env = Env.parse(process.env);
30
+
31
+ export const config = {
32
+ port: env.PORT,
33
+ dataUrl: env.DATA_URL,
34
+ coreUrl: env.CORE_URL,
35
+ pluginSecret: env.PLUGIN_SECRET,
36
+ publicUrl: env.PUBLIC_URL.replace(/\/+$/, ''),
37
+ uiEntryUrl: env.UI_ENTRY_URL ?? `${env.PUBLIC_URL.replace(/\/+$/, '')}/ui/remoteEntry.js`,
38
+ uiDir: env.UI_DIR,
39
+ coreUiOrigin: new URL(env.CORE_UI_URL ?? env.CORE_URL).origin,
40
+ logLevel: env.LOG_LEVEL,
41
+ version: env.VERSION,
42
+ tracing: Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT),
43
+ };
@@ -0,0 +1,37 @@
1
+ import type { PluginManifest } from '@erxes/core-contract';
2
+ import { createCoreClient } from '@erxes/plugin-sdk';
3
+ import { config, PLUGIN } from '#/config.ts';
4
+
5
+ /**
6
+ * Core, called as this plugin: `core.forOrg(orgId).customers.get({ id })`.
7
+ * Tokens last 15 minutes and carry the scopes the organisation granted.
8
+ * Call core from the API only, outside request transactions.
9
+ */
10
+ export const core = createCoreClient({
11
+ coreUrl: config.coreUrl,
12
+ plugin: PLUGIN,
13
+ clientSecret: config.pluginSecret,
14
+ });
15
+
16
+ /** The actions members can be granted in core's roles. */
17
+ export const PERMISSIONS = {
18
+ view: '__id__.item.view',
19
+ manage: '__id__.item.manage',
20
+ } as const;
21
+
22
+ /**
23
+ * What the plugin adds to core, sent on every start. Everything it names
24
+ * starts with `__id__.`. A new scope waits for the owner's approval.
25
+ */
26
+ export const manifest = {
27
+ title: '__title__',
28
+ description: '__description__',
29
+ version: config.version,
30
+ ui: { remote: '__id___ui', entry: config.uiEntryUrl },
31
+ api: { url: `${config.publicUrl}/api` },
32
+ scopes: [],
33
+ permissions: [
34
+ { action: PERMISSIONS.view, label: 'View items', group: '__title__' },
35
+ { action: PERMISSIONS.manage, label: 'Create and change items', group: '__title__' },
36
+ ],
37
+ } satisfies PluginManifest;
@@ -0,0 +1,30 @@
1
+ import { DrizzleQueryError, sql } from 'drizzle-orm';
2
+ import { drizzle } from 'drizzle-orm/node-postgres';
3
+ import { DatabaseError, Pool } from 'pg';
4
+ import { config, PLUGIN } from '#/config.ts';
5
+ import * as schema from './schema.ts';
6
+
7
+ export const pool = new Pool({ connectionString: config.dataUrl, application_name: PLUGIN });
8
+
9
+ export const db = drizzle({ client: pool, schema, casing: 'snake_case' });
10
+
11
+ export type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
12
+
13
+ /** The unique index a failed write hit (Postgres 23505), or undefined for any other error. */
14
+ export const uniqueViolation = (error: unknown) => {
15
+ const cause = error instanceof DrizzleQueryError ? error.cause : error;
16
+
17
+ return cause instanceof DatabaseError && cause.code === '23505' ? cause.constraint : undefined;
18
+ };
19
+
20
+ /**
21
+ * Runs `fn` in a transaction scoped to one organisation. Row-level security
22
+ * shows and accepts only that organisation's rows, so queries carry no org
23
+ * filter, and every query that touches a table goes through here.
24
+ */
25
+ export const withOrg = <T>(orgId: string, fn: (tx: Tx) => Promise<T>) =>
26
+ db.transaction(async (tx) => {
27
+ await tx.execute(sql`select set_config('app.org_id', ${orgId}, true)`);
28
+
29
+ return fn(tx);
30
+ });
@@ -0,0 +1,80 @@
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 } 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
+ };
@@ -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 });