express-file-cluster 0.3.13 → 0.3.14
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/auth/index.cjs +4 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +4 -2
- package/dist/auth/index.d.ts +4 -2
- package/dist/auth/index.js +3 -1
- package/dist/{chunk-QOKLEPTX.cjs → chunk-6522HS2J.cjs} +22 -3
- package/dist/chunk-6522HS2J.cjs.map +1 -0
- package/dist/{chunk-YE4ORV7Z.js → chunk-VIP3PFWZ.js} +20 -1
- package/dist/chunk-VIP3PFWZ.js.map +1 -0
- package/dist/cli/index.cjs +24 -3
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +24 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/index.cjs +96 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +91 -20
- package/dist/index.js.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/{types-CitLbYPp.d.cts → types-BusbSenn.d.cts} +44 -1
- package/dist/{types-CitLbYPp.d.ts → types-BusbSenn.d.ts} +44 -1
- package/package.json +1 -1
- package/dist/chunk-QOKLEPTX.cjs.map +0 -1
- package/dist/chunk-YE4ORV7Z.js.map +0 -1
|
@@ -76,10 +76,33 @@ interface TaskDefinition<TPayload = unknown> {
|
|
|
76
76
|
}
|
|
77
77
|
/** Primitive field types usable directly, or as the item type of an `array` field via `of`. */
|
|
78
78
|
type PrimitiveFieldType = 'string' | 'number' | 'boolean' | 'date' | 'object' | 'objectId';
|
|
79
|
+
/**
|
|
80
|
+
* Sentinel default-value codes, resolved at schema-compile time to a generator
|
|
81
|
+
* function so each document gets a freshly-computed value (never baked in once
|
|
82
|
+
* at schema-definition time):
|
|
83
|
+
* - `'$now'` — the current `Date` (pair with `type: 'date'`)
|
|
84
|
+
* - `'$uuid'` — a fresh `crypto.randomUUID()` string (pair with `type: 'string'`)
|
|
85
|
+
* - `'$objectId'` — a fresh Mongoose `ObjectId` (pair with `type: 'objectId'`)
|
|
86
|
+
* - `'$timestamp'` — the current epoch milliseconds as a `number` (pair with `type: 'number'`)
|
|
87
|
+
* - `'$shortId'` — a random 16-character base64url string (pair with `type: 'string'`);
|
|
88
|
+
* a shorter, non-UUID-shaped alternative to `'$uuid'` for tokens/keys
|
|
89
|
+
* - `'$currentUser'` — the JWT payload `requireAuth` attached to the in-flight request
|
|
90
|
+
* (via `getCurrentUser()`), or `undefined` outside a request / without `requireAuth`
|
|
91
|
+
* - `` `$currentUser.<key>` `` — a single field plucked from that payload, e.g.
|
|
92
|
+
* `'$currentUser.id'` (pair with a `type` matching that field's shape)
|
|
93
|
+
*
|
|
94
|
+
* `'$increment'` is intentionally NOT a `default` code — see `FieldDefinition.sequence`
|
|
95
|
+
* instead. Auto-increment needs an async read-modify-write against a counters
|
|
96
|
+
* collection; mongoose resolves `default` synchronously, so it can't live here.
|
|
97
|
+
*
|
|
98
|
+
* Any other string/value passed to `default` is used as a literal default, unchanged.
|
|
99
|
+
*/
|
|
100
|
+
type DefaultOperator = '$now' | '$uuid' | '$objectId' | '$timestamp' | '$shortId' | '$currentUser' | `$currentUser.${string}`;
|
|
79
101
|
interface FieldDefinition {
|
|
80
102
|
type: PrimitiveFieldType | 'array';
|
|
81
103
|
required?: boolean;
|
|
82
104
|
unique?: boolean;
|
|
105
|
+
/** A literal default value, or a `DefaultOperator` sentinel code (see above). */
|
|
83
106
|
default?: unknown;
|
|
84
107
|
/** Restricts the field to a fixed set of values. Valid on `string` and `number` types. */
|
|
85
108
|
enum?: readonly (string | number)[];
|
|
@@ -87,6 +110,14 @@ interface FieldDefinition {
|
|
|
87
110
|
ref?: string;
|
|
88
111
|
/** Item type for `array` fields, e.g. `{ type: 'array', of: 'string' }`. Omit for an untyped array. */
|
|
89
112
|
of?: PrimitiveFieldType;
|
|
113
|
+
/**
|
|
114
|
+
* Auto-increments a shared counter (stored in an internal `efc_counters` collection)
|
|
115
|
+
* and assigns it on insert, before `required` validation runs. `true` uses
|
|
116
|
+
* `'<ModelName>.<field>'` as the counter key; a string sets an explicit key so
|
|
117
|
+
* multiple fields/models can share one counter (e.g. a global order number).
|
|
118
|
+
* Only supported on top-level fields — not inside nested array sub-schemas.
|
|
119
|
+
*/
|
|
120
|
+
sequence?: boolean | string;
|
|
90
121
|
}
|
|
91
122
|
/**
|
|
92
123
|
* A schema field is either a `FieldDefinition`, or a one-element tuple holding a nested
|
|
@@ -98,6 +129,18 @@ interface ModelQueryOptions {
|
|
|
98
129
|
/** Mongoose `.populate()` path(s) to resolve on `objectId`/ref fields. */
|
|
99
130
|
populate?: string | string[];
|
|
100
131
|
}
|
|
132
|
+
interface ModelOptions {
|
|
133
|
+
/**
|
|
134
|
+
* Passed straight through to mongoose's own schema `timestamps` option.
|
|
135
|
+
* `true` (the default) adds `createdAt`/`updatedAt`; `false` disables both;
|
|
136
|
+
* an object lets you rename or selectively disable one, e.g.
|
|
137
|
+
* `{ createdAt: 'created_at', updatedAt: false }`.
|
|
138
|
+
*/
|
|
139
|
+
timestamps?: boolean | {
|
|
140
|
+
createdAt?: string | false;
|
|
141
|
+
updatedAt?: string | false;
|
|
142
|
+
};
|
|
143
|
+
}
|
|
101
144
|
interface ModelCRUD<T extends object> {
|
|
102
145
|
find(filter?: Partial<T>, options?: ModelQueryOptions): Promise<T[]>;
|
|
103
146
|
findById(id: string, options?: ModelQueryOptions): Promise<(T & {
|
|
@@ -116,4 +159,4 @@ interface ModelCRUD<T extends object> {
|
|
|
116
159
|
count(filter?: Partial<T>): Promise<number>;
|
|
117
160
|
}
|
|
118
161
|
|
|
119
|
-
export type { AuthStrategy as A, CorsConfig as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, ModelSchema as M, RouteEntry as R, TaskOptions as T, TaskDefinition as a,
|
|
162
|
+
export type { AuthStrategy as A, CorsConfig as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, ModelSchema as M, RouteEntry as R, TaskOptions as T, TaskDefinition as a, ModelOptions as b, ModelCRUD as c, DefaultOperator as d, ModelQueryOptions as e, RouteMeta as f, RouteMethodMeta as g };
|
|
@@ -76,10 +76,33 @@ interface TaskDefinition<TPayload = unknown> {
|
|
|
76
76
|
}
|
|
77
77
|
/** Primitive field types usable directly, or as the item type of an `array` field via `of`. */
|
|
78
78
|
type PrimitiveFieldType = 'string' | 'number' | 'boolean' | 'date' | 'object' | 'objectId';
|
|
79
|
+
/**
|
|
80
|
+
* Sentinel default-value codes, resolved at schema-compile time to a generator
|
|
81
|
+
* function so each document gets a freshly-computed value (never baked in once
|
|
82
|
+
* at schema-definition time):
|
|
83
|
+
* - `'$now'` — the current `Date` (pair with `type: 'date'`)
|
|
84
|
+
* - `'$uuid'` — a fresh `crypto.randomUUID()` string (pair with `type: 'string'`)
|
|
85
|
+
* - `'$objectId'` — a fresh Mongoose `ObjectId` (pair with `type: 'objectId'`)
|
|
86
|
+
* - `'$timestamp'` — the current epoch milliseconds as a `number` (pair with `type: 'number'`)
|
|
87
|
+
* - `'$shortId'` — a random 16-character base64url string (pair with `type: 'string'`);
|
|
88
|
+
* a shorter, non-UUID-shaped alternative to `'$uuid'` for tokens/keys
|
|
89
|
+
* - `'$currentUser'` — the JWT payload `requireAuth` attached to the in-flight request
|
|
90
|
+
* (via `getCurrentUser()`), or `undefined` outside a request / without `requireAuth`
|
|
91
|
+
* - `` `$currentUser.<key>` `` — a single field plucked from that payload, e.g.
|
|
92
|
+
* `'$currentUser.id'` (pair with a `type` matching that field's shape)
|
|
93
|
+
*
|
|
94
|
+
* `'$increment'` is intentionally NOT a `default` code — see `FieldDefinition.sequence`
|
|
95
|
+
* instead. Auto-increment needs an async read-modify-write against a counters
|
|
96
|
+
* collection; mongoose resolves `default` synchronously, so it can't live here.
|
|
97
|
+
*
|
|
98
|
+
* Any other string/value passed to `default` is used as a literal default, unchanged.
|
|
99
|
+
*/
|
|
100
|
+
type DefaultOperator = '$now' | '$uuid' | '$objectId' | '$timestamp' | '$shortId' | '$currentUser' | `$currentUser.${string}`;
|
|
79
101
|
interface FieldDefinition {
|
|
80
102
|
type: PrimitiveFieldType | 'array';
|
|
81
103
|
required?: boolean;
|
|
82
104
|
unique?: boolean;
|
|
105
|
+
/** A literal default value, or a `DefaultOperator` sentinel code (see above). */
|
|
83
106
|
default?: unknown;
|
|
84
107
|
/** Restricts the field to a fixed set of values. Valid on `string` and `number` types. */
|
|
85
108
|
enum?: readonly (string | number)[];
|
|
@@ -87,6 +110,14 @@ interface FieldDefinition {
|
|
|
87
110
|
ref?: string;
|
|
88
111
|
/** Item type for `array` fields, e.g. `{ type: 'array', of: 'string' }`. Omit for an untyped array. */
|
|
89
112
|
of?: PrimitiveFieldType;
|
|
113
|
+
/**
|
|
114
|
+
* Auto-increments a shared counter (stored in an internal `efc_counters` collection)
|
|
115
|
+
* and assigns it on insert, before `required` validation runs. `true` uses
|
|
116
|
+
* `'<ModelName>.<field>'` as the counter key; a string sets an explicit key so
|
|
117
|
+
* multiple fields/models can share one counter (e.g. a global order number).
|
|
118
|
+
* Only supported on top-level fields — not inside nested array sub-schemas.
|
|
119
|
+
*/
|
|
120
|
+
sequence?: boolean | string;
|
|
90
121
|
}
|
|
91
122
|
/**
|
|
92
123
|
* A schema field is either a `FieldDefinition`, or a one-element tuple holding a nested
|
|
@@ -98,6 +129,18 @@ interface ModelQueryOptions {
|
|
|
98
129
|
/** Mongoose `.populate()` path(s) to resolve on `objectId`/ref fields. */
|
|
99
130
|
populate?: string | string[];
|
|
100
131
|
}
|
|
132
|
+
interface ModelOptions {
|
|
133
|
+
/**
|
|
134
|
+
* Passed straight through to mongoose's own schema `timestamps` option.
|
|
135
|
+
* `true` (the default) adds `createdAt`/`updatedAt`; `false` disables both;
|
|
136
|
+
* an object lets you rename or selectively disable one, e.g.
|
|
137
|
+
* `{ createdAt: 'created_at', updatedAt: false }`.
|
|
138
|
+
*/
|
|
139
|
+
timestamps?: boolean | {
|
|
140
|
+
createdAt?: string | false;
|
|
141
|
+
updatedAt?: string | false;
|
|
142
|
+
};
|
|
143
|
+
}
|
|
101
144
|
interface ModelCRUD<T extends object> {
|
|
102
145
|
find(filter?: Partial<T>, options?: ModelQueryOptions): Promise<T[]>;
|
|
103
146
|
findById(id: string, options?: ModelQueryOptions): Promise<(T & {
|
|
@@ -116,4 +159,4 @@ interface ModelCRUD<T extends object> {
|
|
|
116
159
|
count(filter?: Partial<T>): Promise<number>;
|
|
117
160
|
}
|
|
118
161
|
|
|
119
|
-
export type { AuthStrategy as A, CorsConfig as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, ModelSchema as M, RouteEntry as R, TaskOptions as T, TaskDefinition as a,
|
|
162
|
+
export type { AuthStrategy as A, CorsConfig as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, ModelSchema as M, RouteEntry as R, TaskOptions as T, TaskDefinition as a, ModelOptions as b, ModelCRUD as c, DefaultOperator as d, ModelQueryOptions as e, RouteMeta as f, RouteMethodMeta as g };
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/efc.js/efc.js/packages/core/dist/chunk-QOKLEPTX.cjs","../src/auth/index.ts"],"names":["req","res","next"],"mappings":"AAAA;ACCA,4BAAmC;AAUnC,IAAI,QAAA,EAA6B,IAAA;AAE1B,SAAS,aAAA,CAAc,MAAA,EAA0B;AACtD,EAAA,QAAA,EAAU,MAAA;AACZ;AAEA,SAAS,SAAA,CAAA,EAAwB;AAC/B,EAAA,GAAA,CAAI,CAAC,OAAA,EAAS,MAAM,IAAI,KAAA,CAAM,6DAAwD,CAAA;AACtF,EAAA,OAAO,OAAA;AACT;AAEA,MAAA,SAAsB,UAAA,CAAW,GAAA,EAAe,OAAA,EAAiD;AAC/F,EAAA,MAAM,EAAE,MAAA,EAAQ,SAAA,EAAW,aAAa,EAAA,EAAI,SAAA,CAAU,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EACP,EAAA,UAAQ;AACN,IAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,eAAe,CAAC,CAAA;AAAA,EAChD;AACF;AAYO,IAAM,YAAA,EAAA,CAA4B,CAAA,GAAI,IAAA,EAAA,GAAoB;AAC/D,EAAA,GAAA,CAAI,IAAA,CAAK,OAAA,EAAS,EAAA,GAAK,OAAO,IAAA,CAAK,CAAC,EAAA,IAAM,QAAA,EAAU;AAClD,IAAA,MAAM,MAAA,EAAQ,IAAA;AACd,IAAA,OAAO,CAACA,IAAAA,EAAcC,IAAAA,EAAeC,KAAAA,EAAAA,GAAuB;AAC1D,MAAA,KAAK,YAAA,CAAaF,IAAAA,EAAKC,IAAAA,EAAKC,KAAAA,EAAM,KAAK,CAAA;AAAA,IACzC,CAAA;AAAA,EACF;AACA,EAAA,MAAM,CAAC,GAAA,EAAK,GAAA,EAAK,IAAI,EAAA,EAAI,IAAA;AACzB,EAAA,KAAK,YAAA,CAAa,GAAA,EAAK,GAAA,EAAK,IAAA,EAAM,CAAC,CAAC,CAAA;AACtC,CAAA,CAAA;AD3CA;AACA;AACE;AACA;AACA;AACA;AACA;AACF,4KAAC","file":"/home/runner/work/efc.js/efc.js/packages/core/dist/chunk-QOKLEPTX.cjs","sourcesContent":[null,"import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { SignJWT, jwtVerify } from 'jose';\nimport type { AuthStrategy } from '../types.js';\n\ninterface AuthConfig {\n secret: string;\n strategy: AuthStrategy;\n expiresIn: string;\n cookieDomain?: string | undefined;\n}\n\nlet _config: AuthConfig | null = null;\n\nexport function configureAuth(config: AuthConfig): void {\n _config = config;\n}\n\nfunction getConfig(): AuthConfig {\n if (!_config) throw new Error('[EFC] Auth not configured — pass jwtSecret to ignite()');\n return _config;\n}\n\nexport async function issueToken(res: Response, payload: Record<string, unknown>): Promise<void> {\n const { secret, expiresIn, cookieDomain } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n const token = await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n\n res.cookie('efc_token', token, {\n httpOnly: true,\n secure: process.env['NODE_ENV'] === 'production',\n sameSite: 'strict',\n ...(cookieDomain !== undefined && { domain: cookieDomain }),\n });\n}\n\nexport function revokeToken(res: Response): void {\n res.clearCookie('efc_token');\n}\n\nexport async function signToken(payload: Record<string, unknown>): Promise<string> {\n const { secret, expiresIn } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n return await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n}\n\nasync function authenticate(\n req: Request,\n res: Response,\n next: NextFunction,\n roles: string[],\n): Promise<void> {\n const { secret, strategy } = getConfig();\n\n try {\n let token: string | undefined;\n\n if (strategy === 'http-only') {\n const cookies = (req as typeof req & { cookies: Record<string, string> }).cookies;\n token = cookies?.['efc_token'];\n } else {\n const auth = req.headers['authorization'];\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n token = auth.slice(7);\n }\n }\n\n if (!token) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n\n const encodedSecret = new TextEncoder().encode(secret);\n const { payload } = await jwtVerify(token, encodedSecret);\n\n if (roles.length > 0) {\n const role = (payload as Record<string, unknown>)['role'];\n if (typeof role !== 'string' || !roles.includes(role)) {\n res.status(403).json({ error: 'Forbidden' });\n return;\n }\n }\n\n (req as typeof req & { user: unknown }).user = payload;\n next();\n } catch {\n res.status(401).json({ error: 'Unauthorized' });\n }\n}\n\n/**\n * Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.\n * Called with role names (`middlewares = [requireAuth('admin')]`) it\n * returns a middleware that also enforces `payload.role` is one of them.\n */\nexport interface RequireAuth {\n (req: Request, res: Response, next: NextFunction): void;\n (...roles: string[]): RequestHandler;\n}\n\nexport const requireAuth: RequireAuth = ((...args: unknown[]) => {\n if (args.length > 0 && typeof args[0] === 'string') {\n const roles = args as string[];\n return (req: Request, res: Response, next: NextFunction) => {\n void authenticate(req, res, next, roles);\n };\n }\n const [req, res, next] = args as [Request, Response, NextFunction];\n void authenticate(req, res, next, []);\n}) as RequireAuth;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/index.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { SignJWT, jwtVerify } from 'jose';\nimport type { AuthStrategy } from '../types.js';\n\ninterface AuthConfig {\n secret: string;\n strategy: AuthStrategy;\n expiresIn: string;\n cookieDomain?: string | undefined;\n}\n\nlet _config: AuthConfig | null = null;\n\nexport function configureAuth(config: AuthConfig): void {\n _config = config;\n}\n\nfunction getConfig(): AuthConfig {\n if (!_config) throw new Error('[EFC] Auth not configured — pass jwtSecret to ignite()');\n return _config;\n}\n\nexport async function issueToken(res: Response, payload: Record<string, unknown>): Promise<void> {\n const { secret, expiresIn, cookieDomain } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n const token = await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n\n res.cookie('efc_token', token, {\n httpOnly: true,\n secure: process.env['NODE_ENV'] === 'production',\n sameSite: 'strict',\n ...(cookieDomain !== undefined && { domain: cookieDomain }),\n });\n}\n\nexport function revokeToken(res: Response): void {\n res.clearCookie('efc_token');\n}\n\nexport async function signToken(payload: Record<string, unknown>): Promise<string> {\n const { secret, expiresIn } = getConfig();\n const encodedSecret = new TextEncoder().encode(secret);\n return await new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setExpirationTime(expiresIn)\n .sign(encodedSecret);\n}\n\nasync function authenticate(\n req: Request,\n res: Response,\n next: NextFunction,\n roles: string[],\n): Promise<void> {\n const { secret, strategy } = getConfig();\n\n try {\n let token: string | undefined;\n\n if (strategy === 'http-only') {\n const cookies = (req as typeof req & { cookies: Record<string, string> }).cookies;\n token = cookies?.['efc_token'];\n } else {\n const auth = req.headers['authorization'];\n if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n token = auth.slice(7);\n }\n }\n\n if (!token) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n\n const encodedSecret = new TextEncoder().encode(secret);\n const { payload } = await jwtVerify(token, encodedSecret);\n\n if (roles.length > 0) {\n const role = (payload as Record<string, unknown>)['role'];\n if (typeof role !== 'string' || !roles.includes(role)) {\n res.status(403).json({ error: 'Forbidden' });\n return;\n }\n }\n\n (req as typeof req & { user: unknown }).user = payload;\n next();\n } catch {\n res.status(401).json({ error: 'Unauthorized' });\n }\n}\n\n/**\n * Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.\n * Called with role names (`middlewares = [requireAuth('admin')]`) it\n * returns a middleware that also enforces `payload.role` is one of them.\n */\nexport interface RequireAuth {\n (req: Request, res: Response, next: NextFunction): void;\n (...roles: string[]): RequestHandler;\n}\n\nexport const requireAuth: RequireAuth = ((...args: unknown[]) => {\n if (args.length > 0 && typeof args[0] === 'string') {\n const roles = args as string[];\n return (req: Request, res: Response, next: NextFunction) => {\n void authenticate(req, res, next, roles);\n };\n }\n const [req, res, next] = args as [Request, Response, NextFunction];\n void authenticate(req, res, next, []);\n}) as RequireAuth;\n"],"mappings":";AACA,SAAS,SAAS,iBAAiB;AAUnC,IAAI,UAA6B;AAE1B,SAAS,cAAc,QAA0B;AACtD,YAAU;AACZ;AAEA,SAAS,YAAwB;AAC/B,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,6DAAwD;AACtF,SAAO;AACT;AAEA,eAAsB,WAAW,KAAe,SAAiD;AAC/F,QAAM,EAAE,QAAQ,WAAW,aAAa,IAAI,UAAU;AACtD,QAAM,gBAAgB,IAAI,YAAY,EAAE,OAAO,MAAM;AACrD,QAAM,QAAQ,MAAM,IAAI,QAAQ,OAAO,EACpC,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,kBAAkB,SA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