Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add .d.ts files generation on cozy-stack-client #1234

Open
wants to merge 30 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
66a7e51
feat: Add .d.ts files generation on cozy-stack-client
Ldoppea Aug 31, 2022
984b395
feat: Check if appNode is instance of HTMLElement to ease TS checks
Ldoppea Aug 31, 2022
4411422
feat: Inverse token checks in setToken to enforce correct TS types
Ldoppea Aug 31, 2022
8021464
fix: Send doctype on normalizeDoc call from KonnectorCollection
Ldoppea Aug 31, 2022
679a41f
chore: Fix JSDoc for async method return types
Ldoppea Aug 31, 2022
59ec290
chore: Fix JSDoc for throwing only methods
Ldoppea Aug 31, 2022
9d39355
chore: Fix JSDoc types declarations
Ldoppea Aug 31, 2022
2565d41
chore: Fix JSDoc types declarations for optional params
Ldoppea Aug 31, 2022
bd1c71f
chore: TS-ignore errors that cannot be easily solved
Ldoppea Aug 31, 2022
760ebef
chore: WIP add missing JSDoc type declarations
Ldoppea Aug 31, 2022
4498f98
chore: Add JDoc type declaration for client.getStackClient()
Ldoppea Aug 31, 2022
e699635
fix: Remove unused argument
Crash-- Sep 22, 2022
6cddc4f
fix: Add default arg to launch option
Crash-- Sep 22, 2022
12213dd
docs: Change to optional args
Crash-- Sep 22, 2022
7f9a8f0
fix: Remove unused options arg
Crash-- Sep 23, 2022
ca6b298
chore: Fixup 097709e90974bf820554ac6d5380a07cccc6fe4e
Crash-- Sep 23, 2022
4897881
chore: Fixup 2447efe6eadbfa34f4befafbd5b2c646dd8d75ad
Crash-- Sep 23, 2022
1f7c51b
docs: Name is a string, not a boolean
Crash-- Sep 24, 2022
e693513
docs: Better import for JSDoc
Crash-- Sep 24, 2022
9270cae
docs: Be more specific about the returned type
Crash-- Sep 24, 2022
e37f6f6
docs: Add a few types
Crash-- Sep 24, 2022
ce75ccc
fix: Few typing issues
Crash-- Sep 24, 2022
c311208
docs: Typing issue
Crash-- Sep 24, 2022
8d3b8ff
docs: Add type
Crash-- Sep 27, 2022
35486f8
fix: Folder doesn't have executable attr
Crash-- Oct 19, 2022
656d210
docs: Try to import types from cozy-client to cozy-stack-client
Crash-- Dec 9, 2022
8b46f7f
chore: Remove type check on cozy-stack-client for now
Crash-- Dec 9, 2022
843fce9
chore: More type
Crash-- Dec 14, 2022
4f3200f
chore: Fix AppCollection get jsdoc
Crash-- Feb 9, 2023
a6d0247
chore: Add types to CozyStackClient
acezard Feb 12, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/cozy-client/src/CozyClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -1645,6 +1645,11 @@ instantiation of the client.`
return this.getStackClient()
}

/**
* Retrieve the CozyStackClient instance used by CozyClient
*
* @returns {CozyStackClient} - CozyStackClient instance
*/
getStackClient() {
if (!this.stackClient) {
this.createClient()
Expand Down
12 changes: 9 additions & 3 deletions packages/cozy-client/types/CozyClient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ declare class CozyClient {
* @returns {DocumentCollection} Collection corresponding to the doctype
*/
collection(doctype: string): DocumentCollection;
fetch(method: any, path: any, body: any, options?: {}): any;
fetch(method: any, path: any, body: any, options?: {}): Promise<object>;
all(doctype: any): QueryDefinition;
find(doctype: any, selector?: any): QueryDefinition;
get(doctype: any, id: any): QueryDefinition;
Expand Down Expand Up @@ -660,8 +660,13 @@ declare class CozyClient {
createClient(): void;
stackClient: any;
client: any;
getClient(): any;
getStackClient(): any;
getClient(): CozyStackClient;
/**
* Retrieve the CozyStackClient instance used by CozyClient
*
* @returns {CozyStackClient} - CozyStackClient instance
*/
getStackClient(): CozyStackClient;
reducer(): (state: {
documents: {};
queries: {};
Expand Down Expand Up @@ -733,6 +738,7 @@ import { OpenURLCallback } from "./types";
import { SessionCode } from "./types";
import { PKCECodes } from "./types";
import { ReduxStore } from "./types";
import CozyStackClient from "cozy-stack-client";
import { CozyClient as SnapshotClient } from "./testing/snapshots";
import { OldCozyClient } from "./types";
import { NodeEnvironment } from "./types";
Expand Down
5 changes: 4 additions & 1 deletion packages/cozy-stack-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
"version": "34.11.0",
"license": "MIT",
"main": "dist/index.js",
"types": "types/index.d.ts",
"files": [
"types",
"dist"
],
"repository": {
Expand All @@ -13,7 +15,8 @@
"scripts": {
"build": "../../bin/build",
"watch": "yarn run build --watch",
"prepublishOnly": "yarn run build"
"prepublishOnly": "yarn run build",
"typecheck": "tsc -p tsconfig.json"
},
"sideEffects": false,
"dependencies": {
Expand Down
41 changes: 38 additions & 3 deletions packages/cozy-stack-client/src/AppCollection.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,17 @@ import Collection from './Collection'
import DocumentCollection, { normalizeDoc } from './DocumentCollection'
import { FetchError } from './errors'
import logger from './logger'

/**
* @typedef {import('./DocumentCollection').CozyClientDocument} CozyClientDocument
*/
export const APPS_DOCTYPE = 'io.cozy.apps'

/**
*
* @param {object} app Doc to normalize
* @param {string} doctype Doctype
* @returns CozyClientDocument document
*/
export const normalizeApp = (app, doctype) => {
return {
...app.attributes,
Expand All @@ -28,7 +36,15 @@ class AppCollection extends DocumentCollection {
super(APPS_DOCTYPE, stackClient)
this.endpoint = '/apps/'
}

/**
* @typedef SourceParams
* @property {Array} sources
*
* @param {string} idArg id
* @param {SourceParams} [query] query
*
* @returns {Promise<{data: CozyClientDocument}>}
*/
async get(idArg, query) {
let id
if (idArg.indexOf('/') > -1) {
Expand Down Expand Up @@ -88,7 +104,8 @@ class AppCollection extends DocumentCollection {
*
* The returned documents are not paginated by the stack.
*
* @returns {{data, meta, skip, next}} The JSON API conformant response.
* @typedef {import("./DocumentCollection").JSONAPIDocument} JSONAPIDocument
* @returns {Promise<JSONAPIDocument>} The JSON API conformant response.
* @throws {FetchError}
*/
async all() {
Expand All @@ -103,14 +120,32 @@ class AppCollection extends DocumentCollection {
}
}

/**
* Not implemented, will throw
*
* @returns {Promise}
* @throws
*/
async create() {
throw new Error('create() method is not available for applications')
}

/**
* Not implemented, will throw
*
* @returns {Promise}
* @throws
*/
async update() {
throw new Error('update() method is not available for applications')
}

/**
* Not implemented, will throw
*
* @returns {Promise}
* @throws
*/
async destroy() {
throw new Error('destroy() method is not available for applications')
}
Expand Down
30 changes: 20 additions & 10 deletions packages/cozy-stack-client/src/CozyStackClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { fetchWithXMLHttpRequest, shouldXMLHTTPRequestBeUsed } from './xhrFetch'
import MicroEE from 'microee'
import { FetchError } from './errors'
import logger from './logger'
import OAuthClient from './OAuthClient'

const normalizeUri = uriArg => {
let uri = uriArg
Expand All @@ -38,9 +39,16 @@ const isRevocationError = err => {
}

/**
* Main API against the `cozy-stack` server.
* @class CozyStackClient
* @classdesc Main API against the `cozy-stack` server.
* @augments {OAuthClient}
*/
class CozyStackClient {
/**
* @type {string}
*/
uri

constructor(options) {
const opts = { ...options }
const { token, uri = '' } = opts
Expand Down Expand Up @@ -100,7 +108,7 @@ class CozyStackClient {
* @param {string} path The URI.
* @param {object} [body] The payload.
* @param {object} [opts={}] Options for fetch
* @returns {object}
* @returns {Promise<object>}
* @throws {FetchError}
*/
async fetch(method, path, body, opts = {}) {
Expand Down Expand Up @@ -132,6 +140,7 @@ class CozyStackClient {
try {
const response = await fetcher(fullPath, options)
if (!response.ok) {
// @ts-ignore - this.emit is added by MicroEE.mixin
this.emit(
'error',
new FetchError(response, `${response.status} ${response.statusText}`)
Expand Down Expand Up @@ -203,7 +212,7 @@ class CozyStackClient {
throw Error("couldn't fetch a new token - doc is not html")
}
const appNode = doc.querySelector('div[role="application"]')
if (!appNode) {
if (!appNode || !(appNode instanceof HTMLElement)) {
throw Error("couldn't fetch a new token - no div[role=application]")
}
const data = appNode.dataset.cozy
Expand All @@ -229,11 +238,12 @@ class CozyStackClient {
/**
* Fetches JSON in an authorized way.
*
* @template T
* @param {string} method The HTTP method.
* @param {string} path The URI.
* @param {object} body The payload.
* @param {object} options Options
* @returns {object}
* @param {object} [body] The payload.
* @param {object} [options] Options
* @returns {Promise<T>}
* @throws {FetchError}
*/
async fetchJSON(method, path, body, options = {}) {
Expand Down Expand Up @@ -315,12 +325,12 @@ class CozyStackClient {
if (!token) {
this.token = null
} else {
if (token.toAuthHeader) {
// AppToken or AccessToken
this.token = token
} else if (typeof token === 'string') {
if (typeof token === 'string') {
// jwt string
this.token = new AppToken(token)
} else if (token.toAuthHeader) {
// AppToken or AccessToken
this.token = token
} else {
logger.warn('Cozy-Client: Unknown token format', token)
throw new Error('Cozy-Client: Unknown token format')
Expand Down
51 changes: 37 additions & 14 deletions packages/cozy-stack-client/src/DocumentCollection.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,6 @@ import head from 'lodash/head'
import merge from 'lodash/merge'
import startsWith from 'lodash/startsWith'
import qs from 'qs'
import {
MangoQueryOptions,
MangoSelector,
MangoPartialFilter,
DesignDoc
} from './mangoIndex'

import Collection, {
dontThrowNotFoundError,
Expand All @@ -30,18 +24,40 @@ import {
normalizeDesignDoc
} from './mangoIndex'
import * as querystring from './querystring'
import { FetchError } from './errors'

import logger from './logger'

const DATABASE_DOES_NOT_EXIST = 'Database does not exist.'

/**
* @typedef {import("cozy-client/types/types").CozyClientDocument} CozyClientDocument
* @typedef {import('./mangoIndex').MangoQueryOptions} MangoQueryOptions
* @typedef {import('./mangoIndex').MangoSelector} MangoSelector
* @typedef {import('./mangoIndex').MangoPartialFilter} MangoPartialFilter
* @typedef {import('./mangoIndex').DesignDoc} DesignDoc
* @typedef {import('./errors').FetchError} FetchError
*
* @typedef JSONAPIDocument
* @property {Array<CozyClientDocument>} data
* @property {number} skip
* @property {boolean} next
* @property {object} [meta]
* @property {string} [bookmark]
* @property {object} [execution_stats]
*
* @typedef JSONAPIDocumentForDataRoute
* @property {Array<CozyClientDocument>} docs
* @property {number} skip
* @property {boolean} next
* @property {object} [meta]
* @property {string} [bookmark]
* @property {object} [execution_stats]
*/
/**
* Normalize a document, adding its doctype if needed
*
* @param {object} doc - Document to normalize
* @param {string} doctype - Document doctype
* @returns {object} normalized document
* @returns {CozyClientDocument} normalized document
* @private
*/
export function normalizeDoc(doc = {}, doctype) {
Expand Down Expand Up @@ -114,7 +130,7 @@ class DocumentCollection {
* @param {number} [options.skip=0] - Pagination Skip
* @param {string} [options.bookmark] - Pagination bookmark
* @param {Array<string>} [options.keys] - Keys to query
* @returns {Promise<{data, meta, skip, bookmark, next}>} The JSON API conformant response.
* @returns {Promise<JSONAPIDocument>} The JSON API conformant response.
* @throws {FetchError}
*/
async all({ limit = 100, skip = 0, bookmark, keys } = {}) {
Expand Down Expand Up @@ -184,6 +200,7 @@ class DocumentCollection {
* @param {string} path - path to fetch
* @param {MangoSelector} selector - selector
* @param {MangoQueryOptions} options - request options
* @returns {Promise<JSONAPIDocumentForDataRoute & JSONAPIDocument>} documents
*/
async fetchDocumentsWithMango(path, selector, options = {}) {
return this.stackClient.fetchJSON(
Expand Down Expand Up @@ -270,7 +287,7 @@ class DocumentCollection {
* @param {MangoSelector} selector The mango selector
* @param {MangoQueryOptions} options The find options
*
* @returns {Promise<object>} - The find response
* @returns {Promise<JSONAPIDocumentForDataRoute & JSONAPIDocument>} - The find response
* @protected
*/
async findWithMango(path, selector, options = {}) {
Expand Down Expand Up @@ -301,7 +318,7 @@ The returned documents are paginated by the stack.
*
* @param {MangoSelector} selector The Mango selector.
* @param {MangoQueryOptions} options MangoQueryOptions
* @returns {Promise<{data, skip, bookmark, next, execution_stats}>} The JSON API conformant response.
* @returns {Promise<JSONAPIDocument>} The JSON API conformant response.
* @throws {FetchError}
*/
async find(selector, options = {}) {
Expand Down Expand Up @@ -332,7 +349,7 @@ The returned documents are paginated by the stack.
*
* @param {MangoSelector} selector The Mango selector.
* @param {MangoQueryOptions} options MangoQueryOptions
* @returns {Promise<Array<{data}>>} Documents fetched
* @returns {Promise<Array<CozyClientDocument>>} Documents fetched
* @throws {FetchError}
*/
async findAll(selector, options = {}) {
Expand All @@ -352,7 +369,7 @@ The returned documents are paginated by the stack.
* Get a document by id
*
* @param {string} id The document id.
* @returns {Promise<object>} JsonAPI response containing normalized document as data attribute
* @returns {Promise<CozyClientDocument>} JsonAPI response containing normalized document as data attribute
*/
async get(id) {
return Collection.get(
Expand Down Expand Up @@ -393,6 +410,8 @@ The returned documents are paginated by the stack.
* Creates a document
*
* @param {object} doc - Document to create. Optional: you can force the id with the _id attribute
*
* @returns {Promise<{data}>} The updated document.
*/
async create({ _id, _type, ...document }) {
// In case of a fixed id, let's use the dedicated creation endpoint
Expand All @@ -410,6 +429,8 @@ The returned documents are paginated by the stack.
* Updates a document
*
* @param {object} document - Document to update. Do not forget the _id attribute
*
* @returns {Promise<{data}>} The updated document.
*/
async update(document) {
const resp = await this.stackClient.fetchJSON(
Expand All @@ -426,6 +447,8 @@ The returned documents are paginated by the stack.
* Destroys a document
*
* @param {object} doc - Document to destroy. Do not forget _id and _rev attributes
*
* @returns {Promise<{data}>} The deleted document
*/
async destroy({ _id, _rev, ...document }) {
const resp = await this.stackClient.fetchJSON(
Expand Down
Loading