cogens 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +25 -0
  4. package/README.md +394 -2
  5. package/dist/admin/app.d.ts +21 -0
  6. package/dist/admin/app.d.ts.map +1 -0
  7. package/dist/admin/app.js +561 -0
  8. package/dist/admin/app.js.map +1 -0
  9. package/dist/admin/assets.d.ts +17 -0
  10. package/dist/admin/assets.d.ts.map +1 -0
  11. package/dist/admin/assets.js +51 -0
  12. package/dist/admin/assets.js.map +1 -0
  13. package/dist/admin/fields.d.ts +27 -0
  14. package/dist/admin/fields.d.ts.map +1 -0
  15. package/dist/admin/fields.js +128 -0
  16. package/dist/admin/fields.js.map +1 -0
  17. package/dist/admin/forms.d.ts +18 -0
  18. package/dist/admin/forms.d.ts.map +1 -0
  19. package/dist/admin/forms.js +53 -0
  20. package/dist/admin/forms.js.map +1 -0
  21. package/dist/admin/index.d.ts +15 -0
  22. package/dist/admin/index.d.ts.map +1 -0
  23. package/dist/admin/index.js +13 -0
  24. package/dist/admin/index.js.map +1 -0
  25. package/dist/admin/rules.d.ts +24 -0
  26. package/dist/admin/rules.d.ts.map +1 -0
  27. package/dist/admin/rules.js +51 -0
  28. package/dist/admin/rules.js.map +1 -0
  29. package/dist/admin/types.d.ts +96 -0
  30. package/dist/admin/types.d.ts.map +1 -0
  31. package/dist/admin/types.js +2 -0
  32. package/dist/admin/types.js.map +1 -0
  33. package/dist/admin/views.d.ts +109 -0
  34. package/dist/admin/views.d.ts.map +1 -0
  35. package/dist/admin/views.js +202 -0
  36. package/dist/admin/views.js.map +1 -0
  37. package/dist/auth/handoff.d.ts +27 -0
  38. package/dist/auth/handoff.d.ts.map +1 -0
  39. package/dist/auth/handoff.js +41 -0
  40. package/dist/auth/handoff.js.map +1 -0
  41. package/dist/auth/index.d.ts +10 -0
  42. package/dist/auth/index.d.ts.map +1 -0
  43. package/dist/auth/index.js +10 -0
  44. package/dist/auth/index.js.map +1 -0
  45. package/dist/auth/password.d.ts +48 -0
  46. package/dist/auth/password.d.ts.map +1 -0
  47. package/dist/auth/password.js +154 -0
  48. package/dist/auth/password.js.map +1 -0
  49. package/dist/auth/principal.d.ts +30 -0
  50. package/dist/auth/principal.d.ts.map +1 -0
  51. package/dist/auth/principal.js +30 -0
  52. package/dist/auth/principal.js.map +1 -0
  53. package/dist/auth/session.d.ts +68 -0
  54. package/dist/auth/session.d.ts.map +1 -0
  55. package/dist/auth/session.js +92 -0
  56. package/dist/auth/session.js.map +1 -0
  57. package/dist/core/access/ability.d.ts +24 -0
  58. package/dist/core/access/ability.d.ts.map +1 -0
  59. package/dist/core/access/ability.js +64 -0
  60. package/dist/core/access/ability.js.map +1 -0
  61. package/dist/core/access/can.d.ts +41 -0
  62. package/dist/core/access/can.d.ts.map +1 -0
  63. package/dist/core/access/can.js +38 -0
  64. package/dist/core/access/can.js.map +1 -0
  65. package/dist/core/access/compile.d.ts +12 -0
  66. package/dist/core/access/compile.d.ts.map +1 -0
  67. package/dist/core/access/compile.js +53 -0
  68. package/dist/core/access/compile.js.map +1 -0
  69. package/dist/core/access/permits.d.ts +24 -0
  70. package/dist/core/access/permits.d.ts.map +1 -0
  71. package/dist/core/access/permits.js +29 -0
  72. package/dist/core/access/permits.js.map +1 -0
  73. package/dist/core/access/when.d.ts +6 -0
  74. package/dist/core/access/when.d.ts.map +1 -0
  75. package/dist/core/access/when.js +64 -0
  76. package/dist/core/access/when.js.map +1 -0
  77. package/dist/core/access/where.d.ts +25 -0
  78. package/dist/core/access/where.d.ts.map +1 -0
  79. package/dist/core/access/where.js +81 -0
  80. package/dist/core/access/where.js.map +1 -0
  81. package/dist/core/columns.d.ts +6 -0
  82. package/dist/core/columns.d.ts.map +1 -0
  83. package/dist/core/columns.js +6 -0
  84. package/dist/core/columns.js.map +1 -0
  85. package/dist/core/config/define.d.ts +101 -0
  86. package/dist/core/config/define.d.ts.map +1 -0
  87. package/dist/core/config/define.js +97 -0
  88. package/dist/core/config/define.js.map +1 -0
  89. package/dist/core/config/field.d.ts +71 -0
  90. package/dist/core/config/field.d.ts.map +1 -0
  91. package/dist/core/config/field.js +64 -0
  92. package/dist/core/config/field.js.map +1 -0
  93. package/dist/core/errors.d.ts +66 -0
  94. package/dist/core/errors.d.ts.map +1 -0
  95. package/dist/core/errors.js +94 -0
  96. package/dist/core/errors.js.map +1 -0
  97. package/dist/core/index.d.ts +31 -0
  98. package/dist/core/index.d.ts.map +1 -0
  99. package/dist/core/index.js +20 -0
  100. package/dist/core/index.js.map +1 -0
  101. package/dist/core/media/index.d.ts +36 -0
  102. package/dist/core/media/index.d.ts.map +1 -0
  103. package/dist/core/media/index.js +99 -0
  104. package/dist/core/media/index.js.map +1 -0
  105. package/dist/core/principal.d.ts +28 -0
  106. package/dist/core/principal.d.ts.map +1 -0
  107. package/dist/core/principal.js +25 -0
  108. package/dist/core/principal.js.map +1 -0
  109. package/dist/core/store/assets.d.ts +3 -0
  110. package/dist/core/store/assets.d.ts.map +1 -0
  111. package/dist/core/store/assets.js +3 -0
  112. package/dist/core/store/assets.js.map +1 -0
  113. package/dist/core/store/cms.d.ts +53 -0
  114. package/dist/core/store/cms.d.ts.map +1 -0
  115. package/dist/core/store/cms.js +154 -0
  116. package/dist/core/store/cms.js.map +1 -0
  117. package/dist/core/store/content.d.ts +57 -0
  118. package/dist/core/store/content.d.ts.map +1 -0
  119. package/dist/core/store/content.js +455 -0
  120. package/dist/core/store/content.js.map +1 -0
  121. package/dist/core/store/sql.d.ts +88 -0
  122. package/dist/core/store/sql.d.ts.map +1 -0
  123. package/dist/core/store/sql.js +149 -0
  124. package/dist/core/store/sql.js.map +1 -0
  125. package/dist/core/store/types.d.ts +107 -0
  126. package/dist/core/store/types.d.ts.map +1 -0
  127. package/dist/core/store/types.js +2 -0
  128. package/dist/core/store/types.js.map +1 -0
  129. package/dist/core/testing/index.d.ts +27 -0
  130. package/dist/core/testing/index.d.ts.map +1 -0
  131. package/dist/core/testing/index.js +60 -0
  132. package/dist/core/testing/index.js.map +1 -0
  133. package/dist/migrations-tool/bin.d.ts +3 -0
  134. package/dist/migrations-tool/bin.d.ts.map +1 -0
  135. package/dist/migrations-tool/bin.js +40 -0
  136. package/dist/migrations-tool/bin.js.map +1 -0
  137. package/dist/migrations-tool/index.d.ts +16 -0
  138. package/dist/migrations-tool/index.d.ts.map +1 -0
  139. package/dist/migrations-tool/index.js +24 -0
  140. package/dist/migrations-tool/index.js.map +1 -0
  141. package/dist/testing/db.d.ts +16 -0
  142. package/dist/testing/db.d.ts.map +1 -0
  143. package/dist/testing/db.js +43 -0
  144. package/dist/testing/db.js.map +1 -0
  145. package/dist/testing/index.d.ts +10 -0
  146. package/dist/testing/index.d.ts.map +1 -0
  147. package/dist/testing/index.js +8 -0
  148. package/dist/testing/index.js.map +1 -0
  149. package/editor/editor-dark.css +2 -0
  150. package/editor/editor.css +9 -0
  151. package/editor/entry.js +28 -0
  152. package/migrations/0001_entries.sql +43 -0
  153. package/migrations/auth/0001_sessions.sql +50 -0
  154. package/migrations/koguma-upgrade.sql +13 -0
  155. package/package.json +108 -4
  156. package/scripts/build-admin-editor.ts +155 -0
  157. package/src/admin/app.ts +608 -0
  158. package/src/admin/assets.ts +52 -0
  159. package/src/admin/fields.ts +172 -0
  160. package/src/admin/forms.ts +64 -0
  161. package/src/admin/index.ts +16 -0
  162. package/src/admin/rules.ts +63 -0
  163. package/src/admin/types.ts +99 -0
  164. package/src/admin/views.ts +360 -0
  165. package/src/auth/handoff.ts +56 -0
  166. package/src/auth/index.ts +29 -0
  167. package/src/auth/password.ts +201 -0
  168. package/src/auth/principal.ts +40 -0
  169. package/src/auth/session.ts +143 -0
  170. package/src/core/access/ability.ts +86 -0
  171. package/src/core/access/can.ts +66 -0
  172. package/src/core/access/compile.ts +62 -0
  173. package/src/core/access/permits.ts +45 -0
  174. package/src/core/access/when.ts +59 -0
  175. package/src/core/access/where.ts +95 -0
  176. package/src/core/columns.ts +7 -0
  177. package/src/core/config/define.ts +206 -0
  178. package/src/core/config/field.ts +119 -0
  179. package/src/core/errors.ts +99 -0
  180. package/src/core/index.ts +44 -0
  181. package/src/core/media/index.ts +132 -0
  182. package/src/core/principal.ts +49 -0
  183. package/src/core/store/assets.ts +2 -0
  184. package/src/core/store/cms.ts +199 -0
  185. package/src/core/store/content.ts +453 -0
  186. package/src/core/store/sql.ts +239 -0
  187. package/src/core/store/types.ts +100 -0
  188. package/src/core/testing/index.ts +75 -0
  189. package/src/migrations-tool/bin.ts +34 -0
  190. package/src/migrations-tool/index.ts +37 -0
  191. package/src/testing/db.ts +53 -0
  192. package/src/testing/index.ts +9 -0
@@ -0,0 +1,28 @@
1
+ // The markdown editor of the content admin: Milkdown's Crepe with the features a text
2
+ // field needs, built by scripts/build-admin-editor.ts. The admin's own script (src/admin/assets.ts)
3
+ // loads this module on a page that has a markdown field and calls createEditor on each text area. Nothing in the Worker
4
+ // imports this file or @milkdown/crepe.
5
+ import { CrepeBuilder } from '@milkdown/crepe/builder';
6
+ import { blockEdit } from '@milkdown/crepe/feature/block-edit';
7
+ import { cursor } from '@milkdown/crepe/feature/cursor';
8
+ import { linkTooltip } from '@milkdown/crepe/feature/link-tooltip';
9
+ import { listItem } from '@milkdown/crepe/feature/list-item';
10
+ import { toolbar } from '@milkdown/crepe/feature/toolbar';
11
+ // Resolved by scripts/build-admin-editor.ts: the host's plugin module given by --plugins, else a module with no default.
12
+ import plugin from 'cogens-editor-plugin';
13
+
14
+ /**
15
+ * Puts an editor in `root` holding `markdown`; `context` is `{ type, field }`, the content type id and field name of the
16
+ * text area, passed on to the host's plugin. Resolves to an object whose getMarkdown() is the text now. */
17
+ export async function createEditor(root, markdown, context = { type: '', field: '' }) {
18
+ const builder = new CrepeBuilder({ root, defaultValue: markdown })
19
+ .addFeature(blockEdit)
20
+ .addFeature(cursor)
21
+ .addFeature(linkTooltip)
22
+ .addFeature(listItem)
23
+ .addFeature(toolbar);
24
+ // The host's own syntax, if it gave a plugin module: called with the builder and the field's context before it is created.
25
+ if (typeof plugin === 'function') await plugin(builder, context);
26
+ await builder.create();
27
+ return { getMarkdown: () => builder.getMarkdown(), editor: builder.editor };
28
+ }
@@ -0,0 +1,43 @@
1
+ -- cogens: the content store's tables. Apply this first on a new database.
2
+ --
3
+ -- `entries` holds every content type's rows (the fields as JSON in `data`) and
4
+ -- `assets` the media rows. The first nine columns of `entries` are Koguma's own;
5
+ -- the last four are cogens's:
6
+ -- owner_id who owns the row. The store compares it and gives it no other meaning.
7
+ -- parent_id the entry this one belongs to (a type that names a `parent`).
8
+ -- sort_key orders children under a parent.
9
+ -- parent_status the parent's status, written by the store for types that mirror it
10
+ -- (a generated column cannot read another row).
11
+ -- A host whose database already holds Koguma's `entries` (its 0001) applies
12
+ -- koguma-upgrade.sql instead of this file.
13
+ --
14
+ -- Indexed fields of your types are not here: they are columns generated from
15
+ -- the entry's JSON, and `bun run print-migration <config>` prints their lines.
16
+
17
+ CREATE TABLE IF NOT EXISTS entries (
18
+ id TEXT PRIMARY KEY,
19
+ content_type TEXT NOT NULL,
20
+ slug TEXT,
21
+ data TEXT NOT NULL,
22
+ status TEXT NOT NULL DEFAULT 'draft',
23
+ publish_at TEXT,
24
+ created_at TEXT DEFAULT (datetime('now')),
25
+ updated_at TEXT DEFAULT (datetime('now')),
26
+ owner_id TEXT,
27
+ parent_id TEXT,
28
+ sort_key TEXT,
29
+ parent_status TEXT
30
+ );
31
+ CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(content_type);
32
+ CREATE INDEX IF NOT EXISTS idx_entries_slug ON entries(content_type, slug);
33
+ CREATE INDEX IF NOT EXISTS idx_entries_owner ON entries(owner_id, content_type);
34
+ CREATE INDEX IF NOT EXISTS idx_entries_parent ON entries(content_type, parent_id, sort_key);
35
+
36
+ CREATE TABLE IF NOT EXISTS assets (
37
+ id TEXT PRIMARY KEY,
38
+ data TEXT NOT NULL,
39
+ created_at TEXT DEFAULT (datetime('now')),
40
+ updated_at TEXT DEFAULT (datetime('now')),
41
+ owner_id TEXT
42
+ );
43
+ CREATE INDEX IF NOT EXISTS idx_assets_owner ON assets(owner_id);
@@ -0,0 +1,50 @@
1
+ -- cogens/auth: the tables of sessions, handoff tokens, identities and the
2
+ -- password sign-in. Needed only by a host that imports `cogens/auth`;
3
+ -- independent of 0001_entries.sql.
4
+
5
+ -- Sessions: a row behind each signed cookie. kind is who the session is for
6
+ -- ('admin', or the host's own); method is how it was made ('password', 'handoff',
7
+ -- later a provider); owner_id is null for the operator. created_at and
8
+ -- expires_at are milliseconds since the epoch.
9
+ CREATE TABLE IF NOT EXISTS sessions (
10
+ id TEXT PRIMARY KEY,
11
+ owner_id TEXT,
12
+ kind TEXT NOT NULL,
13
+ method TEXT NOT NULL,
14
+ created_at INTEGER NOT NULL,
15
+ expires_at INTEGER NOT NULL
16
+ );
17
+ CREATE INDEX IF NOT EXISTS idx_sessions_owner ON sessions(owner_id);
18
+ CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
19
+
20
+ -- One-time handoff tokens: only the SHA-256 of the token is kept, and an exchange
21
+ -- deletes the row (DELETE ... RETURNING), so a token is used once. expires_at is
22
+ -- milliseconds since the epoch.
23
+ CREATE TABLE IF NOT EXISTS handoff_tokens (
24
+ token_hash TEXT PRIMARY KEY,
25
+ owner_id TEXT NOT NULL,
26
+ expires_at INTEGER NOT NULL
27
+ );
28
+ CREATE INDEX IF NOT EXISTS idx_handoff_expires ON handoff_tokens(expires_at);
29
+
30
+ -- Who an owner is at a sign-in provider; empty until a provider is added.
31
+ CREATE TABLE IF NOT EXISTS identities (
32
+ provider TEXT NOT NULL,
33
+ subject TEXT NOT NULL,
34
+ owner_id TEXT NOT NULL,
35
+ created_at INTEGER NOT NULL DEFAULT 0,
36
+ UNIQUE (provider, subject)
37
+ );
38
+ CREATE INDEX IF NOT EXISTS idx_identities_owner ON identities(owner_id);
39
+
40
+ -- The password sign-in's rate limit and its meta values.
41
+ CREATE TABLE IF NOT EXISTS auth_attempts (
42
+ ip TEXT NOT NULL,
43
+ attempted_at TEXT NOT NULL DEFAULT (datetime('now'))
44
+ );
45
+ CREATE INDEX IF NOT EXISTS idx_auth_attempts ON auth_attempts(ip, attempted_at);
46
+
47
+ CREATE TABLE IF NOT EXISTS auth_meta (
48
+ key TEXT PRIMARY KEY,
49
+ value TEXT NOT NULL
50
+ );
@@ -0,0 +1,13 @@
1
+ -- cogens: for a database that already holds Koguma's `entries` and `assets`
2
+ -- (Koguma's 0001) and not 0001_entries.sql. Adds the ownership columns and
3
+ -- indexes. Run it once: ADD COLUMN fails on a column that is there, which is how
4
+ -- you learn it was already applied.
5
+
6
+ ALTER TABLE entries ADD COLUMN owner_id TEXT;
7
+ ALTER TABLE entries ADD COLUMN parent_id TEXT;
8
+ ALTER TABLE entries ADD COLUMN sort_key TEXT;
9
+ ALTER TABLE entries ADD COLUMN parent_status TEXT;
10
+ ALTER TABLE assets ADD COLUMN owner_id TEXT;
11
+ CREATE INDEX IF NOT EXISTS idx_entries_owner ON entries(owner_id, content_type);
12
+ CREATE INDEX IF NOT EXISTS idx_entries_parent ON entries(content_type, parent_id, sort_key);
13
+ CREATE INDEX IF NOT EXISTS idx_assets_owner ON assets(owner_id);
package/package.json CHANGED
@@ -1,6 +1,110 @@
1
1
  {
2
2
  "name": "cogens",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "A light multi-tenant content store for Cloudflare Workers: every entry may have an owner and every query passes an access check. Forked from Koguma.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "author": "Vikram Rojo",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vikramrojo/cogens.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/vikramrojo/cogens/issues"
14
+ },
15
+ "homepage": "https://github.com/vikramrojo/cogens#readme",
16
+ "keywords": [
17
+ "cms",
18
+ "cloudflare",
19
+ "workers",
20
+ "d1",
21
+ "hono",
22
+ "multi-tenant",
23
+ "access-control",
24
+ "casl",
25
+ "content-store"
26
+ ],
27
+ "engines": {
28
+ "node": ">=20",
29
+ "bun": ">=1.4.4"
30
+ },
31
+ "packageManager": "bun@1.4.4",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/core/index.d.ts",
35
+ "default": "./dist/core/index.js"
36
+ },
37
+ "./admin": {
38
+ "types": "./dist/admin/index.d.ts",
39
+ "default": "./dist/admin/index.js"
40
+ },
41
+ "./auth": {
42
+ "types": "./dist/auth/index.d.ts",
43
+ "default": "./dist/auth/index.js"
44
+ },
45
+ "./testing": {
46
+ "types": "./dist/testing/index.d.ts",
47
+ "default": "./dist/testing/index.js"
48
+ },
49
+ "./migrations-tool": {
50
+ "types": "./dist/migrations-tool/index.d.ts",
51
+ "default": "./dist/migrations-tool/index.js"
52
+ },
53
+ "./scripts/*": "./scripts/*",
54
+ "./package.json": "./package.json",
55
+ "./migrations/*": "./migrations/*"
56
+ },
57
+ "bin": {
58
+ "cogens-print-migration": "./dist/migrations-tool/bin.js"
59
+ },
60
+ "files": [
61
+ "dist",
62
+ "src",
63
+ "migrations",
64
+ "scripts",
65
+ "editor",
66
+ "LICENSE",
67
+ "NOTICE",
68
+ "README.md",
69
+ "CHANGELOG.md"
70
+ ],
71
+ "scripts": {
72
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
73
+ "test": "bun run build && bun test",
74
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.scripts.json",
75
+ "print-migration": "bun run src/migrations-tool/bin.ts",
76
+ "build:editor": "bun run scripts/build-admin-editor.ts",
77
+ "prepublishOnly": "bun run build && bun test",
78
+ "example:migrate": "wrangler d1 migrations apply DB --local -c examples/worker/wrangler.jsonc",
79
+ "example:dev": "wrangler dev -c examples/worker/wrangler.jsonc"
80
+ },
81
+ "dependencies": {
82
+ "@casl/ability": "7.1.3",
83
+ "@cfworker/json-schema": "^4.1.1",
84
+ "hono": "~4.12.2"
85
+ },
86
+ "peerDependencies": {
87
+ "@milkdown/crepe": "^7.23.0",
88
+ "miniflare": "^4.20260301.1"
89
+ },
90
+ "peerDependenciesMeta": {
91
+ "miniflare": {
92
+ "optional": true
93
+ },
94
+ "@milkdown/crepe": {
95
+ "optional": true
96
+ }
97
+ },
98
+ "devDependencies": {
99
+ "@cloudflare/workers-types": "^4.20260304.0",
100
+ "@milkdown/crepe": "^7.23.0",
101
+ "@types/bun": "^1.3.0",
102
+ "@types/node": "^22.0.0",
103
+ "miniflare": "^4.20260301.1",
104
+ "remark-directive": "^4.0.0",
105
+ "typescript": "^5.7.0",
106
+ "wrangler": "^4.71.0"
107
+ },
108
+ "main": "./dist/core/index.js",
109
+ "types": "./dist/core/index.d.ts"
110
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Builds the admin's markdown editor (Milkdown Crepe, as one static module) and
3
+ * writes it where the host serves its static files:
4
+ *
5
+ * bun run node_modules/cogens/scripts/build-admin-editor.ts <outDir> [--plugins <module>]
6
+ *
7
+ * writes <outDir>/admin-editor.js, admin-editor.css, admin-editor-dark.css and
8
+ * admin-editor.LICENSES.txt (the licence texts of every package in the bundle,
9
+ * which the module's banner names). Those are the names `createAdmin` links by
10
+ * default (`DEFAULT_ASSETS`), at the root of the host's static folder; serve
11
+ * them elsewhere and pass `assets` to `createAdmin`.
12
+ *
13
+ * `--plugins <module>` names a host file whose default export is a function
14
+ * `(builder, context) => void | Promise<void>`. The bundle calls it with the
15
+ * Crepe builder (`builder.editor` is the Milkdown editor) and `context = { type, field }`
16
+ * (the content type id and field name of the text area) before the editor is
17
+ * created, and the path resolves from the current working directory, so the host can add remark plugins, nodes and node views. The
18
+ * module imports its own Milkdown packages from the host's node_modules.
19
+ * Without it the editor has no syntax of the host's.
20
+ *
21
+ * The build needs `@milkdown/crepe`, an optional peer dependency of cogens:
22
+ * add it to the host (`bun add -d @milkdown/crepe`). Nothing in the Worker
23
+ * imports the editor or Crepe.
24
+ */
25
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
26
+ import { tmpdir } from 'node:os';
27
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
28
+
29
+ const HERE = join(import.meta.dir, '..', 'editor');
30
+
31
+ /** The package folder an input path belongs to: the part up to the last `node_modules/<name>` (or `<@scope/name>`). */
32
+ function packageRoot(input: string): string | null {
33
+ const marker = 'node_modules/';
34
+ const at = input.lastIndexOf(marker);
35
+ if (at < 0) return null;
36
+ const rest = input.slice(at + marker.length).split('/');
37
+ const name = rest[0]!.startsWith('@') ? `${rest[0]}/${rest[1]}` : rest[0]!;
38
+ return input.slice(0, at + marker.length) + name;
39
+ }
40
+
41
+ const PLUGIN_MODULE = 'cogens-editor-plugin';
42
+
43
+ /** Resolves the entry's `cogens-editor-plugin` import to the host's module, or to an empty one. */
44
+ function pluginResolver(plugin: string | null): Bun.BunPlugin {
45
+ return {
46
+ name: 'cogens-editor-plugin',
47
+ setup(build) {
48
+ build.onResolve({ filter: /^cogens-editor-plugin$/ }, () =>
49
+ plugin ? { path: plugin } : { path: PLUGIN_MODULE, namespace: 'cogens-empty' });
50
+ build.onLoad({ filter: /.*/, namespace: 'cogens-empty' }, () => ({ contents: 'export default undefined;', loader: 'js' }));
51
+ }
52
+ };
53
+ }
54
+
55
+ type Notice = { name: string; version: string; license: string; text: string };
56
+
57
+ async function notices(entries: string[], out: string, plugin: string | null): Promise<void> {
58
+ const roots = new Set<string>();
59
+ for (const entry of entries) {
60
+ const result = await Bun.build({ entrypoints: [entry], target: 'browser', minify: true, metafile: true, plugins: [pluginResolver(plugin)] });
61
+ if (!result.success || !result.metafile) throw new Error(`Could not bundle ${entry}: ${result.logs.join('\n')}`);
62
+ for (const input of Object.keys(result.metafile.inputs)) {
63
+ const root = packageRoot(isAbsolute(input) ? input : resolve(process.cwd(), input));
64
+ if (root) roots.add(root);
65
+ }
66
+ }
67
+ const list: Notice[] = [];
68
+ for (const dir of roots) {
69
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { name: string; version: string; license?: string };
70
+ if (pkg.name === 'cogens') continue; // this package's own editor files, under the host's node_modules
71
+ const file = readdirSync(dir).find(f => /^(licen[sc]e|copying)(\.|$)/i.test(f));
72
+ if (!file) throw new Error(`${pkg.name} ${pkg.version} has no licence file in ${dir}; add its text here by hand before shipping.`);
73
+ list.push({ name: pkg.name, version: pkg.version, license: pkg.license ?? 'see text', text: readFileSync(join(dir, file), 'utf8').trim() });
74
+ }
75
+ list.sort((a, b) => a.name.localeCompare(b.name));
76
+ const header = [
77
+ 'Third-party notices for admin-editor.js, admin-editor.css and admin-editor-dark.css',
78
+ "(cogens's admin markdown editor, Milkdown Crepe and the packages it bundles).",
79
+ `${list.length} packages. Written by scripts/build-admin-editor.ts; do not edit by hand.`,
80
+ 'DOMPurify is dual-licensed MPL-2.0 or Apache-2.0 and is used here under Apache-2.0.'
81
+ ].join('\n');
82
+ const body = list.map(n => `${'='.repeat(78)}\n${n.name} ${n.version} (${n.license})\n${'='.repeat(78)}\n\n${n.text}\n`).join('\n');
83
+ writeFileSync(out, `${header}\n\n${body}`);
84
+ console.log(`${out}: ${list.length} packages`);
85
+ }
86
+
87
+ async function build(entry: string, outDir: string, name: string, options: Record<string, unknown>): Promise<void> {
88
+ const result = await Bun.build({ entrypoints: [entry], outdir: outDir, naming: name, minify: true, ...options });
89
+ if (!result.success) throw new Error(`Could not build ${name}:\n${result.logs.join('\n')}`);
90
+ }
91
+
92
+ /**
93
+ * The folder of `@milkdown/crepe` as the host installed it. Its style sheets are not in the package's `exports`, so a
94
+ * bare `@import` cannot name them; editor.css and editor-dark.css write `%CREPE%` and this puts the real folder there.
95
+ */
96
+ function crepeFolder(): string {
97
+ let dir = dirname(Bun.resolveSync('@milkdown/crepe', HERE));
98
+ while (!existsSync(join(dir, 'package.json')) || JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name !== '@milkdown/crepe') {
99
+ const up = dirname(dir);
100
+ if (up === dir) throw new Error('@milkdown/crepe is not installed. Add it: bun add -d @milkdown/crepe');
101
+ dir = up;
102
+ }
103
+ return dir;
104
+ }
105
+
106
+ /** A copy of one of the editor's style sheets with `%CREPE%` filled in, in a folder the caller removes. */
107
+ function stylesheet(name: string, scratch: string): string {
108
+ const out = join(scratch, name);
109
+ writeFileSync(out, readFileSync(join(HERE, name), 'utf8').replaceAll('%CREPE%', crepeFolder()));
110
+ return out;
111
+ }
112
+
113
+ const args = process.argv.slice(2);
114
+ const flag = args.indexOf('--plugins');
115
+ let pluginArg: string | null = null;
116
+ if (flag >= 0) {
117
+ pluginArg = args[flag + 1] ?? null;
118
+ if (!pluginArg) {
119
+ console.error('--plugins needs a module path.');
120
+ process.exit(1);
121
+ }
122
+ args.splice(flag, 2);
123
+ }
124
+ const outArg = args[0];
125
+ if (!outArg) {
126
+ console.error('Usage: bun run scripts/build-admin-editor.ts <outDir> [--plugins <module>]');
127
+ process.exit(1);
128
+ }
129
+ const plugin = pluginArg ? resolve(process.cwd(), pluginArg) : null;
130
+ if (plugin && !existsSync(plugin)) {
131
+ console.error(`Plugin module not found: ${plugin}`);
132
+ process.exit(1);
133
+ }
134
+ const out = resolve(process.cwd(), outArg);
135
+ mkdirSync(out, { recursive: true });
136
+
137
+ await build(join(HERE, 'entry.js'), out, 'admin-editor.js', {
138
+ format: 'esm',
139
+ target: 'browser',
140
+ banner: '/*! Third-party notices: /admin-editor.LICENSES.txt */',
141
+ plugins: [pluginResolver(plugin)]
142
+ });
143
+ const scratch = mkdtempSync(join(tmpdir(), 'cogens-editor-'));
144
+ try {
145
+ const light = stylesheet('editor.css', scratch);
146
+ const dark = stylesheet('editor-dark.css', scratch);
147
+ await build(light, out, 'admin-editor.css', {});
148
+ await build(dark, out, 'admin-editor-dark.css', {});
149
+ await notices([join(HERE, 'entry.js'), light, dark], join(out, 'admin-editor.LICENSES.txt'), plugin);
150
+ } finally {
151
+ rmSync(scratch, { recursive: true, force: true });
152
+ }
153
+ for (const f of ['admin-editor.js', 'admin-editor.css', 'admin-editor-dark.css', 'admin-editor.LICENSES.txt']) {
154
+ if (!existsSync(join(out, f))) throw new Error(`${f} was not written.`);
155
+ }