firebase-rest-firestore 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { FirestoreDocument, FirestoreFieldValue, FirestoreResponse } from "../types";
1
+ import { CommitWrite, FieldTransform, FirestoreDocument, FirestoreFieldValue, FirestoreResponse } from "../types";
2
2
  /**
3
3
  * JSの値をFirestore形式に変換する
4
4
  * @param value 変換する値
@@ -17,6 +17,36 @@ export declare function convertFromFirestoreValue(firestoreValue: FirestoreField
17
17
  * @returns Firestoreドキュメント
18
18
  */
19
19
  export declare function convertToFirestoreDocument(data: Record<string, any>): FirestoreDocument;
20
+ /**
21
+ * Split write data into plain field values and Firestore field transforms.
22
+ *
23
+ * `FieldValue` sentinels (e.g. `serverTimestamp()`) are pulled out into
24
+ * transforms keyed by their (escaped, dot-separated) field path; everything
25
+ * else is left untouched in `fields`. Recursion only descends into plain
26
+ * objects, so class instances (Date / references / geo points) are treated as
27
+ * leaves.
28
+ *
29
+ * @param data Write data (JS values, may contain FieldValue sentinels)
30
+ * @param prefix Field-path prefix used while recursing (internal, pre-escaped)
31
+ */
32
+ export declare function extractFieldTransforms(data: Record<string, any>, prefix?: string): {
33
+ fields: Record<string, any>;
34
+ transforms: FieldTransform[];
35
+ };
36
+ /**
37
+ * Build a single `documents:commit` write that updates a document and applies
38
+ * field transforms. `updateTransforms` / `currentDocument` are only included
39
+ * when relevant.
40
+ *
41
+ * @param documentName Full resource name (projects/.../documents/<path>)
42
+ * @param fields Already-converted Firestore field values
43
+ * @param transforms Field transforms to apply after the update
44
+ * @param currentDocument Optional precondition (e.g. `{ exists: false }`)
45
+ */
46
+ export declare function buildCommitWrite(documentName: string, fields: Record<string, FirestoreFieldValue>, transforms: FieldTransform[], currentDocument?: {
47
+ exists?: boolean;
48
+ updateTime?: string;
49
+ }): CommitWrite;
20
50
  /**
21
51
  * Firestoreドキュメントをオブジェクトに変換
22
52
  * @param doc Firestoreレスポンス
@@ -1,3 +1,6 @@
1
+ import { DocumentReference } from "../client";
2
+ import { FieldValue } from "../field-value";
3
+ import { LiteralDocumentReference, LiteralGeoPointValue, } from "../types";
1
4
  import { getDocumentId } from "./path";
2
5
  /**
3
6
  * JSの値をFirestore形式に変換する
@@ -5,9 +8,24 @@ import { getDocumentId } from "./path";
5
8
  * @returns Firestore形式の値
6
9
  */
7
10
  export function convertToFirestoreValue(value) {
11
+ if (value instanceof FieldValue) {
12
+ // Sentinels (e.g. serverTimestamp) must be extracted into field transforms
13
+ // before conversion. Reaching here means one was used where Firestore
14
+ // cannot express a transform (such as inside an array).
15
+ throw new Error("FieldValue (e.g. serverTimestamp()) can only be used as a top-level or nested document field value, not inside an array.");
16
+ }
8
17
  if (value instanceof Date) {
9
18
  return { timestampValue: value.toISOString() };
10
19
  }
20
+ else if (value instanceof DocumentReference) {
21
+ return { referenceValue: value.referenceValue };
22
+ }
23
+ else if (value instanceof LiteralDocumentReference) {
24
+ return { referenceValue: value.referenceValue };
25
+ }
26
+ else if (value instanceof LiteralGeoPointValue) {
27
+ return { geoPointValue: value.geoPointValue };
28
+ }
11
29
  else if (typeof value === "string") {
12
30
  return { stringValue: value };
13
31
  }
@@ -63,15 +81,21 @@ export function convertFromFirestoreValue(firestoreValue) {
63
81
  else if ("timestampValue" in firestoreValue) {
64
82
  return new Date(firestoreValue.timestampValue);
65
83
  }
84
+ else if ("geoPointValue" in firestoreValue) {
85
+ return new LiteralGeoPointValue(firestoreValue);
86
+ }
87
+ else if ("referenceValue" in firestoreValue) {
88
+ return new LiteralDocumentReference(firestoreValue);
89
+ }
66
90
  else if ("mapValue" in firestoreValue && firestoreValue.mapValue.fields) {
67
91
  return Object.entries(firestoreValue.mapValue.fields).reduce((acc, [key, val]) => ({
68
92
  ...acc,
69
93
  [key]: convertFromFirestoreValue(val),
70
94
  }), {});
71
95
  }
72
- else if ("arrayValue" in firestoreValue &&
73
- firestoreValue.arrayValue.values) {
74
- return firestoreValue.arrayValue.values.map(convertFromFirestoreValue);
96
+ else if ("arrayValue" in firestoreValue) {
97
+ // The `values` field can be undefined, meaning that this is an empty array
98
+ return (firestoreValue.arrayValue.values ?? []).map(convertFromFirestoreValue);
75
99
  }
76
100
  return null;
77
101
  }
@@ -88,6 +112,91 @@ export function convertToFirestoreDocument(data) {
88
112
  }), {}),
89
113
  };
90
114
  }
115
+ /**
116
+ * Whether a value is a plain JS object (`{}` / `Object.create(null)`), as
117
+ * opposed to a class instance such as `Date`, `DocumentReference`,
118
+ * `LiteralGeoPointValue`, `LiteralDocumentReference`, `FieldValue`, or an array.
119
+ * Only plain objects are recursed into when extracting field transforms.
120
+ */
121
+ function isPlainObject(value) {
122
+ if (value === null || typeof value !== "object")
123
+ return false;
124
+ const proto = Object.getPrototypeOf(value);
125
+ return proto === Object.prototype || proto === null;
126
+ }
127
+ /**
128
+ * Escape a single field name for use in a Firestore field path. Simple names
129
+ * (`[A-Za-z_][A-Za-z0-9_]*`) are used as-is; anything else (dashes, dots,
130
+ * leading digits, spaces, ...) is wrapped in backticks with `\` and `` ` ``
131
+ * escaped, so a literal dot in a key is treated as part of the name rather than
132
+ * a path separator.
133
+ * See: https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents#Document
134
+ */
135
+ function escapeFieldPathSegment(segment) {
136
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment)) {
137
+ return segment;
138
+ }
139
+ return "`" + segment.replace(/\\/g, "\\\\").replace(/`/g, "\\`") + "`";
140
+ }
141
+ /**
142
+ * Split write data into plain field values and Firestore field transforms.
143
+ *
144
+ * `FieldValue` sentinels (e.g. `serverTimestamp()`) are pulled out into
145
+ * transforms keyed by their (escaped, dot-separated) field path; everything
146
+ * else is left untouched in `fields`. Recursion only descends into plain
147
+ * objects, so class instances (Date / references / geo points) are treated as
148
+ * leaves.
149
+ *
150
+ * @param data Write data (JS values, may contain FieldValue sentinels)
151
+ * @param prefix Field-path prefix used while recursing (internal, pre-escaped)
152
+ */
153
+ export function extractFieldTransforms(data, prefix = "") {
154
+ const fields = {};
155
+ const transforms = [];
156
+ for (const [key, value] of Object.entries(data)) {
157
+ const escapedKey = escapeFieldPathSegment(key);
158
+ const fieldPath = prefix ? `${prefix}.${escapedKey}` : escapedKey;
159
+ if (value instanceof FieldValue) {
160
+ if (value.methodName === "serverTimestamp") {
161
+ transforms.push({ fieldPath, setToServerValue: "REQUEST_TIME" });
162
+ }
163
+ else {
164
+ throw new Error(`Unsupported FieldValue: ${value.methodName}`);
165
+ }
166
+ }
167
+ else if (isPlainObject(value)) {
168
+ const nested = extractFieldTransforms(value, fieldPath);
169
+ fields[key] = nested.fields;
170
+ transforms.push(...nested.transforms);
171
+ }
172
+ else {
173
+ fields[key] = value;
174
+ }
175
+ }
176
+ return { fields, transforms };
177
+ }
178
+ /**
179
+ * Build a single `documents:commit` write that updates a document and applies
180
+ * field transforms. `updateTransforms` / `currentDocument` are only included
181
+ * when relevant.
182
+ *
183
+ * @param documentName Full resource name (projects/.../documents/<path>)
184
+ * @param fields Already-converted Firestore field values
185
+ * @param transforms Field transforms to apply after the update
186
+ * @param currentDocument Optional precondition (e.g. `{ exists: false }`)
187
+ */
188
+ export function buildCommitWrite(documentName, fields, transforms, currentDocument) {
189
+ const write = {
190
+ update: { name: documentName, fields },
191
+ };
192
+ if (transforms.length > 0) {
193
+ write.updateTransforms = transforms;
194
+ }
195
+ if (currentDocument) {
196
+ write.currentDocument = currentDocument;
197
+ }
198
+ return write;
199
+ }
91
200
  /**
92
201
  * Firestoreドキュメントをオブジェクトに変換
93
202
  * @param doc Firestoreレスポンス
@@ -30,6 +30,30 @@ export declare class FirestoreClient {
30
30
  * @private
31
31
  */
32
32
  private prepareHeaders;
33
+ /**
34
+ * Build the fully-qualified Firestore reference value for a document path,
35
+ * e.g. `projects/{projectId}/databases/{databaseId}/documents/{path}`.
36
+ * Used to encode a DocumentReference without exposing internal path helpers.
37
+ * @param documentPath Document path (ex: "users/uid/posts/postId")
38
+ */
39
+ getReferenceValue(documentPath: string): string;
40
+ /**
41
+ * Apply a single write through the `documents:commit` endpoint. This is the
42
+ * only REST path that supports field transforms (e.g. server timestamps).
43
+ * @param collectionName Collection path
44
+ * @param documentId Document ID
45
+ * @param fields Already-converted Firestore field values
46
+ * @param transforms Field transforms to apply after the update
47
+ * @param currentDocument Optional precondition (e.g. `{ exists: false }`)
48
+ * @private
49
+ */
50
+ private commit;
51
+ /**
52
+ * Commit a write and read the document back, so the resolved transform
53
+ * values (e.g. the server timestamp) are returned to the caller.
54
+ * @private
55
+ */
56
+ private commitAndRead;
33
57
  /**
34
58
  * Get collection reference
35
59
  * @param path Collection path
@@ -57,6 +81,14 @@ export declare class FirestoreClient {
57
81
  add(collectionName: string, data: Record<string, any>): Promise<Record<string, any> & {
58
82
  id: string;
59
83
  }>;
84
+ /**
85
+ * Create a document that contains field transforms (e.g. serverTimestamp)
86
+ * with an auto-generated ID. Uses the commit endpoint with an
87
+ * `exists: false` precondition and retries on the (astronomically unlikely)
88
+ * ID collision, mirroring the uniqueness of server-generated IDs.
89
+ * @private
90
+ */
91
+ private addWithTransforms;
60
92
  /**
61
93
  * Get document
62
94
  * @param collectionName Collection name
@@ -186,6 +218,11 @@ export declare class DocumentReference {
186
218
  * Get document path
187
219
  */
188
220
  get path(): string;
221
+ /**
222
+ * Fully-qualified Firestore reference value for this document, e.g.
223
+ * `projects/{projectId}/databases/{databaseId}/documents/{path}`.
224
+ */
225
+ get referenceValue(): string;
189
226
  /**
190
227
  * Get parent collection reference
191
228
  */
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Sentinel values for special write behaviors, mirroring the native Firebase
3
+ * SDK's `FieldValue`. Currently only `serverTimestamp()` is supported.
4
+ *
5
+ * A `FieldValue` is not a real field value: when used as a field in a write it
6
+ * is translated into a Firestore field transform (applied server-side) rather
7
+ * than serialized as data. Using one anywhere else (e.g. inside an array) is an
8
+ * error.
9
+ */
10
+ export declare class FieldValue {
11
+ readonly methodName: "serverTimestamp";
12
+ private constructor();
13
+ /**
14
+ * Returns a sentinel that sets the field to the server's request timestamp at
15
+ * write time, e.g. `client.add("posts", { createdAt: FieldValue.serverTimestamp() })`.
16
+ */
17
+ static serverTimestamp(): FieldValue;
18
+ /**
19
+ * Whether this sentinel represents the same transform as another.
20
+ */
21
+ isEqual(other: FieldValue): boolean;
22
+ }
@@ -1,5 +1,6 @@
1
1
  export * from "./types";
2
2
  import { FirestoreClient, createFirestoreClient, CollectionReference, DocumentReference, CollectionGroup, Query, QuerySnapshot, DocumentSnapshot, WriteResult } from "./client";
3
+ export { FieldValue } from "./field-value";
3
4
  export { getFirestoreToken } from "./utils/auth";
4
5
  export { convertToFirestoreValue, convertFromFirestoreValue, convertToFirestoreDocument, convertFromFirestoreDocument, } from "./utils/converter";
5
6
  export { getFirestoreBasePath, getDocumentId } from "./utils/path";
@@ -11,8 +11,63 @@ export interface FirestoreConfig {
11
11
  emulatorHost?: string;
12
12
  emulatorPort?: number;
13
13
  }
14
+ /**
15
+ * A reference to a document. For example: `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
16
+ * Used to represent document references globally and not connected to any particular client.
17
+ */
18
+ export declare class LiteralDocumentReference {
19
+ referenceValue: string;
20
+ constructor(options: Pick<LiteralDocumentReference, "referenceValue">);
21
+ /**
22
+ * Globally unique Firestore document reference paths look like:
23
+ * projects/{project_id}/databases/{database_id}/documents/{document_path}
24
+ * The database id (e.g. `(default)`) never contains a slash, while the
25
+ * document path may contain many. A single anchored regex parses this
26
+ * without pulling in a URLPattern polyfill.
27
+ */
28
+ private static readonly pattern;
29
+ private parse;
30
+ /**
31
+ * Get Project ID
32
+ */
33
+ get project_id(): string;
34
+ /**
35
+ * Get Database ID
36
+ * Ex: `(default)`
37
+ */
38
+ get database_id(): string;
39
+ /**
40
+ * Get document ID
41
+ */
42
+ get id(): string;
43
+ /**
44
+ * Get the collection ID
45
+ */
46
+ get collectionPath(): string;
47
+ /**
48
+ * Get document path
49
+ */
50
+ get path(): string;
51
+ }
52
+ /**
53
+ * A geo point value representing a point on the surface of Earth.
54
+ */
55
+ export declare class LiteralGeoPointValue {
56
+ geoPointValue: {
57
+ /**
58
+ * The latitude in degrees. It must be in the range [-90.0, +90.0].
59
+ */
60
+ latitude: number;
61
+ /**
62
+ * The longitude in degrees. It must be in the range [-180.0, +180.0].
63
+ */
64
+ longitude: number;
65
+ };
66
+ constructor(options: Pick<LiteralGeoPointValue, "geoPointValue">);
67
+ }
14
68
  /**
15
69
  * Firestoreの値型定義
70
+ * See: https://github.com/googleapis/google-api-nodejs-client/blob/5870dfe31f4885eebc82c19f7471c50403308f26/src/apis/firestore/v1.ts#L2246
16
71
  */
17
72
  export type FirestoreFieldValue = {
18
73
  stringValue: string;
@@ -26,7 +81,7 @@ export type FirestoreFieldValue = {
26
81
  nullValue: null;
27
82
  } | {
28
83
  timestampValue: string;
29
- } | {
84
+ } | Pick<LiteralGeoPointValue, 'geoPointValue'> | Pick<LiteralDocumentReference, 'referenceValue'> | {
30
85
  mapValue: {
31
86
  fields: Record<string, FirestoreFieldValue>;
32
87
  };
@@ -35,6 +90,28 @@ export type FirestoreFieldValue = {
35
90
  values: FirestoreFieldValue[];
36
91
  };
37
92
  };
93
+ /**
94
+ * A Firestore field transform applied server-side during a commit write.
95
+ * See: https://firebase.google.com/docs/firestore/reference/rest/v1/Write#FieldTransform
96
+ */
97
+ export interface FieldTransform {
98
+ fieldPath: string;
99
+ setToServerValue: "REQUEST_TIME";
100
+ }
101
+ /**
102
+ * A single write in a `documents:commit` request.
103
+ */
104
+ export interface CommitWrite {
105
+ update: {
106
+ name: string;
107
+ fields: Record<string, FirestoreFieldValue>;
108
+ };
109
+ updateTransforms?: FieldTransform[];
110
+ currentDocument?: {
111
+ exists?: boolean;
112
+ updateTime?: string;
113
+ };
114
+ }
38
115
  /**
39
116
  * Firestoreドキュメント型
40
117
  */
@@ -1,4 +1,4 @@
1
- import { FirestoreDocument, FirestoreFieldValue, FirestoreResponse } from "../types";
1
+ import { CommitWrite, FieldTransform, FirestoreDocument, FirestoreFieldValue, FirestoreResponse } from "../types";
2
2
  /**
3
3
  * JSの値をFirestore形式に変換する
4
4
  * @param value 変換する値
@@ -17,6 +17,36 @@ export declare function convertFromFirestoreValue(firestoreValue: FirestoreField
17
17
  * @returns Firestoreドキュメント
18
18
  */
19
19
  export declare function convertToFirestoreDocument(data: Record<string, any>): FirestoreDocument;
20
+ /**
21
+ * Split write data into plain field values and Firestore field transforms.
22
+ *
23
+ * `FieldValue` sentinels (e.g. `serverTimestamp()`) are pulled out into
24
+ * transforms keyed by their (escaped, dot-separated) field path; everything
25
+ * else is left untouched in `fields`. Recursion only descends into plain
26
+ * objects, so class instances (Date / references / geo points) are treated as
27
+ * leaves.
28
+ *
29
+ * @param data Write data (JS values, may contain FieldValue sentinels)
30
+ * @param prefix Field-path prefix used while recursing (internal, pre-escaped)
31
+ */
32
+ export declare function extractFieldTransforms(data: Record<string, any>, prefix?: string): {
33
+ fields: Record<string, any>;
34
+ transforms: FieldTransform[];
35
+ };
36
+ /**
37
+ * Build a single `documents:commit` write that updates a document and applies
38
+ * field transforms. `updateTransforms` / `currentDocument` are only included
39
+ * when relevant.
40
+ *
41
+ * @param documentName Full resource name (projects/.../documents/<path>)
42
+ * @param fields Already-converted Firestore field values
43
+ * @param transforms Field transforms to apply after the update
44
+ * @param currentDocument Optional precondition (e.g. `{ exists: false }`)
45
+ */
46
+ export declare function buildCommitWrite(documentName: string, fields: Record<string, FirestoreFieldValue>, transforms: FieldTransform[], currentDocument?: {
47
+ exists?: boolean;
48
+ updateTime?: string;
49
+ }): CommitWrite;
20
50
  /**
21
51
  * Firestoreドキュメントをオブジェクトに変換
22
52
  * @param doc Firestoreレスポンス
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "firebase-rest-firestore",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
4
4
  "description": "Firebase Firestore REST API client for Edge runtime environments",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -23,6 +23,7 @@
23
23
  "emulator:start": "cd test/emulator && firebase emulators:start -P demo-test-project",
24
24
  "emulator:stop": "npx kill-port -y 4089 8089 9089",
25
25
  "test": "vitest",
26
+ "test:unit": "vitest run test/converter.test.ts test/references.test.ts test/field-value.test.ts test/request-headers.test.ts",
26
27
  "test:emulator": "bash test/scripts/test-with-emulator.sh"
27
28
  },
28
29
  "keywords": [
@@ -46,7 +47,7 @@
46
47
  "@types/node": "^18.16.0",
47
48
  "concurrently": "^8.2.2",
48
49
  "dotenv": "^16.4.7",
49
- "semantic-release": "^24.2.3",
50
+ "semantic-release": "25.0.8",
50
51
  "typescript": "^5.0.4",
51
52
  "vitest": "^3.0.9"
52
53
  },