@guren/core 1.0.0 → 1.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.
package/dist/bin.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  #!/usr/bin/env bun
2
- import '@guren/server';
3
- import '@guren/orm';
4
2
  import '@guren/server/lambda';
5
3
  import '@guren/server/redis';
6
4
  import '@guren/server/runtime';
package/dist/index.d.ts CHANGED
@@ -1,2 +1,62 @@
1
+ import { ApiTokenStore, ApiToken } from '@guren/server';
1
2
  export * from '@guren/server';
2
3
  export { AccessorDefinitions, AccessorFn, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, CastType, DrizzleAdapter, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereOperator, WithRelations, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
4
+
5
+ /**
6
+ * Options for DatabaseApiTokenStore.
7
+ */
8
+ interface DatabaseApiTokenStoreOptions {
9
+ /**
10
+ * How the `abilities` column stores the ability list.
11
+ *
12
+ * - `'json'` (default) passes the array straight through — use with a
13
+ * JSON-capable column (pg `jsonb`/`json`, sqlite `text(..., { mode: 'json' })`).
14
+ * - `'text'` serializes to a JSON string for plain text columns.
15
+ *
16
+ * Reads always accept both representations.
17
+ * @default 'json'
18
+ */
19
+ abilitiesMode?: 'json' | 'text';
20
+ }
21
+ /**
22
+ * Database-backed API token store built on the Guren ORM.
23
+ *
24
+ * Pass the Drizzle table for your `api_tokens` schema. Column property
25
+ * names must match the {@link ApiToken} fields (`id`, `name`,
26
+ * `hashedToken`, `userId`, `abilities`, `lastUsedAt`, `expiresAt`,
27
+ * `createdAt`). The ORM must be configured (the standard
28
+ * `DatabaseProvider` setup) before the store is used.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { DatabaseApiTokenStore, createApiToken } from '@guren/core'
33
+ * import { apiTokens } from '@/db/schema'
34
+ *
35
+ * const store = new DatabaseApiTokenStore(apiTokens)
36
+ *
37
+ * const { plainTextToken } = await createApiToken(store, {
38
+ * name: 'Mobile App Token',
39
+ * userId: user.id,
40
+ * })
41
+ * ```
42
+ */
43
+ declare class DatabaseApiTokenStore implements ApiTokenStore {
44
+ private readonly model;
45
+ private readonly abilitiesMode;
46
+ constructor(table: unknown, options?: DatabaseApiTokenStoreOptions);
47
+ store(token: ApiToken): Promise<void>;
48
+ findByHashedToken(hashedToken: string): Promise<ApiToken | null>;
49
+ findByUserId(userId: string | number): Promise<ApiToken[]>;
50
+ delete(id: string): Promise<void>;
51
+ deleteForUser(userId: string | number): Promise<void>;
52
+ updateLastUsed(id: string, timestamp: Date): Promise<void>;
53
+ /**
54
+ * Delete tokens whose expiration time has passed. Expired tokens are
55
+ * already rejected by `verifyApiToken`; call this from a scheduled
56
+ * job to keep the table small.
57
+ */
58
+ deleteExpired(now?: Date): Promise<void>;
59
+ private deserialize;
60
+ }
61
+
62
+ export { DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/index.ts
2
2
  export * from "@guren/server";
3
3
  import {
4
- Model,
4
+ Model as Model2,
5
5
  defineModel,
6
6
  ModelNotFoundException,
7
7
  MassAssignmentException,
@@ -14,10 +14,77 @@ import {
14
14
  runSeeders,
15
15
  defineSeeder
16
16
  } from "@guren/orm";
17
+
18
+ // src/api-token-store.ts
19
+ import { Model } from "@guren/orm";
20
+ var DatabaseApiTokenStore = class {
21
+ model;
22
+ abilitiesMode;
23
+ constructor(table, options = {}) {
24
+ this.abilitiesMode = options.abilitiesMode ?? "json";
25
+ this.model = class ApiTokenModel extends Model {
26
+ static table = table;
27
+ };
28
+ }
29
+ async store(token) {
30
+ await this.model.forceCreate({
31
+ ...token,
32
+ abilities: this.abilitiesMode === "text" ? JSON.stringify(token.abilities) : token.abilities
33
+ });
34
+ }
35
+ async findByHashedToken(hashedToken) {
36
+ const record = await this.model.where({ hashedToken }).first();
37
+ return record ? this.deserialize(record) : null;
38
+ }
39
+ async findByUserId(userId) {
40
+ const records = await this.model.where({ userId }).get();
41
+ return records.map((record) => this.deserialize(record));
42
+ }
43
+ async delete(id) {
44
+ await this.model.where({ id }).delete();
45
+ }
46
+ async deleteForUser(userId) {
47
+ await this.model.where({ userId }).delete();
48
+ }
49
+ async updateLastUsed(id, timestamp) {
50
+ await this.model.forceUpdate({ id }, { lastUsedAt: timestamp });
51
+ }
52
+ /**
53
+ * Delete tokens whose expiration time has passed. Expired tokens are
54
+ * already rejected by `verifyApiToken`; call this from a scheduled
55
+ * job to keep the table small.
56
+ */
57
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
58
+ await this.model.where("expiresAt", "<", now).delete();
59
+ }
60
+ // Not replaceable with `static casts`: QueryBuilder reads (`where().first()/.get()`)
61
+ // bypass model casts, and cast-based writes would fight drizzle column modes
62
+ // (Date → ISO string breaks timestamp columns; json-stringify double-encodes jsonb).
63
+ deserialize(record) {
64
+ const abilities = record.abilities;
65
+ return {
66
+ id: String(record.id),
67
+ name: String(record.name),
68
+ hashedToken: String(record.hashedToken),
69
+ userId: typeof record.userId === "bigint" ? record.userId.toString() : record.userId,
70
+ abilities: typeof abilities === "string" ? JSON.parse(abilities) : abilities,
71
+ lastUsedAt: toDate(record.lastUsedAt),
72
+ expiresAt: toDate(record.expiresAt),
73
+ createdAt: toDate(record.createdAt) ?? /* @__PURE__ */ new Date(0)
74
+ };
75
+ }
76
+ };
77
+ function toDate(value) {
78
+ if (value == null) return null;
79
+ if (value instanceof Date) return value;
80
+ if (typeof value === "string" || typeof value === "number") return new Date(value);
81
+ return null;
82
+ }
17
83
  export {
84
+ DatabaseApiTokenStore,
18
85
  DrizzleAdapter,
19
86
  MassAssignmentException,
20
- Model,
87
+ Model2 as Model,
21
88
  ModelNotFoundException,
22
89
  QueryBuilder,
23
90
  SoftDeletes,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,12 +52,13 @@
52
52
  "typecheck": "tsc --noEmit"
53
53
  },
54
54
  "dependencies": {
55
- "@guren/cli": "^1.0.0",
55
+ "@guren/cli": "^1.2.0",
56
56
  "@guren/orm": "^1.0.0",
57
- "@guren/server": "^1.0.0"
57
+ "@guren/server": "^1.3.0"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "^20.14.10",
61
+ "drizzle-orm": "1.0.0-rc.4",
61
62
  "tsup": "^8.5.0",
62
63
  "typescript": "^5.4.0"
63
64
  }