@esposter/azure 4.2.0 → 4.3.3

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/README.md CHANGED
@@ -26,6 +26,8 @@ pnpm add @esposter/azure
26
26
 
27
27
  ## <a name="documentation">📖 Documentation</a>
28
28
 
29
+ We highly recommend you take a look at the [documentation](https://github.com/Esposter/Esposter/tree/main/openspec/specs) to level up.
30
+
29
31
  ### Clauses
30
32
 
31
33
  A `Clause<T>` is a filter condition expressed against a property of `T`, and it is what the OData string is
@@ -0,0 +1,159 @@
1
+ import { z } from "zod";
2
+ import { PropertyNames } from "@esposter/shared";
3
+ import { TableEntity } from "@azure/data-tables";
4
+ export declare enum SearchOperator {
5
+ ArrayAny = "arrayAny",
6
+ ArrayContains = "arrayContains"
7
+ }
8
+ export declare enum BinaryOperator {
9
+ Eq = "eq",
10
+ Ge = "ge",
11
+ Gt = "gt",
12
+ Le = "le",
13
+ Lt = "lt",
14
+ Ne = "ne"
15
+ }
16
+ export declare const BinaryOperators: readonly BinaryOperator[];
17
+ export type SerializableValue = boolean | Date | null | number | string;
18
+ export declare const serializableValueSchema: z.ZodType<SerializableValue, SerializableValue>;
19
+ export type Clause<T extends object> = {
20
+ key: keyof T & string;
21
+ not?: boolean;
22
+ } & ({
23
+ operator: BinaryOperator;
24
+ value: SerializableValue;
25
+ } | {
26
+ operator: SearchOperator.ArrayAny;
27
+ } | {
28
+ operator: SearchOperator.ArrayContains;
29
+ value: SerializableValue[];
30
+ });
31
+ export declare enum UnaryOperator {
32
+ And = "and",
33
+ Not = "not",
34
+ Or = "or"
35
+ }
36
+ /**
37
+ Omit any index signatures from the given object type, leaving only explicitly defined properties.
38
+
39
+ This is the counterpart of `PickIndexSignature`.
40
+
41
+ Use-cases:
42
+ - Remove overly permissive signatures from third-party types.
43
+
44
+ This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
45
+
46
+ It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`.
47
+
48
+ (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
49
+
50
+ ```
51
+ const indexed: Record<string, unknown> = {}; // Allowed
52
+
53
+ // @ts-expect-error
54
+ const keyed: Record<'foo', unknown> = {}; // Error
55
+ // TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
56
+ ```
57
+
58
+ Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another:
59
+
60
+ ```
61
+ type Indexed = {} extends Record<string, unknown>
62
+ ? '✅ `{}` is assignable to `Record<string, unknown>`'
63
+ : '❌ `{}` is NOT assignable to `Record<string, unknown>`';
64
+
65
+ type IndexedResult = Indexed;
66
+ //=> '✅ `{}` is assignable to `Record<string, unknown>`'
67
+
68
+ type Keyed = {} extends Record<'foo' | 'bar', unknown>
69
+ ? '✅ `{}` is assignable to `Record<\'foo\' | \'bar\', unknown>`'
70
+ : '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`';
71
+
72
+ type KeyedResult = Keyed;
73
+ //=> '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`'
74
+ ```
75
+
76
+ Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`...
77
+
78
+ ```
79
+ type OmitIndexSignature<ObjectType> = {
80
+ [KeyType in keyof ObjectType // Map each key of `ObjectType`...
81
+ ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
82
+ };
83
+ ```
84
+
85
+ ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
86
+
87
+ ```
88
+ type OmitIndexSignature<ObjectType> = {
89
+ [KeyType in keyof ObjectType
90
+ // Is `{}` assignable to `Record<KeyType, unknown>`?
91
+ as {} extends Record<KeyType, unknown>
92
+ ? never // ✅ `{}` is assignable to `Record<KeyType, unknown>`
93
+ : KeyType // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
94
+ ]: ObjectType[KeyType];
95
+ };
96
+ ```
97
+
98
+ If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it.
99
+
100
+ @example
101
+ ```
102
+ import type {OmitIndexSignature} from 'type-fest';
103
+
104
+ type Example = {
105
+ // These index signatures will be removed.
106
+ [x: string]: any;
107
+ [x: number]: any;
108
+ [x: symbol]: any;
109
+ [x: `head-${string}`]: string;
110
+ [x: `${string}-tail`]: string;
111
+ [x: `head-${string}-tail`]: string;
112
+ [x: `${bigint}`]: string;
113
+ [x: `embedded-${number}`]: string;
114
+
115
+ // These explicitly defined keys will remain.
116
+ foo: 'bar';
117
+ qux?: 'baz';
118
+ };
119
+
120
+ type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
121
+ //=> {foo: 'bar'; qux?: 'baz'}
122
+ ```
123
+
124
+ @see {@link PickIndexSignature}
125
+ @category Object
126
+ */
127
+ type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? never : KeyType]: ObjectType[KeyType]; };
128
+ export declare class CompositeKey implements OmitIndexSignature<TableEntity> {
129
+ partitionKey: string;
130
+ rowKey: string;
131
+ }
132
+ export declare const CompositeKeyPropertyNames: PropertyNames<CompositeKey>;
133
+ export declare const getSearchNonNullClause: <T extends object>(key: keyof T & string) => Clause<T>;
134
+ export declare const getSearchNullClause: <T extends object>(key: keyof T & string) => Clause<T>;
135
+ export declare const AZURE_MAX_BATCH_SIZE = 100;
136
+ export declare const AZURE_MAX_PAGE_SIZE = 1e3;
137
+ export declare const SERIALIZABLE_VALUE_MAX_LENGTH = 100;
138
+ export declare const AZURE_MAX_QUEUE_VISIBILITY_TIMEOUT_MS: number;
139
+ export declare const AZURE_MAX_STRING_PROPERTY_LENGTH: number;
140
+ export declare const KEYS_TO_CAPITALIZE: ReadonlySet<string>;
141
+ export declare const KEYS_TO_UNCAPITALIZE: ReadonlySet<string>;
142
+ export declare const deserializeKey: (key: string) => string;
143
+ export declare const getTableNullClause: <T extends object>(key: keyof T & string) => Clause<T>;
144
+ export declare const serializeKey: (key: string) => string;
145
+ export declare const RangeOperators: (BinaryOperator | SearchOperator)[];
146
+ export declare const DATETIME_LITERAL_PREFIX = "datetime'";
147
+ export declare const CLAUSE_REGEX: RegExp;
148
+ export declare const deserializeClause: (serializedClause: string) => Extract<Clause<Record<string, unknown>>, {
149
+ operator: BinaryOperator;
150
+ }>;
151
+ export declare const deserializeValue: (serializedValue: string) => SerializableValue;
152
+ export declare const escapeValue: (value: string) => string;
153
+ export declare const getPartitionKeyFilter: (partitionKey: CompositeKey["partitionKey"]) => string;
154
+ export declare const serializeClause: (clause: Clause<Record<string, unknown>>, isTableFilter?: boolean) => string;
155
+ export declare const serializeClauses: (clauses: Clause<Record<string, unknown>>[]) => string;
156
+ export declare const serializeClausesCore: (clauses: Clause<Record<string, unknown>>[], isTableFilter: boolean) => string;
157
+ export declare const serializeSearchClauses: (clauses: Clause<Record<string, unknown>>[]) => string;
158
+ export declare const serializeValue: (value: SerializableValue, isTableFilter?: boolean) => string;
159
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,167 @@
1
+ import { z } from "zod";
2
+ import { InvalidOperationError, NotFoundError, Operation, capitalize, getPropertyNames, getResult, normalizeString, takeOne, uncapitalize } from "@esposter/shared";
3
+ // src/models/search/SearchOperator.ts
4
+ let SearchOperator = /* @__PURE__ */ function(SearchOperator) {
5
+ SearchOperator["ArrayAny"] = "arrayAny";
6
+ SearchOperator["ArrayContains"] = "arrayContains";
7
+ return SearchOperator;
8
+ }({});
9
+ // src/models/shared/BinaryOperator.ts
10
+ let BinaryOperator = /* @__PURE__ */ function(BinaryOperator) {
11
+ BinaryOperator["Eq"] = "eq";
12
+ BinaryOperator["Ge"] = "ge";
13
+ BinaryOperator["Gt"] = "gt";
14
+ BinaryOperator["Le"] = "le";
15
+ BinaryOperator["Lt"] = "lt";
16
+ BinaryOperator["Ne"] = "ne";
17
+ return BinaryOperator;
18
+ }({});
19
+ const BinaryOperators = Object.values(BinaryOperator);
20
+ // src/services/shared/constants.ts
21
+ const AZURE_MAX_BATCH_SIZE = 100;
22
+ const AZURE_MAX_PAGE_SIZE = 1e3;
23
+ const SERIALIZABLE_VALUE_MAX_LENGTH = 100;
24
+ const AZURE_MAX_QUEUE_VISIBILITY_TIMEOUT_MS = Temporal.Duration.from({ days: 7 }).total("milliseconds");
25
+ const AZURE_MAX_STRING_PROPERTY_LENGTH = 32768;
26
+ // src/models/shared/SerializableValue.ts
27
+ const serializableValueSchema = z.union([
28
+ z.boolean(),
29
+ z.date(),
30
+ z.null(),
31
+ z.number(),
32
+ z.string().min(1).max(100)
33
+ ]);
34
+ // src/models/shared/UnaryOperator.ts
35
+ let UnaryOperator = /* @__PURE__ */ function(UnaryOperator) {
36
+ UnaryOperator["And"] = "and";
37
+ UnaryOperator["Not"] = "not";
38
+ UnaryOperator["Or"] = "or";
39
+ return UnaryOperator;
40
+ }({});
41
+ // src/models/table/CompositeKey.ts
42
+ var CompositeKey = class {};
43
+ const CompositeKeyPropertyNames = getPropertyNames();
44
+ // src/services/search/getSearchNonNullClause.ts
45
+ const getSearchNonNullClause = (key) => ({
46
+ key,
47
+ operator: "ne",
48
+ value: null
49
+ });
50
+ // src/services/search/getSearchNullClause.ts
51
+ const getSearchNullClause = (key) => ({
52
+ key,
53
+ operator: "eq",
54
+ value: null
55
+ });
56
+ // src/services/table/constants.ts
57
+ const KEYS_TO_CAPITALIZE = /* @__PURE__ */ new Set([CompositeKeyPropertyNames.partitionKey, CompositeKeyPropertyNames.rowKey]);
58
+ const KEYS_TO_UNCAPITALIZE = /* @__PURE__ */ new Set([capitalize(CompositeKeyPropertyNames.partitionKey), capitalize(CompositeKeyPropertyNames.rowKey)]);
59
+ // src/services/table/deserializeKey.ts
60
+ const deserializeKey = (key) => KEYS_TO_UNCAPITALIZE.has(key) ? uncapitalize(key) : key;
61
+ // src/services/table/getTableNullClause.ts
62
+ const getTableNullClause = (key) => ({
63
+ key,
64
+ not: true,
65
+ operator: "ne",
66
+ value: NaN
67
+ });
68
+ // src/services/table/serializeKey.ts
69
+ const serializeKey = (key) => KEYS_TO_CAPITALIZE.has(key) ? capitalize(key) : key;
70
+ // src/services/transformer/RangeOperators.ts
71
+ const RangeOperators = [
72
+ "ge",
73
+ "gt",
74
+ "le",
75
+ "lt"
76
+ ];
77
+ // src/services/transformer/constants.ts
78
+ const DATETIME_LITERAL_PREFIX = "datetime'";
79
+ const VALUE_REGEX = [
80
+ true,
81
+ false,
82
+ String.raw`${DATETIME_LITERAL_PREFIX}[^']*'`,
83
+ String.raw`\d{4}-\d{2}-\d{2}T[^\s]+`,
84
+ String(null),
85
+ String.raw`-?\d+(?:\.\d+)?`,
86
+ String(NaN),
87
+ "'(?:[^']|'')*'"
88
+ ].join("|");
89
+ const CLAUSE_REGEX = new RegExp(String.raw`^(?<not>not\s+)?(?<key>[A-Za-z0-9_]*)\s*(?<operator>${BinaryOperators.join("|")})\s+(?<value>${VALUE_REGEX})$`, "iu");
90
+ // src/services/transformer/deserializeValue.ts
91
+ const parseIsoDate = (isoValue) => getResult(() => new Date(Temporal.Instant.from(isoValue).epochMilliseconds)).unwrapOr(void 0);
92
+ const deserializeValue = (serializedValue) => {
93
+ if (serializedValue === String(true)) return true;
94
+ else if (serializedValue === String(false)) return false;
95
+ else if (serializedValue === String(null)) return null;
96
+ else if (Number.isFinite(Number(serializedValue))) return Number(serializedValue);
97
+ else if (serializedValue === String(NaN)) return NaN;
98
+ else if (serializedValue.startsWith("datetime'") && serializedValue.endsWith("'")) return parseIsoDate(serializedValue.slice(9, -1)) ?? serializedValue;
99
+ else if (serializedValue.startsWith("'") && serializedValue.endsWith("'")) return serializedValue.slice(1, -1).replaceAll("''", "'");
100
+ else return parseIsoDate(serializedValue) ?? serializedValue;
101
+ };
102
+ // src/services/transformer/deserializeClause.ts
103
+ const deserializeClause = (serializedClause) => {
104
+ const normalizedClause = normalizeString(serializedClause);
105
+ const match = CLAUSE_REGEX.exec(normalizedClause);
106
+ if (!match) throw new NotFoundError(deserializeClause.name, normalizedClause);
107
+ const groups = match.groups;
108
+ if (!groups) throw new NotFoundError(deserializeClause.name, normalizedClause);
109
+ return {
110
+ key: deserializeKey(groups.key),
111
+ not: Boolean(groups.not),
112
+ operator: groups.operator.toLowerCase(),
113
+ value: deserializeValue(groups.value)
114
+ };
115
+ };
116
+ // src/services/transformer/escapeValue.ts
117
+ const escapeValue = (value) => `'${value.replaceAll("'", "''")}'`;
118
+ // src/services/transformer/serializeValue.ts
119
+ const serializeValue = (value, isTableFilter = false) => {
120
+ if (value instanceof Date) return isTableFilter ? `${DATETIME_LITERAL_PREFIX}${value.toISOString()}'` : value.toISOString();
121
+ else if (typeof value === "string") return escapeValue(value);
122
+ else return String(value);
123
+ };
124
+ // src/services/transformer/serializeClause.ts
125
+ const serializeClause = (clause, isTableFilter = false) => {
126
+ const keys = clause.key.split("/").map((key) => serializeKey(key));
127
+ const clauseKey = keys.join("/");
128
+ if (clause.operator === "arrayAny") return `${clauseKey}/any()`;
129
+ else if (clause.operator === "arrayContains") {
130
+ const serializedValue = serializeValue(clause.value.join(","));
131
+ if (keys.length === 1) return `${clauseKey}/any(x: search.in(x, ${serializedValue}))`;
132
+ else if (keys.length === 2) {
133
+ const [collectionName, propertyName] = keys;
134
+ return `${collectionName}/any(x: search.in(x/${propertyName}, ${serializedValue}))`;
135
+ } else throw new InvalidOperationError(Operation.Read, serializeClause.name, clause.key);
136
+ }
137
+ const { not, operator, value } = clause;
138
+ const baseClause = `${clauseKey} ${operator} ${serializeValue(value, isTableFilter)}`;
139
+ return not ? `not(${baseClause})` : baseClause;
140
+ };
141
+ // src/services/transformer/serializeClausesCore.ts
142
+ const serializeClausesCore = (clauses, isTableFilter) => {
143
+ if (clauses.length === 0) return "";
144
+ else if (clauses.length === 1) return serializeClause(takeOne(clauses), isTableFilter);
145
+ else {
146
+ const groupedClauses = Object.groupBy(clauses, ({ key }) => key);
147
+ const groupedStrings = [];
148
+ for (const clauseGroup of Object.values(groupedClauses)) if (clauseGroup.length === 1) groupedStrings.push(serializeClause(takeOne(clauseGroup), isTableFilter));
149
+ else {
150
+ const serializedClauses = clauseGroup.map((clause) => serializeClause(clause, isTableFilter));
151
+ const groupedString = clauseGroup.some(({ operator }) => RangeOperators.includes(operator)) ? serializedClauses.join(` and `) : `(${serializedClauses.join(` or `)})`;
152
+ groupedStrings.push(groupedString);
153
+ }
154
+ return groupedStrings.join(` and `);
155
+ }
156
+ };
157
+ // src/services/transformer/serializeClauses.ts
158
+ const serializeClauses = (clauses) => serializeClausesCore(clauses, true);
159
+ // src/services/transformer/getPartitionKeyFilter.ts
160
+ const getPartitionKeyFilter = (partitionKey) => serializeClauses([{
161
+ key: CompositeKeyPropertyNames.partitionKey,
162
+ operator: "eq",
163
+ value: partitionKey
164
+ }]);
165
+ // src/services/transformer/serializeSearchClauses.ts
166
+ const serializeSearchClauses = (clauses) => serializeClausesCore(clauses, false);
167
+ export { AZURE_MAX_BATCH_SIZE, AZURE_MAX_PAGE_SIZE, AZURE_MAX_QUEUE_VISIBILITY_TIMEOUT_MS, AZURE_MAX_STRING_PROPERTY_LENGTH, BinaryOperator, BinaryOperators, CLAUSE_REGEX, CompositeKey, CompositeKeyPropertyNames, DATETIME_LITERAL_PREFIX, KEYS_TO_CAPITALIZE, KEYS_TO_UNCAPITALIZE, RangeOperators, SERIALIZABLE_VALUE_MAX_LENGTH, SearchOperator, UnaryOperator, deserializeClause, deserializeKey, deserializeValue, escapeValue, getPartitionKeyFilter, getSearchNonNullClause, getSearchNullClause, getTableNullClause, serializableValueSchema, serializeClause, serializeClauses, serializeClausesCore, serializeKey, serializeSearchClauses, serializeValue };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@esposter/azure",
3
- "version": "4.2.0",
3
+ "version": "4.3.3",
4
4
  "description": "The Azure wire conventions Esposter's clients and its mocks both speak — OData filter clauses, entity key casing, and service limits.",
5
5
  "keywords": [
6
6
  "azure",
@@ -38,23 +38,18 @@
38
38
  },
39
39
  "scripts": {
40
40
  "build": "tsdown",
41
- "format": "oxfmt",
42
- "format:check": "oxfmt --check",
43
41
  "lint": "eslint .",
44
42
  "lint:fix": "eslint --fix .",
45
43
  "test": "vitest",
46
44
  "typecheck": "tsc"
47
45
  },
48
46
  "dependencies": {
49
- "@esposter/shared": "4.2.0"
47
+ "@esposter/shared": "4.3.3"
50
48
  },
51
49
  "devDependencies": {
52
- "@arethetypeswrong/core": "^0.18.5",
53
- "@esposter/configuration": "4.2.0",
54
- "publint": "^0.3.25",
50
+ "@esposter/configuration": "4.3.3",
55
51
  "tsdown": "^0.23.1",
56
- "type-fest": "^5.10.0",
57
- "vitest": "^5.0.4"
52
+ "type-fest": "^5.10.0"
58
53
  },
59
54
  "peerDependencies": {
60
55
  "@azure/data-tables": "^13.3.2",
@@ -63,5 +58,5 @@
63
58
  "inlinedDependencies": {
64
59
  "type-fest": "5.10.0"
65
60
  },
66
- "gitHead": "fef4971cf6a621a2c1850f32fcec19ee4ec0de99"
61
+ "gitHead": "955bbc130ad9b28877fd4ae8efc73a045141ce01"
67
62
  }