pocketbase-zod-schema 0.2.3 → 0.2.5
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/CHANGELOG.md +14 -0
- package/README.md +209 -24
- package/dist/cli/index.cjs +34 -0
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.d.cts +3 -1
- package/dist/cli/index.d.ts +3 -1
- package/dist/cli/index.js +34 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/migrate.cjs +34 -0
- package/dist/cli/migrate.cjs.map +1 -1
- package/dist/cli/migrate.js +34 -0
- package/dist/cli/migrate.js.map +1 -1
- package/dist/cli/utils/index.d.cts +3 -1
- package/dist/cli/utils/index.d.ts +3 -1
- package/dist/fields-YjcpBXVp.d.cts +348 -0
- package/dist/fields-YjcpBXVp.d.ts +348 -0
- package/dist/index.cjs +833 -694
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -4
- package/dist/index.d.ts +3 -4
- package/dist/index.js +818 -687
- package/dist/index.js.map +1 -1
- package/dist/migration/analyzer.cjs +34 -0
- package/dist/migration/analyzer.cjs.map +1 -1
- package/dist/migration/analyzer.d.cts +2 -1
- package/dist/migration/analyzer.d.ts +2 -1
- package/dist/migration/analyzer.js +34 -0
- package/dist/migration/analyzer.js.map +1 -1
- package/dist/migration/diff.d.cts +3 -1
- package/dist/migration/diff.d.ts +3 -1
- package/dist/migration/generator.d.cts +3 -1
- package/dist/migration/generator.d.ts +3 -1
- package/dist/migration/index.cjs +36 -0
- package/dist/migration/index.cjs.map +1 -1
- package/dist/migration/index.d.cts +2 -1
- package/dist/migration/index.d.ts +2 -1
- package/dist/migration/index.js +35 -1
- package/dist/migration/index.js.map +1 -1
- package/dist/migration/snapshot.cjs.map +1 -1
- package/dist/migration/snapshot.d.cts +3 -1
- package/dist/migration/snapshot.d.ts +3 -1
- package/dist/migration/snapshot.js.map +1 -1
- package/dist/migration/utils/index.cjs +16 -0
- package/dist/migration/utils/index.cjs.map +1 -1
- package/dist/migration/utils/index.d.cts +2 -2
- package/dist/migration/utils/index.d.ts +2 -2
- package/dist/migration/utils/index.js +15 -1
- package/dist/migration/utils/index.js.map +1 -1
- package/dist/mutator.cjs +2 -98
- package/dist/mutator.cjs.map +1 -1
- package/dist/mutator.d.cts +4 -31
- package/dist/mutator.d.ts +4 -31
- package/dist/mutator.js +2 -98
- package/dist/mutator.js.map +1 -1
- package/dist/schema.cjs +200 -78
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.cts +1 -1
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +186 -72
- package/dist/schema.js.map +1 -1
- package/dist/{types-z1Dkjg8m.d.ts → types-LFBGHl9Y.d.ts} +2 -2
- package/dist/{types-BbTgmg6H.d.cts → types-mhQXWNi3.d.cts} +2 -2
- package/package.json +1 -6
- package/dist/types.cjs +0 -4
- package/dist/types.cjs.map +0 -1
- package/dist/types.d.cts +0 -14
- package/dist/types.d.ts +0 -14
- package/dist/types.js +0 -3
- package/dist/types.js.map +0 -1
- package/dist/user-BnFWg5tw.d.cts +0 -161
- package/dist/user-BnFWg5tw.d.ts +0 -161
package/dist/mutator.d.ts
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { RecordModel, RecordService, ListResult, RecordSubscription, UnsubscribeFunc } from 'pocketbase';
|
|
3
|
-
import { TypedPocketBase, UserType, UserInputType } from './types.js';
|
|
4
|
-
import 'zod';
|
|
5
|
-
import './user-BnFWg5tw.js';
|
|
1
|
+
import PocketBase, { RecordModel, RecordService, ListResult, RecordSubscription, UnsubscribeFunc } from 'pocketbase';
|
|
6
2
|
|
|
7
3
|
interface MutatorOptions {
|
|
8
4
|
expand: string[];
|
|
@@ -10,9 +6,9 @@ interface MutatorOptions {
|
|
|
10
6
|
sort: string[];
|
|
11
7
|
}
|
|
12
8
|
declare abstract class BaseMutator<T extends RecordModel, InputType> {
|
|
13
|
-
protected pb:
|
|
9
|
+
protected pb: PocketBase;
|
|
14
10
|
protected options: MutatorOptions;
|
|
15
|
-
constructor(pb:
|
|
11
|
+
constructor(pb: PocketBase, options?: Partial<MutatorOptions>);
|
|
16
12
|
private initializeOptions;
|
|
17
13
|
/**
|
|
18
14
|
* Initialize options with class-specific defaults
|
|
@@ -162,27 +158,4 @@ declare abstract class BaseMutator<T extends RecordModel, InputType> {
|
|
|
162
158
|
unsubscribeAll(): void;
|
|
163
159
|
}
|
|
164
160
|
|
|
165
|
-
|
|
166
|
-
protected setDefaults(): MutatorOptions;
|
|
167
|
-
protected getCollection(): PocketBase.RecordService<{
|
|
168
|
-
collectionName: string;
|
|
169
|
-
id: string;
|
|
170
|
-
collectionId: string;
|
|
171
|
-
expand: Record<string, any>;
|
|
172
|
-
created: string;
|
|
173
|
-
updated: string;
|
|
174
|
-
email: string;
|
|
175
|
-
password: string;
|
|
176
|
-
name?: string | undefined;
|
|
177
|
-
avatar?: File | undefined;
|
|
178
|
-
}>;
|
|
179
|
-
protected validateInput(input: UserInputType): Promise<{
|
|
180
|
-
email: string;
|
|
181
|
-
password: string;
|
|
182
|
-
passwordConfirm: string;
|
|
183
|
-
name?: string | undefined;
|
|
184
|
-
avatar?: File | undefined;
|
|
185
|
-
}>;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
export { UserMutator };
|
|
161
|
+
export { BaseMutator, type MutatorOptions };
|
package/dist/mutator.js
CHANGED
|
@@ -1,83 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// src/schema/base.ts
|
|
4
|
-
var baseSchema = {
|
|
5
|
-
id: z.string().describe("unique id"),
|
|
6
|
-
collectionId: z.string().describe("collection id"),
|
|
7
|
-
collectionName: z.string().describe("collection name"),
|
|
8
|
-
expand: z.record(z.any()).describe("expandable fields"),
|
|
9
|
-
created: z.string().describe("creation timestamp"),
|
|
10
|
-
updated: z.string().describe("last update timestamp")
|
|
11
|
-
};
|
|
12
|
-
({
|
|
13
|
-
...baseSchema,
|
|
14
|
-
created: z.string().describe("creation timestamp"),
|
|
15
|
-
updated: z.string().describe("last update timestamp")
|
|
16
|
-
});
|
|
17
|
-
({
|
|
18
|
-
...baseSchema,
|
|
19
|
-
thumbnailURL: z.string().optional(),
|
|
20
|
-
imageFiles: z.array(z.string())
|
|
21
|
-
});
|
|
22
|
-
({
|
|
23
|
-
imageFiles: z.array(z.instanceof(File))
|
|
24
|
-
});
|
|
25
|
-
function defineCollection(config) {
|
|
26
|
-
const { collectionName, schema, permissions, indexes, type, ...futureOptions } = config;
|
|
27
|
-
const metadata = {
|
|
28
|
-
collectionName
|
|
29
|
-
};
|
|
30
|
-
if (type) {
|
|
31
|
-
metadata.type = type;
|
|
32
|
-
}
|
|
33
|
-
if (permissions) {
|
|
34
|
-
metadata.permissions = permissions;
|
|
35
|
-
}
|
|
36
|
-
if (indexes) {
|
|
37
|
-
metadata.indexes = indexes;
|
|
38
|
-
}
|
|
39
|
-
if (Object.keys(futureOptions).length > 0) {
|
|
40
|
-
Object.assign(metadata, futureOptions);
|
|
41
|
-
}
|
|
42
|
-
return schema.describe(JSON.stringify(metadata));
|
|
43
|
-
}
|
|
44
|
-
var UserInputSchema = z.object({
|
|
45
|
-
name: z.string().optional(),
|
|
46
|
-
email: z.string().email(),
|
|
47
|
-
password: z.string().min(8, "Password must be at least 8 characters"),
|
|
48
|
-
passwordConfirm: z.string(),
|
|
49
|
-
avatar: z.instanceof(File).optional()
|
|
50
|
-
});
|
|
51
|
-
var UserCollectionSchema = z.object({
|
|
52
|
-
name: z.string().optional(),
|
|
53
|
-
email: z.string().email(),
|
|
54
|
-
password: z.string().min(8, "Password must be at least 8 characters"),
|
|
55
|
-
avatar: z.instanceof(File).optional()
|
|
56
|
-
});
|
|
57
|
-
var UserSchema = UserCollectionSchema.extend(baseSchema);
|
|
58
|
-
defineCollection({
|
|
59
|
-
collectionName: "users",
|
|
60
|
-
type: "auth",
|
|
61
|
-
schema: UserSchema,
|
|
62
|
-
permissions: {
|
|
63
|
-
// Users can list their own profile
|
|
64
|
-
listRule: "id = @request.auth.id",
|
|
65
|
-
// Users can view their own profile
|
|
66
|
-
viewRule: "id = @request.auth.id",
|
|
67
|
-
// Anyone can create an account (sign up)
|
|
68
|
-
createRule: "",
|
|
69
|
-
// Users can only update their own profile
|
|
70
|
-
updateRule: "id = @request.auth.id",
|
|
71
|
-
// Users can only delete their own account
|
|
72
|
-
deleteRule: "id = @request.auth.id"
|
|
73
|
-
// manageRule is null in PocketBase default (not set)
|
|
74
|
-
},
|
|
75
|
-
indexes: [
|
|
76
|
-
// PocketBase's default indexes for auth collections
|
|
77
|
-
"CREATE UNIQUE INDEX `idx_tokenKey__pb_users_auth_` ON `users` (`tokenKey`)",
|
|
78
|
-
"CREATE UNIQUE INDEX `idx_email__pb_users_auth_` ON `users` (`email`) WHERE `email` != ''"
|
|
79
|
-
]
|
|
80
|
-
});
|
|
1
|
+
// src/mutator/baseMutator.ts
|
|
81
2
|
var BaseMutator = class {
|
|
82
3
|
pb;
|
|
83
4
|
// Define a default property that subclasses will override
|
|
@@ -406,23 +327,6 @@ var BaseMutator = class {
|
|
|
406
327
|
}
|
|
407
328
|
};
|
|
408
329
|
|
|
409
|
-
|
|
410
|
-
var UserMutator = class extends BaseMutator {
|
|
411
|
-
setDefaults() {
|
|
412
|
-
return {
|
|
413
|
-
expand: [],
|
|
414
|
-
filter: [],
|
|
415
|
-
sort: ["-updated"]
|
|
416
|
-
};
|
|
417
|
-
}
|
|
418
|
-
getCollection() {
|
|
419
|
-
return this.pb.collection("Users");
|
|
420
|
-
}
|
|
421
|
-
async validateInput(input) {
|
|
422
|
-
return UserInputSchema.parse(input);
|
|
423
|
-
}
|
|
424
|
-
};
|
|
425
|
-
|
|
426
|
-
export { UserMutator };
|
|
330
|
+
export { BaseMutator };
|
|
427
331
|
//# sourceMappingURL=mutator.js.map
|
|
428
332
|
//# sourceMappingURL=mutator.js.map
|
package/dist/mutator.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
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,EAC7D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,qBAAA,CACJ,QAAA,EACA,MAAA,EAC0B;AAC1B,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,aAAA,CAAc,MAAM,CAAA;AAC7C,IAAA,MAAM,UAAkC,WAAA,GAAc,EAAE,MAAA,EAAQ,WAAA,KAAgB,EAAC;AAEjF,IAAA,OAAO,KAAK,aAAA,EAAc,CAAE,SAAA,CAAU,GAAA,EAAK,UAAU,OAAO,CAAA;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,sBAAsB,EAAA,EAAkB;AACtC,IAAA,IAAA,CAAK,aAAA,EAAc,CAAE,WAAA,CAAY,EAAE,CAAA;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,yBAAA,GAAkC;AAChC,IAAA,IAAA,CAAK,aAAA,EAAc,CAAE,WAAA,CAAY,GAAG,CAAA;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,cAAA,GAAuB;AACrB,IAAA,IAAA,CAAK,aAAA,GAAgB,WAAA,EAAY;AAAA,EACnC;AACF,CAAA;;;AC3dO,IAAM,WAAA,GAAN,cAA0B,WAAA,CAAqC;AAAA,EAC1D,WAAA,GAA8B;AACtC,IAAA,OAAO;AAAA,MACL,QAAQ,EAAC;AAAA,MACT,QAAQ,EAAC;AAAA,MACT,IAAA,EAAM,CAAC,UAAU;AAAA,KACnB;AAAA,EACF;AAAA,EAEU,aAAA,GAAgB;AACxB,IAAA,OAAO,IAAA,CAAK,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA;AAAA,EACnC;AAAA,EAEA,MAAgB,cAAc,KAAA,EAAsB;AAClD,IAAA,OAAO,eAAA,CAAgB,MAAM,KAAK,CAAA;AAAA,EACpC;AACF","file":"mutator.js","sourcesContent":["import { z } from \"zod\";\nimport type { PermissionSchema, PermissionTemplateConfig } from \"../utils/permissions\";\n\n/**\n * Base schema fields that PocketBase automatically adds to all records\n * These fields are managed by PocketBase and should not be set manually\n */\nexport const baseSchema = {\n id: z.string().describe(\"unique id\"),\n collectionId: z.string().describe(\"collection id\"),\n collectionName: z.string().describe(\"collection name\"),\n expand: z.record(z.any()).describe(\"expandable fields\"),\n created: z.string().describe(\"creation timestamp\"),\n updated: z.string().describe(\"last update timestamp\"),\n};\n\n/**\n * Extended base schema with timestamp fields\n * Includes created and updated autodate fields\n */\nexport const baseSchemaWithTimestamps = {\n ...baseSchema,\n created: z.string().describe(\"creation timestamp\"),\n updated: z.string().describe(\"last update timestamp\"),\n};\n\n/**\n * Base schema for image file collections\n * Extends base schema with thumbnail URL and image files array\n */\nexport const baseImageFileSchema = {\n ...baseSchema,\n thumbnailURL: z.string().optional(),\n imageFiles: z.array(z.string()),\n};\n\n/**\n * Input schema for image file uploads\n * Used in forms where users upload File objects\n * Requires Node.js 20+ or browser environment with File API\n */\nexport const inputImageFileSchema = {\n imageFiles: z.array(z.instanceof(File)),\n};\n\n/**\n * Helper constant for omitting image files from schemas\n * Used with Zod's .omit() method\n */\nexport const omitImageFilesSchema = {\n imageFiles: true,\n} as const;\n\n// ============================================================================\n// Common PocketBase Field Type Patterns\n// ============================================================================\n\n/**\n * Creates a text field schema with optional constraints\n * @param options - Optional constraints for the text field\n */\nexport function textField(options?: { min?: number; max?: number; pattern?: RegExp }) {\n let schema = z.string();\n if (options?.min !== undefined) schema = schema.min(options.min);\n if (options?.max !== undefined) schema = schema.max(options.max);\n if (options?.pattern !== undefined) schema = schema.regex(options.pattern);\n return schema;\n}\n\n/**\n * Creates an email field schema\n * Maps to PocketBase 'email' field type\n */\nexport function emailField() {\n return z.string().email();\n}\n\n/**\n * Creates a URL field schema\n * Maps to PocketBase 'url' field type\n */\nexport function urlField() {\n return z.string().url();\n}\n\n/**\n * Creates a number field schema with optional constraints\n * @param options - Optional constraints for the number field\n */\nexport function numberField(options?: { min?: number; max?: number }) {\n let schema = z.number();\n if (options?.min !== undefined) schema = schema.min(options.min);\n if (options?.max !== undefined) schema = schema.max(options.max);\n return schema;\n}\n\n/**\n * Creates a boolean field schema\n * Maps to PocketBase 'bool' field type\n */\nexport function boolField() {\n return z.boolean();\n}\n\n/**\n * Creates a date field schema\n * Maps to PocketBase 'date' field type\n */\nexport function dateField() {\n return z.date();\n}\n\n/**\n * Creates a select field schema from enum values\n * Maps to PocketBase 'select' field type\n * @param values - Array of allowed string values\n */\nexport function selectField<T extends [string, ...string[]]>(values: T) {\n return z.enum(values);\n}\n\n/**\n * Creates a JSON field schema\n * Maps to PocketBase 'json' field type\n * @param schema - Optional Zod schema for the JSON structure\n */\nexport function jsonField<T extends z.ZodTypeAny>(schema?: T) {\n return schema ?? z.record(z.any());\n}\n\n/**\n * Creates a single file field schema for form input\n * Maps to PocketBase 'file' field type with maxSelect=1\n * Requires Node.js 20+ or browser environment with File API\n */\nexport function fileField() {\n return z.instanceof(File);\n}\n\n/**\n * Creates a multiple file field schema for form input\n * Maps to PocketBase 'file' field type with maxSelect>1\n * Requires Node.js 20+ or browser environment with File API\n * @param options - Optional constraints for the file field\n */\nexport function filesField(options?: { min?: number; max?: number }) {\n let schema = z.array(z.instanceof(File));\n if (options?.min !== undefined) schema = schema.min(options.min);\n if (options?.max !== undefined) schema = schema.max(options.max);\n return schema;\n}\n\n// ============================================================================\n// Relation Field Helpers - Explicit Relationship Definitions\n// ============================================================================\n\n/**\n * Relation field configuration options\n */\nexport interface RelationConfig {\n /**\n * Target collection name (e.g., 'users', 'posts', 'tags')\n * This is the PocketBase collection that the relation points to\n */\n collection: string;\n\n /**\n * Whether to cascade delete related records when this record is deleted\n * @default false\n */\n cascadeDelete?: boolean;\n}\n\n/**\n * Multiple relation field configuration options\n */\nexport interface RelationsConfig extends RelationConfig {\n /**\n * Minimum number of relations required\n * @default 0\n */\n minSelect?: number;\n\n /**\n * Maximum number of relations allowed\n * @default 999\n */\n maxSelect?: number;\n}\n\n/**\n * Internal marker for relation metadata\n * Used by the analyzer to detect explicit relation definitions\n */\nconst RELATION_METADATA_KEY = \"__pocketbase_relation__\";\n\n/**\n * Creates a single relation field schema with explicit collection target\n * Maps to PocketBase 'relation' field type with maxSelect=1\n *\n * This is the recommended way to define relations - it's explicit and doesn't\n * rely on naming conventions.\n *\n * @param config - Relation configuration with target collection\n * @returns Zod string schema with relation metadata\n *\n * @example\n * // Single relation to users collection\n * const PostSchema = z.object({\n * title: z.string(),\n * author: RelationField({ collection: 'users' }),\n * });\n *\n * @example\n * // Relation with cascade delete\n * const CommentSchema = z.object({\n * content: z.string(),\n * post: RelationField({ collection: 'posts', cascadeDelete: true }),\n * });\n */\nexport function RelationField(config: RelationConfig) {\n const metadata = {\n [RELATION_METADATA_KEY]: {\n type: \"single\",\n collection: config.collection,\n cascadeDelete: config.cascadeDelete ?? false,\n maxSelect: 1,\n minSelect: 0,\n },\n };\n\n return z.string().describe(JSON.stringify(metadata));\n}\n\n/**\n * Creates a multiple relation field schema with explicit collection target\n * Maps to PocketBase 'relation' field type with maxSelect>1\n *\n * This is the recommended way to define multi-relations - it's explicit and\n * doesn't rely on naming conventions.\n *\n * @param config - Relations configuration with target collection and limits\n * @returns Zod array of strings schema with relation metadata\n *\n * @example\n * // Multiple relations to tags collection\n * const PostSchema = z.object({\n * title: z.string(),\n * tags: RelationsField({ collection: 'tags' }),\n * });\n *\n * @example\n * // Relations with min/max constraints\n * const ProjectSchema = z.object({\n * title: z.string(),\n * collaborators: RelationsField({\n * collection: 'users',\n * minSelect: 1,\n * maxSelect: 10,\n * }),\n * });\n */\nexport function RelationsField(config: RelationsConfig) {\n const metadata = {\n [RELATION_METADATA_KEY]: {\n type: \"multiple\",\n collection: config.collection,\n cascadeDelete: config.cascadeDelete ?? false,\n maxSelect: config.maxSelect ?? 999,\n minSelect: config.minSelect ?? 0,\n },\n };\n\n let schema = z.array(z.string());\n\n // Apply array constraints for Zod validation\n if (config.minSelect !== undefined) {\n schema = schema.min(config.minSelect);\n }\n if (config.maxSelect !== undefined) {\n schema = schema.max(config.maxSelect);\n }\n\n return schema.describe(JSON.stringify(metadata));\n}\n\n/**\n * Extracts relation metadata from a Zod type's description\n * Used internally by the analyzer to detect explicit relation definitions\n *\n * @param description - The Zod type's description string\n * @returns Relation metadata if present, null otherwise\n */\nexport function extractRelationMetadata(description: string | undefined): {\n type: \"single\" | \"multiple\";\n collection: string;\n cascadeDelete: boolean;\n maxSelect: number;\n minSelect: number;\n} | null {\n if (!description) return null;\n\n try {\n const parsed = JSON.parse(description);\n if (parsed[RELATION_METADATA_KEY]) {\n return parsed[RELATION_METADATA_KEY];\n }\n } catch {\n // Not JSON, ignore\n }\n\n return null;\n}\n\n/**\n * Creates an editor field schema (rich text)\n * Maps to PocketBase 'editor' field type\n */\nexport function editorField() {\n return z.string();\n}\n\n/**\n * Creates a geo point field schema\n * Maps to PocketBase 'geoPoint' field type\n */\nexport function geoPointField() {\n return z.object({\n lon: z.number(),\n lat: z.number(),\n });\n}\n\n/**\n * Attach permission metadata to a Zod schema\n *\n * This helper function allows you to define PocketBase API rules alongside your\n * entity schema definitions. The permissions are stored as metadata using Zod's\n * describe() method and will be extracted during migration generation.\n *\n * @param schema - The Zod schema to attach permissions to\n * @param config - Either a PermissionTemplateConfig (for template-based permissions)\n * or a PermissionSchema (for custom permissions)\n * @returns The schema with permission metadata attached\n *\n * @example\n * // Using a template\n * const ProjectSchema = withPermissions(\n * z.object({ title: z.string(), User: z.string() }),\n * { template: 'owner-only', ownerField: 'User' }\n * );\n *\n * @example\n * // Using custom rules\n * const ProjectSchema = withPermissions(\n * z.object({ title: z.string() }),\n * { listRule: '@request.auth.id != \"\"', viewRule: '' }\n * );\n *\n * @example\n * // Using template with custom rule overrides\n * const ProjectSchema = withPermissions(\n * z.object({ title: z.string(), User: z.string() }),\n * {\n * template: 'owner-only',\n * ownerField: 'User',\n * customRules: { listRule: '@request.auth.id != \"\"' }\n * }\n * );\n */\nexport function withPermissions<T extends z.ZodTypeAny>(\n schema: T,\n config: PermissionTemplateConfig | PermissionSchema\n): T {\n // Create metadata object with permissions config directly\n // The PermissionAnalyzer will handle resolving templates vs direct schemas\n const metadata = {\n permissions: config,\n };\n\n // Attach permission metadata to schema using Zod's describe() method\n // The metadata is serialized as JSON and stored in the schema's description\n return schema.describe(JSON.stringify(metadata)) as T;\n}\n\n/**\n * Attach index definitions to a Zod schema\n *\n * This helper function allows you to define PocketBase indexes alongside your\n * entity schema definitions. The indexes are stored as metadata using Zod's\n * describe() method and will be extracted during migration generation.\n *\n * @param schema - The Zod schema to attach indexes to\n * @param indexes - Array of PocketBase index SQL statements\n * @returns The schema with index metadata attached\n *\n * @example\n * // Define indexes for a user schema\n * const UserSchema = withIndexes(\n * withPermissions(\n * z.object({ name: z.string(), email: z.string().email() }),\n * userPermissions\n * ),\n * [\n * 'CREATE UNIQUE INDEX idx_users_email ON users (email)',\n * 'CREATE INDEX idx_users_name ON users (name)'\n * ]\n * );\n *\n * @example\n * // Single index\n * const ProjectSchema = withIndexes(\n * ProjectDatabaseSchema,\n * ['CREATE INDEX idx_projects_status ON projects (status)']\n * );\n */\nexport function withIndexes<T extends z.ZodTypeAny>(schema: T, indexes: string[]): T {\n // Extract existing metadata if present\n let existingMetadata: any = {};\n\n if (schema.description) {\n try {\n existingMetadata = JSON.parse(schema.description);\n } catch {\n // If description is not JSON, ignore it\n }\n }\n\n // Merge indexes with existing metadata\n const metadata = {\n ...existingMetadata,\n indexes,\n };\n\n // Attach metadata to schema using Zod's describe() method\n return schema.describe(JSON.stringify(metadata)) as T;\n}\n\n/**\n * Configuration options for defining a collection\n */\nexport interface CollectionConfig {\n /**\n * The name of the PocketBase collection\n * This will be used when generating migrations\n */\n collectionName: string;\n\n /**\n * The Zod schema definition for the collection\n */\n schema: z.ZodObject<any>;\n\n /**\n * Optional permission configuration\n * Can be a template-based config or custom permission rules\n */\n permissions?: PermissionTemplateConfig | PermissionSchema;\n\n /**\n * Optional array of index SQL statements\n * Example: ['CREATE UNIQUE INDEX idx_users_email ON users (email)']\n */\n indexes?: string[];\n\n /**\n * Optional collection type\n * - \"base\": Standard collection (default)\n * - \"auth\": Authentication collection with system auth fields\n *\n * If not specified, the type will be auto-detected based on field presence\n * (collections with both email and password fields are detected as auth)\n */\n type?: \"base\" | \"auth\";\n\n /**\n * Future extensibility - additional options can be added here\n */\n [key: string]: unknown;\n}\n\n/**\n * High-level wrapper for defining a PocketBase collection with all metadata\n *\n * This is the recommended way to define collections as it provides a single\n * entry point for collection name, schema, permissions, indexes, and future features.\n *\n * @param config - Collection configuration object\n * @returns The schema with all metadata attached\n *\n * @example\n * // Recommended: Use default export for clarity\n * const PostCollection = defineCollection({\n * collectionName: \"posts\",\n * schema: z.object({\n * title: z.string(),\n * content: z.string(),\n * author: RelationField({ collection: \"users\" }),\n * }),\n * permissions: {\n * template: \"owner-only\",\n * ownerField: \"author\",\n * },\n * });\n * export default PostCollection;\n *\n * @example\n * // Also supported: Named export (backward compatible)\n * export const PostCollection = defineCollection({\n * collectionName: \"posts\",\n * schema: z.object({\n * title: z.string(),\n * content: z.string(),\n * author: RelationField({ collection: \"users\" }),\n * }),\n * permissions: {\n * template: \"owner-only\",\n * ownerField: \"author\",\n * },\n * });\n *\n * @example\n * // Collection with permissions and indexes\n * export const UserSchema = defineCollection({\n * collectionName: \"users\",\n * schema: z.object({\n * name: z.string(),\n * email: z.string().email(),\n * }),\n * permissions: {\n * listRule: \"id = @request.auth.id\",\n * viewRule: \"id = @request.auth.id\",\n * createRule: \"\",\n * updateRule: \"id = @request.auth.id\",\n * deleteRule: \"id = @request.auth.id\",\n * },\n * indexes: [\n * \"CREATE UNIQUE INDEX idx_users_email ON users (email)\",\n * ],\n * });\n *\n * @example\n * // Collection with template and custom rule overrides\n * export const ProjectSchema = defineCollection({\n * collectionName: \"projects\",\n * schema: z.object({\n * title: z.string(),\n * owner: RelationField({ collection: \"users\" }),\n * }),\n * permissions: {\n * template: \"owner-only\",\n * ownerField: \"owner\",\n * customRules: {\n * listRule: '@request.auth.id != \"\"',\n * },\n * },\n * });\n */\nexport function defineCollection(config: CollectionConfig): z.ZodObject<any> {\n const { collectionName, schema, permissions, indexes, type, ...futureOptions } = config;\n\n // Build metadata object\n const metadata: any = {\n collectionName,\n };\n\n // Add type if provided\n if (type) {\n metadata.type = type;\n }\n\n // Add permissions if provided\n if (permissions) {\n metadata.permissions = permissions;\n }\n\n // Add indexes if provided\n if (indexes) {\n metadata.indexes = indexes;\n }\n\n // Add any future options\n if (Object.keys(futureOptions).length > 0) {\n Object.assign(metadata, futureOptions);\n }\n\n // Attach all metadata to schema using Zod's describe() method\n return schema.describe(JSON.stringify(metadata)) as z.ZodObject<any>;\n}\n","import { z } from \"zod\";\nimport { baseSchema, defineCollection } from \"./base\";\n\n/** -- User Collections -- */\n// Input schema for forms (includes passwordConfirm for validation)\nexport const UserInputSchema = z.object({\n name: z.string().optional(),\n email: z.string().email(),\n password: z.string().min(8, \"Password must be at least 8 characters\"),\n passwordConfirm: z.string(),\n avatar: z.instanceof(File).optional(),\n});\n\n// Database schema (excludes passwordConfirm, includes avatar as file field)\nexport const UserCollectionSchema = z.object({\n name: z.string().optional(),\n email: z.string().email(),\n password: z.string().min(8, \"Password must be at least 8 characters\"),\n avatar: z.instanceof(File).optional(),\n});\n\n// Full schema with base fields for type inference (used in types.ts)\n// This includes id, collectionId, collectionName from baseSchema\nexport const UserSchema = UserCollectionSchema.extend(baseSchema);\n\n// Matches PocketBase's default users collection configuration\n// Using default export - the migration tool will automatically use this\nconst UserCollection = defineCollection({\n collectionName: \"users\",\n type: \"auth\",\n schema: UserSchema,\n permissions: {\n // Users can list their own profile\n listRule: \"id = @request.auth.id\",\n // Users can view their own profile\n viewRule: \"id = @request.auth.id\",\n // Anyone can create an account (sign up)\n createRule: \"\",\n // Users can only update their own profile\n updateRule: \"id = @request.auth.id\",\n // Users can only delete their own account\n deleteRule: \"id = @request.auth.id\",\n // manageRule is null in PocketBase default (not set)\n },\n indexes: [\n // PocketBase's default indexes for auth collections\n \"CREATE UNIQUE INDEX `idx_tokenKey__pb_users_auth_` ON `users` (`tokenKey`)\",\n \"CREATE UNIQUE INDEX `idx_email__pb_users_auth_` ON `users` (`email`) WHERE `email` != ''\",\n ],\n});\n\n// Default export - preferred pattern for schema files\n// The migration tool will automatically detect and use this\nexport default UserCollection;\n\n// Named export kept for backward compatibility and type inference\nexport { UserCollection };\n","import {\n RecordService,\n type ListResult,\n type RecordListOptions,\n type RecordModel,\n type RecordOptions,\n type RecordSubscribeOptions,\n type RecordSubscription,\n type UnsubscribeFunc,\n} from \"pocketbase\";\nimport type { TypedPocketBase } from \"../types\";\n\nexport interface MutatorOptions {\n expand: string[];\n filter: string[];\n sort: string[];\n}\n\n// T represents the output model type that extends RecordModel\n// InputType represents the input type for creation operations\nexport abstract class BaseMutator<T extends RecordModel, InputType> {\n protected pb: TypedPocketBase;\n\n // Define a default property that subclasses will override\n protected options: MutatorOptions = {\n expand: [],\n filter: [],\n sort: [],\n };\n\n constructor(pb: TypedPocketBase, options?: Partial<MutatorOptions>) {\n this.pb = pb;\n\n // Initialize with default options first\n this.initializeOptions();\n if (options) {\n this.overrideOptions(options);\n }\n }\n\n private initializeOptions(): void {\n this.options = this.setDefaults();\n }\n /**\n * Initialize options with class-specific defaults\n * Subclasses should override this instead of directly setting options\n */\n protected setDefaults(): MutatorOptions {\n return {\n expand: [],\n filter: [],\n sort: [],\n };\n }\n\n /**\n * Merge provided options with current options\n */\n protected overrideOptions(newOptions: Partial<MutatorOptions>): void {\n if (newOptions.expand !== undefined) {\n this.options.expand = newOptions.expand;\n }\n if (newOptions.filter !== undefined) {\n this.options.filter = newOptions.filter;\n }\n if (newOptions.sort !== undefined) {\n this.options.sort = newOptions.sort;\n }\n }\n\n /**\n * Get the collection instance\n */\n protected abstract getCollection(): RecordService<T>;\n\n toSnakeCase(str: string): string {\n return str\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n }\n\n /**\n * Create a new entity\n */\n async create(input: InputType): Promise<T> {\n try {\n const data = await this.validateInput(input);\n const record = await this.entityCreate(data);\n return await this.processRecord(record);\n } catch (error) {\n return this.errorWrapper(error);\n }\n }\n\n /**\n * Update an existing entity\n */\n async update(id: string, input: Partial<T>): Promise<T> {\n try {\n const record = await this.entityUpdate(id, input);\n return await this.processRecord(record);\n } catch (error) {\n return this.errorWrapper(error);\n }\n }\n\n /**\n * Create or update entity (upsert)\n */\n async upsert(input: InputType & { id?: string }): Promise<T> {\n if (input?.id) {\n return await this.update(input.id, input as Partial<T>);\n }\n\n // Implementations should override this method if they need\n // more specific upsert logic like checking for existing entities\n return await this.create(input);\n }\n\n /**\n * Get entity by ID\n */\n async getById(id: string, expand?: string | string[]): Promise<T | null> {\n try {\n const record = await this.entityGetById(id, expand);\n return await this.processRecord(record);\n } catch (error) {\n return this.handleError(error, { allowNotFound: true });\n }\n }\n\n /**\n * Get first entity by filter\n */\n async getFirstByFilter(filter: string | string[], expand?: string | string[], sort?: string): Promise<T | null> {\n try {\n const record = await this.entityGetFirstByFilter(filter, expand, sort);\n return await this.processRecord(record);\n } catch (error) {\n return this.handleError(error, { allowNotFound: true });\n }\n }\n\n /**\n * Get list of entities\n */\n async getList(\n page = 1,\n perPage = 100,\n filter?: string | string[],\n sort?: string,\n expand?: string | string[]\n ): Promise<ListResult<T>> {\n try {\n const result = await this.entityGetList(page, perPage, filter, sort, expand);\n return await this.processListResult(result);\n } catch (error) {\n return this.errorWrapper(error);\n }\n }\n\n /**\n * Delete entity by ID\n */\n async delete(id: string): Promise<boolean> {\n try {\n return await this.entityDelete(id);\n } catch (error) {\n return this.handleError(error, { returnValue: false });\n }\n }\n\n /**\n * Process a single record before returning it\n * Can be overridden to handle special cases like mapped entities\n */\n protected async processRecord(record: T): Promise<T> {\n return record;\n }\n\n /**\n * Process a list result before returning it\n * Can be overridden to handle special cases like mapped entities\n */\n protected async processListResult(result: ListResult<T>): Promise<ListResult<T>> {\n // Process each item in the list\n const processedItems = await Promise.all(result.items.map((item) => this.processRecord(item)));\n\n return {\n ...result,\n items: processedItems,\n };\n }\n\n /**\n * Prepare expand parameter\n * Combines default expands with provided expands\n */\n protected prepareExpand(expand?: string | string[]): string | undefined {\n // Handle empty defaults case\n if (!this.options.expand.length && !expand) {\n return undefined;\n }\n\n // Convert all inputs to arrays for easy processing\n let expandArray: string[] = [...this.options.expand];\n\n if (expand) {\n // If expand is a string, split it and add the parts\n if (typeof expand === \"string\") {\n expandArray = expandArray.concat(expand.split(\",\").map((e) => e.trim()));\n }\n // If expand is already an array, concatenate\n else {\n expandArray = expandArray.concat(expand);\n }\n }\n\n // Filter out duplicates, empty strings, and undefined values\n const uniqueExpands = [...new Set(expandArray)].filter((e) => e !== \"\" && e !== undefined);\n\n // If no valid expands, return undefined\n if (!uniqueExpands.length) {\n return undefined;\n }\n\n // Join with comma and space\n return uniqueExpands.join(\",\");\n }\n\n /**\n * Prepare filter parameter\n * Combines default filters with provided filters\n */\n protected prepareFilter(filter?: string | string[]): string | undefined {\n // Handle empty case\n if (!this.options.filter.length && !filter) {\n return undefined;\n }\n\n // Convert all inputs to arrays for easy processing\n let filterArray: string[] = [...this.options.filter];\n\n if (filter) {\n // If filter is a string, add it as is (it might contain && already)\n if (typeof filter === \"string\") {\n if (filter) filterArray.push(filter);\n }\n // If filter is an array, concatenate\n else {\n filterArray = filterArray.concat(filter);\n }\n }\n\n // Filter out empty strings and undefined values\n const validFilters = filterArray.filter((f) => f !== \"\" && f !== undefined);\n\n // If no valid filters, return undefined\n if (!validFilters.length) {\n return undefined;\n }\n\n // Join with AND operator\n return validFilters.join(\"&&\");\n }\n\n /**\n * Prepare sort parameter\n * Uses provided sort or falls back to default sort\n */\n protected prepareSort(sort?: string): string | undefined {\n // If explicit sort is provided and not empty, use it (overriding defaults)\n if (sort && sort !== \"\") {\n return sort;\n }\n\n // If no explicit sort but we have defaults\n if (this.options.sort.length) {\n // Filter out empty and undefined values\n const validSorts = this.options.sort.filter((s) => s !== \"\" && s !== undefined);\n\n // If we have valid sort items after filtering\n if (validSorts.length) {\n return validSorts.join(\",\");\n }\n }\n\n // No sort specified\n return undefined;\n }\n\n /**\n * Perform the actual create operation\n */\n protected async entityCreate(data: InputType): Promise<T> {\n return await this.getCollection().create(data as Record<string, any>);\n }\n\n /**\n * Perform the actual update operation\n */\n protected async entityUpdate(id: string, data: Partial<T>): Promise<T> {\n return await this.getCollection().update(id, data);\n }\n\n /**\n * Perform the actual getById operation\n */\n protected async entityGetById(id: string, expand?: string | string[]): Promise<T> {\n const finalExpand = this.prepareExpand(expand);\n const options: RecordOptions = finalExpand ? { expand: finalExpand } : {};\n return await this.getCollection().getOne(id, options);\n }\n\n /**\n * Perform the actual getFirstByFilter operation\n */\n protected async entityGetFirstByFilter(\n filter: string | string[],\n expand?: string | string[],\n sort?: string\n ): Promise<T> {\n const finalFilter = this.prepareFilter(filter);\n const finalExpand = this.prepareExpand(expand);\n const finalSort = this.prepareSort(sort);\n\n const options: RecordListOptions = {};\n if (finalExpand) options.expand = finalExpand;\n if (finalSort) options.sort = finalSort;\n\n return await this.getCollection().getFirstListItem(finalFilter || \"\", options);\n }\n\n /**\n * Perform the actual getList operation\n * Returns a list result with items of type T\n */\n protected async entityGetList(\n page: number,\n perPage: number,\n filter?: string | string[],\n sort?: string,\n expand?: string | string[]\n ): Promise<ListResult<T>> {\n const finalFilter = this.prepareFilter(filter);\n const finalExpand = this.prepareExpand(expand);\n const finalSort = this.prepareSort(sort);\n\n const options: RecordListOptions = {};\n if (finalFilter) options.filter = finalFilter;\n if (finalExpand) options.expand = finalExpand;\n if (finalSort) options.sort = finalSort;\n\n return await this.getCollection().getList(page, perPage, options);\n }\n\n /**\n * Perform the actual delete operation\n */\n protected async entityDelete(id: string): Promise<boolean> {\n await this.getCollection().delete(id);\n return true;\n }\n\n /**\n * Error handler for common errors\n * @param error The error to handle\n * @param options Handler options\n * @returns The value to return if the error is handled, or throws if not handled\n */\n protected handleError<R>(\n error: any,\n options: {\n allowNotFound?: boolean;\n returnValue?: R;\n logError?: boolean;\n } = { logError: true }\n ): R {\n const { allowNotFound = false, returnValue, logError = true } = options;\n\n // Log the error if requested\n if (logError) {\n console.error(`Error in ${this.constructor.name}:`, error);\n }\n\n // Handle 404 errors if allowed\n if (allowNotFound && this.isNotFoundError(error)) {\n return null as R;\n }\n\n // Return specified value or rethrow\n if (returnValue !== undefined) {\n return returnValue;\n }\n\n // Rethrow the error\n throw error;\n }\n\n /**\n * Check if an error is a \"not found\" error\n */\n protected isNotFoundError(error: any): boolean {\n return (\n error instanceof Error && (error.message.includes(\"404\") || error.message.toLowerCase().includes(\"not found\"))\n );\n }\n\n /**\n * Standard error handling wrapper (legacy method, consider using handleError instead)\n */\n protected errorWrapper(error: any): never {\n console.error(`Error in ${this.constructor.name}:`, error);\n throw error;\n }\n\n /**\n * Validate input data before creating/updating\n * Should be implemented by child classes\n */\n protected abstract validateInput(input: InputType): Promise<InputType>;\n\n /**\n * Subscribe to changes on a specific record\n * @param id The ID of the record to subscribe to\n * @param callback Function to call when changes occur\n * @param expand Optional expand parameters\n * @returns Promise that resolves to an unsubscribe function\n */\n async subscribeToRecord(\n id: string,\n callback: (data: RecordSubscription<T>) => void,\n expand?: string | string[]\n ): Promise<UnsubscribeFunc> {\n const finalExpand = this.prepareExpand(expand);\n const options: RecordSubscribeOptions = finalExpand ? { expand: finalExpand } : {};\n\n return this.getCollection().subscribe(id, callback, options);\n }\n\n /**\n * Subscribe to changes on the entire collection\n * @param callback Function to call when changes occur\n * @param expand Optional expand parameters\n * @returns Promise that resolves to an unsubscribe function\n */\n async subscribeToCollection(\n callback: (data: RecordSubscription<T>) => void,\n expand?: string | string[]\n ): Promise<UnsubscribeFunc> {\n const finalExpand = this.prepareExpand(expand);\n const options: RecordSubscribeOptions = finalExpand ? { expand: finalExpand } : {};\n\n return this.getCollection().subscribe(\"*\", callback, options);\n }\n\n /**\n * Unsubscribe from a specific record's changes\n * @param id The ID of the record to unsubscribe from\n */\n unsubscribeFromRecord(id: string): void {\n this.getCollection().unsubscribe(id);\n }\n\n /**\n * Unsubscribe from collection-wide changes\n */\n unsubscribeFromCollection(): void {\n this.getCollection().unsubscribe(\"*\");\n }\n\n /**\n * Unsubscribe from all subscriptions in this collection\n */\n unsubscribeAll(): void {\n this.getCollection().unsubscribe();\n }\n}\n","import { UserInputSchema } from \"../schema\";\nimport type { UserInputType, UserType } from \"../types\";\nimport { BaseMutator, type MutatorOptions } from \"./baseMutator\";\n\nexport class UserMutator extends BaseMutator<UserType, UserInputType> {\n protected setDefaults(): MutatorOptions {\n return {\n expand: [],\n filter: [],\n sort: [\"-updated\"],\n };\n }\n\n protected getCollection() {\n return this.pb.collection(\"Users\");\n }\n\n protected async validateInput(input: UserInputType) {\n return UserInputSchema.parse(input);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/mutator/baseMutator.ts"],"names":[],"mappings":";AAmBO,IAAe,cAAf,MAA6D;AAAA,EACxD,EAAA;AAAA;AAAA,EAGA,OAAA,GAA0B;AAAA,IAClC,QAAQ,EAAC;AAAA,IACT,QAAQ,EAAC;AAAA,IACT,MAAM;AAAC,GACT;AAAA,EAEA,WAAA,CAAY,IAAgB,OAAA,EAAmC;AAC7D,IAAA,IAAA,CAAK,EAAA,GAAK,EAAA;AAGV,IAAA,IAAA,CAAK,iBAAA,EAAkB;AACvB,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,IAAA,CAAK,gBAAgB,OAAO,CAAA;AAAA,IAC9B;AAAA,EACF;AAAA,EAEQ,iBAAA,GAA0B;AAChC,IAAA,IAAA,CAAK,OAAA,GAAU,KAAK,WAAA,EAAY;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA,EAKU,WAAA,GAA8B;AACtC,IAAA,OAAO;AAAA,MACL,QAAQ,EAAC;AAAA,MACT,QAAQ,EAAC;AAAA,MACT,MAAM;AAAC,KACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKU,gBAAgB,UAAA,EAA2C;AACnE,IAAA,IAAI,UAAA,CAAW,WAAW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AAA,CAAU,EAAA,EAAI,UAAU,OAAO,CAAA;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,qBAAA,CACJ,QAAA,EACA,MAAA,EAC0B;AAC1B,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,aAAA,CAAc,MAAM,CAAA;AAC7C,IAAA,MAAM,UAAkC,WAAA,GAAc,EAAE,MAAA,EAAQ,WAAA,KAAgB,EAAC;AAEjF,IAAA,OAAO,KAAK,aAAA,EAAc,CAAE,SAAA,CAAU,GAAA,EAAK,UAAU,OAAO,CAAA;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,sBAAsB,EAAA,EAAkB;AACtC,IAAA,IAAA,CAAK,aAAA,EAAc,CAAE,WAAA,CAAY,EAAE,CAAA;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,yBAAA,GAAkC;AAChC,IAAA,IAAA,CAAK,aAAA,EAAc,CAAE,WAAA,CAAY,GAAG,CAAA;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,cAAA,GAAuB;AACrB,IAAA,IAAA,CAAK,aAAA,GAAgB,WAAA,EAAY;AAAA,EACnC;AACF","file":"mutator.js","sourcesContent":["import PocketBase, {\n RecordService,\n type ListResult,\n type RecordListOptions,\n type RecordModel,\n type RecordOptions,\n type RecordSubscribeOptions,\n type RecordSubscription,\n type UnsubscribeFunc,\n} from \"pocketbase\";\n\nexport interface MutatorOptions {\n expand: string[];\n filter: string[];\n sort: string[];\n}\n\n// T represents the output model type that extends RecordModel\n// InputType represents the input type for creation operations\nexport abstract class BaseMutator<T extends RecordModel, InputType> {\n protected pb: PocketBase;\n\n // Define a default property that subclasses will override\n protected options: MutatorOptions = {\n expand: [],\n filter: [],\n sort: [],\n };\n\n constructor(pb: PocketBase, options?: Partial<MutatorOptions>) {\n this.pb = pb;\n\n // Initialize with default options first\n this.initializeOptions();\n if (options) {\n this.overrideOptions(options);\n }\n }\n\n private initializeOptions(): void {\n this.options = this.setDefaults();\n }\n /**\n * Initialize options with class-specific defaults\n * Subclasses should override this instead of directly setting options\n */\n protected setDefaults(): MutatorOptions {\n return {\n expand: [],\n filter: [],\n sort: [],\n };\n }\n\n /**\n * Merge provided options with current options\n */\n protected overrideOptions(newOptions: Partial<MutatorOptions>): void {\n if (newOptions.expand !== undefined) {\n this.options.expand = newOptions.expand;\n }\n if (newOptions.filter !== undefined) {\n this.options.filter = newOptions.filter;\n }\n if (newOptions.sort !== undefined) {\n this.options.sort = newOptions.sort;\n }\n }\n\n /**\n * Get the collection instance\n */\n protected abstract getCollection(): RecordService<T>;\n\n toSnakeCase(str: string): string {\n return str\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n }\n\n /**\n * Create a new entity\n */\n async create(input: InputType): Promise<T> {\n try {\n const data = await this.validateInput(input);\n const record = await this.entityCreate(data);\n return await this.processRecord(record);\n } catch (error) {\n return this.errorWrapper(error);\n }\n }\n\n /**\n * Update an existing entity\n */\n async update(id: string, input: Partial<T>): Promise<T> {\n try {\n const record = await this.entityUpdate(id, input);\n return await this.processRecord(record);\n } catch (error) {\n return this.errorWrapper(error);\n }\n }\n\n /**\n * Create or update entity (upsert)\n */\n async upsert(input: InputType & { id?: string }): Promise<T> {\n if (input?.id) {\n return await this.update(input.id, input as Partial<T>);\n }\n\n // Implementations should override this method if they need\n // more specific upsert logic like checking for existing entities\n return await this.create(input);\n }\n\n /**\n * Get entity by ID\n */\n async getById(id: string, expand?: string | string[]): Promise<T | null> {\n try {\n const record = await this.entityGetById(id, expand);\n return await this.processRecord(record);\n } catch (error) {\n return this.handleError(error, { allowNotFound: true });\n }\n }\n\n /**\n * Get first entity by filter\n */\n async getFirstByFilter(filter: string | string[], expand?: string | string[], sort?: string): Promise<T | null> {\n try {\n const record = await this.entityGetFirstByFilter(filter, expand, sort);\n return await this.processRecord(record);\n } catch (error) {\n return this.handleError(error, { allowNotFound: true });\n }\n }\n\n /**\n * Get list of entities\n */\n async getList(\n page = 1,\n perPage = 100,\n filter?: string | string[],\n sort?: string,\n expand?: string | string[]\n ): Promise<ListResult<T>> {\n try {\n const result = await this.entityGetList(page, perPage, filter, sort, expand);\n return await this.processListResult(result);\n } catch (error) {\n return this.errorWrapper(error);\n }\n }\n\n /**\n * Delete entity by ID\n */\n async delete(id: string): Promise<boolean> {\n try {\n return await this.entityDelete(id);\n } catch (error) {\n return this.handleError(error, { returnValue: false });\n }\n }\n\n /**\n * Process a single record before returning it\n * Can be overridden to handle special cases like mapped entities\n */\n protected async processRecord(record: T): Promise<T> {\n return record;\n }\n\n /**\n * Process a list result before returning it\n * Can be overridden to handle special cases like mapped entities\n */\n protected async processListResult(result: ListResult<T>): Promise<ListResult<T>> {\n // Process each item in the list\n const processedItems = await Promise.all(result.items.map((item) => this.processRecord(item)));\n\n return {\n ...result,\n items: processedItems,\n };\n }\n\n /**\n * Prepare expand parameter\n * Combines default expands with provided expands\n */\n protected prepareExpand(expand?: string | string[]): string | undefined {\n // Handle empty defaults case\n if (!this.options.expand.length && !expand) {\n return undefined;\n }\n\n // Convert all inputs to arrays for easy processing\n let expandArray: string[] = [...this.options.expand];\n\n if (expand) {\n // If expand is a string, split it and add the parts\n if (typeof expand === \"string\") {\n expandArray = expandArray.concat(expand.split(\",\").map((e) => e.trim()));\n }\n // If expand is already an array, concatenate\n else {\n expandArray = expandArray.concat(expand);\n }\n }\n\n // Filter out duplicates, empty strings, and undefined values\n const uniqueExpands = [...new Set(expandArray)].filter((e) => e !== \"\" && e !== undefined);\n\n // If no valid expands, return undefined\n if (!uniqueExpands.length) {\n return undefined;\n }\n\n // Join with comma and space\n return uniqueExpands.join(\",\");\n }\n\n /**\n * Prepare filter parameter\n * Combines default filters with provided filters\n */\n protected prepareFilter(filter?: string | string[]): string | undefined {\n // Handle empty case\n if (!this.options.filter.length && !filter) {\n return undefined;\n }\n\n // Convert all inputs to arrays for easy processing\n let filterArray: string[] = [...this.options.filter];\n\n if (filter) {\n // If filter is a string, add it as is (it might contain && already)\n if (typeof filter === \"string\") {\n if (filter) filterArray.push(filter);\n }\n // If filter is an array, concatenate\n else {\n filterArray = filterArray.concat(filter);\n }\n }\n\n // Filter out empty strings and undefined values\n const validFilters = filterArray.filter((f) => f !== \"\" && f !== undefined);\n\n // If no valid filters, return undefined\n if (!validFilters.length) {\n return undefined;\n }\n\n // Join with AND operator\n return validFilters.join(\"&&\");\n }\n\n /**\n * Prepare sort parameter\n * Uses provided sort or falls back to default sort\n */\n protected prepareSort(sort?: string): string | undefined {\n // If explicit sort is provided and not empty, use it (overriding defaults)\n if (sort && sort !== \"\") {\n return sort;\n }\n\n // If no explicit sort but we have defaults\n if (this.options.sort.length) {\n // Filter out empty and undefined values\n const validSorts = this.options.sort.filter((s) => s !== \"\" && s !== undefined);\n\n // If we have valid sort items after filtering\n if (validSorts.length) {\n return validSorts.join(\",\");\n }\n }\n\n // No sort specified\n return undefined;\n }\n\n /**\n * Perform the actual create operation\n */\n protected async entityCreate(data: InputType): Promise<T> {\n return await this.getCollection().create(data as Record<string, any>);\n }\n\n /**\n * Perform the actual update operation\n */\n protected async entityUpdate(id: string, data: Partial<T>): Promise<T> {\n return await this.getCollection().update(id, data);\n }\n\n /**\n * Perform the actual getById operation\n */\n protected async entityGetById(id: string, expand?: string | string[]): Promise<T> {\n const finalExpand = this.prepareExpand(expand);\n const options: RecordOptions = finalExpand ? { expand: finalExpand } : {};\n return await this.getCollection().getOne(id, options);\n }\n\n /**\n * Perform the actual getFirstByFilter operation\n */\n protected async entityGetFirstByFilter(\n filter: string | string[],\n expand?: string | string[],\n sort?: string\n ): Promise<T> {\n const finalFilter = this.prepareFilter(filter);\n const finalExpand = this.prepareExpand(expand);\n const finalSort = this.prepareSort(sort);\n\n const options: RecordListOptions = {};\n if (finalExpand) options.expand = finalExpand;\n if (finalSort) options.sort = finalSort;\n\n return await this.getCollection().getFirstListItem(finalFilter || \"\", options);\n }\n\n /**\n * Perform the actual getList operation\n * Returns a list result with items of type T\n */\n protected async entityGetList(\n page: number,\n perPage: number,\n filter?: string | string[],\n sort?: string,\n expand?: string | string[]\n ): Promise<ListResult<T>> {\n const finalFilter = this.prepareFilter(filter);\n const finalExpand = this.prepareExpand(expand);\n const finalSort = this.prepareSort(sort);\n\n const options: RecordListOptions = {};\n if (finalFilter) options.filter = finalFilter;\n if (finalExpand) options.expand = finalExpand;\n if (finalSort) options.sort = finalSort;\n\n return await this.getCollection().getList(page, perPage, options);\n }\n\n /**\n * Perform the actual delete operation\n */\n protected async entityDelete(id: string): Promise<boolean> {\n await this.getCollection().delete(id);\n return true;\n }\n\n /**\n * Error handler for common errors\n * @param error The error to handle\n * @param options Handler options\n * @returns The value to return if the error is handled, or throws if not handled\n */\n protected handleError<R>(\n error: any,\n options: {\n allowNotFound?: boolean;\n returnValue?: R;\n logError?: boolean;\n } = { logError: true }\n ): R {\n const { allowNotFound = false, returnValue, logError = true } = options;\n\n // Log the error if requested\n if (logError) {\n console.error(`Error in ${this.constructor.name}:`, error);\n }\n\n // Handle 404 errors if allowed\n if (allowNotFound && this.isNotFoundError(error)) {\n return null as R;\n }\n\n // Return specified value or rethrow\n if (returnValue !== undefined) {\n return returnValue;\n }\n\n // Rethrow the error\n throw error;\n }\n\n /**\n * Check if an error is a \"not found\" error\n */\n protected isNotFoundError(error: any): boolean {\n return (\n error instanceof Error && (error.message.includes(\"404\") || error.message.toLowerCase().includes(\"not found\"))\n );\n }\n\n /**\n * Standard error handling wrapper (legacy method, consider using handleError instead)\n */\n protected errorWrapper(error: any): never {\n console.error(`Error in ${this.constructor.name}:`, error);\n throw error;\n }\n\n /**\n * Validate input data before creating/updating\n * Should be implemented by child classes\n */\n protected abstract validateInput(input: InputType): Promise<InputType>;\n\n /**\n * Subscribe to changes on a specific record\n * @param id The ID of the record to subscribe to\n * @param callback Function to call when changes occur\n * @param expand Optional expand parameters\n * @returns Promise that resolves to an unsubscribe function\n */\n async subscribeToRecord(\n id: string,\n callback: (data: RecordSubscription<T>) => void,\n expand?: string | string[]\n ): Promise<UnsubscribeFunc> {\n const finalExpand = this.prepareExpand(expand);\n const options: RecordSubscribeOptions = finalExpand ? { expand: finalExpand } : {};\n\n return this.getCollection().subscribe(id, callback, options);\n }\n\n /**\n * Subscribe to changes on the entire collection\n * @param callback Function to call when changes occur\n * @param expand Optional expand parameters\n * @returns Promise that resolves to an unsubscribe function\n */\n async subscribeToCollection(\n callback: (data: RecordSubscription<T>) => void,\n expand?: string | string[]\n ): Promise<UnsubscribeFunc> {\n const finalExpand = this.prepareExpand(expand);\n const options: RecordSubscribeOptions = finalExpand ? { expand: finalExpand } : {};\n\n return this.getCollection().subscribe(\"*\", callback, options);\n }\n\n /**\n * Unsubscribe from a specific record's changes\n * @param id The ID of the record to unsubscribe from\n */\n unsubscribeFromRecord(id: string): void {\n this.getCollection().unsubscribe(id);\n }\n\n /**\n * Unsubscribe from collection-wide changes\n */\n unsubscribeFromCollection(): void {\n this.getCollection().unsubscribe(\"*\");\n }\n\n /**\n * Unsubscribe from all subscriptions in this collection\n */\n unsubscribeAll(): void {\n this.getCollection().unsubscribe();\n }\n}\n"]}
|
package/dist/schema.cjs
CHANGED
|
@@ -158,6 +158,191 @@ function defineCollection(config) {
|
|
|
158
158
|
}
|
|
159
159
|
return schema.describe(JSON.stringify(metadata));
|
|
160
160
|
}
|
|
161
|
+
var FIELD_METADATA_KEY = "__pocketbase_field__";
|
|
162
|
+
function extractFieldMetadata(description) {
|
|
163
|
+
if (!description) return null;
|
|
164
|
+
try {
|
|
165
|
+
const parsed = JSON.parse(description);
|
|
166
|
+
if (parsed[FIELD_METADATA_KEY]) {
|
|
167
|
+
return parsed[FIELD_METADATA_KEY];
|
|
168
|
+
}
|
|
169
|
+
} catch {
|
|
170
|
+
}
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
function BoolField() {
|
|
174
|
+
const metadata = {
|
|
175
|
+
[FIELD_METADATA_KEY]: {
|
|
176
|
+
type: "bool"
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
return zod.z.boolean().describe(JSON.stringify(metadata));
|
|
180
|
+
}
|
|
181
|
+
function NumberField(options) {
|
|
182
|
+
if (options?.min !== void 0 && options?.max !== void 0) {
|
|
183
|
+
if (options.min > options.max) {
|
|
184
|
+
throw new Error("NumberField: min cannot be greater than max");
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
let schema = zod.z.number();
|
|
188
|
+
if (options?.min !== void 0) {
|
|
189
|
+
schema = schema.min(options.min);
|
|
190
|
+
}
|
|
191
|
+
if (options?.max !== void 0) {
|
|
192
|
+
schema = schema.max(options.max);
|
|
193
|
+
}
|
|
194
|
+
const metadata = {
|
|
195
|
+
[FIELD_METADATA_KEY]: {
|
|
196
|
+
type: "number",
|
|
197
|
+
options: options || {}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
return schema.describe(JSON.stringify(metadata));
|
|
201
|
+
}
|
|
202
|
+
function TextField(options) {
|
|
203
|
+
if (options?.min !== void 0 && options?.max !== void 0) {
|
|
204
|
+
if (options.min > options.max) {
|
|
205
|
+
throw new Error("TextField: min cannot be greater than max");
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
let schema = zod.z.string();
|
|
209
|
+
if (options?.min !== void 0) {
|
|
210
|
+
schema = schema.min(options.min);
|
|
211
|
+
}
|
|
212
|
+
if (options?.max !== void 0) {
|
|
213
|
+
schema = schema.max(options.max);
|
|
214
|
+
}
|
|
215
|
+
if (options?.pattern !== void 0) {
|
|
216
|
+
const pattern = options.pattern instanceof RegExp ? options.pattern : new RegExp(options.pattern);
|
|
217
|
+
schema = schema.regex(pattern);
|
|
218
|
+
}
|
|
219
|
+
const metadata = {
|
|
220
|
+
[FIELD_METADATA_KEY]: {
|
|
221
|
+
type: "text",
|
|
222
|
+
options: options || {}
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
return schema.describe(JSON.stringify(metadata));
|
|
226
|
+
}
|
|
227
|
+
function EmailField() {
|
|
228
|
+
const metadata = {
|
|
229
|
+
[FIELD_METADATA_KEY]: {
|
|
230
|
+
type: "email"
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
return zod.z.string().email().describe(JSON.stringify(metadata));
|
|
234
|
+
}
|
|
235
|
+
function URLField() {
|
|
236
|
+
const metadata = {
|
|
237
|
+
[FIELD_METADATA_KEY]: {
|
|
238
|
+
type: "url"
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
return zod.z.string().url().describe(JSON.stringify(metadata));
|
|
242
|
+
}
|
|
243
|
+
function EditorField() {
|
|
244
|
+
const metadata = {
|
|
245
|
+
[FIELD_METADATA_KEY]: {
|
|
246
|
+
type: "editor"
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
return zod.z.string().describe(JSON.stringify(metadata));
|
|
250
|
+
}
|
|
251
|
+
function DateField(options) {
|
|
252
|
+
if (options?.min !== void 0 && options?.max !== void 0) {
|
|
253
|
+
const minDate = typeof options.min === "string" ? new Date(options.min) : options.min;
|
|
254
|
+
const maxDate = typeof options.max === "string" ? new Date(options.max) : options.max;
|
|
255
|
+
if (minDate > maxDate) {
|
|
256
|
+
throw new Error("DateField: min cannot be greater than max");
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const schema = zod.z.string();
|
|
260
|
+
const metadata = {
|
|
261
|
+
[FIELD_METADATA_KEY]: {
|
|
262
|
+
type: "date",
|
|
263
|
+
options: options || {}
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
return schema.describe(JSON.stringify(metadata));
|
|
267
|
+
}
|
|
268
|
+
function AutodateField(options) {
|
|
269
|
+
const schema = zod.z.string();
|
|
270
|
+
const metadata = {
|
|
271
|
+
[FIELD_METADATA_KEY]: {
|
|
272
|
+
type: "autodate",
|
|
273
|
+
options: options || {}
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
return schema.describe(JSON.stringify(metadata));
|
|
277
|
+
}
|
|
278
|
+
function SelectField(values, options) {
|
|
279
|
+
const enumSchema = zod.z.enum(values);
|
|
280
|
+
const metadata = {
|
|
281
|
+
[FIELD_METADATA_KEY]: {
|
|
282
|
+
type: "select",
|
|
283
|
+
options: {
|
|
284
|
+
values,
|
|
285
|
+
maxSelect: options?.maxSelect ?? 1
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
if (options?.maxSelect && options.maxSelect > 1) {
|
|
290
|
+
return zod.z.array(enumSchema).describe(JSON.stringify(metadata));
|
|
291
|
+
}
|
|
292
|
+
return enumSchema.describe(JSON.stringify(metadata));
|
|
293
|
+
}
|
|
294
|
+
function FileField(options) {
|
|
295
|
+
const schema = zod.z.instanceof(File);
|
|
296
|
+
const metadata = {
|
|
297
|
+
[FIELD_METADATA_KEY]: {
|
|
298
|
+
type: "file",
|
|
299
|
+
options: options || {}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
return schema.describe(JSON.stringify(metadata));
|
|
303
|
+
}
|
|
304
|
+
function FilesField(options) {
|
|
305
|
+
if (options?.minSelect !== void 0 && options?.maxSelect !== void 0) {
|
|
306
|
+
if (options.minSelect > options.maxSelect) {
|
|
307
|
+
throw new Error("FilesField: minSelect cannot be greater than maxSelect");
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
let schema = zod.z.array(zod.z.instanceof(File));
|
|
311
|
+
if (options?.minSelect !== void 0) {
|
|
312
|
+
schema = schema.min(options.minSelect);
|
|
313
|
+
}
|
|
314
|
+
if (options?.maxSelect !== void 0) {
|
|
315
|
+
schema = schema.max(options.maxSelect);
|
|
316
|
+
}
|
|
317
|
+
const metadata = {
|
|
318
|
+
[FIELD_METADATA_KEY]: {
|
|
319
|
+
type: "file",
|
|
320
|
+
options: options || {}
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
return schema.describe(JSON.stringify(metadata));
|
|
324
|
+
}
|
|
325
|
+
function JSONField(schema) {
|
|
326
|
+
const baseSchema2 = schema ?? zod.z.record(zod.z.string(), zod.z.any());
|
|
327
|
+
const metadata = {
|
|
328
|
+
[FIELD_METADATA_KEY]: {
|
|
329
|
+
type: "json"
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
return baseSchema2.describe(JSON.stringify(metadata));
|
|
333
|
+
}
|
|
334
|
+
function GeoPointField() {
|
|
335
|
+
const schema = zod.z.object({
|
|
336
|
+
lon: zod.z.number(),
|
|
337
|
+
lat: zod.z.number()
|
|
338
|
+
});
|
|
339
|
+
const metadata = {
|
|
340
|
+
[FIELD_METADATA_KEY]: {
|
|
341
|
+
type: "geoPoint"
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
return schema.describe(JSON.stringify(metadata));
|
|
345
|
+
}
|
|
161
346
|
|
|
162
347
|
// src/utils/permission-templates.ts
|
|
163
348
|
var PermissionTemplates = {
|
|
@@ -378,88 +563,24 @@ function mergePermissions(...schemas) {
|
|
|
378
563
|
}
|
|
379
564
|
return merged;
|
|
380
565
|
}
|
|
381
|
-
var StatusEnum = zod.z.enum([
|
|
382
|
-
"draft",
|
|
383
|
-
// Initial proposal stage (RequestDraft, ProjectDraft)
|
|
384
|
-
"active",
|
|
385
|
-
// Work in progress
|
|
386
|
-
"complete",
|
|
387
|
-
// Fully completed project
|
|
388
|
-
"fail"
|
|
389
|
-
// Failed project at any stage
|
|
390
|
-
]);
|
|
391
|
-
|
|
392
|
-
// src/schema/project.ts
|
|
393
|
-
var ProjectInputSchema = zod.z.object({
|
|
394
|
-
// Required fields
|
|
395
|
-
title: zod.z.string(),
|
|
396
|
-
content: zod.z.string(),
|
|
397
|
-
status: StatusEnum,
|
|
398
|
-
summary: zod.z.string().optional(),
|
|
399
|
-
OwnerUser: RelationField({ collection: "Users" }),
|
|
400
|
-
SubscriberUsers: RelationsField({ collection: "Users" })
|
|
401
|
-
}).extend(inputImageFileSchema);
|
|
402
|
-
var ProjectSchema = ProjectInputSchema.omit(omitImageFilesSchema).extend(baseImageFileSchema);
|
|
403
|
-
var ProjectCollection = defineCollection({
|
|
404
|
-
collectionName: "Projects",
|
|
405
|
-
schema: ProjectSchema,
|
|
406
|
-
permissions: {
|
|
407
|
-
template: "owner-only",
|
|
408
|
-
ownerField: "OwnerUser",
|
|
409
|
-
customRules: {
|
|
410
|
-
listRule: '@request.auth.id != ""',
|
|
411
|
-
viewRule: '@request.auth.id != "" && (OwnerUser = @request.auth.id || SubscriberUsers ?= @request.auth.id)'
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
});
|
|
415
|
-
var UserInputSchema = zod.z.object({
|
|
416
|
-
name: zod.z.string().optional(),
|
|
417
|
-
email: zod.z.string().email(),
|
|
418
|
-
password: zod.z.string().min(8, "Password must be at least 8 characters"),
|
|
419
|
-
passwordConfirm: zod.z.string(),
|
|
420
|
-
avatar: zod.z.instanceof(File).optional()
|
|
421
|
-
});
|
|
422
|
-
var UserCollectionSchema = zod.z.object({
|
|
423
|
-
name: zod.z.string().optional(),
|
|
424
|
-
email: zod.z.string().email(),
|
|
425
|
-
password: zod.z.string().min(8, "Password must be at least 8 characters"),
|
|
426
|
-
avatar: zod.z.instanceof(File).optional()
|
|
427
|
-
});
|
|
428
|
-
var UserSchema = UserCollectionSchema.extend(baseSchema);
|
|
429
|
-
var UserCollection = defineCollection({
|
|
430
|
-
collectionName: "users",
|
|
431
|
-
type: "auth",
|
|
432
|
-
schema: UserSchema,
|
|
433
|
-
permissions: {
|
|
434
|
-
// Users can list their own profile
|
|
435
|
-
listRule: "id = @request.auth.id",
|
|
436
|
-
// Users can view their own profile
|
|
437
|
-
viewRule: "id = @request.auth.id",
|
|
438
|
-
// Anyone can create an account (sign up)
|
|
439
|
-
createRule: "",
|
|
440
|
-
// Users can only update their own profile
|
|
441
|
-
updateRule: "id = @request.auth.id",
|
|
442
|
-
// Users can only delete their own account
|
|
443
|
-
deleteRule: "id = @request.auth.id"
|
|
444
|
-
// manageRule is null in PocketBase default (not set)
|
|
445
|
-
},
|
|
446
|
-
indexes: [
|
|
447
|
-
// PocketBase's default indexes for auth collections
|
|
448
|
-
"CREATE UNIQUE INDEX `idx_tokenKey__pb_users_auth_` ON `users` (`tokenKey`)",
|
|
449
|
-
"CREATE UNIQUE INDEX `idx_email__pb_users_auth_` ON `users` (`email`) WHERE `email` != ''"
|
|
450
|
-
]
|
|
451
|
-
});
|
|
452
566
|
|
|
567
|
+
exports.AutodateField = AutodateField;
|
|
568
|
+
exports.BoolField = BoolField;
|
|
569
|
+
exports.DateField = DateField;
|
|
570
|
+
exports.EditorField = EditorField;
|
|
571
|
+
exports.EmailField = EmailField;
|
|
572
|
+
exports.FIELD_METADATA_KEY = FIELD_METADATA_KEY;
|
|
573
|
+
exports.FileField = FileField;
|
|
574
|
+
exports.FilesField = FilesField;
|
|
575
|
+
exports.GeoPointField = GeoPointField;
|
|
576
|
+
exports.JSONField = JSONField;
|
|
577
|
+
exports.NumberField = NumberField;
|
|
453
578
|
exports.PermissionTemplates = PermissionTemplates;
|
|
454
|
-
exports.ProjectCollection = ProjectCollection;
|
|
455
|
-
exports.ProjectInputSchema = ProjectInputSchema;
|
|
456
|
-
exports.ProjectSchema = ProjectSchema;
|
|
457
579
|
exports.RelationField = RelationField;
|
|
458
580
|
exports.RelationsField = RelationsField;
|
|
459
|
-
exports.
|
|
460
|
-
exports.
|
|
461
|
-
exports.
|
|
462
|
-
exports.UserSchema = UserSchema;
|
|
581
|
+
exports.SelectField = SelectField;
|
|
582
|
+
exports.TextField = TextField;
|
|
583
|
+
exports.URLField = URLField;
|
|
463
584
|
exports.baseImageFileSchema = baseImageFileSchema;
|
|
464
585
|
exports.baseSchema = baseSchema;
|
|
465
586
|
exports.baseSchemaWithTimestamps = baseSchemaWithTimestamps;
|
|
@@ -469,6 +590,7 @@ exports.dateField = dateField;
|
|
|
469
590
|
exports.defineCollection = defineCollection;
|
|
470
591
|
exports.editorField = editorField;
|
|
471
592
|
exports.emailField = emailField;
|
|
593
|
+
exports.extractFieldMetadata = extractFieldMetadata;
|
|
472
594
|
exports.extractRelationMetadata = extractRelationMetadata;
|
|
473
595
|
exports.fileField = fileField;
|
|
474
596
|
exports.filesField = filesField;
|